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