SemaOverload.cpp revision 699c9044c7d53a2774d0dd261a6901dd2c4a545f
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 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/SemaInternal.h" 15#include "clang/Sema/Lookup.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Template.h" 18#include "clang/Sema/TemplateDeduction.h" 19#include "clang/Basic/Diagnostic.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprObjC.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "llvm/ADT/DenseSet.h" 30#include "llvm/ADT/SmallPtrSet.h" 31#include "llvm/ADT/SmallString.h" 32#include "llvm/ADT/STLExtras.h" 33#include <algorithm> 34 35namespace clang { 36using namespace sema; 37 38/// A convenience routine for creating a decayed reference to a 39/// function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 42 SourceLocation Loc = SourceLocation(), 43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 44 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 45 VK_LValue, Loc, LocInfo); 46 if (HadMultipleCandidates) 47 DRE->setHadMultipleCandidates(true); 48 ExprResult E = S.Owned(DRE); 49 E = S.DefaultFunctionArrayConversion(E.take()); 50 if (E.isInvalid()) 51 return ExprError(); 52 return move(E); 53} 54 55static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 56 bool InOverloadResolution, 57 StandardConversionSequence &SCS, 58 bool CStyle, 59 bool AllowObjCWritebackConversion); 60 61static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 62 QualType &ToType, 63 bool InOverloadResolution, 64 StandardConversionSequence &SCS, 65 bool CStyle); 66static OverloadingResult 67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 68 UserDefinedConversionSequence& User, 69 OverloadCandidateSet& Conversions, 70 bool AllowExplicit); 71 72 73static ImplicitConversionSequence::CompareKind 74CompareStandardConversionSequences(Sema &S, 75 const StandardConversionSequence& SCS1, 76 const StandardConversionSequence& SCS2); 77 78static ImplicitConversionSequence::CompareKind 79CompareQualificationConversions(Sema &S, 80 const StandardConversionSequence& SCS1, 81 const StandardConversionSequence& SCS2); 82 83static ImplicitConversionSequence::CompareKind 84CompareDerivedToBaseConversions(Sema &S, 85 const StandardConversionSequence& SCS1, 86 const StandardConversionSequence& SCS2); 87 88 89 90/// GetConversionCategory - Retrieve the implicit conversion 91/// category corresponding to the given implicit conversion kind. 92ImplicitConversionCategory 93GetConversionCategory(ImplicitConversionKind Kind) { 94 static const ImplicitConversionCategory 95 Category[(int)ICK_Num_Conversion_Kinds] = { 96 ICC_Identity, 97 ICC_Lvalue_Transformation, 98 ICC_Lvalue_Transformation, 99 ICC_Lvalue_Transformation, 100 ICC_Identity, 101 ICC_Qualification_Adjustment, 102 ICC_Promotion, 103 ICC_Promotion, 104 ICC_Promotion, 105 ICC_Conversion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 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 }; 119 return Category[(int)Kind]; 120} 121 122/// GetConversionRank - Retrieve the implicit conversion rank 123/// corresponding to the given implicit conversion kind. 124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 125 static const ImplicitConversionRank 126 Rank[(int)ICK_Num_Conversion_Kinds] = { 127 ICR_Exact_Match, 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Promotion, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Complex_Real_Conversion, 148 ICR_Conversion, 149 ICR_Conversion, 150 ICR_Writeback_Conversion 151 }; 152 return Rank[(int)Kind]; 153} 154 155/// GetImplicitConversionName - Return the name of this kind of 156/// implicit conversion. 157const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Noreturn adjustment", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion" 182 "Writeback conversion" 183 }; 184 return Name[Kind]; 185} 186 187/// StandardConversionSequence - Set the standard conversion 188/// sequence to the identity conversion. 189void StandardConversionSequence::setAsIdentityConversion() { 190 First = ICK_Identity; 191 Second = ICK_Identity; 192 Third = ICK_Identity; 193 DeprecatedStringLiteralToCharPtr = false; 194 QualificationIncludesObjCLifetime = false; 195 ReferenceBinding = false; 196 DirectBinding = false; 197 IsLvalueReference = true; 198 BindsToFunctionLvalue = false; 199 BindsToRvalue = false; 200 BindsImplicitObjectArgumentWithoutRefQualifier = false; 201 ObjCLifetimeConversionBinding = false; 202 CopyConstructor = 0; 203} 204 205/// getRank - Retrieve the rank of this standard conversion sequence 206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 207/// implicit conversions. 208ImplicitConversionRank StandardConversionSequence::getRank() const { 209 ImplicitConversionRank Rank = ICR_Exact_Match; 210 if (GetConversionRank(First) > Rank) 211 Rank = GetConversionRank(First); 212 if (GetConversionRank(Second) > Rank) 213 Rank = GetConversionRank(Second); 214 if (GetConversionRank(Third) > Rank) 215 Rank = GetConversionRank(Third); 216 return Rank; 217} 218 219/// isPointerConversionToBool - Determines whether this conversion is 220/// a conversion of a pointer or pointer-to-member to bool. This is 221/// used as part of the ranking of standard conversion sequences 222/// (C++ 13.3.3.2p4). 223bool StandardConversionSequence::isPointerConversionToBool() const { 224 // Note that FromType has not necessarily been transformed by the 225 // array-to-pointer or function-to-pointer implicit conversions, so 226 // check for their presence as well as checking whether FromType is 227 // a pointer. 228 if (getToType(1)->isBooleanType() && 229 (getFromType()->isPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237} 238 239/// isPointerConversionToVoidPointer - Determines whether this 240/// conversion is a conversion of a pointer to a void pointer. This is 241/// used as part of the ranking of standard conversion sequences (C++ 242/// 13.3.3.2p4). 243bool 244StandardConversionSequence:: 245isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260} 261 262/// Skip any implicit casts which could be either part of a narrowing conversion 263/// or after one in an implicit conversion. 264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 266 switch (ICE->getCastKind()) { 267 case CK_NoOp: 268 case CK_IntegralCast: 269 case CK_IntegralToBoolean: 270 case CK_IntegralToFloating: 271 case CK_FloatingToIntegral: 272 case CK_FloatingToBoolean: 273 case CK_FloatingCast: 274 Converted = ICE->getSubExpr(); 275 continue; 276 277 default: 278 return Converted; 279 } 280 } 281 282 return Converted; 283} 284 285/// Check if this standard conversion sequence represents a narrowing 286/// conversion, according to C++11 [dcl.init.list]p7. 287/// 288/// \param Ctx The AST context. 289/// \param Converted The result of applying this standard conversion sequence. 290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 291/// value of the expression prior to the narrowing conversion. 292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 293/// type of the expression prior to the narrowing conversion. 294NarrowingKind 295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 296 const Expr *Converted, 297 APValue &ConstantValue, 298 QualType &ConstantType) const { 299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 300 301 // C++11 [dcl.init.list]p7: 302 // A narrowing conversion is an implicit conversion ... 303 QualType FromType = getToType(0); 304 QualType ToType = getToType(1); 305 switch (Second) { 306 // -- from a floating-point type to an integer type, or 307 // 308 // -- from an integer type or unscoped enumeration type to a floating-point 309 // type, except where the source is a constant expression and the actual 310 // value after conversion will fit into the target type and will produce 311 // the original value when converted back to the original type, or 312 case ICK_Floating_Integral: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Boolean_Conversion: // Bools are integers too. 378 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 379 // Boolean conversions can be from pointers and pointers to members 380 // [conv.bool], and those aren't considered narrowing conversions. 381 return NK_Not_Narrowing; 382 } // Otherwise, fall through to the integral case. 383 case ICK_Integral_Conversion: { 384 assert(FromType->isIntegralOrUnscopedEnumerationType()); 385 assert(ToType->isIntegralOrUnscopedEnumerationType()); 386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 387 const unsigned FromWidth = Ctx.getIntWidth(FromType); 388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 389 const unsigned ToWidth = Ctx.getIntWidth(ToType); 390 391 if (FromWidth > ToWidth || 392 (FromWidth == ToWidth && FromSigned != ToSigned) || 393 (FromSigned && !ToSigned)) { 394 // Not all values of FromType can be represented in ToType. 395 llvm::APSInt InitializerValue; 396 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 398 // Such conversions on variables are always narrowing. 399 return NK_Variable_Narrowing; 400 } else if (FromWidth < ToWidth) { 401 // Negative -> unsigned is narrowing. Otherwise, more bits is never 402 // narrowing. 403 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 404 return NK_Constant_Narrowing; 405 } else { 406 ConstantValue = APValue(InitializerValue); 407 408 // Add a bit to the InitializerValue so we don't have to worry about 409 // signed vs. unsigned comparisons. 410 InitializerValue = InitializerValue.extend( 411 InitializerValue.getBitWidth() + 1); 412 // Convert the initializer to and from the target width and signed-ness. 413 llvm::APSInt ConvertedValue = InitializerValue; 414 ConvertedValue = ConvertedValue.trunc(ToWidth); 415 ConvertedValue.setIsSigned(ToSigned); 416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 417 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 418 // If the result is different, this was a narrowing conversion. 419 if (ConvertedValue != InitializerValue) { 420 ConstantType = Initializer->getType(); 421 return NK_Constant_Narrowing; 422 } 423 } 424 } 425 return NK_Not_Narrowing; 426 } 427 428 default: 429 // Other kinds of conversions are not narrowings. 430 return NK_Not_Narrowing; 431 } 432} 433 434/// DebugPrint - Print this standard conversion sequence to standard 435/// error. Useful for debugging overloading issues. 436void StandardConversionSequence::DebugPrint() const { 437 raw_ostream &OS = llvm::errs(); 438 bool PrintedSomething = false; 439 if (First != ICK_Identity) { 440 OS << GetImplicitConversionName(First); 441 PrintedSomething = true; 442 } 443 444 if (Second != ICK_Identity) { 445 if (PrintedSomething) { 446 OS << " -> "; 447 } 448 OS << GetImplicitConversionName(Second); 449 450 if (CopyConstructor) { 451 OS << " (by copy constructor)"; 452 } else if (DirectBinding) { 453 OS << " (direct reference binding)"; 454 } else if (ReferenceBinding) { 455 OS << " (reference binding)"; 456 } 457 PrintedSomething = true; 458 } 459 460 if (Third != ICK_Identity) { 461 if (PrintedSomething) { 462 OS << " -> "; 463 } 464 OS << GetImplicitConversionName(Third); 465 PrintedSomething = true; 466 } 467 468 if (!PrintedSomething) { 469 OS << "No conversions required"; 470 } 471} 472 473/// DebugPrint - Print this user-defined conversion sequence to standard 474/// error. Useful for debugging overloading issues. 475void UserDefinedConversionSequence::DebugPrint() const { 476 raw_ostream &OS = llvm::errs(); 477 if (Before.First || Before.Second || Before.Third) { 478 Before.DebugPrint(); 479 OS << " -> "; 480 } 481 if (ConversionFunction) 482 OS << '\'' << *ConversionFunction << '\''; 483 else 484 OS << "aggregate initialization"; 485 if (After.First || After.Second || After.Third) { 486 OS << " -> "; 487 After.DebugPrint(); 488 } 489} 490 491/// DebugPrint - Print this implicit conversion sequence to standard 492/// error. Useful for debugging overloading issues. 493void ImplicitConversionSequence::DebugPrint() const { 494 raw_ostream &OS = llvm::errs(); 495 switch (ConversionKind) { 496 case StandardConversion: 497 OS << "Standard conversion: "; 498 Standard.DebugPrint(); 499 break; 500 case UserDefinedConversion: 501 OS << "User-defined conversion: "; 502 UserDefined.DebugPrint(); 503 break; 504 case EllipsisConversion: 505 OS << "Ellipsis conversion"; 506 break; 507 case AmbiguousConversion: 508 OS << "Ambiguous conversion"; 509 break; 510 case BadConversion: 511 OS << "Bad conversion"; 512 break; 513 } 514 515 OS << "\n"; 516} 517 518void AmbiguousConversionSequence::construct() { 519 new (&conversions()) ConversionSet(); 520} 521 522void AmbiguousConversionSequence::destruct() { 523 conversions().~ConversionSet(); 524} 525 526void 527AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 528 FromTypePtr = O.FromTypePtr; 529 ToTypePtr = O.ToTypePtr; 530 new (&conversions()) ConversionSet(O.conversions()); 531} 532 533namespace { 534 // Structure used by OverloadCandidate::DeductionFailureInfo to store 535 // template parameter and template argument information. 536 struct DFIParamWithArguments { 537 TemplateParameter Param; 538 TemplateArgument FirstArg; 539 TemplateArgument SecondArg; 540 }; 541} 542 543/// \brief Convert from Sema's representation of template deduction information 544/// to the form used in overload-candidate information. 545OverloadCandidate::DeductionFailureInfo 546static MakeDeductionFailureInfo(ASTContext &Context, 547 Sema::TemplateDeductionResult TDK, 548 TemplateDeductionInfo &Info) { 549 OverloadCandidate::DeductionFailureInfo Result; 550 Result.Result = static_cast<unsigned>(TDK); 551 Result.HasDiagnostic = false; 552 Result.Data = 0; 553 switch (TDK) { 554 case Sema::TDK_Success: 555 case Sema::TDK_InstantiationDepth: 556 case Sema::TDK_TooManyArguments: 557 case Sema::TDK_TooFewArguments: 558 break; 559 560 case Sema::TDK_Incomplete: 561 case Sema::TDK_InvalidExplicitArguments: 562 Result.Data = Info.Param.getOpaqueValue(); 563 break; 564 565 case Sema::TDK_Inconsistent: 566 case Sema::TDK_Underqualified: { 567 // FIXME: Should allocate from normal heap so that we can free this later. 568 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 569 Saved->Param = Info.Param; 570 Saved->FirstArg = Info.FirstArg; 571 Saved->SecondArg = Info.SecondArg; 572 Result.Data = Saved; 573 break; 574 } 575 576 case Sema::TDK_SubstitutionFailure: 577 Result.Data = Info.take(); 578 if (Info.hasSFINAEDiagnostic()) { 579 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 580 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 581 Info.takeSFINAEDiagnostic(*Diag); 582 Result.HasDiagnostic = true; 583 } 584 break; 585 586 case Sema::TDK_NonDeducedMismatch: 587 case Sema::TDK_FailedOverloadResolution: 588 break; 589 } 590 591 return Result; 592} 593 594void OverloadCandidate::DeductionFailureInfo::Destroy() { 595 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 596 case Sema::TDK_Success: 597 case Sema::TDK_InstantiationDepth: 598 case Sema::TDK_Incomplete: 599 case Sema::TDK_TooManyArguments: 600 case Sema::TDK_TooFewArguments: 601 case Sema::TDK_InvalidExplicitArguments: 602 break; 603 604 case Sema::TDK_Inconsistent: 605 case Sema::TDK_Underqualified: 606 // FIXME: Destroy the data? 607 Data = 0; 608 break; 609 610 case Sema::TDK_SubstitutionFailure: 611 // FIXME: Destroy the template argument list? 612 Data = 0; 613 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 614 Diag->~PartialDiagnosticAt(); 615 HasDiagnostic = false; 616 } 617 break; 618 619 // Unhandled 620 case Sema::TDK_NonDeducedMismatch: 621 case Sema::TDK_FailedOverloadResolution: 622 break; 623 } 624} 625 626PartialDiagnosticAt * 627OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 628 if (HasDiagnostic) 629 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 630 return 0; 631} 632 633TemplateParameter 634OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 635 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 636 case Sema::TDK_Success: 637 case Sema::TDK_InstantiationDepth: 638 case Sema::TDK_TooManyArguments: 639 case Sema::TDK_TooFewArguments: 640 case Sema::TDK_SubstitutionFailure: 641 return TemplateParameter(); 642 643 case Sema::TDK_Incomplete: 644 case Sema::TDK_InvalidExplicitArguments: 645 return TemplateParameter::getFromOpaqueValue(Data); 646 647 case Sema::TDK_Inconsistent: 648 case Sema::TDK_Underqualified: 649 return static_cast<DFIParamWithArguments*>(Data)->Param; 650 651 // Unhandled 652 case Sema::TDK_NonDeducedMismatch: 653 case Sema::TDK_FailedOverloadResolution: 654 break; 655 } 656 657 return TemplateParameter(); 658} 659 660TemplateArgumentList * 661OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 663 case Sema::TDK_Success: 664 case Sema::TDK_InstantiationDepth: 665 case Sema::TDK_TooManyArguments: 666 case Sema::TDK_TooFewArguments: 667 case Sema::TDK_Incomplete: 668 case Sema::TDK_InvalidExplicitArguments: 669 case Sema::TDK_Inconsistent: 670 case Sema::TDK_Underqualified: 671 return 0; 672 673 case Sema::TDK_SubstitutionFailure: 674 return static_cast<TemplateArgumentList*>(Data); 675 676 // Unhandled 677 case Sema::TDK_NonDeducedMismatch: 678 case Sema::TDK_FailedOverloadResolution: 679 break; 680 } 681 682 return 0; 683} 684 685const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 686 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 687 case Sema::TDK_Success: 688 case Sema::TDK_InstantiationDepth: 689 case Sema::TDK_Incomplete: 690 case Sema::TDK_TooManyArguments: 691 case Sema::TDK_TooFewArguments: 692 case Sema::TDK_InvalidExplicitArguments: 693 case Sema::TDK_SubstitutionFailure: 694 return 0; 695 696 case Sema::TDK_Inconsistent: 697 case Sema::TDK_Underqualified: 698 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 699 700 // Unhandled 701 case Sema::TDK_NonDeducedMismatch: 702 case Sema::TDK_FailedOverloadResolution: 703 break; 704 } 705 706 return 0; 707} 708 709const TemplateArgument * 710OverloadCandidate::DeductionFailureInfo::getSecondArg() { 711 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 712 case Sema::TDK_Success: 713 case Sema::TDK_InstantiationDepth: 714 case Sema::TDK_Incomplete: 715 case Sema::TDK_TooManyArguments: 716 case Sema::TDK_TooFewArguments: 717 case Sema::TDK_InvalidExplicitArguments: 718 case Sema::TDK_SubstitutionFailure: 719 return 0; 720 721 case Sema::TDK_Inconsistent: 722 case Sema::TDK_Underqualified: 723 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 724 725 // Unhandled 726 case Sema::TDK_NonDeducedMismatch: 727 case Sema::TDK_FailedOverloadResolution: 728 break; 729 } 730 731 return 0; 732} 733 734void OverloadCandidateSet::clear() { 735 for (iterator i = begin(), e = end(); i != e; ++i) 736 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 737 i->Conversions[ii].~ImplicitConversionSequence(); 738 NumInlineSequences = 0; 739 Candidates.clear(); 740 Functions.clear(); 741} 742 743namespace { 744 class UnbridgedCastsSet { 745 struct Entry { 746 Expr **Addr; 747 Expr *Saved; 748 }; 749 SmallVector<Entry, 2> Entries; 750 751 public: 752 void save(Sema &S, Expr *&E) { 753 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 754 Entry entry = { &E, E }; 755 Entries.push_back(entry); 756 E = S.stripARCUnbridgedCast(E); 757 } 758 759 void restore() { 760 for (SmallVectorImpl<Entry>::iterator 761 i = Entries.begin(), e = Entries.end(); i != e; ++i) 762 *i->Addr = i->Saved; 763 } 764 }; 765} 766 767/// checkPlaceholderForOverload - Do any interesting placeholder-like 768/// preprocessing on the given expression. 769/// 770/// \param unbridgedCasts a collection to which to add unbridged casts; 771/// without this, they will be immediately diagnosed as errors 772/// 773/// Return true on unrecoverable error. 774static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 775 UnbridgedCastsSet *unbridgedCasts = 0) { 776 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 777 // We can't handle overloaded expressions here because overload 778 // resolution might reasonably tweak them. 779 if (placeholder->getKind() == BuiltinType::Overload) return false; 780 781 // If the context potentially accepts unbridged ARC casts, strip 782 // the unbridged cast and add it to the collection for later restoration. 783 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 784 unbridgedCasts) { 785 unbridgedCasts->save(S, E); 786 return false; 787 } 788 789 // Go ahead and check everything else. 790 ExprResult result = S.CheckPlaceholderExpr(E); 791 if (result.isInvalid()) 792 return true; 793 794 E = result.take(); 795 return false; 796 } 797 798 // Nothing to do. 799 return false; 800} 801 802/// checkArgPlaceholdersForOverload - Check a set of call operands for 803/// placeholders. 804static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 805 unsigned numArgs, 806 UnbridgedCastsSet &unbridged) { 807 for (unsigned i = 0; i != numArgs; ++i) 808 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 809 return true; 810 811 return false; 812} 813 814// IsOverload - Determine whether the given New declaration is an 815// overload of the declarations in Old. This routine returns false if 816// New and Old cannot be overloaded, e.g., if New has the same 817// signature as some function in Old (C++ 1.3.10) or if the Old 818// declarations aren't functions (or function templates) at all. When 819// it does return false, MatchedDecl will point to the decl that New 820// cannot be overloaded with. This decl may be a UsingShadowDecl on 821// top of the underlying declaration. 822// 823// Example: Given the following input: 824// 825// void f(int, float); // #1 826// void f(int, int); // #2 827// int f(int, int); // #3 828// 829// When we process #1, there is no previous declaration of "f", 830// so IsOverload will not be used. 831// 832// When we process #2, Old contains only the FunctionDecl for #1. By 833// comparing the parameter types, we see that #1 and #2 are overloaded 834// (since they have different signatures), so this routine returns 835// false; MatchedDecl is unchanged. 836// 837// When we process #3, Old is an overload set containing #1 and #2. We 838// compare the signatures of #3 to #1 (they're overloaded, so we do 839// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 840// identical (return types of functions are not part of the 841// signature), IsOverload returns false and MatchedDecl will be set to 842// point to the FunctionDecl for #2. 843// 844// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 845// into a class by a using declaration. The rules for whether to hide 846// shadow declarations ignore some properties which otherwise figure 847// into a function template's signature. 848Sema::OverloadKind 849Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 850 NamedDecl *&Match, bool NewIsUsingDecl) { 851 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 852 I != E; ++I) { 853 NamedDecl *OldD = *I; 854 855 bool OldIsUsingDecl = false; 856 if (isa<UsingShadowDecl>(OldD)) { 857 OldIsUsingDecl = true; 858 859 // We can always introduce two using declarations into the same 860 // context, even if they have identical signatures. 861 if (NewIsUsingDecl) continue; 862 863 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 864 } 865 866 // If either declaration was introduced by a using declaration, 867 // we'll need to use slightly different rules for matching. 868 // Essentially, these rules are the normal rules, except that 869 // function templates hide function templates with different 870 // return types or template parameter lists. 871 bool UseMemberUsingDeclRules = 872 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 873 874 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 875 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 876 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 877 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 878 continue; 879 } 880 881 Match = *I; 882 return Ovl_Match; 883 } 884 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 885 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 886 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 887 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 888 continue; 889 } 890 891 Match = *I; 892 return Ovl_Match; 893 } 894 } else if (isa<UsingDecl>(OldD)) { 895 // We can overload with these, which can show up when doing 896 // redeclaration checks for UsingDecls. 897 assert(Old.getLookupKind() == LookupUsingDeclName); 898 } else if (isa<TagDecl>(OldD)) { 899 // We can always overload with tags by hiding them. 900 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 901 // Optimistically assume that an unresolved using decl will 902 // overload; if it doesn't, we'll have to diagnose during 903 // template instantiation. 904 } else { 905 // (C++ 13p1): 906 // Only function declarations can be overloaded; object and type 907 // declarations cannot be overloaded. 908 Match = *I; 909 return Ovl_NonFunction; 910 } 911 } 912 913 return Ovl_Overload; 914} 915 916bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 917 bool UseUsingDeclRules) { 918 // If both of the functions are extern "C", then they are not 919 // overloads. 920 if (Old->isExternC() && New->isExternC()) 921 return false; 922 923 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 924 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 925 926 // C++ [temp.fct]p2: 927 // A function template can be overloaded with other function templates 928 // and with normal (non-template) functions. 929 if ((OldTemplate == 0) != (NewTemplate == 0)) 930 return true; 931 932 // Is the function New an overload of the function Old? 933 QualType OldQType = Context.getCanonicalType(Old->getType()); 934 QualType NewQType = Context.getCanonicalType(New->getType()); 935 936 // Compare the signatures (C++ 1.3.10) of the two functions to 937 // determine whether they are overloads. If we find any mismatch 938 // in the signature, they are overloads. 939 940 // If either of these functions is a K&R-style function (no 941 // prototype), then we consider them to have matching signatures. 942 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 943 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 944 return false; 945 946 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 947 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 948 949 // The signature of a function includes the types of its 950 // parameters (C++ 1.3.10), which includes the presence or absence 951 // of the ellipsis; see C++ DR 357). 952 if (OldQType != NewQType && 953 (OldType->getNumArgs() != NewType->getNumArgs() || 954 OldType->isVariadic() != NewType->isVariadic() || 955 !FunctionArgTypesAreEqual(OldType, NewType))) 956 return true; 957 958 // C++ [temp.over.link]p4: 959 // The signature of a function template consists of its function 960 // signature, its return type and its template parameter list. The names 961 // of the template parameters are significant only for establishing the 962 // relationship between the template parameters and the rest of the 963 // signature. 964 // 965 // We check the return type and template parameter lists for function 966 // templates first; the remaining checks follow. 967 // 968 // However, we don't consider either of these when deciding whether 969 // a member introduced by a shadow declaration is hidden. 970 if (!UseUsingDeclRules && NewTemplate && 971 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 972 OldTemplate->getTemplateParameters(), 973 false, TPL_TemplateMatch) || 974 OldType->getResultType() != NewType->getResultType())) 975 return true; 976 977 // If the function is a class member, its signature includes the 978 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 979 // 980 // As part of this, also check whether one of the member functions 981 // is static, in which case they are not overloads (C++ 982 // 13.1p2). While not part of the definition of the signature, 983 // this check is important to determine whether these functions 984 // can be overloaded. 985 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 986 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 987 if (OldMethod && NewMethod && 988 !OldMethod->isStatic() && !NewMethod->isStatic() && 989 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 990 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 991 if (!UseUsingDeclRules && 992 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 993 (OldMethod->getRefQualifier() == RQ_None || 994 NewMethod->getRefQualifier() == RQ_None)) { 995 // C++0x [over.load]p2: 996 // - Member function declarations with the same name and the same 997 // parameter-type-list as well as member function template 998 // declarations with the same name, the same parameter-type-list, and 999 // the same template parameter lists cannot be overloaded if any of 1000 // them, but not all, have a ref-qualifier (8.3.5). 1001 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1002 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1003 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1004 } 1005 1006 return true; 1007 } 1008 1009 // The signatures match; this is not an overload. 1010 return false; 1011} 1012 1013/// \brief Checks availability of the function depending on the current 1014/// function context. Inside an unavailable function, unavailability is ignored. 1015/// 1016/// \returns true if \arg FD is unavailable and current context is inside 1017/// an available function, false otherwise. 1018bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1019 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1020} 1021 1022/// \brief Tries a user-defined conversion from From to ToType. 1023/// 1024/// Produces an implicit conversion sequence for when a standard conversion 1025/// is not an option. See TryImplicitConversion for more information. 1026static ImplicitConversionSequence 1027TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1028 bool SuppressUserConversions, 1029 bool AllowExplicit, 1030 bool InOverloadResolution, 1031 bool CStyle, 1032 bool AllowObjCWritebackConversion) { 1033 ImplicitConversionSequence ICS; 1034 1035 if (SuppressUserConversions) { 1036 // We're not in the case above, so there is no conversion that 1037 // we can perform. 1038 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1039 return ICS; 1040 } 1041 1042 // Attempt user-defined conversion. 1043 OverloadCandidateSet Conversions(From->getExprLoc()); 1044 OverloadingResult UserDefResult 1045 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1046 AllowExplicit); 1047 1048 if (UserDefResult == OR_Success) { 1049 ICS.setUserDefined(); 1050 // C++ [over.ics.user]p4: 1051 // A conversion of an expression of class type to the same class 1052 // type is given Exact Match rank, and a conversion of an 1053 // expression of class type to a base class of that type is 1054 // given Conversion rank, in spite of the fact that a copy 1055 // constructor (i.e., a user-defined conversion function) is 1056 // called for those cases. 1057 if (CXXConstructorDecl *Constructor 1058 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1059 QualType FromCanon 1060 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1061 QualType ToCanon 1062 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1063 if (Constructor->isCopyConstructor() && 1064 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1065 // Turn this into a "standard" conversion sequence, so that it 1066 // gets ranked with standard conversion sequences. 1067 ICS.setStandard(); 1068 ICS.Standard.setAsIdentityConversion(); 1069 ICS.Standard.setFromType(From->getType()); 1070 ICS.Standard.setAllToTypes(ToType); 1071 ICS.Standard.CopyConstructor = Constructor; 1072 if (ToCanon != FromCanon) 1073 ICS.Standard.Second = ICK_Derived_To_Base; 1074 } 1075 } 1076 1077 // C++ [over.best.ics]p4: 1078 // However, when considering the argument of a user-defined 1079 // conversion function that is a candidate by 13.3.1.3 when 1080 // invoked for the copying of the temporary in the second step 1081 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1082 // 13.3.1.6 in all cases, only standard conversion sequences and 1083 // ellipsis conversion sequences are allowed. 1084 if (SuppressUserConversions && ICS.isUserDefined()) { 1085 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1086 } 1087 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1088 ICS.setAmbiguous(); 1089 ICS.Ambiguous.setFromType(From->getType()); 1090 ICS.Ambiguous.setToType(ToType); 1091 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1092 Cand != Conversions.end(); ++Cand) 1093 if (Cand->Viable) 1094 ICS.Ambiguous.addConversion(Cand->Function); 1095 } else { 1096 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1097 } 1098 1099 return ICS; 1100} 1101 1102/// TryImplicitConversion - Attempt to perform an implicit conversion 1103/// from the given expression (Expr) to the given type (ToType). This 1104/// function returns an implicit conversion sequence that can be used 1105/// to perform the initialization. Given 1106/// 1107/// void f(float f); 1108/// void g(int i) { f(i); } 1109/// 1110/// this routine would produce an implicit conversion sequence to 1111/// describe the initialization of f from i, which will be a standard 1112/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1113/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1114// 1115/// Note that this routine only determines how the conversion can be 1116/// performed; it does not actually perform the conversion. As such, 1117/// it will not produce any diagnostics if no conversion is available, 1118/// but will instead return an implicit conversion sequence of kind 1119/// "BadConversion". 1120/// 1121/// If @p SuppressUserConversions, then user-defined conversions are 1122/// not permitted. 1123/// If @p AllowExplicit, then explicit user-defined conversions are 1124/// permitted. 1125/// 1126/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1127/// writeback conversion, which allows __autoreleasing id* parameters to 1128/// be initialized with __strong id* or __weak id* arguments. 1129static ImplicitConversionSequence 1130TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1131 bool SuppressUserConversions, 1132 bool AllowExplicit, 1133 bool InOverloadResolution, 1134 bool CStyle, 1135 bool AllowObjCWritebackConversion) { 1136 ImplicitConversionSequence ICS; 1137 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1138 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1139 ICS.setStandard(); 1140 return ICS; 1141 } 1142 1143 if (!S.getLangOpts().CPlusPlus) { 1144 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1145 return ICS; 1146 } 1147 1148 // C++ [over.ics.user]p4: 1149 // A conversion of an expression of class type to the same class 1150 // type is given Exact Match rank, and a conversion of an 1151 // expression of class type to a base class of that type is 1152 // given Conversion rank, in spite of the fact that a copy/move 1153 // constructor (i.e., a user-defined conversion function) is 1154 // called for those cases. 1155 QualType FromType = From->getType(); 1156 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1157 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1158 S.IsDerivedFrom(FromType, ToType))) { 1159 ICS.setStandard(); 1160 ICS.Standard.setAsIdentityConversion(); 1161 ICS.Standard.setFromType(FromType); 1162 ICS.Standard.setAllToTypes(ToType); 1163 1164 // We don't actually check at this point whether there is a valid 1165 // copy/move constructor, since overloading just assumes that it 1166 // exists. When we actually perform initialization, we'll find the 1167 // appropriate constructor to copy the returned object, if needed. 1168 ICS.Standard.CopyConstructor = 0; 1169 1170 // Determine whether this is considered a derived-to-base conversion. 1171 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1172 ICS.Standard.Second = ICK_Derived_To_Base; 1173 1174 return ICS; 1175 } 1176 1177 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1178 AllowExplicit, InOverloadResolution, CStyle, 1179 AllowObjCWritebackConversion); 1180} 1181 1182ImplicitConversionSequence 1183Sema::TryImplicitConversion(Expr *From, QualType ToType, 1184 bool SuppressUserConversions, 1185 bool AllowExplicit, 1186 bool InOverloadResolution, 1187 bool CStyle, 1188 bool AllowObjCWritebackConversion) { 1189 return clang::TryImplicitConversion(*this, From, ToType, 1190 SuppressUserConversions, AllowExplicit, 1191 InOverloadResolution, CStyle, 1192 AllowObjCWritebackConversion); 1193} 1194 1195/// PerformImplicitConversion - Perform an implicit conversion of the 1196/// expression From to the type ToType. Returns the 1197/// converted expression. Flavor is the kind of conversion we're 1198/// performing, used in the error message. If @p AllowExplicit, 1199/// explicit user-defined conversions are permitted. 1200ExprResult 1201Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1202 AssignmentAction Action, bool AllowExplicit) { 1203 ImplicitConversionSequence ICS; 1204 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1205} 1206 1207ExprResult 1208Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1209 AssignmentAction Action, bool AllowExplicit, 1210 ImplicitConversionSequence& ICS) { 1211 if (checkPlaceholderForOverload(*this, From)) 1212 return ExprError(); 1213 1214 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1215 bool AllowObjCWritebackConversion 1216 = getLangOpts().ObjCAutoRefCount && 1217 (Action == AA_Passing || Action == AA_Sending); 1218 1219 ICS = clang::TryImplicitConversion(*this, From, ToType, 1220 /*SuppressUserConversions=*/false, 1221 AllowExplicit, 1222 /*InOverloadResolution=*/false, 1223 /*CStyle=*/false, 1224 AllowObjCWritebackConversion); 1225 return PerformImplicitConversion(From, ToType, ICS, Action); 1226} 1227 1228/// \brief Determine whether the conversion from FromType to ToType is a valid 1229/// conversion that strips "noreturn" off the nested function type. 1230bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1231 QualType &ResultTy) { 1232 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1233 return false; 1234 1235 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1236 // where F adds one of the following at most once: 1237 // - a pointer 1238 // - a member pointer 1239 // - a block pointer 1240 CanQualType CanTo = Context.getCanonicalType(ToType); 1241 CanQualType CanFrom = Context.getCanonicalType(FromType); 1242 Type::TypeClass TyClass = CanTo->getTypeClass(); 1243 if (TyClass != CanFrom->getTypeClass()) return false; 1244 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1245 if (TyClass == Type::Pointer) { 1246 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1247 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1248 } else if (TyClass == Type::BlockPointer) { 1249 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1250 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1251 } else if (TyClass == Type::MemberPointer) { 1252 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1253 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1254 } else { 1255 return false; 1256 } 1257 1258 TyClass = CanTo->getTypeClass(); 1259 if (TyClass != CanFrom->getTypeClass()) return false; 1260 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1261 return false; 1262 } 1263 1264 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1265 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1266 if (!EInfo.getNoReturn()) return false; 1267 1268 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1269 assert(QualType(FromFn, 0).isCanonical()); 1270 if (QualType(FromFn, 0) != CanTo) return false; 1271 1272 ResultTy = ToType; 1273 return true; 1274} 1275 1276/// \brief Determine whether the conversion from FromType to ToType is a valid 1277/// vector conversion. 1278/// 1279/// \param ICK Will be set to the vector conversion kind, if this is a vector 1280/// conversion. 1281static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1282 QualType ToType, ImplicitConversionKind &ICK) { 1283 // We need at least one of these types to be a vector type to have a vector 1284 // conversion. 1285 if (!ToType->isVectorType() && !FromType->isVectorType()) 1286 return false; 1287 1288 // Identical types require no conversions. 1289 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1290 return false; 1291 1292 // There are no conversions between extended vector types, only identity. 1293 if (ToType->isExtVectorType()) { 1294 // There are no conversions between extended vector types other than the 1295 // identity conversion. 1296 if (FromType->isExtVectorType()) 1297 return false; 1298 1299 // Vector splat from any arithmetic type to a vector. 1300 if (FromType->isArithmeticType()) { 1301 ICK = ICK_Vector_Splat; 1302 return true; 1303 } 1304 } 1305 1306 // We can perform the conversion between vector types in the following cases: 1307 // 1)vector types are equivalent AltiVec and GCC vector types 1308 // 2)lax vector conversions are permitted and the vector types are of the 1309 // same size 1310 if (ToType->isVectorType() && FromType->isVectorType()) { 1311 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1312 (Context.getLangOpts().LaxVectorConversions && 1313 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1314 ICK = ICK_Vector_Conversion; 1315 return true; 1316 } 1317 } 1318 1319 return false; 1320} 1321 1322static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1323 bool InOverloadResolution, 1324 StandardConversionSequence &SCS, 1325 bool CStyle); 1326 1327/// IsStandardConversion - Determines whether there is a standard 1328/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1329/// expression From to the type ToType. Standard conversion sequences 1330/// only consider non-class types; for conversions that involve class 1331/// types, use TryImplicitConversion. If a conversion exists, SCS will 1332/// contain the standard conversion sequence required to perform this 1333/// conversion and this routine will return true. Otherwise, this 1334/// routine will return false and the value of SCS is unspecified. 1335static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1336 bool InOverloadResolution, 1337 StandardConversionSequence &SCS, 1338 bool CStyle, 1339 bool AllowObjCWritebackConversion) { 1340 QualType FromType = From->getType(); 1341 1342 // Standard conversions (C++ [conv]) 1343 SCS.setAsIdentityConversion(); 1344 SCS.DeprecatedStringLiteralToCharPtr = false; 1345 SCS.IncompatibleObjC = false; 1346 SCS.setFromType(FromType); 1347 SCS.CopyConstructor = 0; 1348 1349 // There are no standard conversions for class types in C++, so 1350 // abort early. When overloading in C, however, we do permit 1351 if (FromType->isRecordType() || ToType->isRecordType()) { 1352 if (S.getLangOpts().CPlusPlus) 1353 return false; 1354 1355 // When we're overloading in C, we allow, as standard conversions, 1356 } 1357 1358 // The first conversion can be an lvalue-to-rvalue conversion, 1359 // array-to-pointer conversion, or function-to-pointer conversion 1360 // (C++ 4p1). 1361 1362 if (FromType == S.Context.OverloadTy) { 1363 DeclAccessPair AccessPair; 1364 if (FunctionDecl *Fn 1365 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1366 AccessPair)) { 1367 // We were able to resolve the address of the overloaded function, 1368 // so we can convert to the type of that function. 1369 FromType = Fn->getType(); 1370 1371 // we can sometimes resolve &foo<int> regardless of ToType, so check 1372 // if the type matches (identity) or we are converting to bool 1373 if (!S.Context.hasSameUnqualifiedType( 1374 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1375 QualType resultTy; 1376 // if the function type matches except for [[noreturn]], it's ok 1377 if (!S.IsNoReturnConversion(FromType, 1378 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1379 // otherwise, only a boolean conversion is standard 1380 if (!ToType->isBooleanType()) 1381 return false; 1382 } 1383 1384 // Check if the "from" expression is taking the address of an overloaded 1385 // function and recompute the FromType accordingly. Take advantage of the 1386 // fact that non-static member functions *must* have such an address-of 1387 // expression. 1388 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1389 if (Method && !Method->isStatic()) { 1390 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1391 "Non-unary operator on non-static member address"); 1392 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1393 == UO_AddrOf && 1394 "Non-address-of operator on non-static member address"); 1395 const Type *ClassType 1396 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1397 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1398 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1399 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1400 UO_AddrOf && 1401 "Non-address-of operator for overloaded function expression"); 1402 FromType = S.Context.getPointerType(FromType); 1403 } 1404 1405 // Check that we've computed the proper type after overload resolution. 1406 assert(S.Context.hasSameType( 1407 FromType, 1408 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1409 } else { 1410 return false; 1411 } 1412 } 1413 // Lvalue-to-rvalue conversion (C++11 4.1): 1414 // A glvalue (3.10) of a non-function, non-array type T can 1415 // be converted to a prvalue. 1416 bool argIsLValue = From->isGLValue(); 1417 if (argIsLValue && 1418 !FromType->isFunctionType() && !FromType->isArrayType() && 1419 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1420 SCS.First = ICK_Lvalue_To_Rvalue; 1421 1422 // C11 6.3.2.1p2: 1423 // ... if the lvalue has atomic type, the value has the non-atomic version 1424 // of the type of the lvalue ... 1425 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1426 FromType = Atomic->getValueType(); 1427 1428 // If T is a non-class type, the type of the rvalue is the 1429 // cv-unqualified version of T. Otherwise, the type of the rvalue 1430 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1431 // just strip the qualifiers because they don't matter. 1432 FromType = FromType.getUnqualifiedType(); 1433 } else if (FromType->isArrayType()) { 1434 // Array-to-pointer conversion (C++ 4.2) 1435 SCS.First = ICK_Array_To_Pointer; 1436 1437 // An lvalue or rvalue of type "array of N T" or "array of unknown 1438 // bound of T" can be converted to an rvalue of type "pointer to 1439 // T" (C++ 4.2p1). 1440 FromType = S.Context.getArrayDecayedType(FromType); 1441 1442 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1443 // This conversion is deprecated. (C++ D.4). 1444 SCS.DeprecatedStringLiteralToCharPtr = true; 1445 1446 // For the purpose of ranking in overload resolution 1447 // (13.3.3.1.1), this conversion is considered an 1448 // array-to-pointer conversion followed by a qualification 1449 // conversion (4.4). (C++ 4.2p2) 1450 SCS.Second = ICK_Identity; 1451 SCS.Third = ICK_Qualification; 1452 SCS.QualificationIncludesObjCLifetime = false; 1453 SCS.setAllToTypes(FromType); 1454 return true; 1455 } 1456 } else if (FromType->isFunctionType() && argIsLValue) { 1457 // Function-to-pointer conversion (C++ 4.3). 1458 SCS.First = ICK_Function_To_Pointer; 1459 1460 // An lvalue of function type T can be converted to an rvalue of 1461 // type "pointer to T." The result is a pointer to the 1462 // function. (C++ 4.3p1). 1463 FromType = S.Context.getPointerType(FromType); 1464 } else { 1465 // We don't require any conversions for the first step. 1466 SCS.First = ICK_Identity; 1467 } 1468 SCS.setToType(0, FromType); 1469 1470 // The second conversion can be an integral promotion, floating 1471 // point promotion, integral conversion, floating point conversion, 1472 // floating-integral conversion, pointer conversion, 1473 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1474 // For overloading in C, this can also be a "compatible-type" 1475 // conversion. 1476 bool IncompatibleObjC = false; 1477 ImplicitConversionKind SecondICK = ICK_Identity; 1478 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1479 // The unqualified versions of the types are the same: there's no 1480 // conversion to do. 1481 SCS.Second = ICK_Identity; 1482 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1483 // Integral promotion (C++ 4.5). 1484 SCS.Second = ICK_Integral_Promotion; 1485 FromType = ToType.getUnqualifiedType(); 1486 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1487 // Floating point promotion (C++ 4.6). 1488 SCS.Second = ICK_Floating_Promotion; 1489 FromType = ToType.getUnqualifiedType(); 1490 } else if (S.IsComplexPromotion(FromType, ToType)) { 1491 // Complex promotion (Clang extension) 1492 SCS.Second = ICK_Complex_Promotion; 1493 FromType = ToType.getUnqualifiedType(); 1494 } else if (ToType->isBooleanType() && 1495 (FromType->isArithmeticType() || 1496 FromType->isAnyPointerType() || 1497 FromType->isBlockPointerType() || 1498 FromType->isMemberPointerType() || 1499 FromType->isNullPtrType())) { 1500 // Boolean conversions (C++ 4.12). 1501 SCS.Second = ICK_Boolean_Conversion; 1502 FromType = S.Context.BoolTy; 1503 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1504 ToType->isIntegralType(S.Context)) { 1505 // Integral conversions (C++ 4.7). 1506 SCS.Second = ICK_Integral_Conversion; 1507 FromType = ToType.getUnqualifiedType(); 1508 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1509 // Complex conversions (C99 6.3.1.6) 1510 SCS.Second = ICK_Complex_Conversion; 1511 FromType = ToType.getUnqualifiedType(); 1512 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1513 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1514 // Complex-real conversions (C99 6.3.1.7) 1515 SCS.Second = ICK_Complex_Real; 1516 FromType = ToType.getUnqualifiedType(); 1517 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1518 // Floating point conversions (C++ 4.8). 1519 SCS.Second = ICK_Floating_Conversion; 1520 FromType = ToType.getUnqualifiedType(); 1521 } else if ((FromType->isRealFloatingType() && 1522 ToType->isIntegralType(S.Context)) || 1523 (FromType->isIntegralOrUnscopedEnumerationType() && 1524 ToType->isRealFloatingType())) { 1525 // Floating-integral conversions (C++ 4.9). 1526 SCS.Second = ICK_Floating_Integral; 1527 FromType = ToType.getUnqualifiedType(); 1528 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1529 SCS.Second = ICK_Block_Pointer_Conversion; 1530 } else if (AllowObjCWritebackConversion && 1531 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1532 SCS.Second = ICK_Writeback_Conversion; 1533 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1534 FromType, IncompatibleObjC)) { 1535 // Pointer conversions (C++ 4.10). 1536 SCS.Second = ICK_Pointer_Conversion; 1537 SCS.IncompatibleObjC = IncompatibleObjC; 1538 FromType = FromType.getUnqualifiedType(); 1539 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1540 InOverloadResolution, FromType)) { 1541 // Pointer to member conversions (4.11). 1542 SCS.Second = ICK_Pointer_Member; 1543 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1544 SCS.Second = SecondICK; 1545 FromType = ToType.getUnqualifiedType(); 1546 } else if (!S.getLangOpts().CPlusPlus && 1547 S.Context.typesAreCompatible(ToType, FromType)) { 1548 // Compatible conversions (Clang extension for C function overloading) 1549 SCS.Second = ICK_Compatible_Conversion; 1550 FromType = ToType.getUnqualifiedType(); 1551 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1552 // Treat a conversion that strips "noreturn" as an identity conversion. 1553 SCS.Second = ICK_NoReturn_Adjustment; 1554 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1555 InOverloadResolution, 1556 SCS, CStyle)) { 1557 SCS.Second = ICK_TransparentUnionConversion; 1558 FromType = ToType; 1559 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1560 CStyle)) { 1561 // tryAtomicConversion has updated the standard conversion sequence 1562 // appropriately. 1563 return true; 1564 } else { 1565 // No second conversion required. 1566 SCS.Second = ICK_Identity; 1567 } 1568 SCS.setToType(1, FromType); 1569 1570 QualType CanonFrom; 1571 QualType CanonTo; 1572 // The third conversion can be a qualification conversion (C++ 4p1). 1573 bool ObjCLifetimeConversion; 1574 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1575 ObjCLifetimeConversion)) { 1576 SCS.Third = ICK_Qualification; 1577 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1578 FromType = ToType; 1579 CanonFrom = S.Context.getCanonicalType(FromType); 1580 CanonTo = S.Context.getCanonicalType(ToType); 1581 } else { 1582 // No conversion required 1583 SCS.Third = ICK_Identity; 1584 1585 // C++ [over.best.ics]p6: 1586 // [...] Any difference in top-level cv-qualification is 1587 // subsumed by the initialization itself and does not constitute 1588 // a conversion. [...] 1589 CanonFrom = S.Context.getCanonicalType(FromType); 1590 CanonTo = S.Context.getCanonicalType(ToType); 1591 if (CanonFrom.getLocalUnqualifiedType() 1592 == CanonTo.getLocalUnqualifiedType() && 1593 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1594 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1595 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1596 FromType = ToType; 1597 CanonFrom = CanonTo; 1598 } 1599 } 1600 SCS.setToType(2, FromType); 1601 1602 // If we have not converted the argument type to the parameter type, 1603 // this is a bad conversion sequence. 1604 if (CanonFrom != CanonTo) 1605 return false; 1606 1607 return true; 1608} 1609 1610static bool 1611IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1612 QualType &ToType, 1613 bool InOverloadResolution, 1614 StandardConversionSequence &SCS, 1615 bool CStyle) { 1616 1617 const RecordType *UT = ToType->getAsUnionType(); 1618 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1619 return false; 1620 // The field to initialize within the transparent union. 1621 RecordDecl *UD = UT->getDecl(); 1622 // It's compatible if the expression matches any of the fields. 1623 for (RecordDecl::field_iterator it = UD->field_begin(), 1624 itend = UD->field_end(); 1625 it != itend; ++it) { 1626 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1627 CStyle, /*ObjCWritebackConversion=*/false)) { 1628 ToType = it->getType(); 1629 return true; 1630 } 1631 } 1632 return false; 1633} 1634 1635/// IsIntegralPromotion - Determines whether the conversion from the 1636/// expression From (whose potentially-adjusted type is FromType) to 1637/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1638/// sets PromotedType to the promoted type. 1639bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1640 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1641 // All integers are built-in. 1642 if (!To) { 1643 return false; 1644 } 1645 1646 // An rvalue of type char, signed char, unsigned char, short int, or 1647 // unsigned short int can be converted to an rvalue of type int if 1648 // int can represent all the values of the source type; otherwise, 1649 // the source rvalue can be converted to an rvalue of type unsigned 1650 // int (C++ 4.5p1). 1651 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1652 !FromType->isEnumeralType()) { 1653 if (// We can promote any signed, promotable integer type to an int 1654 (FromType->isSignedIntegerType() || 1655 // We can promote any unsigned integer type whose size is 1656 // less than int to an int. 1657 (!FromType->isSignedIntegerType() && 1658 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1659 return To->getKind() == BuiltinType::Int; 1660 } 1661 1662 return To->getKind() == BuiltinType::UInt; 1663 } 1664 1665 // C++0x [conv.prom]p3: 1666 // A prvalue of an unscoped enumeration type whose underlying type is not 1667 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1668 // following types that can represent all the values of the enumeration 1669 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1670 // unsigned int, long int, unsigned long int, long long int, or unsigned 1671 // long long int. If none of the types in that list can represent all the 1672 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1673 // type can be converted to an rvalue a prvalue of the extended integer type 1674 // with lowest integer conversion rank (4.13) greater than the rank of long 1675 // long in which all the values of the enumeration can be represented. If 1676 // there are two such extended types, the signed one is chosen. 1677 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1678 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1679 // provided for a scoped enumeration. 1680 if (FromEnumType->getDecl()->isScoped()) 1681 return false; 1682 1683 // We have already pre-calculated the promotion type, so this is trivial. 1684 if (ToType->isIntegerType() && 1685 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1686 return Context.hasSameUnqualifiedType(ToType, 1687 FromEnumType->getDecl()->getPromotionType()); 1688 } 1689 1690 // C++0x [conv.prom]p2: 1691 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1692 // to an rvalue a prvalue of the first of the following types that can 1693 // represent all the values of its underlying type: int, unsigned int, 1694 // long int, unsigned long int, long long int, or unsigned long long int. 1695 // If none of the types in that list can represent all the values of its 1696 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1697 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1698 // type. 1699 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1700 ToType->isIntegerType()) { 1701 // Determine whether the type we're converting from is signed or 1702 // unsigned. 1703 bool FromIsSigned = FromType->isSignedIntegerType(); 1704 uint64_t FromSize = Context.getTypeSize(FromType); 1705 1706 // The types we'll try to promote to, in the appropriate 1707 // order. Try each of these types. 1708 QualType PromoteTypes[6] = { 1709 Context.IntTy, Context.UnsignedIntTy, 1710 Context.LongTy, Context.UnsignedLongTy , 1711 Context.LongLongTy, Context.UnsignedLongLongTy 1712 }; 1713 for (int Idx = 0; Idx < 6; ++Idx) { 1714 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1715 if (FromSize < ToSize || 1716 (FromSize == ToSize && 1717 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1718 // We found the type that we can promote to. If this is the 1719 // type we wanted, we have a promotion. Otherwise, no 1720 // promotion. 1721 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1722 } 1723 } 1724 } 1725 1726 // An rvalue for an integral bit-field (9.6) can be converted to an 1727 // rvalue of type int if int can represent all the values of the 1728 // bit-field; otherwise, it can be converted to unsigned int if 1729 // unsigned int can represent all the values of the bit-field. If 1730 // the bit-field is larger yet, no integral promotion applies to 1731 // it. If the bit-field has an enumerated type, it is treated as any 1732 // other value of that type for promotion purposes (C++ 4.5p3). 1733 // FIXME: We should delay checking of bit-fields until we actually perform the 1734 // conversion. 1735 using llvm::APSInt; 1736 if (From) 1737 if (FieldDecl *MemberDecl = From->getBitField()) { 1738 APSInt BitWidth; 1739 if (FromType->isIntegralType(Context) && 1740 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1741 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1742 ToSize = Context.getTypeSize(ToType); 1743 1744 // Are we promoting to an int from a bitfield that fits in an int? 1745 if (BitWidth < ToSize || 1746 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1747 return To->getKind() == BuiltinType::Int; 1748 } 1749 1750 // Are we promoting to an unsigned int from an unsigned bitfield 1751 // that fits into an unsigned int? 1752 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1753 return To->getKind() == BuiltinType::UInt; 1754 } 1755 1756 return false; 1757 } 1758 } 1759 1760 // An rvalue of type bool can be converted to an rvalue of type int, 1761 // with false becoming zero and true becoming one (C++ 4.5p4). 1762 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1763 return true; 1764 } 1765 1766 return false; 1767} 1768 1769/// IsFloatingPointPromotion - Determines whether the conversion from 1770/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1771/// returns true and sets PromotedType to the promoted type. 1772bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1773 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1774 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1775 /// An rvalue of type float can be converted to an rvalue of type 1776 /// double. (C++ 4.6p1). 1777 if (FromBuiltin->getKind() == BuiltinType::Float && 1778 ToBuiltin->getKind() == BuiltinType::Double) 1779 return true; 1780 1781 // C99 6.3.1.5p1: 1782 // When a float is promoted to double or long double, or a 1783 // double is promoted to long double [...]. 1784 if (!getLangOpts().CPlusPlus && 1785 (FromBuiltin->getKind() == BuiltinType::Float || 1786 FromBuiltin->getKind() == BuiltinType::Double) && 1787 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1788 return true; 1789 1790 // Half can be promoted to float. 1791 if (FromBuiltin->getKind() == BuiltinType::Half && 1792 ToBuiltin->getKind() == BuiltinType::Float) 1793 return true; 1794 } 1795 1796 return false; 1797} 1798 1799/// \brief Determine if a conversion is a complex promotion. 1800/// 1801/// A complex promotion is defined as a complex -> complex conversion 1802/// where the conversion between the underlying real types is a 1803/// floating-point or integral promotion. 1804bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1805 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1806 if (!FromComplex) 1807 return false; 1808 1809 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1810 if (!ToComplex) 1811 return false; 1812 1813 return IsFloatingPointPromotion(FromComplex->getElementType(), 1814 ToComplex->getElementType()) || 1815 IsIntegralPromotion(0, FromComplex->getElementType(), 1816 ToComplex->getElementType()); 1817} 1818 1819/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1820/// the pointer type FromPtr to a pointer to type ToPointee, with the 1821/// same type qualifiers as FromPtr has on its pointee type. ToType, 1822/// if non-empty, will be a pointer to ToType that may or may not have 1823/// the right set of qualifiers on its pointee. 1824/// 1825static QualType 1826BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1827 QualType ToPointee, QualType ToType, 1828 ASTContext &Context, 1829 bool StripObjCLifetime = false) { 1830 assert((FromPtr->getTypeClass() == Type::Pointer || 1831 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1832 "Invalid similarly-qualified pointer type"); 1833 1834 /// Conversions to 'id' subsume cv-qualifier conversions. 1835 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1836 return ToType.getUnqualifiedType(); 1837 1838 QualType CanonFromPointee 1839 = Context.getCanonicalType(FromPtr->getPointeeType()); 1840 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1841 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1842 1843 if (StripObjCLifetime) 1844 Quals.removeObjCLifetime(); 1845 1846 // Exact qualifier match -> return the pointer type we're converting to. 1847 if (CanonToPointee.getLocalQualifiers() == Quals) { 1848 // ToType is exactly what we need. Return it. 1849 if (!ToType.isNull()) 1850 return ToType.getUnqualifiedType(); 1851 1852 // Build a pointer to ToPointee. It has the right qualifiers 1853 // already. 1854 if (isa<ObjCObjectPointerType>(ToType)) 1855 return Context.getObjCObjectPointerType(ToPointee); 1856 return Context.getPointerType(ToPointee); 1857 } 1858 1859 // Just build a canonical type that has the right qualifiers. 1860 QualType QualifiedCanonToPointee 1861 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1862 1863 if (isa<ObjCObjectPointerType>(ToType)) 1864 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1865 return Context.getPointerType(QualifiedCanonToPointee); 1866} 1867 1868static bool isNullPointerConstantForConversion(Expr *Expr, 1869 bool InOverloadResolution, 1870 ASTContext &Context) { 1871 // Handle value-dependent integral null pointer constants correctly. 1872 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1873 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1874 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1875 return !InOverloadResolution; 1876 1877 return Expr->isNullPointerConstant(Context, 1878 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1879 : Expr::NPC_ValueDependentIsNull); 1880} 1881 1882/// IsPointerConversion - Determines whether the conversion of the 1883/// expression From, which has the (possibly adjusted) type FromType, 1884/// can be converted to the type ToType via a pointer conversion (C++ 1885/// 4.10). If so, returns true and places the converted type (that 1886/// might differ from ToType in its cv-qualifiers at some level) into 1887/// ConvertedType. 1888/// 1889/// This routine also supports conversions to and from block pointers 1890/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1891/// pointers to interfaces. FIXME: Once we've determined the 1892/// appropriate overloading rules for Objective-C, we may want to 1893/// split the Objective-C checks into a different routine; however, 1894/// GCC seems to consider all of these conversions to be pointer 1895/// conversions, so for now they live here. IncompatibleObjC will be 1896/// set if the conversion is an allowed Objective-C conversion that 1897/// should result in a warning. 1898bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1899 bool InOverloadResolution, 1900 QualType& ConvertedType, 1901 bool &IncompatibleObjC) { 1902 IncompatibleObjC = false; 1903 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1904 IncompatibleObjC)) 1905 return true; 1906 1907 // Conversion from a null pointer constant to any Objective-C pointer type. 1908 if (ToType->isObjCObjectPointerType() && 1909 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1910 ConvertedType = ToType; 1911 return true; 1912 } 1913 1914 // Blocks: Block pointers can be converted to void*. 1915 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1916 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1917 ConvertedType = ToType; 1918 return true; 1919 } 1920 // Blocks: A null pointer constant can be converted to a block 1921 // pointer type. 1922 if (ToType->isBlockPointerType() && 1923 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1924 ConvertedType = ToType; 1925 return true; 1926 } 1927 1928 // If the left-hand-side is nullptr_t, the right side can be a null 1929 // pointer constant. 1930 if (ToType->isNullPtrType() && 1931 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1932 ConvertedType = ToType; 1933 return true; 1934 } 1935 1936 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1937 if (!ToTypePtr) 1938 return false; 1939 1940 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1941 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1942 ConvertedType = ToType; 1943 return true; 1944 } 1945 1946 // Beyond this point, both types need to be pointers 1947 // , including objective-c pointers. 1948 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1949 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1950 !getLangOpts().ObjCAutoRefCount) { 1951 ConvertedType = BuildSimilarlyQualifiedPointerType( 1952 FromType->getAs<ObjCObjectPointerType>(), 1953 ToPointeeType, 1954 ToType, Context); 1955 return true; 1956 } 1957 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1958 if (!FromTypePtr) 1959 return false; 1960 1961 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1962 1963 // If the unqualified pointee types are the same, this can't be a 1964 // pointer conversion, so don't do all of the work below. 1965 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1966 return false; 1967 1968 // An rvalue of type "pointer to cv T," where T is an object type, 1969 // can be converted to an rvalue of type "pointer to cv void" (C++ 1970 // 4.10p2). 1971 if (FromPointeeType->isIncompleteOrObjectType() && 1972 ToPointeeType->isVoidType()) { 1973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1974 ToPointeeType, 1975 ToType, Context, 1976 /*StripObjCLifetime=*/true); 1977 return true; 1978 } 1979 1980 // MSVC allows implicit function to void* type conversion. 1981 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 1982 ToPointeeType->isVoidType()) { 1983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1984 ToPointeeType, 1985 ToType, Context); 1986 return true; 1987 } 1988 1989 // When we're overloading in C, we allow a special kind of pointer 1990 // conversion for compatible-but-not-identical pointee types. 1991 if (!getLangOpts().CPlusPlus && 1992 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1993 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1994 ToPointeeType, 1995 ToType, Context); 1996 return true; 1997 } 1998 1999 // C++ [conv.ptr]p3: 2000 // 2001 // An rvalue of type "pointer to cv D," where D is a class type, 2002 // can be converted to an rvalue of type "pointer to cv B," where 2003 // B is a base class (clause 10) of D. If B is an inaccessible 2004 // (clause 11) or ambiguous (10.2) base class of D, a program that 2005 // necessitates this conversion is ill-formed. The result of the 2006 // conversion is a pointer to the base class sub-object of the 2007 // derived class object. The null pointer value is converted to 2008 // the null pointer value of the destination type. 2009 // 2010 // Note that we do not check for ambiguity or inaccessibility 2011 // here. That is handled by CheckPointerConversion. 2012 if (getLangOpts().CPlusPlus && 2013 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2014 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2015 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2016 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2017 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2018 ToPointeeType, 2019 ToType, Context); 2020 return true; 2021 } 2022 2023 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2024 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2026 ToPointeeType, 2027 ToType, Context); 2028 return true; 2029 } 2030 2031 return false; 2032} 2033 2034/// \brief Adopt the given qualifiers for the given type. 2035static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2036 Qualifiers TQs = T.getQualifiers(); 2037 2038 // Check whether qualifiers already match. 2039 if (TQs == Qs) 2040 return T; 2041 2042 if (Qs.compatiblyIncludes(TQs)) 2043 return Context.getQualifiedType(T, Qs); 2044 2045 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2046} 2047 2048/// isObjCPointerConversion - Determines whether this is an 2049/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2050/// with the same arguments and return values. 2051bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2052 QualType& ConvertedType, 2053 bool &IncompatibleObjC) { 2054 if (!getLangOpts().ObjC1) 2055 return false; 2056 2057 // The set of qualifiers on the type we're converting from. 2058 Qualifiers FromQualifiers = FromType.getQualifiers(); 2059 2060 // First, we handle all conversions on ObjC object pointer types. 2061 const ObjCObjectPointerType* ToObjCPtr = 2062 ToType->getAs<ObjCObjectPointerType>(); 2063 const ObjCObjectPointerType *FromObjCPtr = 2064 FromType->getAs<ObjCObjectPointerType>(); 2065 2066 if (ToObjCPtr && FromObjCPtr) { 2067 // If the pointee types are the same (ignoring qualifications), 2068 // then this is not a pointer conversion. 2069 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2070 FromObjCPtr->getPointeeType())) 2071 return false; 2072 2073 // Check for compatible 2074 // Objective C++: We're able to convert between "id" or "Class" and a 2075 // pointer to any interface (in both directions). 2076 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2077 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2078 return true; 2079 } 2080 // Conversions with Objective-C's id<...>. 2081 if ((FromObjCPtr->isObjCQualifiedIdType() || 2082 ToObjCPtr->isObjCQualifiedIdType()) && 2083 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2084 /*compare=*/false)) { 2085 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2086 return true; 2087 } 2088 // Objective C++: We're able to convert from a pointer to an 2089 // interface to a pointer to a different interface. 2090 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2091 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2092 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2093 if (getLangOpts().CPlusPlus && LHS && RHS && 2094 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2095 FromObjCPtr->getPointeeType())) 2096 return false; 2097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2098 ToObjCPtr->getPointeeType(), 2099 ToType, Context); 2100 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2101 return true; 2102 } 2103 2104 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2105 // Okay: this is some kind of implicit downcast of Objective-C 2106 // interfaces, which is permitted. However, we're going to 2107 // complain about it. 2108 IncompatibleObjC = true; 2109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2110 ToObjCPtr->getPointeeType(), 2111 ToType, Context); 2112 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2113 return true; 2114 } 2115 } 2116 // Beyond this point, both types need to be C pointers or block pointers. 2117 QualType ToPointeeType; 2118 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2119 ToPointeeType = ToCPtr->getPointeeType(); 2120 else if (const BlockPointerType *ToBlockPtr = 2121 ToType->getAs<BlockPointerType>()) { 2122 // Objective C++: We're able to convert from a pointer to any object 2123 // to a block pointer type. 2124 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2125 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2126 return true; 2127 } 2128 ToPointeeType = ToBlockPtr->getPointeeType(); 2129 } 2130 else if (FromType->getAs<BlockPointerType>() && 2131 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2132 // Objective C++: We're able to convert from a block pointer type to a 2133 // pointer to any object. 2134 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2135 return true; 2136 } 2137 else 2138 return false; 2139 2140 QualType FromPointeeType; 2141 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2142 FromPointeeType = FromCPtr->getPointeeType(); 2143 else if (const BlockPointerType *FromBlockPtr = 2144 FromType->getAs<BlockPointerType>()) 2145 FromPointeeType = FromBlockPtr->getPointeeType(); 2146 else 2147 return false; 2148 2149 // If we have pointers to pointers, recursively check whether this 2150 // is an Objective-C conversion. 2151 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2152 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2153 IncompatibleObjC)) { 2154 // We always complain about this conversion. 2155 IncompatibleObjC = true; 2156 ConvertedType = Context.getPointerType(ConvertedType); 2157 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2158 return true; 2159 } 2160 // Allow conversion of pointee being objective-c pointer to another one; 2161 // as in I* to id. 2162 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2163 ToPointeeType->getAs<ObjCObjectPointerType>() && 2164 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2165 IncompatibleObjC)) { 2166 2167 ConvertedType = Context.getPointerType(ConvertedType); 2168 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2169 return true; 2170 } 2171 2172 // If we have pointers to functions or blocks, check whether the only 2173 // differences in the argument and result types are in Objective-C 2174 // pointer conversions. If so, we permit the conversion (but 2175 // complain about it). 2176 const FunctionProtoType *FromFunctionType 2177 = FromPointeeType->getAs<FunctionProtoType>(); 2178 const FunctionProtoType *ToFunctionType 2179 = ToPointeeType->getAs<FunctionProtoType>(); 2180 if (FromFunctionType && ToFunctionType) { 2181 // If the function types are exactly the same, this isn't an 2182 // Objective-C pointer conversion. 2183 if (Context.getCanonicalType(FromPointeeType) 2184 == Context.getCanonicalType(ToPointeeType)) 2185 return false; 2186 2187 // Perform the quick checks that will tell us whether these 2188 // function types are obviously different. 2189 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2190 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2191 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2192 return false; 2193 2194 bool HasObjCConversion = false; 2195 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2196 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2197 // Okay, the types match exactly. Nothing to do. 2198 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2199 ToFunctionType->getResultType(), 2200 ConvertedType, IncompatibleObjC)) { 2201 // Okay, we have an Objective-C pointer conversion. 2202 HasObjCConversion = true; 2203 } else { 2204 // Function types are too different. Abort. 2205 return false; 2206 } 2207 2208 // Check argument types. 2209 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2210 ArgIdx != NumArgs; ++ArgIdx) { 2211 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2212 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2213 if (Context.getCanonicalType(FromArgType) 2214 == Context.getCanonicalType(ToArgType)) { 2215 // Okay, the types match exactly. Nothing to do. 2216 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2217 ConvertedType, IncompatibleObjC)) { 2218 // Okay, we have an Objective-C pointer conversion. 2219 HasObjCConversion = true; 2220 } else { 2221 // Argument types are too different. Abort. 2222 return false; 2223 } 2224 } 2225 2226 if (HasObjCConversion) { 2227 // We had an Objective-C conversion. Allow this pointer 2228 // conversion, but complain about it. 2229 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2230 IncompatibleObjC = true; 2231 return true; 2232 } 2233 } 2234 2235 return false; 2236} 2237 2238/// \brief Determine whether this is an Objective-C writeback conversion, 2239/// used for parameter passing when performing automatic reference counting. 2240/// 2241/// \param FromType The type we're converting form. 2242/// 2243/// \param ToType The type we're converting to. 2244/// 2245/// \param ConvertedType The type that will be produced after applying 2246/// this conversion. 2247bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2248 QualType &ConvertedType) { 2249 if (!getLangOpts().ObjCAutoRefCount || 2250 Context.hasSameUnqualifiedType(FromType, ToType)) 2251 return false; 2252 2253 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2254 QualType ToPointee; 2255 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2256 ToPointee = ToPointer->getPointeeType(); 2257 else 2258 return false; 2259 2260 Qualifiers ToQuals = ToPointee.getQualifiers(); 2261 if (!ToPointee->isObjCLifetimeType() || 2262 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2263 !ToQuals.withoutObjCLifetime().empty()) 2264 return false; 2265 2266 // Argument must be a pointer to __strong to __weak. 2267 QualType FromPointee; 2268 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2269 FromPointee = FromPointer->getPointeeType(); 2270 else 2271 return false; 2272 2273 Qualifiers FromQuals = FromPointee.getQualifiers(); 2274 if (!FromPointee->isObjCLifetimeType() || 2275 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2276 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2277 return false; 2278 2279 // Make sure that we have compatible qualifiers. 2280 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2281 if (!ToQuals.compatiblyIncludes(FromQuals)) 2282 return false; 2283 2284 // Remove qualifiers from the pointee type we're converting from; they 2285 // aren't used in the compatibility check belong, and we'll be adding back 2286 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2287 FromPointee = FromPointee.getUnqualifiedType(); 2288 2289 // The unqualified form of the pointee types must be compatible. 2290 ToPointee = ToPointee.getUnqualifiedType(); 2291 bool IncompatibleObjC; 2292 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2293 FromPointee = ToPointee; 2294 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2295 IncompatibleObjC)) 2296 return false; 2297 2298 /// \brief Construct the type we're converting to, which is a pointer to 2299 /// __autoreleasing pointee. 2300 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2301 ConvertedType = Context.getPointerType(FromPointee); 2302 return true; 2303} 2304 2305bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2306 QualType& ConvertedType) { 2307 QualType ToPointeeType; 2308 if (const BlockPointerType *ToBlockPtr = 2309 ToType->getAs<BlockPointerType>()) 2310 ToPointeeType = ToBlockPtr->getPointeeType(); 2311 else 2312 return false; 2313 2314 QualType FromPointeeType; 2315 if (const BlockPointerType *FromBlockPtr = 2316 FromType->getAs<BlockPointerType>()) 2317 FromPointeeType = FromBlockPtr->getPointeeType(); 2318 else 2319 return false; 2320 // We have pointer to blocks, check whether the only 2321 // differences in the argument and result types are in Objective-C 2322 // pointer conversions. If so, we permit the conversion. 2323 2324 const FunctionProtoType *FromFunctionType 2325 = FromPointeeType->getAs<FunctionProtoType>(); 2326 const FunctionProtoType *ToFunctionType 2327 = ToPointeeType->getAs<FunctionProtoType>(); 2328 2329 if (!FromFunctionType || !ToFunctionType) 2330 return false; 2331 2332 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2333 return true; 2334 2335 // Perform the quick checks that will tell us whether these 2336 // function types are obviously different. 2337 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2338 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2339 return false; 2340 2341 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2342 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2343 if (FromEInfo != ToEInfo) 2344 return false; 2345 2346 bool IncompatibleObjC = false; 2347 if (Context.hasSameType(FromFunctionType->getResultType(), 2348 ToFunctionType->getResultType())) { 2349 // Okay, the types match exactly. Nothing to do. 2350 } else { 2351 QualType RHS = FromFunctionType->getResultType(); 2352 QualType LHS = ToFunctionType->getResultType(); 2353 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2354 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2355 LHS = LHS.getUnqualifiedType(); 2356 2357 if (Context.hasSameType(RHS,LHS)) { 2358 // OK exact match. 2359 } else if (isObjCPointerConversion(RHS, LHS, 2360 ConvertedType, IncompatibleObjC)) { 2361 if (IncompatibleObjC) 2362 return false; 2363 // Okay, we have an Objective-C pointer conversion. 2364 } 2365 else 2366 return false; 2367 } 2368 2369 // Check argument types. 2370 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2371 ArgIdx != NumArgs; ++ArgIdx) { 2372 IncompatibleObjC = false; 2373 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2374 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2375 if (Context.hasSameType(FromArgType, ToArgType)) { 2376 // Okay, the types match exactly. Nothing to do. 2377 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2378 ConvertedType, IncompatibleObjC)) { 2379 if (IncompatibleObjC) 2380 return false; 2381 // Okay, we have an Objective-C pointer conversion. 2382 } else 2383 // Argument types are too different. Abort. 2384 return false; 2385 } 2386 if (LangOpts.ObjCAutoRefCount && 2387 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2388 ToFunctionType)) 2389 return false; 2390 2391 ConvertedType = ToType; 2392 return true; 2393} 2394 2395enum { 2396 ft_default, 2397 ft_different_class, 2398 ft_parameter_arity, 2399 ft_parameter_mismatch, 2400 ft_return_type, 2401 ft_qualifer_mismatch 2402}; 2403 2404/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2405/// function types. Catches different number of parameter, mismatch in 2406/// parameter types, and different return types. 2407void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2408 QualType FromType, QualType ToType) { 2409 // If either type is not valid, include no extra info. 2410 if (FromType.isNull() || ToType.isNull()) { 2411 PDiag << ft_default; 2412 return; 2413 } 2414 2415 // Get the function type from the pointers. 2416 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2417 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2418 *ToMember = ToType->getAs<MemberPointerType>(); 2419 if (FromMember->getClass() != ToMember->getClass()) { 2420 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2421 << QualType(FromMember->getClass(), 0); 2422 return; 2423 } 2424 FromType = FromMember->getPointeeType(); 2425 ToType = ToMember->getPointeeType(); 2426 } 2427 2428 if (FromType->isPointerType()) 2429 FromType = FromType->getPointeeType(); 2430 if (ToType->isPointerType()) 2431 ToType = ToType->getPointeeType(); 2432 2433 // Remove references. 2434 FromType = FromType.getNonReferenceType(); 2435 ToType = ToType.getNonReferenceType(); 2436 2437 // Don't print extra info for non-specialized template functions. 2438 if (FromType->isInstantiationDependentType() && 2439 !FromType->getAs<TemplateSpecializationType>()) { 2440 PDiag << ft_default; 2441 return; 2442 } 2443 2444 // No extra info for same types. 2445 if (Context.hasSameType(FromType, ToType)) { 2446 PDiag << ft_default; 2447 return; 2448 } 2449 2450 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2451 *ToFunction = ToType->getAs<FunctionProtoType>(); 2452 2453 // Both types need to be function types. 2454 if (!FromFunction || !ToFunction) { 2455 PDiag << ft_default; 2456 return; 2457 } 2458 2459 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2460 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2461 << FromFunction->getNumArgs(); 2462 return; 2463 } 2464 2465 // Handle different parameter types. 2466 unsigned ArgPos; 2467 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2468 PDiag << ft_parameter_mismatch << ArgPos + 1 2469 << ToFunction->getArgType(ArgPos) 2470 << FromFunction->getArgType(ArgPos); 2471 return; 2472 } 2473 2474 // Handle different return type. 2475 if (!Context.hasSameType(FromFunction->getResultType(), 2476 ToFunction->getResultType())) { 2477 PDiag << ft_return_type << ToFunction->getResultType() 2478 << FromFunction->getResultType(); 2479 return; 2480 } 2481 2482 unsigned FromQuals = FromFunction->getTypeQuals(), 2483 ToQuals = ToFunction->getTypeQuals(); 2484 if (FromQuals != ToQuals) { 2485 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2486 return; 2487 } 2488 2489 // Unable to find a difference, so add no extra info. 2490 PDiag << ft_default; 2491} 2492 2493/// FunctionArgTypesAreEqual - This routine checks two function proto types 2494/// for equality of their argument types. Caller has already checked that 2495/// they have same number of arguments. This routine assumes that Objective-C 2496/// pointer types which only differ in their protocol qualifiers are equal. 2497/// If the parameters are different, ArgPos will have the the parameter index 2498/// of the first different parameter. 2499bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2500 const FunctionProtoType *NewType, 2501 unsigned *ArgPos) { 2502 if (!getLangOpts().ObjC1) { 2503 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2504 N = NewType->arg_type_begin(), 2505 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2506 if (!Context.hasSameType(*O, *N)) { 2507 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2508 return false; 2509 } 2510 } 2511 return true; 2512 } 2513 2514 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2515 N = NewType->arg_type_begin(), 2516 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2517 QualType ToType = (*O); 2518 QualType FromType = (*N); 2519 if (!Context.hasSameType(ToType, FromType)) { 2520 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2521 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2522 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2523 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2524 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2525 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2526 continue; 2527 } 2528 else if (const ObjCObjectPointerType *PTTo = 2529 ToType->getAs<ObjCObjectPointerType>()) { 2530 if (const ObjCObjectPointerType *PTFr = 2531 FromType->getAs<ObjCObjectPointerType>()) 2532 if (Context.hasSameUnqualifiedType( 2533 PTTo->getObjectType()->getBaseType(), 2534 PTFr->getObjectType()->getBaseType())) 2535 continue; 2536 } 2537 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2538 return false; 2539 } 2540 } 2541 return true; 2542} 2543 2544/// CheckPointerConversion - Check the pointer conversion from the 2545/// expression From to the type ToType. This routine checks for 2546/// ambiguous or inaccessible derived-to-base pointer 2547/// conversions for which IsPointerConversion has already returned 2548/// true. It returns true and produces a diagnostic if there was an 2549/// error, or returns false otherwise. 2550bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2551 CastKind &Kind, 2552 CXXCastPath& BasePath, 2553 bool IgnoreBaseAccess) { 2554 QualType FromType = From->getType(); 2555 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2556 2557 Kind = CK_BitCast; 2558 2559 if (!IsCStyleOrFunctionalCast && 2560 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) && 2561 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 2562 DiagRuntimeBehavior(From->getExprLoc(), From, 2563 PDiag(diag::warn_impcast_bool_to_null_pointer) 2564 << ToType << From->getSourceRange()); 2565 2566 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2567 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2568 QualType FromPointeeType = FromPtrType->getPointeeType(), 2569 ToPointeeType = ToPtrType->getPointeeType(); 2570 2571 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2572 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2573 // We must have a derived-to-base conversion. Check an 2574 // ambiguous or inaccessible conversion. 2575 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2576 From->getExprLoc(), 2577 From->getSourceRange(), &BasePath, 2578 IgnoreBaseAccess)) 2579 return true; 2580 2581 // The conversion was successful. 2582 Kind = CK_DerivedToBase; 2583 } 2584 } 2585 } else if (const ObjCObjectPointerType *ToPtrType = 2586 ToType->getAs<ObjCObjectPointerType>()) { 2587 if (const ObjCObjectPointerType *FromPtrType = 2588 FromType->getAs<ObjCObjectPointerType>()) { 2589 // Objective-C++ conversions are always okay. 2590 // FIXME: We should have a different class of conversions for the 2591 // Objective-C++ implicit conversions. 2592 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2593 return false; 2594 } else if (FromType->isBlockPointerType()) { 2595 Kind = CK_BlockPointerToObjCPointerCast; 2596 } else { 2597 Kind = CK_CPointerToObjCPointerCast; 2598 } 2599 } else if (ToType->isBlockPointerType()) { 2600 if (!FromType->isBlockPointerType()) 2601 Kind = CK_AnyPointerToBlockPointerCast; 2602 } 2603 2604 // We shouldn't fall into this case unless it's valid for other 2605 // reasons. 2606 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2607 Kind = CK_NullToPointer; 2608 2609 return false; 2610} 2611 2612/// IsMemberPointerConversion - Determines whether the conversion of the 2613/// expression From, which has the (possibly adjusted) type FromType, can be 2614/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2615/// If so, returns true and places the converted type (that might differ from 2616/// ToType in its cv-qualifiers at some level) into ConvertedType. 2617bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2618 QualType ToType, 2619 bool InOverloadResolution, 2620 QualType &ConvertedType) { 2621 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2622 if (!ToTypePtr) 2623 return false; 2624 2625 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2626 if (From->isNullPointerConstant(Context, 2627 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2628 : Expr::NPC_ValueDependentIsNull)) { 2629 ConvertedType = ToType; 2630 return true; 2631 } 2632 2633 // Otherwise, both types have to be member pointers. 2634 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2635 if (!FromTypePtr) 2636 return false; 2637 2638 // A pointer to member of B can be converted to a pointer to member of D, 2639 // where D is derived from B (C++ 4.11p2). 2640 QualType FromClass(FromTypePtr->getClass(), 0); 2641 QualType ToClass(ToTypePtr->getClass(), 0); 2642 2643 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2644 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2645 IsDerivedFrom(ToClass, FromClass)) { 2646 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2647 ToClass.getTypePtr()); 2648 return true; 2649 } 2650 2651 return false; 2652} 2653 2654/// CheckMemberPointerConversion - Check the member pointer conversion from the 2655/// expression From to the type ToType. This routine checks for ambiguous or 2656/// virtual or inaccessible base-to-derived member pointer conversions 2657/// for which IsMemberPointerConversion has already returned true. It returns 2658/// true and produces a diagnostic if there was an error, or returns false 2659/// otherwise. 2660bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2661 CastKind &Kind, 2662 CXXCastPath &BasePath, 2663 bool IgnoreBaseAccess) { 2664 QualType FromType = From->getType(); 2665 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2666 if (!FromPtrType) { 2667 // This must be a null pointer to member pointer conversion 2668 assert(From->isNullPointerConstant(Context, 2669 Expr::NPC_ValueDependentIsNull) && 2670 "Expr must be null pointer constant!"); 2671 Kind = CK_NullToMemberPointer; 2672 return false; 2673 } 2674 2675 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2676 assert(ToPtrType && "No member pointer cast has a target type " 2677 "that is not a member pointer."); 2678 2679 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2680 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2681 2682 // FIXME: What about dependent types? 2683 assert(FromClass->isRecordType() && "Pointer into non-class."); 2684 assert(ToClass->isRecordType() && "Pointer into non-class."); 2685 2686 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2687 /*DetectVirtual=*/true); 2688 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2689 assert(DerivationOkay && 2690 "Should not have been called if derivation isn't OK."); 2691 (void)DerivationOkay; 2692 2693 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2694 getUnqualifiedType())) { 2695 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2696 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2697 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2698 return true; 2699 } 2700 2701 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2702 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2703 << FromClass << ToClass << QualType(VBase, 0) 2704 << From->getSourceRange(); 2705 return true; 2706 } 2707 2708 if (!IgnoreBaseAccess) 2709 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2710 Paths.front(), 2711 diag::err_downcast_from_inaccessible_base); 2712 2713 // Must be a base to derived member conversion. 2714 BuildBasePathArray(Paths, BasePath); 2715 Kind = CK_BaseToDerivedMemberPointer; 2716 return false; 2717} 2718 2719/// IsQualificationConversion - Determines whether the conversion from 2720/// an rvalue of type FromType to ToType is a qualification conversion 2721/// (C++ 4.4). 2722/// 2723/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2724/// when the qualification conversion involves a change in the Objective-C 2725/// object lifetime. 2726bool 2727Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2728 bool CStyle, bool &ObjCLifetimeConversion) { 2729 FromType = Context.getCanonicalType(FromType); 2730 ToType = Context.getCanonicalType(ToType); 2731 ObjCLifetimeConversion = false; 2732 2733 // If FromType and ToType are the same type, this is not a 2734 // qualification conversion. 2735 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2736 return false; 2737 2738 // (C++ 4.4p4): 2739 // A conversion can add cv-qualifiers at levels other than the first 2740 // in multi-level pointers, subject to the following rules: [...] 2741 bool PreviousToQualsIncludeConst = true; 2742 bool UnwrappedAnyPointer = false; 2743 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2744 // Within each iteration of the loop, we check the qualifiers to 2745 // determine if this still looks like a qualification 2746 // conversion. Then, if all is well, we unwrap one more level of 2747 // pointers or pointers-to-members and do it all again 2748 // until there are no more pointers or pointers-to-members left to 2749 // unwrap. 2750 UnwrappedAnyPointer = true; 2751 2752 Qualifiers FromQuals = FromType.getQualifiers(); 2753 Qualifiers ToQuals = ToType.getQualifiers(); 2754 2755 // Objective-C ARC: 2756 // Check Objective-C lifetime conversions. 2757 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2758 UnwrappedAnyPointer) { 2759 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2760 ObjCLifetimeConversion = true; 2761 FromQuals.removeObjCLifetime(); 2762 ToQuals.removeObjCLifetime(); 2763 } else { 2764 // Qualification conversions cannot cast between different 2765 // Objective-C lifetime qualifiers. 2766 return false; 2767 } 2768 } 2769 2770 // Allow addition/removal of GC attributes but not changing GC attributes. 2771 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2772 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2773 FromQuals.removeObjCGCAttr(); 2774 ToQuals.removeObjCGCAttr(); 2775 } 2776 2777 // -- for every j > 0, if const is in cv 1,j then const is in cv 2778 // 2,j, and similarly for volatile. 2779 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2780 return false; 2781 2782 // -- if the cv 1,j and cv 2,j are different, then const is in 2783 // every cv for 0 < k < j. 2784 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2785 && !PreviousToQualsIncludeConst) 2786 return false; 2787 2788 // Keep track of whether all prior cv-qualifiers in the "to" type 2789 // include const. 2790 PreviousToQualsIncludeConst 2791 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2792 } 2793 2794 // We are left with FromType and ToType being the pointee types 2795 // after unwrapping the original FromType and ToType the same number 2796 // of types. If we unwrapped any pointers, and if FromType and 2797 // ToType have the same unqualified type (since we checked 2798 // qualifiers above), then this is a qualification conversion. 2799 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2800} 2801 2802/// \brief - Determine whether this is a conversion from a scalar type to an 2803/// atomic type. 2804/// 2805/// If successful, updates \c SCS's second and third steps in the conversion 2806/// sequence to finish the conversion. 2807static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2808 bool InOverloadResolution, 2809 StandardConversionSequence &SCS, 2810 bool CStyle) { 2811 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2812 if (!ToAtomic) 2813 return false; 2814 2815 StandardConversionSequence InnerSCS; 2816 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2817 InOverloadResolution, InnerSCS, 2818 CStyle, /*AllowObjCWritebackConversion=*/false)) 2819 return false; 2820 2821 SCS.Second = InnerSCS.Second; 2822 SCS.setToType(1, InnerSCS.getToType(1)); 2823 SCS.Third = InnerSCS.Third; 2824 SCS.QualificationIncludesObjCLifetime 2825 = InnerSCS.QualificationIncludesObjCLifetime; 2826 SCS.setToType(2, InnerSCS.getToType(2)); 2827 return true; 2828} 2829 2830static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2831 CXXConstructorDecl *Constructor, 2832 QualType Type) { 2833 const FunctionProtoType *CtorType = 2834 Constructor->getType()->getAs<FunctionProtoType>(); 2835 if (CtorType->getNumArgs() > 0) { 2836 QualType FirstArg = CtorType->getArgType(0); 2837 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2838 return true; 2839 } 2840 return false; 2841} 2842 2843static OverloadingResult 2844IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2845 CXXRecordDecl *To, 2846 UserDefinedConversionSequence &User, 2847 OverloadCandidateSet &CandidateSet, 2848 bool AllowExplicit) { 2849 DeclContext::lookup_iterator Con, ConEnd; 2850 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2851 Con != ConEnd; ++Con) { 2852 NamedDecl *D = *Con; 2853 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2854 2855 // Find the constructor (which may be a template). 2856 CXXConstructorDecl *Constructor = 0; 2857 FunctionTemplateDecl *ConstructorTmpl 2858 = dyn_cast<FunctionTemplateDecl>(D); 2859 if (ConstructorTmpl) 2860 Constructor 2861 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2862 else 2863 Constructor = cast<CXXConstructorDecl>(D); 2864 2865 bool Usable = !Constructor->isInvalidDecl() && 2866 S.isInitListConstructor(Constructor) && 2867 (AllowExplicit || !Constructor->isExplicit()); 2868 if (Usable) { 2869 // If the first argument is (a reference to) the target type, 2870 // suppress conversions. 2871 bool SuppressUserConversions = 2872 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2873 if (ConstructorTmpl) 2874 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2875 /*ExplicitArgs*/ 0, 2876 From, CandidateSet, 2877 SuppressUserConversions); 2878 else 2879 S.AddOverloadCandidate(Constructor, FoundDecl, 2880 From, CandidateSet, 2881 SuppressUserConversions); 2882 } 2883 } 2884 2885 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2886 2887 OverloadCandidateSet::iterator Best; 2888 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2889 case OR_Success: { 2890 // Record the standard conversion we used and the conversion function. 2891 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2892 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 2893 2894 QualType ThisType = Constructor->getThisType(S.Context); 2895 // Initializer lists don't have conversions as such. 2896 User.Before.setAsIdentityConversion(); 2897 User.HadMultipleCandidates = HadMultipleCandidates; 2898 User.ConversionFunction = Constructor; 2899 User.FoundConversionFunction = Best->FoundDecl; 2900 User.After.setAsIdentityConversion(); 2901 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2902 User.After.setAllToTypes(ToType); 2903 return OR_Success; 2904 } 2905 2906 case OR_No_Viable_Function: 2907 return OR_No_Viable_Function; 2908 case OR_Deleted: 2909 return OR_Deleted; 2910 case OR_Ambiguous: 2911 return OR_Ambiguous; 2912 } 2913 2914 llvm_unreachable("Invalid OverloadResult!"); 2915} 2916 2917/// Determines whether there is a user-defined conversion sequence 2918/// (C++ [over.ics.user]) that converts expression From to the type 2919/// ToType. If such a conversion exists, User will contain the 2920/// user-defined conversion sequence that performs such a conversion 2921/// and this routine will return true. Otherwise, this routine returns 2922/// false and User is unspecified. 2923/// 2924/// \param AllowExplicit true if the conversion should consider C++0x 2925/// "explicit" conversion functions as well as non-explicit conversion 2926/// functions (C++0x [class.conv.fct]p2). 2927static OverloadingResult 2928IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2929 UserDefinedConversionSequence &User, 2930 OverloadCandidateSet &CandidateSet, 2931 bool AllowExplicit) { 2932 // Whether we will only visit constructors. 2933 bool ConstructorsOnly = false; 2934 2935 // If the type we are conversion to is a class type, enumerate its 2936 // constructors. 2937 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2938 // C++ [over.match.ctor]p1: 2939 // When objects of class type are direct-initialized (8.5), or 2940 // copy-initialized from an expression of the same or a 2941 // derived class type (8.5), overload resolution selects the 2942 // constructor. [...] For copy-initialization, the candidate 2943 // functions are all the converting constructors (12.3.1) of 2944 // that class. The argument list is the expression-list within 2945 // the parentheses of the initializer. 2946 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2947 (From->getType()->getAs<RecordType>() && 2948 S.IsDerivedFrom(From->getType(), ToType))) 2949 ConstructorsOnly = true; 2950 2951 S.RequireCompleteType(From->getLocStart(), ToType, 0); 2952 // RequireCompleteType may have returned true due to some invalid decl 2953 // during template instantiation, but ToType may be complete enough now 2954 // to try to recover. 2955 if (ToType->isIncompleteType()) { 2956 // We're not going to find any constructors. 2957 } else if (CXXRecordDecl *ToRecordDecl 2958 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2959 2960 Expr **Args = &From; 2961 unsigned NumArgs = 1; 2962 bool ListInitializing = false; 2963 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2964 // But first, see if there is an init-list-contructor that will work. 2965 OverloadingResult Result = IsInitializerListConstructorConversion( 2966 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2967 if (Result != OR_No_Viable_Function) 2968 return Result; 2969 // Never mind. 2970 CandidateSet.clear(); 2971 2972 // If we're list-initializing, we pass the individual elements as 2973 // arguments, not the entire list. 2974 Args = InitList->getInits(); 2975 NumArgs = InitList->getNumInits(); 2976 ListInitializing = true; 2977 } 2978 2979 DeclContext::lookup_iterator Con, ConEnd; 2980 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2981 Con != ConEnd; ++Con) { 2982 NamedDecl *D = *Con; 2983 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2984 2985 // Find the constructor (which may be a template). 2986 CXXConstructorDecl *Constructor = 0; 2987 FunctionTemplateDecl *ConstructorTmpl 2988 = dyn_cast<FunctionTemplateDecl>(D); 2989 if (ConstructorTmpl) 2990 Constructor 2991 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2992 else 2993 Constructor = cast<CXXConstructorDecl>(D); 2994 2995 bool Usable = !Constructor->isInvalidDecl(); 2996 if (ListInitializing) 2997 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 2998 else 2999 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3000 if (Usable) { 3001 bool SuppressUserConversions = !ConstructorsOnly; 3002 if (SuppressUserConversions && ListInitializing) { 3003 SuppressUserConversions = false; 3004 if (NumArgs == 1) { 3005 // If the first argument is (a reference to) the target type, 3006 // suppress conversions. 3007 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3008 S.Context, Constructor, ToType); 3009 } 3010 } 3011 if (ConstructorTmpl) 3012 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3013 /*ExplicitArgs*/ 0, 3014 llvm::makeArrayRef(Args, NumArgs), 3015 CandidateSet, SuppressUserConversions); 3016 else 3017 // Allow one user-defined conversion when user specifies a 3018 // From->ToType conversion via an static cast (c-style, etc). 3019 S.AddOverloadCandidate(Constructor, FoundDecl, 3020 llvm::makeArrayRef(Args, NumArgs), 3021 CandidateSet, SuppressUserConversions); 3022 } 3023 } 3024 } 3025 } 3026 3027 // Enumerate conversion functions, if we're allowed to. 3028 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3029 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3030 // No conversion functions from incomplete types. 3031 } else if (const RecordType *FromRecordType 3032 = From->getType()->getAs<RecordType>()) { 3033 if (CXXRecordDecl *FromRecordDecl 3034 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3035 // Add all of the conversion functions as candidates. 3036 const UnresolvedSetImpl *Conversions 3037 = FromRecordDecl->getVisibleConversionFunctions(); 3038 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3039 E = Conversions->end(); I != E; ++I) { 3040 DeclAccessPair FoundDecl = I.getPair(); 3041 NamedDecl *D = FoundDecl.getDecl(); 3042 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3043 if (isa<UsingShadowDecl>(D)) 3044 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3045 3046 CXXConversionDecl *Conv; 3047 FunctionTemplateDecl *ConvTemplate; 3048 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3050 else 3051 Conv = cast<CXXConversionDecl>(D); 3052 3053 if (AllowExplicit || !Conv->isExplicit()) { 3054 if (ConvTemplate) 3055 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3056 ActingContext, From, ToType, 3057 CandidateSet); 3058 else 3059 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3060 From, ToType, CandidateSet); 3061 } 3062 } 3063 } 3064 } 3065 3066 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3067 3068 OverloadCandidateSet::iterator Best; 3069 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3070 case OR_Success: 3071 // Record the standard conversion we used and the conversion function. 3072 if (CXXConstructorDecl *Constructor 3073 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3074 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 3075 3076 // C++ [over.ics.user]p1: 3077 // If the user-defined conversion is specified by a 3078 // constructor (12.3.1), the initial standard conversion 3079 // sequence converts the source type to the type required by 3080 // the argument of the constructor. 3081 // 3082 QualType ThisType = Constructor->getThisType(S.Context); 3083 if (isa<InitListExpr>(From)) { 3084 // Initializer lists don't have conversions as such. 3085 User.Before.setAsIdentityConversion(); 3086 } else { 3087 if (Best->Conversions[0].isEllipsis()) 3088 User.EllipsisConversion = true; 3089 else { 3090 User.Before = Best->Conversions[0].Standard; 3091 User.EllipsisConversion = false; 3092 } 3093 } 3094 User.HadMultipleCandidates = HadMultipleCandidates; 3095 User.ConversionFunction = Constructor; 3096 User.FoundConversionFunction = Best->FoundDecl; 3097 User.After.setAsIdentityConversion(); 3098 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3099 User.After.setAllToTypes(ToType); 3100 return OR_Success; 3101 } 3102 if (CXXConversionDecl *Conversion 3103 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3104 S.MarkFunctionReferenced(From->getLocStart(), Conversion); 3105 3106 // C++ [over.ics.user]p1: 3107 // 3108 // [...] If the user-defined conversion is specified by a 3109 // conversion function (12.3.2), the initial standard 3110 // conversion sequence converts the source type to the 3111 // implicit object parameter of the conversion function. 3112 User.Before = Best->Conversions[0].Standard; 3113 User.HadMultipleCandidates = HadMultipleCandidates; 3114 User.ConversionFunction = Conversion; 3115 User.FoundConversionFunction = Best->FoundDecl; 3116 User.EllipsisConversion = false; 3117 3118 // C++ [over.ics.user]p2: 3119 // The second standard conversion sequence converts the 3120 // result of the user-defined conversion to the target type 3121 // for the sequence. Since an implicit conversion sequence 3122 // is an initialization, the special rules for 3123 // initialization by user-defined conversion apply when 3124 // selecting the best user-defined conversion for a 3125 // user-defined conversion sequence (see 13.3.3 and 3126 // 13.3.3.1). 3127 User.After = Best->FinalConversion; 3128 return OR_Success; 3129 } 3130 llvm_unreachable("Not a constructor or conversion function?"); 3131 3132 case OR_No_Viable_Function: 3133 return OR_No_Viable_Function; 3134 case OR_Deleted: 3135 // No conversion here! We're done. 3136 return OR_Deleted; 3137 3138 case OR_Ambiguous: 3139 return OR_Ambiguous; 3140 } 3141 3142 llvm_unreachable("Invalid OverloadResult!"); 3143} 3144 3145bool 3146Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3147 ImplicitConversionSequence ICS; 3148 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3149 OverloadingResult OvResult = 3150 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3151 CandidateSet, false); 3152 if (OvResult == OR_Ambiguous) 3153 Diag(From->getLocStart(), 3154 diag::err_typecheck_ambiguous_condition) 3155 << From->getType() << ToType << From->getSourceRange(); 3156 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3157 Diag(From->getLocStart(), 3158 diag::err_typecheck_nonviable_condition) 3159 << From->getType() << ToType << From->getSourceRange(); 3160 else 3161 return false; 3162 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3163 return true; 3164} 3165 3166/// \brief Compare the user-defined conversion functions or constructors 3167/// of two user-defined conversion sequences to determine whether any ordering 3168/// is possible. 3169static ImplicitConversionSequence::CompareKind 3170compareConversionFunctions(Sema &S, 3171 FunctionDecl *Function1, 3172 FunctionDecl *Function2) { 3173 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3174 return ImplicitConversionSequence::Indistinguishable; 3175 3176 // Objective-C++: 3177 // If both conversion functions are implicitly-declared conversions from 3178 // a lambda closure type to a function pointer and a block pointer, 3179 // respectively, always prefer the conversion to a function pointer, 3180 // because the function pointer is more lightweight and is more likely 3181 // to keep code working. 3182 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3183 if (!Conv1) 3184 return ImplicitConversionSequence::Indistinguishable; 3185 3186 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3187 if (!Conv2) 3188 return ImplicitConversionSequence::Indistinguishable; 3189 3190 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3191 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3192 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3193 if (Block1 != Block2) 3194 return Block1? ImplicitConversionSequence::Worse 3195 : ImplicitConversionSequence::Better; 3196 } 3197 3198 return ImplicitConversionSequence::Indistinguishable; 3199} 3200 3201/// CompareImplicitConversionSequences - Compare two implicit 3202/// conversion sequences to determine whether one is better than the 3203/// other or if they are indistinguishable (C++ 13.3.3.2). 3204static ImplicitConversionSequence::CompareKind 3205CompareImplicitConversionSequences(Sema &S, 3206 const ImplicitConversionSequence& ICS1, 3207 const ImplicitConversionSequence& ICS2) 3208{ 3209 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3210 // conversion sequences (as defined in 13.3.3.1) 3211 // -- a standard conversion sequence (13.3.3.1.1) is a better 3212 // conversion sequence than a user-defined conversion sequence or 3213 // an ellipsis conversion sequence, and 3214 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3215 // conversion sequence than an ellipsis conversion sequence 3216 // (13.3.3.1.3). 3217 // 3218 // C++0x [over.best.ics]p10: 3219 // For the purpose of ranking implicit conversion sequences as 3220 // described in 13.3.3.2, the ambiguous conversion sequence is 3221 // treated as a user-defined sequence that is indistinguishable 3222 // from any other user-defined conversion sequence. 3223 if (ICS1.getKindRank() < ICS2.getKindRank()) 3224 return ImplicitConversionSequence::Better; 3225 if (ICS2.getKindRank() < ICS1.getKindRank()) 3226 return ImplicitConversionSequence::Worse; 3227 3228 // The following checks require both conversion sequences to be of 3229 // the same kind. 3230 if (ICS1.getKind() != ICS2.getKind()) 3231 return ImplicitConversionSequence::Indistinguishable; 3232 3233 ImplicitConversionSequence::CompareKind Result = 3234 ImplicitConversionSequence::Indistinguishable; 3235 3236 // Two implicit conversion sequences of the same form are 3237 // indistinguishable conversion sequences unless one of the 3238 // following rules apply: (C++ 13.3.3.2p3): 3239 if (ICS1.isStandard()) 3240 Result = CompareStandardConversionSequences(S, 3241 ICS1.Standard, ICS2.Standard); 3242 else if (ICS1.isUserDefined()) { 3243 // User-defined conversion sequence U1 is a better conversion 3244 // sequence than another user-defined conversion sequence U2 if 3245 // they contain the same user-defined conversion function or 3246 // constructor and if the second standard conversion sequence of 3247 // U1 is better than the second standard conversion sequence of 3248 // U2 (C++ 13.3.3.2p3). 3249 if (ICS1.UserDefined.ConversionFunction == 3250 ICS2.UserDefined.ConversionFunction) 3251 Result = CompareStandardConversionSequences(S, 3252 ICS1.UserDefined.After, 3253 ICS2.UserDefined.After); 3254 else 3255 Result = compareConversionFunctions(S, 3256 ICS1.UserDefined.ConversionFunction, 3257 ICS2.UserDefined.ConversionFunction); 3258 } 3259 3260 // List-initialization sequence L1 is a better conversion sequence than 3261 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3262 // for some X and L2 does not. 3263 if (Result == ImplicitConversionSequence::Indistinguishable && 3264 !ICS1.isBad() && 3265 ICS1.isListInitializationSequence() && 3266 ICS2.isListInitializationSequence()) { 3267 if (ICS1.isStdInitializerListElement() && 3268 !ICS2.isStdInitializerListElement()) 3269 return ImplicitConversionSequence::Better; 3270 if (!ICS1.isStdInitializerListElement() && 3271 ICS2.isStdInitializerListElement()) 3272 return ImplicitConversionSequence::Worse; 3273 } 3274 3275 return Result; 3276} 3277 3278static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3279 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3280 Qualifiers Quals; 3281 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3282 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3283 } 3284 3285 return Context.hasSameUnqualifiedType(T1, T2); 3286} 3287 3288// Per 13.3.3.2p3, compare the given standard conversion sequences to 3289// determine if one is a proper subset of the other. 3290static ImplicitConversionSequence::CompareKind 3291compareStandardConversionSubsets(ASTContext &Context, 3292 const StandardConversionSequence& SCS1, 3293 const StandardConversionSequence& SCS2) { 3294 ImplicitConversionSequence::CompareKind Result 3295 = ImplicitConversionSequence::Indistinguishable; 3296 3297 // the identity conversion sequence is considered to be a subsequence of 3298 // any non-identity conversion sequence 3299 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3300 return ImplicitConversionSequence::Better; 3301 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3302 return ImplicitConversionSequence::Worse; 3303 3304 if (SCS1.Second != SCS2.Second) { 3305 if (SCS1.Second == ICK_Identity) 3306 Result = ImplicitConversionSequence::Better; 3307 else if (SCS2.Second == ICK_Identity) 3308 Result = ImplicitConversionSequence::Worse; 3309 else 3310 return ImplicitConversionSequence::Indistinguishable; 3311 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3312 return ImplicitConversionSequence::Indistinguishable; 3313 3314 if (SCS1.Third == SCS2.Third) { 3315 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3316 : ImplicitConversionSequence::Indistinguishable; 3317 } 3318 3319 if (SCS1.Third == ICK_Identity) 3320 return Result == ImplicitConversionSequence::Worse 3321 ? ImplicitConversionSequence::Indistinguishable 3322 : ImplicitConversionSequence::Better; 3323 3324 if (SCS2.Third == ICK_Identity) 3325 return Result == ImplicitConversionSequence::Better 3326 ? ImplicitConversionSequence::Indistinguishable 3327 : ImplicitConversionSequence::Worse; 3328 3329 return ImplicitConversionSequence::Indistinguishable; 3330} 3331 3332/// \brief Determine whether one of the given reference bindings is better 3333/// than the other based on what kind of bindings they are. 3334static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3335 const StandardConversionSequence &SCS2) { 3336 // C++0x [over.ics.rank]p3b4: 3337 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3338 // implicit object parameter of a non-static member function declared 3339 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3340 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3341 // lvalue reference to a function lvalue and S2 binds an rvalue 3342 // reference*. 3343 // 3344 // FIXME: Rvalue references. We're going rogue with the above edits, 3345 // because the semantics in the current C++0x working paper (N3225 at the 3346 // time of this writing) break the standard definition of std::forward 3347 // and std::reference_wrapper when dealing with references to functions. 3348 // Proposed wording changes submitted to CWG for consideration. 3349 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3350 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3351 return false; 3352 3353 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3354 SCS2.IsLvalueReference) || 3355 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3356 !SCS2.IsLvalueReference); 3357} 3358 3359/// CompareStandardConversionSequences - Compare two standard 3360/// conversion sequences to determine whether one is better than the 3361/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3362static ImplicitConversionSequence::CompareKind 3363CompareStandardConversionSequences(Sema &S, 3364 const StandardConversionSequence& SCS1, 3365 const StandardConversionSequence& SCS2) 3366{ 3367 // Standard conversion sequence S1 is a better conversion sequence 3368 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3369 3370 // -- S1 is a proper subsequence of S2 (comparing the conversion 3371 // sequences in the canonical form defined by 13.3.3.1.1, 3372 // excluding any Lvalue Transformation; the identity conversion 3373 // sequence is considered to be a subsequence of any 3374 // non-identity conversion sequence) or, if not that, 3375 if (ImplicitConversionSequence::CompareKind CK 3376 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3377 return CK; 3378 3379 // -- the rank of S1 is better than the rank of S2 (by the rules 3380 // defined below), or, if not that, 3381 ImplicitConversionRank Rank1 = SCS1.getRank(); 3382 ImplicitConversionRank Rank2 = SCS2.getRank(); 3383 if (Rank1 < Rank2) 3384 return ImplicitConversionSequence::Better; 3385 else if (Rank2 < Rank1) 3386 return ImplicitConversionSequence::Worse; 3387 3388 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3389 // are indistinguishable unless one of the following rules 3390 // applies: 3391 3392 // A conversion that is not a conversion of a pointer, or 3393 // pointer to member, to bool is better than another conversion 3394 // that is such a conversion. 3395 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3396 return SCS2.isPointerConversionToBool() 3397 ? ImplicitConversionSequence::Better 3398 : ImplicitConversionSequence::Worse; 3399 3400 // C++ [over.ics.rank]p4b2: 3401 // 3402 // If class B is derived directly or indirectly from class A, 3403 // conversion of B* to A* is better than conversion of B* to 3404 // void*, and conversion of A* to void* is better than conversion 3405 // of B* to void*. 3406 bool SCS1ConvertsToVoid 3407 = SCS1.isPointerConversionToVoidPointer(S.Context); 3408 bool SCS2ConvertsToVoid 3409 = SCS2.isPointerConversionToVoidPointer(S.Context); 3410 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3411 // Exactly one of the conversion sequences is a conversion to 3412 // a void pointer; it's the worse conversion. 3413 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3414 : ImplicitConversionSequence::Worse; 3415 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3416 // Neither conversion sequence converts to a void pointer; compare 3417 // their derived-to-base conversions. 3418 if (ImplicitConversionSequence::CompareKind DerivedCK 3419 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3420 return DerivedCK; 3421 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3422 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3423 // Both conversion sequences are conversions to void 3424 // pointers. Compare the source types to determine if there's an 3425 // inheritance relationship in their sources. 3426 QualType FromType1 = SCS1.getFromType(); 3427 QualType FromType2 = SCS2.getFromType(); 3428 3429 // Adjust the types we're converting from via the array-to-pointer 3430 // conversion, if we need to. 3431 if (SCS1.First == ICK_Array_To_Pointer) 3432 FromType1 = S.Context.getArrayDecayedType(FromType1); 3433 if (SCS2.First == ICK_Array_To_Pointer) 3434 FromType2 = S.Context.getArrayDecayedType(FromType2); 3435 3436 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3437 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3438 3439 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3440 return ImplicitConversionSequence::Better; 3441 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3442 return ImplicitConversionSequence::Worse; 3443 3444 // Objective-C++: If one interface is more specific than the 3445 // other, it is the better one. 3446 const ObjCObjectPointerType* FromObjCPtr1 3447 = FromType1->getAs<ObjCObjectPointerType>(); 3448 const ObjCObjectPointerType* FromObjCPtr2 3449 = FromType2->getAs<ObjCObjectPointerType>(); 3450 if (FromObjCPtr1 && FromObjCPtr2) { 3451 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3452 FromObjCPtr2); 3453 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3454 FromObjCPtr1); 3455 if (AssignLeft != AssignRight) { 3456 return AssignLeft? ImplicitConversionSequence::Better 3457 : ImplicitConversionSequence::Worse; 3458 } 3459 } 3460 } 3461 3462 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3463 // bullet 3). 3464 if (ImplicitConversionSequence::CompareKind QualCK 3465 = CompareQualificationConversions(S, SCS1, SCS2)) 3466 return QualCK; 3467 3468 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3469 // Check for a better reference binding based on the kind of bindings. 3470 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3471 return ImplicitConversionSequence::Better; 3472 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3473 return ImplicitConversionSequence::Worse; 3474 3475 // C++ [over.ics.rank]p3b4: 3476 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3477 // which the references refer are the same type except for 3478 // top-level cv-qualifiers, and the type to which the reference 3479 // initialized by S2 refers is more cv-qualified than the type 3480 // to which the reference initialized by S1 refers. 3481 QualType T1 = SCS1.getToType(2); 3482 QualType T2 = SCS2.getToType(2); 3483 T1 = S.Context.getCanonicalType(T1); 3484 T2 = S.Context.getCanonicalType(T2); 3485 Qualifiers T1Quals, T2Quals; 3486 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3487 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3488 if (UnqualT1 == UnqualT2) { 3489 // Objective-C++ ARC: If the references refer to objects with different 3490 // lifetimes, prefer bindings that don't change lifetime. 3491 if (SCS1.ObjCLifetimeConversionBinding != 3492 SCS2.ObjCLifetimeConversionBinding) { 3493 return SCS1.ObjCLifetimeConversionBinding 3494 ? ImplicitConversionSequence::Worse 3495 : ImplicitConversionSequence::Better; 3496 } 3497 3498 // If the type is an array type, promote the element qualifiers to the 3499 // type for comparison. 3500 if (isa<ArrayType>(T1) && T1Quals) 3501 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3502 if (isa<ArrayType>(T2) && T2Quals) 3503 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3504 if (T2.isMoreQualifiedThan(T1)) 3505 return ImplicitConversionSequence::Better; 3506 else if (T1.isMoreQualifiedThan(T2)) 3507 return ImplicitConversionSequence::Worse; 3508 } 3509 } 3510 3511 // In Microsoft mode, prefer an integral conversion to a 3512 // floating-to-integral conversion if the integral conversion 3513 // is between types of the same size. 3514 // For example: 3515 // void f(float); 3516 // void f(int); 3517 // int main { 3518 // long a; 3519 // f(a); 3520 // } 3521 // Here, MSVC will call f(int) instead of generating a compile error 3522 // as clang will do in standard mode. 3523 if (S.getLangOpts().MicrosoftMode && 3524 SCS1.Second == ICK_Integral_Conversion && 3525 SCS2.Second == ICK_Floating_Integral && 3526 S.Context.getTypeSize(SCS1.getFromType()) == 3527 S.Context.getTypeSize(SCS1.getToType(2))) 3528 return ImplicitConversionSequence::Better; 3529 3530 return ImplicitConversionSequence::Indistinguishable; 3531} 3532 3533/// CompareQualificationConversions - Compares two standard conversion 3534/// sequences to determine whether they can be ranked based on their 3535/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3536ImplicitConversionSequence::CompareKind 3537CompareQualificationConversions(Sema &S, 3538 const StandardConversionSequence& SCS1, 3539 const StandardConversionSequence& SCS2) { 3540 // C++ 13.3.3.2p3: 3541 // -- S1 and S2 differ only in their qualification conversion and 3542 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3543 // cv-qualification signature of type T1 is a proper subset of 3544 // the cv-qualification signature of type T2, and S1 is not the 3545 // deprecated string literal array-to-pointer conversion (4.2). 3546 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3547 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3548 return ImplicitConversionSequence::Indistinguishable; 3549 3550 // FIXME: the example in the standard doesn't use a qualification 3551 // conversion (!) 3552 QualType T1 = SCS1.getToType(2); 3553 QualType T2 = SCS2.getToType(2); 3554 T1 = S.Context.getCanonicalType(T1); 3555 T2 = S.Context.getCanonicalType(T2); 3556 Qualifiers T1Quals, T2Quals; 3557 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3558 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3559 3560 // If the types are the same, we won't learn anything by unwrapped 3561 // them. 3562 if (UnqualT1 == UnqualT2) 3563 return ImplicitConversionSequence::Indistinguishable; 3564 3565 // If the type is an array type, promote the element qualifiers to the type 3566 // for comparison. 3567 if (isa<ArrayType>(T1) && T1Quals) 3568 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3569 if (isa<ArrayType>(T2) && T2Quals) 3570 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3571 3572 ImplicitConversionSequence::CompareKind Result 3573 = ImplicitConversionSequence::Indistinguishable; 3574 3575 // Objective-C++ ARC: 3576 // Prefer qualification conversions not involving a change in lifetime 3577 // to qualification conversions that do not change lifetime. 3578 if (SCS1.QualificationIncludesObjCLifetime != 3579 SCS2.QualificationIncludesObjCLifetime) { 3580 Result = SCS1.QualificationIncludesObjCLifetime 3581 ? ImplicitConversionSequence::Worse 3582 : ImplicitConversionSequence::Better; 3583 } 3584 3585 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3586 // Within each iteration of the loop, we check the qualifiers to 3587 // determine if this still looks like a qualification 3588 // conversion. Then, if all is well, we unwrap one more level of 3589 // pointers or pointers-to-members and do it all again 3590 // until there are no more pointers or pointers-to-members left 3591 // to unwrap. This essentially mimics what 3592 // IsQualificationConversion does, but here we're checking for a 3593 // strict subset of qualifiers. 3594 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3595 // The qualifiers are the same, so this doesn't tell us anything 3596 // about how the sequences rank. 3597 ; 3598 else if (T2.isMoreQualifiedThan(T1)) { 3599 // T1 has fewer qualifiers, so it could be the better sequence. 3600 if (Result == ImplicitConversionSequence::Worse) 3601 // Neither has qualifiers that are a subset of the other's 3602 // qualifiers. 3603 return ImplicitConversionSequence::Indistinguishable; 3604 3605 Result = ImplicitConversionSequence::Better; 3606 } else if (T1.isMoreQualifiedThan(T2)) { 3607 // T2 has fewer qualifiers, so it could be the better sequence. 3608 if (Result == ImplicitConversionSequence::Better) 3609 // Neither has qualifiers that are a subset of the other's 3610 // qualifiers. 3611 return ImplicitConversionSequence::Indistinguishable; 3612 3613 Result = ImplicitConversionSequence::Worse; 3614 } else { 3615 // Qualifiers are disjoint. 3616 return ImplicitConversionSequence::Indistinguishable; 3617 } 3618 3619 // If the types after this point are equivalent, we're done. 3620 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3621 break; 3622 } 3623 3624 // Check that the winning standard conversion sequence isn't using 3625 // the deprecated string literal array to pointer conversion. 3626 switch (Result) { 3627 case ImplicitConversionSequence::Better: 3628 if (SCS1.DeprecatedStringLiteralToCharPtr) 3629 Result = ImplicitConversionSequence::Indistinguishable; 3630 break; 3631 3632 case ImplicitConversionSequence::Indistinguishable: 3633 break; 3634 3635 case ImplicitConversionSequence::Worse: 3636 if (SCS2.DeprecatedStringLiteralToCharPtr) 3637 Result = ImplicitConversionSequence::Indistinguishable; 3638 break; 3639 } 3640 3641 return Result; 3642} 3643 3644/// CompareDerivedToBaseConversions - Compares two standard conversion 3645/// sequences to determine whether they can be ranked based on their 3646/// various kinds of derived-to-base conversions (C++ 3647/// [over.ics.rank]p4b3). As part of these checks, we also look at 3648/// conversions between Objective-C interface types. 3649ImplicitConversionSequence::CompareKind 3650CompareDerivedToBaseConversions(Sema &S, 3651 const StandardConversionSequence& SCS1, 3652 const StandardConversionSequence& SCS2) { 3653 QualType FromType1 = SCS1.getFromType(); 3654 QualType ToType1 = SCS1.getToType(1); 3655 QualType FromType2 = SCS2.getFromType(); 3656 QualType ToType2 = SCS2.getToType(1); 3657 3658 // Adjust the types we're converting from via the array-to-pointer 3659 // conversion, if we need to. 3660 if (SCS1.First == ICK_Array_To_Pointer) 3661 FromType1 = S.Context.getArrayDecayedType(FromType1); 3662 if (SCS2.First == ICK_Array_To_Pointer) 3663 FromType2 = S.Context.getArrayDecayedType(FromType2); 3664 3665 // Canonicalize all of the types. 3666 FromType1 = S.Context.getCanonicalType(FromType1); 3667 ToType1 = S.Context.getCanonicalType(ToType1); 3668 FromType2 = S.Context.getCanonicalType(FromType2); 3669 ToType2 = S.Context.getCanonicalType(ToType2); 3670 3671 // C++ [over.ics.rank]p4b3: 3672 // 3673 // If class B is derived directly or indirectly from class A and 3674 // class C is derived directly or indirectly from B, 3675 // 3676 // Compare based on pointer conversions. 3677 if (SCS1.Second == ICK_Pointer_Conversion && 3678 SCS2.Second == ICK_Pointer_Conversion && 3679 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3680 FromType1->isPointerType() && FromType2->isPointerType() && 3681 ToType1->isPointerType() && ToType2->isPointerType()) { 3682 QualType FromPointee1 3683 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3684 QualType ToPointee1 3685 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3686 QualType FromPointee2 3687 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3688 QualType ToPointee2 3689 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3690 3691 // -- conversion of C* to B* is better than conversion of C* to A*, 3692 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3693 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3694 return ImplicitConversionSequence::Better; 3695 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3696 return ImplicitConversionSequence::Worse; 3697 } 3698 3699 // -- conversion of B* to A* is better than conversion of C* to A*, 3700 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3701 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3702 return ImplicitConversionSequence::Better; 3703 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3704 return ImplicitConversionSequence::Worse; 3705 } 3706 } else if (SCS1.Second == ICK_Pointer_Conversion && 3707 SCS2.Second == ICK_Pointer_Conversion) { 3708 const ObjCObjectPointerType *FromPtr1 3709 = FromType1->getAs<ObjCObjectPointerType>(); 3710 const ObjCObjectPointerType *FromPtr2 3711 = FromType2->getAs<ObjCObjectPointerType>(); 3712 const ObjCObjectPointerType *ToPtr1 3713 = ToType1->getAs<ObjCObjectPointerType>(); 3714 const ObjCObjectPointerType *ToPtr2 3715 = ToType2->getAs<ObjCObjectPointerType>(); 3716 3717 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3718 // Apply the same conversion ranking rules for Objective-C pointer types 3719 // that we do for C++ pointers to class types. However, we employ the 3720 // Objective-C pseudo-subtyping relationship used for assignment of 3721 // Objective-C pointer types. 3722 bool FromAssignLeft 3723 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3724 bool FromAssignRight 3725 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3726 bool ToAssignLeft 3727 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3728 bool ToAssignRight 3729 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3730 3731 // A conversion to an a non-id object pointer type or qualified 'id' 3732 // type is better than a conversion to 'id'. 3733 if (ToPtr1->isObjCIdType() && 3734 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3735 return ImplicitConversionSequence::Worse; 3736 if (ToPtr2->isObjCIdType() && 3737 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3738 return ImplicitConversionSequence::Better; 3739 3740 // A conversion to a non-id object pointer type is better than a 3741 // conversion to a qualified 'id' type 3742 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3743 return ImplicitConversionSequence::Worse; 3744 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3745 return ImplicitConversionSequence::Better; 3746 3747 // A conversion to an a non-Class object pointer type or qualified 'Class' 3748 // type is better than a conversion to 'Class'. 3749 if (ToPtr1->isObjCClassType() && 3750 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3751 return ImplicitConversionSequence::Worse; 3752 if (ToPtr2->isObjCClassType() && 3753 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3754 return ImplicitConversionSequence::Better; 3755 3756 // A conversion to a non-Class object pointer type is better than a 3757 // conversion to a qualified 'Class' type. 3758 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3759 return ImplicitConversionSequence::Worse; 3760 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3761 return ImplicitConversionSequence::Better; 3762 3763 // -- "conversion of C* to B* is better than conversion of C* to A*," 3764 if (S.Context.hasSameType(FromType1, FromType2) && 3765 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3766 (ToAssignLeft != ToAssignRight)) 3767 return ToAssignLeft? ImplicitConversionSequence::Worse 3768 : ImplicitConversionSequence::Better; 3769 3770 // -- "conversion of B* to A* is better than conversion of C* to A*," 3771 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3772 (FromAssignLeft != FromAssignRight)) 3773 return FromAssignLeft? ImplicitConversionSequence::Better 3774 : ImplicitConversionSequence::Worse; 3775 } 3776 } 3777 3778 // Ranking of member-pointer types. 3779 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3780 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3781 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3782 const MemberPointerType * FromMemPointer1 = 3783 FromType1->getAs<MemberPointerType>(); 3784 const MemberPointerType * ToMemPointer1 = 3785 ToType1->getAs<MemberPointerType>(); 3786 const MemberPointerType * FromMemPointer2 = 3787 FromType2->getAs<MemberPointerType>(); 3788 const MemberPointerType * ToMemPointer2 = 3789 ToType2->getAs<MemberPointerType>(); 3790 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3791 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3792 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3793 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3794 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3795 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3796 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3797 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3798 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3799 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3800 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3801 return ImplicitConversionSequence::Worse; 3802 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3803 return ImplicitConversionSequence::Better; 3804 } 3805 // conversion of B::* to C::* is better than conversion of A::* to C::* 3806 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3807 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3808 return ImplicitConversionSequence::Better; 3809 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3810 return ImplicitConversionSequence::Worse; 3811 } 3812 } 3813 3814 if (SCS1.Second == ICK_Derived_To_Base) { 3815 // -- conversion of C to B is better than conversion of C to A, 3816 // -- binding of an expression of type C to a reference of type 3817 // B& is better than binding an expression of type C to a 3818 // reference of type A&, 3819 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3820 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3821 if (S.IsDerivedFrom(ToType1, ToType2)) 3822 return ImplicitConversionSequence::Better; 3823 else if (S.IsDerivedFrom(ToType2, ToType1)) 3824 return ImplicitConversionSequence::Worse; 3825 } 3826 3827 // -- conversion of B to A is better than conversion of C to A. 3828 // -- binding of an expression of type B to a reference of type 3829 // A& is better than binding an expression of type C to a 3830 // reference of type A&, 3831 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3832 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3833 if (S.IsDerivedFrom(FromType2, FromType1)) 3834 return ImplicitConversionSequence::Better; 3835 else if (S.IsDerivedFrom(FromType1, FromType2)) 3836 return ImplicitConversionSequence::Worse; 3837 } 3838 } 3839 3840 return ImplicitConversionSequence::Indistinguishable; 3841} 3842 3843/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3844/// determine whether they are reference-related, 3845/// reference-compatible, reference-compatible with added 3846/// qualification, or incompatible, for use in C++ initialization by 3847/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3848/// type, and the first type (T1) is the pointee type of the reference 3849/// type being initialized. 3850Sema::ReferenceCompareResult 3851Sema::CompareReferenceRelationship(SourceLocation Loc, 3852 QualType OrigT1, QualType OrigT2, 3853 bool &DerivedToBase, 3854 bool &ObjCConversion, 3855 bool &ObjCLifetimeConversion) { 3856 assert(!OrigT1->isReferenceType() && 3857 "T1 must be the pointee type of the reference type"); 3858 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3859 3860 QualType T1 = Context.getCanonicalType(OrigT1); 3861 QualType T2 = Context.getCanonicalType(OrigT2); 3862 Qualifiers T1Quals, T2Quals; 3863 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3864 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3865 3866 // C++ [dcl.init.ref]p4: 3867 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3868 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3869 // T1 is a base class of T2. 3870 DerivedToBase = false; 3871 ObjCConversion = false; 3872 ObjCLifetimeConversion = false; 3873 if (UnqualT1 == UnqualT2) { 3874 // Nothing to do. 3875 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3876 IsDerivedFrom(UnqualT2, UnqualT1)) 3877 DerivedToBase = true; 3878 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3879 UnqualT2->isObjCObjectOrInterfaceType() && 3880 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3881 ObjCConversion = true; 3882 else 3883 return Ref_Incompatible; 3884 3885 // At this point, we know that T1 and T2 are reference-related (at 3886 // least). 3887 3888 // If the type is an array type, promote the element qualifiers to the type 3889 // for comparison. 3890 if (isa<ArrayType>(T1) && T1Quals) 3891 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3892 if (isa<ArrayType>(T2) && T2Quals) 3893 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3894 3895 // C++ [dcl.init.ref]p4: 3896 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3897 // reference-related to T2 and cv1 is the same cv-qualification 3898 // as, or greater cv-qualification than, cv2. For purposes of 3899 // overload resolution, cases for which cv1 is greater 3900 // cv-qualification than cv2 are identified as 3901 // reference-compatible with added qualification (see 13.3.3.2). 3902 // 3903 // Note that we also require equivalence of Objective-C GC and address-space 3904 // qualifiers when performing these computations, so that e.g., an int in 3905 // address space 1 is not reference-compatible with an int in address 3906 // space 2. 3907 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3908 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3909 T1Quals.removeObjCLifetime(); 3910 T2Quals.removeObjCLifetime(); 3911 ObjCLifetimeConversion = true; 3912 } 3913 3914 if (T1Quals == T2Quals) 3915 return Ref_Compatible; 3916 else if (T1Quals.compatiblyIncludes(T2Quals)) 3917 return Ref_Compatible_With_Added_Qualification; 3918 else 3919 return Ref_Related; 3920} 3921 3922/// \brief Look for a user-defined conversion to an value reference-compatible 3923/// with DeclType. Return true if something definite is found. 3924static bool 3925FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3926 QualType DeclType, SourceLocation DeclLoc, 3927 Expr *Init, QualType T2, bool AllowRvalues, 3928 bool AllowExplicit) { 3929 assert(T2->isRecordType() && "Can only find conversions of record types."); 3930 CXXRecordDecl *T2RecordDecl 3931 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3932 3933 OverloadCandidateSet CandidateSet(DeclLoc); 3934 const UnresolvedSetImpl *Conversions 3935 = T2RecordDecl->getVisibleConversionFunctions(); 3936 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3937 E = Conversions->end(); I != E; ++I) { 3938 NamedDecl *D = *I; 3939 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3940 if (isa<UsingShadowDecl>(D)) 3941 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3942 3943 FunctionTemplateDecl *ConvTemplate 3944 = dyn_cast<FunctionTemplateDecl>(D); 3945 CXXConversionDecl *Conv; 3946 if (ConvTemplate) 3947 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3948 else 3949 Conv = cast<CXXConversionDecl>(D); 3950 3951 // If this is an explicit conversion, and we're not allowed to consider 3952 // explicit conversions, skip it. 3953 if (!AllowExplicit && Conv->isExplicit()) 3954 continue; 3955 3956 if (AllowRvalues) { 3957 bool DerivedToBase = false; 3958 bool ObjCConversion = false; 3959 bool ObjCLifetimeConversion = false; 3960 3961 // If we are initializing an rvalue reference, don't permit conversion 3962 // functions that return lvalues. 3963 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3964 const ReferenceType *RefType 3965 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3966 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3967 continue; 3968 } 3969 3970 if (!ConvTemplate && 3971 S.CompareReferenceRelationship( 3972 DeclLoc, 3973 Conv->getConversionType().getNonReferenceType() 3974 .getUnqualifiedType(), 3975 DeclType.getNonReferenceType().getUnqualifiedType(), 3976 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3977 Sema::Ref_Incompatible) 3978 continue; 3979 } else { 3980 // If the conversion function doesn't return a reference type, 3981 // it can't be considered for this conversion. An rvalue reference 3982 // is only acceptable if its referencee is a function type. 3983 3984 const ReferenceType *RefType = 3985 Conv->getConversionType()->getAs<ReferenceType>(); 3986 if (!RefType || 3987 (!RefType->isLValueReferenceType() && 3988 !RefType->getPointeeType()->isFunctionType())) 3989 continue; 3990 } 3991 3992 if (ConvTemplate) 3993 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 3994 Init, DeclType, CandidateSet); 3995 else 3996 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 3997 DeclType, CandidateSet); 3998 } 3999 4000 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4001 4002 OverloadCandidateSet::iterator Best; 4003 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4004 case OR_Success: 4005 // C++ [over.ics.ref]p1: 4006 // 4007 // [...] If the parameter binds directly to the result of 4008 // applying a conversion function to the argument 4009 // expression, the implicit conversion sequence is a 4010 // user-defined conversion sequence (13.3.3.1.2), with the 4011 // second standard conversion sequence either an identity 4012 // conversion or, if the conversion function returns an 4013 // entity of a type that is a derived class of the parameter 4014 // type, a derived-to-base Conversion. 4015 if (!Best->FinalConversion.DirectBinding) 4016 return false; 4017 4018 if (Best->Function) 4019 S.MarkFunctionReferenced(DeclLoc, Best->Function); 4020 ICS.setUserDefined(); 4021 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4022 ICS.UserDefined.After = Best->FinalConversion; 4023 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4024 ICS.UserDefined.ConversionFunction = Best->Function; 4025 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4026 ICS.UserDefined.EllipsisConversion = false; 4027 assert(ICS.UserDefined.After.ReferenceBinding && 4028 ICS.UserDefined.After.DirectBinding && 4029 "Expected a direct reference binding!"); 4030 return true; 4031 4032 case OR_Ambiguous: 4033 ICS.setAmbiguous(); 4034 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4035 Cand != CandidateSet.end(); ++Cand) 4036 if (Cand->Viable) 4037 ICS.Ambiguous.addConversion(Cand->Function); 4038 return true; 4039 4040 case OR_No_Viable_Function: 4041 case OR_Deleted: 4042 // There was no suitable conversion, or we found a deleted 4043 // conversion; continue with other checks. 4044 return false; 4045 } 4046 4047 llvm_unreachable("Invalid OverloadResult!"); 4048} 4049 4050/// \brief Compute an implicit conversion sequence for reference 4051/// initialization. 4052static ImplicitConversionSequence 4053TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4054 SourceLocation DeclLoc, 4055 bool SuppressUserConversions, 4056 bool AllowExplicit) { 4057 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4058 4059 // Most paths end in a failed conversion. 4060 ImplicitConversionSequence ICS; 4061 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4062 4063 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4064 QualType T2 = Init->getType(); 4065 4066 // If the initializer is the address of an overloaded function, try 4067 // to resolve the overloaded function. If all goes well, T2 is the 4068 // type of the resulting function. 4069 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4070 DeclAccessPair Found; 4071 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4072 false, Found)) 4073 T2 = Fn->getType(); 4074 } 4075 4076 // Compute some basic properties of the types and the initializer. 4077 bool isRValRef = DeclType->isRValueReferenceType(); 4078 bool DerivedToBase = false; 4079 bool ObjCConversion = false; 4080 bool ObjCLifetimeConversion = false; 4081 Expr::Classification InitCategory = Init->Classify(S.Context); 4082 Sema::ReferenceCompareResult RefRelationship 4083 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4084 ObjCConversion, ObjCLifetimeConversion); 4085 4086 4087 // C++0x [dcl.init.ref]p5: 4088 // A reference to type "cv1 T1" is initialized by an expression 4089 // of type "cv2 T2" as follows: 4090 4091 // -- If reference is an lvalue reference and the initializer expression 4092 if (!isRValRef) { 4093 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4094 // reference-compatible with "cv2 T2," or 4095 // 4096 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4097 if (InitCategory.isLValue() && 4098 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4099 // C++ [over.ics.ref]p1: 4100 // When a parameter of reference type binds directly (8.5.3) 4101 // to an argument expression, the implicit conversion sequence 4102 // is the identity conversion, unless the argument expression 4103 // has a type that is a derived class of the parameter type, 4104 // in which case the implicit conversion sequence is a 4105 // derived-to-base Conversion (13.3.3.1). 4106 ICS.setStandard(); 4107 ICS.Standard.First = ICK_Identity; 4108 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4109 : ObjCConversion? ICK_Compatible_Conversion 4110 : ICK_Identity; 4111 ICS.Standard.Third = ICK_Identity; 4112 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4113 ICS.Standard.setToType(0, T2); 4114 ICS.Standard.setToType(1, T1); 4115 ICS.Standard.setToType(2, T1); 4116 ICS.Standard.ReferenceBinding = true; 4117 ICS.Standard.DirectBinding = true; 4118 ICS.Standard.IsLvalueReference = !isRValRef; 4119 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4120 ICS.Standard.BindsToRvalue = false; 4121 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4122 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4123 ICS.Standard.CopyConstructor = 0; 4124 4125 // Nothing more to do: the inaccessibility/ambiguity check for 4126 // derived-to-base conversions is suppressed when we're 4127 // computing the implicit conversion sequence (C++ 4128 // [over.best.ics]p2). 4129 return ICS; 4130 } 4131 4132 // -- has a class type (i.e., T2 is a class type), where T1 is 4133 // not reference-related to T2, and can be implicitly 4134 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4135 // is reference-compatible with "cv3 T3" 92) (this 4136 // conversion is selected by enumerating the applicable 4137 // conversion functions (13.3.1.6) and choosing the best 4138 // one through overload resolution (13.3)), 4139 if (!SuppressUserConversions && T2->isRecordType() && 4140 !S.RequireCompleteType(DeclLoc, T2, 0) && 4141 RefRelationship == Sema::Ref_Incompatible) { 4142 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4143 Init, T2, /*AllowRvalues=*/false, 4144 AllowExplicit)) 4145 return ICS; 4146 } 4147 } 4148 4149 // -- Otherwise, the reference shall be an lvalue reference to a 4150 // non-volatile const type (i.e., cv1 shall be const), or the reference 4151 // shall be an rvalue reference. 4152 // 4153 // We actually handle one oddity of C++ [over.ics.ref] at this 4154 // point, which is that, due to p2 (which short-circuits reference 4155 // binding by only attempting a simple conversion for non-direct 4156 // bindings) and p3's strange wording, we allow a const volatile 4157 // reference to bind to an rvalue. Hence the check for the presence 4158 // of "const" rather than checking for "const" being the only 4159 // qualifier. 4160 // This is also the point where rvalue references and lvalue inits no longer 4161 // go together. 4162 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4163 return ICS; 4164 4165 // -- If the initializer expression 4166 // 4167 // -- is an xvalue, class prvalue, array prvalue or function 4168 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4169 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4170 (InitCategory.isXValue() || 4171 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4172 (InitCategory.isLValue() && T2->isFunctionType()))) { 4173 ICS.setStandard(); 4174 ICS.Standard.First = ICK_Identity; 4175 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4176 : ObjCConversion? ICK_Compatible_Conversion 4177 : ICK_Identity; 4178 ICS.Standard.Third = ICK_Identity; 4179 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4180 ICS.Standard.setToType(0, T2); 4181 ICS.Standard.setToType(1, T1); 4182 ICS.Standard.setToType(2, T1); 4183 ICS.Standard.ReferenceBinding = true; 4184 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4185 // binding unless we're binding to a class prvalue. 4186 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4187 // allow the use of rvalue references in C++98/03 for the benefit of 4188 // standard library implementors; therefore, we need the xvalue check here. 4189 ICS.Standard.DirectBinding = 4190 S.getLangOpts().CPlusPlus0x || 4191 (InitCategory.isPRValue() && !T2->isRecordType()); 4192 ICS.Standard.IsLvalueReference = !isRValRef; 4193 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4194 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4195 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4196 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4197 ICS.Standard.CopyConstructor = 0; 4198 return ICS; 4199 } 4200 4201 // -- has a class type (i.e., T2 is a class type), where T1 is not 4202 // reference-related to T2, and can be implicitly converted to 4203 // an xvalue, class prvalue, or function lvalue of type 4204 // "cv3 T3", where "cv1 T1" is reference-compatible with 4205 // "cv3 T3", 4206 // 4207 // then the reference is bound to the value of the initializer 4208 // expression in the first case and to the result of the conversion 4209 // in the second case (or, in either case, to an appropriate base 4210 // class subobject). 4211 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4212 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4213 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4214 Init, T2, /*AllowRvalues=*/true, 4215 AllowExplicit)) { 4216 // In the second case, if the reference is an rvalue reference 4217 // and the second standard conversion sequence of the 4218 // user-defined conversion sequence includes an lvalue-to-rvalue 4219 // conversion, the program is ill-formed. 4220 if (ICS.isUserDefined() && isRValRef && 4221 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4222 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4223 4224 return ICS; 4225 } 4226 4227 // -- Otherwise, a temporary of type "cv1 T1" is created and 4228 // initialized from the initializer expression using the 4229 // rules for a non-reference copy initialization (8.5). The 4230 // reference is then bound to the temporary. If T1 is 4231 // reference-related to T2, cv1 must be the same 4232 // cv-qualification as, or greater cv-qualification than, 4233 // cv2; otherwise, the program is ill-formed. 4234 if (RefRelationship == Sema::Ref_Related) { 4235 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4236 // we would be reference-compatible or reference-compatible with 4237 // added qualification. But that wasn't the case, so the reference 4238 // initialization fails. 4239 // 4240 // Note that we only want to check address spaces and cvr-qualifiers here. 4241 // ObjC GC and lifetime qualifiers aren't important. 4242 Qualifiers T1Quals = T1.getQualifiers(); 4243 Qualifiers T2Quals = T2.getQualifiers(); 4244 T1Quals.removeObjCGCAttr(); 4245 T1Quals.removeObjCLifetime(); 4246 T2Quals.removeObjCGCAttr(); 4247 T2Quals.removeObjCLifetime(); 4248 if (!T1Quals.compatiblyIncludes(T2Quals)) 4249 return ICS; 4250 } 4251 4252 // If at least one of the types is a class type, the types are not 4253 // related, and we aren't allowed any user conversions, the 4254 // reference binding fails. This case is important for breaking 4255 // recursion, since TryImplicitConversion below will attempt to 4256 // create a temporary through the use of a copy constructor. 4257 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4258 (T1->isRecordType() || T2->isRecordType())) 4259 return ICS; 4260 4261 // If T1 is reference-related to T2 and the reference is an rvalue 4262 // reference, the initializer expression shall not be an lvalue. 4263 if (RefRelationship >= Sema::Ref_Related && 4264 isRValRef && Init->Classify(S.Context).isLValue()) 4265 return ICS; 4266 4267 // C++ [over.ics.ref]p2: 4268 // When a parameter of reference type is not bound directly to 4269 // an argument expression, the conversion sequence is the one 4270 // required to convert the argument expression to the 4271 // underlying type of the reference according to 4272 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4273 // to copy-initializing a temporary of the underlying type with 4274 // the argument expression. Any difference in top-level 4275 // cv-qualification is subsumed by the initialization itself 4276 // and does not constitute a conversion. 4277 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4278 /*AllowExplicit=*/false, 4279 /*InOverloadResolution=*/false, 4280 /*CStyle=*/false, 4281 /*AllowObjCWritebackConversion=*/false); 4282 4283 // Of course, that's still a reference binding. 4284 if (ICS.isStandard()) { 4285 ICS.Standard.ReferenceBinding = true; 4286 ICS.Standard.IsLvalueReference = !isRValRef; 4287 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4288 ICS.Standard.BindsToRvalue = true; 4289 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4290 ICS.Standard.ObjCLifetimeConversionBinding = false; 4291 } else if (ICS.isUserDefined()) { 4292 // Don't allow rvalue references to bind to lvalues. 4293 if (DeclType->isRValueReferenceType()) { 4294 if (const ReferenceType *RefType 4295 = ICS.UserDefined.ConversionFunction->getResultType() 4296 ->getAs<LValueReferenceType>()) { 4297 if (!RefType->getPointeeType()->isFunctionType()) { 4298 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4299 DeclType); 4300 return ICS; 4301 } 4302 } 4303 } 4304 4305 ICS.UserDefined.After.ReferenceBinding = true; 4306 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4307 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4308 ICS.UserDefined.After.BindsToRvalue = true; 4309 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4310 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4311 } 4312 4313 return ICS; 4314} 4315 4316static ImplicitConversionSequence 4317TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4318 bool SuppressUserConversions, 4319 bool InOverloadResolution, 4320 bool AllowObjCWritebackConversion, 4321 bool AllowExplicit = false); 4322 4323/// TryListConversion - Try to copy-initialize a value of type ToType from the 4324/// initializer list From. 4325static ImplicitConversionSequence 4326TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4327 bool SuppressUserConversions, 4328 bool InOverloadResolution, 4329 bool AllowObjCWritebackConversion) { 4330 // C++11 [over.ics.list]p1: 4331 // When an argument is an initializer list, it is not an expression and 4332 // special rules apply for converting it to a parameter type. 4333 4334 ImplicitConversionSequence Result; 4335 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4336 Result.setListInitializationSequence(); 4337 4338 // We need a complete type for what follows. Incomplete types can never be 4339 // initialized from init lists. 4340 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4341 return Result; 4342 4343 // C++11 [over.ics.list]p2: 4344 // If the parameter type is std::initializer_list<X> or "array of X" and 4345 // all the elements can be implicitly converted to X, the implicit 4346 // conversion sequence is the worst conversion necessary to convert an 4347 // element of the list to X. 4348 bool toStdInitializerList = false; 4349 QualType X; 4350 if (ToType->isArrayType()) 4351 X = S.Context.getBaseElementType(ToType); 4352 else 4353 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4354 if (!X.isNull()) { 4355 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4356 Expr *Init = From->getInit(i); 4357 ImplicitConversionSequence ICS = 4358 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4359 InOverloadResolution, 4360 AllowObjCWritebackConversion); 4361 // If a single element isn't convertible, fail. 4362 if (ICS.isBad()) { 4363 Result = ICS; 4364 break; 4365 } 4366 // Otherwise, look for the worst conversion. 4367 if (Result.isBad() || 4368 CompareImplicitConversionSequences(S, ICS, Result) == 4369 ImplicitConversionSequence::Worse) 4370 Result = ICS; 4371 } 4372 4373 // For an empty list, we won't have computed any conversion sequence. 4374 // Introduce the identity conversion sequence. 4375 if (From->getNumInits() == 0) { 4376 Result.setStandard(); 4377 Result.Standard.setAsIdentityConversion(); 4378 Result.Standard.setFromType(ToType); 4379 Result.Standard.setAllToTypes(ToType); 4380 } 4381 4382 Result.setListInitializationSequence(); 4383 Result.setStdInitializerListElement(toStdInitializerList); 4384 return Result; 4385 } 4386 4387 // C++11 [over.ics.list]p3: 4388 // Otherwise, if the parameter is a non-aggregate class X and overload 4389 // resolution chooses a single best constructor [...] the implicit 4390 // conversion sequence is a user-defined conversion sequence. If multiple 4391 // constructors are viable but none is better than the others, the 4392 // implicit conversion sequence is a user-defined conversion sequence. 4393 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4394 // This function can deal with initializer lists. 4395 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4396 /*AllowExplicit=*/false, 4397 InOverloadResolution, /*CStyle=*/false, 4398 AllowObjCWritebackConversion); 4399 Result.setListInitializationSequence(); 4400 return Result; 4401 } 4402 4403 // C++11 [over.ics.list]p4: 4404 // Otherwise, if the parameter has an aggregate type which can be 4405 // initialized from the initializer list [...] the implicit conversion 4406 // sequence is a user-defined conversion sequence. 4407 if (ToType->isAggregateType()) { 4408 // Type is an aggregate, argument is an init list. At this point it comes 4409 // down to checking whether the initialization works. 4410 // FIXME: Find out whether this parameter is consumed or not. 4411 InitializedEntity Entity = 4412 InitializedEntity::InitializeParameter(S.Context, ToType, 4413 /*Consumed=*/false); 4414 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4415 Result.setUserDefined(); 4416 Result.UserDefined.Before.setAsIdentityConversion(); 4417 // Initializer lists don't have a type. 4418 Result.UserDefined.Before.setFromType(QualType()); 4419 Result.UserDefined.Before.setAllToTypes(QualType()); 4420 4421 Result.UserDefined.After.setAsIdentityConversion(); 4422 Result.UserDefined.After.setFromType(ToType); 4423 Result.UserDefined.After.setAllToTypes(ToType); 4424 Result.UserDefined.ConversionFunction = 0; 4425 } 4426 return Result; 4427 } 4428 4429 // C++11 [over.ics.list]p5: 4430 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4431 if (ToType->isReferenceType()) { 4432 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4433 // mention initializer lists in any way. So we go by what list- 4434 // initialization would do and try to extrapolate from that. 4435 4436 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4437 4438 // If the initializer list has a single element that is reference-related 4439 // to the parameter type, we initialize the reference from that. 4440 if (From->getNumInits() == 1) { 4441 Expr *Init = From->getInit(0); 4442 4443 QualType T2 = Init->getType(); 4444 4445 // If the initializer is the address of an overloaded function, try 4446 // to resolve the overloaded function. If all goes well, T2 is the 4447 // type of the resulting function. 4448 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4449 DeclAccessPair Found; 4450 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4451 Init, ToType, false, Found)) 4452 T2 = Fn->getType(); 4453 } 4454 4455 // Compute some basic properties of the types and the initializer. 4456 bool dummy1 = false; 4457 bool dummy2 = false; 4458 bool dummy3 = false; 4459 Sema::ReferenceCompareResult RefRelationship 4460 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4461 dummy2, dummy3); 4462 4463 if (RefRelationship >= Sema::Ref_Related) 4464 return TryReferenceInit(S, Init, ToType, 4465 /*FIXME:*/From->getLocStart(), 4466 SuppressUserConversions, 4467 /*AllowExplicit=*/false); 4468 } 4469 4470 // Otherwise, we bind the reference to a temporary created from the 4471 // initializer list. 4472 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4473 InOverloadResolution, 4474 AllowObjCWritebackConversion); 4475 if (Result.isFailure()) 4476 return Result; 4477 assert(!Result.isEllipsis() && 4478 "Sub-initialization cannot result in ellipsis conversion."); 4479 4480 // Can we even bind to a temporary? 4481 if (ToType->isRValueReferenceType() || 4482 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4483 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4484 Result.UserDefined.After; 4485 SCS.ReferenceBinding = true; 4486 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4487 SCS.BindsToRvalue = true; 4488 SCS.BindsToFunctionLvalue = false; 4489 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4490 SCS.ObjCLifetimeConversionBinding = false; 4491 } else 4492 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4493 From, ToType); 4494 return Result; 4495 } 4496 4497 // C++11 [over.ics.list]p6: 4498 // Otherwise, if the parameter type is not a class: 4499 if (!ToType->isRecordType()) { 4500 // - if the initializer list has one element, the implicit conversion 4501 // sequence is the one required to convert the element to the 4502 // parameter type. 4503 unsigned NumInits = From->getNumInits(); 4504 if (NumInits == 1) 4505 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4506 SuppressUserConversions, 4507 InOverloadResolution, 4508 AllowObjCWritebackConversion); 4509 // - if the initializer list has no elements, the implicit conversion 4510 // sequence is the identity conversion. 4511 else if (NumInits == 0) { 4512 Result.setStandard(); 4513 Result.Standard.setAsIdentityConversion(); 4514 Result.Standard.setFromType(ToType); 4515 Result.Standard.setAllToTypes(ToType); 4516 } 4517 Result.setListInitializationSequence(); 4518 return Result; 4519 } 4520 4521 // C++11 [over.ics.list]p7: 4522 // In all cases other than those enumerated above, no conversion is possible 4523 return Result; 4524} 4525 4526/// TryCopyInitialization - Try to copy-initialize a value of type 4527/// ToType from the expression From. Return the implicit conversion 4528/// sequence required to pass this argument, which may be a bad 4529/// conversion sequence (meaning that the argument cannot be passed to 4530/// a parameter of this type). If @p SuppressUserConversions, then we 4531/// do not permit any user-defined conversion sequences. 4532static ImplicitConversionSequence 4533TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4534 bool SuppressUserConversions, 4535 bool InOverloadResolution, 4536 bool AllowObjCWritebackConversion, 4537 bool AllowExplicit) { 4538 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4539 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4540 InOverloadResolution,AllowObjCWritebackConversion); 4541 4542 if (ToType->isReferenceType()) 4543 return TryReferenceInit(S, From, ToType, 4544 /*FIXME:*/From->getLocStart(), 4545 SuppressUserConversions, 4546 AllowExplicit); 4547 4548 return TryImplicitConversion(S, From, ToType, 4549 SuppressUserConversions, 4550 /*AllowExplicit=*/false, 4551 InOverloadResolution, 4552 /*CStyle=*/false, 4553 AllowObjCWritebackConversion); 4554} 4555 4556static bool TryCopyInitialization(const CanQualType FromQTy, 4557 const CanQualType ToQTy, 4558 Sema &S, 4559 SourceLocation Loc, 4560 ExprValueKind FromVK) { 4561 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4562 ImplicitConversionSequence ICS = 4563 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4564 4565 return !ICS.isBad(); 4566} 4567 4568/// TryObjectArgumentInitialization - Try to initialize the object 4569/// parameter of the given member function (@c Method) from the 4570/// expression @p From. 4571static ImplicitConversionSequence 4572TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4573 Expr::Classification FromClassification, 4574 CXXMethodDecl *Method, 4575 CXXRecordDecl *ActingContext) { 4576 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4577 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4578 // const volatile object. 4579 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4580 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4581 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4582 4583 // Set up the conversion sequence as a "bad" conversion, to allow us 4584 // to exit early. 4585 ImplicitConversionSequence ICS; 4586 4587 // We need to have an object of class type. 4588 QualType FromType = OrigFromType; 4589 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4590 FromType = PT->getPointeeType(); 4591 4592 // When we had a pointer, it's implicitly dereferenced, so we 4593 // better have an lvalue. 4594 assert(FromClassification.isLValue()); 4595 } 4596 4597 assert(FromType->isRecordType()); 4598 4599 // C++0x [over.match.funcs]p4: 4600 // For non-static member functions, the type of the implicit object 4601 // parameter is 4602 // 4603 // - "lvalue reference to cv X" for functions declared without a 4604 // ref-qualifier or with the & ref-qualifier 4605 // - "rvalue reference to cv X" for functions declared with the && 4606 // ref-qualifier 4607 // 4608 // where X is the class of which the function is a member and cv is the 4609 // cv-qualification on the member function declaration. 4610 // 4611 // However, when finding an implicit conversion sequence for the argument, we 4612 // are not allowed to create temporaries or perform user-defined conversions 4613 // (C++ [over.match.funcs]p5). We perform a simplified version of 4614 // reference binding here, that allows class rvalues to bind to 4615 // non-constant references. 4616 4617 // First check the qualifiers. 4618 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4619 if (ImplicitParamType.getCVRQualifiers() 4620 != FromTypeCanon.getLocalCVRQualifiers() && 4621 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4622 ICS.setBad(BadConversionSequence::bad_qualifiers, 4623 OrigFromType, ImplicitParamType); 4624 return ICS; 4625 } 4626 4627 // Check that we have either the same type or a derived type. It 4628 // affects the conversion rank. 4629 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4630 ImplicitConversionKind SecondKind; 4631 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4632 SecondKind = ICK_Identity; 4633 } else if (S.IsDerivedFrom(FromType, ClassType)) 4634 SecondKind = ICK_Derived_To_Base; 4635 else { 4636 ICS.setBad(BadConversionSequence::unrelated_class, 4637 FromType, ImplicitParamType); 4638 return ICS; 4639 } 4640 4641 // Check the ref-qualifier. 4642 switch (Method->getRefQualifier()) { 4643 case RQ_None: 4644 // Do nothing; we don't care about lvalueness or rvalueness. 4645 break; 4646 4647 case RQ_LValue: 4648 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4649 // non-const lvalue reference cannot bind to an rvalue 4650 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4651 ImplicitParamType); 4652 return ICS; 4653 } 4654 break; 4655 4656 case RQ_RValue: 4657 if (!FromClassification.isRValue()) { 4658 // rvalue reference cannot bind to an lvalue 4659 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4660 ImplicitParamType); 4661 return ICS; 4662 } 4663 break; 4664 } 4665 4666 // Success. Mark this as a reference binding. 4667 ICS.setStandard(); 4668 ICS.Standard.setAsIdentityConversion(); 4669 ICS.Standard.Second = SecondKind; 4670 ICS.Standard.setFromType(FromType); 4671 ICS.Standard.setAllToTypes(ImplicitParamType); 4672 ICS.Standard.ReferenceBinding = true; 4673 ICS.Standard.DirectBinding = true; 4674 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4675 ICS.Standard.BindsToFunctionLvalue = false; 4676 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4677 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4678 = (Method->getRefQualifier() == RQ_None); 4679 return ICS; 4680} 4681 4682/// PerformObjectArgumentInitialization - Perform initialization of 4683/// the implicit object parameter for the given Method with the given 4684/// expression. 4685ExprResult 4686Sema::PerformObjectArgumentInitialization(Expr *From, 4687 NestedNameSpecifier *Qualifier, 4688 NamedDecl *FoundDecl, 4689 CXXMethodDecl *Method) { 4690 QualType FromRecordType, DestType; 4691 QualType ImplicitParamRecordType = 4692 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4693 4694 Expr::Classification FromClassification; 4695 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4696 FromRecordType = PT->getPointeeType(); 4697 DestType = Method->getThisType(Context); 4698 FromClassification = Expr::Classification::makeSimpleLValue(); 4699 } else { 4700 FromRecordType = From->getType(); 4701 DestType = ImplicitParamRecordType; 4702 FromClassification = From->Classify(Context); 4703 } 4704 4705 // Note that we always use the true parent context when performing 4706 // the actual argument initialization. 4707 ImplicitConversionSequence ICS 4708 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4709 Method, Method->getParent()); 4710 if (ICS.isBad()) { 4711 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4712 Qualifiers FromQs = FromRecordType.getQualifiers(); 4713 Qualifiers ToQs = DestType.getQualifiers(); 4714 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4715 if (CVR) { 4716 Diag(From->getLocStart(), 4717 diag::err_member_function_call_bad_cvr) 4718 << Method->getDeclName() << FromRecordType << (CVR - 1) 4719 << From->getSourceRange(); 4720 Diag(Method->getLocation(), diag::note_previous_decl) 4721 << Method->getDeclName(); 4722 return ExprError(); 4723 } 4724 } 4725 4726 return Diag(From->getLocStart(), 4727 diag::err_implicit_object_parameter_init) 4728 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4729 } 4730 4731 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4732 ExprResult FromRes = 4733 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4734 if (FromRes.isInvalid()) 4735 return ExprError(); 4736 From = FromRes.take(); 4737 } 4738 4739 if (!Context.hasSameType(From->getType(), DestType)) 4740 From = ImpCastExprToType(From, DestType, CK_NoOp, 4741 From->getValueKind()).take(); 4742 return Owned(From); 4743} 4744 4745/// TryContextuallyConvertToBool - Attempt to contextually convert the 4746/// expression From to bool (C++0x [conv]p3). 4747static ImplicitConversionSequence 4748TryContextuallyConvertToBool(Sema &S, Expr *From) { 4749 // FIXME: This is pretty broken. 4750 return TryImplicitConversion(S, From, S.Context.BoolTy, 4751 // FIXME: Are these flags correct? 4752 /*SuppressUserConversions=*/false, 4753 /*AllowExplicit=*/true, 4754 /*InOverloadResolution=*/false, 4755 /*CStyle=*/false, 4756 /*AllowObjCWritebackConversion=*/false); 4757} 4758 4759/// PerformContextuallyConvertToBool - Perform a contextual conversion 4760/// of the expression From to bool (C++0x [conv]p3). 4761ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4762 if (checkPlaceholderForOverload(*this, From)) 4763 return ExprError(); 4764 4765 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4766 if (!ICS.isBad()) 4767 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4768 4769 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4770 return Diag(From->getLocStart(), 4771 diag::err_typecheck_bool_condition) 4772 << From->getType() << From->getSourceRange(); 4773 return ExprError(); 4774} 4775 4776/// Check that the specified conversion is permitted in a converted constant 4777/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4778/// is acceptable. 4779static bool CheckConvertedConstantConversions(Sema &S, 4780 StandardConversionSequence &SCS) { 4781 // Since we know that the target type is an integral or unscoped enumeration 4782 // type, most conversion kinds are impossible. All possible First and Third 4783 // conversions are fine. 4784 switch (SCS.Second) { 4785 case ICK_Identity: 4786 case ICK_Integral_Promotion: 4787 case ICK_Integral_Conversion: 4788 return true; 4789 4790 case ICK_Boolean_Conversion: 4791 // Conversion from an integral or unscoped enumeration type to bool is 4792 // classified as ICK_Boolean_Conversion, but it's also an integral 4793 // conversion, so it's permitted in a converted constant expression. 4794 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4795 SCS.getToType(2)->isBooleanType(); 4796 4797 case ICK_Floating_Integral: 4798 case ICK_Complex_Real: 4799 return false; 4800 4801 case ICK_Lvalue_To_Rvalue: 4802 case ICK_Array_To_Pointer: 4803 case ICK_Function_To_Pointer: 4804 case ICK_NoReturn_Adjustment: 4805 case ICK_Qualification: 4806 case ICK_Compatible_Conversion: 4807 case ICK_Vector_Conversion: 4808 case ICK_Vector_Splat: 4809 case ICK_Derived_To_Base: 4810 case ICK_Pointer_Conversion: 4811 case ICK_Pointer_Member: 4812 case ICK_Block_Pointer_Conversion: 4813 case ICK_Writeback_Conversion: 4814 case ICK_Floating_Promotion: 4815 case ICK_Complex_Promotion: 4816 case ICK_Complex_Conversion: 4817 case ICK_Floating_Conversion: 4818 case ICK_TransparentUnionConversion: 4819 llvm_unreachable("unexpected second conversion kind"); 4820 4821 case ICK_Num_Conversion_Kinds: 4822 break; 4823 } 4824 4825 llvm_unreachable("unknown conversion kind"); 4826} 4827 4828/// CheckConvertedConstantExpression - Check that the expression From is a 4829/// converted constant expression of type T, perform the conversion and produce 4830/// the converted expression, per C++11 [expr.const]p3. 4831ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4832 llvm::APSInt &Value, 4833 CCEKind CCE) { 4834 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4835 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4836 4837 if (checkPlaceholderForOverload(*this, From)) 4838 return ExprError(); 4839 4840 // C++11 [expr.const]p3 with proposed wording fixes: 4841 // A converted constant expression of type T is a core constant expression, 4842 // implicitly converted to a prvalue of type T, where the converted 4843 // expression is a literal constant expression and the implicit conversion 4844 // sequence contains only user-defined conversions, lvalue-to-rvalue 4845 // conversions, integral promotions, and integral conversions other than 4846 // narrowing conversions. 4847 ImplicitConversionSequence ICS = 4848 TryImplicitConversion(From, T, 4849 /*SuppressUserConversions=*/false, 4850 /*AllowExplicit=*/false, 4851 /*InOverloadResolution=*/false, 4852 /*CStyle=*/false, 4853 /*AllowObjcWritebackConversion=*/false); 4854 StandardConversionSequence *SCS = 0; 4855 switch (ICS.getKind()) { 4856 case ImplicitConversionSequence::StandardConversion: 4857 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4858 return Diag(From->getLocStart(), 4859 diag::err_typecheck_converted_constant_expression_disallowed) 4860 << From->getType() << From->getSourceRange() << T; 4861 SCS = &ICS.Standard; 4862 break; 4863 case ImplicitConversionSequence::UserDefinedConversion: 4864 // We are converting from class type to an integral or enumeration type, so 4865 // the Before sequence must be trivial. 4866 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4867 return Diag(From->getLocStart(), 4868 diag::err_typecheck_converted_constant_expression_disallowed) 4869 << From->getType() << From->getSourceRange() << T; 4870 SCS = &ICS.UserDefined.After; 4871 break; 4872 case ImplicitConversionSequence::AmbiguousConversion: 4873 case ImplicitConversionSequence::BadConversion: 4874 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4875 return Diag(From->getLocStart(), 4876 diag::err_typecheck_converted_constant_expression) 4877 << From->getType() << From->getSourceRange() << T; 4878 return ExprError(); 4879 4880 case ImplicitConversionSequence::EllipsisConversion: 4881 llvm_unreachable("ellipsis conversion in converted constant expression"); 4882 } 4883 4884 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4885 if (Result.isInvalid()) 4886 return Result; 4887 4888 // Check for a narrowing implicit conversion. 4889 APValue PreNarrowingValue; 4890 QualType PreNarrowingType; 4891 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4892 PreNarrowingType)) { 4893 case NK_Variable_Narrowing: 4894 // Implicit conversion to a narrower type, and the value is not a constant 4895 // expression. We'll diagnose this in a moment. 4896 case NK_Not_Narrowing: 4897 break; 4898 4899 case NK_Constant_Narrowing: 4900 Diag(From->getLocStart(), 4901 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4902 diag::err_cce_narrowing) 4903 << CCE << /*Constant*/1 4904 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4905 break; 4906 4907 case NK_Type_Narrowing: 4908 Diag(From->getLocStart(), 4909 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4910 diag::err_cce_narrowing) 4911 << CCE << /*Constant*/0 << From->getType() << T; 4912 break; 4913 } 4914 4915 // Check the expression is a constant expression. 4916 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4917 Expr::EvalResult Eval; 4918 Eval.Diag = &Notes; 4919 4920 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4921 // The expression can't be folded, so we can't keep it at this position in 4922 // the AST. 4923 Result = ExprError(); 4924 } else { 4925 Value = Eval.Val.getInt(); 4926 4927 if (Notes.empty()) { 4928 // It's a constant expression. 4929 return Result; 4930 } 4931 } 4932 4933 // It's not a constant expression. Produce an appropriate diagnostic. 4934 if (Notes.size() == 1 && 4935 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4936 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4937 else { 4938 Diag(From->getLocStart(), diag::err_expr_not_cce) 4939 << CCE << From->getSourceRange(); 4940 for (unsigned I = 0; I < Notes.size(); ++I) 4941 Diag(Notes[I].first, Notes[I].second); 4942 } 4943 return Result; 4944} 4945 4946/// dropPointerConversions - If the given standard conversion sequence 4947/// involves any pointer conversions, remove them. This may change 4948/// the result type of the conversion sequence. 4949static void dropPointerConversion(StandardConversionSequence &SCS) { 4950 if (SCS.Second == ICK_Pointer_Conversion) { 4951 SCS.Second = ICK_Identity; 4952 SCS.Third = ICK_Identity; 4953 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4954 } 4955} 4956 4957/// TryContextuallyConvertToObjCPointer - Attempt to contextually 4958/// convert the expression From to an Objective-C pointer type. 4959static ImplicitConversionSequence 4960TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4961 // Do an implicit conversion to 'id'. 4962 QualType Ty = S.Context.getObjCIdType(); 4963 ImplicitConversionSequence ICS 4964 = TryImplicitConversion(S, From, Ty, 4965 // FIXME: Are these flags correct? 4966 /*SuppressUserConversions=*/false, 4967 /*AllowExplicit=*/true, 4968 /*InOverloadResolution=*/false, 4969 /*CStyle=*/false, 4970 /*AllowObjCWritebackConversion=*/false); 4971 4972 // Strip off any final conversions to 'id'. 4973 switch (ICS.getKind()) { 4974 case ImplicitConversionSequence::BadConversion: 4975 case ImplicitConversionSequence::AmbiguousConversion: 4976 case ImplicitConversionSequence::EllipsisConversion: 4977 break; 4978 4979 case ImplicitConversionSequence::UserDefinedConversion: 4980 dropPointerConversion(ICS.UserDefined.After); 4981 break; 4982 4983 case ImplicitConversionSequence::StandardConversion: 4984 dropPointerConversion(ICS.Standard); 4985 break; 4986 } 4987 4988 return ICS; 4989} 4990 4991/// PerformContextuallyConvertToObjCPointer - Perform a contextual 4992/// conversion of the expression From to an Objective-C pointer type. 4993ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 4994 if (checkPlaceholderForOverload(*this, From)) 4995 return ExprError(); 4996 4997 QualType Ty = Context.getObjCIdType(); 4998 ImplicitConversionSequence ICS = 4999 TryContextuallyConvertToObjCPointer(*this, From); 5000 if (!ICS.isBad()) 5001 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5002 return ExprError(); 5003} 5004 5005/// Determine whether the provided type is an integral type, or an enumeration 5006/// type of a permitted flavor. 5007static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5008 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5009 : T->isIntegralOrUnscopedEnumerationType(); 5010} 5011 5012/// \brief Attempt to convert the given expression to an integral or 5013/// enumeration type. 5014/// 5015/// This routine will attempt to convert an expression of class type to an 5016/// integral or enumeration type, if that class type only has a single 5017/// conversion to an integral or enumeration type. 5018/// 5019/// \param Loc The source location of the construct that requires the 5020/// conversion. 5021/// 5022/// \param FromE The expression we're converting from. 5023/// 5024/// \param NotIntDiag The diagnostic to be emitted if the expression does not 5025/// have integral or enumeration type. 5026/// 5027/// \param IncompleteDiag The diagnostic to be emitted if the expression has 5028/// incomplete class type. 5029/// 5030/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an 5031/// explicit conversion function (because no implicit conversion functions 5032/// were available). This is a recovery mode. 5033/// 5034/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag, 5035/// showing which conversion was picked. 5036/// 5037/// \param AmbigDiag The diagnostic to be emitted if there is more than one 5038/// conversion function that could convert to integral or enumeration type. 5039/// 5040/// \param AmbigNote The note to be emitted with \p AmbigDiag for each 5041/// usable conversion function. 5042/// 5043/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion 5044/// function, which may be an extension in this case. 5045/// 5046/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5047/// enumerations should be considered. 5048/// 5049/// \returns The expression, converted to an integral or enumeration type if 5050/// successful. 5051ExprResult 5052Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5053 ICEConvertDiagnoser &Diagnoser, 5054 bool AllowScopedEnumerations) { 5055 // We can't perform any more checking for type-dependent expressions. 5056 if (From->isTypeDependent()) 5057 return Owned(From); 5058 5059 // Process placeholders immediately. 5060 if (From->hasPlaceholderType()) { 5061 ExprResult result = CheckPlaceholderExpr(From); 5062 if (result.isInvalid()) return result; 5063 From = result.take(); 5064 } 5065 5066 // If the expression already has integral or enumeration type, we're golden. 5067 QualType T = From->getType(); 5068 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5069 return DefaultLvalueConversion(From); 5070 5071 // FIXME: Check for missing '()' if T is a function type? 5072 5073 // If we don't have a class type in C++, there's no way we can get an 5074 // expression of integral or enumeration type. 5075 const RecordType *RecordTy = T->getAs<RecordType>(); 5076 if (!RecordTy || !getLangOpts().CPlusPlus) { 5077 if (!Diagnoser.Suppress) 5078 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5079 return Owned(From); 5080 } 5081 5082 // We must have a complete class type. 5083 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5084 ICEConvertDiagnoser &Diagnoser; 5085 Expr *From; 5086 5087 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5088 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5089 5090 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5091 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5092 } 5093 } IncompleteDiagnoser(Diagnoser, From); 5094 5095 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5096 return Owned(From); 5097 5098 // Look for a conversion to an integral or enumeration type. 5099 UnresolvedSet<4> ViableConversions; 5100 UnresolvedSet<4> ExplicitConversions; 5101 const UnresolvedSetImpl *Conversions 5102 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5103 5104 bool HadMultipleCandidates = (Conversions->size() > 1); 5105 5106 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5107 E = Conversions->end(); 5108 I != E; 5109 ++I) { 5110 if (CXXConversionDecl *Conversion 5111 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5112 if (isIntegralOrEnumerationType( 5113 Conversion->getConversionType().getNonReferenceType(), 5114 AllowScopedEnumerations)) { 5115 if (Conversion->isExplicit()) 5116 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5117 else 5118 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5119 } 5120 } 5121 } 5122 5123 switch (ViableConversions.size()) { 5124 case 0: 5125 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5126 DeclAccessPair Found = ExplicitConversions[0]; 5127 CXXConversionDecl *Conversion 5128 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5129 5130 // The user probably meant to invoke the given explicit 5131 // conversion; use it. 5132 QualType ConvTy 5133 = Conversion->getConversionType().getNonReferenceType(); 5134 std::string TypeStr; 5135 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5136 5137 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5138 << FixItHint::CreateInsertion(From->getLocStart(), 5139 "static_cast<" + TypeStr + ">(") 5140 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5141 ")"); 5142 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5143 5144 // If we aren't in a SFINAE context, build a call to the 5145 // explicit conversion function. 5146 if (isSFINAEContext()) 5147 return ExprError(); 5148 5149 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5150 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5151 HadMultipleCandidates); 5152 if (Result.isInvalid()) 5153 return ExprError(); 5154 // Record usage of conversion in an implicit cast. 5155 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5156 CK_UserDefinedConversion, 5157 Result.get(), 0, 5158 Result.get()->getValueKind()); 5159 } 5160 5161 // We'll complain below about a non-integral condition type. 5162 break; 5163 5164 case 1: { 5165 // Apply this conversion. 5166 DeclAccessPair Found = ViableConversions[0]; 5167 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5168 5169 CXXConversionDecl *Conversion 5170 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5171 QualType ConvTy 5172 = Conversion->getConversionType().getNonReferenceType(); 5173 if (!Diagnoser.SuppressConversion) { 5174 if (isSFINAEContext()) 5175 return ExprError(); 5176 5177 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5178 << From->getSourceRange(); 5179 } 5180 5181 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5182 HadMultipleCandidates); 5183 if (Result.isInvalid()) 5184 return ExprError(); 5185 // Record usage of conversion in an implicit cast. 5186 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5187 CK_UserDefinedConversion, 5188 Result.get(), 0, 5189 Result.get()->getValueKind()); 5190 break; 5191 } 5192 5193 default: 5194 if (Diagnoser.Suppress) 5195 return ExprError(); 5196 5197 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5198 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5199 CXXConversionDecl *Conv 5200 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5201 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5202 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5203 } 5204 return Owned(From); 5205 } 5206 5207 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5208 !Diagnoser.Suppress) { 5209 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5210 << From->getSourceRange(); 5211 } 5212 5213 return DefaultLvalueConversion(From); 5214} 5215 5216/// AddOverloadCandidate - Adds the given function to the set of 5217/// candidate functions, using the given function call arguments. If 5218/// @p SuppressUserConversions, then don't allow user-defined 5219/// conversions via constructors or conversion operators. 5220/// 5221/// \param PartialOverloading true if we are performing "partial" overloading 5222/// based on an incomplete set of function arguments. This feature is used by 5223/// code completion. 5224void 5225Sema::AddOverloadCandidate(FunctionDecl *Function, 5226 DeclAccessPair FoundDecl, 5227 llvm::ArrayRef<Expr *> Args, 5228 OverloadCandidateSet& CandidateSet, 5229 bool SuppressUserConversions, 5230 bool PartialOverloading, 5231 bool AllowExplicit) { 5232 const FunctionProtoType* Proto 5233 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5234 assert(Proto && "Functions without a prototype cannot be overloaded"); 5235 assert(!Function->getDescribedFunctionTemplate() && 5236 "Use AddTemplateOverloadCandidate for function templates"); 5237 5238 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5239 if (!isa<CXXConstructorDecl>(Method)) { 5240 // If we get here, it's because we're calling a member function 5241 // that is named without a member access expression (e.g., 5242 // "this->f") that was either written explicitly or created 5243 // implicitly. This can happen with a qualified call to a member 5244 // function, e.g., X::f(). We use an empty type for the implied 5245 // object argument (C++ [over.call.func]p3), and the acting context 5246 // is irrelevant. 5247 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5248 QualType(), Expr::Classification::makeSimpleLValue(), 5249 Args, CandidateSet, SuppressUserConversions); 5250 return; 5251 } 5252 // We treat a constructor like a non-member function, since its object 5253 // argument doesn't participate in overload resolution. 5254 } 5255 5256 if (!CandidateSet.isNewCandidate(Function)) 5257 return; 5258 5259 // Overload resolution is always an unevaluated context. 5260 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5261 5262 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5263 // C++ [class.copy]p3: 5264 // A member function template is never instantiated to perform the copy 5265 // of a class object to an object of its class type. 5266 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5267 if (Args.size() == 1 && 5268 Constructor->isSpecializationCopyingObject() && 5269 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5270 IsDerivedFrom(Args[0]->getType(), ClassType))) 5271 return; 5272 } 5273 5274 // Add this candidate 5275 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5276 Candidate.FoundDecl = FoundDecl; 5277 Candidate.Function = Function; 5278 Candidate.Viable = true; 5279 Candidate.IsSurrogate = false; 5280 Candidate.IgnoreObjectArgument = false; 5281 Candidate.ExplicitCallArguments = Args.size(); 5282 5283 unsigned NumArgsInProto = Proto->getNumArgs(); 5284 5285 // (C++ 13.3.2p2): A candidate function having fewer than m 5286 // parameters is viable only if it has an ellipsis in its parameter 5287 // list (8.3.5). 5288 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5289 !Proto->isVariadic()) { 5290 Candidate.Viable = false; 5291 Candidate.FailureKind = ovl_fail_too_many_arguments; 5292 return; 5293 } 5294 5295 // (C++ 13.3.2p2): A candidate function having more than m parameters 5296 // is viable only if the (m+1)st parameter has a default argument 5297 // (8.3.6). For the purposes of overload resolution, the 5298 // parameter list is truncated on the right, so that there are 5299 // exactly m parameters. 5300 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5301 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5302 // Not enough arguments. 5303 Candidate.Viable = false; 5304 Candidate.FailureKind = ovl_fail_too_few_arguments; 5305 return; 5306 } 5307 5308 // (CUDA B.1): Check for invalid calls between targets. 5309 if (getLangOpts().CUDA) 5310 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5311 if (CheckCUDATarget(Caller, Function)) { 5312 Candidate.Viable = false; 5313 Candidate.FailureKind = ovl_fail_bad_target; 5314 return; 5315 } 5316 5317 // Determine the implicit conversion sequences for each of the 5318 // arguments. 5319 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5320 if (ArgIdx < NumArgsInProto) { 5321 // (C++ 13.3.2p3): for F to be a viable function, there shall 5322 // exist for each argument an implicit conversion sequence 5323 // (13.3.3.1) that converts that argument to the corresponding 5324 // parameter of F. 5325 QualType ParamType = Proto->getArgType(ArgIdx); 5326 Candidate.Conversions[ArgIdx] 5327 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5328 SuppressUserConversions, 5329 /*InOverloadResolution=*/true, 5330 /*AllowObjCWritebackConversion=*/ 5331 getLangOpts().ObjCAutoRefCount, 5332 AllowExplicit); 5333 if (Candidate.Conversions[ArgIdx].isBad()) { 5334 Candidate.Viable = false; 5335 Candidate.FailureKind = ovl_fail_bad_conversion; 5336 break; 5337 } 5338 } else { 5339 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5340 // argument for which there is no corresponding parameter is 5341 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5342 Candidate.Conversions[ArgIdx].setEllipsis(); 5343 } 5344 } 5345} 5346 5347/// \brief Add all of the function declarations in the given function set to 5348/// the overload canddiate set. 5349void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5350 llvm::ArrayRef<Expr *> Args, 5351 OverloadCandidateSet& CandidateSet, 5352 bool SuppressUserConversions, 5353 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5354 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5355 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5356 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5357 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5358 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5359 cast<CXXMethodDecl>(FD)->getParent(), 5360 Args[0]->getType(), Args[0]->Classify(Context), 5361 Args.slice(1), CandidateSet, 5362 SuppressUserConversions); 5363 else 5364 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5365 SuppressUserConversions); 5366 } else { 5367 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5368 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5369 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5370 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5371 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5372 ExplicitTemplateArgs, 5373 Args[0]->getType(), 5374 Args[0]->Classify(Context), Args.slice(1), 5375 CandidateSet, SuppressUserConversions); 5376 else 5377 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5378 ExplicitTemplateArgs, Args, 5379 CandidateSet, SuppressUserConversions); 5380 } 5381 } 5382} 5383 5384/// AddMethodCandidate - Adds a named decl (which is some kind of 5385/// method) as a method candidate to the given overload set. 5386void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5387 QualType ObjectType, 5388 Expr::Classification ObjectClassification, 5389 Expr **Args, unsigned NumArgs, 5390 OverloadCandidateSet& CandidateSet, 5391 bool SuppressUserConversions) { 5392 NamedDecl *Decl = FoundDecl.getDecl(); 5393 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5394 5395 if (isa<UsingShadowDecl>(Decl)) 5396 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5397 5398 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5399 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5400 "Expected a member function template"); 5401 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5402 /*ExplicitArgs*/ 0, 5403 ObjectType, ObjectClassification, 5404 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5405 SuppressUserConversions); 5406 } else { 5407 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5408 ObjectType, ObjectClassification, 5409 llvm::makeArrayRef(Args, NumArgs), 5410 CandidateSet, SuppressUserConversions); 5411 } 5412} 5413 5414/// AddMethodCandidate - Adds the given C++ member function to the set 5415/// of candidate functions, using the given function call arguments 5416/// and the object argument (@c Object). For example, in a call 5417/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5418/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5419/// allow user-defined conversions via constructors or conversion 5420/// operators. 5421void 5422Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5423 CXXRecordDecl *ActingContext, QualType ObjectType, 5424 Expr::Classification ObjectClassification, 5425 llvm::ArrayRef<Expr *> Args, 5426 OverloadCandidateSet& CandidateSet, 5427 bool SuppressUserConversions) { 5428 const FunctionProtoType* Proto 5429 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5430 assert(Proto && "Methods without a prototype cannot be overloaded"); 5431 assert(!isa<CXXConstructorDecl>(Method) && 5432 "Use AddOverloadCandidate for constructors"); 5433 5434 if (!CandidateSet.isNewCandidate(Method)) 5435 return; 5436 5437 // Overload resolution is always an unevaluated context. 5438 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5439 5440 // Add this candidate 5441 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5442 Candidate.FoundDecl = FoundDecl; 5443 Candidate.Function = Method; 5444 Candidate.IsSurrogate = false; 5445 Candidate.IgnoreObjectArgument = false; 5446 Candidate.ExplicitCallArguments = Args.size(); 5447 5448 unsigned NumArgsInProto = Proto->getNumArgs(); 5449 5450 // (C++ 13.3.2p2): A candidate function having fewer than m 5451 // parameters is viable only if it has an ellipsis in its parameter 5452 // list (8.3.5). 5453 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5454 Candidate.Viable = false; 5455 Candidate.FailureKind = ovl_fail_too_many_arguments; 5456 return; 5457 } 5458 5459 // (C++ 13.3.2p2): A candidate function having more than m parameters 5460 // is viable only if the (m+1)st parameter has a default argument 5461 // (8.3.6). For the purposes of overload resolution, the 5462 // parameter list is truncated on the right, so that there are 5463 // exactly m parameters. 5464 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5465 if (Args.size() < MinRequiredArgs) { 5466 // Not enough arguments. 5467 Candidate.Viable = false; 5468 Candidate.FailureKind = ovl_fail_too_few_arguments; 5469 return; 5470 } 5471 5472 Candidate.Viable = true; 5473 5474 if (Method->isStatic() || ObjectType.isNull()) 5475 // The implicit object argument is ignored. 5476 Candidate.IgnoreObjectArgument = true; 5477 else { 5478 // Determine the implicit conversion sequence for the object 5479 // parameter. 5480 Candidate.Conversions[0] 5481 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5482 Method, ActingContext); 5483 if (Candidate.Conversions[0].isBad()) { 5484 Candidate.Viable = false; 5485 Candidate.FailureKind = ovl_fail_bad_conversion; 5486 return; 5487 } 5488 } 5489 5490 // Determine the implicit conversion sequences for each of the 5491 // arguments. 5492 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5493 if (ArgIdx < NumArgsInProto) { 5494 // (C++ 13.3.2p3): for F to be a viable function, there shall 5495 // exist for each argument an implicit conversion sequence 5496 // (13.3.3.1) that converts that argument to the corresponding 5497 // parameter of F. 5498 QualType ParamType = Proto->getArgType(ArgIdx); 5499 Candidate.Conversions[ArgIdx + 1] 5500 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5501 SuppressUserConversions, 5502 /*InOverloadResolution=*/true, 5503 /*AllowObjCWritebackConversion=*/ 5504 getLangOpts().ObjCAutoRefCount); 5505 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5506 Candidate.Viable = false; 5507 Candidate.FailureKind = ovl_fail_bad_conversion; 5508 break; 5509 } 5510 } else { 5511 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5512 // argument for which there is no corresponding parameter is 5513 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5514 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5515 } 5516 } 5517} 5518 5519/// \brief Add a C++ member function template as a candidate to the candidate 5520/// set, using template argument deduction to produce an appropriate member 5521/// function template specialization. 5522void 5523Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5524 DeclAccessPair FoundDecl, 5525 CXXRecordDecl *ActingContext, 5526 TemplateArgumentListInfo *ExplicitTemplateArgs, 5527 QualType ObjectType, 5528 Expr::Classification ObjectClassification, 5529 llvm::ArrayRef<Expr *> Args, 5530 OverloadCandidateSet& CandidateSet, 5531 bool SuppressUserConversions) { 5532 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5533 return; 5534 5535 // C++ [over.match.funcs]p7: 5536 // In each case where a candidate is a function template, candidate 5537 // function template specializations are generated using template argument 5538 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5539 // candidate functions in the usual way.113) A given name can refer to one 5540 // or more function templates and also to a set of overloaded non-template 5541 // functions. In such a case, the candidate functions generated from each 5542 // function template are combined with the set of non-template candidate 5543 // functions. 5544 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5545 FunctionDecl *Specialization = 0; 5546 if (TemplateDeductionResult Result 5547 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5548 Specialization, Info)) { 5549 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5550 Candidate.FoundDecl = FoundDecl; 5551 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5552 Candidate.Viable = false; 5553 Candidate.FailureKind = ovl_fail_bad_deduction; 5554 Candidate.IsSurrogate = false; 5555 Candidate.IgnoreObjectArgument = false; 5556 Candidate.ExplicitCallArguments = Args.size(); 5557 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5558 Info); 5559 return; 5560 } 5561 5562 // Add the function template specialization produced by template argument 5563 // deduction as a candidate. 5564 assert(Specialization && "Missing member function template specialization?"); 5565 assert(isa<CXXMethodDecl>(Specialization) && 5566 "Specialization is not a member function?"); 5567 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5568 ActingContext, ObjectType, ObjectClassification, Args, 5569 CandidateSet, SuppressUserConversions); 5570} 5571 5572/// \brief Add a C++ function template specialization as a candidate 5573/// in the candidate set, using template argument deduction to produce 5574/// an appropriate function template specialization. 5575void 5576Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5577 DeclAccessPair FoundDecl, 5578 TemplateArgumentListInfo *ExplicitTemplateArgs, 5579 llvm::ArrayRef<Expr *> Args, 5580 OverloadCandidateSet& CandidateSet, 5581 bool SuppressUserConversions) { 5582 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5583 return; 5584 5585 // C++ [over.match.funcs]p7: 5586 // In each case where a candidate is a function template, candidate 5587 // function template specializations are generated using template argument 5588 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5589 // candidate functions in the usual way.113) A given name can refer to one 5590 // or more function templates and also to a set of overloaded non-template 5591 // functions. In such a case, the candidate functions generated from each 5592 // function template are combined with the set of non-template candidate 5593 // functions. 5594 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5595 FunctionDecl *Specialization = 0; 5596 if (TemplateDeductionResult Result 5597 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5598 Specialization, Info)) { 5599 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5600 Candidate.FoundDecl = FoundDecl; 5601 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5602 Candidate.Viable = false; 5603 Candidate.FailureKind = ovl_fail_bad_deduction; 5604 Candidate.IsSurrogate = false; 5605 Candidate.IgnoreObjectArgument = false; 5606 Candidate.ExplicitCallArguments = Args.size(); 5607 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5608 Info); 5609 return; 5610 } 5611 5612 // Add the function template specialization produced by template argument 5613 // deduction as a candidate. 5614 assert(Specialization && "Missing function template specialization?"); 5615 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5616 SuppressUserConversions); 5617} 5618 5619/// AddConversionCandidate - Add a C++ conversion function as a 5620/// candidate in the candidate set (C++ [over.match.conv], 5621/// C++ [over.match.copy]). From is the expression we're converting from, 5622/// and ToType is the type that we're eventually trying to convert to 5623/// (which may or may not be the same type as the type that the 5624/// conversion function produces). 5625void 5626Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5627 DeclAccessPair FoundDecl, 5628 CXXRecordDecl *ActingContext, 5629 Expr *From, QualType ToType, 5630 OverloadCandidateSet& CandidateSet) { 5631 assert(!Conversion->getDescribedFunctionTemplate() && 5632 "Conversion function templates use AddTemplateConversionCandidate"); 5633 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5634 if (!CandidateSet.isNewCandidate(Conversion)) 5635 return; 5636 5637 // Overload resolution is always an unevaluated context. 5638 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5639 5640 // Add this candidate 5641 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5642 Candidate.FoundDecl = FoundDecl; 5643 Candidate.Function = Conversion; 5644 Candidate.IsSurrogate = false; 5645 Candidate.IgnoreObjectArgument = false; 5646 Candidate.FinalConversion.setAsIdentityConversion(); 5647 Candidate.FinalConversion.setFromType(ConvType); 5648 Candidate.FinalConversion.setAllToTypes(ToType); 5649 Candidate.Viable = true; 5650 Candidate.ExplicitCallArguments = 1; 5651 5652 // C++ [over.match.funcs]p4: 5653 // For conversion functions, the function is considered to be a member of 5654 // the class of the implicit implied object argument for the purpose of 5655 // defining the type of the implicit object parameter. 5656 // 5657 // Determine the implicit conversion sequence for the implicit 5658 // object parameter. 5659 QualType ImplicitParamType = From->getType(); 5660 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5661 ImplicitParamType = FromPtrType->getPointeeType(); 5662 CXXRecordDecl *ConversionContext 5663 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5664 5665 Candidate.Conversions[0] 5666 = TryObjectArgumentInitialization(*this, From->getType(), 5667 From->Classify(Context), 5668 Conversion, ConversionContext); 5669 5670 if (Candidate.Conversions[0].isBad()) { 5671 Candidate.Viable = false; 5672 Candidate.FailureKind = ovl_fail_bad_conversion; 5673 return; 5674 } 5675 5676 // We won't go through a user-define type conversion function to convert a 5677 // derived to base as such conversions are given Conversion Rank. They only 5678 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5679 QualType FromCanon 5680 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5681 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5682 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5683 Candidate.Viable = false; 5684 Candidate.FailureKind = ovl_fail_trivial_conversion; 5685 return; 5686 } 5687 5688 // To determine what the conversion from the result of calling the 5689 // conversion function to the type we're eventually trying to 5690 // convert to (ToType), we need to synthesize a call to the 5691 // conversion function and attempt copy initialization from it. This 5692 // makes sure that we get the right semantics with respect to 5693 // lvalues/rvalues and the type. Fortunately, we can allocate this 5694 // call on the stack and we don't need its arguments to be 5695 // well-formed. 5696 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5697 VK_LValue, From->getLocStart()); 5698 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5699 Context.getPointerType(Conversion->getType()), 5700 CK_FunctionToPointerDecay, 5701 &ConversionRef, VK_RValue); 5702 5703 QualType ConversionType = Conversion->getConversionType(); 5704 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5705 Candidate.Viable = false; 5706 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5707 return; 5708 } 5709 5710 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5711 5712 // Note that it is safe to allocate CallExpr on the stack here because 5713 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5714 // allocator). 5715 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5716 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK, 5717 From->getLocStart()); 5718 ImplicitConversionSequence ICS = 5719 TryCopyInitialization(*this, &Call, ToType, 5720 /*SuppressUserConversions=*/true, 5721 /*InOverloadResolution=*/false, 5722 /*AllowObjCWritebackConversion=*/false); 5723 5724 switch (ICS.getKind()) { 5725 case ImplicitConversionSequence::StandardConversion: 5726 Candidate.FinalConversion = ICS.Standard; 5727 5728 // C++ [over.ics.user]p3: 5729 // If the user-defined conversion is specified by a specialization of a 5730 // conversion function template, the second standard conversion sequence 5731 // shall have exact match rank. 5732 if (Conversion->getPrimaryTemplate() && 5733 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5734 Candidate.Viable = false; 5735 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5736 } 5737 5738 // C++0x [dcl.init.ref]p5: 5739 // In the second case, if the reference is an rvalue reference and 5740 // the second standard conversion sequence of the user-defined 5741 // conversion sequence includes an lvalue-to-rvalue conversion, the 5742 // program is ill-formed. 5743 if (ToType->isRValueReferenceType() && 5744 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5745 Candidate.Viable = false; 5746 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5747 } 5748 break; 5749 5750 case ImplicitConversionSequence::BadConversion: 5751 Candidate.Viable = false; 5752 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5753 break; 5754 5755 default: 5756 llvm_unreachable( 5757 "Can only end up with a standard conversion sequence or failure"); 5758 } 5759} 5760 5761/// \brief Adds a conversion function template specialization 5762/// candidate to the overload set, using template argument deduction 5763/// to deduce the template arguments of the conversion function 5764/// template from the type that we are converting to (C++ 5765/// [temp.deduct.conv]). 5766void 5767Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5768 DeclAccessPair FoundDecl, 5769 CXXRecordDecl *ActingDC, 5770 Expr *From, QualType ToType, 5771 OverloadCandidateSet &CandidateSet) { 5772 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5773 "Only conversion function templates permitted here"); 5774 5775 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5776 return; 5777 5778 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5779 CXXConversionDecl *Specialization = 0; 5780 if (TemplateDeductionResult Result 5781 = DeduceTemplateArguments(FunctionTemplate, ToType, 5782 Specialization, Info)) { 5783 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5784 Candidate.FoundDecl = FoundDecl; 5785 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5786 Candidate.Viable = false; 5787 Candidate.FailureKind = ovl_fail_bad_deduction; 5788 Candidate.IsSurrogate = false; 5789 Candidate.IgnoreObjectArgument = false; 5790 Candidate.ExplicitCallArguments = 1; 5791 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5792 Info); 5793 return; 5794 } 5795 5796 // Add the conversion function template specialization produced by 5797 // template argument deduction as a candidate. 5798 assert(Specialization && "Missing function template specialization?"); 5799 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5800 CandidateSet); 5801} 5802 5803/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5804/// converts the given @c Object to a function pointer via the 5805/// conversion function @c Conversion, and then attempts to call it 5806/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5807/// the type of function that we'll eventually be calling. 5808void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5809 DeclAccessPair FoundDecl, 5810 CXXRecordDecl *ActingContext, 5811 const FunctionProtoType *Proto, 5812 Expr *Object, 5813 llvm::ArrayRef<Expr *> Args, 5814 OverloadCandidateSet& CandidateSet) { 5815 if (!CandidateSet.isNewCandidate(Conversion)) 5816 return; 5817 5818 // Overload resolution is always an unevaluated context. 5819 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5820 5821 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5822 Candidate.FoundDecl = FoundDecl; 5823 Candidate.Function = 0; 5824 Candidate.Surrogate = Conversion; 5825 Candidate.Viable = true; 5826 Candidate.IsSurrogate = true; 5827 Candidate.IgnoreObjectArgument = false; 5828 Candidate.ExplicitCallArguments = Args.size(); 5829 5830 // Determine the implicit conversion sequence for the implicit 5831 // object parameter. 5832 ImplicitConversionSequence ObjectInit 5833 = TryObjectArgumentInitialization(*this, Object->getType(), 5834 Object->Classify(Context), 5835 Conversion, ActingContext); 5836 if (ObjectInit.isBad()) { 5837 Candidate.Viable = false; 5838 Candidate.FailureKind = ovl_fail_bad_conversion; 5839 Candidate.Conversions[0] = ObjectInit; 5840 return; 5841 } 5842 5843 // The first conversion is actually a user-defined conversion whose 5844 // first conversion is ObjectInit's standard conversion (which is 5845 // effectively a reference binding). Record it as such. 5846 Candidate.Conversions[0].setUserDefined(); 5847 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5848 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5849 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5850 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5851 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5852 Candidate.Conversions[0].UserDefined.After 5853 = Candidate.Conversions[0].UserDefined.Before; 5854 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5855 5856 // Find the 5857 unsigned NumArgsInProto = Proto->getNumArgs(); 5858 5859 // (C++ 13.3.2p2): A candidate function having fewer than m 5860 // parameters is viable only if it has an ellipsis in its parameter 5861 // list (8.3.5). 5862 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5863 Candidate.Viable = false; 5864 Candidate.FailureKind = ovl_fail_too_many_arguments; 5865 return; 5866 } 5867 5868 // Function types don't have any default arguments, so just check if 5869 // we have enough arguments. 5870 if (Args.size() < NumArgsInProto) { 5871 // Not enough arguments. 5872 Candidate.Viable = false; 5873 Candidate.FailureKind = ovl_fail_too_few_arguments; 5874 return; 5875 } 5876 5877 // Determine the implicit conversion sequences for each of the 5878 // arguments. 5879 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5880 if (ArgIdx < NumArgsInProto) { 5881 // (C++ 13.3.2p3): for F to be a viable function, there shall 5882 // exist for each argument an implicit conversion sequence 5883 // (13.3.3.1) that converts that argument to the corresponding 5884 // parameter of F. 5885 QualType ParamType = Proto->getArgType(ArgIdx); 5886 Candidate.Conversions[ArgIdx + 1] 5887 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5888 /*SuppressUserConversions=*/false, 5889 /*InOverloadResolution=*/false, 5890 /*AllowObjCWritebackConversion=*/ 5891 getLangOpts().ObjCAutoRefCount); 5892 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5893 Candidate.Viable = false; 5894 Candidate.FailureKind = ovl_fail_bad_conversion; 5895 break; 5896 } 5897 } else { 5898 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5899 // argument for which there is no corresponding parameter is 5900 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5901 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5902 } 5903 } 5904} 5905 5906/// \brief Add overload candidates for overloaded operators that are 5907/// member functions. 5908/// 5909/// Add the overloaded operator candidates that are member functions 5910/// for the operator Op that was used in an operator expression such 5911/// as "x Op y". , Args/NumArgs provides the operator arguments, and 5912/// CandidateSet will store the added overload candidates. (C++ 5913/// [over.match.oper]). 5914void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5915 SourceLocation OpLoc, 5916 Expr **Args, unsigned NumArgs, 5917 OverloadCandidateSet& CandidateSet, 5918 SourceRange OpRange) { 5919 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5920 5921 // C++ [over.match.oper]p3: 5922 // For a unary operator @ with an operand of a type whose 5923 // cv-unqualified version is T1, and for a binary operator @ with 5924 // a left operand of a type whose cv-unqualified version is T1 and 5925 // a right operand of a type whose cv-unqualified version is T2, 5926 // three sets of candidate functions, designated member 5927 // candidates, non-member candidates and built-in candidates, are 5928 // constructed as follows: 5929 QualType T1 = Args[0]->getType(); 5930 5931 // -- If T1 is a class type, the set of member candidates is the 5932 // result of the qualified lookup of T1::operator@ 5933 // (13.3.1.1.1); otherwise, the set of member candidates is 5934 // empty. 5935 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5936 // Complete the type if it can be completed. Otherwise, we're done. 5937 if (RequireCompleteType(OpLoc, T1, 0)) 5938 return; 5939 5940 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5941 LookupQualifiedName(Operators, T1Rec->getDecl()); 5942 Operators.suppressDiagnostics(); 5943 5944 for (LookupResult::iterator Oper = Operators.begin(), 5945 OperEnd = Operators.end(); 5946 Oper != OperEnd; 5947 ++Oper) 5948 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5949 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5950 CandidateSet, 5951 /* SuppressUserConversions = */ false); 5952 } 5953} 5954 5955/// AddBuiltinCandidate - Add a candidate for a built-in 5956/// operator. ResultTy and ParamTys are the result and parameter types 5957/// of the built-in candidate, respectively. Args and NumArgs are the 5958/// arguments being passed to the candidate. IsAssignmentOperator 5959/// should be true when this built-in candidate is an assignment 5960/// operator. NumContextualBoolArguments is the number of arguments 5961/// (at the beginning of the argument list) that will be contextually 5962/// converted to bool. 5963void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5964 Expr **Args, unsigned NumArgs, 5965 OverloadCandidateSet& CandidateSet, 5966 bool IsAssignmentOperator, 5967 unsigned NumContextualBoolArguments) { 5968 // Overload resolution is always an unevaluated context. 5969 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5970 5971 // Add this candidate 5972 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5973 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5974 Candidate.Function = 0; 5975 Candidate.IsSurrogate = false; 5976 Candidate.IgnoreObjectArgument = false; 5977 Candidate.BuiltinTypes.ResultTy = ResultTy; 5978 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5979 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5980 5981 // Determine the implicit conversion sequences for each of the 5982 // arguments. 5983 Candidate.Viable = true; 5984 Candidate.ExplicitCallArguments = NumArgs; 5985 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5986 // C++ [over.match.oper]p4: 5987 // For the built-in assignment operators, conversions of the 5988 // left operand are restricted as follows: 5989 // -- no temporaries are introduced to hold the left operand, and 5990 // -- no user-defined conversions are applied to the left 5991 // operand to achieve a type match with the left-most 5992 // parameter of a built-in candidate. 5993 // 5994 // We block these conversions by turning off user-defined 5995 // conversions, since that is the only way that initialization of 5996 // a reference to a non-class type can occur from something that 5997 // is not of the same type. 5998 if (ArgIdx < NumContextualBoolArguments) { 5999 assert(ParamTys[ArgIdx] == Context.BoolTy && 6000 "Contextual conversion to bool requires bool type"); 6001 Candidate.Conversions[ArgIdx] 6002 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6003 } else { 6004 Candidate.Conversions[ArgIdx] 6005 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6006 ArgIdx == 0 && IsAssignmentOperator, 6007 /*InOverloadResolution=*/false, 6008 /*AllowObjCWritebackConversion=*/ 6009 getLangOpts().ObjCAutoRefCount); 6010 } 6011 if (Candidate.Conversions[ArgIdx].isBad()) { 6012 Candidate.Viable = false; 6013 Candidate.FailureKind = ovl_fail_bad_conversion; 6014 break; 6015 } 6016 } 6017} 6018 6019/// BuiltinCandidateTypeSet - A set of types that will be used for the 6020/// candidate operator functions for built-in operators (C++ 6021/// [over.built]). The types are separated into pointer types and 6022/// enumeration types. 6023class BuiltinCandidateTypeSet { 6024 /// TypeSet - A set of types. 6025 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6026 6027 /// PointerTypes - The set of pointer types that will be used in the 6028 /// built-in candidates. 6029 TypeSet PointerTypes; 6030 6031 /// MemberPointerTypes - The set of member pointer types that will be 6032 /// used in the built-in candidates. 6033 TypeSet MemberPointerTypes; 6034 6035 /// EnumerationTypes - The set of enumeration types that will be 6036 /// used in the built-in candidates. 6037 TypeSet EnumerationTypes; 6038 6039 /// \brief The set of vector types that will be used in the built-in 6040 /// candidates. 6041 TypeSet VectorTypes; 6042 6043 /// \brief A flag indicating non-record types are viable candidates 6044 bool HasNonRecordTypes; 6045 6046 /// \brief A flag indicating whether either arithmetic or enumeration types 6047 /// were present in the candidate set. 6048 bool HasArithmeticOrEnumeralTypes; 6049 6050 /// \brief A flag indicating whether the nullptr type was present in the 6051 /// candidate set. 6052 bool HasNullPtrType; 6053 6054 /// Sema - The semantic analysis instance where we are building the 6055 /// candidate type set. 6056 Sema &SemaRef; 6057 6058 /// Context - The AST context in which we will build the type sets. 6059 ASTContext &Context; 6060 6061 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6062 const Qualifiers &VisibleQuals); 6063 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6064 6065public: 6066 /// iterator - Iterates through the types that are part of the set. 6067 typedef TypeSet::iterator iterator; 6068 6069 BuiltinCandidateTypeSet(Sema &SemaRef) 6070 : HasNonRecordTypes(false), 6071 HasArithmeticOrEnumeralTypes(false), 6072 HasNullPtrType(false), 6073 SemaRef(SemaRef), 6074 Context(SemaRef.Context) { } 6075 6076 void AddTypesConvertedFrom(QualType Ty, 6077 SourceLocation Loc, 6078 bool AllowUserConversions, 6079 bool AllowExplicitConversions, 6080 const Qualifiers &VisibleTypeConversionsQuals); 6081 6082 /// pointer_begin - First pointer type found; 6083 iterator pointer_begin() { return PointerTypes.begin(); } 6084 6085 /// pointer_end - Past the last pointer type found; 6086 iterator pointer_end() { return PointerTypes.end(); } 6087 6088 /// member_pointer_begin - First member pointer type found; 6089 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6090 6091 /// member_pointer_end - Past the last member pointer type found; 6092 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6093 6094 /// enumeration_begin - First enumeration type found; 6095 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6096 6097 /// enumeration_end - Past the last enumeration type found; 6098 iterator enumeration_end() { return EnumerationTypes.end(); } 6099 6100 iterator vector_begin() { return VectorTypes.begin(); } 6101 iterator vector_end() { return VectorTypes.end(); } 6102 6103 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6104 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6105 bool hasNullPtrType() const { return HasNullPtrType; } 6106}; 6107 6108/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6109/// the set of pointer types along with any more-qualified variants of 6110/// that type. For example, if @p Ty is "int const *", this routine 6111/// will add "int const *", "int const volatile *", "int const 6112/// restrict *", and "int const volatile restrict *" to the set of 6113/// pointer types. Returns true if the add of @p Ty itself succeeded, 6114/// false otherwise. 6115/// 6116/// FIXME: what to do about extended qualifiers? 6117bool 6118BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6119 const Qualifiers &VisibleQuals) { 6120 6121 // Insert this type. 6122 if (!PointerTypes.insert(Ty)) 6123 return false; 6124 6125 QualType PointeeTy; 6126 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6127 bool buildObjCPtr = false; 6128 if (!PointerTy) { 6129 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6130 PointeeTy = PTy->getPointeeType(); 6131 buildObjCPtr = true; 6132 } else { 6133 PointeeTy = PointerTy->getPointeeType(); 6134 } 6135 6136 // Don't add qualified variants of arrays. For one, they're not allowed 6137 // (the qualifier would sink to the element type), and for another, the 6138 // only overload situation where it matters is subscript or pointer +- int, 6139 // and those shouldn't have qualifier variants anyway. 6140 if (PointeeTy->isArrayType()) 6141 return true; 6142 6143 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6144 bool hasVolatile = VisibleQuals.hasVolatile(); 6145 bool hasRestrict = VisibleQuals.hasRestrict(); 6146 6147 // Iterate through all strict supersets of BaseCVR. 6148 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6149 if ((CVR | BaseCVR) != CVR) continue; 6150 // Skip over volatile if no volatile found anywhere in the types. 6151 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6152 6153 // Skip over restrict if no restrict found anywhere in the types, or if 6154 // the type cannot be restrict-qualified. 6155 if ((CVR & Qualifiers::Restrict) && 6156 (!hasRestrict || 6157 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6158 continue; 6159 6160 // Build qualified pointee type. 6161 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6162 6163 // Build qualified pointer type. 6164 QualType QPointerTy; 6165 if (!buildObjCPtr) 6166 QPointerTy = Context.getPointerType(QPointeeTy); 6167 else 6168 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6169 6170 // Insert qualified pointer type. 6171 PointerTypes.insert(QPointerTy); 6172 } 6173 6174 return true; 6175} 6176 6177/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6178/// to the set of pointer types along with any more-qualified variants of 6179/// that type. For example, if @p Ty is "int const *", this routine 6180/// will add "int const *", "int const volatile *", "int const 6181/// restrict *", and "int const volatile restrict *" to the set of 6182/// pointer types. Returns true if the add of @p Ty itself succeeded, 6183/// false otherwise. 6184/// 6185/// FIXME: what to do about extended qualifiers? 6186bool 6187BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6188 QualType Ty) { 6189 // Insert this type. 6190 if (!MemberPointerTypes.insert(Ty)) 6191 return false; 6192 6193 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6194 assert(PointerTy && "type was not a member pointer type!"); 6195 6196 QualType PointeeTy = PointerTy->getPointeeType(); 6197 // Don't add qualified variants of arrays. For one, they're not allowed 6198 // (the qualifier would sink to the element type), and for another, the 6199 // only overload situation where it matters is subscript or pointer +- int, 6200 // and those shouldn't have qualifier variants anyway. 6201 if (PointeeTy->isArrayType()) 6202 return true; 6203 const Type *ClassTy = PointerTy->getClass(); 6204 6205 // Iterate through all strict supersets of the pointee type's CVR 6206 // qualifiers. 6207 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6208 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6209 if ((CVR | BaseCVR) != CVR) continue; 6210 6211 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6212 MemberPointerTypes.insert( 6213 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6214 } 6215 6216 return true; 6217} 6218 6219/// AddTypesConvertedFrom - Add each of the types to which the type @p 6220/// Ty can be implicit converted to the given set of @p Types. We're 6221/// primarily interested in pointer types and enumeration types. We also 6222/// take member pointer types, for the conditional operator. 6223/// AllowUserConversions is true if we should look at the conversion 6224/// functions of a class type, and AllowExplicitConversions if we 6225/// should also include the explicit conversion functions of a class 6226/// type. 6227void 6228BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6229 SourceLocation Loc, 6230 bool AllowUserConversions, 6231 bool AllowExplicitConversions, 6232 const Qualifiers &VisibleQuals) { 6233 // Only deal with canonical types. 6234 Ty = Context.getCanonicalType(Ty); 6235 6236 // Look through reference types; they aren't part of the type of an 6237 // expression for the purposes of conversions. 6238 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6239 Ty = RefTy->getPointeeType(); 6240 6241 // If we're dealing with an array type, decay to the pointer. 6242 if (Ty->isArrayType()) 6243 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6244 6245 // Otherwise, we don't care about qualifiers on the type. 6246 Ty = Ty.getLocalUnqualifiedType(); 6247 6248 // Flag if we ever add a non-record type. 6249 const RecordType *TyRec = Ty->getAs<RecordType>(); 6250 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6251 6252 // Flag if we encounter an arithmetic type. 6253 HasArithmeticOrEnumeralTypes = 6254 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6255 6256 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6257 PointerTypes.insert(Ty); 6258 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6259 // Insert our type, and its more-qualified variants, into the set 6260 // of types. 6261 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6262 return; 6263 } else if (Ty->isMemberPointerType()) { 6264 // Member pointers are far easier, since the pointee can't be converted. 6265 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6266 return; 6267 } else if (Ty->isEnumeralType()) { 6268 HasArithmeticOrEnumeralTypes = true; 6269 EnumerationTypes.insert(Ty); 6270 } else if (Ty->isVectorType()) { 6271 // We treat vector types as arithmetic types in many contexts as an 6272 // extension. 6273 HasArithmeticOrEnumeralTypes = true; 6274 VectorTypes.insert(Ty); 6275 } else if (Ty->isNullPtrType()) { 6276 HasNullPtrType = true; 6277 } else if (AllowUserConversions && TyRec) { 6278 // No conversion functions in incomplete types. 6279 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6280 return; 6281 6282 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6283 const UnresolvedSetImpl *Conversions 6284 = ClassDecl->getVisibleConversionFunctions(); 6285 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6286 E = Conversions->end(); I != E; ++I) { 6287 NamedDecl *D = I.getDecl(); 6288 if (isa<UsingShadowDecl>(D)) 6289 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6290 6291 // Skip conversion function templates; they don't tell us anything 6292 // about which builtin types we can convert to. 6293 if (isa<FunctionTemplateDecl>(D)) 6294 continue; 6295 6296 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6297 if (AllowExplicitConversions || !Conv->isExplicit()) { 6298 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6299 VisibleQuals); 6300 } 6301 } 6302 } 6303} 6304 6305/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6306/// the volatile- and non-volatile-qualified assignment operators for the 6307/// given type to the candidate set. 6308static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6309 QualType T, 6310 Expr **Args, 6311 unsigned NumArgs, 6312 OverloadCandidateSet &CandidateSet) { 6313 QualType ParamTypes[2]; 6314 6315 // T& operator=(T&, T) 6316 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6317 ParamTypes[1] = T; 6318 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6319 /*IsAssignmentOperator=*/true); 6320 6321 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6322 // volatile T& operator=(volatile T&, T) 6323 ParamTypes[0] 6324 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6325 ParamTypes[1] = T; 6326 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6327 /*IsAssignmentOperator=*/true); 6328 } 6329} 6330 6331/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6332/// if any, found in visible type conversion functions found in ArgExpr's type. 6333static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6334 Qualifiers VRQuals; 6335 const RecordType *TyRec; 6336 if (const MemberPointerType *RHSMPType = 6337 ArgExpr->getType()->getAs<MemberPointerType>()) 6338 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6339 else 6340 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6341 if (!TyRec) { 6342 // Just to be safe, assume the worst case. 6343 VRQuals.addVolatile(); 6344 VRQuals.addRestrict(); 6345 return VRQuals; 6346 } 6347 6348 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6349 if (!ClassDecl->hasDefinition()) 6350 return VRQuals; 6351 6352 const UnresolvedSetImpl *Conversions = 6353 ClassDecl->getVisibleConversionFunctions(); 6354 6355 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6356 E = Conversions->end(); I != E; ++I) { 6357 NamedDecl *D = I.getDecl(); 6358 if (isa<UsingShadowDecl>(D)) 6359 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6360 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6361 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6362 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6363 CanTy = ResTypeRef->getPointeeType(); 6364 // Need to go down the pointer/mempointer chain and add qualifiers 6365 // as see them. 6366 bool done = false; 6367 while (!done) { 6368 if (CanTy.isRestrictQualified()) 6369 VRQuals.addRestrict(); 6370 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6371 CanTy = ResTypePtr->getPointeeType(); 6372 else if (const MemberPointerType *ResTypeMPtr = 6373 CanTy->getAs<MemberPointerType>()) 6374 CanTy = ResTypeMPtr->getPointeeType(); 6375 else 6376 done = true; 6377 if (CanTy.isVolatileQualified()) 6378 VRQuals.addVolatile(); 6379 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6380 return VRQuals; 6381 } 6382 } 6383 } 6384 return VRQuals; 6385} 6386 6387namespace { 6388 6389/// \brief Helper class to manage the addition of builtin operator overload 6390/// candidates. It provides shared state and utility methods used throughout 6391/// the process, as well as a helper method to add each group of builtin 6392/// operator overloads from the standard to a candidate set. 6393class BuiltinOperatorOverloadBuilder { 6394 // Common instance state available to all overload candidate addition methods. 6395 Sema &S; 6396 Expr **Args; 6397 unsigned NumArgs; 6398 Qualifiers VisibleTypeConversionsQuals; 6399 bool HasArithmeticOrEnumeralCandidateType; 6400 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6401 OverloadCandidateSet &CandidateSet; 6402 6403 // Define some constants used to index and iterate over the arithemetic types 6404 // provided via the getArithmeticType() method below. 6405 // The "promoted arithmetic types" are the arithmetic 6406 // types are that preserved by promotion (C++ [over.built]p2). 6407 static const unsigned FirstIntegralType = 3; 6408 static const unsigned LastIntegralType = 20; 6409 static const unsigned FirstPromotedIntegralType = 3, 6410 LastPromotedIntegralType = 11; 6411 static const unsigned FirstPromotedArithmeticType = 0, 6412 LastPromotedArithmeticType = 11; 6413 static const unsigned NumArithmeticTypes = 20; 6414 6415 /// \brief Get the canonical type for a given arithmetic type index. 6416 CanQualType getArithmeticType(unsigned index) { 6417 assert(index < NumArithmeticTypes); 6418 static CanQualType ASTContext::* const 6419 ArithmeticTypes[NumArithmeticTypes] = { 6420 // Start of promoted types. 6421 &ASTContext::FloatTy, 6422 &ASTContext::DoubleTy, 6423 &ASTContext::LongDoubleTy, 6424 6425 // Start of integral types. 6426 &ASTContext::IntTy, 6427 &ASTContext::LongTy, 6428 &ASTContext::LongLongTy, 6429 &ASTContext::Int128Ty, 6430 &ASTContext::UnsignedIntTy, 6431 &ASTContext::UnsignedLongTy, 6432 &ASTContext::UnsignedLongLongTy, 6433 &ASTContext::UnsignedInt128Ty, 6434 // End of promoted types. 6435 6436 &ASTContext::BoolTy, 6437 &ASTContext::CharTy, 6438 &ASTContext::WCharTy, 6439 &ASTContext::Char16Ty, 6440 &ASTContext::Char32Ty, 6441 &ASTContext::SignedCharTy, 6442 &ASTContext::ShortTy, 6443 &ASTContext::UnsignedCharTy, 6444 &ASTContext::UnsignedShortTy, 6445 // End of integral types. 6446 // FIXME: What about complex? What about half? 6447 }; 6448 return S.Context.*ArithmeticTypes[index]; 6449 } 6450 6451 /// \brief Gets the canonical type resulting from the usual arithemetic 6452 /// converions for the given arithmetic types. 6453 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6454 // Accelerator table for performing the usual arithmetic conversions. 6455 // The rules are basically: 6456 // - if either is floating-point, use the wider floating-point 6457 // - if same signedness, use the higher rank 6458 // - if same size, use unsigned of the higher rank 6459 // - use the larger type 6460 // These rules, together with the axiom that higher ranks are 6461 // never smaller, are sufficient to precompute all of these results 6462 // *except* when dealing with signed types of higher rank. 6463 // (we could precompute SLL x UI for all known platforms, but it's 6464 // better not to make any assumptions). 6465 // We assume that int128 has a higher rank than long long on all platforms. 6466 enum PromotedType { 6467 Dep=-1, 6468 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6469 }; 6470 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6471 [LastPromotedArithmeticType] = { 6472/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6473/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6474/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6475/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6476/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6477/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6478/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6479/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6480/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6481/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6482/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6483 }; 6484 6485 assert(L < LastPromotedArithmeticType); 6486 assert(R < LastPromotedArithmeticType); 6487 int Idx = ConversionsTable[L][R]; 6488 6489 // Fast path: the table gives us a concrete answer. 6490 if (Idx != Dep) return getArithmeticType(Idx); 6491 6492 // Slow path: we need to compare widths. 6493 // An invariant is that the signed type has higher rank. 6494 CanQualType LT = getArithmeticType(L), 6495 RT = getArithmeticType(R); 6496 unsigned LW = S.Context.getIntWidth(LT), 6497 RW = S.Context.getIntWidth(RT); 6498 6499 // If they're different widths, use the signed type. 6500 if (LW > RW) return LT; 6501 else if (LW < RW) return RT; 6502 6503 // Otherwise, use the unsigned type of the signed type's rank. 6504 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6505 assert(L == SLL || R == SLL); 6506 return S.Context.UnsignedLongLongTy; 6507 } 6508 6509 /// \brief Helper method to factor out the common pattern of adding overloads 6510 /// for '++' and '--' builtin operators. 6511 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6512 bool HasVolatile, 6513 bool HasRestrict) { 6514 QualType ParamTypes[2] = { 6515 S.Context.getLValueReferenceType(CandidateTy), 6516 S.Context.IntTy 6517 }; 6518 6519 // Non-volatile version. 6520 if (NumArgs == 1) 6521 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6522 else 6523 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6524 6525 // Use a heuristic to reduce number of builtin candidates in the set: 6526 // add volatile version only if there are conversions to a volatile type. 6527 if (HasVolatile) { 6528 ParamTypes[0] = 6529 S.Context.getLValueReferenceType( 6530 S.Context.getVolatileType(CandidateTy)); 6531 if (NumArgs == 1) 6532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6533 else 6534 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6535 } 6536 6537 // Add restrict version only if there are conversions to a restrict type 6538 // and our candidate type is a non-restrict-qualified pointer. 6539 if (HasRestrict && CandidateTy->isAnyPointerType() && 6540 !CandidateTy.isRestrictQualified()) { 6541 ParamTypes[0] 6542 = S.Context.getLValueReferenceType( 6543 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6544 if (NumArgs == 1) 6545 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6546 else 6547 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6548 6549 if (HasVolatile) { 6550 ParamTypes[0] 6551 = S.Context.getLValueReferenceType( 6552 S.Context.getCVRQualifiedType(CandidateTy, 6553 (Qualifiers::Volatile | 6554 Qualifiers::Restrict))); 6555 if (NumArgs == 1) 6556 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6557 CandidateSet); 6558 else 6559 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6560 } 6561 } 6562 6563 } 6564 6565public: 6566 BuiltinOperatorOverloadBuilder( 6567 Sema &S, Expr **Args, unsigned NumArgs, 6568 Qualifiers VisibleTypeConversionsQuals, 6569 bool HasArithmeticOrEnumeralCandidateType, 6570 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6571 OverloadCandidateSet &CandidateSet) 6572 : S(S), Args(Args), NumArgs(NumArgs), 6573 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6574 HasArithmeticOrEnumeralCandidateType( 6575 HasArithmeticOrEnumeralCandidateType), 6576 CandidateTypes(CandidateTypes), 6577 CandidateSet(CandidateSet) { 6578 // Validate some of our static helper constants in debug builds. 6579 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6580 "Invalid first promoted integral type"); 6581 assert(getArithmeticType(LastPromotedIntegralType - 1) 6582 == S.Context.UnsignedInt128Ty && 6583 "Invalid last promoted integral type"); 6584 assert(getArithmeticType(FirstPromotedArithmeticType) 6585 == S.Context.FloatTy && 6586 "Invalid first promoted arithmetic type"); 6587 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6588 == S.Context.UnsignedInt128Ty && 6589 "Invalid last promoted arithmetic type"); 6590 } 6591 6592 // C++ [over.built]p3: 6593 // 6594 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6595 // is either volatile or empty, there exist candidate operator 6596 // functions of the form 6597 // 6598 // VQ T& operator++(VQ T&); 6599 // T operator++(VQ T&, int); 6600 // 6601 // C++ [over.built]p4: 6602 // 6603 // For every pair (T, VQ), where T is an arithmetic type other 6604 // than bool, and VQ is either volatile or empty, there exist 6605 // candidate operator functions of the form 6606 // 6607 // VQ T& operator--(VQ T&); 6608 // T operator--(VQ T&, int); 6609 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6610 if (!HasArithmeticOrEnumeralCandidateType) 6611 return; 6612 6613 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6614 Arith < NumArithmeticTypes; ++Arith) { 6615 addPlusPlusMinusMinusStyleOverloads( 6616 getArithmeticType(Arith), 6617 VisibleTypeConversionsQuals.hasVolatile(), 6618 VisibleTypeConversionsQuals.hasRestrict()); 6619 } 6620 } 6621 6622 // C++ [over.built]p5: 6623 // 6624 // For every pair (T, VQ), where T is a cv-qualified or 6625 // cv-unqualified object type, and VQ is either volatile or 6626 // empty, there exist candidate operator functions of the form 6627 // 6628 // T*VQ& operator++(T*VQ&); 6629 // T*VQ& operator--(T*VQ&); 6630 // T* operator++(T*VQ&, int); 6631 // T* operator--(T*VQ&, int); 6632 void addPlusPlusMinusMinusPointerOverloads() { 6633 for (BuiltinCandidateTypeSet::iterator 6634 Ptr = CandidateTypes[0].pointer_begin(), 6635 PtrEnd = CandidateTypes[0].pointer_end(); 6636 Ptr != PtrEnd; ++Ptr) { 6637 // Skip pointer types that aren't pointers to object types. 6638 if (!(*Ptr)->getPointeeType()->isObjectType()) 6639 continue; 6640 6641 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6642 (!(*Ptr).isVolatileQualified() && 6643 VisibleTypeConversionsQuals.hasVolatile()), 6644 (!(*Ptr).isRestrictQualified() && 6645 VisibleTypeConversionsQuals.hasRestrict())); 6646 } 6647 } 6648 6649 // C++ [over.built]p6: 6650 // For every cv-qualified or cv-unqualified object type T, there 6651 // exist candidate operator functions of the form 6652 // 6653 // T& operator*(T*); 6654 // 6655 // C++ [over.built]p7: 6656 // For every function type T that does not have cv-qualifiers or a 6657 // ref-qualifier, there exist candidate operator functions of the form 6658 // T& operator*(T*); 6659 void addUnaryStarPointerOverloads() { 6660 for (BuiltinCandidateTypeSet::iterator 6661 Ptr = CandidateTypes[0].pointer_begin(), 6662 PtrEnd = CandidateTypes[0].pointer_end(); 6663 Ptr != PtrEnd; ++Ptr) { 6664 QualType ParamTy = *Ptr; 6665 QualType PointeeTy = ParamTy->getPointeeType(); 6666 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6667 continue; 6668 6669 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6670 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6671 continue; 6672 6673 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6674 &ParamTy, Args, 1, CandidateSet); 6675 } 6676 } 6677 6678 // C++ [over.built]p9: 6679 // For every promoted arithmetic type T, there exist candidate 6680 // operator functions of the form 6681 // 6682 // T operator+(T); 6683 // T operator-(T); 6684 void addUnaryPlusOrMinusArithmeticOverloads() { 6685 if (!HasArithmeticOrEnumeralCandidateType) 6686 return; 6687 6688 for (unsigned Arith = FirstPromotedArithmeticType; 6689 Arith < LastPromotedArithmeticType; ++Arith) { 6690 QualType ArithTy = getArithmeticType(Arith); 6691 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6692 } 6693 6694 // Extension: We also add these operators for vector types. 6695 for (BuiltinCandidateTypeSet::iterator 6696 Vec = CandidateTypes[0].vector_begin(), 6697 VecEnd = CandidateTypes[0].vector_end(); 6698 Vec != VecEnd; ++Vec) { 6699 QualType VecTy = *Vec; 6700 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6701 } 6702 } 6703 6704 // C++ [over.built]p8: 6705 // For every type T, there exist candidate operator functions of 6706 // the form 6707 // 6708 // T* operator+(T*); 6709 void addUnaryPlusPointerOverloads() { 6710 for (BuiltinCandidateTypeSet::iterator 6711 Ptr = CandidateTypes[0].pointer_begin(), 6712 PtrEnd = CandidateTypes[0].pointer_end(); 6713 Ptr != PtrEnd; ++Ptr) { 6714 QualType ParamTy = *Ptr; 6715 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6716 } 6717 } 6718 6719 // C++ [over.built]p10: 6720 // For every promoted integral type T, there exist candidate 6721 // operator functions of the form 6722 // 6723 // T operator~(T); 6724 void addUnaryTildePromotedIntegralOverloads() { 6725 if (!HasArithmeticOrEnumeralCandidateType) 6726 return; 6727 6728 for (unsigned Int = FirstPromotedIntegralType; 6729 Int < LastPromotedIntegralType; ++Int) { 6730 QualType IntTy = getArithmeticType(Int); 6731 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6732 } 6733 6734 // Extension: We also add this operator for vector types. 6735 for (BuiltinCandidateTypeSet::iterator 6736 Vec = CandidateTypes[0].vector_begin(), 6737 VecEnd = CandidateTypes[0].vector_end(); 6738 Vec != VecEnd; ++Vec) { 6739 QualType VecTy = *Vec; 6740 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6741 } 6742 } 6743 6744 // C++ [over.match.oper]p16: 6745 // For every pointer to member type T, there exist candidate operator 6746 // functions of the form 6747 // 6748 // bool operator==(T,T); 6749 // bool operator!=(T,T); 6750 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6751 /// Set of (canonical) types that we've already handled. 6752 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6753 6754 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6755 for (BuiltinCandidateTypeSet::iterator 6756 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6757 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6758 MemPtr != MemPtrEnd; 6759 ++MemPtr) { 6760 // Don't add the same builtin candidate twice. 6761 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6762 continue; 6763 6764 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6765 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6766 CandidateSet); 6767 } 6768 } 6769 } 6770 6771 // C++ [over.built]p15: 6772 // 6773 // For every T, where T is an enumeration type, a pointer type, or 6774 // std::nullptr_t, there exist candidate operator functions of the form 6775 // 6776 // bool operator<(T, T); 6777 // bool operator>(T, T); 6778 // bool operator<=(T, T); 6779 // bool operator>=(T, T); 6780 // bool operator==(T, T); 6781 // bool operator!=(T, T); 6782 void addRelationalPointerOrEnumeralOverloads() { 6783 // C++ [over.built]p1: 6784 // If there is a user-written candidate with the same name and parameter 6785 // types as a built-in candidate operator function, the built-in operator 6786 // function is hidden and is not included in the set of candidate 6787 // functions. 6788 // 6789 // The text is actually in a note, but if we don't implement it then we end 6790 // up with ambiguities when the user provides an overloaded operator for 6791 // an enumeration type. Note that only enumeration types have this problem, 6792 // so we track which enumeration types we've seen operators for. Also, the 6793 // only other overloaded operator with enumeration argumenst, operator=, 6794 // cannot be overloaded for enumeration types, so this is the only place 6795 // where we must suppress candidates like this. 6796 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6797 UserDefinedBinaryOperators; 6798 6799 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6800 if (CandidateTypes[ArgIdx].enumeration_begin() != 6801 CandidateTypes[ArgIdx].enumeration_end()) { 6802 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6803 CEnd = CandidateSet.end(); 6804 C != CEnd; ++C) { 6805 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6806 continue; 6807 6808 QualType FirstParamType = 6809 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6810 QualType SecondParamType = 6811 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6812 6813 // Skip if either parameter isn't of enumeral type. 6814 if (!FirstParamType->isEnumeralType() || 6815 !SecondParamType->isEnumeralType()) 6816 continue; 6817 6818 // Add this operator to the set of known user-defined operators. 6819 UserDefinedBinaryOperators.insert( 6820 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6821 S.Context.getCanonicalType(SecondParamType))); 6822 } 6823 } 6824 } 6825 6826 /// Set of (canonical) types that we've already handled. 6827 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6828 6829 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6830 for (BuiltinCandidateTypeSet::iterator 6831 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6832 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6833 Ptr != PtrEnd; ++Ptr) { 6834 // Don't add the same builtin candidate twice. 6835 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6836 continue; 6837 6838 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6839 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6840 CandidateSet); 6841 } 6842 for (BuiltinCandidateTypeSet::iterator 6843 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6844 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6845 Enum != EnumEnd; ++Enum) { 6846 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6847 6848 // Don't add the same builtin candidate twice, or if a user defined 6849 // candidate exists. 6850 if (!AddedTypes.insert(CanonType) || 6851 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6852 CanonType))) 6853 continue; 6854 6855 QualType ParamTypes[2] = { *Enum, *Enum }; 6856 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6857 CandidateSet); 6858 } 6859 6860 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6861 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6862 if (AddedTypes.insert(NullPtrTy) && 6863 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6864 NullPtrTy))) { 6865 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6866 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6867 CandidateSet); 6868 } 6869 } 6870 } 6871 } 6872 6873 // C++ [over.built]p13: 6874 // 6875 // For every cv-qualified or cv-unqualified object type T 6876 // there exist candidate operator functions of the form 6877 // 6878 // T* operator+(T*, ptrdiff_t); 6879 // T& operator[](T*, ptrdiff_t); [BELOW] 6880 // T* operator-(T*, ptrdiff_t); 6881 // T* operator+(ptrdiff_t, T*); 6882 // T& operator[](ptrdiff_t, T*); [BELOW] 6883 // 6884 // C++ [over.built]p14: 6885 // 6886 // For every T, where T is a pointer to object type, there 6887 // exist candidate operator functions of the form 6888 // 6889 // ptrdiff_t operator-(T, T); 6890 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6891 /// Set of (canonical) types that we've already handled. 6892 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6893 6894 for (int Arg = 0; Arg < 2; ++Arg) { 6895 QualType AsymetricParamTypes[2] = { 6896 S.Context.getPointerDiffType(), 6897 S.Context.getPointerDiffType(), 6898 }; 6899 for (BuiltinCandidateTypeSet::iterator 6900 Ptr = CandidateTypes[Arg].pointer_begin(), 6901 PtrEnd = CandidateTypes[Arg].pointer_end(); 6902 Ptr != PtrEnd; ++Ptr) { 6903 QualType PointeeTy = (*Ptr)->getPointeeType(); 6904 if (!PointeeTy->isObjectType()) 6905 continue; 6906 6907 AsymetricParamTypes[Arg] = *Ptr; 6908 if (Arg == 0 || Op == OO_Plus) { 6909 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6910 // T* operator+(ptrdiff_t, T*); 6911 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6912 CandidateSet); 6913 } 6914 if (Op == OO_Minus) { 6915 // ptrdiff_t operator-(T, T); 6916 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6917 continue; 6918 6919 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6920 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6921 Args, 2, CandidateSet); 6922 } 6923 } 6924 } 6925 } 6926 6927 // C++ [over.built]p12: 6928 // 6929 // For every pair of promoted arithmetic types L and R, there 6930 // exist candidate operator functions of the form 6931 // 6932 // LR operator*(L, R); 6933 // LR operator/(L, R); 6934 // LR operator+(L, R); 6935 // LR operator-(L, R); 6936 // bool operator<(L, R); 6937 // bool operator>(L, R); 6938 // bool operator<=(L, R); 6939 // bool operator>=(L, R); 6940 // bool operator==(L, R); 6941 // bool operator!=(L, R); 6942 // 6943 // where LR is the result of the usual arithmetic conversions 6944 // between types L and R. 6945 // 6946 // C++ [over.built]p24: 6947 // 6948 // For every pair of promoted arithmetic types L and R, there exist 6949 // candidate operator functions of the form 6950 // 6951 // LR operator?(bool, L, R); 6952 // 6953 // where LR is the result of the usual arithmetic conversions 6954 // between types L and R. 6955 // Our candidates ignore the first parameter. 6956 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6957 if (!HasArithmeticOrEnumeralCandidateType) 6958 return; 6959 6960 for (unsigned Left = FirstPromotedArithmeticType; 6961 Left < LastPromotedArithmeticType; ++Left) { 6962 for (unsigned Right = FirstPromotedArithmeticType; 6963 Right < LastPromotedArithmeticType; ++Right) { 6964 QualType LandR[2] = { getArithmeticType(Left), 6965 getArithmeticType(Right) }; 6966 QualType Result = 6967 isComparison ? S.Context.BoolTy 6968 : getUsualArithmeticConversions(Left, Right); 6969 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6970 } 6971 } 6972 6973 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6974 // conditional operator for vector types. 6975 for (BuiltinCandidateTypeSet::iterator 6976 Vec1 = CandidateTypes[0].vector_begin(), 6977 Vec1End = CandidateTypes[0].vector_end(); 6978 Vec1 != Vec1End; ++Vec1) { 6979 for (BuiltinCandidateTypeSet::iterator 6980 Vec2 = CandidateTypes[1].vector_begin(), 6981 Vec2End = CandidateTypes[1].vector_end(); 6982 Vec2 != Vec2End; ++Vec2) { 6983 QualType LandR[2] = { *Vec1, *Vec2 }; 6984 QualType Result = S.Context.BoolTy; 6985 if (!isComparison) { 6986 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 6987 Result = *Vec1; 6988 else 6989 Result = *Vec2; 6990 } 6991 6992 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6993 } 6994 } 6995 } 6996 6997 // C++ [over.built]p17: 6998 // 6999 // For every pair of promoted integral types L and R, there 7000 // exist candidate operator functions of the form 7001 // 7002 // LR operator%(L, R); 7003 // LR operator&(L, R); 7004 // LR operator^(L, R); 7005 // LR operator|(L, R); 7006 // L operator<<(L, R); 7007 // L operator>>(L, R); 7008 // 7009 // where LR is the result of the usual arithmetic conversions 7010 // between types L and R. 7011 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7012 if (!HasArithmeticOrEnumeralCandidateType) 7013 return; 7014 7015 for (unsigned Left = FirstPromotedIntegralType; 7016 Left < LastPromotedIntegralType; ++Left) { 7017 for (unsigned Right = FirstPromotedIntegralType; 7018 Right < LastPromotedIntegralType; ++Right) { 7019 QualType LandR[2] = { getArithmeticType(Left), 7020 getArithmeticType(Right) }; 7021 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7022 ? LandR[0] 7023 : getUsualArithmeticConversions(Left, Right); 7024 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7025 } 7026 } 7027 } 7028 7029 // C++ [over.built]p20: 7030 // 7031 // For every pair (T, VQ), where T is an enumeration or 7032 // pointer to member type and VQ is either volatile or 7033 // empty, there exist candidate operator functions of the form 7034 // 7035 // VQ T& operator=(VQ T&, T); 7036 void addAssignmentMemberPointerOrEnumeralOverloads() { 7037 /// Set of (canonical) types that we've already handled. 7038 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7039 7040 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7041 for (BuiltinCandidateTypeSet::iterator 7042 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7043 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7044 Enum != EnumEnd; ++Enum) { 7045 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7046 continue; 7047 7048 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7049 CandidateSet); 7050 } 7051 7052 for (BuiltinCandidateTypeSet::iterator 7053 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7054 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7055 MemPtr != MemPtrEnd; ++MemPtr) { 7056 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7057 continue; 7058 7059 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7060 CandidateSet); 7061 } 7062 } 7063 } 7064 7065 // C++ [over.built]p19: 7066 // 7067 // For every pair (T, VQ), where T is any type and VQ is either 7068 // volatile or empty, there exist candidate operator functions 7069 // of the form 7070 // 7071 // T*VQ& operator=(T*VQ&, T*); 7072 // 7073 // C++ [over.built]p21: 7074 // 7075 // For every pair (T, VQ), where T is a cv-qualified or 7076 // cv-unqualified object type and VQ is either volatile or 7077 // empty, there exist candidate operator functions of the form 7078 // 7079 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7080 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7081 void addAssignmentPointerOverloads(bool isEqualOp) { 7082 /// Set of (canonical) types that we've already handled. 7083 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7084 7085 for (BuiltinCandidateTypeSet::iterator 7086 Ptr = CandidateTypes[0].pointer_begin(), 7087 PtrEnd = CandidateTypes[0].pointer_end(); 7088 Ptr != PtrEnd; ++Ptr) { 7089 // If this is operator=, keep track of the builtin candidates we added. 7090 if (isEqualOp) 7091 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7092 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7093 continue; 7094 7095 // non-volatile version 7096 QualType ParamTypes[2] = { 7097 S.Context.getLValueReferenceType(*Ptr), 7098 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7099 }; 7100 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7101 /*IsAssigmentOperator=*/ isEqualOp); 7102 7103 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7104 VisibleTypeConversionsQuals.hasVolatile(); 7105 if (NeedVolatile) { 7106 // volatile version 7107 ParamTypes[0] = 7108 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7109 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7110 /*IsAssigmentOperator=*/isEqualOp); 7111 } 7112 7113 if (!(*Ptr).isRestrictQualified() && 7114 VisibleTypeConversionsQuals.hasRestrict()) { 7115 // restrict version 7116 ParamTypes[0] 7117 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7119 /*IsAssigmentOperator=*/isEqualOp); 7120 7121 if (NeedVolatile) { 7122 // volatile restrict version 7123 ParamTypes[0] 7124 = S.Context.getLValueReferenceType( 7125 S.Context.getCVRQualifiedType(*Ptr, 7126 (Qualifiers::Volatile | 7127 Qualifiers::Restrict))); 7128 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7129 CandidateSet, 7130 /*IsAssigmentOperator=*/isEqualOp); 7131 } 7132 } 7133 } 7134 7135 if (isEqualOp) { 7136 for (BuiltinCandidateTypeSet::iterator 7137 Ptr = CandidateTypes[1].pointer_begin(), 7138 PtrEnd = CandidateTypes[1].pointer_end(); 7139 Ptr != PtrEnd; ++Ptr) { 7140 // Make sure we don't add the same candidate twice. 7141 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7142 continue; 7143 7144 QualType ParamTypes[2] = { 7145 S.Context.getLValueReferenceType(*Ptr), 7146 *Ptr, 7147 }; 7148 7149 // non-volatile version 7150 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7151 /*IsAssigmentOperator=*/true); 7152 7153 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7154 VisibleTypeConversionsQuals.hasVolatile(); 7155 if (NeedVolatile) { 7156 // volatile version 7157 ParamTypes[0] = 7158 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7159 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7160 CandidateSet, /*IsAssigmentOperator=*/true); 7161 } 7162 7163 if (!(*Ptr).isRestrictQualified() && 7164 VisibleTypeConversionsQuals.hasRestrict()) { 7165 // restrict version 7166 ParamTypes[0] 7167 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7169 CandidateSet, /*IsAssigmentOperator=*/true); 7170 7171 if (NeedVolatile) { 7172 // volatile restrict version 7173 ParamTypes[0] 7174 = S.Context.getLValueReferenceType( 7175 S.Context.getCVRQualifiedType(*Ptr, 7176 (Qualifiers::Volatile | 7177 Qualifiers::Restrict))); 7178 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7179 CandidateSet, /*IsAssigmentOperator=*/true); 7180 7181 } 7182 } 7183 } 7184 } 7185 } 7186 7187 // C++ [over.built]p18: 7188 // 7189 // For every triple (L, VQ, R), where L is an arithmetic type, 7190 // VQ is either volatile or empty, and R is a promoted 7191 // arithmetic type, there exist candidate operator functions of 7192 // the form 7193 // 7194 // VQ L& operator=(VQ L&, R); 7195 // VQ L& operator*=(VQ L&, R); 7196 // VQ L& operator/=(VQ L&, R); 7197 // VQ L& operator+=(VQ L&, R); 7198 // VQ L& operator-=(VQ L&, R); 7199 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7200 if (!HasArithmeticOrEnumeralCandidateType) 7201 return; 7202 7203 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7204 for (unsigned Right = FirstPromotedArithmeticType; 7205 Right < LastPromotedArithmeticType; ++Right) { 7206 QualType ParamTypes[2]; 7207 ParamTypes[1] = getArithmeticType(Right); 7208 7209 // Add this built-in operator as a candidate (VQ is empty). 7210 ParamTypes[0] = 7211 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7212 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7213 /*IsAssigmentOperator=*/isEqualOp); 7214 7215 // Add this built-in operator as a candidate (VQ is 'volatile'). 7216 if (VisibleTypeConversionsQuals.hasVolatile()) { 7217 ParamTypes[0] = 7218 S.Context.getVolatileType(getArithmeticType(Left)); 7219 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7220 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7221 CandidateSet, 7222 /*IsAssigmentOperator=*/isEqualOp); 7223 } 7224 } 7225 } 7226 7227 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7228 for (BuiltinCandidateTypeSet::iterator 7229 Vec1 = CandidateTypes[0].vector_begin(), 7230 Vec1End = CandidateTypes[0].vector_end(); 7231 Vec1 != Vec1End; ++Vec1) { 7232 for (BuiltinCandidateTypeSet::iterator 7233 Vec2 = CandidateTypes[1].vector_begin(), 7234 Vec2End = CandidateTypes[1].vector_end(); 7235 Vec2 != Vec2End; ++Vec2) { 7236 QualType ParamTypes[2]; 7237 ParamTypes[1] = *Vec2; 7238 // Add this built-in operator as a candidate (VQ is empty). 7239 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7241 /*IsAssigmentOperator=*/isEqualOp); 7242 7243 // Add this built-in operator as a candidate (VQ is 'volatile'). 7244 if (VisibleTypeConversionsQuals.hasVolatile()) { 7245 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7246 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7247 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7248 CandidateSet, 7249 /*IsAssigmentOperator=*/isEqualOp); 7250 } 7251 } 7252 } 7253 } 7254 7255 // C++ [over.built]p22: 7256 // 7257 // For every triple (L, VQ, R), where L is an integral type, VQ 7258 // is either volatile or empty, and R is a promoted integral 7259 // type, there exist candidate operator functions of the form 7260 // 7261 // VQ L& operator%=(VQ L&, R); 7262 // VQ L& operator<<=(VQ L&, R); 7263 // VQ L& operator>>=(VQ L&, R); 7264 // VQ L& operator&=(VQ L&, R); 7265 // VQ L& operator^=(VQ L&, R); 7266 // VQ L& operator|=(VQ L&, R); 7267 void addAssignmentIntegralOverloads() { 7268 if (!HasArithmeticOrEnumeralCandidateType) 7269 return; 7270 7271 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7272 for (unsigned Right = FirstPromotedIntegralType; 7273 Right < LastPromotedIntegralType; ++Right) { 7274 QualType ParamTypes[2]; 7275 ParamTypes[1] = getArithmeticType(Right); 7276 7277 // Add this built-in operator as a candidate (VQ is empty). 7278 ParamTypes[0] = 7279 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7281 if (VisibleTypeConversionsQuals.hasVolatile()) { 7282 // Add this built-in operator as a candidate (VQ is 'volatile'). 7283 ParamTypes[0] = getArithmeticType(Left); 7284 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7285 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7286 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7287 CandidateSet); 7288 } 7289 } 7290 } 7291 } 7292 7293 // C++ [over.operator]p23: 7294 // 7295 // There also exist candidate operator functions of the form 7296 // 7297 // bool operator!(bool); 7298 // bool operator&&(bool, bool); 7299 // bool operator||(bool, bool); 7300 void addExclaimOverload() { 7301 QualType ParamTy = S.Context.BoolTy; 7302 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7303 /*IsAssignmentOperator=*/false, 7304 /*NumContextualBoolArguments=*/1); 7305 } 7306 void addAmpAmpOrPipePipeOverload() { 7307 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7308 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7309 /*IsAssignmentOperator=*/false, 7310 /*NumContextualBoolArguments=*/2); 7311 } 7312 7313 // C++ [over.built]p13: 7314 // 7315 // For every cv-qualified or cv-unqualified object type T there 7316 // exist candidate operator functions of the form 7317 // 7318 // T* operator+(T*, ptrdiff_t); [ABOVE] 7319 // T& operator[](T*, ptrdiff_t); 7320 // T* operator-(T*, ptrdiff_t); [ABOVE] 7321 // T* operator+(ptrdiff_t, T*); [ABOVE] 7322 // T& operator[](ptrdiff_t, T*); 7323 void addSubscriptOverloads() { 7324 for (BuiltinCandidateTypeSet::iterator 7325 Ptr = CandidateTypes[0].pointer_begin(), 7326 PtrEnd = CandidateTypes[0].pointer_end(); 7327 Ptr != PtrEnd; ++Ptr) { 7328 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7329 QualType PointeeType = (*Ptr)->getPointeeType(); 7330 if (!PointeeType->isObjectType()) 7331 continue; 7332 7333 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7334 7335 // T& operator[](T*, ptrdiff_t) 7336 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7337 } 7338 7339 for (BuiltinCandidateTypeSet::iterator 7340 Ptr = CandidateTypes[1].pointer_begin(), 7341 PtrEnd = CandidateTypes[1].pointer_end(); 7342 Ptr != PtrEnd; ++Ptr) { 7343 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7344 QualType PointeeType = (*Ptr)->getPointeeType(); 7345 if (!PointeeType->isObjectType()) 7346 continue; 7347 7348 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7349 7350 // T& operator[](ptrdiff_t, T*) 7351 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7352 } 7353 } 7354 7355 // C++ [over.built]p11: 7356 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7357 // C1 is the same type as C2 or is a derived class of C2, T is an object 7358 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7359 // there exist candidate operator functions of the form 7360 // 7361 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7362 // 7363 // where CV12 is the union of CV1 and CV2. 7364 void addArrowStarOverloads() { 7365 for (BuiltinCandidateTypeSet::iterator 7366 Ptr = CandidateTypes[0].pointer_begin(), 7367 PtrEnd = CandidateTypes[0].pointer_end(); 7368 Ptr != PtrEnd; ++Ptr) { 7369 QualType C1Ty = (*Ptr); 7370 QualType C1; 7371 QualifierCollector Q1; 7372 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7373 if (!isa<RecordType>(C1)) 7374 continue; 7375 // heuristic to reduce number of builtin candidates in the set. 7376 // Add volatile/restrict version only if there are conversions to a 7377 // volatile/restrict type. 7378 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7379 continue; 7380 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7381 continue; 7382 for (BuiltinCandidateTypeSet::iterator 7383 MemPtr = CandidateTypes[1].member_pointer_begin(), 7384 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7385 MemPtr != MemPtrEnd; ++MemPtr) { 7386 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7387 QualType C2 = QualType(mptr->getClass(), 0); 7388 C2 = C2.getUnqualifiedType(); 7389 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7390 break; 7391 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7392 // build CV12 T& 7393 QualType T = mptr->getPointeeType(); 7394 if (!VisibleTypeConversionsQuals.hasVolatile() && 7395 T.isVolatileQualified()) 7396 continue; 7397 if (!VisibleTypeConversionsQuals.hasRestrict() && 7398 T.isRestrictQualified()) 7399 continue; 7400 T = Q1.apply(S.Context, T); 7401 QualType ResultTy = S.Context.getLValueReferenceType(T); 7402 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7403 } 7404 } 7405 } 7406 7407 // Note that we don't consider the first argument, since it has been 7408 // contextually converted to bool long ago. The candidates below are 7409 // therefore added as binary. 7410 // 7411 // C++ [over.built]p25: 7412 // For every type T, where T is a pointer, pointer-to-member, or scoped 7413 // enumeration type, there exist candidate operator functions of the form 7414 // 7415 // T operator?(bool, T, T); 7416 // 7417 void addConditionalOperatorOverloads() { 7418 /// Set of (canonical) types that we've already handled. 7419 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7420 7421 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7422 for (BuiltinCandidateTypeSet::iterator 7423 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7424 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7425 Ptr != PtrEnd; ++Ptr) { 7426 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7427 continue; 7428 7429 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7430 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7431 } 7432 7433 for (BuiltinCandidateTypeSet::iterator 7434 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7435 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7436 MemPtr != MemPtrEnd; ++MemPtr) { 7437 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7438 continue; 7439 7440 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7441 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7442 } 7443 7444 if (S.getLangOpts().CPlusPlus0x) { 7445 for (BuiltinCandidateTypeSet::iterator 7446 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7447 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7448 Enum != EnumEnd; ++Enum) { 7449 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7450 continue; 7451 7452 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7453 continue; 7454 7455 QualType ParamTypes[2] = { *Enum, *Enum }; 7456 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7457 } 7458 } 7459 } 7460 } 7461}; 7462 7463} // end anonymous namespace 7464 7465/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7466/// operator overloads to the candidate set (C++ [over.built]), based 7467/// on the operator @p Op and the arguments given. For example, if the 7468/// operator is a binary '+', this routine might add "int 7469/// operator+(int, int)" to cover integer addition. 7470void 7471Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7472 SourceLocation OpLoc, 7473 Expr **Args, unsigned NumArgs, 7474 OverloadCandidateSet& CandidateSet) { 7475 // Find all of the types that the arguments can convert to, but only 7476 // if the operator we're looking at has built-in operator candidates 7477 // that make use of these types. Also record whether we encounter non-record 7478 // candidate types or either arithmetic or enumeral candidate types. 7479 Qualifiers VisibleTypeConversionsQuals; 7480 VisibleTypeConversionsQuals.addConst(); 7481 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7482 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7483 7484 bool HasNonRecordCandidateType = false; 7485 bool HasArithmeticOrEnumeralCandidateType = false; 7486 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7487 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7488 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7489 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7490 OpLoc, 7491 true, 7492 (Op == OO_Exclaim || 7493 Op == OO_AmpAmp || 7494 Op == OO_PipePipe), 7495 VisibleTypeConversionsQuals); 7496 HasNonRecordCandidateType = HasNonRecordCandidateType || 7497 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7498 HasArithmeticOrEnumeralCandidateType = 7499 HasArithmeticOrEnumeralCandidateType || 7500 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7501 } 7502 7503 // Exit early when no non-record types have been added to the candidate set 7504 // for any of the arguments to the operator. 7505 // 7506 // We can't exit early for !, ||, or &&, since there we have always have 7507 // 'bool' overloads. 7508 if (!HasNonRecordCandidateType && 7509 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7510 return; 7511 7512 // Setup an object to manage the common state for building overloads. 7513 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7514 VisibleTypeConversionsQuals, 7515 HasArithmeticOrEnumeralCandidateType, 7516 CandidateTypes, CandidateSet); 7517 7518 // Dispatch over the operation to add in only those overloads which apply. 7519 switch (Op) { 7520 case OO_None: 7521 case NUM_OVERLOADED_OPERATORS: 7522 llvm_unreachable("Expected an overloaded operator"); 7523 7524 case OO_New: 7525 case OO_Delete: 7526 case OO_Array_New: 7527 case OO_Array_Delete: 7528 case OO_Call: 7529 llvm_unreachable( 7530 "Special operators don't use AddBuiltinOperatorCandidates"); 7531 7532 case OO_Comma: 7533 case OO_Arrow: 7534 // C++ [over.match.oper]p3: 7535 // -- For the operator ',', the unary operator '&', or the 7536 // operator '->', the built-in candidates set is empty. 7537 break; 7538 7539 case OO_Plus: // '+' is either unary or binary 7540 if (NumArgs == 1) 7541 OpBuilder.addUnaryPlusPointerOverloads(); 7542 // Fall through. 7543 7544 case OO_Minus: // '-' is either unary or binary 7545 if (NumArgs == 1) { 7546 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7547 } else { 7548 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7549 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7550 } 7551 break; 7552 7553 case OO_Star: // '*' is either unary or binary 7554 if (NumArgs == 1) 7555 OpBuilder.addUnaryStarPointerOverloads(); 7556 else 7557 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7558 break; 7559 7560 case OO_Slash: 7561 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7562 break; 7563 7564 case OO_PlusPlus: 7565 case OO_MinusMinus: 7566 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7567 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7568 break; 7569 7570 case OO_EqualEqual: 7571 case OO_ExclaimEqual: 7572 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7573 // Fall through. 7574 7575 case OO_Less: 7576 case OO_Greater: 7577 case OO_LessEqual: 7578 case OO_GreaterEqual: 7579 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7580 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7581 break; 7582 7583 case OO_Percent: 7584 case OO_Caret: 7585 case OO_Pipe: 7586 case OO_LessLess: 7587 case OO_GreaterGreater: 7588 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7589 break; 7590 7591 case OO_Amp: // '&' is either unary or binary 7592 if (NumArgs == 1) 7593 // C++ [over.match.oper]p3: 7594 // -- For the operator ',', the unary operator '&', or the 7595 // operator '->', the built-in candidates set is empty. 7596 break; 7597 7598 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7599 break; 7600 7601 case OO_Tilde: 7602 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7603 break; 7604 7605 case OO_Equal: 7606 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7607 // Fall through. 7608 7609 case OO_PlusEqual: 7610 case OO_MinusEqual: 7611 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7612 // Fall through. 7613 7614 case OO_StarEqual: 7615 case OO_SlashEqual: 7616 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7617 break; 7618 7619 case OO_PercentEqual: 7620 case OO_LessLessEqual: 7621 case OO_GreaterGreaterEqual: 7622 case OO_AmpEqual: 7623 case OO_CaretEqual: 7624 case OO_PipeEqual: 7625 OpBuilder.addAssignmentIntegralOverloads(); 7626 break; 7627 7628 case OO_Exclaim: 7629 OpBuilder.addExclaimOverload(); 7630 break; 7631 7632 case OO_AmpAmp: 7633 case OO_PipePipe: 7634 OpBuilder.addAmpAmpOrPipePipeOverload(); 7635 break; 7636 7637 case OO_Subscript: 7638 OpBuilder.addSubscriptOverloads(); 7639 break; 7640 7641 case OO_ArrowStar: 7642 OpBuilder.addArrowStarOverloads(); 7643 break; 7644 7645 case OO_Conditional: 7646 OpBuilder.addConditionalOperatorOverloads(); 7647 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7648 break; 7649 } 7650} 7651 7652/// \brief Add function candidates found via argument-dependent lookup 7653/// to the set of overloading candidates. 7654/// 7655/// This routine performs argument-dependent name lookup based on the 7656/// given function name (which may also be an operator name) and adds 7657/// all of the overload candidates found by ADL to the overload 7658/// candidate set (C++ [basic.lookup.argdep]). 7659void 7660Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7661 bool Operator, SourceLocation Loc, 7662 llvm::ArrayRef<Expr *> Args, 7663 TemplateArgumentListInfo *ExplicitTemplateArgs, 7664 OverloadCandidateSet& CandidateSet, 7665 bool PartialOverloading, 7666 bool StdNamespaceIsAssociated) { 7667 ADLResult Fns; 7668 7669 // FIXME: This approach for uniquing ADL results (and removing 7670 // redundant candidates from the set) relies on pointer-equality, 7671 // which means we need to key off the canonical decl. However, 7672 // always going back to the canonical decl might not get us the 7673 // right set of default arguments. What default arguments are 7674 // we supposed to consider on ADL candidates, anyway? 7675 7676 // FIXME: Pass in the explicit template arguments? 7677 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns, 7678 StdNamespaceIsAssociated); 7679 7680 // Erase all of the candidates we already knew about. 7681 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7682 CandEnd = CandidateSet.end(); 7683 Cand != CandEnd; ++Cand) 7684 if (Cand->Function) { 7685 Fns.erase(Cand->Function); 7686 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7687 Fns.erase(FunTmpl); 7688 } 7689 7690 // For each of the ADL candidates we found, add it to the overload 7691 // set. 7692 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7693 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7694 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7695 if (ExplicitTemplateArgs) 7696 continue; 7697 7698 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7699 PartialOverloading); 7700 } else 7701 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7702 FoundDecl, ExplicitTemplateArgs, 7703 Args, CandidateSet); 7704 } 7705} 7706 7707/// isBetterOverloadCandidate - Determines whether the first overload 7708/// candidate is a better candidate than the second (C++ 13.3.3p1). 7709bool 7710isBetterOverloadCandidate(Sema &S, 7711 const OverloadCandidate &Cand1, 7712 const OverloadCandidate &Cand2, 7713 SourceLocation Loc, 7714 bool UserDefinedConversion) { 7715 // Define viable functions to be better candidates than non-viable 7716 // functions. 7717 if (!Cand2.Viable) 7718 return Cand1.Viable; 7719 else if (!Cand1.Viable) 7720 return false; 7721 7722 // C++ [over.match.best]p1: 7723 // 7724 // -- if F is a static member function, ICS1(F) is defined such 7725 // that ICS1(F) is neither better nor worse than ICS1(G) for 7726 // any function G, and, symmetrically, ICS1(G) is neither 7727 // better nor worse than ICS1(F). 7728 unsigned StartArg = 0; 7729 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7730 StartArg = 1; 7731 7732 // C++ [over.match.best]p1: 7733 // A viable function F1 is defined to be a better function than another 7734 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7735 // conversion sequence than ICSi(F2), and then... 7736 unsigned NumArgs = Cand1.NumConversions; 7737 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7738 bool HasBetterConversion = false; 7739 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7740 switch (CompareImplicitConversionSequences(S, 7741 Cand1.Conversions[ArgIdx], 7742 Cand2.Conversions[ArgIdx])) { 7743 case ImplicitConversionSequence::Better: 7744 // Cand1 has a better conversion sequence. 7745 HasBetterConversion = true; 7746 break; 7747 7748 case ImplicitConversionSequence::Worse: 7749 // Cand1 can't be better than Cand2. 7750 return false; 7751 7752 case ImplicitConversionSequence::Indistinguishable: 7753 // Do nothing. 7754 break; 7755 } 7756 } 7757 7758 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7759 // ICSj(F2), or, if not that, 7760 if (HasBetterConversion) 7761 return true; 7762 7763 // - F1 is a non-template function and F2 is a function template 7764 // specialization, or, if not that, 7765 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7766 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7767 return true; 7768 7769 // -- F1 and F2 are function template specializations, and the function 7770 // template for F1 is more specialized than the template for F2 7771 // according to the partial ordering rules described in 14.5.5.2, or, 7772 // if not that, 7773 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7774 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7775 if (FunctionTemplateDecl *BetterTemplate 7776 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7777 Cand2.Function->getPrimaryTemplate(), 7778 Loc, 7779 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7780 : TPOC_Call, 7781 Cand1.ExplicitCallArguments)) 7782 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7783 } 7784 7785 // -- the context is an initialization by user-defined conversion 7786 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7787 // from the return type of F1 to the destination type (i.e., 7788 // the type of the entity being initialized) is a better 7789 // conversion sequence than the standard conversion sequence 7790 // from the return type of F2 to the destination type. 7791 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7792 isa<CXXConversionDecl>(Cand1.Function) && 7793 isa<CXXConversionDecl>(Cand2.Function)) { 7794 // First check whether we prefer one of the conversion functions over the 7795 // other. This only distinguishes the results in non-standard, extension 7796 // cases such as the conversion from a lambda closure type to a function 7797 // pointer or block. 7798 ImplicitConversionSequence::CompareKind FuncResult 7799 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7800 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7801 return FuncResult; 7802 7803 switch (CompareStandardConversionSequences(S, 7804 Cand1.FinalConversion, 7805 Cand2.FinalConversion)) { 7806 case ImplicitConversionSequence::Better: 7807 // Cand1 has a better conversion sequence. 7808 return true; 7809 7810 case ImplicitConversionSequence::Worse: 7811 // Cand1 can't be better than Cand2. 7812 return false; 7813 7814 case ImplicitConversionSequence::Indistinguishable: 7815 // Do nothing 7816 break; 7817 } 7818 } 7819 7820 return false; 7821} 7822 7823/// \brief Computes the best viable function (C++ 13.3.3) 7824/// within an overload candidate set. 7825/// 7826/// \param CandidateSet the set of candidate functions. 7827/// 7828/// \param Loc the location of the function name (or operator symbol) for 7829/// which overload resolution occurs. 7830/// 7831/// \param Best f overload resolution was successful or found a deleted 7832/// function, Best points to the candidate function found. 7833/// 7834/// \returns The result of overload resolution. 7835OverloadingResult 7836OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7837 iterator &Best, 7838 bool UserDefinedConversion) { 7839 // Find the best viable function. 7840 Best = end(); 7841 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7842 if (Cand->Viable) 7843 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7844 UserDefinedConversion)) 7845 Best = Cand; 7846 } 7847 7848 // If we didn't find any viable functions, abort. 7849 if (Best == end()) 7850 return OR_No_Viable_Function; 7851 7852 // Make sure that this function is better than every other viable 7853 // function. If not, we have an ambiguity. 7854 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7855 if (Cand->Viable && 7856 Cand != Best && 7857 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7858 UserDefinedConversion)) { 7859 Best = end(); 7860 return OR_Ambiguous; 7861 } 7862 } 7863 7864 // Best is the best viable function. 7865 if (Best->Function && 7866 (Best->Function->isDeleted() || 7867 S.isFunctionConsideredUnavailable(Best->Function))) 7868 return OR_Deleted; 7869 7870 return OR_Success; 7871} 7872 7873namespace { 7874 7875enum OverloadCandidateKind { 7876 oc_function, 7877 oc_method, 7878 oc_constructor, 7879 oc_function_template, 7880 oc_method_template, 7881 oc_constructor_template, 7882 oc_implicit_default_constructor, 7883 oc_implicit_copy_constructor, 7884 oc_implicit_move_constructor, 7885 oc_implicit_copy_assignment, 7886 oc_implicit_move_assignment, 7887 oc_implicit_inherited_constructor 7888}; 7889 7890OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7891 FunctionDecl *Fn, 7892 std::string &Description) { 7893 bool isTemplate = false; 7894 7895 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7896 isTemplate = true; 7897 Description = S.getTemplateArgumentBindingsText( 7898 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7899 } 7900 7901 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7902 if (!Ctor->isImplicit()) 7903 return isTemplate ? oc_constructor_template : oc_constructor; 7904 7905 if (Ctor->getInheritedConstructor()) 7906 return oc_implicit_inherited_constructor; 7907 7908 if (Ctor->isDefaultConstructor()) 7909 return oc_implicit_default_constructor; 7910 7911 if (Ctor->isMoveConstructor()) 7912 return oc_implicit_move_constructor; 7913 7914 assert(Ctor->isCopyConstructor() && 7915 "unexpected sort of implicit constructor"); 7916 return oc_implicit_copy_constructor; 7917 } 7918 7919 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7920 // This actually gets spelled 'candidate function' for now, but 7921 // it doesn't hurt to split it out. 7922 if (!Meth->isImplicit()) 7923 return isTemplate ? oc_method_template : oc_method; 7924 7925 if (Meth->isMoveAssignmentOperator()) 7926 return oc_implicit_move_assignment; 7927 7928 if (Meth->isCopyAssignmentOperator()) 7929 return oc_implicit_copy_assignment; 7930 7931 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7932 return oc_method; 7933 } 7934 7935 return isTemplate ? oc_function_template : oc_function; 7936} 7937 7938void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7939 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7940 if (!Ctor) return; 7941 7942 Ctor = Ctor->getInheritedConstructor(); 7943 if (!Ctor) return; 7944 7945 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7946} 7947 7948} // end anonymous namespace 7949 7950// Notes the location of an overload candidate. 7951void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7952 std::string FnDesc; 7953 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7954 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7955 << (unsigned) K << FnDesc; 7956 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7957 Diag(Fn->getLocation(), PD); 7958 MaybeEmitInheritedConstructorNote(*this, Fn); 7959} 7960 7961//Notes the location of all overload candidates designated through 7962// OverloadedExpr 7963void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7964 assert(OverloadedExpr->getType() == Context.OverloadTy); 7965 7966 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7967 OverloadExpr *OvlExpr = Ovl.Expression; 7968 7969 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7970 IEnd = OvlExpr->decls_end(); 7971 I != IEnd; ++I) { 7972 if (FunctionTemplateDecl *FunTmpl = 7973 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7974 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7975 } else if (FunctionDecl *Fun 7976 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7977 NoteOverloadCandidate(Fun, DestType); 7978 } 7979 } 7980} 7981 7982/// Diagnoses an ambiguous conversion. The partial diagnostic is the 7983/// "lead" diagnostic; it will be given two arguments, the source and 7984/// target types of the conversion. 7985void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7986 Sema &S, 7987 SourceLocation CaretLoc, 7988 const PartialDiagnostic &PDiag) const { 7989 S.Diag(CaretLoc, PDiag) 7990 << Ambiguous.getFromType() << Ambiguous.getToType(); 7991 for (AmbiguousConversionSequence::const_iterator 7992 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 7993 S.NoteOverloadCandidate(*I); 7994 } 7995} 7996 7997namespace { 7998 7999void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8000 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8001 assert(Conv.isBad()); 8002 assert(Cand->Function && "for now, candidate must be a function"); 8003 FunctionDecl *Fn = Cand->Function; 8004 8005 // There's a conversion slot for the object argument if this is a 8006 // non-constructor method. Note that 'I' corresponds the 8007 // conversion-slot index. 8008 bool isObjectArgument = false; 8009 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8010 if (I == 0) 8011 isObjectArgument = true; 8012 else 8013 I--; 8014 } 8015 8016 std::string FnDesc; 8017 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8018 8019 Expr *FromExpr = Conv.Bad.FromExpr; 8020 QualType FromTy = Conv.Bad.getFromType(); 8021 QualType ToTy = Conv.Bad.getToType(); 8022 8023 if (FromTy == S.Context.OverloadTy) { 8024 assert(FromExpr && "overload set argument came from implicit argument?"); 8025 Expr *E = FromExpr->IgnoreParens(); 8026 if (isa<UnaryOperator>(E)) 8027 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8028 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8029 8030 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8031 << (unsigned) FnKind << FnDesc 8032 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8033 << ToTy << Name << I+1; 8034 MaybeEmitInheritedConstructorNote(S, Fn); 8035 return; 8036 } 8037 8038 // Do some hand-waving analysis to see if the non-viability is due 8039 // to a qualifier mismatch. 8040 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8041 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8042 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8043 CToTy = RT->getPointeeType(); 8044 else { 8045 // TODO: detect and diagnose the full richness of const mismatches. 8046 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8047 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8048 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8049 } 8050 8051 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8052 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8053 Qualifiers FromQs = CFromTy.getQualifiers(); 8054 Qualifiers ToQs = CToTy.getQualifiers(); 8055 8056 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8057 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8058 << (unsigned) FnKind << FnDesc 8059 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8060 << FromTy 8061 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8062 << (unsigned) isObjectArgument << I+1; 8063 MaybeEmitInheritedConstructorNote(S, Fn); 8064 return; 8065 } 8066 8067 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8068 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8069 << (unsigned) FnKind << FnDesc 8070 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8071 << FromTy 8072 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8073 << (unsigned) isObjectArgument << I+1; 8074 MaybeEmitInheritedConstructorNote(S, Fn); 8075 return; 8076 } 8077 8078 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8079 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8080 << (unsigned) FnKind << FnDesc 8081 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8082 << FromTy 8083 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8084 << (unsigned) isObjectArgument << I+1; 8085 MaybeEmitInheritedConstructorNote(S, Fn); 8086 return; 8087 } 8088 8089 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8090 assert(CVR && "unexpected qualifiers mismatch"); 8091 8092 if (isObjectArgument) { 8093 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8094 << (unsigned) FnKind << FnDesc 8095 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8096 << FromTy << (CVR - 1); 8097 } else { 8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8099 << (unsigned) FnKind << FnDesc 8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8101 << FromTy << (CVR - 1) << I+1; 8102 } 8103 MaybeEmitInheritedConstructorNote(S, Fn); 8104 return; 8105 } 8106 8107 // Special diagnostic for failure to convert an initializer list, since 8108 // telling the user that it has type void is not useful. 8109 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8111 << (unsigned) FnKind << FnDesc 8112 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8113 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8114 MaybeEmitInheritedConstructorNote(S, Fn); 8115 return; 8116 } 8117 8118 // Diagnose references or pointers to incomplete types differently, 8119 // since it's far from impossible that the incompleteness triggered 8120 // the failure. 8121 QualType TempFromTy = FromTy.getNonReferenceType(); 8122 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8123 TempFromTy = PTy->getPointeeType(); 8124 if (TempFromTy->isIncompleteType()) { 8125 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8126 << (unsigned) FnKind << FnDesc 8127 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8128 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8129 MaybeEmitInheritedConstructorNote(S, Fn); 8130 return; 8131 } 8132 8133 // Diagnose base -> derived pointer conversions. 8134 unsigned BaseToDerivedConversion = 0; 8135 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8136 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8137 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8138 FromPtrTy->getPointeeType()) && 8139 !FromPtrTy->getPointeeType()->isIncompleteType() && 8140 !ToPtrTy->getPointeeType()->isIncompleteType() && 8141 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8142 FromPtrTy->getPointeeType())) 8143 BaseToDerivedConversion = 1; 8144 } 8145 } else if (const ObjCObjectPointerType *FromPtrTy 8146 = FromTy->getAs<ObjCObjectPointerType>()) { 8147 if (const ObjCObjectPointerType *ToPtrTy 8148 = ToTy->getAs<ObjCObjectPointerType>()) 8149 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8150 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8151 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8152 FromPtrTy->getPointeeType()) && 8153 FromIface->isSuperClassOf(ToIface)) 8154 BaseToDerivedConversion = 2; 8155 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8156 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8157 !FromTy->isIncompleteType() && 8158 !ToRefTy->getPointeeType()->isIncompleteType() && 8159 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) 8160 BaseToDerivedConversion = 3; 8161 } 8162 8163 if (BaseToDerivedConversion) { 8164 S.Diag(Fn->getLocation(), 8165 diag::note_ovl_candidate_bad_base_to_derived_conv) 8166 << (unsigned) FnKind << FnDesc 8167 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8168 << (BaseToDerivedConversion - 1) 8169 << FromTy << ToTy << I+1; 8170 MaybeEmitInheritedConstructorNote(S, Fn); 8171 return; 8172 } 8173 8174 if (isa<ObjCObjectPointerType>(CFromTy) && 8175 isa<PointerType>(CToTy)) { 8176 Qualifiers FromQs = CFromTy.getQualifiers(); 8177 Qualifiers ToQs = CToTy.getQualifiers(); 8178 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8180 << (unsigned) FnKind << FnDesc 8181 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8182 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8183 MaybeEmitInheritedConstructorNote(S, Fn); 8184 return; 8185 } 8186 } 8187 8188 // Emit the generic diagnostic and, optionally, add the hints to it. 8189 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8190 FDiag << (unsigned) FnKind << FnDesc 8191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8192 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8193 << (unsigned) (Cand->Fix.Kind); 8194 8195 // If we can fix the conversion, suggest the FixIts. 8196 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8197 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8198 FDiag << *HI; 8199 S.Diag(Fn->getLocation(), FDiag); 8200 8201 MaybeEmitInheritedConstructorNote(S, Fn); 8202} 8203 8204void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8205 unsigned NumFormalArgs) { 8206 // TODO: treat calls to a missing default constructor as a special case 8207 8208 FunctionDecl *Fn = Cand->Function; 8209 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8210 8211 unsigned MinParams = Fn->getMinRequiredArguments(); 8212 8213 // With invalid overloaded operators, it's possible that we think we 8214 // have an arity mismatch when it fact it looks like we have the 8215 // right number of arguments, because only overloaded operators have 8216 // the weird behavior of overloading member and non-member functions. 8217 // Just don't report anything. 8218 if (Fn->isInvalidDecl() && 8219 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8220 return; 8221 8222 // at least / at most / exactly 8223 unsigned mode, modeCount; 8224 if (NumFormalArgs < MinParams) { 8225 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8226 (Cand->FailureKind == ovl_fail_bad_deduction && 8227 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8228 if (MinParams != FnTy->getNumArgs() || 8229 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8230 mode = 0; // "at least" 8231 else 8232 mode = 2; // "exactly" 8233 modeCount = MinParams; 8234 } else { 8235 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8236 (Cand->FailureKind == ovl_fail_bad_deduction && 8237 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8238 if (MinParams != FnTy->getNumArgs()) 8239 mode = 1; // "at most" 8240 else 8241 mode = 2; // "exactly" 8242 modeCount = FnTy->getNumArgs(); 8243 } 8244 8245 std::string Description; 8246 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8247 8248 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8249 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8250 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8251 << Fn->getParamDecl(0) << NumFormalArgs; 8252 else 8253 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8254 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8255 << modeCount << NumFormalArgs; 8256 MaybeEmitInheritedConstructorNote(S, Fn); 8257} 8258 8259/// Diagnose a failed template-argument deduction. 8260void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8261 unsigned NumArgs) { 8262 FunctionDecl *Fn = Cand->Function; // pattern 8263 8264 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8265 NamedDecl *ParamD; 8266 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8267 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8268 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8269 switch (Cand->DeductionFailure.Result) { 8270 case Sema::TDK_Success: 8271 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8272 8273 case Sema::TDK_Incomplete: { 8274 assert(ParamD && "no parameter found for incomplete deduction result"); 8275 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8276 << ParamD->getDeclName(); 8277 MaybeEmitInheritedConstructorNote(S, Fn); 8278 return; 8279 } 8280 8281 case Sema::TDK_Underqualified: { 8282 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8283 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8284 8285 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8286 8287 // Param will have been canonicalized, but it should just be a 8288 // qualified version of ParamD, so move the qualifiers to that. 8289 QualifierCollector Qs; 8290 Qs.strip(Param); 8291 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8292 assert(S.Context.hasSameType(Param, NonCanonParam)); 8293 8294 // Arg has also been canonicalized, but there's nothing we can do 8295 // about that. It also doesn't matter as much, because it won't 8296 // have any template parameters in it (because deduction isn't 8297 // done on dependent types). 8298 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8299 8300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8301 << ParamD->getDeclName() << Arg << NonCanonParam; 8302 MaybeEmitInheritedConstructorNote(S, Fn); 8303 return; 8304 } 8305 8306 case Sema::TDK_Inconsistent: { 8307 assert(ParamD && "no parameter found for inconsistent deduction result"); 8308 int which = 0; 8309 if (isa<TemplateTypeParmDecl>(ParamD)) 8310 which = 0; 8311 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8312 which = 1; 8313 else { 8314 which = 2; 8315 } 8316 8317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8318 << which << ParamD->getDeclName() 8319 << *Cand->DeductionFailure.getFirstArg() 8320 << *Cand->DeductionFailure.getSecondArg(); 8321 MaybeEmitInheritedConstructorNote(S, Fn); 8322 return; 8323 } 8324 8325 case Sema::TDK_InvalidExplicitArguments: 8326 assert(ParamD && "no parameter found for invalid explicit arguments"); 8327 if (ParamD->getDeclName()) 8328 S.Diag(Fn->getLocation(), 8329 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8330 << ParamD->getDeclName(); 8331 else { 8332 int index = 0; 8333 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8334 index = TTP->getIndex(); 8335 else if (NonTypeTemplateParmDecl *NTTP 8336 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8337 index = NTTP->getIndex(); 8338 else 8339 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8340 S.Diag(Fn->getLocation(), 8341 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8342 << (index + 1); 8343 } 8344 MaybeEmitInheritedConstructorNote(S, Fn); 8345 return; 8346 8347 case Sema::TDK_TooManyArguments: 8348 case Sema::TDK_TooFewArguments: 8349 DiagnoseArityMismatch(S, Cand, NumArgs); 8350 return; 8351 8352 case Sema::TDK_InstantiationDepth: 8353 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8354 MaybeEmitInheritedConstructorNote(S, Fn); 8355 return; 8356 8357 case Sema::TDK_SubstitutionFailure: { 8358 // Format the template argument list into the argument string. 8359 llvm::SmallString<128> TemplateArgString; 8360 if (TemplateArgumentList *Args = 8361 Cand->DeductionFailure.getTemplateArgumentList()) { 8362 TemplateArgString = " "; 8363 TemplateArgString += S.getTemplateArgumentBindingsText( 8364 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8365 } 8366 8367 // If this candidate was disabled by enable_if, say so. 8368 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8369 if (PDiag && PDiag->second.getDiagID() == 8370 diag::err_typename_nested_not_found_enable_if) { 8371 // FIXME: Use the source range of the condition, and the fully-qualified 8372 // name of the enable_if template. These are both present in PDiag. 8373 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8374 << "'enable_if'" << TemplateArgString; 8375 return; 8376 } 8377 8378 // Format the SFINAE diagnostic into the argument string. 8379 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8380 // formatted message in another diagnostic. 8381 llvm::SmallString<128> SFINAEArgString; 8382 SourceRange R; 8383 if (PDiag) { 8384 SFINAEArgString = ": "; 8385 R = SourceRange(PDiag->first, PDiag->first); 8386 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8387 } 8388 8389 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8390 << TemplateArgString << SFINAEArgString << R; 8391 MaybeEmitInheritedConstructorNote(S, Fn); 8392 return; 8393 } 8394 8395 // TODO: diagnose these individually, then kill off 8396 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8397 case Sema::TDK_NonDeducedMismatch: 8398 case Sema::TDK_FailedOverloadResolution: 8399 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8400 MaybeEmitInheritedConstructorNote(S, Fn); 8401 return; 8402 } 8403} 8404 8405/// CUDA: diagnose an invalid call across targets. 8406void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8407 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8408 FunctionDecl *Callee = Cand->Function; 8409 8410 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8411 CalleeTarget = S.IdentifyCUDATarget(Callee); 8412 8413 std::string FnDesc; 8414 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8415 8416 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8417 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8418} 8419 8420/// Generates a 'note' diagnostic for an overload candidate. We've 8421/// already generated a primary error at the call site. 8422/// 8423/// It really does need to be a single diagnostic with its caret 8424/// pointed at the candidate declaration. Yes, this creates some 8425/// major challenges of technical writing. Yes, this makes pointing 8426/// out problems with specific arguments quite awkward. It's still 8427/// better than generating twenty screens of text for every failed 8428/// overload. 8429/// 8430/// It would be great to be able to express per-candidate problems 8431/// more richly for those diagnostic clients that cared, but we'd 8432/// still have to be just as careful with the default diagnostics. 8433void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8434 unsigned NumArgs) { 8435 FunctionDecl *Fn = Cand->Function; 8436 8437 // Note deleted candidates, but only if they're viable. 8438 if (Cand->Viable && (Fn->isDeleted() || 8439 S.isFunctionConsideredUnavailable(Fn))) { 8440 std::string FnDesc; 8441 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8442 8443 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8444 << FnKind << FnDesc 8445 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8446 MaybeEmitInheritedConstructorNote(S, Fn); 8447 return; 8448 } 8449 8450 // We don't really have anything else to say about viable candidates. 8451 if (Cand->Viable) { 8452 S.NoteOverloadCandidate(Fn); 8453 return; 8454 } 8455 8456 switch (Cand->FailureKind) { 8457 case ovl_fail_too_many_arguments: 8458 case ovl_fail_too_few_arguments: 8459 return DiagnoseArityMismatch(S, Cand, NumArgs); 8460 8461 case ovl_fail_bad_deduction: 8462 return DiagnoseBadDeduction(S, Cand, NumArgs); 8463 8464 case ovl_fail_trivial_conversion: 8465 case ovl_fail_bad_final_conversion: 8466 case ovl_fail_final_conversion_not_exact: 8467 return S.NoteOverloadCandidate(Fn); 8468 8469 case ovl_fail_bad_conversion: { 8470 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8471 for (unsigned N = Cand->NumConversions; I != N; ++I) 8472 if (Cand->Conversions[I].isBad()) 8473 return DiagnoseBadConversion(S, Cand, I); 8474 8475 // FIXME: this currently happens when we're called from SemaInit 8476 // when user-conversion overload fails. Figure out how to handle 8477 // those conditions and diagnose them well. 8478 return S.NoteOverloadCandidate(Fn); 8479 } 8480 8481 case ovl_fail_bad_target: 8482 return DiagnoseBadTarget(S, Cand); 8483 } 8484} 8485 8486void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8487 // Desugar the type of the surrogate down to a function type, 8488 // retaining as many typedefs as possible while still showing 8489 // the function type (and, therefore, its parameter types). 8490 QualType FnType = Cand->Surrogate->getConversionType(); 8491 bool isLValueReference = false; 8492 bool isRValueReference = false; 8493 bool isPointer = false; 8494 if (const LValueReferenceType *FnTypeRef = 8495 FnType->getAs<LValueReferenceType>()) { 8496 FnType = FnTypeRef->getPointeeType(); 8497 isLValueReference = true; 8498 } else if (const RValueReferenceType *FnTypeRef = 8499 FnType->getAs<RValueReferenceType>()) { 8500 FnType = FnTypeRef->getPointeeType(); 8501 isRValueReference = true; 8502 } 8503 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8504 FnType = FnTypePtr->getPointeeType(); 8505 isPointer = true; 8506 } 8507 // Desugar down to a function type. 8508 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8509 // Reconstruct the pointer/reference as appropriate. 8510 if (isPointer) FnType = S.Context.getPointerType(FnType); 8511 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8512 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8513 8514 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8515 << FnType; 8516 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8517} 8518 8519void NoteBuiltinOperatorCandidate(Sema &S, 8520 const char *Opc, 8521 SourceLocation OpLoc, 8522 OverloadCandidate *Cand) { 8523 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8524 std::string TypeStr("operator"); 8525 TypeStr += Opc; 8526 TypeStr += "("; 8527 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8528 if (Cand->NumConversions == 1) { 8529 TypeStr += ")"; 8530 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8531 } else { 8532 TypeStr += ", "; 8533 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8534 TypeStr += ")"; 8535 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8536 } 8537} 8538 8539void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8540 OverloadCandidate *Cand) { 8541 unsigned NoOperands = Cand->NumConversions; 8542 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8543 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8544 if (ICS.isBad()) break; // all meaningless after first invalid 8545 if (!ICS.isAmbiguous()) continue; 8546 8547 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8548 S.PDiag(diag::note_ambiguous_type_conversion)); 8549 } 8550} 8551 8552SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8553 if (Cand->Function) 8554 return Cand->Function->getLocation(); 8555 if (Cand->IsSurrogate) 8556 return Cand->Surrogate->getLocation(); 8557 return SourceLocation(); 8558} 8559 8560static unsigned 8561RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8562 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8563 case Sema::TDK_Success: 8564 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8565 8566 case Sema::TDK_Incomplete: 8567 return 1; 8568 8569 case Sema::TDK_Underqualified: 8570 case Sema::TDK_Inconsistent: 8571 return 2; 8572 8573 case Sema::TDK_SubstitutionFailure: 8574 case Sema::TDK_NonDeducedMismatch: 8575 return 3; 8576 8577 case Sema::TDK_InstantiationDepth: 8578 case Sema::TDK_FailedOverloadResolution: 8579 return 4; 8580 8581 case Sema::TDK_InvalidExplicitArguments: 8582 return 5; 8583 8584 case Sema::TDK_TooManyArguments: 8585 case Sema::TDK_TooFewArguments: 8586 return 6; 8587 } 8588 llvm_unreachable("Unhandled deduction result"); 8589} 8590 8591struct CompareOverloadCandidatesForDisplay { 8592 Sema &S; 8593 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8594 8595 bool operator()(const OverloadCandidate *L, 8596 const OverloadCandidate *R) { 8597 // Fast-path this check. 8598 if (L == R) return false; 8599 8600 // Order first by viability. 8601 if (L->Viable) { 8602 if (!R->Viable) return true; 8603 8604 // TODO: introduce a tri-valued comparison for overload 8605 // candidates. Would be more worthwhile if we had a sort 8606 // that could exploit it. 8607 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8608 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8609 } else if (R->Viable) 8610 return false; 8611 8612 assert(L->Viable == R->Viable); 8613 8614 // Criteria by which we can sort non-viable candidates: 8615 if (!L->Viable) { 8616 // 1. Arity mismatches come after other candidates. 8617 if (L->FailureKind == ovl_fail_too_many_arguments || 8618 L->FailureKind == ovl_fail_too_few_arguments) 8619 return false; 8620 if (R->FailureKind == ovl_fail_too_many_arguments || 8621 R->FailureKind == ovl_fail_too_few_arguments) 8622 return true; 8623 8624 // 2. Bad conversions come first and are ordered by the number 8625 // of bad conversions and quality of good conversions. 8626 if (L->FailureKind == ovl_fail_bad_conversion) { 8627 if (R->FailureKind != ovl_fail_bad_conversion) 8628 return true; 8629 8630 // The conversion that can be fixed with a smaller number of changes, 8631 // comes first. 8632 unsigned numLFixes = L->Fix.NumConversionsFixed; 8633 unsigned numRFixes = R->Fix.NumConversionsFixed; 8634 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8635 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8636 if (numLFixes != numRFixes) { 8637 if (numLFixes < numRFixes) 8638 return true; 8639 else 8640 return false; 8641 } 8642 8643 // If there's any ordering between the defined conversions... 8644 // FIXME: this might not be transitive. 8645 assert(L->NumConversions == R->NumConversions); 8646 8647 int leftBetter = 0; 8648 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8649 for (unsigned E = L->NumConversions; I != E; ++I) { 8650 switch (CompareImplicitConversionSequences(S, 8651 L->Conversions[I], 8652 R->Conversions[I])) { 8653 case ImplicitConversionSequence::Better: 8654 leftBetter++; 8655 break; 8656 8657 case ImplicitConversionSequence::Worse: 8658 leftBetter--; 8659 break; 8660 8661 case ImplicitConversionSequence::Indistinguishable: 8662 break; 8663 } 8664 } 8665 if (leftBetter > 0) return true; 8666 if (leftBetter < 0) return false; 8667 8668 } else if (R->FailureKind == ovl_fail_bad_conversion) 8669 return false; 8670 8671 if (L->FailureKind == ovl_fail_bad_deduction) { 8672 if (R->FailureKind != ovl_fail_bad_deduction) 8673 return true; 8674 8675 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8676 return RankDeductionFailure(L->DeductionFailure) 8677 < RankDeductionFailure(R->DeductionFailure); 8678 } else if (R->FailureKind == ovl_fail_bad_deduction) 8679 return false; 8680 8681 // TODO: others? 8682 } 8683 8684 // Sort everything else by location. 8685 SourceLocation LLoc = GetLocationForCandidate(L); 8686 SourceLocation RLoc = GetLocationForCandidate(R); 8687 8688 // Put candidates without locations (e.g. builtins) at the end. 8689 if (LLoc.isInvalid()) return false; 8690 if (RLoc.isInvalid()) return true; 8691 8692 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8693 } 8694}; 8695 8696/// CompleteNonViableCandidate - Normally, overload resolution only 8697/// computes up to the first. Produces the FixIt set if possible. 8698void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8699 llvm::ArrayRef<Expr *> Args) { 8700 assert(!Cand->Viable); 8701 8702 // Don't do anything on failures other than bad conversion. 8703 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8704 8705 // We only want the FixIts if all the arguments can be corrected. 8706 bool Unfixable = false; 8707 // Use a implicit copy initialization to check conversion fixes. 8708 Cand->Fix.setConversionChecker(TryCopyInitialization); 8709 8710 // Skip forward to the first bad conversion. 8711 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8712 unsigned ConvCount = Cand->NumConversions; 8713 while (true) { 8714 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8715 ConvIdx++; 8716 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8717 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8718 break; 8719 } 8720 } 8721 8722 if (ConvIdx == ConvCount) 8723 return; 8724 8725 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8726 "remaining conversion is initialized?"); 8727 8728 // FIXME: this should probably be preserved from the overload 8729 // operation somehow. 8730 bool SuppressUserConversions = false; 8731 8732 const FunctionProtoType* Proto; 8733 unsigned ArgIdx = ConvIdx; 8734 8735 if (Cand->IsSurrogate) { 8736 QualType ConvType 8737 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8738 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8739 ConvType = ConvPtrType->getPointeeType(); 8740 Proto = ConvType->getAs<FunctionProtoType>(); 8741 ArgIdx--; 8742 } else if (Cand->Function) { 8743 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8744 if (isa<CXXMethodDecl>(Cand->Function) && 8745 !isa<CXXConstructorDecl>(Cand->Function)) 8746 ArgIdx--; 8747 } else { 8748 // Builtin binary operator with a bad first conversion. 8749 assert(ConvCount <= 3); 8750 for (; ConvIdx != ConvCount; ++ConvIdx) 8751 Cand->Conversions[ConvIdx] 8752 = TryCopyInitialization(S, Args[ConvIdx], 8753 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8754 SuppressUserConversions, 8755 /*InOverloadResolution*/ true, 8756 /*AllowObjCWritebackConversion=*/ 8757 S.getLangOpts().ObjCAutoRefCount); 8758 return; 8759 } 8760 8761 // Fill in the rest of the conversions. 8762 unsigned NumArgsInProto = Proto->getNumArgs(); 8763 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8764 if (ArgIdx < NumArgsInProto) { 8765 Cand->Conversions[ConvIdx] 8766 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8767 SuppressUserConversions, 8768 /*InOverloadResolution=*/true, 8769 /*AllowObjCWritebackConversion=*/ 8770 S.getLangOpts().ObjCAutoRefCount); 8771 // Store the FixIt in the candidate if it exists. 8772 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8773 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8774 } 8775 else 8776 Cand->Conversions[ConvIdx].setEllipsis(); 8777 } 8778} 8779 8780} // end anonymous namespace 8781 8782/// PrintOverloadCandidates - When overload resolution fails, prints 8783/// diagnostic messages containing the candidates in the candidate 8784/// set. 8785void OverloadCandidateSet::NoteCandidates(Sema &S, 8786 OverloadCandidateDisplayKind OCD, 8787 llvm::ArrayRef<Expr *> Args, 8788 const char *Opc, 8789 SourceLocation OpLoc) { 8790 // Sort the candidates by viability and position. Sorting directly would 8791 // be prohibitive, so we make a set of pointers and sort those. 8792 SmallVector<OverloadCandidate*, 32> Cands; 8793 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8794 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8795 if (Cand->Viable) 8796 Cands.push_back(Cand); 8797 else if (OCD == OCD_AllCandidates) { 8798 CompleteNonViableCandidate(S, Cand, Args); 8799 if (Cand->Function || Cand->IsSurrogate) 8800 Cands.push_back(Cand); 8801 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8802 // want to list every possible builtin candidate. 8803 } 8804 } 8805 8806 std::sort(Cands.begin(), Cands.end(), 8807 CompareOverloadCandidatesForDisplay(S)); 8808 8809 bool ReportedAmbiguousConversions = false; 8810 8811 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8812 const DiagnosticsEngine::OverloadsShown ShowOverloads = 8813 S.Diags.getShowOverloads(); 8814 unsigned CandsShown = 0; 8815 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8816 OverloadCandidate *Cand = *I; 8817 8818 // Set an arbitrary limit on the number of candidate functions we'll spam 8819 // the user with. FIXME: This limit should depend on details of the 8820 // candidate list. 8821 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) { 8822 break; 8823 } 8824 ++CandsShown; 8825 8826 if (Cand->Function) 8827 NoteFunctionCandidate(S, Cand, Args.size()); 8828 else if (Cand->IsSurrogate) 8829 NoteSurrogateCandidate(S, Cand); 8830 else { 8831 assert(Cand->Viable && 8832 "Non-viable built-in candidates are not added to Cands."); 8833 // Generally we only see ambiguities including viable builtin 8834 // operators if overload resolution got screwed up by an 8835 // ambiguous user-defined conversion. 8836 // 8837 // FIXME: It's quite possible for different conversions to see 8838 // different ambiguities, though. 8839 if (!ReportedAmbiguousConversions) { 8840 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8841 ReportedAmbiguousConversions = true; 8842 } 8843 8844 // If this is a viable builtin, print it. 8845 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8846 } 8847 } 8848 8849 if (I != E) 8850 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8851} 8852 8853// [PossiblyAFunctionType] --> [Return] 8854// NonFunctionType --> NonFunctionType 8855// R (A) --> R(A) 8856// R (*)(A) --> R (A) 8857// R (&)(A) --> R (A) 8858// R (S::*)(A) --> R (A) 8859QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8860 QualType Ret = PossiblyAFunctionType; 8861 if (const PointerType *ToTypePtr = 8862 PossiblyAFunctionType->getAs<PointerType>()) 8863 Ret = ToTypePtr->getPointeeType(); 8864 else if (const ReferenceType *ToTypeRef = 8865 PossiblyAFunctionType->getAs<ReferenceType>()) 8866 Ret = ToTypeRef->getPointeeType(); 8867 else if (const MemberPointerType *MemTypePtr = 8868 PossiblyAFunctionType->getAs<MemberPointerType>()) 8869 Ret = MemTypePtr->getPointeeType(); 8870 Ret = 8871 Context.getCanonicalType(Ret).getUnqualifiedType(); 8872 return Ret; 8873} 8874 8875// A helper class to help with address of function resolution 8876// - allows us to avoid passing around all those ugly parameters 8877class AddressOfFunctionResolver 8878{ 8879 Sema& S; 8880 Expr* SourceExpr; 8881 const QualType& TargetType; 8882 QualType TargetFunctionType; // Extracted function type from target type 8883 8884 bool Complain; 8885 //DeclAccessPair& ResultFunctionAccessPair; 8886 ASTContext& Context; 8887 8888 bool TargetTypeIsNonStaticMemberFunction; 8889 bool FoundNonTemplateFunction; 8890 8891 OverloadExpr::FindResult OvlExprInfo; 8892 OverloadExpr *OvlExpr; 8893 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8894 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8895 8896public: 8897 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8898 const QualType& TargetType, bool Complain) 8899 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8900 Complain(Complain), Context(S.getASTContext()), 8901 TargetTypeIsNonStaticMemberFunction( 8902 !!TargetType->getAs<MemberPointerType>()), 8903 FoundNonTemplateFunction(false), 8904 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8905 OvlExpr(OvlExprInfo.Expression) 8906 { 8907 ExtractUnqualifiedFunctionTypeFromTargetType(); 8908 8909 if (!TargetFunctionType->isFunctionType()) { 8910 if (OvlExpr->hasExplicitTemplateArgs()) { 8911 DeclAccessPair dap; 8912 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8913 OvlExpr, false, &dap) ) { 8914 8915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8916 if (!Method->isStatic()) { 8917 // If the target type is a non-function type and the function 8918 // found is a non-static member function, pretend as if that was 8919 // the target, it's the only possible type to end up with. 8920 TargetTypeIsNonStaticMemberFunction = true; 8921 8922 // And skip adding the function if its not in the proper form. 8923 // We'll diagnose this due to an empty set of functions. 8924 if (!OvlExprInfo.HasFormOfMemberPointer) 8925 return; 8926 } 8927 } 8928 8929 Matches.push_back(std::make_pair(dap,Fn)); 8930 } 8931 } 8932 return; 8933 } 8934 8935 if (OvlExpr->hasExplicitTemplateArgs()) 8936 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8937 8938 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8939 // C++ [over.over]p4: 8940 // If more than one function is selected, [...] 8941 if (Matches.size() > 1) { 8942 if (FoundNonTemplateFunction) 8943 EliminateAllTemplateMatches(); 8944 else 8945 EliminateAllExceptMostSpecializedTemplate(); 8946 } 8947 } 8948 } 8949 8950private: 8951 bool isTargetTypeAFunction() const { 8952 return TargetFunctionType->isFunctionType(); 8953 } 8954 8955 // [ToType] [Return] 8956 8957 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8958 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8959 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8960 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8961 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8962 } 8963 8964 // return true if any matching specializations were found 8965 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8966 const DeclAccessPair& CurAccessFunPair) { 8967 if (CXXMethodDecl *Method 8968 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8969 // Skip non-static function templates when converting to pointer, and 8970 // static when converting to member pointer. 8971 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 8972 return false; 8973 } 8974 else if (TargetTypeIsNonStaticMemberFunction) 8975 return false; 8976 8977 // C++ [over.over]p2: 8978 // If the name is a function template, template argument deduction is 8979 // done (14.8.2.2), and if the argument deduction succeeds, the 8980 // resulting template argument list is used to generate a single 8981 // function template specialization, which is added to the set of 8982 // overloaded functions considered. 8983 FunctionDecl *Specialization = 0; 8984 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 8985 if (Sema::TemplateDeductionResult Result 8986 = S.DeduceTemplateArguments(FunctionTemplate, 8987 &OvlExplicitTemplateArgs, 8988 TargetFunctionType, Specialization, 8989 Info)) { 8990 // FIXME: make a note of the failed deduction for diagnostics. 8991 (void)Result; 8992 return false; 8993 } 8994 8995 // Template argument deduction ensures that we have an exact match. 8996 // This function template specicalization works. 8997 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 8998 assert(TargetFunctionType 8999 == Context.getCanonicalType(Specialization->getType())); 9000 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9001 return true; 9002 } 9003 9004 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9005 const DeclAccessPair& CurAccessFunPair) { 9006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9007 // Skip non-static functions when converting to pointer, and static 9008 // when converting to member pointer. 9009 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9010 return false; 9011 } 9012 else if (TargetTypeIsNonStaticMemberFunction) 9013 return false; 9014 9015 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9016 if (S.getLangOpts().CUDA) 9017 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9018 if (S.CheckCUDATarget(Caller, FunDecl)) 9019 return false; 9020 9021 QualType ResultTy; 9022 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9023 FunDecl->getType()) || 9024 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9025 ResultTy)) { 9026 Matches.push_back(std::make_pair(CurAccessFunPair, 9027 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9028 FoundNonTemplateFunction = true; 9029 return true; 9030 } 9031 } 9032 9033 return false; 9034 } 9035 9036 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9037 bool Ret = false; 9038 9039 // If the overload expression doesn't have the form of a pointer to 9040 // member, don't try to convert it to a pointer-to-member type. 9041 if (IsInvalidFormOfPointerToMemberFunction()) 9042 return false; 9043 9044 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9045 E = OvlExpr->decls_end(); 9046 I != E; ++I) { 9047 // Look through any using declarations to find the underlying function. 9048 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9049 9050 // C++ [over.over]p3: 9051 // Non-member functions and static member functions match 9052 // targets of type "pointer-to-function" or "reference-to-function." 9053 // Nonstatic member functions match targets of 9054 // type "pointer-to-member-function." 9055 // Note that according to DR 247, the containing class does not matter. 9056 if (FunctionTemplateDecl *FunctionTemplate 9057 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9058 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9059 Ret = true; 9060 } 9061 // If we have explicit template arguments supplied, skip non-templates. 9062 else if (!OvlExpr->hasExplicitTemplateArgs() && 9063 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9064 Ret = true; 9065 } 9066 assert(Ret || Matches.empty()); 9067 return Ret; 9068 } 9069 9070 void EliminateAllExceptMostSpecializedTemplate() { 9071 // [...] and any given function template specialization F1 is 9072 // eliminated if the set contains a second function template 9073 // specialization whose function template is more specialized 9074 // than the function template of F1 according to the partial 9075 // ordering rules of 14.5.5.2. 9076 9077 // The algorithm specified above is quadratic. We instead use a 9078 // two-pass algorithm (similar to the one used to identify the 9079 // best viable function in an overload set) that identifies the 9080 // best function template (if it exists). 9081 9082 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9083 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9084 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9085 9086 UnresolvedSetIterator Result = 9087 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9088 TPOC_Other, 0, SourceExpr->getLocStart(), 9089 S.PDiag(), 9090 S.PDiag(diag::err_addr_ovl_ambiguous) 9091 << Matches[0].second->getDeclName(), 9092 S.PDiag(diag::note_ovl_candidate) 9093 << (unsigned) oc_function_template, 9094 Complain, TargetFunctionType); 9095 9096 if (Result != MatchesCopy.end()) { 9097 // Make it the first and only element 9098 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9099 Matches[0].second = cast<FunctionDecl>(*Result); 9100 Matches.resize(1); 9101 } 9102 } 9103 9104 void EliminateAllTemplateMatches() { 9105 // [...] any function template specializations in the set are 9106 // eliminated if the set also contains a non-template function, [...] 9107 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9108 if (Matches[I].second->getPrimaryTemplate() == 0) 9109 ++I; 9110 else { 9111 Matches[I] = Matches[--N]; 9112 Matches.set_size(N); 9113 } 9114 } 9115 } 9116 9117public: 9118 void ComplainNoMatchesFound() const { 9119 assert(Matches.empty()); 9120 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9121 << OvlExpr->getName() << TargetFunctionType 9122 << OvlExpr->getSourceRange(); 9123 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9124 } 9125 9126 bool IsInvalidFormOfPointerToMemberFunction() const { 9127 return TargetTypeIsNonStaticMemberFunction && 9128 !OvlExprInfo.HasFormOfMemberPointer; 9129 } 9130 9131 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9132 // TODO: Should we condition this on whether any functions might 9133 // have matched, or is it more appropriate to do that in callers? 9134 // TODO: a fixit wouldn't hurt. 9135 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9136 << TargetType << OvlExpr->getSourceRange(); 9137 } 9138 9139 void ComplainOfInvalidConversion() const { 9140 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9141 << OvlExpr->getName() << TargetType; 9142 } 9143 9144 void ComplainMultipleMatchesFound() const { 9145 assert(Matches.size() > 1); 9146 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9147 << OvlExpr->getName() 9148 << OvlExpr->getSourceRange(); 9149 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9150 } 9151 9152 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9153 9154 int getNumMatches() const { return Matches.size(); } 9155 9156 FunctionDecl* getMatchingFunctionDecl() const { 9157 if (Matches.size() != 1) return 0; 9158 return Matches[0].second; 9159 } 9160 9161 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9162 if (Matches.size() != 1) return 0; 9163 return &Matches[0].first; 9164 } 9165}; 9166 9167/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9168/// an overloaded function (C++ [over.over]), where @p From is an 9169/// expression with overloaded function type and @p ToType is the type 9170/// we're trying to resolve to. For example: 9171/// 9172/// @code 9173/// int f(double); 9174/// int f(int); 9175/// 9176/// int (*pfd)(double) = f; // selects f(double) 9177/// @endcode 9178/// 9179/// This routine returns the resulting FunctionDecl if it could be 9180/// resolved, and NULL otherwise. When @p Complain is true, this 9181/// routine will emit diagnostics if there is an error. 9182FunctionDecl * 9183Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9184 QualType TargetType, 9185 bool Complain, 9186 DeclAccessPair &FoundResult, 9187 bool *pHadMultipleCandidates) { 9188 assert(AddressOfExpr->getType() == Context.OverloadTy); 9189 9190 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9191 Complain); 9192 int NumMatches = Resolver.getNumMatches(); 9193 FunctionDecl* Fn = 0; 9194 if (NumMatches == 0 && Complain) { 9195 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9196 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9197 else 9198 Resolver.ComplainNoMatchesFound(); 9199 } 9200 else if (NumMatches > 1 && Complain) 9201 Resolver.ComplainMultipleMatchesFound(); 9202 else if (NumMatches == 1) { 9203 Fn = Resolver.getMatchingFunctionDecl(); 9204 assert(Fn); 9205 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9206 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn); 9207 if (Complain) 9208 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9209 } 9210 9211 if (pHadMultipleCandidates) 9212 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9213 return Fn; 9214} 9215 9216/// \brief Given an expression that refers to an overloaded function, try to 9217/// resolve that overloaded function expression down to a single function. 9218/// 9219/// This routine can only resolve template-ids that refer to a single function 9220/// template, where that template-id refers to a single template whose template 9221/// arguments are either provided by the template-id or have defaults, 9222/// as described in C++0x [temp.arg.explicit]p3. 9223FunctionDecl * 9224Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9225 bool Complain, 9226 DeclAccessPair *FoundResult) { 9227 // C++ [over.over]p1: 9228 // [...] [Note: any redundant set of parentheses surrounding the 9229 // overloaded function name is ignored (5.1). ] 9230 // C++ [over.over]p1: 9231 // [...] The overloaded function name can be preceded by the & 9232 // operator. 9233 9234 // If we didn't actually find any template-ids, we're done. 9235 if (!ovl->hasExplicitTemplateArgs()) 9236 return 0; 9237 9238 TemplateArgumentListInfo ExplicitTemplateArgs; 9239 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9240 9241 // Look through all of the overloaded functions, searching for one 9242 // whose type matches exactly. 9243 FunctionDecl *Matched = 0; 9244 for (UnresolvedSetIterator I = ovl->decls_begin(), 9245 E = ovl->decls_end(); I != E; ++I) { 9246 // C++0x [temp.arg.explicit]p3: 9247 // [...] In contexts where deduction is done and fails, or in contexts 9248 // where deduction is not done, if a template argument list is 9249 // specified and it, along with any default template arguments, 9250 // identifies a single function template specialization, then the 9251 // template-id is an lvalue for the function template specialization. 9252 FunctionTemplateDecl *FunctionTemplate 9253 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9254 9255 // C++ [over.over]p2: 9256 // If the name is a function template, template argument deduction is 9257 // done (14.8.2.2), and if the argument deduction succeeds, the 9258 // resulting template argument list is used to generate a single 9259 // function template specialization, which is added to the set of 9260 // overloaded functions considered. 9261 FunctionDecl *Specialization = 0; 9262 TemplateDeductionInfo Info(Context, ovl->getNameLoc()); 9263 if (TemplateDeductionResult Result 9264 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9265 Specialization, Info)) { 9266 // FIXME: make a note of the failed deduction for diagnostics. 9267 (void)Result; 9268 continue; 9269 } 9270 9271 assert(Specialization && "no specialization and no error?"); 9272 9273 // Multiple matches; we can't resolve to a single declaration. 9274 if (Matched) { 9275 if (Complain) { 9276 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9277 << ovl->getName(); 9278 NoteAllOverloadCandidates(ovl); 9279 } 9280 return 0; 9281 } 9282 9283 Matched = Specialization; 9284 if (FoundResult) *FoundResult = I.getPair(); 9285 } 9286 9287 return Matched; 9288} 9289 9290 9291 9292 9293// Resolve and fix an overloaded expression that can be resolved 9294// because it identifies a single function template specialization. 9295// 9296// Last three arguments should only be supplied if Complain = true 9297// 9298// Return true if it was logically possible to so resolve the 9299// expression, regardless of whether or not it succeeded. Always 9300// returns true if 'complain' is set. 9301bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9302 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9303 bool complain, const SourceRange& OpRangeForComplaining, 9304 QualType DestTypeForComplaining, 9305 unsigned DiagIDForComplaining) { 9306 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9307 9308 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9309 9310 DeclAccessPair found; 9311 ExprResult SingleFunctionExpression; 9312 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9313 ovl.Expression, /*complain*/ false, &found)) { 9314 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9315 SrcExpr = ExprError(); 9316 return true; 9317 } 9318 9319 // It is only correct to resolve to an instance method if we're 9320 // resolving a form that's permitted to be a pointer to member. 9321 // Otherwise we'll end up making a bound member expression, which 9322 // is illegal in all the contexts we resolve like this. 9323 if (!ovl.HasFormOfMemberPointer && 9324 isa<CXXMethodDecl>(fn) && 9325 cast<CXXMethodDecl>(fn)->isInstance()) { 9326 if (!complain) return false; 9327 9328 Diag(ovl.Expression->getExprLoc(), 9329 diag::err_bound_member_function) 9330 << 0 << ovl.Expression->getSourceRange(); 9331 9332 // TODO: I believe we only end up here if there's a mix of 9333 // static and non-static candidates (otherwise the expression 9334 // would have 'bound member' type, not 'overload' type). 9335 // Ideally we would note which candidate was chosen and why 9336 // the static candidates were rejected. 9337 SrcExpr = ExprError(); 9338 return true; 9339 } 9340 9341 // Fix the expresion to refer to 'fn'. 9342 SingleFunctionExpression = 9343 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9344 9345 // If desired, do function-to-pointer decay. 9346 if (doFunctionPointerConverion) { 9347 SingleFunctionExpression = 9348 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9349 if (SingleFunctionExpression.isInvalid()) { 9350 SrcExpr = ExprError(); 9351 return true; 9352 } 9353 } 9354 } 9355 9356 if (!SingleFunctionExpression.isUsable()) { 9357 if (complain) { 9358 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9359 << ovl.Expression->getName() 9360 << DestTypeForComplaining 9361 << OpRangeForComplaining 9362 << ovl.Expression->getQualifierLoc().getSourceRange(); 9363 NoteAllOverloadCandidates(SrcExpr.get()); 9364 9365 SrcExpr = ExprError(); 9366 return true; 9367 } 9368 9369 return false; 9370 } 9371 9372 SrcExpr = SingleFunctionExpression; 9373 return true; 9374} 9375 9376/// \brief Add a single candidate to the overload set. 9377static void AddOverloadedCallCandidate(Sema &S, 9378 DeclAccessPair FoundDecl, 9379 TemplateArgumentListInfo *ExplicitTemplateArgs, 9380 llvm::ArrayRef<Expr *> Args, 9381 OverloadCandidateSet &CandidateSet, 9382 bool PartialOverloading, 9383 bool KnownValid) { 9384 NamedDecl *Callee = FoundDecl.getDecl(); 9385 if (isa<UsingShadowDecl>(Callee)) 9386 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9387 9388 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9389 if (ExplicitTemplateArgs) { 9390 assert(!KnownValid && "Explicit template arguments?"); 9391 return; 9392 } 9393 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9394 PartialOverloading); 9395 return; 9396 } 9397 9398 if (FunctionTemplateDecl *FuncTemplate 9399 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9400 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9401 ExplicitTemplateArgs, Args, CandidateSet); 9402 return; 9403 } 9404 9405 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9406} 9407 9408/// \brief Add the overload candidates named by callee and/or found by argument 9409/// dependent lookup to the given overload set. 9410void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9411 llvm::ArrayRef<Expr *> Args, 9412 OverloadCandidateSet &CandidateSet, 9413 bool PartialOverloading) { 9414 9415#ifndef NDEBUG 9416 // Verify that ArgumentDependentLookup is consistent with the rules 9417 // in C++0x [basic.lookup.argdep]p3: 9418 // 9419 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9420 // and let Y be the lookup set produced by argument dependent 9421 // lookup (defined as follows). If X contains 9422 // 9423 // -- a declaration of a class member, or 9424 // 9425 // -- a block-scope function declaration that is not a 9426 // using-declaration, or 9427 // 9428 // -- a declaration that is neither a function or a function 9429 // template 9430 // 9431 // then Y is empty. 9432 9433 if (ULE->requiresADL()) { 9434 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9435 E = ULE->decls_end(); I != E; ++I) { 9436 assert(!(*I)->getDeclContext()->isRecord()); 9437 assert(isa<UsingShadowDecl>(*I) || 9438 !(*I)->getDeclContext()->isFunctionOrMethod()); 9439 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9440 } 9441 } 9442#endif 9443 9444 // It would be nice to avoid this copy. 9445 TemplateArgumentListInfo TABuffer; 9446 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9447 if (ULE->hasExplicitTemplateArgs()) { 9448 ULE->copyTemplateArgumentsInto(TABuffer); 9449 ExplicitTemplateArgs = &TABuffer; 9450 } 9451 9452 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9453 E = ULE->decls_end(); I != E; ++I) 9454 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9455 CandidateSet, PartialOverloading, 9456 /*KnownValid*/ true); 9457 9458 if (ULE->requiresADL()) 9459 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9460 ULE->getExprLoc(), 9461 Args, ExplicitTemplateArgs, 9462 CandidateSet, PartialOverloading, 9463 ULE->isStdAssociatedNamespace()); 9464} 9465 9466/// Attempt to recover from an ill-formed use of a non-dependent name in a 9467/// template, where the non-dependent name was declared after the template 9468/// was defined. This is common in code written for a compilers which do not 9469/// correctly implement two-stage name lookup. 9470/// 9471/// Returns true if a viable candidate was found and a diagnostic was issued. 9472static bool 9473DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9474 const CXXScopeSpec &SS, LookupResult &R, 9475 TemplateArgumentListInfo *ExplicitTemplateArgs, 9476 llvm::ArrayRef<Expr *> Args) { 9477 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9478 return false; 9479 9480 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9481 if (DC->isTransparentContext()) 9482 continue; 9483 9484 SemaRef.LookupQualifiedName(R, DC); 9485 9486 if (!R.empty()) { 9487 R.suppressDiagnostics(); 9488 9489 if (isa<CXXRecordDecl>(DC)) { 9490 // Don't diagnose names we find in classes; we get much better 9491 // diagnostics for these from DiagnoseEmptyLookup. 9492 R.clear(); 9493 return false; 9494 } 9495 9496 OverloadCandidateSet Candidates(FnLoc); 9497 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9498 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9499 ExplicitTemplateArgs, Args, 9500 Candidates, false, /*KnownValid*/ false); 9501 9502 OverloadCandidateSet::iterator Best; 9503 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9504 // No viable functions. Don't bother the user with notes for functions 9505 // which don't work and shouldn't be found anyway. 9506 R.clear(); 9507 return false; 9508 } 9509 9510 // Find the namespaces where ADL would have looked, and suggest 9511 // declaring the function there instead. 9512 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9513 Sema::AssociatedClassSet AssociatedClasses; 9514 SemaRef.FindAssociatedClassesAndNamespaces(Args, 9515 AssociatedNamespaces, 9516 AssociatedClasses); 9517 // Never suggest declaring a function within namespace 'std'. 9518 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9519 if (DeclContext *Std = SemaRef.getStdNamespace()) { 9520 for (Sema::AssociatedNamespaceSet::iterator 9521 it = AssociatedNamespaces.begin(), 9522 end = AssociatedNamespaces.end(); it != end; ++it) { 9523 if (!Std->Encloses(*it)) 9524 SuggestedNamespaces.insert(*it); 9525 } 9526 } else { 9527 // Lacking the 'std::' namespace, use all of the associated namespaces. 9528 SuggestedNamespaces = AssociatedNamespaces; 9529 } 9530 9531 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9532 << R.getLookupName(); 9533 if (SuggestedNamespaces.empty()) { 9534 SemaRef.Diag(Best->Function->getLocation(), 9535 diag::note_not_found_by_two_phase_lookup) 9536 << R.getLookupName() << 0; 9537 } else if (SuggestedNamespaces.size() == 1) { 9538 SemaRef.Diag(Best->Function->getLocation(), 9539 diag::note_not_found_by_two_phase_lookup) 9540 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9541 } else { 9542 // FIXME: It would be useful to list the associated namespaces here, 9543 // but the diagnostics infrastructure doesn't provide a way to produce 9544 // a localized representation of a list of items. 9545 SemaRef.Diag(Best->Function->getLocation(), 9546 diag::note_not_found_by_two_phase_lookup) 9547 << R.getLookupName() << 2; 9548 } 9549 9550 // Try to recover by calling this function. 9551 return true; 9552 } 9553 9554 R.clear(); 9555 } 9556 9557 return false; 9558} 9559 9560/// Attempt to recover from ill-formed use of a non-dependent operator in a 9561/// template, where the non-dependent operator was declared after the template 9562/// was defined. 9563/// 9564/// Returns true if a viable candidate was found and a diagnostic was issued. 9565static bool 9566DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9567 SourceLocation OpLoc, 9568 llvm::ArrayRef<Expr *> Args) { 9569 DeclarationName OpName = 9570 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9571 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9572 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9573 /*ExplicitTemplateArgs=*/0, Args); 9574} 9575 9576namespace { 9577// Callback to limit the allowed keywords and to only accept typo corrections 9578// that are keywords or whose decls refer to functions (or template functions) 9579// that accept the given number of arguments. 9580class RecoveryCallCCC : public CorrectionCandidateCallback { 9581 public: 9582 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9583 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9584 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9585 WantRemainingKeywords = false; 9586 } 9587 9588 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9589 if (!candidate.getCorrectionDecl()) 9590 return candidate.isKeyword(); 9591 9592 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9593 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9594 FunctionDecl *FD = 0; 9595 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9596 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9597 FD = FTD->getTemplatedDecl(); 9598 if (!HasExplicitTemplateArgs && !FD) { 9599 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9600 // If the Decl is neither a function nor a template function, 9601 // determine if it is a pointer or reference to a function. If so, 9602 // check against the number of arguments expected for the pointee. 9603 QualType ValType = cast<ValueDecl>(ND)->getType(); 9604 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9605 ValType = ValType->getPointeeType(); 9606 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9607 if (FPT->getNumArgs() == NumArgs) 9608 return true; 9609 } 9610 } 9611 if (FD && FD->getNumParams() >= NumArgs && 9612 FD->getMinRequiredArguments() <= NumArgs) 9613 return true; 9614 } 9615 return false; 9616 } 9617 9618 private: 9619 unsigned NumArgs; 9620 bool HasExplicitTemplateArgs; 9621}; 9622 9623// Callback that effectively disabled typo correction 9624class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9625 public: 9626 NoTypoCorrectionCCC() { 9627 WantTypeSpecifiers = false; 9628 WantExpressionKeywords = false; 9629 WantCXXNamedCasts = false; 9630 WantRemainingKeywords = false; 9631 } 9632 9633 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9634 return false; 9635 } 9636}; 9637} 9638 9639/// Attempts to recover from a call where no functions were found. 9640/// 9641/// Returns true if new candidates were found. 9642static ExprResult 9643BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9644 UnresolvedLookupExpr *ULE, 9645 SourceLocation LParenLoc, 9646 llvm::MutableArrayRef<Expr *> Args, 9647 SourceLocation RParenLoc, 9648 bool EmptyLookup, bool AllowTypoCorrection) { 9649 9650 CXXScopeSpec SS; 9651 SS.Adopt(ULE->getQualifierLoc()); 9652 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9653 9654 TemplateArgumentListInfo TABuffer; 9655 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9656 if (ULE->hasExplicitTemplateArgs()) { 9657 ULE->copyTemplateArgumentsInto(TABuffer); 9658 ExplicitTemplateArgs = &TABuffer; 9659 } 9660 9661 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9662 Sema::LookupOrdinaryName); 9663 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9664 NoTypoCorrectionCCC RejectAll; 9665 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9666 (CorrectionCandidateCallback*)&Validator : 9667 (CorrectionCandidateCallback*)&RejectAll; 9668 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9669 ExplicitTemplateArgs, Args) && 9670 (!EmptyLookup || 9671 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9672 ExplicitTemplateArgs, Args))) 9673 return ExprError(); 9674 9675 assert(!R.empty() && "lookup results empty despite recovery"); 9676 9677 // Build an implicit member call if appropriate. Just drop the 9678 // casts and such from the call, we don't really care. 9679 ExprResult NewFn = ExprError(); 9680 if ((*R.begin())->isCXXClassMember()) 9681 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9682 R, ExplicitTemplateArgs); 9683 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9684 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9685 ExplicitTemplateArgs); 9686 else 9687 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9688 9689 if (NewFn.isInvalid()) 9690 return ExprError(); 9691 9692 // This shouldn't cause an infinite loop because we're giving it 9693 // an expression with viable lookup results, which should never 9694 // end up here. 9695 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9696 MultiExprArg(Args.data(), Args.size()), 9697 RParenLoc); 9698} 9699 9700/// ResolveOverloadedCallFn - Given the call expression that calls Fn 9701/// (which eventually refers to the declaration Func) and the call 9702/// arguments Args/NumArgs, attempt to resolve the function call down 9703/// to a specific function. If overload resolution succeeds, returns 9704/// the function declaration produced by overload 9705/// resolution. Otherwise, emits diagnostics, deletes all of the 9706/// arguments and Fn, and returns NULL. 9707ExprResult 9708Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 9709 SourceLocation LParenLoc, 9710 Expr **Args, unsigned NumArgs, 9711 SourceLocation RParenLoc, 9712 Expr *ExecConfig, 9713 bool AllowTypoCorrection) { 9714#ifndef NDEBUG 9715 if (ULE->requiresADL()) { 9716 // To do ADL, we must have found an unqualified name. 9717 assert(!ULE->getQualifier() && "qualified name with ADL"); 9718 9719 // We don't perform ADL for implicit declarations of builtins. 9720 // Verify that this was correctly set up. 9721 FunctionDecl *F; 9722 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9723 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9724 F->getBuiltinID() && F->isImplicit()) 9725 llvm_unreachable("performing ADL for builtin"); 9726 9727 // We don't perform ADL in C. 9728 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9729 } else 9730 assert(!ULE->isStdAssociatedNamespace() && 9731 "std is associated namespace but not doing ADL"); 9732#endif 9733 9734 UnbridgedCastsSet UnbridgedCasts; 9735 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 9736 return ExprError(); 9737 9738 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9739 9740 // Add the functions denoted by the callee to the set of candidate 9741 // functions, including those from argument-dependent lookup. 9742 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9743 CandidateSet); 9744 9745 // If we found nothing, try to recover. 9746 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9747 // out if it fails. 9748 if (CandidateSet.empty()) { 9749 // In Microsoft mode, if we are inside a template class member function then 9750 // create a type dependent CallExpr. The goal is to postpone name lookup 9751 // to instantiation time to be able to search into type dependent base 9752 // classes. 9753 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9754 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9755 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs, 9756 Context.DependentTy, VK_RValue, 9757 RParenLoc); 9758 CE->setTypeDependent(true); 9759 return Owned(CE); 9760 } 9761 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, 9762 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9763 RParenLoc, /*EmptyLookup=*/true, 9764 AllowTypoCorrection); 9765 } 9766 9767 UnbridgedCasts.restore(); 9768 9769 OverloadCandidateSet::iterator Best; 9770 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) { 9771 case OR_Success: { 9772 FunctionDecl *FDecl = Best->Function; 9773 MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9774 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 9775 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9776 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 9777 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc, 9778 ExecConfig); 9779 } 9780 9781 case OR_No_Viable_Function: { 9782 // Try to recover by looking for viable functions which the user might 9783 // have meant to call. 9784 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, 9785 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9786 RParenLoc, 9787 /*EmptyLookup=*/false, 9788 AllowTypoCorrection); 9789 if (!Recovery.isInvalid()) 9790 return Recovery; 9791 9792 Diag(Fn->getLocStart(), 9793 diag::err_ovl_no_viable_function_in_call) 9794 << ULE->getName() << Fn->getSourceRange(); 9795 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 9796 llvm::makeArrayRef(Args, NumArgs)); 9797 break; 9798 } 9799 9800 case OR_Ambiguous: 9801 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9802 << ULE->getName() << Fn->getSourceRange(); 9803 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 9804 llvm::makeArrayRef(Args, NumArgs)); 9805 break; 9806 9807 case OR_Deleted: 9808 { 9809 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9810 << Best->Function->isDeleted() 9811 << ULE->getName() 9812 << getDeletedOrUnavailableSuffix(Best->Function) 9813 << Fn->getSourceRange(); 9814 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 9815 llvm::makeArrayRef(Args, NumArgs)); 9816 9817 // We emitted an error for the unvailable/deleted function call but keep 9818 // the call in the AST. 9819 FunctionDecl *FDecl = Best->Function; 9820 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 9821 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9822 RParenLoc, ExecConfig); 9823 } 9824 } 9825 9826 // Overload resolution failed. 9827 return ExprError(); 9828} 9829 9830static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9831 return Functions.size() > 1 || 9832 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9833} 9834 9835/// \brief Create a unary operation that may resolve to an overloaded 9836/// operator. 9837/// 9838/// \param OpLoc The location of the operator itself (e.g., '*'). 9839/// 9840/// \param OpcIn The UnaryOperator::Opcode that describes this 9841/// operator. 9842/// 9843/// \param Functions The set of non-member functions that will be 9844/// considered by overload resolution. The caller needs to build this 9845/// set based on the context using, e.g., 9846/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9847/// set should not contain any member functions; those will be added 9848/// by CreateOverloadedUnaryOp(). 9849/// 9850/// \param input The input argument. 9851ExprResult 9852Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9853 const UnresolvedSetImpl &Fns, 9854 Expr *Input) { 9855 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9856 9857 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9858 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9859 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9860 // TODO: provide better source location info. 9861 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9862 9863 if (checkPlaceholderForOverload(*this, Input)) 9864 return ExprError(); 9865 9866 Expr *Args[2] = { Input, 0 }; 9867 unsigned NumArgs = 1; 9868 9869 // For post-increment and post-decrement, add the implicit '0' as 9870 // the second argument, so that we know this is a post-increment or 9871 // post-decrement. 9872 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9873 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9874 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9875 SourceLocation()); 9876 NumArgs = 2; 9877 } 9878 9879 if (Input->isTypeDependent()) { 9880 if (Fns.empty()) 9881 return Owned(new (Context) UnaryOperator(Input, 9882 Opc, 9883 Context.DependentTy, 9884 VK_RValue, OK_Ordinary, 9885 OpLoc)); 9886 9887 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9888 UnresolvedLookupExpr *Fn 9889 = UnresolvedLookupExpr::Create(Context, NamingClass, 9890 NestedNameSpecifierLoc(), OpNameInfo, 9891 /*ADL*/ true, IsOverloaded(Fns), 9892 Fns.begin(), Fns.end()); 9893 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9894 &Args[0], NumArgs, 9895 Context.DependentTy, 9896 VK_RValue, 9897 OpLoc)); 9898 } 9899 9900 // Build an empty overload set. 9901 OverloadCandidateSet CandidateSet(OpLoc); 9902 9903 // Add the candidates from the given function set. 9904 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9905 false); 9906 9907 // Add operator candidates that are member functions. 9908 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9909 9910 // Add candidates from ADL. 9911 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 9912 OpLoc, llvm::makeArrayRef(Args, NumArgs), 9913 /*ExplicitTemplateArgs*/ 0, 9914 CandidateSet); 9915 9916 // Add builtin operator candidates. 9917 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9918 9919 bool HadMultipleCandidates = (CandidateSet.size() > 1); 9920 9921 // Perform overload resolution. 9922 OverloadCandidateSet::iterator Best; 9923 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 9924 case OR_Success: { 9925 // We found a built-in operator or an overloaded operator. 9926 FunctionDecl *FnDecl = Best->Function; 9927 9928 if (FnDecl) { 9929 // We matched an overloaded operator. Build a call to that 9930 // operator. 9931 9932 MarkFunctionReferenced(OpLoc, FnDecl); 9933 9934 // Convert the arguments. 9935 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 9936 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 9937 9938 ExprResult InputRes = 9939 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 9940 Best->FoundDecl, Method); 9941 if (InputRes.isInvalid()) 9942 return ExprError(); 9943 Input = InputRes.take(); 9944 } else { 9945 // Convert the arguments. 9946 ExprResult InputInit 9947 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9948 Context, 9949 FnDecl->getParamDecl(0)), 9950 SourceLocation(), 9951 Input); 9952 if (InputInit.isInvalid()) 9953 return ExprError(); 9954 Input = InputInit.take(); 9955 } 9956 9957 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 9958 9959 // Determine the result type. 9960 QualType ResultTy = FnDecl->getResultType(); 9961 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9962 ResultTy = ResultTy.getNonLValueExprType(Context); 9963 9964 // Build the actual expression node. 9965 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 9966 HadMultipleCandidates, OpLoc); 9967 if (FnExpr.isInvalid()) 9968 return ExprError(); 9969 9970 Args[0] = Input; 9971 CallExpr *TheCall = 9972 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 9973 Args, NumArgs, ResultTy, VK, OpLoc); 9974 9975 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 9976 FnDecl)) 9977 return ExprError(); 9978 9979 return MaybeBindToTemporary(TheCall); 9980 } else { 9981 // We matched a built-in operator. Convert the arguments, then 9982 // break out so that we will build the appropriate built-in 9983 // operator node. 9984 ExprResult InputRes = 9985 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 9986 Best->Conversions[0], AA_Passing); 9987 if (InputRes.isInvalid()) 9988 return ExprError(); 9989 Input = InputRes.take(); 9990 break; 9991 } 9992 } 9993 9994 case OR_No_Viable_Function: 9995 // This is an erroneous use of an operator which can be overloaded by 9996 // a non-member function. Check for non-member operators which were 9997 // defined too late to be candidates. 9998 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 9999 llvm::makeArrayRef(Args, NumArgs))) 10000 // FIXME: Recover by calling the found function. 10001 return ExprError(); 10002 10003 // No viable function; fall through to handling this as a 10004 // built-in operator, which will produce an error message for us. 10005 break; 10006 10007 case OR_Ambiguous: 10008 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10009 << UnaryOperator::getOpcodeStr(Opc) 10010 << Input->getType() 10011 << Input->getSourceRange(); 10012 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10013 llvm::makeArrayRef(Args, NumArgs), 10014 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10015 return ExprError(); 10016 10017 case OR_Deleted: 10018 Diag(OpLoc, diag::err_ovl_deleted_oper) 10019 << Best->Function->isDeleted() 10020 << UnaryOperator::getOpcodeStr(Opc) 10021 << getDeletedOrUnavailableSuffix(Best->Function) 10022 << Input->getSourceRange(); 10023 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10024 llvm::makeArrayRef(Args, NumArgs), 10025 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10026 return ExprError(); 10027 } 10028 10029 // Either we found no viable overloaded operator or we matched a 10030 // built-in operator. In either case, fall through to trying to 10031 // build a built-in operation. 10032 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10033} 10034 10035/// \brief Create a binary operation that may resolve to an overloaded 10036/// operator. 10037/// 10038/// \param OpLoc The location of the operator itself (e.g., '+'). 10039/// 10040/// \param OpcIn The BinaryOperator::Opcode that describes this 10041/// operator. 10042/// 10043/// \param Functions The set of non-member functions that will be 10044/// considered by overload resolution. The caller needs to build this 10045/// set based on the context using, e.g., 10046/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10047/// set should not contain any member functions; those will be added 10048/// by CreateOverloadedBinOp(). 10049/// 10050/// \param LHS Left-hand argument. 10051/// \param RHS Right-hand argument. 10052ExprResult 10053Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10054 unsigned OpcIn, 10055 const UnresolvedSetImpl &Fns, 10056 Expr *LHS, Expr *RHS) { 10057 Expr *Args[2] = { LHS, RHS }; 10058 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10059 10060 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10061 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10062 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10063 10064 // If either side is type-dependent, create an appropriate dependent 10065 // expression. 10066 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10067 if (Fns.empty()) { 10068 // If there are no functions to store, just build a dependent 10069 // BinaryOperator or CompoundAssignment. 10070 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10071 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10072 Context.DependentTy, 10073 VK_RValue, OK_Ordinary, 10074 OpLoc)); 10075 10076 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10077 Context.DependentTy, 10078 VK_LValue, 10079 OK_Ordinary, 10080 Context.DependentTy, 10081 Context.DependentTy, 10082 OpLoc)); 10083 } 10084 10085 // FIXME: save results of ADL from here? 10086 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10087 // TODO: provide better source location info in DNLoc component. 10088 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10089 UnresolvedLookupExpr *Fn 10090 = UnresolvedLookupExpr::Create(Context, NamingClass, 10091 NestedNameSpecifierLoc(), OpNameInfo, 10092 /*ADL*/ true, IsOverloaded(Fns), 10093 Fns.begin(), Fns.end()); 10094 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10095 Args, 2, 10096 Context.DependentTy, 10097 VK_RValue, 10098 OpLoc)); 10099 } 10100 10101 // Always do placeholder-like conversions on the RHS. 10102 if (checkPlaceholderForOverload(*this, Args[1])) 10103 return ExprError(); 10104 10105 // Do placeholder-like conversion on the LHS; note that we should 10106 // not get here with a PseudoObject LHS. 10107 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10108 if (checkPlaceholderForOverload(*this, Args[0])) 10109 return ExprError(); 10110 10111 // If this is the assignment operator, we only perform overload resolution 10112 // if the left-hand side is a class or enumeration type. This is actually 10113 // a hack. The standard requires that we do overload resolution between the 10114 // various built-in candidates, but as DR507 points out, this can lead to 10115 // problems. So we do it this way, which pretty much follows what GCC does. 10116 // Note that we go the traditional code path for compound assignment forms. 10117 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10118 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10119 10120 // If this is the .* operator, which is not overloadable, just 10121 // create a built-in binary operator. 10122 if (Opc == BO_PtrMemD) 10123 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10124 10125 // Build an empty overload set. 10126 OverloadCandidateSet CandidateSet(OpLoc); 10127 10128 // Add the candidates from the given function set. 10129 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10130 10131 // Add operator candidates that are member functions. 10132 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10133 10134 // Add candidates from ADL. 10135 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10136 OpLoc, Args, 10137 /*ExplicitTemplateArgs*/ 0, 10138 CandidateSet); 10139 10140 // Add builtin operator candidates. 10141 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10142 10143 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10144 10145 // Perform overload resolution. 10146 OverloadCandidateSet::iterator Best; 10147 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10148 case OR_Success: { 10149 // We found a built-in operator or an overloaded operator. 10150 FunctionDecl *FnDecl = Best->Function; 10151 10152 if (FnDecl) { 10153 // We matched an overloaded operator. Build a call to that 10154 // operator. 10155 10156 MarkFunctionReferenced(OpLoc, FnDecl); 10157 10158 // Convert the arguments. 10159 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10160 // Best->Access is only meaningful for class members. 10161 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10162 10163 ExprResult Arg1 = 10164 PerformCopyInitialization( 10165 InitializedEntity::InitializeParameter(Context, 10166 FnDecl->getParamDecl(0)), 10167 SourceLocation(), Owned(Args[1])); 10168 if (Arg1.isInvalid()) 10169 return ExprError(); 10170 10171 ExprResult Arg0 = 10172 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10173 Best->FoundDecl, Method); 10174 if (Arg0.isInvalid()) 10175 return ExprError(); 10176 Args[0] = Arg0.takeAs<Expr>(); 10177 Args[1] = RHS = Arg1.takeAs<Expr>(); 10178 } else { 10179 // Convert the arguments. 10180 ExprResult Arg0 = PerformCopyInitialization( 10181 InitializedEntity::InitializeParameter(Context, 10182 FnDecl->getParamDecl(0)), 10183 SourceLocation(), Owned(Args[0])); 10184 if (Arg0.isInvalid()) 10185 return ExprError(); 10186 10187 ExprResult Arg1 = 10188 PerformCopyInitialization( 10189 InitializedEntity::InitializeParameter(Context, 10190 FnDecl->getParamDecl(1)), 10191 SourceLocation(), Owned(Args[1])); 10192 if (Arg1.isInvalid()) 10193 return ExprError(); 10194 Args[0] = LHS = Arg0.takeAs<Expr>(); 10195 Args[1] = RHS = Arg1.takeAs<Expr>(); 10196 } 10197 10198 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10199 10200 // Determine the result type. 10201 QualType ResultTy = FnDecl->getResultType(); 10202 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10203 ResultTy = ResultTy.getNonLValueExprType(Context); 10204 10205 // Build the actual expression node. 10206 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10207 HadMultipleCandidates, OpLoc); 10208 if (FnExpr.isInvalid()) 10209 return ExprError(); 10210 10211 CXXOperatorCallExpr *TheCall = 10212 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10213 Args, 2, ResultTy, VK, OpLoc); 10214 10215 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10216 FnDecl)) 10217 return ExprError(); 10218 10219 return MaybeBindToTemporary(TheCall); 10220 } else { 10221 // We matched a built-in operator. Convert the arguments, then 10222 // break out so that we will build the appropriate built-in 10223 // operator node. 10224 ExprResult ArgsRes0 = 10225 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10226 Best->Conversions[0], AA_Passing); 10227 if (ArgsRes0.isInvalid()) 10228 return ExprError(); 10229 Args[0] = ArgsRes0.take(); 10230 10231 ExprResult ArgsRes1 = 10232 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10233 Best->Conversions[1], AA_Passing); 10234 if (ArgsRes1.isInvalid()) 10235 return ExprError(); 10236 Args[1] = ArgsRes1.take(); 10237 break; 10238 } 10239 } 10240 10241 case OR_No_Viable_Function: { 10242 // C++ [over.match.oper]p9: 10243 // If the operator is the operator , [...] and there are no 10244 // viable functions, then the operator is assumed to be the 10245 // built-in operator and interpreted according to clause 5. 10246 if (Opc == BO_Comma) 10247 break; 10248 10249 // For class as left operand for assignment or compound assigment 10250 // operator do not fall through to handling in built-in, but report that 10251 // no overloaded assignment operator found 10252 ExprResult Result = ExprError(); 10253 if (Args[0]->getType()->isRecordType() && 10254 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10255 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10256 << BinaryOperator::getOpcodeStr(Opc) 10257 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10258 } else { 10259 // This is an erroneous use of an operator which can be overloaded by 10260 // a non-member function. Check for non-member operators which were 10261 // defined too late to be candidates. 10262 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10263 // FIXME: Recover by calling the found function. 10264 return ExprError(); 10265 10266 // No viable function; try to create a built-in operation, which will 10267 // produce an error. Then, show the non-viable candidates. 10268 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10269 } 10270 assert(Result.isInvalid() && 10271 "C++ binary operator overloading is missing candidates!"); 10272 if (Result.isInvalid()) 10273 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10274 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10275 return move(Result); 10276 } 10277 10278 case OR_Ambiguous: 10279 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10280 << BinaryOperator::getOpcodeStr(Opc) 10281 << Args[0]->getType() << Args[1]->getType() 10282 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10283 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10284 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10285 return ExprError(); 10286 10287 case OR_Deleted: 10288 if (isImplicitlyDeleted(Best->Function)) { 10289 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10290 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10291 << getSpecialMember(Method) 10292 << BinaryOperator::getOpcodeStr(Opc) 10293 << getDeletedOrUnavailableSuffix(Best->Function); 10294 10295 if (getSpecialMember(Method) != CXXInvalid) { 10296 // The user probably meant to call this special member. Just 10297 // explain why it's deleted. 10298 NoteDeletedFunction(Method); 10299 return ExprError(); 10300 } 10301 } else { 10302 Diag(OpLoc, diag::err_ovl_deleted_oper) 10303 << Best->Function->isDeleted() 10304 << BinaryOperator::getOpcodeStr(Opc) 10305 << getDeletedOrUnavailableSuffix(Best->Function) 10306 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10307 } 10308 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10309 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10310 return ExprError(); 10311 } 10312 10313 // We matched a built-in operator; build it. 10314 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10315} 10316 10317ExprResult 10318Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10319 SourceLocation RLoc, 10320 Expr *Base, Expr *Idx) { 10321 Expr *Args[2] = { Base, Idx }; 10322 DeclarationName OpName = 10323 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10324 10325 // If either side is type-dependent, create an appropriate dependent 10326 // expression. 10327 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10328 10329 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10330 // CHECKME: no 'operator' keyword? 10331 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10332 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10333 UnresolvedLookupExpr *Fn 10334 = UnresolvedLookupExpr::Create(Context, NamingClass, 10335 NestedNameSpecifierLoc(), OpNameInfo, 10336 /*ADL*/ true, /*Overloaded*/ false, 10337 UnresolvedSetIterator(), 10338 UnresolvedSetIterator()); 10339 // Can't add any actual overloads yet 10340 10341 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10342 Args, 2, 10343 Context.DependentTy, 10344 VK_RValue, 10345 RLoc)); 10346 } 10347 10348 // Handle placeholders on both operands. 10349 if (checkPlaceholderForOverload(*this, Args[0])) 10350 return ExprError(); 10351 if (checkPlaceholderForOverload(*this, Args[1])) 10352 return ExprError(); 10353 10354 // Build an empty overload set. 10355 OverloadCandidateSet CandidateSet(LLoc); 10356 10357 // Subscript can only be overloaded as a member function. 10358 10359 // Add operator candidates that are member functions. 10360 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10361 10362 // Add builtin operator candidates. 10363 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10364 10365 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10366 10367 // Perform overload resolution. 10368 OverloadCandidateSet::iterator Best; 10369 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10370 case OR_Success: { 10371 // We found a built-in operator or an overloaded operator. 10372 FunctionDecl *FnDecl = Best->Function; 10373 10374 if (FnDecl) { 10375 // We matched an overloaded operator. Build a call to that 10376 // operator. 10377 10378 MarkFunctionReferenced(LLoc, FnDecl); 10379 10380 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10381 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10382 10383 // Convert the arguments. 10384 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10385 ExprResult Arg0 = 10386 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10387 Best->FoundDecl, Method); 10388 if (Arg0.isInvalid()) 10389 return ExprError(); 10390 Args[0] = Arg0.take(); 10391 10392 // Convert the arguments. 10393 ExprResult InputInit 10394 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10395 Context, 10396 FnDecl->getParamDecl(0)), 10397 SourceLocation(), 10398 Owned(Args[1])); 10399 if (InputInit.isInvalid()) 10400 return ExprError(); 10401 10402 Args[1] = InputInit.takeAs<Expr>(); 10403 10404 // Determine the result type 10405 QualType ResultTy = FnDecl->getResultType(); 10406 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10407 ResultTy = ResultTy.getNonLValueExprType(Context); 10408 10409 // Build the actual expression node. 10410 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10411 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10412 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10413 HadMultipleCandidates, 10414 OpLocInfo.getLoc(), 10415 OpLocInfo.getInfo()); 10416 if (FnExpr.isInvalid()) 10417 return ExprError(); 10418 10419 CXXOperatorCallExpr *TheCall = 10420 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10421 FnExpr.take(), Args, 2, 10422 ResultTy, VK, RLoc); 10423 10424 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10425 FnDecl)) 10426 return ExprError(); 10427 10428 return MaybeBindToTemporary(TheCall); 10429 } else { 10430 // We matched a built-in operator. Convert the arguments, then 10431 // break out so that we will build the appropriate built-in 10432 // operator node. 10433 ExprResult ArgsRes0 = 10434 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10435 Best->Conversions[0], AA_Passing); 10436 if (ArgsRes0.isInvalid()) 10437 return ExprError(); 10438 Args[0] = ArgsRes0.take(); 10439 10440 ExprResult ArgsRes1 = 10441 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10442 Best->Conversions[1], AA_Passing); 10443 if (ArgsRes1.isInvalid()) 10444 return ExprError(); 10445 Args[1] = ArgsRes1.take(); 10446 10447 break; 10448 } 10449 } 10450 10451 case OR_No_Viable_Function: { 10452 if (CandidateSet.empty()) 10453 Diag(LLoc, diag::err_ovl_no_oper) 10454 << Args[0]->getType() << /*subscript*/ 0 10455 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10456 else 10457 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10458 << Args[0]->getType() 10459 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10460 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10461 "[]", LLoc); 10462 return ExprError(); 10463 } 10464 10465 case OR_Ambiguous: 10466 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10467 << "[]" 10468 << Args[0]->getType() << Args[1]->getType() 10469 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10470 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10471 "[]", LLoc); 10472 return ExprError(); 10473 10474 case OR_Deleted: 10475 Diag(LLoc, diag::err_ovl_deleted_oper) 10476 << Best->Function->isDeleted() << "[]" 10477 << getDeletedOrUnavailableSuffix(Best->Function) 10478 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10479 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10480 "[]", LLoc); 10481 return ExprError(); 10482 } 10483 10484 // We matched a built-in operator; build it. 10485 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10486} 10487 10488/// BuildCallToMemberFunction - Build a call to a member 10489/// function. MemExpr is the expression that refers to the member 10490/// function (and includes the object parameter), Args/NumArgs are the 10491/// arguments to the function call (not including the object 10492/// parameter). The caller needs to validate that the member 10493/// expression refers to a non-static member function or an overloaded 10494/// member function. 10495ExprResult 10496Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10497 SourceLocation LParenLoc, Expr **Args, 10498 unsigned NumArgs, SourceLocation RParenLoc) { 10499 assert(MemExprE->getType() == Context.BoundMemberTy || 10500 MemExprE->getType() == Context.OverloadTy); 10501 10502 // Dig out the member expression. This holds both the object 10503 // argument and the member function we're referring to. 10504 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10505 10506 // Determine whether this is a call to a pointer-to-member function. 10507 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10508 assert(op->getType() == Context.BoundMemberTy); 10509 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10510 10511 QualType fnType = 10512 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10513 10514 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10515 QualType resultType = proto->getCallResultType(Context); 10516 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10517 10518 // Check that the object type isn't more qualified than the 10519 // member function we're calling. 10520 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10521 10522 QualType objectType = op->getLHS()->getType(); 10523 if (op->getOpcode() == BO_PtrMemI) 10524 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10525 Qualifiers objectQuals = objectType.getQualifiers(); 10526 10527 Qualifiers difference = objectQuals - funcQuals; 10528 difference.removeObjCGCAttr(); 10529 difference.removeAddressSpace(); 10530 if (difference) { 10531 std::string qualsString = difference.getAsString(); 10532 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10533 << fnType.getUnqualifiedType() 10534 << qualsString 10535 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10536 } 10537 10538 CXXMemberCallExpr *call 10539 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 10540 resultType, valueKind, RParenLoc); 10541 10542 if (CheckCallReturnType(proto->getResultType(), 10543 op->getRHS()->getLocStart(), 10544 call, 0)) 10545 return ExprError(); 10546 10547 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10548 return ExprError(); 10549 10550 return MaybeBindToTemporary(call); 10551 } 10552 10553 UnbridgedCastsSet UnbridgedCasts; 10554 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10555 return ExprError(); 10556 10557 MemberExpr *MemExpr; 10558 CXXMethodDecl *Method = 0; 10559 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10560 NestedNameSpecifier *Qualifier = 0; 10561 if (isa<MemberExpr>(NakedMemExpr)) { 10562 MemExpr = cast<MemberExpr>(NakedMemExpr); 10563 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10564 FoundDecl = MemExpr->getFoundDecl(); 10565 Qualifier = MemExpr->getQualifier(); 10566 UnbridgedCasts.restore(); 10567 } else { 10568 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10569 Qualifier = UnresExpr->getQualifier(); 10570 10571 QualType ObjectType = UnresExpr->getBaseType(); 10572 Expr::Classification ObjectClassification 10573 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10574 : UnresExpr->getBase()->Classify(Context); 10575 10576 // Add overload candidates 10577 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10578 10579 // FIXME: avoid copy. 10580 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10581 if (UnresExpr->hasExplicitTemplateArgs()) { 10582 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10583 TemplateArgs = &TemplateArgsBuffer; 10584 } 10585 10586 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10587 E = UnresExpr->decls_end(); I != E; ++I) { 10588 10589 NamedDecl *Func = *I; 10590 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10591 if (isa<UsingShadowDecl>(Func)) 10592 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10593 10594 10595 // Microsoft supports direct constructor calls. 10596 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10597 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10598 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10599 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10600 // If explicit template arguments were provided, we can't call a 10601 // non-template member function. 10602 if (TemplateArgs) 10603 continue; 10604 10605 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10606 ObjectClassification, 10607 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10608 /*SuppressUserConversions=*/false); 10609 } else { 10610 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10611 I.getPair(), ActingDC, TemplateArgs, 10612 ObjectType, ObjectClassification, 10613 llvm::makeArrayRef(Args, NumArgs), 10614 CandidateSet, 10615 /*SuppressUsedConversions=*/false); 10616 } 10617 } 10618 10619 DeclarationName DeclName = UnresExpr->getMemberName(); 10620 10621 UnbridgedCasts.restore(); 10622 10623 OverloadCandidateSet::iterator Best; 10624 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10625 Best)) { 10626 case OR_Success: 10627 Method = cast<CXXMethodDecl>(Best->Function); 10628 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10629 FoundDecl = Best->FoundDecl; 10630 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10631 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10632 break; 10633 10634 case OR_No_Viable_Function: 10635 Diag(UnresExpr->getMemberLoc(), 10636 diag::err_ovl_no_viable_member_function_in_call) 10637 << DeclName << MemExprE->getSourceRange(); 10638 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10639 llvm::makeArrayRef(Args, NumArgs)); 10640 // FIXME: Leaking incoming expressions! 10641 return ExprError(); 10642 10643 case OR_Ambiguous: 10644 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10645 << DeclName << MemExprE->getSourceRange(); 10646 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10647 llvm::makeArrayRef(Args, NumArgs)); 10648 // FIXME: Leaking incoming expressions! 10649 return ExprError(); 10650 10651 case OR_Deleted: 10652 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10653 << Best->Function->isDeleted() 10654 << DeclName 10655 << getDeletedOrUnavailableSuffix(Best->Function) 10656 << MemExprE->getSourceRange(); 10657 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10658 llvm::makeArrayRef(Args, NumArgs)); 10659 // FIXME: Leaking incoming expressions! 10660 return ExprError(); 10661 } 10662 10663 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10664 10665 // If overload resolution picked a static member, build a 10666 // non-member call based on that function. 10667 if (Method->isStatic()) { 10668 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10669 Args, NumArgs, RParenLoc); 10670 } 10671 10672 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10673 } 10674 10675 QualType ResultType = Method->getResultType(); 10676 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10677 ResultType = ResultType.getNonLValueExprType(Context); 10678 10679 assert(Method && "Member call to something that isn't a method?"); 10680 CXXMemberCallExpr *TheCall = 10681 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 10682 ResultType, VK, RParenLoc); 10683 10684 // Check for a valid return type. 10685 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10686 TheCall, Method)) 10687 return ExprError(); 10688 10689 // Convert the object argument (for a non-static member function call). 10690 // We only need to do this if there was actually an overload; otherwise 10691 // it was done at lookup. 10692 if (!Method->isStatic()) { 10693 ExprResult ObjectArg = 10694 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10695 FoundDecl, Method); 10696 if (ObjectArg.isInvalid()) 10697 return ExprError(); 10698 MemExpr->setBase(ObjectArg.take()); 10699 } 10700 10701 // Convert the rest of the arguments 10702 const FunctionProtoType *Proto = 10703 Method->getType()->getAs<FunctionProtoType>(); 10704 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10705 RParenLoc)) 10706 return ExprError(); 10707 10708 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10709 10710 if (CheckFunctionCall(Method, TheCall)) 10711 return ExprError(); 10712 10713 if ((isa<CXXConstructorDecl>(CurContext) || 10714 isa<CXXDestructorDecl>(CurContext)) && 10715 TheCall->getMethodDecl()->isPure()) { 10716 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10717 10718 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10719 Diag(MemExpr->getLocStart(), 10720 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10721 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10722 << MD->getParent()->getDeclName(); 10723 10724 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10725 } 10726 } 10727 return MaybeBindToTemporary(TheCall); 10728} 10729 10730/// BuildCallToObjectOfClassType - Build a call to an object of class 10731/// type (C++ [over.call.object]), which can end up invoking an 10732/// overloaded function call operator (@c operator()) or performing a 10733/// user-defined conversion on the object argument. 10734ExprResult 10735Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10736 SourceLocation LParenLoc, 10737 Expr **Args, unsigned NumArgs, 10738 SourceLocation RParenLoc) { 10739 if (checkPlaceholderForOverload(*this, Obj)) 10740 return ExprError(); 10741 ExprResult Object = Owned(Obj); 10742 10743 UnbridgedCastsSet UnbridgedCasts; 10744 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10745 return ExprError(); 10746 10747 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10748 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10749 10750 // C++ [over.call.object]p1: 10751 // If the primary-expression E in the function call syntax 10752 // evaluates to a class object of type "cv T", then the set of 10753 // candidate functions includes at least the function call 10754 // operators of T. The function call operators of T are obtained by 10755 // ordinary lookup of the name operator() in the context of 10756 // (E).operator(). 10757 OverloadCandidateSet CandidateSet(LParenLoc); 10758 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10759 10760 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10761 diag::err_incomplete_object_call, Object.get())) 10762 return true; 10763 10764 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10765 LookupQualifiedName(R, Record->getDecl()); 10766 R.suppressDiagnostics(); 10767 10768 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10769 Oper != OperEnd; ++Oper) { 10770 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10771 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10772 /*SuppressUserConversions=*/ false); 10773 } 10774 10775 // C++ [over.call.object]p2: 10776 // In addition, for each (non-explicit in C++0x) conversion function 10777 // declared in T of the form 10778 // 10779 // operator conversion-type-id () cv-qualifier; 10780 // 10781 // where cv-qualifier is the same cv-qualification as, or a 10782 // greater cv-qualification than, cv, and where conversion-type-id 10783 // denotes the type "pointer to function of (P1,...,Pn) returning 10784 // R", or the type "reference to pointer to function of 10785 // (P1,...,Pn) returning R", or the type "reference to function 10786 // of (P1,...,Pn) returning R", a surrogate call function [...] 10787 // is also considered as a candidate function. Similarly, 10788 // surrogate call functions are added to the set of candidate 10789 // functions for each conversion function declared in an 10790 // accessible base class provided the function is not hidden 10791 // within T by another intervening declaration. 10792 const UnresolvedSetImpl *Conversions 10793 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10794 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 10795 E = Conversions->end(); I != E; ++I) { 10796 NamedDecl *D = *I; 10797 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10798 if (isa<UsingShadowDecl>(D)) 10799 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10800 10801 // Skip over templated conversion functions; they aren't 10802 // surrogates. 10803 if (isa<FunctionTemplateDecl>(D)) 10804 continue; 10805 10806 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10807 if (!Conv->isExplicit()) { 10808 // Strip the reference type (if any) and then the pointer type (if 10809 // any) to get down to what might be a function type. 10810 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10811 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10812 ConvType = ConvPtrType->getPointeeType(); 10813 10814 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10815 { 10816 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10817 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10818 CandidateSet); 10819 } 10820 } 10821 } 10822 10823 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10824 10825 // Perform overload resolution. 10826 OverloadCandidateSet::iterator Best; 10827 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10828 Best)) { 10829 case OR_Success: 10830 // Overload resolution succeeded; we'll build the appropriate call 10831 // below. 10832 break; 10833 10834 case OR_No_Viable_Function: 10835 if (CandidateSet.empty()) 10836 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10837 << Object.get()->getType() << /*call*/ 1 10838 << Object.get()->getSourceRange(); 10839 else 10840 Diag(Object.get()->getLocStart(), 10841 diag::err_ovl_no_viable_object_call) 10842 << Object.get()->getType() << Object.get()->getSourceRange(); 10843 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10844 llvm::makeArrayRef(Args, NumArgs)); 10845 break; 10846 10847 case OR_Ambiguous: 10848 Diag(Object.get()->getLocStart(), 10849 diag::err_ovl_ambiguous_object_call) 10850 << Object.get()->getType() << Object.get()->getSourceRange(); 10851 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10852 llvm::makeArrayRef(Args, NumArgs)); 10853 break; 10854 10855 case OR_Deleted: 10856 Diag(Object.get()->getLocStart(), 10857 diag::err_ovl_deleted_object_call) 10858 << Best->Function->isDeleted() 10859 << Object.get()->getType() 10860 << getDeletedOrUnavailableSuffix(Best->Function) 10861 << Object.get()->getSourceRange(); 10862 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10863 llvm::makeArrayRef(Args, NumArgs)); 10864 break; 10865 } 10866 10867 if (Best == CandidateSet.end()) 10868 return true; 10869 10870 UnbridgedCasts.restore(); 10871 10872 if (Best->Function == 0) { 10873 // Since there is no function declaration, this is one of the 10874 // surrogate candidates. Dig out the conversion function. 10875 CXXConversionDecl *Conv 10876 = cast<CXXConversionDecl>( 10877 Best->Conversions[0].UserDefined.ConversionFunction); 10878 10879 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10880 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10881 10882 // We selected one of the surrogate functions that converts the 10883 // object parameter to a function pointer. Perform the conversion 10884 // on the object argument, then let ActOnCallExpr finish the job. 10885 10886 // Create an implicit member expr to refer to the conversion operator. 10887 // and then call it. 10888 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10889 Conv, HadMultipleCandidates); 10890 if (Call.isInvalid()) 10891 return ExprError(); 10892 // Record usage of conversion in an implicit cast. 10893 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10894 CK_UserDefinedConversion, 10895 Call.get(), 0, VK_RValue)); 10896 10897 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10898 RParenLoc); 10899 } 10900 10901 MarkFunctionReferenced(LParenLoc, Best->Function); 10902 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10903 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10904 10905 // We found an overloaded operator(). Build a CXXOperatorCallExpr 10906 // that calls this method, using Object for the implicit object 10907 // parameter and passing along the remaining arguments. 10908 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10909 const FunctionProtoType *Proto = 10910 Method->getType()->getAs<FunctionProtoType>(); 10911 10912 unsigned NumArgsInProto = Proto->getNumArgs(); 10913 unsigned NumArgsToCheck = NumArgs; 10914 10915 // Build the full argument list for the method call (the 10916 // implicit object parameter is placed at the beginning of the 10917 // list). 10918 Expr **MethodArgs; 10919 if (NumArgs < NumArgsInProto) { 10920 NumArgsToCheck = NumArgsInProto; 10921 MethodArgs = new Expr*[NumArgsInProto + 1]; 10922 } else { 10923 MethodArgs = new Expr*[NumArgs + 1]; 10924 } 10925 MethodArgs[0] = Object.get(); 10926 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 10927 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 10928 10929 DeclarationNameInfo OpLocInfo( 10930 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 10931 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 10932 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 10933 HadMultipleCandidates, 10934 OpLocInfo.getLoc(), 10935 OpLocInfo.getInfo()); 10936 if (NewFn.isInvalid()) 10937 return true; 10938 10939 // Once we've built TheCall, all of the expressions are properly 10940 // owned. 10941 QualType ResultTy = Method->getResultType(); 10942 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10943 ResultTy = ResultTy.getNonLValueExprType(Context); 10944 10945 CXXOperatorCallExpr *TheCall = 10946 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 10947 MethodArgs, NumArgs + 1, 10948 ResultTy, VK, RParenLoc); 10949 delete [] MethodArgs; 10950 10951 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 10952 Method)) 10953 return true; 10954 10955 // We may have default arguments. If so, we need to allocate more 10956 // slots in the call for them. 10957 if (NumArgs < NumArgsInProto) 10958 TheCall->setNumArgs(Context, NumArgsInProto + 1); 10959 else if (NumArgs > NumArgsInProto) 10960 NumArgsToCheck = NumArgsInProto; 10961 10962 bool IsError = false; 10963 10964 // Initialize the implicit object parameter. 10965 ExprResult ObjRes = 10966 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 10967 Best->FoundDecl, Method); 10968 if (ObjRes.isInvalid()) 10969 IsError = true; 10970 else 10971 Object = move(ObjRes); 10972 TheCall->setArg(0, Object.take()); 10973 10974 // Check the argument types. 10975 for (unsigned i = 0; i != NumArgsToCheck; i++) { 10976 Expr *Arg; 10977 if (i < NumArgs) { 10978 Arg = Args[i]; 10979 10980 // Pass the argument. 10981 10982 ExprResult InputInit 10983 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10984 Context, 10985 Method->getParamDecl(i)), 10986 SourceLocation(), Arg); 10987 10988 IsError |= InputInit.isInvalid(); 10989 Arg = InputInit.takeAs<Expr>(); 10990 } else { 10991 ExprResult DefArg 10992 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 10993 if (DefArg.isInvalid()) { 10994 IsError = true; 10995 break; 10996 } 10997 10998 Arg = DefArg.takeAs<Expr>(); 10999 } 11000 11001 TheCall->setArg(i + 1, Arg); 11002 } 11003 11004 // If this is a variadic call, handle args passed through "...". 11005 if (Proto->isVariadic()) { 11006 // Promote the arguments (C99 6.5.2.2p7). 11007 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 11008 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11009 IsError |= Arg.isInvalid(); 11010 TheCall->setArg(i + 1, Arg.take()); 11011 } 11012 } 11013 11014 if (IsError) return true; 11015 11016 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11017 11018 if (CheckFunctionCall(Method, TheCall)) 11019 return true; 11020 11021 return MaybeBindToTemporary(TheCall); 11022} 11023 11024/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11025/// (if one exists), where @c Base is an expression of class type and 11026/// @c Member is the name of the member we're trying to find. 11027ExprResult 11028Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11029 assert(Base->getType()->isRecordType() && 11030 "left-hand side must have class type"); 11031 11032 if (checkPlaceholderForOverload(*this, Base)) 11033 return ExprError(); 11034 11035 SourceLocation Loc = Base->getExprLoc(); 11036 11037 // C++ [over.ref]p1: 11038 // 11039 // [...] An expression x->m is interpreted as (x.operator->())->m 11040 // for a class object x of type T if T::operator->() exists and if 11041 // the operator is selected as the best match function by the 11042 // overload resolution mechanism (13.3). 11043 DeclarationName OpName = 11044 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11045 OverloadCandidateSet CandidateSet(Loc); 11046 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11047 11048 if (RequireCompleteType(Loc, Base->getType(), 11049 diag::err_typecheck_incomplete_tag, Base)) 11050 return ExprError(); 11051 11052 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11053 LookupQualifiedName(R, BaseRecord->getDecl()); 11054 R.suppressDiagnostics(); 11055 11056 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11057 Oper != OperEnd; ++Oper) { 11058 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11059 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11060 } 11061 11062 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11063 11064 // Perform overload resolution. 11065 OverloadCandidateSet::iterator Best; 11066 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11067 case OR_Success: 11068 // Overload resolution succeeded; we'll build the call below. 11069 break; 11070 11071 case OR_No_Viable_Function: 11072 if (CandidateSet.empty()) 11073 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11074 << Base->getType() << Base->getSourceRange(); 11075 else 11076 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11077 << "operator->" << Base->getSourceRange(); 11078 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11079 return ExprError(); 11080 11081 case OR_Ambiguous: 11082 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11083 << "->" << Base->getType() << Base->getSourceRange(); 11084 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11085 return ExprError(); 11086 11087 case OR_Deleted: 11088 Diag(OpLoc, diag::err_ovl_deleted_oper) 11089 << Best->Function->isDeleted() 11090 << "->" 11091 << getDeletedOrUnavailableSuffix(Best->Function) 11092 << Base->getSourceRange(); 11093 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11094 return ExprError(); 11095 } 11096 11097 MarkFunctionReferenced(OpLoc, Best->Function); 11098 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11099 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11100 11101 // Convert the object parameter. 11102 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11103 ExprResult BaseResult = 11104 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11105 Best->FoundDecl, Method); 11106 if (BaseResult.isInvalid()) 11107 return ExprError(); 11108 Base = BaseResult.take(); 11109 11110 // Build the operator call. 11111 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11112 HadMultipleCandidates, OpLoc); 11113 if (FnExpr.isInvalid()) 11114 return ExprError(); 11115 11116 QualType ResultTy = Method->getResultType(); 11117 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11118 ResultTy = ResultTy.getNonLValueExprType(Context); 11119 CXXOperatorCallExpr *TheCall = 11120 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11121 &Base, 1, ResultTy, VK, OpLoc); 11122 11123 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11124 Method)) 11125 return ExprError(); 11126 11127 return MaybeBindToTemporary(TheCall); 11128} 11129 11130/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11131/// a literal operator described by the provided lookup results. 11132ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11133 DeclarationNameInfo &SuffixInfo, 11134 ArrayRef<Expr*> Args, 11135 SourceLocation LitEndLoc, 11136 TemplateArgumentListInfo *TemplateArgs) { 11137 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11138 11139 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11140 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11141 TemplateArgs); 11142 11143 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11144 11145 // Perform overload resolution. This will usually be trivial, but might need 11146 // to perform substitutions for a literal operator template. 11147 OverloadCandidateSet::iterator Best; 11148 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11149 case OR_Success: 11150 case OR_Deleted: 11151 break; 11152 11153 case OR_No_Viable_Function: 11154 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11155 << R.getLookupName(); 11156 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11157 return ExprError(); 11158 11159 case OR_Ambiguous: 11160 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11161 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11162 return ExprError(); 11163 } 11164 11165 FunctionDecl *FD = Best->Function; 11166 MarkFunctionReferenced(UDSuffixLoc, FD); 11167 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11168 11169 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11170 SuffixInfo.getLoc(), 11171 SuffixInfo.getInfo()); 11172 if (Fn.isInvalid()) 11173 return true; 11174 11175 // Check the argument types. This should almost always be a no-op, except 11176 // that array-to-pointer decay is applied to string literals. 11177 Expr *ConvArgs[2]; 11178 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11179 ExprResult InputInit = PerformCopyInitialization( 11180 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11181 SourceLocation(), Args[ArgIdx]); 11182 if (InputInit.isInvalid()) 11183 return true; 11184 ConvArgs[ArgIdx] = InputInit.take(); 11185 } 11186 11187 QualType ResultTy = FD->getResultType(); 11188 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11189 ResultTy = ResultTy.getNonLValueExprType(Context); 11190 11191 UserDefinedLiteral *UDL = 11192 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(), 11193 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11194 11195 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11196 return ExprError(); 11197 11198 if (CheckFunctionCall(FD, UDL)) 11199 return ExprError(); 11200 11201 return MaybeBindToTemporary(UDL); 11202} 11203 11204/// FixOverloadedFunctionReference - E is an expression that refers to 11205/// a C++ overloaded function (possibly with some parentheses and 11206/// perhaps a '&' around it). We have resolved the overloaded function 11207/// to the function declaration Fn, so patch up the expression E to 11208/// refer (possibly indirectly) to Fn. Returns the new expr. 11209Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11210 FunctionDecl *Fn) { 11211 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11212 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11213 Found, Fn); 11214 if (SubExpr == PE->getSubExpr()) 11215 return PE; 11216 11217 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11218 } 11219 11220 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11221 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11222 Found, Fn); 11223 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11224 SubExpr->getType()) && 11225 "Implicit cast type cannot be determined from overload"); 11226 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11227 if (SubExpr == ICE->getSubExpr()) 11228 return ICE; 11229 11230 return ImplicitCastExpr::Create(Context, ICE->getType(), 11231 ICE->getCastKind(), 11232 SubExpr, 0, 11233 ICE->getValueKind()); 11234 } 11235 11236 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11237 assert(UnOp->getOpcode() == UO_AddrOf && 11238 "Can only take the address of an overloaded function"); 11239 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11240 if (Method->isStatic()) { 11241 // Do nothing: static member functions aren't any different 11242 // from non-member functions. 11243 } else { 11244 // Fix the sub expression, which really has to be an 11245 // UnresolvedLookupExpr holding an overloaded member function 11246 // or template. 11247 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11248 Found, Fn); 11249 if (SubExpr == UnOp->getSubExpr()) 11250 return UnOp; 11251 11252 assert(isa<DeclRefExpr>(SubExpr) 11253 && "fixed to something other than a decl ref"); 11254 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11255 && "fixed to a member ref with no nested name qualifier"); 11256 11257 // We have taken the address of a pointer to member 11258 // function. Perform the computation here so that we get the 11259 // appropriate pointer to member type. 11260 QualType ClassType 11261 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11262 QualType MemPtrType 11263 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11264 11265 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11266 VK_RValue, OK_Ordinary, 11267 UnOp->getOperatorLoc()); 11268 } 11269 } 11270 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11271 Found, Fn); 11272 if (SubExpr == UnOp->getSubExpr()) 11273 return UnOp; 11274 11275 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11276 Context.getPointerType(SubExpr->getType()), 11277 VK_RValue, OK_Ordinary, 11278 UnOp->getOperatorLoc()); 11279 } 11280 11281 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11282 // FIXME: avoid copy. 11283 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11284 if (ULE->hasExplicitTemplateArgs()) { 11285 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11286 TemplateArgs = &TemplateArgsBuffer; 11287 } 11288 11289 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11290 ULE->getQualifierLoc(), 11291 ULE->getTemplateKeywordLoc(), 11292 Fn, 11293 /*enclosing*/ false, // FIXME? 11294 ULE->getNameLoc(), 11295 Fn->getType(), 11296 VK_LValue, 11297 Found.getDecl(), 11298 TemplateArgs); 11299 MarkDeclRefReferenced(DRE); 11300 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11301 return DRE; 11302 } 11303 11304 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11305 // FIXME: avoid copy. 11306 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11307 if (MemExpr->hasExplicitTemplateArgs()) { 11308 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11309 TemplateArgs = &TemplateArgsBuffer; 11310 } 11311 11312 Expr *Base; 11313 11314 // If we're filling in a static method where we used to have an 11315 // implicit member access, rewrite to a simple decl ref. 11316 if (MemExpr->isImplicitAccess()) { 11317 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11318 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11319 MemExpr->getQualifierLoc(), 11320 MemExpr->getTemplateKeywordLoc(), 11321 Fn, 11322 /*enclosing*/ false, 11323 MemExpr->getMemberLoc(), 11324 Fn->getType(), 11325 VK_LValue, 11326 Found.getDecl(), 11327 TemplateArgs); 11328 MarkDeclRefReferenced(DRE); 11329 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11330 return DRE; 11331 } else { 11332 SourceLocation Loc = MemExpr->getMemberLoc(); 11333 if (MemExpr->getQualifier()) 11334 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11335 CheckCXXThisCapture(Loc); 11336 Base = new (Context) CXXThisExpr(Loc, 11337 MemExpr->getBaseType(), 11338 /*isImplicit=*/true); 11339 } 11340 } else 11341 Base = MemExpr->getBase(); 11342 11343 ExprValueKind valueKind; 11344 QualType type; 11345 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11346 valueKind = VK_LValue; 11347 type = Fn->getType(); 11348 } else { 11349 valueKind = VK_RValue; 11350 type = Context.BoundMemberTy; 11351 } 11352 11353 MemberExpr *ME = MemberExpr::Create(Context, Base, 11354 MemExpr->isArrow(), 11355 MemExpr->getQualifierLoc(), 11356 MemExpr->getTemplateKeywordLoc(), 11357 Fn, 11358 Found, 11359 MemExpr->getMemberNameInfo(), 11360 TemplateArgs, 11361 type, valueKind, OK_Ordinary); 11362 ME->setHadMultipleCandidates(true); 11363 return ME; 11364 } 11365 11366 llvm_unreachable("Invalid reference to overloaded function"); 11367} 11368 11369ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11370 DeclAccessPair Found, 11371 FunctionDecl *Fn) { 11372 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11373} 11374 11375} // end namespace clang 11376