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