SemaOverload.cpp revision 5509f37aacf8a4d65f759554c9ec18adc1ac7b4e
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file provides Sema routines for C++ overloading. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/Overload.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/CXXInheritance.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/AST/TypeOrdering.h" 22#include "clang/Basic/Diagnostic.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Lex/Preprocessor.h" 25#include "clang/Sema/Initialization.h" 26#include "clang/Sema/Lookup.h" 27#include "clang/Sema/SemaInternal.h" 28#include "clang/Sema/Template.h" 29#include "clang/Sema/TemplateDeduction.h" 30#include "llvm/ADT/DenseSet.h" 31#include "llvm/ADT/STLExtras.h" 32#include "llvm/ADT/SmallPtrSet.h" 33#include "llvm/ADT/SmallString.h" 34#include <algorithm> 35 36namespace clang { 37using namespace sema; 38 39/// A convenience routine for creating a decayed reference to a function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 42 bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 46 VK_LValue, Loc, LocInfo); 47 if (HadMultipleCandidates) 48 DRE->setHadMultipleCandidates(true); 49 50 S.MarkDeclRefReferenced(DRE); 51 S.DiagnoseUseOfDecl(FoundDecl, Loc); 52 53 ExprResult E = S.Owned(DRE); 54 E = S.DefaultFunctionArrayConversion(E.take()); 55 if (E.isInvalid()) 56 return ExprError(); 57 return E; 58} 59 60static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 61 bool InOverloadResolution, 62 StandardConversionSequence &SCS, 63 bool CStyle, 64 bool AllowObjCWritebackConversion); 65 66static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 67 QualType &ToType, 68 bool InOverloadResolution, 69 StandardConversionSequence &SCS, 70 bool CStyle); 71static OverloadingResult 72IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 73 UserDefinedConversionSequence& User, 74 OverloadCandidateSet& Conversions, 75 bool AllowExplicit); 76 77 78static ImplicitConversionSequence::CompareKind 79CompareStandardConversionSequences(Sema &S, 80 const StandardConversionSequence& SCS1, 81 const StandardConversionSequence& SCS2); 82 83static ImplicitConversionSequence::CompareKind 84CompareQualificationConversions(Sema &S, 85 const StandardConversionSequence& SCS1, 86 const StandardConversionSequence& SCS2); 87 88static ImplicitConversionSequence::CompareKind 89CompareDerivedToBaseConversions(Sema &S, 90 const StandardConversionSequence& SCS1, 91 const StandardConversionSequence& SCS2); 92 93 94 95/// GetConversionCategory - Retrieve the implicit conversion 96/// category corresponding to the given implicit conversion kind. 97ImplicitConversionCategory 98GetConversionCategory(ImplicitConversionKind Kind) { 99 static const ImplicitConversionCategory 100 Category[(int)ICK_Num_Conversion_Kinds] = { 101 ICC_Identity, 102 ICC_Lvalue_Transformation, 103 ICC_Lvalue_Transformation, 104 ICC_Lvalue_Transformation, 105 ICC_Identity, 106 ICC_Qualification_Adjustment, 107 ICC_Promotion, 108 ICC_Promotion, 109 ICC_Promotion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion, 117 ICC_Conversion, 118 ICC_Conversion, 119 ICC_Conversion, 120 ICC_Conversion, 121 ICC_Conversion, 122 ICC_Conversion 123 }; 124 return Category[(int)Kind]; 125} 126 127/// GetConversionRank - Retrieve the implicit conversion rank 128/// corresponding to the given implicit conversion kind. 129ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 130 static const ImplicitConversionRank 131 Rank[(int)ICK_Num_Conversion_Kinds] = { 132 ICR_Exact_Match, 133 ICR_Exact_Match, 134 ICR_Exact_Match, 135 ICR_Exact_Match, 136 ICR_Exact_Match, 137 ICR_Exact_Match, 138 ICR_Promotion, 139 ICR_Promotion, 140 ICR_Promotion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Conversion, 148 ICR_Conversion, 149 ICR_Conversion, 150 ICR_Conversion, 151 ICR_Conversion, 152 ICR_Complex_Real_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Writeback_Conversion 156 }; 157 return Rank[(int)Kind]; 158} 159 160/// GetImplicitConversionName - Return the name of this kind of 161/// implicit conversion. 162const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 163 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 164 "No conversion", 165 "Lvalue-to-rvalue", 166 "Array-to-pointer", 167 "Function-to-pointer", 168 "Noreturn adjustment", 169 "Qualification", 170 "Integral promotion", 171 "Floating point promotion", 172 "Complex promotion", 173 "Integral conversion", 174 "Floating conversion", 175 "Complex conversion", 176 "Floating-integral conversion", 177 "Pointer conversion", 178 "Pointer-to-member conversion", 179 "Boolean conversion", 180 "Compatible-types conversion", 181 "Derived-to-base conversion", 182 "Vector conversion", 183 "Vector splat", 184 "Complex-real conversion", 185 "Block Pointer conversion", 186 "Transparent Union Conversion" 187 "Writeback conversion" 188 }; 189 return Name[Kind]; 190} 191 192/// StandardConversionSequence - Set the standard conversion 193/// sequence to the identity conversion. 194void StandardConversionSequence::setAsIdentityConversion() { 195 First = ICK_Identity; 196 Second = ICK_Identity; 197 Third = ICK_Identity; 198 DeprecatedStringLiteralToCharPtr = false; 199 QualificationIncludesObjCLifetime = false; 200 ReferenceBinding = false; 201 DirectBinding = false; 202 IsLvalueReference = true; 203 BindsToFunctionLvalue = false; 204 BindsToRvalue = false; 205 BindsImplicitObjectArgumentWithoutRefQualifier = false; 206 ObjCLifetimeConversionBinding = false; 207 CopyConstructor = 0; 208} 209 210/// getRank - Retrieve the rank of this standard conversion sequence 211/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 212/// implicit conversions. 213ImplicitConversionRank StandardConversionSequence::getRank() const { 214 ImplicitConversionRank Rank = ICR_Exact_Match; 215 if (GetConversionRank(First) > Rank) 216 Rank = GetConversionRank(First); 217 if (GetConversionRank(Second) > Rank) 218 Rank = GetConversionRank(Second); 219 if (GetConversionRank(Third) > Rank) 220 Rank = GetConversionRank(Third); 221 return Rank; 222} 223 224/// isPointerConversionToBool - Determines whether this conversion is 225/// a conversion of a pointer or pointer-to-member to bool. This is 226/// used as part of the ranking of standard conversion sequences 227/// (C++ 13.3.3.2p4). 228bool StandardConversionSequence::isPointerConversionToBool() const { 229 // Note that FromType has not necessarily been transformed by the 230 // array-to-pointer or function-to-pointer implicit conversions, so 231 // check for their presence as well as checking whether FromType is 232 // a pointer. 233 if (getToType(1)->isBooleanType() && 234 (getFromType()->isPointerType() || 235 getFromType()->isObjCObjectPointerType() || 236 getFromType()->isBlockPointerType() || 237 getFromType()->isNullPtrType() || 238 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 239 return true; 240 241 return false; 242} 243 244/// isPointerConversionToVoidPointer - Determines whether this 245/// conversion is a conversion of a pointer to a void pointer. This is 246/// used as part of the ranking of standard conversion sequences (C++ 247/// 13.3.3.2p4). 248bool 249StandardConversionSequence:: 250isPointerConversionToVoidPointer(ASTContext& Context) const { 251 QualType FromType = getFromType(); 252 QualType ToType = getToType(1); 253 254 // Note that FromType has not necessarily been transformed by the 255 // array-to-pointer implicit conversion, so check for its presence 256 // and redo the conversion to get a pointer. 257 if (First == ICK_Array_To_Pointer) 258 FromType = Context.getArrayDecayedType(FromType); 259 260 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 261 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 262 return ToPtrType->getPointeeType()->isVoidType(); 263 264 return false; 265} 266 267/// Skip any implicit casts which could be either part of a narrowing conversion 268/// or after one in an implicit conversion. 269static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 270 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 271 switch (ICE->getCastKind()) { 272 case CK_NoOp: 273 case CK_IntegralCast: 274 case CK_IntegralToBoolean: 275 case CK_IntegralToFloating: 276 case CK_FloatingToIntegral: 277 case CK_FloatingToBoolean: 278 case CK_FloatingCast: 279 Converted = ICE->getSubExpr(); 280 continue; 281 282 default: 283 return Converted; 284 } 285 } 286 287 return Converted; 288} 289 290/// Check if this standard conversion sequence represents a narrowing 291/// conversion, according to C++11 [dcl.init.list]p7. 292/// 293/// \param Ctx The AST context. 294/// \param Converted The result of applying this standard conversion sequence. 295/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 296/// value of the expression prior to the narrowing conversion. 297/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 298/// type of the expression prior to the narrowing conversion. 299NarrowingKind 300StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 301 const Expr *Converted, 302 APValue &ConstantValue, 303 QualType &ConstantType) const { 304 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 305 306 // C++11 [dcl.init.list]p7: 307 // A narrowing conversion is an implicit conversion ... 308 QualType FromType = getToType(0); 309 QualType ToType = getToType(1); 310 switch (Second) { 311 // -- from a floating-point type to an integer type, or 312 // 313 // -- from an integer type or unscoped enumeration type to a floating-point 314 // type, except where the source is a constant expression and the actual 315 // value after conversion will fit into the target type and will produce 316 // the original value when converted back to the original type, or 317 case ICK_Floating_Integral: 318 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 319 return NK_Type_Narrowing; 320 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 321 llvm::APSInt IntConstantValue; 322 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 323 if (Initializer && 324 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 325 // Convert the integer to the floating type. 326 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 327 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 328 llvm::APFloat::rmNearestTiesToEven); 329 // And back. 330 llvm::APSInt ConvertedValue = IntConstantValue; 331 bool ignored; 332 Result.convertToInteger(ConvertedValue, 333 llvm::APFloat::rmTowardZero, &ignored); 334 // If the resulting value is different, this was a narrowing conversion. 335 if (IntConstantValue != ConvertedValue) { 336 ConstantValue = APValue(IntConstantValue); 337 ConstantType = Initializer->getType(); 338 return NK_Constant_Narrowing; 339 } 340 } else { 341 // Variables are always narrowings. 342 return NK_Variable_Narrowing; 343 } 344 } 345 return NK_Not_Narrowing; 346 347 // -- from long double to double or float, or from double to float, except 348 // where the source is a constant expression and the actual value after 349 // conversion is within the range of values that can be represented (even 350 // if it cannot be represented exactly), or 351 case ICK_Floating_Conversion: 352 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 353 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 354 // FromType is larger than ToType. 355 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 356 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 357 // Constant! 358 assert(ConstantValue.isFloat()); 359 llvm::APFloat FloatVal = ConstantValue.getFloat(); 360 // Convert the source value into the target type. 361 bool ignored; 362 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 363 Ctx.getFloatTypeSemantics(ToType), 364 llvm::APFloat::rmNearestTiesToEven, &ignored); 365 // If there was no overflow, the source value is within the range of 366 // values that can be represented. 367 if (ConvertStatus & llvm::APFloat::opOverflow) { 368 ConstantType = Initializer->getType(); 369 return NK_Constant_Narrowing; 370 } 371 } else { 372 return NK_Variable_Narrowing; 373 } 374 } 375 return NK_Not_Narrowing; 376 377 // -- from an integer type or unscoped enumeration type to an integer type 378 // that cannot represent all the values of the original type, except where 379 // the source is a constant expression and the actual value after 380 // conversion will fit into the target type and will produce the original 381 // value when converted back to the original type. 382 case ICK_Boolean_Conversion: // Bools are integers too. 383 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 384 // Boolean conversions can be from pointers and pointers to members 385 // [conv.bool], and those aren't considered narrowing conversions. 386 return NK_Not_Narrowing; 387 } // Otherwise, fall through to the integral case. 388 case ICK_Integral_Conversion: { 389 assert(FromType->isIntegralOrUnscopedEnumerationType()); 390 assert(ToType->isIntegralOrUnscopedEnumerationType()); 391 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 392 const unsigned FromWidth = Ctx.getIntWidth(FromType); 393 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 394 const unsigned ToWidth = Ctx.getIntWidth(ToType); 395 396 if (FromWidth > ToWidth || 397 (FromWidth == ToWidth && FromSigned != ToSigned) || 398 (FromSigned && !ToSigned)) { 399 // Not all values of FromType can be represented in ToType. 400 llvm::APSInt InitializerValue; 401 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 402 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 403 // Such conversions on variables are always narrowing. 404 return NK_Variable_Narrowing; 405 } 406 bool Narrowing = false; 407 if (FromWidth < ToWidth) { 408 // Negative -> unsigned is narrowing. Otherwise, more bits is never 409 // narrowing. 410 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 411 Narrowing = true; 412 } else { 413 // Add a bit to the InitializerValue so we don't have to worry about 414 // signed vs. unsigned comparisons. 415 InitializerValue = InitializerValue.extend( 416 InitializerValue.getBitWidth() + 1); 417 // Convert the initializer to and from the target width and signed-ness. 418 llvm::APSInt ConvertedValue = InitializerValue; 419 ConvertedValue = ConvertedValue.trunc(ToWidth); 420 ConvertedValue.setIsSigned(ToSigned); 421 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 422 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 423 // If the result is different, this was a narrowing conversion. 424 if (ConvertedValue != InitializerValue) 425 Narrowing = true; 426 } 427 if (Narrowing) { 428 ConstantType = Initializer->getType(); 429 ConstantValue = APValue(InitializerValue); 430 return NK_Constant_Narrowing; 431 } 432 } 433 return NK_Not_Narrowing; 434 } 435 436 default: 437 // Other kinds of conversions are not narrowings. 438 return NK_Not_Narrowing; 439 } 440} 441 442/// DebugPrint - Print this standard conversion sequence to standard 443/// error. Useful for debugging overloading issues. 444void StandardConversionSequence::DebugPrint() const { 445 raw_ostream &OS = llvm::errs(); 446 bool PrintedSomething = false; 447 if (First != ICK_Identity) { 448 OS << GetImplicitConversionName(First); 449 PrintedSomething = true; 450 } 451 452 if (Second != ICK_Identity) { 453 if (PrintedSomething) { 454 OS << " -> "; 455 } 456 OS << GetImplicitConversionName(Second); 457 458 if (CopyConstructor) { 459 OS << " (by copy constructor)"; 460 } else if (DirectBinding) { 461 OS << " (direct reference binding)"; 462 } else if (ReferenceBinding) { 463 OS << " (reference binding)"; 464 } 465 PrintedSomething = true; 466 } 467 468 if (Third != ICK_Identity) { 469 if (PrintedSomething) { 470 OS << " -> "; 471 } 472 OS << GetImplicitConversionName(Third); 473 PrintedSomething = true; 474 } 475 476 if (!PrintedSomething) { 477 OS << "No conversions required"; 478 } 479} 480 481/// DebugPrint - Print this user-defined conversion sequence to standard 482/// error. Useful for debugging overloading issues. 483void UserDefinedConversionSequence::DebugPrint() const { 484 raw_ostream &OS = llvm::errs(); 485 if (Before.First || Before.Second || Before.Third) { 486 Before.DebugPrint(); 487 OS << " -> "; 488 } 489 if (ConversionFunction) 490 OS << '\'' << *ConversionFunction << '\''; 491 else 492 OS << "aggregate initialization"; 493 if (After.First || After.Second || After.Third) { 494 OS << " -> "; 495 After.DebugPrint(); 496 } 497} 498 499/// DebugPrint - Print this implicit conversion sequence to standard 500/// error. Useful for debugging overloading issues. 501void ImplicitConversionSequence::DebugPrint() const { 502 raw_ostream &OS = llvm::errs(); 503 switch (ConversionKind) { 504 case StandardConversion: 505 OS << "Standard conversion: "; 506 Standard.DebugPrint(); 507 break; 508 case UserDefinedConversion: 509 OS << "User-defined conversion: "; 510 UserDefined.DebugPrint(); 511 break; 512 case EllipsisConversion: 513 OS << "Ellipsis conversion"; 514 break; 515 case AmbiguousConversion: 516 OS << "Ambiguous conversion"; 517 break; 518 case BadConversion: 519 OS << "Bad conversion"; 520 break; 521 } 522 523 OS << "\n"; 524} 525 526void AmbiguousConversionSequence::construct() { 527 new (&conversions()) ConversionSet(); 528} 529 530void AmbiguousConversionSequence::destruct() { 531 conversions().~ConversionSet(); 532} 533 534void 535AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 536 FromTypePtr = O.FromTypePtr; 537 ToTypePtr = O.ToTypePtr; 538 new (&conversions()) ConversionSet(O.conversions()); 539} 540 541namespace { 542 // Structure used by OverloadCandidate::DeductionFailureInfo to store 543 // template argument information. 544 struct DFIArguments { 545 TemplateArgument FirstArg; 546 TemplateArgument SecondArg; 547 }; 548 // Structure used by OverloadCandidate::DeductionFailureInfo to store 549 // template parameter and template argument information. 550 struct DFIParamWithArguments : DFIArguments { 551 TemplateParameter Param; 552 }; 553} 554 555/// \brief Convert from Sema's representation of template deduction information 556/// to the form used in overload-candidate information. 557OverloadCandidate::DeductionFailureInfo 558static MakeDeductionFailureInfo(ASTContext &Context, 559 Sema::TemplateDeductionResult TDK, 560 TemplateDeductionInfo &Info) { 561 OverloadCandidate::DeductionFailureInfo Result; 562 Result.Result = static_cast<unsigned>(TDK); 563 Result.HasDiagnostic = false; 564 Result.Data = 0; 565 switch (TDK) { 566 case Sema::TDK_Success: 567 case Sema::TDK_Invalid: 568 case Sema::TDK_InstantiationDepth: 569 case Sema::TDK_TooManyArguments: 570 case Sema::TDK_TooFewArguments: 571 break; 572 573 case Sema::TDK_Incomplete: 574 case Sema::TDK_InvalidExplicitArguments: 575 Result.Data = Info.Param.getOpaqueValue(); 576 break; 577 578 case Sema::TDK_NonDeducedMismatch: { 579 // FIXME: Should allocate from normal heap so that we can free this later. 580 DFIArguments *Saved = new (Context) DFIArguments; 581 Saved->FirstArg = Info.FirstArg; 582 Saved->SecondArg = Info.SecondArg; 583 Result.Data = Saved; 584 break; 585 } 586 587 case Sema::TDK_Inconsistent: 588 case Sema::TDK_Underqualified: { 589 // FIXME: Should allocate from normal heap so that we can free this later. 590 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 591 Saved->Param = Info.Param; 592 Saved->FirstArg = Info.FirstArg; 593 Saved->SecondArg = Info.SecondArg; 594 Result.Data = Saved; 595 break; 596 } 597 598 case Sema::TDK_SubstitutionFailure: 599 Result.Data = Info.take(); 600 if (Info.hasSFINAEDiagnostic()) { 601 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 602 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 603 Info.takeSFINAEDiagnostic(*Diag); 604 Result.HasDiagnostic = true; 605 } 606 break; 607 608 case Sema::TDK_FailedOverloadResolution: 609 Result.Data = Info.Expression; 610 break; 611 612 case Sema::TDK_MiscellaneousDeductionFailure: 613 break; 614 } 615 616 return Result; 617} 618 619void OverloadCandidate::DeductionFailureInfo::Destroy() { 620 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 621 case Sema::TDK_Success: 622 case Sema::TDK_Invalid: 623 case Sema::TDK_InstantiationDepth: 624 case Sema::TDK_Incomplete: 625 case Sema::TDK_TooManyArguments: 626 case Sema::TDK_TooFewArguments: 627 case Sema::TDK_InvalidExplicitArguments: 628 case Sema::TDK_FailedOverloadResolution: 629 break; 630 631 case Sema::TDK_Inconsistent: 632 case Sema::TDK_Underqualified: 633 case Sema::TDK_NonDeducedMismatch: 634 // FIXME: Destroy the data? 635 Data = 0; 636 break; 637 638 case Sema::TDK_SubstitutionFailure: 639 // FIXME: Destroy the template argument list? 640 Data = 0; 641 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 642 Diag->~PartialDiagnosticAt(); 643 HasDiagnostic = false; 644 } 645 break; 646 647 // Unhandled 648 case Sema::TDK_MiscellaneousDeductionFailure: 649 break; 650 } 651} 652 653PartialDiagnosticAt * 654OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 655 if (HasDiagnostic) 656 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 657 return 0; 658} 659 660TemplateParameter 661OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 663 case Sema::TDK_Success: 664 case Sema::TDK_Invalid: 665 case Sema::TDK_InstantiationDepth: 666 case Sema::TDK_TooManyArguments: 667 case Sema::TDK_TooFewArguments: 668 case Sema::TDK_SubstitutionFailure: 669 case Sema::TDK_NonDeducedMismatch: 670 case Sema::TDK_FailedOverloadResolution: 671 return TemplateParameter(); 672 673 case Sema::TDK_Incomplete: 674 case Sema::TDK_InvalidExplicitArguments: 675 return TemplateParameter::getFromOpaqueValue(Data); 676 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 return static_cast<DFIParamWithArguments*>(Data)->Param; 680 681 // Unhandled 682 case Sema::TDK_MiscellaneousDeductionFailure: 683 break; 684 } 685 686 return TemplateParameter(); 687} 688 689TemplateArgumentList * 690OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 692 case Sema::TDK_Success: 693 case Sema::TDK_Invalid: 694 case Sema::TDK_InstantiationDepth: 695 case Sema::TDK_TooManyArguments: 696 case Sema::TDK_TooFewArguments: 697 case Sema::TDK_Incomplete: 698 case Sema::TDK_InvalidExplicitArguments: 699 case Sema::TDK_Inconsistent: 700 case Sema::TDK_Underqualified: 701 case Sema::TDK_NonDeducedMismatch: 702 case Sema::TDK_FailedOverloadResolution: 703 return 0; 704 705 case Sema::TDK_SubstitutionFailure: 706 return static_cast<TemplateArgumentList*>(Data); 707 708 // Unhandled 709 case Sema::TDK_MiscellaneousDeductionFailure: 710 break; 711 } 712 713 return 0; 714} 715 716const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 717 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 718 case Sema::TDK_Success: 719 case Sema::TDK_Invalid: 720 case Sema::TDK_InstantiationDepth: 721 case Sema::TDK_Incomplete: 722 case Sema::TDK_TooManyArguments: 723 case Sema::TDK_TooFewArguments: 724 case Sema::TDK_InvalidExplicitArguments: 725 case Sema::TDK_SubstitutionFailure: 726 case Sema::TDK_FailedOverloadResolution: 727 return 0; 728 729 case Sema::TDK_Inconsistent: 730 case Sema::TDK_Underqualified: 731 case Sema::TDK_NonDeducedMismatch: 732 return &static_cast<DFIArguments*>(Data)->FirstArg; 733 734 // Unhandled 735 case Sema::TDK_MiscellaneousDeductionFailure: 736 break; 737 } 738 739 return 0; 740} 741 742const TemplateArgument * 743OverloadCandidate::DeductionFailureInfo::getSecondArg() { 744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 745 case Sema::TDK_Success: 746 case Sema::TDK_Invalid: 747 case Sema::TDK_InstantiationDepth: 748 case Sema::TDK_Incomplete: 749 case Sema::TDK_TooManyArguments: 750 case Sema::TDK_TooFewArguments: 751 case Sema::TDK_InvalidExplicitArguments: 752 case Sema::TDK_SubstitutionFailure: 753 case Sema::TDK_FailedOverloadResolution: 754 return 0; 755 756 case Sema::TDK_Inconsistent: 757 case Sema::TDK_Underqualified: 758 case Sema::TDK_NonDeducedMismatch: 759 return &static_cast<DFIArguments*>(Data)->SecondArg; 760 761 // Unhandled 762 case Sema::TDK_MiscellaneousDeductionFailure: 763 break; 764 } 765 766 return 0; 767} 768 769Expr * 770OverloadCandidate::DeductionFailureInfo::getExpr() { 771 if (static_cast<Sema::TemplateDeductionResult>(Result) == 772 Sema::TDK_FailedOverloadResolution) 773 return static_cast<Expr*>(Data); 774 775 return 0; 776} 777 778void OverloadCandidateSet::destroyCandidates() { 779 for (iterator i = begin(), e = end(); i != e; ++i) { 780 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 781 i->Conversions[ii].~ImplicitConversionSequence(); 782 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 783 i->DeductionFailure.Destroy(); 784 } 785} 786 787void OverloadCandidateSet::clear() { 788 destroyCandidates(); 789 NumInlineSequences = 0; 790 Candidates.clear(); 791 Functions.clear(); 792} 793 794namespace { 795 class UnbridgedCastsSet { 796 struct Entry { 797 Expr **Addr; 798 Expr *Saved; 799 }; 800 SmallVector<Entry, 2> Entries; 801 802 public: 803 void save(Sema &S, Expr *&E) { 804 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 805 Entry entry = { &E, E }; 806 Entries.push_back(entry); 807 E = S.stripARCUnbridgedCast(E); 808 } 809 810 void restore() { 811 for (SmallVectorImpl<Entry>::iterator 812 i = Entries.begin(), e = Entries.end(); i != e; ++i) 813 *i->Addr = i->Saved; 814 } 815 }; 816} 817 818/// checkPlaceholderForOverload - Do any interesting placeholder-like 819/// preprocessing on the given expression. 820/// 821/// \param unbridgedCasts a collection to which to add unbridged casts; 822/// without this, they will be immediately diagnosed as errors 823/// 824/// Return true on unrecoverable error. 825static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 826 UnbridgedCastsSet *unbridgedCasts = 0) { 827 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 828 // We can't handle overloaded expressions here because overload 829 // resolution might reasonably tweak them. 830 if (placeholder->getKind() == BuiltinType::Overload) return false; 831 832 // If the context potentially accepts unbridged ARC casts, strip 833 // the unbridged cast and add it to the collection for later restoration. 834 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 835 unbridgedCasts) { 836 unbridgedCasts->save(S, E); 837 return false; 838 } 839 840 // Go ahead and check everything else. 841 ExprResult result = S.CheckPlaceholderExpr(E); 842 if (result.isInvalid()) 843 return true; 844 845 E = result.take(); 846 return false; 847 } 848 849 // Nothing to do. 850 return false; 851} 852 853/// checkArgPlaceholdersForOverload - Check a set of call operands for 854/// placeholders. 855static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 856 unsigned numArgs, 857 UnbridgedCastsSet &unbridged) { 858 for (unsigned i = 0; i != numArgs; ++i) 859 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 860 return true; 861 862 return false; 863} 864 865// IsOverload - Determine whether the given New declaration is an 866// overload of the declarations in Old. This routine returns false if 867// New and Old cannot be overloaded, e.g., if New has the same 868// signature as some function in Old (C++ 1.3.10) or if the Old 869// declarations aren't functions (or function templates) at all. When 870// it does return false, MatchedDecl will point to the decl that New 871// cannot be overloaded with. This decl may be a UsingShadowDecl on 872// top of the underlying declaration. 873// 874// Example: Given the following input: 875// 876// void f(int, float); // #1 877// void f(int, int); // #2 878// int f(int, int); // #3 879// 880// When we process #1, there is no previous declaration of "f", 881// so IsOverload will not be used. 882// 883// When we process #2, Old contains only the FunctionDecl for #1. By 884// comparing the parameter types, we see that #1 and #2 are overloaded 885// (since they have different signatures), so this routine returns 886// false; MatchedDecl is unchanged. 887// 888// When we process #3, Old is an overload set containing #1 and #2. We 889// compare the signatures of #3 to #1 (they're overloaded, so we do 890// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 891// identical (return types of functions are not part of the 892// signature), IsOverload returns false and MatchedDecl will be set to 893// point to the FunctionDecl for #2. 894// 895// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 896// into a class by a using declaration. The rules for whether to hide 897// shadow declarations ignore some properties which otherwise figure 898// into a function template's signature. 899Sema::OverloadKind 900Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 901 NamedDecl *&Match, bool NewIsUsingDecl) { 902 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 903 I != E; ++I) { 904 NamedDecl *OldD = *I; 905 906 bool OldIsUsingDecl = false; 907 if (isa<UsingShadowDecl>(OldD)) { 908 OldIsUsingDecl = true; 909 910 // We can always introduce two using declarations into the same 911 // context, even if they have identical signatures. 912 if (NewIsUsingDecl) continue; 913 914 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 915 } 916 917 // If either declaration was introduced by a using declaration, 918 // we'll need to use slightly different rules for matching. 919 // Essentially, these rules are the normal rules, except that 920 // function templates hide function templates with different 921 // return types or template parameter lists. 922 bool UseMemberUsingDeclRules = 923 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 924 925 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 926 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 927 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 928 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 929 continue; 930 } 931 932 Match = *I; 933 return Ovl_Match; 934 } 935 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 937 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 939 continue; 940 } 941 942 Match = *I; 943 return Ovl_Match; 944 } 945 } else if (isa<UsingDecl>(OldD)) { 946 // We can overload with these, which can show up when doing 947 // redeclaration checks for UsingDecls. 948 assert(Old.getLookupKind() == LookupUsingDeclName); 949 } else if (isa<TagDecl>(OldD)) { 950 // We can always overload with tags by hiding them. 951 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 952 // Optimistically assume that an unresolved using decl will 953 // overload; if it doesn't, we'll have to diagnose during 954 // template instantiation. 955 } else { 956 // (C++ 13p1): 957 // Only function declarations can be overloaded; object and type 958 // declarations cannot be overloaded. 959 Match = *I; 960 return Ovl_NonFunction; 961 } 962 } 963 964 return Ovl_Overload; 965} 966 967static bool canBeOverloaded(const FunctionDecl &D) { 968 if (D.getAttr<OverloadableAttr>()) 969 return true; 970 if (D.isExternC()) 971 return false; 972 973 // Main cannot be overloaded (basic.start.main). 974 if (D.isMain()) 975 return false; 976 977 return true; 978} 979 980bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 981 bool UseUsingDeclRules) { 982 // If both of the functions are extern "C", then they are not 983 // overloads. 984 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New)) 985 return false; 986 987 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 988 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 989 990 // C++ [temp.fct]p2: 991 // A function template can be overloaded with other function templates 992 // and with normal (non-template) functions. 993 if ((OldTemplate == 0) != (NewTemplate == 0)) 994 return true; 995 996 // Is the function New an overload of the function Old? 997 QualType OldQType = Context.getCanonicalType(Old->getType()); 998 QualType NewQType = Context.getCanonicalType(New->getType()); 999 1000 // Compare the signatures (C++ 1.3.10) of the two functions to 1001 // determine whether they are overloads. If we find any mismatch 1002 // in the signature, they are overloads. 1003 1004 // If either of these functions is a K&R-style function (no 1005 // prototype), then we consider them to have matching signatures. 1006 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1007 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1008 return false; 1009 1010 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1011 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1012 1013 // The signature of a function includes the types of its 1014 // parameters (C++ 1.3.10), which includes the presence or absence 1015 // of the ellipsis; see C++ DR 357). 1016 if (OldQType != NewQType && 1017 (OldType->getNumArgs() != NewType->getNumArgs() || 1018 OldType->isVariadic() != NewType->isVariadic() || 1019 !FunctionArgTypesAreEqual(OldType, NewType))) 1020 return true; 1021 1022 // C++ [temp.over.link]p4: 1023 // The signature of a function template consists of its function 1024 // signature, its return type and its template parameter list. The names 1025 // of the template parameters are significant only for establishing the 1026 // relationship between the template parameters and the rest of the 1027 // signature. 1028 // 1029 // We check the return type and template parameter lists for function 1030 // templates first; the remaining checks follow. 1031 // 1032 // However, we don't consider either of these when deciding whether 1033 // a member introduced by a shadow declaration is hidden. 1034 if (!UseUsingDeclRules && NewTemplate && 1035 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1036 OldTemplate->getTemplateParameters(), 1037 false, TPL_TemplateMatch) || 1038 OldType->getResultType() != NewType->getResultType())) 1039 return true; 1040 1041 // If the function is a class member, its signature includes the 1042 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1043 // 1044 // As part of this, also check whether one of the member functions 1045 // is static, in which case they are not overloads (C++ 1046 // 13.1p2). While not part of the definition of the signature, 1047 // this check is important to determine whether these functions 1048 // can be overloaded. 1049 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1050 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1051 if (OldMethod && NewMethod && 1052 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1053 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1054 if (!UseUsingDeclRules && 1055 (OldMethod->getRefQualifier() == RQ_None || 1056 NewMethod->getRefQualifier() == RQ_None)) { 1057 // C++0x [over.load]p2: 1058 // - Member function declarations with the same name and the same 1059 // parameter-type-list as well as member function template 1060 // declarations with the same name, the same parameter-type-list, and 1061 // the same template parameter lists cannot be overloaded if any of 1062 // them, but not all, have a ref-qualifier (8.3.5). 1063 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1064 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1065 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1066 } 1067 return true; 1068 } 1069 1070 // We may not have applied the implicit const for a constexpr member 1071 // function yet (because we haven't yet resolved whether this is a static 1072 // or non-static member function). Add it now, on the assumption that this 1073 // is a redeclaration of OldMethod. 1074 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1075 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod)) 1076 NewQuals |= Qualifiers::Const; 1077 if (OldMethod->getTypeQualifiers() != NewQuals) 1078 return true; 1079 } 1080 1081 // The signatures match; this is not an overload. 1082 return false; 1083} 1084 1085/// \brief Checks availability of the function depending on the current 1086/// function context. Inside an unavailable function, unavailability is ignored. 1087/// 1088/// \returns true if \arg FD is unavailable and current context is inside 1089/// an available function, false otherwise. 1090bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1091 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1092} 1093 1094/// \brief Tries a user-defined conversion from From to ToType. 1095/// 1096/// Produces an implicit conversion sequence for when a standard conversion 1097/// is not an option. See TryImplicitConversion for more information. 1098static ImplicitConversionSequence 1099TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1100 bool SuppressUserConversions, 1101 bool AllowExplicit, 1102 bool InOverloadResolution, 1103 bool CStyle, 1104 bool AllowObjCWritebackConversion) { 1105 ImplicitConversionSequence ICS; 1106 1107 if (SuppressUserConversions) { 1108 // We're not in the case above, so there is no conversion that 1109 // we can perform. 1110 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1111 return ICS; 1112 } 1113 1114 // Attempt user-defined conversion. 1115 OverloadCandidateSet Conversions(From->getExprLoc()); 1116 OverloadingResult UserDefResult 1117 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1118 AllowExplicit); 1119 1120 if (UserDefResult == OR_Success) { 1121 ICS.setUserDefined(); 1122 // C++ [over.ics.user]p4: 1123 // A conversion of an expression of class type to the same class 1124 // type is given Exact Match rank, and a conversion of an 1125 // expression of class type to a base class of that type is 1126 // given Conversion rank, in spite of the fact that a copy 1127 // constructor (i.e., a user-defined conversion function) is 1128 // called for those cases. 1129 if (CXXConstructorDecl *Constructor 1130 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1131 QualType FromCanon 1132 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1133 QualType ToCanon 1134 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1135 if (Constructor->isCopyConstructor() && 1136 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1137 // Turn this into a "standard" conversion sequence, so that it 1138 // gets ranked with standard conversion sequences. 1139 ICS.setStandard(); 1140 ICS.Standard.setAsIdentityConversion(); 1141 ICS.Standard.setFromType(From->getType()); 1142 ICS.Standard.setAllToTypes(ToType); 1143 ICS.Standard.CopyConstructor = Constructor; 1144 if (ToCanon != FromCanon) 1145 ICS.Standard.Second = ICK_Derived_To_Base; 1146 } 1147 } 1148 1149 // C++ [over.best.ics]p4: 1150 // However, when considering the argument of a user-defined 1151 // conversion function that is a candidate by 13.3.1.3 when 1152 // invoked for the copying of the temporary in the second step 1153 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1154 // 13.3.1.6 in all cases, only standard conversion sequences and 1155 // ellipsis conversion sequences are allowed. 1156 if (SuppressUserConversions && ICS.isUserDefined()) { 1157 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1158 } 1159 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1160 ICS.setAmbiguous(); 1161 ICS.Ambiguous.setFromType(From->getType()); 1162 ICS.Ambiguous.setToType(ToType); 1163 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1164 Cand != Conversions.end(); ++Cand) 1165 if (Cand->Viable) 1166 ICS.Ambiguous.addConversion(Cand->Function); 1167 } else { 1168 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1169 } 1170 1171 return ICS; 1172} 1173 1174/// TryImplicitConversion - Attempt to perform an implicit conversion 1175/// from the given expression (Expr) to the given type (ToType). This 1176/// function returns an implicit conversion sequence that can be used 1177/// to perform the initialization. Given 1178/// 1179/// void f(float f); 1180/// void g(int i) { f(i); } 1181/// 1182/// this routine would produce an implicit conversion sequence to 1183/// describe the initialization of f from i, which will be a standard 1184/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1185/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1186// 1187/// Note that this routine only determines how the conversion can be 1188/// performed; it does not actually perform the conversion. As such, 1189/// it will not produce any diagnostics if no conversion is available, 1190/// but will instead return an implicit conversion sequence of kind 1191/// "BadConversion". 1192/// 1193/// If @p SuppressUserConversions, then user-defined conversions are 1194/// not permitted. 1195/// If @p AllowExplicit, then explicit user-defined conversions are 1196/// permitted. 1197/// 1198/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1199/// writeback conversion, which allows __autoreleasing id* parameters to 1200/// be initialized with __strong id* or __weak id* arguments. 1201static ImplicitConversionSequence 1202TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1203 bool SuppressUserConversions, 1204 bool AllowExplicit, 1205 bool InOverloadResolution, 1206 bool CStyle, 1207 bool AllowObjCWritebackConversion) { 1208 ImplicitConversionSequence ICS; 1209 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1210 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1211 ICS.setStandard(); 1212 return ICS; 1213 } 1214 1215 if (!S.getLangOpts().CPlusPlus) { 1216 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1217 return ICS; 1218 } 1219 1220 // C++ [over.ics.user]p4: 1221 // A conversion of an expression of class type to the same class 1222 // type is given Exact Match rank, and a conversion of an 1223 // expression of class type to a base class of that type is 1224 // given Conversion rank, in spite of the fact that a copy/move 1225 // constructor (i.e., a user-defined conversion function) is 1226 // called for those cases. 1227 QualType FromType = From->getType(); 1228 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1229 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1230 S.IsDerivedFrom(FromType, ToType))) { 1231 ICS.setStandard(); 1232 ICS.Standard.setAsIdentityConversion(); 1233 ICS.Standard.setFromType(FromType); 1234 ICS.Standard.setAllToTypes(ToType); 1235 1236 // We don't actually check at this point whether there is a valid 1237 // copy/move constructor, since overloading just assumes that it 1238 // exists. When we actually perform initialization, we'll find the 1239 // appropriate constructor to copy the returned object, if needed. 1240 ICS.Standard.CopyConstructor = 0; 1241 1242 // Determine whether this is considered a derived-to-base conversion. 1243 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1244 ICS.Standard.Second = ICK_Derived_To_Base; 1245 1246 return ICS; 1247 } 1248 1249 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1250 AllowExplicit, InOverloadResolution, CStyle, 1251 AllowObjCWritebackConversion); 1252} 1253 1254ImplicitConversionSequence 1255Sema::TryImplicitConversion(Expr *From, QualType ToType, 1256 bool SuppressUserConversions, 1257 bool AllowExplicit, 1258 bool InOverloadResolution, 1259 bool CStyle, 1260 bool AllowObjCWritebackConversion) { 1261 return clang::TryImplicitConversion(*this, From, ToType, 1262 SuppressUserConversions, AllowExplicit, 1263 InOverloadResolution, CStyle, 1264 AllowObjCWritebackConversion); 1265} 1266 1267/// PerformImplicitConversion - Perform an implicit conversion of the 1268/// expression From to the type ToType. Returns the 1269/// converted expression. Flavor is the kind of conversion we're 1270/// performing, used in the error message. If @p AllowExplicit, 1271/// explicit user-defined conversions are permitted. 1272ExprResult 1273Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1274 AssignmentAction Action, bool AllowExplicit) { 1275 ImplicitConversionSequence ICS; 1276 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1277} 1278 1279ExprResult 1280Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1281 AssignmentAction Action, bool AllowExplicit, 1282 ImplicitConversionSequence& ICS) { 1283 if (checkPlaceholderForOverload(*this, From)) 1284 return ExprError(); 1285 1286 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1287 bool AllowObjCWritebackConversion 1288 = getLangOpts().ObjCAutoRefCount && 1289 (Action == AA_Passing || Action == AA_Sending); 1290 1291 ICS = clang::TryImplicitConversion(*this, From, ToType, 1292 /*SuppressUserConversions=*/false, 1293 AllowExplicit, 1294 /*InOverloadResolution=*/false, 1295 /*CStyle=*/false, 1296 AllowObjCWritebackConversion); 1297 return PerformImplicitConversion(From, ToType, ICS, Action); 1298} 1299 1300/// \brief Determine whether the conversion from FromType to ToType is a valid 1301/// conversion that strips "noreturn" off the nested function type. 1302bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1303 QualType &ResultTy) { 1304 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1305 return false; 1306 1307 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1308 // where F adds one of the following at most once: 1309 // - a pointer 1310 // - a member pointer 1311 // - a block pointer 1312 CanQualType CanTo = Context.getCanonicalType(ToType); 1313 CanQualType CanFrom = Context.getCanonicalType(FromType); 1314 Type::TypeClass TyClass = CanTo->getTypeClass(); 1315 if (TyClass != CanFrom->getTypeClass()) return false; 1316 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1317 if (TyClass == Type::Pointer) { 1318 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1319 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1320 } else if (TyClass == Type::BlockPointer) { 1321 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1322 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1323 } else if (TyClass == Type::MemberPointer) { 1324 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1325 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1326 } else { 1327 return false; 1328 } 1329 1330 TyClass = CanTo->getTypeClass(); 1331 if (TyClass != CanFrom->getTypeClass()) return false; 1332 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1333 return false; 1334 } 1335 1336 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1337 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1338 if (!EInfo.getNoReturn()) return false; 1339 1340 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1341 assert(QualType(FromFn, 0).isCanonical()); 1342 if (QualType(FromFn, 0) != CanTo) return false; 1343 1344 ResultTy = ToType; 1345 return true; 1346} 1347 1348/// \brief Determine whether the conversion from FromType to ToType is a valid 1349/// vector conversion. 1350/// 1351/// \param ICK Will be set to the vector conversion kind, if this is a vector 1352/// conversion. 1353static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1354 QualType ToType, ImplicitConversionKind &ICK) { 1355 // We need at least one of these types to be a vector type to have a vector 1356 // conversion. 1357 if (!ToType->isVectorType() && !FromType->isVectorType()) 1358 return false; 1359 1360 // Identical types require no conversions. 1361 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1362 return false; 1363 1364 // There are no conversions between extended vector types, only identity. 1365 if (ToType->isExtVectorType()) { 1366 // There are no conversions between extended vector types other than the 1367 // identity conversion. 1368 if (FromType->isExtVectorType()) 1369 return false; 1370 1371 // Vector splat from any arithmetic type to a vector. 1372 if (FromType->isArithmeticType()) { 1373 ICK = ICK_Vector_Splat; 1374 return true; 1375 } 1376 } 1377 1378 // We can perform the conversion between vector types in the following cases: 1379 // 1)vector types are equivalent AltiVec and GCC vector types 1380 // 2)lax vector conversions are permitted and the vector types are of the 1381 // same size 1382 if (ToType->isVectorType() && FromType->isVectorType()) { 1383 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1384 (Context.getLangOpts().LaxVectorConversions && 1385 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1386 ICK = ICK_Vector_Conversion; 1387 return true; 1388 } 1389 } 1390 1391 return false; 1392} 1393 1394static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1395 bool InOverloadResolution, 1396 StandardConversionSequence &SCS, 1397 bool CStyle); 1398 1399/// IsStandardConversion - Determines whether there is a standard 1400/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1401/// expression From to the type ToType. Standard conversion sequences 1402/// only consider non-class types; for conversions that involve class 1403/// types, use TryImplicitConversion. If a conversion exists, SCS will 1404/// contain the standard conversion sequence required to perform this 1405/// conversion and this routine will return true. Otherwise, this 1406/// routine will return false and the value of SCS is unspecified. 1407static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1408 bool InOverloadResolution, 1409 StandardConversionSequence &SCS, 1410 bool CStyle, 1411 bool AllowObjCWritebackConversion) { 1412 QualType FromType = From->getType(); 1413 1414 // Standard conversions (C++ [conv]) 1415 SCS.setAsIdentityConversion(); 1416 SCS.DeprecatedStringLiteralToCharPtr = false; 1417 SCS.IncompatibleObjC = false; 1418 SCS.setFromType(FromType); 1419 SCS.CopyConstructor = 0; 1420 1421 // There are no standard conversions for class types in C++, so 1422 // abort early. When overloading in C, however, we do permit 1423 if (FromType->isRecordType() || ToType->isRecordType()) { 1424 if (S.getLangOpts().CPlusPlus) 1425 return false; 1426 1427 // When we're overloading in C, we allow, as standard conversions, 1428 } 1429 1430 // The first conversion can be an lvalue-to-rvalue conversion, 1431 // array-to-pointer conversion, or function-to-pointer conversion 1432 // (C++ 4p1). 1433 1434 if (FromType == S.Context.OverloadTy) { 1435 DeclAccessPair AccessPair; 1436 if (FunctionDecl *Fn 1437 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1438 AccessPair)) { 1439 // We were able to resolve the address of the overloaded function, 1440 // so we can convert to the type of that function. 1441 FromType = Fn->getType(); 1442 1443 // we can sometimes resolve &foo<int> regardless of ToType, so check 1444 // if the type matches (identity) or we are converting to bool 1445 if (!S.Context.hasSameUnqualifiedType( 1446 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1447 QualType resultTy; 1448 // if the function type matches except for [[noreturn]], it's ok 1449 if (!S.IsNoReturnConversion(FromType, 1450 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1451 // otherwise, only a boolean conversion is standard 1452 if (!ToType->isBooleanType()) 1453 return false; 1454 } 1455 1456 // Check if the "from" expression is taking the address of an overloaded 1457 // function and recompute the FromType accordingly. Take advantage of the 1458 // fact that non-static member functions *must* have such an address-of 1459 // expression. 1460 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1461 if (Method && !Method->isStatic()) { 1462 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1463 "Non-unary operator on non-static member address"); 1464 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1465 == UO_AddrOf && 1466 "Non-address-of operator on non-static member address"); 1467 const Type *ClassType 1468 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1469 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1470 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1471 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1472 UO_AddrOf && 1473 "Non-address-of operator for overloaded function expression"); 1474 FromType = S.Context.getPointerType(FromType); 1475 } 1476 1477 // Check that we've computed the proper type after overload resolution. 1478 assert(S.Context.hasSameType( 1479 FromType, 1480 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1481 } else { 1482 return false; 1483 } 1484 } 1485 // Lvalue-to-rvalue conversion (C++11 4.1): 1486 // A glvalue (3.10) of a non-function, non-array type T can 1487 // be converted to a prvalue. 1488 bool argIsLValue = From->isGLValue(); 1489 if (argIsLValue && 1490 !FromType->isFunctionType() && !FromType->isArrayType() && 1491 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1492 SCS.First = ICK_Lvalue_To_Rvalue; 1493 1494 // C11 6.3.2.1p2: 1495 // ... if the lvalue has atomic type, the value has the non-atomic version 1496 // of the type of the lvalue ... 1497 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1498 FromType = Atomic->getValueType(); 1499 1500 // If T is a non-class type, the type of the rvalue is the 1501 // cv-unqualified version of T. Otherwise, the type of the rvalue 1502 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1503 // just strip the qualifiers because they don't matter. 1504 FromType = FromType.getUnqualifiedType(); 1505 } else if (FromType->isArrayType()) { 1506 // Array-to-pointer conversion (C++ 4.2) 1507 SCS.First = ICK_Array_To_Pointer; 1508 1509 // An lvalue or rvalue of type "array of N T" or "array of unknown 1510 // bound of T" can be converted to an rvalue of type "pointer to 1511 // T" (C++ 4.2p1). 1512 FromType = S.Context.getArrayDecayedType(FromType); 1513 1514 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1515 // This conversion is deprecated. (C++ D.4). 1516 SCS.DeprecatedStringLiteralToCharPtr = true; 1517 1518 // For the purpose of ranking in overload resolution 1519 // (13.3.3.1.1), this conversion is considered an 1520 // array-to-pointer conversion followed by a qualification 1521 // conversion (4.4). (C++ 4.2p2) 1522 SCS.Second = ICK_Identity; 1523 SCS.Third = ICK_Qualification; 1524 SCS.QualificationIncludesObjCLifetime = false; 1525 SCS.setAllToTypes(FromType); 1526 return true; 1527 } 1528 } else if (FromType->isFunctionType() && argIsLValue) { 1529 // Function-to-pointer conversion (C++ 4.3). 1530 SCS.First = ICK_Function_To_Pointer; 1531 1532 // An lvalue of function type T can be converted to an rvalue of 1533 // type "pointer to T." The result is a pointer to the 1534 // function. (C++ 4.3p1). 1535 FromType = S.Context.getPointerType(FromType); 1536 } else { 1537 // We don't require any conversions for the first step. 1538 SCS.First = ICK_Identity; 1539 } 1540 SCS.setToType(0, FromType); 1541 1542 // The second conversion can be an integral promotion, floating 1543 // point promotion, integral conversion, floating point conversion, 1544 // floating-integral conversion, pointer conversion, 1545 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1546 // For overloading in C, this can also be a "compatible-type" 1547 // conversion. 1548 bool IncompatibleObjC = false; 1549 ImplicitConversionKind SecondICK = ICK_Identity; 1550 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1551 // The unqualified versions of the types are the same: there's no 1552 // conversion to do. 1553 SCS.Second = ICK_Identity; 1554 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1555 // Integral promotion (C++ 4.5). 1556 SCS.Second = ICK_Integral_Promotion; 1557 FromType = ToType.getUnqualifiedType(); 1558 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1559 // Floating point promotion (C++ 4.6). 1560 SCS.Second = ICK_Floating_Promotion; 1561 FromType = ToType.getUnqualifiedType(); 1562 } else if (S.IsComplexPromotion(FromType, ToType)) { 1563 // Complex promotion (Clang extension) 1564 SCS.Second = ICK_Complex_Promotion; 1565 FromType = ToType.getUnqualifiedType(); 1566 } else if (ToType->isBooleanType() && 1567 (FromType->isArithmeticType() || 1568 FromType->isAnyPointerType() || 1569 FromType->isBlockPointerType() || 1570 FromType->isMemberPointerType() || 1571 FromType->isNullPtrType())) { 1572 // Boolean conversions (C++ 4.12). 1573 SCS.Second = ICK_Boolean_Conversion; 1574 FromType = S.Context.BoolTy; 1575 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1576 ToType->isIntegralType(S.Context)) { 1577 // Integral conversions (C++ 4.7). 1578 SCS.Second = ICK_Integral_Conversion; 1579 FromType = ToType.getUnqualifiedType(); 1580 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1581 // Complex conversions (C99 6.3.1.6) 1582 SCS.Second = ICK_Complex_Conversion; 1583 FromType = ToType.getUnqualifiedType(); 1584 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1585 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1586 // Complex-real conversions (C99 6.3.1.7) 1587 SCS.Second = ICK_Complex_Real; 1588 FromType = ToType.getUnqualifiedType(); 1589 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1590 // Floating point conversions (C++ 4.8). 1591 SCS.Second = ICK_Floating_Conversion; 1592 FromType = ToType.getUnqualifiedType(); 1593 } else if ((FromType->isRealFloatingType() && 1594 ToType->isIntegralType(S.Context)) || 1595 (FromType->isIntegralOrUnscopedEnumerationType() && 1596 ToType->isRealFloatingType())) { 1597 // Floating-integral conversions (C++ 4.9). 1598 SCS.Second = ICK_Floating_Integral; 1599 FromType = ToType.getUnqualifiedType(); 1600 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1601 SCS.Second = ICK_Block_Pointer_Conversion; 1602 } else if (AllowObjCWritebackConversion && 1603 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1604 SCS.Second = ICK_Writeback_Conversion; 1605 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1606 FromType, IncompatibleObjC)) { 1607 // Pointer conversions (C++ 4.10). 1608 SCS.Second = ICK_Pointer_Conversion; 1609 SCS.IncompatibleObjC = IncompatibleObjC; 1610 FromType = FromType.getUnqualifiedType(); 1611 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1612 InOverloadResolution, FromType)) { 1613 // Pointer to member conversions (4.11). 1614 SCS.Second = ICK_Pointer_Member; 1615 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1616 SCS.Second = SecondICK; 1617 FromType = ToType.getUnqualifiedType(); 1618 } else if (!S.getLangOpts().CPlusPlus && 1619 S.Context.typesAreCompatible(ToType, FromType)) { 1620 // Compatible conversions (Clang extension for C function overloading) 1621 SCS.Second = ICK_Compatible_Conversion; 1622 FromType = ToType.getUnqualifiedType(); 1623 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1624 // Treat a conversion that strips "noreturn" as an identity conversion. 1625 SCS.Second = ICK_NoReturn_Adjustment; 1626 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1627 InOverloadResolution, 1628 SCS, CStyle)) { 1629 SCS.Second = ICK_TransparentUnionConversion; 1630 FromType = ToType; 1631 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1632 CStyle)) { 1633 // tryAtomicConversion has updated the standard conversion sequence 1634 // appropriately. 1635 return true; 1636 } else if (ToType->isEventT() && 1637 From->isIntegerConstantExpr(S.getASTContext()) && 1638 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1639 SCS.Second = ICK_Zero_Event_Conversion; 1640 FromType = ToType; 1641 } else { 1642 // No second conversion required. 1643 SCS.Second = ICK_Identity; 1644 } 1645 SCS.setToType(1, FromType); 1646 1647 QualType CanonFrom; 1648 QualType CanonTo; 1649 // The third conversion can be a qualification conversion (C++ 4p1). 1650 bool ObjCLifetimeConversion; 1651 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1652 ObjCLifetimeConversion)) { 1653 SCS.Third = ICK_Qualification; 1654 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1655 FromType = ToType; 1656 CanonFrom = S.Context.getCanonicalType(FromType); 1657 CanonTo = S.Context.getCanonicalType(ToType); 1658 } else { 1659 // No conversion required 1660 SCS.Third = ICK_Identity; 1661 1662 // C++ [over.best.ics]p6: 1663 // [...] Any difference in top-level cv-qualification is 1664 // subsumed by the initialization itself and does not constitute 1665 // a conversion. [...] 1666 CanonFrom = S.Context.getCanonicalType(FromType); 1667 CanonTo = S.Context.getCanonicalType(ToType); 1668 if (CanonFrom.getLocalUnqualifiedType() 1669 == CanonTo.getLocalUnqualifiedType() && 1670 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1671 FromType = ToType; 1672 CanonFrom = CanonTo; 1673 } 1674 } 1675 SCS.setToType(2, FromType); 1676 1677 // If we have not converted the argument type to the parameter type, 1678 // this is a bad conversion sequence. 1679 if (CanonFrom != CanonTo) 1680 return false; 1681 1682 return true; 1683} 1684 1685static bool 1686IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1687 QualType &ToType, 1688 bool InOverloadResolution, 1689 StandardConversionSequence &SCS, 1690 bool CStyle) { 1691 1692 const RecordType *UT = ToType->getAsUnionType(); 1693 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1694 return false; 1695 // The field to initialize within the transparent union. 1696 RecordDecl *UD = UT->getDecl(); 1697 // It's compatible if the expression matches any of the fields. 1698 for (RecordDecl::field_iterator it = UD->field_begin(), 1699 itend = UD->field_end(); 1700 it != itend; ++it) { 1701 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1702 CStyle, /*ObjCWritebackConversion=*/false)) { 1703 ToType = it->getType(); 1704 return true; 1705 } 1706 } 1707 return false; 1708} 1709 1710/// IsIntegralPromotion - Determines whether the conversion from the 1711/// expression From (whose potentially-adjusted type is FromType) to 1712/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1713/// sets PromotedType to the promoted type. 1714bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1715 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1716 // All integers are built-in. 1717 if (!To) { 1718 return false; 1719 } 1720 1721 // An rvalue of type char, signed char, unsigned char, short int, or 1722 // unsigned short int can be converted to an rvalue of type int if 1723 // int can represent all the values of the source type; otherwise, 1724 // the source rvalue can be converted to an rvalue of type unsigned 1725 // int (C++ 4.5p1). 1726 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1727 !FromType->isEnumeralType()) { 1728 if (// We can promote any signed, promotable integer type to an int 1729 (FromType->isSignedIntegerType() || 1730 // We can promote any unsigned integer type whose size is 1731 // less than int to an int. 1732 (!FromType->isSignedIntegerType() && 1733 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1734 return To->getKind() == BuiltinType::Int; 1735 } 1736 1737 return To->getKind() == BuiltinType::UInt; 1738 } 1739 1740 // C++11 [conv.prom]p3: 1741 // A prvalue of an unscoped enumeration type whose underlying type is not 1742 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1743 // following types that can represent all the values of the enumeration 1744 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1745 // unsigned int, long int, unsigned long int, long long int, or unsigned 1746 // long long int. If none of the types in that list can represent all the 1747 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1748 // type can be converted to an rvalue a prvalue of the extended integer type 1749 // with lowest integer conversion rank (4.13) greater than the rank of long 1750 // long in which all the values of the enumeration can be represented. If 1751 // there are two such extended types, the signed one is chosen. 1752 // C++11 [conv.prom]p4: 1753 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1754 // can be converted to a prvalue of its underlying type. Moreover, if 1755 // integral promotion can be applied to its underlying type, a prvalue of an 1756 // unscoped enumeration type whose underlying type is fixed can also be 1757 // converted to a prvalue of the promoted underlying type. 1758 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1759 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1760 // provided for a scoped enumeration. 1761 if (FromEnumType->getDecl()->isScoped()) 1762 return false; 1763 1764 // We can perform an integral promotion to the underlying type of the enum, 1765 // even if that's not the promoted type. 1766 if (FromEnumType->getDecl()->isFixed()) { 1767 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1768 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1769 IsIntegralPromotion(From, Underlying, ToType); 1770 } 1771 1772 // We have already pre-calculated the promotion type, so this is trivial. 1773 if (ToType->isIntegerType() && 1774 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1775 return Context.hasSameUnqualifiedType(ToType, 1776 FromEnumType->getDecl()->getPromotionType()); 1777 } 1778 1779 // C++0x [conv.prom]p2: 1780 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1781 // to an rvalue a prvalue of the first of the following types that can 1782 // represent all the values of its underlying type: int, unsigned int, 1783 // long int, unsigned long int, long long int, or unsigned long long int. 1784 // If none of the types in that list can represent all the values of its 1785 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1786 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1787 // type. 1788 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1789 ToType->isIntegerType()) { 1790 // Determine whether the type we're converting from is signed or 1791 // unsigned. 1792 bool FromIsSigned = FromType->isSignedIntegerType(); 1793 uint64_t FromSize = Context.getTypeSize(FromType); 1794 1795 // The types we'll try to promote to, in the appropriate 1796 // order. Try each of these types. 1797 QualType PromoteTypes[6] = { 1798 Context.IntTy, Context.UnsignedIntTy, 1799 Context.LongTy, Context.UnsignedLongTy , 1800 Context.LongLongTy, Context.UnsignedLongLongTy 1801 }; 1802 for (int Idx = 0; Idx < 6; ++Idx) { 1803 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1804 if (FromSize < ToSize || 1805 (FromSize == ToSize && 1806 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1807 // We found the type that we can promote to. If this is the 1808 // type we wanted, we have a promotion. Otherwise, no 1809 // promotion. 1810 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1811 } 1812 } 1813 } 1814 1815 // An rvalue for an integral bit-field (9.6) can be converted to an 1816 // rvalue of type int if int can represent all the values of the 1817 // bit-field; otherwise, it can be converted to unsigned int if 1818 // unsigned int can represent all the values of the bit-field. If 1819 // the bit-field is larger yet, no integral promotion applies to 1820 // it. If the bit-field has an enumerated type, it is treated as any 1821 // other value of that type for promotion purposes (C++ 4.5p3). 1822 // FIXME: We should delay checking of bit-fields until we actually perform the 1823 // conversion. 1824 using llvm::APSInt; 1825 if (From) 1826 if (FieldDecl *MemberDecl = From->getBitField()) { 1827 APSInt BitWidth; 1828 if (FromType->isIntegralType(Context) && 1829 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1830 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1831 ToSize = Context.getTypeSize(ToType); 1832 1833 // Are we promoting to an int from a bitfield that fits in an int? 1834 if (BitWidth < ToSize || 1835 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1836 return To->getKind() == BuiltinType::Int; 1837 } 1838 1839 // Are we promoting to an unsigned int from an unsigned bitfield 1840 // that fits into an unsigned int? 1841 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1842 return To->getKind() == BuiltinType::UInt; 1843 } 1844 1845 return false; 1846 } 1847 } 1848 1849 // An rvalue of type bool can be converted to an rvalue of type int, 1850 // with false becoming zero and true becoming one (C++ 4.5p4). 1851 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1852 return true; 1853 } 1854 1855 return false; 1856} 1857 1858/// IsFloatingPointPromotion - Determines whether the conversion from 1859/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1860/// returns true and sets PromotedType to the promoted type. 1861bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1862 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1863 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1864 /// An rvalue of type float can be converted to an rvalue of type 1865 /// double. (C++ 4.6p1). 1866 if (FromBuiltin->getKind() == BuiltinType::Float && 1867 ToBuiltin->getKind() == BuiltinType::Double) 1868 return true; 1869 1870 // C99 6.3.1.5p1: 1871 // When a float is promoted to double or long double, or a 1872 // double is promoted to long double [...]. 1873 if (!getLangOpts().CPlusPlus && 1874 (FromBuiltin->getKind() == BuiltinType::Float || 1875 FromBuiltin->getKind() == BuiltinType::Double) && 1876 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1877 return true; 1878 1879 // Half can be promoted to float. 1880 if (!getLangOpts().NativeHalfType && 1881 FromBuiltin->getKind() == BuiltinType::Half && 1882 ToBuiltin->getKind() == BuiltinType::Float) 1883 return true; 1884 } 1885 1886 return false; 1887} 1888 1889/// \brief Determine if a conversion is a complex promotion. 1890/// 1891/// A complex promotion is defined as a complex -> complex conversion 1892/// where the conversion between the underlying real types is a 1893/// floating-point or integral promotion. 1894bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1895 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1896 if (!FromComplex) 1897 return false; 1898 1899 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1900 if (!ToComplex) 1901 return false; 1902 1903 return IsFloatingPointPromotion(FromComplex->getElementType(), 1904 ToComplex->getElementType()) || 1905 IsIntegralPromotion(0, FromComplex->getElementType(), 1906 ToComplex->getElementType()); 1907} 1908 1909/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1910/// the pointer type FromPtr to a pointer to type ToPointee, with the 1911/// same type qualifiers as FromPtr has on its pointee type. ToType, 1912/// if non-empty, will be a pointer to ToType that may or may not have 1913/// the right set of qualifiers on its pointee. 1914/// 1915static QualType 1916BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1917 QualType ToPointee, QualType ToType, 1918 ASTContext &Context, 1919 bool StripObjCLifetime = false) { 1920 assert((FromPtr->getTypeClass() == Type::Pointer || 1921 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1922 "Invalid similarly-qualified pointer type"); 1923 1924 /// Conversions to 'id' subsume cv-qualifier conversions. 1925 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1926 return ToType.getUnqualifiedType(); 1927 1928 QualType CanonFromPointee 1929 = Context.getCanonicalType(FromPtr->getPointeeType()); 1930 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1931 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1932 1933 if (StripObjCLifetime) 1934 Quals.removeObjCLifetime(); 1935 1936 // Exact qualifier match -> return the pointer type we're converting to. 1937 if (CanonToPointee.getLocalQualifiers() == Quals) { 1938 // ToType is exactly what we need. Return it. 1939 if (!ToType.isNull()) 1940 return ToType.getUnqualifiedType(); 1941 1942 // Build a pointer to ToPointee. It has the right qualifiers 1943 // already. 1944 if (isa<ObjCObjectPointerType>(ToType)) 1945 return Context.getObjCObjectPointerType(ToPointee); 1946 return Context.getPointerType(ToPointee); 1947 } 1948 1949 // Just build a canonical type that has the right qualifiers. 1950 QualType QualifiedCanonToPointee 1951 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1952 1953 if (isa<ObjCObjectPointerType>(ToType)) 1954 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1955 return Context.getPointerType(QualifiedCanonToPointee); 1956} 1957 1958static bool isNullPointerConstantForConversion(Expr *Expr, 1959 bool InOverloadResolution, 1960 ASTContext &Context) { 1961 // Handle value-dependent integral null pointer constants correctly. 1962 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1963 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1964 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1965 return !InOverloadResolution; 1966 1967 return Expr->isNullPointerConstant(Context, 1968 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1969 : Expr::NPC_ValueDependentIsNull); 1970} 1971 1972/// IsPointerConversion - Determines whether the conversion of the 1973/// expression From, which has the (possibly adjusted) type FromType, 1974/// can be converted to the type ToType via a pointer conversion (C++ 1975/// 4.10). If so, returns true and places the converted type (that 1976/// might differ from ToType in its cv-qualifiers at some level) into 1977/// ConvertedType. 1978/// 1979/// This routine also supports conversions to and from block pointers 1980/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1981/// pointers to interfaces. FIXME: Once we've determined the 1982/// appropriate overloading rules for Objective-C, we may want to 1983/// split the Objective-C checks into a different routine; however, 1984/// GCC seems to consider all of these conversions to be pointer 1985/// conversions, so for now they live here. IncompatibleObjC will be 1986/// set if the conversion is an allowed Objective-C conversion that 1987/// should result in a warning. 1988bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1989 bool InOverloadResolution, 1990 QualType& ConvertedType, 1991 bool &IncompatibleObjC) { 1992 IncompatibleObjC = false; 1993 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1994 IncompatibleObjC)) 1995 return true; 1996 1997 // Conversion from a null pointer constant to any Objective-C pointer type. 1998 if (ToType->isObjCObjectPointerType() && 1999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2000 ConvertedType = ToType; 2001 return true; 2002 } 2003 2004 // Blocks: Block pointers can be converted to void*. 2005 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2006 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2007 ConvertedType = ToType; 2008 return true; 2009 } 2010 // Blocks: A null pointer constant can be converted to a block 2011 // pointer type. 2012 if (ToType->isBlockPointerType() && 2013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2014 ConvertedType = ToType; 2015 return true; 2016 } 2017 2018 // If the left-hand-side is nullptr_t, the right side can be a null 2019 // pointer constant. 2020 if (ToType->isNullPtrType() && 2021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2022 ConvertedType = ToType; 2023 return true; 2024 } 2025 2026 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2027 if (!ToTypePtr) 2028 return false; 2029 2030 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2031 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2032 ConvertedType = ToType; 2033 return true; 2034 } 2035 2036 // Beyond this point, both types need to be pointers 2037 // , including objective-c pointers. 2038 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2039 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2040 !getLangOpts().ObjCAutoRefCount) { 2041 ConvertedType = BuildSimilarlyQualifiedPointerType( 2042 FromType->getAs<ObjCObjectPointerType>(), 2043 ToPointeeType, 2044 ToType, Context); 2045 return true; 2046 } 2047 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2048 if (!FromTypePtr) 2049 return false; 2050 2051 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2052 2053 // If the unqualified pointee types are the same, this can't be a 2054 // pointer conversion, so don't do all of the work below. 2055 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2056 return false; 2057 2058 // An rvalue of type "pointer to cv T," where T is an object type, 2059 // can be converted to an rvalue of type "pointer to cv void" (C++ 2060 // 4.10p2). 2061 if (FromPointeeType->isIncompleteOrObjectType() && 2062 ToPointeeType->isVoidType()) { 2063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2064 ToPointeeType, 2065 ToType, Context, 2066 /*StripObjCLifetime=*/true); 2067 return true; 2068 } 2069 2070 // MSVC allows implicit function to void* type conversion. 2071 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2072 ToPointeeType->isVoidType()) { 2073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2074 ToPointeeType, 2075 ToType, Context); 2076 return true; 2077 } 2078 2079 // When we're overloading in C, we allow a special kind of pointer 2080 // conversion for compatible-but-not-identical pointee types. 2081 if (!getLangOpts().CPlusPlus && 2082 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2083 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2084 ToPointeeType, 2085 ToType, Context); 2086 return true; 2087 } 2088 2089 // C++ [conv.ptr]p3: 2090 // 2091 // An rvalue of type "pointer to cv D," where D is a class type, 2092 // can be converted to an rvalue of type "pointer to cv B," where 2093 // B is a base class (clause 10) of D. If B is an inaccessible 2094 // (clause 11) or ambiguous (10.2) base class of D, a program that 2095 // necessitates this conversion is ill-formed. The result of the 2096 // conversion is a pointer to the base class sub-object of the 2097 // derived class object. The null pointer value is converted to 2098 // the null pointer value of the destination type. 2099 // 2100 // Note that we do not check for ambiguity or inaccessibility 2101 // here. That is handled by CheckPointerConversion. 2102 if (getLangOpts().CPlusPlus && 2103 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2104 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2105 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2106 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2108 ToPointeeType, 2109 ToType, Context); 2110 return true; 2111 } 2112 2113 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2114 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2116 ToPointeeType, 2117 ToType, Context); 2118 return true; 2119 } 2120 2121 return false; 2122} 2123 2124/// \brief Adopt the given qualifiers for the given type. 2125static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2126 Qualifiers TQs = T.getQualifiers(); 2127 2128 // Check whether qualifiers already match. 2129 if (TQs == Qs) 2130 return T; 2131 2132 if (Qs.compatiblyIncludes(TQs)) 2133 return Context.getQualifiedType(T, Qs); 2134 2135 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2136} 2137 2138/// isObjCPointerConversion - Determines whether this is an 2139/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2140/// with the same arguments and return values. 2141bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2142 QualType& ConvertedType, 2143 bool &IncompatibleObjC) { 2144 if (!getLangOpts().ObjC1) 2145 return false; 2146 2147 // The set of qualifiers on the type we're converting from. 2148 Qualifiers FromQualifiers = FromType.getQualifiers(); 2149 2150 // First, we handle all conversions on ObjC object pointer types. 2151 const ObjCObjectPointerType* ToObjCPtr = 2152 ToType->getAs<ObjCObjectPointerType>(); 2153 const ObjCObjectPointerType *FromObjCPtr = 2154 FromType->getAs<ObjCObjectPointerType>(); 2155 2156 if (ToObjCPtr && FromObjCPtr) { 2157 // If the pointee types are the same (ignoring qualifications), 2158 // then this is not a pointer conversion. 2159 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2160 FromObjCPtr->getPointeeType())) 2161 return false; 2162 2163 // Check for compatible 2164 // Objective C++: We're able to convert between "id" or "Class" and a 2165 // pointer to any interface (in both directions). 2166 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2167 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2168 return true; 2169 } 2170 // Conversions with Objective-C's id<...>. 2171 if ((FromObjCPtr->isObjCQualifiedIdType() || 2172 ToObjCPtr->isObjCQualifiedIdType()) && 2173 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2174 /*compare=*/false)) { 2175 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2176 return true; 2177 } 2178 // Objective C++: We're able to convert from a pointer to an 2179 // interface to a pointer to a different interface. 2180 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2181 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2182 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2183 if (getLangOpts().CPlusPlus && LHS && RHS && 2184 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2185 FromObjCPtr->getPointeeType())) 2186 return false; 2187 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2188 ToObjCPtr->getPointeeType(), 2189 ToType, Context); 2190 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2191 return true; 2192 } 2193 2194 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2195 // Okay: this is some kind of implicit downcast of Objective-C 2196 // interfaces, which is permitted. However, we're going to 2197 // complain about it. 2198 IncompatibleObjC = true; 2199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2200 ToObjCPtr->getPointeeType(), 2201 ToType, Context); 2202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2203 return true; 2204 } 2205 } 2206 // Beyond this point, both types need to be C pointers or block pointers. 2207 QualType ToPointeeType; 2208 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2209 ToPointeeType = ToCPtr->getPointeeType(); 2210 else if (const BlockPointerType *ToBlockPtr = 2211 ToType->getAs<BlockPointerType>()) { 2212 // Objective C++: We're able to convert from a pointer to any object 2213 // to a block pointer type. 2214 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2215 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2216 return true; 2217 } 2218 ToPointeeType = ToBlockPtr->getPointeeType(); 2219 } 2220 else if (FromType->getAs<BlockPointerType>() && 2221 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2222 // Objective C++: We're able to convert from a block pointer type to a 2223 // pointer to any object. 2224 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2225 return true; 2226 } 2227 else 2228 return false; 2229 2230 QualType FromPointeeType; 2231 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2232 FromPointeeType = FromCPtr->getPointeeType(); 2233 else if (const BlockPointerType *FromBlockPtr = 2234 FromType->getAs<BlockPointerType>()) 2235 FromPointeeType = FromBlockPtr->getPointeeType(); 2236 else 2237 return false; 2238 2239 // If we have pointers to pointers, recursively check whether this 2240 // is an Objective-C conversion. 2241 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2242 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2243 IncompatibleObjC)) { 2244 // We always complain about this conversion. 2245 IncompatibleObjC = true; 2246 ConvertedType = Context.getPointerType(ConvertedType); 2247 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2248 return true; 2249 } 2250 // Allow conversion of pointee being objective-c pointer to another one; 2251 // as in I* to id. 2252 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2253 ToPointeeType->getAs<ObjCObjectPointerType>() && 2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2255 IncompatibleObjC)) { 2256 2257 ConvertedType = Context.getPointerType(ConvertedType); 2258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2259 return true; 2260 } 2261 2262 // If we have pointers to functions or blocks, check whether the only 2263 // differences in the argument and result types are in Objective-C 2264 // pointer conversions. If so, we permit the conversion (but 2265 // complain about it). 2266 const FunctionProtoType *FromFunctionType 2267 = FromPointeeType->getAs<FunctionProtoType>(); 2268 const FunctionProtoType *ToFunctionType 2269 = ToPointeeType->getAs<FunctionProtoType>(); 2270 if (FromFunctionType && ToFunctionType) { 2271 // If the function types are exactly the same, this isn't an 2272 // Objective-C pointer conversion. 2273 if (Context.getCanonicalType(FromPointeeType) 2274 == Context.getCanonicalType(ToPointeeType)) 2275 return false; 2276 2277 // Perform the quick checks that will tell us whether these 2278 // function types are obviously different. 2279 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2280 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2281 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2282 return false; 2283 2284 bool HasObjCConversion = false; 2285 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2286 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2287 // Okay, the types match exactly. Nothing to do. 2288 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2289 ToFunctionType->getResultType(), 2290 ConvertedType, IncompatibleObjC)) { 2291 // Okay, we have an Objective-C pointer conversion. 2292 HasObjCConversion = true; 2293 } else { 2294 // Function types are too different. Abort. 2295 return false; 2296 } 2297 2298 // Check argument types. 2299 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2300 ArgIdx != NumArgs; ++ArgIdx) { 2301 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2302 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2303 if (Context.getCanonicalType(FromArgType) 2304 == Context.getCanonicalType(ToArgType)) { 2305 // Okay, the types match exactly. Nothing to do. 2306 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2307 ConvertedType, IncompatibleObjC)) { 2308 // Okay, we have an Objective-C pointer conversion. 2309 HasObjCConversion = true; 2310 } else { 2311 // Argument types are too different. Abort. 2312 return false; 2313 } 2314 } 2315 2316 if (HasObjCConversion) { 2317 // We had an Objective-C conversion. Allow this pointer 2318 // conversion, but complain about it. 2319 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2320 IncompatibleObjC = true; 2321 return true; 2322 } 2323 } 2324 2325 return false; 2326} 2327 2328/// \brief Determine whether this is an Objective-C writeback conversion, 2329/// used for parameter passing when performing automatic reference counting. 2330/// 2331/// \param FromType The type we're converting form. 2332/// 2333/// \param ToType The type we're converting to. 2334/// 2335/// \param ConvertedType The type that will be produced after applying 2336/// this conversion. 2337bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2338 QualType &ConvertedType) { 2339 if (!getLangOpts().ObjCAutoRefCount || 2340 Context.hasSameUnqualifiedType(FromType, ToType)) 2341 return false; 2342 2343 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2344 QualType ToPointee; 2345 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2346 ToPointee = ToPointer->getPointeeType(); 2347 else 2348 return false; 2349 2350 Qualifiers ToQuals = ToPointee.getQualifiers(); 2351 if (!ToPointee->isObjCLifetimeType() || 2352 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2353 !ToQuals.withoutObjCLifetime().empty()) 2354 return false; 2355 2356 // Argument must be a pointer to __strong to __weak. 2357 QualType FromPointee; 2358 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2359 FromPointee = FromPointer->getPointeeType(); 2360 else 2361 return false; 2362 2363 Qualifiers FromQuals = FromPointee.getQualifiers(); 2364 if (!FromPointee->isObjCLifetimeType() || 2365 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2366 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2367 return false; 2368 2369 // Make sure that we have compatible qualifiers. 2370 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2371 if (!ToQuals.compatiblyIncludes(FromQuals)) 2372 return false; 2373 2374 // Remove qualifiers from the pointee type we're converting from; they 2375 // aren't used in the compatibility check belong, and we'll be adding back 2376 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2377 FromPointee = FromPointee.getUnqualifiedType(); 2378 2379 // The unqualified form of the pointee types must be compatible. 2380 ToPointee = ToPointee.getUnqualifiedType(); 2381 bool IncompatibleObjC; 2382 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2383 FromPointee = ToPointee; 2384 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2385 IncompatibleObjC)) 2386 return false; 2387 2388 /// \brief Construct the type we're converting to, which is a pointer to 2389 /// __autoreleasing pointee. 2390 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2391 ConvertedType = Context.getPointerType(FromPointee); 2392 return true; 2393} 2394 2395bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2396 QualType& ConvertedType) { 2397 QualType ToPointeeType; 2398 if (const BlockPointerType *ToBlockPtr = 2399 ToType->getAs<BlockPointerType>()) 2400 ToPointeeType = ToBlockPtr->getPointeeType(); 2401 else 2402 return false; 2403 2404 QualType FromPointeeType; 2405 if (const BlockPointerType *FromBlockPtr = 2406 FromType->getAs<BlockPointerType>()) 2407 FromPointeeType = FromBlockPtr->getPointeeType(); 2408 else 2409 return false; 2410 // We have pointer to blocks, check whether the only 2411 // differences in the argument and result types are in Objective-C 2412 // pointer conversions. If so, we permit the conversion. 2413 2414 const FunctionProtoType *FromFunctionType 2415 = FromPointeeType->getAs<FunctionProtoType>(); 2416 const FunctionProtoType *ToFunctionType 2417 = ToPointeeType->getAs<FunctionProtoType>(); 2418 2419 if (!FromFunctionType || !ToFunctionType) 2420 return false; 2421 2422 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2423 return true; 2424 2425 // Perform the quick checks that will tell us whether these 2426 // function types are obviously different. 2427 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2428 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2429 return false; 2430 2431 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2432 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2433 if (FromEInfo != ToEInfo) 2434 return false; 2435 2436 bool IncompatibleObjC = false; 2437 if (Context.hasSameType(FromFunctionType->getResultType(), 2438 ToFunctionType->getResultType())) { 2439 // Okay, the types match exactly. Nothing to do. 2440 } else { 2441 QualType RHS = FromFunctionType->getResultType(); 2442 QualType LHS = ToFunctionType->getResultType(); 2443 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2444 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2445 LHS = LHS.getUnqualifiedType(); 2446 2447 if (Context.hasSameType(RHS,LHS)) { 2448 // OK exact match. 2449 } else if (isObjCPointerConversion(RHS, LHS, 2450 ConvertedType, IncompatibleObjC)) { 2451 if (IncompatibleObjC) 2452 return false; 2453 // Okay, we have an Objective-C pointer conversion. 2454 } 2455 else 2456 return false; 2457 } 2458 2459 // Check argument types. 2460 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2461 ArgIdx != NumArgs; ++ArgIdx) { 2462 IncompatibleObjC = false; 2463 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2464 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2465 if (Context.hasSameType(FromArgType, ToArgType)) { 2466 // Okay, the types match exactly. Nothing to do. 2467 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2468 ConvertedType, IncompatibleObjC)) { 2469 if (IncompatibleObjC) 2470 return false; 2471 // Okay, we have an Objective-C pointer conversion. 2472 } else 2473 // Argument types are too different. Abort. 2474 return false; 2475 } 2476 if (LangOpts.ObjCAutoRefCount && 2477 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2478 ToFunctionType)) 2479 return false; 2480 2481 ConvertedType = ToType; 2482 return true; 2483} 2484 2485enum { 2486 ft_default, 2487 ft_different_class, 2488 ft_parameter_arity, 2489 ft_parameter_mismatch, 2490 ft_return_type, 2491 ft_qualifer_mismatch 2492}; 2493 2494/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2495/// function types. Catches different number of parameter, mismatch in 2496/// parameter types, and different return types. 2497void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2498 QualType FromType, QualType ToType) { 2499 // If either type is not valid, include no extra info. 2500 if (FromType.isNull() || ToType.isNull()) { 2501 PDiag << ft_default; 2502 return; 2503 } 2504 2505 // Get the function type from the pointers. 2506 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2507 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2508 *ToMember = ToType->getAs<MemberPointerType>(); 2509 if (FromMember->getClass() != ToMember->getClass()) { 2510 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2511 << QualType(FromMember->getClass(), 0); 2512 return; 2513 } 2514 FromType = FromMember->getPointeeType(); 2515 ToType = ToMember->getPointeeType(); 2516 } 2517 2518 if (FromType->isPointerType()) 2519 FromType = FromType->getPointeeType(); 2520 if (ToType->isPointerType()) 2521 ToType = ToType->getPointeeType(); 2522 2523 // Remove references. 2524 FromType = FromType.getNonReferenceType(); 2525 ToType = ToType.getNonReferenceType(); 2526 2527 // Don't print extra info for non-specialized template functions. 2528 if (FromType->isInstantiationDependentType() && 2529 !FromType->getAs<TemplateSpecializationType>()) { 2530 PDiag << ft_default; 2531 return; 2532 } 2533 2534 // No extra info for same types. 2535 if (Context.hasSameType(FromType, ToType)) { 2536 PDiag << ft_default; 2537 return; 2538 } 2539 2540 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2541 *ToFunction = ToType->getAs<FunctionProtoType>(); 2542 2543 // Both types need to be function types. 2544 if (!FromFunction || !ToFunction) { 2545 PDiag << ft_default; 2546 return; 2547 } 2548 2549 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2550 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2551 << FromFunction->getNumArgs(); 2552 return; 2553 } 2554 2555 // Handle different parameter types. 2556 unsigned ArgPos; 2557 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2558 PDiag << ft_parameter_mismatch << ArgPos + 1 2559 << ToFunction->getArgType(ArgPos) 2560 << FromFunction->getArgType(ArgPos); 2561 return; 2562 } 2563 2564 // Handle different return type. 2565 if (!Context.hasSameType(FromFunction->getResultType(), 2566 ToFunction->getResultType())) { 2567 PDiag << ft_return_type << ToFunction->getResultType() 2568 << FromFunction->getResultType(); 2569 return; 2570 } 2571 2572 unsigned FromQuals = FromFunction->getTypeQuals(), 2573 ToQuals = ToFunction->getTypeQuals(); 2574 if (FromQuals != ToQuals) { 2575 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2576 return; 2577 } 2578 2579 // Unable to find a difference, so add no extra info. 2580 PDiag << ft_default; 2581} 2582 2583/// FunctionArgTypesAreEqual - This routine checks two function proto types 2584/// for equality of their argument types. Caller has already checked that 2585/// they have same number of arguments. This routine assumes that Objective-C 2586/// pointer types which only differ in their protocol qualifiers are equal. 2587/// If the parameters are different, ArgPos will have the parameter index 2588/// of the first different parameter. 2589bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2590 const FunctionProtoType *NewType, 2591 unsigned *ArgPos) { 2592 if (!getLangOpts().ObjC1) { 2593 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2594 N = NewType->arg_type_begin(), 2595 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2596 if (!Context.hasSameType(*O, *N)) { 2597 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2598 return false; 2599 } 2600 } 2601 return true; 2602 } 2603 2604 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2605 N = NewType->arg_type_begin(), 2606 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2607 QualType ToType = (*O); 2608 QualType FromType = (*N); 2609 if (!Context.hasSameType(ToType, FromType)) { 2610 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2611 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2612 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2613 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2614 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2615 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2616 continue; 2617 } 2618 else if (const ObjCObjectPointerType *PTTo = 2619 ToType->getAs<ObjCObjectPointerType>()) { 2620 if (const ObjCObjectPointerType *PTFr = 2621 FromType->getAs<ObjCObjectPointerType>()) 2622 if (Context.hasSameUnqualifiedType( 2623 PTTo->getObjectType()->getBaseType(), 2624 PTFr->getObjectType()->getBaseType())) 2625 continue; 2626 } 2627 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2628 return false; 2629 } 2630 } 2631 return true; 2632} 2633 2634/// CheckPointerConversion - Check the pointer conversion from the 2635/// expression From to the type ToType. This routine checks for 2636/// ambiguous or inaccessible derived-to-base pointer 2637/// conversions for which IsPointerConversion has already returned 2638/// true. It returns true and produces a diagnostic if there was an 2639/// error, or returns false otherwise. 2640bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2641 CastKind &Kind, 2642 CXXCastPath& BasePath, 2643 bool IgnoreBaseAccess) { 2644 QualType FromType = From->getType(); 2645 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2646 2647 Kind = CK_BitCast; 2648 2649 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2650 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2651 Expr::NPCK_ZeroExpression) { 2652 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2653 DiagRuntimeBehavior(From->getExprLoc(), From, 2654 PDiag(diag::warn_impcast_bool_to_null_pointer) 2655 << ToType << From->getSourceRange()); 2656 else if (!isUnevaluatedContext()) 2657 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2658 << ToType << From->getSourceRange(); 2659 } 2660 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2661 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2662 QualType FromPointeeType = FromPtrType->getPointeeType(), 2663 ToPointeeType = ToPtrType->getPointeeType(); 2664 2665 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2666 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2667 // We must have a derived-to-base conversion. Check an 2668 // ambiguous or inaccessible conversion. 2669 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2670 From->getExprLoc(), 2671 From->getSourceRange(), &BasePath, 2672 IgnoreBaseAccess)) 2673 return true; 2674 2675 // The conversion was successful. 2676 Kind = CK_DerivedToBase; 2677 } 2678 } 2679 } else if (const ObjCObjectPointerType *ToPtrType = 2680 ToType->getAs<ObjCObjectPointerType>()) { 2681 if (const ObjCObjectPointerType *FromPtrType = 2682 FromType->getAs<ObjCObjectPointerType>()) { 2683 // Objective-C++ conversions are always okay. 2684 // FIXME: We should have a different class of conversions for the 2685 // Objective-C++ implicit conversions. 2686 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2687 return false; 2688 } else if (FromType->isBlockPointerType()) { 2689 Kind = CK_BlockPointerToObjCPointerCast; 2690 } else { 2691 Kind = CK_CPointerToObjCPointerCast; 2692 } 2693 } else if (ToType->isBlockPointerType()) { 2694 if (!FromType->isBlockPointerType()) 2695 Kind = CK_AnyPointerToBlockPointerCast; 2696 } 2697 2698 // We shouldn't fall into this case unless it's valid for other 2699 // reasons. 2700 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2701 Kind = CK_NullToPointer; 2702 2703 return false; 2704} 2705 2706/// IsMemberPointerConversion - Determines whether the conversion of the 2707/// expression From, which has the (possibly adjusted) type FromType, can be 2708/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2709/// If so, returns true and places the converted type (that might differ from 2710/// ToType in its cv-qualifiers at some level) into ConvertedType. 2711bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2712 QualType ToType, 2713 bool InOverloadResolution, 2714 QualType &ConvertedType) { 2715 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2716 if (!ToTypePtr) 2717 return false; 2718 2719 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2720 if (From->isNullPointerConstant(Context, 2721 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2722 : Expr::NPC_ValueDependentIsNull)) { 2723 ConvertedType = ToType; 2724 return true; 2725 } 2726 2727 // Otherwise, both types have to be member pointers. 2728 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2729 if (!FromTypePtr) 2730 return false; 2731 2732 // A pointer to member of B can be converted to a pointer to member of D, 2733 // where D is derived from B (C++ 4.11p2). 2734 QualType FromClass(FromTypePtr->getClass(), 0); 2735 QualType ToClass(ToTypePtr->getClass(), 0); 2736 2737 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2738 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2739 IsDerivedFrom(ToClass, FromClass)) { 2740 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2741 ToClass.getTypePtr()); 2742 return true; 2743 } 2744 2745 return false; 2746} 2747 2748/// CheckMemberPointerConversion - Check the member pointer conversion from the 2749/// expression From to the type ToType. This routine checks for ambiguous or 2750/// virtual or inaccessible base-to-derived member pointer conversions 2751/// for which IsMemberPointerConversion has already returned true. It returns 2752/// true and produces a diagnostic if there was an error, or returns false 2753/// otherwise. 2754bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2755 CastKind &Kind, 2756 CXXCastPath &BasePath, 2757 bool IgnoreBaseAccess) { 2758 QualType FromType = From->getType(); 2759 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2760 if (!FromPtrType) { 2761 // This must be a null pointer to member pointer conversion 2762 assert(From->isNullPointerConstant(Context, 2763 Expr::NPC_ValueDependentIsNull) && 2764 "Expr must be null pointer constant!"); 2765 Kind = CK_NullToMemberPointer; 2766 return false; 2767 } 2768 2769 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2770 assert(ToPtrType && "No member pointer cast has a target type " 2771 "that is not a member pointer."); 2772 2773 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2774 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2775 2776 // FIXME: What about dependent types? 2777 assert(FromClass->isRecordType() && "Pointer into non-class."); 2778 assert(ToClass->isRecordType() && "Pointer into non-class."); 2779 2780 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2781 /*DetectVirtual=*/true); 2782 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2783 assert(DerivationOkay && 2784 "Should not have been called if derivation isn't OK."); 2785 (void)DerivationOkay; 2786 2787 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2788 getUnqualifiedType())) { 2789 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2790 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2791 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2792 return true; 2793 } 2794 2795 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2796 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2797 << FromClass << ToClass << QualType(VBase, 0) 2798 << From->getSourceRange(); 2799 return true; 2800 } 2801 2802 if (!IgnoreBaseAccess) 2803 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2804 Paths.front(), 2805 diag::err_downcast_from_inaccessible_base); 2806 2807 // Must be a base to derived member conversion. 2808 BuildBasePathArray(Paths, BasePath); 2809 Kind = CK_BaseToDerivedMemberPointer; 2810 return false; 2811} 2812 2813/// IsQualificationConversion - Determines whether the conversion from 2814/// an rvalue of type FromType to ToType is a qualification conversion 2815/// (C++ 4.4). 2816/// 2817/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2818/// when the qualification conversion involves a change in the Objective-C 2819/// object lifetime. 2820bool 2821Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2822 bool CStyle, bool &ObjCLifetimeConversion) { 2823 FromType = Context.getCanonicalType(FromType); 2824 ToType = Context.getCanonicalType(ToType); 2825 ObjCLifetimeConversion = false; 2826 2827 // If FromType and ToType are the same type, this is not a 2828 // qualification conversion. 2829 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2830 return false; 2831 2832 // (C++ 4.4p4): 2833 // A conversion can add cv-qualifiers at levels other than the first 2834 // in multi-level pointers, subject to the following rules: [...] 2835 bool PreviousToQualsIncludeConst = true; 2836 bool UnwrappedAnyPointer = false; 2837 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2838 // Within each iteration of the loop, we check the qualifiers to 2839 // determine if this still looks like a qualification 2840 // conversion. Then, if all is well, we unwrap one more level of 2841 // pointers or pointers-to-members and do it all again 2842 // until there are no more pointers or pointers-to-members left to 2843 // unwrap. 2844 UnwrappedAnyPointer = true; 2845 2846 Qualifiers FromQuals = FromType.getQualifiers(); 2847 Qualifiers ToQuals = ToType.getQualifiers(); 2848 2849 // Objective-C ARC: 2850 // Check Objective-C lifetime conversions. 2851 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2852 UnwrappedAnyPointer) { 2853 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2854 ObjCLifetimeConversion = true; 2855 FromQuals.removeObjCLifetime(); 2856 ToQuals.removeObjCLifetime(); 2857 } else { 2858 // Qualification conversions cannot cast between different 2859 // Objective-C lifetime qualifiers. 2860 return false; 2861 } 2862 } 2863 2864 // Allow addition/removal of GC attributes but not changing GC attributes. 2865 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2866 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2867 FromQuals.removeObjCGCAttr(); 2868 ToQuals.removeObjCGCAttr(); 2869 } 2870 2871 // -- for every j > 0, if const is in cv 1,j then const is in cv 2872 // 2,j, and similarly for volatile. 2873 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2874 return false; 2875 2876 // -- if the cv 1,j and cv 2,j are different, then const is in 2877 // every cv for 0 < k < j. 2878 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2879 && !PreviousToQualsIncludeConst) 2880 return false; 2881 2882 // Keep track of whether all prior cv-qualifiers in the "to" type 2883 // include const. 2884 PreviousToQualsIncludeConst 2885 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2886 } 2887 2888 // We are left with FromType and ToType being the pointee types 2889 // after unwrapping the original FromType and ToType the same number 2890 // of types. If we unwrapped any pointers, and if FromType and 2891 // ToType have the same unqualified type (since we checked 2892 // qualifiers above), then this is a qualification conversion. 2893 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2894} 2895 2896/// \brief - Determine whether this is a conversion from a scalar type to an 2897/// atomic type. 2898/// 2899/// If successful, updates \c SCS's second and third steps in the conversion 2900/// sequence to finish the conversion. 2901static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2902 bool InOverloadResolution, 2903 StandardConversionSequence &SCS, 2904 bool CStyle) { 2905 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2906 if (!ToAtomic) 2907 return false; 2908 2909 StandardConversionSequence InnerSCS; 2910 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2911 InOverloadResolution, InnerSCS, 2912 CStyle, /*AllowObjCWritebackConversion=*/false)) 2913 return false; 2914 2915 SCS.Second = InnerSCS.Second; 2916 SCS.setToType(1, InnerSCS.getToType(1)); 2917 SCS.Third = InnerSCS.Third; 2918 SCS.QualificationIncludesObjCLifetime 2919 = InnerSCS.QualificationIncludesObjCLifetime; 2920 SCS.setToType(2, InnerSCS.getToType(2)); 2921 return true; 2922} 2923 2924static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2925 CXXConstructorDecl *Constructor, 2926 QualType Type) { 2927 const FunctionProtoType *CtorType = 2928 Constructor->getType()->getAs<FunctionProtoType>(); 2929 if (CtorType->getNumArgs() > 0) { 2930 QualType FirstArg = CtorType->getArgType(0); 2931 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2932 return true; 2933 } 2934 return false; 2935} 2936 2937static OverloadingResult 2938IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2939 CXXRecordDecl *To, 2940 UserDefinedConversionSequence &User, 2941 OverloadCandidateSet &CandidateSet, 2942 bool AllowExplicit) { 2943 DeclContext::lookup_result R = S.LookupConstructors(To); 2944 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2945 Con != ConEnd; ++Con) { 2946 NamedDecl *D = *Con; 2947 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2948 2949 // Find the constructor (which may be a template). 2950 CXXConstructorDecl *Constructor = 0; 2951 FunctionTemplateDecl *ConstructorTmpl 2952 = dyn_cast<FunctionTemplateDecl>(D); 2953 if (ConstructorTmpl) 2954 Constructor 2955 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2956 else 2957 Constructor = cast<CXXConstructorDecl>(D); 2958 2959 bool Usable = !Constructor->isInvalidDecl() && 2960 S.isInitListConstructor(Constructor) && 2961 (AllowExplicit || !Constructor->isExplicit()); 2962 if (Usable) { 2963 // If the first argument is (a reference to) the target type, 2964 // suppress conversions. 2965 bool SuppressUserConversions = 2966 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2967 if (ConstructorTmpl) 2968 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2969 /*ExplicitArgs*/ 0, 2970 From, CandidateSet, 2971 SuppressUserConversions); 2972 else 2973 S.AddOverloadCandidate(Constructor, FoundDecl, 2974 From, CandidateSet, 2975 SuppressUserConversions); 2976 } 2977 } 2978 2979 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2980 2981 OverloadCandidateSet::iterator Best; 2982 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2983 case OR_Success: { 2984 // Record the standard conversion we used and the conversion function. 2985 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2986 QualType ThisType = Constructor->getThisType(S.Context); 2987 // Initializer lists don't have conversions as such. 2988 User.Before.setAsIdentityConversion(); 2989 User.HadMultipleCandidates = HadMultipleCandidates; 2990 User.ConversionFunction = Constructor; 2991 User.FoundConversionFunction = Best->FoundDecl; 2992 User.After.setAsIdentityConversion(); 2993 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2994 User.After.setAllToTypes(ToType); 2995 return OR_Success; 2996 } 2997 2998 case OR_No_Viable_Function: 2999 return OR_No_Viable_Function; 3000 case OR_Deleted: 3001 return OR_Deleted; 3002 case OR_Ambiguous: 3003 return OR_Ambiguous; 3004 } 3005 3006 llvm_unreachable("Invalid OverloadResult!"); 3007} 3008 3009/// Determines whether there is a user-defined conversion sequence 3010/// (C++ [over.ics.user]) that converts expression From to the type 3011/// ToType. If such a conversion exists, User will contain the 3012/// user-defined conversion sequence that performs such a conversion 3013/// and this routine will return true. Otherwise, this routine returns 3014/// false and User is unspecified. 3015/// 3016/// \param AllowExplicit true if the conversion should consider C++0x 3017/// "explicit" conversion functions as well as non-explicit conversion 3018/// functions (C++0x [class.conv.fct]p2). 3019static OverloadingResult 3020IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3021 UserDefinedConversionSequence &User, 3022 OverloadCandidateSet &CandidateSet, 3023 bool AllowExplicit) { 3024 // Whether we will only visit constructors. 3025 bool ConstructorsOnly = false; 3026 3027 // If the type we are conversion to is a class type, enumerate its 3028 // constructors. 3029 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3030 // C++ [over.match.ctor]p1: 3031 // When objects of class type are direct-initialized (8.5), or 3032 // copy-initialized from an expression of the same or a 3033 // derived class type (8.5), overload resolution selects the 3034 // constructor. [...] For copy-initialization, the candidate 3035 // functions are all the converting constructors (12.3.1) of 3036 // that class. The argument list is the expression-list within 3037 // the parentheses of the initializer. 3038 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3039 (From->getType()->getAs<RecordType>() && 3040 S.IsDerivedFrom(From->getType(), ToType))) 3041 ConstructorsOnly = true; 3042 3043 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3044 // RequireCompleteType may have returned true due to some invalid decl 3045 // during template instantiation, but ToType may be complete enough now 3046 // to try to recover. 3047 if (ToType->isIncompleteType()) { 3048 // We're not going to find any constructors. 3049 } else if (CXXRecordDecl *ToRecordDecl 3050 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3051 3052 Expr **Args = &From; 3053 unsigned NumArgs = 1; 3054 bool ListInitializing = false; 3055 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3056 // But first, see if there is an init-list-contructor that will work. 3057 OverloadingResult Result = IsInitializerListConstructorConversion( 3058 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3059 if (Result != OR_No_Viable_Function) 3060 return Result; 3061 // Never mind. 3062 CandidateSet.clear(); 3063 3064 // If we're list-initializing, we pass the individual elements as 3065 // arguments, not the entire list. 3066 Args = InitList->getInits(); 3067 NumArgs = InitList->getNumInits(); 3068 ListInitializing = true; 3069 } 3070 3071 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3072 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3073 Con != ConEnd; ++Con) { 3074 NamedDecl *D = *Con; 3075 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3076 3077 // Find the constructor (which may be a template). 3078 CXXConstructorDecl *Constructor = 0; 3079 FunctionTemplateDecl *ConstructorTmpl 3080 = dyn_cast<FunctionTemplateDecl>(D); 3081 if (ConstructorTmpl) 3082 Constructor 3083 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3084 else 3085 Constructor = cast<CXXConstructorDecl>(D); 3086 3087 bool Usable = !Constructor->isInvalidDecl(); 3088 if (ListInitializing) 3089 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3090 else 3091 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3092 if (Usable) { 3093 bool SuppressUserConversions = !ConstructorsOnly; 3094 if (SuppressUserConversions && ListInitializing) { 3095 SuppressUserConversions = false; 3096 if (NumArgs == 1) { 3097 // If the first argument is (a reference to) the target type, 3098 // suppress conversions. 3099 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3100 S.Context, Constructor, ToType); 3101 } 3102 } 3103 if (ConstructorTmpl) 3104 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3105 /*ExplicitArgs*/ 0, 3106 llvm::makeArrayRef(Args, NumArgs), 3107 CandidateSet, SuppressUserConversions); 3108 else 3109 // Allow one user-defined conversion when user specifies a 3110 // From->ToType conversion via an static cast (c-style, etc). 3111 S.AddOverloadCandidate(Constructor, FoundDecl, 3112 llvm::makeArrayRef(Args, NumArgs), 3113 CandidateSet, SuppressUserConversions); 3114 } 3115 } 3116 } 3117 } 3118 3119 // Enumerate conversion functions, if we're allowed to. 3120 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3121 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3122 // No conversion functions from incomplete types. 3123 } else if (const RecordType *FromRecordType 3124 = From->getType()->getAs<RecordType>()) { 3125 if (CXXRecordDecl *FromRecordDecl 3126 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3127 // Add all of the conversion functions as candidates. 3128 std::pair<CXXRecordDecl::conversion_iterator, 3129 CXXRecordDecl::conversion_iterator> 3130 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3131 for (CXXRecordDecl::conversion_iterator 3132 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3133 DeclAccessPair FoundDecl = I.getPair(); 3134 NamedDecl *D = FoundDecl.getDecl(); 3135 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3136 if (isa<UsingShadowDecl>(D)) 3137 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3138 3139 CXXConversionDecl *Conv; 3140 FunctionTemplateDecl *ConvTemplate; 3141 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3142 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3143 else 3144 Conv = cast<CXXConversionDecl>(D); 3145 3146 if (AllowExplicit || !Conv->isExplicit()) { 3147 if (ConvTemplate) 3148 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3149 ActingContext, From, ToType, 3150 CandidateSet); 3151 else 3152 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3153 From, ToType, CandidateSet); 3154 } 3155 } 3156 } 3157 } 3158 3159 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3160 3161 OverloadCandidateSet::iterator Best; 3162 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3163 case OR_Success: 3164 // Record the standard conversion we used and the conversion function. 3165 if (CXXConstructorDecl *Constructor 3166 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3167 // C++ [over.ics.user]p1: 3168 // If the user-defined conversion is specified by a 3169 // constructor (12.3.1), the initial standard conversion 3170 // sequence converts the source type to the type required by 3171 // the argument of the constructor. 3172 // 3173 QualType ThisType = Constructor->getThisType(S.Context); 3174 if (isa<InitListExpr>(From)) { 3175 // Initializer lists don't have conversions as such. 3176 User.Before.setAsIdentityConversion(); 3177 } else { 3178 if (Best->Conversions[0].isEllipsis()) 3179 User.EllipsisConversion = true; 3180 else { 3181 User.Before = Best->Conversions[0].Standard; 3182 User.EllipsisConversion = false; 3183 } 3184 } 3185 User.HadMultipleCandidates = HadMultipleCandidates; 3186 User.ConversionFunction = Constructor; 3187 User.FoundConversionFunction = Best->FoundDecl; 3188 User.After.setAsIdentityConversion(); 3189 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3190 User.After.setAllToTypes(ToType); 3191 return OR_Success; 3192 } 3193 if (CXXConversionDecl *Conversion 3194 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3195 // C++ [over.ics.user]p1: 3196 // 3197 // [...] If the user-defined conversion is specified by a 3198 // conversion function (12.3.2), the initial standard 3199 // conversion sequence converts the source type to the 3200 // implicit object parameter of the conversion function. 3201 User.Before = Best->Conversions[0].Standard; 3202 User.HadMultipleCandidates = HadMultipleCandidates; 3203 User.ConversionFunction = Conversion; 3204 User.FoundConversionFunction = Best->FoundDecl; 3205 User.EllipsisConversion = false; 3206 3207 // C++ [over.ics.user]p2: 3208 // The second standard conversion sequence converts the 3209 // result of the user-defined conversion to the target type 3210 // for the sequence. Since an implicit conversion sequence 3211 // is an initialization, the special rules for 3212 // initialization by user-defined conversion apply when 3213 // selecting the best user-defined conversion for a 3214 // user-defined conversion sequence (see 13.3.3 and 3215 // 13.3.3.1). 3216 User.After = Best->FinalConversion; 3217 return OR_Success; 3218 } 3219 llvm_unreachable("Not a constructor or conversion function?"); 3220 3221 case OR_No_Viable_Function: 3222 return OR_No_Viable_Function; 3223 case OR_Deleted: 3224 // No conversion here! We're done. 3225 return OR_Deleted; 3226 3227 case OR_Ambiguous: 3228 return OR_Ambiguous; 3229 } 3230 3231 llvm_unreachable("Invalid OverloadResult!"); 3232} 3233 3234bool 3235Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3236 ImplicitConversionSequence ICS; 3237 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3238 OverloadingResult OvResult = 3239 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3240 CandidateSet, false); 3241 if (OvResult == OR_Ambiguous) 3242 Diag(From->getLocStart(), 3243 diag::err_typecheck_ambiguous_condition) 3244 << From->getType() << ToType << From->getSourceRange(); 3245 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3246 Diag(From->getLocStart(), 3247 diag::err_typecheck_nonviable_condition) 3248 << From->getType() << ToType << From->getSourceRange(); 3249 else 3250 return false; 3251 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3252 return true; 3253} 3254 3255/// \brief Compare the user-defined conversion functions or constructors 3256/// of two user-defined conversion sequences to determine whether any ordering 3257/// is possible. 3258static ImplicitConversionSequence::CompareKind 3259compareConversionFunctions(Sema &S, 3260 FunctionDecl *Function1, 3261 FunctionDecl *Function2) { 3262 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3263 return ImplicitConversionSequence::Indistinguishable; 3264 3265 // Objective-C++: 3266 // If both conversion functions are implicitly-declared conversions from 3267 // a lambda closure type to a function pointer and a block pointer, 3268 // respectively, always prefer the conversion to a function pointer, 3269 // because the function pointer is more lightweight and is more likely 3270 // to keep code working. 3271 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3272 if (!Conv1) 3273 return ImplicitConversionSequence::Indistinguishable; 3274 3275 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3276 if (!Conv2) 3277 return ImplicitConversionSequence::Indistinguishable; 3278 3279 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3280 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3281 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3282 if (Block1 != Block2) 3283 return Block1? ImplicitConversionSequence::Worse 3284 : ImplicitConversionSequence::Better; 3285 } 3286 3287 return ImplicitConversionSequence::Indistinguishable; 3288} 3289 3290/// CompareImplicitConversionSequences - Compare two implicit 3291/// conversion sequences to determine whether one is better than the 3292/// other or if they are indistinguishable (C++ 13.3.3.2). 3293static ImplicitConversionSequence::CompareKind 3294CompareImplicitConversionSequences(Sema &S, 3295 const ImplicitConversionSequence& ICS1, 3296 const ImplicitConversionSequence& ICS2) 3297{ 3298 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3299 // conversion sequences (as defined in 13.3.3.1) 3300 // -- a standard conversion sequence (13.3.3.1.1) is a better 3301 // conversion sequence than a user-defined conversion sequence or 3302 // an ellipsis conversion sequence, and 3303 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3304 // conversion sequence than an ellipsis conversion sequence 3305 // (13.3.3.1.3). 3306 // 3307 // C++0x [over.best.ics]p10: 3308 // For the purpose of ranking implicit conversion sequences as 3309 // described in 13.3.3.2, the ambiguous conversion sequence is 3310 // treated as a user-defined sequence that is indistinguishable 3311 // from any other user-defined conversion sequence. 3312 if (ICS1.getKindRank() < ICS2.getKindRank()) 3313 return ImplicitConversionSequence::Better; 3314 if (ICS2.getKindRank() < ICS1.getKindRank()) 3315 return ImplicitConversionSequence::Worse; 3316 3317 // The following checks require both conversion sequences to be of 3318 // the same kind. 3319 if (ICS1.getKind() != ICS2.getKind()) 3320 return ImplicitConversionSequence::Indistinguishable; 3321 3322 ImplicitConversionSequence::CompareKind Result = 3323 ImplicitConversionSequence::Indistinguishable; 3324 3325 // Two implicit conversion sequences of the same form are 3326 // indistinguishable conversion sequences unless one of the 3327 // following rules apply: (C++ 13.3.3.2p3): 3328 if (ICS1.isStandard()) 3329 Result = CompareStandardConversionSequences(S, 3330 ICS1.Standard, ICS2.Standard); 3331 else if (ICS1.isUserDefined()) { 3332 // User-defined conversion sequence U1 is a better conversion 3333 // sequence than another user-defined conversion sequence U2 if 3334 // they contain the same user-defined conversion function or 3335 // constructor and if the second standard conversion sequence of 3336 // U1 is better than the second standard conversion sequence of 3337 // U2 (C++ 13.3.3.2p3). 3338 if (ICS1.UserDefined.ConversionFunction == 3339 ICS2.UserDefined.ConversionFunction) 3340 Result = CompareStandardConversionSequences(S, 3341 ICS1.UserDefined.After, 3342 ICS2.UserDefined.After); 3343 else 3344 Result = compareConversionFunctions(S, 3345 ICS1.UserDefined.ConversionFunction, 3346 ICS2.UserDefined.ConversionFunction); 3347 } 3348 3349 // List-initialization sequence L1 is a better conversion sequence than 3350 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3351 // for some X and L2 does not. 3352 if (Result == ImplicitConversionSequence::Indistinguishable && 3353 !ICS1.isBad() && 3354 ICS1.isListInitializationSequence() && 3355 ICS2.isListInitializationSequence()) { 3356 if (ICS1.isStdInitializerListElement() && 3357 !ICS2.isStdInitializerListElement()) 3358 return ImplicitConversionSequence::Better; 3359 if (!ICS1.isStdInitializerListElement() && 3360 ICS2.isStdInitializerListElement()) 3361 return ImplicitConversionSequence::Worse; 3362 } 3363 3364 return Result; 3365} 3366 3367static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3368 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3369 Qualifiers Quals; 3370 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3371 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3372 } 3373 3374 return Context.hasSameUnqualifiedType(T1, T2); 3375} 3376 3377// Per 13.3.3.2p3, compare the given standard conversion sequences to 3378// determine if one is a proper subset of the other. 3379static ImplicitConversionSequence::CompareKind 3380compareStandardConversionSubsets(ASTContext &Context, 3381 const StandardConversionSequence& SCS1, 3382 const StandardConversionSequence& SCS2) { 3383 ImplicitConversionSequence::CompareKind Result 3384 = ImplicitConversionSequence::Indistinguishable; 3385 3386 // the identity conversion sequence is considered to be a subsequence of 3387 // any non-identity conversion sequence 3388 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3389 return ImplicitConversionSequence::Better; 3390 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3391 return ImplicitConversionSequence::Worse; 3392 3393 if (SCS1.Second != SCS2.Second) { 3394 if (SCS1.Second == ICK_Identity) 3395 Result = ImplicitConversionSequence::Better; 3396 else if (SCS2.Second == ICK_Identity) 3397 Result = ImplicitConversionSequence::Worse; 3398 else 3399 return ImplicitConversionSequence::Indistinguishable; 3400 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3401 return ImplicitConversionSequence::Indistinguishable; 3402 3403 if (SCS1.Third == SCS2.Third) { 3404 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3405 : ImplicitConversionSequence::Indistinguishable; 3406 } 3407 3408 if (SCS1.Third == ICK_Identity) 3409 return Result == ImplicitConversionSequence::Worse 3410 ? ImplicitConversionSequence::Indistinguishable 3411 : ImplicitConversionSequence::Better; 3412 3413 if (SCS2.Third == ICK_Identity) 3414 return Result == ImplicitConversionSequence::Better 3415 ? ImplicitConversionSequence::Indistinguishable 3416 : ImplicitConversionSequence::Worse; 3417 3418 return ImplicitConversionSequence::Indistinguishable; 3419} 3420 3421/// \brief Determine whether one of the given reference bindings is better 3422/// than the other based on what kind of bindings they are. 3423static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3424 const StandardConversionSequence &SCS2) { 3425 // C++0x [over.ics.rank]p3b4: 3426 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3427 // implicit object parameter of a non-static member function declared 3428 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3429 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3430 // lvalue reference to a function lvalue and S2 binds an rvalue 3431 // reference*. 3432 // 3433 // FIXME: Rvalue references. We're going rogue with the above edits, 3434 // because the semantics in the current C++0x working paper (N3225 at the 3435 // time of this writing) break the standard definition of std::forward 3436 // and std::reference_wrapper when dealing with references to functions. 3437 // Proposed wording changes submitted to CWG for consideration. 3438 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3439 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3440 return false; 3441 3442 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3443 SCS2.IsLvalueReference) || 3444 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3445 !SCS2.IsLvalueReference); 3446} 3447 3448/// CompareStandardConversionSequences - Compare two standard 3449/// conversion sequences to determine whether one is better than the 3450/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3451static ImplicitConversionSequence::CompareKind 3452CompareStandardConversionSequences(Sema &S, 3453 const StandardConversionSequence& SCS1, 3454 const StandardConversionSequence& SCS2) 3455{ 3456 // Standard conversion sequence S1 is a better conversion sequence 3457 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3458 3459 // -- S1 is a proper subsequence of S2 (comparing the conversion 3460 // sequences in the canonical form defined by 13.3.3.1.1, 3461 // excluding any Lvalue Transformation; the identity conversion 3462 // sequence is considered to be a subsequence of any 3463 // non-identity conversion sequence) or, if not that, 3464 if (ImplicitConversionSequence::CompareKind CK 3465 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3466 return CK; 3467 3468 // -- the rank of S1 is better than the rank of S2 (by the rules 3469 // defined below), or, if not that, 3470 ImplicitConversionRank Rank1 = SCS1.getRank(); 3471 ImplicitConversionRank Rank2 = SCS2.getRank(); 3472 if (Rank1 < Rank2) 3473 return ImplicitConversionSequence::Better; 3474 else if (Rank2 < Rank1) 3475 return ImplicitConversionSequence::Worse; 3476 3477 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3478 // are indistinguishable unless one of the following rules 3479 // applies: 3480 3481 // A conversion that is not a conversion of a pointer, or 3482 // pointer to member, to bool is better than another conversion 3483 // that is such a conversion. 3484 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3485 return SCS2.isPointerConversionToBool() 3486 ? ImplicitConversionSequence::Better 3487 : ImplicitConversionSequence::Worse; 3488 3489 // C++ [over.ics.rank]p4b2: 3490 // 3491 // If class B is derived directly or indirectly from class A, 3492 // conversion of B* to A* is better than conversion of B* to 3493 // void*, and conversion of A* to void* is better than conversion 3494 // of B* to void*. 3495 bool SCS1ConvertsToVoid 3496 = SCS1.isPointerConversionToVoidPointer(S.Context); 3497 bool SCS2ConvertsToVoid 3498 = SCS2.isPointerConversionToVoidPointer(S.Context); 3499 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3500 // Exactly one of the conversion sequences is a conversion to 3501 // a void pointer; it's the worse conversion. 3502 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3503 : ImplicitConversionSequence::Worse; 3504 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3505 // Neither conversion sequence converts to a void pointer; compare 3506 // their derived-to-base conversions. 3507 if (ImplicitConversionSequence::CompareKind DerivedCK 3508 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3509 return DerivedCK; 3510 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3511 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3512 // Both conversion sequences are conversions to void 3513 // pointers. Compare the source types to determine if there's an 3514 // inheritance relationship in their sources. 3515 QualType FromType1 = SCS1.getFromType(); 3516 QualType FromType2 = SCS2.getFromType(); 3517 3518 // Adjust the types we're converting from via the array-to-pointer 3519 // conversion, if we need to. 3520 if (SCS1.First == ICK_Array_To_Pointer) 3521 FromType1 = S.Context.getArrayDecayedType(FromType1); 3522 if (SCS2.First == ICK_Array_To_Pointer) 3523 FromType2 = S.Context.getArrayDecayedType(FromType2); 3524 3525 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3526 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3527 3528 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3529 return ImplicitConversionSequence::Better; 3530 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3531 return ImplicitConversionSequence::Worse; 3532 3533 // Objective-C++: If one interface is more specific than the 3534 // other, it is the better one. 3535 const ObjCObjectPointerType* FromObjCPtr1 3536 = FromType1->getAs<ObjCObjectPointerType>(); 3537 const ObjCObjectPointerType* FromObjCPtr2 3538 = FromType2->getAs<ObjCObjectPointerType>(); 3539 if (FromObjCPtr1 && FromObjCPtr2) { 3540 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3541 FromObjCPtr2); 3542 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3543 FromObjCPtr1); 3544 if (AssignLeft != AssignRight) { 3545 return AssignLeft? ImplicitConversionSequence::Better 3546 : ImplicitConversionSequence::Worse; 3547 } 3548 } 3549 } 3550 3551 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3552 // bullet 3). 3553 if (ImplicitConversionSequence::CompareKind QualCK 3554 = CompareQualificationConversions(S, SCS1, SCS2)) 3555 return QualCK; 3556 3557 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3558 // Check for a better reference binding based on the kind of bindings. 3559 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3560 return ImplicitConversionSequence::Better; 3561 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3562 return ImplicitConversionSequence::Worse; 3563 3564 // C++ [over.ics.rank]p3b4: 3565 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3566 // which the references refer are the same type except for 3567 // top-level cv-qualifiers, and the type to which the reference 3568 // initialized by S2 refers is more cv-qualified than the type 3569 // to which the reference initialized by S1 refers. 3570 QualType T1 = SCS1.getToType(2); 3571 QualType T2 = SCS2.getToType(2); 3572 T1 = S.Context.getCanonicalType(T1); 3573 T2 = S.Context.getCanonicalType(T2); 3574 Qualifiers T1Quals, T2Quals; 3575 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3576 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3577 if (UnqualT1 == UnqualT2) { 3578 // Objective-C++ ARC: If the references refer to objects with different 3579 // lifetimes, prefer bindings that don't change lifetime. 3580 if (SCS1.ObjCLifetimeConversionBinding != 3581 SCS2.ObjCLifetimeConversionBinding) { 3582 return SCS1.ObjCLifetimeConversionBinding 3583 ? ImplicitConversionSequence::Worse 3584 : ImplicitConversionSequence::Better; 3585 } 3586 3587 // If the type is an array type, promote the element qualifiers to the 3588 // type for comparison. 3589 if (isa<ArrayType>(T1) && T1Quals) 3590 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3591 if (isa<ArrayType>(T2) && T2Quals) 3592 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3593 if (T2.isMoreQualifiedThan(T1)) 3594 return ImplicitConversionSequence::Better; 3595 else if (T1.isMoreQualifiedThan(T2)) 3596 return ImplicitConversionSequence::Worse; 3597 } 3598 } 3599 3600 // In Microsoft mode, prefer an integral conversion to a 3601 // floating-to-integral conversion if the integral conversion 3602 // is between types of the same size. 3603 // For example: 3604 // void f(float); 3605 // void f(int); 3606 // int main { 3607 // long a; 3608 // f(a); 3609 // } 3610 // Here, MSVC will call f(int) instead of generating a compile error 3611 // as clang will do in standard mode. 3612 if (S.getLangOpts().MicrosoftMode && 3613 SCS1.Second == ICK_Integral_Conversion && 3614 SCS2.Second == ICK_Floating_Integral && 3615 S.Context.getTypeSize(SCS1.getFromType()) == 3616 S.Context.getTypeSize(SCS1.getToType(2))) 3617 return ImplicitConversionSequence::Better; 3618 3619 return ImplicitConversionSequence::Indistinguishable; 3620} 3621 3622/// CompareQualificationConversions - Compares two standard conversion 3623/// sequences to determine whether they can be ranked based on their 3624/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3625ImplicitConversionSequence::CompareKind 3626CompareQualificationConversions(Sema &S, 3627 const StandardConversionSequence& SCS1, 3628 const StandardConversionSequence& SCS2) { 3629 // C++ 13.3.3.2p3: 3630 // -- S1 and S2 differ only in their qualification conversion and 3631 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3632 // cv-qualification signature of type T1 is a proper subset of 3633 // the cv-qualification signature of type T2, and S1 is not the 3634 // deprecated string literal array-to-pointer conversion (4.2). 3635 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3636 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3637 return ImplicitConversionSequence::Indistinguishable; 3638 3639 // FIXME: the example in the standard doesn't use a qualification 3640 // conversion (!) 3641 QualType T1 = SCS1.getToType(2); 3642 QualType T2 = SCS2.getToType(2); 3643 T1 = S.Context.getCanonicalType(T1); 3644 T2 = S.Context.getCanonicalType(T2); 3645 Qualifiers T1Quals, T2Quals; 3646 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3647 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3648 3649 // If the types are the same, we won't learn anything by unwrapped 3650 // them. 3651 if (UnqualT1 == UnqualT2) 3652 return ImplicitConversionSequence::Indistinguishable; 3653 3654 // If the type is an array type, promote the element qualifiers to the type 3655 // for comparison. 3656 if (isa<ArrayType>(T1) && T1Quals) 3657 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3658 if (isa<ArrayType>(T2) && T2Quals) 3659 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3660 3661 ImplicitConversionSequence::CompareKind Result 3662 = ImplicitConversionSequence::Indistinguishable; 3663 3664 // Objective-C++ ARC: 3665 // Prefer qualification conversions not involving a change in lifetime 3666 // to qualification conversions that do not change lifetime. 3667 if (SCS1.QualificationIncludesObjCLifetime != 3668 SCS2.QualificationIncludesObjCLifetime) { 3669 Result = SCS1.QualificationIncludesObjCLifetime 3670 ? ImplicitConversionSequence::Worse 3671 : ImplicitConversionSequence::Better; 3672 } 3673 3674 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3675 // Within each iteration of the loop, we check the qualifiers to 3676 // determine if this still looks like a qualification 3677 // conversion. Then, if all is well, we unwrap one more level of 3678 // pointers or pointers-to-members and do it all again 3679 // until there are no more pointers or pointers-to-members left 3680 // to unwrap. This essentially mimics what 3681 // IsQualificationConversion does, but here we're checking for a 3682 // strict subset of qualifiers. 3683 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3684 // The qualifiers are the same, so this doesn't tell us anything 3685 // about how the sequences rank. 3686 ; 3687 else if (T2.isMoreQualifiedThan(T1)) { 3688 // T1 has fewer qualifiers, so it could be the better sequence. 3689 if (Result == ImplicitConversionSequence::Worse) 3690 // Neither has qualifiers that are a subset of the other's 3691 // qualifiers. 3692 return ImplicitConversionSequence::Indistinguishable; 3693 3694 Result = ImplicitConversionSequence::Better; 3695 } else if (T1.isMoreQualifiedThan(T2)) { 3696 // T2 has fewer qualifiers, so it could be the better sequence. 3697 if (Result == ImplicitConversionSequence::Better) 3698 // Neither has qualifiers that are a subset of the other's 3699 // qualifiers. 3700 return ImplicitConversionSequence::Indistinguishable; 3701 3702 Result = ImplicitConversionSequence::Worse; 3703 } else { 3704 // Qualifiers are disjoint. 3705 return ImplicitConversionSequence::Indistinguishable; 3706 } 3707 3708 // If the types after this point are equivalent, we're done. 3709 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3710 break; 3711 } 3712 3713 // Check that the winning standard conversion sequence isn't using 3714 // the deprecated string literal array to pointer conversion. 3715 switch (Result) { 3716 case ImplicitConversionSequence::Better: 3717 if (SCS1.DeprecatedStringLiteralToCharPtr) 3718 Result = ImplicitConversionSequence::Indistinguishable; 3719 break; 3720 3721 case ImplicitConversionSequence::Indistinguishable: 3722 break; 3723 3724 case ImplicitConversionSequence::Worse: 3725 if (SCS2.DeprecatedStringLiteralToCharPtr) 3726 Result = ImplicitConversionSequence::Indistinguishable; 3727 break; 3728 } 3729 3730 return Result; 3731} 3732 3733/// CompareDerivedToBaseConversions - Compares two standard conversion 3734/// sequences to determine whether they can be ranked based on their 3735/// various kinds of derived-to-base conversions (C++ 3736/// [over.ics.rank]p4b3). As part of these checks, we also look at 3737/// conversions between Objective-C interface types. 3738ImplicitConversionSequence::CompareKind 3739CompareDerivedToBaseConversions(Sema &S, 3740 const StandardConversionSequence& SCS1, 3741 const StandardConversionSequence& SCS2) { 3742 QualType FromType1 = SCS1.getFromType(); 3743 QualType ToType1 = SCS1.getToType(1); 3744 QualType FromType2 = SCS2.getFromType(); 3745 QualType ToType2 = SCS2.getToType(1); 3746 3747 // Adjust the types we're converting from via the array-to-pointer 3748 // conversion, if we need to. 3749 if (SCS1.First == ICK_Array_To_Pointer) 3750 FromType1 = S.Context.getArrayDecayedType(FromType1); 3751 if (SCS2.First == ICK_Array_To_Pointer) 3752 FromType2 = S.Context.getArrayDecayedType(FromType2); 3753 3754 // Canonicalize all of the types. 3755 FromType1 = S.Context.getCanonicalType(FromType1); 3756 ToType1 = S.Context.getCanonicalType(ToType1); 3757 FromType2 = S.Context.getCanonicalType(FromType2); 3758 ToType2 = S.Context.getCanonicalType(ToType2); 3759 3760 // C++ [over.ics.rank]p4b3: 3761 // 3762 // If class B is derived directly or indirectly from class A and 3763 // class C is derived directly or indirectly from B, 3764 // 3765 // Compare based on pointer conversions. 3766 if (SCS1.Second == ICK_Pointer_Conversion && 3767 SCS2.Second == ICK_Pointer_Conversion && 3768 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3769 FromType1->isPointerType() && FromType2->isPointerType() && 3770 ToType1->isPointerType() && ToType2->isPointerType()) { 3771 QualType FromPointee1 3772 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3773 QualType ToPointee1 3774 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3775 QualType FromPointee2 3776 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3777 QualType ToPointee2 3778 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3779 3780 // -- conversion of C* to B* is better than conversion of C* to A*, 3781 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3782 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3783 return ImplicitConversionSequence::Better; 3784 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3785 return ImplicitConversionSequence::Worse; 3786 } 3787 3788 // -- conversion of B* to A* is better than conversion of C* to A*, 3789 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3790 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3791 return ImplicitConversionSequence::Better; 3792 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3793 return ImplicitConversionSequence::Worse; 3794 } 3795 } else if (SCS1.Second == ICK_Pointer_Conversion && 3796 SCS2.Second == ICK_Pointer_Conversion) { 3797 const ObjCObjectPointerType *FromPtr1 3798 = FromType1->getAs<ObjCObjectPointerType>(); 3799 const ObjCObjectPointerType *FromPtr2 3800 = FromType2->getAs<ObjCObjectPointerType>(); 3801 const ObjCObjectPointerType *ToPtr1 3802 = ToType1->getAs<ObjCObjectPointerType>(); 3803 const ObjCObjectPointerType *ToPtr2 3804 = ToType2->getAs<ObjCObjectPointerType>(); 3805 3806 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3807 // Apply the same conversion ranking rules for Objective-C pointer types 3808 // that we do for C++ pointers to class types. However, we employ the 3809 // Objective-C pseudo-subtyping relationship used for assignment of 3810 // Objective-C pointer types. 3811 bool FromAssignLeft 3812 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3813 bool FromAssignRight 3814 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3815 bool ToAssignLeft 3816 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3817 bool ToAssignRight 3818 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3819 3820 // A conversion to an a non-id object pointer type or qualified 'id' 3821 // type is better than a conversion to 'id'. 3822 if (ToPtr1->isObjCIdType() && 3823 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3824 return ImplicitConversionSequence::Worse; 3825 if (ToPtr2->isObjCIdType() && 3826 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3827 return ImplicitConversionSequence::Better; 3828 3829 // A conversion to a non-id object pointer type is better than a 3830 // conversion to a qualified 'id' type 3831 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3832 return ImplicitConversionSequence::Worse; 3833 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3834 return ImplicitConversionSequence::Better; 3835 3836 // A conversion to an a non-Class object pointer type or qualified 'Class' 3837 // type is better than a conversion to 'Class'. 3838 if (ToPtr1->isObjCClassType() && 3839 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3840 return ImplicitConversionSequence::Worse; 3841 if (ToPtr2->isObjCClassType() && 3842 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3843 return ImplicitConversionSequence::Better; 3844 3845 // A conversion to a non-Class object pointer type is better than a 3846 // conversion to a qualified 'Class' type. 3847 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3848 return ImplicitConversionSequence::Worse; 3849 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3850 return ImplicitConversionSequence::Better; 3851 3852 // -- "conversion of C* to B* is better than conversion of C* to A*," 3853 if (S.Context.hasSameType(FromType1, FromType2) && 3854 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3855 (ToAssignLeft != ToAssignRight)) 3856 return ToAssignLeft? ImplicitConversionSequence::Worse 3857 : ImplicitConversionSequence::Better; 3858 3859 // -- "conversion of B* to A* is better than conversion of C* to A*," 3860 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3861 (FromAssignLeft != FromAssignRight)) 3862 return FromAssignLeft? ImplicitConversionSequence::Better 3863 : ImplicitConversionSequence::Worse; 3864 } 3865 } 3866 3867 // Ranking of member-pointer types. 3868 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3869 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3870 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3871 const MemberPointerType * FromMemPointer1 = 3872 FromType1->getAs<MemberPointerType>(); 3873 const MemberPointerType * ToMemPointer1 = 3874 ToType1->getAs<MemberPointerType>(); 3875 const MemberPointerType * FromMemPointer2 = 3876 FromType2->getAs<MemberPointerType>(); 3877 const MemberPointerType * ToMemPointer2 = 3878 ToType2->getAs<MemberPointerType>(); 3879 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3880 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3881 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3882 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3883 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3884 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3885 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3886 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3887 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3888 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3889 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3890 return ImplicitConversionSequence::Worse; 3891 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3892 return ImplicitConversionSequence::Better; 3893 } 3894 // conversion of B::* to C::* is better than conversion of A::* to C::* 3895 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3896 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3897 return ImplicitConversionSequence::Better; 3898 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3899 return ImplicitConversionSequence::Worse; 3900 } 3901 } 3902 3903 if (SCS1.Second == ICK_Derived_To_Base) { 3904 // -- conversion of C to B is better than conversion of C to A, 3905 // -- binding of an expression of type C to a reference of type 3906 // B& is better than binding an expression of type C to a 3907 // reference of type A&, 3908 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3909 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3910 if (S.IsDerivedFrom(ToType1, ToType2)) 3911 return ImplicitConversionSequence::Better; 3912 else if (S.IsDerivedFrom(ToType2, ToType1)) 3913 return ImplicitConversionSequence::Worse; 3914 } 3915 3916 // -- conversion of B to A is better than conversion of C to A. 3917 // -- binding of an expression of type B to a reference of type 3918 // A& 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(FromType2, FromType1)) 3923 return ImplicitConversionSequence::Better; 3924 else if (S.IsDerivedFrom(FromType1, FromType2)) 3925 return ImplicitConversionSequence::Worse; 3926 } 3927 } 3928 3929 return ImplicitConversionSequence::Indistinguishable; 3930} 3931 3932/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3933/// determine whether they are reference-related, 3934/// reference-compatible, reference-compatible with added 3935/// qualification, or incompatible, for use in C++ initialization by 3936/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3937/// type, and the first type (T1) is the pointee type of the reference 3938/// type being initialized. 3939Sema::ReferenceCompareResult 3940Sema::CompareReferenceRelationship(SourceLocation Loc, 3941 QualType OrigT1, QualType OrigT2, 3942 bool &DerivedToBase, 3943 bool &ObjCConversion, 3944 bool &ObjCLifetimeConversion) { 3945 assert(!OrigT1->isReferenceType() && 3946 "T1 must be the pointee type of the reference type"); 3947 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3948 3949 QualType T1 = Context.getCanonicalType(OrigT1); 3950 QualType T2 = Context.getCanonicalType(OrigT2); 3951 Qualifiers T1Quals, T2Quals; 3952 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3953 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3954 3955 // C++ [dcl.init.ref]p4: 3956 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3957 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3958 // T1 is a base class of T2. 3959 DerivedToBase = false; 3960 ObjCConversion = false; 3961 ObjCLifetimeConversion = false; 3962 if (UnqualT1 == UnqualT2) { 3963 // Nothing to do. 3964 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3965 IsDerivedFrom(UnqualT2, UnqualT1)) 3966 DerivedToBase = true; 3967 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3968 UnqualT2->isObjCObjectOrInterfaceType() && 3969 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3970 ObjCConversion = true; 3971 else 3972 return Ref_Incompatible; 3973 3974 // At this point, we know that T1 and T2 are reference-related (at 3975 // least). 3976 3977 // If the type is an array type, promote the element qualifiers to the type 3978 // for comparison. 3979 if (isa<ArrayType>(T1) && T1Quals) 3980 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3981 if (isa<ArrayType>(T2) && T2Quals) 3982 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3983 3984 // C++ [dcl.init.ref]p4: 3985 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3986 // reference-related to T2 and cv1 is the same cv-qualification 3987 // as, or greater cv-qualification than, cv2. For purposes of 3988 // overload resolution, cases for which cv1 is greater 3989 // cv-qualification than cv2 are identified as 3990 // reference-compatible with added qualification (see 13.3.3.2). 3991 // 3992 // Note that we also require equivalence of Objective-C GC and address-space 3993 // qualifiers when performing these computations, so that e.g., an int in 3994 // address space 1 is not reference-compatible with an int in address 3995 // space 2. 3996 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3997 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3998 T1Quals.removeObjCLifetime(); 3999 T2Quals.removeObjCLifetime(); 4000 ObjCLifetimeConversion = true; 4001 } 4002 4003 if (T1Quals == T2Quals) 4004 return Ref_Compatible; 4005 else if (T1Quals.compatiblyIncludes(T2Quals)) 4006 return Ref_Compatible_With_Added_Qualification; 4007 else 4008 return Ref_Related; 4009} 4010 4011/// \brief Look for a user-defined conversion to an value reference-compatible 4012/// with DeclType. Return true if something definite is found. 4013static bool 4014FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4015 QualType DeclType, SourceLocation DeclLoc, 4016 Expr *Init, QualType T2, bool AllowRvalues, 4017 bool AllowExplicit) { 4018 assert(T2->isRecordType() && "Can only find conversions of record types."); 4019 CXXRecordDecl *T2RecordDecl 4020 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4021 4022 OverloadCandidateSet CandidateSet(DeclLoc); 4023 std::pair<CXXRecordDecl::conversion_iterator, 4024 CXXRecordDecl::conversion_iterator> 4025 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4026 for (CXXRecordDecl::conversion_iterator 4027 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4028 NamedDecl *D = *I; 4029 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4030 if (isa<UsingShadowDecl>(D)) 4031 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4032 4033 FunctionTemplateDecl *ConvTemplate 4034 = dyn_cast<FunctionTemplateDecl>(D); 4035 CXXConversionDecl *Conv; 4036 if (ConvTemplate) 4037 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4038 else 4039 Conv = cast<CXXConversionDecl>(D); 4040 4041 // If this is an explicit conversion, and we're not allowed to consider 4042 // explicit conversions, skip it. 4043 if (!AllowExplicit && Conv->isExplicit()) 4044 continue; 4045 4046 if (AllowRvalues) { 4047 bool DerivedToBase = false; 4048 bool ObjCConversion = false; 4049 bool ObjCLifetimeConversion = false; 4050 4051 // If we are initializing an rvalue reference, don't permit conversion 4052 // functions that return lvalues. 4053 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4054 const ReferenceType *RefType 4055 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4056 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4057 continue; 4058 } 4059 4060 if (!ConvTemplate && 4061 S.CompareReferenceRelationship( 4062 DeclLoc, 4063 Conv->getConversionType().getNonReferenceType() 4064 .getUnqualifiedType(), 4065 DeclType.getNonReferenceType().getUnqualifiedType(), 4066 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4067 Sema::Ref_Incompatible) 4068 continue; 4069 } else { 4070 // If the conversion function doesn't return a reference type, 4071 // it can't be considered for this conversion. An rvalue reference 4072 // is only acceptable if its referencee is a function type. 4073 4074 const ReferenceType *RefType = 4075 Conv->getConversionType()->getAs<ReferenceType>(); 4076 if (!RefType || 4077 (!RefType->isLValueReferenceType() && 4078 !RefType->getPointeeType()->isFunctionType())) 4079 continue; 4080 } 4081 4082 if (ConvTemplate) 4083 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4084 Init, DeclType, CandidateSet); 4085 else 4086 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4087 DeclType, CandidateSet); 4088 } 4089 4090 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4091 4092 OverloadCandidateSet::iterator Best; 4093 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4094 case OR_Success: 4095 // C++ [over.ics.ref]p1: 4096 // 4097 // [...] If the parameter binds directly to the result of 4098 // applying a conversion function to the argument 4099 // expression, the implicit conversion sequence is a 4100 // user-defined conversion sequence (13.3.3.1.2), with the 4101 // second standard conversion sequence either an identity 4102 // conversion or, if the conversion function returns an 4103 // entity of a type that is a derived class of the parameter 4104 // type, a derived-to-base Conversion. 4105 if (!Best->FinalConversion.DirectBinding) 4106 return false; 4107 4108 ICS.setUserDefined(); 4109 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4110 ICS.UserDefined.After = Best->FinalConversion; 4111 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4112 ICS.UserDefined.ConversionFunction = Best->Function; 4113 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4114 ICS.UserDefined.EllipsisConversion = false; 4115 assert(ICS.UserDefined.After.ReferenceBinding && 4116 ICS.UserDefined.After.DirectBinding && 4117 "Expected a direct reference binding!"); 4118 return true; 4119 4120 case OR_Ambiguous: 4121 ICS.setAmbiguous(); 4122 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4123 Cand != CandidateSet.end(); ++Cand) 4124 if (Cand->Viable) 4125 ICS.Ambiguous.addConversion(Cand->Function); 4126 return true; 4127 4128 case OR_No_Viable_Function: 4129 case OR_Deleted: 4130 // There was no suitable conversion, or we found a deleted 4131 // conversion; continue with other checks. 4132 return false; 4133 } 4134 4135 llvm_unreachable("Invalid OverloadResult!"); 4136} 4137 4138/// \brief Compute an implicit conversion sequence for reference 4139/// initialization. 4140static ImplicitConversionSequence 4141TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4142 SourceLocation DeclLoc, 4143 bool SuppressUserConversions, 4144 bool AllowExplicit) { 4145 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4146 4147 // Most paths end in a failed conversion. 4148 ImplicitConversionSequence ICS; 4149 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4150 4151 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4152 QualType T2 = Init->getType(); 4153 4154 // If the initializer is the address of an overloaded function, try 4155 // to resolve the overloaded function. If all goes well, T2 is the 4156 // type of the resulting function. 4157 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4158 DeclAccessPair Found; 4159 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4160 false, Found)) 4161 T2 = Fn->getType(); 4162 } 4163 4164 // Compute some basic properties of the types and the initializer. 4165 bool isRValRef = DeclType->isRValueReferenceType(); 4166 bool DerivedToBase = false; 4167 bool ObjCConversion = false; 4168 bool ObjCLifetimeConversion = false; 4169 Expr::Classification InitCategory = Init->Classify(S.Context); 4170 Sema::ReferenceCompareResult RefRelationship 4171 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4172 ObjCConversion, ObjCLifetimeConversion); 4173 4174 4175 // C++0x [dcl.init.ref]p5: 4176 // A reference to type "cv1 T1" is initialized by an expression 4177 // of type "cv2 T2" as follows: 4178 4179 // -- If reference is an lvalue reference and the initializer expression 4180 if (!isRValRef) { 4181 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4182 // reference-compatible with "cv2 T2," or 4183 // 4184 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4185 if (InitCategory.isLValue() && 4186 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4187 // C++ [over.ics.ref]p1: 4188 // When a parameter of reference type binds directly (8.5.3) 4189 // to an argument expression, the implicit conversion sequence 4190 // is the identity conversion, unless the argument expression 4191 // has a type that is a derived class of the parameter type, 4192 // in which case the implicit conversion sequence is a 4193 // derived-to-base Conversion (13.3.3.1). 4194 ICS.setStandard(); 4195 ICS.Standard.First = ICK_Identity; 4196 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4197 : ObjCConversion? ICK_Compatible_Conversion 4198 : ICK_Identity; 4199 ICS.Standard.Third = ICK_Identity; 4200 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4201 ICS.Standard.setToType(0, T2); 4202 ICS.Standard.setToType(1, T1); 4203 ICS.Standard.setToType(2, T1); 4204 ICS.Standard.ReferenceBinding = true; 4205 ICS.Standard.DirectBinding = true; 4206 ICS.Standard.IsLvalueReference = !isRValRef; 4207 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4208 ICS.Standard.BindsToRvalue = false; 4209 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4210 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4211 ICS.Standard.CopyConstructor = 0; 4212 4213 // Nothing more to do: the inaccessibility/ambiguity check for 4214 // derived-to-base conversions is suppressed when we're 4215 // computing the implicit conversion sequence (C++ 4216 // [over.best.ics]p2). 4217 return ICS; 4218 } 4219 4220 // -- has a class type (i.e., T2 is a class type), where T1 is 4221 // not reference-related to T2, and can be implicitly 4222 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4223 // is reference-compatible with "cv3 T3" 92) (this 4224 // conversion is selected by enumerating the applicable 4225 // conversion functions (13.3.1.6) and choosing the best 4226 // one through overload resolution (13.3)), 4227 if (!SuppressUserConversions && T2->isRecordType() && 4228 !S.RequireCompleteType(DeclLoc, T2, 0) && 4229 RefRelationship == Sema::Ref_Incompatible) { 4230 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4231 Init, T2, /*AllowRvalues=*/false, 4232 AllowExplicit)) 4233 return ICS; 4234 } 4235 } 4236 4237 // -- Otherwise, the reference shall be an lvalue reference to a 4238 // non-volatile const type (i.e., cv1 shall be const), or the reference 4239 // shall be an rvalue reference. 4240 // 4241 // We actually handle one oddity of C++ [over.ics.ref] at this 4242 // point, which is that, due to p2 (which short-circuits reference 4243 // binding by only attempting a simple conversion for non-direct 4244 // bindings) and p3's strange wording, we allow a const volatile 4245 // reference to bind to an rvalue. Hence the check for the presence 4246 // of "const" rather than checking for "const" being the only 4247 // qualifier. 4248 // This is also the point where rvalue references and lvalue inits no longer 4249 // go together. 4250 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4251 return ICS; 4252 4253 // -- If the initializer expression 4254 // 4255 // -- is an xvalue, class prvalue, array prvalue or function 4256 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4257 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4258 (InitCategory.isXValue() || 4259 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4260 (InitCategory.isLValue() && T2->isFunctionType()))) { 4261 ICS.setStandard(); 4262 ICS.Standard.First = ICK_Identity; 4263 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4264 : ObjCConversion? ICK_Compatible_Conversion 4265 : ICK_Identity; 4266 ICS.Standard.Third = ICK_Identity; 4267 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4268 ICS.Standard.setToType(0, T2); 4269 ICS.Standard.setToType(1, T1); 4270 ICS.Standard.setToType(2, T1); 4271 ICS.Standard.ReferenceBinding = true; 4272 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4273 // binding unless we're binding to a class prvalue. 4274 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4275 // allow the use of rvalue references in C++98/03 for the benefit of 4276 // standard library implementors; therefore, we need the xvalue check here. 4277 ICS.Standard.DirectBinding = 4278 S.getLangOpts().CPlusPlus11 || 4279 (InitCategory.isPRValue() && !T2->isRecordType()); 4280 ICS.Standard.IsLvalueReference = !isRValRef; 4281 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4282 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4283 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4284 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4285 ICS.Standard.CopyConstructor = 0; 4286 return ICS; 4287 } 4288 4289 // -- has a class type (i.e., T2 is a class type), where T1 is not 4290 // reference-related to T2, and can be implicitly converted to 4291 // an xvalue, class prvalue, or function lvalue of type 4292 // "cv3 T3", where "cv1 T1" is reference-compatible with 4293 // "cv3 T3", 4294 // 4295 // then the reference is bound to the value of the initializer 4296 // expression in the first case and to the result of the conversion 4297 // in the second case (or, in either case, to an appropriate base 4298 // class subobject). 4299 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4300 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4301 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4302 Init, T2, /*AllowRvalues=*/true, 4303 AllowExplicit)) { 4304 // In the second case, if the reference is an rvalue reference 4305 // and the second standard conversion sequence of the 4306 // user-defined conversion sequence includes an lvalue-to-rvalue 4307 // conversion, the program is ill-formed. 4308 if (ICS.isUserDefined() && isRValRef && 4309 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4310 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4311 4312 return ICS; 4313 } 4314 4315 // -- Otherwise, a temporary of type "cv1 T1" is created and 4316 // initialized from the initializer expression using the 4317 // rules for a non-reference copy initialization (8.5). The 4318 // reference is then bound to the temporary. If T1 is 4319 // reference-related to T2, cv1 must be the same 4320 // cv-qualification as, or greater cv-qualification than, 4321 // cv2; otherwise, the program is ill-formed. 4322 if (RefRelationship == Sema::Ref_Related) { 4323 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4324 // we would be reference-compatible or reference-compatible with 4325 // added qualification. But that wasn't the case, so the reference 4326 // initialization fails. 4327 // 4328 // Note that we only want to check address spaces and cvr-qualifiers here. 4329 // ObjC GC and lifetime qualifiers aren't important. 4330 Qualifiers T1Quals = T1.getQualifiers(); 4331 Qualifiers T2Quals = T2.getQualifiers(); 4332 T1Quals.removeObjCGCAttr(); 4333 T1Quals.removeObjCLifetime(); 4334 T2Quals.removeObjCGCAttr(); 4335 T2Quals.removeObjCLifetime(); 4336 if (!T1Quals.compatiblyIncludes(T2Quals)) 4337 return ICS; 4338 } 4339 4340 // If at least one of the types is a class type, the types are not 4341 // related, and we aren't allowed any user conversions, the 4342 // reference binding fails. This case is important for breaking 4343 // recursion, since TryImplicitConversion below will attempt to 4344 // create a temporary through the use of a copy constructor. 4345 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4346 (T1->isRecordType() || T2->isRecordType())) 4347 return ICS; 4348 4349 // If T1 is reference-related to T2 and the reference is an rvalue 4350 // reference, the initializer expression shall not be an lvalue. 4351 if (RefRelationship >= Sema::Ref_Related && 4352 isRValRef && Init->Classify(S.Context).isLValue()) 4353 return ICS; 4354 4355 // C++ [over.ics.ref]p2: 4356 // When a parameter of reference type is not bound directly to 4357 // an argument expression, the conversion sequence is the one 4358 // required to convert the argument expression to the 4359 // underlying type of the reference according to 4360 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4361 // to copy-initializing a temporary of the underlying type with 4362 // the argument expression. Any difference in top-level 4363 // cv-qualification is subsumed by the initialization itself 4364 // and does not constitute a conversion. 4365 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4366 /*AllowExplicit=*/false, 4367 /*InOverloadResolution=*/false, 4368 /*CStyle=*/false, 4369 /*AllowObjCWritebackConversion=*/false); 4370 4371 // Of course, that's still a reference binding. 4372 if (ICS.isStandard()) { 4373 ICS.Standard.ReferenceBinding = true; 4374 ICS.Standard.IsLvalueReference = !isRValRef; 4375 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4376 ICS.Standard.BindsToRvalue = true; 4377 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4378 ICS.Standard.ObjCLifetimeConversionBinding = false; 4379 } else if (ICS.isUserDefined()) { 4380 // Don't allow rvalue references to bind to lvalues. 4381 if (DeclType->isRValueReferenceType()) { 4382 if (const ReferenceType *RefType 4383 = ICS.UserDefined.ConversionFunction->getResultType() 4384 ->getAs<LValueReferenceType>()) { 4385 if (!RefType->getPointeeType()->isFunctionType()) { 4386 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4387 DeclType); 4388 return ICS; 4389 } 4390 } 4391 } 4392 4393 ICS.UserDefined.After.ReferenceBinding = true; 4394 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4395 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4396 ICS.UserDefined.After.BindsToRvalue = true; 4397 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4398 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4399 } 4400 4401 return ICS; 4402} 4403 4404static ImplicitConversionSequence 4405TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4406 bool SuppressUserConversions, 4407 bool InOverloadResolution, 4408 bool AllowObjCWritebackConversion, 4409 bool AllowExplicit = false); 4410 4411/// TryListConversion - Try to copy-initialize a value of type ToType from the 4412/// initializer list From. 4413static ImplicitConversionSequence 4414TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4415 bool SuppressUserConversions, 4416 bool InOverloadResolution, 4417 bool AllowObjCWritebackConversion) { 4418 // C++11 [over.ics.list]p1: 4419 // When an argument is an initializer list, it is not an expression and 4420 // special rules apply for converting it to a parameter type. 4421 4422 ImplicitConversionSequence Result; 4423 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4424 Result.setListInitializationSequence(); 4425 4426 // We need a complete type for what follows. Incomplete types can never be 4427 // initialized from init lists. 4428 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4429 return Result; 4430 4431 // C++11 [over.ics.list]p2: 4432 // If the parameter type is std::initializer_list<X> or "array of X" and 4433 // all the elements can be implicitly converted to X, the implicit 4434 // conversion sequence is the worst conversion necessary to convert an 4435 // element of the list to X. 4436 bool toStdInitializerList = false; 4437 QualType X; 4438 if (ToType->isArrayType()) 4439 X = S.Context.getAsArrayType(ToType)->getElementType(); 4440 else 4441 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4442 if (!X.isNull()) { 4443 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4444 Expr *Init = From->getInit(i); 4445 ImplicitConversionSequence ICS = 4446 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4447 InOverloadResolution, 4448 AllowObjCWritebackConversion); 4449 // If a single element isn't convertible, fail. 4450 if (ICS.isBad()) { 4451 Result = ICS; 4452 break; 4453 } 4454 // Otherwise, look for the worst conversion. 4455 if (Result.isBad() || 4456 CompareImplicitConversionSequences(S, ICS, Result) == 4457 ImplicitConversionSequence::Worse) 4458 Result = ICS; 4459 } 4460 4461 // For an empty list, we won't have computed any conversion sequence. 4462 // Introduce the identity conversion sequence. 4463 if (From->getNumInits() == 0) { 4464 Result.setStandard(); 4465 Result.Standard.setAsIdentityConversion(); 4466 Result.Standard.setFromType(ToType); 4467 Result.Standard.setAllToTypes(ToType); 4468 } 4469 4470 Result.setListInitializationSequence(); 4471 Result.setStdInitializerListElement(toStdInitializerList); 4472 return Result; 4473 } 4474 4475 // C++11 [over.ics.list]p3: 4476 // Otherwise, if the parameter is a non-aggregate class X and overload 4477 // resolution chooses a single best constructor [...] the implicit 4478 // conversion sequence is a user-defined conversion sequence. If multiple 4479 // constructors are viable but none is better than the others, the 4480 // implicit conversion sequence is a user-defined conversion sequence. 4481 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4482 // This function can deal with initializer lists. 4483 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4484 /*AllowExplicit=*/false, 4485 InOverloadResolution, /*CStyle=*/false, 4486 AllowObjCWritebackConversion); 4487 Result.setListInitializationSequence(); 4488 return Result; 4489 } 4490 4491 // C++11 [over.ics.list]p4: 4492 // Otherwise, if the parameter has an aggregate type which can be 4493 // initialized from the initializer list [...] the implicit conversion 4494 // sequence is a user-defined conversion sequence. 4495 if (ToType->isAggregateType()) { 4496 // Type is an aggregate, argument is an init list. At this point it comes 4497 // down to checking whether the initialization works. 4498 // FIXME: Find out whether this parameter is consumed or not. 4499 InitializedEntity Entity = 4500 InitializedEntity::InitializeParameter(S.Context, ToType, 4501 /*Consumed=*/false); 4502 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4503 Result.setUserDefined(); 4504 Result.UserDefined.Before.setAsIdentityConversion(); 4505 // Initializer lists don't have a type. 4506 Result.UserDefined.Before.setFromType(QualType()); 4507 Result.UserDefined.Before.setAllToTypes(QualType()); 4508 4509 Result.UserDefined.After.setAsIdentityConversion(); 4510 Result.UserDefined.After.setFromType(ToType); 4511 Result.UserDefined.After.setAllToTypes(ToType); 4512 Result.UserDefined.ConversionFunction = 0; 4513 } 4514 return Result; 4515 } 4516 4517 // C++11 [over.ics.list]p5: 4518 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4519 if (ToType->isReferenceType()) { 4520 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4521 // mention initializer lists in any way. So we go by what list- 4522 // initialization would do and try to extrapolate from that. 4523 4524 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4525 4526 // If the initializer list has a single element that is reference-related 4527 // to the parameter type, we initialize the reference from that. 4528 if (From->getNumInits() == 1) { 4529 Expr *Init = From->getInit(0); 4530 4531 QualType T2 = Init->getType(); 4532 4533 // If the initializer is the address of an overloaded function, try 4534 // to resolve the overloaded function. If all goes well, T2 is the 4535 // type of the resulting function. 4536 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4537 DeclAccessPair Found; 4538 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4539 Init, ToType, false, Found)) 4540 T2 = Fn->getType(); 4541 } 4542 4543 // Compute some basic properties of the types and the initializer. 4544 bool dummy1 = false; 4545 bool dummy2 = false; 4546 bool dummy3 = false; 4547 Sema::ReferenceCompareResult RefRelationship 4548 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4549 dummy2, dummy3); 4550 4551 if (RefRelationship >= Sema::Ref_Related) 4552 return TryReferenceInit(S, Init, ToType, 4553 /*FIXME:*/From->getLocStart(), 4554 SuppressUserConversions, 4555 /*AllowExplicit=*/false); 4556 } 4557 4558 // Otherwise, we bind the reference to a temporary created from the 4559 // initializer list. 4560 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4561 InOverloadResolution, 4562 AllowObjCWritebackConversion); 4563 if (Result.isFailure()) 4564 return Result; 4565 assert(!Result.isEllipsis() && 4566 "Sub-initialization cannot result in ellipsis conversion."); 4567 4568 // Can we even bind to a temporary? 4569 if (ToType->isRValueReferenceType() || 4570 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4571 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4572 Result.UserDefined.After; 4573 SCS.ReferenceBinding = true; 4574 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4575 SCS.BindsToRvalue = true; 4576 SCS.BindsToFunctionLvalue = false; 4577 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4578 SCS.ObjCLifetimeConversionBinding = false; 4579 } else 4580 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4581 From, ToType); 4582 return Result; 4583 } 4584 4585 // C++11 [over.ics.list]p6: 4586 // Otherwise, if the parameter type is not a class: 4587 if (!ToType->isRecordType()) { 4588 // - if the initializer list has one element, the implicit conversion 4589 // sequence is the one required to convert the element to the 4590 // parameter type. 4591 unsigned NumInits = From->getNumInits(); 4592 if (NumInits == 1) 4593 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4594 SuppressUserConversions, 4595 InOverloadResolution, 4596 AllowObjCWritebackConversion); 4597 // - if the initializer list has no elements, the implicit conversion 4598 // sequence is the identity conversion. 4599 else if (NumInits == 0) { 4600 Result.setStandard(); 4601 Result.Standard.setAsIdentityConversion(); 4602 Result.Standard.setFromType(ToType); 4603 Result.Standard.setAllToTypes(ToType); 4604 } 4605 Result.setListInitializationSequence(); 4606 return Result; 4607 } 4608 4609 // C++11 [over.ics.list]p7: 4610 // In all cases other than those enumerated above, no conversion is possible 4611 return Result; 4612} 4613 4614/// TryCopyInitialization - Try to copy-initialize a value of type 4615/// ToType from the expression From. Return the implicit conversion 4616/// sequence required to pass this argument, which may be a bad 4617/// conversion sequence (meaning that the argument cannot be passed to 4618/// a parameter of this type). If @p SuppressUserConversions, then we 4619/// do not permit any user-defined conversion sequences. 4620static ImplicitConversionSequence 4621TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4622 bool SuppressUserConversions, 4623 bool InOverloadResolution, 4624 bool AllowObjCWritebackConversion, 4625 bool AllowExplicit) { 4626 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4627 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4628 InOverloadResolution,AllowObjCWritebackConversion); 4629 4630 if (ToType->isReferenceType()) 4631 return TryReferenceInit(S, From, ToType, 4632 /*FIXME:*/From->getLocStart(), 4633 SuppressUserConversions, 4634 AllowExplicit); 4635 4636 return TryImplicitConversion(S, From, ToType, 4637 SuppressUserConversions, 4638 /*AllowExplicit=*/false, 4639 InOverloadResolution, 4640 /*CStyle=*/false, 4641 AllowObjCWritebackConversion); 4642} 4643 4644static bool TryCopyInitialization(const CanQualType FromQTy, 4645 const CanQualType ToQTy, 4646 Sema &S, 4647 SourceLocation Loc, 4648 ExprValueKind FromVK) { 4649 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4650 ImplicitConversionSequence ICS = 4651 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4652 4653 return !ICS.isBad(); 4654} 4655 4656/// TryObjectArgumentInitialization - Try to initialize the object 4657/// parameter of the given member function (@c Method) from the 4658/// expression @p From. 4659static ImplicitConversionSequence 4660TryObjectArgumentInitialization(Sema &S, QualType FromType, 4661 Expr::Classification FromClassification, 4662 CXXMethodDecl *Method, 4663 CXXRecordDecl *ActingContext) { 4664 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4665 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4666 // const volatile object. 4667 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4668 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4669 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4670 4671 // Set up the conversion sequence as a "bad" conversion, to allow us 4672 // to exit early. 4673 ImplicitConversionSequence ICS; 4674 4675 // We need to have an object of class type. 4676 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4677 FromType = PT->getPointeeType(); 4678 4679 // When we had a pointer, it's implicitly dereferenced, so we 4680 // better have an lvalue. 4681 assert(FromClassification.isLValue()); 4682 } 4683 4684 assert(FromType->isRecordType()); 4685 4686 // C++0x [over.match.funcs]p4: 4687 // For non-static member functions, the type of the implicit object 4688 // parameter is 4689 // 4690 // - "lvalue reference to cv X" for functions declared without a 4691 // ref-qualifier or with the & ref-qualifier 4692 // - "rvalue reference to cv X" for functions declared with the && 4693 // ref-qualifier 4694 // 4695 // where X is the class of which the function is a member and cv is the 4696 // cv-qualification on the member function declaration. 4697 // 4698 // However, when finding an implicit conversion sequence for the argument, we 4699 // are not allowed to create temporaries or perform user-defined conversions 4700 // (C++ [over.match.funcs]p5). We perform a simplified version of 4701 // reference binding here, that allows class rvalues to bind to 4702 // non-constant references. 4703 4704 // First check the qualifiers. 4705 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4706 if (ImplicitParamType.getCVRQualifiers() 4707 != FromTypeCanon.getLocalCVRQualifiers() && 4708 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4709 ICS.setBad(BadConversionSequence::bad_qualifiers, 4710 FromType, ImplicitParamType); 4711 return ICS; 4712 } 4713 4714 // Check that we have either the same type or a derived type. It 4715 // affects the conversion rank. 4716 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4717 ImplicitConversionKind SecondKind; 4718 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4719 SecondKind = ICK_Identity; 4720 } else if (S.IsDerivedFrom(FromType, ClassType)) 4721 SecondKind = ICK_Derived_To_Base; 4722 else { 4723 ICS.setBad(BadConversionSequence::unrelated_class, 4724 FromType, ImplicitParamType); 4725 return ICS; 4726 } 4727 4728 // Check the ref-qualifier. 4729 switch (Method->getRefQualifier()) { 4730 case RQ_None: 4731 // Do nothing; we don't care about lvalueness or rvalueness. 4732 break; 4733 4734 case RQ_LValue: 4735 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4736 // non-const lvalue reference cannot bind to an rvalue 4737 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4738 ImplicitParamType); 4739 return ICS; 4740 } 4741 break; 4742 4743 case RQ_RValue: 4744 if (!FromClassification.isRValue()) { 4745 // rvalue reference cannot bind to an lvalue 4746 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4747 ImplicitParamType); 4748 return ICS; 4749 } 4750 break; 4751 } 4752 4753 // Success. Mark this as a reference binding. 4754 ICS.setStandard(); 4755 ICS.Standard.setAsIdentityConversion(); 4756 ICS.Standard.Second = SecondKind; 4757 ICS.Standard.setFromType(FromType); 4758 ICS.Standard.setAllToTypes(ImplicitParamType); 4759 ICS.Standard.ReferenceBinding = true; 4760 ICS.Standard.DirectBinding = true; 4761 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4762 ICS.Standard.BindsToFunctionLvalue = false; 4763 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4764 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4765 = (Method->getRefQualifier() == RQ_None); 4766 return ICS; 4767} 4768 4769/// PerformObjectArgumentInitialization - Perform initialization of 4770/// the implicit object parameter for the given Method with the given 4771/// expression. 4772ExprResult 4773Sema::PerformObjectArgumentInitialization(Expr *From, 4774 NestedNameSpecifier *Qualifier, 4775 NamedDecl *FoundDecl, 4776 CXXMethodDecl *Method) { 4777 QualType FromRecordType, DestType; 4778 QualType ImplicitParamRecordType = 4779 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4780 4781 Expr::Classification FromClassification; 4782 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4783 FromRecordType = PT->getPointeeType(); 4784 DestType = Method->getThisType(Context); 4785 FromClassification = Expr::Classification::makeSimpleLValue(); 4786 } else { 4787 FromRecordType = From->getType(); 4788 DestType = ImplicitParamRecordType; 4789 FromClassification = From->Classify(Context); 4790 } 4791 4792 // Note that we always use the true parent context when performing 4793 // the actual argument initialization. 4794 ImplicitConversionSequence ICS 4795 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4796 Method, Method->getParent()); 4797 if (ICS.isBad()) { 4798 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4799 Qualifiers FromQs = FromRecordType.getQualifiers(); 4800 Qualifiers ToQs = DestType.getQualifiers(); 4801 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4802 if (CVR) { 4803 Diag(From->getLocStart(), 4804 diag::err_member_function_call_bad_cvr) 4805 << Method->getDeclName() << FromRecordType << (CVR - 1) 4806 << From->getSourceRange(); 4807 Diag(Method->getLocation(), diag::note_previous_decl) 4808 << Method->getDeclName(); 4809 return ExprError(); 4810 } 4811 } 4812 4813 return Diag(From->getLocStart(), 4814 diag::err_implicit_object_parameter_init) 4815 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4816 } 4817 4818 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4819 ExprResult FromRes = 4820 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4821 if (FromRes.isInvalid()) 4822 return ExprError(); 4823 From = FromRes.take(); 4824 } 4825 4826 if (!Context.hasSameType(From->getType(), DestType)) 4827 From = ImpCastExprToType(From, DestType, CK_NoOp, 4828 From->getValueKind()).take(); 4829 return Owned(From); 4830} 4831 4832/// TryContextuallyConvertToBool - Attempt to contextually convert the 4833/// expression From to bool (C++0x [conv]p3). 4834static ImplicitConversionSequence 4835TryContextuallyConvertToBool(Sema &S, Expr *From) { 4836 // FIXME: This is pretty broken. 4837 return TryImplicitConversion(S, From, S.Context.BoolTy, 4838 // FIXME: Are these flags correct? 4839 /*SuppressUserConversions=*/false, 4840 /*AllowExplicit=*/true, 4841 /*InOverloadResolution=*/false, 4842 /*CStyle=*/false, 4843 /*AllowObjCWritebackConversion=*/false); 4844} 4845 4846/// PerformContextuallyConvertToBool - Perform a contextual conversion 4847/// of the expression From to bool (C++0x [conv]p3). 4848ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4849 if (checkPlaceholderForOverload(*this, From)) 4850 return ExprError(); 4851 4852 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4853 if (!ICS.isBad()) 4854 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4855 4856 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4857 return Diag(From->getLocStart(), 4858 diag::err_typecheck_bool_condition) 4859 << From->getType() << From->getSourceRange(); 4860 return ExprError(); 4861} 4862 4863/// Check that the specified conversion is permitted in a converted constant 4864/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4865/// is acceptable. 4866static bool CheckConvertedConstantConversions(Sema &S, 4867 StandardConversionSequence &SCS) { 4868 // Since we know that the target type is an integral or unscoped enumeration 4869 // type, most conversion kinds are impossible. All possible First and Third 4870 // conversions are fine. 4871 switch (SCS.Second) { 4872 case ICK_Identity: 4873 case ICK_Integral_Promotion: 4874 case ICK_Integral_Conversion: 4875 case ICK_Zero_Event_Conversion: 4876 return true; 4877 4878 case ICK_Boolean_Conversion: 4879 // Conversion from an integral or unscoped enumeration type to bool is 4880 // classified as ICK_Boolean_Conversion, but it's also an integral 4881 // conversion, so it's permitted in a converted constant expression. 4882 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4883 SCS.getToType(2)->isBooleanType(); 4884 4885 case ICK_Floating_Integral: 4886 case ICK_Complex_Real: 4887 return false; 4888 4889 case ICK_Lvalue_To_Rvalue: 4890 case ICK_Array_To_Pointer: 4891 case ICK_Function_To_Pointer: 4892 case ICK_NoReturn_Adjustment: 4893 case ICK_Qualification: 4894 case ICK_Compatible_Conversion: 4895 case ICK_Vector_Conversion: 4896 case ICK_Vector_Splat: 4897 case ICK_Derived_To_Base: 4898 case ICK_Pointer_Conversion: 4899 case ICK_Pointer_Member: 4900 case ICK_Block_Pointer_Conversion: 4901 case ICK_Writeback_Conversion: 4902 case ICK_Floating_Promotion: 4903 case ICK_Complex_Promotion: 4904 case ICK_Complex_Conversion: 4905 case ICK_Floating_Conversion: 4906 case ICK_TransparentUnionConversion: 4907 llvm_unreachable("unexpected second conversion kind"); 4908 4909 case ICK_Num_Conversion_Kinds: 4910 break; 4911 } 4912 4913 llvm_unreachable("unknown conversion kind"); 4914} 4915 4916/// CheckConvertedConstantExpression - Check that the expression From is a 4917/// converted constant expression of type T, perform the conversion and produce 4918/// the converted expression, per C++11 [expr.const]p3. 4919ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4920 llvm::APSInt &Value, 4921 CCEKind CCE) { 4922 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4923 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4924 4925 if (checkPlaceholderForOverload(*this, From)) 4926 return ExprError(); 4927 4928 // C++11 [expr.const]p3 with proposed wording fixes: 4929 // A converted constant expression of type T is a core constant expression, 4930 // implicitly converted to a prvalue of type T, where the converted 4931 // expression is a literal constant expression and the implicit conversion 4932 // sequence contains only user-defined conversions, lvalue-to-rvalue 4933 // conversions, integral promotions, and integral conversions other than 4934 // narrowing conversions. 4935 ImplicitConversionSequence ICS = 4936 TryImplicitConversion(From, T, 4937 /*SuppressUserConversions=*/false, 4938 /*AllowExplicit=*/false, 4939 /*InOverloadResolution=*/false, 4940 /*CStyle=*/false, 4941 /*AllowObjcWritebackConversion=*/false); 4942 StandardConversionSequence *SCS = 0; 4943 switch (ICS.getKind()) { 4944 case ImplicitConversionSequence::StandardConversion: 4945 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4946 return Diag(From->getLocStart(), 4947 diag::err_typecheck_converted_constant_expression_disallowed) 4948 << From->getType() << From->getSourceRange() << T; 4949 SCS = &ICS.Standard; 4950 break; 4951 case ImplicitConversionSequence::UserDefinedConversion: 4952 // We are converting from class type to an integral or enumeration type, so 4953 // the Before sequence must be trivial. 4954 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4955 return Diag(From->getLocStart(), 4956 diag::err_typecheck_converted_constant_expression_disallowed) 4957 << From->getType() << From->getSourceRange() << T; 4958 SCS = &ICS.UserDefined.After; 4959 break; 4960 case ImplicitConversionSequence::AmbiguousConversion: 4961 case ImplicitConversionSequence::BadConversion: 4962 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4963 return Diag(From->getLocStart(), 4964 diag::err_typecheck_converted_constant_expression) 4965 << From->getType() << From->getSourceRange() << T; 4966 return ExprError(); 4967 4968 case ImplicitConversionSequence::EllipsisConversion: 4969 llvm_unreachable("ellipsis conversion in converted constant expression"); 4970 } 4971 4972 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4973 if (Result.isInvalid()) 4974 return Result; 4975 4976 // Check for a narrowing implicit conversion. 4977 APValue PreNarrowingValue; 4978 QualType PreNarrowingType; 4979 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4980 PreNarrowingType)) { 4981 case NK_Variable_Narrowing: 4982 // Implicit conversion to a narrower type, and the value is not a constant 4983 // expression. We'll diagnose this in a moment. 4984 case NK_Not_Narrowing: 4985 break; 4986 4987 case NK_Constant_Narrowing: 4988 Diag(From->getLocStart(), 4989 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4990 diag::err_cce_narrowing) 4991 << CCE << /*Constant*/1 4992 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4993 break; 4994 4995 case NK_Type_Narrowing: 4996 Diag(From->getLocStart(), 4997 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4998 diag::err_cce_narrowing) 4999 << CCE << /*Constant*/0 << From->getType() << T; 5000 break; 5001 } 5002 5003 // Check the expression is a constant expression. 5004 SmallVector<PartialDiagnosticAt, 8> Notes; 5005 Expr::EvalResult Eval; 5006 Eval.Diag = &Notes; 5007 5008 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 5009 // The expression can't be folded, so we can't keep it at this position in 5010 // the AST. 5011 Result = ExprError(); 5012 } else { 5013 Value = Eval.Val.getInt(); 5014 5015 if (Notes.empty()) { 5016 // It's a constant expression. 5017 return Result; 5018 } 5019 } 5020 5021 // It's not a constant expression. Produce an appropriate diagnostic. 5022 if (Notes.size() == 1 && 5023 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5024 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5025 else { 5026 Diag(From->getLocStart(), diag::err_expr_not_cce) 5027 << CCE << From->getSourceRange(); 5028 for (unsigned I = 0; I < Notes.size(); ++I) 5029 Diag(Notes[I].first, Notes[I].second); 5030 } 5031 return Result; 5032} 5033 5034/// dropPointerConversions - If the given standard conversion sequence 5035/// involves any pointer conversions, remove them. This may change 5036/// the result type of the conversion sequence. 5037static void dropPointerConversion(StandardConversionSequence &SCS) { 5038 if (SCS.Second == ICK_Pointer_Conversion) { 5039 SCS.Second = ICK_Identity; 5040 SCS.Third = ICK_Identity; 5041 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5042 } 5043} 5044 5045/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5046/// convert the expression From to an Objective-C pointer type. 5047static ImplicitConversionSequence 5048TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5049 // Do an implicit conversion to 'id'. 5050 QualType Ty = S.Context.getObjCIdType(); 5051 ImplicitConversionSequence ICS 5052 = TryImplicitConversion(S, From, Ty, 5053 // FIXME: Are these flags correct? 5054 /*SuppressUserConversions=*/false, 5055 /*AllowExplicit=*/true, 5056 /*InOverloadResolution=*/false, 5057 /*CStyle=*/false, 5058 /*AllowObjCWritebackConversion=*/false); 5059 5060 // Strip off any final conversions to 'id'. 5061 switch (ICS.getKind()) { 5062 case ImplicitConversionSequence::BadConversion: 5063 case ImplicitConversionSequence::AmbiguousConversion: 5064 case ImplicitConversionSequence::EllipsisConversion: 5065 break; 5066 5067 case ImplicitConversionSequence::UserDefinedConversion: 5068 dropPointerConversion(ICS.UserDefined.After); 5069 break; 5070 5071 case ImplicitConversionSequence::StandardConversion: 5072 dropPointerConversion(ICS.Standard); 5073 break; 5074 } 5075 5076 return ICS; 5077} 5078 5079/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5080/// conversion of the expression From to an Objective-C pointer type. 5081ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5082 if (checkPlaceholderForOverload(*this, From)) 5083 return ExprError(); 5084 5085 QualType Ty = Context.getObjCIdType(); 5086 ImplicitConversionSequence ICS = 5087 TryContextuallyConvertToObjCPointer(*this, From); 5088 if (!ICS.isBad()) 5089 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5090 return ExprError(); 5091} 5092 5093/// Determine whether the provided type is an integral type, or an enumeration 5094/// type of a permitted flavor. 5095static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5096 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5097 : T->isIntegralOrUnscopedEnumerationType(); 5098} 5099 5100/// \brief Attempt to convert the given expression to an integral or 5101/// enumeration type. 5102/// 5103/// This routine will attempt to convert an expression of class type to an 5104/// integral or enumeration type, if that class type only has a single 5105/// conversion to an integral or enumeration type. 5106/// 5107/// \param Loc The source location of the construct that requires the 5108/// conversion. 5109/// 5110/// \param From The expression we're converting from. 5111/// 5112/// \param Diagnoser Used to output any diagnostics. 5113/// 5114/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5115/// enumerations should be considered. 5116/// 5117/// \returns The expression, converted to an integral or enumeration type if 5118/// successful. 5119ExprResult 5120Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5121 ICEConvertDiagnoser &Diagnoser, 5122 bool AllowScopedEnumerations) { 5123 // We can't perform any more checking for type-dependent expressions. 5124 if (From->isTypeDependent()) 5125 return Owned(From); 5126 5127 // Process placeholders immediately. 5128 if (From->hasPlaceholderType()) { 5129 ExprResult result = CheckPlaceholderExpr(From); 5130 if (result.isInvalid()) return result; 5131 From = result.take(); 5132 } 5133 5134 // If the expression already has integral or enumeration type, we're golden. 5135 QualType T = From->getType(); 5136 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5137 return DefaultLvalueConversion(From); 5138 5139 // FIXME: Check for missing '()' if T is a function type? 5140 5141 // If we don't have a class type in C++, there's no way we can get an 5142 // expression of integral or enumeration type. 5143 const RecordType *RecordTy = T->getAs<RecordType>(); 5144 if (!RecordTy || !getLangOpts().CPlusPlus) { 5145 if (!Diagnoser.Suppress) 5146 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5147 return Owned(From); 5148 } 5149 5150 // We must have a complete class type. 5151 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5152 ICEConvertDiagnoser &Diagnoser; 5153 Expr *From; 5154 5155 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5156 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5157 5158 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5159 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5160 } 5161 } IncompleteDiagnoser(Diagnoser, From); 5162 5163 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5164 return Owned(From); 5165 5166 // Look for a conversion to an integral or enumeration type. 5167 UnresolvedSet<4> ViableConversions; 5168 UnresolvedSet<4> ExplicitConversions; 5169 std::pair<CXXRecordDecl::conversion_iterator, 5170 CXXRecordDecl::conversion_iterator> Conversions 5171 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5172 5173 bool HadMultipleCandidates 5174 = (std::distance(Conversions.first, Conversions.second) > 1); 5175 5176 for (CXXRecordDecl::conversion_iterator 5177 I = Conversions.first, E = Conversions.second; I != E; ++I) { 5178 if (CXXConversionDecl *Conversion 5179 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5180 if (isIntegralOrEnumerationType( 5181 Conversion->getConversionType().getNonReferenceType(), 5182 AllowScopedEnumerations)) { 5183 if (Conversion->isExplicit()) 5184 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5185 else 5186 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5187 } 5188 } 5189 } 5190 5191 switch (ViableConversions.size()) { 5192 case 0: 5193 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5194 DeclAccessPair Found = ExplicitConversions[0]; 5195 CXXConversionDecl *Conversion 5196 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5197 5198 // The user probably meant to invoke the given explicit 5199 // conversion; use it. 5200 QualType ConvTy 5201 = Conversion->getConversionType().getNonReferenceType(); 5202 std::string TypeStr; 5203 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5204 5205 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5206 << FixItHint::CreateInsertion(From->getLocStart(), 5207 "static_cast<" + TypeStr + ">(") 5208 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5209 ")"); 5210 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5211 5212 // If we aren't in a SFINAE context, build a call to the 5213 // explicit conversion function. 5214 if (isSFINAEContext()) 5215 return ExprError(); 5216 5217 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5218 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5219 HadMultipleCandidates); 5220 if (Result.isInvalid()) 5221 return ExprError(); 5222 // Record usage of conversion in an implicit cast. 5223 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5224 CK_UserDefinedConversion, 5225 Result.get(), 0, 5226 Result.get()->getValueKind()); 5227 } 5228 5229 // We'll complain below about a non-integral condition type. 5230 break; 5231 5232 case 1: { 5233 // Apply this conversion. 5234 DeclAccessPair Found = ViableConversions[0]; 5235 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5236 5237 CXXConversionDecl *Conversion 5238 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5239 QualType ConvTy 5240 = Conversion->getConversionType().getNonReferenceType(); 5241 if (!Diagnoser.SuppressConversion) { 5242 if (isSFINAEContext()) 5243 return ExprError(); 5244 5245 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5246 << From->getSourceRange(); 5247 } 5248 5249 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5250 HadMultipleCandidates); 5251 if (Result.isInvalid()) 5252 return ExprError(); 5253 // Record usage of conversion in an implicit cast. 5254 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5255 CK_UserDefinedConversion, 5256 Result.get(), 0, 5257 Result.get()->getValueKind()); 5258 break; 5259 } 5260 5261 default: 5262 if (Diagnoser.Suppress) 5263 return ExprError(); 5264 5265 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5266 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5267 CXXConversionDecl *Conv 5268 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5269 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5270 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5271 } 5272 return Owned(From); 5273 } 5274 5275 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5276 !Diagnoser.Suppress) { 5277 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5278 << From->getSourceRange(); 5279 } 5280 5281 return DefaultLvalueConversion(From); 5282} 5283 5284/// AddOverloadCandidate - Adds the given function to the set of 5285/// candidate functions, using the given function call arguments. If 5286/// @p SuppressUserConversions, then don't allow user-defined 5287/// conversions via constructors or conversion operators. 5288/// 5289/// \param PartialOverloading true if we are performing "partial" overloading 5290/// based on an incomplete set of function arguments. This feature is used by 5291/// code completion. 5292void 5293Sema::AddOverloadCandidate(FunctionDecl *Function, 5294 DeclAccessPair FoundDecl, 5295 ArrayRef<Expr *> Args, 5296 OverloadCandidateSet& CandidateSet, 5297 bool SuppressUserConversions, 5298 bool PartialOverloading, 5299 bool AllowExplicit) { 5300 const FunctionProtoType* Proto 5301 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5302 assert(Proto && "Functions without a prototype cannot be overloaded"); 5303 assert(!Function->getDescribedFunctionTemplate() && 5304 "Use AddTemplateOverloadCandidate for function templates"); 5305 5306 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5307 if (!isa<CXXConstructorDecl>(Method)) { 5308 // If we get here, it's because we're calling a member function 5309 // that is named without a member access expression (e.g., 5310 // "this->f") that was either written explicitly or created 5311 // implicitly. This can happen with a qualified call to a member 5312 // function, e.g., X::f(). We use an empty type for the implied 5313 // object argument (C++ [over.call.func]p3), and the acting context 5314 // is irrelevant. 5315 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5316 QualType(), Expr::Classification::makeSimpleLValue(), 5317 Args, CandidateSet, SuppressUserConversions); 5318 return; 5319 } 5320 // We treat a constructor like a non-member function, since its object 5321 // argument doesn't participate in overload resolution. 5322 } 5323 5324 if (!CandidateSet.isNewCandidate(Function)) 5325 return; 5326 5327 // Overload resolution is always an unevaluated context. 5328 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5329 5330 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5331 // C++ [class.copy]p3: 5332 // A member function template is never instantiated to perform the copy 5333 // of a class object to an object of its class type. 5334 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5335 if (Args.size() == 1 && 5336 Constructor->isSpecializationCopyingObject() && 5337 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5338 IsDerivedFrom(Args[0]->getType(), ClassType))) 5339 return; 5340 } 5341 5342 // Add this candidate 5343 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5344 Candidate.FoundDecl = FoundDecl; 5345 Candidate.Function = Function; 5346 Candidate.Viable = true; 5347 Candidate.IsSurrogate = false; 5348 Candidate.IgnoreObjectArgument = false; 5349 Candidate.ExplicitCallArguments = Args.size(); 5350 5351 unsigned NumArgsInProto = Proto->getNumArgs(); 5352 5353 // (C++ 13.3.2p2): A candidate function having fewer than m 5354 // parameters is viable only if it has an ellipsis in its parameter 5355 // list (8.3.5). 5356 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5357 !Proto->isVariadic()) { 5358 Candidate.Viable = false; 5359 Candidate.FailureKind = ovl_fail_too_many_arguments; 5360 return; 5361 } 5362 5363 // (C++ 13.3.2p2): A candidate function having more than m parameters 5364 // is viable only if the (m+1)st parameter has a default argument 5365 // (8.3.6). For the purposes of overload resolution, the 5366 // parameter list is truncated on the right, so that there are 5367 // exactly m parameters. 5368 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5369 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5370 // Not enough arguments. 5371 Candidate.Viable = false; 5372 Candidate.FailureKind = ovl_fail_too_few_arguments; 5373 return; 5374 } 5375 5376 // (CUDA B.1): Check for invalid calls between targets. 5377 if (getLangOpts().CUDA) 5378 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5379 if (CheckCUDATarget(Caller, Function)) { 5380 Candidate.Viable = false; 5381 Candidate.FailureKind = ovl_fail_bad_target; 5382 return; 5383 } 5384 5385 // Determine the implicit conversion sequences for each of the 5386 // arguments. 5387 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5388 if (ArgIdx < NumArgsInProto) { 5389 // (C++ 13.3.2p3): for F to be a viable function, there shall 5390 // exist for each argument an implicit conversion sequence 5391 // (13.3.3.1) that converts that argument to the corresponding 5392 // parameter of F. 5393 QualType ParamType = Proto->getArgType(ArgIdx); 5394 Candidate.Conversions[ArgIdx] 5395 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5396 SuppressUserConversions, 5397 /*InOverloadResolution=*/true, 5398 /*AllowObjCWritebackConversion=*/ 5399 getLangOpts().ObjCAutoRefCount, 5400 AllowExplicit); 5401 if (Candidate.Conversions[ArgIdx].isBad()) { 5402 Candidate.Viable = false; 5403 Candidate.FailureKind = ovl_fail_bad_conversion; 5404 break; 5405 } 5406 } else { 5407 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5408 // argument for which there is no corresponding parameter is 5409 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5410 Candidate.Conversions[ArgIdx].setEllipsis(); 5411 } 5412 } 5413} 5414 5415/// \brief Add all of the function declarations in the given function set to 5416/// the overload canddiate set. 5417void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5418 ArrayRef<Expr *> Args, 5419 OverloadCandidateSet& CandidateSet, 5420 bool SuppressUserConversions, 5421 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5422 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5423 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5424 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5425 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5426 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5427 cast<CXXMethodDecl>(FD)->getParent(), 5428 Args[0]->getType(), Args[0]->Classify(Context), 5429 Args.slice(1), CandidateSet, 5430 SuppressUserConversions); 5431 else 5432 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5433 SuppressUserConversions); 5434 } else { 5435 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5436 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5437 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5438 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5439 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5440 ExplicitTemplateArgs, 5441 Args[0]->getType(), 5442 Args[0]->Classify(Context), Args.slice(1), 5443 CandidateSet, SuppressUserConversions); 5444 else 5445 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5446 ExplicitTemplateArgs, Args, 5447 CandidateSet, SuppressUserConversions); 5448 } 5449 } 5450} 5451 5452/// AddMethodCandidate - Adds a named decl (which is some kind of 5453/// method) as a method candidate to the given overload set. 5454void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5455 QualType ObjectType, 5456 Expr::Classification ObjectClassification, 5457 Expr **Args, unsigned NumArgs, 5458 OverloadCandidateSet& CandidateSet, 5459 bool SuppressUserConversions) { 5460 NamedDecl *Decl = FoundDecl.getDecl(); 5461 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5462 5463 if (isa<UsingShadowDecl>(Decl)) 5464 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5465 5466 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5467 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5468 "Expected a member function template"); 5469 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5470 /*ExplicitArgs*/ 0, 5471 ObjectType, ObjectClassification, 5472 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5473 SuppressUserConversions); 5474 } else { 5475 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5476 ObjectType, ObjectClassification, 5477 llvm::makeArrayRef(Args, NumArgs), 5478 CandidateSet, SuppressUserConversions); 5479 } 5480} 5481 5482/// AddMethodCandidate - Adds the given C++ member function to the set 5483/// of candidate functions, using the given function call arguments 5484/// and the object argument (@c Object). For example, in a call 5485/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5486/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5487/// allow user-defined conversions via constructors or conversion 5488/// operators. 5489void 5490Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5491 CXXRecordDecl *ActingContext, QualType ObjectType, 5492 Expr::Classification ObjectClassification, 5493 ArrayRef<Expr *> Args, 5494 OverloadCandidateSet& CandidateSet, 5495 bool SuppressUserConversions) { 5496 const FunctionProtoType* Proto 5497 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5498 assert(Proto && "Methods without a prototype cannot be overloaded"); 5499 assert(!isa<CXXConstructorDecl>(Method) && 5500 "Use AddOverloadCandidate for constructors"); 5501 5502 if (!CandidateSet.isNewCandidate(Method)) 5503 return; 5504 5505 // Overload resolution is always an unevaluated context. 5506 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5507 5508 // Add this candidate 5509 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5510 Candidate.FoundDecl = FoundDecl; 5511 Candidate.Function = Method; 5512 Candidate.IsSurrogate = false; 5513 Candidate.IgnoreObjectArgument = false; 5514 Candidate.ExplicitCallArguments = Args.size(); 5515 5516 unsigned NumArgsInProto = Proto->getNumArgs(); 5517 5518 // (C++ 13.3.2p2): A candidate function having fewer than m 5519 // parameters is viable only if it has an ellipsis in its parameter 5520 // list (8.3.5). 5521 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5522 Candidate.Viable = false; 5523 Candidate.FailureKind = ovl_fail_too_many_arguments; 5524 return; 5525 } 5526 5527 // (C++ 13.3.2p2): A candidate function having more than m parameters 5528 // is viable only if the (m+1)st parameter has a default argument 5529 // (8.3.6). For the purposes of overload resolution, the 5530 // parameter list is truncated on the right, so that there are 5531 // exactly m parameters. 5532 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5533 if (Args.size() < MinRequiredArgs) { 5534 // Not enough arguments. 5535 Candidate.Viable = false; 5536 Candidate.FailureKind = ovl_fail_too_few_arguments; 5537 return; 5538 } 5539 5540 Candidate.Viable = true; 5541 5542 if (Method->isStatic() || ObjectType.isNull()) 5543 // The implicit object argument is ignored. 5544 Candidate.IgnoreObjectArgument = true; 5545 else { 5546 // Determine the implicit conversion sequence for the object 5547 // parameter. 5548 Candidate.Conversions[0] 5549 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5550 Method, ActingContext); 5551 if (Candidate.Conversions[0].isBad()) { 5552 Candidate.Viable = false; 5553 Candidate.FailureKind = ovl_fail_bad_conversion; 5554 return; 5555 } 5556 } 5557 5558 // Determine the implicit conversion sequences for each of the 5559 // arguments. 5560 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5561 if (ArgIdx < NumArgsInProto) { 5562 // (C++ 13.3.2p3): for F to be a viable function, there shall 5563 // exist for each argument an implicit conversion sequence 5564 // (13.3.3.1) that converts that argument to the corresponding 5565 // parameter of F. 5566 QualType ParamType = Proto->getArgType(ArgIdx); 5567 Candidate.Conversions[ArgIdx + 1] 5568 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5569 SuppressUserConversions, 5570 /*InOverloadResolution=*/true, 5571 /*AllowObjCWritebackConversion=*/ 5572 getLangOpts().ObjCAutoRefCount); 5573 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5574 Candidate.Viable = false; 5575 Candidate.FailureKind = ovl_fail_bad_conversion; 5576 break; 5577 } 5578 } else { 5579 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5580 // argument for which there is no corresponding parameter is 5581 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5582 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5583 } 5584 } 5585} 5586 5587/// \brief Add a C++ member function template as a candidate to the candidate 5588/// set, using template argument deduction to produce an appropriate member 5589/// function template specialization. 5590void 5591Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5592 DeclAccessPair FoundDecl, 5593 CXXRecordDecl *ActingContext, 5594 TemplateArgumentListInfo *ExplicitTemplateArgs, 5595 QualType ObjectType, 5596 Expr::Classification ObjectClassification, 5597 ArrayRef<Expr *> Args, 5598 OverloadCandidateSet& CandidateSet, 5599 bool SuppressUserConversions) { 5600 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5601 return; 5602 5603 // C++ [over.match.funcs]p7: 5604 // In each case where a candidate is a function template, candidate 5605 // function template specializations are generated using template argument 5606 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5607 // candidate functions in the usual way.113) A given name can refer to one 5608 // or more function templates and also to a set of overloaded non-template 5609 // functions. In such a case, the candidate functions generated from each 5610 // function template are combined with the set of non-template candidate 5611 // functions. 5612 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5613 FunctionDecl *Specialization = 0; 5614 if (TemplateDeductionResult Result 5615 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5616 Specialization, Info)) { 5617 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5618 Candidate.FoundDecl = FoundDecl; 5619 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5620 Candidate.Viable = false; 5621 Candidate.FailureKind = ovl_fail_bad_deduction; 5622 Candidate.IsSurrogate = false; 5623 Candidate.IgnoreObjectArgument = false; 5624 Candidate.ExplicitCallArguments = Args.size(); 5625 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5626 Info); 5627 return; 5628 } 5629 5630 // Add the function template specialization produced by template argument 5631 // deduction as a candidate. 5632 assert(Specialization && "Missing member function template specialization?"); 5633 assert(isa<CXXMethodDecl>(Specialization) && 5634 "Specialization is not a member function?"); 5635 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5636 ActingContext, ObjectType, ObjectClassification, Args, 5637 CandidateSet, SuppressUserConversions); 5638} 5639 5640/// \brief Add a C++ function template specialization as a candidate 5641/// in the candidate set, using template argument deduction to produce 5642/// an appropriate function template specialization. 5643void 5644Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5645 DeclAccessPair FoundDecl, 5646 TemplateArgumentListInfo *ExplicitTemplateArgs, 5647 ArrayRef<Expr *> Args, 5648 OverloadCandidateSet& CandidateSet, 5649 bool SuppressUserConversions) { 5650 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5651 return; 5652 5653 // C++ [over.match.funcs]p7: 5654 // In each case where a candidate is a function template, candidate 5655 // function template specializations are generated using template argument 5656 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5657 // candidate functions in the usual way.113) A given name can refer to one 5658 // or more function templates and also to a set of overloaded non-template 5659 // functions. In such a case, the candidate functions generated from each 5660 // function template are combined with the set of non-template candidate 5661 // functions. 5662 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5663 FunctionDecl *Specialization = 0; 5664 if (TemplateDeductionResult Result 5665 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5666 Specialization, Info)) { 5667 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5668 Candidate.FoundDecl = FoundDecl; 5669 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5670 Candidate.Viable = false; 5671 Candidate.FailureKind = ovl_fail_bad_deduction; 5672 Candidate.IsSurrogate = false; 5673 Candidate.IgnoreObjectArgument = false; 5674 Candidate.ExplicitCallArguments = Args.size(); 5675 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5676 Info); 5677 return; 5678 } 5679 5680 // Add the function template specialization produced by template argument 5681 // deduction as a candidate. 5682 assert(Specialization && "Missing function template specialization?"); 5683 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5684 SuppressUserConversions); 5685} 5686 5687/// AddConversionCandidate - Add a C++ conversion function as a 5688/// candidate in the candidate set (C++ [over.match.conv], 5689/// C++ [over.match.copy]). From is the expression we're converting from, 5690/// and ToType is the type that we're eventually trying to convert to 5691/// (which may or may not be the same type as the type that the 5692/// conversion function produces). 5693void 5694Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5695 DeclAccessPair FoundDecl, 5696 CXXRecordDecl *ActingContext, 5697 Expr *From, QualType ToType, 5698 OverloadCandidateSet& CandidateSet) { 5699 assert(!Conversion->getDescribedFunctionTemplate() && 5700 "Conversion function templates use AddTemplateConversionCandidate"); 5701 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5702 if (!CandidateSet.isNewCandidate(Conversion)) 5703 return; 5704 5705 // Overload resolution is always an unevaluated context. 5706 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5707 5708 // Add this candidate 5709 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5710 Candidate.FoundDecl = FoundDecl; 5711 Candidate.Function = Conversion; 5712 Candidate.IsSurrogate = false; 5713 Candidate.IgnoreObjectArgument = false; 5714 Candidate.FinalConversion.setAsIdentityConversion(); 5715 Candidate.FinalConversion.setFromType(ConvType); 5716 Candidate.FinalConversion.setAllToTypes(ToType); 5717 Candidate.Viable = true; 5718 Candidate.ExplicitCallArguments = 1; 5719 5720 // C++ [over.match.funcs]p4: 5721 // For conversion functions, the function is considered to be a member of 5722 // the class of the implicit implied object argument for the purpose of 5723 // defining the type of the implicit object parameter. 5724 // 5725 // Determine the implicit conversion sequence for the implicit 5726 // object parameter. 5727 QualType ImplicitParamType = From->getType(); 5728 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5729 ImplicitParamType = FromPtrType->getPointeeType(); 5730 CXXRecordDecl *ConversionContext 5731 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5732 5733 Candidate.Conversions[0] 5734 = TryObjectArgumentInitialization(*this, From->getType(), 5735 From->Classify(Context), 5736 Conversion, ConversionContext); 5737 5738 if (Candidate.Conversions[0].isBad()) { 5739 Candidate.Viable = false; 5740 Candidate.FailureKind = ovl_fail_bad_conversion; 5741 return; 5742 } 5743 5744 // We won't go through a user-define type conversion function to convert a 5745 // derived to base as such conversions are given Conversion Rank. They only 5746 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5747 QualType FromCanon 5748 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5749 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5750 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5751 Candidate.Viable = false; 5752 Candidate.FailureKind = ovl_fail_trivial_conversion; 5753 return; 5754 } 5755 5756 // To determine what the conversion from the result of calling the 5757 // conversion function to the type we're eventually trying to 5758 // convert to (ToType), we need to synthesize a call to the 5759 // conversion function and attempt copy initialization from it. This 5760 // makes sure that we get the right semantics with respect to 5761 // lvalues/rvalues and the type. Fortunately, we can allocate this 5762 // call on the stack and we don't need its arguments to be 5763 // well-formed. 5764 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5765 VK_LValue, From->getLocStart()); 5766 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5767 Context.getPointerType(Conversion->getType()), 5768 CK_FunctionToPointerDecay, 5769 &ConversionRef, VK_RValue); 5770 5771 QualType ConversionType = Conversion->getConversionType(); 5772 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5773 Candidate.Viable = false; 5774 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5775 return; 5776 } 5777 5778 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5779 5780 // Note that it is safe to allocate CallExpr on the stack here because 5781 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5782 // allocator). 5783 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5784 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5785 From->getLocStart()); 5786 ImplicitConversionSequence ICS = 5787 TryCopyInitialization(*this, &Call, ToType, 5788 /*SuppressUserConversions=*/true, 5789 /*InOverloadResolution=*/false, 5790 /*AllowObjCWritebackConversion=*/false); 5791 5792 switch (ICS.getKind()) { 5793 case ImplicitConversionSequence::StandardConversion: 5794 Candidate.FinalConversion = ICS.Standard; 5795 5796 // C++ [over.ics.user]p3: 5797 // If the user-defined conversion is specified by a specialization of a 5798 // conversion function template, the second standard conversion sequence 5799 // shall have exact match rank. 5800 if (Conversion->getPrimaryTemplate() && 5801 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5802 Candidate.Viable = false; 5803 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5804 } 5805 5806 // C++0x [dcl.init.ref]p5: 5807 // In the second case, if the reference is an rvalue reference and 5808 // the second standard conversion sequence of the user-defined 5809 // conversion sequence includes an lvalue-to-rvalue conversion, the 5810 // program is ill-formed. 5811 if (ToType->isRValueReferenceType() && 5812 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5813 Candidate.Viable = false; 5814 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5815 } 5816 break; 5817 5818 case ImplicitConversionSequence::BadConversion: 5819 Candidate.Viable = false; 5820 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5821 break; 5822 5823 default: 5824 llvm_unreachable( 5825 "Can only end up with a standard conversion sequence or failure"); 5826 } 5827} 5828 5829/// \brief Adds a conversion function template specialization 5830/// candidate to the overload set, using template argument deduction 5831/// to deduce the template arguments of the conversion function 5832/// template from the type that we are converting to (C++ 5833/// [temp.deduct.conv]). 5834void 5835Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5836 DeclAccessPair FoundDecl, 5837 CXXRecordDecl *ActingDC, 5838 Expr *From, QualType ToType, 5839 OverloadCandidateSet &CandidateSet) { 5840 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5841 "Only conversion function templates permitted here"); 5842 5843 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5844 return; 5845 5846 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5847 CXXConversionDecl *Specialization = 0; 5848 if (TemplateDeductionResult Result 5849 = DeduceTemplateArguments(FunctionTemplate, ToType, 5850 Specialization, Info)) { 5851 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5852 Candidate.FoundDecl = FoundDecl; 5853 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5854 Candidate.Viable = false; 5855 Candidate.FailureKind = ovl_fail_bad_deduction; 5856 Candidate.IsSurrogate = false; 5857 Candidate.IgnoreObjectArgument = false; 5858 Candidate.ExplicitCallArguments = 1; 5859 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5860 Info); 5861 return; 5862 } 5863 5864 // Add the conversion function template specialization produced by 5865 // template argument deduction as a candidate. 5866 assert(Specialization && "Missing function template specialization?"); 5867 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5868 CandidateSet); 5869} 5870 5871/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5872/// converts the given @c Object to a function pointer via the 5873/// conversion function @c Conversion, and then attempts to call it 5874/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5875/// the type of function that we'll eventually be calling. 5876void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5877 DeclAccessPair FoundDecl, 5878 CXXRecordDecl *ActingContext, 5879 const FunctionProtoType *Proto, 5880 Expr *Object, 5881 ArrayRef<Expr *> Args, 5882 OverloadCandidateSet& CandidateSet) { 5883 if (!CandidateSet.isNewCandidate(Conversion)) 5884 return; 5885 5886 // Overload resolution is always an unevaluated context. 5887 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5888 5889 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5890 Candidate.FoundDecl = FoundDecl; 5891 Candidate.Function = 0; 5892 Candidate.Surrogate = Conversion; 5893 Candidate.Viable = true; 5894 Candidate.IsSurrogate = true; 5895 Candidate.IgnoreObjectArgument = false; 5896 Candidate.ExplicitCallArguments = Args.size(); 5897 5898 // Determine the implicit conversion sequence for the implicit 5899 // object parameter. 5900 ImplicitConversionSequence ObjectInit 5901 = TryObjectArgumentInitialization(*this, Object->getType(), 5902 Object->Classify(Context), 5903 Conversion, ActingContext); 5904 if (ObjectInit.isBad()) { 5905 Candidate.Viable = false; 5906 Candidate.FailureKind = ovl_fail_bad_conversion; 5907 Candidate.Conversions[0] = ObjectInit; 5908 return; 5909 } 5910 5911 // The first conversion is actually a user-defined conversion whose 5912 // first conversion is ObjectInit's standard conversion (which is 5913 // effectively a reference binding). Record it as such. 5914 Candidate.Conversions[0].setUserDefined(); 5915 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5916 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5917 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5918 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5919 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5920 Candidate.Conversions[0].UserDefined.After 5921 = Candidate.Conversions[0].UserDefined.Before; 5922 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5923 5924 // Find the 5925 unsigned NumArgsInProto = Proto->getNumArgs(); 5926 5927 // (C++ 13.3.2p2): A candidate function having fewer than m 5928 // parameters is viable only if it has an ellipsis in its parameter 5929 // list (8.3.5). 5930 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5931 Candidate.Viable = false; 5932 Candidate.FailureKind = ovl_fail_too_many_arguments; 5933 return; 5934 } 5935 5936 // Function types don't have any default arguments, so just check if 5937 // we have enough arguments. 5938 if (Args.size() < NumArgsInProto) { 5939 // Not enough arguments. 5940 Candidate.Viable = false; 5941 Candidate.FailureKind = ovl_fail_too_few_arguments; 5942 return; 5943 } 5944 5945 // Determine the implicit conversion sequences for each of the 5946 // arguments. 5947 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5948 if (ArgIdx < NumArgsInProto) { 5949 // (C++ 13.3.2p3): for F to be a viable function, there shall 5950 // exist for each argument an implicit conversion sequence 5951 // (13.3.3.1) that converts that argument to the corresponding 5952 // parameter of F. 5953 QualType ParamType = Proto->getArgType(ArgIdx); 5954 Candidate.Conversions[ArgIdx + 1] 5955 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5956 /*SuppressUserConversions=*/false, 5957 /*InOverloadResolution=*/false, 5958 /*AllowObjCWritebackConversion=*/ 5959 getLangOpts().ObjCAutoRefCount); 5960 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5961 Candidate.Viable = false; 5962 Candidate.FailureKind = ovl_fail_bad_conversion; 5963 break; 5964 } 5965 } else { 5966 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5967 // argument for which there is no corresponding parameter is 5968 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5969 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5970 } 5971 } 5972} 5973 5974/// \brief Add overload candidates for overloaded operators that are 5975/// member functions. 5976/// 5977/// Add the overloaded operator candidates that are member functions 5978/// for the operator Op that was used in an operator expression such 5979/// as "x Op y". , Args/NumArgs provides the operator arguments, and 5980/// CandidateSet will store the added overload candidates. (C++ 5981/// [over.match.oper]). 5982void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5983 SourceLocation OpLoc, 5984 Expr **Args, unsigned NumArgs, 5985 OverloadCandidateSet& CandidateSet, 5986 SourceRange OpRange) { 5987 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5988 5989 // C++ [over.match.oper]p3: 5990 // For a unary operator @ with an operand of a type whose 5991 // cv-unqualified version is T1, and for a binary operator @ with 5992 // a left operand of a type whose cv-unqualified version is T1 and 5993 // a right operand of a type whose cv-unqualified version is T2, 5994 // three sets of candidate functions, designated member 5995 // candidates, non-member candidates and built-in candidates, are 5996 // constructed as follows: 5997 QualType T1 = Args[0]->getType(); 5998 5999 // -- If T1 is a class type, the set of member candidates is the 6000 // result of the qualified lookup of T1::operator@ 6001 // (13.3.1.1.1); otherwise, the set of member candidates is 6002 // empty. 6003 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6004 // Complete the type if it can be completed. Otherwise, we're done. 6005 if (RequireCompleteType(OpLoc, T1, 0)) 6006 return; 6007 6008 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6009 LookupQualifiedName(Operators, T1Rec->getDecl()); 6010 Operators.suppressDiagnostics(); 6011 6012 for (LookupResult::iterator Oper = Operators.begin(), 6013 OperEnd = Operators.end(); 6014 Oper != OperEnd; 6015 ++Oper) 6016 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6017 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 6018 CandidateSet, 6019 /* SuppressUserConversions = */ false); 6020 } 6021} 6022 6023/// AddBuiltinCandidate - Add a candidate for a built-in 6024/// operator. ResultTy and ParamTys are the result and parameter types 6025/// of the built-in candidate, respectively. Args and NumArgs are the 6026/// arguments being passed to the candidate. IsAssignmentOperator 6027/// should be true when this built-in candidate is an assignment 6028/// operator. NumContextualBoolArguments is the number of arguments 6029/// (at the beginning of the argument list) that will be contextually 6030/// converted to bool. 6031void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6032 Expr **Args, unsigned NumArgs, 6033 OverloadCandidateSet& CandidateSet, 6034 bool IsAssignmentOperator, 6035 unsigned NumContextualBoolArguments) { 6036 // Overload resolution is always an unevaluated context. 6037 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6038 6039 // Add this candidate 6040 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 6041 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6042 Candidate.Function = 0; 6043 Candidate.IsSurrogate = false; 6044 Candidate.IgnoreObjectArgument = false; 6045 Candidate.BuiltinTypes.ResultTy = ResultTy; 6046 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6047 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6048 6049 // Determine the implicit conversion sequences for each of the 6050 // arguments. 6051 Candidate.Viable = true; 6052 Candidate.ExplicitCallArguments = NumArgs; 6053 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6054 // C++ [over.match.oper]p4: 6055 // For the built-in assignment operators, conversions of the 6056 // left operand are restricted as follows: 6057 // -- no temporaries are introduced to hold the left operand, and 6058 // -- no user-defined conversions are applied to the left 6059 // operand to achieve a type match with the left-most 6060 // parameter of a built-in candidate. 6061 // 6062 // We block these conversions by turning off user-defined 6063 // conversions, since that is the only way that initialization of 6064 // a reference to a non-class type can occur from something that 6065 // is not of the same type. 6066 if (ArgIdx < NumContextualBoolArguments) { 6067 assert(ParamTys[ArgIdx] == Context.BoolTy && 6068 "Contextual conversion to bool requires bool type"); 6069 Candidate.Conversions[ArgIdx] 6070 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6071 } else { 6072 Candidate.Conversions[ArgIdx] 6073 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6074 ArgIdx == 0 && IsAssignmentOperator, 6075 /*InOverloadResolution=*/false, 6076 /*AllowObjCWritebackConversion=*/ 6077 getLangOpts().ObjCAutoRefCount); 6078 } 6079 if (Candidate.Conversions[ArgIdx].isBad()) { 6080 Candidate.Viable = false; 6081 Candidate.FailureKind = ovl_fail_bad_conversion; 6082 break; 6083 } 6084 } 6085} 6086 6087/// BuiltinCandidateTypeSet - A set of types that will be used for the 6088/// candidate operator functions for built-in operators (C++ 6089/// [over.built]). The types are separated into pointer types and 6090/// enumeration types. 6091class BuiltinCandidateTypeSet { 6092 /// TypeSet - A set of types. 6093 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6094 6095 /// PointerTypes - The set of pointer types that will be used in the 6096 /// built-in candidates. 6097 TypeSet PointerTypes; 6098 6099 /// MemberPointerTypes - The set of member pointer types that will be 6100 /// used in the built-in candidates. 6101 TypeSet MemberPointerTypes; 6102 6103 /// EnumerationTypes - The set of enumeration types that will be 6104 /// used in the built-in candidates. 6105 TypeSet EnumerationTypes; 6106 6107 /// \brief The set of vector types that will be used in the built-in 6108 /// candidates. 6109 TypeSet VectorTypes; 6110 6111 /// \brief A flag indicating non-record types are viable candidates 6112 bool HasNonRecordTypes; 6113 6114 /// \brief A flag indicating whether either arithmetic or enumeration types 6115 /// were present in the candidate set. 6116 bool HasArithmeticOrEnumeralTypes; 6117 6118 /// \brief A flag indicating whether the nullptr type was present in the 6119 /// candidate set. 6120 bool HasNullPtrType; 6121 6122 /// Sema - The semantic analysis instance where we are building the 6123 /// candidate type set. 6124 Sema &SemaRef; 6125 6126 /// Context - The AST context in which we will build the type sets. 6127 ASTContext &Context; 6128 6129 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6130 const Qualifiers &VisibleQuals); 6131 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6132 6133public: 6134 /// iterator - Iterates through the types that are part of the set. 6135 typedef TypeSet::iterator iterator; 6136 6137 BuiltinCandidateTypeSet(Sema &SemaRef) 6138 : HasNonRecordTypes(false), 6139 HasArithmeticOrEnumeralTypes(false), 6140 HasNullPtrType(false), 6141 SemaRef(SemaRef), 6142 Context(SemaRef.Context) { } 6143 6144 void AddTypesConvertedFrom(QualType Ty, 6145 SourceLocation Loc, 6146 bool AllowUserConversions, 6147 bool AllowExplicitConversions, 6148 const Qualifiers &VisibleTypeConversionsQuals); 6149 6150 /// pointer_begin - First pointer type found; 6151 iterator pointer_begin() { return PointerTypes.begin(); } 6152 6153 /// pointer_end - Past the last pointer type found; 6154 iterator pointer_end() { return PointerTypes.end(); } 6155 6156 /// member_pointer_begin - First member pointer type found; 6157 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6158 6159 /// member_pointer_end - Past the last member pointer type found; 6160 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6161 6162 /// enumeration_begin - First enumeration type found; 6163 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6164 6165 /// enumeration_end - Past the last enumeration type found; 6166 iterator enumeration_end() { return EnumerationTypes.end(); } 6167 6168 iterator vector_begin() { return VectorTypes.begin(); } 6169 iterator vector_end() { return VectorTypes.end(); } 6170 6171 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6172 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6173 bool hasNullPtrType() const { return HasNullPtrType; } 6174}; 6175 6176/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6177/// the set of pointer types along with any more-qualified variants of 6178/// that type. For example, if @p Ty is "int const *", this routine 6179/// will add "int const *", "int const volatile *", "int const 6180/// restrict *", and "int const volatile restrict *" to the set of 6181/// pointer types. Returns true if the add of @p Ty itself succeeded, 6182/// false otherwise. 6183/// 6184/// FIXME: what to do about extended qualifiers? 6185bool 6186BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6187 const Qualifiers &VisibleQuals) { 6188 6189 // Insert this type. 6190 if (!PointerTypes.insert(Ty)) 6191 return false; 6192 6193 QualType PointeeTy; 6194 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6195 bool buildObjCPtr = false; 6196 if (!PointerTy) { 6197 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6198 PointeeTy = PTy->getPointeeType(); 6199 buildObjCPtr = true; 6200 } else { 6201 PointeeTy = PointerTy->getPointeeType(); 6202 } 6203 6204 // Don't add qualified variants of arrays. For one, they're not allowed 6205 // (the qualifier would sink to the element type), and for another, the 6206 // only overload situation where it matters is subscript or pointer +- int, 6207 // and those shouldn't have qualifier variants anyway. 6208 if (PointeeTy->isArrayType()) 6209 return true; 6210 6211 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6212 bool hasVolatile = VisibleQuals.hasVolatile(); 6213 bool hasRestrict = VisibleQuals.hasRestrict(); 6214 6215 // Iterate through all strict supersets of BaseCVR. 6216 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6217 if ((CVR | BaseCVR) != CVR) continue; 6218 // Skip over volatile if no volatile found anywhere in the types. 6219 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6220 6221 // Skip over restrict if no restrict found anywhere in the types, or if 6222 // the type cannot be restrict-qualified. 6223 if ((CVR & Qualifiers::Restrict) && 6224 (!hasRestrict || 6225 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6226 continue; 6227 6228 // Build qualified pointee type. 6229 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6230 6231 // Build qualified pointer type. 6232 QualType QPointerTy; 6233 if (!buildObjCPtr) 6234 QPointerTy = Context.getPointerType(QPointeeTy); 6235 else 6236 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6237 6238 // Insert qualified pointer type. 6239 PointerTypes.insert(QPointerTy); 6240 } 6241 6242 return true; 6243} 6244 6245/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6246/// to the set of pointer types along with any more-qualified variants of 6247/// that type. For example, if @p Ty is "int const *", this routine 6248/// will add "int const *", "int const volatile *", "int const 6249/// restrict *", and "int const volatile restrict *" to the set of 6250/// pointer types. Returns true if the add of @p Ty itself succeeded, 6251/// false otherwise. 6252/// 6253/// FIXME: what to do about extended qualifiers? 6254bool 6255BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6256 QualType Ty) { 6257 // Insert this type. 6258 if (!MemberPointerTypes.insert(Ty)) 6259 return false; 6260 6261 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6262 assert(PointerTy && "type was not a member pointer type!"); 6263 6264 QualType PointeeTy = PointerTy->getPointeeType(); 6265 // Don't add qualified variants of arrays. For one, they're not allowed 6266 // (the qualifier would sink to the element type), and for another, the 6267 // only overload situation where it matters is subscript or pointer +- int, 6268 // and those shouldn't have qualifier variants anyway. 6269 if (PointeeTy->isArrayType()) 6270 return true; 6271 const Type *ClassTy = PointerTy->getClass(); 6272 6273 // Iterate through all strict supersets of the pointee type's CVR 6274 // qualifiers. 6275 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6276 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6277 if ((CVR | BaseCVR) != CVR) continue; 6278 6279 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6280 MemberPointerTypes.insert( 6281 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6282 } 6283 6284 return true; 6285} 6286 6287/// AddTypesConvertedFrom - Add each of the types to which the type @p 6288/// Ty can be implicit converted to the given set of @p Types. We're 6289/// primarily interested in pointer types and enumeration types. We also 6290/// take member pointer types, for the conditional operator. 6291/// AllowUserConversions is true if we should look at the conversion 6292/// functions of a class type, and AllowExplicitConversions if we 6293/// should also include the explicit conversion functions of a class 6294/// type. 6295void 6296BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6297 SourceLocation Loc, 6298 bool AllowUserConversions, 6299 bool AllowExplicitConversions, 6300 const Qualifiers &VisibleQuals) { 6301 // Only deal with canonical types. 6302 Ty = Context.getCanonicalType(Ty); 6303 6304 // Look through reference types; they aren't part of the type of an 6305 // expression for the purposes of conversions. 6306 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6307 Ty = RefTy->getPointeeType(); 6308 6309 // If we're dealing with an array type, decay to the pointer. 6310 if (Ty->isArrayType()) 6311 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6312 6313 // Otherwise, we don't care about qualifiers on the type. 6314 Ty = Ty.getLocalUnqualifiedType(); 6315 6316 // Flag if we ever add a non-record type. 6317 const RecordType *TyRec = Ty->getAs<RecordType>(); 6318 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6319 6320 // Flag if we encounter an arithmetic type. 6321 HasArithmeticOrEnumeralTypes = 6322 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6323 6324 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6325 PointerTypes.insert(Ty); 6326 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6327 // Insert our type, and its more-qualified variants, into the set 6328 // of types. 6329 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6330 return; 6331 } else if (Ty->isMemberPointerType()) { 6332 // Member pointers are far easier, since the pointee can't be converted. 6333 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6334 return; 6335 } else if (Ty->isEnumeralType()) { 6336 HasArithmeticOrEnumeralTypes = true; 6337 EnumerationTypes.insert(Ty); 6338 } else if (Ty->isVectorType()) { 6339 // We treat vector types as arithmetic types in many contexts as an 6340 // extension. 6341 HasArithmeticOrEnumeralTypes = true; 6342 VectorTypes.insert(Ty); 6343 } else if (Ty->isNullPtrType()) { 6344 HasNullPtrType = true; 6345 } else if (AllowUserConversions && TyRec) { 6346 // No conversion functions in incomplete types. 6347 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6348 return; 6349 6350 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6351 std::pair<CXXRecordDecl::conversion_iterator, 6352 CXXRecordDecl::conversion_iterator> 6353 Conversions = ClassDecl->getVisibleConversionFunctions(); 6354 for (CXXRecordDecl::conversion_iterator 6355 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6356 NamedDecl *D = I.getDecl(); 6357 if (isa<UsingShadowDecl>(D)) 6358 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6359 6360 // Skip conversion function templates; they don't tell us anything 6361 // about which builtin types we can convert to. 6362 if (isa<FunctionTemplateDecl>(D)) 6363 continue; 6364 6365 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6366 if (AllowExplicitConversions || !Conv->isExplicit()) { 6367 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6368 VisibleQuals); 6369 } 6370 } 6371 } 6372} 6373 6374/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6375/// the volatile- and non-volatile-qualified assignment operators for the 6376/// given type to the candidate set. 6377static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6378 QualType T, 6379 Expr **Args, 6380 unsigned NumArgs, 6381 OverloadCandidateSet &CandidateSet) { 6382 QualType ParamTypes[2]; 6383 6384 // T& operator=(T&, T) 6385 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6386 ParamTypes[1] = T; 6387 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6388 /*IsAssignmentOperator=*/true); 6389 6390 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6391 // volatile T& operator=(volatile T&, T) 6392 ParamTypes[0] 6393 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6394 ParamTypes[1] = T; 6395 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6396 /*IsAssignmentOperator=*/true); 6397 } 6398} 6399 6400/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6401/// if any, found in visible type conversion functions found in ArgExpr's type. 6402static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6403 Qualifiers VRQuals; 6404 const RecordType *TyRec; 6405 if (const MemberPointerType *RHSMPType = 6406 ArgExpr->getType()->getAs<MemberPointerType>()) 6407 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6408 else 6409 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6410 if (!TyRec) { 6411 // Just to be safe, assume the worst case. 6412 VRQuals.addVolatile(); 6413 VRQuals.addRestrict(); 6414 return VRQuals; 6415 } 6416 6417 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6418 if (!ClassDecl->hasDefinition()) 6419 return VRQuals; 6420 6421 std::pair<CXXRecordDecl::conversion_iterator, 6422 CXXRecordDecl::conversion_iterator> 6423 Conversions = ClassDecl->getVisibleConversionFunctions(); 6424 6425 for (CXXRecordDecl::conversion_iterator 6426 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6427 NamedDecl *D = I.getDecl(); 6428 if (isa<UsingShadowDecl>(D)) 6429 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6430 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6431 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6432 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6433 CanTy = ResTypeRef->getPointeeType(); 6434 // Need to go down the pointer/mempointer chain and add qualifiers 6435 // as see them. 6436 bool done = false; 6437 while (!done) { 6438 if (CanTy.isRestrictQualified()) 6439 VRQuals.addRestrict(); 6440 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6441 CanTy = ResTypePtr->getPointeeType(); 6442 else if (const MemberPointerType *ResTypeMPtr = 6443 CanTy->getAs<MemberPointerType>()) 6444 CanTy = ResTypeMPtr->getPointeeType(); 6445 else 6446 done = true; 6447 if (CanTy.isVolatileQualified()) 6448 VRQuals.addVolatile(); 6449 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6450 return VRQuals; 6451 } 6452 } 6453 } 6454 return VRQuals; 6455} 6456 6457namespace { 6458 6459/// \brief Helper class to manage the addition of builtin operator overload 6460/// candidates. It provides shared state and utility methods used throughout 6461/// the process, as well as a helper method to add each group of builtin 6462/// operator overloads from the standard to a candidate set. 6463class BuiltinOperatorOverloadBuilder { 6464 // Common instance state available to all overload candidate addition methods. 6465 Sema &S; 6466 Expr **Args; 6467 unsigned NumArgs; 6468 Qualifiers VisibleTypeConversionsQuals; 6469 bool HasArithmeticOrEnumeralCandidateType; 6470 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6471 OverloadCandidateSet &CandidateSet; 6472 6473 // Define some constants used to index and iterate over the arithemetic types 6474 // provided via the getArithmeticType() method below. 6475 // The "promoted arithmetic types" are the arithmetic 6476 // types are that preserved by promotion (C++ [over.built]p2). 6477 static const unsigned FirstIntegralType = 3; 6478 static const unsigned LastIntegralType = 20; 6479 static const unsigned FirstPromotedIntegralType = 3, 6480 LastPromotedIntegralType = 11; 6481 static const unsigned FirstPromotedArithmeticType = 0, 6482 LastPromotedArithmeticType = 11; 6483 static const unsigned NumArithmeticTypes = 20; 6484 6485 /// \brief Get the canonical type for a given arithmetic type index. 6486 CanQualType getArithmeticType(unsigned index) { 6487 assert(index < NumArithmeticTypes); 6488 static CanQualType ASTContext::* const 6489 ArithmeticTypes[NumArithmeticTypes] = { 6490 // Start of promoted types. 6491 &ASTContext::FloatTy, 6492 &ASTContext::DoubleTy, 6493 &ASTContext::LongDoubleTy, 6494 6495 // Start of integral types. 6496 &ASTContext::IntTy, 6497 &ASTContext::LongTy, 6498 &ASTContext::LongLongTy, 6499 &ASTContext::Int128Ty, 6500 &ASTContext::UnsignedIntTy, 6501 &ASTContext::UnsignedLongTy, 6502 &ASTContext::UnsignedLongLongTy, 6503 &ASTContext::UnsignedInt128Ty, 6504 // End of promoted types. 6505 6506 &ASTContext::BoolTy, 6507 &ASTContext::CharTy, 6508 &ASTContext::WCharTy, 6509 &ASTContext::Char16Ty, 6510 &ASTContext::Char32Ty, 6511 &ASTContext::SignedCharTy, 6512 &ASTContext::ShortTy, 6513 &ASTContext::UnsignedCharTy, 6514 &ASTContext::UnsignedShortTy, 6515 // End of integral types. 6516 // FIXME: What about complex? What about half? 6517 }; 6518 return S.Context.*ArithmeticTypes[index]; 6519 } 6520 6521 /// \brief Gets the canonical type resulting from the usual arithemetic 6522 /// converions for the given arithmetic types. 6523 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6524 // Accelerator table for performing the usual arithmetic conversions. 6525 // The rules are basically: 6526 // - if either is floating-point, use the wider floating-point 6527 // - if same signedness, use the higher rank 6528 // - if same size, use unsigned of the higher rank 6529 // - use the larger type 6530 // These rules, together with the axiom that higher ranks are 6531 // never smaller, are sufficient to precompute all of these results 6532 // *except* when dealing with signed types of higher rank. 6533 // (we could precompute SLL x UI for all known platforms, but it's 6534 // better not to make any assumptions). 6535 // We assume that int128 has a higher rank than long long on all platforms. 6536 enum PromotedType { 6537 Dep=-1, 6538 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6539 }; 6540 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6541 [LastPromotedArithmeticType] = { 6542/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6543/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6544/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6545/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6546/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6547/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6548/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6549/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6550/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6551/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6552/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6553 }; 6554 6555 assert(L < LastPromotedArithmeticType); 6556 assert(R < LastPromotedArithmeticType); 6557 int Idx = ConversionsTable[L][R]; 6558 6559 // Fast path: the table gives us a concrete answer. 6560 if (Idx != Dep) return getArithmeticType(Idx); 6561 6562 // Slow path: we need to compare widths. 6563 // An invariant is that the signed type has higher rank. 6564 CanQualType LT = getArithmeticType(L), 6565 RT = getArithmeticType(R); 6566 unsigned LW = S.Context.getIntWidth(LT), 6567 RW = S.Context.getIntWidth(RT); 6568 6569 // If they're different widths, use the signed type. 6570 if (LW > RW) return LT; 6571 else if (LW < RW) return RT; 6572 6573 // Otherwise, use the unsigned type of the signed type's rank. 6574 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6575 assert(L == SLL || R == SLL); 6576 return S.Context.UnsignedLongLongTy; 6577 } 6578 6579 /// \brief Helper method to factor out the common pattern of adding overloads 6580 /// for '++' and '--' builtin operators. 6581 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6582 bool HasVolatile, 6583 bool HasRestrict) { 6584 QualType ParamTypes[2] = { 6585 S.Context.getLValueReferenceType(CandidateTy), 6586 S.Context.IntTy 6587 }; 6588 6589 // Non-volatile version. 6590 if (NumArgs == 1) 6591 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6592 else 6593 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6594 6595 // Use a heuristic to reduce number of builtin candidates in the set: 6596 // add volatile version only if there are conversions to a volatile type. 6597 if (HasVolatile) { 6598 ParamTypes[0] = 6599 S.Context.getLValueReferenceType( 6600 S.Context.getVolatileType(CandidateTy)); 6601 if (NumArgs == 1) 6602 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6603 else 6604 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6605 } 6606 6607 // Add restrict version only if there are conversions to a restrict type 6608 // and our candidate type is a non-restrict-qualified pointer. 6609 if (HasRestrict && CandidateTy->isAnyPointerType() && 6610 !CandidateTy.isRestrictQualified()) { 6611 ParamTypes[0] 6612 = S.Context.getLValueReferenceType( 6613 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6614 if (NumArgs == 1) 6615 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6616 else 6617 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6618 6619 if (HasVolatile) { 6620 ParamTypes[0] 6621 = S.Context.getLValueReferenceType( 6622 S.Context.getCVRQualifiedType(CandidateTy, 6623 (Qualifiers::Volatile | 6624 Qualifiers::Restrict))); 6625 if (NumArgs == 1) 6626 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6627 CandidateSet); 6628 else 6629 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6630 } 6631 } 6632 6633 } 6634 6635public: 6636 BuiltinOperatorOverloadBuilder( 6637 Sema &S, Expr **Args, unsigned NumArgs, 6638 Qualifiers VisibleTypeConversionsQuals, 6639 bool HasArithmeticOrEnumeralCandidateType, 6640 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6641 OverloadCandidateSet &CandidateSet) 6642 : S(S), Args(Args), NumArgs(NumArgs), 6643 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6644 HasArithmeticOrEnumeralCandidateType( 6645 HasArithmeticOrEnumeralCandidateType), 6646 CandidateTypes(CandidateTypes), 6647 CandidateSet(CandidateSet) { 6648 // Validate some of our static helper constants in debug builds. 6649 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6650 "Invalid first promoted integral type"); 6651 assert(getArithmeticType(LastPromotedIntegralType - 1) 6652 == S.Context.UnsignedInt128Ty && 6653 "Invalid last promoted integral type"); 6654 assert(getArithmeticType(FirstPromotedArithmeticType) 6655 == S.Context.FloatTy && 6656 "Invalid first promoted arithmetic type"); 6657 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6658 == S.Context.UnsignedInt128Ty && 6659 "Invalid last promoted arithmetic type"); 6660 } 6661 6662 // C++ [over.built]p3: 6663 // 6664 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6665 // is either volatile or empty, there exist candidate operator 6666 // functions of the form 6667 // 6668 // VQ T& operator++(VQ T&); 6669 // T operator++(VQ T&, int); 6670 // 6671 // C++ [over.built]p4: 6672 // 6673 // For every pair (T, VQ), where T is an arithmetic type other 6674 // than bool, and VQ is either volatile or empty, there exist 6675 // candidate operator functions of the form 6676 // 6677 // VQ T& operator--(VQ T&); 6678 // T operator--(VQ T&, int); 6679 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6680 if (!HasArithmeticOrEnumeralCandidateType) 6681 return; 6682 6683 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6684 Arith < NumArithmeticTypes; ++Arith) { 6685 addPlusPlusMinusMinusStyleOverloads( 6686 getArithmeticType(Arith), 6687 VisibleTypeConversionsQuals.hasVolatile(), 6688 VisibleTypeConversionsQuals.hasRestrict()); 6689 } 6690 } 6691 6692 // C++ [over.built]p5: 6693 // 6694 // For every pair (T, VQ), where T is a cv-qualified or 6695 // cv-unqualified object type, and VQ is either volatile or 6696 // empty, there exist candidate operator functions of the form 6697 // 6698 // T*VQ& operator++(T*VQ&); 6699 // T*VQ& operator--(T*VQ&); 6700 // T* operator++(T*VQ&, int); 6701 // T* operator--(T*VQ&, int); 6702 void addPlusPlusMinusMinusPointerOverloads() { 6703 for (BuiltinCandidateTypeSet::iterator 6704 Ptr = CandidateTypes[0].pointer_begin(), 6705 PtrEnd = CandidateTypes[0].pointer_end(); 6706 Ptr != PtrEnd; ++Ptr) { 6707 // Skip pointer types that aren't pointers to object types. 6708 if (!(*Ptr)->getPointeeType()->isObjectType()) 6709 continue; 6710 6711 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6712 (!(*Ptr).isVolatileQualified() && 6713 VisibleTypeConversionsQuals.hasVolatile()), 6714 (!(*Ptr).isRestrictQualified() && 6715 VisibleTypeConversionsQuals.hasRestrict())); 6716 } 6717 } 6718 6719 // C++ [over.built]p6: 6720 // For every cv-qualified or cv-unqualified object type T, there 6721 // exist candidate operator functions of the form 6722 // 6723 // T& operator*(T*); 6724 // 6725 // C++ [over.built]p7: 6726 // For every function type T that does not have cv-qualifiers or a 6727 // ref-qualifier, there exist candidate operator functions of the form 6728 // T& operator*(T*); 6729 void addUnaryStarPointerOverloads() { 6730 for (BuiltinCandidateTypeSet::iterator 6731 Ptr = CandidateTypes[0].pointer_begin(), 6732 PtrEnd = CandidateTypes[0].pointer_end(); 6733 Ptr != PtrEnd; ++Ptr) { 6734 QualType ParamTy = *Ptr; 6735 QualType PointeeTy = ParamTy->getPointeeType(); 6736 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6737 continue; 6738 6739 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6740 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6741 continue; 6742 6743 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6744 &ParamTy, Args, 1, CandidateSet); 6745 } 6746 } 6747 6748 // C++ [over.built]p9: 6749 // For every promoted arithmetic type T, there exist candidate 6750 // operator functions of the form 6751 // 6752 // T operator+(T); 6753 // T operator-(T); 6754 void addUnaryPlusOrMinusArithmeticOverloads() { 6755 if (!HasArithmeticOrEnumeralCandidateType) 6756 return; 6757 6758 for (unsigned Arith = FirstPromotedArithmeticType; 6759 Arith < LastPromotedArithmeticType; ++Arith) { 6760 QualType ArithTy = getArithmeticType(Arith); 6761 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6762 } 6763 6764 // Extension: We also add these operators for vector types. 6765 for (BuiltinCandidateTypeSet::iterator 6766 Vec = CandidateTypes[0].vector_begin(), 6767 VecEnd = CandidateTypes[0].vector_end(); 6768 Vec != VecEnd; ++Vec) { 6769 QualType VecTy = *Vec; 6770 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6771 } 6772 } 6773 6774 // C++ [over.built]p8: 6775 // For every type T, there exist candidate operator functions of 6776 // the form 6777 // 6778 // T* operator+(T*); 6779 void addUnaryPlusPointerOverloads() { 6780 for (BuiltinCandidateTypeSet::iterator 6781 Ptr = CandidateTypes[0].pointer_begin(), 6782 PtrEnd = CandidateTypes[0].pointer_end(); 6783 Ptr != PtrEnd; ++Ptr) { 6784 QualType ParamTy = *Ptr; 6785 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6786 } 6787 } 6788 6789 // C++ [over.built]p10: 6790 // For every promoted integral type T, there exist candidate 6791 // operator functions of the form 6792 // 6793 // T operator~(T); 6794 void addUnaryTildePromotedIntegralOverloads() { 6795 if (!HasArithmeticOrEnumeralCandidateType) 6796 return; 6797 6798 for (unsigned Int = FirstPromotedIntegralType; 6799 Int < LastPromotedIntegralType; ++Int) { 6800 QualType IntTy = getArithmeticType(Int); 6801 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6802 } 6803 6804 // Extension: We also add this operator for vector types. 6805 for (BuiltinCandidateTypeSet::iterator 6806 Vec = CandidateTypes[0].vector_begin(), 6807 VecEnd = CandidateTypes[0].vector_end(); 6808 Vec != VecEnd; ++Vec) { 6809 QualType VecTy = *Vec; 6810 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6811 } 6812 } 6813 6814 // C++ [over.match.oper]p16: 6815 // For every pointer to member type T, there exist candidate operator 6816 // functions of the form 6817 // 6818 // bool operator==(T,T); 6819 // bool operator!=(T,T); 6820 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6821 /// Set of (canonical) types that we've already handled. 6822 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6823 6824 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6825 for (BuiltinCandidateTypeSet::iterator 6826 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6827 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6828 MemPtr != MemPtrEnd; 6829 ++MemPtr) { 6830 // Don't add the same builtin candidate twice. 6831 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6832 continue; 6833 6834 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6835 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6836 CandidateSet); 6837 } 6838 } 6839 } 6840 6841 // C++ [over.built]p15: 6842 // 6843 // For every T, where T is an enumeration type, a pointer type, or 6844 // std::nullptr_t, there exist candidate operator functions of the form 6845 // 6846 // bool operator<(T, T); 6847 // bool operator>(T, T); 6848 // bool operator<=(T, T); 6849 // bool operator>=(T, T); 6850 // bool operator==(T, T); 6851 // bool operator!=(T, T); 6852 void addRelationalPointerOrEnumeralOverloads() { 6853 // C++ [over.match.oper]p3: 6854 // [...]the built-in candidates include all of the candidate operator 6855 // functions defined in 13.6 that, compared to the given operator, [...] 6856 // do not have the same parameter-type-list as any non-template non-member 6857 // candidate. 6858 // 6859 // Note that in practice, this only affects enumeration types because there 6860 // aren't any built-in candidates of record type, and a user-defined operator 6861 // must have an operand of record or enumeration type. Also, the only other 6862 // overloaded operator with enumeration arguments, operator=, 6863 // cannot be overloaded for enumeration types, so this is the only place 6864 // where we must suppress candidates like this. 6865 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6866 UserDefinedBinaryOperators; 6867 6868 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6869 if (CandidateTypes[ArgIdx].enumeration_begin() != 6870 CandidateTypes[ArgIdx].enumeration_end()) { 6871 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6872 CEnd = CandidateSet.end(); 6873 C != CEnd; ++C) { 6874 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6875 continue; 6876 6877 if (C->Function->isFunctionTemplateSpecialization()) 6878 continue; 6879 6880 QualType FirstParamType = 6881 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6882 QualType SecondParamType = 6883 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6884 6885 // Skip if either parameter isn't of enumeral type. 6886 if (!FirstParamType->isEnumeralType() || 6887 !SecondParamType->isEnumeralType()) 6888 continue; 6889 6890 // Add this operator to the set of known user-defined operators. 6891 UserDefinedBinaryOperators.insert( 6892 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6893 S.Context.getCanonicalType(SecondParamType))); 6894 } 6895 } 6896 } 6897 6898 /// Set of (canonical) types that we've already handled. 6899 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6900 6901 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6902 for (BuiltinCandidateTypeSet::iterator 6903 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6904 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6905 Ptr != PtrEnd; ++Ptr) { 6906 // Don't add the same builtin candidate twice. 6907 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6908 continue; 6909 6910 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6911 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6912 CandidateSet); 6913 } 6914 for (BuiltinCandidateTypeSet::iterator 6915 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6916 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6917 Enum != EnumEnd; ++Enum) { 6918 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6919 6920 // Don't add the same builtin candidate twice, or if a user defined 6921 // candidate exists. 6922 if (!AddedTypes.insert(CanonType) || 6923 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6924 CanonType))) 6925 continue; 6926 6927 QualType ParamTypes[2] = { *Enum, *Enum }; 6928 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6929 CandidateSet); 6930 } 6931 6932 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6933 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6934 if (AddedTypes.insert(NullPtrTy) && 6935 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6936 NullPtrTy))) { 6937 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6938 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6939 CandidateSet); 6940 } 6941 } 6942 } 6943 } 6944 6945 // C++ [over.built]p13: 6946 // 6947 // For every cv-qualified or cv-unqualified object type T 6948 // there exist candidate operator functions of the form 6949 // 6950 // T* operator+(T*, ptrdiff_t); 6951 // T& operator[](T*, ptrdiff_t); [BELOW] 6952 // T* operator-(T*, ptrdiff_t); 6953 // T* operator+(ptrdiff_t, T*); 6954 // T& operator[](ptrdiff_t, T*); [BELOW] 6955 // 6956 // C++ [over.built]p14: 6957 // 6958 // For every T, where T is a pointer to object type, there 6959 // exist candidate operator functions of the form 6960 // 6961 // ptrdiff_t operator-(T, T); 6962 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6963 /// Set of (canonical) types that we've already handled. 6964 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6965 6966 for (int Arg = 0; Arg < 2; ++Arg) { 6967 QualType AsymetricParamTypes[2] = { 6968 S.Context.getPointerDiffType(), 6969 S.Context.getPointerDiffType(), 6970 }; 6971 for (BuiltinCandidateTypeSet::iterator 6972 Ptr = CandidateTypes[Arg].pointer_begin(), 6973 PtrEnd = CandidateTypes[Arg].pointer_end(); 6974 Ptr != PtrEnd; ++Ptr) { 6975 QualType PointeeTy = (*Ptr)->getPointeeType(); 6976 if (!PointeeTy->isObjectType()) 6977 continue; 6978 6979 AsymetricParamTypes[Arg] = *Ptr; 6980 if (Arg == 0 || Op == OO_Plus) { 6981 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6982 // T* operator+(ptrdiff_t, T*); 6983 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6984 CandidateSet); 6985 } 6986 if (Op == OO_Minus) { 6987 // ptrdiff_t operator-(T, T); 6988 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6989 continue; 6990 6991 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6992 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6993 Args, 2, CandidateSet); 6994 } 6995 } 6996 } 6997 } 6998 6999 // C++ [over.built]p12: 7000 // 7001 // For every pair of promoted arithmetic types L and R, there 7002 // exist candidate operator functions of the form 7003 // 7004 // LR operator*(L, R); 7005 // LR operator/(L, R); 7006 // LR operator+(L, R); 7007 // LR operator-(L, R); 7008 // bool operator<(L, R); 7009 // bool operator>(L, R); 7010 // bool operator<=(L, R); 7011 // bool operator>=(L, R); 7012 // bool operator==(L, R); 7013 // bool operator!=(L, R); 7014 // 7015 // where LR is the result of the usual arithmetic conversions 7016 // between types L and R. 7017 // 7018 // C++ [over.built]p24: 7019 // 7020 // For every pair of promoted arithmetic types L and R, there exist 7021 // candidate operator functions of the form 7022 // 7023 // LR operator?(bool, L, R); 7024 // 7025 // where LR is the result of the usual arithmetic conversions 7026 // between types L and R. 7027 // Our candidates ignore the first parameter. 7028 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7029 if (!HasArithmeticOrEnumeralCandidateType) 7030 return; 7031 7032 for (unsigned Left = FirstPromotedArithmeticType; 7033 Left < LastPromotedArithmeticType; ++Left) { 7034 for (unsigned Right = FirstPromotedArithmeticType; 7035 Right < LastPromotedArithmeticType; ++Right) { 7036 QualType LandR[2] = { getArithmeticType(Left), 7037 getArithmeticType(Right) }; 7038 QualType Result = 7039 isComparison ? S.Context.BoolTy 7040 : getUsualArithmeticConversions(Left, Right); 7041 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7042 } 7043 } 7044 7045 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7046 // conditional operator for vector types. 7047 for (BuiltinCandidateTypeSet::iterator 7048 Vec1 = CandidateTypes[0].vector_begin(), 7049 Vec1End = CandidateTypes[0].vector_end(); 7050 Vec1 != Vec1End; ++Vec1) { 7051 for (BuiltinCandidateTypeSet::iterator 7052 Vec2 = CandidateTypes[1].vector_begin(), 7053 Vec2End = CandidateTypes[1].vector_end(); 7054 Vec2 != Vec2End; ++Vec2) { 7055 QualType LandR[2] = { *Vec1, *Vec2 }; 7056 QualType Result = S.Context.BoolTy; 7057 if (!isComparison) { 7058 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7059 Result = *Vec1; 7060 else 7061 Result = *Vec2; 7062 } 7063 7064 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7065 } 7066 } 7067 } 7068 7069 // C++ [over.built]p17: 7070 // 7071 // For every pair of promoted integral types L and R, there 7072 // exist candidate operator functions of the form 7073 // 7074 // LR operator%(L, R); 7075 // LR operator&(L, R); 7076 // LR operator^(L, R); 7077 // LR operator|(L, R); 7078 // L operator<<(L, R); 7079 // L operator>>(L, R); 7080 // 7081 // where LR is the result of the usual arithmetic conversions 7082 // between types L and R. 7083 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7084 if (!HasArithmeticOrEnumeralCandidateType) 7085 return; 7086 7087 for (unsigned Left = FirstPromotedIntegralType; 7088 Left < LastPromotedIntegralType; ++Left) { 7089 for (unsigned Right = FirstPromotedIntegralType; 7090 Right < LastPromotedIntegralType; ++Right) { 7091 QualType LandR[2] = { getArithmeticType(Left), 7092 getArithmeticType(Right) }; 7093 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7094 ? LandR[0] 7095 : getUsualArithmeticConversions(Left, Right); 7096 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7097 } 7098 } 7099 } 7100 7101 // C++ [over.built]p20: 7102 // 7103 // For every pair (T, VQ), where T is an enumeration or 7104 // pointer to member type and VQ is either volatile or 7105 // empty, there exist candidate operator functions of the form 7106 // 7107 // VQ T& operator=(VQ T&, T); 7108 void addAssignmentMemberPointerOrEnumeralOverloads() { 7109 /// Set of (canonical) types that we've already handled. 7110 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7111 7112 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7113 for (BuiltinCandidateTypeSet::iterator 7114 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7115 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7116 Enum != EnumEnd; ++Enum) { 7117 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7118 continue; 7119 7120 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7121 CandidateSet); 7122 } 7123 7124 for (BuiltinCandidateTypeSet::iterator 7125 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7126 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7127 MemPtr != MemPtrEnd; ++MemPtr) { 7128 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7129 continue; 7130 7131 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7132 CandidateSet); 7133 } 7134 } 7135 } 7136 7137 // C++ [over.built]p19: 7138 // 7139 // For every pair (T, VQ), where T is any type and VQ is either 7140 // volatile or empty, there exist candidate operator functions 7141 // of the form 7142 // 7143 // T*VQ& operator=(T*VQ&, T*); 7144 // 7145 // C++ [over.built]p21: 7146 // 7147 // For every pair (T, VQ), where T is a cv-qualified or 7148 // cv-unqualified object type and VQ is either volatile or 7149 // empty, there exist candidate operator functions of the form 7150 // 7151 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7152 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7153 void addAssignmentPointerOverloads(bool isEqualOp) { 7154 /// Set of (canonical) types that we've already handled. 7155 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7156 7157 for (BuiltinCandidateTypeSet::iterator 7158 Ptr = CandidateTypes[0].pointer_begin(), 7159 PtrEnd = CandidateTypes[0].pointer_end(); 7160 Ptr != PtrEnd; ++Ptr) { 7161 // If this is operator=, keep track of the builtin candidates we added. 7162 if (isEqualOp) 7163 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7164 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7165 continue; 7166 7167 // non-volatile version 7168 QualType ParamTypes[2] = { 7169 S.Context.getLValueReferenceType(*Ptr), 7170 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7171 }; 7172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7173 /*IsAssigmentOperator=*/ isEqualOp); 7174 7175 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7176 VisibleTypeConversionsQuals.hasVolatile(); 7177 if (NeedVolatile) { 7178 // volatile version 7179 ParamTypes[0] = 7180 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7182 /*IsAssigmentOperator=*/isEqualOp); 7183 } 7184 7185 if (!(*Ptr).isRestrictQualified() && 7186 VisibleTypeConversionsQuals.hasRestrict()) { 7187 // restrict version 7188 ParamTypes[0] 7189 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7190 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7191 /*IsAssigmentOperator=*/isEqualOp); 7192 7193 if (NeedVolatile) { 7194 // volatile restrict version 7195 ParamTypes[0] 7196 = S.Context.getLValueReferenceType( 7197 S.Context.getCVRQualifiedType(*Ptr, 7198 (Qualifiers::Volatile | 7199 Qualifiers::Restrict))); 7200 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7201 CandidateSet, 7202 /*IsAssigmentOperator=*/isEqualOp); 7203 } 7204 } 7205 } 7206 7207 if (isEqualOp) { 7208 for (BuiltinCandidateTypeSet::iterator 7209 Ptr = CandidateTypes[1].pointer_begin(), 7210 PtrEnd = CandidateTypes[1].pointer_end(); 7211 Ptr != PtrEnd; ++Ptr) { 7212 // Make sure we don't add the same candidate twice. 7213 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7214 continue; 7215 7216 QualType ParamTypes[2] = { 7217 S.Context.getLValueReferenceType(*Ptr), 7218 *Ptr, 7219 }; 7220 7221 // non-volatile version 7222 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7223 /*IsAssigmentOperator=*/true); 7224 7225 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7226 VisibleTypeConversionsQuals.hasVolatile(); 7227 if (NeedVolatile) { 7228 // volatile version 7229 ParamTypes[0] = 7230 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7231 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7232 CandidateSet, /*IsAssigmentOperator=*/true); 7233 } 7234 7235 if (!(*Ptr).isRestrictQualified() && 7236 VisibleTypeConversionsQuals.hasRestrict()) { 7237 // restrict version 7238 ParamTypes[0] 7239 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7241 CandidateSet, /*IsAssigmentOperator=*/true); 7242 7243 if (NeedVolatile) { 7244 // volatile restrict version 7245 ParamTypes[0] 7246 = S.Context.getLValueReferenceType( 7247 S.Context.getCVRQualifiedType(*Ptr, 7248 (Qualifiers::Volatile | 7249 Qualifiers::Restrict))); 7250 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7251 CandidateSet, /*IsAssigmentOperator=*/true); 7252 7253 } 7254 } 7255 } 7256 } 7257 } 7258 7259 // C++ [over.built]p18: 7260 // 7261 // For every triple (L, VQ, R), where L is an arithmetic type, 7262 // VQ is either volatile or empty, and R is a promoted 7263 // arithmetic type, there exist candidate operator functions of 7264 // the form 7265 // 7266 // VQ L& operator=(VQ L&, R); 7267 // VQ L& operator*=(VQ L&, R); 7268 // VQ L& operator/=(VQ L&, R); 7269 // VQ L& operator+=(VQ L&, R); 7270 // VQ L& operator-=(VQ L&, R); 7271 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7272 if (!HasArithmeticOrEnumeralCandidateType) 7273 return; 7274 7275 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7276 for (unsigned Right = FirstPromotedArithmeticType; 7277 Right < LastPromotedArithmeticType; ++Right) { 7278 QualType ParamTypes[2]; 7279 ParamTypes[1] = getArithmeticType(Right); 7280 7281 // Add this built-in operator as a candidate (VQ is empty). 7282 ParamTypes[0] = 7283 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7284 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7285 /*IsAssigmentOperator=*/isEqualOp); 7286 7287 // Add this built-in operator as a candidate (VQ is 'volatile'). 7288 if (VisibleTypeConversionsQuals.hasVolatile()) { 7289 ParamTypes[0] = 7290 S.Context.getVolatileType(getArithmeticType(Left)); 7291 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7293 CandidateSet, 7294 /*IsAssigmentOperator=*/isEqualOp); 7295 } 7296 } 7297 } 7298 7299 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7300 for (BuiltinCandidateTypeSet::iterator 7301 Vec1 = CandidateTypes[0].vector_begin(), 7302 Vec1End = CandidateTypes[0].vector_end(); 7303 Vec1 != Vec1End; ++Vec1) { 7304 for (BuiltinCandidateTypeSet::iterator 7305 Vec2 = CandidateTypes[1].vector_begin(), 7306 Vec2End = CandidateTypes[1].vector_end(); 7307 Vec2 != Vec2End; ++Vec2) { 7308 QualType ParamTypes[2]; 7309 ParamTypes[1] = *Vec2; 7310 // Add this built-in operator as a candidate (VQ is empty). 7311 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7313 /*IsAssigmentOperator=*/isEqualOp); 7314 7315 // Add this built-in operator as a candidate (VQ is 'volatile'). 7316 if (VisibleTypeConversionsQuals.hasVolatile()) { 7317 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7318 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7319 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7320 CandidateSet, 7321 /*IsAssigmentOperator=*/isEqualOp); 7322 } 7323 } 7324 } 7325 } 7326 7327 // C++ [over.built]p22: 7328 // 7329 // For every triple (L, VQ, R), where L is an integral type, VQ 7330 // is either volatile or empty, and R is a promoted integral 7331 // type, there exist candidate operator functions of the form 7332 // 7333 // VQ L& operator%=(VQ L&, R); 7334 // VQ L& operator<<=(VQ L&, R); 7335 // VQ L& operator>>=(VQ L&, R); 7336 // VQ L& operator&=(VQ L&, R); 7337 // VQ L& operator^=(VQ L&, R); 7338 // VQ L& operator|=(VQ L&, R); 7339 void addAssignmentIntegralOverloads() { 7340 if (!HasArithmeticOrEnumeralCandidateType) 7341 return; 7342 7343 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7344 for (unsigned Right = FirstPromotedIntegralType; 7345 Right < LastPromotedIntegralType; ++Right) { 7346 QualType ParamTypes[2]; 7347 ParamTypes[1] = getArithmeticType(Right); 7348 7349 // Add this built-in operator as a candidate (VQ is empty). 7350 ParamTypes[0] = 7351 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7352 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7353 if (VisibleTypeConversionsQuals.hasVolatile()) { 7354 // Add this built-in operator as a candidate (VQ is 'volatile'). 7355 ParamTypes[0] = getArithmeticType(Left); 7356 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7357 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7358 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7359 CandidateSet); 7360 } 7361 } 7362 } 7363 } 7364 7365 // C++ [over.operator]p23: 7366 // 7367 // There also exist candidate operator functions of the form 7368 // 7369 // bool operator!(bool); 7370 // bool operator&&(bool, bool); 7371 // bool operator||(bool, bool); 7372 void addExclaimOverload() { 7373 QualType ParamTy = S.Context.BoolTy; 7374 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7375 /*IsAssignmentOperator=*/false, 7376 /*NumContextualBoolArguments=*/1); 7377 } 7378 void addAmpAmpOrPipePipeOverload() { 7379 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7380 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7381 /*IsAssignmentOperator=*/false, 7382 /*NumContextualBoolArguments=*/2); 7383 } 7384 7385 // C++ [over.built]p13: 7386 // 7387 // For every cv-qualified or cv-unqualified object type T there 7388 // exist candidate operator functions of the form 7389 // 7390 // T* operator+(T*, ptrdiff_t); [ABOVE] 7391 // T& operator[](T*, ptrdiff_t); 7392 // T* operator-(T*, ptrdiff_t); [ABOVE] 7393 // T* operator+(ptrdiff_t, T*); [ABOVE] 7394 // T& operator[](ptrdiff_t, T*); 7395 void addSubscriptOverloads() { 7396 for (BuiltinCandidateTypeSet::iterator 7397 Ptr = CandidateTypes[0].pointer_begin(), 7398 PtrEnd = CandidateTypes[0].pointer_end(); 7399 Ptr != PtrEnd; ++Ptr) { 7400 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7401 QualType PointeeType = (*Ptr)->getPointeeType(); 7402 if (!PointeeType->isObjectType()) 7403 continue; 7404 7405 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7406 7407 // T& operator[](T*, ptrdiff_t) 7408 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7409 } 7410 7411 for (BuiltinCandidateTypeSet::iterator 7412 Ptr = CandidateTypes[1].pointer_begin(), 7413 PtrEnd = CandidateTypes[1].pointer_end(); 7414 Ptr != PtrEnd; ++Ptr) { 7415 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7416 QualType PointeeType = (*Ptr)->getPointeeType(); 7417 if (!PointeeType->isObjectType()) 7418 continue; 7419 7420 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7421 7422 // T& operator[](ptrdiff_t, T*) 7423 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7424 } 7425 } 7426 7427 // C++ [over.built]p11: 7428 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7429 // C1 is the same type as C2 or is a derived class of C2, T is an object 7430 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7431 // there exist candidate operator functions of the form 7432 // 7433 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7434 // 7435 // where CV12 is the union of CV1 and CV2. 7436 void addArrowStarOverloads() { 7437 for (BuiltinCandidateTypeSet::iterator 7438 Ptr = CandidateTypes[0].pointer_begin(), 7439 PtrEnd = CandidateTypes[0].pointer_end(); 7440 Ptr != PtrEnd; ++Ptr) { 7441 QualType C1Ty = (*Ptr); 7442 QualType C1; 7443 QualifierCollector Q1; 7444 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7445 if (!isa<RecordType>(C1)) 7446 continue; 7447 // heuristic to reduce number of builtin candidates in the set. 7448 // Add volatile/restrict version only if there are conversions to a 7449 // volatile/restrict type. 7450 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7451 continue; 7452 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7453 continue; 7454 for (BuiltinCandidateTypeSet::iterator 7455 MemPtr = CandidateTypes[1].member_pointer_begin(), 7456 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7457 MemPtr != MemPtrEnd; ++MemPtr) { 7458 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7459 QualType C2 = QualType(mptr->getClass(), 0); 7460 C2 = C2.getUnqualifiedType(); 7461 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7462 break; 7463 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7464 // build CV12 T& 7465 QualType T = mptr->getPointeeType(); 7466 if (!VisibleTypeConversionsQuals.hasVolatile() && 7467 T.isVolatileQualified()) 7468 continue; 7469 if (!VisibleTypeConversionsQuals.hasRestrict() && 7470 T.isRestrictQualified()) 7471 continue; 7472 T = Q1.apply(S.Context, T); 7473 QualType ResultTy = S.Context.getLValueReferenceType(T); 7474 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7475 } 7476 } 7477 } 7478 7479 // Note that we don't consider the first argument, since it has been 7480 // contextually converted to bool long ago. The candidates below are 7481 // therefore added as binary. 7482 // 7483 // C++ [over.built]p25: 7484 // For every type T, where T is a pointer, pointer-to-member, or scoped 7485 // enumeration type, there exist candidate operator functions of the form 7486 // 7487 // T operator?(bool, T, T); 7488 // 7489 void addConditionalOperatorOverloads() { 7490 /// Set of (canonical) types that we've already handled. 7491 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7492 7493 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7494 for (BuiltinCandidateTypeSet::iterator 7495 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7496 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7497 Ptr != PtrEnd; ++Ptr) { 7498 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7499 continue; 7500 7501 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7502 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7503 } 7504 7505 for (BuiltinCandidateTypeSet::iterator 7506 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7507 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7508 MemPtr != MemPtrEnd; ++MemPtr) { 7509 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7510 continue; 7511 7512 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7513 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7514 } 7515 7516 if (S.getLangOpts().CPlusPlus11) { 7517 for (BuiltinCandidateTypeSet::iterator 7518 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7519 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7520 Enum != EnumEnd; ++Enum) { 7521 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7522 continue; 7523 7524 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7525 continue; 7526 7527 QualType ParamTypes[2] = { *Enum, *Enum }; 7528 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7529 } 7530 } 7531 } 7532 } 7533}; 7534 7535} // end anonymous namespace 7536 7537/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7538/// operator overloads to the candidate set (C++ [over.built]), based 7539/// on the operator @p Op and the arguments given. For example, if the 7540/// operator is a binary '+', this routine might add "int 7541/// operator+(int, int)" to cover integer addition. 7542void 7543Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7544 SourceLocation OpLoc, 7545 Expr **Args, unsigned NumArgs, 7546 OverloadCandidateSet& CandidateSet) { 7547 // Find all of the types that the arguments can convert to, but only 7548 // if the operator we're looking at has built-in operator candidates 7549 // that make use of these types. Also record whether we encounter non-record 7550 // candidate types or either arithmetic or enumeral candidate types. 7551 Qualifiers VisibleTypeConversionsQuals; 7552 VisibleTypeConversionsQuals.addConst(); 7553 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7554 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7555 7556 bool HasNonRecordCandidateType = false; 7557 bool HasArithmeticOrEnumeralCandidateType = false; 7558 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7560 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7561 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7562 OpLoc, 7563 true, 7564 (Op == OO_Exclaim || 7565 Op == OO_AmpAmp || 7566 Op == OO_PipePipe), 7567 VisibleTypeConversionsQuals); 7568 HasNonRecordCandidateType = HasNonRecordCandidateType || 7569 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7570 HasArithmeticOrEnumeralCandidateType = 7571 HasArithmeticOrEnumeralCandidateType || 7572 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7573 } 7574 7575 // Exit early when no non-record types have been added to the candidate set 7576 // for any of the arguments to the operator. 7577 // 7578 // We can't exit early for !, ||, or &&, since there we have always have 7579 // 'bool' overloads. 7580 if (!HasNonRecordCandidateType && 7581 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7582 return; 7583 7584 // Setup an object to manage the common state for building overloads. 7585 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7586 VisibleTypeConversionsQuals, 7587 HasArithmeticOrEnumeralCandidateType, 7588 CandidateTypes, CandidateSet); 7589 7590 // Dispatch over the operation to add in only those overloads which apply. 7591 switch (Op) { 7592 case OO_None: 7593 case NUM_OVERLOADED_OPERATORS: 7594 llvm_unreachable("Expected an overloaded operator"); 7595 7596 case OO_New: 7597 case OO_Delete: 7598 case OO_Array_New: 7599 case OO_Array_Delete: 7600 case OO_Call: 7601 llvm_unreachable( 7602 "Special operators don't use AddBuiltinOperatorCandidates"); 7603 7604 case OO_Comma: 7605 case OO_Arrow: 7606 // C++ [over.match.oper]p3: 7607 // -- For the operator ',', the unary operator '&', or the 7608 // operator '->', the built-in candidates set is empty. 7609 break; 7610 7611 case OO_Plus: // '+' is either unary or binary 7612 if (NumArgs == 1) 7613 OpBuilder.addUnaryPlusPointerOverloads(); 7614 // Fall through. 7615 7616 case OO_Minus: // '-' is either unary or binary 7617 if (NumArgs == 1) { 7618 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7619 } else { 7620 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7621 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7622 } 7623 break; 7624 7625 case OO_Star: // '*' is either unary or binary 7626 if (NumArgs == 1) 7627 OpBuilder.addUnaryStarPointerOverloads(); 7628 else 7629 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7630 break; 7631 7632 case OO_Slash: 7633 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7634 break; 7635 7636 case OO_PlusPlus: 7637 case OO_MinusMinus: 7638 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7639 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7640 break; 7641 7642 case OO_EqualEqual: 7643 case OO_ExclaimEqual: 7644 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7645 // Fall through. 7646 7647 case OO_Less: 7648 case OO_Greater: 7649 case OO_LessEqual: 7650 case OO_GreaterEqual: 7651 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7652 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7653 break; 7654 7655 case OO_Percent: 7656 case OO_Caret: 7657 case OO_Pipe: 7658 case OO_LessLess: 7659 case OO_GreaterGreater: 7660 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7661 break; 7662 7663 case OO_Amp: // '&' is either unary or binary 7664 if (NumArgs == 1) 7665 // C++ [over.match.oper]p3: 7666 // -- For the operator ',', the unary operator '&', or the 7667 // operator '->', the built-in candidates set is empty. 7668 break; 7669 7670 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7671 break; 7672 7673 case OO_Tilde: 7674 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7675 break; 7676 7677 case OO_Equal: 7678 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7679 // Fall through. 7680 7681 case OO_PlusEqual: 7682 case OO_MinusEqual: 7683 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7684 // Fall through. 7685 7686 case OO_StarEqual: 7687 case OO_SlashEqual: 7688 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7689 break; 7690 7691 case OO_PercentEqual: 7692 case OO_LessLessEqual: 7693 case OO_GreaterGreaterEqual: 7694 case OO_AmpEqual: 7695 case OO_CaretEqual: 7696 case OO_PipeEqual: 7697 OpBuilder.addAssignmentIntegralOverloads(); 7698 break; 7699 7700 case OO_Exclaim: 7701 OpBuilder.addExclaimOverload(); 7702 break; 7703 7704 case OO_AmpAmp: 7705 case OO_PipePipe: 7706 OpBuilder.addAmpAmpOrPipePipeOverload(); 7707 break; 7708 7709 case OO_Subscript: 7710 OpBuilder.addSubscriptOverloads(); 7711 break; 7712 7713 case OO_ArrowStar: 7714 OpBuilder.addArrowStarOverloads(); 7715 break; 7716 7717 case OO_Conditional: 7718 OpBuilder.addConditionalOperatorOverloads(); 7719 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7720 break; 7721 } 7722} 7723 7724/// \brief Add function candidates found via argument-dependent lookup 7725/// to the set of overloading candidates. 7726/// 7727/// This routine performs argument-dependent name lookup based on the 7728/// given function name (which may also be an operator name) and adds 7729/// all of the overload candidates found by ADL to the overload 7730/// candidate set (C++ [basic.lookup.argdep]). 7731void 7732Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7733 bool Operator, SourceLocation Loc, 7734 ArrayRef<Expr *> Args, 7735 TemplateArgumentListInfo *ExplicitTemplateArgs, 7736 OverloadCandidateSet& CandidateSet, 7737 bool PartialOverloading) { 7738 ADLResult Fns; 7739 7740 // FIXME: This approach for uniquing ADL results (and removing 7741 // redundant candidates from the set) relies on pointer-equality, 7742 // which means we need to key off the canonical decl. However, 7743 // always going back to the canonical decl might not get us the 7744 // right set of default arguments. What default arguments are 7745 // we supposed to consider on ADL candidates, anyway? 7746 7747 // FIXME: Pass in the explicit template arguments? 7748 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7749 7750 // Erase all of the candidates we already knew about. 7751 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7752 CandEnd = CandidateSet.end(); 7753 Cand != CandEnd; ++Cand) 7754 if (Cand->Function) { 7755 Fns.erase(Cand->Function); 7756 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7757 Fns.erase(FunTmpl); 7758 } 7759 7760 // For each of the ADL candidates we found, add it to the overload 7761 // set. 7762 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7763 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7764 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7765 if (ExplicitTemplateArgs) 7766 continue; 7767 7768 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7769 PartialOverloading); 7770 } else 7771 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7772 FoundDecl, ExplicitTemplateArgs, 7773 Args, CandidateSet); 7774 } 7775} 7776 7777/// isBetterOverloadCandidate - Determines whether the first overload 7778/// candidate is a better candidate than the second (C++ 13.3.3p1). 7779bool 7780isBetterOverloadCandidate(Sema &S, 7781 const OverloadCandidate &Cand1, 7782 const OverloadCandidate &Cand2, 7783 SourceLocation Loc, 7784 bool UserDefinedConversion) { 7785 // Define viable functions to be better candidates than non-viable 7786 // functions. 7787 if (!Cand2.Viable) 7788 return Cand1.Viable; 7789 else if (!Cand1.Viable) 7790 return false; 7791 7792 // C++ [over.match.best]p1: 7793 // 7794 // -- if F is a static member function, ICS1(F) is defined such 7795 // that ICS1(F) is neither better nor worse than ICS1(G) for 7796 // any function G, and, symmetrically, ICS1(G) is neither 7797 // better nor worse than ICS1(F). 7798 unsigned StartArg = 0; 7799 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7800 StartArg = 1; 7801 7802 // C++ [over.match.best]p1: 7803 // A viable function F1 is defined to be a better function than another 7804 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7805 // conversion sequence than ICSi(F2), and then... 7806 unsigned NumArgs = Cand1.NumConversions; 7807 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7808 bool HasBetterConversion = false; 7809 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7810 switch (CompareImplicitConversionSequences(S, 7811 Cand1.Conversions[ArgIdx], 7812 Cand2.Conversions[ArgIdx])) { 7813 case ImplicitConversionSequence::Better: 7814 // Cand1 has a better conversion sequence. 7815 HasBetterConversion = true; 7816 break; 7817 7818 case ImplicitConversionSequence::Worse: 7819 // Cand1 can't be better than Cand2. 7820 return false; 7821 7822 case ImplicitConversionSequence::Indistinguishable: 7823 // Do nothing. 7824 break; 7825 } 7826 } 7827 7828 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7829 // ICSj(F2), or, if not that, 7830 if (HasBetterConversion) 7831 return true; 7832 7833 // - F1 is a non-template function and F2 is a function template 7834 // specialization, or, if not that, 7835 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7836 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7837 return true; 7838 7839 // -- F1 and F2 are function template specializations, and the function 7840 // template for F1 is more specialized than the template for F2 7841 // according to the partial ordering rules described in 14.5.5.2, or, 7842 // if not that, 7843 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7844 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7845 if (FunctionTemplateDecl *BetterTemplate 7846 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7847 Cand2.Function->getPrimaryTemplate(), 7848 Loc, 7849 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7850 : TPOC_Call, 7851 Cand1.ExplicitCallArguments)) 7852 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7853 } 7854 7855 // -- the context is an initialization by user-defined conversion 7856 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7857 // from the return type of F1 to the destination type (i.e., 7858 // the type of the entity being initialized) is a better 7859 // conversion sequence than the standard conversion sequence 7860 // from the return type of F2 to the destination type. 7861 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7862 isa<CXXConversionDecl>(Cand1.Function) && 7863 isa<CXXConversionDecl>(Cand2.Function)) { 7864 // First check whether we prefer one of the conversion functions over the 7865 // other. This only distinguishes the results in non-standard, extension 7866 // cases such as the conversion from a lambda closure type to a function 7867 // pointer or block. 7868 ImplicitConversionSequence::CompareKind FuncResult 7869 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7870 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7871 return FuncResult; 7872 7873 switch (CompareStandardConversionSequences(S, 7874 Cand1.FinalConversion, 7875 Cand2.FinalConversion)) { 7876 case ImplicitConversionSequence::Better: 7877 // Cand1 has a better conversion sequence. 7878 return true; 7879 7880 case ImplicitConversionSequence::Worse: 7881 // Cand1 can't be better than Cand2. 7882 return false; 7883 7884 case ImplicitConversionSequence::Indistinguishable: 7885 // Do nothing 7886 break; 7887 } 7888 } 7889 7890 return false; 7891} 7892 7893/// \brief Computes the best viable function (C++ 13.3.3) 7894/// within an overload candidate set. 7895/// 7896/// \param Loc The location of the function name (or operator symbol) for 7897/// which overload resolution occurs. 7898/// 7899/// \param Best If overload resolution was successful or found a deleted 7900/// function, \p Best points to the candidate function found. 7901/// 7902/// \returns The result of overload resolution. 7903OverloadingResult 7904OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7905 iterator &Best, 7906 bool UserDefinedConversion) { 7907 // Find the best viable function. 7908 Best = end(); 7909 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7910 if (Cand->Viable) 7911 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7912 UserDefinedConversion)) 7913 Best = Cand; 7914 } 7915 7916 // If we didn't find any viable functions, abort. 7917 if (Best == end()) 7918 return OR_No_Viable_Function; 7919 7920 // Make sure that this function is better than every other viable 7921 // function. If not, we have an ambiguity. 7922 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7923 if (Cand->Viable && 7924 Cand != Best && 7925 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7926 UserDefinedConversion)) { 7927 Best = end(); 7928 return OR_Ambiguous; 7929 } 7930 } 7931 7932 // Best is the best viable function. 7933 if (Best->Function && 7934 (Best->Function->isDeleted() || 7935 S.isFunctionConsideredUnavailable(Best->Function))) 7936 return OR_Deleted; 7937 7938 return OR_Success; 7939} 7940 7941namespace { 7942 7943enum OverloadCandidateKind { 7944 oc_function, 7945 oc_method, 7946 oc_constructor, 7947 oc_function_template, 7948 oc_method_template, 7949 oc_constructor_template, 7950 oc_implicit_default_constructor, 7951 oc_implicit_copy_constructor, 7952 oc_implicit_move_constructor, 7953 oc_implicit_copy_assignment, 7954 oc_implicit_move_assignment, 7955 oc_implicit_inherited_constructor 7956}; 7957 7958OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7959 FunctionDecl *Fn, 7960 std::string &Description) { 7961 bool isTemplate = false; 7962 7963 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7964 isTemplate = true; 7965 Description = S.getTemplateArgumentBindingsText( 7966 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7967 } 7968 7969 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7970 if (!Ctor->isImplicit()) 7971 return isTemplate ? oc_constructor_template : oc_constructor; 7972 7973 if (Ctor->getInheritedConstructor()) 7974 return oc_implicit_inherited_constructor; 7975 7976 if (Ctor->isDefaultConstructor()) 7977 return oc_implicit_default_constructor; 7978 7979 if (Ctor->isMoveConstructor()) 7980 return oc_implicit_move_constructor; 7981 7982 assert(Ctor->isCopyConstructor() && 7983 "unexpected sort of implicit constructor"); 7984 return oc_implicit_copy_constructor; 7985 } 7986 7987 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7988 // This actually gets spelled 'candidate function' for now, but 7989 // it doesn't hurt to split it out. 7990 if (!Meth->isImplicit()) 7991 return isTemplate ? oc_method_template : oc_method; 7992 7993 if (Meth->isMoveAssignmentOperator()) 7994 return oc_implicit_move_assignment; 7995 7996 if (Meth->isCopyAssignmentOperator()) 7997 return oc_implicit_copy_assignment; 7998 7999 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8000 return oc_method; 8001 } 8002 8003 return isTemplate ? oc_function_template : oc_function; 8004} 8005 8006void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 8007 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8008 if (!Ctor) return; 8009 8010 Ctor = Ctor->getInheritedConstructor(); 8011 if (!Ctor) return; 8012 8013 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8014} 8015 8016} // end anonymous namespace 8017 8018// Notes the location of an overload candidate. 8019void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8020 std::string FnDesc; 8021 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8022 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8023 << (unsigned) K << FnDesc; 8024 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8025 Diag(Fn->getLocation(), PD); 8026 MaybeEmitInheritedConstructorNote(*this, Fn); 8027} 8028 8029//Notes the location of all overload candidates designated through 8030// OverloadedExpr 8031void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8032 assert(OverloadedExpr->getType() == Context.OverloadTy); 8033 8034 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8035 OverloadExpr *OvlExpr = Ovl.Expression; 8036 8037 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8038 IEnd = OvlExpr->decls_end(); 8039 I != IEnd; ++I) { 8040 if (FunctionTemplateDecl *FunTmpl = 8041 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8042 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8043 } else if (FunctionDecl *Fun 8044 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8045 NoteOverloadCandidate(Fun, DestType); 8046 } 8047 } 8048} 8049 8050/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8051/// "lead" diagnostic; it will be given two arguments, the source and 8052/// target types of the conversion. 8053void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8054 Sema &S, 8055 SourceLocation CaretLoc, 8056 const PartialDiagnostic &PDiag) const { 8057 S.Diag(CaretLoc, PDiag) 8058 << Ambiguous.getFromType() << Ambiguous.getToType(); 8059 // FIXME: The note limiting machinery is borrowed from 8060 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8061 // refactoring here. 8062 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8063 unsigned CandsShown = 0; 8064 AmbiguousConversionSequence::const_iterator I, E; 8065 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8066 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8067 break; 8068 ++CandsShown; 8069 S.NoteOverloadCandidate(*I); 8070 } 8071 if (I != E) 8072 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8073} 8074 8075namespace { 8076 8077void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8078 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8079 assert(Conv.isBad()); 8080 assert(Cand->Function && "for now, candidate must be a function"); 8081 FunctionDecl *Fn = Cand->Function; 8082 8083 // There's a conversion slot for the object argument if this is a 8084 // non-constructor method. Note that 'I' corresponds the 8085 // conversion-slot index. 8086 bool isObjectArgument = false; 8087 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8088 if (I == 0) 8089 isObjectArgument = true; 8090 else 8091 I--; 8092 } 8093 8094 std::string FnDesc; 8095 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8096 8097 Expr *FromExpr = Conv.Bad.FromExpr; 8098 QualType FromTy = Conv.Bad.getFromType(); 8099 QualType ToTy = Conv.Bad.getToType(); 8100 8101 if (FromTy == S.Context.OverloadTy) { 8102 assert(FromExpr && "overload set argument came from implicit argument?"); 8103 Expr *E = FromExpr->IgnoreParens(); 8104 if (isa<UnaryOperator>(E)) 8105 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8106 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8107 8108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8109 << (unsigned) FnKind << FnDesc 8110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8111 << ToTy << Name << I+1; 8112 MaybeEmitInheritedConstructorNote(S, Fn); 8113 return; 8114 } 8115 8116 // Do some hand-waving analysis to see if the non-viability is due 8117 // to a qualifier mismatch. 8118 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8119 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8120 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8121 CToTy = RT->getPointeeType(); 8122 else { 8123 // TODO: detect and diagnose the full richness of const mismatches. 8124 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8125 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8126 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8127 } 8128 8129 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8130 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8131 Qualifiers FromQs = CFromTy.getQualifiers(); 8132 Qualifiers ToQs = CToTy.getQualifiers(); 8133 8134 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8136 << (unsigned) FnKind << FnDesc 8137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8138 << FromTy 8139 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8140 << (unsigned) isObjectArgument << I+1; 8141 MaybeEmitInheritedConstructorNote(S, Fn); 8142 return; 8143 } 8144 8145 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8146 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8147 << (unsigned) FnKind << FnDesc 8148 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8149 << FromTy 8150 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8151 << (unsigned) isObjectArgument << I+1; 8152 MaybeEmitInheritedConstructorNote(S, Fn); 8153 return; 8154 } 8155 8156 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8157 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8158 << (unsigned) FnKind << FnDesc 8159 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8160 << FromTy 8161 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8162 << (unsigned) isObjectArgument << I+1; 8163 MaybeEmitInheritedConstructorNote(S, Fn); 8164 return; 8165 } 8166 8167 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8168 assert(CVR && "unexpected qualifiers mismatch"); 8169 8170 if (isObjectArgument) { 8171 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8172 << (unsigned) FnKind << FnDesc 8173 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8174 << FromTy << (CVR - 1); 8175 } else { 8176 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8177 << (unsigned) FnKind << FnDesc 8178 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8179 << FromTy << (CVR - 1) << I+1; 8180 } 8181 MaybeEmitInheritedConstructorNote(S, Fn); 8182 return; 8183 } 8184 8185 // Special diagnostic for failure to convert an initializer list, since 8186 // telling the user that it has type void is not useful. 8187 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8188 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8189 << (unsigned) FnKind << FnDesc 8190 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8191 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8192 MaybeEmitInheritedConstructorNote(S, Fn); 8193 return; 8194 } 8195 8196 // Diagnose references or pointers to incomplete types differently, 8197 // since it's far from impossible that the incompleteness triggered 8198 // the failure. 8199 QualType TempFromTy = FromTy.getNonReferenceType(); 8200 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8201 TempFromTy = PTy->getPointeeType(); 8202 if (TempFromTy->isIncompleteType()) { 8203 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8204 << (unsigned) FnKind << FnDesc 8205 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8206 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8207 MaybeEmitInheritedConstructorNote(S, Fn); 8208 return; 8209 } 8210 8211 // Diagnose base -> derived pointer conversions. 8212 unsigned BaseToDerivedConversion = 0; 8213 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8214 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8215 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8216 FromPtrTy->getPointeeType()) && 8217 !FromPtrTy->getPointeeType()->isIncompleteType() && 8218 !ToPtrTy->getPointeeType()->isIncompleteType() && 8219 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8220 FromPtrTy->getPointeeType())) 8221 BaseToDerivedConversion = 1; 8222 } 8223 } else if (const ObjCObjectPointerType *FromPtrTy 8224 = FromTy->getAs<ObjCObjectPointerType>()) { 8225 if (const ObjCObjectPointerType *ToPtrTy 8226 = ToTy->getAs<ObjCObjectPointerType>()) 8227 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8228 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8229 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8230 FromPtrTy->getPointeeType()) && 8231 FromIface->isSuperClassOf(ToIface)) 8232 BaseToDerivedConversion = 2; 8233 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8234 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8235 !FromTy->isIncompleteType() && 8236 !ToRefTy->getPointeeType()->isIncompleteType() && 8237 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8238 BaseToDerivedConversion = 3; 8239 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8240 ToTy.getNonReferenceType().getCanonicalType() == 8241 FromTy.getNonReferenceType().getCanonicalType()) { 8242 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8243 << (unsigned) FnKind << FnDesc 8244 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8245 << (unsigned) isObjectArgument << I + 1; 8246 MaybeEmitInheritedConstructorNote(S, Fn); 8247 return; 8248 } 8249 } 8250 8251 if (BaseToDerivedConversion) { 8252 S.Diag(Fn->getLocation(), 8253 diag::note_ovl_candidate_bad_base_to_derived_conv) 8254 << (unsigned) FnKind << FnDesc 8255 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8256 << (BaseToDerivedConversion - 1) 8257 << FromTy << ToTy << I+1; 8258 MaybeEmitInheritedConstructorNote(S, Fn); 8259 return; 8260 } 8261 8262 if (isa<ObjCObjectPointerType>(CFromTy) && 8263 isa<PointerType>(CToTy)) { 8264 Qualifiers FromQs = CFromTy.getQualifiers(); 8265 Qualifiers ToQs = CToTy.getQualifiers(); 8266 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8268 << (unsigned) FnKind << FnDesc 8269 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8270 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8271 MaybeEmitInheritedConstructorNote(S, Fn); 8272 return; 8273 } 8274 } 8275 8276 // Emit the generic diagnostic and, optionally, add the hints to it. 8277 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8278 FDiag << (unsigned) FnKind << FnDesc 8279 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8280 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8281 << (unsigned) (Cand->Fix.Kind); 8282 8283 // If we can fix the conversion, suggest the FixIts. 8284 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8285 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8286 FDiag << *HI; 8287 S.Diag(Fn->getLocation(), FDiag); 8288 8289 MaybeEmitInheritedConstructorNote(S, Fn); 8290} 8291 8292void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8293 unsigned NumFormalArgs) { 8294 // TODO: treat calls to a missing default constructor as a special case 8295 8296 FunctionDecl *Fn = Cand->Function; 8297 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8298 8299 unsigned MinParams = Fn->getMinRequiredArguments(); 8300 8301 // With invalid overloaded operators, it's possible that we think we 8302 // have an arity mismatch when it fact it looks like we have the 8303 // right number of arguments, because only overloaded operators have 8304 // the weird behavior of overloading member and non-member functions. 8305 // Just don't report anything. 8306 if (Fn->isInvalidDecl() && 8307 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8308 return; 8309 8310 // at least / at most / exactly 8311 unsigned mode, modeCount; 8312 if (NumFormalArgs < MinParams) { 8313 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8314 (Cand->FailureKind == ovl_fail_bad_deduction && 8315 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8316 if (MinParams != FnTy->getNumArgs() || 8317 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8318 mode = 0; // "at least" 8319 else 8320 mode = 2; // "exactly" 8321 modeCount = MinParams; 8322 } else { 8323 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8324 (Cand->FailureKind == ovl_fail_bad_deduction && 8325 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8326 if (MinParams != FnTy->getNumArgs()) 8327 mode = 1; // "at most" 8328 else 8329 mode = 2; // "exactly" 8330 modeCount = FnTy->getNumArgs(); 8331 } 8332 8333 std::string Description; 8334 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8335 8336 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8338 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8339 << Fn->getParamDecl(0) << NumFormalArgs; 8340 else 8341 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8342 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8343 << modeCount << NumFormalArgs; 8344 MaybeEmitInheritedConstructorNote(S, Fn); 8345} 8346 8347/// Diagnose a failed template-argument deduction. 8348void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8349 unsigned NumArgs) { 8350 FunctionDecl *Fn = Cand->Function; // pattern 8351 8352 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8353 NamedDecl *ParamD; 8354 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8355 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8356 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8357 switch (Cand->DeductionFailure.Result) { 8358 case Sema::TDK_Success: 8359 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8360 8361 case Sema::TDK_Incomplete: { 8362 assert(ParamD && "no parameter found for incomplete deduction result"); 8363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8364 << ParamD->getDeclName(); 8365 MaybeEmitInheritedConstructorNote(S, Fn); 8366 return; 8367 } 8368 8369 case Sema::TDK_Underqualified: { 8370 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8371 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8372 8373 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8374 8375 // Param will have been canonicalized, but it should just be a 8376 // qualified version of ParamD, so move the qualifiers to that. 8377 QualifierCollector Qs; 8378 Qs.strip(Param); 8379 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8380 assert(S.Context.hasSameType(Param, NonCanonParam)); 8381 8382 // Arg has also been canonicalized, but there's nothing we can do 8383 // about that. It also doesn't matter as much, because it won't 8384 // have any template parameters in it (because deduction isn't 8385 // done on dependent types). 8386 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8387 8388 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8389 << ParamD->getDeclName() << Arg << NonCanonParam; 8390 MaybeEmitInheritedConstructorNote(S, Fn); 8391 return; 8392 } 8393 8394 case Sema::TDK_Inconsistent: { 8395 assert(ParamD && "no parameter found for inconsistent deduction result"); 8396 int which = 0; 8397 if (isa<TemplateTypeParmDecl>(ParamD)) 8398 which = 0; 8399 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8400 which = 1; 8401 else { 8402 which = 2; 8403 } 8404 8405 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8406 << which << ParamD->getDeclName() 8407 << *Cand->DeductionFailure.getFirstArg() 8408 << *Cand->DeductionFailure.getSecondArg(); 8409 MaybeEmitInheritedConstructorNote(S, Fn); 8410 return; 8411 } 8412 8413 case Sema::TDK_InvalidExplicitArguments: 8414 assert(ParamD && "no parameter found for invalid explicit arguments"); 8415 if (ParamD->getDeclName()) 8416 S.Diag(Fn->getLocation(), 8417 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8418 << ParamD->getDeclName(); 8419 else { 8420 int index = 0; 8421 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8422 index = TTP->getIndex(); 8423 else if (NonTypeTemplateParmDecl *NTTP 8424 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8425 index = NTTP->getIndex(); 8426 else 8427 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8428 S.Diag(Fn->getLocation(), 8429 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8430 << (index + 1); 8431 } 8432 MaybeEmitInheritedConstructorNote(S, Fn); 8433 return; 8434 8435 case Sema::TDK_TooManyArguments: 8436 case Sema::TDK_TooFewArguments: 8437 DiagnoseArityMismatch(S, Cand, NumArgs); 8438 return; 8439 8440 case Sema::TDK_InstantiationDepth: 8441 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8442 MaybeEmitInheritedConstructorNote(S, Fn); 8443 return; 8444 8445 case Sema::TDK_SubstitutionFailure: { 8446 // Format the template argument list into the argument string. 8447 SmallString<128> TemplateArgString; 8448 if (TemplateArgumentList *Args = 8449 Cand->DeductionFailure.getTemplateArgumentList()) { 8450 TemplateArgString = " "; 8451 TemplateArgString += S.getTemplateArgumentBindingsText( 8452 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8453 } 8454 8455 // If this candidate was disabled by enable_if, say so. 8456 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8457 if (PDiag && PDiag->second.getDiagID() == 8458 diag::err_typename_nested_not_found_enable_if) { 8459 // FIXME: Use the source range of the condition, and the fully-qualified 8460 // name of the enable_if template. These are both present in PDiag. 8461 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8462 << "'enable_if'" << TemplateArgString; 8463 return; 8464 } 8465 8466 // Format the SFINAE diagnostic into the argument string. 8467 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8468 // formatted message in another diagnostic. 8469 SmallString<128> SFINAEArgString; 8470 SourceRange R; 8471 if (PDiag) { 8472 SFINAEArgString = ": "; 8473 R = SourceRange(PDiag->first, PDiag->first); 8474 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8475 } 8476 8477 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8478 << TemplateArgString << SFINAEArgString << R; 8479 MaybeEmitInheritedConstructorNote(S, Fn); 8480 return; 8481 } 8482 8483 case Sema::TDK_FailedOverloadResolution: { 8484 OverloadExpr::FindResult R = 8485 OverloadExpr::find(Cand->DeductionFailure.getExpr()); 8486 S.Diag(Fn->getLocation(), 8487 diag::note_ovl_candidate_failed_overload_resolution) 8488 << R.Expression->getName(); 8489 return; 8490 } 8491 8492 case Sema::TDK_NonDeducedMismatch: 8493 // FIXME: Provide a source location to indicate what we couldn't match. 8494 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch) 8495 << *Cand->DeductionFailure.getFirstArg() 8496 << *Cand->DeductionFailure.getSecondArg(); 8497 return; 8498 8499 // TODO: diagnose these individually, then kill off 8500 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8501 case Sema::TDK_MiscellaneousDeductionFailure: 8502 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8503 MaybeEmitInheritedConstructorNote(S, Fn); 8504 return; 8505 } 8506} 8507 8508/// CUDA: diagnose an invalid call across targets. 8509void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8510 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8511 FunctionDecl *Callee = Cand->Function; 8512 8513 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8514 CalleeTarget = S.IdentifyCUDATarget(Callee); 8515 8516 std::string FnDesc; 8517 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8518 8519 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8520 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8521} 8522 8523/// Generates a 'note' diagnostic for an overload candidate. We've 8524/// already generated a primary error at the call site. 8525/// 8526/// It really does need to be a single diagnostic with its caret 8527/// pointed at the candidate declaration. Yes, this creates some 8528/// major challenges of technical writing. Yes, this makes pointing 8529/// out problems with specific arguments quite awkward. It's still 8530/// better than generating twenty screens of text for every failed 8531/// overload. 8532/// 8533/// It would be great to be able to express per-candidate problems 8534/// more richly for those diagnostic clients that cared, but we'd 8535/// still have to be just as careful with the default diagnostics. 8536void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8537 unsigned NumArgs) { 8538 FunctionDecl *Fn = Cand->Function; 8539 8540 // Note deleted candidates, but only if they're viable. 8541 if (Cand->Viable && (Fn->isDeleted() || 8542 S.isFunctionConsideredUnavailable(Fn))) { 8543 std::string FnDesc; 8544 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8545 8546 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8547 << FnKind << FnDesc 8548 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8549 MaybeEmitInheritedConstructorNote(S, Fn); 8550 return; 8551 } 8552 8553 // We don't really have anything else to say about viable candidates. 8554 if (Cand->Viable) { 8555 S.NoteOverloadCandidate(Fn); 8556 return; 8557 } 8558 8559 switch (Cand->FailureKind) { 8560 case ovl_fail_too_many_arguments: 8561 case ovl_fail_too_few_arguments: 8562 return DiagnoseArityMismatch(S, Cand, NumArgs); 8563 8564 case ovl_fail_bad_deduction: 8565 return DiagnoseBadDeduction(S, Cand, NumArgs); 8566 8567 case ovl_fail_trivial_conversion: 8568 case ovl_fail_bad_final_conversion: 8569 case ovl_fail_final_conversion_not_exact: 8570 return S.NoteOverloadCandidate(Fn); 8571 8572 case ovl_fail_bad_conversion: { 8573 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8574 for (unsigned N = Cand->NumConversions; I != N; ++I) 8575 if (Cand->Conversions[I].isBad()) 8576 return DiagnoseBadConversion(S, Cand, I); 8577 8578 // FIXME: this currently happens when we're called from SemaInit 8579 // when user-conversion overload fails. Figure out how to handle 8580 // those conditions and diagnose them well. 8581 return S.NoteOverloadCandidate(Fn); 8582 } 8583 8584 case ovl_fail_bad_target: 8585 return DiagnoseBadTarget(S, Cand); 8586 } 8587} 8588 8589void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8590 // Desugar the type of the surrogate down to a function type, 8591 // retaining as many typedefs as possible while still showing 8592 // the function type (and, therefore, its parameter types). 8593 QualType FnType = Cand->Surrogate->getConversionType(); 8594 bool isLValueReference = false; 8595 bool isRValueReference = false; 8596 bool isPointer = false; 8597 if (const LValueReferenceType *FnTypeRef = 8598 FnType->getAs<LValueReferenceType>()) { 8599 FnType = FnTypeRef->getPointeeType(); 8600 isLValueReference = true; 8601 } else if (const RValueReferenceType *FnTypeRef = 8602 FnType->getAs<RValueReferenceType>()) { 8603 FnType = FnTypeRef->getPointeeType(); 8604 isRValueReference = true; 8605 } 8606 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8607 FnType = FnTypePtr->getPointeeType(); 8608 isPointer = true; 8609 } 8610 // Desugar down to a function type. 8611 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8612 // Reconstruct the pointer/reference as appropriate. 8613 if (isPointer) FnType = S.Context.getPointerType(FnType); 8614 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8615 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8616 8617 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8618 << FnType; 8619 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8620} 8621 8622void NoteBuiltinOperatorCandidate(Sema &S, 8623 StringRef Opc, 8624 SourceLocation OpLoc, 8625 OverloadCandidate *Cand) { 8626 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8627 std::string TypeStr("operator"); 8628 TypeStr += Opc; 8629 TypeStr += "("; 8630 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8631 if (Cand->NumConversions == 1) { 8632 TypeStr += ")"; 8633 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8634 } else { 8635 TypeStr += ", "; 8636 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8637 TypeStr += ")"; 8638 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8639 } 8640} 8641 8642void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8643 OverloadCandidate *Cand) { 8644 unsigned NoOperands = Cand->NumConversions; 8645 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8646 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8647 if (ICS.isBad()) break; // all meaningless after first invalid 8648 if (!ICS.isAmbiguous()) continue; 8649 8650 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8651 S.PDiag(diag::note_ambiguous_type_conversion)); 8652 } 8653} 8654 8655SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8656 if (Cand->Function) 8657 return Cand->Function->getLocation(); 8658 if (Cand->IsSurrogate) 8659 return Cand->Surrogate->getLocation(); 8660 return SourceLocation(); 8661} 8662 8663static unsigned 8664RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8665 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8666 case Sema::TDK_Success: 8667 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8668 8669 case Sema::TDK_Invalid: 8670 case Sema::TDK_Incomplete: 8671 return 1; 8672 8673 case Sema::TDK_Underqualified: 8674 case Sema::TDK_Inconsistent: 8675 return 2; 8676 8677 case Sema::TDK_SubstitutionFailure: 8678 case Sema::TDK_NonDeducedMismatch: 8679 case Sema::TDK_MiscellaneousDeductionFailure: 8680 return 3; 8681 8682 case Sema::TDK_InstantiationDepth: 8683 case Sema::TDK_FailedOverloadResolution: 8684 return 4; 8685 8686 case Sema::TDK_InvalidExplicitArguments: 8687 return 5; 8688 8689 case Sema::TDK_TooManyArguments: 8690 case Sema::TDK_TooFewArguments: 8691 return 6; 8692 } 8693 llvm_unreachable("Unhandled deduction result"); 8694} 8695 8696struct CompareOverloadCandidatesForDisplay { 8697 Sema &S; 8698 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8699 8700 bool operator()(const OverloadCandidate *L, 8701 const OverloadCandidate *R) { 8702 // Fast-path this check. 8703 if (L == R) return false; 8704 8705 // Order first by viability. 8706 if (L->Viable) { 8707 if (!R->Viable) return true; 8708 8709 // TODO: introduce a tri-valued comparison for overload 8710 // candidates. Would be more worthwhile if we had a sort 8711 // that could exploit it. 8712 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8713 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8714 } else if (R->Viable) 8715 return false; 8716 8717 assert(L->Viable == R->Viable); 8718 8719 // Criteria by which we can sort non-viable candidates: 8720 if (!L->Viable) { 8721 // 1. Arity mismatches come after other candidates. 8722 if (L->FailureKind == ovl_fail_too_many_arguments || 8723 L->FailureKind == ovl_fail_too_few_arguments) 8724 return false; 8725 if (R->FailureKind == ovl_fail_too_many_arguments || 8726 R->FailureKind == ovl_fail_too_few_arguments) 8727 return true; 8728 8729 // 2. Bad conversions come first and are ordered by the number 8730 // of bad conversions and quality of good conversions. 8731 if (L->FailureKind == ovl_fail_bad_conversion) { 8732 if (R->FailureKind != ovl_fail_bad_conversion) 8733 return true; 8734 8735 // The conversion that can be fixed with a smaller number of changes, 8736 // comes first. 8737 unsigned numLFixes = L->Fix.NumConversionsFixed; 8738 unsigned numRFixes = R->Fix.NumConversionsFixed; 8739 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8740 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8741 if (numLFixes != numRFixes) { 8742 if (numLFixes < numRFixes) 8743 return true; 8744 else 8745 return false; 8746 } 8747 8748 // If there's any ordering between the defined conversions... 8749 // FIXME: this might not be transitive. 8750 assert(L->NumConversions == R->NumConversions); 8751 8752 int leftBetter = 0; 8753 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8754 for (unsigned E = L->NumConversions; I != E; ++I) { 8755 switch (CompareImplicitConversionSequences(S, 8756 L->Conversions[I], 8757 R->Conversions[I])) { 8758 case ImplicitConversionSequence::Better: 8759 leftBetter++; 8760 break; 8761 8762 case ImplicitConversionSequence::Worse: 8763 leftBetter--; 8764 break; 8765 8766 case ImplicitConversionSequence::Indistinguishable: 8767 break; 8768 } 8769 } 8770 if (leftBetter > 0) return true; 8771 if (leftBetter < 0) return false; 8772 8773 } else if (R->FailureKind == ovl_fail_bad_conversion) 8774 return false; 8775 8776 if (L->FailureKind == ovl_fail_bad_deduction) { 8777 if (R->FailureKind != ovl_fail_bad_deduction) 8778 return true; 8779 8780 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8781 return RankDeductionFailure(L->DeductionFailure) 8782 < RankDeductionFailure(R->DeductionFailure); 8783 } else if (R->FailureKind == ovl_fail_bad_deduction) 8784 return false; 8785 8786 // TODO: others? 8787 } 8788 8789 // Sort everything else by location. 8790 SourceLocation LLoc = GetLocationForCandidate(L); 8791 SourceLocation RLoc = GetLocationForCandidate(R); 8792 8793 // Put candidates without locations (e.g. builtins) at the end. 8794 if (LLoc.isInvalid()) return false; 8795 if (RLoc.isInvalid()) return true; 8796 8797 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8798 } 8799}; 8800 8801/// CompleteNonViableCandidate - Normally, overload resolution only 8802/// computes up to the first. Produces the FixIt set if possible. 8803void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8804 ArrayRef<Expr *> Args) { 8805 assert(!Cand->Viable); 8806 8807 // Don't do anything on failures other than bad conversion. 8808 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8809 8810 // We only want the FixIts if all the arguments can be corrected. 8811 bool Unfixable = false; 8812 // Use a implicit copy initialization to check conversion fixes. 8813 Cand->Fix.setConversionChecker(TryCopyInitialization); 8814 8815 // Skip forward to the first bad conversion. 8816 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8817 unsigned ConvCount = Cand->NumConversions; 8818 while (true) { 8819 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8820 ConvIdx++; 8821 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8822 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8823 break; 8824 } 8825 } 8826 8827 if (ConvIdx == ConvCount) 8828 return; 8829 8830 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8831 "remaining conversion is initialized?"); 8832 8833 // FIXME: this should probably be preserved from the overload 8834 // operation somehow. 8835 bool SuppressUserConversions = false; 8836 8837 const FunctionProtoType* Proto; 8838 unsigned ArgIdx = ConvIdx; 8839 8840 if (Cand->IsSurrogate) { 8841 QualType ConvType 8842 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8843 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8844 ConvType = ConvPtrType->getPointeeType(); 8845 Proto = ConvType->getAs<FunctionProtoType>(); 8846 ArgIdx--; 8847 } else if (Cand->Function) { 8848 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8849 if (isa<CXXMethodDecl>(Cand->Function) && 8850 !isa<CXXConstructorDecl>(Cand->Function)) 8851 ArgIdx--; 8852 } else { 8853 // Builtin binary operator with a bad first conversion. 8854 assert(ConvCount <= 3); 8855 for (; ConvIdx != ConvCount; ++ConvIdx) 8856 Cand->Conversions[ConvIdx] 8857 = TryCopyInitialization(S, Args[ConvIdx], 8858 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8859 SuppressUserConversions, 8860 /*InOverloadResolution*/ true, 8861 /*AllowObjCWritebackConversion=*/ 8862 S.getLangOpts().ObjCAutoRefCount); 8863 return; 8864 } 8865 8866 // Fill in the rest of the conversions. 8867 unsigned NumArgsInProto = Proto->getNumArgs(); 8868 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8869 if (ArgIdx < NumArgsInProto) { 8870 Cand->Conversions[ConvIdx] 8871 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8872 SuppressUserConversions, 8873 /*InOverloadResolution=*/true, 8874 /*AllowObjCWritebackConversion=*/ 8875 S.getLangOpts().ObjCAutoRefCount); 8876 // Store the FixIt in the candidate if it exists. 8877 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8878 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8879 } 8880 else 8881 Cand->Conversions[ConvIdx].setEllipsis(); 8882 } 8883} 8884 8885} // end anonymous namespace 8886 8887/// PrintOverloadCandidates - When overload resolution fails, prints 8888/// diagnostic messages containing the candidates in the candidate 8889/// set. 8890void OverloadCandidateSet::NoteCandidates(Sema &S, 8891 OverloadCandidateDisplayKind OCD, 8892 ArrayRef<Expr *> Args, 8893 StringRef Opc, 8894 SourceLocation OpLoc) { 8895 // Sort the candidates by viability and position. Sorting directly would 8896 // be prohibitive, so we make a set of pointers and sort those. 8897 SmallVector<OverloadCandidate*, 32> Cands; 8898 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8899 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8900 if (Cand->Viable) 8901 Cands.push_back(Cand); 8902 else if (OCD == OCD_AllCandidates) { 8903 CompleteNonViableCandidate(S, Cand, Args); 8904 if (Cand->Function || Cand->IsSurrogate) 8905 Cands.push_back(Cand); 8906 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8907 // want to list every possible builtin candidate. 8908 } 8909 } 8910 8911 std::sort(Cands.begin(), Cands.end(), 8912 CompareOverloadCandidatesForDisplay(S)); 8913 8914 bool ReportedAmbiguousConversions = false; 8915 8916 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8917 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8918 unsigned CandsShown = 0; 8919 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8920 OverloadCandidate *Cand = *I; 8921 8922 // Set an arbitrary limit on the number of candidate functions we'll spam 8923 // the user with. FIXME: This limit should depend on details of the 8924 // candidate list. 8925 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 8926 break; 8927 } 8928 ++CandsShown; 8929 8930 if (Cand->Function) 8931 NoteFunctionCandidate(S, Cand, Args.size()); 8932 else if (Cand->IsSurrogate) 8933 NoteSurrogateCandidate(S, Cand); 8934 else { 8935 assert(Cand->Viable && 8936 "Non-viable built-in candidates are not added to Cands."); 8937 // Generally we only see ambiguities including viable builtin 8938 // operators if overload resolution got screwed up by an 8939 // ambiguous user-defined conversion. 8940 // 8941 // FIXME: It's quite possible for different conversions to see 8942 // different ambiguities, though. 8943 if (!ReportedAmbiguousConversions) { 8944 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8945 ReportedAmbiguousConversions = true; 8946 } 8947 8948 // If this is a viable builtin, print it. 8949 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8950 } 8951 } 8952 8953 if (I != E) 8954 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8955} 8956 8957// [PossiblyAFunctionType] --> [Return] 8958// NonFunctionType --> NonFunctionType 8959// R (A) --> R(A) 8960// R (*)(A) --> R (A) 8961// R (&)(A) --> R (A) 8962// R (S::*)(A) --> R (A) 8963QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8964 QualType Ret = PossiblyAFunctionType; 8965 if (const PointerType *ToTypePtr = 8966 PossiblyAFunctionType->getAs<PointerType>()) 8967 Ret = ToTypePtr->getPointeeType(); 8968 else if (const ReferenceType *ToTypeRef = 8969 PossiblyAFunctionType->getAs<ReferenceType>()) 8970 Ret = ToTypeRef->getPointeeType(); 8971 else if (const MemberPointerType *MemTypePtr = 8972 PossiblyAFunctionType->getAs<MemberPointerType>()) 8973 Ret = MemTypePtr->getPointeeType(); 8974 Ret = 8975 Context.getCanonicalType(Ret).getUnqualifiedType(); 8976 return Ret; 8977} 8978 8979// A helper class to help with address of function resolution 8980// - allows us to avoid passing around all those ugly parameters 8981class AddressOfFunctionResolver 8982{ 8983 Sema& S; 8984 Expr* SourceExpr; 8985 const QualType& TargetType; 8986 QualType TargetFunctionType; // Extracted function type from target type 8987 8988 bool Complain; 8989 //DeclAccessPair& ResultFunctionAccessPair; 8990 ASTContext& Context; 8991 8992 bool TargetTypeIsNonStaticMemberFunction; 8993 bool FoundNonTemplateFunction; 8994 8995 OverloadExpr::FindResult OvlExprInfo; 8996 OverloadExpr *OvlExpr; 8997 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8998 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8999 9000public: 9001 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 9002 const QualType& TargetType, bool Complain) 9003 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9004 Complain(Complain), Context(S.getASTContext()), 9005 TargetTypeIsNonStaticMemberFunction( 9006 !!TargetType->getAs<MemberPointerType>()), 9007 FoundNonTemplateFunction(false), 9008 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9009 OvlExpr(OvlExprInfo.Expression) 9010 { 9011 ExtractUnqualifiedFunctionTypeFromTargetType(); 9012 9013 if (!TargetFunctionType->isFunctionType()) { 9014 if (OvlExpr->hasExplicitTemplateArgs()) { 9015 DeclAccessPair dap; 9016 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 9017 OvlExpr, false, &dap) ) { 9018 9019 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9020 if (!Method->isStatic()) { 9021 // If the target type is a non-function type and the function 9022 // found is a non-static member function, pretend as if that was 9023 // the target, it's the only possible type to end up with. 9024 TargetTypeIsNonStaticMemberFunction = true; 9025 9026 // And skip adding the function if its not in the proper form. 9027 // We'll diagnose this due to an empty set of functions. 9028 if (!OvlExprInfo.HasFormOfMemberPointer) 9029 return; 9030 } 9031 } 9032 9033 Matches.push_back(std::make_pair(dap,Fn)); 9034 } 9035 } 9036 return; 9037 } 9038 9039 if (OvlExpr->hasExplicitTemplateArgs()) 9040 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9041 9042 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9043 // C++ [over.over]p4: 9044 // If more than one function is selected, [...] 9045 if (Matches.size() > 1) { 9046 if (FoundNonTemplateFunction) 9047 EliminateAllTemplateMatches(); 9048 else 9049 EliminateAllExceptMostSpecializedTemplate(); 9050 } 9051 } 9052 } 9053 9054private: 9055 bool isTargetTypeAFunction() const { 9056 return TargetFunctionType->isFunctionType(); 9057 } 9058 9059 // [ToType] [Return] 9060 9061 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9062 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9063 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9064 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9065 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9066 } 9067 9068 // return true if any matching specializations were found 9069 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9070 const DeclAccessPair& CurAccessFunPair) { 9071 if (CXXMethodDecl *Method 9072 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9073 // Skip non-static function templates when converting to pointer, and 9074 // static when converting to member pointer. 9075 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9076 return false; 9077 } 9078 else if (TargetTypeIsNonStaticMemberFunction) 9079 return false; 9080 9081 // C++ [over.over]p2: 9082 // If the name is a function template, template argument deduction is 9083 // done (14.8.2.2), and if the argument deduction succeeds, the 9084 // resulting template argument list is used to generate a single 9085 // function template specialization, which is added to the set of 9086 // overloaded functions considered. 9087 FunctionDecl *Specialization = 0; 9088 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9089 if (Sema::TemplateDeductionResult Result 9090 = S.DeduceTemplateArguments(FunctionTemplate, 9091 &OvlExplicitTemplateArgs, 9092 TargetFunctionType, Specialization, 9093 Info)) { 9094 // FIXME: make a note of the failed deduction for diagnostics. 9095 (void)Result; 9096 return false; 9097 } 9098 9099 // Template argument deduction ensures that we have an exact match. 9100 // This function template specicalization works. 9101 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9102 assert(TargetFunctionType 9103 == Context.getCanonicalType(Specialization->getType())); 9104 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9105 return true; 9106 } 9107 9108 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9109 const DeclAccessPair& CurAccessFunPair) { 9110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9111 // Skip non-static functions when converting to pointer, and static 9112 // when converting to member pointer. 9113 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9114 return false; 9115 } 9116 else if (TargetTypeIsNonStaticMemberFunction) 9117 return false; 9118 9119 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9120 if (S.getLangOpts().CUDA) 9121 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9122 if (S.CheckCUDATarget(Caller, FunDecl)) 9123 return false; 9124 9125 QualType ResultTy; 9126 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9127 FunDecl->getType()) || 9128 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9129 ResultTy)) { 9130 Matches.push_back(std::make_pair(CurAccessFunPair, 9131 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9132 FoundNonTemplateFunction = true; 9133 return true; 9134 } 9135 } 9136 9137 return false; 9138 } 9139 9140 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9141 bool Ret = false; 9142 9143 // If the overload expression doesn't have the form of a pointer to 9144 // member, don't try to convert it to a pointer-to-member type. 9145 if (IsInvalidFormOfPointerToMemberFunction()) 9146 return false; 9147 9148 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9149 E = OvlExpr->decls_end(); 9150 I != E; ++I) { 9151 // Look through any using declarations to find the underlying function. 9152 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9153 9154 // C++ [over.over]p3: 9155 // Non-member functions and static member functions match 9156 // targets of type "pointer-to-function" or "reference-to-function." 9157 // Nonstatic member functions match targets of 9158 // type "pointer-to-member-function." 9159 // Note that according to DR 247, the containing class does not matter. 9160 if (FunctionTemplateDecl *FunctionTemplate 9161 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9162 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9163 Ret = true; 9164 } 9165 // If we have explicit template arguments supplied, skip non-templates. 9166 else if (!OvlExpr->hasExplicitTemplateArgs() && 9167 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9168 Ret = true; 9169 } 9170 assert(Ret || Matches.empty()); 9171 return Ret; 9172 } 9173 9174 void EliminateAllExceptMostSpecializedTemplate() { 9175 // [...] and any given function template specialization F1 is 9176 // eliminated if the set contains a second function template 9177 // specialization whose function template is more specialized 9178 // than the function template of F1 according to the partial 9179 // ordering rules of 14.5.5.2. 9180 9181 // The algorithm specified above is quadratic. We instead use a 9182 // two-pass algorithm (similar to the one used to identify the 9183 // best viable function in an overload set) that identifies the 9184 // best function template (if it exists). 9185 9186 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9187 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9188 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9189 9190 UnresolvedSetIterator Result = 9191 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9192 TPOC_Other, 0, SourceExpr->getLocStart(), 9193 S.PDiag(), 9194 S.PDiag(diag::err_addr_ovl_ambiguous) 9195 << Matches[0].second->getDeclName(), 9196 S.PDiag(diag::note_ovl_candidate) 9197 << (unsigned) oc_function_template, 9198 Complain, TargetFunctionType); 9199 9200 if (Result != MatchesCopy.end()) { 9201 // Make it the first and only element 9202 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9203 Matches[0].second = cast<FunctionDecl>(*Result); 9204 Matches.resize(1); 9205 } 9206 } 9207 9208 void EliminateAllTemplateMatches() { 9209 // [...] any function template specializations in the set are 9210 // eliminated if the set also contains a non-template function, [...] 9211 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9212 if (Matches[I].second->getPrimaryTemplate() == 0) 9213 ++I; 9214 else { 9215 Matches[I] = Matches[--N]; 9216 Matches.set_size(N); 9217 } 9218 } 9219 } 9220 9221public: 9222 void ComplainNoMatchesFound() const { 9223 assert(Matches.empty()); 9224 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9225 << OvlExpr->getName() << TargetFunctionType 9226 << OvlExpr->getSourceRange(); 9227 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9228 } 9229 9230 bool IsInvalidFormOfPointerToMemberFunction() const { 9231 return TargetTypeIsNonStaticMemberFunction && 9232 !OvlExprInfo.HasFormOfMemberPointer; 9233 } 9234 9235 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9236 // TODO: Should we condition this on whether any functions might 9237 // have matched, or is it more appropriate to do that in callers? 9238 // TODO: a fixit wouldn't hurt. 9239 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9240 << TargetType << OvlExpr->getSourceRange(); 9241 } 9242 9243 void ComplainOfInvalidConversion() const { 9244 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9245 << OvlExpr->getName() << TargetType; 9246 } 9247 9248 void ComplainMultipleMatchesFound() const { 9249 assert(Matches.size() > 1); 9250 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9251 << OvlExpr->getName() 9252 << OvlExpr->getSourceRange(); 9253 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9254 } 9255 9256 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9257 9258 int getNumMatches() const { return Matches.size(); } 9259 9260 FunctionDecl* getMatchingFunctionDecl() const { 9261 if (Matches.size() != 1) return 0; 9262 return Matches[0].second; 9263 } 9264 9265 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9266 if (Matches.size() != 1) return 0; 9267 return &Matches[0].first; 9268 } 9269}; 9270 9271/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9272/// an overloaded function (C++ [over.over]), where @p From is an 9273/// expression with overloaded function type and @p ToType is the type 9274/// we're trying to resolve to. For example: 9275/// 9276/// @code 9277/// int f(double); 9278/// int f(int); 9279/// 9280/// int (*pfd)(double) = f; // selects f(double) 9281/// @endcode 9282/// 9283/// This routine returns the resulting FunctionDecl if it could be 9284/// resolved, and NULL otherwise. When @p Complain is true, this 9285/// routine will emit diagnostics if there is an error. 9286FunctionDecl * 9287Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9288 QualType TargetType, 9289 bool Complain, 9290 DeclAccessPair &FoundResult, 9291 bool *pHadMultipleCandidates) { 9292 assert(AddressOfExpr->getType() == Context.OverloadTy); 9293 9294 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9295 Complain); 9296 int NumMatches = Resolver.getNumMatches(); 9297 FunctionDecl* Fn = 0; 9298 if (NumMatches == 0 && Complain) { 9299 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9300 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9301 else 9302 Resolver.ComplainNoMatchesFound(); 9303 } 9304 else if (NumMatches > 1 && Complain) 9305 Resolver.ComplainMultipleMatchesFound(); 9306 else if (NumMatches == 1) { 9307 Fn = Resolver.getMatchingFunctionDecl(); 9308 assert(Fn); 9309 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9310 if (Complain) 9311 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9312 } 9313 9314 if (pHadMultipleCandidates) 9315 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9316 return Fn; 9317} 9318 9319/// \brief Given an expression that refers to an overloaded function, try to 9320/// resolve that overloaded function expression down to a single function. 9321/// 9322/// This routine can only resolve template-ids that refer to a single function 9323/// template, where that template-id refers to a single template whose template 9324/// arguments are either provided by the template-id or have defaults, 9325/// as described in C++0x [temp.arg.explicit]p3. 9326FunctionDecl * 9327Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9328 bool Complain, 9329 DeclAccessPair *FoundResult) { 9330 // C++ [over.over]p1: 9331 // [...] [Note: any redundant set of parentheses surrounding the 9332 // overloaded function name is ignored (5.1). ] 9333 // C++ [over.over]p1: 9334 // [...] The overloaded function name can be preceded by the & 9335 // operator. 9336 9337 // If we didn't actually find any template-ids, we're done. 9338 if (!ovl->hasExplicitTemplateArgs()) 9339 return 0; 9340 9341 TemplateArgumentListInfo ExplicitTemplateArgs; 9342 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9343 9344 // Look through all of the overloaded functions, searching for one 9345 // whose type matches exactly. 9346 FunctionDecl *Matched = 0; 9347 for (UnresolvedSetIterator I = ovl->decls_begin(), 9348 E = ovl->decls_end(); I != E; ++I) { 9349 // C++0x [temp.arg.explicit]p3: 9350 // [...] In contexts where deduction is done and fails, or in contexts 9351 // where deduction is not done, if a template argument list is 9352 // specified and it, along with any default template arguments, 9353 // identifies a single function template specialization, then the 9354 // template-id is an lvalue for the function template specialization. 9355 FunctionTemplateDecl *FunctionTemplate 9356 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9357 9358 // C++ [over.over]p2: 9359 // If the name is a function template, template argument deduction is 9360 // done (14.8.2.2), and if the argument deduction succeeds, the 9361 // resulting template argument list is used to generate a single 9362 // function template specialization, which is added to the set of 9363 // overloaded functions considered. 9364 FunctionDecl *Specialization = 0; 9365 TemplateDeductionInfo Info(ovl->getNameLoc()); 9366 if (TemplateDeductionResult Result 9367 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9368 Specialization, Info)) { 9369 // FIXME: make a note of the failed deduction for diagnostics. 9370 (void)Result; 9371 continue; 9372 } 9373 9374 assert(Specialization && "no specialization and no error?"); 9375 9376 // Multiple matches; we can't resolve to a single declaration. 9377 if (Matched) { 9378 if (Complain) { 9379 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9380 << ovl->getName(); 9381 NoteAllOverloadCandidates(ovl); 9382 } 9383 return 0; 9384 } 9385 9386 Matched = Specialization; 9387 if (FoundResult) *FoundResult = I.getPair(); 9388 } 9389 9390 return Matched; 9391} 9392 9393 9394 9395 9396// Resolve and fix an overloaded expression that can be resolved 9397// because it identifies a single function template specialization. 9398// 9399// Last three arguments should only be supplied if Complain = true 9400// 9401// Return true if it was logically possible to so resolve the 9402// expression, regardless of whether or not it succeeded. Always 9403// returns true if 'complain' is set. 9404bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9405 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9406 bool complain, const SourceRange& OpRangeForComplaining, 9407 QualType DestTypeForComplaining, 9408 unsigned DiagIDForComplaining) { 9409 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9410 9411 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9412 9413 DeclAccessPair found; 9414 ExprResult SingleFunctionExpression; 9415 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9416 ovl.Expression, /*complain*/ false, &found)) { 9417 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9418 SrcExpr = ExprError(); 9419 return true; 9420 } 9421 9422 // It is only correct to resolve to an instance method if we're 9423 // resolving a form that's permitted to be a pointer to member. 9424 // Otherwise we'll end up making a bound member expression, which 9425 // is illegal in all the contexts we resolve like this. 9426 if (!ovl.HasFormOfMemberPointer && 9427 isa<CXXMethodDecl>(fn) && 9428 cast<CXXMethodDecl>(fn)->isInstance()) { 9429 if (!complain) return false; 9430 9431 Diag(ovl.Expression->getExprLoc(), 9432 diag::err_bound_member_function) 9433 << 0 << ovl.Expression->getSourceRange(); 9434 9435 // TODO: I believe we only end up here if there's a mix of 9436 // static and non-static candidates (otherwise the expression 9437 // would have 'bound member' type, not 'overload' type). 9438 // Ideally we would note which candidate was chosen and why 9439 // the static candidates were rejected. 9440 SrcExpr = ExprError(); 9441 return true; 9442 } 9443 9444 // Fix the expression to refer to 'fn'. 9445 SingleFunctionExpression = 9446 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9447 9448 // If desired, do function-to-pointer decay. 9449 if (doFunctionPointerConverion) { 9450 SingleFunctionExpression = 9451 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9452 if (SingleFunctionExpression.isInvalid()) { 9453 SrcExpr = ExprError(); 9454 return true; 9455 } 9456 } 9457 } 9458 9459 if (!SingleFunctionExpression.isUsable()) { 9460 if (complain) { 9461 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9462 << ovl.Expression->getName() 9463 << DestTypeForComplaining 9464 << OpRangeForComplaining 9465 << ovl.Expression->getQualifierLoc().getSourceRange(); 9466 NoteAllOverloadCandidates(SrcExpr.get()); 9467 9468 SrcExpr = ExprError(); 9469 return true; 9470 } 9471 9472 return false; 9473 } 9474 9475 SrcExpr = SingleFunctionExpression; 9476 return true; 9477} 9478 9479/// \brief Add a single candidate to the overload set. 9480static void AddOverloadedCallCandidate(Sema &S, 9481 DeclAccessPair FoundDecl, 9482 TemplateArgumentListInfo *ExplicitTemplateArgs, 9483 ArrayRef<Expr *> Args, 9484 OverloadCandidateSet &CandidateSet, 9485 bool PartialOverloading, 9486 bool KnownValid) { 9487 NamedDecl *Callee = FoundDecl.getDecl(); 9488 if (isa<UsingShadowDecl>(Callee)) 9489 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9490 9491 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9492 if (ExplicitTemplateArgs) { 9493 assert(!KnownValid && "Explicit template arguments?"); 9494 return; 9495 } 9496 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9497 PartialOverloading); 9498 return; 9499 } 9500 9501 if (FunctionTemplateDecl *FuncTemplate 9502 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9503 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9504 ExplicitTemplateArgs, Args, CandidateSet); 9505 return; 9506 } 9507 9508 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9509} 9510 9511/// \brief Add the overload candidates named by callee and/or found by argument 9512/// dependent lookup to the given overload set. 9513void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9514 ArrayRef<Expr *> Args, 9515 OverloadCandidateSet &CandidateSet, 9516 bool PartialOverloading) { 9517 9518#ifndef NDEBUG 9519 // Verify that ArgumentDependentLookup is consistent with the rules 9520 // in C++0x [basic.lookup.argdep]p3: 9521 // 9522 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9523 // and let Y be the lookup set produced by argument dependent 9524 // lookup (defined as follows). If X contains 9525 // 9526 // -- a declaration of a class member, or 9527 // 9528 // -- a block-scope function declaration that is not a 9529 // using-declaration, or 9530 // 9531 // -- a declaration that is neither a function or a function 9532 // template 9533 // 9534 // then Y is empty. 9535 9536 if (ULE->requiresADL()) { 9537 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9538 E = ULE->decls_end(); I != E; ++I) { 9539 assert(!(*I)->getDeclContext()->isRecord()); 9540 assert(isa<UsingShadowDecl>(*I) || 9541 !(*I)->getDeclContext()->isFunctionOrMethod()); 9542 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9543 } 9544 } 9545#endif 9546 9547 // It would be nice to avoid this copy. 9548 TemplateArgumentListInfo TABuffer; 9549 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9550 if (ULE->hasExplicitTemplateArgs()) { 9551 ULE->copyTemplateArgumentsInto(TABuffer); 9552 ExplicitTemplateArgs = &TABuffer; 9553 } 9554 9555 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9556 E = ULE->decls_end(); I != E; ++I) 9557 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9558 CandidateSet, PartialOverloading, 9559 /*KnownValid*/ true); 9560 9561 if (ULE->requiresADL()) 9562 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9563 ULE->getExprLoc(), 9564 Args, ExplicitTemplateArgs, 9565 CandidateSet, PartialOverloading); 9566} 9567 9568/// Attempt to recover from an ill-formed use of a non-dependent name in a 9569/// template, where the non-dependent name was declared after the template 9570/// was defined. This is common in code written for a compilers which do not 9571/// correctly implement two-stage name lookup. 9572/// 9573/// Returns true if a viable candidate was found and a diagnostic was issued. 9574static bool 9575DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9576 const CXXScopeSpec &SS, LookupResult &R, 9577 TemplateArgumentListInfo *ExplicitTemplateArgs, 9578 ArrayRef<Expr *> Args) { 9579 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9580 return false; 9581 9582 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9583 if (DC->isTransparentContext()) 9584 continue; 9585 9586 SemaRef.LookupQualifiedName(R, DC); 9587 9588 if (!R.empty()) { 9589 R.suppressDiagnostics(); 9590 9591 if (isa<CXXRecordDecl>(DC)) { 9592 // Don't diagnose names we find in classes; we get much better 9593 // diagnostics for these from DiagnoseEmptyLookup. 9594 R.clear(); 9595 return false; 9596 } 9597 9598 OverloadCandidateSet Candidates(FnLoc); 9599 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9600 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9601 ExplicitTemplateArgs, Args, 9602 Candidates, false, /*KnownValid*/ false); 9603 9604 OverloadCandidateSet::iterator Best; 9605 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9606 // No viable functions. Don't bother the user with notes for functions 9607 // which don't work and shouldn't be found anyway. 9608 R.clear(); 9609 return false; 9610 } 9611 9612 // Find the namespaces where ADL would have looked, and suggest 9613 // declaring the function there instead. 9614 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9615 Sema::AssociatedClassSet AssociatedClasses; 9616 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9617 AssociatedNamespaces, 9618 AssociatedClasses); 9619 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9620 DeclContext *Std = SemaRef.getStdNamespace(); 9621 for (Sema::AssociatedNamespaceSet::iterator 9622 it = AssociatedNamespaces.begin(), 9623 end = AssociatedNamespaces.end(); it != end; ++it) { 9624 // Never suggest declaring a function within namespace 'std'. 9625 if (Std && Std->Encloses(*it)) 9626 continue; 9627 9628 // Never suggest declaring a function within a namespace with a reserved 9629 // name, like __gnu_cxx. 9630 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9631 if (NS && 9632 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9633 continue; 9634 9635 SuggestedNamespaces.insert(*it); 9636 } 9637 9638 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9639 << R.getLookupName(); 9640 if (SuggestedNamespaces.empty()) { 9641 SemaRef.Diag(Best->Function->getLocation(), 9642 diag::note_not_found_by_two_phase_lookup) 9643 << R.getLookupName() << 0; 9644 } else if (SuggestedNamespaces.size() == 1) { 9645 SemaRef.Diag(Best->Function->getLocation(), 9646 diag::note_not_found_by_two_phase_lookup) 9647 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9648 } else { 9649 // FIXME: It would be useful to list the associated namespaces here, 9650 // but the diagnostics infrastructure doesn't provide a way to produce 9651 // a localized representation of a list of items. 9652 SemaRef.Diag(Best->Function->getLocation(), 9653 diag::note_not_found_by_two_phase_lookup) 9654 << R.getLookupName() << 2; 9655 } 9656 9657 // Try to recover by calling this function. 9658 return true; 9659 } 9660 9661 R.clear(); 9662 } 9663 9664 return false; 9665} 9666 9667/// Attempt to recover from ill-formed use of a non-dependent operator in a 9668/// template, where the non-dependent operator was declared after the template 9669/// was defined. 9670/// 9671/// Returns true if a viable candidate was found and a diagnostic was issued. 9672static bool 9673DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9674 SourceLocation OpLoc, 9675 ArrayRef<Expr *> Args) { 9676 DeclarationName OpName = 9677 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9678 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9679 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9680 /*ExplicitTemplateArgs=*/0, Args); 9681} 9682 9683namespace { 9684// Callback to limit the allowed keywords and to only accept typo corrections 9685// that are keywords or whose decls refer to functions (or template functions) 9686// that accept the given number of arguments. 9687class RecoveryCallCCC : public CorrectionCandidateCallback { 9688 public: 9689 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9690 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9691 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9692 WantRemainingKeywords = false; 9693 } 9694 9695 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9696 if (!candidate.getCorrectionDecl()) 9697 return candidate.isKeyword(); 9698 9699 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9700 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9701 FunctionDecl *FD = 0; 9702 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9703 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9704 FD = FTD->getTemplatedDecl(); 9705 if (!HasExplicitTemplateArgs && !FD) { 9706 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9707 // If the Decl is neither a function nor a template function, 9708 // determine if it is a pointer or reference to a function. If so, 9709 // check against the number of arguments expected for the pointee. 9710 QualType ValType = cast<ValueDecl>(ND)->getType(); 9711 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9712 ValType = ValType->getPointeeType(); 9713 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9714 if (FPT->getNumArgs() == NumArgs) 9715 return true; 9716 } 9717 } 9718 if (FD && FD->getNumParams() >= NumArgs && 9719 FD->getMinRequiredArguments() <= NumArgs) 9720 return true; 9721 } 9722 return false; 9723 } 9724 9725 private: 9726 unsigned NumArgs; 9727 bool HasExplicitTemplateArgs; 9728}; 9729 9730// Callback that effectively disabled typo correction 9731class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9732 public: 9733 NoTypoCorrectionCCC() { 9734 WantTypeSpecifiers = false; 9735 WantExpressionKeywords = false; 9736 WantCXXNamedCasts = false; 9737 WantRemainingKeywords = false; 9738 } 9739 9740 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9741 return false; 9742 } 9743}; 9744 9745class BuildRecoveryCallExprRAII { 9746 Sema &SemaRef; 9747public: 9748 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9749 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9750 SemaRef.IsBuildingRecoveryCallExpr = true; 9751 } 9752 9753 ~BuildRecoveryCallExprRAII() { 9754 SemaRef.IsBuildingRecoveryCallExpr = false; 9755 } 9756}; 9757 9758} 9759 9760/// Attempts to recover from a call where no functions were found. 9761/// 9762/// Returns true if new candidates were found. 9763static ExprResult 9764BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9765 UnresolvedLookupExpr *ULE, 9766 SourceLocation LParenLoc, 9767 llvm::MutableArrayRef<Expr *> Args, 9768 SourceLocation RParenLoc, 9769 bool EmptyLookup, bool AllowTypoCorrection) { 9770 // Do not try to recover if it is already building a recovery call. 9771 // This stops infinite loops for template instantiations like 9772 // 9773 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9774 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9775 // 9776 if (SemaRef.IsBuildingRecoveryCallExpr) 9777 return ExprError(); 9778 BuildRecoveryCallExprRAII RCE(SemaRef); 9779 9780 CXXScopeSpec SS; 9781 SS.Adopt(ULE->getQualifierLoc()); 9782 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9783 9784 TemplateArgumentListInfo TABuffer; 9785 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9786 if (ULE->hasExplicitTemplateArgs()) { 9787 ULE->copyTemplateArgumentsInto(TABuffer); 9788 ExplicitTemplateArgs = &TABuffer; 9789 } 9790 9791 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9792 Sema::LookupOrdinaryName); 9793 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9794 NoTypoCorrectionCCC RejectAll; 9795 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9796 (CorrectionCandidateCallback*)&Validator : 9797 (CorrectionCandidateCallback*)&RejectAll; 9798 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9799 ExplicitTemplateArgs, Args) && 9800 (!EmptyLookup || 9801 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9802 ExplicitTemplateArgs, Args))) 9803 return ExprError(); 9804 9805 assert(!R.empty() && "lookup results empty despite recovery"); 9806 9807 // Build an implicit member call if appropriate. Just drop the 9808 // casts and such from the call, we don't really care. 9809 ExprResult NewFn = ExprError(); 9810 if ((*R.begin())->isCXXClassMember()) 9811 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9812 R, ExplicitTemplateArgs); 9813 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9814 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9815 ExplicitTemplateArgs); 9816 else 9817 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9818 9819 if (NewFn.isInvalid()) 9820 return ExprError(); 9821 9822 // This shouldn't cause an infinite loop because we're giving it 9823 // an expression with viable lookup results, which should never 9824 // end up here. 9825 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9826 MultiExprArg(Args.data(), Args.size()), 9827 RParenLoc); 9828} 9829 9830/// \brief Constructs and populates an OverloadedCandidateSet from 9831/// the given function. 9832/// \returns true when an the ExprResult output parameter has been set. 9833bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9834 UnresolvedLookupExpr *ULE, 9835 Expr **Args, unsigned NumArgs, 9836 SourceLocation RParenLoc, 9837 OverloadCandidateSet *CandidateSet, 9838 ExprResult *Result) { 9839#ifndef NDEBUG 9840 if (ULE->requiresADL()) { 9841 // To do ADL, we must have found an unqualified name. 9842 assert(!ULE->getQualifier() && "qualified name with ADL"); 9843 9844 // We don't perform ADL for implicit declarations of builtins. 9845 // Verify that this was correctly set up. 9846 FunctionDecl *F; 9847 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9848 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9849 F->getBuiltinID() && F->isImplicit()) 9850 llvm_unreachable("performing ADL for builtin"); 9851 9852 // We don't perform ADL in C. 9853 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9854 } 9855#endif 9856 9857 UnbridgedCastsSet UnbridgedCasts; 9858 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9859 *Result = ExprError(); 9860 return true; 9861 } 9862 9863 // Add the functions denoted by the callee to the set of candidate 9864 // functions, including those from argument-dependent lookup. 9865 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9866 *CandidateSet); 9867 9868 // If we found nothing, try to recover. 9869 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9870 // out if it fails. 9871 if (CandidateSet->empty()) { 9872 // In Microsoft mode, if we are inside a template class member function then 9873 // create a type dependent CallExpr. The goal is to postpone name lookup 9874 // to instantiation time to be able to search into type dependent base 9875 // classes. 9876 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9877 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9878 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9879 llvm::makeArrayRef(Args, NumArgs), 9880 Context.DependentTy, VK_RValue, 9881 RParenLoc); 9882 CE->setTypeDependent(true); 9883 *Result = Owned(CE); 9884 return true; 9885 } 9886 return false; 9887 } 9888 9889 UnbridgedCasts.restore(); 9890 return false; 9891} 9892 9893/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9894/// the completed call expression. If overload resolution fails, emits 9895/// diagnostics and returns ExprError() 9896static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9897 UnresolvedLookupExpr *ULE, 9898 SourceLocation LParenLoc, 9899 Expr **Args, unsigned NumArgs, 9900 SourceLocation RParenLoc, 9901 Expr *ExecConfig, 9902 OverloadCandidateSet *CandidateSet, 9903 OverloadCandidateSet::iterator *Best, 9904 OverloadingResult OverloadResult, 9905 bool AllowTypoCorrection) { 9906 if (CandidateSet->empty()) 9907 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9908 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9909 RParenLoc, /*EmptyLookup=*/true, 9910 AllowTypoCorrection); 9911 9912 switch (OverloadResult) { 9913 case OR_Success: { 9914 FunctionDecl *FDecl = (*Best)->Function; 9915 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9916 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9917 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9918 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9919 RParenLoc, ExecConfig); 9920 } 9921 9922 case OR_No_Viable_Function: { 9923 // Try to recover by looking for viable functions which the user might 9924 // have meant to call. 9925 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9926 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9927 RParenLoc, 9928 /*EmptyLookup=*/false, 9929 AllowTypoCorrection); 9930 if (!Recovery.isInvalid()) 9931 return Recovery; 9932 9933 SemaRef.Diag(Fn->getLocStart(), 9934 diag::err_ovl_no_viable_function_in_call) 9935 << ULE->getName() << Fn->getSourceRange(); 9936 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9937 llvm::makeArrayRef(Args, NumArgs)); 9938 break; 9939 } 9940 9941 case OR_Ambiguous: 9942 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9943 << ULE->getName() << Fn->getSourceRange(); 9944 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9945 llvm::makeArrayRef(Args, NumArgs)); 9946 break; 9947 9948 case OR_Deleted: { 9949 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9950 << (*Best)->Function->isDeleted() 9951 << ULE->getName() 9952 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9953 << Fn->getSourceRange(); 9954 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9955 llvm::makeArrayRef(Args, NumArgs)); 9956 9957 // We emitted an error for the unvailable/deleted function call but keep 9958 // the call in the AST. 9959 FunctionDecl *FDecl = (*Best)->Function; 9960 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9961 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9962 RParenLoc, ExecConfig); 9963 } 9964 } 9965 9966 // Overload resolution failed. 9967 return ExprError(); 9968} 9969 9970/// BuildOverloadedCallExpr - Given the call expression that calls Fn 9971/// (which eventually refers to the declaration Func) and the call 9972/// arguments Args/NumArgs, attempt to resolve the function call down 9973/// to a specific function. If overload resolution succeeds, returns 9974/// the call expression produced by overload resolution. 9975/// Otherwise, emits diagnostics and returns ExprError. 9976ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9977 UnresolvedLookupExpr *ULE, 9978 SourceLocation LParenLoc, 9979 Expr **Args, unsigned NumArgs, 9980 SourceLocation RParenLoc, 9981 Expr *ExecConfig, 9982 bool AllowTypoCorrection) { 9983 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9984 ExprResult result; 9985 9986 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9987 &CandidateSet, &result)) 9988 return result; 9989 9990 OverloadCandidateSet::iterator Best; 9991 OverloadingResult OverloadResult = 9992 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9993 9994 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9995 RParenLoc, ExecConfig, &CandidateSet, 9996 &Best, OverloadResult, 9997 AllowTypoCorrection); 9998} 9999 10000static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10001 return Functions.size() > 1 || 10002 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10003} 10004 10005/// \brief Create a unary operation that may resolve to an overloaded 10006/// operator. 10007/// 10008/// \param OpLoc The location of the operator itself (e.g., '*'). 10009/// 10010/// \param OpcIn The UnaryOperator::Opcode that describes this 10011/// operator. 10012/// 10013/// \param Fns The set of non-member functions that will be 10014/// considered by overload resolution. The caller needs to build this 10015/// set based on the context using, e.g., 10016/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10017/// set should not contain any member functions; those will be added 10018/// by CreateOverloadedUnaryOp(). 10019/// 10020/// \param Input The input argument. 10021ExprResult 10022Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10023 const UnresolvedSetImpl &Fns, 10024 Expr *Input) { 10025 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10026 10027 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10028 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10029 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10030 // TODO: provide better source location info. 10031 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10032 10033 if (checkPlaceholderForOverload(*this, Input)) 10034 return ExprError(); 10035 10036 Expr *Args[2] = { Input, 0 }; 10037 unsigned NumArgs = 1; 10038 10039 // For post-increment and post-decrement, add the implicit '0' as 10040 // the second argument, so that we know this is a post-increment or 10041 // post-decrement. 10042 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10043 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10044 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10045 SourceLocation()); 10046 NumArgs = 2; 10047 } 10048 10049 if (Input->isTypeDependent()) { 10050 if (Fns.empty()) 10051 return Owned(new (Context) UnaryOperator(Input, 10052 Opc, 10053 Context.DependentTy, 10054 VK_RValue, OK_Ordinary, 10055 OpLoc)); 10056 10057 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10058 UnresolvedLookupExpr *Fn 10059 = UnresolvedLookupExpr::Create(Context, NamingClass, 10060 NestedNameSpecifierLoc(), OpNameInfo, 10061 /*ADL*/ true, IsOverloaded(Fns), 10062 Fns.begin(), Fns.end()); 10063 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10064 llvm::makeArrayRef(Args, NumArgs), 10065 Context.DependentTy, 10066 VK_RValue, 10067 OpLoc, false)); 10068 } 10069 10070 // Build an empty overload set. 10071 OverloadCandidateSet CandidateSet(OpLoc); 10072 10073 // Add the candidates from the given function set. 10074 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10075 false); 10076 10077 // Add operator candidates that are member functions. 10078 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10079 10080 // Add candidates from ADL. 10081 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10082 OpLoc, llvm::makeArrayRef(Args, NumArgs), 10083 /*ExplicitTemplateArgs*/ 0, 10084 CandidateSet); 10085 10086 // Add builtin operator candidates. 10087 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10088 10089 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10090 10091 // Perform overload resolution. 10092 OverloadCandidateSet::iterator Best; 10093 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10094 case OR_Success: { 10095 // We found a built-in operator or an overloaded operator. 10096 FunctionDecl *FnDecl = Best->Function; 10097 10098 if (FnDecl) { 10099 // We matched an overloaded operator. Build a call to that 10100 // operator. 10101 10102 // Convert the arguments. 10103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10104 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10105 10106 ExprResult InputRes = 10107 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10108 Best->FoundDecl, Method); 10109 if (InputRes.isInvalid()) 10110 return ExprError(); 10111 Input = InputRes.take(); 10112 } else { 10113 // Convert the arguments. 10114 ExprResult InputInit 10115 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10116 Context, 10117 FnDecl->getParamDecl(0)), 10118 SourceLocation(), 10119 Input); 10120 if (InputInit.isInvalid()) 10121 return ExprError(); 10122 Input = InputInit.take(); 10123 } 10124 10125 // Determine the result type. 10126 QualType ResultTy = FnDecl->getResultType(); 10127 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10128 ResultTy = ResultTy.getNonLValueExprType(Context); 10129 10130 // Build the actual expression node. 10131 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10132 HadMultipleCandidates, OpLoc); 10133 if (FnExpr.isInvalid()) 10134 return ExprError(); 10135 10136 Args[0] = Input; 10137 CallExpr *TheCall = 10138 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10139 llvm::makeArrayRef(Args, NumArgs), 10140 ResultTy, VK, OpLoc, false); 10141 10142 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10143 FnDecl)) 10144 return ExprError(); 10145 10146 return MaybeBindToTemporary(TheCall); 10147 } else { 10148 // We matched a built-in operator. Convert the arguments, then 10149 // break out so that we will build the appropriate built-in 10150 // operator node. 10151 ExprResult InputRes = 10152 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10153 Best->Conversions[0], AA_Passing); 10154 if (InputRes.isInvalid()) 10155 return ExprError(); 10156 Input = InputRes.take(); 10157 break; 10158 } 10159 } 10160 10161 case OR_No_Viable_Function: 10162 // This is an erroneous use of an operator which can be overloaded by 10163 // a non-member function. Check for non-member operators which were 10164 // defined too late to be candidates. 10165 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10166 llvm::makeArrayRef(Args, NumArgs))) 10167 // FIXME: Recover by calling the found function. 10168 return ExprError(); 10169 10170 // No viable function; fall through to handling this as a 10171 // built-in operator, which will produce an error message for us. 10172 break; 10173 10174 case OR_Ambiguous: 10175 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10176 << UnaryOperator::getOpcodeStr(Opc) 10177 << Input->getType() 10178 << Input->getSourceRange(); 10179 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10180 llvm::makeArrayRef(Args, NumArgs), 10181 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10182 return ExprError(); 10183 10184 case OR_Deleted: 10185 Diag(OpLoc, diag::err_ovl_deleted_oper) 10186 << Best->Function->isDeleted() 10187 << UnaryOperator::getOpcodeStr(Opc) 10188 << getDeletedOrUnavailableSuffix(Best->Function) 10189 << Input->getSourceRange(); 10190 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10191 llvm::makeArrayRef(Args, NumArgs), 10192 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10193 return ExprError(); 10194 } 10195 10196 // Either we found no viable overloaded operator or we matched a 10197 // built-in operator. In either case, fall through to trying to 10198 // build a built-in operation. 10199 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10200} 10201 10202/// \brief Create a binary operation that may resolve to an overloaded 10203/// operator. 10204/// 10205/// \param OpLoc The location of the operator itself (e.g., '+'). 10206/// 10207/// \param OpcIn The BinaryOperator::Opcode that describes this 10208/// operator. 10209/// 10210/// \param Fns The set of non-member functions that will be 10211/// considered by overload resolution. The caller needs to build this 10212/// set based on the context using, e.g., 10213/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10214/// set should not contain any member functions; those will be added 10215/// by CreateOverloadedBinOp(). 10216/// 10217/// \param LHS Left-hand argument. 10218/// \param RHS Right-hand argument. 10219ExprResult 10220Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10221 unsigned OpcIn, 10222 const UnresolvedSetImpl &Fns, 10223 Expr *LHS, Expr *RHS) { 10224 Expr *Args[2] = { LHS, RHS }; 10225 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10226 10227 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10228 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10229 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10230 10231 // If either side is type-dependent, create an appropriate dependent 10232 // expression. 10233 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10234 if (Fns.empty()) { 10235 // If there are no functions to store, just build a dependent 10236 // BinaryOperator or CompoundAssignment. 10237 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10238 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10239 Context.DependentTy, 10240 VK_RValue, OK_Ordinary, 10241 OpLoc, 10242 FPFeatures.fp_contract)); 10243 10244 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10245 Context.DependentTy, 10246 VK_LValue, 10247 OK_Ordinary, 10248 Context.DependentTy, 10249 Context.DependentTy, 10250 OpLoc, 10251 FPFeatures.fp_contract)); 10252 } 10253 10254 // FIXME: save results of ADL from here? 10255 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10256 // TODO: provide better source location info in DNLoc component. 10257 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10258 UnresolvedLookupExpr *Fn 10259 = UnresolvedLookupExpr::Create(Context, NamingClass, 10260 NestedNameSpecifierLoc(), OpNameInfo, 10261 /*ADL*/ true, IsOverloaded(Fns), 10262 Fns.begin(), Fns.end()); 10263 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10264 Context.DependentTy, VK_RValue, 10265 OpLoc, FPFeatures.fp_contract)); 10266 } 10267 10268 // Always do placeholder-like conversions on the RHS. 10269 if (checkPlaceholderForOverload(*this, Args[1])) 10270 return ExprError(); 10271 10272 // Do placeholder-like conversion on the LHS; note that we should 10273 // not get here with a PseudoObject LHS. 10274 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10275 if (checkPlaceholderForOverload(*this, Args[0])) 10276 return ExprError(); 10277 10278 // If this is the assignment operator, we only perform overload resolution 10279 // if the left-hand side is a class or enumeration type. This is actually 10280 // a hack. The standard requires that we do overload resolution between the 10281 // various built-in candidates, but as DR507 points out, this can lead to 10282 // problems. So we do it this way, which pretty much follows what GCC does. 10283 // Note that we go the traditional code path for compound assignment forms. 10284 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10285 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10286 10287 // If this is the .* operator, which is not overloadable, just 10288 // create a built-in binary operator. 10289 if (Opc == BO_PtrMemD) 10290 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10291 10292 // Build an empty overload set. 10293 OverloadCandidateSet CandidateSet(OpLoc); 10294 10295 // Add the candidates from the given function set. 10296 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10297 10298 // Add operator candidates that are member functions. 10299 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10300 10301 // Add candidates from ADL. 10302 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10303 OpLoc, Args, 10304 /*ExplicitTemplateArgs*/ 0, 10305 CandidateSet); 10306 10307 // Add builtin operator candidates. 10308 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10309 10310 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10311 10312 // Perform overload resolution. 10313 OverloadCandidateSet::iterator Best; 10314 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10315 case OR_Success: { 10316 // We found a built-in operator or an overloaded operator. 10317 FunctionDecl *FnDecl = Best->Function; 10318 10319 if (FnDecl) { 10320 // We matched an overloaded operator. Build a call to that 10321 // operator. 10322 10323 // Convert the arguments. 10324 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10325 // Best->Access is only meaningful for class members. 10326 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10327 10328 ExprResult Arg1 = 10329 PerformCopyInitialization( 10330 InitializedEntity::InitializeParameter(Context, 10331 FnDecl->getParamDecl(0)), 10332 SourceLocation(), Owned(Args[1])); 10333 if (Arg1.isInvalid()) 10334 return ExprError(); 10335 10336 ExprResult Arg0 = 10337 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10338 Best->FoundDecl, Method); 10339 if (Arg0.isInvalid()) 10340 return ExprError(); 10341 Args[0] = Arg0.takeAs<Expr>(); 10342 Args[1] = RHS = Arg1.takeAs<Expr>(); 10343 } else { 10344 // Convert the arguments. 10345 ExprResult Arg0 = PerformCopyInitialization( 10346 InitializedEntity::InitializeParameter(Context, 10347 FnDecl->getParamDecl(0)), 10348 SourceLocation(), Owned(Args[0])); 10349 if (Arg0.isInvalid()) 10350 return ExprError(); 10351 10352 ExprResult Arg1 = 10353 PerformCopyInitialization( 10354 InitializedEntity::InitializeParameter(Context, 10355 FnDecl->getParamDecl(1)), 10356 SourceLocation(), Owned(Args[1])); 10357 if (Arg1.isInvalid()) 10358 return ExprError(); 10359 Args[0] = LHS = Arg0.takeAs<Expr>(); 10360 Args[1] = RHS = Arg1.takeAs<Expr>(); 10361 } 10362 10363 // Determine the result type. 10364 QualType ResultTy = FnDecl->getResultType(); 10365 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10366 ResultTy = ResultTy.getNonLValueExprType(Context); 10367 10368 // Build the actual expression node. 10369 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10370 Best->FoundDecl, 10371 HadMultipleCandidates, OpLoc); 10372 if (FnExpr.isInvalid()) 10373 return ExprError(); 10374 10375 CXXOperatorCallExpr *TheCall = 10376 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10377 Args, ResultTy, VK, OpLoc, 10378 FPFeatures.fp_contract); 10379 10380 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10381 FnDecl)) 10382 return ExprError(); 10383 10384 ArrayRef<const Expr *> ArgsArray(Args, 2); 10385 // Cut off the implicit 'this'. 10386 if (isa<CXXMethodDecl>(FnDecl)) 10387 ArgsArray = ArgsArray.slice(1); 10388 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10389 TheCall->getSourceRange(), VariadicDoesNotApply); 10390 10391 return MaybeBindToTemporary(TheCall); 10392 } else { 10393 // We matched a built-in operator. Convert the arguments, then 10394 // break out so that we will build the appropriate built-in 10395 // operator node. 10396 ExprResult ArgsRes0 = 10397 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10398 Best->Conversions[0], AA_Passing); 10399 if (ArgsRes0.isInvalid()) 10400 return ExprError(); 10401 Args[0] = ArgsRes0.take(); 10402 10403 ExprResult ArgsRes1 = 10404 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10405 Best->Conversions[1], AA_Passing); 10406 if (ArgsRes1.isInvalid()) 10407 return ExprError(); 10408 Args[1] = ArgsRes1.take(); 10409 break; 10410 } 10411 } 10412 10413 case OR_No_Viable_Function: { 10414 // C++ [over.match.oper]p9: 10415 // If the operator is the operator , [...] and there are no 10416 // viable functions, then the operator is assumed to be the 10417 // built-in operator and interpreted according to clause 5. 10418 if (Opc == BO_Comma) 10419 break; 10420 10421 // For class as left operand for assignment or compound assigment 10422 // operator do not fall through to handling in built-in, but report that 10423 // no overloaded assignment operator found 10424 ExprResult Result = ExprError(); 10425 if (Args[0]->getType()->isRecordType() && 10426 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10427 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10428 << BinaryOperator::getOpcodeStr(Opc) 10429 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10430 } else { 10431 // This is an erroneous use of an operator which can be overloaded by 10432 // a non-member function. Check for non-member operators which were 10433 // defined too late to be candidates. 10434 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10435 // FIXME: Recover by calling the found function. 10436 return ExprError(); 10437 10438 // No viable function; try to create a built-in operation, which will 10439 // produce an error. Then, show the non-viable candidates. 10440 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10441 } 10442 assert(Result.isInvalid() && 10443 "C++ binary operator overloading is missing candidates!"); 10444 if (Result.isInvalid()) 10445 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10446 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10447 return Result; 10448 } 10449 10450 case OR_Ambiguous: 10451 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10452 << BinaryOperator::getOpcodeStr(Opc) 10453 << Args[0]->getType() << Args[1]->getType() 10454 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10455 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10456 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10457 return ExprError(); 10458 10459 case OR_Deleted: 10460 if (isImplicitlyDeleted(Best->Function)) { 10461 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10462 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10463 << Context.getRecordType(Method->getParent()) 10464 << getSpecialMember(Method); 10465 10466 // The user probably meant to call this special member. Just 10467 // explain why it's deleted. 10468 NoteDeletedFunction(Method); 10469 return ExprError(); 10470 } else { 10471 Diag(OpLoc, diag::err_ovl_deleted_oper) 10472 << Best->Function->isDeleted() 10473 << BinaryOperator::getOpcodeStr(Opc) 10474 << getDeletedOrUnavailableSuffix(Best->Function) 10475 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10476 } 10477 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10478 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10479 return ExprError(); 10480 } 10481 10482 // We matched a built-in operator; build it. 10483 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10484} 10485 10486ExprResult 10487Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10488 SourceLocation RLoc, 10489 Expr *Base, Expr *Idx) { 10490 Expr *Args[2] = { Base, Idx }; 10491 DeclarationName OpName = 10492 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10493 10494 // If either side is type-dependent, create an appropriate dependent 10495 // expression. 10496 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10497 10498 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10499 // CHECKME: no 'operator' keyword? 10500 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10501 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10502 UnresolvedLookupExpr *Fn 10503 = UnresolvedLookupExpr::Create(Context, NamingClass, 10504 NestedNameSpecifierLoc(), OpNameInfo, 10505 /*ADL*/ true, /*Overloaded*/ false, 10506 UnresolvedSetIterator(), 10507 UnresolvedSetIterator()); 10508 // Can't add any actual overloads yet 10509 10510 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10511 Args, 10512 Context.DependentTy, 10513 VK_RValue, 10514 RLoc, false)); 10515 } 10516 10517 // Handle placeholders on both operands. 10518 if (checkPlaceholderForOverload(*this, Args[0])) 10519 return ExprError(); 10520 if (checkPlaceholderForOverload(*this, Args[1])) 10521 return ExprError(); 10522 10523 // Build an empty overload set. 10524 OverloadCandidateSet CandidateSet(LLoc); 10525 10526 // Subscript can only be overloaded as a member function. 10527 10528 // Add operator candidates that are member functions. 10529 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10530 10531 // Add builtin operator candidates. 10532 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10533 10534 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10535 10536 // Perform overload resolution. 10537 OverloadCandidateSet::iterator Best; 10538 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10539 case OR_Success: { 10540 // We found a built-in operator or an overloaded operator. 10541 FunctionDecl *FnDecl = Best->Function; 10542 10543 if (FnDecl) { 10544 // We matched an overloaded operator. Build a call to that 10545 // operator. 10546 10547 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10548 10549 // Convert the arguments. 10550 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10551 ExprResult Arg0 = 10552 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10553 Best->FoundDecl, Method); 10554 if (Arg0.isInvalid()) 10555 return ExprError(); 10556 Args[0] = Arg0.take(); 10557 10558 // Convert the arguments. 10559 ExprResult InputInit 10560 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10561 Context, 10562 FnDecl->getParamDecl(0)), 10563 SourceLocation(), 10564 Owned(Args[1])); 10565 if (InputInit.isInvalid()) 10566 return ExprError(); 10567 10568 Args[1] = InputInit.takeAs<Expr>(); 10569 10570 // Determine the result type 10571 QualType ResultTy = FnDecl->getResultType(); 10572 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10573 ResultTy = ResultTy.getNonLValueExprType(Context); 10574 10575 // Build the actual expression node. 10576 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10577 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10578 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10579 Best->FoundDecl, 10580 HadMultipleCandidates, 10581 OpLocInfo.getLoc(), 10582 OpLocInfo.getInfo()); 10583 if (FnExpr.isInvalid()) 10584 return ExprError(); 10585 10586 CXXOperatorCallExpr *TheCall = 10587 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10588 FnExpr.take(), Args, 10589 ResultTy, VK, RLoc, 10590 false); 10591 10592 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10593 FnDecl)) 10594 return ExprError(); 10595 10596 return MaybeBindToTemporary(TheCall); 10597 } else { 10598 // We matched a built-in operator. Convert the arguments, then 10599 // break out so that we will build the appropriate built-in 10600 // operator node. 10601 ExprResult ArgsRes0 = 10602 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10603 Best->Conversions[0], AA_Passing); 10604 if (ArgsRes0.isInvalid()) 10605 return ExprError(); 10606 Args[0] = ArgsRes0.take(); 10607 10608 ExprResult ArgsRes1 = 10609 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10610 Best->Conversions[1], AA_Passing); 10611 if (ArgsRes1.isInvalid()) 10612 return ExprError(); 10613 Args[1] = ArgsRes1.take(); 10614 10615 break; 10616 } 10617 } 10618 10619 case OR_No_Viable_Function: { 10620 if (CandidateSet.empty()) 10621 Diag(LLoc, diag::err_ovl_no_oper) 10622 << Args[0]->getType() << /*subscript*/ 0 10623 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10624 else 10625 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10626 << Args[0]->getType() 10627 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10628 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10629 "[]", LLoc); 10630 return ExprError(); 10631 } 10632 10633 case OR_Ambiguous: 10634 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10635 << "[]" 10636 << Args[0]->getType() << Args[1]->getType() 10637 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10638 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10639 "[]", LLoc); 10640 return ExprError(); 10641 10642 case OR_Deleted: 10643 Diag(LLoc, diag::err_ovl_deleted_oper) 10644 << Best->Function->isDeleted() << "[]" 10645 << getDeletedOrUnavailableSuffix(Best->Function) 10646 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10647 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10648 "[]", LLoc); 10649 return ExprError(); 10650 } 10651 10652 // We matched a built-in operator; build it. 10653 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10654} 10655 10656/// BuildCallToMemberFunction - Build a call to a member 10657/// function. MemExpr is the expression that refers to the member 10658/// function (and includes the object parameter), Args/NumArgs are the 10659/// arguments to the function call (not including the object 10660/// parameter). The caller needs to validate that the member 10661/// expression refers to a non-static member function or an overloaded 10662/// member function. 10663ExprResult 10664Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10665 SourceLocation LParenLoc, Expr **Args, 10666 unsigned NumArgs, SourceLocation RParenLoc) { 10667 assert(MemExprE->getType() == Context.BoundMemberTy || 10668 MemExprE->getType() == Context.OverloadTy); 10669 10670 // Dig out the member expression. This holds both the object 10671 // argument and the member function we're referring to. 10672 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10673 10674 // Determine whether this is a call to a pointer-to-member function. 10675 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10676 assert(op->getType() == Context.BoundMemberTy); 10677 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10678 10679 QualType fnType = 10680 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10681 10682 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10683 QualType resultType = proto->getCallResultType(Context); 10684 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10685 10686 // Check that the object type isn't more qualified than the 10687 // member function we're calling. 10688 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10689 10690 QualType objectType = op->getLHS()->getType(); 10691 if (op->getOpcode() == BO_PtrMemI) 10692 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10693 Qualifiers objectQuals = objectType.getQualifiers(); 10694 10695 Qualifiers difference = objectQuals - funcQuals; 10696 difference.removeObjCGCAttr(); 10697 difference.removeAddressSpace(); 10698 if (difference) { 10699 std::string qualsString = difference.getAsString(); 10700 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10701 << fnType.getUnqualifiedType() 10702 << qualsString 10703 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10704 } 10705 10706 CXXMemberCallExpr *call 10707 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10708 llvm::makeArrayRef(Args, NumArgs), 10709 resultType, valueKind, RParenLoc); 10710 10711 if (CheckCallReturnType(proto->getResultType(), 10712 op->getRHS()->getLocStart(), 10713 call, 0)) 10714 return ExprError(); 10715 10716 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10717 return ExprError(); 10718 10719 return MaybeBindToTemporary(call); 10720 } 10721 10722 UnbridgedCastsSet UnbridgedCasts; 10723 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10724 return ExprError(); 10725 10726 MemberExpr *MemExpr; 10727 CXXMethodDecl *Method = 0; 10728 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10729 NestedNameSpecifier *Qualifier = 0; 10730 if (isa<MemberExpr>(NakedMemExpr)) { 10731 MemExpr = cast<MemberExpr>(NakedMemExpr); 10732 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10733 FoundDecl = MemExpr->getFoundDecl(); 10734 Qualifier = MemExpr->getQualifier(); 10735 UnbridgedCasts.restore(); 10736 } else { 10737 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10738 Qualifier = UnresExpr->getQualifier(); 10739 10740 QualType ObjectType = UnresExpr->getBaseType(); 10741 Expr::Classification ObjectClassification 10742 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10743 : UnresExpr->getBase()->Classify(Context); 10744 10745 // Add overload candidates 10746 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10747 10748 // FIXME: avoid copy. 10749 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10750 if (UnresExpr->hasExplicitTemplateArgs()) { 10751 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10752 TemplateArgs = &TemplateArgsBuffer; 10753 } 10754 10755 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10756 E = UnresExpr->decls_end(); I != E; ++I) { 10757 10758 NamedDecl *Func = *I; 10759 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10760 if (isa<UsingShadowDecl>(Func)) 10761 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10762 10763 10764 // Microsoft supports direct constructor calls. 10765 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10766 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10767 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10768 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10769 // If explicit template arguments were provided, we can't call a 10770 // non-template member function. 10771 if (TemplateArgs) 10772 continue; 10773 10774 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10775 ObjectClassification, 10776 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10777 /*SuppressUserConversions=*/false); 10778 } else { 10779 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10780 I.getPair(), ActingDC, TemplateArgs, 10781 ObjectType, ObjectClassification, 10782 llvm::makeArrayRef(Args, NumArgs), 10783 CandidateSet, 10784 /*SuppressUsedConversions=*/false); 10785 } 10786 } 10787 10788 DeclarationName DeclName = UnresExpr->getMemberName(); 10789 10790 UnbridgedCasts.restore(); 10791 10792 OverloadCandidateSet::iterator Best; 10793 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10794 Best)) { 10795 case OR_Success: 10796 Method = cast<CXXMethodDecl>(Best->Function); 10797 FoundDecl = Best->FoundDecl; 10798 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10799 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10800 break; 10801 10802 case OR_No_Viable_Function: 10803 Diag(UnresExpr->getMemberLoc(), 10804 diag::err_ovl_no_viable_member_function_in_call) 10805 << DeclName << MemExprE->getSourceRange(); 10806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10807 llvm::makeArrayRef(Args, NumArgs)); 10808 // FIXME: Leaking incoming expressions! 10809 return ExprError(); 10810 10811 case OR_Ambiguous: 10812 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10813 << DeclName << MemExprE->getSourceRange(); 10814 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10815 llvm::makeArrayRef(Args, NumArgs)); 10816 // FIXME: Leaking incoming expressions! 10817 return ExprError(); 10818 10819 case OR_Deleted: 10820 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10821 << Best->Function->isDeleted() 10822 << DeclName 10823 << getDeletedOrUnavailableSuffix(Best->Function) 10824 << MemExprE->getSourceRange(); 10825 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10826 llvm::makeArrayRef(Args, NumArgs)); 10827 // FIXME: Leaking incoming expressions! 10828 return ExprError(); 10829 } 10830 10831 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10832 10833 // If overload resolution picked a static member, build a 10834 // non-member call based on that function. 10835 if (Method->isStatic()) { 10836 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10837 Args, NumArgs, RParenLoc); 10838 } 10839 10840 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10841 } 10842 10843 QualType ResultType = Method->getResultType(); 10844 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10845 ResultType = ResultType.getNonLValueExprType(Context); 10846 10847 assert(Method && "Member call to something that isn't a method?"); 10848 CXXMemberCallExpr *TheCall = 10849 new (Context) CXXMemberCallExpr(Context, MemExprE, 10850 llvm::makeArrayRef(Args, NumArgs), 10851 ResultType, VK, RParenLoc); 10852 10853 // Check for a valid return type. 10854 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10855 TheCall, Method)) 10856 return ExprError(); 10857 10858 // Convert the object argument (for a non-static member function call). 10859 // We only need to do this if there was actually an overload; otherwise 10860 // it was done at lookup. 10861 if (!Method->isStatic()) { 10862 ExprResult ObjectArg = 10863 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10864 FoundDecl, Method); 10865 if (ObjectArg.isInvalid()) 10866 return ExprError(); 10867 MemExpr->setBase(ObjectArg.take()); 10868 } 10869 10870 // Convert the rest of the arguments 10871 const FunctionProtoType *Proto = 10872 Method->getType()->getAs<FunctionProtoType>(); 10873 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10874 RParenLoc)) 10875 return ExprError(); 10876 10877 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10878 10879 if (CheckFunctionCall(Method, TheCall, Proto)) 10880 return ExprError(); 10881 10882 if ((isa<CXXConstructorDecl>(CurContext) || 10883 isa<CXXDestructorDecl>(CurContext)) && 10884 TheCall->getMethodDecl()->isPure()) { 10885 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10886 10887 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10888 Diag(MemExpr->getLocStart(), 10889 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10890 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10891 << MD->getParent()->getDeclName(); 10892 10893 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10894 } 10895 } 10896 return MaybeBindToTemporary(TheCall); 10897} 10898 10899/// BuildCallToObjectOfClassType - Build a call to an object of class 10900/// type (C++ [over.call.object]), which can end up invoking an 10901/// overloaded function call operator (@c operator()) or performing a 10902/// user-defined conversion on the object argument. 10903ExprResult 10904Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10905 SourceLocation LParenLoc, 10906 Expr **Args, unsigned NumArgs, 10907 SourceLocation RParenLoc) { 10908 if (checkPlaceholderForOverload(*this, Obj)) 10909 return ExprError(); 10910 ExprResult Object = Owned(Obj); 10911 10912 UnbridgedCastsSet UnbridgedCasts; 10913 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10914 return ExprError(); 10915 10916 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10917 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10918 10919 // C++ [over.call.object]p1: 10920 // If the primary-expression E in the function call syntax 10921 // evaluates to a class object of type "cv T", then the set of 10922 // candidate functions includes at least the function call 10923 // operators of T. The function call operators of T are obtained by 10924 // ordinary lookup of the name operator() in the context of 10925 // (E).operator(). 10926 OverloadCandidateSet CandidateSet(LParenLoc); 10927 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10928 10929 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10930 diag::err_incomplete_object_call, Object.get())) 10931 return true; 10932 10933 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10934 LookupQualifiedName(R, Record->getDecl()); 10935 R.suppressDiagnostics(); 10936 10937 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10938 Oper != OperEnd; ++Oper) { 10939 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10940 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10941 /*SuppressUserConversions=*/ false); 10942 } 10943 10944 // C++ [over.call.object]p2: 10945 // In addition, for each (non-explicit in C++0x) conversion function 10946 // declared in T of the form 10947 // 10948 // operator conversion-type-id () cv-qualifier; 10949 // 10950 // where cv-qualifier is the same cv-qualification as, or a 10951 // greater cv-qualification than, cv, and where conversion-type-id 10952 // denotes the type "pointer to function of (P1,...,Pn) returning 10953 // R", or the type "reference to pointer to function of 10954 // (P1,...,Pn) returning R", or the type "reference to function 10955 // of (P1,...,Pn) returning R", a surrogate call function [...] 10956 // is also considered as a candidate function. Similarly, 10957 // surrogate call functions are added to the set of candidate 10958 // functions for each conversion function declared in an 10959 // accessible base class provided the function is not hidden 10960 // within T by another intervening declaration. 10961 std::pair<CXXRecordDecl::conversion_iterator, 10962 CXXRecordDecl::conversion_iterator> Conversions 10963 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10964 for (CXXRecordDecl::conversion_iterator 10965 I = Conversions.first, E = Conversions.second; I != E; ++I) { 10966 NamedDecl *D = *I; 10967 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10968 if (isa<UsingShadowDecl>(D)) 10969 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10970 10971 // Skip over templated conversion functions; they aren't 10972 // surrogates. 10973 if (isa<FunctionTemplateDecl>(D)) 10974 continue; 10975 10976 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10977 if (!Conv->isExplicit()) { 10978 // Strip the reference type (if any) and then the pointer type (if 10979 // any) to get down to what might be a function type. 10980 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10981 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10982 ConvType = ConvPtrType->getPointeeType(); 10983 10984 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10985 { 10986 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10987 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10988 CandidateSet); 10989 } 10990 } 10991 } 10992 10993 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10994 10995 // Perform overload resolution. 10996 OverloadCandidateSet::iterator Best; 10997 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10998 Best)) { 10999 case OR_Success: 11000 // Overload resolution succeeded; we'll build the appropriate call 11001 // below. 11002 break; 11003 11004 case OR_No_Viable_Function: 11005 if (CandidateSet.empty()) 11006 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11007 << Object.get()->getType() << /*call*/ 1 11008 << Object.get()->getSourceRange(); 11009 else 11010 Diag(Object.get()->getLocStart(), 11011 diag::err_ovl_no_viable_object_call) 11012 << Object.get()->getType() << Object.get()->getSourceRange(); 11013 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11014 llvm::makeArrayRef(Args, NumArgs)); 11015 break; 11016 11017 case OR_Ambiguous: 11018 Diag(Object.get()->getLocStart(), 11019 diag::err_ovl_ambiguous_object_call) 11020 << Object.get()->getType() << Object.get()->getSourceRange(); 11021 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 11022 llvm::makeArrayRef(Args, NumArgs)); 11023 break; 11024 11025 case OR_Deleted: 11026 Diag(Object.get()->getLocStart(), 11027 diag::err_ovl_deleted_object_call) 11028 << Best->Function->isDeleted() 11029 << Object.get()->getType() 11030 << getDeletedOrUnavailableSuffix(Best->Function) 11031 << Object.get()->getSourceRange(); 11032 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11033 llvm::makeArrayRef(Args, NumArgs)); 11034 break; 11035 } 11036 11037 if (Best == CandidateSet.end()) 11038 return true; 11039 11040 UnbridgedCasts.restore(); 11041 11042 if (Best->Function == 0) { 11043 // Since there is no function declaration, this is one of the 11044 // surrogate candidates. Dig out the conversion function. 11045 CXXConversionDecl *Conv 11046 = cast<CXXConversionDecl>( 11047 Best->Conversions[0].UserDefined.ConversionFunction); 11048 11049 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11050 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 11051 11052 // We selected one of the surrogate functions that converts the 11053 // object parameter to a function pointer. Perform the conversion 11054 // on the object argument, then let ActOnCallExpr finish the job. 11055 11056 // Create an implicit member expr to refer to the conversion operator. 11057 // and then call it. 11058 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11059 Conv, HadMultipleCandidates); 11060 if (Call.isInvalid()) 11061 return ExprError(); 11062 // Record usage of conversion in an implicit cast. 11063 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11064 CK_UserDefinedConversion, 11065 Call.get(), 0, VK_RValue)); 11066 11067 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 11068 RParenLoc); 11069 } 11070 11071 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11072 11073 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11074 // that calls this method, using Object for the implicit object 11075 // parameter and passing along the remaining arguments. 11076 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11077 11078 // An error diagnostic has already been printed when parsing the declaration. 11079 if (Method->isInvalidDecl()) 11080 return ExprError(); 11081 11082 const FunctionProtoType *Proto = 11083 Method->getType()->getAs<FunctionProtoType>(); 11084 11085 unsigned NumArgsInProto = Proto->getNumArgs(); 11086 unsigned NumArgsToCheck = NumArgs; 11087 11088 // Build the full argument list for the method call (the 11089 // implicit object parameter is placed at the beginning of the 11090 // list). 11091 Expr **MethodArgs; 11092 if (NumArgs < NumArgsInProto) { 11093 NumArgsToCheck = NumArgsInProto; 11094 MethodArgs = new Expr*[NumArgsInProto + 1]; 11095 } else { 11096 MethodArgs = new Expr*[NumArgs + 1]; 11097 } 11098 MethodArgs[0] = Object.get(); 11099 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11100 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11101 11102 DeclarationNameInfo OpLocInfo( 11103 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11104 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11105 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11106 HadMultipleCandidates, 11107 OpLocInfo.getLoc(), 11108 OpLocInfo.getInfo()); 11109 if (NewFn.isInvalid()) 11110 return true; 11111 11112 // Once we've built TheCall, all of the expressions are properly 11113 // owned. 11114 QualType ResultTy = Method->getResultType(); 11115 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11116 ResultTy = ResultTy.getNonLValueExprType(Context); 11117 11118 CXXOperatorCallExpr *TheCall = 11119 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11120 llvm::makeArrayRef(MethodArgs, NumArgs+1), 11121 ResultTy, VK, RParenLoc, false); 11122 delete [] MethodArgs; 11123 11124 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11125 Method)) 11126 return true; 11127 11128 // We may have default arguments. If so, we need to allocate more 11129 // slots in the call for them. 11130 if (NumArgs < NumArgsInProto) 11131 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11132 else if (NumArgs > NumArgsInProto) 11133 NumArgsToCheck = NumArgsInProto; 11134 11135 bool IsError = false; 11136 11137 // Initialize the implicit object parameter. 11138 ExprResult ObjRes = 11139 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11140 Best->FoundDecl, Method); 11141 if (ObjRes.isInvalid()) 11142 IsError = true; 11143 else 11144 Object = ObjRes; 11145 TheCall->setArg(0, Object.take()); 11146 11147 // Check the argument types. 11148 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11149 Expr *Arg; 11150 if (i < NumArgs) { 11151 Arg = Args[i]; 11152 11153 // Pass the argument. 11154 11155 ExprResult InputInit 11156 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11157 Context, 11158 Method->getParamDecl(i)), 11159 SourceLocation(), Arg); 11160 11161 IsError |= InputInit.isInvalid(); 11162 Arg = InputInit.takeAs<Expr>(); 11163 } else { 11164 ExprResult DefArg 11165 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11166 if (DefArg.isInvalid()) { 11167 IsError = true; 11168 break; 11169 } 11170 11171 Arg = DefArg.takeAs<Expr>(); 11172 } 11173 11174 TheCall->setArg(i + 1, Arg); 11175 } 11176 11177 // If this is a variadic call, handle args passed through "...". 11178 if (Proto->isVariadic()) { 11179 // Promote the arguments (C99 6.5.2.2p7). 11180 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11181 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11182 IsError |= Arg.isInvalid(); 11183 TheCall->setArg(i + 1, Arg.take()); 11184 } 11185 } 11186 11187 if (IsError) return true; 11188 11189 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11190 11191 if (CheckFunctionCall(Method, TheCall, Proto)) 11192 return true; 11193 11194 return MaybeBindToTemporary(TheCall); 11195} 11196 11197/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11198/// (if one exists), where @c Base is an expression of class type and 11199/// @c Member is the name of the member we're trying to find. 11200ExprResult 11201Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11202 assert(Base->getType()->isRecordType() && 11203 "left-hand side must have class type"); 11204 11205 if (checkPlaceholderForOverload(*this, Base)) 11206 return ExprError(); 11207 11208 SourceLocation Loc = Base->getExprLoc(); 11209 11210 // C++ [over.ref]p1: 11211 // 11212 // [...] An expression x->m is interpreted as (x.operator->())->m 11213 // for a class object x of type T if T::operator->() exists and if 11214 // the operator is selected as the best match function by the 11215 // overload resolution mechanism (13.3). 11216 DeclarationName OpName = 11217 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11218 OverloadCandidateSet CandidateSet(Loc); 11219 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11220 11221 if (RequireCompleteType(Loc, Base->getType(), 11222 diag::err_typecheck_incomplete_tag, Base)) 11223 return ExprError(); 11224 11225 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11226 LookupQualifiedName(R, BaseRecord->getDecl()); 11227 R.suppressDiagnostics(); 11228 11229 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11230 Oper != OperEnd; ++Oper) { 11231 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11232 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11233 } 11234 11235 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11236 11237 // Perform overload resolution. 11238 OverloadCandidateSet::iterator Best; 11239 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11240 case OR_Success: 11241 // Overload resolution succeeded; we'll build the call below. 11242 break; 11243 11244 case OR_No_Viable_Function: 11245 if (CandidateSet.empty()) 11246 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11247 << Base->getType() << Base->getSourceRange(); 11248 else 11249 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11250 << "operator->" << Base->getSourceRange(); 11251 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11252 return ExprError(); 11253 11254 case OR_Ambiguous: 11255 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11256 << "->" << Base->getType() << Base->getSourceRange(); 11257 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11258 return ExprError(); 11259 11260 case OR_Deleted: 11261 Diag(OpLoc, diag::err_ovl_deleted_oper) 11262 << Best->Function->isDeleted() 11263 << "->" 11264 << getDeletedOrUnavailableSuffix(Best->Function) 11265 << Base->getSourceRange(); 11266 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11267 return ExprError(); 11268 } 11269 11270 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11271 11272 // Convert the object parameter. 11273 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11274 ExprResult BaseResult = 11275 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11276 Best->FoundDecl, Method); 11277 if (BaseResult.isInvalid()) 11278 return ExprError(); 11279 Base = BaseResult.take(); 11280 11281 // Build the operator call. 11282 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11283 HadMultipleCandidates, OpLoc); 11284 if (FnExpr.isInvalid()) 11285 return ExprError(); 11286 11287 QualType ResultTy = Method->getResultType(); 11288 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11289 ResultTy = ResultTy.getNonLValueExprType(Context); 11290 CXXOperatorCallExpr *TheCall = 11291 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11292 Base, ResultTy, VK, OpLoc, false); 11293 11294 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11295 Method)) 11296 return ExprError(); 11297 11298 return MaybeBindToTemporary(TheCall); 11299} 11300 11301/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11302/// a literal operator described by the provided lookup results. 11303ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11304 DeclarationNameInfo &SuffixInfo, 11305 ArrayRef<Expr*> Args, 11306 SourceLocation LitEndLoc, 11307 TemplateArgumentListInfo *TemplateArgs) { 11308 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11309 11310 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11311 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11312 TemplateArgs); 11313 11314 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11315 11316 // Perform overload resolution. This will usually be trivial, but might need 11317 // to perform substitutions for a literal operator template. 11318 OverloadCandidateSet::iterator Best; 11319 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11320 case OR_Success: 11321 case OR_Deleted: 11322 break; 11323 11324 case OR_No_Viable_Function: 11325 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11326 << R.getLookupName(); 11327 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11328 return ExprError(); 11329 11330 case OR_Ambiguous: 11331 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11332 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11333 return ExprError(); 11334 } 11335 11336 FunctionDecl *FD = Best->Function; 11337 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11338 HadMultipleCandidates, 11339 SuffixInfo.getLoc(), 11340 SuffixInfo.getInfo()); 11341 if (Fn.isInvalid()) 11342 return true; 11343 11344 // Check the argument types. This should almost always be a no-op, except 11345 // that array-to-pointer decay is applied to string literals. 11346 Expr *ConvArgs[2]; 11347 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11348 ExprResult InputInit = PerformCopyInitialization( 11349 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11350 SourceLocation(), Args[ArgIdx]); 11351 if (InputInit.isInvalid()) 11352 return true; 11353 ConvArgs[ArgIdx] = InputInit.take(); 11354 } 11355 11356 QualType ResultTy = FD->getResultType(); 11357 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11358 ResultTy = ResultTy.getNonLValueExprType(Context); 11359 11360 UserDefinedLiteral *UDL = 11361 new (Context) UserDefinedLiteral(Context, Fn.take(), 11362 llvm::makeArrayRef(ConvArgs, Args.size()), 11363 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11364 11365 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11366 return ExprError(); 11367 11368 if (CheckFunctionCall(FD, UDL, NULL)) 11369 return ExprError(); 11370 11371 return MaybeBindToTemporary(UDL); 11372} 11373 11374/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11375/// given LookupResult is non-empty, it is assumed to describe a member which 11376/// will be invoked. Otherwise, the function will be found via argument 11377/// dependent lookup. 11378/// CallExpr is set to a valid expression and FRS_Success returned on success, 11379/// otherwise CallExpr is set to ExprError() and some non-success value 11380/// is returned. 11381Sema::ForRangeStatus 11382Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11383 SourceLocation RangeLoc, VarDecl *Decl, 11384 BeginEndFunction BEF, 11385 const DeclarationNameInfo &NameInfo, 11386 LookupResult &MemberLookup, 11387 OverloadCandidateSet *CandidateSet, 11388 Expr *Range, ExprResult *CallExpr) { 11389 CandidateSet->clear(); 11390 if (!MemberLookup.empty()) { 11391 ExprResult MemberRef = 11392 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11393 /*IsPtr=*/false, CXXScopeSpec(), 11394 /*TemplateKWLoc=*/SourceLocation(), 11395 /*FirstQualifierInScope=*/0, 11396 MemberLookup, 11397 /*TemplateArgs=*/0); 11398 if (MemberRef.isInvalid()) { 11399 *CallExpr = ExprError(); 11400 Diag(Range->getLocStart(), diag::note_in_for_range) 11401 << RangeLoc << BEF << Range->getType(); 11402 return FRS_DiagnosticIssued; 11403 } 11404 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11405 if (CallExpr->isInvalid()) { 11406 *CallExpr = ExprError(); 11407 Diag(Range->getLocStart(), diag::note_in_for_range) 11408 << RangeLoc << BEF << Range->getType(); 11409 return FRS_DiagnosticIssued; 11410 } 11411 } else { 11412 UnresolvedSet<0> FoundNames; 11413 UnresolvedLookupExpr *Fn = 11414 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11415 NestedNameSpecifierLoc(), NameInfo, 11416 /*NeedsADL=*/true, /*Overloaded=*/false, 11417 FoundNames.begin(), FoundNames.end()); 11418 11419 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11420 CandidateSet, CallExpr); 11421 if (CandidateSet->empty() || CandidateSetError) { 11422 *CallExpr = ExprError(); 11423 return FRS_NoViableFunction; 11424 } 11425 OverloadCandidateSet::iterator Best; 11426 OverloadingResult OverloadResult = 11427 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11428 11429 if (OverloadResult == OR_No_Viable_Function) { 11430 *CallExpr = ExprError(); 11431 return FRS_NoViableFunction; 11432 } 11433 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11434 Loc, 0, CandidateSet, &Best, 11435 OverloadResult, 11436 /*AllowTypoCorrection=*/false); 11437 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11438 *CallExpr = ExprError(); 11439 Diag(Range->getLocStart(), diag::note_in_for_range) 11440 << RangeLoc << BEF << Range->getType(); 11441 return FRS_DiagnosticIssued; 11442 } 11443 } 11444 return FRS_Success; 11445} 11446 11447 11448/// FixOverloadedFunctionReference - E is an expression that refers to 11449/// a C++ overloaded function (possibly with some parentheses and 11450/// perhaps a '&' around it). We have resolved the overloaded function 11451/// to the function declaration Fn, so patch up the expression E to 11452/// refer (possibly indirectly) to Fn. Returns the new expr. 11453Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11454 FunctionDecl *Fn) { 11455 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11456 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11457 Found, Fn); 11458 if (SubExpr == PE->getSubExpr()) 11459 return PE; 11460 11461 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11462 } 11463 11464 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11465 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11466 Found, Fn); 11467 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11468 SubExpr->getType()) && 11469 "Implicit cast type cannot be determined from overload"); 11470 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11471 if (SubExpr == ICE->getSubExpr()) 11472 return ICE; 11473 11474 return ImplicitCastExpr::Create(Context, ICE->getType(), 11475 ICE->getCastKind(), 11476 SubExpr, 0, 11477 ICE->getValueKind()); 11478 } 11479 11480 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11481 assert(UnOp->getOpcode() == UO_AddrOf && 11482 "Can only take the address of an overloaded function"); 11483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11484 if (Method->isStatic()) { 11485 // Do nothing: static member functions aren't any different 11486 // from non-member functions. 11487 } else { 11488 // Fix the sub expression, which really has to be an 11489 // UnresolvedLookupExpr holding an overloaded member function 11490 // or template. 11491 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11492 Found, Fn); 11493 if (SubExpr == UnOp->getSubExpr()) 11494 return UnOp; 11495 11496 assert(isa<DeclRefExpr>(SubExpr) 11497 && "fixed to something other than a decl ref"); 11498 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11499 && "fixed to a member ref with no nested name qualifier"); 11500 11501 // We have taken the address of a pointer to member 11502 // function. Perform the computation here so that we get the 11503 // appropriate pointer to member type. 11504 QualType ClassType 11505 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11506 QualType MemPtrType 11507 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11508 11509 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11510 VK_RValue, OK_Ordinary, 11511 UnOp->getOperatorLoc()); 11512 } 11513 } 11514 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11515 Found, Fn); 11516 if (SubExpr == UnOp->getSubExpr()) 11517 return UnOp; 11518 11519 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11520 Context.getPointerType(SubExpr->getType()), 11521 VK_RValue, OK_Ordinary, 11522 UnOp->getOperatorLoc()); 11523 } 11524 11525 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11526 // FIXME: avoid copy. 11527 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11528 if (ULE->hasExplicitTemplateArgs()) { 11529 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11530 TemplateArgs = &TemplateArgsBuffer; 11531 } 11532 11533 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11534 ULE->getQualifierLoc(), 11535 ULE->getTemplateKeywordLoc(), 11536 Fn, 11537 /*enclosing*/ false, // FIXME? 11538 ULE->getNameLoc(), 11539 Fn->getType(), 11540 VK_LValue, 11541 Found.getDecl(), 11542 TemplateArgs); 11543 MarkDeclRefReferenced(DRE); 11544 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11545 return DRE; 11546 } 11547 11548 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11549 // FIXME: avoid copy. 11550 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11551 if (MemExpr->hasExplicitTemplateArgs()) { 11552 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11553 TemplateArgs = &TemplateArgsBuffer; 11554 } 11555 11556 Expr *Base; 11557 11558 // If we're filling in a static method where we used to have an 11559 // implicit member access, rewrite to a simple decl ref. 11560 if (MemExpr->isImplicitAccess()) { 11561 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11562 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11563 MemExpr->getQualifierLoc(), 11564 MemExpr->getTemplateKeywordLoc(), 11565 Fn, 11566 /*enclosing*/ false, 11567 MemExpr->getMemberLoc(), 11568 Fn->getType(), 11569 VK_LValue, 11570 Found.getDecl(), 11571 TemplateArgs); 11572 MarkDeclRefReferenced(DRE); 11573 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11574 return DRE; 11575 } else { 11576 SourceLocation Loc = MemExpr->getMemberLoc(); 11577 if (MemExpr->getQualifier()) 11578 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11579 CheckCXXThisCapture(Loc); 11580 Base = new (Context) CXXThisExpr(Loc, 11581 MemExpr->getBaseType(), 11582 /*isImplicit=*/true); 11583 } 11584 } else 11585 Base = MemExpr->getBase(); 11586 11587 ExprValueKind valueKind; 11588 QualType type; 11589 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11590 valueKind = VK_LValue; 11591 type = Fn->getType(); 11592 } else { 11593 valueKind = VK_RValue; 11594 type = Context.BoundMemberTy; 11595 } 11596 11597 MemberExpr *ME = MemberExpr::Create(Context, Base, 11598 MemExpr->isArrow(), 11599 MemExpr->getQualifierLoc(), 11600 MemExpr->getTemplateKeywordLoc(), 11601 Fn, 11602 Found, 11603 MemExpr->getMemberNameInfo(), 11604 TemplateArgs, 11605 type, valueKind, OK_Ordinary); 11606 ME->setHadMultipleCandidates(true); 11607 MarkMemberReferenced(ME); 11608 return ME; 11609 } 11610 11611 llvm_unreachable("Invalid reference to overloaded function"); 11612} 11613 11614ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11615 DeclAccessPair Found, 11616 FunctionDecl *Fn) { 11617 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11618} 11619 11620} // end namespace clang 11621