1249423Sdim//===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This file provides Sema routines for C++ overloading. 11193326Sed// 12193326Sed//===----------------------------------------------------------------------===// 13193326Sed 14249423Sdim#include "clang/Sema/Overload.h" 15193326Sed#include "clang/AST/ASTContext.h" 16198092Srdivacky#include "clang/AST/CXXInheritance.h" 17212904Sdim#include "clang/AST/DeclObjC.h" 18193326Sed#include "clang/AST/Expr.h" 19193326Sed#include "clang/AST/ExprCXX.h" 20218893Sdim#include "clang/AST/ExprObjC.h" 21193326Sed#include "clang/AST/TypeOrdering.h" 22249423Sdim#include "clang/Basic/Diagnostic.h" 23198092Srdivacky#include "clang/Basic/PartialDiagnostic.h" 24249423Sdim#include "clang/Lex/Preprocessor.h" 25249423Sdim#include "clang/Sema/Initialization.h" 26249423Sdim#include "clang/Sema/Lookup.h" 27249423Sdim#include "clang/Sema/SemaInternal.h" 28249423Sdim#include "clang/Sema/Template.h" 29249423Sdim#include "clang/Sema/TemplateDeduction.h" 30218893Sdim#include "llvm/ADT/DenseSet.h" 31249423Sdim#include "llvm/ADT/STLExtras.h" 32193326Sed#include "llvm/ADT/SmallPtrSet.h" 33239462Sdim#include "llvm/ADT/SmallString.h" 34193326Sed#include <algorithm> 35193326Sed 36193326Sednamespace clang { 37212904Sdimusing namespace sema; 38193326Sed 39249423Sdim/// A convenience routine for creating a decayed reference to a function. 40221345Sdimstatic ExprResult 41249423SdimCreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 42249423Sdim bool HadMultipleCandidates, 43224145Sdim SourceLocation Loc = SourceLocation(), 44224145Sdim const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45251662Sdim if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 46251662Sdim return ExprError(); 47251662Sdim 48234353Sdim DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 49226633Sdim VK_LValue, Loc, LocInfo); 50226633Sdim if (HadMultipleCandidates) 51226633Sdim DRE->setHadMultipleCandidates(true); 52249423Sdim 53249423Sdim S.MarkDeclRefReferenced(DRE); 54249423Sdim 55226633Sdim ExprResult E = S.Owned(DRE); 56221345Sdim E = S.DefaultFunctionArrayConversion(E.take()); 57221345Sdim if (E.isInvalid()) 58221345Sdim return ExprError(); 59243830Sdim return E; 60218893Sdim} 61218893Sdim 62212904Sdimstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 63212904Sdim bool InOverloadResolution, 64218893Sdim StandardConversionSequence &SCS, 65224145Sdim bool CStyle, 66224145Sdim bool AllowObjCWritebackConversion); 67239462Sdim 68221345Sdimstatic bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 69221345Sdim QualType &ToType, 70221345Sdim bool InOverloadResolution, 71221345Sdim StandardConversionSequence &SCS, 72221345Sdim bool CStyle); 73212904Sdimstatic OverloadingResult 74212904SdimIsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 75212904Sdim UserDefinedConversionSequence& User, 76212904Sdim OverloadCandidateSet& Conversions, 77212904Sdim bool AllowExplicit); 78212904Sdim 79212904Sdim 80212904Sdimstatic ImplicitConversionSequence::CompareKind 81212904SdimCompareStandardConversionSequences(Sema &S, 82212904Sdim const StandardConversionSequence& SCS1, 83212904Sdim const StandardConversionSequence& SCS2); 84212904Sdim 85212904Sdimstatic ImplicitConversionSequence::CompareKind 86212904SdimCompareQualificationConversions(Sema &S, 87212904Sdim const StandardConversionSequence& SCS1, 88212904Sdim const StandardConversionSequence& SCS2); 89212904Sdim 90212904Sdimstatic ImplicitConversionSequence::CompareKind 91212904SdimCompareDerivedToBaseConversions(Sema &S, 92212904Sdim const StandardConversionSequence& SCS1, 93212904Sdim const StandardConversionSequence& SCS2); 94212904Sdim 95212904Sdim 96212904Sdim 97193326Sed/// GetConversionCategory - Retrieve the implicit conversion 98193326Sed/// category corresponding to the given implicit conversion kind. 99198092SrdivackyImplicitConversionCategory 100193326SedGetConversionCategory(ImplicitConversionKind Kind) { 101193326Sed static const ImplicitConversionCategory 102193326Sed Category[(int)ICK_Num_Conversion_Kinds] = { 103193326Sed ICC_Identity, 104193326Sed ICC_Lvalue_Transformation, 105193326Sed ICC_Lvalue_Transformation, 106193326Sed ICC_Lvalue_Transformation, 107200583Srdivacky ICC_Identity, 108193326Sed ICC_Qualification_Adjustment, 109193326Sed ICC_Promotion, 110193326Sed ICC_Promotion, 111193326Sed ICC_Promotion, 112193326Sed ICC_Conversion, 113193326Sed ICC_Conversion, 114193326Sed ICC_Conversion, 115193326Sed ICC_Conversion, 116193326Sed ICC_Conversion, 117193326Sed ICC_Conversion, 118193326Sed ICC_Conversion, 119193326Sed ICC_Conversion, 120193326Sed ICC_Conversion, 121208600Srdivacky ICC_Conversion, 122208600Srdivacky ICC_Conversion, 123224145Sdim ICC_Conversion, 124193326Sed ICC_Conversion 125193326Sed }; 126193326Sed return Category[(int)Kind]; 127193326Sed} 128193326Sed 129193326Sed/// GetConversionRank - Retrieve the implicit conversion rank 130193326Sed/// corresponding to the given implicit conversion kind. 131193326SedImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 132193326Sed static const ImplicitConversionRank 133193326Sed Rank[(int)ICK_Num_Conversion_Kinds] = { 134193326Sed ICR_Exact_Match, 135193326Sed ICR_Exact_Match, 136193326Sed ICR_Exact_Match, 137193326Sed ICR_Exact_Match, 138193326Sed ICR_Exact_Match, 139200583Srdivacky ICR_Exact_Match, 140193326Sed ICR_Promotion, 141193326Sed ICR_Promotion, 142193326Sed ICR_Promotion, 143193326Sed ICR_Conversion, 144193326Sed ICR_Conversion, 145193326Sed ICR_Conversion, 146193326Sed ICR_Conversion, 147193326Sed ICR_Conversion, 148193326Sed ICR_Conversion, 149193326Sed ICR_Conversion, 150193326Sed ICR_Conversion, 151193326Sed ICR_Conversion, 152208600Srdivacky ICR_Conversion, 153208600Srdivacky ICR_Conversion, 154221345Sdim ICR_Complex_Real_Conversion, 155221345Sdim ICR_Conversion, 156224145Sdim ICR_Conversion, 157224145Sdim ICR_Writeback_Conversion 158193326Sed }; 159193326Sed return Rank[(int)Kind]; 160193326Sed} 161193326Sed 162193326Sed/// GetImplicitConversionName - Return the name of this kind of 163193326Sed/// implicit conversion. 164193326Sedconst char* GetImplicitConversionName(ImplicitConversionKind Kind) { 165201361Srdivacky static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 166193326Sed "No conversion", 167193326Sed "Lvalue-to-rvalue", 168193326Sed "Array-to-pointer", 169193326Sed "Function-to-pointer", 170200583Srdivacky "Noreturn adjustment", 171193326Sed "Qualification", 172193326Sed "Integral promotion", 173193326Sed "Floating point promotion", 174193326Sed "Complex promotion", 175193326Sed "Integral conversion", 176193326Sed "Floating conversion", 177193326Sed "Complex conversion", 178193326Sed "Floating-integral conversion", 179193326Sed "Pointer conversion", 180193326Sed "Pointer-to-member conversion", 181193326Sed "Boolean conversion", 182193326Sed "Compatible-types conversion", 183208600Srdivacky "Derived-to-base conversion", 184208600Srdivacky "Vector conversion", 185208600Srdivacky "Vector splat", 186221345Sdim "Complex-real conversion", 187221345Sdim "Block Pointer conversion", 188221345Sdim "Transparent Union Conversion" 189224145Sdim "Writeback conversion" 190193326Sed }; 191193326Sed return Name[Kind]; 192193326Sed} 193193326Sed 194193326Sed/// StandardConversionSequence - Set the standard conversion 195193326Sed/// sequence to the identity conversion. 196193326Sedvoid StandardConversionSequence::setAsIdentityConversion() { 197193326Sed First = ICK_Identity; 198193326Sed Second = ICK_Identity; 199193326Sed Third = ICK_Identity; 200204643Srdivacky DeprecatedStringLiteralToCharPtr = false; 201224145Sdim QualificationIncludesObjCLifetime = false; 202193326Sed ReferenceBinding = false; 203193326Sed DirectBinding = false; 204218893Sdim IsLvalueReference = true; 205218893Sdim BindsToFunctionLvalue = false; 206218893Sdim BindsToRvalue = false; 207218893Sdim BindsImplicitObjectArgumentWithoutRefQualifier = false; 208224145Sdim ObjCLifetimeConversionBinding = false; 209193326Sed CopyConstructor = 0; 210193326Sed} 211193326Sed 212193326Sed/// getRank - Retrieve the rank of this standard conversion sequence 213193326Sed/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 214193326Sed/// implicit conversions. 215193326SedImplicitConversionRank StandardConversionSequence::getRank() const { 216193326Sed ImplicitConversionRank Rank = ICR_Exact_Match; 217193326Sed if (GetConversionRank(First) > Rank) 218193326Sed Rank = GetConversionRank(First); 219193326Sed if (GetConversionRank(Second) > Rank) 220193326Sed Rank = GetConversionRank(Second); 221193326Sed if (GetConversionRank(Third) > Rank) 222193326Sed Rank = GetConversionRank(Third); 223193326Sed return Rank; 224193326Sed} 225193326Sed 226193326Sed/// isPointerConversionToBool - Determines whether this conversion is 227193326Sed/// a conversion of a pointer or pointer-to-member to bool. This is 228198092Srdivacky/// used as part of the ranking of standard conversion sequences 229193326Sed/// (C++ 13.3.3.2p4). 230198092Srdivackybool StandardConversionSequence::isPointerConversionToBool() const { 231193326Sed // Note that FromType has not necessarily been transformed by the 232193326Sed // array-to-pointer or function-to-pointer implicit conversions, so 233193326Sed // check for their presence as well as checking whether FromType is 234193326Sed // a pointer. 235203955Srdivacky if (getToType(1)->isBooleanType() && 236210299Sed (getFromType()->isPointerType() || 237210299Sed getFromType()->isObjCObjectPointerType() || 238210299Sed getFromType()->isBlockPointerType() || 239218893Sdim getFromType()->isNullPtrType() || 240193326Sed First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 241193326Sed return true; 242193326Sed 243193326Sed return false; 244193326Sed} 245193326Sed 246193326Sed/// isPointerConversionToVoidPointer - Determines whether this 247193326Sed/// conversion is a conversion of a pointer to a void pointer. This is 248193326Sed/// used as part of the ranking of standard conversion sequences (C++ 249193326Sed/// 13.3.3.2p4). 250198092Srdivackybool 251193326SedStandardConversionSequence:: 252198092SrdivackyisPointerConversionToVoidPointer(ASTContext& Context) const { 253202379Srdivacky QualType FromType = getFromType(); 254203955Srdivacky QualType ToType = getToType(1); 255193326Sed 256193326Sed // Note that FromType has not necessarily been transformed by the 257193326Sed // array-to-pointer implicit conversion, so check for its presence 258193326Sed // and redo the conversion to get a pointer. 259193326Sed if (First == ICK_Array_To_Pointer) 260193326Sed FromType = Context.getArrayDecayedType(FromType); 261193326Sed 262221345Sdim if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 263198092Srdivacky if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 264193326Sed return ToPtrType->getPointeeType()->isVoidType(); 265193326Sed 266193326Sed return false; 267193326Sed} 268193326Sed 269234353Sdim/// Skip any implicit casts which could be either part of a narrowing conversion 270234353Sdim/// or after one in an implicit conversion. 271234353Sdimstatic const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 272234353Sdim while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 273234353Sdim switch (ICE->getCastKind()) { 274234353Sdim case CK_NoOp: 275234353Sdim case CK_IntegralCast: 276234353Sdim case CK_IntegralToBoolean: 277234353Sdim case CK_IntegralToFloating: 278234353Sdim case CK_FloatingToIntegral: 279234353Sdim case CK_FloatingToBoolean: 280234353Sdim case CK_FloatingCast: 281234353Sdim Converted = ICE->getSubExpr(); 282234353Sdim continue; 283234353Sdim 284234353Sdim default: 285234353Sdim return Converted; 286234353Sdim } 287234353Sdim } 288234353Sdim 289234353Sdim return Converted; 290234353Sdim} 291234353Sdim 292234353Sdim/// Check if this standard conversion sequence represents a narrowing 293234353Sdim/// conversion, according to C++11 [dcl.init.list]p7. 294234353Sdim/// 295234353Sdim/// \param Ctx The AST context. 296234353Sdim/// \param Converted The result of applying this standard conversion sequence. 297234353Sdim/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 298234353Sdim/// value of the expression prior to the narrowing conversion. 299234353Sdim/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 300234353Sdim/// type of the expression prior to the narrowing conversion. 301234353SdimNarrowingKind 302234353SdimStandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 303234353Sdim const Expr *Converted, 304234353Sdim APValue &ConstantValue, 305234353Sdim QualType &ConstantType) const { 306234353Sdim assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 307234353Sdim 308234353Sdim // C++11 [dcl.init.list]p7: 309234353Sdim // A narrowing conversion is an implicit conversion ... 310234353Sdim QualType FromType = getToType(0); 311234353Sdim QualType ToType = getToType(1); 312234353Sdim switch (Second) { 313234353Sdim // -- from a floating-point type to an integer type, or 314234353Sdim // 315234353Sdim // -- from an integer type or unscoped enumeration type to a floating-point 316234353Sdim // type, except where the source is a constant expression and the actual 317234353Sdim // value after conversion will fit into the target type and will produce 318234353Sdim // the original value when converted back to the original type, or 319234353Sdim case ICK_Floating_Integral: 320234353Sdim if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 321234353Sdim return NK_Type_Narrowing; 322234353Sdim } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 323234353Sdim llvm::APSInt IntConstantValue; 324234353Sdim const Expr *Initializer = IgnoreNarrowingConversion(Converted); 325234353Sdim if (Initializer && 326234353Sdim Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 327234353Sdim // Convert the integer to the floating type. 328234353Sdim llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 329234353Sdim Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 330234353Sdim llvm::APFloat::rmNearestTiesToEven); 331234353Sdim // And back. 332234353Sdim llvm::APSInt ConvertedValue = IntConstantValue; 333234353Sdim bool ignored; 334234353Sdim Result.convertToInteger(ConvertedValue, 335234353Sdim llvm::APFloat::rmTowardZero, &ignored); 336234353Sdim // If the resulting value is different, this was a narrowing conversion. 337234353Sdim if (IntConstantValue != ConvertedValue) { 338234353Sdim ConstantValue = APValue(IntConstantValue); 339234353Sdim ConstantType = Initializer->getType(); 340234353Sdim return NK_Constant_Narrowing; 341234353Sdim } 342234353Sdim } else { 343234353Sdim // Variables are always narrowings. 344234353Sdim return NK_Variable_Narrowing; 345234353Sdim } 346234353Sdim } 347234353Sdim return NK_Not_Narrowing; 348234353Sdim 349234353Sdim // -- from long double to double or float, or from double to float, except 350234353Sdim // where the source is a constant expression and the actual value after 351234353Sdim // conversion is within the range of values that can be represented (even 352234353Sdim // if it cannot be represented exactly), or 353234353Sdim case ICK_Floating_Conversion: 354234353Sdim if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 355234353Sdim Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 356234353Sdim // FromType is larger than ToType. 357234353Sdim const Expr *Initializer = IgnoreNarrowingConversion(Converted); 358234353Sdim if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 359234353Sdim // Constant! 360234353Sdim assert(ConstantValue.isFloat()); 361234353Sdim llvm::APFloat FloatVal = ConstantValue.getFloat(); 362234353Sdim // Convert the source value into the target type. 363234353Sdim bool ignored; 364234353Sdim llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 365234353Sdim Ctx.getFloatTypeSemantics(ToType), 366234353Sdim llvm::APFloat::rmNearestTiesToEven, &ignored); 367234353Sdim // If there was no overflow, the source value is within the range of 368234353Sdim // values that can be represented. 369234353Sdim if (ConvertStatus & llvm::APFloat::opOverflow) { 370234353Sdim ConstantType = Initializer->getType(); 371234353Sdim return NK_Constant_Narrowing; 372234353Sdim } 373234353Sdim } else { 374234353Sdim return NK_Variable_Narrowing; 375234353Sdim } 376234353Sdim } 377234353Sdim return NK_Not_Narrowing; 378234353Sdim 379234353Sdim // -- from an integer type or unscoped enumeration type to an integer type 380234353Sdim // that cannot represent all the values of the original type, except where 381234353Sdim // the source is a constant expression and the actual value after 382234353Sdim // conversion will fit into the target type and will produce the original 383234353Sdim // value when converted back to the original type. 384234353Sdim case ICK_Boolean_Conversion: // Bools are integers too. 385234353Sdim if (!FromType->isIntegralOrUnscopedEnumerationType()) { 386234353Sdim // Boolean conversions can be from pointers and pointers to members 387234353Sdim // [conv.bool], and those aren't considered narrowing conversions. 388234353Sdim return NK_Not_Narrowing; 389234353Sdim } // Otherwise, fall through to the integral case. 390234353Sdim case ICK_Integral_Conversion: { 391234353Sdim assert(FromType->isIntegralOrUnscopedEnumerationType()); 392234353Sdim assert(ToType->isIntegralOrUnscopedEnumerationType()); 393234353Sdim const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 394234353Sdim const unsigned FromWidth = Ctx.getIntWidth(FromType); 395234353Sdim const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 396234353Sdim const unsigned ToWidth = Ctx.getIntWidth(ToType); 397234353Sdim 398234353Sdim if (FromWidth > ToWidth || 399239462Sdim (FromWidth == ToWidth && FromSigned != ToSigned) || 400239462Sdim (FromSigned && !ToSigned)) { 401234353Sdim // Not all values of FromType can be represented in ToType. 402234353Sdim llvm::APSInt InitializerValue; 403234353Sdim const Expr *Initializer = IgnoreNarrowingConversion(Converted); 404239462Sdim if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 405239462Sdim // Such conversions on variables are always narrowing. 406239462Sdim return NK_Variable_Narrowing; 407239462Sdim } 408239462Sdim bool Narrowing = false; 409239462Sdim if (FromWidth < ToWidth) { 410239462Sdim // Negative -> unsigned is narrowing. Otherwise, more bits is never 411239462Sdim // narrowing. 412239462Sdim if (InitializerValue.isSigned() && InitializerValue.isNegative()) 413239462Sdim Narrowing = true; 414239462Sdim } else { 415234353Sdim // Add a bit to the InitializerValue so we don't have to worry about 416234353Sdim // signed vs. unsigned comparisons. 417234353Sdim InitializerValue = InitializerValue.extend( 418234353Sdim InitializerValue.getBitWidth() + 1); 419234353Sdim // Convert the initializer to and from the target width and signed-ness. 420234353Sdim llvm::APSInt ConvertedValue = InitializerValue; 421234353Sdim ConvertedValue = ConvertedValue.trunc(ToWidth); 422234353Sdim ConvertedValue.setIsSigned(ToSigned); 423234353Sdim ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 424234353Sdim ConvertedValue.setIsSigned(InitializerValue.isSigned()); 425234353Sdim // If the result is different, this was a narrowing conversion. 426239462Sdim if (ConvertedValue != InitializerValue) 427239462Sdim Narrowing = true; 428234353Sdim } 429239462Sdim if (Narrowing) { 430239462Sdim ConstantType = Initializer->getType(); 431239462Sdim ConstantValue = APValue(InitializerValue); 432239462Sdim return NK_Constant_Narrowing; 433239462Sdim } 434234353Sdim } 435234353Sdim return NK_Not_Narrowing; 436234353Sdim } 437234353Sdim 438234353Sdim default: 439234353Sdim // Other kinds of conversions are not narrowings. 440234353Sdim return NK_Not_Narrowing; 441234353Sdim } 442234353Sdim} 443234353Sdim 444193326Sed/// DebugPrint - Print this standard conversion sequence to standard 445193326Sed/// error. Useful for debugging overloading issues. 446193326Sedvoid StandardConversionSequence::DebugPrint() const { 447226633Sdim raw_ostream &OS = llvm::errs(); 448193326Sed bool PrintedSomething = false; 449193326Sed if (First != ICK_Identity) { 450202879Srdivacky OS << GetImplicitConversionName(First); 451193326Sed PrintedSomething = true; 452193326Sed } 453193326Sed 454193326Sed if (Second != ICK_Identity) { 455193326Sed if (PrintedSomething) { 456202879Srdivacky OS << " -> "; 457193326Sed } 458202879Srdivacky OS << GetImplicitConversionName(Second); 459193326Sed 460193326Sed if (CopyConstructor) { 461202879Srdivacky OS << " (by copy constructor)"; 462193326Sed } else if (DirectBinding) { 463202879Srdivacky OS << " (direct reference binding)"; 464193326Sed } else if (ReferenceBinding) { 465202879Srdivacky OS << " (reference binding)"; 466193326Sed } 467193326Sed PrintedSomething = true; 468193326Sed } 469193326Sed 470193326Sed if (Third != ICK_Identity) { 471193326Sed if (PrintedSomething) { 472202879Srdivacky OS << " -> "; 473193326Sed } 474202879Srdivacky OS << GetImplicitConversionName(Third); 475193326Sed PrintedSomething = true; 476193326Sed } 477193326Sed 478193326Sed if (!PrintedSomething) { 479202879Srdivacky OS << "No conversions required"; 480193326Sed } 481193326Sed} 482193326Sed 483193326Sed/// DebugPrint - Print this user-defined conversion sequence to standard 484193326Sed/// error. Useful for debugging overloading issues. 485193326Sedvoid UserDefinedConversionSequence::DebugPrint() const { 486226633Sdim raw_ostream &OS = llvm::errs(); 487193326Sed if (Before.First || Before.Second || Before.Third) { 488193326Sed Before.DebugPrint(); 489202879Srdivacky OS << " -> "; 490193326Sed } 491234353Sdim if (ConversionFunction) 492234353Sdim OS << '\'' << *ConversionFunction << '\''; 493234353Sdim else 494234353Sdim OS << "aggregate initialization"; 495193326Sed if (After.First || After.Second || After.Third) { 496202879Srdivacky OS << " -> "; 497193326Sed After.DebugPrint(); 498193326Sed } 499193326Sed} 500193326Sed 501193326Sed/// DebugPrint - Print this implicit conversion sequence to standard 502193326Sed/// error. Useful for debugging overloading issues. 503193326Sedvoid ImplicitConversionSequence::DebugPrint() const { 504226633Sdim raw_ostream &OS = llvm::errs(); 505193326Sed switch (ConversionKind) { 506193326Sed case StandardConversion: 507202879Srdivacky OS << "Standard conversion: "; 508193326Sed Standard.DebugPrint(); 509193326Sed break; 510193326Sed case UserDefinedConversion: 511202879Srdivacky OS << "User-defined conversion: "; 512193326Sed UserDefined.DebugPrint(); 513193326Sed break; 514193326Sed case EllipsisConversion: 515202879Srdivacky OS << "Ellipsis conversion"; 516193326Sed break; 517202379Srdivacky case AmbiguousConversion: 518202879Srdivacky OS << "Ambiguous conversion"; 519202379Srdivacky break; 520193326Sed case BadConversion: 521202879Srdivacky OS << "Bad conversion"; 522193326Sed break; 523193326Sed } 524193326Sed 525202879Srdivacky OS << "\n"; 526193326Sed} 527193326Sed 528202379Srdivackyvoid AmbiguousConversionSequence::construct() { 529202379Srdivacky new (&conversions()) ConversionSet(); 530202379Srdivacky} 531202379Srdivacky 532202379Srdivackyvoid AmbiguousConversionSequence::destruct() { 533202379Srdivacky conversions().~ConversionSet(); 534202379Srdivacky} 535202379Srdivacky 536202379Srdivackyvoid 537202379SrdivackyAmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 538202379Srdivacky FromTypePtr = O.FromTypePtr; 539202379Srdivacky ToTypePtr = O.ToTypePtr; 540202379Srdivacky new (&conversions()) ConversionSet(O.conversions()); 541202379Srdivacky} 542202379Srdivacky 543208600Srdivackynamespace { 544208600Srdivacky // Structure used by OverloadCandidate::DeductionFailureInfo to store 545249423Sdim // template argument information. 546249423Sdim struct DFIArguments { 547208600Srdivacky TemplateArgument FirstArg; 548208600Srdivacky TemplateArgument SecondArg; 549208600Srdivacky }; 550249423Sdim // Structure used by OverloadCandidate::DeductionFailureInfo to store 551249423Sdim // template parameter and template argument information. 552249423Sdim struct DFIParamWithArguments : DFIArguments { 553249423Sdim TemplateParameter Param; 554249423Sdim }; 555208600Srdivacky} 556218893Sdim 557208600Srdivacky/// \brief Convert from Sema's representation of template deduction information 558208600Srdivacky/// to the form used in overload-candidate information. 559208600SrdivackyOverloadCandidate::DeductionFailureInfo 560208600Srdivackystatic MakeDeductionFailureInfo(ASTContext &Context, 561208600Srdivacky Sema::TemplateDeductionResult TDK, 562212904Sdim TemplateDeductionInfo &Info) { 563208600Srdivacky OverloadCandidate::DeductionFailureInfo Result; 564208600Srdivacky Result.Result = static_cast<unsigned>(TDK); 565239462Sdim Result.HasDiagnostic = false; 566208600Srdivacky Result.Data = 0; 567208600Srdivacky switch (TDK) { 568208600Srdivacky case Sema::TDK_Success: 569243830Sdim case Sema::TDK_Invalid: 570208600Srdivacky case Sema::TDK_InstantiationDepth: 571208600Srdivacky case Sema::TDK_TooManyArguments: 572208600Srdivacky case Sema::TDK_TooFewArguments: 573208600Srdivacky break; 574218893Sdim 575208600Srdivacky case Sema::TDK_Incomplete: 576208600Srdivacky case Sema::TDK_InvalidExplicitArguments: 577208600Srdivacky Result.Data = Info.Param.getOpaqueValue(); 578208600Srdivacky break; 579218893Sdim 580249423Sdim case Sema::TDK_NonDeducedMismatch: { 581249423Sdim // FIXME: Should allocate from normal heap so that we can free this later. 582249423Sdim DFIArguments *Saved = new (Context) DFIArguments; 583249423Sdim Saved->FirstArg = Info.FirstArg; 584249423Sdim Saved->SecondArg = Info.SecondArg; 585249423Sdim Result.Data = Saved; 586249423Sdim break; 587249423Sdim } 588249423Sdim 589208600Srdivacky case Sema::TDK_Inconsistent: 590212904Sdim case Sema::TDK_Underqualified: { 591208600Srdivacky // FIXME: Should allocate from normal heap so that we can free this later. 592208600Srdivacky DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 593208600Srdivacky Saved->Param = Info.Param; 594208600Srdivacky Saved->FirstArg = Info.FirstArg; 595208600Srdivacky Saved->SecondArg = Info.SecondArg; 596208600Srdivacky Result.Data = Saved; 597208600Srdivacky break; 598208600Srdivacky } 599218893Sdim 600208600Srdivacky case Sema::TDK_SubstitutionFailure: 601208600Srdivacky Result.Data = Info.take(); 602239462Sdim if (Info.hasSFINAEDiagnostic()) { 603239462Sdim PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 604239462Sdim SourceLocation(), PartialDiagnostic::NullDiagnostic()); 605239462Sdim Info.takeSFINAEDiagnostic(*Diag); 606239462Sdim Result.HasDiagnostic = true; 607239462Sdim } 608208600Srdivacky break; 609218893Sdim 610208600Srdivacky case Sema::TDK_FailedOverloadResolution: 611249423Sdim Result.Data = Info.Expression; 612218893Sdim break; 613249423Sdim 614249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 615249423Sdim break; 616208600Srdivacky } 617218893Sdim 618208600Srdivacky return Result; 619208600Srdivacky} 620202379Srdivacky 621208600Srdivackyvoid OverloadCandidate::DeductionFailureInfo::Destroy() { 622208600Srdivacky switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 623208600Srdivacky case Sema::TDK_Success: 624243830Sdim case Sema::TDK_Invalid: 625208600Srdivacky case Sema::TDK_InstantiationDepth: 626208600Srdivacky case Sema::TDK_Incomplete: 627208600Srdivacky case Sema::TDK_TooManyArguments: 628208600Srdivacky case Sema::TDK_TooFewArguments: 629208600Srdivacky case Sema::TDK_InvalidExplicitArguments: 630249423Sdim case Sema::TDK_FailedOverloadResolution: 631208600Srdivacky break; 632218893Sdim 633208600Srdivacky case Sema::TDK_Inconsistent: 634212904Sdim case Sema::TDK_Underqualified: 635249423Sdim case Sema::TDK_NonDeducedMismatch: 636208600Srdivacky // FIXME: Destroy the data? 637208600Srdivacky Data = 0; 638208600Srdivacky break; 639208600Srdivacky 640208600Srdivacky case Sema::TDK_SubstitutionFailure: 641239462Sdim // FIXME: Destroy the template argument list? 642208600Srdivacky Data = 0; 643239462Sdim if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 644239462Sdim Diag->~PartialDiagnosticAt(); 645239462Sdim HasDiagnostic = false; 646239462Sdim } 647208600Srdivacky break; 648218893Sdim 649208600Srdivacky // Unhandled 650249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 651208600Srdivacky break; 652208600Srdivacky } 653208600Srdivacky} 654218893Sdim 655239462SdimPartialDiagnosticAt * 656239462SdimOverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 657239462Sdim if (HasDiagnostic) 658239462Sdim return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 659239462Sdim return 0; 660239462Sdim} 661239462Sdim 662218893SdimTemplateParameter 663208600SrdivackyOverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 664208600Srdivacky switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 665208600Srdivacky case Sema::TDK_Success: 666243830Sdim case Sema::TDK_Invalid: 667208600Srdivacky case Sema::TDK_InstantiationDepth: 668208600Srdivacky case Sema::TDK_TooManyArguments: 669208600Srdivacky case Sema::TDK_TooFewArguments: 670208600Srdivacky case Sema::TDK_SubstitutionFailure: 671249423Sdim case Sema::TDK_NonDeducedMismatch: 672249423Sdim case Sema::TDK_FailedOverloadResolution: 673208600Srdivacky return TemplateParameter(); 674218893Sdim 675208600Srdivacky case Sema::TDK_Incomplete: 676208600Srdivacky case Sema::TDK_InvalidExplicitArguments: 677218893Sdim return TemplateParameter::getFromOpaqueValue(Data); 678208600Srdivacky 679208600Srdivacky case Sema::TDK_Inconsistent: 680212904Sdim case Sema::TDK_Underqualified: 681208600Srdivacky return static_cast<DFIParamWithArguments*>(Data)->Param; 682218893Sdim 683208600Srdivacky // Unhandled 684249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 685208600Srdivacky break; 686208600Srdivacky } 687218893Sdim 688208600Srdivacky return TemplateParameter(); 689208600Srdivacky} 690218893Sdim 691208600SrdivackyTemplateArgumentList * 692208600SrdivackyOverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 693208600Srdivacky switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 694249423Sdim case Sema::TDK_Success: 695249423Sdim case Sema::TDK_Invalid: 696249423Sdim case Sema::TDK_InstantiationDepth: 697249423Sdim case Sema::TDK_TooManyArguments: 698249423Sdim case Sema::TDK_TooFewArguments: 699249423Sdim case Sema::TDK_Incomplete: 700249423Sdim case Sema::TDK_InvalidExplicitArguments: 701249423Sdim case Sema::TDK_Inconsistent: 702249423Sdim case Sema::TDK_Underqualified: 703249423Sdim case Sema::TDK_NonDeducedMismatch: 704249423Sdim case Sema::TDK_FailedOverloadResolution: 705249423Sdim return 0; 706208600Srdivacky 707249423Sdim case Sema::TDK_SubstitutionFailure: 708249423Sdim return static_cast<TemplateArgumentList*>(Data); 709218893Sdim 710249423Sdim // Unhandled 711249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 712249423Sdim break; 713208600Srdivacky } 714208600Srdivacky 715208600Srdivacky return 0; 716208600Srdivacky} 717208600Srdivacky 718208600Srdivackyconst TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 719208600Srdivacky switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 720208600Srdivacky case Sema::TDK_Success: 721243830Sdim case Sema::TDK_Invalid: 722208600Srdivacky case Sema::TDK_InstantiationDepth: 723208600Srdivacky case Sema::TDK_Incomplete: 724208600Srdivacky case Sema::TDK_TooManyArguments: 725208600Srdivacky case Sema::TDK_TooFewArguments: 726208600Srdivacky case Sema::TDK_InvalidExplicitArguments: 727208600Srdivacky case Sema::TDK_SubstitutionFailure: 728249423Sdim case Sema::TDK_FailedOverloadResolution: 729208600Srdivacky return 0; 730208600Srdivacky 731208600Srdivacky case Sema::TDK_Inconsistent: 732212904Sdim case Sema::TDK_Underqualified: 733249423Sdim case Sema::TDK_NonDeducedMismatch: 734249423Sdim return &static_cast<DFIArguments*>(Data)->FirstArg; 735208600Srdivacky 736208600Srdivacky // Unhandled 737249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 738208600Srdivacky break; 739208600Srdivacky } 740218893Sdim 741208600Srdivacky return 0; 742218893Sdim} 743208600Srdivacky 744208600Srdivackyconst TemplateArgument * 745208600SrdivackyOverloadCandidate::DeductionFailureInfo::getSecondArg() { 746208600Srdivacky switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 747208600Srdivacky case Sema::TDK_Success: 748243830Sdim case Sema::TDK_Invalid: 749208600Srdivacky case Sema::TDK_InstantiationDepth: 750208600Srdivacky case Sema::TDK_Incomplete: 751208600Srdivacky case Sema::TDK_TooManyArguments: 752208600Srdivacky case Sema::TDK_TooFewArguments: 753208600Srdivacky case Sema::TDK_InvalidExplicitArguments: 754208600Srdivacky case Sema::TDK_SubstitutionFailure: 755249423Sdim case Sema::TDK_FailedOverloadResolution: 756208600Srdivacky return 0; 757208600Srdivacky 758208600Srdivacky case Sema::TDK_Inconsistent: 759212904Sdim case Sema::TDK_Underqualified: 760249423Sdim case Sema::TDK_NonDeducedMismatch: 761249423Sdim return &static_cast<DFIArguments*>(Data)->SecondArg; 762208600Srdivacky 763208600Srdivacky // Unhandled 764249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 765208600Srdivacky break; 766208600Srdivacky } 767218893Sdim 768208600Srdivacky return 0; 769208600Srdivacky} 770208600Srdivacky 771249423SdimExpr * 772249423SdimOverloadCandidate::DeductionFailureInfo::getExpr() { 773249423Sdim if (static_cast<Sema::TemplateDeductionResult>(Result) == 774249423Sdim Sema::TDK_FailedOverloadResolution) 775249423Sdim return static_cast<Expr*>(Data); 776249423Sdim 777249423Sdim return 0; 778249423Sdim} 779249423Sdim 780243830Sdimvoid OverloadCandidateSet::destroyCandidates() { 781239462Sdim for (iterator i = begin(), e = end(); i != e; ++i) { 782234353Sdim for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 783234353Sdim i->Conversions[ii].~ImplicitConversionSequence(); 784239462Sdim if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 785239462Sdim i->DeductionFailure.Destroy(); 786239462Sdim } 787243830Sdim} 788243830Sdim 789243830Sdimvoid OverloadCandidateSet::clear() { 790243830Sdim destroyCandidates(); 791234353Sdim NumInlineSequences = 0; 792234353Sdim Candidates.clear(); 793208600Srdivacky Functions.clear(); 794208600Srdivacky} 795218893Sdim 796234353Sdimnamespace { 797234353Sdim class UnbridgedCastsSet { 798234353Sdim struct Entry { 799234353Sdim Expr **Addr; 800234353Sdim Expr *Saved; 801234353Sdim }; 802234353Sdim SmallVector<Entry, 2> Entries; 803234353Sdim 804234353Sdim public: 805234353Sdim void save(Sema &S, Expr *&E) { 806234353Sdim assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 807234353Sdim Entry entry = { &E, E }; 808234353Sdim Entries.push_back(entry); 809234353Sdim E = S.stripARCUnbridgedCast(E); 810234353Sdim } 811234353Sdim 812234353Sdim void restore() { 813234353Sdim for (SmallVectorImpl<Entry>::iterator 814234353Sdim i = Entries.begin(), e = Entries.end(); i != e; ++i) 815234353Sdim *i->Addr = i->Saved; 816234353Sdim } 817234353Sdim }; 818234353Sdim} 819234353Sdim 820234353Sdim/// checkPlaceholderForOverload - Do any interesting placeholder-like 821234353Sdim/// preprocessing on the given expression. 822234353Sdim/// 823234353Sdim/// \param unbridgedCasts a collection to which to add unbridged casts; 824234353Sdim/// without this, they will be immediately diagnosed as errors 825234353Sdim/// 826234353Sdim/// Return true on unrecoverable error. 827234353Sdimstatic bool checkPlaceholderForOverload(Sema &S, Expr *&E, 828234353Sdim UnbridgedCastsSet *unbridgedCasts = 0) { 829234353Sdim if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 830234353Sdim // We can't handle overloaded expressions here because overload 831234353Sdim // resolution might reasonably tweak them. 832234353Sdim if (placeholder->getKind() == BuiltinType::Overload) return false; 833234353Sdim 834234353Sdim // If the context potentially accepts unbridged ARC casts, strip 835234353Sdim // the unbridged cast and add it to the collection for later restoration. 836234353Sdim if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 837234353Sdim unbridgedCasts) { 838234353Sdim unbridgedCasts->save(S, E); 839234353Sdim return false; 840234353Sdim } 841234353Sdim 842234353Sdim // Go ahead and check everything else. 843234353Sdim ExprResult result = S.CheckPlaceholderExpr(E); 844234353Sdim if (result.isInvalid()) 845234353Sdim return true; 846234353Sdim 847234353Sdim E = result.take(); 848234353Sdim return false; 849234353Sdim } 850234353Sdim 851234353Sdim // Nothing to do. 852234353Sdim return false; 853234353Sdim} 854234353Sdim 855234353Sdim/// checkArgPlaceholdersForOverload - Check a set of call operands for 856234353Sdim/// placeholders. 857234353Sdimstatic bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 858234353Sdim unsigned numArgs, 859234353Sdim UnbridgedCastsSet &unbridged) { 860234353Sdim for (unsigned i = 0; i != numArgs; ++i) 861234353Sdim if (checkPlaceholderForOverload(S, args[i], &unbridged)) 862234353Sdim return true; 863234353Sdim 864234353Sdim return false; 865234353Sdim} 866234353Sdim 867193326Sed// IsOverload - Determine whether the given New declaration is an 868200583Srdivacky// overload of the declarations in Old. This routine returns false if 869200583Srdivacky// New and Old cannot be overloaded, e.g., if New has the same 870200583Srdivacky// signature as some function in Old (C++ 1.3.10) or if the Old 871200583Srdivacky// declarations aren't functions (or function templates) at all. When 872200583Srdivacky// it does return false, MatchedDecl will point to the decl that New 873200583Srdivacky// cannot be overloaded with. This decl may be a UsingShadowDecl on 874200583Srdivacky// top of the underlying declaration. 875193326Sed// 876193326Sed// Example: Given the following input: 877193326Sed// 878193326Sed// void f(int, float); // #1 879193326Sed// void f(int, int); // #2 880193326Sed// int f(int, int); // #3 881193326Sed// 882193326Sed// When we process #1, there is no previous declaration of "f", 883198092Srdivacky// so IsOverload will not be used. 884193326Sed// 885200583Srdivacky// When we process #2, Old contains only the FunctionDecl for #1. By 886200583Srdivacky// comparing the parameter types, we see that #1 and #2 are overloaded 887200583Srdivacky// (since they have different signatures), so this routine returns 888200583Srdivacky// false; MatchedDecl is unchanged. 889193326Sed// 890200583Srdivacky// When we process #3, Old is an overload set containing #1 and #2. We 891200583Srdivacky// compare the signatures of #3 to #1 (they're overloaded, so we do 892200583Srdivacky// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 893200583Srdivacky// identical (return types of functions are not part of the 894193326Sed// signature), IsOverload returns false and MatchedDecl will be set to 895193326Sed// point to the FunctionDecl for #2. 896210299Sed// 897210299Sed// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 898210299Sed// into a class by a using declaration. The rules for whether to hide 899210299Sed// shadow declarations ignore some properties which otherwise figure 900210299Sed// into a function template's signature. 901200583SrdivackySema::OverloadKind 902210299SedSema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 903210299Sed NamedDecl *&Match, bool NewIsUsingDecl) { 904200583Srdivacky for (LookupResult::iterator I = Old.begin(), E = Old.end(); 905199512Srdivacky I != E; ++I) { 906210299Sed NamedDecl *OldD = *I; 907210299Sed 908210299Sed bool OldIsUsingDecl = false; 909210299Sed if (isa<UsingShadowDecl>(OldD)) { 910210299Sed OldIsUsingDecl = true; 911210299Sed 912210299Sed // We can always introduce two using declarations into the same 913210299Sed // context, even if they have identical signatures. 914210299Sed if (NewIsUsingDecl) continue; 915210299Sed 916210299Sed OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 917210299Sed } 918210299Sed 919210299Sed // If either declaration was introduced by a using declaration, 920210299Sed // we'll need to use slightly different rules for matching. 921210299Sed // Essentially, these rules are the normal rules, except that 922210299Sed // function templates hide function templates with different 923210299Sed // return types or template parameter lists. 924210299Sed bool UseMemberUsingDeclRules = 925249423Sdim (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 926249423Sdim !New->getFriendObjectKind(); 927210299Sed 928200583Srdivacky if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 929210299Sed if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 930210299Sed if (UseMemberUsingDeclRules && OldIsUsingDecl) { 931210299Sed HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 932210299Sed continue; 933210299Sed } 934210299Sed 935200583Srdivacky Match = *I; 936200583Srdivacky return Ovl_Match; 937193326Sed } 938200583Srdivacky } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 939210299Sed if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 940210299Sed if (UseMemberUsingDeclRules && OldIsUsingDecl) { 941210299Sed HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 942210299Sed continue; 943210299Sed } 944210299Sed 945251662Sdim if (!shouldLinkPossiblyHiddenDecl(*I, New)) 946251662Sdim continue; 947251662Sdim 948200583Srdivacky Match = *I; 949200583Srdivacky return Ovl_Match; 950199512Srdivacky } 951218893Sdim } else if (isa<UsingDecl>(OldD)) { 952200583Srdivacky // We can overload with these, which can show up when doing 953200583Srdivacky // redeclaration checks for UsingDecls. 954200583Srdivacky assert(Old.getLookupKind() == LookupUsingDeclName); 955218893Sdim } else if (isa<TagDecl>(OldD)) { 956218893Sdim // We can always overload with tags by hiding them. 957200583Srdivacky } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 958200583Srdivacky // Optimistically assume that an unresolved using decl will 959200583Srdivacky // overload; if it doesn't, we'll have to diagnose during 960200583Srdivacky // template instantiation. 961199512Srdivacky } else { 962199512Srdivacky // (C++ 13p1): 963199512Srdivacky // Only function declarations can be overloaded; object and type 964199512Srdivacky // declarations cannot be overloaded. 965200583Srdivacky Match = *I; 966200583Srdivacky return Ovl_NonFunction; 967193326Sed } 968199512Srdivacky } 969193326Sed 970200583Srdivacky return Ovl_Overload; 971199512Srdivacky} 972198092Srdivacky 973249423Sdimstatic bool canBeOverloaded(const FunctionDecl &D) { 974249423Sdim if (D.getAttr<OverloadableAttr>()) 975249423Sdim return true; 976249423Sdim if (D.isExternC()) 977212904Sdim return false; 978212904Sdim 979249423Sdim // Main cannot be overloaded (basic.start.main). 980249423Sdim if (D.isMain()) 981249423Sdim return false; 982249423Sdim 983249423Sdim return true; 984249423Sdim} 985249423Sdim 986249423Sdimstatic bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old, 987249423Sdim bool UseUsingDeclRules) { 988199512Srdivacky FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 989199512Srdivacky FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 990195099Sed 991199512Srdivacky // C++ [temp.fct]p2: 992199512Srdivacky // A function template can be overloaded with other function templates 993199512Srdivacky // and with normal (non-template) functions. 994199512Srdivacky if ((OldTemplate == 0) != (NewTemplate == 0)) 995199512Srdivacky return true; 996193326Sed 997199512Srdivacky // Is the function New an overload of the function Old? 998249423Sdim QualType OldQType = S.Context.getCanonicalType(Old->getType()); 999249423Sdim QualType NewQType = S.Context.getCanonicalType(New->getType()); 1000193326Sed 1001199512Srdivacky // Compare the signatures (C++ 1.3.10) of the two functions to 1002199512Srdivacky // determine whether they are overloads. If we find any mismatch 1003199512Srdivacky // in the signature, they are overloads. 1004193326Sed 1005199512Srdivacky // If either of these functions is a K&R-style function (no 1006199512Srdivacky // prototype), then we consider them to have matching signatures. 1007199512Srdivacky if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1008199512Srdivacky isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1009199512Srdivacky return false; 1010193326Sed 1011218893Sdim const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1012218893Sdim const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1013193326Sed 1014199512Srdivacky // The signature of a function includes the types of its 1015199512Srdivacky // parameters (C++ 1.3.10), which includes the presence or absence 1016199512Srdivacky // of the ellipsis; see C++ DR 357). 1017199512Srdivacky if (OldQType != NewQType && 1018199512Srdivacky (OldType->getNumArgs() != NewType->getNumArgs() || 1019199512Srdivacky OldType->isVariadic() != NewType->isVariadic() || 1020249423Sdim !S.FunctionArgTypesAreEqual(OldType, NewType))) 1021199512Srdivacky return true; 1022198092Srdivacky 1023199512Srdivacky // C++ [temp.over.link]p4: 1024199512Srdivacky // The signature of a function template consists of its function 1025199512Srdivacky // signature, its return type and its template parameter list. The names 1026199512Srdivacky // of the template parameters are significant only for establishing the 1027199512Srdivacky // relationship between the template parameters and the rest of the 1028199512Srdivacky // signature. 1029199512Srdivacky // 1030199512Srdivacky // We check the return type and template parameter lists for function 1031199512Srdivacky // templates first; the remaining checks follow. 1032210299Sed // 1033210299Sed // However, we don't consider either of these when deciding whether 1034210299Sed // a member introduced by a shadow declaration is hidden. 1035210299Sed if (!UseUsingDeclRules && NewTemplate && 1036249423Sdim (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1037249423Sdim OldTemplate->getTemplateParameters(), 1038249423Sdim false, S.TPL_TemplateMatch) || 1039199512Srdivacky OldType->getResultType() != NewType->getResultType())) 1040199512Srdivacky return true; 1041193326Sed 1042199512Srdivacky // If the function is a class member, its signature includes the 1043218893Sdim // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1044199512Srdivacky // 1045199512Srdivacky // As part of this, also check whether one of the member functions 1046199512Srdivacky // is static, in which case they are not overloads (C++ 1047199512Srdivacky // 13.1p2). While not part of the definition of the signature, 1048199512Srdivacky // this check is important to determine whether these functions 1049199512Srdivacky // can be overloaded. 1050249423Sdim CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1051249423Sdim CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1052199512Srdivacky if (OldMethod && NewMethod && 1053249423Sdim !OldMethod->isStatic() && !NewMethod->isStatic()) { 1054249423Sdim if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1055249423Sdim if (!UseUsingDeclRules && 1056249423Sdim (OldMethod->getRefQualifier() == RQ_None || 1057249423Sdim NewMethod->getRefQualifier() == RQ_None)) { 1058249423Sdim // C++0x [over.load]p2: 1059249423Sdim // - Member function declarations with the same name and the same 1060249423Sdim // parameter-type-list as well as member function template 1061249423Sdim // declarations with the same name, the same parameter-type-list, and 1062249423Sdim // the same template parameter lists cannot be overloaded if any of 1063249423Sdim // them, but not all, have a ref-qualifier (8.3.5). 1064249423Sdim S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1065249423Sdim << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1066249423Sdim S.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1067249423Sdim } 1068249423Sdim return true; 1069218893Sdim } 1070218893Sdim 1071249423Sdim // We may not have applied the implicit const for a constexpr member 1072249423Sdim // function yet (because we haven't yet resolved whether this is a static 1073249423Sdim // or non-static member function). Add it now, on the assumption that this 1074249423Sdim // is a redeclaration of OldMethod. 1075249423Sdim unsigned NewQuals = NewMethod->getTypeQualifiers(); 1076249423Sdim if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod)) 1077249423Sdim NewQuals |= Qualifiers::Const; 1078249423Sdim if (OldMethod->getTypeQualifiers() != NewQuals) 1079249423Sdim return true; 1080218893Sdim } 1081218893Sdim 1082199512Srdivacky // The signatures match; this is not an overload. 1083199512Srdivacky return false; 1084193326Sed} 1085193326Sed 1086249423Sdimbool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1087249423Sdim bool UseUsingDeclRules) { 1088249423Sdim if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules)) 1089249423Sdim return false; 1090249423Sdim 1091249423Sdim // If both of the functions are extern "C", then they are not 1092249423Sdim // overloads. 1093249423Sdim if (!canBeOverloaded(*Old) && !canBeOverloaded(*New)) 1094249423Sdim return false; 1095249423Sdim 1096249423Sdim return true; 1097249423Sdim} 1098249423Sdim 1099224145Sdim/// \brief Checks availability of the function depending on the current 1100224145Sdim/// function context. Inside an unavailable function, unavailability is ignored. 1101224145Sdim/// 1102224145Sdim/// \returns true if \arg FD is unavailable and current context is inside 1103224145Sdim/// an available function, false otherwise. 1104224145Sdimbool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1105224145Sdim return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1106224145Sdim} 1107224145Sdim 1108234353Sdim/// \brief Tries a user-defined conversion from From to ToType. 1109234353Sdim/// 1110234353Sdim/// Produces an implicit conversion sequence for when a standard conversion 1111234353Sdim/// is not an option. See TryImplicitConversion for more information. 1112234353Sdimstatic ImplicitConversionSequence 1113234353SdimTryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1114234353Sdim bool SuppressUserConversions, 1115234353Sdim bool AllowExplicit, 1116234353Sdim bool InOverloadResolution, 1117234353Sdim bool CStyle, 1118234353Sdim bool AllowObjCWritebackConversion) { 1119234353Sdim ImplicitConversionSequence ICS; 1120234353Sdim 1121234353Sdim if (SuppressUserConversions) { 1122234353Sdim // We're not in the case above, so there is no conversion that 1123234353Sdim // we can perform. 1124234353Sdim ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1125234353Sdim return ICS; 1126234353Sdim } 1127234353Sdim 1128234353Sdim // Attempt user-defined conversion. 1129234353Sdim OverloadCandidateSet Conversions(From->getExprLoc()); 1130234353Sdim OverloadingResult UserDefResult 1131234353Sdim = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1132234353Sdim AllowExplicit); 1133234353Sdim 1134234353Sdim if (UserDefResult == OR_Success) { 1135234353Sdim ICS.setUserDefined(); 1136234353Sdim // C++ [over.ics.user]p4: 1137234353Sdim // A conversion of an expression of class type to the same class 1138234353Sdim // type is given Exact Match rank, and a conversion of an 1139234353Sdim // expression of class type to a base class of that type is 1140234353Sdim // given Conversion rank, in spite of the fact that a copy 1141234353Sdim // constructor (i.e., a user-defined conversion function) is 1142234353Sdim // called for those cases. 1143234353Sdim if (CXXConstructorDecl *Constructor 1144234353Sdim = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1145234353Sdim QualType FromCanon 1146234353Sdim = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1147234353Sdim QualType ToCanon 1148234353Sdim = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1149234353Sdim if (Constructor->isCopyConstructor() && 1150234353Sdim (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1151234353Sdim // Turn this into a "standard" conversion sequence, so that it 1152234353Sdim // gets ranked with standard conversion sequences. 1153234353Sdim ICS.setStandard(); 1154234353Sdim ICS.Standard.setAsIdentityConversion(); 1155234353Sdim ICS.Standard.setFromType(From->getType()); 1156234353Sdim ICS.Standard.setAllToTypes(ToType); 1157234353Sdim ICS.Standard.CopyConstructor = Constructor; 1158234353Sdim if (ToCanon != FromCanon) 1159234353Sdim ICS.Standard.Second = ICK_Derived_To_Base; 1160234353Sdim } 1161234353Sdim } 1162234353Sdim 1163234353Sdim // C++ [over.best.ics]p4: 1164234353Sdim // However, when considering the argument of a user-defined 1165234353Sdim // conversion function that is a candidate by 13.3.1.3 when 1166234353Sdim // invoked for the copying of the temporary in the second step 1167234353Sdim // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1168234353Sdim // 13.3.1.6 in all cases, only standard conversion sequences and 1169234353Sdim // ellipsis conversion sequences are allowed. 1170234353Sdim if (SuppressUserConversions && ICS.isUserDefined()) { 1171234353Sdim ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1172234353Sdim } 1173234353Sdim } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1174234353Sdim ICS.setAmbiguous(); 1175234353Sdim ICS.Ambiguous.setFromType(From->getType()); 1176234353Sdim ICS.Ambiguous.setToType(ToType); 1177234353Sdim for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1178234353Sdim Cand != Conversions.end(); ++Cand) 1179234353Sdim if (Cand->Viable) 1180234353Sdim ICS.Ambiguous.addConversion(Cand->Function); 1181234353Sdim } else { 1182234353Sdim ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1183234353Sdim } 1184234353Sdim 1185234353Sdim return ICS; 1186234353Sdim} 1187234353Sdim 1188193326Sed/// TryImplicitConversion - Attempt to perform an implicit conversion 1189193326Sed/// from the given expression (Expr) to the given type (ToType). This 1190193326Sed/// function returns an implicit conversion sequence that can be used 1191193326Sed/// to perform the initialization. Given 1192193326Sed/// 1193193326Sed/// void f(float f); 1194193326Sed/// void g(int i) { f(i); } 1195193326Sed/// 1196193326Sed/// this routine would produce an implicit conversion sequence to 1197193326Sed/// describe the initialization of f from i, which will be a standard 1198193326Sed/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1199193326Sed/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1200193326Sed// 1201193326Sed/// Note that this routine only determines how the conversion can be 1202193326Sed/// performed; it does not actually perform the conversion. As such, 1203193326Sed/// it will not produce any diagnostics if no conversion is available, 1204193326Sed/// but will instead return an implicit conversion sequence of kind 1205193326Sed/// "BadConversion". 1206193326Sed/// 1207193326Sed/// If @p SuppressUserConversions, then user-defined conversions are 1208193326Sed/// not permitted. 1209193326Sed/// If @p AllowExplicit, then explicit user-defined conversions are 1210193326Sed/// permitted. 1211224145Sdim/// 1212224145Sdim/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1213224145Sdim/// writeback conversion, which allows __autoreleasing id* parameters to 1214224145Sdim/// be initialized with __strong id* or __weak id* arguments. 1215212904Sdimstatic ImplicitConversionSequence 1216212904SdimTryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1217212904Sdim bool SuppressUserConversions, 1218218893Sdim bool AllowExplicit, 1219218893Sdim bool InOverloadResolution, 1220224145Sdim bool CStyle, 1221224145Sdim bool AllowObjCWritebackConversion) { 1222193326Sed ImplicitConversionSequence ICS; 1223212904Sdim if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1224224145Sdim ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1225202379Srdivacky ICS.setStandard(); 1226203955Srdivacky return ICS; 1227203955Srdivacky } 1228203955Srdivacky 1229234353Sdim if (!S.getLangOpts().CPlusPlus) { 1230204643Srdivacky ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1231203955Srdivacky return ICS; 1232203955Srdivacky } 1233203955Srdivacky 1234212904Sdim // C++ [over.ics.user]p4: 1235212904Sdim // A conversion of an expression of class type to the same class 1236212904Sdim // type is given Exact Match rank, and a conversion of an 1237212904Sdim // expression of class type to a base class of that type is 1238212904Sdim // given Conversion rank, in spite of the fact that a copy/move 1239212904Sdim // constructor (i.e., a user-defined conversion function) is 1240212904Sdim // called for those cases. 1241212904Sdim QualType FromType = From->getType(); 1242212904Sdim if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1243212904Sdim (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1244212904Sdim S.IsDerivedFrom(FromType, ToType))) { 1245207619Srdivacky ICS.setStandard(); 1246207619Srdivacky ICS.Standard.setAsIdentityConversion(); 1247207619Srdivacky ICS.Standard.setFromType(FromType); 1248207619Srdivacky ICS.Standard.setAllToTypes(ToType); 1249218893Sdim 1250207619Srdivacky // We don't actually check at this point whether there is a valid 1251207619Srdivacky // copy/move constructor, since overloading just assumes that it 1252207619Srdivacky // exists. When we actually perform initialization, we'll find the 1253207619Srdivacky // appropriate constructor to copy the returned object, if needed. 1254207619Srdivacky ICS.Standard.CopyConstructor = 0; 1255218893Sdim 1256207619Srdivacky // Determine whether this is considered a derived-to-base conversion. 1257212904Sdim if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1258207619Srdivacky ICS.Standard.Second = ICK_Derived_To_Base; 1259218893Sdim 1260207619Srdivacky return ICS; 1261207619Srdivacky } 1262218893Sdim 1263234353Sdim return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1264234353Sdim AllowExplicit, InOverloadResolution, CStyle, 1265234353Sdim AllowObjCWritebackConversion); 1266193326Sed} 1267193326Sed 1268224145SdimImplicitConversionSequence 1269224145SdimSema::TryImplicitConversion(Expr *From, QualType ToType, 1270224145Sdim bool SuppressUserConversions, 1271224145Sdim bool AllowExplicit, 1272224145Sdim bool InOverloadResolution, 1273224145Sdim bool CStyle, 1274224145Sdim bool AllowObjCWritebackConversion) { 1275224145Sdim return clang::TryImplicitConversion(*this, From, ToType, 1276224145Sdim SuppressUserConversions, AllowExplicit, 1277224145Sdim InOverloadResolution, CStyle, 1278224145Sdim AllowObjCWritebackConversion); 1279212904Sdim} 1280212904Sdim 1281207619Srdivacky/// PerformImplicitConversion - Perform an implicit conversion of the 1282221345Sdim/// expression From to the type ToType. Returns the 1283207619Srdivacky/// converted expression. Flavor is the kind of conversion we're 1284207619Srdivacky/// performing, used in the error message. If @p AllowExplicit, 1285207619Srdivacky/// explicit user-defined conversions are permitted. 1286221345SdimExprResult 1287221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType, 1288234353Sdim AssignmentAction Action, bool AllowExplicit) { 1289207619Srdivacky ImplicitConversionSequence ICS; 1290234353Sdim return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1291207619Srdivacky} 1292207619Srdivacky 1293221345SdimExprResult 1294221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType, 1295207619Srdivacky AssignmentAction Action, bool AllowExplicit, 1296234353Sdim ImplicitConversionSequence& ICS) { 1297234353Sdim if (checkPlaceholderForOverload(*this, From)) 1298234353Sdim return ExprError(); 1299234353Sdim 1300224145Sdim // Objective-C ARC: Determine whether we will allow the writeback conversion. 1301224145Sdim bool AllowObjCWritebackConversion 1302234353Sdim = getLangOpts().ObjCAutoRefCount && 1303224145Sdim (Action == AA_Passing || Action == AA_Sending); 1304224145Sdim 1305212904Sdim ICS = clang::TryImplicitConversion(*this, From, ToType, 1306212904Sdim /*SuppressUserConversions=*/false, 1307212904Sdim AllowExplicit, 1308218893Sdim /*InOverloadResolution=*/false, 1309224145Sdim /*CStyle=*/false, 1310224145Sdim AllowObjCWritebackConversion); 1311207619Srdivacky return PerformImplicitConversion(From, ToType, ICS, Action); 1312207619Srdivacky} 1313218893Sdim 1314218893Sdim/// \brief Determine whether the conversion from FromType to ToType is a valid 1315200583Srdivacky/// conversion that strips "noreturn" off the nested function type. 1316224145Sdimbool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1317224145Sdim QualType &ResultTy) { 1318200583Srdivacky if (Context.hasSameUnqualifiedType(FromType, ToType)) 1319200583Srdivacky return false; 1320200583Srdivacky 1321218893Sdim // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1322218893Sdim // where F adds one of the following at most once: 1323218893Sdim // - a pointer 1324218893Sdim // - a member pointer 1325218893Sdim // - a block pointer 1326218893Sdim CanQualType CanTo = Context.getCanonicalType(ToType); 1327218893Sdim CanQualType CanFrom = Context.getCanonicalType(FromType); 1328218893Sdim Type::TypeClass TyClass = CanTo->getTypeClass(); 1329218893Sdim if (TyClass != CanFrom->getTypeClass()) return false; 1330218893Sdim if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1331218893Sdim if (TyClass == Type::Pointer) { 1332218893Sdim CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1333218893Sdim CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1334218893Sdim } else if (TyClass == Type::BlockPointer) { 1335218893Sdim CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1336218893Sdim CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1337218893Sdim } else if (TyClass == Type::MemberPointer) { 1338218893Sdim CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1339218893Sdim CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1340218893Sdim } else { 1341218893Sdim return false; 1342218893Sdim } 1343218893Sdim 1344218893Sdim TyClass = CanTo->getTypeClass(); 1345218893Sdim if (TyClass != CanFrom->getTypeClass()) return false; 1346218893Sdim if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1347218893Sdim return false; 1348218893Sdim } 1349218893Sdim 1350218893Sdim const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1351218893Sdim FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1352218893Sdim if (!EInfo.getNoReturn()) return false; 1353218893Sdim 1354218893Sdim FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1355218893Sdim assert(QualType(FromFn, 0).isCanonical()); 1356218893Sdim if (QualType(FromFn, 0) != CanTo) return false; 1357218893Sdim 1358218893Sdim ResultTy = ToType; 1359200583Srdivacky return true; 1360200583Srdivacky} 1361218893Sdim 1362208600Srdivacky/// \brief Determine whether the conversion from FromType to ToType is a valid 1363208600Srdivacky/// vector conversion. 1364208600Srdivacky/// 1365208600Srdivacky/// \param ICK Will be set to the vector conversion kind, if this is a vector 1366208600Srdivacky/// conversion. 1367218893Sdimstatic bool IsVectorConversion(ASTContext &Context, QualType FromType, 1368218893Sdim QualType ToType, ImplicitConversionKind &ICK) { 1369208600Srdivacky // We need at least one of these types to be a vector type to have a vector 1370208600Srdivacky // conversion. 1371208600Srdivacky if (!ToType->isVectorType() && !FromType->isVectorType()) 1372208600Srdivacky return false; 1373208600Srdivacky 1374208600Srdivacky // Identical types require no conversions. 1375208600Srdivacky if (Context.hasSameUnqualifiedType(FromType, ToType)) 1376208600Srdivacky return false; 1377208600Srdivacky 1378208600Srdivacky // There are no conversions between extended vector types, only identity. 1379208600Srdivacky if (ToType->isExtVectorType()) { 1380208600Srdivacky // There are no conversions between extended vector types other than the 1381208600Srdivacky // identity conversion. 1382208600Srdivacky if (FromType->isExtVectorType()) 1383208600Srdivacky return false; 1384218893Sdim 1385208600Srdivacky // Vector splat from any arithmetic type to a vector. 1386210299Sed if (FromType->isArithmeticType()) { 1387208600Srdivacky ICK = ICK_Vector_Splat; 1388208600Srdivacky return true; 1389208600Srdivacky } 1390208600Srdivacky } 1391212904Sdim 1392212904Sdim // We can perform the conversion between vector types in the following cases: 1393212904Sdim // 1)vector types are equivalent AltiVec and GCC vector types 1394212904Sdim // 2)lax vector conversions are permitted and the vector types are of the 1395212904Sdim // same size 1396212904Sdim if (ToType->isVectorType() && FromType->isVectorType()) { 1397212904Sdim if (Context.areCompatibleVectorTypes(FromType, ToType) || 1398234353Sdim (Context.getLangOpts().LaxVectorConversions && 1399212904Sdim (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1400212904Sdim ICK = ICK_Vector_Conversion; 1401212904Sdim return true; 1402212904Sdim } 1403208600Srdivacky } 1404212904Sdim 1405208600Srdivacky return false; 1406208600Srdivacky} 1407218893Sdim 1408234353Sdimstatic bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1409234353Sdim bool InOverloadResolution, 1410234353Sdim StandardConversionSequence &SCS, 1411234353Sdim bool CStyle); 1412234353Sdim 1413193326Sed/// IsStandardConversion - Determines whether there is a standard 1414193326Sed/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1415193326Sed/// expression From to the type ToType. Standard conversion sequences 1416193326Sed/// only consider non-class types; for conversions that involve class 1417193326Sed/// types, use TryImplicitConversion. If a conversion exists, SCS will 1418193326Sed/// contain the standard conversion sequence required to perform this 1419193326Sed/// conversion and this routine will return true. Otherwise, this 1420193326Sed/// routine will return false and the value of SCS is unspecified. 1421212904Sdimstatic bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1422212904Sdim bool InOverloadResolution, 1423218893Sdim StandardConversionSequence &SCS, 1424224145Sdim bool CStyle, 1425224145Sdim bool AllowObjCWritebackConversion) { 1426193326Sed QualType FromType = From->getType(); 1427218893Sdim 1428193326Sed // Standard conversions (C++ [conv]) 1429193326Sed SCS.setAsIdentityConversion(); 1430204643Srdivacky SCS.DeprecatedStringLiteralToCharPtr = false; 1431193326Sed SCS.IncompatibleObjC = false; 1432202379Srdivacky SCS.setFromType(FromType); 1433193326Sed SCS.CopyConstructor = 0; 1434193326Sed 1435193326Sed // There are no standard conversions for class types in C++, so 1436198092Srdivacky // abort early. When overloading in C, however, we do permit 1437193326Sed if (FromType->isRecordType() || ToType->isRecordType()) { 1438234353Sdim if (S.getLangOpts().CPlusPlus) 1439193326Sed return false; 1440193326Sed 1441198092Srdivacky // When we're overloading in C, we allow, as standard conversions, 1442193326Sed } 1443193326Sed 1444193326Sed // The first conversion can be an lvalue-to-rvalue conversion, 1445193326Sed // array-to-pointer conversion, or function-to-pointer conversion 1446193326Sed // (C++ 4p1). 1447193326Sed 1448212904Sdim if (FromType == S.Context.OverloadTy) { 1449207619Srdivacky DeclAccessPair AccessPair; 1450207619Srdivacky if (FunctionDecl *Fn 1451218893Sdim = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1452212904Sdim AccessPair)) { 1453207619Srdivacky // We were able to resolve the address of the overloaded function, 1454207619Srdivacky // so we can convert to the type of that function. 1455207619Srdivacky FromType = Fn->getType(); 1456218893Sdim 1457218893Sdim // we can sometimes resolve &foo<int> regardless of ToType, so check 1458218893Sdim // if the type matches (identity) or we are converting to bool 1459218893Sdim if (!S.Context.hasSameUnqualifiedType( 1460218893Sdim S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1461218893Sdim QualType resultTy; 1462218893Sdim // if the function type matches except for [[noreturn]], it's ok 1463224145Sdim if (!S.IsNoReturnConversion(FromType, 1464218893Sdim S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1465218893Sdim // otherwise, only a boolean conversion is standard 1466218893Sdim if (!ToType->isBooleanType()) 1467218893Sdim return false; 1468221345Sdim } 1469218893Sdim 1470221345Sdim // Check if the "from" expression is taking the address of an overloaded 1471221345Sdim // function and recompute the FromType accordingly. Take advantage of the 1472221345Sdim // fact that non-static member functions *must* have such an address-of 1473221345Sdim // expression. 1474221345Sdim CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1475221345Sdim if (Method && !Method->isStatic()) { 1476221345Sdim assert(isa<UnaryOperator>(From->IgnoreParens()) && 1477221345Sdim "Non-unary operator on non-static member address"); 1478221345Sdim assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1479221345Sdim == UO_AddrOf && 1480221345Sdim "Non-address-of operator on non-static member address"); 1481221345Sdim const Type *ClassType 1482221345Sdim = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1483221345Sdim FromType = S.Context.getMemberPointerType(FromType, ClassType); 1484221345Sdim } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1485221345Sdim assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1486221345Sdim UO_AddrOf && 1487221345Sdim "Non-address-of operator for overloaded function expression"); 1488221345Sdim FromType = S.Context.getPointerType(FromType); 1489218893Sdim } 1490218893Sdim 1491207619Srdivacky // Check that we've computed the proper type after overload resolution. 1492221345Sdim assert(S.Context.hasSameType( 1493221345Sdim FromType, 1494221345Sdim S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1495207619Srdivacky } else { 1496207619Srdivacky return false; 1497207619Srdivacky } 1498218893Sdim } 1499226633Sdim // Lvalue-to-rvalue conversion (C++11 4.1): 1500226633Sdim // A glvalue (3.10) of a non-function, non-array type T can 1501226633Sdim // be converted to a prvalue. 1502226633Sdim bool argIsLValue = From->isGLValue(); 1503218893Sdim if (argIsLValue && 1504193326Sed !FromType->isFunctionType() && !FromType->isArrayType() && 1505212904Sdim S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1506193326Sed SCS.First = ICK_Lvalue_To_Rvalue; 1507193326Sed 1508234353Sdim // C11 6.3.2.1p2: 1509234353Sdim // ... if the lvalue has atomic type, the value has the non-atomic version 1510234353Sdim // of the type of the lvalue ... 1511234353Sdim if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1512234353Sdim FromType = Atomic->getValueType(); 1513234353Sdim 1514193326Sed // If T is a non-class type, the type of the rvalue is the 1515193326Sed // cv-unqualified version of T. Otherwise, the type of the rvalue 1516193326Sed // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1517193326Sed // just strip the qualifiers because they don't matter. 1518193326Sed FromType = FromType.getUnqualifiedType(); 1519198092Srdivacky } else if (FromType->isArrayType()) { 1520198092Srdivacky // Array-to-pointer conversion (C++ 4.2) 1521193326Sed SCS.First = ICK_Array_To_Pointer; 1522193326Sed 1523193326Sed // An lvalue or rvalue of type "array of N T" or "array of unknown 1524193326Sed // bound of T" can be converted to an rvalue of type "pointer to 1525193326Sed // T" (C++ 4.2p1). 1526212904Sdim FromType = S.Context.getArrayDecayedType(FromType); 1527193326Sed 1528212904Sdim if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1529193326Sed // This conversion is deprecated. (C++ D.4). 1530204643Srdivacky SCS.DeprecatedStringLiteralToCharPtr = true; 1531193326Sed 1532193326Sed // For the purpose of ranking in overload resolution 1533193326Sed // (13.3.3.1.1), this conversion is considered an 1534193326Sed // array-to-pointer conversion followed by a qualification 1535193326Sed // conversion (4.4). (C++ 4.2p2) 1536193326Sed SCS.Second = ICK_Identity; 1537193326Sed SCS.Third = ICK_Qualification; 1538224145Sdim SCS.QualificationIncludesObjCLifetime = false; 1539203955Srdivacky SCS.setAllToTypes(FromType); 1540193326Sed return true; 1541193326Sed } 1542218893Sdim } else if (FromType->isFunctionType() && argIsLValue) { 1543198092Srdivacky // Function-to-pointer conversion (C++ 4.3). 1544193326Sed SCS.First = ICK_Function_To_Pointer; 1545193326Sed 1546193326Sed // An lvalue of function type T can be converted to an rvalue of 1547193326Sed // type "pointer to T." The result is a pointer to the 1548193326Sed // function. (C++ 4.3p1). 1549212904Sdim FromType = S.Context.getPointerType(FromType); 1550198092Srdivacky } else { 1551198092Srdivacky // We don't require any conversions for the first step. 1552193326Sed SCS.First = ICK_Identity; 1553193326Sed } 1554203955Srdivacky SCS.setToType(0, FromType); 1555193326Sed 1556193326Sed // The second conversion can be an integral promotion, floating 1557193326Sed // point promotion, integral conversion, floating point conversion, 1558193326Sed // floating-integral conversion, pointer conversion, 1559193326Sed // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1560193326Sed // For overloading in C, this can also be a "compatible-type" 1561193326Sed // conversion. 1562193326Sed bool IncompatibleObjC = false; 1563208600Srdivacky ImplicitConversionKind SecondICK = ICK_Identity; 1564212904Sdim if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1565193326Sed // The unqualified versions of the types are the same: there's no 1566193326Sed // conversion to do. 1567193326Sed SCS.Second = ICK_Identity; 1568212904Sdim } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1569198092Srdivacky // Integral promotion (C++ 4.5). 1570193326Sed SCS.Second = ICK_Integral_Promotion; 1571193326Sed FromType = ToType.getUnqualifiedType(); 1572212904Sdim } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1573198092Srdivacky // Floating point promotion (C++ 4.6). 1574193326Sed SCS.Second = ICK_Floating_Promotion; 1575193326Sed FromType = ToType.getUnqualifiedType(); 1576212904Sdim } else if (S.IsComplexPromotion(FromType, ToType)) { 1577198092Srdivacky // Complex promotion (Clang extension) 1578193326Sed SCS.Second = ICK_Complex_Promotion; 1579193326Sed FromType = ToType.getUnqualifiedType(); 1580218893Sdim } else if (ToType->isBooleanType() && 1581218893Sdim (FromType->isArithmeticType() || 1582218893Sdim FromType->isAnyPointerType() || 1583218893Sdim FromType->isBlockPointerType() || 1584218893Sdim FromType->isMemberPointerType() || 1585218893Sdim FromType->isNullPtrType())) { 1586218893Sdim // Boolean conversions (C++ 4.12). 1587218893Sdim SCS.Second = ICK_Boolean_Conversion; 1588218893Sdim FromType = S.Context.BoolTy; 1589218893Sdim } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1590212904Sdim ToType->isIntegralType(S.Context)) { 1591198092Srdivacky // Integral conversions (C++ 4.7). 1592193326Sed SCS.Second = ICK_Integral_Conversion; 1593193326Sed FromType = ToType.getUnqualifiedType(); 1594218893Sdim } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1595204643Srdivacky // Complex conversions (C99 6.3.1.6) 1596204643Srdivacky SCS.Second = ICK_Complex_Conversion; 1597204643Srdivacky FromType = ToType.getUnqualifiedType(); 1598218893Sdim } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1599218893Sdim (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1600204643Srdivacky // Complex-real conversions (C99 6.3.1.7) 1601204643Srdivacky SCS.Second = ICK_Complex_Real; 1602204643Srdivacky FromType = ToType.getUnqualifiedType(); 1603210299Sed } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1604198092Srdivacky // Floating point conversions (C++ 4.8). 1605193326Sed SCS.Second = ICK_Floating_Conversion; 1606193326Sed FromType = ToType.getUnqualifiedType(); 1607218893Sdim } else if ((FromType->isRealFloatingType() && 1608218893Sdim ToType->isIntegralType(S.Context)) || 1609218893Sdim (FromType->isIntegralOrUnscopedEnumerationType() && 1610210299Sed ToType->isRealFloatingType())) { 1611198092Srdivacky // Floating-integral conversions (C++ 4.9). 1612193326Sed SCS.Second = ICK_Floating_Integral; 1613193326Sed FromType = ToType.getUnqualifiedType(); 1614218893Sdim } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1615224145Sdim SCS.Second = ICK_Block_Pointer_Conversion; 1616224145Sdim } else if (AllowObjCWritebackConversion && 1617224145Sdim S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1618224145Sdim SCS.Second = ICK_Writeback_Conversion; 1619212904Sdim } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1620212904Sdim FromType, IncompatibleObjC)) { 1621198092Srdivacky // Pointer conversions (C++ 4.10). 1622193326Sed SCS.Second = ICK_Pointer_Conversion; 1623193326Sed SCS.IncompatibleObjC = IncompatibleObjC; 1624221345Sdim FromType = FromType.getUnqualifiedType(); 1625218893Sdim } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1626212904Sdim InOverloadResolution, FromType)) { 1627198092Srdivacky // Pointer to member conversions (4.11). 1628193326Sed SCS.Second = ICK_Pointer_Member; 1629212904Sdim } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1630208600Srdivacky SCS.Second = SecondICK; 1631208600Srdivacky FromType = ToType.getUnqualifiedType(); 1632234353Sdim } else if (!S.getLangOpts().CPlusPlus && 1633212904Sdim S.Context.typesAreCompatible(ToType, FromType)) { 1634198092Srdivacky // Compatible conversions (Clang extension for C function overloading) 1635193326Sed SCS.Second = ICK_Compatible_Conversion; 1636208600Srdivacky FromType = ToType.getUnqualifiedType(); 1637224145Sdim } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1638200583Srdivacky // Treat a conversion that strips "noreturn" as an identity conversion. 1639200583Srdivacky SCS.Second = ICK_NoReturn_Adjustment; 1640221345Sdim } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1641221345Sdim InOverloadResolution, 1642221345Sdim SCS, CStyle)) { 1643221345Sdim SCS.Second = ICK_TransparentUnionConversion; 1644221345Sdim FromType = ToType; 1645234353Sdim } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1646234353Sdim CStyle)) { 1647234353Sdim // tryAtomicConversion has updated the standard conversion sequence 1648234353Sdim // appropriately. 1649234353Sdim return true; 1650249423Sdim } else if (ToType->isEventT() && 1651249423Sdim From->isIntegerConstantExpr(S.getASTContext()) && 1652249423Sdim (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1653249423Sdim SCS.Second = ICK_Zero_Event_Conversion; 1654249423Sdim FromType = ToType; 1655193326Sed } else { 1656193326Sed // No second conversion required. 1657193326Sed SCS.Second = ICK_Identity; 1658193326Sed } 1659203955Srdivacky SCS.setToType(1, FromType); 1660193326Sed 1661193326Sed QualType CanonFrom; 1662193326Sed QualType CanonTo; 1663193326Sed // The third conversion can be a qualification conversion (C++ 4p1). 1664224145Sdim bool ObjCLifetimeConversion; 1665224145Sdim if (S.IsQualificationConversion(FromType, ToType, CStyle, 1666224145Sdim ObjCLifetimeConversion)) { 1667193326Sed SCS.Third = ICK_Qualification; 1668224145Sdim SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1669193326Sed FromType = ToType; 1670212904Sdim CanonFrom = S.Context.getCanonicalType(FromType); 1671212904Sdim CanonTo = S.Context.getCanonicalType(ToType); 1672193326Sed } else { 1673193326Sed // No conversion required 1674193326Sed SCS.Third = ICK_Identity; 1675193326Sed 1676198092Srdivacky // C++ [over.best.ics]p6: 1677193326Sed // [...] Any difference in top-level cv-qualification is 1678193326Sed // subsumed by the initialization itself and does not constitute 1679193326Sed // a conversion. [...] 1680212904Sdim CanonFrom = S.Context.getCanonicalType(FromType); 1681212904Sdim CanonTo = S.Context.getCanonicalType(ToType); 1682218893Sdim if (CanonFrom.getLocalUnqualifiedType() 1683199482Srdivacky == CanonTo.getLocalUnqualifiedType() && 1684249423Sdim CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1685193326Sed FromType = ToType; 1686193326Sed CanonFrom = CanonTo; 1687193326Sed } 1688193326Sed } 1689203955Srdivacky SCS.setToType(2, FromType); 1690193326Sed 1691193326Sed // If we have not converted the argument type to the parameter type, 1692193326Sed // this is a bad conversion sequence. 1693193326Sed if (CanonFrom != CanonTo) 1694193326Sed return false; 1695193326Sed 1696193326Sed return true; 1697193326Sed} 1698221345Sdim 1699221345Sdimstatic bool 1700221345SdimIsTransparentUnionStandardConversion(Sema &S, Expr* From, 1701221345Sdim QualType &ToType, 1702221345Sdim bool InOverloadResolution, 1703221345Sdim StandardConversionSequence &SCS, 1704221345Sdim bool CStyle) { 1705221345Sdim 1706221345Sdim const RecordType *UT = ToType->getAsUnionType(); 1707221345Sdim if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1708221345Sdim return false; 1709221345Sdim // The field to initialize within the transparent union. 1710221345Sdim RecordDecl *UD = UT->getDecl(); 1711221345Sdim // It's compatible if the expression matches any of the fields. 1712221345Sdim for (RecordDecl::field_iterator it = UD->field_begin(), 1713221345Sdim itend = UD->field_end(); 1714221345Sdim it != itend; ++it) { 1715224145Sdim if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1716224145Sdim CStyle, /*ObjCWritebackConversion=*/false)) { 1717221345Sdim ToType = it->getType(); 1718221345Sdim return true; 1719221345Sdim } 1720221345Sdim } 1721221345Sdim return false; 1722221345Sdim} 1723193326Sed 1724193326Sed/// IsIntegralPromotion - Determines whether the conversion from the 1725193326Sed/// expression From (whose potentially-adjusted type is FromType) to 1726193326Sed/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1727193326Sed/// sets PromotedType to the promoted type. 1728198092Srdivackybool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1729198092Srdivacky const BuiltinType *To = ToType->getAs<BuiltinType>(); 1730193326Sed // All integers are built-in. 1731193326Sed if (!To) { 1732193326Sed return false; 1733193326Sed } 1734193326Sed 1735193326Sed // An rvalue of type char, signed char, unsigned char, short int, or 1736193326Sed // unsigned short int can be converted to an rvalue of type int if 1737193326Sed // int can represent all the values of the source type; otherwise, 1738193326Sed // the source rvalue can be converted to an rvalue of type unsigned 1739193326Sed // int (C++ 4.5p1). 1740203955Srdivacky if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1741203955Srdivacky !FromType->isEnumeralType()) { 1742193326Sed if (// We can promote any signed, promotable integer type to an int 1743193326Sed (FromType->isSignedIntegerType() || 1744193326Sed // We can promote any unsigned integer type whose size is 1745193326Sed // less than int to an int. 1746198092Srdivacky (!FromType->isSignedIntegerType() && 1747193326Sed Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1748193326Sed return To->getKind() == BuiltinType::Int; 1749193326Sed } 1750193326Sed 1751193326Sed return To->getKind() == BuiltinType::UInt; 1752193326Sed } 1753193326Sed 1754243830Sdim // C++11 [conv.prom]p3: 1755218893Sdim // A prvalue of an unscoped enumeration type whose underlying type is not 1756218893Sdim // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1757218893Sdim // following types that can represent all the values of the enumeration 1758218893Sdim // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1759218893Sdim // unsigned int, long int, unsigned long int, long long int, or unsigned 1760218893Sdim // long long int. If none of the types in that list can represent all the 1761218893Sdim // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1762218893Sdim // type can be converted to an rvalue a prvalue of the extended integer type 1763218893Sdim // with lowest integer conversion rank (4.13) greater than the rank of long 1764218893Sdim // long in which all the values of the enumeration can be represented. If 1765218893Sdim // there are two such extended types, the signed one is chosen. 1766243830Sdim // C++11 [conv.prom]p4: 1767243830Sdim // A prvalue of an unscoped enumeration type whose underlying type is fixed 1768243830Sdim // can be converted to a prvalue of its underlying type. Moreover, if 1769243830Sdim // integral promotion can be applied to its underlying type, a prvalue of an 1770243830Sdim // unscoped enumeration type whose underlying type is fixed can also be 1771243830Sdim // converted to a prvalue of the promoted underlying type. 1772218893Sdim if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1773218893Sdim // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1774218893Sdim // provided for a scoped enumeration. 1775218893Sdim if (FromEnumType->getDecl()->isScoped()) 1776218893Sdim return false; 1777200583Srdivacky 1778243830Sdim // We can perform an integral promotion to the underlying type of the enum, 1779243830Sdim // even if that's not the promoted type. 1780243830Sdim if (FromEnumType->getDecl()->isFixed()) { 1781243830Sdim QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1782243830Sdim return Context.hasSameUnqualifiedType(Underlying, ToType) || 1783243830Sdim IsIntegralPromotion(From, Underlying, ToType); 1784243830Sdim } 1785243830Sdim 1786218893Sdim // We have already pre-calculated the promotion type, so this is trivial. 1787218893Sdim if (ToType->isIntegerType() && 1788239462Sdim !RequireCompleteType(From->getLocStart(), FromType, 0)) 1789200583Srdivacky return Context.hasSameUnqualifiedType(ToType, 1790200583Srdivacky FromEnumType->getDecl()->getPromotionType()); 1791218893Sdim } 1792200583Srdivacky 1793218893Sdim // C++0x [conv.prom]p2: 1794218893Sdim // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1795218893Sdim // to an rvalue a prvalue of the first of the following types that can 1796218893Sdim // represent all the values of its underlying type: int, unsigned int, 1797218893Sdim // long int, unsigned long int, long long int, or unsigned long long int. 1798218893Sdim // If none of the types in that list can represent all the values of its 1799218893Sdim // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1800218893Sdim // or wchar_t can be converted to an rvalue a prvalue of its underlying 1801218893Sdim // type. 1802218893Sdim if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1803218893Sdim ToType->isIntegerType()) { 1804193326Sed // Determine whether the type we're converting from is signed or 1805193326Sed // unsigned. 1806226633Sdim bool FromIsSigned = FromType->isSignedIntegerType(); 1807193326Sed uint64_t FromSize = Context.getTypeSize(FromType); 1808218893Sdim 1809193326Sed // The types we'll try to promote to, in the appropriate 1810193326Sed // order. Try each of these types. 1811198092Srdivacky QualType PromoteTypes[6] = { 1812198092Srdivacky Context.IntTy, Context.UnsignedIntTy, 1813193326Sed Context.LongTy, Context.UnsignedLongTy , 1814193326Sed Context.LongLongTy, Context.UnsignedLongLongTy 1815193326Sed }; 1816193326Sed for (int Idx = 0; Idx < 6; ++Idx) { 1817193326Sed uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1818193326Sed if (FromSize < ToSize || 1819198092Srdivacky (FromSize == ToSize && 1820193326Sed FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1821193326Sed // We found the type that we can promote to. If this is the 1822193326Sed // type we wanted, we have a promotion. Otherwise, no 1823193326Sed // promotion. 1824199482Srdivacky return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1825193326Sed } 1826193326Sed } 1827193326Sed } 1828193326Sed 1829193326Sed // An rvalue for an integral bit-field (9.6) can be converted to an 1830193326Sed // rvalue of type int if int can represent all the values of the 1831193326Sed // bit-field; otherwise, it can be converted to unsigned int if 1832193326Sed // unsigned int can represent all the values of the bit-field. If 1833193326Sed // the bit-field is larger yet, no integral promotion applies to 1834193326Sed // it. If the bit-field has an enumerated type, it is treated as any 1835193326Sed // other value of that type for promotion purposes (C++ 4.5p3). 1836193326Sed // FIXME: We should delay checking of bit-fields until we actually perform the 1837193326Sed // conversion. 1838193326Sed using llvm::APSInt; 1839193326Sed if (From) 1840251662Sdim if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1841193326Sed APSInt BitWidth; 1842210299Sed if (FromType->isIntegralType(Context) && 1843193326Sed MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1844193326Sed APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1845193326Sed ToSize = Context.getTypeSize(ToType); 1846198092Srdivacky 1847193326Sed // Are we promoting to an int from a bitfield that fits in an int? 1848193326Sed if (BitWidth < ToSize || 1849193326Sed (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1850193326Sed return To->getKind() == BuiltinType::Int; 1851193326Sed } 1852198092Srdivacky 1853193326Sed // Are we promoting to an unsigned int from an unsigned bitfield 1854193326Sed // that fits into an unsigned int? 1855193326Sed if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1856193326Sed return To->getKind() == BuiltinType::UInt; 1857193326Sed } 1858198092Srdivacky 1859193326Sed return false; 1860193326Sed } 1861193326Sed } 1862198092Srdivacky 1863193326Sed // An rvalue of type bool can be converted to an rvalue of type int, 1864193326Sed // with false becoming zero and true becoming one (C++ 4.5p4). 1865193326Sed if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1866193326Sed return true; 1867193326Sed } 1868193326Sed 1869193326Sed return false; 1870193326Sed} 1871193326Sed 1872193326Sed/// IsFloatingPointPromotion - Determines whether the conversion from 1873193326Sed/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1874193326Sed/// returns true and sets PromotedType to the promoted type. 1875198092Srdivackybool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1876198092Srdivacky if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1877198092Srdivacky if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1878226633Sdim /// An rvalue of type float can be converted to an rvalue of type 1879226633Sdim /// double. (C++ 4.6p1). 1880193326Sed if (FromBuiltin->getKind() == BuiltinType::Float && 1881193326Sed ToBuiltin->getKind() == BuiltinType::Double) 1882193326Sed return true; 1883193326Sed 1884193326Sed // C99 6.3.1.5p1: 1885193326Sed // When a float is promoted to double or long double, or a 1886193326Sed // double is promoted to long double [...]. 1887234353Sdim if (!getLangOpts().CPlusPlus && 1888193326Sed (FromBuiltin->getKind() == BuiltinType::Float || 1889193326Sed FromBuiltin->getKind() == BuiltinType::Double) && 1890193326Sed (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1891193326Sed return true; 1892226633Sdim 1893226633Sdim // Half can be promoted to float. 1894249423Sdim if (!getLangOpts().NativeHalfType && 1895249423Sdim FromBuiltin->getKind() == BuiltinType::Half && 1896226633Sdim ToBuiltin->getKind() == BuiltinType::Float) 1897226633Sdim return true; 1898193326Sed } 1899193326Sed 1900193326Sed return false; 1901193326Sed} 1902193326Sed 1903193326Sed/// \brief Determine if a conversion is a complex promotion. 1904193326Sed/// 1905193326Sed/// A complex promotion is defined as a complex -> complex conversion 1906193326Sed/// where the conversion between the underlying real types is a 1907193326Sed/// floating-point or integral promotion. 1908193326Sedbool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1909198092Srdivacky const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1910193326Sed if (!FromComplex) 1911193326Sed return false; 1912193326Sed 1913198092Srdivacky const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1914193326Sed if (!ToComplex) 1915193326Sed return false; 1916193326Sed 1917193326Sed return IsFloatingPointPromotion(FromComplex->getElementType(), 1918193326Sed ToComplex->getElementType()) || 1919193326Sed IsIntegralPromotion(0, FromComplex->getElementType(), 1920193326Sed ToComplex->getElementType()); 1921193326Sed} 1922193326Sed 1923193326Sed/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1924193326Sed/// the pointer type FromPtr to a pointer to type ToPointee, with the 1925193326Sed/// same type qualifiers as FromPtr has on its pointee type. ToType, 1926193326Sed/// if non-empty, will be a pointer to ToType that may or may not have 1927193326Sed/// the right set of qualifiers on its pointee. 1928224145Sdim/// 1929198092Srdivackystatic QualType 1930218893SdimBuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1931193326Sed QualType ToPointee, QualType ToType, 1932224145Sdim ASTContext &Context, 1933224145Sdim bool StripObjCLifetime = false) { 1934218893Sdim assert((FromPtr->getTypeClass() == Type::Pointer || 1935218893Sdim FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1936218893Sdim "Invalid similarly-qualified pointer type"); 1937218893Sdim 1938224145Sdim /// Conversions to 'id' subsume cv-qualifier conversions. 1939224145Sdim if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1940218893Sdim return ToType.getUnqualifiedType(); 1941218893Sdim 1942218893Sdim QualType CanonFromPointee 1943218893Sdim = Context.getCanonicalType(FromPtr->getPointeeType()); 1944193326Sed QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1945198092Srdivacky Qualifiers Quals = CanonFromPointee.getQualifiers(); 1946198092Srdivacky 1947224145Sdim if (StripObjCLifetime) 1948224145Sdim Quals.removeObjCLifetime(); 1949224145Sdim 1950198092Srdivacky // Exact qualifier match -> return the pointer type we're converting to. 1951199482Srdivacky if (CanonToPointee.getLocalQualifiers() == Quals) { 1952193326Sed // ToType is exactly what we need. Return it. 1953198092Srdivacky if (!ToType.isNull()) 1954208600Srdivacky return ToType.getUnqualifiedType(); 1955193326Sed 1956193326Sed // Build a pointer to ToPointee. It has the right qualifiers 1957193326Sed // already. 1958218893Sdim if (isa<ObjCObjectPointerType>(ToType)) 1959218893Sdim return Context.getObjCObjectPointerType(ToPointee); 1960193326Sed return Context.getPointerType(ToPointee); 1961193326Sed } 1962193326Sed 1963193326Sed // Just build a canonical type that has the right qualifiers. 1964218893Sdim QualType QualifiedCanonToPointee 1965218893Sdim = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1966218893Sdim 1967218893Sdim if (isa<ObjCObjectPointerType>(ToType)) 1968218893Sdim return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1969218893Sdim return Context.getPointerType(QualifiedCanonToPointee); 1970193326Sed} 1971193326Sed 1972198092Srdivackystatic bool isNullPointerConstantForConversion(Expr *Expr, 1973198092Srdivacky bool InOverloadResolution, 1974198092Srdivacky ASTContext &Context) { 1975198092Srdivacky // Handle value-dependent integral null pointer constants correctly. 1976198092Srdivacky // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1977198092Srdivacky if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1978210299Sed Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1979198092Srdivacky return !InOverloadResolution; 1980198092Srdivacky 1981198092Srdivacky return Expr->isNullPointerConstant(Context, 1982198092Srdivacky InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1983198092Srdivacky : Expr::NPC_ValueDependentIsNull); 1984198092Srdivacky} 1985198092Srdivacky 1986193326Sed/// IsPointerConversion - Determines whether the conversion of the 1987193326Sed/// expression From, which has the (possibly adjusted) type FromType, 1988193326Sed/// can be converted to the type ToType via a pointer conversion (C++ 1989193326Sed/// 4.10). If so, returns true and places the converted type (that 1990193326Sed/// might differ from ToType in its cv-qualifiers at some level) into 1991193326Sed/// ConvertedType. 1992193326Sed/// 1993193326Sed/// This routine also supports conversions to and from block pointers 1994193326Sed/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1995193326Sed/// pointers to interfaces. FIXME: Once we've determined the 1996193326Sed/// appropriate overloading rules for Objective-C, we may want to 1997193326Sed/// split the Objective-C checks into a different routine; however, 1998193326Sed/// GCC seems to consider all of these conversions to be pointer 1999193326Sed/// conversions, so for now they live here. IncompatibleObjC will be 2000193326Sed/// set if the conversion is an allowed Objective-C conversion that 2001193326Sed/// should result in a warning. 2002193326Sedbool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2003198092Srdivacky bool InOverloadResolution, 2004193326Sed QualType& ConvertedType, 2005198092Srdivacky bool &IncompatibleObjC) { 2006193326Sed IncompatibleObjC = false; 2007218893Sdim if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2008218893Sdim IncompatibleObjC)) 2009193326Sed return true; 2010193326Sed 2011198092Srdivacky // Conversion from a null pointer constant to any Objective-C pointer type. 2012198092Srdivacky if (ToType->isObjCObjectPointerType() && 2013198092Srdivacky isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2014193326Sed ConvertedType = ToType; 2015193326Sed return true; 2016193326Sed } 2017193326Sed 2018193326Sed // Blocks: Block pointers can be converted to void*. 2019193326Sed if (FromType->isBlockPointerType() && ToType->isPointerType() && 2020198092Srdivacky ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2021193326Sed ConvertedType = ToType; 2022193326Sed return true; 2023193326Sed } 2024193326Sed // Blocks: A null pointer constant can be converted to a block 2025193326Sed // pointer type. 2026198092Srdivacky if (ToType->isBlockPointerType() && 2027198092Srdivacky isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2028193326Sed ConvertedType = ToType; 2029193326Sed return true; 2030193326Sed } 2031193326Sed 2032193326Sed // If the left-hand-side is nullptr_t, the right side can be a null 2033193326Sed // pointer constant. 2034198092Srdivacky if (ToType->isNullPtrType() && 2035198092Srdivacky isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2036193326Sed ConvertedType = ToType; 2037193326Sed return true; 2038193326Sed } 2039193326Sed 2040198092Srdivacky const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2041193326Sed if (!ToTypePtr) 2042193326Sed return false; 2043193326Sed 2044193326Sed // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2045198092Srdivacky if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2046193326Sed ConvertedType = ToType; 2047193326Sed return true; 2048193326Sed } 2049193326Sed 2050218893Sdim // Beyond this point, both types need to be pointers 2051201361Srdivacky // , including objective-c pointers. 2052201361Srdivacky QualType ToPointeeType = ToTypePtr->getPointeeType(); 2053224145Sdim if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2054234353Sdim !getLangOpts().ObjCAutoRefCount) { 2055218893Sdim ConvertedType = BuildSimilarlyQualifiedPointerType( 2056218893Sdim FromType->getAs<ObjCObjectPointerType>(), 2057218893Sdim ToPointeeType, 2058201361Srdivacky ToType, Context); 2059201361Srdivacky return true; 2060201361Srdivacky } 2061198092Srdivacky const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2062193326Sed if (!FromTypePtr) 2063193326Sed return false; 2064193326Sed 2065193326Sed QualType FromPointeeType = FromTypePtr->getPointeeType(); 2066193326Sed 2067218893Sdim // If the unqualified pointee types are the same, this can't be a 2068212904Sdim // pointer conversion, so don't do all of the work below. 2069212904Sdim if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2070212904Sdim return false; 2071212904Sdim 2072193326Sed // An rvalue of type "pointer to cv T," where T is an object type, 2073193326Sed // can be converted to an rvalue of type "pointer to cv void" (C++ 2074193326Sed // 4.10p2). 2075212904Sdim if (FromPointeeType->isIncompleteOrObjectType() && 2076212904Sdim ToPointeeType->isVoidType()) { 2077198092Srdivacky ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2078193326Sed ToPointeeType, 2079224145Sdim ToType, Context, 2080224145Sdim /*StripObjCLifetime=*/true); 2081193326Sed return true; 2082193326Sed } 2083193326Sed 2084223017Sdim // MSVC allows implicit function to void* type conversion. 2085234353Sdim if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2086223017Sdim ToPointeeType->isVoidType()) { 2087223017Sdim ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2088223017Sdim ToPointeeType, 2089223017Sdim ToType, Context); 2090223017Sdim return true; 2091223017Sdim } 2092223017Sdim 2093193326Sed // When we're overloading in C, we allow a special kind of pointer 2094193326Sed // conversion for compatible-but-not-identical pointee types. 2095234353Sdim if (!getLangOpts().CPlusPlus && 2096193326Sed Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2097198092Srdivacky ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2098193326Sed ToPointeeType, 2099198092Srdivacky ToType, Context); 2100193326Sed return true; 2101193326Sed } 2102193326Sed 2103193326Sed // C++ [conv.ptr]p3: 2104198092Srdivacky // 2105193326Sed // An rvalue of type "pointer to cv D," where D is a class type, 2106193326Sed // can be converted to an rvalue of type "pointer to cv B," where 2107193326Sed // B is a base class (clause 10) of D. If B is an inaccessible 2108193326Sed // (clause 11) or ambiguous (10.2) base class of D, a program that 2109193326Sed // necessitates this conversion is ill-formed. The result of the 2110193326Sed // conversion is a pointer to the base class sub-object of the 2111193326Sed // derived class object. The null pointer value is converted to 2112193326Sed // the null pointer value of the destination type. 2113193326Sed // 2114193326Sed // Note that we do not check for ambiguity or inaccessibility 2115193326Sed // here. That is handled by CheckPointerConversion. 2116234353Sdim if (getLangOpts().CPlusPlus && 2117193326Sed FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2118204643Srdivacky !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2119239462Sdim !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2120193326Sed IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2121198092Srdivacky ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2122193326Sed ToPointeeType, 2123193326Sed ToType, Context); 2124193326Sed return true; 2125193326Sed } 2126193326Sed 2127221345Sdim if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2128221345Sdim Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2129221345Sdim ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2130221345Sdim ToPointeeType, 2131221345Sdim ToType, Context); 2132221345Sdim return true; 2133221345Sdim } 2134221345Sdim 2135193326Sed return false; 2136193326Sed} 2137221345Sdim 2138221345Sdim/// \brief Adopt the given qualifiers for the given type. 2139221345Sdimstatic QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2140221345Sdim Qualifiers TQs = T.getQualifiers(); 2141221345Sdim 2142221345Sdim // Check whether qualifiers already match. 2143221345Sdim if (TQs == Qs) 2144221345Sdim return T; 2145221345Sdim 2146221345Sdim if (Qs.compatiblyIncludes(TQs)) 2147221345Sdim return Context.getQualifiedType(T, Qs); 2148221345Sdim 2149221345Sdim return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2150221345Sdim} 2151193326Sed 2152193326Sed/// isObjCPointerConversion - Determines whether this is an 2153193326Sed/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2154193326Sed/// with the same arguments and return values. 2155198092Srdivackybool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2156193326Sed QualType& ConvertedType, 2157193326Sed bool &IncompatibleObjC) { 2158234353Sdim if (!getLangOpts().ObjC1) 2159193326Sed return false; 2160218893Sdim 2161221345Sdim // The set of qualifiers on the type we're converting from. 2162221345Sdim Qualifiers FromQualifiers = FromType.getQualifiers(); 2163221345Sdim 2164198092Srdivacky // First, we handle all conversions on ObjC object pointer types. 2165218893Sdim const ObjCObjectPointerType* ToObjCPtr = 2166218893Sdim ToType->getAs<ObjCObjectPointerType>(); 2167198092Srdivacky const ObjCObjectPointerType *FromObjCPtr = 2168198092Srdivacky FromType->getAs<ObjCObjectPointerType>(); 2169198092Srdivacky 2170198092Srdivacky if (ToObjCPtr && FromObjCPtr) { 2171218893Sdim // If the pointee types are the same (ignoring qualifications), 2172218893Sdim // then this is not a pointer conversion. 2173218893Sdim if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2174218893Sdim FromObjCPtr->getPointeeType())) 2175218893Sdim return false; 2176218893Sdim 2177221345Sdim // Check for compatible 2178198092Srdivacky // Objective C++: We're able to convert between "id" or "Class" and a 2179198092Srdivacky // pointer to any interface (in both directions). 2180198092Srdivacky if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2181221345Sdim ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2182198092Srdivacky return true; 2183198092Srdivacky } 2184198092Srdivacky // Conversions with Objective-C's id<...>. 2185198092Srdivacky if ((FromObjCPtr->isObjCQualifiedIdType() || 2186198092Srdivacky ToObjCPtr->isObjCQualifiedIdType()) && 2187198092Srdivacky Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2188198092Srdivacky /*compare=*/false)) { 2189221345Sdim ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2190198092Srdivacky return true; 2191198092Srdivacky } 2192198092Srdivacky // Objective C++: We're able to convert from a pointer to an 2193198092Srdivacky // interface to a pointer to a different interface. 2194198092Srdivacky if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2195205219Srdivacky const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2196205219Srdivacky const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2197234353Sdim if (getLangOpts().CPlusPlus && LHS && RHS && 2198205219Srdivacky !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2199205219Srdivacky FromObjCPtr->getPointeeType())) 2200205219Srdivacky return false; 2201218893Sdim ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2202218893Sdim ToObjCPtr->getPointeeType(), 2203218893Sdim ToType, Context); 2204221345Sdim ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2205198092Srdivacky return true; 2206198092Srdivacky } 2207198092Srdivacky 2208198092Srdivacky if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2209198092Srdivacky // Okay: this is some kind of implicit downcast of Objective-C 2210198092Srdivacky // interfaces, which is permitted. However, we're going to 2211198092Srdivacky // complain about it. 2212198092Srdivacky IncompatibleObjC = true; 2213218893Sdim ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2214218893Sdim ToObjCPtr->getPointeeType(), 2215218893Sdim ToType, Context); 2216221345Sdim ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2217198092Srdivacky return true; 2218198092Srdivacky } 2219193326Sed } 2220198092Srdivacky // Beyond this point, both types need to be C pointers or block pointers. 2221193326Sed QualType ToPointeeType; 2222198092Srdivacky if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2223198092Srdivacky ToPointeeType = ToCPtr->getPointeeType(); 2224218893Sdim else if (const BlockPointerType *ToBlockPtr = 2225202879Srdivacky ToType->getAs<BlockPointerType>()) { 2226202879Srdivacky // Objective C++: We're able to convert from a pointer to any object 2227202879Srdivacky // to a block pointer type. 2228202879Srdivacky if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2229221345Sdim ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2230202879Srdivacky return true; 2231202879Srdivacky } 2232193326Sed ToPointeeType = ToBlockPtr->getPointeeType(); 2233202879Srdivacky } 2234218893Sdim else if (FromType->getAs<BlockPointerType>() && 2235202879Srdivacky ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2236218893Sdim // Objective C++: We're able to convert from a block pointer type to a 2237202879Srdivacky // pointer to any object. 2238221345Sdim ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2239202879Srdivacky return true; 2240202879Srdivacky } 2241193326Sed else 2242193326Sed return false; 2243193326Sed 2244193326Sed QualType FromPointeeType; 2245198092Srdivacky if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2246198092Srdivacky FromPointeeType = FromCPtr->getPointeeType(); 2247218893Sdim else if (const BlockPointerType *FromBlockPtr = 2248218893Sdim FromType->getAs<BlockPointerType>()) 2249193326Sed FromPointeeType = FromBlockPtr->getPointeeType(); 2250193326Sed else 2251193326Sed return false; 2252193326Sed 2253193326Sed // If we have pointers to pointers, recursively check whether this 2254193326Sed // is an Objective-C conversion. 2255193326Sed if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2256193326Sed isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2257193326Sed IncompatibleObjC)) { 2258193326Sed // We always complain about this conversion. 2259193326Sed IncompatibleObjC = true; 2260218893Sdim ConvertedType = Context.getPointerType(ConvertedType); 2261221345Sdim ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2262193326Sed return true; 2263193326Sed } 2264202879Srdivacky // Allow conversion of pointee being objective-c pointer to another one; 2265202879Srdivacky // as in I* to id. 2266202879Srdivacky if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2267202879Srdivacky ToPointeeType->getAs<ObjCObjectPointerType>() && 2268202879Srdivacky isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2269202879Srdivacky IncompatibleObjC)) { 2270224145Sdim 2271218893Sdim ConvertedType = Context.getPointerType(ConvertedType); 2272221345Sdim ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2273202879Srdivacky return true; 2274202879Srdivacky } 2275218893Sdim 2276193326Sed // If we have pointers to functions or blocks, check whether the only 2277193326Sed // differences in the argument and result types are in Objective-C 2278193326Sed // pointer conversions. If so, we permit the conversion (but 2279193326Sed // complain about it). 2280198092Srdivacky const FunctionProtoType *FromFunctionType 2281198092Srdivacky = FromPointeeType->getAs<FunctionProtoType>(); 2282193326Sed const FunctionProtoType *ToFunctionType 2283198092Srdivacky = ToPointeeType->getAs<FunctionProtoType>(); 2284193326Sed if (FromFunctionType && ToFunctionType) { 2285193326Sed // If the function types are exactly the same, this isn't an 2286193326Sed // Objective-C pointer conversion. 2287193326Sed if (Context.getCanonicalType(FromPointeeType) 2288193326Sed == Context.getCanonicalType(ToPointeeType)) 2289193326Sed return false; 2290193326Sed 2291193326Sed // Perform the quick checks that will tell us whether these 2292193326Sed // function types are obviously different. 2293193326Sed if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2294193326Sed FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2295193326Sed FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2296193326Sed return false; 2297193326Sed 2298193326Sed bool HasObjCConversion = false; 2299193326Sed if (Context.getCanonicalType(FromFunctionType->getResultType()) 2300193326Sed == Context.getCanonicalType(ToFunctionType->getResultType())) { 2301193326Sed // Okay, the types match exactly. Nothing to do. 2302193326Sed } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2303193326Sed ToFunctionType->getResultType(), 2304193326Sed ConvertedType, IncompatibleObjC)) { 2305193326Sed // Okay, we have an Objective-C pointer conversion. 2306193326Sed HasObjCConversion = true; 2307193326Sed } else { 2308193326Sed // Function types are too different. Abort. 2309193326Sed return false; 2310193326Sed } 2311198092Srdivacky 2312193326Sed // Check argument types. 2313193326Sed for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2314193326Sed ArgIdx != NumArgs; ++ArgIdx) { 2315193326Sed QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2316193326Sed QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2317193326Sed if (Context.getCanonicalType(FromArgType) 2318193326Sed == Context.getCanonicalType(ToArgType)) { 2319193326Sed // Okay, the types match exactly. Nothing to do. 2320193326Sed } else if (isObjCPointerConversion(FromArgType, ToArgType, 2321193326Sed ConvertedType, IncompatibleObjC)) { 2322193326Sed // Okay, we have an Objective-C pointer conversion. 2323193326Sed HasObjCConversion = true; 2324193326Sed } else { 2325193326Sed // Argument types are too different. Abort. 2326193326Sed return false; 2327193326Sed } 2328193326Sed } 2329193326Sed 2330193326Sed if (HasObjCConversion) { 2331193326Sed // We had an Objective-C conversion. Allow this pointer 2332193326Sed // conversion, but complain about it. 2333221345Sdim ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2334193326Sed IncompatibleObjC = true; 2335193326Sed return true; 2336193326Sed } 2337193326Sed } 2338193326Sed 2339193326Sed return false; 2340193326Sed} 2341218893Sdim 2342224145Sdim/// \brief Determine whether this is an Objective-C writeback conversion, 2343224145Sdim/// used for parameter passing when performing automatic reference counting. 2344224145Sdim/// 2345224145Sdim/// \param FromType The type we're converting form. 2346224145Sdim/// 2347224145Sdim/// \param ToType The type we're converting to. 2348224145Sdim/// 2349224145Sdim/// \param ConvertedType The type that will be produced after applying 2350224145Sdim/// this conversion. 2351224145Sdimbool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2352224145Sdim QualType &ConvertedType) { 2353234353Sdim if (!getLangOpts().ObjCAutoRefCount || 2354224145Sdim Context.hasSameUnqualifiedType(FromType, ToType)) 2355224145Sdim return false; 2356224145Sdim 2357224145Sdim // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2358224145Sdim QualType ToPointee; 2359224145Sdim if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2360224145Sdim ToPointee = ToPointer->getPointeeType(); 2361224145Sdim else 2362224145Sdim return false; 2363224145Sdim 2364224145Sdim Qualifiers ToQuals = ToPointee.getQualifiers(); 2365224145Sdim if (!ToPointee->isObjCLifetimeType() || 2366224145Sdim ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2367234353Sdim !ToQuals.withoutObjCLifetime().empty()) 2368224145Sdim return false; 2369224145Sdim 2370224145Sdim // Argument must be a pointer to __strong to __weak. 2371224145Sdim QualType FromPointee; 2372224145Sdim if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2373224145Sdim FromPointee = FromPointer->getPointeeType(); 2374224145Sdim else 2375224145Sdim return false; 2376224145Sdim 2377224145Sdim Qualifiers FromQuals = FromPointee.getQualifiers(); 2378224145Sdim if (!FromPointee->isObjCLifetimeType() || 2379224145Sdim (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2380224145Sdim FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2381224145Sdim return false; 2382224145Sdim 2383224145Sdim // Make sure that we have compatible qualifiers. 2384224145Sdim FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2385224145Sdim if (!ToQuals.compatiblyIncludes(FromQuals)) 2386224145Sdim return false; 2387224145Sdim 2388224145Sdim // Remove qualifiers from the pointee type we're converting from; they 2389224145Sdim // aren't used in the compatibility check belong, and we'll be adding back 2390224145Sdim // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2391224145Sdim FromPointee = FromPointee.getUnqualifiedType(); 2392224145Sdim 2393224145Sdim // The unqualified form of the pointee types must be compatible. 2394224145Sdim ToPointee = ToPointee.getUnqualifiedType(); 2395224145Sdim bool IncompatibleObjC; 2396224145Sdim if (Context.typesAreCompatible(FromPointee, ToPointee)) 2397224145Sdim FromPointee = ToPointee; 2398224145Sdim else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2399224145Sdim IncompatibleObjC)) 2400224145Sdim return false; 2401224145Sdim 2402224145Sdim /// \brief Construct the type we're converting to, which is a pointer to 2403224145Sdim /// __autoreleasing pointee. 2404224145Sdim FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2405224145Sdim ConvertedType = Context.getPointerType(FromPointee); 2406224145Sdim return true; 2407224145Sdim} 2408224145Sdim 2409218893Sdimbool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2410218893Sdim QualType& ConvertedType) { 2411218893Sdim QualType ToPointeeType; 2412218893Sdim if (const BlockPointerType *ToBlockPtr = 2413218893Sdim ToType->getAs<BlockPointerType>()) 2414218893Sdim ToPointeeType = ToBlockPtr->getPointeeType(); 2415218893Sdim else 2416218893Sdim return false; 2417218893Sdim 2418218893Sdim QualType FromPointeeType; 2419218893Sdim if (const BlockPointerType *FromBlockPtr = 2420218893Sdim FromType->getAs<BlockPointerType>()) 2421218893Sdim FromPointeeType = FromBlockPtr->getPointeeType(); 2422218893Sdim else 2423218893Sdim return false; 2424218893Sdim // We have pointer to blocks, check whether the only 2425218893Sdim // differences in the argument and result types are in Objective-C 2426218893Sdim // pointer conversions. If so, we permit the conversion. 2427218893Sdim 2428218893Sdim const FunctionProtoType *FromFunctionType 2429218893Sdim = FromPointeeType->getAs<FunctionProtoType>(); 2430218893Sdim const FunctionProtoType *ToFunctionType 2431218893Sdim = ToPointeeType->getAs<FunctionProtoType>(); 2432218893Sdim 2433218893Sdim if (!FromFunctionType || !ToFunctionType) 2434218893Sdim return false; 2435218893Sdim 2436218893Sdim if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2437218893Sdim return true; 2438218893Sdim 2439218893Sdim // Perform the quick checks that will tell us whether these 2440218893Sdim // function types are obviously different. 2441218893Sdim if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2442218893Sdim FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2443218893Sdim return false; 2444218893Sdim 2445218893Sdim FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2446218893Sdim FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2447218893Sdim if (FromEInfo != ToEInfo) 2448218893Sdim return false; 2449218893Sdim 2450218893Sdim bool IncompatibleObjC = false; 2451218893Sdim if (Context.hasSameType(FromFunctionType->getResultType(), 2452218893Sdim ToFunctionType->getResultType())) { 2453218893Sdim // Okay, the types match exactly. Nothing to do. 2454218893Sdim } else { 2455218893Sdim QualType RHS = FromFunctionType->getResultType(); 2456218893Sdim QualType LHS = ToFunctionType->getResultType(); 2457234353Sdim if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2458218893Sdim !RHS.hasQualifiers() && LHS.hasQualifiers()) 2459218893Sdim LHS = LHS.getUnqualifiedType(); 2460218893Sdim 2461218893Sdim if (Context.hasSameType(RHS,LHS)) { 2462218893Sdim // OK exact match. 2463218893Sdim } else if (isObjCPointerConversion(RHS, LHS, 2464218893Sdim ConvertedType, IncompatibleObjC)) { 2465218893Sdim if (IncompatibleObjC) 2466218893Sdim return false; 2467218893Sdim // Okay, we have an Objective-C pointer conversion. 2468218893Sdim } 2469218893Sdim else 2470218893Sdim return false; 2471218893Sdim } 2472218893Sdim 2473218893Sdim // Check argument types. 2474218893Sdim for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2475218893Sdim ArgIdx != NumArgs; ++ArgIdx) { 2476218893Sdim IncompatibleObjC = false; 2477218893Sdim QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2478218893Sdim QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2479218893Sdim if (Context.hasSameType(FromArgType, ToArgType)) { 2480218893Sdim // Okay, the types match exactly. Nothing to do. 2481218893Sdim } else if (isObjCPointerConversion(ToArgType, FromArgType, 2482218893Sdim ConvertedType, IncompatibleObjC)) { 2483218893Sdim if (IncompatibleObjC) 2484218893Sdim return false; 2485218893Sdim // Okay, we have an Objective-C pointer conversion. 2486218893Sdim } else 2487218893Sdim // Argument types are too different. Abort. 2488218893Sdim return false; 2489218893Sdim } 2490226633Sdim if (LangOpts.ObjCAutoRefCount && 2491226633Sdim !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2492226633Sdim ToFunctionType)) 2493226633Sdim return false; 2494226633Sdim 2495218893Sdim ConvertedType = ToType; 2496218893Sdim return true; 2497218893Sdim} 2498218893Sdim 2499234353Sdimenum { 2500234353Sdim ft_default, 2501234353Sdim ft_different_class, 2502234353Sdim ft_parameter_arity, 2503234353Sdim ft_parameter_mismatch, 2504234353Sdim ft_return_type, 2505234353Sdim ft_qualifer_mismatch 2506234353Sdim}; 2507234353Sdim 2508234353Sdim/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2509234353Sdim/// function types. Catches different number of parameter, mismatch in 2510234353Sdim/// parameter types, and different return types. 2511234353Sdimvoid Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2512234353Sdim QualType FromType, QualType ToType) { 2513234353Sdim // If either type is not valid, include no extra info. 2514234353Sdim if (FromType.isNull() || ToType.isNull()) { 2515234353Sdim PDiag << ft_default; 2516234353Sdim return; 2517234353Sdim } 2518234353Sdim 2519234353Sdim // Get the function type from the pointers. 2520234353Sdim if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2521234353Sdim const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2522234353Sdim *ToMember = ToType->getAs<MemberPointerType>(); 2523234353Sdim if (FromMember->getClass() != ToMember->getClass()) { 2524234353Sdim PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2525234353Sdim << QualType(FromMember->getClass(), 0); 2526234353Sdim return; 2527234353Sdim } 2528234353Sdim FromType = FromMember->getPointeeType(); 2529234353Sdim ToType = ToMember->getPointeeType(); 2530234353Sdim } 2531234353Sdim 2532234353Sdim if (FromType->isPointerType()) 2533234353Sdim FromType = FromType->getPointeeType(); 2534234353Sdim if (ToType->isPointerType()) 2535234353Sdim ToType = ToType->getPointeeType(); 2536234353Sdim 2537234353Sdim // Remove references. 2538234353Sdim FromType = FromType.getNonReferenceType(); 2539234353Sdim ToType = ToType.getNonReferenceType(); 2540234353Sdim 2541234353Sdim // Don't print extra info for non-specialized template functions. 2542234353Sdim if (FromType->isInstantiationDependentType() && 2543234353Sdim !FromType->getAs<TemplateSpecializationType>()) { 2544234353Sdim PDiag << ft_default; 2545234353Sdim return; 2546234353Sdim } 2547234353Sdim 2548234353Sdim // No extra info for same types. 2549234353Sdim if (Context.hasSameType(FromType, ToType)) { 2550234353Sdim PDiag << ft_default; 2551234353Sdim return; 2552234353Sdim } 2553234353Sdim 2554234353Sdim const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2555234353Sdim *ToFunction = ToType->getAs<FunctionProtoType>(); 2556234353Sdim 2557234353Sdim // Both types need to be function types. 2558234353Sdim if (!FromFunction || !ToFunction) { 2559234353Sdim PDiag << ft_default; 2560234353Sdim return; 2561234353Sdim } 2562234353Sdim 2563234353Sdim if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2564234353Sdim PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2565234353Sdim << FromFunction->getNumArgs(); 2566234353Sdim return; 2567234353Sdim } 2568234353Sdim 2569234353Sdim // Handle different parameter types. 2570234353Sdim unsigned ArgPos; 2571234353Sdim if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2572234353Sdim PDiag << ft_parameter_mismatch << ArgPos + 1 2573234353Sdim << ToFunction->getArgType(ArgPos) 2574234353Sdim << FromFunction->getArgType(ArgPos); 2575234353Sdim return; 2576234353Sdim } 2577234353Sdim 2578234353Sdim // Handle different return type. 2579234353Sdim if (!Context.hasSameType(FromFunction->getResultType(), 2580234353Sdim ToFunction->getResultType())) { 2581234353Sdim PDiag << ft_return_type << ToFunction->getResultType() 2582234353Sdim << FromFunction->getResultType(); 2583234353Sdim return; 2584234353Sdim } 2585234353Sdim 2586234353Sdim unsigned FromQuals = FromFunction->getTypeQuals(), 2587234353Sdim ToQuals = ToFunction->getTypeQuals(); 2588234353Sdim if (FromQuals != ToQuals) { 2589234353Sdim PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2590234353Sdim return; 2591234353Sdim } 2592234353Sdim 2593234353Sdim // Unable to find a difference, so add no extra info. 2594234353Sdim PDiag << ft_default; 2595234353Sdim} 2596234353Sdim 2597207619Srdivacky/// FunctionArgTypesAreEqual - This routine checks two function proto types 2598234353Sdim/// for equality of their argument types. Caller has already checked that 2599207619Srdivacky/// they have same number of arguments. This routine assumes that Objective-C 2600207619Srdivacky/// pointer types which only differ in their protocol qualifiers are equal. 2601239462Sdim/// If the parameters are different, ArgPos will have the parameter index 2602234353Sdim/// of the first different parameter. 2603218893Sdimbool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2604234353Sdim const FunctionProtoType *NewType, 2605234353Sdim unsigned *ArgPos) { 2606234353Sdim if (!getLangOpts().ObjC1) { 2607234353Sdim for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2608234353Sdim N = NewType->arg_type_begin(), 2609234353Sdim E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2610234353Sdim if (!Context.hasSameType(*O, *N)) { 2611234353Sdim if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2612234353Sdim return false; 2613234353Sdim } 2614234353Sdim } 2615234353Sdim return true; 2616234353Sdim } 2617218893Sdim 2618207619Srdivacky for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2619207619Srdivacky N = NewType->arg_type_begin(), 2620207619Srdivacky E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2621207619Srdivacky QualType ToType = (*O); 2622207619Srdivacky QualType FromType = (*N); 2623234353Sdim if (!Context.hasSameType(ToType, FromType)) { 2624207619Srdivacky if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2625207619Srdivacky if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2626208600Srdivacky if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2627208600Srdivacky PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2628208600Srdivacky (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2629208600Srdivacky PTFr->getPointeeType()->isObjCQualifiedClassType())) 2630207619Srdivacky continue; 2631207619Srdivacky } 2632208600Srdivacky else if (const ObjCObjectPointerType *PTTo = 2633208600Srdivacky ToType->getAs<ObjCObjectPointerType>()) { 2634218893Sdim if (const ObjCObjectPointerType *PTFr = 2635208600Srdivacky FromType->getAs<ObjCObjectPointerType>()) 2636234353Sdim if (Context.hasSameUnqualifiedType( 2637234353Sdim PTTo->getObjectType()->getBaseType(), 2638234353Sdim PTFr->getObjectType()->getBaseType())) 2639208600Srdivacky continue; 2640207619Srdivacky } 2641234353Sdim if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2642218893Sdim return false; 2643207619Srdivacky } 2644207619Srdivacky } 2645207619Srdivacky return true; 2646207619Srdivacky} 2647193326Sed 2648193326Sed/// CheckPointerConversion - Check the pointer conversion from the 2649193326Sed/// expression From to the type ToType. This routine checks for 2650198092Srdivacky/// ambiguous or inaccessible derived-to-base pointer 2651193326Sed/// conversions for which IsPointerConversion has already returned 2652193326Sed/// true. It returns true and produces a diagnostic if there was an 2653193326Sed/// error, or returns false otherwise. 2654198092Srdivackybool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2655212904Sdim CastKind &Kind, 2656212904Sdim CXXCastPath& BasePath, 2657199482Srdivacky bool IgnoreBaseAccess) { 2658193326Sed QualType FromType = From->getType(); 2659218893Sdim bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2660193326Sed 2661218893Sdim Kind = CK_BitCast; 2662218893Sdim 2663239462Sdim if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2664239462Sdim From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2665239462Sdim Expr::NPCK_ZeroExpression) { 2666239462Sdim if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2667239462Sdim DiagRuntimeBehavior(From->getExprLoc(), From, 2668239462Sdim PDiag(diag::warn_impcast_bool_to_null_pointer) 2669239462Sdim << ToType << From->getSourceRange()); 2670239462Sdim else if (!isUnevaluatedContext()) 2671239462Sdim Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2672239462Sdim << ToType << From->getSourceRange(); 2673239462Sdim } 2674226633Sdim if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2675226633Sdim if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2676193326Sed QualType FromPointeeType = FromPtrType->getPointeeType(), 2677193326Sed ToPointeeType = ToPtrType->getPointeeType(); 2678193326Sed 2679204793Srdivacky if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2680204793Srdivacky !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2681193326Sed // We must have a derived-to-base conversion. Check an 2682193326Sed // ambiguous or inaccessible conversion. 2683198092Srdivacky if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2684198092Srdivacky From->getExprLoc(), 2685207619Srdivacky From->getSourceRange(), &BasePath, 2686199482Srdivacky IgnoreBaseAccess)) 2687198092Srdivacky return true; 2688218893Sdim 2689198092Srdivacky // The conversion was successful. 2690212904Sdim Kind = CK_DerivedToBase; 2691193326Sed } 2692193326Sed } 2693226633Sdim } else if (const ObjCObjectPointerType *ToPtrType = 2694226633Sdim ToType->getAs<ObjCObjectPointerType>()) { 2695226633Sdim if (const ObjCObjectPointerType *FromPtrType = 2696226633Sdim FromType->getAs<ObjCObjectPointerType>()) { 2697198092Srdivacky // Objective-C++ conversions are always okay. 2698198092Srdivacky // FIXME: We should have a different class of conversions for the 2699198092Srdivacky // Objective-C++ implicit conversions. 2700198092Srdivacky if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2701198092Srdivacky return false; 2702226633Sdim } else if (FromType->isBlockPointerType()) { 2703226633Sdim Kind = CK_BlockPointerToObjCPointerCast; 2704226633Sdim } else { 2705226633Sdim Kind = CK_CPointerToObjCPointerCast; 2706218893Sdim } 2707226633Sdim } else if (ToType->isBlockPointerType()) { 2708226633Sdim if (!FromType->isBlockPointerType()) 2709226633Sdim Kind = CK_AnyPointerToBlockPointerCast; 2710218893Sdim } 2711193326Sed 2712218893Sdim // We shouldn't fall into this case unless it's valid for other 2713218893Sdim // reasons. 2714218893Sdim if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2715218893Sdim Kind = CK_NullToPointer; 2716218893Sdim 2717193326Sed return false; 2718193326Sed} 2719193326Sed 2720193326Sed/// IsMemberPointerConversion - Determines whether the conversion of the 2721193326Sed/// expression From, which has the (possibly adjusted) type FromType, can be 2722193326Sed/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2723193326Sed/// If so, returns true and places the converted type (that might differ from 2724193326Sed/// ToType in its cv-qualifiers at some level) into ConvertedType. 2725193326Sedbool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2726218893Sdim QualType ToType, 2727198092Srdivacky bool InOverloadResolution, 2728198092Srdivacky QualType &ConvertedType) { 2729198092Srdivacky const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2730193326Sed if (!ToTypePtr) 2731193326Sed return false; 2732193326Sed 2733193326Sed // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2734198092Srdivacky if (From->isNullPointerConstant(Context, 2735198092Srdivacky InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2736198092Srdivacky : Expr::NPC_ValueDependentIsNull)) { 2737193326Sed ConvertedType = ToType; 2738193326Sed return true; 2739193326Sed } 2740193326Sed 2741193326Sed // Otherwise, both types have to be member pointers. 2742198092Srdivacky const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2743193326Sed if (!FromTypePtr) 2744193326Sed return false; 2745193326Sed 2746193326Sed // A pointer to member of B can be converted to a pointer to member of D, 2747193326Sed // where D is derived from B (C++ 4.11p2). 2748193326Sed QualType FromClass(FromTypePtr->getClass(), 0); 2749193326Sed QualType ToClass(ToTypePtr->getClass(), 0); 2750193326Sed 2751218893Sdim if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2752239462Sdim !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2753218893Sdim IsDerivedFrom(ToClass, FromClass)) { 2754193326Sed ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2755193326Sed ToClass.getTypePtr()); 2756193326Sed return true; 2757193326Sed } 2758193326Sed 2759193326Sed return false; 2760193326Sed} 2761218893Sdim 2762193326Sed/// CheckMemberPointerConversion - Check the member pointer conversion from the 2763193326Sed/// expression From to the type ToType. This routine checks for ambiguous or 2764203955Srdivacky/// virtual or inaccessible base-to-derived member pointer conversions 2765193326Sed/// for which IsMemberPointerConversion has already returned true. It returns 2766193326Sed/// true and produces a diagnostic if there was an error, or returns false 2767193326Sed/// otherwise. 2768198092Srdivackybool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2769212904Sdim CastKind &Kind, 2770212904Sdim CXXCastPath &BasePath, 2771199482Srdivacky bool IgnoreBaseAccess) { 2772193326Sed QualType FromType = From->getType(); 2773198092Srdivacky const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2774198092Srdivacky if (!FromPtrType) { 2775198092Srdivacky // This must be a null pointer to member pointer conversion 2776218893Sdim assert(From->isNullPointerConstant(Context, 2777198092Srdivacky Expr::NPC_ValueDependentIsNull) && 2778198092Srdivacky "Expr must be null pointer constant!"); 2779212904Sdim Kind = CK_NullToMemberPointer; 2780193326Sed return false; 2781198092Srdivacky } 2782193326Sed 2783198092Srdivacky const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2784193326Sed assert(ToPtrType && "No member pointer cast has a target type " 2785193326Sed "that is not a member pointer."); 2786193326Sed 2787193326Sed QualType FromClass = QualType(FromPtrType->getClass(), 0); 2788193326Sed QualType ToClass = QualType(ToPtrType->getClass(), 0); 2789193326Sed 2790193326Sed // FIXME: What about dependent types? 2791193326Sed assert(FromClass->isRecordType() && "Pointer into non-class."); 2792193326Sed assert(ToClass->isRecordType() && "Pointer into non-class."); 2793193326Sed 2794207619Srdivacky CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2795198092Srdivacky /*DetectVirtual=*/true); 2796193326Sed bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2797193326Sed assert(DerivationOkay && 2798193326Sed "Should not have been called if derivation isn't OK."); 2799193326Sed (void)DerivationOkay; 2800193326Sed 2801193326Sed if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2802193326Sed getUnqualifiedType())) { 2803193326Sed std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2804193326Sed Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2805193326Sed << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2806193326Sed return true; 2807193326Sed } 2808193326Sed 2809193326Sed if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2810193326Sed Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2811193326Sed << FromClass << ToClass << QualType(VBase, 0) 2812193326Sed << From->getSourceRange(); 2813193326Sed return true; 2814193326Sed } 2815193326Sed 2816203955Srdivacky if (!IgnoreBaseAccess) 2817205219Srdivacky CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2818205219Srdivacky Paths.front(), 2819205219Srdivacky diag::err_downcast_from_inaccessible_base); 2820203955Srdivacky 2821198092Srdivacky // Must be a base to derived member conversion. 2822207619Srdivacky BuildBasePathArray(Paths, BasePath); 2823212904Sdim Kind = CK_BaseToDerivedMemberPointer; 2824193326Sed return false; 2825193326Sed} 2826193326Sed 2827193326Sed/// IsQualificationConversion - Determines whether the conversion from 2828193326Sed/// an rvalue of type FromType to ToType is a qualification conversion 2829193326Sed/// (C++ 4.4). 2830224145Sdim/// 2831224145Sdim/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2832224145Sdim/// when the qualification conversion involves a change in the Objective-C 2833224145Sdim/// object lifetime. 2834198092Srdivackybool 2835218893SdimSema::IsQualificationConversion(QualType FromType, QualType ToType, 2836224145Sdim bool CStyle, bool &ObjCLifetimeConversion) { 2837193326Sed FromType = Context.getCanonicalType(FromType); 2838193326Sed ToType = Context.getCanonicalType(ToType); 2839224145Sdim ObjCLifetimeConversion = false; 2840224145Sdim 2841193326Sed // If FromType and ToType are the same type, this is not a 2842193326Sed // qualification conversion. 2843203955Srdivacky if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2844193326Sed return false; 2845193326Sed 2846193326Sed // (C++ 4.4p4): 2847193326Sed // A conversion can add cv-qualifiers at levels other than the first 2848193326Sed // in multi-level pointers, subject to the following rules: [...] 2849193326Sed bool PreviousToQualsIncludeConst = true; 2850193326Sed bool UnwrappedAnyPointer = false; 2851210299Sed while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2852193326Sed // Within each iteration of the loop, we check the qualifiers to 2853193326Sed // determine if this still looks like a qualification 2854193326Sed // conversion. Then, if all is well, we unwrap one more level of 2855193326Sed // pointers or pointers-to-members and do it all again 2856193326Sed // until there are no more pointers or pointers-to-members left to 2857193326Sed // unwrap. 2858193326Sed UnwrappedAnyPointer = true; 2859193326Sed 2860221345Sdim Qualifiers FromQuals = FromType.getQualifiers(); 2861221345Sdim Qualifiers ToQuals = ToType.getQualifiers(); 2862221345Sdim 2863224145Sdim // Objective-C ARC: 2864224145Sdim // Check Objective-C lifetime conversions. 2865224145Sdim if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2866224145Sdim UnwrappedAnyPointer) { 2867224145Sdim if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2868224145Sdim ObjCLifetimeConversion = true; 2869224145Sdim FromQuals.removeObjCLifetime(); 2870224145Sdim ToQuals.removeObjCLifetime(); 2871224145Sdim } else { 2872224145Sdim // Qualification conversions cannot cast between different 2873224145Sdim // Objective-C lifetime qualifiers. 2874224145Sdim return false; 2875224145Sdim } 2876224145Sdim } 2877224145Sdim 2878223017Sdim // Allow addition/removal of GC attributes but not changing GC attributes. 2879223017Sdim if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2880223017Sdim (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2881223017Sdim FromQuals.removeObjCGCAttr(); 2882223017Sdim ToQuals.removeObjCGCAttr(); 2883223017Sdim } 2884223017Sdim 2885193326Sed // -- for every j > 0, if const is in cv 1,j then const is in cv 2886193326Sed // 2,j, and similarly for volatile. 2887221345Sdim if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2888193326Sed return false; 2889198092Srdivacky 2890193326Sed // -- if the cv 1,j and cv 2,j are different, then const is in 2891193326Sed // every cv for 0 < k < j. 2892221345Sdim if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2893193326Sed && !PreviousToQualsIncludeConst) 2894193326Sed return false; 2895198092Srdivacky 2896193326Sed // Keep track of whether all prior cv-qualifiers in the "to" type 2897193326Sed // include const. 2898198092Srdivacky PreviousToQualsIncludeConst 2899221345Sdim = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2900193326Sed } 2901193326Sed 2902193326Sed // We are left with FromType and ToType being the pointee types 2903193326Sed // after unwrapping the original FromType and ToType the same number 2904193326Sed // of types. If we unwrapped any pointers, and if FromType and 2905193326Sed // ToType have the same unqualified type (since we checked 2906193326Sed // qualifiers above), then this is a qualification conversion. 2907199482Srdivacky return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2908193326Sed} 2909193326Sed 2910234353Sdim/// \brief - Determine whether this is a conversion from a scalar type to an 2911234353Sdim/// atomic type. 2912234353Sdim/// 2913234353Sdim/// If successful, updates \c SCS's second and third steps in the conversion 2914234353Sdim/// sequence to finish the conversion. 2915234353Sdimstatic bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2916234353Sdim bool InOverloadResolution, 2917234353Sdim StandardConversionSequence &SCS, 2918234353Sdim bool CStyle) { 2919234353Sdim const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2920234353Sdim if (!ToAtomic) 2921234353Sdim return false; 2922234353Sdim 2923234353Sdim StandardConversionSequence InnerSCS; 2924234353Sdim if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2925234353Sdim InOverloadResolution, InnerSCS, 2926234353Sdim CStyle, /*AllowObjCWritebackConversion=*/false)) 2927234353Sdim return false; 2928234353Sdim 2929234353Sdim SCS.Second = InnerSCS.Second; 2930234353Sdim SCS.setToType(1, InnerSCS.getToType(1)); 2931234353Sdim SCS.Third = InnerSCS.Third; 2932234353Sdim SCS.QualificationIncludesObjCLifetime 2933234353Sdim = InnerSCS.QualificationIncludesObjCLifetime; 2934234353Sdim SCS.setToType(2, InnerSCS.getToType(2)); 2935234353Sdim return true; 2936234353Sdim} 2937234353Sdim 2938234353Sdimstatic bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2939234353Sdim CXXConstructorDecl *Constructor, 2940234353Sdim QualType Type) { 2941234353Sdim const FunctionProtoType *CtorType = 2942234353Sdim Constructor->getType()->getAs<FunctionProtoType>(); 2943234353Sdim if (CtorType->getNumArgs() > 0) { 2944234353Sdim QualType FirstArg = CtorType->getArgType(0); 2945234353Sdim if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2946234353Sdim return true; 2947234353Sdim } 2948234353Sdim return false; 2949234353Sdim} 2950234353Sdim 2951234353Sdimstatic OverloadingResult 2952234353SdimIsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2953234353Sdim CXXRecordDecl *To, 2954234353Sdim UserDefinedConversionSequence &User, 2955234353Sdim OverloadCandidateSet &CandidateSet, 2956234353Sdim bool AllowExplicit) { 2957249423Sdim DeclContext::lookup_result R = S.LookupConstructors(To); 2958249423Sdim for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2959234353Sdim Con != ConEnd; ++Con) { 2960234353Sdim NamedDecl *D = *Con; 2961234353Sdim DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2962234353Sdim 2963234353Sdim // Find the constructor (which may be a template). 2964234353Sdim CXXConstructorDecl *Constructor = 0; 2965234353Sdim FunctionTemplateDecl *ConstructorTmpl 2966234353Sdim = dyn_cast<FunctionTemplateDecl>(D); 2967234353Sdim if (ConstructorTmpl) 2968234353Sdim Constructor 2969234353Sdim = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2970234353Sdim else 2971234353Sdim Constructor = cast<CXXConstructorDecl>(D); 2972234353Sdim 2973234353Sdim bool Usable = !Constructor->isInvalidDecl() && 2974234353Sdim S.isInitListConstructor(Constructor) && 2975234353Sdim (AllowExplicit || !Constructor->isExplicit()); 2976234353Sdim if (Usable) { 2977234353Sdim // If the first argument is (a reference to) the target type, 2978234353Sdim // suppress conversions. 2979234353Sdim bool SuppressUserConversions = 2980234353Sdim isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2981234353Sdim if (ConstructorTmpl) 2982234353Sdim S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2983234353Sdim /*ExplicitArgs*/ 0, 2984234353Sdim From, CandidateSet, 2985234353Sdim SuppressUserConversions); 2986234353Sdim else 2987234353Sdim S.AddOverloadCandidate(Constructor, FoundDecl, 2988234353Sdim From, CandidateSet, 2989234353Sdim SuppressUserConversions); 2990234353Sdim } 2991234353Sdim } 2992234353Sdim 2993234353Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 2994234353Sdim 2995234353Sdim OverloadCandidateSet::iterator Best; 2996234353Sdim switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2997234353Sdim case OR_Success: { 2998234353Sdim // Record the standard conversion we used and the conversion function. 2999234353Sdim CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3000234353Sdim QualType ThisType = Constructor->getThisType(S.Context); 3001234353Sdim // Initializer lists don't have conversions as such. 3002234353Sdim User.Before.setAsIdentityConversion(); 3003234353Sdim User.HadMultipleCandidates = HadMultipleCandidates; 3004234353Sdim User.ConversionFunction = Constructor; 3005234353Sdim User.FoundConversionFunction = Best->FoundDecl; 3006234353Sdim User.After.setAsIdentityConversion(); 3007234353Sdim User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3008234353Sdim User.After.setAllToTypes(ToType); 3009234353Sdim return OR_Success; 3010234353Sdim } 3011234353Sdim 3012234353Sdim case OR_No_Viable_Function: 3013234353Sdim return OR_No_Viable_Function; 3014234353Sdim case OR_Deleted: 3015234353Sdim return OR_Deleted; 3016234353Sdim case OR_Ambiguous: 3017234353Sdim return OR_Ambiguous; 3018234353Sdim } 3019234353Sdim 3020234353Sdim llvm_unreachable("Invalid OverloadResult!"); 3021234353Sdim} 3022234353Sdim 3023193326Sed/// Determines whether there is a user-defined conversion sequence 3024193326Sed/// (C++ [over.ics.user]) that converts expression From to the type 3025193326Sed/// ToType. If such a conversion exists, User will contain the 3026193326Sed/// user-defined conversion sequence that performs such a conversion 3027193326Sed/// and this routine will return true. Otherwise, this routine returns 3028193326Sed/// false and User is unspecified. 3029193326Sed/// 3030193326Sed/// \param AllowExplicit true if the conversion should consider C++0x 3031193326Sed/// "explicit" conversion functions as well as non-explicit conversion 3032193326Sed/// functions (C++0x [class.conv.fct]p2). 3033212904Sdimstatic OverloadingResult 3034212904SdimIsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3035234353Sdim UserDefinedConversionSequence &User, 3036234353Sdim OverloadCandidateSet &CandidateSet, 3037212904Sdim bool AllowExplicit) { 3038207619Srdivacky // Whether we will only visit constructors. 3039207619Srdivacky bool ConstructorsOnly = false; 3040207619Srdivacky 3041207619Srdivacky // If the type we are conversion to is a class type, enumerate its 3042207619Srdivacky // constructors. 3043198092Srdivacky if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3044207619Srdivacky // C++ [over.match.ctor]p1: 3045207619Srdivacky // When objects of class type are direct-initialized (8.5), or 3046207619Srdivacky // copy-initialized from an expression of the same or a 3047207619Srdivacky // derived class type (8.5), overload resolution selects the 3048207619Srdivacky // constructor. [...] For copy-initialization, the candidate 3049207619Srdivacky // functions are all the converting constructors (12.3.1) of 3050207619Srdivacky // that class. The argument list is the expression-list within 3051207619Srdivacky // the parentheses of the initializer. 3052212904Sdim if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3053207619Srdivacky (From->getType()->getAs<RecordType>() && 3054212904Sdim S.IsDerivedFrom(From->getType(), ToType))) 3055207619Srdivacky ConstructorsOnly = true; 3056207619Srdivacky 3057249423Sdim S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3058221345Sdim // RequireCompleteType may have returned true due to some invalid decl 3059221345Sdim // during template instantiation, but ToType may be complete enough now 3060221345Sdim // to try to recover. 3061221345Sdim if (ToType->isIncompleteType()) { 3062198954Srdivacky // We're not going to find any constructors. 3063198954Srdivacky } else if (CXXRecordDecl *ToRecordDecl 3064198954Srdivacky = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3065234353Sdim 3066234353Sdim Expr **Args = &From; 3067234353Sdim unsigned NumArgs = 1; 3068234353Sdim bool ListInitializing = false; 3069234353Sdim if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3070234353Sdim // But first, see if there is an init-list-contructor that will work. 3071234353Sdim OverloadingResult Result = IsInitializerListConstructorConversion( 3072234353Sdim S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3073234353Sdim if (Result != OR_No_Viable_Function) 3074234353Sdim return Result; 3075234353Sdim // Never mind. 3076234353Sdim CandidateSet.clear(); 3077234353Sdim 3078234353Sdim // If we're list-initializing, we pass the individual elements as 3079234353Sdim // arguments, not the entire list. 3080234353Sdim Args = InitList->getInits(); 3081234353Sdim NumArgs = InitList->getNumInits(); 3082234353Sdim ListInitializing = true; 3083234353Sdim } 3084234353Sdim 3085249423Sdim DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3086249423Sdim for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3087193326Sed Con != ConEnd; ++Con) { 3088205408Srdivacky NamedDecl *D = *Con; 3089205408Srdivacky DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3090205408Srdivacky 3091198092Srdivacky // Find the constructor (which may be a template). 3092198092Srdivacky CXXConstructorDecl *Constructor = 0; 3093198092Srdivacky FunctionTemplateDecl *ConstructorTmpl 3094205408Srdivacky = dyn_cast<FunctionTemplateDecl>(D); 3095198092Srdivacky if (ConstructorTmpl) 3096198092Srdivacky Constructor 3097198092Srdivacky = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3098198092Srdivacky else 3099205408Srdivacky Constructor = cast<CXXConstructorDecl>(D); 3100218893Sdim 3101234353Sdim bool Usable = !Constructor->isInvalidDecl(); 3102234353Sdim if (ListInitializing) 3103234353Sdim Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3104234353Sdim else 3105234353Sdim Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3106234353Sdim if (Usable) { 3107234353Sdim bool SuppressUserConversions = !ConstructorsOnly; 3108234353Sdim if (SuppressUserConversions && ListInitializing) { 3109234353Sdim SuppressUserConversions = false; 3110234353Sdim if (NumArgs == 1) { 3111234353Sdim // If the first argument is (a reference to) the target type, 3112234353Sdim // suppress conversions. 3113234353Sdim SuppressUserConversions = isFirstArgumentCompatibleWithType( 3114234353Sdim S.Context, Constructor, ToType); 3115234353Sdim } 3116234353Sdim } 3117198092Srdivacky if (ConstructorTmpl) 3118212904Sdim S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3119212904Sdim /*ExplicitArgs*/ 0, 3120234353Sdim llvm::makeArrayRef(Args, NumArgs), 3121234353Sdim CandidateSet, SuppressUserConversions); 3122198092Srdivacky else 3123198092Srdivacky // Allow one user-defined conversion when user specifies a 3124198092Srdivacky // From->ToType conversion via an static cast (c-style, etc). 3125212904Sdim S.AddOverloadCandidate(Constructor, FoundDecl, 3126234353Sdim llvm::makeArrayRef(Args, NumArgs), 3127234353Sdim CandidateSet, SuppressUserConversions); 3128198092Srdivacky } 3129193326Sed } 3130193326Sed } 3131193326Sed } 3132193326Sed 3133207619Srdivacky // Enumerate conversion functions, if we're allowed to. 3134234353Sdim if (ConstructorsOnly || isa<InitListExpr>(From)) { 3135239462Sdim } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3136198092Srdivacky // No conversion functions from incomplete types. 3137198092Srdivacky } else if (const RecordType *FromRecordType 3138207619Srdivacky = From->getType()->getAs<RecordType>()) { 3139198092Srdivacky if (CXXRecordDecl *FromRecordDecl 3140198092Srdivacky = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3141193326Sed // Add all of the conversion functions as candidates. 3142249423Sdim std::pair<CXXRecordDecl::conversion_iterator, 3143249423Sdim CXXRecordDecl::conversion_iterator> 3144249423Sdim Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3145249423Sdim for (CXXRecordDecl::conversion_iterator 3146249423Sdim I = Conversions.first, E = Conversions.second; I != E; ++I) { 3147205408Srdivacky DeclAccessPair FoundDecl = I.getPair(); 3148205408Srdivacky NamedDecl *D = FoundDecl.getDecl(); 3149200583Srdivacky CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3150200583Srdivacky if (isa<UsingShadowDecl>(D)) 3151200583Srdivacky D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3152200583Srdivacky 3153198092Srdivacky CXXConversionDecl *Conv; 3154198092Srdivacky FunctionTemplateDecl *ConvTemplate; 3155206084Srdivacky if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3156206084Srdivacky Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3157198092Srdivacky else 3158206084Srdivacky Conv = cast<CXXConversionDecl>(D); 3159198092Srdivacky 3160198092Srdivacky if (AllowExplicit || !Conv->isExplicit()) { 3161198092Srdivacky if (ConvTemplate) 3162212904Sdim S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3163212904Sdim ActingContext, From, ToType, 3164212904Sdim CandidateSet); 3165198092Srdivacky else 3166212904Sdim S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3167212904Sdim From, ToType, CandidateSet); 3168198092Srdivacky } 3169193326Sed } 3170193326Sed } 3171193326Sed } 3172193326Sed 3173226633Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 3174226633Sdim 3175193326Sed OverloadCandidateSet::iterator Best; 3176218893Sdim switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3177212904Sdim case OR_Success: 3178212904Sdim // Record the standard conversion we used and the conversion function. 3179212904Sdim if (CXXConstructorDecl *Constructor 3180212904Sdim = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3181212904Sdim // C++ [over.ics.user]p1: 3182212904Sdim // If the user-defined conversion is specified by a 3183212904Sdim // constructor (12.3.1), the initial standard conversion 3184212904Sdim // sequence converts the source type to the type required by 3185212904Sdim // the argument of the constructor. 3186212904Sdim // 3187212904Sdim QualType ThisType = Constructor->getThisType(S.Context); 3188234353Sdim if (isa<InitListExpr>(From)) { 3189234353Sdim // Initializer lists don't have conversions as such. 3190234353Sdim User.Before.setAsIdentityConversion(); 3191234353Sdim } else { 3192234353Sdim if (Best->Conversions[0].isEllipsis()) 3193234353Sdim User.EllipsisConversion = true; 3194234353Sdim else { 3195234353Sdim User.Before = Best->Conversions[0].Standard; 3196234353Sdim User.EllipsisConversion = false; 3197234353Sdim } 3198193326Sed } 3199226633Sdim User.HadMultipleCandidates = HadMultipleCandidates; 3200212904Sdim User.ConversionFunction = Constructor; 3201226633Sdim User.FoundConversionFunction = Best->FoundDecl; 3202212904Sdim User.After.setAsIdentityConversion(); 3203212904Sdim User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3204212904Sdim User.After.setAllToTypes(ToType); 3205212904Sdim return OR_Success; 3206234353Sdim } 3207234353Sdim if (CXXConversionDecl *Conversion 3208212904Sdim = dyn_cast<CXXConversionDecl>(Best->Function)) { 3209212904Sdim // C++ [over.ics.user]p1: 3210212904Sdim // 3211212904Sdim // [...] If the user-defined conversion is specified by a 3212212904Sdim // conversion function (12.3.2), the initial standard 3213212904Sdim // conversion sequence converts the source type to the 3214212904Sdim // implicit object parameter of the conversion function. 3215212904Sdim User.Before = Best->Conversions[0].Standard; 3216226633Sdim User.HadMultipleCandidates = HadMultipleCandidates; 3217212904Sdim User.ConversionFunction = Conversion; 3218226633Sdim User.FoundConversionFunction = Best->FoundDecl; 3219212904Sdim User.EllipsisConversion = false; 3220198092Srdivacky 3221212904Sdim // C++ [over.ics.user]p2: 3222212904Sdim // The second standard conversion sequence converts the 3223212904Sdim // result of the user-defined conversion to the target type 3224212904Sdim // for the sequence. Since an implicit conversion sequence 3225212904Sdim // is an initialization, the special rules for 3226212904Sdim // initialization by user-defined conversion apply when 3227212904Sdim // selecting the best user-defined conversion for a 3228212904Sdim // user-defined conversion sequence (see 13.3.3 and 3229212904Sdim // 13.3.3.1). 3230212904Sdim User.After = Best->FinalConversion; 3231212904Sdim return OR_Success; 3232193326Sed } 3233234353Sdim llvm_unreachable("Not a constructor or conversion function?"); 3234193326Sed 3235212904Sdim case OR_No_Viable_Function: 3236212904Sdim return OR_No_Viable_Function; 3237212904Sdim case OR_Deleted: 3238212904Sdim // No conversion here! We're done. 3239212904Sdim return OR_Deleted; 3240218893Sdim 3241212904Sdim case OR_Ambiguous: 3242212904Sdim return OR_Ambiguous; 3243212904Sdim } 3244212904Sdim 3245234353Sdim llvm_unreachable("Invalid OverloadResult!"); 3246193326Sed} 3247218893Sdim 3248198092Srdivackybool 3249199512SrdivackySema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3250198092Srdivacky ImplicitConversionSequence ICS; 3251203955Srdivacky OverloadCandidateSet CandidateSet(From->getExprLoc()); 3252218893Sdim OverloadingResult OvResult = 3253212904Sdim IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3254207619Srdivacky CandidateSet, false); 3255199512Srdivacky if (OvResult == OR_Ambiguous) 3256234353Sdim Diag(From->getLocStart(), 3257199512Srdivacky diag::err_typecheck_ambiguous_condition) 3258199512Srdivacky << From->getType() << ToType << From->getSourceRange(); 3259199512Srdivacky else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3260234353Sdim Diag(From->getLocStart(), 3261199512Srdivacky diag::err_typecheck_nonviable_condition) 3262199512Srdivacky << From->getType() << ToType << From->getSourceRange(); 3263199512Srdivacky else 3264198092Srdivacky return false; 3265234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3266218893Sdim return true; 3267198092Srdivacky} 3268193326Sed 3269234353Sdim/// \brief Compare the user-defined conversion functions or constructors 3270234353Sdim/// of two user-defined conversion sequences to determine whether any ordering 3271234353Sdim/// is possible. 3272234353Sdimstatic ImplicitConversionSequence::CompareKind 3273234353SdimcompareConversionFunctions(Sema &S, 3274234353Sdim FunctionDecl *Function1, 3275234353Sdim FunctionDecl *Function2) { 3276249423Sdim if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3277234353Sdim return ImplicitConversionSequence::Indistinguishable; 3278234353Sdim 3279234353Sdim // Objective-C++: 3280234353Sdim // If both conversion functions are implicitly-declared conversions from 3281234353Sdim // a lambda closure type to a function pointer and a block pointer, 3282234353Sdim // respectively, always prefer the conversion to a function pointer, 3283234353Sdim // because the function pointer is more lightweight and is more likely 3284234353Sdim // to keep code working. 3285234353Sdim CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3286234353Sdim if (!Conv1) 3287234353Sdim return ImplicitConversionSequence::Indistinguishable; 3288234353Sdim 3289234353Sdim CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3290234353Sdim if (!Conv2) 3291234353Sdim return ImplicitConversionSequence::Indistinguishable; 3292234353Sdim 3293234353Sdim if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3294234353Sdim bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3295234353Sdim bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3296234353Sdim if (Block1 != Block2) 3297234353Sdim return Block1? ImplicitConversionSequence::Worse 3298234353Sdim : ImplicitConversionSequence::Better; 3299234353Sdim } 3300234353Sdim 3301234353Sdim return ImplicitConversionSequence::Indistinguishable; 3302234353Sdim} 3303234353Sdim 3304193326Sed/// CompareImplicitConversionSequences - Compare two implicit 3305193326Sed/// conversion sequences to determine whether one is better than the 3306193326Sed/// other or if they are indistinguishable (C++ 13.3.3.2). 3307212904Sdimstatic ImplicitConversionSequence::CompareKind 3308212904SdimCompareImplicitConversionSequences(Sema &S, 3309212904Sdim const ImplicitConversionSequence& ICS1, 3310212904Sdim const ImplicitConversionSequence& ICS2) 3311193326Sed{ 3312193326Sed // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3313193326Sed // conversion sequences (as defined in 13.3.3.1) 3314193326Sed // -- a standard conversion sequence (13.3.3.1.1) is a better 3315193326Sed // conversion sequence than a user-defined conversion sequence or 3316193326Sed // an ellipsis conversion sequence, and 3317193326Sed // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3318193326Sed // conversion sequence than an ellipsis conversion sequence 3319193326Sed // (13.3.3.1.3). 3320198092Srdivacky // 3321202379Srdivacky // C++0x [over.best.ics]p10: 3322202379Srdivacky // For the purpose of ranking implicit conversion sequences as 3323202379Srdivacky // described in 13.3.3.2, the ambiguous conversion sequence is 3324202379Srdivacky // treated as a user-defined sequence that is indistinguishable 3325202379Srdivacky // from any other user-defined conversion sequence. 3326207619Srdivacky if (ICS1.getKindRank() < ICS2.getKindRank()) 3327207619Srdivacky return ImplicitConversionSequence::Better; 3328234353Sdim if (ICS2.getKindRank() < ICS1.getKindRank()) 3329207619Srdivacky return ImplicitConversionSequence::Worse; 3330193326Sed 3331207619Srdivacky // The following checks require both conversion sequences to be of 3332207619Srdivacky // the same kind. 3333207619Srdivacky if (ICS1.getKind() != ICS2.getKind()) 3334202379Srdivacky return ImplicitConversionSequence::Indistinguishable; 3335202379Srdivacky 3336234353Sdim ImplicitConversionSequence::CompareKind Result = 3337234353Sdim ImplicitConversionSequence::Indistinguishable; 3338234353Sdim 3339193326Sed // Two implicit conversion sequences of the same form are 3340193326Sed // indistinguishable conversion sequences unless one of the 3341193326Sed // following rules apply: (C++ 13.3.3.2p3): 3342202379Srdivacky if (ICS1.isStandard()) 3343234353Sdim Result = CompareStandardConversionSequences(S, 3344234353Sdim ICS1.Standard, ICS2.Standard); 3345202379Srdivacky else if (ICS1.isUserDefined()) { 3346193326Sed // User-defined conversion sequence U1 is a better conversion 3347193326Sed // sequence than another user-defined conversion sequence U2 if 3348193326Sed // they contain the same user-defined conversion function or 3349193326Sed // constructor and if the second standard conversion sequence of 3350193326Sed // U1 is better than the second standard conversion sequence of 3351193326Sed // U2 (C++ 13.3.3.2p3). 3352198092Srdivacky if (ICS1.UserDefined.ConversionFunction == 3353193326Sed ICS2.UserDefined.ConversionFunction) 3354234353Sdim Result = CompareStandardConversionSequences(S, 3355234353Sdim ICS1.UserDefined.After, 3356234353Sdim ICS2.UserDefined.After); 3357234353Sdim else 3358234353Sdim Result = compareConversionFunctions(S, 3359234353Sdim ICS1.UserDefined.ConversionFunction, 3360234353Sdim ICS2.UserDefined.ConversionFunction); 3361193326Sed } 3362193326Sed 3363234353Sdim // List-initialization sequence L1 is a better conversion sequence than 3364234353Sdim // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3365234353Sdim // for some X and L2 does not. 3366234353Sdim if (Result == ImplicitConversionSequence::Indistinguishable && 3367234353Sdim !ICS1.isBad() && 3368234353Sdim ICS1.isListInitializationSequence() && 3369234353Sdim ICS2.isListInitializationSequence()) { 3370234353Sdim if (ICS1.isStdInitializerListElement() && 3371234353Sdim !ICS2.isStdInitializerListElement()) 3372234353Sdim return ImplicitConversionSequence::Better; 3373234353Sdim if (!ICS1.isStdInitializerListElement() && 3374234353Sdim ICS2.isStdInitializerListElement()) 3375234353Sdim return ImplicitConversionSequence::Worse; 3376234353Sdim } 3377234353Sdim 3378234353Sdim return Result; 3379193326Sed} 3380193326Sed 3381210299Sedstatic bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3382210299Sed while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3383210299Sed Qualifiers Quals; 3384210299Sed T1 = Context.getUnqualifiedArrayType(T1, Quals); 3385218893Sdim T2 = Context.getUnqualifiedArrayType(T2, Quals); 3386210299Sed } 3387218893Sdim 3388210299Sed return Context.hasSameUnqualifiedType(T1, T2); 3389210299Sed} 3390218893Sdim 3391203955Srdivacky// Per 13.3.3.2p3, compare the given standard conversion sequences to 3392203955Srdivacky// determine if one is a proper subset of the other. 3393203955Srdivackystatic ImplicitConversionSequence::CompareKind 3394203955SrdivackycompareStandardConversionSubsets(ASTContext &Context, 3395203955Srdivacky const StandardConversionSequence& SCS1, 3396203955Srdivacky const StandardConversionSequence& SCS2) { 3397203955Srdivacky ImplicitConversionSequence::CompareKind Result 3398203955Srdivacky = ImplicitConversionSequence::Indistinguishable; 3399203955Srdivacky 3400218893Sdim // the identity conversion sequence is considered to be a subsequence of 3401208600Srdivacky // any non-identity conversion sequence 3402223017Sdim if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3403223017Sdim return ImplicitConversionSequence::Better; 3404223017Sdim else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3405223017Sdim return ImplicitConversionSequence::Worse; 3406218893Sdim 3407203955Srdivacky if (SCS1.Second != SCS2.Second) { 3408203955Srdivacky if (SCS1.Second == ICK_Identity) 3409203955Srdivacky Result = ImplicitConversionSequence::Better; 3410203955Srdivacky else if (SCS2.Second == ICK_Identity) 3411203955Srdivacky Result = ImplicitConversionSequence::Worse; 3412203955Srdivacky else 3413203955Srdivacky return ImplicitConversionSequence::Indistinguishable; 3414210299Sed } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3415203955Srdivacky return ImplicitConversionSequence::Indistinguishable; 3416203955Srdivacky 3417203955Srdivacky if (SCS1.Third == SCS2.Third) { 3418203955Srdivacky return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3419203955Srdivacky : ImplicitConversionSequence::Indistinguishable; 3420203955Srdivacky } 3421203955Srdivacky 3422203955Srdivacky if (SCS1.Third == ICK_Identity) 3423203955Srdivacky return Result == ImplicitConversionSequence::Worse 3424203955Srdivacky ? ImplicitConversionSequence::Indistinguishable 3425203955Srdivacky : ImplicitConversionSequence::Better; 3426203955Srdivacky 3427203955Srdivacky if (SCS2.Third == ICK_Identity) 3428203955Srdivacky return Result == ImplicitConversionSequence::Better 3429203955Srdivacky ? ImplicitConversionSequence::Indistinguishable 3430203955Srdivacky : ImplicitConversionSequence::Worse; 3431218893Sdim 3432203955Srdivacky return ImplicitConversionSequence::Indistinguishable; 3433203955Srdivacky} 3434203955Srdivacky 3435218893Sdim/// \brief Determine whether one of the given reference bindings is better 3436218893Sdim/// than the other based on what kind of bindings they are. 3437218893Sdimstatic bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3438218893Sdim const StandardConversionSequence &SCS2) { 3439218893Sdim // C++0x [over.ics.rank]p3b4: 3440218893Sdim // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3441218893Sdim // implicit object parameter of a non-static member function declared 3442218893Sdim // without a ref-qualifier, and *either* S1 binds an rvalue reference 3443218893Sdim // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3444218893Sdim // lvalue reference to a function lvalue and S2 binds an rvalue 3445218893Sdim // reference*. 3446218893Sdim // 3447218893Sdim // FIXME: Rvalue references. We're going rogue with the above edits, 3448218893Sdim // because the semantics in the current C++0x working paper (N3225 at the 3449218893Sdim // time of this writing) break the standard definition of std::forward 3450218893Sdim // and std::reference_wrapper when dealing with references to functions. 3451218893Sdim // Proposed wording changes submitted to CWG for consideration. 3452218893Sdim if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3453218893Sdim SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3454218893Sdim return false; 3455218893Sdim 3456218893Sdim return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3457218893Sdim SCS2.IsLvalueReference) || 3458218893Sdim (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3459218893Sdim !SCS2.IsLvalueReference); 3460218893Sdim} 3461218893Sdim 3462193326Sed/// CompareStandardConversionSequences - Compare two standard 3463193326Sed/// conversion sequences to determine whether one is better than the 3464193326Sed/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3465212904Sdimstatic ImplicitConversionSequence::CompareKind 3466212904SdimCompareStandardConversionSequences(Sema &S, 3467212904Sdim const StandardConversionSequence& SCS1, 3468212904Sdim const StandardConversionSequence& SCS2) 3469193326Sed{ 3470193326Sed // Standard conversion sequence S1 is a better conversion sequence 3471193326Sed // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3472193326Sed 3473193326Sed // -- S1 is a proper subsequence of S2 (comparing the conversion 3474193326Sed // sequences in the canonical form defined by 13.3.3.1.1, 3475193326Sed // excluding any Lvalue Transformation; the identity conversion 3476193326Sed // sequence is considered to be a subsequence of any 3477193326Sed // non-identity conversion sequence) or, if not that, 3478203955Srdivacky if (ImplicitConversionSequence::CompareKind CK 3479212904Sdim = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3480203955Srdivacky return CK; 3481193326Sed 3482193326Sed // -- the rank of S1 is better than the rank of S2 (by the rules 3483193326Sed // defined below), or, if not that, 3484193326Sed ImplicitConversionRank Rank1 = SCS1.getRank(); 3485193326Sed ImplicitConversionRank Rank2 = SCS2.getRank(); 3486193326Sed if (Rank1 < Rank2) 3487193326Sed return ImplicitConversionSequence::Better; 3488193326Sed else if (Rank2 < Rank1) 3489193326Sed return ImplicitConversionSequence::Worse; 3490193326Sed 3491193326Sed // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3492193326Sed // are indistinguishable unless one of the following rules 3493193326Sed // applies: 3494198092Srdivacky 3495193326Sed // A conversion that is not a conversion of a pointer, or 3496193326Sed // pointer to member, to bool is better than another conversion 3497193326Sed // that is such a conversion. 3498193326Sed if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3499193326Sed return SCS2.isPointerConversionToBool() 3500193326Sed ? ImplicitConversionSequence::Better 3501193326Sed : ImplicitConversionSequence::Worse; 3502193326Sed 3503193326Sed // C++ [over.ics.rank]p4b2: 3504193326Sed // 3505193326Sed // If class B is derived directly or indirectly from class A, 3506193326Sed // conversion of B* to A* is better than conversion of B* to 3507193326Sed // void*, and conversion of A* to void* is better than conversion 3508193326Sed // of B* to void*. 3509198092Srdivacky bool SCS1ConvertsToVoid 3510212904Sdim = SCS1.isPointerConversionToVoidPointer(S.Context); 3511198092Srdivacky bool SCS2ConvertsToVoid 3512212904Sdim = SCS2.isPointerConversionToVoidPointer(S.Context); 3513193326Sed if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3514193326Sed // Exactly one of the conversion sequences is a conversion to 3515193326Sed // a void pointer; it's the worse conversion. 3516193326Sed return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3517193326Sed : ImplicitConversionSequence::Worse; 3518193326Sed } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3519193326Sed // Neither conversion sequence converts to a void pointer; compare 3520193326Sed // their derived-to-base conversions. 3521193326Sed if (ImplicitConversionSequence::CompareKind DerivedCK 3522212904Sdim = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3523193326Sed return DerivedCK; 3524221345Sdim } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3525221345Sdim !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3526193326Sed // Both conversion sequences are conversions to void 3527193326Sed // pointers. Compare the source types to determine if there's an 3528193326Sed // inheritance relationship in their sources. 3529202379Srdivacky QualType FromType1 = SCS1.getFromType(); 3530202379Srdivacky QualType FromType2 = SCS2.getFromType(); 3531193326Sed 3532193326Sed // Adjust the types we're converting from via the array-to-pointer 3533193326Sed // conversion, if we need to. 3534193326Sed if (SCS1.First == ICK_Array_To_Pointer) 3535212904Sdim FromType1 = S.Context.getArrayDecayedType(FromType1); 3536193326Sed if (SCS2.First == ICK_Array_To_Pointer) 3537212904Sdim FromType2 = S.Context.getArrayDecayedType(FromType2); 3538193326Sed 3539221345Sdim QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3540221345Sdim QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3541193326Sed 3542212904Sdim if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3543193326Sed return ImplicitConversionSequence::Better; 3544212904Sdim else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3545193326Sed return ImplicitConversionSequence::Worse; 3546193326Sed 3547193326Sed // Objective-C++: If one interface is more specific than the 3548193326Sed // other, it is the better one. 3549221345Sdim const ObjCObjectPointerType* FromObjCPtr1 3550221345Sdim = FromType1->getAs<ObjCObjectPointerType>(); 3551221345Sdim const ObjCObjectPointerType* FromObjCPtr2 3552221345Sdim = FromType2->getAs<ObjCObjectPointerType>(); 3553221345Sdim if (FromObjCPtr1 && FromObjCPtr2) { 3554221345Sdim bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3555221345Sdim FromObjCPtr2); 3556221345Sdim bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3557221345Sdim FromObjCPtr1); 3558221345Sdim if (AssignLeft != AssignRight) { 3559221345Sdim return AssignLeft? ImplicitConversionSequence::Better 3560221345Sdim : ImplicitConversionSequence::Worse; 3561221345Sdim } 3562193326Sed } 3563193326Sed } 3564193326Sed 3565193326Sed // Compare based on qualification conversions (C++ 13.3.3.2p3, 3566193326Sed // bullet 3). 3567198092Srdivacky if (ImplicitConversionSequence::CompareKind QualCK 3568212904Sdim = CompareQualificationConversions(S, SCS1, SCS2)) 3569193326Sed return QualCK; 3570193326Sed 3571193326Sed if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3572218893Sdim // Check for a better reference binding based on the kind of bindings. 3573218893Sdim if (isBetterReferenceBindingKind(SCS1, SCS2)) 3574218893Sdim return ImplicitConversionSequence::Better; 3575218893Sdim else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3576218893Sdim return ImplicitConversionSequence::Worse; 3577193326Sed 3578193326Sed // C++ [over.ics.rank]p3b4: 3579193326Sed // -- S1 and S2 are reference bindings (8.5.3), and the types to 3580193326Sed // which the references refer are the same type except for 3581193326Sed // top-level cv-qualifiers, and the type to which the reference 3582193326Sed // initialized by S2 refers is more cv-qualified than the type 3583193326Sed // to which the reference initialized by S1 refers. 3584203955Srdivacky QualType T1 = SCS1.getToType(2); 3585203955Srdivacky QualType T2 = SCS2.getToType(2); 3586212904Sdim T1 = S.Context.getCanonicalType(T1); 3587212904Sdim T2 = S.Context.getCanonicalType(T2); 3588201361Srdivacky Qualifiers T1Quals, T2Quals; 3589212904Sdim QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3590212904Sdim QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3591201361Srdivacky if (UnqualT1 == UnqualT2) { 3592224145Sdim // Objective-C++ ARC: If the references refer to objects with different 3593224145Sdim // lifetimes, prefer bindings that don't change lifetime. 3594224145Sdim if (SCS1.ObjCLifetimeConversionBinding != 3595224145Sdim SCS2.ObjCLifetimeConversionBinding) { 3596224145Sdim return SCS1.ObjCLifetimeConversionBinding 3597224145Sdim ? ImplicitConversionSequence::Worse 3598224145Sdim : ImplicitConversionSequence::Better; 3599224145Sdim } 3600224145Sdim 3601218893Sdim // If the type is an array type, promote the element qualifiers to the 3602218893Sdim // type for comparison. 3603201361Srdivacky if (isa<ArrayType>(T1) && T1Quals) 3604212904Sdim T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3605201361Srdivacky if (isa<ArrayType>(T2) && T2Quals) 3606212904Sdim T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3607193326Sed if (T2.isMoreQualifiedThan(T1)) 3608193326Sed return ImplicitConversionSequence::Better; 3609193326Sed else if (T1.isMoreQualifiedThan(T2)) 3610224145Sdim return ImplicitConversionSequence::Worse; 3611193326Sed } 3612193326Sed } 3613193326Sed 3614226633Sdim // In Microsoft mode, prefer an integral conversion to a 3615226633Sdim // floating-to-integral conversion if the integral conversion 3616226633Sdim // is between types of the same size. 3617226633Sdim // For example: 3618226633Sdim // void f(float); 3619226633Sdim // void f(int); 3620226633Sdim // int main { 3621226633Sdim // long a; 3622226633Sdim // f(a); 3623226633Sdim // } 3624226633Sdim // Here, MSVC will call f(int) instead of generating a compile error 3625226633Sdim // as clang will do in standard mode. 3626234353Sdim if (S.getLangOpts().MicrosoftMode && 3627226633Sdim SCS1.Second == ICK_Integral_Conversion && 3628226633Sdim SCS2.Second == ICK_Floating_Integral && 3629226633Sdim S.Context.getTypeSize(SCS1.getFromType()) == 3630226633Sdim S.Context.getTypeSize(SCS1.getToType(2))) 3631226633Sdim return ImplicitConversionSequence::Better; 3632226633Sdim 3633193326Sed return ImplicitConversionSequence::Indistinguishable; 3634193326Sed} 3635193326Sed 3636193326Sed/// CompareQualificationConversions - Compares two standard conversion 3637193326Sed/// sequences to determine whether they can be ranked based on their 3638198092Srdivacky/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3639198092SrdivackyImplicitConversionSequence::CompareKind 3640212904SdimCompareQualificationConversions(Sema &S, 3641212904Sdim const StandardConversionSequence& SCS1, 3642212904Sdim const StandardConversionSequence& SCS2) { 3643193326Sed // C++ 13.3.3.2p3: 3644193326Sed // -- S1 and S2 differ only in their qualification conversion and 3645193326Sed // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3646193326Sed // cv-qualification signature of type T1 is a proper subset of 3647193326Sed // the cv-qualification signature of type T2, and S1 is not the 3648193326Sed // deprecated string literal array-to-pointer conversion (4.2). 3649193326Sed if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3650193326Sed SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3651193326Sed return ImplicitConversionSequence::Indistinguishable; 3652193326Sed 3653193326Sed // FIXME: the example in the standard doesn't use a qualification 3654193326Sed // conversion (!) 3655203955Srdivacky QualType T1 = SCS1.getToType(2); 3656203955Srdivacky QualType T2 = SCS2.getToType(2); 3657212904Sdim T1 = S.Context.getCanonicalType(T1); 3658212904Sdim T2 = S.Context.getCanonicalType(T2); 3659201361Srdivacky Qualifiers T1Quals, T2Quals; 3660212904Sdim QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3661212904Sdim QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3662193326Sed 3663193326Sed // If the types are the same, we won't learn anything by unwrapped 3664193326Sed // them. 3665201361Srdivacky if (UnqualT1 == UnqualT2) 3666193326Sed return ImplicitConversionSequence::Indistinguishable; 3667193326Sed 3668201361Srdivacky // If the type is an array type, promote the element qualifiers to the type 3669201361Srdivacky // for comparison. 3670201361Srdivacky if (isa<ArrayType>(T1) && T1Quals) 3671212904Sdim T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3672201361Srdivacky if (isa<ArrayType>(T2) && T2Quals) 3673212904Sdim T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3674201361Srdivacky 3675198092Srdivacky ImplicitConversionSequence::CompareKind Result 3676193326Sed = ImplicitConversionSequence::Indistinguishable; 3677224145Sdim 3678224145Sdim // Objective-C++ ARC: 3679224145Sdim // Prefer qualification conversions not involving a change in lifetime 3680224145Sdim // to qualification conversions that do not change lifetime. 3681224145Sdim if (SCS1.QualificationIncludesObjCLifetime != 3682224145Sdim SCS2.QualificationIncludesObjCLifetime) { 3683224145Sdim Result = SCS1.QualificationIncludesObjCLifetime 3684224145Sdim ? ImplicitConversionSequence::Worse 3685224145Sdim : ImplicitConversionSequence::Better; 3686224145Sdim } 3687224145Sdim 3688212904Sdim while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3689193326Sed // Within each iteration of the loop, we check the qualifiers to 3690193326Sed // determine if this still looks like a qualification 3691193326Sed // conversion. Then, if all is well, we unwrap one more level of 3692193326Sed // pointers or pointers-to-members and do it all again 3693193326Sed // until there are no more pointers or pointers-to-members left 3694193326Sed // to unwrap. This essentially mimics what 3695193326Sed // IsQualificationConversion does, but here we're checking for a 3696193326Sed // strict subset of qualifiers. 3697193326Sed if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3698193326Sed // The qualifiers are the same, so this doesn't tell us anything 3699193326Sed // about how the sequences rank. 3700193326Sed ; 3701193326Sed else if (T2.isMoreQualifiedThan(T1)) { 3702193326Sed // T1 has fewer qualifiers, so it could be the better sequence. 3703193326Sed if (Result == ImplicitConversionSequence::Worse) 3704193326Sed // Neither has qualifiers that are a subset of the other's 3705193326Sed // qualifiers. 3706193326Sed return ImplicitConversionSequence::Indistinguishable; 3707198092Srdivacky 3708193326Sed Result = ImplicitConversionSequence::Better; 3709193326Sed } else if (T1.isMoreQualifiedThan(T2)) { 3710193326Sed // T2 has fewer qualifiers, so it could be the better sequence. 3711193326Sed if (Result == ImplicitConversionSequence::Better) 3712193326Sed // Neither has qualifiers that are a subset of the other's 3713193326Sed // qualifiers. 3714193326Sed return ImplicitConversionSequence::Indistinguishable; 3715198092Srdivacky 3716193326Sed Result = ImplicitConversionSequence::Worse; 3717193326Sed } else { 3718193326Sed // Qualifiers are disjoint. 3719193326Sed return ImplicitConversionSequence::Indistinguishable; 3720193326Sed } 3721193326Sed 3722193326Sed // If the types after this point are equivalent, we're done. 3723212904Sdim if (S.Context.hasSameUnqualifiedType(T1, T2)) 3724193326Sed break; 3725193326Sed } 3726193326Sed 3727193326Sed // Check that the winning standard conversion sequence isn't using 3728193326Sed // the deprecated string literal array to pointer conversion. 3729193326Sed switch (Result) { 3730193326Sed case ImplicitConversionSequence::Better: 3731204643Srdivacky if (SCS1.DeprecatedStringLiteralToCharPtr) 3732193326Sed Result = ImplicitConversionSequence::Indistinguishable; 3733193326Sed break; 3734193326Sed 3735193326Sed case ImplicitConversionSequence::Indistinguishable: 3736193326Sed break; 3737193326Sed 3738193326Sed case ImplicitConversionSequence::Worse: 3739204643Srdivacky if (SCS2.DeprecatedStringLiteralToCharPtr) 3740193326Sed Result = ImplicitConversionSequence::Indistinguishable; 3741193326Sed break; 3742193326Sed } 3743193326Sed 3744193326Sed return Result; 3745193326Sed} 3746193326Sed 3747193326Sed/// CompareDerivedToBaseConversions - Compares two standard conversion 3748193326Sed/// sequences to determine whether they can be ranked based on their 3749193326Sed/// various kinds of derived-to-base conversions (C++ 3750193326Sed/// [over.ics.rank]p4b3). As part of these checks, we also look at 3751193326Sed/// conversions between Objective-C interface types. 3752193326SedImplicitConversionSequence::CompareKind 3753212904SdimCompareDerivedToBaseConversions(Sema &S, 3754212904Sdim const StandardConversionSequence& SCS1, 3755212904Sdim const StandardConversionSequence& SCS2) { 3756202379Srdivacky QualType FromType1 = SCS1.getFromType(); 3757203955Srdivacky QualType ToType1 = SCS1.getToType(1); 3758202379Srdivacky QualType FromType2 = SCS2.getFromType(); 3759203955Srdivacky QualType ToType2 = SCS2.getToType(1); 3760193326Sed 3761193326Sed // Adjust the types we're converting from via the array-to-pointer 3762193326Sed // conversion, if we need to. 3763193326Sed if (SCS1.First == ICK_Array_To_Pointer) 3764212904Sdim FromType1 = S.Context.getArrayDecayedType(FromType1); 3765193326Sed if (SCS2.First == ICK_Array_To_Pointer) 3766212904Sdim FromType2 = S.Context.getArrayDecayedType(FromType2); 3767193326Sed 3768193326Sed // Canonicalize all of the types. 3769212904Sdim FromType1 = S.Context.getCanonicalType(FromType1); 3770212904Sdim ToType1 = S.Context.getCanonicalType(ToType1); 3771212904Sdim FromType2 = S.Context.getCanonicalType(FromType2); 3772212904Sdim ToType2 = S.Context.getCanonicalType(ToType2); 3773193326Sed 3774193326Sed // C++ [over.ics.rank]p4b3: 3775193326Sed // 3776193326Sed // If class B is derived directly or indirectly from class A and 3777193326Sed // class C is derived directly or indirectly from B, 3778193326Sed // 3779193326Sed // Compare based on pointer conversions. 3780198092Srdivacky if (SCS1.Second == ICK_Pointer_Conversion && 3781193326Sed SCS2.Second == ICK_Pointer_Conversion && 3782193326Sed /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3783193326Sed FromType1->isPointerType() && FromType2->isPointerType() && 3784193326Sed ToType1->isPointerType() && ToType2->isPointerType()) { 3785198092Srdivacky QualType FromPointee1 3786198092Srdivacky = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3787198092Srdivacky QualType ToPointee1 3788198092Srdivacky = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3789193326Sed QualType FromPointee2 3790198092Srdivacky = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3791193326Sed QualType ToPointee2 3792198092Srdivacky = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3793193326Sed 3794193326Sed // -- conversion of C* to B* is better than conversion of C* to A*, 3795193326Sed if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3796212904Sdim if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3797193326Sed return ImplicitConversionSequence::Better; 3798212904Sdim else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3799193326Sed return ImplicitConversionSequence::Worse; 3800193326Sed } 3801193326Sed 3802193326Sed // -- conversion of B* to A* is better than conversion of C* to A*, 3803193326Sed if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3804212904Sdim if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3805193326Sed return ImplicitConversionSequence::Better; 3806212904Sdim else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3807193326Sed return ImplicitConversionSequence::Worse; 3808218893Sdim } 3809218893Sdim } else if (SCS1.Second == ICK_Pointer_Conversion && 3810218893Sdim SCS2.Second == ICK_Pointer_Conversion) { 3811218893Sdim const ObjCObjectPointerType *FromPtr1 3812218893Sdim = FromType1->getAs<ObjCObjectPointerType>(); 3813218893Sdim const ObjCObjectPointerType *FromPtr2 3814218893Sdim = FromType2->getAs<ObjCObjectPointerType>(); 3815218893Sdim const ObjCObjectPointerType *ToPtr1 3816218893Sdim = ToType1->getAs<ObjCObjectPointerType>(); 3817218893Sdim const ObjCObjectPointerType *ToPtr2 3818218893Sdim = ToType2->getAs<ObjCObjectPointerType>(); 3819218893Sdim 3820218893Sdim if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3821218893Sdim // Apply the same conversion ranking rules for Objective-C pointer types 3822218893Sdim // that we do for C++ pointers to class types. However, we employ the 3823218893Sdim // Objective-C pseudo-subtyping relationship used for assignment of 3824218893Sdim // Objective-C pointer types. 3825218893Sdim bool FromAssignLeft 3826218893Sdim = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3827218893Sdim bool FromAssignRight 3828218893Sdim = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3829218893Sdim bool ToAssignLeft 3830218893Sdim = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3831218893Sdim bool ToAssignRight 3832218893Sdim = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3833218893Sdim 3834218893Sdim // A conversion to an a non-id object pointer type or qualified 'id' 3835218893Sdim // type is better than a conversion to 'id'. 3836218893Sdim if (ToPtr1->isObjCIdType() && 3837218893Sdim (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3838218893Sdim return ImplicitConversionSequence::Worse; 3839218893Sdim if (ToPtr2->isObjCIdType() && 3840218893Sdim (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3841218893Sdim return ImplicitConversionSequence::Better; 3842218893Sdim 3843218893Sdim // A conversion to a non-id object pointer type is better than a 3844218893Sdim // conversion to a qualified 'id' type 3845218893Sdim if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3846218893Sdim return ImplicitConversionSequence::Worse; 3847218893Sdim if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3848218893Sdim return ImplicitConversionSequence::Better; 3849218893Sdim 3850218893Sdim // A conversion to an a non-Class object pointer type or qualified 'Class' 3851218893Sdim // type is better than a conversion to 'Class'. 3852218893Sdim if (ToPtr1->isObjCClassType() && 3853218893Sdim (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3854218893Sdim return ImplicitConversionSequence::Worse; 3855218893Sdim if (ToPtr2->isObjCClassType() && 3856218893Sdim (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3857218893Sdim return ImplicitConversionSequence::Better; 3858218893Sdim 3859218893Sdim // A conversion to a non-Class object pointer type is better than a 3860218893Sdim // conversion to a qualified 'Class' type. 3861218893Sdim if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3862218893Sdim return ImplicitConversionSequence::Worse; 3863218893Sdim if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3864218893Sdim return ImplicitConversionSequence::Better; 3865198092Srdivacky 3866218893Sdim // -- "conversion of C* to B* is better than conversion of C* to A*," 3867218893Sdim if (S.Context.hasSameType(FromType1, FromType2) && 3868218893Sdim !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3869218893Sdim (ToAssignLeft != ToAssignRight)) 3870218893Sdim return ToAssignLeft? ImplicitConversionSequence::Worse 3871218893Sdim : ImplicitConversionSequence::Better; 3872218893Sdim 3873218893Sdim // -- "conversion of B* to A* is better than conversion of C* to A*," 3874218893Sdim if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3875218893Sdim (FromAssignLeft != FromAssignRight)) 3876218893Sdim return FromAssignLeft? ImplicitConversionSequence::Better 3877218893Sdim : ImplicitConversionSequence::Worse; 3878193326Sed } 3879193326Sed } 3880218893Sdim 3881198398Srdivacky // Ranking of member-pointer types. 3882198398Srdivacky if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3883198398Srdivacky FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3884198398Srdivacky ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3885218893Sdim const MemberPointerType * FromMemPointer1 = 3886198398Srdivacky FromType1->getAs<MemberPointerType>(); 3887218893Sdim const MemberPointerType * ToMemPointer1 = 3888198398Srdivacky ToType1->getAs<MemberPointerType>(); 3889218893Sdim const MemberPointerType * FromMemPointer2 = 3890198398Srdivacky FromType2->getAs<MemberPointerType>(); 3891218893Sdim const MemberPointerType * ToMemPointer2 = 3892198398Srdivacky ToType2->getAs<MemberPointerType>(); 3893198398Srdivacky const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3894198398Srdivacky const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3895198398Srdivacky const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3896198398Srdivacky const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3897198398Srdivacky QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3898198398Srdivacky QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3899198398Srdivacky QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3900198398Srdivacky QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3901198398Srdivacky // conversion of A::* to B::* is better than conversion of A::* to C::*, 3902198398Srdivacky if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3903212904Sdim if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3904198398Srdivacky return ImplicitConversionSequence::Worse; 3905212904Sdim else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3906198398Srdivacky return ImplicitConversionSequence::Better; 3907198398Srdivacky } 3908198398Srdivacky // conversion of B::* to C::* is better than conversion of A::* to C::* 3909198398Srdivacky if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3910212904Sdim if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3911198398Srdivacky return ImplicitConversionSequence::Better; 3912212904Sdim else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3913198398Srdivacky return ImplicitConversionSequence::Worse; 3914198398Srdivacky } 3915198398Srdivacky } 3916218893Sdim 3917207619Srdivacky if (SCS1.Second == ICK_Derived_To_Base) { 3918193326Sed // -- conversion of C to B is better than conversion of C to A, 3919204643Srdivacky // -- binding of an expression of type C to a reference of type 3920204643Srdivacky // B& is better than binding an expression of type C to a 3921204643Srdivacky // reference of type A&, 3922212904Sdim if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3923212904Sdim !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3924212904Sdim if (S.IsDerivedFrom(ToType1, ToType2)) 3925193326Sed return ImplicitConversionSequence::Better; 3926212904Sdim else if (S.IsDerivedFrom(ToType2, ToType1)) 3927193326Sed return ImplicitConversionSequence::Worse; 3928193326Sed } 3929193326Sed 3930193326Sed // -- conversion of B to A is better than conversion of C to A. 3931204643Srdivacky // -- binding of an expression of type B to a reference of type 3932204643Srdivacky // A& is better than binding an expression of type C to a 3933204643Srdivacky // reference of type A&, 3934212904Sdim if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3935212904Sdim S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3936212904Sdim if (S.IsDerivedFrom(FromType2, FromType1)) 3937193326Sed return ImplicitConversionSequence::Better; 3938212904Sdim else if (S.IsDerivedFrom(FromType1, FromType2)) 3939193326Sed return ImplicitConversionSequence::Worse; 3940193326Sed } 3941193326Sed } 3942193326Sed 3943193326Sed return ImplicitConversionSequence::Indistinguishable; 3944193326Sed} 3945193326Sed 3946249423Sdim/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3947249423Sdim/// C++ class. 3948249423Sdimstatic bool isTypeValid(QualType T) { 3949249423Sdim if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3950249423Sdim return !Record->isInvalidDecl(); 3951249423Sdim 3952249423Sdim return true; 3953249423Sdim} 3954249423Sdim 3955207619Srdivacky/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3956207619Srdivacky/// determine whether they are reference-related, 3957207619Srdivacky/// reference-compatible, reference-compatible with added 3958207619Srdivacky/// qualification, or incompatible, for use in C++ initialization by 3959207619Srdivacky/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3960207619Srdivacky/// type, and the first type (T1) is the pointee type of the reference 3961207619Srdivacky/// type being initialized. 3962207619SrdivackySema::ReferenceCompareResult 3963207619SrdivackySema::CompareReferenceRelationship(SourceLocation Loc, 3964207619Srdivacky QualType OrigT1, QualType OrigT2, 3965212904Sdim bool &DerivedToBase, 3966224145Sdim bool &ObjCConversion, 3967224145Sdim bool &ObjCLifetimeConversion) { 3968207619Srdivacky assert(!OrigT1->isReferenceType() && 3969207619Srdivacky "T1 must be the pointee type of the reference type"); 3970207619Srdivacky assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3971207619Srdivacky 3972207619Srdivacky QualType T1 = Context.getCanonicalType(OrigT1); 3973207619Srdivacky QualType T2 = Context.getCanonicalType(OrigT2); 3974207619Srdivacky Qualifiers T1Quals, T2Quals; 3975207619Srdivacky QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3976207619Srdivacky QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3977207619Srdivacky 3978207619Srdivacky // C++ [dcl.init.ref]p4: 3979207619Srdivacky // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3980207619Srdivacky // reference-related to "cv2 T2" if T1 is the same type as T2, or 3981207619Srdivacky // T1 is a base class of T2. 3982212904Sdim DerivedToBase = false; 3983212904Sdim ObjCConversion = false; 3984224145Sdim ObjCLifetimeConversion = false; 3985212904Sdim if (UnqualT1 == UnqualT2) { 3986212904Sdim // Nothing to do. 3987239462Sdim } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3988249423Sdim isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3989249423Sdim IsDerivedFrom(UnqualT2, UnqualT1)) 3990207619Srdivacky DerivedToBase = true; 3991212904Sdim else if (UnqualT1->isObjCObjectOrInterfaceType() && 3992212904Sdim UnqualT2->isObjCObjectOrInterfaceType() && 3993212904Sdim Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3994212904Sdim ObjCConversion = true; 3995207619Srdivacky else 3996207619Srdivacky return Ref_Incompatible; 3997207619Srdivacky 3998207619Srdivacky // At this point, we know that T1 and T2 are reference-related (at 3999207619Srdivacky // least). 4000207619Srdivacky 4001207619Srdivacky // If the type is an array type, promote the element qualifiers to the type 4002207619Srdivacky // for comparison. 4003207619Srdivacky if (isa<ArrayType>(T1) && T1Quals) 4004207619Srdivacky T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4005207619Srdivacky if (isa<ArrayType>(T2) && T2Quals) 4006207619Srdivacky T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4007207619Srdivacky 4008207619Srdivacky // C++ [dcl.init.ref]p4: 4009207619Srdivacky // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4010207619Srdivacky // reference-related to T2 and cv1 is the same cv-qualification 4011207619Srdivacky // as, or greater cv-qualification than, cv2. For purposes of 4012207619Srdivacky // overload resolution, cases for which cv1 is greater 4013207619Srdivacky // cv-qualification than cv2 are identified as 4014207619Srdivacky // reference-compatible with added qualification (see 13.3.3.2). 4015221345Sdim // 4016221345Sdim // Note that we also require equivalence of Objective-C GC and address-space 4017221345Sdim // qualifiers when performing these computations, so that e.g., an int in 4018221345Sdim // address space 1 is not reference-compatible with an int in address 4019221345Sdim // space 2. 4020224145Sdim if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4021224145Sdim T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4022224145Sdim T1Quals.removeObjCLifetime(); 4023224145Sdim T2Quals.removeObjCLifetime(); 4024224145Sdim ObjCLifetimeConversion = true; 4025224145Sdim } 4026224145Sdim 4027221345Sdim if (T1Quals == T2Quals) 4028207619Srdivacky return Ref_Compatible; 4029224145Sdim else if (T1Quals.compatiblyIncludes(T2Quals)) 4030207619Srdivacky return Ref_Compatible_With_Added_Qualification; 4031207619Srdivacky else 4032207619Srdivacky return Ref_Related; 4033207619Srdivacky} 4034207619Srdivacky 4035212904Sdim/// \brief Look for a user-defined conversion to an value reference-compatible 4036210299Sed/// with DeclType. Return true if something definite is found. 4037210299Sedstatic bool 4038212904SdimFindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4039212904Sdim QualType DeclType, SourceLocation DeclLoc, 4040212904Sdim Expr *Init, QualType T2, bool AllowRvalues, 4041212904Sdim bool AllowExplicit) { 4042210299Sed assert(T2->isRecordType() && "Can only find conversions of record types."); 4043210299Sed CXXRecordDecl *T2RecordDecl 4044210299Sed = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4045210299Sed 4046210299Sed OverloadCandidateSet CandidateSet(DeclLoc); 4047249423Sdim std::pair<CXXRecordDecl::conversion_iterator, 4048249423Sdim CXXRecordDecl::conversion_iterator> 4049249423Sdim Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4050249423Sdim for (CXXRecordDecl::conversion_iterator 4051249423Sdim I = Conversions.first, E = Conversions.second; I != E; ++I) { 4052210299Sed NamedDecl *D = *I; 4053210299Sed CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4054210299Sed if (isa<UsingShadowDecl>(D)) 4055210299Sed D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4056210299Sed 4057210299Sed FunctionTemplateDecl *ConvTemplate 4058210299Sed = dyn_cast<FunctionTemplateDecl>(D); 4059210299Sed CXXConversionDecl *Conv; 4060210299Sed if (ConvTemplate) 4061210299Sed Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4062210299Sed else 4063210299Sed Conv = cast<CXXConversionDecl>(D); 4064210299Sed 4065218893Sdim // If this is an explicit conversion, and we're not allowed to consider 4066212904Sdim // explicit conversions, skip it. 4067212904Sdim if (!AllowExplicit && Conv->isExplicit()) 4068212904Sdim continue; 4069218893Sdim 4070212904Sdim if (AllowRvalues) { 4071212904Sdim bool DerivedToBase = false; 4072212904Sdim bool ObjCConversion = false; 4073224145Sdim bool ObjCLifetimeConversion = false; 4074226633Sdim 4075226633Sdim // If we are initializing an rvalue reference, don't permit conversion 4076226633Sdim // functions that return lvalues. 4077226633Sdim if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4078226633Sdim const ReferenceType *RefType 4079226633Sdim = Conv->getConversionType()->getAs<LValueReferenceType>(); 4080226633Sdim if (RefType && !RefType->getPointeeType()->isFunctionType()) 4081226633Sdim continue; 4082226633Sdim } 4083226633Sdim 4084212904Sdim if (!ConvTemplate && 4085218893Sdim S.CompareReferenceRelationship( 4086218893Sdim DeclLoc, 4087218893Sdim Conv->getConversionType().getNonReferenceType() 4088218893Sdim .getUnqualifiedType(), 4089218893Sdim DeclType.getNonReferenceType().getUnqualifiedType(), 4090224145Sdim DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4091218893Sdim Sema::Ref_Incompatible) 4092212904Sdim continue; 4093212904Sdim } else { 4094212904Sdim // If the conversion function doesn't return a reference type, 4095212904Sdim // it can't be considered for this conversion. An rvalue reference 4096212904Sdim // is only acceptable if its referencee is a function type. 4097212904Sdim 4098212904Sdim const ReferenceType *RefType = 4099212904Sdim Conv->getConversionType()->getAs<ReferenceType>(); 4100212904Sdim if (!RefType || 4101212904Sdim (!RefType->isLValueReferenceType() && 4102212904Sdim !RefType->getPointeeType()->isFunctionType())) 4103212904Sdim continue; 4104210299Sed } 4105218893Sdim 4106212904Sdim if (ConvTemplate) 4107212904Sdim S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4108218893Sdim Init, DeclType, CandidateSet); 4109212904Sdim else 4110212904Sdim S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4111218893Sdim DeclType, CandidateSet); 4112210299Sed } 4113210299Sed 4114226633Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 4115226633Sdim 4116210299Sed OverloadCandidateSet::iterator Best; 4117218893Sdim switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4118210299Sed case OR_Success: 4119210299Sed // C++ [over.ics.ref]p1: 4120210299Sed // 4121210299Sed // [...] If the parameter binds directly to the result of 4122210299Sed // applying a conversion function to the argument 4123210299Sed // expression, the implicit conversion sequence is a 4124210299Sed // user-defined conversion sequence (13.3.3.1.2), with the 4125210299Sed // second standard conversion sequence either an identity 4126210299Sed // conversion or, if the conversion function returns an 4127210299Sed // entity of a type that is a derived class of the parameter 4128210299Sed // type, a derived-to-base Conversion. 4129210299Sed if (!Best->FinalConversion.DirectBinding) 4130210299Sed return false; 4131210299Sed 4132210299Sed ICS.setUserDefined(); 4133210299Sed ICS.UserDefined.Before = Best->Conversions[0].Standard; 4134210299Sed ICS.UserDefined.After = Best->FinalConversion; 4135226633Sdim ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4136210299Sed ICS.UserDefined.ConversionFunction = Best->Function; 4137226633Sdim ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4138210299Sed ICS.UserDefined.EllipsisConversion = false; 4139210299Sed assert(ICS.UserDefined.After.ReferenceBinding && 4140210299Sed ICS.UserDefined.After.DirectBinding && 4141210299Sed "Expected a direct reference binding!"); 4142210299Sed return true; 4143210299Sed 4144210299Sed case OR_Ambiguous: 4145210299Sed ICS.setAmbiguous(); 4146210299Sed for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4147210299Sed Cand != CandidateSet.end(); ++Cand) 4148210299Sed if (Cand->Viable) 4149210299Sed ICS.Ambiguous.addConversion(Cand->Function); 4150210299Sed return true; 4151210299Sed 4152210299Sed case OR_No_Viable_Function: 4153210299Sed case OR_Deleted: 4154210299Sed // There was no suitable conversion, or we found a deleted 4155210299Sed // conversion; continue with other checks. 4156210299Sed return false; 4157210299Sed } 4158218893Sdim 4159234353Sdim llvm_unreachable("Invalid OverloadResult!"); 4160210299Sed} 4161210299Sed 4162207619Srdivacky/// \brief Compute an implicit conversion sequence for reference 4163207619Srdivacky/// initialization. 4164207619Srdivackystatic ImplicitConversionSequence 4165234353SdimTryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4166207619Srdivacky SourceLocation DeclLoc, 4167207619Srdivacky bool SuppressUserConversions, 4168207619Srdivacky bool AllowExplicit) { 4169207619Srdivacky assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4170207619Srdivacky 4171207619Srdivacky // Most paths end in a failed conversion. 4172207619Srdivacky ImplicitConversionSequence ICS; 4173207619Srdivacky ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4174207619Srdivacky 4175207619Srdivacky QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4176207619Srdivacky QualType T2 = Init->getType(); 4177207619Srdivacky 4178207619Srdivacky // If the initializer is the address of an overloaded function, try 4179207619Srdivacky // to resolve the overloaded function. If all goes well, T2 is the 4180207619Srdivacky // type of the resulting function. 4181207619Srdivacky if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4182207619Srdivacky DeclAccessPair Found; 4183207619Srdivacky if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4184207619Srdivacky false, Found)) 4185207619Srdivacky T2 = Fn->getType(); 4186207619Srdivacky } 4187207619Srdivacky 4188207619Srdivacky // Compute some basic properties of the types and the initializer. 4189207619Srdivacky bool isRValRef = DeclType->isRValueReferenceType(); 4190207619Srdivacky bool DerivedToBase = false; 4191212904Sdim bool ObjCConversion = false; 4192224145Sdim bool ObjCLifetimeConversion = false; 4193210299Sed Expr::Classification InitCategory = Init->Classify(S.Context); 4194207619Srdivacky Sema::ReferenceCompareResult RefRelationship 4195212904Sdim = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4196224145Sdim ObjCConversion, ObjCLifetimeConversion); 4197207619Srdivacky 4198207619Srdivacky 4199210299Sed // C++0x [dcl.init.ref]p5: 4200207619Srdivacky // A reference to type "cv1 T1" is initialized by an expression 4201207619Srdivacky // of type "cv2 T2" as follows: 4202207619Srdivacky 4203210299Sed // -- If reference is an lvalue reference and the initializer expression 4204218893Sdim if (!isRValRef) { 4205210299Sed // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4206210299Sed // reference-compatible with "cv2 T2," or 4207210299Sed // 4208210299Sed // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4209210299Sed if (InitCategory.isLValue() && 4210210299Sed RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4211207619Srdivacky // C++ [over.ics.ref]p1: 4212210299Sed // When a parameter of reference type binds directly (8.5.3) 4213210299Sed // to an argument expression, the implicit conversion sequence 4214210299Sed // is the identity conversion, unless the argument expression 4215210299Sed // has a type that is a derived class of the parameter type, 4216210299Sed // in which case the implicit conversion sequence is a 4217210299Sed // derived-to-base Conversion (13.3.3.1). 4218210299Sed ICS.setStandard(); 4219210299Sed ICS.Standard.First = ICK_Identity; 4220212904Sdim ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4221212904Sdim : ObjCConversion? ICK_Compatible_Conversion 4222212904Sdim : ICK_Identity; 4223210299Sed ICS.Standard.Third = ICK_Identity; 4224210299Sed ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4225210299Sed ICS.Standard.setToType(0, T2); 4226210299Sed ICS.Standard.setToType(1, T1); 4227210299Sed ICS.Standard.setToType(2, T1); 4228210299Sed ICS.Standard.ReferenceBinding = true; 4229210299Sed ICS.Standard.DirectBinding = true; 4230218893Sdim ICS.Standard.IsLvalueReference = !isRValRef; 4231218893Sdim ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4232218893Sdim ICS.Standard.BindsToRvalue = false; 4233218893Sdim ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4234224145Sdim ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4235210299Sed ICS.Standard.CopyConstructor = 0; 4236207619Srdivacky 4237210299Sed // Nothing more to do: the inaccessibility/ambiguity check for 4238210299Sed // derived-to-base conversions is suppressed when we're 4239210299Sed // computing the implicit conversion sequence (C++ 4240210299Sed // [over.best.ics]p2). 4241207619Srdivacky return ICS; 4242210299Sed } 4243207619Srdivacky 4244210299Sed // -- has a class type (i.e., T2 is a class type), where T1 is 4245210299Sed // not reference-related to T2, and can be implicitly 4246210299Sed // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4247210299Sed // is reference-compatible with "cv3 T3" 92) (this 4248210299Sed // conversion is selected by enumerating the applicable 4249210299Sed // conversion functions (13.3.1.6) and choosing the best 4250210299Sed // one through overload resolution (13.3)), 4251210299Sed if (!SuppressUserConversions && T2->isRecordType() && 4252218893Sdim !S.RequireCompleteType(DeclLoc, T2, 0) && 4253210299Sed RefRelationship == Sema::Ref_Incompatible) { 4254212904Sdim if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4255212904Sdim Init, T2, /*AllowRvalues=*/false, 4256212904Sdim AllowExplicit)) 4257210299Sed return ICS; 4258207619Srdivacky } 4259207619Srdivacky } 4260207619Srdivacky 4261210299Sed // -- Otherwise, the reference shall be an lvalue reference to a 4262210299Sed // non-volatile const type (i.e., cv1 shall be const), or the reference 4263218893Sdim // shall be an rvalue reference. 4264218893Sdim // 4265207619Srdivacky // We actually handle one oddity of C++ [over.ics.ref] at this 4266207619Srdivacky // point, which is that, due to p2 (which short-circuits reference 4267207619Srdivacky // binding by only attempting a simple conversion for non-direct 4268207619Srdivacky // bindings) and p3's strange wording, we allow a const volatile 4269207619Srdivacky // reference to bind to an rvalue. Hence the check for the presence 4270207619Srdivacky // of "const" rather than checking for "const" being the only 4271207619Srdivacky // qualifier. 4272210299Sed // This is also the point where rvalue references and lvalue inits no longer 4273210299Sed // go together. 4274239462Sdim if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4275207619Srdivacky return ICS; 4276207619Srdivacky 4277218893Sdim // -- If the initializer expression 4278218893Sdim // 4279218893Sdim // -- is an xvalue, class prvalue, array prvalue or function 4280224145Sdim // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4281218893Sdim if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4282218893Sdim (InitCategory.isXValue() || 4283218893Sdim (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4284218893Sdim (InitCategory.isLValue() && T2->isFunctionType()))) { 4285218893Sdim ICS.setStandard(); 4286218893Sdim ICS.Standard.First = ICK_Identity; 4287218893Sdim ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4288218893Sdim : ObjCConversion? ICK_Compatible_Conversion 4289218893Sdim : ICK_Identity; 4290218893Sdim ICS.Standard.Third = ICK_Identity; 4291218893Sdim ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4292218893Sdim ICS.Standard.setToType(0, T2); 4293218893Sdim ICS.Standard.setToType(1, T1); 4294218893Sdim ICS.Standard.setToType(2, T1); 4295218893Sdim ICS.Standard.ReferenceBinding = true; 4296218893Sdim // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4297218893Sdim // binding unless we're binding to a class prvalue. 4298218893Sdim // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4299218893Sdim // allow the use of rvalue references in C++98/03 for the benefit of 4300218893Sdim // standard library implementors; therefore, we need the xvalue check here. 4301218893Sdim ICS.Standard.DirectBinding = 4302249423Sdim S.getLangOpts().CPlusPlus11 || 4303218893Sdim (InitCategory.isPRValue() && !T2->isRecordType()); 4304218893Sdim ICS.Standard.IsLvalueReference = !isRValRef; 4305218893Sdim ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4306218893Sdim ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4307218893Sdim ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4308224145Sdim ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4309218893Sdim ICS.Standard.CopyConstructor = 0; 4310210299Sed return ICS; 4311218893Sdim } 4312210299Sed 4313218893Sdim // -- has a class type (i.e., T2 is a class type), where T1 is not 4314218893Sdim // reference-related to T2, and can be implicitly converted to 4315218893Sdim // an xvalue, class prvalue, or function lvalue of type 4316218893Sdim // "cv3 T3", where "cv1 T1" is reference-compatible with 4317218893Sdim // "cv3 T3", 4318207619Srdivacky // 4319218893Sdim // then the reference is bound to the value of the initializer 4320218893Sdim // expression in the first case and to the result of the conversion 4321218893Sdim // in the second case (or, in either case, to an appropriate base 4322218893Sdim // class subobject). 4323218893Sdim if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4324218893Sdim T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4325218893Sdim FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4326218893Sdim Init, T2, /*AllowRvalues=*/true, 4327218893Sdim AllowExplicit)) { 4328218893Sdim // In the second case, if the reference is an rvalue reference 4329218893Sdim // and the second standard conversion sequence of the 4330218893Sdim // user-defined conversion sequence includes an lvalue-to-rvalue 4331218893Sdim // conversion, the program is ill-formed. 4332218893Sdim if (ICS.isUserDefined() && isRValRef && 4333218893Sdim ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4334218893Sdim ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4335218893Sdim 4336218893Sdim return ICS; 4337207619Srdivacky } 4338218893Sdim 4339207619Srdivacky // -- Otherwise, a temporary of type "cv1 T1" is created and 4340207619Srdivacky // initialized from the initializer expression using the 4341207619Srdivacky // rules for a non-reference copy initialization (8.5). The 4342207619Srdivacky // reference is then bound to the temporary. If T1 is 4343207619Srdivacky // reference-related to T2, cv1 must be the same 4344207619Srdivacky // cv-qualification as, or greater cv-qualification than, 4345207619Srdivacky // cv2; otherwise, the program is ill-formed. 4346207619Srdivacky if (RefRelationship == Sema::Ref_Related) { 4347207619Srdivacky // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4348207619Srdivacky // we would be reference-compatible or reference-compatible with 4349207619Srdivacky // added qualification. But that wasn't the case, so the reference 4350207619Srdivacky // initialization fails. 4351224145Sdim // 4352224145Sdim // Note that we only want to check address spaces and cvr-qualifiers here. 4353224145Sdim // ObjC GC and lifetime qualifiers aren't important. 4354224145Sdim Qualifiers T1Quals = T1.getQualifiers(); 4355224145Sdim Qualifiers T2Quals = T2.getQualifiers(); 4356224145Sdim T1Quals.removeObjCGCAttr(); 4357224145Sdim T1Quals.removeObjCLifetime(); 4358224145Sdim T2Quals.removeObjCGCAttr(); 4359224145Sdim T2Quals.removeObjCLifetime(); 4360224145Sdim if (!T1Quals.compatiblyIncludes(T2Quals)) 4361224145Sdim return ICS; 4362207619Srdivacky } 4363207619Srdivacky 4364207619Srdivacky // If at least one of the types is a class type, the types are not 4365207619Srdivacky // related, and we aren't allowed any user conversions, the 4366207619Srdivacky // reference binding fails. This case is important for breaking 4367207619Srdivacky // recursion, since TryImplicitConversion below will attempt to 4368207619Srdivacky // create a temporary through the use of a copy constructor. 4369207619Srdivacky if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4370207619Srdivacky (T1->isRecordType() || T2->isRecordType())) 4371207619Srdivacky return ICS; 4372207619Srdivacky 4373218893Sdim // If T1 is reference-related to T2 and the reference is an rvalue 4374218893Sdim // reference, the initializer expression shall not be an lvalue. 4375218893Sdim if (RefRelationship >= Sema::Ref_Related && 4376218893Sdim isRValRef && Init->Classify(S.Context).isLValue()) 4377218893Sdim return ICS; 4378218893Sdim 4379207619Srdivacky // C++ [over.ics.ref]p2: 4380207619Srdivacky // When a parameter of reference type is not bound directly to 4381207619Srdivacky // an argument expression, the conversion sequence is the one 4382207619Srdivacky // required to convert the argument expression to the 4383207619Srdivacky // underlying type of the reference according to 4384207619Srdivacky // 13.3.3.1. Conceptually, this conversion sequence corresponds 4385207619Srdivacky // to copy-initializing a temporary of the underlying type with 4386207619Srdivacky // the argument expression. Any difference in top-level 4387207619Srdivacky // cv-qualification is subsumed by the initialization itself 4388207619Srdivacky // and does not constitute a conversion. 4389212904Sdim ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4390212904Sdim /*AllowExplicit=*/false, 4391218893Sdim /*InOverloadResolution=*/false, 4392224145Sdim /*CStyle=*/false, 4393224145Sdim /*AllowObjCWritebackConversion=*/false); 4394207619Srdivacky 4395207619Srdivacky // Of course, that's still a reference binding. 4396207619Srdivacky if (ICS.isStandard()) { 4397207619Srdivacky ICS.Standard.ReferenceBinding = true; 4398218893Sdim ICS.Standard.IsLvalueReference = !isRValRef; 4399218893Sdim ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4400218893Sdim ICS.Standard.BindsToRvalue = true; 4401218893Sdim ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4402224145Sdim ICS.Standard.ObjCLifetimeConversionBinding = false; 4403207619Srdivacky } else if (ICS.isUserDefined()) { 4404226633Sdim // Don't allow rvalue references to bind to lvalues. 4405226633Sdim if (DeclType->isRValueReferenceType()) { 4406226633Sdim if (const ReferenceType *RefType 4407226633Sdim = ICS.UserDefined.ConversionFunction->getResultType() 4408226633Sdim ->getAs<LValueReferenceType>()) { 4409226633Sdim if (!RefType->getPointeeType()->isFunctionType()) { 4410226633Sdim ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4411226633Sdim DeclType); 4412226633Sdim return ICS; 4413226633Sdim } 4414226633Sdim } 4415226633Sdim } 4416226633Sdim 4417207619Srdivacky ICS.UserDefined.After.ReferenceBinding = true; 4418226633Sdim ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4419226633Sdim ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4420226633Sdim ICS.UserDefined.After.BindsToRvalue = true; 4421226633Sdim ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4422226633Sdim ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4423207619Srdivacky } 4424218893Sdim 4425207619Srdivacky return ICS; 4426207619Srdivacky} 4427207619Srdivacky 4428234353Sdimstatic ImplicitConversionSequence 4429234353SdimTryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4430234353Sdim bool SuppressUserConversions, 4431234353Sdim bool InOverloadResolution, 4432234353Sdim bool AllowObjCWritebackConversion, 4433234353Sdim bool AllowExplicit = false); 4434234353Sdim 4435234353Sdim/// TryListConversion - Try to copy-initialize a value of type ToType from the 4436234353Sdim/// initializer list From. 4437234353Sdimstatic ImplicitConversionSequence 4438234353SdimTryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4439234353Sdim bool SuppressUserConversions, 4440234353Sdim bool InOverloadResolution, 4441234353Sdim bool AllowObjCWritebackConversion) { 4442234353Sdim // C++11 [over.ics.list]p1: 4443234353Sdim // When an argument is an initializer list, it is not an expression and 4444234353Sdim // special rules apply for converting it to a parameter type. 4445234353Sdim 4446234353Sdim ImplicitConversionSequence Result; 4447234353Sdim Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4448234353Sdim Result.setListInitializationSequence(); 4449234353Sdim 4450234353Sdim // We need a complete type for what follows. Incomplete types can never be 4451234353Sdim // initialized from init lists. 4452239462Sdim if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4453234353Sdim return Result; 4454234353Sdim 4455234353Sdim // C++11 [over.ics.list]p2: 4456234353Sdim // If the parameter type is std::initializer_list<X> or "array of X" and 4457234353Sdim // all the elements can be implicitly converted to X, the implicit 4458234353Sdim // conversion sequence is the worst conversion necessary to convert an 4459234353Sdim // element of the list to X. 4460234353Sdim bool toStdInitializerList = false; 4461234353Sdim QualType X; 4462234353Sdim if (ToType->isArrayType()) 4463249423Sdim X = S.Context.getAsArrayType(ToType)->getElementType(); 4464234353Sdim else 4465234353Sdim toStdInitializerList = S.isStdInitializerList(ToType, &X); 4466234353Sdim if (!X.isNull()) { 4467234353Sdim for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4468234353Sdim Expr *Init = From->getInit(i); 4469234353Sdim ImplicitConversionSequence ICS = 4470234353Sdim TryCopyInitialization(S, Init, X, SuppressUserConversions, 4471234353Sdim InOverloadResolution, 4472234353Sdim AllowObjCWritebackConversion); 4473234353Sdim // If a single element isn't convertible, fail. 4474234353Sdim if (ICS.isBad()) { 4475234353Sdim Result = ICS; 4476234353Sdim break; 4477234353Sdim } 4478234353Sdim // Otherwise, look for the worst conversion. 4479234353Sdim if (Result.isBad() || 4480234353Sdim CompareImplicitConversionSequences(S, ICS, Result) == 4481234353Sdim ImplicitConversionSequence::Worse) 4482234353Sdim Result = ICS; 4483234353Sdim } 4484234353Sdim 4485234353Sdim // For an empty list, we won't have computed any conversion sequence. 4486234353Sdim // Introduce the identity conversion sequence. 4487234353Sdim if (From->getNumInits() == 0) { 4488234353Sdim Result.setStandard(); 4489234353Sdim Result.Standard.setAsIdentityConversion(); 4490234353Sdim Result.Standard.setFromType(ToType); 4491234353Sdim Result.Standard.setAllToTypes(ToType); 4492234353Sdim } 4493234353Sdim 4494234353Sdim Result.setListInitializationSequence(); 4495234353Sdim Result.setStdInitializerListElement(toStdInitializerList); 4496234353Sdim return Result; 4497234353Sdim } 4498234353Sdim 4499234353Sdim // C++11 [over.ics.list]p3: 4500234353Sdim // Otherwise, if the parameter is a non-aggregate class X and overload 4501234353Sdim // resolution chooses a single best constructor [...] the implicit 4502234353Sdim // conversion sequence is a user-defined conversion sequence. If multiple 4503234353Sdim // constructors are viable but none is better than the others, the 4504234353Sdim // implicit conversion sequence is a user-defined conversion sequence. 4505234353Sdim if (ToType->isRecordType() && !ToType->isAggregateType()) { 4506234353Sdim // This function can deal with initializer lists. 4507234353Sdim Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4508234353Sdim /*AllowExplicit=*/false, 4509234353Sdim InOverloadResolution, /*CStyle=*/false, 4510234353Sdim AllowObjCWritebackConversion); 4511234353Sdim Result.setListInitializationSequence(); 4512234353Sdim return Result; 4513234353Sdim } 4514234353Sdim 4515234353Sdim // C++11 [over.ics.list]p4: 4516234353Sdim // Otherwise, if the parameter has an aggregate type which can be 4517234353Sdim // initialized from the initializer list [...] the implicit conversion 4518234353Sdim // sequence is a user-defined conversion sequence. 4519234353Sdim if (ToType->isAggregateType()) { 4520234353Sdim // Type is an aggregate, argument is an init list. At this point it comes 4521234353Sdim // down to checking whether the initialization works. 4522234353Sdim // FIXME: Find out whether this parameter is consumed or not. 4523234353Sdim InitializedEntity Entity = 4524234353Sdim InitializedEntity::InitializeParameter(S.Context, ToType, 4525234353Sdim /*Consumed=*/false); 4526234353Sdim if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4527234353Sdim Result.setUserDefined(); 4528234353Sdim Result.UserDefined.Before.setAsIdentityConversion(); 4529234353Sdim // Initializer lists don't have a type. 4530234353Sdim Result.UserDefined.Before.setFromType(QualType()); 4531234353Sdim Result.UserDefined.Before.setAllToTypes(QualType()); 4532234353Sdim 4533234353Sdim Result.UserDefined.After.setAsIdentityConversion(); 4534234353Sdim Result.UserDefined.After.setFromType(ToType); 4535234353Sdim Result.UserDefined.After.setAllToTypes(ToType); 4536234353Sdim Result.UserDefined.ConversionFunction = 0; 4537234353Sdim } 4538234353Sdim return Result; 4539234353Sdim } 4540234353Sdim 4541234353Sdim // C++11 [over.ics.list]p5: 4542234353Sdim // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4543234353Sdim if (ToType->isReferenceType()) { 4544234353Sdim // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4545234353Sdim // mention initializer lists in any way. So we go by what list- 4546234353Sdim // initialization would do and try to extrapolate from that. 4547234353Sdim 4548234353Sdim QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4549234353Sdim 4550234353Sdim // If the initializer list has a single element that is reference-related 4551234353Sdim // to the parameter type, we initialize the reference from that. 4552234353Sdim if (From->getNumInits() == 1) { 4553234353Sdim Expr *Init = From->getInit(0); 4554234353Sdim 4555234353Sdim QualType T2 = Init->getType(); 4556234353Sdim 4557234353Sdim // If the initializer is the address of an overloaded function, try 4558234353Sdim // to resolve the overloaded function. If all goes well, T2 is the 4559234353Sdim // type of the resulting function. 4560234353Sdim if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4561234353Sdim DeclAccessPair Found; 4562234353Sdim if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4563234353Sdim Init, ToType, false, Found)) 4564234353Sdim T2 = Fn->getType(); 4565234353Sdim } 4566234353Sdim 4567234353Sdim // Compute some basic properties of the types and the initializer. 4568234353Sdim bool dummy1 = false; 4569234353Sdim bool dummy2 = false; 4570234353Sdim bool dummy3 = false; 4571234353Sdim Sema::ReferenceCompareResult RefRelationship 4572234353Sdim = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4573234353Sdim dummy2, dummy3); 4574234353Sdim 4575234353Sdim if (RefRelationship >= Sema::Ref_Related) 4576234353Sdim return TryReferenceInit(S, Init, ToType, 4577234353Sdim /*FIXME:*/From->getLocStart(), 4578234353Sdim SuppressUserConversions, 4579234353Sdim /*AllowExplicit=*/false); 4580234353Sdim } 4581234353Sdim 4582234353Sdim // Otherwise, we bind the reference to a temporary created from the 4583234353Sdim // initializer list. 4584234353Sdim Result = TryListConversion(S, From, T1, SuppressUserConversions, 4585234353Sdim InOverloadResolution, 4586234353Sdim AllowObjCWritebackConversion); 4587234353Sdim if (Result.isFailure()) 4588234353Sdim return Result; 4589234353Sdim assert(!Result.isEllipsis() && 4590234353Sdim "Sub-initialization cannot result in ellipsis conversion."); 4591234353Sdim 4592234353Sdim // Can we even bind to a temporary? 4593234353Sdim if (ToType->isRValueReferenceType() || 4594234353Sdim (T1.isConstQualified() && !T1.isVolatileQualified())) { 4595234353Sdim StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4596234353Sdim Result.UserDefined.After; 4597234353Sdim SCS.ReferenceBinding = true; 4598234353Sdim SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4599234353Sdim SCS.BindsToRvalue = true; 4600234353Sdim SCS.BindsToFunctionLvalue = false; 4601234353Sdim SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4602234353Sdim SCS.ObjCLifetimeConversionBinding = false; 4603234353Sdim } else 4604234353Sdim Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4605234353Sdim From, ToType); 4606234353Sdim return Result; 4607234353Sdim } 4608234353Sdim 4609234353Sdim // C++11 [over.ics.list]p6: 4610234353Sdim // Otherwise, if the parameter type is not a class: 4611234353Sdim if (!ToType->isRecordType()) { 4612234353Sdim // - if the initializer list has one element, the implicit conversion 4613234353Sdim // sequence is the one required to convert the element to the 4614234353Sdim // parameter type. 4615234353Sdim unsigned NumInits = From->getNumInits(); 4616234353Sdim if (NumInits == 1) 4617234353Sdim Result = TryCopyInitialization(S, From->getInit(0), ToType, 4618234353Sdim SuppressUserConversions, 4619234353Sdim InOverloadResolution, 4620234353Sdim AllowObjCWritebackConversion); 4621234353Sdim // - if the initializer list has no elements, the implicit conversion 4622234353Sdim // sequence is the identity conversion. 4623234353Sdim else if (NumInits == 0) { 4624234353Sdim Result.setStandard(); 4625234353Sdim Result.Standard.setAsIdentityConversion(); 4626234353Sdim Result.Standard.setFromType(ToType); 4627234353Sdim Result.Standard.setAllToTypes(ToType); 4628234353Sdim } 4629234353Sdim Result.setListInitializationSequence(); 4630234353Sdim return Result; 4631234353Sdim } 4632234353Sdim 4633234353Sdim // C++11 [over.ics.list]p7: 4634234353Sdim // In all cases other than those enumerated above, no conversion is possible 4635234353Sdim return Result; 4636234353Sdim} 4637234353Sdim 4638193326Sed/// TryCopyInitialization - Try to copy-initialize a value of type 4639193326Sed/// ToType from the expression From. Return the implicit conversion 4640193326Sed/// sequence required to pass this argument, which may be a bad 4641193326Sed/// conversion sequence (meaning that the argument cannot be passed to 4642193326Sed/// a parameter of this type). If @p SuppressUserConversions, then we 4643207619Srdivacky/// do not permit any user-defined conversion sequences. 4644207619Srdivackystatic ImplicitConversionSequence 4645207619SrdivackyTryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4646218893Sdim bool SuppressUserConversions, 4647224145Sdim bool InOverloadResolution, 4648234353Sdim bool AllowObjCWritebackConversion, 4649234353Sdim bool AllowExplicit) { 4650234353Sdim if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4651234353Sdim return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4652234353Sdim InOverloadResolution,AllowObjCWritebackConversion); 4653234353Sdim 4654207619Srdivacky if (ToType->isReferenceType()) 4655207619Srdivacky return TryReferenceInit(S, From, ToType, 4656207619Srdivacky /*FIXME:*/From->getLocStart(), 4657207619Srdivacky SuppressUserConversions, 4658234353Sdim AllowExplicit); 4659207619Srdivacky 4660212904Sdim return TryImplicitConversion(S, From, ToType, 4661212904Sdim SuppressUserConversions, 4662212904Sdim /*AllowExplicit=*/false, 4663218893Sdim InOverloadResolution, 4664224145Sdim /*CStyle=*/false, 4665224145Sdim AllowObjCWritebackConversion); 4666193326Sed} 4667193326Sed 4668226633Sdimstatic bool TryCopyInitialization(const CanQualType FromQTy, 4669226633Sdim const CanQualType ToQTy, 4670226633Sdim Sema &S, 4671226633Sdim SourceLocation Loc, 4672226633Sdim ExprValueKind FromVK) { 4673226633Sdim OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4674226633Sdim ImplicitConversionSequence ICS = 4675226633Sdim TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4676226633Sdim 4677226633Sdim return !ICS.isBad(); 4678226633Sdim} 4679226633Sdim 4680193326Sed/// TryObjectArgumentInitialization - Try to initialize the object 4681193326Sed/// parameter of the given member function (@c Method) from the 4682193326Sed/// expression @p From. 4683212904Sdimstatic ImplicitConversionSequence 4684249423SdimTryObjectArgumentInitialization(Sema &S, QualType FromType, 4685218893Sdim Expr::Classification FromClassification, 4686212904Sdim CXXMethodDecl *Method, 4687212904Sdim CXXRecordDecl *ActingContext) { 4688212904Sdim QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4689199512Srdivacky // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4690199512Srdivacky // const volatile object. 4691199512Srdivacky unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4692199512Srdivacky Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4693212904Sdim QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4694193326Sed 4695193326Sed // Set up the conversion sequence as a "bad" conversion, to allow us 4696193326Sed // to exit early. 4697193326Sed ImplicitConversionSequence ICS; 4698193326Sed 4699193326Sed // We need to have an object of class type. 4700218893Sdim if (const PointerType *PT = FromType->getAs<PointerType>()) { 4701193326Sed FromType = PT->getPointeeType(); 4702193326Sed 4703218893Sdim // When we had a pointer, it's implicitly dereferenced, so we 4704218893Sdim // better have an lvalue. 4705218893Sdim assert(FromClassification.isLValue()); 4706218893Sdim } 4707218893Sdim 4708193326Sed assert(FromType->isRecordType()); 4709193326Sed 4710218893Sdim // C++0x [over.match.funcs]p4: 4711218893Sdim // For non-static member functions, the type of the implicit object 4712218893Sdim // parameter is 4713218893Sdim // 4714218893Sdim // - "lvalue reference to cv X" for functions declared without a 4715218893Sdim // ref-qualifier or with the & ref-qualifier 4716218893Sdim // - "rvalue reference to cv X" for functions declared with the && 4717218893Sdim // ref-qualifier 4718218893Sdim // 4719218893Sdim // where X is the class of which the function is a member and cv is the 4720218893Sdim // cv-qualification on the member function declaration. 4721218893Sdim // 4722218893Sdim // However, when finding an implicit conversion sequence for the argument, we 4723218893Sdim // are not allowed to create temporaries or perform user-defined conversions 4724193326Sed // (C++ [over.match.funcs]p5). We perform a simplified version of 4725193326Sed // reference binding here, that allows class rvalues to bind to 4726193326Sed // non-constant references. 4727193326Sed 4728218893Sdim // First check the qualifiers. 4729212904Sdim QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4730218893Sdim if (ImplicitParamType.getCVRQualifiers() 4731199482Srdivacky != FromTypeCanon.getLocalCVRQualifiers() && 4732202379Srdivacky !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4733204643Srdivacky ICS.setBad(BadConversionSequence::bad_qualifiers, 4734249423Sdim FromType, ImplicitParamType); 4735193326Sed return ICS; 4736202379Srdivacky } 4737193326Sed 4738193326Sed // Check that we have either the same type or a derived type. It 4739193326Sed // affects the conversion rank. 4740212904Sdim QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4741204643Srdivacky ImplicitConversionKind SecondKind; 4742204643Srdivacky if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4743204643Srdivacky SecondKind = ICK_Identity; 4744212904Sdim } else if (S.IsDerivedFrom(FromType, ClassType)) 4745204643Srdivacky SecondKind = ICK_Derived_To_Base; 4746202379Srdivacky else { 4747204643Srdivacky ICS.setBad(BadConversionSequence::unrelated_class, 4748204643Srdivacky FromType, ImplicitParamType); 4749193326Sed return ICS; 4750202379Srdivacky } 4751193326Sed 4752218893Sdim // Check the ref-qualifier. 4753218893Sdim switch (Method->getRefQualifier()) { 4754218893Sdim case RQ_None: 4755218893Sdim // Do nothing; we don't care about lvalueness or rvalueness. 4756218893Sdim break; 4757218893Sdim 4758218893Sdim case RQ_LValue: 4759218893Sdim if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4760218893Sdim // non-const lvalue reference cannot bind to an rvalue 4761218893Sdim ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4762218893Sdim ImplicitParamType); 4763218893Sdim return ICS; 4764218893Sdim } 4765218893Sdim break; 4766218893Sdim 4767218893Sdim case RQ_RValue: 4768218893Sdim if (!FromClassification.isRValue()) { 4769218893Sdim // rvalue reference cannot bind to an lvalue 4770218893Sdim ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4771218893Sdim ImplicitParamType); 4772218893Sdim return ICS; 4773218893Sdim } 4774218893Sdim break; 4775218893Sdim } 4776218893Sdim 4777193326Sed // Success. Mark this as a reference binding. 4778202379Srdivacky ICS.setStandard(); 4779204643Srdivacky ICS.Standard.setAsIdentityConversion(); 4780204643Srdivacky ICS.Standard.Second = SecondKind; 4781202379Srdivacky ICS.Standard.setFromType(FromType); 4782203955Srdivacky ICS.Standard.setAllToTypes(ImplicitParamType); 4783193326Sed ICS.Standard.ReferenceBinding = true; 4784193326Sed ICS.Standard.DirectBinding = true; 4785218893Sdim ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4786218893Sdim ICS.Standard.BindsToFunctionLvalue = false; 4787218893Sdim ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4788218893Sdim ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4789218893Sdim = (Method->getRefQualifier() == RQ_None); 4790193326Sed return ICS; 4791193326Sed} 4792193326Sed 4793193326Sed/// PerformObjectArgumentInitialization - Perform initialization of 4794193326Sed/// the implicit object parameter for the given Method with the given 4795193326Sed/// expression. 4796221345SdimExprResult 4797221345SdimSema::PerformObjectArgumentInitialization(Expr *From, 4798218893Sdim NestedNameSpecifier *Qualifier, 4799206084Srdivacky NamedDecl *FoundDecl, 4800204793Srdivacky CXXMethodDecl *Method) { 4801193326Sed QualType FromRecordType, DestType; 4802198092Srdivacky QualType ImplicitParamRecordType = 4803198092Srdivacky Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4804198092Srdivacky 4805218893Sdim Expr::Classification FromClassification; 4806198092Srdivacky if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4807193326Sed FromRecordType = PT->getPointeeType(); 4808193326Sed DestType = Method->getThisType(Context); 4809218893Sdim FromClassification = Expr::Classification::makeSimpleLValue(); 4810193326Sed } else { 4811193326Sed FromRecordType = From->getType(); 4812193326Sed DestType = ImplicitParamRecordType; 4813218893Sdim FromClassification = From->Classify(Context); 4814193326Sed } 4815193326Sed 4816200583Srdivacky // Note that we always use the true parent context when performing 4817200583Srdivacky // the actual argument initialization. 4818198092Srdivacky ImplicitConversionSequence ICS 4819218893Sdim = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4820218893Sdim Method, Method->getParent()); 4821218893Sdim if (ICS.isBad()) { 4822218893Sdim if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4823218893Sdim Qualifiers FromQs = FromRecordType.getQualifiers(); 4824218893Sdim Qualifiers ToQs = DestType.getQualifiers(); 4825218893Sdim unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4826218893Sdim if (CVR) { 4827234353Sdim Diag(From->getLocStart(), 4828218893Sdim diag::err_member_function_call_bad_cvr) 4829218893Sdim << Method->getDeclName() << FromRecordType << (CVR - 1) 4830218893Sdim << From->getSourceRange(); 4831218893Sdim Diag(Method->getLocation(), diag::note_previous_decl) 4832218893Sdim << Method->getDeclName(); 4833221345Sdim return ExprError(); 4834218893Sdim } 4835218893Sdim } 4836218893Sdim 4837234353Sdim return Diag(From->getLocStart(), 4838193326Sed diag::err_implicit_object_parameter_init) 4839193326Sed << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4840218893Sdim } 4841198092Srdivacky 4842221345Sdim if (ICS.Standard.Second == ICK_Derived_To_Base) { 4843221345Sdim ExprResult FromRes = 4844221345Sdim PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4845221345Sdim if (FromRes.isInvalid()) 4846221345Sdim return ExprError(); 4847221345Sdim From = FromRes.take(); 4848221345Sdim } 4849193326Sed 4850204793Srdivacky if (!Context.hasSameType(From->getType(), DestType)) 4851221345Sdim From = ImpCastExprToType(From, DestType, CK_NoOp, 4852234353Sdim From->getValueKind()).take(); 4853221345Sdim return Owned(From); 4854193326Sed} 4855193326Sed 4856193326Sed/// TryContextuallyConvertToBool - Attempt to contextually convert the 4857193326Sed/// expression From to bool (C++0x [conv]p3). 4858212904Sdimstatic ImplicitConversionSequence 4859212904SdimTryContextuallyConvertToBool(Sema &S, Expr *From) { 4860208600Srdivacky // FIXME: This is pretty broken. 4861212904Sdim return TryImplicitConversion(S, From, S.Context.BoolTy, 4862198092Srdivacky // FIXME: Are these flags correct? 4863198092Srdivacky /*SuppressUserConversions=*/false, 4864198092Srdivacky /*AllowExplicit=*/true, 4865218893Sdim /*InOverloadResolution=*/false, 4866224145Sdim /*CStyle=*/false, 4867224145Sdim /*AllowObjCWritebackConversion=*/false); 4868193326Sed} 4869193326Sed 4870193326Sed/// PerformContextuallyConvertToBool - Perform a contextual conversion 4871193326Sed/// of the expression From to bool (C++0x [conv]p3). 4872221345SdimExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4873234353Sdim if (checkPlaceholderForOverload(*this, From)) 4874234353Sdim return ExprError(); 4875234353Sdim 4876212904Sdim ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4877202379Srdivacky if (!ICS.isBad()) 4878202379Srdivacky return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4879218893Sdim 4880199512Srdivacky if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4881234353Sdim return Diag(From->getLocStart(), 4882221345Sdim diag::err_typecheck_bool_condition) 4883198092Srdivacky << From->getType() << From->getSourceRange(); 4884221345Sdim return ExprError(); 4885193326Sed} 4886218893Sdim 4887234353Sdim/// Check that the specified conversion is permitted in a converted constant 4888234353Sdim/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4889234353Sdim/// is acceptable. 4890234353Sdimstatic bool CheckConvertedConstantConversions(Sema &S, 4891234353Sdim StandardConversionSequence &SCS) { 4892234353Sdim // Since we know that the target type is an integral or unscoped enumeration 4893234353Sdim // type, most conversion kinds are impossible. All possible First and Third 4894234353Sdim // conversions are fine. 4895234353Sdim switch (SCS.Second) { 4896234353Sdim case ICK_Identity: 4897234353Sdim case ICK_Integral_Promotion: 4898234353Sdim case ICK_Integral_Conversion: 4899249423Sdim case ICK_Zero_Event_Conversion: 4900234353Sdim return true; 4901234353Sdim 4902234353Sdim case ICK_Boolean_Conversion: 4903234353Sdim // Conversion from an integral or unscoped enumeration type to bool is 4904234353Sdim // classified as ICK_Boolean_Conversion, but it's also an integral 4905234353Sdim // conversion, so it's permitted in a converted constant expression. 4906234353Sdim return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4907234353Sdim SCS.getToType(2)->isBooleanType(); 4908234353Sdim 4909234353Sdim case ICK_Floating_Integral: 4910234353Sdim case ICK_Complex_Real: 4911234353Sdim return false; 4912234353Sdim 4913234353Sdim case ICK_Lvalue_To_Rvalue: 4914234353Sdim case ICK_Array_To_Pointer: 4915234353Sdim case ICK_Function_To_Pointer: 4916234353Sdim case ICK_NoReturn_Adjustment: 4917234353Sdim case ICK_Qualification: 4918234353Sdim case ICK_Compatible_Conversion: 4919234353Sdim case ICK_Vector_Conversion: 4920234353Sdim case ICK_Vector_Splat: 4921234353Sdim case ICK_Derived_To_Base: 4922234353Sdim case ICK_Pointer_Conversion: 4923234353Sdim case ICK_Pointer_Member: 4924234353Sdim case ICK_Block_Pointer_Conversion: 4925234353Sdim case ICK_Writeback_Conversion: 4926234353Sdim case ICK_Floating_Promotion: 4927234353Sdim case ICK_Complex_Promotion: 4928234353Sdim case ICK_Complex_Conversion: 4929234353Sdim case ICK_Floating_Conversion: 4930234353Sdim case ICK_TransparentUnionConversion: 4931234353Sdim llvm_unreachable("unexpected second conversion kind"); 4932234353Sdim 4933234353Sdim case ICK_Num_Conversion_Kinds: 4934234353Sdim break; 4935234353Sdim } 4936234353Sdim 4937234353Sdim llvm_unreachable("unknown conversion kind"); 4938234353Sdim} 4939234353Sdim 4940234353Sdim/// CheckConvertedConstantExpression - Check that the expression From is a 4941234353Sdim/// converted constant expression of type T, perform the conversion and produce 4942234353Sdim/// the converted expression, per C++11 [expr.const]p3. 4943234353SdimExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4944234353Sdim llvm::APSInt &Value, 4945234353Sdim CCEKind CCE) { 4946249423Sdim assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4947234353Sdim assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4948234353Sdim 4949234353Sdim if (checkPlaceholderForOverload(*this, From)) 4950234353Sdim return ExprError(); 4951234353Sdim 4952234353Sdim // C++11 [expr.const]p3 with proposed wording fixes: 4953234353Sdim // A converted constant expression of type T is a core constant expression, 4954234353Sdim // implicitly converted to a prvalue of type T, where the converted 4955234353Sdim // expression is a literal constant expression and the implicit conversion 4956234353Sdim // sequence contains only user-defined conversions, lvalue-to-rvalue 4957234353Sdim // conversions, integral promotions, and integral conversions other than 4958234353Sdim // narrowing conversions. 4959234353Sdim ImplicitConversionSequence ICS = 4960234353Sdim TryImplicitConversion(From, T, 4961234353Sdim /*SuppressUserConversions=*/false, 4962234353Sdim /*AllowExplicit=*/false, 4963234353Sdim /*InOverloadResolution=*/false, 4964234353Sdim /*CStyle=*/false, 4965234353Sdim /*AllowObjcWritebackConversion=*/false); 4966234353Sdim StandardConversionSequence *SCS = 0; 4967234353Sdim switch (ICS.getKind()) { 4968234353Sdim case ImplicitConversionSequence::StandardConversion: 4969234353Sdim if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4970234353Sdim return Diag(From->getLocStart(), 4971234353Sdim diag::err_typecheck_converted_constant_expression_disallowed) 4972234353Sdim << From->getType() << From->getSourceRange() << T; 4973234353Sdim SCS = &ICS.Standard; 4974234353Sdim break; 4975234353Sdim case ImplicitConversionSequence::UserDefinedConversion: 4976234353Sdim // We are converting from class type to an integral or enumeration type, so 4977234353Sdim // the Before sequence must be trivial. 4978234353Sdim if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4979234353Sdim return Diag(From->getLocStart(), 4980234353Sdim diag::err_typecheck_converted_constant_expression_disallowed) 4981234353Sdim << From->getType() << From->getSourceRange() << T; 4982234353Sdim SCS = &ICS.UserDefined.After; 4983234353Sdim break; 4984234353Sdim case ImplicitConversionSequence::AmbiguousConversion: 4985234353Sdim case ImplicitConversionSequence::BadConversion: 4986234353Sdim if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4987234353Sdim return Diag(From->getLocStart(), 4988234353Sdim diag::err_typecheck_converted_constant_expression) 4989234353Sdim << From->getType() << From->getSourceRange() << T; 4990234353Sdim return ExprError(); 4991234353Sdim 4992234353Sdim case ImplicitConversionSequence::EllipsisConversion: 4993234353Sdim llvm_unreachable("ellipsis conversion in converted constant expression"); 4994234353Sdim } 4995234353Sdim 4996234353Sdim ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4997234353Sdim if (Result.isInvalid()) 4998234353Sdim return Result; 4999234353Sdim 5000234353Sdim // Check for a narrowing implicit conversion. 5001234353Sdim APValue PreNarrowingValue; 5002234353Sdim QualType PreNarrowingType; 5003234353Sdim switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 5004234353Sdim PreNarrowingType)) { 5005234353Sdim case NK_Variable_Narrowing: 5006234353Sdim // Implicit conversion to a narrower type, and the value is not a constant 5007234353Sdim // expression. We'll diagnose this in a moment. 5008234353Sdim case NK_Not_Narrowing: 5009234353Sdim break; 5010234353Sdim 5011234353Sdim case NK_Constant_Narrowing: 5012234353Sdim Diag(From->getLocStart(), 5013234353Sdim isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 5014234353Sdim diag::err_cce_narrowing) 5015234353Sdim << CCE << /*Constant*/1 5016234353Sdim << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5017234353Sdim break; 5018234353Sdim 5019234353Sdim case NK_Type_Narrowing: 5020234353Sdim Diag(From->getLocStart(), 5021234353Sdim isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 5022234353Sdim diag::err_cce_narrowing) 5023234353Sdim << CCE << /*Constant*/0 << From->getType() << T; 5024234353Sdim break; 5025234353Sdim } 5026234353Sdim 5027234353Sdim // Check the expression is a constant expression. 5028249423Sdim SmallVector<PartialDiagnosticAt, 8> Notes; 5029234353Sdim Expr::EvalResult Eval; 5030234353Sdim Eval.Diag = &Notes; 5031234353Sdim 5032251662Sdim if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5033234353Sdim // The expression can't be folded, so we can't keep it at this position in 5034234353Sdim // the AST. 5035234353Sdim Result = ExprError(); 5036234353Sdim } else { 5037234353Sdim Value = Eval.Val.getInt(); 5038234353Sdim 5039234353Sdim if (Notes.empty()) { 5040234353Sdim // It's a constant expression. 5041234353Sdim return Result; 5042234353Sdim } 5043234353Sdim } 5044234353Sdim 5045234353Sdim // It's not a constant expression. Produce an appropriate diagnostic. 5046234353Sdim if (Notes.size() == 1 && 5047234353Sdim Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5048234353Sdim Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5049234353Sdim else { 5050234353Sdim Diag(From->getLocStart(), diag::err_expr_not_cce) 5051234353Sdim << CCE << From->getSourceRange(); 5052234353Sdim for (unsigned I = 0; I < Notes.size(); ++I) 5053234353Sdim Diag(Notes[I].first, Notes[I].second); 5054234353Sdim } 5055234353Sdim return Result; 5056234353Sdim} 5057234353Sdim 5058226633Sdim/// dropPointerConversions - If the given standard conversion sequence 5059226633Sdim/// involves any pointer conversions, remove them. This may change 5060226633Sdim/// the result type of the conversion sequence. 5061226633Sdimstatic void dropPointerConversion(StandardConversionSequence &SCS) { 5062226633Sdim if (SCS.Second == ICK_Pointer_Conversion) { 5063226633Sdim SCS.Second = ICK_Identity; 5064226633Sdim SCS.Third = ICK_Identity; 5065226633Sdim SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5066226633Sdim } 5067226633Sdim} 5068226633Sdim 5069226633Sdim/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5070226633Sdim/// convert the expression From to an Objective-C pointer type. 5071212904Sdimstatic ImplicitConversionSequence 5072226633SdimTryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5073226633Sdim // Do an implicit conversion to 'id'. 5074212904Sdim QualType Ty = S.Context.getObjCIdType(); 5075226633Sdim ImplicitConversionSequence ICS 5076226633Sdim = TryImplicitConversion(S, From, Ty, 5077226633Sdim // FIXME: Are these flags correct? 5078226633Sdim /*SuppressUserConversions=*/false, 5079226633Sdim /*AllowExplicit=*/true, 5080226633Sdim /*InOverloadResolution=*/false, 5081226633Sdim /*CStyle=*/false, 5082226633Sdim /*AllowObjCWritebackConversion=*/false); 5083226633Sdim 5084226633Sdim // Strip off any final conversions to 'id'. 5085226633Sdim switch (ICS.getKind()) { 5086226633Sdim case ImplicitConversionSequence::BadConversion: 5087226633Sdim case ImplicitConversionSequence::AmbiguousConversion: 5088226633Sdim case ImplicitConversionSequence::EllipsisConversion: 5089226633Sdim break; 5090226633Sdim 5091226633Sdim case ImplicitConversionSequence::UserDefinedConversion: 5092226633Sdim dropPointerConversion(ICS.UserDefined.After); 5093226633Sdim break; 5094226633Sdim 5095226633Sdim case ImplicitConversionSequence::StandardConversion: 5096226633Sdim dropPointerConversion(ICS.Standard); 5097226633Sdim break; 5098226633Sdim } 5099226633Sdim 5100226633Sdim return ICS; 5101208600Srdivacky} 5102212904Sdim 5103226633Sdim/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5104226633Sdim/// conversion of the expression From to an Objective-C pointer type. 5105226633SdimExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5106234353Sdim if (checkPlaceholderForOverload(*this, From)) 5107234353Sdim return ExprError(); 5108234353Sdim 5109208600Srdivacky QualType Ty = Context.getObjCIdType(); 5110226633Sdim ImplicitConversionSequence ICS = 5111226633Sdim TryContextuallyConvertToObjCPointer(*this, From); 5112208600Srdivacky if (!ICS.isBad()) 5113208600Srdivacky return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5114221345Sdim return ExprError(); 5115208600Srdivacky} 5116193326Sed 5117234353Sdim/// Determine whether the provided type is an integral type, or an enumeration 5118234353Sdim/// type of a permitted flavor. 5119234353Sdimstatic bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5120234353Sdim return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5121234353Sdim : T->isIntegralOrUnscopedEnumerationType(); 5122234353Sdim} 5123234353Sdim 5124218893Sdim/// \brief Attempt to convert the given expression to an integral or 5125210299Sed/// enumeration type. 5126210299Sed/// 5127210299Sed/// This routine will attempt to convert an expression of class type to an 5128210299Sed/// integral or enumeration type, if that class type only has a single 5129210299Sed/// conversion to an integral or enumeration type. 5130210299Sed/// 5131210299Sed/// \param Loc The source location of the construct that requires the 5132210299Sed/// conversion. 5133210299Sed/// 5134239462Sdim/// \param From The expression we're converting from. 5135210299Sed/// 5136239462Sdim/// \param Diagnoser Used to output any diagnostics. 5137210299Sed/// 5138234353Sdim/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5139234353Sdim/// enumerations should be considered. 5140234353Sdim/// 5141210299Sed/// \returns The expression, converted to an integral or enumeration type if 5142210299Sed/// successful. 5143218893SdimExprResult 5144212904SdimSema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5145239462Sdim ICEConvertDiagnoser &Diagnoser, 5146234353Sdim bool AllowScopedEnumerations) { 5147210299Sed // We can't perform any more checking for type-dependent expressions. 5148210299Sed if (From->isTypeDependent()) 5149212904Sdim return Owned(From); 5150218893Sdim 5151234353Sdim // Process placeholders immediately. 5152234353Sdim if (From->hasPlaceholderType()) { 5153234353Sdim ExprResult result = CheckPlaceholderExpr(From); 5154234353Sdim if (result.isInvalid()) return result; 5155234353Sdim From = result.take(); 5156234353Sdim } 5157234353Sdim 5158210299Sed // If the expression already has integral or enumeration type, we're golden. 5159210299Sed QualType T = From->getType(); 5160234353Sdim if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5161234353Sdim return DefaultLvalueConversion(From); 5162210299Sed 5163210299Sed // FIXME: Check for missing '()' if T is a function type? 5164210299Sed 5165218893Sdim // If we don't have a class type in C++, there's no way we can get an 5166210299Sed // expression of integral or enumeration type. 5167210299Sed const RecordType *RecordTy = T->getAs<RecordType>(); 5168234353Sdim if (!RecordTy || !getLangOpts().CPlusPlus) { 5169239462Sdim if (!Diagnoser.Suppress) 5170239462Sdim Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5171212904Sdim return Owned(From); 5172210299Sed } 5173218893Sdim 5174210299Sed // We must have a complete class type. 5175239462Sdim struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5176239462Sdim ICEConvertDiagnoser &Diagnoser; 5177239462Sdim Expr *From; 5178239462Sdim 5179239462Sdim TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5180239462Sdim : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5181239462Sdim 5182239462Sdim virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5183239462Sdim Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5184239462Sdim } 5185239462Sdim } IncompleteDiagnoser(Diagnoser, From); 5186239462Sdim 5187239462Sdim if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5188212904Sdim return Owned(From); 5189218893Sdim 5190210299Sed // Look for a conversion to an integral or enumeration type. 5191210299Sed UnresolvedSet<4> ViableConversions; 5192210299Sed UnresolvedSet<4> ExplicitConversions; 5193249423Sdim std::pair<CXXRecordDecl::conversion_iterator, 5194249423Sdim CXXRecordDecl::conversion_iterator> Conversions 5195210299Sed = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5196218893Sdim 5197249423Sdim bool HadMultipleCandidates 5198249423Sdim = (std::distance(Conversions.first, Conversions.second) > 1); 5199226633Sdim 5200249423Sdim for (CXXRecordDecl::conversion_iterator 5201249423Sdim I = Conversions.first, E = Conversions.second; I != E; ++I) { 5202210299Sed if (CXXConversionDecl *Conversion 5203234353Sdim = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5204234353Sdim if (isIntegralOrEnumerationType( 5205234353Sdim Conversion->getConversionType().getNonReferenceType(), 5206234353Sdim AllowScopedEnumerations)) { 5207210299Sed if (Conversion->isExplicit()) 5208210299Sed ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5209210299Sed else 5210210299Sed ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5211210299Sed } 5212234353Sdim } 5213210299Sed } 5214218893Sdim 5215210299Sed switch (ViableConversions.size()) { 5216210299Sed case 0: 5217239462Sdim if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5218210299Sed DeclAccessPair Found = ExplicitConversions[0]; 5219210299Sed CXXConversionDecl *Conversion 5220210299Sed = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5221218893Sdim 5222210299Sed // The user probably meant to invoke the given explicit 5223210299Sed // conversion; use it. 5224210299Sed QualType ConvTy 5225210299Sed = Conversion->getConversionType().getNonReferenceType(); 5226210299Sed std::string TypeStr; 5227226633Sdim ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5228218893Sdim 5229239462Sdim Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5230210299Sed << FixItHint::CreateInsertion(From->getLocStart(), 5231210299Sed "static_cast<" + TypeStr + ">(") 5232210299Sed << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5233210299Sed ")"); 5234239462Sdim Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5235218893Sdim 5236218893Sdim // If we aren't in a SFINAE context, build a call to the 5237210299Sed // explicit conversion function. 5238210299Sed if (isSFINAEContext()) 5239210299Sed return ExprError(); 5240218893Sdim 5241210299Sed CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5242226633Sdim ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5243226633Sdim HadMultipleCandidates); 5244218893Sdim if (Result.isInvalid()) 5245218893Sdim return ExprError(); 5246234353Sdim // Record usage of conversion in an implicit cast. 5247234353Sdim From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5248234353Sdim CK_UserDefinedConversion, 5249234353Sdim Result.get(), 0, 5250234353Sdim Result.get()->getValueKind()); 5251210299Sed } 5252218893Sdim 5253210299Sed // We'll complain below about a non-integral condition type. 5254210299Sed break; 5255218893Sdim 5256210299Sed case 1: { 5257210299Sed // Apply this conversion. 5258210299Sed DeclAccessPair Found = ViableConversions[0]; 5259210299Sed CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5260218893Sdim 5261210299Sed CXXConversionDecl *Conversion 5262210299Sed = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5263210299Sed QualType ConvTy 5264218893Sdim = Conversion->getConversionType().getNonReferenceType(); 5265239462Sdim if (!Diagnoser.SuppressConversion) { 5266210299Sed if (isSFINAEContext()) 5267210299Sed return ExprError(); 5268218893Sdim 5269239462Sdim Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5270239462Sdim << From->getSourceRange(); 5271210299Sed } 5272218893Sdim 5273226633Sdim ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5274226633Sdim HadMultipleCandidates); 5275218893Sdim if (Result.isInvalid()) 5276218893Sdim return ExprError(); 5277234353Sdim // Record usage of conversion in an implicit cast. 5278234353Sdim From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5279234353Sdim CK_UserDefinedConversion, 5280234353Sdim Result.get(), 0, 5281234353Sdim Result.get()->getValueKind()); 5282210299Sed break; 5283210299Sed } 5284218893Sdim 5285210299Sed default: 5286239462Sdim if (Diagnoser.Suppress) 5287239462Sdim return ExprError(); 5288234353Sdim 5289239462Sdim Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5290210299Sed for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5291210299Sed CXXConversionDecl *Conv 5292210299Sed = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5293210299Sed QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5294239462Sdim Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5295210299Sed } 5296212904Sdim return Owned(From); 5297210299Sed } 5298218893Sdim 5299234353Sdim if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5300239462Sdim !Diagnoser.Suppress) { 5301239462Sdim Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5302239462Sdim << From->getSourceRange(); 5303239462Sdim } 5304210299Sed 5305234353Sdim return DefaultLvalueConversion(From); 5306210299Sed} 5307210299Sed 5308193326Sed/// AddOverloadCandidate - Adds the given function to the set of 5309193326Sed/// candidate functions, using the given function call arguments. If 5310193326Sed/// @p SuppressUserConversions, then don't allow user-defined 5311193326Sed/// conversions via constructors or conversion operators. 5312198092Srdivacky/// 5313239462Sdim/// \param PartialOverloading true if we are performing "partial" overloading 5314198092Srdivacky/// based on an incomplete set of function arguments. This feature is used by 5315198092Srdivacky/// code completion. 5316198092Srdivackyvoid 5317198092SrdivackySema::AddOverloadCandidate(FunctionDecl *Function, 5318205408Srdivacky DeclAccessPair FoundDecl, 5319249423Sdim ArrayRef<Expr *> Args, 5320193326Sed OverloadCandidateSet& CandidateSet, 5321193326Sed bool SuppressUserConversions, 5322234353Sdim bool PartialOverloading, 5323234353Sdim bool AllowExplicit) { 5324198092Srdivacky const FunctionProtoType* Proto 5325198092Srdivacky = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5326193326Sed assert(Proto && "Functions without a prototype cannot be overloaded"); 5327198092Srdivacky assert(!Function->getDescribedFunctionTemplate() && 5328195099Sed "Use AddTemplateOverloadCandidate for function templates"); 5329198092Srdivacky 5330193326Sed if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5331193326Sed if (!isa<CXXConstructorDecl>(Method)) { 5332193326Sed // If we get here, it's because we're calling a member function 5333193326Sed // that is named without a member access expression (e.g., 5334193326Sed // "this->f") that was either written explicitly or created 5335193326Sed // implicitly. This can happen with a qualified call to a member 5336200583Srdivacky // function, e.g., X::f(). We use an empty type for the implied 5337200583Srdivacky // object argument (C++ [over.call.func]p3), and the acting context 5338200583Srdivacky // is irrelevant. 5339205408Srdivacky AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5340218893Sdim QualType(), Expr::Classification::makeSimpleLValue(), 5341234353Sdim Args, CandidateSet, SuppressUserConversions); 5342193326Sed return; 5343193326Sed } 5344193326Sed // We treat a constructor like a non-member function, since its object 5345193326Sed // argument doesn't participate in overload resolution. 5346193326Sed } 5347193326Sed 5348198092Srdivacky if (!CandidateSet.isNewCandidate(Function)) 5349198092Srdivacky return; 5350199482Srdivacky 5351199990Srdivacky // Overload resolution is always an unevaluated context. 5352212904Sdim EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5353199990Srdivacky 5354199482Srdivacky if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5355199482Srdivacky // C++ [class.copy]p3: 5356199482Srdivacky // A member function template is never instantiated to perform the copy 5357199482Srdivacky // of a class object to an object of its class type. 5358199482Srdivacky QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5359234353Sdim if (Args.size() == 1 && 5360218893Sdim Constructor->isSpecializationCopyingObject() && 5361204643Srdivacky (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5362204643Srdivacky IsDerivedFrom(Args[0]->getType(), ClassType))) 5363199482Srdivacky return; 5364199482Srdivacky } 5365218893Sdim 5366193326Sed // Add this candidate 5367234353Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5368205408Srdivacky Candidate.FoundDecl = FoundDecl; 5369193326Sed Candidate.Function = Function; 5370193326Sed Candidate.Viable = true; 5371193326Sed Candidate.IsSurrogate = false; 5372193326Sed Candidate.IgnoreObjectArgument = false; 5373234353Sdim Candidate.ExplicitCallArguments = Args.size(); 5374193326Sed 5375193326Sed unsigned NumArgsInProto = Proto->getNumArgs(); 5376193326Sed 5377193326Sed // (C++ 13.3.2p2): A candidate function having fewer than m 5378193326Sed // parameters is viable only if it has an ellipsis in its parameter 5379193326Sed // list (8.3.5). 5380234353Sdim if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5381198092Srdivacky !Proto->isVariadic()) { 5382193326Sed Candidate.Viable = false; 5383202379Srdivacky Candidate.FailureKind = ovl_fail_too_many_arguments; 5384193326Sed return; 5385193326Sed } 5386193326Sed 5387193326Sed // (C++ 13.3.2p2): A candidate function having more than m parameters 5388193326Sed // is viable only if the (m+1)st parameter has a default argument 5389193326Sed // (8.3.6). For the purposes of overload resolution, the 5390193326Sed // parameter list is truncated on the right, so that there are 5391193326Sed // exactly m parameters. 5392193326Sed unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5393234353Sdim if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5394193326Sed // Not enough arguments. 5395193326Sed Candidate.Viable = false; 5396202379Srdivacky Candidate.FailureKind = ovl_fail_too_few_arguments; 5397193326Sed return; 5398193326Sed } 5399193326Sed 5400226633Sdim // (CUDA B.1): Check for invalid calls between targets. 5401234353Sdim if (getLangOpts().CUDA) 5402226633Sdim if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5403226633Sdim if (CheckCUDATarget(Caller, Function)) { 5404226633Sdim Candidate.Viable = false; 5405226633Sdim Candidate.FailureKind = ovl_fail_bad_target; 5406226633Sdim return; 5407226633Sdim } 5408226633Sdim 5409193326Sed // Determine the implicit conversion sequences for each of the 5410193326Sed // arguments. 5411234353Sdim for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5412193326Sed if (ArgIdx < NumArgsInProto) { 5413193326Sed // (C++ 13.3.2p3): for F to be a viable function, there shall 5414193326Sed // exist for each argument an implicit conversion sequence 5415193326Sed // (13.3.3.1) that converts that argument to the corresponding 5416193326Sed // parameter of F. 5417193326Sed QualType ParamType = Proto->getArgType(ArgIdx); 5418198092Srdivacky Candidate.Conversions[ArgIdx] 5419207619Srdivacky = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5420218893Sdim SuppressUserConversions, 5421224145Sdim /*InOverloadResolution=*/true, 5422224145Sdim /*AllowObjCWritebackConversion=*/ 5423234353Sdim getLangOpts().ObjCAutoRefCount, 5424234353Sdim AllowExplicit); 5425202379Srdivacky if (Candidate.Conversions[ArgIdx].isBad()) { 5426202379Srdivacky Candidate.Viable = false; 5427202379Srdivacky Candidate.FailureKind = ovl_fail_bad_conversion; 5428202379Srdivacky break; 5429193326Sed } 5430193326Sed } else { 5431193326Sed // (C++ 13.3.2p2): For the purposes of overload resolution, any 5432193326Sed // argument for which there is no corresponding parameter is 5433193326Sed // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5434202379Srdivacky Candidate.Conversions[ArgIdx].setEllipsis(); 5435193326Sed } 5436193326Sed } 5437193326Sed} 5438193326Sed 5439193326Sed/// \brief Add all of the function declarations in the given function set to 5440193326Sed/// the overload canddiate set. 5441203955Srdivackyvoid Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5442249423Sdim ArrayRef<Expr *> Args, 5443193326Sed OverloadCandidateSet& CandidateSet, 5444234353Sdim bool SuppressUserConversions, 5445234353Sdim TemplateArgumentListInfo *ExplicitTemplateArgs) { 5446203955Srdivacky for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5447205408Srdivacky NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5448205408Srdivacky if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5449198092Srdivacky if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5450205408Srdivacky AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5451200583Srdivacky cast<CXXMethodDecl>(FD)->getParent(), 5452218893Sdim Args[0]->getType(), Args[0]->Classify(Context), 5453234353Sdim Args.slice(1), CandidateSet, 5454234353Sdim SuppressUserConversions); 5455198092Srdivacky else 5456234353Sdim AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5457198092Srdivacky SuppressUserConversions); 5458198092Srdivacky } else { 5459205408Srdivacky FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5460198092Srdivacky if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5461198092Srdivacky !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5462205408Srdivacky AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5463200583Srdivacky cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5464234353Sdim ExplicitTemplateArgs, 5465218893Sdim Args[0]->getType(), 5466234353Sdim Args[0]->Classify(Context), Args.slice(1), 5467234353Sdim CandidateSet, SuppressUserConversions); 5468198092Srdivacky else 5469205408Srdivacky AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5470234353Sdim ExplicitTemplateArgs, Args, 5471234353Sdim CandidateSet, SuppressUserConversions); 5472198092Srdivacky } 5473195341Sed } 5474193326Sed} 5475193326Sed 5476199482Srdivacky/// AddMethodCandidate - Adds a named decl (which is some kind of 5477199482Srdivacky/// method) as a method candidate to the given overload set. 5478205408Srdivackyvoid Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5479200583Srdivacky QualType ObjectType, 5480218893Sdim Expr::Classification ObjectClassification, 5481251662Sdim ArrayRef<Expr *> Args, 5482199482Srdivacky OverloadCandidateSet& CandidateSet, 5483207619Srdivacky bool SuppressUserConversions) { 5484205408Srdivacky NamedDecl *Decl = FoundDecl.getDecl(); 5485200583Srdivacky CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5486199482Srdivacky 5487199482Srdivacky if (isa<UsingShadowDecl>(Decl)) 5488199482Srdivacky Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5489218893Sdim 5490199482Srdivacky if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5491199482Srdivacky assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5492199482Srdivacky "Expected a member function template"); 5493205408Srdivacky AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5494205408Srdivacky /*ExplicitArgs*/ 0, 5495234353Sdim ObjectType, ObjectClassification, 5496251662Sdim Args, CandidateSet, 5497207619Srdivacky SuppressUserConversions); 5498199482Srdivacky } else { 5499205408Srdivacky AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5500234353Sdim ObjectType, ObjectClassification, 5501251662Sdim Args, 5502207619Srdivacky CandidateSet, SuppressUserConversions); 5503199482Srdivacky } 5504199482Srdivacky} 5505199482Srdivacky 5506193326Sed/// AddMethodCandidate - Adds the given C++ member function to the set 5507193326Sed/// of candidate functions, using the given function call arguments 5508193326Sed/// and the object argument (@c Object). For example, in a call 5509193326Sed/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5510193326Sed/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5511193326Sed/// allow user-defined conversions via constructors or conversion 5512207619Srdivacky/// operators. 5513198092Srdivackyvoid 5514205408SrdivackySema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5515203955Srdivacky CXXRecordDecl *ActingContext, QualType ObjectType, 5516218893Sdim Expr::Classification ObjectClassification, 5517249423Sdim ArrayRef<Expr *> Args, 5518193326Sed OverloadCandidateSet& CandidateSet, 5519207619Srdivacky bool SuppressUserConversions) { 5520198092Srdivacky const FunctionProtoType* Proto 5521198092Srdivacky = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5522193326Sed assert(Proto && "Methods without a prototype cannot be overloaded"); 5523193326Sed assert(!isa<CXXConstructorDecl>(Method) && 5524193326Sed "Use AddOverloadCandidate for constructors"); 5525193326Sed 5526198092Srdivacky if (!CandidateSet.isNewCandidate(Method)) 5527198092Srdivacky return; 5528198092Srdivacky 5529199990Srdivacky // Overload resolution is always an unevaluated context. 5530212904Sdim EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5531199990Srdivacky 5532193326Sed // Add this candidate 5533234353Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5534205408Srdivacky Candidate.FoundDecl = FoundDecl; 5535193326Sed Candidate.Function = Method; 5536193326Sed Candidate.IsSurrogate = false; 5537193326Sed Candidate.IgnoreObjectArgument = false; 5538234353Sdim Candidate.ExplicitCallArguments = Args.size(); 5539193326Sed 5540193326Sed unsigned NumArgsInProto = Proto->getNumArgs(); 5541193326Sed 5542193326Sed // (C++ 13.3.2p2): A candidate function having fewer than m 5543193326Sed // parameters is viable only if it has an ellipsis in its parameter 5544193326Sed // list (8.3.5). 5545234353Sdim if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5546193326Sed Candidate.Viable = false; 5547202379Srdivacky Candidate.FailureKind = ovl_fail_too_many_arguments; 5548193326Sed return; 5549193326Sed } 5550193326Sed 5551193326Sed // (C++ 13.3.2p2): A candidate function having more than m parameters 5552193326Sed // is viable only if the (m+1)st parameter has a default argument 5553193326Sed // (8.3.6). For the purposes of overload resolution, the 5554193326Sed // parameter list is truncated on the right, so that there are 5555193326Sed // exactly m parameters. 5556193326Sed unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5557234353Sdim if (Args.size() < MinRequiredArgs) { 5558193326Sed // Not enough arguments. 5559193326Sed Candidate.Viable = false; 5560202379Srdivacky Candidate.FailureKind = ovl_fail_too_few_arguments; 5561193326Sed return; 5562193326Sed } 5563193326Sed 5564193326Sed Candidate.Viable = true; 5565193326Sed 5566200583Srdivacky if (Method->isStatic() || ObjectType.isNull()) 5567193326Sed // The implicit object argument is ignored. 5568193326Sed Candidate.IgnoreObjectArgument = true; 5569193326Sed else { 5570193326Sed // Determine the implicit conversion sequence for the object 5571193326Sed // parameter. 5572200583Srdivacky Candidate.Conversions[0] 5573218893Sdim = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5574218893Sdim Method, ActingContext); 5575202379Srdivacky if (Candidate.Conversions[0].isBad()) { 5576193326Sed Candidate.Viable = false; 5577202379Srdivacky Candidate.FailureKind = ovl_fail_bad_conversion; 5578193326Sed return; 5579193326Sed } 5580193326Sed } 5581193326Sed 5582193326Sed // Determine the implicit conversion sequences for each of the 5583193326Sed // arguments. 5584234353Sdim for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5585193326Sed if (ArgIdx < NumArgsInProto) { 5586193326Sed // (C++ 13.3.2p3): for F to be a viable function, there shall 5587193326Sed // exist for each argument an implicit conversion sequence 5588193326Sed // (13.3.3.1) that converts that argument to the corresponding 5589193326Sed // parameter of F. 5590193326Sed QualType ParamType = Proto->getArgType(ArgIdx); 5591198092Srdivacky Candidate.Conversions[ArgIdx + 1] 5592207619Srdivacky = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5593218893Sdim SuppressUserConversions, 5594224145Sdim /*InOverloadResolution=*/true, 5595224145Sdim /*AllowObjCWritebackConversion=*/ 5596234353Sdim getLangOpts().ObjCAutoRefCount); 5597202379Srdivacky if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5598193326Sed Candidate.Viable = false; 5599202379Srdivacky Candidate.FailureKind = ovl_fail_bad_conversion; 5600193326Sed break; 5601193326Sed } 5602193326Sed } else { 5603193326Sed // (C++ 13.3.2p2): For the purposes of overload resolution, any 5604193326Sed // argument for which there is no corresponding parameter is 5605193326Sed // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5606202379Srdivacky Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5607193326Sed } 5608193326Sed } 5609193326Sed} 5610218893Sdim 5611198092Srdivacky/// \brief Add a C++ member function template as a candidate to the candidate 5612198092Srdivacky/// set, using template argument deduction to produce an appropriate member 5613198092Srdivacky/// function template specialization. 5614198092Srdivackyvoid 5615198092SrdivackySema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5616205408Srdivacky DeclAccessPair FoundDecl, 5617200583Srdivacky CXXRecordDecl *ActingContext, 5618221345Sdim TemplateArgumentListInfo *ExplicitTemplateArgs, 5619200583Srdivacky QualType ObjectType, 5620218893Sdim Expr::Classification ObjectClassification, 5621249423Sdim ArrayRef<Expr *> Args, 5622198092Srdivacky OverloadCandidateSet& CandidateSet, 5623207619Srdivacky bool SuppressUserConversions) { 5624198092Srdivacky if (!CandidateSet.isNewCandidate(MethodTmpl)) 5625198092Srdivacky return; 5626198092Srdivacky 5627198092Srdivacky // C++ [over.match.funcs]p7: 5628198092Srdivacky // In each case where a candidate is a function template, candidate 5629198092Srdivacky // function template specializations are generated using template argument 5630198092Srdivacky // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5631198092Srdivacky // candidate functions in the usual way.113) A given name can refer to one 5632198092Srdivacky // or more function templates and also to a set of overloaded non-template 5633198092Srdivacky // functions. In such a case, the candidate functions generated from each 5634198092Srdivacky // function template are combined with the set of non-template candidate 5635198092Srdivacky // functions. 5636243830Sdim TemplateDeductionInfo Info(CandidateSet.getLocation()); 5637198092Srdivacky FunctionDecl *Specialization = 0; 5638198092Srdivacky if (TemplateDeductionResult Result 5639234353Sdim = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5640234353Sdim Specialization, Info)) { 5641234353Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5642208600Srdivacky Candidate.FoundDecl = FoundDecl; 5643208600Srdivacky Candidate.Function = MethodTmpl->getTemplatedDecl(); 5644208600Srdivacky Candidate.Viable = false; 5645208600Srdivacky Candidate.FailureKind = ovl_fail_bad_deduction; 5646208600Srdivacky Candidate.IsSurrogate = false; 5647208600Srdivacky Candidate.IgnoreObjectArgument = false; 5648234353Sdim Candidate.ExplicitCallArguments = Args.size(); 5649218893Sdim Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5650208600Srdivacky Info); 5651208600Srdivacky return; 5652208600Srdivacky } 5653198092Srdivacky 5654198092Srdivacky // Add the function template specialization produced by template argument 5655198092Srdivacky // deduction as a candidate. 5656198092Srdivacky assert(Specialization && "Missing member function template specialization?"); 5657198092Srdivacky assert(isa<CXXMethodDecl>(Specialization) && 5658198092Srdivacky "Specialization is not a member function?"); 5659205408Srdivacky AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5660234353Sdim ActingContext, ObjectType, ObjectClassification, Args, 5661234353Sdim CandidateSet, SuppressUserConversions); 5662198092Srdivacky} 5663198092Srdivacky 5664198092Srdivacky/// \brief Add a C++ function template specialization as a candidate 5665198092Srdivacky/// in the candidate set, using template argument deduction to produce 5666198092Srdivacky/// an appropriate function template specialization. 5667198092Srdivackyvoid 5668195099SedSema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5669205408Srdivacky DeclAccessPair FoundDecl, 5670221345Sdim TemplateArgumentListInfo *ExplicitTemplateArgs, 5671249423Sdim ArrayRef<Expr *> Args, 5672195099Sed OverloadCandidateSet& CandidateSet, 5673207619Srdivacky bool SuppressUserConversions) { 5674198092Srdivacky if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5675198092Srdivacky return; 5676198092Srdivacky 5677195099Sed // C++ [over.match.funcs]p7: 5678198092Srdivacky // In each case where a candidate is a function template, candidate 5679195099Sed // function template specializations are generated using template argument 5680198092Srdivacky // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5681195099Sed // candidate functions in the usual way.113) A given name can refer to one 5682195099Sed // or more function templates and also to a set of overloaded non-template 5683195099Sed // functions. In such a case, the candidate functions generated from each 5684195099Sed // function template are combined with the set of non-template candidate 5685195099Sed // functions. 5686243830Sdim TemplateDeductionInfo Info(CandidateSet.getLocation()); 5687195099Sed FunctionDecl *Specialization = 0; 5688195099Sed if (TemplateDeductionResult Result 5689234353Sdim = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5690234353Sdim Specialization, Info)) { 5691234353Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5692205408Srdivacky Candidate.FoundDecl = FoundDecl; 5693201361Srdivacky Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5694201361Srdivacky Candidate.Viable = false; 5695202379Srdivacky Candidate.FailureKind = ovl_fail_bad_deduction; 5696201361Srdivacky Candidate.IsSurrogate = false; 5697201361Srdivacky Candidate.IgnoreObjectArgument = false; 5698234353Sdim Candidate.ExplicitCallArguments = Args.size(); 5699218893Sdim Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5700208600Srdivacky Info); 5701195099Sed return; 5702195099Sed } 5703198092Srdivacky 5704195099Sed // Add the function template specialization produced by template argument 5705195099Sed // deduction as a candidate. 5706195099Sed assert(Specialization && "Missing function template specialization?"); 5707234353Sdim AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5708207619Srdivacky SuppressUserConversions); 5709195099Sed} 5710198092Srdivacky 5711193326Sed/// AddConversionCandidate - Add a C++ conversion function as a 5712198092Srdivacky/// candidate in the candidate set (C++ [over.match.conv], 5713193326Sed/// C++ [over.match.copy]). From is the expression we're converting from, 5714198092Srdivacky/// and ToType is the type that we're eventually trying to convert to 5715193326Sed/// (which may or may not be the same type as the type that the 5716193326Sed/// conversion function produces). 5717193326Sedvoid 5718193326SedSema::AddConversionCandidate(CXXConversionDecl *Conversion, 5719205408Srdivacky DeclAccessPair FoundDecl, 5720200583Srdivacky CXXRecordDecl *ActingContext, 5721193326Sed Expr *From, QualType ToType, 5722193326Sed OverloadCandidateSet& CandidateSet) { 5723198092Srdivacky assert(!Conversion->getDescribedFunctionTemplate() && 5724198092Srdivacky "Conversion function templates use AddTemplateConversionCandidate"); 5725207619Srdivacky QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5726198092Srdivacky if (!CandidateSet.isNewCandidate(Conversion)) 5727198092Srdivacky return; 5728198092Srdivacky 5729251662Sdim // If the conversion function has an undeduced return type, trigger its 5730251662Sdim // deduction now. 5731251662Sdim if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 5732251662Sdim if (DeduceReturnType(Conversion, From->getExprLoc())) 5733251662Sdim return; 5734251662Sdim ConvType = Conversion->getConversionType().getNonReferenceType(); 5735251662Sdim } 5736251662Sdim 5737199990Srdivacky // Overload resolution is always an unevaluated context. 5738212904Sdim EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5739199990Srdivacky 5740193326Sed // Add this candidate 5741234353Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5742205408Srdivacky Candidate.FoundDecl = FoundDecl; 5743193326Sed Candidate.Function = Conversion; 5744193326Sed Candidate.IsSurrogate = false; 5745193326Sed Candidate.IgnoreObjectArgument = false; 5746193326Sed Candidate.FinalConversion.setAsIdentityConversion(); 5747207619Srdivacky Candidate.FinalConversion.setFromType(ConvType); 5748203955Srdivacky Candidate.FinalConversion.setAllToTypes(ToType); 5749212904Sdim Candidate.Viable = true; 5750218893Sdim Candidate.ExplicitCallArguments = 1; 5751193326Sed 5752212904Sdim // C++ [over.match.funcs]p4: 5753218893Sdim // For conversion functions, the function is considered to be a member of 5754218893Sdim // the class of the implicit implied object argument for the purpose of 5755212904Sdim // defining the type of the implicit object parameter. 5756212904Sdim // 5757193326Sed // Determine the implicit conversion sequence for the implicit 5758193326Sed // object parameter. 5759212904Sdim QualType ImplicitParamType = From->getType(); 5760212904Sdim if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5761212904Sdim ImplicitParamType = FromPtrType->getPointeeType(); 5762212904Sdim CXXRecordDecl *ConversionContext 5763212904Sdim = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5764218893Sdim 5765200583Srdivacky Candidate.Conversions[0] 5766218893Sdim = TryObjectArgumentInitialization(*this, From->getType(), 5767218893Sdim From->Classify(Context), 5768218893Sdim Conversion, ConversionContext); 5769218893Sdim 5770202379Srdivacky if (Candidate.Conversions[0].isBad()) { 5771193326Sed Candidate.Viable = false; 5772202379Srdivacky Candidate.FailureKind = ovl_fail_bad_conversion; 5773193326Sed return; 5774193326Sed } 5775212904Sdim 5776218893Sdim // We won't go through a user-define type conversion function to convert a 5777198398Srdivacky // derived to base as such conversions are given Conversion Rank. They only 5778198398Srdivacky // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5779198398Srdivacky QualType FromCanon 5780198398Srdivacky = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5781198398Srdivacky QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5782198398Srdivacky if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5783198398Srdivacky Candidate.Viable = false; 5784202879Srdivacky Candidate.FailureKind = ovl_fail_trivial_conversion; 5785198398Srdivacky return; 5786198398Srdivacky } 5787218893Sdim 5788193326Sed // To determine what the conversion from the result of calling the 5789193326Sed // conversion function to the type we're eventually trying to 5790193326Sed // convert to (ToType), we need to synthesize a call to the 5791193326Sed // conversion function and attempt copy initialization from it. This 5792193326Sed // makes sure that we get the right semantics with respect to 5793193326Sed // lvalues/rvalues and the type. Fortunately, we can allocate this 5794193326Sed // call on the stack and we don't need its arguments to be 5795193326Sed // well-formed. 5796234353Sdim DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5797218893Sdim VK_LValue, From->getLocStart()); 5798212904Sdim ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5799212904Sdim Context.getPointerType(Conversion->getType()), 5800212904Sdim CK_FunctionToPointerDecay, 5801212904Sdim &ConversionRef, VK_RValue); 5802198092Srdivacky 5803224145Sdim QualType ConversionType = Conversion->getConversionType(); 5804224145Sdim if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5805218893Sdim Candidate.Viable = false; 5806218893Sdim Candidate.FailureKind = ovl_fail_bad_final_conversion; 5807218893Sdim return; 5808218893Sdim } 5809218893Sdim 5810224145Sdim ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5811218893Sdim 5812198092Srdivacky // Note that it is safe to allocate CallExpr on the stack here because 5813193326Sed // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5814193326Sed // allocator). 5815224145Sdim QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5816251662Sdim CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 5817199482Srdivacky From->getLocStart()); 5818198092Srdivacky ImplicitConversionSequence ICS = 5819207619Srdivacky TryCopyInitialization(*this, &Call, ToType, 5820198092Srdivacky /*SuppressUserConversions=*/true, 5821224145Sdim /*InOverloadResolution=*/false, 5822224145Sdim /*AllowObjCWritebackConversion=*/false); 5823198092Srdivacky 5824202379Srdivacky switch (ICS.getKind()) { 5825193326Sed case ImplicitConversionSequence::StandardConversion: 5826193326Sed Candidate.FinalConversion = ICS.Standard; 5827218893Sdim 5828207619Srdivacky // C++ [over.ics.user]p3: 5829207619Srdivacky // If the user-defined conversion is specified by a specialization of a 5830218893Sdim // conversion function template, the second standard conversion sequence 5831207619Srdivacky // shall have exact match rank. 5832207619Srdivacky if (Conversion->getPrimaryTemplate() && 5833207619Srdivacky GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5834207619Srdivacky Candidate.Viable = false; 5835207619Srdivacky Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5836207619Srdivacky } 5837218893Sdim 5838218893Sdim // C++0x [dcl.init.ref]p5: 5839218893Sdim // In the second case, if the reference is an rvalue reference and 5840218893Sdim // the second standard conversion sequence of the user-defined 5841218893Sdim // conversion sequence includes an lvalue-to-rvalue conversion, the 5842218893Sdim // program is ill-formed. 5843218893Sdim if (ToType->isRValueReferenceType() && 5844218893Sdim ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5845218893Sdim Candidate.Viable = false; 5846218893Sdim Candidate.FailureKind = ovl_fail_bad_final_conversion; 5847218893Sdim } 5848193326Sed break; 5849193326Sed 5850193326Sed case ImplicitConversionSequence::BadConversion: 5851193326Sed Candidate.Viable = false; 5852202879Srdivacky Candidate.FailureKind = ovl_fail_bad_final_conversion; 5853193326Sed break; 5854193326Sed 5855193326Sed default: 5856226633Sdim llvm_unreachable( 5857193326Sed "Can only end up with a standard conversion sequence or failure"); 5858193326Sed } 5859193326Sed} 5860193326Sed 5861198092Srdivacky/// \brief Adds a conversion function template specialization 5862198092Srdivacky/// candidate to the overload set, using template argument deduction 5863198092Srdivacky/// to deduce the template arguments of the conversion function 5864198092Srdivacky/// template from the type that we are converting to (C++ 5865198092Srdivacky/// [temp.deduct.conv]). 5866198092Srdivackyvoid 5867198092SrdivackySema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5868205408Srdivacky DeclAccessPair FoundDecl, 5869200583Srdivacky CXXRecordDecl *ActingDC, 5870198092Srdivacky Expr *From, QualType ToType, 5871198092Srdivacky OverloadCandidateSet &CandidateSet) { 5872198092Srdivacky assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5873198092Srdivacky "Only conversion function templates permitted here"); 5874198092Srdivacky 5875198092Srdivacky if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5876198092Srdivacky return; 5877198092Srdivacky 5878243830Sdim TemplateDeductionInfo Info(CandidateSet.getLocation()); 5879198092Srdivacky CXXConversionDecl *Specialization = 0; 5880198092Srdivacky if (TemplateDeductionResult Result 5881198092Srdivacky = DeduceTemplateArguments(FunctionTemplate, ToType, 5882198092Srdivacky Specialization, Info)) { 5883234353Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5884208600Srdivacky Candidate.FoundDecl = FoundDecl; 5885208600Srdivacky Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5886208600Srdivacky Candidate.Viable = false; 5887208600Srdivacky Candidate.FailureKind = ovl_fail_bad_deduction; 5888208600Srdivacky Candidate.IsSurrogate = false; 5889208600Srdivacky Candidate.IgnoreObjectArgument = false; 5890218893Sdim Candidate.ExplicitCallArguments = 1; 5891218893Sdim Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5892208600Srdivacky Info); 5893198092Srdivacky return; 5894198092Srdivacky } 5895198092Srdivacky 5896198092Srdivacky // Add the conversion function template specialization produced by 5897198092Srdivacky // template argument deduction as a candidate. 5898198092Srdivacky assert(Specialization && "Missing function template specialization?"); 5899205408Srdivacky AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5900203955Srdivacky CandidateSet); 5901198092Srdivacky} 5902198092Srdivacky 5903193326Sed/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5904193326Sed/// converts the given @c Object to a function pointer via the 5905193326Sed/// conversion function @c Conversion, and then attempts to call it 5906193326Sed/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5907193326Sed/// the type of function that we'll eventually be calling. 5908193326Sedvoid Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5909205408Srdivacky DeclAccessPair FoundDecl, 5910200583Srdivacky CXXRecordDecl *ActingContext, 5911193326Sed const FunctionProtoType *Proto, 5912218893Sdim Expr *Object, 5913249423Sdim ArrayRef<Expr *> Args, 5914193326Sed OverloadCandidateSet& CandidateSet) { 5915198092Srdivacky if (!CandidateSet.isNewCandidate(Conversion)) 5916198092Srdivacky return; 5917198092Srdivacky 5918199990Srdivacky // Overload resolution is always an unevaluated context. 5919212904Sdim EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5920199990Srdivacky 5921234353Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5922205408Srdivacky Candidate.FoundDecl = FoundDecl; 5923193326Sed Candidate.Function = 0; 5924193326Sed Candidate.Surrogate = Conversion; 5925193326Sed Candidate.Viable = true; 5926193326Sed Candidate.IsSurrogate = true; 5927193326Sed Candidate.IgnoreObjectArgument = false; 5928234353Sdim Candidate.ExplicitCallArguments = Args.size(); 5929193326Sed 5930193326Sed // Determine the implicit conversion sequence for the implicit 5931193326Sed // object parameter. 5932198092Srdivacky ImplicitConversionSequence ObjectInit 5933218893Sdim = TryObjectArgumentInitialization(*this, Object->getType(), 5934218893Sdim Object->Classify(Context), 5935218893Sdim Conversion, ActingContext); 5936202379Srdivacky if (ObjectInit.isBad()) { 5937193326Sed Candidate.Viable = false; 5938202379Srdivacky Candidate.FailureKind = ovl_fail_bad_conversion; 5939202879Srdivacky Candidate.Conversions[0] = ObjectInit; 5940193326Sed return; 5941193326Sed } 5942193326Sed 5943193326Sed // The first conversion is actually a user-defined conversion whose 5944193326Sed // first conversion is ObjectInit's standard conversion (which is 5945193326Sed // effectively a reference binding). Record it as such. 5946202379Srdivacky Candidate.Conversions[0].setUserDefined(); 5947193326Sed Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5948199482Srdivacky Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5949226633Sdim Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5950193326Sed Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5951226633Sdim Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5952198092Srdivacky Candidate.Conversions[0].UserDefined.After 5953193326Sed = Candidate.Conversions[0].UserDefined.Before; 5954193326Sed Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5955193326Sed 5956198092Srdivacky // Find the 5957193326Sed unsigned NumArgsInProto = Proto->getNumArgs(); 5958193326Sed 5959193326Sed // (C++ 13.3.2p2): A candidate function having fewer than m 5960193326Sed // parameters is viable only if it has an ellipsis in its parameter 5961193326Sed // list (8.3.5). 5962234353Sdim if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5963193326Sed Candidate.Viable = false; 5964202379Srdivacky Candidate.FailureKind = ovl_fail_too_many_arguments; 5965193326Sed return; 5966193326Sed } 5967193326Sed 5968193326Sed // Function types don't have any default arguments, so just check if 5969193326Sed // we have enough arguments. 5970234353Sdim if (Args.size() < NumArgsInProto) { 5971193326Sed // Not enough arguments. 5972193326Sed Candidate.Viable = false; 5973202379Srdivacky Candidate.FailureKind = ovl_fail_too_few_arguments; 5974193326Sed return; 5975193326Sed } 5976193326Sed 5977193326Sed // Determine the implicit conversion sequences for each of the 5978193326Sed // arguments. 5979251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 5980193326Sed if (ArgIdx < NumArgsInProto) { 5981193326Sed // (C++ 13.3.2p3): for F to be a viable function, there shall 5982193326Sed // exist for each argument an implicit conversion sequence 5983193326Sed // (13.3.3.1) that converts that argument to the corresponding 5984193326Sed // parameter of F. 5985193326Sed QualType ParamType = Proto->getArgType(ArgIdx); 5986198092Srdivacky Candidate.Conversions[ArgIdx + 1] 5987207619Srdivacky = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5988198092Srdivacky /*SuppressUserConversions=*/false, 5989224145Sdim /*InOverloadResolution=*/false, 5990224145Sdim /*AllowObjCWritebackConversion=*/ 5991234353Sdim getLangOpts().ObjCAutoRefCount); 5992202379Srdivacky if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5993193326Sed Candidate.Viable = false; 5994202379Srdivacky Candidate.FailureKind = ovl_fail_bad_conversion; 5995193326Sed break; 5996193326Sed } 5997193326Sed } else { 5998193326Sed // (C++ 13.3.2p2): For the purposes of overload resolution, any 5999193326Sed // argument for which there is no corresponding parameter is 6000193326Sed // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6001202379Srdivacky Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6002193326Sed } 6003193326Sed } 6004193326Sed} 6005193326Sed 6006193326Sed/// \brief Add overload candidates for overloaded operators that are 6007193326Sed/// member functions. 6008193326Sed/// 6009193326Sed/// Add the overloaded operator candidates that are member functions 6010193326Sed/// for the operator Op that was used in an operator expression such 6011193326Sed/// as "x Op y". , Args/NumArgs provides the operator arguments, and 6012193326Sed/// CandidateSet will store the added overload candidates. (C++ 6013193326Sed/// [over.match.oper]). 6014193326Sedvoid Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6015193326Sed SourceLocation OpLoc, 6016251662Sdim ArrayRef<Expr *> Args, 6017193326Sed OverloadCandidateSet& CandidateSet, 6018193326Sed SourceRange OpRange) { 6019193326Sed DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6020193326Sed 6021193326Sed // C++ [over.match.oper]p3: 6022193326Sed // For a unary operator @ with an operand of a type whose 6023193326Sed // cv-unqualified version is T1, and for a binary operator @ with 6024193326Sed // a left operand of a type whose cv-unqualified version is T1 and 6025193326Sed // a right operand of a type whose cv-unqualified version is T2, 6026193326Sed // three sets of candidate functions, designated member 6027193326Sed // candidates, non-member candidates and built-in candidates, are 6028193326Sed // constructed as follows: 6029193326Sed QualType T1 = Args[0]->getType(); 6030193326Sed 6031251662Sdim // -- If T1 is a complete class type or a class currently being 6032251662Sdim // defined, the set of member candidates is the result of the 6033251662Sdim // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6034251662Sdim // the set of member candidates is empty. 6035198092Srdivacky if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6036251662Sdim // Complete the type if it can be completed. 6037251662Sdim RequireCompleteType(OpLoc, T1, 0); 6038251662Sdim // If the type is neither complete nor being defined, bail out now. 6039251662Sdim if (!T1Rec->getDecl()->getDefinition()) 6040198092Srdivacky return; 6041198092Srdivacky 6042199482Srdivacky LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6043199482Srdivacky LookupQualifiedName(Operators, T1Rec->getDecl()); 6044199482Srdivacky Operators.suppressDiagnostics(); 6045199482Srdivacky 6046198092Srdivacky for (LookupResult::iterator Oper = Operators.begin(), 6047198092Srdivacky OperEnd = Operators.end(); 6048198092Srdivacky Oper != OperEnd; 6049199482Srdivacky ++Oper) 6050205408Srdivacky AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6051251662Sdim Args[0]->Classify(Context), 6052251662Sdim Args.slice(1), 6053218893Sdim CandidateSet, 6054199482Srdivacky /* SuppressUserConversions = */ false); 6055193326Sed } 6056193326Sed} 6057193326Sed 6058193326Sed/// AddBuiltinCandidate - Add a candidate for a built-in 6059193326Sed/// operator. ResultTy and ParamTys are the result and parameter types 6060193326Sed/// of the built-in candidate, respectively. Args and NumArgs are the 6061193326Sed/// arguments being passed to the candidate. IsAssignmentOperator 6062193326Sed/// should be true when this built-in candidate is an assignment 6063193326Sed/// operator. NumContextualBoolArguments is the number of arguments 6064193326Sed/// (at the beginning of the argument list) that will be contextually 6065193326Sed/// converted to bool. 6066198092Srdivackyvoid Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6067251662Sdim ArrayRef<Expr *> Args, 6068193326Sed OverloadCandidateSet& CandidateSet, 6069193326Sed bool IsAssignmentOperator, 6070193326Sed unsigned NumContextualBoolArguments) { 6071199990Srdivacky // Overload resolution is always an unevaluated context. 6072212904Sdim EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6073199990Srdivacky 6074193326Sed // Add this candidate 6075251662Sdim OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6076205408Srdivacky Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6077193326Sed Candidate.Function = 0; 6078193326Sed Candidate.IsSurrogate = false; 6079193326Sed Candidate.IgnoreObjectArgument = false; 6080193326Sed Candidate.BuiltinTypes.ResultTy = ResultTy; 6081251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6082193326Sed Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6083193326Sed 6084193326Sed // Determine the implicit conversion sequences for each of the 6085193326Sed // arguments. 6086193326Sed Candidate.Viable = true; 6087251662Sdim Candidate.ExplicitCallArguments = Args.size(); 6088251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6089193326Sed // C++ [over.match.oper]p4: 6090193326Sed // For the built-in assignment operators, conversions of the 6091193326Sed // left operand are restricted as follows: 6092193326Sed // -- no temporaries are introduced to hold the left operand, and 6093193326Sed // -- no user-defined conversions are applied to the left 6094193326Sed // operand to achieve a type match with the left-most 6095198092Srdivacky // parameter of a built-in candidate. 6096193326Sed // 6097193326Sed // We block these conversions by turning off user-defined 6098193326Sed // conversions, since that is the only way that initialization of 6099193326Sed // a reference to a non-class type can occur from something that 6100193326Sed // is not of the same type. 6101193326Sed if (ArgIdx < NumContextualBoolArguments) { 6102198092Srdivacky assert(ParamTys[ArgIdx] == Context.BoolTy && 6103193326Sed "Contextual conversion to bool requires bool type"); 6104212904Sdim Candidate.Conversions[ArgIdx] 6105212904Sdim = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6106193326Sed } else { 6107198092Srdivacky Candidate.Conversions[ArgIdx] 6108207619Srdivacky = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6109198092Srdivacky ArgIdx == 0 && IsAssignmentOperator, 6110224145Sdim /*InOverloadResolution=*/false, 6111224145Sdim /*AllowObjCWritebackConversion=*/ 6112234353Sdim getLangOpts().ObjCAutoRefCount); 6113193326Sed } 6114202379Srdivacky if (Candidate.Conversions[ArgIdx].isBad()) { 6115193326Sed Candidate.Viable = false; 6116202379Srdivacky Candidate.FailureKind = ovl_fail_bad_conversion; 6117193326Sed break; 6118193326Sed } 6119193326Sed } 6120193326Sed} 6121193326Sed 6122193326Sed/// BuiltinCandidateTypeSet - A set of types that will be used for the 6123193326Sed/// candidate operator functions for built-in operators (C++ 6124193326Sed/// [over.built]). The types are separated into pointer types and 6125193326Sed/// enumeration types. 6126193326Sedclass BuiltinCandidateTypeSet { 6127193326Sed /// TypeSet - A set of types. 6128193326Sed typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6129193326Sed 6130193326Sed /// PointerTypes - The set of pointer types that will be used in the 6131193326Sed /// built-in candidates. 6132193326Sed TypeSet PointerTypes; 6133193326Sed 6134193326Sed /// MemberPointerTypes - The set of member pointer types that will be 6135193326Sed /// used in the built-in candidates. 6136193326Sed TypeSet MemberPointerTypes; 6137193326Sed 6138193326Sed /// EnumerationTypes - The set of enumeration types that will be 6139193326Sed /// used in the built-in candidates. 6140193326Sed TypeSet EnumerationTypes; 6141193326Sed 6142218893Sdim /// \brief The set of vector types that will be used in the built-in 6143208600Srdivacky /// candidates. 6144208600Srdivacky TypeSet VectorTypes; 6145218893Sdim 6146218893Sdim /// \brief A flag indicating non-record types are viable candidates 6147218893Sdim bool HasNonRecordTypes; 6148218893Sdim 6149218893Sdim /// \brief A flag indicating whether either arithmetic or enumeration types 6150218893Sdim /// were present in the candidate set. 6151218893Sdim bool HasArithmeticOrEnumeralTypes; 6152218893Sdim 6153223017Sdim /// \brief A flag indicating whether the nullptr type was present in the 6154223017Sdim /// candidate set. 6155223017Sdim bool HasNullPtrType; 6156223017Sdim 6157198092Srdivacky /// Sema - The semantic analysis instance where we are building the 6158198092Srdivacky /// candidate type set. 6159198092Srdivacky Sema &SemaRef; 6160198092Srdivacky 6161193326Sed /// Context - The AST context in which we will build the type sets. 6162193326Sed ASTContext &Context; 6163193326Sed 6164198398Srdivacky bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6165198398Srdivacky const Qualifiers &VisibleQuals); 6166193326Sed bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6167193326Sed 6168193326Sedpublic: 6169193326Sed /// iterator - Iterates through the types that are part of the set. 6170193326Sed typedef TypeSet::iterator iterator; 6171193326Sed 6172198092Srdivacky BuiltinCandidateTypeSet(Sema &SemaRef) 6173218893Sdim : HasNonRecordTypes(false), 6174218893Sdim HasArithmeticOrEnumeralTypes(false), 6175223017Sdim HasNullPtrType(false), 6176218893Sdim SemaRef(SemaRef), 6177218893Sdim Context(SemaRef.Context) { } 6178193326Sed 6179218893Sdim void AddTypesConvertedFrom(QualType Ty, 6180198398Srdivacky SourceLocation Loc, 6181198398Srdivacky bool AllowUserConversions, 6182198398Srdivacky bool AllowExplicitConversions, 6183198398Srdivacky const Qualifiers &VisibleTypeConversionsQuals); 6184193326Sed 6185193326Sed /// pointer_begin - First pointer type found; 6186193326Sed iterator pointer_begin() { return PointerTypes.begin(); } 6187193326Sed 6188193326Sed /// pointer_end - Past the last pointer type found; 6189193326Sed iterator pointer_end() { return PointerTypes.end(); } 6190193326Sed 6191193326Sed /// member_pointer_begin - First member pointer type found; 6192193326Sed iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6193193326Sed 6194193326Sed /// member_pointer_end - Past the last member pointer type found; 6195193326Sed iterator member_pointer_end() { return MemberPointerTypes.end(); } 6196193326Sed 6197193326Sed /// enumeration_begin - First enumeration type found; 6198193326Sed iterator enumeration_begin() { return EnumerationTypes.begin(); } 6199193326Sed 6200193326Sed /// enumeration_end - Past the last enumeration type found; 6201193326Sed iterator enumeration_end() { return EnumerationTypes.end(); } 6202218893Sdim 6203208600Srdivacky iterator vector_begin() { return VectorTypes.begin(); } 6204208600Srdivacky iterator vector_end() { return VectorTypes.end(); } 6205218893Sdim 6206218893Sdim bool hasNonRecordTypes() { return HasNonRecordTypes; } 6207218893Sdim bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6208223017Sdim bool hasNullPtrType() const { return HasNullPtrType; } 6209193326Sed}; 6210193326Sed 6211193326Sed/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6212193326Sed/// the set of pointer types along with any more-qualified variants of 6213193326Sed/// that type. For example, if @p Ty is "int const *", this routine 6214193326Sed/// will add "int const *", "int const volatile *", "int const 6215193326Sed/// restrict *", and "int const volatile restrict *" to the set of 6216193326Sed/// pointer types. Returns true if the add of @p Ty itself succeeded, 6217193326Sed/// false otherwise. 6218198092Srdivacky/// 6219198092Srdivacky/// FIXME: what to do about extended qualifiers? 6220193326Sedbool 6221198398SrdivackyBuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6222198398Srdivacky const Qualifiers &VisibleQuals) { 6223198092Srdivacky 6224193326Sed // Insert this type. 6225193326Sed if (!PointerTypes.insert(Ty)) 6226193326Sed return false; 6227218893Sdim 6228212904Sdim QualType PointeeTy; 6229198092Srdivacky const PointerType *PointerTy = Ty->getAs<PointerType>(); 6230212904Sdim bool buildObjCPtr = false; 6231212904Sdim if (!PointerTy) { 6232239462Sdim const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6233239462Sdim PointeeTy = PTy->getPointeeType(); 6234239462Sdim buildObjCPtr = true; 6235239462Sdim } else { 6236239462Sdim PointeeTy = PointerTy->getPointeeType(); 6237212904Sdim } 6238239462Sdim 6239199512Srdivacky // Don't add qualified variants of arrays. For one, they're not allowed 6240199512Srdivacky // (the qualifier would sink to the element type), and for another, the 6241199512Srdivacky // only overload situation where it matters is subscript or pointer +- int, 6242199512Srdivacky // and those shouldn't have qualifier variants anyway. 6243199512Srdivacky if (PointeeTy->isArrayType()) 6244199512Srdivacky return true; 6245239462Sdim 6246198092Srdivacky unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6247198398Srdivacky bool hasVolatile = VisibleQuals.hasVolatile(); 6248198398Srdivacky bool hasRestrict = VisibleQuals.hasRestrict(); 6249218893Sdim 6250198092Srdivacky // Iterate through all strict supersets of BaseCVR. 6251198092Srdivacky for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6252198092Srdivacky if ((CVR | BaseCVR) != CVR) continue; 6253239462Sdim // Skip over volatile if no volatile found anywhere in the types. 6254198398Srdivacky if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6255239462Sdim 6256239462Sdim // Skip over restrict if no restrict found anywhere in the types, or if 6257239462Sdim // the type cannot be restrict-qualified. 6258239462Sdim if ((CVR & Qualifiers::Restrict) && 6259239462Sdim (!hasRestrict || 6260239462Sdim (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6261239462Sdim continue; 6262239462Sdim 6263239462Sdim // Build qualified pointee type. 6264198092Srdivacky QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6265239462Sdim 6266239462Sdim // Build qualified pointer type. 6267239462Sdim QualType QPointerTy; 6268212904Sdim if (!buildObjCPtr) 6269239462Sdim QPointerTy = Context.getPointerType(QPointeeTy); 6270212904Sdim else 6271239462Sdim QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6272239462Sdim 6273239462Sdim // Insert qualified pointer type. 6274239462Sdim PointerTypes.insert(QPointerTy); 6275193326Sed } 6276193326Sed 6277193326Sed return true; 6278193326Sed} 6279193326Sed 6280193326Sed/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6281193326Sed/// to the set of pointer types along with any more-qualified variants of 6282193326Sed/// that type. For example, if @p Ty is "int const *", this routine 6283193326Sed/// will add "int const *", "int const volatile *", "int const 6284193326Sed/// restrict *", and "int const volatile restrict *" to the set of 6285193326Sed/// pointer types. Returns true if the add of @p Ty itself succeeded, 6286193326Sed/// false otherwise. 6287198092Srdivacky/// 6288198092Srdivacky/// FIXME: what to do about extended qualifiers? 6289193326Sedbool 6290193326SedBuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6291193326Sed QualType Ty) { 6292193326Sed // Insert this type. 6293193326Sed if (!MemberPointerTypes.insert(Ty)) 6294193326Sed return false; 6295193326Sed 6296198092Srdivacky const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6297198092Srdivacky assert(PointerTy && "type was not a member pointer type!"); 6298193326Sed 6299198092Srdivacky QualType PointeeTy = PointerTy->getPointeeType(); 6300199512Srdivacky // Don't add qualified variants of arrays. For one, they're not allowed 6301199512Srdivacky // (the qualifier would sink to the element type), and for another, the 6302199512Srdivacky // only overload situation where it matters is subscript or pointer +- int, 6303199512Srdivacky // and those shouldn't have qualifier variants anyway. 6304199512Srdivacky if (PointeeTy->isArrayType()) 6305199512Srdivacky return true; 6306198092Srdivacky const Type *ClassTy = PointerTy->getClass(); 6307198092Srdivacky 6308198092Srdivacky // Iterate through all strict supersets of the pointee type's CVR 6309198092Srdivacky // qualifiers. 6310198092Srdivacky unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6311198092Srdivacky for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6312198092Srdivacky if ((CVR | BaseCVR) != CVR) continue; 6313218893Sdim 6314198092Srdivacky QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6315218893Sdim MemberPointerTypes.insert( 6316218893Sdim Context.getMemberPointerType(QPointeeTy, ClassTy)); 6317193326Sed } 6318193326Sed 6319193326Sed return true; 6320193326Sed} 6321193326Sed 6322193326Sed/// AddTypesConvertedFrom - Add each of the types to which the type @p 6323193326Sed/// Ty can be implicit converted to the given set of @p Types. We're 6324193326Sed/// primarily interested in pointer types and enumeration types. We also 6325193326Sed/// take member pointer types, for the conditional operator. 6326193326Sed/// AllowUserConversions is true if we should look at the conversion 6327193326Sed/// functions of a class type, and AllowExplicitConversions if we 6328193326Sed/// should also include the explicit conversion functions of a class 6329193326Sed/// type. 6330198092Srdivackyvoid 6331193326SedBuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6332198398Srdivacky SourceLocation Loc, 6333193326Sed bool AllowUserConversions, 6334198398Srdivacky bool AllowExplicitConversions, 6335198398Srdivacky const Qualifiers &VisibleQuals) { 6336193326Sed // Only deal with canonical types. 6337193326Sed Ty = Context.getCanonicalType(Ty); 6338193326Sed 6339193326Sed // Look through reference types; they aren't part of the type of an 6340193326Sed // expression for the purposes of conversions. 6341198092Srdivacky if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6342193326Sed Ty = RefTy->getPointeeType(); 6343193326Sed 6344198954Srdivacky // If we're dealing with an array type, decay to the pointer. 6345198954Srdivacky if (Ty->isArrayType()) 6346198954Srdivacky Ty = SemaRef.Context.getArrayDecayedType(Ty); 6347218893Sdim 6348218893Sdim // Otherwise, we don't care about qualifiers on the type. 6349218893Sdim Ty = Ty.getLocalUnqualifiedType(); 6350218893Sdim 6351218893Sdim // Flag if we ever add a non-record type. 6352218893Sdim const RecordType *TyRec = Ty->getAs<RecordType>(); 6353218893Sdim HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6354218893Sdim 6355218893Sdim // Flag if we encounter an arithmetic type. 6356218893Sdim HasArithmeticOrEnumeralTypes = 6357218893Sdim HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6358218893Sdim 6359212904Sdim if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6360212904Sdim PointerTypes.insert(Ty); 6361212904Sdim else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6362193326Sed // Insert our type, and its more-qualified variants, into the set 6363193326Sed // of types. 6364198398Srdivacky if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6365193326Sed return; 6366193326Sed } else if (Ty->isMemberPointerType()) { 6367193326Sed // Member pointers are far easier, since the pointee can't be converted. 6368193326Sed if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6369193326Sed return; 6370193326Sed } else if (Ty->isEnumeralType()) { 6371218893Sdim HasArithmeticOrEnumeralTypes = true; 6372193326Sed EnumerationTypes.insert(Ty); 6373208600Srdivacky } else if (Ty->isVectorType()) { 6374218893Sdim // We treat vector types as arithmetic types in many contexts as an 6375218893Sdim // extension. 6376218893Sdim HasArithmeticOrEnumeralTypes = true; 6377208600Srdivacky VectorTypes.insert(Ty); 6378223017Sdim } else if (Ty->isNullPtrType()) { 6379223017Sdim HasNullPtrType = true; 6380218893Sdim } else if (AllowUserConversions && TyRec) { 6381218893Sdim // No conversion functions in incomplete types. 6382218893Sdim if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6383218893Sdim return; 6384198092Srdivacky 6385218893Sdim CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6386249423Sdim std::pair<CXXRecordDecl::conversion_iterator, 6387249423Sdim CXXRecordDecl::conversion_iterator> 6388249423Sdim Conversions = ClassDecl->getVisibleConversionFunctions(); 6389249423Sdim for (CXXRecordDecl::conversion_iterator 6390249423Sdim I = Conversions.first, E = Conversions.second; I != E; ++I) { 6391218893Sdim NamedDecl *D = I.getDecl(); 6392218893Sdim if (isa<UsingShadowDecl>(D)) 6393218893Sdim D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6394198092Srdivacky 6395218893Sdim // Skip conversion function templates; they don't tell us anything 6396218893Sdim // about which builtin types we can convert to. 6397218893Sdim if (isa<FunctionTemplateDecl>(D)) 6398218893Sdim continue; 6399198092Srdivacky 6400218893Sdim CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6401218893Sdim if (AllowExplicitConversions || !Conv->isExplicit()) { 6402218893Sdim AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6403218893Sdim VisibleQuals); 6404193326Sed } 6405193326Sed } 6406193326Sed } 6407193326Sed} 6408193326Sed 6409198092Srdivacky/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6410198092Srdivacky/// the volatile- and non-volatile-qualified assignment operators for the 6411198092Srdivacky/// given type to the candidate set. 6412198092Srdivackystatic void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6413198092Srdivacky QualType T, 6414251662Sdim ArrayRef<Expr *> Args, 6415198092Srdivacky OverloadCandidateSet &CandidateSet) { 6416198092Srdivacky QualType ParamTypes[2]; 6417198092Srdivacky 6418198092Srdivacky // T& operator=(T&, T) 6419198092Srdivacky ParamTypes[0] = S.Context.getLValueReferenceType(T); 6420198092Srdivacky ParamTypes[1] = T; 6421251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6422198092Srdivacky /*IsAssignmentOperator=*/true); 6423198092Srdivacky 6424198092Srdivacky if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6425198092Srdivacky // volatile T& operator=(volatile T&, T) 6426198092Srdivacky ParamTypes[0] 6427198092Srdivacky = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6428198092Srdivacky ParamTypes[1] = T; 6429251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6430198092Srdivacky /*IsAssignmentOperator=*/true); 6431198092Srdivacky } 6432198092Srdivacky} 6433198092Srdivacky 6434198893Srdivacky/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6435198893Srdivacky/// if any, found in visible type conversion functions found in ArgExpr's type. 6436198398Srdivackystatic Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6437198398Srdivacky Qualifiers VRQuals; 6438198398Srdivacky const RecordType *TyRec; 6439198398Srdivacky if (const MemberPointerType *RHSMPType = 6440198398Srdivacky ArgExpr->getType()->getAs<MemberPointerType>()) 6441207619Srdivacky TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6442198398Srdivacky else 6443198398Srdivacky TyRec = ArgExpr->getType()->getAs<RecordType>(); 6444198398Srdivacky if (!TyRec) { 6445198398Srdivacky // Just to be safe, assume the worst case. 6446198398Srdivacky VRQuals.addVolatile(); 6447198398Srdivacky VRQuals.addRestrict(); 6448198398Srdivacky return VRQuals; 6449198398Srdivacky } 6450218893Sdim 6451198398Srdivacky CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6452203955Srdivacky if (!ClassDecl->hasDefinition()) 6453203955Srdivacky return VRQuals; 6454203955Srdivacky 6455249423Sdim std::pair<CXXRecordDecl::conversion_iterator, 6456249423Sdim CXXRecordDecl::conversion_iterator> 6457249423Sdim Conversions = ClassDecl->getVisibleConversionFunctions(); 6458218893Sdim 6459249423Sdim for (CXXRecordDecl::conversion_iterator 6460249423Sdim I = Conversions.first, E = Conversions.second; I != E; ++I) { 6461206084Srdivacky NamedDecl *D = I.getDecl(); 6462206084Srdivacky if (isa<UsingShadowDecl>(D)) 6463206084Srdivacky D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6464206084Srdivacky if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6465198398Srdivacky QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6466198398Srdivacky if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6467198398Srdivacky CanTy = ResTypeRef->getPointeeType(); 6468198398Srdivacky // Need to go down the pointer/mempointer chain and add qualifiers 6469198398Srdivacky // as see them. 6470198398Srdivacky bool done = false; 6471198398Srdivacky while (!done) { 6472239462Sdim if (CanTy.isRestrictQualified()) 6473239462Sdim VRQuals.addRestrict(); 6474198398Srdivacky if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6475198398Srdivacky CanTy = ResTypePtr->getPointeeType(); 6476218893Sdim else if (const MemberPointerType *ResTypeMPtr = 6477198398Srdivacky CanTy->getAs<MemberPointerType>()) 6478198398Srdivacky CanTy = ResTypeMPtr->getPointeeType(); 6479198398Srdivacky else 6480198398Srdivacky done = true; 6481198398Srdivacky if (CanTy.isVolatileQualified()) 6482198398Srdivacky VRQuals.addVolatile(); 6483198398Srdivacky if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6484198398Srdivacky return VRQuals; 6485198398Srdivacky } 6486198398Srdivacky } 6487198398Srdivacky } 6488198398Srdivacky return VRQuals; 6489198398Srdivacky} 6490218893Sdim 6491218893Sdimnamespace { 6492218893Sdim 6493218893Sdim/// \brief Helper class to manage the addition of builtin operator overload 6494218893Sdim/// candidates. It provides shared state and utility methods used throughout 6495218893Sdim/// the process, as well as a helper method to add each group of builtin 6496218893Sdim/// operator overloads from the standard to a candidate set. 6497218893Sdimclass BuiltinOperatorOverloadBuilder { 6498218893Sdim // Common instance state available to all overload candidate addition methods. 6499218893Sdim Sema &S; 6500251662Sdim ArrayRef<Expr *> Args; 6501198398Srdivacky Qualifiers VisibleTypeConversionsQuals; 6502218893Sdim bool HasArithmeticOrEnumeralCandidateType; 6503226633Sdim SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6504218893Sdim OverloadCandidateSet &CandidateSet; 6505193326Sed 6506218893Sdim // Define some constants used to index and iterate over the arithemetic types 6507218893Sdim // provided via the getArithmeticType() method below. 6508218893Sdim // The "promoted arithmetic types" are the arithmetic 6509218893Sdim // types are that preserved by promotion (C++ [over.built]p2). 6510218893Sdim static const unsigned FirstIntegralType = 3; 6511239462Sdim static const unsigned LastIntegralType = 20; 6512218893Sdim static const unsigned FirstPromotedIntegralType = 3, 6513239462Sdim LastPromotedIntegralType = 11; 6514218893Sdim static const unsigned FirstPromotedArithmeticType = 0, 6515239462Sdim LastPromotedArithmeticType = 11; 6516239462Sdim static const unsigned NumArithmeticTypes = 20; 6517193326Sed 6518218893Sdim /// \brief Get the canonical type for a given arithmetic type index. 6519218893Sdim CanQualType getArithmeticType(unsigned index) { 6520218893Sdim assert(index < NumArithmeticTypes); 6521218893Sdim static CanQualType ASTContext::* const 6522218893Sdim ArithmeticTypes[NumArithmeticTypes] = { 6523218893Sdim // Start of promoted types. 6524218893Sdim &ASTContext::FloatTy, 6525218893Sdim &ASTContext::DoubleTy, 6526218893Sdim &ASTContext::LongDoubleTy, 6527193326Sed 6528218893Sdim // Start of integral types. 6529218893Sdim &ASTContext::IntTy, 6530218893Sdim &ASTContext::LongTy, 6531218893Sdim &ASTContext::LongLongTy, 6532239462Sdim &ASTContext::Int128Ty, 6533218893Sdim &ASTContext::UnsignedIntTy, 6534218893Sdim &ASTContext::UnsignedLongTy, 6535218893Sdim &ASTContext::UnsignedLongLongTy, 6536239462Sdim &ASTContext::UnsignedInt128Ty, 6537218893Sdim // End of promoted types. 6538193326Sed 6539218893Sdim &ASTContext::BoolTy, 6540218893Sdim &ASTContext::CharTy, 6541218893Sdim &ASTContext::WCharTy, 6542218893Sdim &ASTContext::Char16Ty, 6543218893Sdim &ASTContext::Char32Ty, 6544218893Sdim &ASTContext::SignedCharTy, 6545218893Sdim &ASTContext::ShortTy, 6546218893Sdim &ASTContext::UnsignedCharTy, 6547218893Sdim &ASTContext::UnsignedShortTy, 6548218893Sdim // End of integral types. 6549239462Sdim // FIXME: What about complex? What about half? 6550218893Sdim }; 6551218893Sdim return S.Context.*ArithmeticTypes[index]; 6552218893Sdim } 6553193326Sed 6554218893Sdim /// \brief Gets the canonical type resulting from the usual arithemetic 6555218893Sdim /// converions for the given arithmetic types. 6556218893Sdim CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6557218893Sdim // Accelerator table for performing the usual arithmetic conversions. 6558218893Sdim // The rules are basically: 6559218893Sdim // - if either is floating-point, use the wider floating-point 6560218893Sdim // - if same signedness, use the higher rank 6561218893Sdim // - if same size, use unsigned of the higher rank 6562218893Sdim // - use the larger type 6563218893Sdim // These rules, together with the axiom that higher ranks are 6564218893Sdim // never smaller, are sufficient to precompute all of these results 6565218893Sdim // *except* when dealing with signed types of higher rank. 6566218893Sdim // (we could precompute SLL x UI for all known platforms, but it's 6567218893Sdim // better not to make any assumptions). 6568239462Sdim // We assume that int128 has a higher rank than long long on all platforms. 6569218893Sdim enum PromotedType { 6570239462Sdim Dep=-1, 6571239462Sdim Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6572218893Sdim }; 6573239462Sdim static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6574218893Sdim [LastPromotedArithmeticType] = { 6575239462Sdim/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6576239462Sdim/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6577239462Sdim/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6578239462Sdim/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6579239462Sdim/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6580239462Sdim/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6581239462Sdim/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6582239462Sdim/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6583239462Sdim/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6584239462Sdim/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6585239462Sdim/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6586218893Sdim }; 6587218893Sdim 6588218893Sdim assert(L < LastPromotedArithmeticType); 6589218893Sdim assert(R < LastPromotedArithmeticType); 6590218893Sdim int Idx = ConversionsTable[L][R]; 6591218893Sdim 6592218893Sdim // Fast path: the table gives us a concrete answer. 6593218893Sdim if (Idx != Dep) return getArithmeticType(Idx); 6594218893Sdim 6595218893Sdim // Slow path: we need to compare widths. 6596218893Sdim // An invariant is that the signed type has higher rank. 6597218893Sdim CanQualType LT = getArithmeticType(L), 6598218893Sdim RT = getArithmeticType(R); 6599218893Sdim unsigned LW = S.Context.getIntWidth(LT), 6600218893Sdim RW = S.Context.getIntWidth(RT); 6601218893Sdim 6602218893Sdim // If they're different widths, use the signed type. 6603218893Sdim if (LW > RW) return LT; 6604218893Sdim else if (LW < RW) return RT; 6605218893Sdim 6606218893Sdim // Otherwise, use the unsigned type of the signed type's rank. 6607218893Sdim if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6608218893Sdim assert(L == SLL || R == SLL); 6609218893Sdim return S.Context.UnsignedLongLongTy; 6610218893Sdim } 6611218893Sdim 6612218893Sdim /// \brief Helper method to factor out the common pattern of adding overloads 6613218893Sdim /// for '++' and '--' builtin operators. 6614218893Sdim void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6615239462Sdim bool HasVolatile, 6616239462Sdim bool HasRestrict) { 6617218893Sdim QualType ParamTypes[2] = { 6618218893Sdim S.Context.getLValueReferenceType(CandidateTy), 6619218893Sdim S.Context.IntTy 6620218893Sdim }; 6621218893Sdim 6622218893Sdim // Non-volatile version. 6623251662Sdim if (Args.size() == 1) 6624251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6625193326Sed else 6626251662Sdim S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6627193326Sed 6628218893Sdim // Use a heuristic to reduce number of builtin candidates in the set: 6629218893Sdim // add volatile version only if there are conversions to a volatile type. 6630218893Sdim if (HasVolatile) { 6631218893Sdim ParamTypes[0] = 6632218893Sdim S.Context.getLValueReferenceType( 6633218893Sdim S.Context.getVolatileType(CandidateTy)); 6634251662Sdim if (Args.size() == 1) 6635251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6636193326Sed else 6637251662Sdim S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6638193326Sed } 6639239462Sdim 6640239462Sdim // Add restrict version only if there are conversions to a restrict type 6641239462Sdim // and our candidate type is a non-restrict-qualified pointer. 6642239462Sdim if (HasRestrict && CandidateTy->isAnyPointerType() && 6643239462Sdim !CandidateTy.isRestrictQualified()) { 6644239462Sdim ParamTypes[0] 6645239462Sdim = S.Context.getLValueReferenceType( 6646239462Sdim S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6647251662Sdim if (Args.size() == 1) 6648251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6649239462Sdim else 6650251662Sdim S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6651239462Sdim 6652239462Sdim if (HasVolatile) { 6653239462Sdim ParamTypes[0] 6654239462Sdim = S.Context.getLValueReferenceType( 6655239462Sdim S.Context.getCVRQualifiedType(CandidateTy, 6656239462Sdim (Qualifiers::Volatile | 6657239462Sdim Qualifiers::Restrict))); 6658251662Sdim if (Args.size() == 1) 6659251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6660239462Sdim else 6661251662Sdim S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6662239462Sdim } 6663239462Sdim } 6664239462Sdim 6665218893Sdim } 6666193326Sed 6667218893Sdimpublic: 6668218893Sdim BuiltinOperatorOverloadBuilder( 6669251662Sdim Sema &S, ArrayRef<Expr *> Args, 6670218893Sdim Qualifiers VisibleTypeConversionsQuals, 6671218893Sdim bool HasArithmeticOrEnumeralCandidateType, 6672226633Sdim SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6673218893Sdim OverloadCandidateSet &CandidateSet) 6674251662Sdim : S(S), Args(Args), 6675218893Sdim VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6676218893Sdim HasArithmeticOrEnumeralCandidateType( 6677218893Sdim HasArithmeticOrEnumeralCandidateType), 6678218893Sdim CandidateTypes(CandidateTypes), 6679218893Sdim CandidateSet(CandidateSet) { 6680218893Sdim // Validate some of our static helper constants in debug builds. 6681218893Sdim assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6682218893Sdim "Invalid first promoted integral type"); 6683218893Sdim assert(getArithmeticType(LastPromotedIntegralType - 1) 6684239462Sdim == S.Context.UnsignedInt128Ty && 6685218893Sdim "Invalid last promoted integral type"); 6686218893Sdim assert(getArithmeticType(FirstPromotedArithmeticType) 6687218893Sdim == S.Context.FloatTy && 6688218893Sdim "Invalid first promoted arithmetic type"); 6689218893Sdim assert(getArithmeticType(LastPromotedArithmeticType - 1) 6690239462Sdim == S.Context.UnsignedInt128Ty && 6691218893Sdim "Invalid last promoted arithmetic type"); 6692218893Sdim } 6693218893Sdim 6694218893Sdim // C++ [over.built]p3: 6695218893Sdim // 6696218893Sdim // For every pair (T, VQ), where T is an arithmetic type, and VQ 6697218893Sdim // is either volatile or empty, there exist candidate operator 6698218893Sdim // functions of the form 6699218893Sdim // 6700218893Sdim // VQ T& operator++(VQ T&); 6701218893Sdim // T operator++(VQ T&, int); 6702218893Sdim // 6703218893Sdim // C++ [over.built]p4: 6704218893Sdim // 6705218893Sdim // For every pair (T, VQ), where T is an arithmetic type other 6706218893Sdim // than bool, and VQ is either volatile or empty, there exist 6707218893Sdim // candidate operator functions of the form 6708218893Sdim // 6709218893Sdim // VQ T& operator--(VQ T&); 6710218893Sdim // T operator--(VQ T&, int); 6711218893Sdim void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6712218893Sdim if (!HasArithmeticOrEnumeralCandidateType) 6713218893Sdim return; 6714218893Sdim 6715218893Sdim for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6716218893Sdim Arith < NumArithmeticTypes; ++Arith) { 6717218893Sdim addPlusPlusMinusMinusStyleOverloads( 6718218893Sdim getArithmeticType(Arith), 6719239462Sdim VisibleTypeConversionsQuals.hasVolatile(), 6720239462Sdim VisibleTypeConversionsQuals.hasRestrict()); 6721218893Sdim } 6722218893Sdim } 6723218893Sdim 6724218893Sdim // C++ [over.built]p5: 6725218893Sdim // 6726218893Sdim // For every pair (T, VQ), where T is a cv-qualified or 6727218893Sdim // cv-unqualified object type, and VQ is either volatile or 6728218893Sdim // empty, there exist candidate operator functions of the form 6729218893Sdim // 6730218893Sdim // T*VQ& operator++(T*VQ&); 6731218893Sdim // T*VQ& operator--(T*VQ&); 6732218893Sdim // T* operator++(T*VQ&, int); 6733218893Sdim // T* operator--(T*VQ&, int); 6734218893Sdim void addPlusPlusMinusMinusPointerOverloads() { 6735218893Sdim for (BuiltinCandidateTypeSet::iterator 6736218893Sdim Ptr = CandidateTypes[0].pointer_begin(), 6737218893Sdim PtrEnd = CandidateTypes[0].pointer_end(); 6738218893Sdim Ptr != PtrEnd; ++Ptr) { 6739193326Sed // Skip pointer types that aren't pointers to object types. 6740218893Sdim if (!(*Ptr)->getPointeeType()->isObjectType()) 6741193326Sed continue; 6742193326Sed 6743218893Sdim addPlusPlusMinusMinusStyleOverloads(*Ptr, 6744239462Sdim (!(*Ptr).isVolatileQualified() && 6745239462Sdim VisibleTypeConversionsQuals.hasVolatile()), 6746239462Sdim (!(*Ptr).isRestrictQualified() && 6747239462Sdim VisibleTypeConversionsQuals.hasRestrict())); 6748193326Sed } 6749218893Sdim } 6750193326Sed 6751218893Sdim // C++ [over.built]p6: 6752218893Sdim // For every cv-qualified or cv-unqualified object type T, there 6753218893Sdim // exist candidate operator functions of the form 6754218893Sdim // 6755218893Sdim // T& operator*(T*); 6756218893Sdim // 6757218893Sdim // C++ [over.built]p7: 6758218893Sdim // For every function type T that does not have cv-qualifiers or a 6759218893Sdim // ref-qualifier, there exist candidate operator functions of the form 6760218893Sdim // T& operator*(T*); 6761218893Sdim void addUnaryStarPointerOverloads() { 6762218893Sdim for (BuiltinCandidateTypeSet::iterator 6763218893Sdim Ptr = CandidateTypes[0].pointer_begin(), 6764218893Sdim PtrEnd = CandidateTypes[0].pointer_end(); 6765218893Sdim Ptr != PtrEnd; ++Ptr) { 6766193326Sed QualType ParamTy = *Ptr; 6767212904Sdim QualType PointeeTy = ParamTy->getPointeeType(); 6768218893Sdim if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6769218893Sdim continue; 6770193326Sed 6771218893Sdim if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6772218893Sdim if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6773218893Sdim continue; 6774218893Sdim 6775218893Sdim S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6776251662Sdim &ParamTy, Args, CandidateSet); 6777193326Sed } 6778218893Sdim } 6779198092Srdivacky 6780218893Sdim // C++ [over.built]p9: 6781218893Sdim // For every promoted arithmetic type T, there exist candidate 6782218893Sdim // operator functions of the form 6783218893Sdim // 6784218893Sdim // T operator+(T); 6785218893Sdim // T operator-(T); 6786218893Sdim void addUnaryPlusOrMinusArithmeticOverloads() { 6787218893Sdim if (!HasArithmeticOrEnumeralCandidateType) 6788218893Sdim return; 6789193326Sed 6790198092Srdivacky for (unsigned Arith = FirstPromotedArithmeticType; 6791193326Sed Arith < LastPromotedArithmeticType; ++Arith) { 6792218893Sdim QualType ArithTy = getArithmeticType(Arith); 6793251662Sdim S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 6794193326Sed } 6795218893Sdim 6796208600Srdivacky // Extension: We also add these operators for vector types. 6797218893Sdim for (BuiltinCandidateTypeSet::iterator 6798218893Sdim Vec = CandidateTypes[0].vector_begin(), 6799218893Sdim VecEnd = CandidateTypes[0].vector_end(); 6800208600Srdivacky Vec != VecEnd; ++Vec) { 6801208600Srdivacky QualType VecTy = *Vec; 6802251662Sdim S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6803208600Srdivacky } 6804218893Sdim } 6805193326Sed 6806218893Sdim // C++ [over.built]p8: 6807218893Sdim // For every type T, there exist candidate operator functions of 6808218893Sdim // the form 6809218893Sdim // 6810218893Sdim // T* operator+(T*); 6811218893Sdim void addUnaryPlusPointerOverloads() { 6812218893Sdim for (BuiltinCandidateTypeSet::iterator 6813218893Sdim Ptr = CandidateTypes[0].pointer_begin(), 6814218893Sdim PtrEnd = CandidateTypes[0].pointer_end(); 6815218893Sdim Ptr != PtrEnd; ++Ptr) { 6816218893Sdim QualType ParamTy = *Ptr; 6817251662Sdim S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 6818218893Sdim } 6819218893Sdim } 6820218893Sdim 6821218893Sdim // C++ [over.built]p10: 6822218893Sdim // For every promoted integral type T, there exist candidate 6823218893Sdim // operator functions of the form 6824218893Sdim // 6825218893Sdim // T operator~(T); 6826218893Sdim void addUnaryTildePromotedIntegralOverloads() { 6827218893Sdim if (!HasArithmeticOrEnumeralCandidateType) 6828218893Sdim return; 6829218893Sdim 6830198092Srdivacky for (unsigned Int = FirstPromotedIntegralType; 6831193326Sed Int < LastPromotedIntegralType; ++Int) { 6832218893Sdim QualType IntTy = getArithmeticType(Int); 6833251662Sdim S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 6834193326Sed } 6835218893Sdim 6836208600Srdivacky // Extension: We also add this operator for vector types. 6837218893Sdim for (BuiltinCandidateTypeSet::iterator 6838218893Sdim Vec = CandidateTypes[0].vector_begin(), 6839218893Sdim VecEnd = CandidateTypes[0].vector_end(); 6840208600Srdivacky Vec != VecEnd; ++Vec) { 6841208600Srdivacky QualType VecTy = *Vec; 6842251662Sdim S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6843218893Sdim } 6844218893Sdim } 6845193326Sed 6846218893Sdim // C++ [over.match.oper]p16: 6847218893Sdim // For every pointer to member type T, there exist candidate operator 6848218893Sdim // functions of the form 6849218893Sdim // 6850218893Sdim // bool operator==(T,T); 6851218893Sdim // bool operator!=(T,T); 6852218893Sdim void addEqualEqualOrNotEqualMemberPointerOverloads() { 6853218893Sdim /// Set of (canonical) types that we've already handled. 6854218893Sdim llvm::SmallPtrSet<QualType, 8> AddedTypes; 6855193326Sed 6856251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6857218893Sdim for (BuiltinCandidateTypeSet::iterator 6858218893Sdim MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6859218893Sdim MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6860218893Sdim MemPtr != MemPtrEnd; 6861218893Sdim ++MemPtr) { 6862218893Sdim // Don't add the same builtin candidate twice. 6863218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6864218893Sdim continue; 6865193326Sed 6866218893Sdim QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6867251662Sdim S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6868218893Sdim } 6869198092Srdivacky } 6870218893Sdim } 6871198092Srdivacky 6872218893Sdim // C++ [over.built]p15: 6873218893Sdim // 6874223017Sdim // For every T, where T is an enumeration type, a pointer type, or 6875223017Sdim // std::nullptr_t, there exist candidate operator functions of the form 6876218893Sdim // 6877218893Sdim // bool operator<(T, T); 6878218893Sdim // bool operator>(T, T); 6879218893Sdim // bool operator<=(T, T); 6880218893Sdim // bool operator>=(T, T); 6881218893Sdim // bool operator==(T, T); 6882218893Sdim // bool operator!=(T, T); 6883218893Sdim void addRelationalPointerOrEnumeralOverloads() { 6884243830Sdim // C++ [over.match.oper]p3: 6885243830Sdim // [...]the built-in candidates include all of the candidate operator 6886243830Sdim // functions defined in 13.6 that, compared to the given operator, [...] 6887243830Sdim // do not have the same parameter-type-list as any non-template non-member 6888243830Sdim // candidate. 6889218893Sdim // 6890243830Sdim // Note that in practice, this only affects enumeration types because there 6891243830Sdim // aren't any built-in candidates of record type, and a user-defined operator 6892243830Sdim // must have an operand of record or enumeration type. Also, the only other 6893243830Sdim // overloaded operator with enumeration arguments, operator=, 6894218893Sdim // cannot be overloaded for enumeration types, so this is the only place 6895218893Sdim // where we must suppress candidates like this. 6896218893Sdim llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6897218893Sdim UserDefinedBinaryOperators; 6898198092Srdivacky 6899251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6900218893Sdim if (CandidateTypes[ArgIdx].enumeration_begin() != 6901218893Sdim CandidateTypes[ArgIdx].enumeration_end()) { 6902218893Sdim for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6903218893Sdim CEnd = CandidateSet.end(); 6904218893Sdim C != CEnd; ++C) { 6905218893Sdim if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6906218893Sdim continue; 6907218893Sdim 6908243830Sdim if (C->Function->isFunctionTemplateSpecialization()) 6909243830Sdim continue; 6910243830Sdim 6911218893Sdim QualType FirstParamType = 6912218893Sdim C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6913218893Sdim QualType SecondParamType = 6914218893Sdim C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6915218893Sdim 6916218893Sdim // Skip if either parameter isn't of enumeral type. 6917218893Sdim if (!FirstParamType->isEnumeralType() || 6918218893Sdim !SecondParamType->isEnumeralType()) 6919218893Sdim continue; 6920218893Sdim 6921218893Sdim // Add this operator to the set of known user-defined operators. 6922218893Sdim UserDefinedBinaryOperators.insert( 6923218893Sdim std::make_pair(S.Context.getCanonicalType(FirstParamType), 6924218893Sdim S.Context.getCanonicalType(SecondParamType))); 6925218893Sdim } 6926218893Sdim } 6927193326Sed } 6928193326Sed 6929218893Sdim /// Set of (canonical) types that we've already handled. 6930218893Sdim llvm::SmallPtrSet<QualType, 8> AddedTypes; 6931193326Sed 6932251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6933218893Sdim for (BuiltinCandidateTypeSet::iterator 6934218893Sdim Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6935218893Sdim PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6936218893Sdim Ptr != PtrEnd; ++Ptr) { 6937218893Sdim // Don't add the same builtin candidate twice. 6938218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6939218893Sdim continue; 6940193326Sed 6941218893Sdim QualType ParamTypes[2] = { *Ptr, *Ptr }; 6942251662Sdim S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6943218893Sdim } 6944218893Sdim for (BuiltinCandidateTypeSet::iterator 6945218893Sdim Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6946218893Sdim EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6947218893Sdim Enum != EnumEnd; ++Enum) { 6948218893Sdim CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6949193326Sed 6950218893Sdim // Don't add the same builtin candidate twice, or if a user defined 6951218893Sdim // candidate exists. 6952218893Sdim if (!AddedTypes.insert(CanonType) || 6953218893Sdim UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6954218893Sdim CanonType))) 6955218893Sdim continue; 6956193326Sed 6957218893Sdim QualType ParamTypes[2] = { *Enum, *Enum }; 6958251662Sdim S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6959218893Sdim } 6960223017Sdim 6961223017Sdim if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6962223017Sdim CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6963223017Sdim if (AddedTypes.insert(NullPtrTy) && 6964251662Sdim !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6965223017Sdim NullPtrTy))) { 6966223017Sdim QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6967251662Sdim S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 6968223017Sdim CandidateSet); 6969223017Sdim } 6970223017Sdim } 6971218893Sdim } 6972218893Sdim } 6973218893Sdim 6974218893Sdim // C++ [over.built]p13: 6975218893Sdim // 6976218893Sdim // For every cv-qualified or cv-unqualified object type T 6977218893Sdim // there exist candidate operator functions of the form 6978218893Sdim // 6979218893Sdim // T* operator+(T*, ptrdiff_t); 6980218893Sdim // T& operator[](T*, ptrdiff_t); [BELOW] 6981218893Sdim // T* operator-(T*, ptrdiff_t); 6982218893Sdim // T* operator+(ptrdiff_t, T*); 6983218893Sdim // T& operator[](ptrdiff_t, T*); [BELOW] 6984218893Sdim // 6985218893Sdim // C++ [over.built]p14: 6986218893Sdim // 6987218893Sdim // For every T, where T is a pointer to object type, there 6988218893Sdim // exist candidate operator functions of the form 6989218893Sdim // 6990218893Sdim // ptrdiff_t operator-(T, T); 6991218893Sdim void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6992218893Sdim /// Set of (canonical) types that we've already handled. 6993218893Sdim llvm::SmallPtrSet<QualType, 8> AddedTypes; 6994218893Sdim 6995218893Sdim for (int Arg = 0; Arg < 2; ++Arg) { 6996218893Sdim QualType AsymetricParamTypes[2] = { 6997218893Sdim S.Context.getPointerDiffType(), 6998218893Sdim S.Context.getPointerDiffType(), 6999218893Sdim }; 7000218893Sdim for (BuiltinCandidateTypeSet::iterator 7001218893Sdim Ptr = CandidateTypes[Arg].pointer_begin(), 7002218893Sdim PtrEnd = CandidateTypes[Arg].pointer_end(); 7003218893Sdim Ptr != PtrEnd; ++Ptr) { 7004218893Sdim QualType PointeeTy = (*Ptr)->getPointeeType(); 7005218893Sdim if (!PointeeTy->isObjectType()) 7006218893Sdim continue; 7007218893Sdim 7008218893Sdim AsymetricParamTypes[Arg] = *Ptr; 7009218893Sdim if (Arg == 0 || Op == OO_Plus) { 7010218893Sdim // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7011193326Sed // T* operator+(ptrdiff_t, T*); 7012251662Sdim S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7013218893Sdim } 7014218893Sdim if (Op == OO_Minus) { 7015193326Sed // ptrdiff_t operator-(T, T); 7016218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7017218893Sdim continue; 7018218893Sdim 7019218893Sdim QualType ParamTypes[2] = { *Ptr, *Ptr }; 7020218893Sdim S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7021251662Sdim Args, CandidateSet); 7022193326Sed } 7023193326Sed } 7024193326Sed } 7025218893Sdim } 7026193326Sed 7027218893Sdim // C++ [over.built]p12: 7028218893Sdim // 7029218893Sdim // For every pair of promoted arithmetic types L and R, there 7030218893Sdim // exist candidate operator functions of the form 7031218893Sdim // 7032218893Sdim // LR operator*(L, R); 7033218893Sdim // LR operator/(L, R); 7034218893Sdim // LR operator+(L, R); 7035218893Sdim // LR operator-(L, R); 7036218893Sdim // bool operator<(L, R); 7037218893Sdim // bool operator>(L, R); 7038218893Sdim // bool operator<=(L, R); 7039218893Sdim // bool operator>=(L, R); 7040218893Sdim // bool operator==(L, R); 7041218893Sdim // bool operator!=(L, R); 7042218893Sdim // 7043218893Sdim // where LR is the result of the usual arithmetic conversions 7044218893Sdim // between types L and R. 7045218893Sdim // 7046218893Sdim // C++ [over.built]p24: 7047218893Sdim // 7048218893Sdim // For every pair of promoted arithmetic types L and R, there exist 7049218893Sdim // candidate operator functions of the form 7050218893Sdim // 7051218893Sdim // LR operator?(bool, L, R); 7052218893Sdim // 7053218893Sdim // where LR is the result of the usual arithmetic conversions 7054218893Sdim // between types L and R. 7055218893Sdim // Our candidates ignore the first parameter. 7056218893Sdim void addGenericBinaryArithmeticOverloads(bool isComparison) { 7057218893Sdim if (!HasArithmeticOrEnumeralCandidateType) 7058218893Sdim return; 7059218893Sdim 7060198092Srdivacky for (unsigned Left = FirstPromotedArithmeticType; 7061193326Sed Left < LastPromotedArithmeticType; ++Left) { 7062198092Srdivacky for (unsigned Right = FirstPromotedArithmeticType; 7063193326Sed Right < LastPromotedArithmeticType; ++Right) { 7064218893Sdim QualType LandR[2] = { getArithmeticType(Left), 7065218893Sdim getArithmeticType(Right) }; 7066218893Sdim QualType Result = 7067218893Sdim isComparison ? S.Context.BoolTy 7068218893Sdim : getUsualArithmeticConversions(Left, Right); 7069251662Sdim S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7070193326Sed } 7071193326Sed } 7072208600Srdivacky 7073208600Srdivacky // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7074208600Srdivacky // conditional operator for vector types. 7075218893Sdim for (BuiltinCandidateTypeSet::iterator 7076218893Sdim Vec1 = CandidateTypes[0].vector_begin(), 7077218893Sdim Vec1End = CandidateTypes[0].vector_end(); 7078218893Sdim Vec1 != Vec1End; ++Vec1) { 7079218893Sdim for (BuiltinCandidateTypeSet::iterator 7080218893Sdim Vec2 = CandidateTypes[1].vector_begin(), 7081218893Sdim Vec2End = CandidateTypes[1].vector_end(); 7082208600Srdivacky Vec2 != Vec2End; ++Vec2) { 7083208600Srdivacky QualType LandR[2] = { *Vec1, *Vec2 }; 7084218893Sdim QualType Result = S.Context.BoolTy; 7085218893Sdim if (!isComparison) { 7086208600Srdivacky if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7087208600Srdivacky Result = *Vec1; 7088208600Srdivacky else 7089208600Srdivacky Result = *Vec2; 7090208600Srdivacky } 7091218893Sdim 7092251662Sdim S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7093208600Srdivacky } 7094218893Sdim } 7095218893Sdim } 7096193326Sed 7097218893Sdim // C++ [over.built]p17: 7098218893Sdim // 7099218893Sdim // For every pair of promoted integral types L and R, there 7100218893Sdim // exist candidate operator functions of the form 7101218893Sdim // 7102218893Sdim // LR operator%(L, R); 7103218893Sdim // LR operator&(L, R); 7104218893Sdim // LR operator^(L, R); 7105218893Sdim // LR operator|(L, R); 7106218893Sdim // L operator<<(L, R); 7107218893Sdim // L operator>>(L, R); 7108218893Sdim // 7109218893Sdim // where LR is the result of the usual arithmetic conversions 7110218893Sdim // between types L and R. 7111218893Sdim void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7112218893Sdim if (!HasArithmeticOrEnumeralCandidateType) 7113218893Sdim return; 7114218893Sdim 7115198092Srdivacky for (unsigned Left = FirstPromotedIntegralType; 7116193326Sed Left < LastPromotedIntegralType; ++Left) { 7117198092Srdivacky for (unsigned Right = FirstPromotedIntegralType; 7118193326Sed Right < LastPromotedIntegralType; ++Right) { 7119218893Sdim QualType LandR[2] = { getArithmeticType(Left), 7120218893Sdim getArithmeticType(Right) }; 7121193326Sed QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7122193326Sed ? LandR[0] 7123218893Sdim : getUsualArithmeticConversions(Left, Right); 7124251662Sdim S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7125193326Sed } 7126193326Sed } 7127218893Sdim } 7128193326Sed 7129218893Sdim // C++ [over.built]p20: 7130218893Sdim // 7131218893Sdim // For every pair (T, VQ), where T is an enumeration or 7132218893Sdim // pointer to member type and VQ is either volatile or 7133218893Sdim // empty, there exist candidate operator functions of the form 7134218893Sdim // 7135218893Sdim // VQ T& operator=(VQ T&, T); 7136218893Sdim void addAssignmentMemberPointerOrEnumeralOverloads() { 7137218893Sdim /// Set of (canonical) types that we've already handled. 7138218893Sdim llvm::SmallPtrSet<QualType, 8> AddedTypes; 7139218893Sdim 7140218893Sdim for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7141218893Sdim for (BuiltinCandidateTypeSet::iterator 7142218893Sdim Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7143218893Sdim EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7144218893Sdim Enum != EnumEnd; ++Enum) { 7145218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7146218893Sdim continue; 7147218893Sdim 7148251662Sdim AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7149218893Sdim } 7150218893Sdim 7151218893Sdim for (BuiltinCandidateTypeSet::iterator 7152218893Sdim MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7153218893Sdim MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7154218893Sdim MemPtr != MemPtrEnd; ++MemPtr) { 7155218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7156218893Sdim continue; 7157218893Sdim 7158251662Sdim AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7159218893Sdim } 7160218893Sdim } 7161218893Sdim } 7162218893Sdim 7163218893Sdim // C++ [over.built]p19: 7164218893Sdim // 7165218893Sdim // For every pair (T, VQ), where T is any type and VQ is either 7166218893Sdim // volatile or empty, there exist candidate operator functions 7167218893Sdim // of the form 7168218893Sdim // 7169218893Sdim // T*VQ& operator=(T*VQ&, T*); 7170218893Sdim // 7171218893Sdim // C++ [over.built]p21: 7172218893Sdim // 7173218893Sdim // For every pair (T, VQ), where T is a cv-qualified or 7174218893Sdim // cv-unqualified object type and VQ is either volatile or 7175218893Sdim // empty, there exist candidate operator functions of the form 7176218893Sdim // 7177218893Sdim // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7178218893Sdim // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7179218893Sdim void addAssignmentPointerOverloads(bool isEqualOp) { 7180218893Sdim /// Set of (canonical) types that we've already handled. 7181218893Sdim llvm::SmallPtrSet<QualType, 8> AddedTypes; 7182218893Sdim 7183198092Srdivacky for (BuiltinCandidateTypeSet::iterator 7184218893Sdim Ptr = CandidateTypes[0].pointer_begin(), 7185218893Sdim PtrEnd = CandidateTypes[0].pointer_end(); 7186218893Sdim Ptr != PtrEnd; ++Ptr) { 7187218893Sdim // If this is operator=, keep track of the builtin candidates we added. 7188218893Sdim if (isEqualOp) 7189218893Sdim AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7190218893Sdim else if (!(*Ptr)->getPointeeType()->isObjectType()) 7191218893Sdim continue; 7192193326Sed 7193193326Sed // non-volatile version 7194218893Sdim QualType ParamTypes[2] = { 7195218893Sdim S.Context.getLValueReferenceType(*Ptr), 7196218893Sdim isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7197218893Sdim }; 7198251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7199218893Sdim /*IsAssigmentOperator=*/ isEqualOp); 7200193326Sed 7201239462Sdim bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7202239462Sdim VisibleTypeConversionsQuals.hasVolatile(); 7203239462Sdim if (NeedVolatile) { 7204193326Sed // volatile version 7205218893Sdim ParamTypes[0] = 7206218893Sdim S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7207251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7208218893Sdim /*IsAssigmentOperator=*/isEqualOp); 7209193326Sed } 7210239462Sdim 7211239462Sdim if (!(*Ptr).isRestrictQualified() && 7212239462Sdim VisibleTypeConversionsQuals.hasRestrict()) { 7213239462Sdim // restrict version 7214239462Sdim ParamTypes[0] 7215239462Sdim = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7216251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7217239462Sdim /*IsAssigmentOperator=*/isEqualOp); 7218239462Sdim 7219239462Sdim if (NeedVolatile) { 7220239462Sdim // volatile restrict version 7221239462Sdim ParamTypes[0] 7222239462Sdim = S.Context.getLValueReferenceType( 7223239462Sdim S.Context.getCVRQualifiedType(*Ptr, 7224239462Sdim (Qualifiers::Volatile | 7225239462Sdim Qualifiers::Restrict))); 7226251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7227239462Sdim /*IsAssigmentOperator=*/isEqualOp); 7228239462Sdim } 7229239462Sdim } 7230193326Sed } 7231193326Sed 7232218893Sdim if (isEqualOp) { 7233218893Sdim for (BuiltinCandidateTypeSet::iterator 7234218893Sdim Ptr = CandidateTypes[1].pointer_begin(), 7235218893Sdim PtrEnd = CandidateTypes[1].pointer_end(); 7236218893Sdim Ptr != PtrEnd; ++Ptr) { 7237218893Sdim // Make sure we don't add the same candidate twice. 7238218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7239218893Sdim continue; 7240218893Sdim 7241218893Sdim QualType ParamTypes[2] = { 7242218893Sdim S.Context.getLValueReferenceType(*Ptr), 7243218893Sdim *Ptr, 7244218893Sdim }; 7245218893Sdim 7246218893Sdim // non-volatile version 7247251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7248218893Sdim /*IsAssigmentOperator=*/true); 7249218893Sdim 7250239462Sdim bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7251239462Sdim VisibleTypeConversionsQuals.hasVolatile(); 7252239462Sdim if (NeedVolatile) { 7253218893Sdim // volatile version 7254218893Sdim ParamTypes[0] = 7255218893Sdim S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7256251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7257251662Sdim /*IsAssigmentOperator=*/true); 7258218893Sdim } 7259239462Sdim 7260239462Sdim if (!(*Ptr).isRestrictQualified() && 7261239462Sdim VisibleTypeConversionsQuals.hasRestrict()) { 7262239462Sdim // restrict version 7263239462Sdim ParamTypes[0] 7264239462Sdim = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7265251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7266251662Sdim /*IsAssigmentOperator=*/true); 7267239462Sdim 7268239462Sdim if (NeedVolatile) { 7269239462Sdim // volatile restrict version 7270239462Sdim ParamTypes[0] 7271239462Sdim = S.Context.getLValueReferenceType( 7272239462Sdim S.Context.getCVRQualifiedType(*Ptr, 7273239462Sdim (Qualifiers::Volatile | 7274239462Sdim Qualifiers::Restrict))); 7275251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7276251662Sdim /*IsAssigmentOperator=*/true); 7277239462Sdim } 7278239462Sdim } 7279218893Sdim } 7280218893Sdim } 7281218893Sdim } 7282218893Sdim 7283218893Sdim // C++ [over.built]p18: 7284218893Sdim // 7285218893Sdim // For every triple (L, VQ, R), where L is an arithmetic type, 7286218893Sdim // VQ is either volatile or empty, and R is a promoted 7287218893Sdim // arithmetic type, there exist candidate operator functions of 7288218893Sdim // the form 7289218893Sdim // 7290218893Sdim // VQ L& operator=(VQ L&, R); 7291218893Sdim // VQ L& operator*=(VQ L&, R); 7292218893Sdim // VQ L& operator/=(VQ L&, R); 7293218893Sdim // VQ L& operator+=(VQ L&, R); 7294218893Sdim // VQ L& operator-=(VQ L&, R); 7295218893Sdim void addAssignmentArithmeticOverloads(bool isEqualOp) { 7296218893Sdim if (!HasArithmeticOrEnumeralCandidateType) 7297218893Sdim return; 7298218893Sdim 7299193326Sed for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7300198092Srdivacky for (unsigned Right = FirstPromotedArithmeticType; 7301193326Sed Right < LastPromotedArithmeticType; ++Right) { 7302193326Sed QualType ParamTypes[2]; 7303218893Sdim ParamTypes[1] = getArithmeticType(Right); 7304193326Sed 7305193326Sed // Add this built-in operator as a candidate (VQ is empty). 7306218893Sdim ParamTypes[0] = 7307218893Sdim S.Context.getLValueReferenceType(getArithmeticType(Left)); 7308251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7309218893Sdim /*IsAssigmentOperator=*/isEqualOp); 7310193326Sed 7311193326Sed // Add this built-in operator as a candidate (VQ is 'volatile'). 7312198398Srdivacky if (VisibleTypeConversionsQuals.hasVolatile()) { 7313218893Sdim ParamTypes[0] = 7314218893Sdim S.Context.getVolatileType(getArithmeticType(Left)); 7315218893Sdim ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7316251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7317218893Sdim /*IsAssigmentOperator=*/isEqualOp); 7318198398Srdivacky } 7319193326Sed } 7320193326Sed } 7321218893Sdim 7322208600Srdivacky // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7323218893Sdim for (BuiltinCandidateTypeSet::iterator 7324218893Sdim Vec1 = CandidateTypes[0].vector_begin(), 7325218893Sdim Vec1End = CandidateTypes[0].vector_end(); 7326218893Sdim Vec1 != Vec1End; ++Vec1) { 7327218893Sdim for (BuiltinCandidateTypeSet::iterator 7328218893Sdim Vec2 = CandidateTypes[1].vector_begin(), 7329218893Sdim Vec2End = CandidateTypes[1].vector_end(); 7330208600Srdivacky Vec2 != Vec2End; ++Vec2) { 7331208600Srdivacky QualType ParamTypes[2]; 7332208600Srdivacky ParamTypes[1] = *Vec2; 7333208600Srdivacky // Add this built-in operator as a candidate (VQ is empty). 7334218893Sdim ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7335251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7336218893Sdim /*IsAssigmentOperator=*/isEqualOp); 7337218893Sdim 7338208600Srdivacky // Add this built-in operator as a candidate (VQ is 'volatile'). 7339208600Srdivacky if (VisibleTypeConversionsQuals.hasVolatile()) { 7340218893Sdim ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7341218893Sdim ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7342251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7343218893Sdim /*IsAssigmentOperator=*/isEqualOp); 7344208600Srdivacky } 7345208600Srdivacky } 7346218893Sdim } 7347218893Sdim } 7348193326Sed 7349218893Sdim // C++ [over.built]p22: 7350218893Sdim // 7351218893Sdim // For every triple (L, VQ, R), where L is an integral type, VQ 7352218893Sdim // is either volatile or empty, and R is a promoted integral 7353218893Sdim // type, there exist candidate operator functions of the form 7354218893Sdim // 7355218893Sdim // VQ L& operator%=(VQ L&, R); 7356218893Sdim // VQ L& operator<<=(VQ L&, R); 7357218893Sdim // VQ L& operator>>=(VQ L&, R); 7358218893Sdim // VQ L& operator&=(VQ L&, R); 7359218893Sdim // VQ L& operator^=(VQ L&, R); 7360218893Sdim // VQ L& operator|=(VQ L&, R); 7361218893Sdim void addAssignmentIntegralOverloads() { 7362218893Sdim if (!HasArithmeticOrEnumeralCandidateType) 7363218893Sdim return; 7364218893Sdim 7365193326Sed for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7366198092Srdivacky for (unsigned Right = FirstPromotedIntegralType; 7367193326Sed Right < LastPromotedIntegralType; ++Right) { 7368193326Sed QualType ParamTypes[2]; 7369218893Sdim ParamTypes[1] = getArithmeticType(Right); 7370193326Sed 7371193326Sed // Add this built-in operator as a candidate (VQ is empty). 7372218893Sdim ParamTypes[0] = 7373218893Sdim S.Context.getLValueReferenceType(getArithmeticType(Left)); 7374251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7375198398Srdivacky if (VisibleTypeConversionsQuals.hasVolatile()) { 7376198398Srdivacky // Add this built-in operator as a candidate (VQ is 'volatile'). 7377218893Sdim ParamTypes[0] = getArithmeticType(Left); 7378218893Sdim ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7379218893Sdim ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7380251662Sdim S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7381198398Srdivacky } 7382193326Sed } 7383193326Sed } 7384193326Sed } 7385193326Sed 7386218893Sdim // C++ [over.operator]p23: 7387218893Sdim // 7388218893Sdim // There also exist candidate operator functions of the form 7389218893Sdim // 7390218893Sdim // bool operator!(bool); 7391218893Sdim // bool operator&&(bool, bool); 7392218893Sdim // bool operator||(bool, bool); 7393218893Sdim void addExclaimOverload() { 7394218893Sdim QualType ParamTy = S.Context.BoolTy; 7395251662Sdim S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7396218893Sdim /*IsAssignmentOperator=*/false, 7397218893Sdim /*NumContextualBoolArguments=*/1); 7398193326Sed } 7399218893Sdim void addAmpAmpOrPipePipeOverload() { 7400218893Sdim QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7401251662Sdim S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7402218893Sdim /*IsAssignmentOperator=*/false, 7403218893Sdim /*NumContextualBoolArguments=*/2); 7404218893Sdim } 7405193326Sed 7406218893Sdim // C++ [over.built]p13: 7407218893Sdim // 7408218893Sdim // For every cv-qualified or cv-unqualified object type T there 7409218893Sdim // exist candidate operator functions of the form 7410218893Sdim // 7411218893Sdim // T* operator+(T*, ptrdiff_t); [ABOVE] 7412218893Sdim // T& operator[](T*, ptrdiff_t); 7413218893Sdim // T* operator-(T*, ptrdiff_t); [ABOVE] 7414218893Sdim // T* operator+(ptrdiff_t, T*); [ABOVE] 7415218893Sdim // T& operator[](ptrdiff_t, T*); 7416218893Sdim void addSubscriptOverloads() { 7417218893Sdim for (BuiltinCandidateTypeSet::iterator 7418218893Sdim Ptr = CandidateTypes[0].pointer_begin(), 7419218893Sdim PtrEnd = CandidateTypes[0].pointer_end(); 7420218893Sdim Ptr != PtrEnd; ++Ptr) { 7421218893Sdim QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7422212904Sdim QualType PointeeType = (*Ptr)->getPointeeType(); 7423218893Sdim if (!PointeeType->isObjectType()) 7424218893Sdim continue; 7425193326Sed 7426218893Sdim QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7427218893Sdim 7428193326Sed // T& operator[](T*, ptrdiff_t) 7429251662Sdim S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7430218893Sdim } 7431193326Sed 7432218893Sdim for (BuiltinCandidateTypeSet::iterator 7433218893Sdim Ptr = CandidateTypes[1].pointer_begin(), 7434218893Sdim PtrEnd = CandidateTypes[1].pointer_end(); 7435218893Sdim Ptr != PtrEnd; ++Ptr) { 7436218893Sdim QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7437218893Sdim QualType PointeeType = (*Ptr)->getPointeeType(); 7438218893Sdim if (!PointeeType->isObjectType()) 7439218893Sdim continue; 7440193326Sed 7441218893Sdim QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7442218893Sdim 7443218893Sdim // T& operator[](ptrdiff_t, T*) 7444251662Sdim S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7445218893Sdim } 7446218893Sdim } 7447218893Sdim 7448218893Sdim // C++ [over.built]p11: 7449218893Sdim // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7450218893Sdim // C1 is the same type as C2 or is a derived class of C2, T is an object 7451218893Sdim // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7452218893Sdim // there exist candidate operator functions of the form 7453218893Sdim // 7454218893Sdim // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7455218893Sdim // 7456218893Sdim // where CV12 is the union of CV1 and CV2. 7457218893Sdim void addArrowStarOverloads() { 7458218893Sdim for (BuiltinCandidateTypeSet::iterator 7459218893Sdim Ptr = CandidateTypes[0].pointer_begin(), 7460218893Sdim PtrEnd = CandidateTypes[0].pointer_end(); 7461218893Sdim Ptr != PtrEnd; ++Ptr) { 7462218893Sdim QualType C1Ty = (*Ptr); 7463218893Sdim QualType C1; 7464218893Sdim QualifierCollector Q1; 7465218893Sdim C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7466218893Sdim if (!isa<RecordType>(C1)) 7467218893Sdim continue; 7468218893Sdim // heuristic to reduce number of builtin candidates in the set. 7469218893Sdim // Add volatile/restrict version only if there are conversions to a 7470218893Sdim // volatile/restrict type. 7471218893Sdim if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7472218893Sdim continue; 7473218893Sdim if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7474218893Sdim continue; 7475218893Sdim for (BuiltinCandidateTypeSet::iterator 7476218893Sdim MemPtr = CandidateTypes[1].member_pointer_begin(), 7477218893Sdim MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7478218893Sdim MemPtr != MemPtrEnd; ++MemPtr) { 7479218893Sdim const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7480218893Sdim QualType C2 = QualType(mptr->getClass(), 0); 7481218893Sdim C2 = C2.getUnqualifiedType(); 7482218893Sdim if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7483218893Sdim break; 7484218893Sdim QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7485218893Sdim // build CV12 T& 7486218893Sdim QualType T = mptr->getPointeeType(); 7487218893Sdim if (!VisibleTypeConversionsQuals.hasVolatile() && 7488218893Sdim T.isVolatileQualified()) 7489212904Sdim continue; 7490218893Sdim if (!VisibleTypeConversionsQuals.hasRestrict() && 7491218893Sdim T.isRestrictQualified()) 7492212904Sdim continue; 7493218893Sdim T = Q1.apply(S.Context, T); 7494218893Sdim QualType ResultTy = S.Context.getLValueReferenceType(T); 7495251662Sdim S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7496218893Sdim } 7497218893Sdim } 7498218893Sdim } 7499218893Sdim 7500218893Sdim // Note that we don't consider the first argument, since it has been 7501218893Sdim // contextually converted to bool long ago. The candidates below are 7502218893Sdim // therefore added as binary. 7503218893Sdim // 7504218893Sdim // C++ [over.built]p25: 7505218893Sdim // For every type T, where T is a pointer, pointer-to-member, or scoped 7506218893Sdim // enumeration type, there exist candidate operator functions of the form 7507218893Sdim // 7508218893Sdim // T operator?(bool, T, T); 7509218893Sdim // 7510218893Sdim void addConditionalOperatorOverloads() { 7511218893Sdim /// Set of (canonical) types that we've already handled. 7512218893Sdim llvm::SmallPtrSet<QualType, 8> AddedTypes; 7513218893Sdim 7514218893Sdim for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7515218893Sdim for (BuiltinCandidateTypeSet::iterator 7516218893Sdim Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7517218893Sdim PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7518218893Sdim Ptr != PtrEnd; ++Ptr) { 7519218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7520212904Sdim continue; 7521218893Sdim 7522218893Sdim QualType ParamTypes[2] = { *Ptr, *Ptr }; 7523251662Sdim S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7524218893Sdim } 7525218893Sdim 7526218893Sdim for (BuiltinCandidateTypeSet::iterator 7527218893Sdim MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7528218893Sdim MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7529218893Sdim MemPtr != MemPtrEnd; ++MemPtr) { 7530218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7531218893Sdim continue; 7532218893Sdim 7533218893Sdim QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7534251662Sdim S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7535218893Sdim } 7536218893Sdim 7537249423Sdim if (S.getLangOpts().CPlusPlus11) { 7538198092Srdivacky for (BuiltinCandidateTypeSet::iterator 7539218893Sdim Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7540218893Sdim EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7541218893Sdim Enum != EnumEnd; ++Enum) { 7542218893Sdim if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7543198398Srdivacky continue; 7544218893Sdim 7545218893Sdim if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7546198398Srdivacky continue; 7547218893Sdim 7548218893Sdim QualType ParamTypes[2] = { *Enum, *Enum }; 7549251662Sdim S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7550198092Srdivacky } 7551198092Srdivacky } 7552198092Srdivacky } 7553218893Sdim } 7554218893Sdim}; 7555218893Sdim 7556218893Sdim} // end anonymous namespace 7557218893Sdim 7558218893Sdim/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7559218893Sdim/// operator overloads to the candidate set (C++ [over.built]), based 7560218893Sdim/// on the operator @p Op and the arguments given. For example, if the 7561218893Sdim/// operator is a binary '+', this routine might add "int 7562218893Sdim/// operator+(int, int)" to cover integer addition. 7563218893Sdimvoid 7564218893SdimSema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7565218893Sdim SourceLocation OpLoc, 7566251662Sdim llvm::ArrayRef<Expr *> Args, 7567218893Sdim OverloadCandidateSet& CandidateSet) { 7568218893Sdim // Find all of the types that the arguments can convert to, but only 7569218893Sdim // if the operator we're looking at has built-in operator candidates 7570218893Sdim // that make use of these types. Also record whether we encounter non-record 7571218893Sdim // candidate types or either arithmetic or enumeral candidate types. 7572218893Sdim Qualifiers VisibleTypeConversionsQuals; 7573218893Sdim VisibleTypeConversionsQuals.addConst(); 7574251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7575218893Sdim VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7576218893Sdim 7577218893Sdim bool HasNonRecordCandidateType = false; 7578218893Sdim bool HasArithmeticOrEnumeralCandidateType = false; 7579226633Sdim SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7580251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7581218893Sdim CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7582218893Sdim CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7583218893Sdim OpLoc, 7584218893Sdim true, 7585218893Sdim (Op == OO_Exclaim || 7586218893Sdim Op == OO_AmpAmp || 7587218893Sdim Op == OO_PipePipe), 7588218893Sdim VisibleTypeConversionsQuals); 7589218893Sdim HasNonRecordCandidateType = HasNonRecordCandidateType || 7590218893Sdim CandidateTypes[ArgIdx].hasNonRecordTypes(); 7591218893Sdim HasArithmeticOrEnumeralCandidateType = 7592218893Sdim HasArithmeticOrEnumeralCandidateType || 7593218893Sdim CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7594218893Sdim } 7595218893Sdim 7596218893Sdim // Exit early when no non-record types have been added to the candidate set 7597218893Sdim // for any of the arguments to the operator. 7598226633Sdim // 7599226633Sdim // We can't exit early for !, ||, or &&, since there we have always have 7600226633Sdim // 'bool' overloads. 7601251662Sdim if (!HasNonRecordCandidateType && 7602226633Sdim !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7603218893Sdim return; 7604218893Sdim 7605218893Sdim // Setup an object to manage the common state for building overloads. 7606251662Sdim BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7607218893Sdim VisibleTypeConversionsQuals, 7608218893Sdim HasArithmeticOrEnumeralCandidateType, 7609218893Sdim CandidateTypes, CandidateSet); 7610218893Sdim 7611218893Sdim // Dispatch over the operation to add in only those overloads which apply. 7612218893Sdim switch (Op) { 7613218893Sdim case OO_None: 7614218893Sdim case NUM_OVERLOADED_OPERATORS: 7615226633Sdim llvm_unreachable("Expected an overloaded operator"); 7616193326Sed 7617218893Sdim case OO_New: 7618218893Sdim case OO_Delete: 7619218893Sdim case OO_Array_New: 7620218893Sdim case OO_Array_Delete: 7621218893Sdim case OO_Call: 7622226633Sdim llvm_unreachable( 7623226633Sdim "Special operators don't use AddBuiltinOperatorCandidates"); 7624218893Sdim 7625218893Sdim case OO_Comma: 7626218893Sdim case OO_Arrow: 7627218893Sdim // C++ [over.match.oper]p3: 7628218893Sdim // -- For the operator ',', the unary operator '&', or the 7629218893Sdim // operator '->', the built-in candidates set is empty. 7630218893Sdim break; 7631218893Sdim 7632218893Sdim case OO_Plus: // '+' is either unary or binary 7633251662Sdim if (Args.size() == 1) 7634218893Sdim OpBuilder.addUnaryPlusPointerOverloads(); 7635218893Sdim // Fall through. 7636218893Sdim 7637218893Sdim case OO_Minus: // '-' is either unary or binary 7638251662Sdim if (Args.size() == 1) { 7639218893Sdim OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7640218893Sdim } else { 7641218893Sdim OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7642218893Sdim OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7643218893Sdim } 7644218893Sdim break; 7645218893Sdim 7646218893Sdim case OO_Star: // '*' is either unary or binary 7647251662Sdim if (Args.size() == 1) 7648218893Sdim OpBuilder.addUnaryStarPointerOverloads(); 7649218893Sdim else 7650218893Sdim OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7651218893Sdim break; 7652218893Sdim 7653218893Sdim case OO_Slash: 7654218893Sdim OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7655218893Sdim break; 7656218893Sdim 7657218893Sdim case OO_PlusPlus: 7658218893Sdim case OO_MinusMinus: 7659218893Sdim OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7660218893Sdim OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7661218893Sdim break; 7662218893Sdim 7663218893Sdim case OO_EqualEqual: 7664218893Sdim case OO_ExclaimEqual: 7665218893Sdim OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7666218893Sdim // Fall through. 7667218893Sdim 7668218893Sdim case OO_Less: 7669218893Sdim case OO_Greater: 7670218893Sdim case OO_LessEqual: 7671218893Sdim case OO_GreaterEqual: 7672218893Sdim OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7673218893Sdim OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7674218893Sdim break; 7675218893Sdim 7676218893Sdim case OO_Percent: 7677218893Sdim case OO_Caret: 7678218893Sdim case OO_Pipe: 7679218893Sdim case OO_LessLess: 7680218893Sdim case OO_GreaterGreater: 7681218893Sdim OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7682218893Sdim break; 7683218893Sdim 7684218893Sdim case OO_Amp: // '&' is either unary or binary 7685251662Sdim if (Args.size() == 1) 7686218893Sdim // C++ [over.match.oper]p3: 7687218893Sdim // -- For the operator ',', the unary operator '&', or the 7688218893Sdim // operator '->', the built-in candidates set is empty. 7689218893Sdim break; 7690218893Sdim 7691218893Sdim OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7692218893Sdim break; 7693218893Sdim 7694218893Sdim case OO_Tilde: 7695218893Sdim OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7696218893Sdim break; 7697218893Sdim 7698218893Sdim case OO_Equal: 7699218893Sdim OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7700218893Sdim // Fall through. 7701218893Sdim 7702218893Sdim case OO_PlusEqual: 7703218893Sdim case OO_MinusEqual: 7704218893Sdim OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7705218893Sdim // Fall through. 7706218893Sdim 7707218893Sdim case OO_StarEqual: 7708218893Sdim case OO_SlashEqual: 7709218893Sdim OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7710218893Sdim break; 7711218893Sdim 7712218893Sdim case OO_PercentEqual: 7713218893Sdim case OO_LessLessEqual: 7714218893Sdim case OO_GreaterGreaterEqual: 7715218893Sdim case OO_AmpEqual: 7716218893Sdim case OO_CaretEqual: 7717218893Sdim case OO_PipeEqual: 7718218893Sdim OpBuilder.addAssignmentIntegralOverloads(); 7719218893Sdim break; 7720218893Sdim 7721218893Sdim case OO_Exclaim: 7722218893Sdim OpBuilder.addExclaimOverload(); 7723218893Sdim break; 7724218893Sdim 7725218893Sdim case OO_AmpAmp: 7726218893Sdim case OO_PipePipe: 7727218893Sdim OpBuilder.addAmpAmpOrPipePipeOverload(); 7728218893Sdim break; 7729218893Sdim 7730218893Sdim case OO_Subscript: 7731218893Sdim OpBuilder.addSubscriptOverloads(); 7732218893Sdim break; 7733218893Sdim 7734218893Sdim case OO_ArrowStar: 7735218893Sdim OpBuilder.addArrowStarOverloads(); 7736218893Sdim break; 7737218893Sdim 7738193326Sed case OO_Conditional: 7739218893Sdim OpBuilder.addConditionalOperatorOverloads(); 7740218893Sdim OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7741218893Sdim break; 7742193326Sed } 7743193326Sed} 7744193326Sed 7745193326Sed/// \brief Add function candidates found via argument-dependent lookup 7746193326Sed/// to the set of overloading candidates. 7747193326Sed/// 7748193326Sed/// This routine performs argument-dependent name lookup based on the 7749193326Sed/// given function name (which may also be an operator name) and adds 7750193326Sed/// all of the overload candidates found by ADL to the overload 7751193326Sed/// candidate set (C++ [basic.lookup.argdep]). 7752198092Srdivackyvoid 7753193326SedSema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7754234353Sdim bool Operator, SourceLocation Loc, 7755249423Sdim ArrayRef<Expr *> Args, 7756221345Sdim TemplateArgumentListInfo *ExplicitTemplateArgs, 7757198092Srdivacky OverloadCandidateSet& CandidateSet, 7758243830Sdim bool PartialOverloading) { 7759203955Srdivacky ADLResult Fns; 7760193326Sed 7761203955Srdivacky // FIXME: This approach for uniquing ADL results (and removing 7762203955Srdivacky // redundant candidates from the set) relies on pointer-equality, 7763203955Srdivacky // which means we need to key off the canonical decl. However, 7764203955Srdivacky // always going back to the canonical decl might not get us the 7765203955Srdivacky // right set of default arguments. What default arguments are 7766203955Srdivacky // we supposed to consider on ADL candidates, anyway? 7767193326Sed 7768198092Srdivacky // FIXME: Pass in the explicit template arguments? 7769243830Sdim ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7770193326Sed 7771193326Sed // Erase all of the candidates we already knew about. 7772193326Sed for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7773193326Sed CandEnd = CandidateSet.end(); 7774193326Sed Cand != CandEnd; ++Cand) 7775195341Sed if (Cand->Function) { 7776203955Srdivacky Fns.erase(Cand->Function); 7777195341Sed if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7778203955Srdivacky Fns.erase(FunTmpl); 7779195341Sed } 7780193326Sed 7781193326Sed // For each of the ADL candidates we found, add it to the overload 7782193326Sed // set. 7783203955Srdivacky for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7784205408Srdivacky DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7785203955Srdivacky if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7786199990Srdivacky if (ExplicitTemplateArgs) 7787198092Srdivacky continue; 7788218893Sdim 7789234353Sdim AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7790234353Sdim PartialOverloading); 7791198092Srdivacky } else 7792203955Srdivacky AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7793205408Srdivacky FoundDecl, ExplicitTemplateArgs, 7794234353Sdim Args, CandidateSet); 7795195341Sed } 7796193326Sed} 7797193326Sed 7798193326Sed/// isBetterOverloadCandidate - Determines whether the first overload 7799193326Sed/// candidate is a better candidate than the second (C++ 13.3.3p1). 7800198092Srdivackybool 7801212904SdimisBetterOverloadCandidate(Sema &S, 7802218893Sdim const OverloadCandidate &Cand1, 7803218893Sdim const OverloadCandidate &Cand2, 7804218893Sdim SourceLocation Loc, 7805218893Sdim bool UserDefinedConversion) { 7806193326Sed // Define viable functions to be better candidates than non-viable 7807193326Sed // functions. 7808193326Sed if (!Cand2.Viable) 7809193326Sed return Cand1.Viable; 7810193326Sed else if (!Cand1.Viable) 7811193326Sed return false; 7812193326Sed 7813193326Sed // C++ [over.match.best]p1: 7814193326Sed // 7815193326Sed // -- if F is a static member function, ICS1(F) is defined such 7816193326Sed // that ICS1(F) is neither better nor worse than ICS1(G) for 7817193326Sed // any function G, and, symmetrically, ICS1(G) is neither 7818193326Sed // better nor worse than ICS1(F). 7819193326Sed unsigned StartArg = 0; 7820193326Sed if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7821193326Sed StartArg = 1; 7822193326Sed 7823198092Srdivacky // C++ [over.match.best]p1: 7824198092Srdivacky // A viable function F1 is defined to be a better function than another 7825198092Srdivacky // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7826198092Srdivacky // conversion sequence than ICSi(F2), and then... 7827234353Sdim unsigned NumArgs = Cand1.NumConversions; 7828234353Sdim assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7829193326Sed bool HasBetterConversion = false; 7830193326Sed for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7831212904Sdim switch (CompareImplicitConversionSequences(S, 7832212904Sdim Cand1.Conversions[ArgIdx], 7833193326Sed Cand2.Conversions[ArgIdx])) { 7834193326Sed case ImplicitConversionSequence::Better: 7835193326Sed // Cand1 has a better conversion sequence. 7836193326Sed HasBetterConversion = true; 7837193326Sed break; 7838193326Sed 7839193326Sed case ImplicitConversionSequence::Worse: 7840193326Sed // Cand1 can't be better than Cand2. 7841193326Sed return false; 7842193326Sed 7843193326Sed case ImplicitConversionSequence::Indistinguishable: 7844193326Sed // Do nothing. 7845193326Sed break; 7846193326Sed } 7847193326Sed } 7848193326Sed 7849198092Srdivacky // -- for some argument j, ICSj(F1) is a better conversion sequence than 7850198092Srdivacky // ICSj(F2), or, if not that, 7851193326Sed if (HasBetterConversion) 7852193326Sed return true; 7853193326Sed 7854198092Srdivacky // - F1 is a non-template function and F2 is a function template 7855198092Srdivacky // specialization, or, if not that, 7856210299Sed if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7857198092Srdivacky Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7858198092Srdivacky return true; 7859193326Sed 7860198092Srdivacky // -- F1 and F2 are function template specializations, and the function 7861198092Srdivacky // template for F1 is more specialized than the template for F2 7862198092Srdivacky // according to the partial ordering rules described in 14.5.5.2, or, 7863198092Srdivacky // if not that, 7864198092Srdivacky if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7865218893Sdim Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7866198092Srdivacky if (FunctionTemplateDecl *BetterTemplate 7867212904Sdim = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7868212904Sdim Cand2.Function->getPrimaryTemplate(), 7869212904Sdim Loc, 7870218893Sdim isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7871218893Sdim : TPOC_Call, 7872218893Sdim Cand1.ExplicitCallArguments)) 7873198092Srdivacky return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7874218893Sdim } 7875198092Srdivacky 7876193326Sed // -- the context is an initialization by user-defined conversion 7877193326Sed // (see 8.5, 13.3.1.5) and the standard conversion sequence 7878193326Sed // from the return type of F1 to the destination type (i.e., 7879193326Sed // the type of the entity being initialized) is a better 7880193326Sed // conversion sequence than the standard conversion sequence 7881193326Sed // from the return type of F2 to the destination type. 7882218893Sdim if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7883198092Srdivacky isa<CXXConversionDecl>(Cand1.Function) && 7884193326Sed isa<CXXConversionDecl>(Cand2.Function)) { 7885234353Sdim // First check whether we prefer one of the conversion functions over the 7886234353Sdim // other. This only distinguishes the results in non-standard, extension 7887234353Sdim // cases such as the conversion from a lambda closure type to a function 7888234353Sdim // pointer or block. 7889234353Sdim ImplicitConversionSequence::CompareKind FuncResult 7890234353Sdim = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7891234353Sdim if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7892234353Sdim return FuncResult; 7893234353Sdim 7894212904Sdim switch (CompareStandardConversionSequences(S, 7895212904Sdim Cand1.FinalConversion, 7896193326Sed Cand2.FinalConversion)) { 7897193326Sed case ImplicitConversionSequence::Better: 7898193326Sed // Cand1 has a better conversion sequence. 7899193326Sed return true; 7900193326Sed 7901193326Sed case ImplicitConversionSequence::Worse: 7902193326Sed // Cand1 can't be better than Cand2. 7903193326Sed return false; 7904193326Sed 7905193326Sed case ImplicitConversionSequence::Indistinguishable: 7906193326Sed // Do nothing 7907193326Sed break; 7908193326Sed } 7909193326Sed } 7910193326Sed 7911193326Sed return false; 7912193326Sed} 7913193326Sed 7914198092Srdivacky/// \brief Computes the best viable function (C++ 13.3.3) 7915194613Sed/// within an overload candidate set. 7916194613Sed/// 7917239462Sdim/// \param Loc The location of the function name (or operator symbol) for 7918194613Sed/// which overload resolution occurs. 7919194613Sed/// 7920239462Sdim/// \param Best If overload resolution was successful or found a deleted 7921239462Sdim/// function, \p Best points to the candidate function found. 7922194613Sed/// 7923194613Sed/// \returns The result of overload resolution. 7924212904SdimOverloadingResult 7925212904SdimOverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7926218893Sdim iterator &Best, 7927218893Sdim bool UserDefinedConversion) { 7928193326Sed // Find the best viable function. 7929212904Sdim Best = end(); 7930212904Sdim for (iterator Cand = begin(); Cand != end(); ++Cand) { 7931212904Sdim if (Cand->Viable) 7932218893Sdim if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7933218893Sdim UserDefinedConversion)) 7934193326Sed Best = Cand; 7935193326Sed } 7936193326Sed 7937193326Sed // If we didn't find any viable functions, abort. 7938212904Sdim if (Best == end()) 7939193326Sed return OR_No_Viable_Function; 7940193326Sed 7941193326Sed // Make sure that this function is better than every other viable 7942193326Sed // function. If not, we have an ambiguity. 7943212904Sdim for (iterator Cand = begin(); Cand != end(); ++Cand) { 7944198092Srdivacky if (Cand->Viable && 7945193326Sed Cand != Best && 7946218893Sdim !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7947218893Sdim UserDefinedConversion)) { 7948212904Sdim Best = end(); 7949193326Sed return OR_Ambiguous; 7950193326Sed } 7951193326Sed } 7952198092Srdivacky 7953193326Sed // Best is the best viable function. 7954193326Sed if (Best->Function && 7955224145Sdim (Best->Function->isDeleted() || 7956224145Sdim S.isFunctionConsideredUnavailable(Best->Function))) 7957193326Sed return OR_Deleted; 7958193326Sed 7959193326Sed return OR_Success; 7960193326Sed} 7961193326Sed 7962202379Srdivackynamespace { 7963202379Srdivacky 7964202379Srdivackyenum OverloadCandidateKind { 7965202379Srdivacky oc_function, 7966202379Srdivacky oc_method, 7967202379Srdivacky oc_constructor, 7968202379Srdivacky oc_function_template, 7969202379Srdivacky oc_method_template, 7970202379Srdivacky oc_constructor_template, 7971202379Srdivacky oc_implicit_default_constructor, 7972202379Srdivacky oc_implicit_copy_constructor, 7973223017Sdim oc_implicit_move_constructor, 7974218893Sdim oc_implicit_copy_assignment, 7975223017Sdim oc_implicit_move_assignment, 7976218893Sdim oc_implicit_inherited_constructor 7977202379Srdivacky}; 7978202379Srdivacky 7979202379SrdivackyOverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7980202379Srdivacky FunctionDecl *Fn, 7981202379Srdivacky std::string &Description) { 7982202379Srdivacky bool isTemplate = false; 7983202379Srdivacky 7984202379Srdivacky if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7985202379Srdivacky isTemplate = true; 7986202379Srdivacky Description = S.getTemplateArgumentBindingsText( 7987202379Srdivacky FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7988202379Srdivacky } 7989202379Srdivacky 7990202379Srdivacky if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7991202379Srdivacky if (!Ctor->isImplicit()) 7992202379Srdivacky return isTemplate ? oc_constructor_template : oc_constructor; 7993202379Srdivacky 7994218893Sdim if (Ctor->getInheritedConstructor()) 7995218893Sdim return oc_implicit_inherited_constructor; 7996218893Sdim 7997223017Sdim if (Ctor->isDefaultConstructor()) 7998223017Sdim return oc_implicit_default_constructor; 7999223017Sdim 8000223017Sdim if (Ctor->isMoveConstructor()) 8001223017Sdim return oc_implicit_move_constructor; 8002223017Sdim 8003223017Sdim assert(Ctor->isCopyConstructor() && 8004223017Sdim "unexpected sort of implicit constructor"); 8005223017Sdim return oc_implicit_copy_constructor; 8006202379Srdivacky } 8007202379Srdivacky 8008202379Srdivacky if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8009202379Srdivacky // This actually gets spelled 'candidate function' for now, but 8010202379Srdivacky // it doesn't hurt to split it out. 8011202379Srdivacky if (!Meth->isImplicit()) 8012202379Srdivacky return isTemplate ? oc_method_template : oc_method; 8013202379Srdivacky 8014223017Sdim if (Meth->isMoveAssignmentOperator()) 8015223017Sdim return oc_implicit_move_assignment; 8016223017Sdim 8017234353Sdim if (Meth->isCopyAssignmentOperator()) 8018234353Sdim return oc_implicit_copy_assignment; 8019234353Sdim 8020234353Sdim assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8021234353Sdim return oc_method; 8022202379Srdivacky } 8023202379Srdivacky 8024202379Srdivacky return isTemplate ? oc_function_template : oc_function; 8025202379Srdivacky} 8026202379Srdivacky 8027218893Sdimvoid MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 8028218893Sdim const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8029218893Sdim if (!Ctor) return; 8030218893Sdim 8031218893Sdim Ctor = Ctor->getInheritedConstructor(); 8032218893Sdim if (!Ctor) return; 8033218893Sdim 8034218893Sdim S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8035218893Sdim} 8036218893Sdim 8037202379Srdivacky} // end anonymous namespace 8038202379Srdivacky 8039202379Srdivacky// Notes the location of an overload candidate. 8040234353Sdimvoid Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8041202379Srdivacky std::string FnDesc; 8042202379Srdivacky OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8043234353Sdim PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8044234353Sdim << (unsigned) K << FnDesc; 8045234353Sdim HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8046234353Sdim Diag(Fn->getLocation(), PD); 8047218893Sdim MaybeEmitInheritedConstructorNote(*this, Fn); 8048202379Srdivacky} 8049202379Srdivacky 8050218893Sdim//Notes the location of all overload candidates designated through 8051218893Sdim// OverloadedExpr 8052234353Sdimvoid Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8053218893Sdim assert(OverloadedExpr->getType() == Context.OverloadTy); 8054218893Sdim 8055218893Sdim OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8056218893Sdim OverloadExpr *OvlExpr = Ovl.Expression; 8057218893Sdim 8058218893Sdim for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8059218893Sdim IEnd = OvlExpr->decls_end(); 8060218893Sdim I != IEnd; ++I) { 8061218893Sdim if (FunctionTemplateDecl *FunTmpl = 8062218893Sdim dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8063234353Sdim NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8064218893Sdim } else if (FunctionDecl *Fun 8065218893Sdim = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8066234353Sdim NoteOverloadCandidate(Fun, DestType); 8067218893Sdim } 8068218893Sdim } 8069218893Sdim} 8070218893Sdim 8071202379Srdivacky/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8072202379Srdivacky/// "lead" diagnostic; it will be given two arguments, the source and 8073202379Srdivacky/// target types of the conversion. 8074212904Sdimvoid ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8075212904Sdim Sema &S, 8076212904Sdim SourceLocation CaretLoc, 8077212904Sdim const PartialDiagnostic &PDiag) const { 8078212904Sdim S.Diag(CaretLoc, PDiag) 8079212904Sdim << Ambiguous.getFromType() << Ambiguous.getToType(); 8080243830Sdim // FIXME: The note limiting machinery is borrowed from 8081243830Sdim // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8082243830Sdim // refactoring here. 8083243830Sdim const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8084243830Sdim unsigned CandsShown = 0; 8085243830Sdim AmbiguousConversionSequence::const_iterator I, E; 8086243830Sdim for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8087243830Sdim if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8088243830Sdim break; 8089243830Sdim ++CandsShown; 8090212904Sdim S.NoteOverloadCandidate(*I); 8091202379Srdivacky } 8092243830Sdim if (I != E) 8093243830Sdim S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8094202379Srdivacky} 8095202379Srdivacky 8096202379Srdivackynamespace { 8097202379Srdivacky 8098202379Srdivackyvoid DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8099202379Srdivacky const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8100202379Srdivacky assert(Conv.isBad()); 8101202379Srdivacky assert(Cand->Function && "for now, candidate must be a function"); 8102202379Srdivacky FunctionDecl *Fn = Cand->Function; 8103202379Srdivacky 8104202379Srdivacky // There's a conversion slot for the object argument if this is a 8105202379Srdivacky // non-constructor method. Note that 'I' corresponds the 8106202379Srdivacky // conversion-slot index. 8107202379Srdivacky bool isObjectArgument = false; 8108202379Srdivacky if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8109202379Srdivacky if (I == 0) 8110202379Srdivacky isObjectArgument = true; 8111202379Srdivacky else 8112202379Srdivacky I--; 8113202379Srdivacky } 8114202379Srdivacky 8115202379Srdivacky std::string FnDesc; 8116202379Srdivacky OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8117202379Srdivacky 8118202379Srdivacky Expr *FromExpr = Conv.Bad.FromExpr; 8119202379Srdivacky QualType FromTy = Conv.Bad.getFromType(); 8120202379Srdivacky QualType ToTy = Conv.Bad.getToType(); 8121202379Srdivacky 8122203955Srdivacky if (FromTy == S.Context.OverloadTy) { 8123204643Srdivacky assert(FromExpr && "overload set argument came from implicit argument?"); 8124203955Srdivacky Expr *E = FromExpr->IgnoreParens(); 8125203955Srdivacky if (isa<UnaryOperator>(E)) 8126203955Srdivacky E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8127203955Srdivacky DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8128203955Srdivacky 8129203955Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8130203955Srdivacky << (unsigned) FnKind << FnDesc 8131203955Srdivacky << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8132203955Srdivacky << ToTy << Name << I+1; 8133218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8134203955Srdivacky return; 8135203955Srdivacky } 8136203955Srdivacky 8137202879Srdivacky // Do some hand-waving analysis to see if the non-viability is due 8138202879Srdivacky // to a qualifier mismatch. 8139202379Srdivacky CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8140202379Srdivacky CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8141202379Srdivacky if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8142202379Srdivacky CToTy = RT->getPointeeType(); 8143202379Srdivacky else { 8144202379Srdivacky // TODO: detect and diagnose the full richness of const mismatches. 8145202379Srdivacky if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8146202379Srdivacky if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8147202379Srdivacky CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8148202379Srdivacky } 8149202379Srdivacky 8150202379Srdivacky if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8151202379Srdivacky !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8152202379Srdivacky Qualifiers FromQs = CFromTy.getQualifiers(); 8153202379Srdivacky Qualifiers ToQs = CToTy.getQualifiers(); 8154202379Srdivacky 8155202379Srdivacky if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8156202379Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8157202379Srdivacky << (unsigned) FnKind << FnDesc 8158202379Srdivacky << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8159202379Srdivacky << FromTy 8160202379Srdivacky << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8161202379Srdivacky << (unsigned) isObjectArgument << I+1; 8162218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8163202379Srdivacky return; 8164202379Srdivacky } 8165202379Srdivacky 8166224145Sdim if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8167224145Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8168224145Sdim << (unsigned) FnKind << FnDesc 8169224145Sdim << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8170224145Sdim << FromTy 8171224145Sdim << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8172224145Sdim << (unsigned) isObjectArgument << I+1; 8173224145Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8174224145Sdim return; 8175224145Sdim } 8176224145Sdim 8177221345Sdim if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8178221345Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8179221345Sdim << (unsigned) FnKind << FnDesc 8180221345Sdim << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8181221345Sdim << FromTy 8182221345Sdim << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8183221345Sdim << (unsigned) isObjectArgument << I+1; 8184221345Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8185221345Sdim return; 8186221345Sdim } 8187221345Sdim 8188202379Srdivacky unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8189202379Srdivacky assert(CVR && "unexpected qualifiers mismatch"); 8190202379Srdivacky 8191202379Srdivacky if (isObjectArgument) { 8192202379Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8193202379Srdivacky << (unsigned) FnKind << FnDesc 8194202379Srdivacky << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8195202379Srdivacky << FromTy << (CVR - 1); 8196202379Srdivacky } else { 8197202379Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8198202379Srdivacky << (unsigned) FnKind << FnDesc 8199202379Srdivacky << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8200202379Srdivacky << FromTy << (CVR - 1) << I+1; 8201202379Srdivacky } 8202218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8203202379Srdivacky return; 8204202379Srdivacky } 8205202379Srdivacky 8206226633Sdim // Special diagnostic for failure to convert an initializer list, since 8207226633Sdim // telling the user that it has type void is not useful. 8208226633Sdim if (FromExpr && isa<InitListExpr>(FromExpr)) { 8209226633Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8210226633Sdim << (unsigned) FnKind << FnDesc 8211226633Sdim << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8212226633Sdim << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8213226633Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8214226633Sdim return; 8215226633Sdim } 8216226633Sdim 8217202879Srdivacky // Diagnose references or pointers to incomplete types differently, 8218202879Srdivacky // since it's far from impossible that the incompleteness triggered 8219202879Srdivacky // the failure. 8220202879Srdivacky QualType TempFromTy = FromTy.getNonReferenceType(); 8221202879Srdivacky if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8222202879Srdivacky TempFromTy = PTy->getPointeeType(); 8223202879Srdivacky if (TempFromTy->isIncompleteType()) { 8224202879Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8225202879Srdivacky << (unsigned) FnKind << FnDesc 8226202879Srdivacky << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8227202879Srdivacky << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8228218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8229202879Srdivacky return; 8230202879Srdivacky } 8231202879Srdivacky 8232210299Sed // Diagnose base -> derived pointer conversions. 8233210299Sed unsigned BaseToDerivedConversion = 0; 8234210299Sed if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8235210299Sed if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8236210299Sed if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8237210299Sed FromPtrTy->getPointeeType()) && 8238210299Sed !FromPtrTy->getPointeeType()->isIncompleteType() && 8239210299Sed !ToPtrTy->getPointeeType()->isIncompleteType() && 8240218893Sdim S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8241210299Sed FromPtrTy->getPointeeType())) 8242210299Sed BaseToDerivedConversion = 1; 8243210299Sed } 8244210299Sed } else if (const ObjCObjectPointerType *FromPtrTy 8245210299Sed = FromTy->getAs<ObjCObjectPointerType>()) { 8246210299Sed if (const ObjCObjectPointerType *ToPtrTy 8247210299Sed = ToTy->getAs<ObjCObjectPointerType>()) 8248210299Sed if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8249210299Sed if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8250210299Sed if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8251210299Sed FromPtrTy->getPointeeType()) && 8252210299Sed FromIface->isSuperClassOf(ToIface)) 8253210299Sed BaseToDerivedConversion = 2; 8254210299Sed } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8255239462Sdim if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8256239462Sdim !FromTy->isIncompleteType() && 8257239462Sdim !ToRefTy->getPointeeType()->isIncompleteType() && 8258239462Sdim S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8259239462Sdim BaseToDerivedConversion = 3; 8260239462Sdim } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8261239462Sdim ToTy.getNonReferenceType().getCanonicalType() == 8262239462Sdim FromTy.getNonReferenceType().getCanonicalType()) { 8263239462Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8264239462Sdim << (unsigned) FnKind << FnDesc 8265239462Sdim << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8266239462Sdim << (unsigned) isObjectArgument << I + 1; 8267239462Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8268239462Sdim return; 8269210299Sed } 8270239462Sdim } 8271218893Sdim 8272210299Sed if (BaseToDerivedConversion) { 8273218893Sdim S.Diag(Fn->getLocation(), 8274210299Sed diag::note_ovl_candidate_bad_base_to_derived_conv) 8275210299Sed << (unsigned) FnKind << FnDesc 8276210299Sed << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8277210299Sed << (BaseToDerivedConversion - 1) 8278218893Sdim << FromTy << ToTy << I+1; 8279218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8280210299Sed return; 8281210299Sed } 8282218893Sdim 8283226633Sdim if (isa<ObjCObjectPointerType>(CFromTy) && 8284226633Sdim isa<PointerType>(CToTy)) { 8285226633Sdim Qualifiers FromQs = CFromTy.getQualifiers(); 8286226633Sdim Qualifiers ToQs = CToTy.getQualifiers(); 8287226633Sdim if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8288226633Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8289226633Sdim << (unsigned) FnKind << FnDesc 8290226633Sdim << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8291226633Sdim << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8292226633Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8293226633Sdim return; 8294226633Sdim } 8295226633Sdim } 8296226633Sdim 8297226633Sdim // Emit the generic diagnostic and, optionally, add the hints to it. 8298226633Sdim PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8299226633Sdim FDiag << (unsigned) FnKind << FnDesc 8300202379Srdivacky << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8301226633Sdim << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8302226633Sdim << (unsigned) (Cand->Fix.Kind); 8303226633Sdim 8304226633Sdim // If we can fix the conversion, suggest the FixIts. 8305234353Sdim for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8306234353Sdim HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8307226633Sdim FDiag << *HI; 8308226633Sdim S.Diag(Fn->getLocation(), FDiag); 8309226633Sdim 8310218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8311202379Srdivacky} 8312202379Srdivacky 8313202379Srdivackyvoid DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8314202379Srdivacky unsigned NumFormalArgs) { 8315202379Srdivacky // TODO: treat calls to a missing default constructor as a special case 8316202379Srdivacky 8317202379Srdivacky FunctionDecl *Fn = Cand->Function; 8318202379Srdivacky const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8319202379Srdivacky 8320202379Srdivacky unsigned MinParams = Fn->getMinRequiredArguments(); 8321218893Sdim 8322223017Sdim // With invalid overloaded operators, it's possible that we think we 8323223017Sdim // have an arity mismatch when it fact it looks like we have the 8324223017Sdim // right number of arguments, because only overloaded operators have 8325223017Sdim // the weird behavior of overloading member and non-member functions. 8326223017Sdim // Just don't report anything. 8327223017Sdim if (Fn->isInvalidDecl() && 8328223017Sdim Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8329223017Sdim return; 8330223017Sdim 8331202379Srdivacky // at least / at most / exactly 8332202379Srdivacky unsigned mode, modeCount; 8333202379Srdivacky if (NumFormalArgs < MinParams) { 8334208600Srdivacky assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8335208600Srdivacky (Cand->FailureKind == ovl_fail_bad_deduction && 8336208600Srdivacky Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8337218893Sdim if (MinParams != FnTy->getNumArgs() || 8338218893Sdim FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8339202379Srdivacky mode = 0; // "at least" 8340202379Srdivacky else 8341202379Srdivacky mode = 2; // "exactly" 8342202379Srdivacky modeCount = MinParams; 8343202379Srdivacky } else { 8344208600Srdivacky assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8345208600Srdivacky (Cand->FailureKind == ovl_fail_bad_deduction && 8346208600Srdivacky Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8347202379Srdivacky if (MinParams != FnTy->getNumArgs()) 8348202379Srdivacky mode = 1; // "at most" 8349202379Srdivacky else 8350202379Srdivacky mode = 2; // "exactly" 8351202379Srdivacky modeCount = FnTy->getNumArgs(); 8352202379Srdivacky } 8353202379Srdivacky 8354202379Srdivacky std::string Description; 8355202379Srdivacky OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8356202379Srdivacky 8357239462Sdim if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8358239462Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8359239462Sdim << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8360239462Sdim << Fn->getParamDecl(0) << NumFormalArgs; 8361239462Sdim else 8362239462Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8363239462Sdim << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8364239462Sdim << modeCount << NumFormalArgs; 8365218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8366202379Srdivacky} 8367202379Srdivacky 8368203955Srdivacky/// Diagnose a failed template-argument deduction. 8369203955Srdivackyvoid DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8370234353Sdim unsigned NumArgs) { 8371203955Srdivacky FunctionDecl *Fn = Cand->Function; // pattern 8372203955Srdivacky 8373208600Srdivacky TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8374208600Srdivacky NamedDecl *ParamD; 8375208600Srdivacky (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8376208600Srdivacky (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8377208600Srdivacky (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8378203955Srdivacky switch (Cand->DeductionFailure.Result) { 8379203955Srdivacky case Sema::TDK_Success: 8380203955Srdivacky llvm_unreachable("TDK_success while diagnosing bad deduction"); 8381203955Srdivacky 8382203955Srdivacky case Sema::TDK_Incomplete: { 8383203955Srdivacky assert(ParamD && "no parameter found for incomplete deduction result"); 8384203955Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8385203955Srdivacky << ParamD->getDeclName(); 8386218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8387203955Srdivacky return; 8388203955Srdivacky } 8389203955Srdivacky 8390212904Sdim case Sema::TDK_Underqualified: { 8391212904Sdim assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8392212904Sdim TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8393212904Sdim 8394212904Sdim QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8395212904Sdim 8396212904Sdim // Param will have been canonicalized, but it should just be a 8397212904Sdim // qualified version of ParamD, so move the qualifiers to that. 8398218893Sdim QualifierCollector Qs; 8399212904Sdim Qs.strip(Param); 8400218893Sdim QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8401212904Sdim assert(S.Context.hasSameType(Param, NonCanonParam)); 8402212904Sdim 8403212904Sdim // Arg has also been canonicalized, but there's nothing we can do 8404212904Sdim // about that. It also doesn't matter as much, because it won't 8405212904Sdim // have any template parameters in it (because deduction isn't 8406212904Sdim // done on dependent types). 8407212904Sdim QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8408212904Sdim 8409212904Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8410212904Sdim << ParamD->getDeclName() << Arg << NonCanonParam; 8411218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8412212904Sdim return; 8413212904Sdim } 8414212904Sdim 8415212904Sdim case Sema::TDK_Inconsistent: { 8416218893Sdim assert(ParamD && "no parameter found for inconsistent deduction result"); 8417208600Srdivacky int which = 0; 8418208600Srdivacky if (isa<TemplateTypeParmDecl>(ParamD)) 8419208600Srdivacky which = 0; 8420208600Srdivacky else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8421208600Srdivacky which = 1; 8422208600Srdivacky else { 8423208600Srdivacky which = 2; 8424208600Srdivacky } 8425218893Sdim 8426208600Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8427218893Sdim << which << ParamD->getDeclName() 8428208600Srdivacky << *Cand->DeductionFailure.getFirstArg() 8429208600Srdivacky << *Cand->DeductionFailure.getSecondArg(); 8430218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8431208600Srdivacky return; 8432208600Srdivacky } 8433208600Srdivacky 8434208600Srdivacky case Sema::TDK_InvalidExplicitArguments: 8435218893Sdim assert(ParamD && "no parameter found for invalid explicit arguments"); 8436208600Srdivacky if (ParamD->getDeclName()) 8437218893Sdim S.Diag(Fn->getLocation(), 8438208600Srdivacky diag::note_ovl_candidate_explicit_arg_mismatch_named) 8439208600Srdivacky << ParamD->getDeclName(); 8440208600Srdivacky else { 8441208600Srdivacky int index = 0; 8442208600Srdivacky if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8443208600Srdivacky index = TTP->getIndex(); 8444208600Srdivacky else if (NonTypeTemplateParmDecl *NTTP 8445208600Srdivacky = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8446208600Srdivacky index = NTTP->getIndex(); 8447208600Srdivacky else 8448208600Srdivacky index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8449218893Sdim S.Diag(Fn->getLocation(), 8450208600Srdivacky diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8451208600Srdivacky << (index + 1); 8452208600Srdivacky } 8453218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8454208600Srdivacky return; 8455218893Sdim 8456208600Srdivacky case Sema::TDK_TooManyArguments: 8457208600Srdivacky case Sema::TDK_TooFewArguments: 8458208600Srdivacky DiagnoseArityMismatch(S, Cand, NumArgs); 8459208600Srdivacky return; 8460208600Srdivacky 8461208600Srdivacky case Sema::TDK_InstantiationDepth: 8462208600Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8463218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8464208600Srdivacky return; 8465208600Srdivacky 8466208600Srdivacky case Sema::TDK_SubstitutionFailure: { 8467239462Sdim // Format the template argument list into the argument string. 8468249423Sdim SmallString<128> TemplateArgString; 8469239462Sdim if (TemplateArgumentList *Args = 8470239462Sdim Cand->DeductionFailure.getTemplateArgumentList()) { 8471239462Sdim TemplateArgString = " "; 8472239462Sdim TemplateArgString += S.getTemplateArgumentBindingsText( 8473239462Sdim Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8474239462Sdim } 8475239462Sdim 8476239462Sdim // If this candidate was disabled by enable_if, say so. 8477239462Sdim PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8478239462Sdim if (PDiag && PDiag->second.getDiagID() == 8479239462Sdim diag::err_typename_nested_not_found_enable_if) { 8480239462Sdim // FIXME: Use the source range of the condition, and the fully-qualified 8481239462Sdim // name of the enable_if template. These are both present in PDiag. 8482239462Sdim S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8483239462Sdim << "'enable_if'" << TemplateArgString; 8484239462Sdim return; 8485239462Sdim } 8486239462Sdim 8487239462Sdim // Format the SFINAE diagnostic into the argument string. 8488239462Sdim // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8489239462Sdim // formatted message in another diagnostic. 8490249423Sdim SmallString<128> SFINAEArgString; 8491239462Sdim SourceRange R; 8492239462Sdim if (PDiag) { 8493239462Sdim SFINAEArgString = ": "; 8494239462Sdim R = SourceRange(PDiag->first, PDiag->first); 8495239462Sdim PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8496239462Sdim } 8497239462Sdim 8498208600Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8499239462Sdim << TemplateArgString << SFINAEArgString << R; 8500218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8501208600Srdivacky return; 8502208600Srdivacky } 8503218893Sdim 8504249423Sdim case Sema::TDK_FailedOverloadResolution: { 8505249423Sdim OverloadExpr::FindResult R = 8506249423Sdim OverloadExpr::find(Cand->DeductionFailure.getExpr()); 8507249423Sdim S.Diag(Fn->getLocation(), 8508249423Sdim diag::note_ovl_candidate_failed_overload_resolution) 8509249423Sdim << R.Expression->getName(); 8510249423Sdim return; 8511249423Sdim } 8512249423Sdim 8513251662Sdim case Sema::TDK_NonDeducedMismatch: { 8514249423Sdim // FIXME: Provide a source location to indicate what we couldn't match. 8515251662Sdim TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg(); 8516251662Sdim TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg(); 8517251662Sdim if (FirstTA.getKind() == TemplateArgument::Template && 8518251662Sdim SecondTA.getKind() == TemplateArgument::Template) { 8519251662Sdim TemplateName FirstTN = FirstTA.getAsTemplate(); 8520251662Sdim TemplateName SecondTN = SecondTA.getAsTemplate(); 8521251662Sdim if (FirstTN.getKind() == TemplateName::Template && 8522251662Sdim SecondTN.getKind() == TemplateName::Template) { 8523251662Sdim if (FirstTN.getAsTemplateDecl()->getName() == 8524251662Sdim SecondTN.getAsTemplateDecl()->getName()) { 8525251662Sdim // FIXME: This fixes a bad diagnostic where both templates are named 8526251662Sdim // the same. This particular case is a bit difficult since: 8527251662Sdim // 1) It is passed as a string to the diagnostic printer. 8528251662Sdim // 2) The diagnostic printer only attempts to find a better 8529251662Sdim // name for types, not decls. 8530251662Sdim // Ideally, this should folded into the diagnostic printer. 8531251662Sdim S.Diag(Fn->getLocation(), 8532251662Sdim diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8533251662Sdim << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8534251662Sdim return; 8535251662Sdim } 8536251662Sdim } 8537251662Sdim } 8538249423Sdim S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch) 8539251662Sdim << FirstTA << SecondTA; 8540249423Sdim return; 8541251662Sdim } 8542203955Srdivacky // TODO: diagnose these individually, then kill off 8543203955Srdivacky // note_ovl_candidate_bad_deduction, which is uselessly vague. 8544249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 8545203955Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8546218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8547203955Srdivacky return; 8548203955Srdivacky } 8549203955Srdivacky} 8550203955Srdivacky 8551226633Sdim/// CUDA: diagnose an invalid call across targets. 8552226633Sdimvoid DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8553226633Sdim FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8554226633Sdim FunctionDecl *Callee = Cand->Function; 8555226633Sdim 8556226633Sdim Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8557226633Sdim CalleeTarget = S.IdentifyCUDATarget(Callee); 8558226633Sdim 8559226633Sdim std::string FnDesc; 8560226633Sdim OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8561226633Sdim 8562226633Sdim S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8563226633Sdim << (unsigned) FnKind << CalleeTarget << CallerTarget; 8564226633Sdim} 8565226633Sdim 8566203955Srdivacky/// Generates a 'note' diagnostic for an overload candidate. We've 8567203955Srdivacky/// already generated a primary error at the call site. 8568203955Srdivacky/// 8569203955Srdivacky/// It really does need to be a single diagnostic with its caret 8570203955Srdivacky/// pointed at the candidate declaration. Yes, this creates some 8571203955Srdivacky/// major challenges of technical writing. Yes, this makes pointing 8572203955Srdivacky/// out problems with specific arguments quite awkward. It's still 8573203955Srdivacky/// better than generating twenty screens of text for every failed 8574203955Srdivacky/// overload. 8575203955Srdivacky/// 8576203955Srdivacky/// It would be great to be able to express per-candidate problems 8577203955Srdivacky/// more richly for those diagnostic clients that cared, but we'd 8578203955Srdivacky/// still have to be just as careful with the default diagnostics. 8579202379Srdivackyvoid NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8580234353Sdim unsigned NumArgs) { 8581202379Srdivacky FunctionDecl *Fn = Cand->Function; 8582202379Srdivacky 8583202379Srdivacky // Note deleted candidates, but only if they're viable. 8584224145Sdim if (Cand->Viable && (Fn->isDeleted() || 8585224145Sdim S.isFunctionConsideredUnavailable(Fn))) { 8586202379Srdivacky std::string FnDesc; 8587202379Srdivacky OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8588202379Srdivacky 8589202379Srdivacky S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8590234353Sdim << FnKind << FnDesc 8591234353Sdim << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8592218893Sdim MaybeEmitInheritedConstructorNote(S, Fn); 8593202379Srdivacky return; 8594202379Srdivacky } 8595202379Srdivacky 8596202379Srdivacky // We don't really have anything else to say about viable candidates. 8597202379Srdivacky if (Cand->Viable) { 8598202379Srdivacky S.NoteOverloadCandidate(Fn); 8599202379Srdivacky return; 8600202379Srdivacky } 8601202379Srdivacky 8602202379Srdivacky switch (Cand->FailureKind) { 8603202379Srdivacky case ovl_fail_too_many_arguments: 8604202379Srdivacky case ovl_fail_too_few_arguments: 8605202379Srdivacky return DiagnoseArityMismatch(S, Cand, NumArgs); 8606202379Srdivacky 8607202379Srdivacky case ovl_fail_bad_deduction: 8608234353Sdim return DiagnoseBadDeduction(S, Cand, NumArgs); 8609203955Srdivacky 8610202879Srdivacky case ovl_fail_trivial_conversion: 8611202879Srdivacky case ovl_fail_bad_final_conversion: 8612207619Srdivacky case ovl_fail_final_conversion_not_exact: 8613202379Srdivacky return S.NoteOverloadCandidate(Fn); 8614202379Srdivacky 8615204643Srdivacky case ovl_fail_bad_conversion: { 8616204643Srdivacky unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8617234353Sdim for (unsigned N = Cand->NumConversions; I != N; ++I) 8618202379Srdivacky if (Cand->Conversions[I].isBad()) 8619202379Srdivacky return DiagnoseBadConversion(S, Cand, I); 8620218893Sdim 8621202379Srdivacky // FIXME: this currently happens when we're called from SemaInit 8622202379Srdivacky // when user-conversion overload fails. Figure out how to handle 8623202379Srdivacky // those conditions and diagnose them well. 8624202379Srdivacky return S.NoteOverloadCandidate(Fn); 8625202379Srdivacky } 8626226633Sdim 8627226633Sdim case ovl_fail_bad_target: 8628226633Sdim return DiagnoseBadTarget(S, Cand); 8629204643Srdivacky } 8630202379Srdivacky} 8631202379Srdivacky 8632202379Srdivackyvoid NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8633202379Srdivacky // Desugar the type of the surrogate down to a function type, 8634202379Srdivacky // retaining as many typedefs as possible while still showing 8635202379Srdivacky // the function type (and, therefore, its parameter types). 8636202379Srdivacky QualType FnType = Cand->Surrogate->getConversionType(); 8637202379Srdivacky bool isLValueReference = false; 8638202379Srdivacky bool isRValueReference = false; 8639202379Srdivacky bool isPointer = false; 8640202379Srdivacky if (const LValueReferenceType *FnTypeRef = 8641202379Srdivacky FnType->getAs<LValueReferenceType>()) { 8642202379Srdivacky FnType = FnTypeRef->getPointeeType(); 8643202379Srdivacky isLValueReference = true; 8644202379Srdivacky } else if (const RValueReferenceType *FnTypeRef = 8645202379Srdivacky FnType->getAs<RValueReferenceType>()) { 8646202379Srdivacky FnType = FnTypeRef->getPointeeType(); 8647202379Srdivacky isRValueReference = true; 8648202379Srdivacky } 8649202379Srdivacky if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8650202379Srdivacky FnType = FnTypePtr->getPointeeType(); 8651202379Srdivacky isPointer = true; 8652202379Srdivacky } 8653202379Srdivacky // Desugar down to a function type. 8654202379Srdivacky FnType = QualType(FnType->getAs<FunctionType>(), 0); 8655202379Srdivacky // Reconstruct the pointer/reference as appropriate. 8656202379Srdivacky if (isPointer) FnType = S.Context.getPointerType(FnType); 8657202379Srdivacky if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8658202379Srdivacky if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8659202379Srdivacky 8660202379Srdivacky S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8661202379Srdivacky << FnType; 8662218893Sdim MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8663202379Srdivacky} 8664202379Srdivacky 8665202379Srdivackyvoid NoteBuiltinOperatorCandidate(Sema &S, 8666243830Sdim StringRef Opc, 8667202379Srdivacky SourceLocation OpLoc, 8668202379Srdivacky OverloadCandidate *Cand) { 8669234353Sdim assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8670202379Srdivacky std::string TypeStr("operator"); 8671202379Srdivacky TypeStr += Opc; 8672202379Srdivacky TypeStr += "("; 8673202379Srdivacky TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8674234353Sdim if (Cand->NumConversions == 1) { 8675202379Srdivacky TypeStr += ")"; 8676202379Srdivacky S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8677202379Srdivacky } else { 8678202379Srdivacky TypeStr += ", "; 8679202379Srdivacky TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8680202379Srdivacky TypeStr += ")"; 8681202379Srdivacky S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8682202379Srdivacky } 8683202379Srdivacky} 8684202379Srdivacky 8685202379Srdivackyvoid NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8686202379Srdivacky OverloadCandidate *Cand) { 8687234353Sdim unsigned NoOperands = Cand->NumConversions; 8688202379Srdivacky for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8689202379Srdivacky const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8690202379Srdivacky if (ICS.isBad()) break; // all meaningless after first invalid 8691202379Srdivacky if (!ICS.isAmbiguous()) continue; 8692202379Srdivacky 8693212904Sdim ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8694206084Srdivacky S.PDiag(diag::note_ambiguous_type_conversion)); 8695202379Srdivacky } 8696202379Srdivacky} 8697202379Srdivacky 8698202879SrdivackySourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8699202879Srdivacky if (Cand->Function) 8700202879Srdivacky return Cand->Function->getLocation(); 8701202879Srdivacky if (Cand->IsSurrogate) 8702202879Srdivacky return Cand->Surrogate->getLocation(); 8703202879Srdivacky return SourceLocation(); 8704202879Srdivacky} 8705202879Srdivacky 8706226633Sdimstatic unsigned 8707226633SdimRankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8708226633Sdim switch ((Sema::TemplateDeductionResult)DFI.Result) { 8709226633Sdim case Sema::TDK_Success: 8710226633Sdim llvm_unreachable("TDK_success while diagnosing bad deduction"); 8711226633Sdim 8712243830Sdim case Sema::TDK_Invalid: 8713226633Sdim case Sema::TDK_Incomplete: 8714226633Sdim return 1; 8715226633Sdim 8716226633Sdim case Sema::TDK_Underqualified: 8717226633Sdim case Sema::TDK_Inconsistent: 8718226633Sdim return 2; 8719226633Sdim 8720226633Sdim case Sema::TDK_SubstitutionFailure: 8721226633Sdim case Sema::TDK_NonDeducedMismatch: 8722249423Sdim case Sema::TDK_MiscellaneousDeductionFailure: 8723226633Sdim return 3; 8724226633Sdim 8725226633Sdim case Sema::TDK_InstantiationDepth: 8726226633Sdim case Sema::TDK_FailedOverloadResolution: 8727226633Sdim return 4; 8728226633Sdim 8729226633Sdim case Sema::TDK_InvalidExplicitArguments: 8730226633Sdim return 5; 8731226633Sdim 8732226633Sdim case Sema::TDK_TooManyArguments: 8733226633Sdim case Sema::TDK_TooFewArguments: 8734226633Sdim return 6; 8735226633Sdim } 8736226633Sdim llvm_unreachable("Unhandled deduction result"); 8737226633Sdim} 8738226633Sdim 8739202379Srdivackystruct CompareOverloadCandidatesForDisplay { 8740202379Srdivacky Sema &S; 8741202379Srdivacky CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8742202379Srdivacky 8743202379Srdivacky bool operator()(const OverloadCandidate *L, 8744202379Srdivacky const OverloadCandidate *R) { 8745202879Srdivacky // Fast-path this check. 8746202879Srdivacky if (L == R) return false; 8747202879Srdivacky 8748202379Srdivacky // Order first by viability. 8749202379Srdivacky if (L->Viable) { 8750202379Srdivacky if (!R->Viable) return true; 8751202379Srdivacky 8752202379Srdivacky // TODO: introduce a tri-valued comparison for overload 8753202379Srdivacky // candidates. Would be more worthwhile if we had a sort 8754202379Srdivacky // that could exploit it. 8755212904Sdim if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8756212904Sdim if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8757202379Srdivacky } else if (R->Viable) 8758202379Srdivacky return false; 8759202379Srdivacky 8760202879Srdivacky assert(L->Viable == R->Viable); 8761202379Srdivacky 8762202879Srdivacky // Criteria by which we can sort non-viable candidates: 8763202879Srdivacky if (!L->Viable) { 8764202879Srdivacky // 1. Arity mismatches come after other candidates. 8765202879Srdivacky if (L->FailureKind == ovl_fail_too_many_arguments || 8766202879Srdivacky L->FailureKind == ovl_fail_too_few_arguments) 8767202879Srdivacky return false; 8768202879Srdivacky if (R->FailureKind == ovl_fail_too_many_arguments || 8769202879Srdivacky R->FailureKind == ovl_fail_too_few_arguments) 8770202879Srdivacky return true; 8771202379Srdivacky 8772202879Srdivacky // 2. Bad conversions come first and are ordered by the number 8773202879Srdivacky // of bad conversions and quality of good conversions. 8774202879Srdivacky if (L->FailureKind == ovl_fail_bad_conversion) { 8775202879Srdivacky if (R->FailureKind != ovl_fail_bad_conversion) 8776202879Srdivacky return true; 8777202879Srdivacky 8778226633Sdim // The conversion that can be fixed with a smaller number of changes, 8779226633Sdim // comes first. 8780226633Sdim unsigned numLFixes = L->Fix.NumConversionsFixed; 8781226633Sdim unsigned numRFixes = R->Fix.NumConversionsFixed; 8782226633Sdim numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8783226633Sdim numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8784226633Sdim if (numLFixes != numRFixes) { 8785226633Sdim if (numLFixes < numRFixes) 8786226633Sdim return true; 8787226633Sdim else 8788226633Sdim return false; 8789226633Sdim } 8790226633Sdim 8791202879Srdivacky // If there's any ordering between the defined conversions... 8792202879Srdivacky // FIXME: this might not be transitive. 8793234353Sdim assert(L->NumConversions == R->NumConversions); 8794202879Srdivacky 8795202879Srdivacky int leftBetter = 0; 8796204643Srdivacky unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8797234353Sdim for (unsigned E = L->NumConversions; I != E; ++I) { 8798212904Sdim switch (CompareImplicitConversionSequences(S, 8799212904Sdim L->Conversions[I], 8800212904Sdim R->Conversions[I])) { 8801202879Srdivacky case ImplicitConversionSequence::Better: 8802202879Srdivacky leftBetter++; 8803202879Srdivacky break; 8804202879Srdivacky 8805202879Srdivacky case ImplicitConversionSequence::Worse: 8806202879Srdivacky leftBetter--; 8807202879Srdivacky break; 8808202879Srdivacky 8809202879Srdivacky case ImplicitConversionSequence::Indistinguishable: 8810202879Srdivacky break; 8811202879Srdivacky } 8812202879Srdivacky } 8813202879Srdivacky if (leftBetter > 0) return true; 8814202879Srdivacky if (leftBetter < 0) return false; 8815202879Srdivacky 8816202879Srdivacky } else if (R->FailureKind == ovl_fail_bad_conversion) 8817202879Srdivacky return false; 8818202879Srdivacky 8819226633Sdim if (L->FailureKind == ovl_fail_bad_deduction) { 8820226633Sdim if (R->FailureKind != ovl_fail_bad_deduction) 8821226633Sdim return true; 8822226633Sdim 8823226633Sdim if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8824226633Sdim return RankDeductionFailure(L->DeductionFailure) 8825226633Sdim < RankDeductionFailure(R->DeductionFailure); 8826226633Sdim } else if (R->FailureKind == ovl_fail_bad_deduction) 8827226633Sdim return false; 8828226633Sdim 8829202879Srdivacky // TODO: others? 8830202879Srdivacky } 8831202879Srdivacky 8832202879Srdivacky // Sort everything else by location. 8833202879Srdivacky SourceLocation LLoc = GetLocationForCandidate(L); 8834202879Srdivacky SourceLocation RLoc = GetLocationForCandidate(R); 8835202879Srdivacky 8836202879Srdivacky // Put candidates without locations (e.g. builtins) at the end. 8837202879Srdivacky if (LLoc.isInvalid()) return false; 8838202879Srdivacky if (RLoc.isInvalid()) return true; 8839202879Srdivacky 8840202879Srdivacky return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8841202379Srdivacky } 8842202379Srdivacky}; 8843202379Srdivacky 8844202879Srdivacky/// CompleteNonViableCandidate - Normally, overload resolution only 8845226633Sdim/// computes up to the first. Produces the FixIt set if possible. 8846202879Srdivackyvoid CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8847249423Sdim ArrayRef<Expr *> Args) { 8848202879Srdivacky assert(!Cand->Viable); 8849202879Srdivacky 8850202879Srdivacky // Don't do anything on failures other than bad conversion. 8851202879Srdivacky if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8852202879Srdivacky 8853226633Sdim // We only want the FixIts if all the arguments can be corrected. 8854226633Sdim bool Unfixable = false; 8855226633Sdim // Use a implicit copy initialization to check conversion fixes. 8856226633Sdim Cand->Fix.setConversionChecker(TryCopyInitialization); 8857226633Sdim 8858202879Srdivacky // Skip forward to the first bad conversion. 8859204643Srdivacky unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8860234353Sdim unsigned ConvCount = Cand->NumConversions; 8861202879Srdivacky while (true) { 8862202879Srdivacky assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8863202879Srdivacky ConvIdx++; 8864226633Sdim if (Cand->Conversions[ConvIdx - 1].isBad()) { 8865226633Sdim Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8866202879Srdivacky break; 8867226633Sdim } 8868202879Srdivacky } 8869202879Srdivacky 8870202879Srdivacky if (ConvIdx == ConvCount) 8871202879Srdivacky return; 8872202879Srdivacky 8873204643Srdivacky assert(!Cand->Conversions[ConvIdx].isInitialized() && 8874204643Srdivacky "remaining conversion is initialized?"); 8875204643Srdivacky 8876207619Srdivacky // FIXME: this should probably be preserved from the overload 8877202879Srdivacky // operation somehow. 8878202879Srdivacky bool SuppressUserConversions = false; 8879202879Srdivacky 8880202879Srdivacky const FunctionProtoType* Proto; 8881202879Srdivacky unsigned ArgIdx = ConvIdx; 8882202879Srdivacky 8883202879Srdivacky if (Cand->IsSurrogate) { 8884202879Srdivacky QualType ConvType 8885202879Srdivacky = Cand->Surrogate->getConversionType().getNonReferenceType(); 8886202879Srdivacky if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8887202879Srdivacky ConvType = ConvPtrType->getPointeeType(); 8888202879Srdivacky Proto = ConvType->getAs<FunctionProtoType>(); 8889202879Srdivacky ArgIdx--; 8890202879Srdivacky } else if (Cand->Function) { 8891202879Srdivacky Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8892202879Srdivacky if (isa<CXXMethodDecl>(Cand->Function) && 8893202879Srdivacky !isa<CXXConstructorDecl>(Cand->Function)) 8894202879Srdivacky ArgIdx--; 8895202879Srdivacky } else { 8896202879Srdivacky // Builtin binary operator with a bad first conversion. 8897202879Srdivacky assert(ConvCount <= 3); 8898202879Srdivacky for (; ConvIdx != ConvCount; ++ConvIdx) 8899202879Srdivacky Cand->Conversions[ConvIdx] 8900207619Srdivacky = TryCopyInitialization(S, Args[ConvIdx], 8901207619Srdivacky Cand->BuiltinTypes.ParamTypes[ConvIdx], 8902218893Sdim SuppressUserConversions, 8903224145Sdim /*InOverloadResolution*/ true, 8904224145Sdim /*AllowObjCWritebackConversion=*/ 8905234353Sdim S.getLangOpts().ObjCAutoRefCount); 8906202879Srdivacky return; 8907202879Srdivacky } 8908202879Srdivacky 8909202879Srdivacky // Fill in the rest of the conversions. 8910202879Srdivacky unsigned NumArgsInProto = Proto->getNumArgs(); 8911202879Srdivacky for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8912226633Sdim if (ArgIdx < NumArgsInProto) { 8913202879Srdivacky Cand->Conversions[ConvIdx] 8914207619Srdivacky = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8915218893Sdim SuppressUserConversions, 8916224145Sdim /*InOverloadResolution=*/true, 8917224145Sdim /*AllowObjCWritebackConversion=*/ 8918234353Sdim S.getLangOpts().ObjCAutoRefCount); 8919226633Sdim // Store the FixIt in the candidate if it exists. 8920226633Sdim if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8921226633Sdim Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8922226633Sdim } 8923202879Srdivacky else 8924202879Srdivacky Cand->Conversions[ConvIdx].setEllipsis(); 8925202879Srdivacky } 8926202879Srdivacky} 8927202879Srdivacky 8928202379Srdivacky} // end anonymous namespace 8929202379Srdivacky 8930193326Sed/// PrintOverloadCandidates - When overload resolution fails, prints 8931193326Sed/// diagnostic messages containing the candidates in the candidate 8932202379Srdivacky/// set. 8933212904Sdimvoid OverloadCandidateSet::NoteCandidates(Sema &S, 8934212904Sdim OverloadCandidateDisplayKind OCD, 8935249423Sdim ArrayRef<Expr *> Args, 8936243830Sdim StringRef Opc, 8937212904Sdim SourceLocation OpLoc) { 8938202379Srdivacky // Sort the candidates by viability and position. Sorting directly would 8939202379Srdivacky // be prohibitive, so we make a set of pointers and sort those. 8940226633Sdim SmallVector<OverloadCandidate*, 32> Cands; 8941212904Sdim if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8942212904Sdim for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8943202879Srdivacky if (Cand->Viable) 8944202379Srdivacky Cands.push_back(Cand); 8945202879Srdivacky else if (OCD == OCD_AllCandidates) { 8946234353Sdim CompleteNonViableCandidate(S, Cand, Args); 8947210299Sed if (Cand->Function || Cand->IsSurrogate) 8948210299Sed Cands.push_back(Cand); 8949210299Sed // Otherwise, this a non-viable builtin candidate. We do not, in general, 8950210299Sed // want to list every possible builtin candidate. 8951202879Srdivacky } 8952202879Srdivacky } 8953202879Srdivacky 8954202379Srdivacky std::sort(Cands.begin(), Cands.end(), 8955212904Sdim CompareOverloadCandidatesForDisplay(S)); 8956218893Sdim 8957202379Srdivacky bool ReportedAmbiguousConversions = false; 8958193326Sed 8959226633Sdim SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8960243830Sdim const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8961210299Sed unsigned CandsShown = 0; 8962202379Srdivacky for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8963202379Srdivacky OverloadCandidate *Cand = *I; 8964202379Srdivacky 8965210299Sed // Set an arbitrary limit on the number of candidate functions we'll spam 8966210299Sed // the user with. FIXME: This limit should depend on details of the 8967210299Sed // candidate list. 8968243830Sdim if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 8969210299Sed break; 8970210299Sed } 8971210299Sed ++CandsShown; 8972210299Sed 8973202379Srdivacky if (Cand->Function) 8974234353Sdim NoteFunctionCandidate(S, Cand, Args.size()); 8975202379Srdivacky else if (Cand->IsSurrogate) 8976212904Sdim NoteSurrogateCandidate(S, Cand); 8977210299Sed else { 8978210299Sed assert(Cand->Viable && 8979210299Sed "Non-viable built-in candidates are not added to Cands."); 8980202379Srdivacky // Generally we only see ambiguities including viable builtin 8981202379Srdivacky // operators if overload resolution got screwed up by an 8982202379Srdivacky // ambiguous user-defined conversion. 8983202379Srdivacky // 8984202379Srdivacky // FIXME: It's quite possible for different conversions to see 8985202379Srdivacky // different ambiguities, though. 8986202379Srdivacky if (!ReportedAmbiguousConversions) { 8987212904Sdim NoteAmbiguousUserConversions(S, OpLoc, Cand); 8988202379Srdivacky ReportedAmbiguousConversions = true; 8989193326Sed } 8990202379Srdivacky 8991202379Srdivacky // If this is a viable builtin, print it. 8992212904Sdim NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8993193326Sed } 8994193326Sed } 8995210299Sed 8996210299Sed if (I != E) 8997212904Sdim S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8998193326Sed} 8999193326Sed 9000218893Sdim// [PossiblyAFunctionType] --> [Return] 9001218893Sdim// NonFunctionType --> NonFunctionType 9002218893Sdim// R (A) --> R(A) 9003218893Sdim// R (*)(A) --> R (A) 9004218893Sdim// R (&)(A) --> R (A) 9005218893Sdim// R (S::*)(A) --> R (A) 9006218893SdimQualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9007218893Sdim QualType Ret = PossiblyAFunctionType; 9008218893Sdim if (const PointerType *ToTypePtr = 9009218893Sdim PossiblyAFunctionType->getAs<PointerType>()) 9010218893Sdim Ret = ToTypePtr->getPointeeType(); 9011218893Sdim else if (const ReferenceType *ToTypeRef = 9012218893Sdim PossiblyAFunctionType->getAs<ReferenceType>()) 9013218893Sdim Ret = ToTypeRef->getPointeeType(); 9014218893Sdim else if (const MemberPointerType *MemTypePtr = 9015218893Sdim PossiblyAFunctionType->getAs<MemberPointerType>()) 9016218893Sdim Ret = MemTypePtr->getPointeeType(); 9017218893Sdim Ret = 9018218893Sdim Context.getCanonicalType(Ret).getUnqualifiedType(); 9019218893Sdim return Ret; 9020218893Sdim} 9021212904Sdim 9022218893Sdim// A helper class to help with address of function resolution 9023218893Sdim// - allows us to avoid passing around all those ugly parameters 9024218893Sdimclass AddressOfFunctionResolver 9025218893Sdim{ 9026218893Sdim Sema& S; 9027218893Sdim Expr* SourceExpr; 9028218893Sdim const QualType& TargetType; 9029218893Sdim QualType TargetFunctionType; // Extracted function type from target type 9030218893Sdim 9031218893Sdim bool Complain; 9032218893Sdim //DeclAccessPair& ResultFunctionAccessPair; 9033218893Sdim ASTContext& Context; 9034212904Sdim 9035218893Sdim bool TargetTypeIsNonStaticMemberFunction; 9036218893Sdim bool FoundNonTemplateFunction; 9037207619Srdivacky 9038218893Sdim OverloadExpr::FindResult OvlExprInfo; 9039218893Sdim OverloadExpr *OvlExpr; 9040218893Sdim TemplateArgumentListInfo OvlExplicitTemplateArgs; 9041226633Sdim SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9042206084Srdivacky 9043218893Sdimpublic: 9044218893Sdim AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 9045218893Sdim const QualType& TargetType, bool Complain) 9046218893Sdim : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9047218893Sdim Complain(Complain), Context(S.getASTContext()), 9048218893Sdim TargetTypeIsNonStaticMemberFunction( 9049218893Sdim !!TargetType->getAs<MemberPointerType>()), 9050218893Sdim FoundNonTemplateFunction(false), 9051218893Sdim OvlExprInfo(OverloadExpr::find(SourceExpr)), 9052218893Sdim OvlExpr(OvlExprInfo.Expression) 9053218893Sdim { 9054218893Sdim ExtractUnqualifiedFunctionTypeFromTargetType(); 9055218893Sdim 9056218893Sdim if (!TargetFunctionType->isFunctionType()) { 9057218893Sdim if (OvlExpr->hasExplicitTemplateArgs()) { 9058218893Sdim DeclAccessPair dap; 9059221345Sdim if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 9060218893Sdim OvlExpr, false, &dap) ) { 9061221345Sdim 9062221345Sdim if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9063221345Sdim if (!Method->isStatic()) { 9064221345Sdim // If the target type is a non-function type and the function 9065221345Sdim // found is a non-static member function, pretend as if that was 9066221345Sdim // the target, it's the only possible type to end up with. 9067221345Sdim TargetTypeIsNonStaticMemberFunction = true; 9068221345Sdim 9069221345Sdim // And skip adding the function if its not in the proper form. 9070221345Sdim // We'll diagnose this due to an empty set of functions. 9071221345Sdim if (!OvlExprInfo.HasFormOfMemberPointer) 9072221345Sdim return; 9073221345Sdim } 9074221345Sdim } 9075221345Sdim 9076218893Sdim Matches.push_back(std::make_pair(dap,Fn)); 9077218893Sdim } 9078218893Sdim } 9079218893Sdim return; 9080218893Sdim } 9081218893Sdim 9082218893Sdim if (OvlExpr->hasExplicitTemplateArgs()) 9083218893Sdim OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9084201361Srdivacky 9085218893Sdim if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9086218893Sdim // C++ [over.over]p4: 9087218893Sdim // If more than one function is selected, [...] 9088218893Sdim if (Matches.size() > 1) { 9089218893Sdim if (FoundNonTemplateFunction) 9090218893Sdim EliminateAllTemplateMatches(); 9091218893Sdim else 9092218893Sdim EliminateAllExceptMostSpecializedTemplate(); 9093218893Sdim } 9094218893Sdim } 9095218893Sdim } 9096218893Sdim 9097218893Sdimprivate: 9098218893Sdim bool isTargetTypeAFunction() const { 9099218893Sdim return TargetFunctionType->isFunctionType(); 9100218893Sdim } 9101198092Srdivacky 9102218893Sdim // [ToType] [Return] 9103198092Srdivacky 9104218893Sdim // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9105218893Sdim // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9106218893Sdim // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9107218893Sdim void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9108218893Sdim TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9109218893Sdim } 9110199990Srdivacky 9111218893Sdim // return true if any matching specializations were found 9112218893Sdim bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9113218893Sdim const DeclAccessPair& CurAccessFunPair) { 9114218893Sdim if (CXXMethodDecl *Method 9115218893Sdim = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9116218893Sdim // Skip non-static function templates when converting to pointer, and 9117218893Sdim // static when converting to member pointer. 9118218893Sdim if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9119218893Sdim return false; 9120218893Sdim } 9121218893Sdim else if (TargetTypeIsNonStaticMemberFunction) 9122218893Sdim return false; 9123198092Srdivacky 9124218893Sdim // C++ [over.over]p2: 9125218893Sdim // If the name is a function template, template argument deduction is 9126218893Sdim // done (14.8.2.2), and if the argument deduction succeeds, the 9127218893Sdim // resulting template argument list is used to generate a single 9128218893Sdim // function template specialization, which is added to the set of 9129218893Sdim // overloaded functions considered. 9130218893Sdim FunctionDecl *Specialization = 0; 9131243830Sdim TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9132218893Sdim if (Sema::TemplateDeductionResult Result 9133218893Sdim = S.DeduceTemplateArguments(FunctionTemplate, 9134218893Sdim &OvlExplicitTemplateArgs, 9135218893Sdim TargetFunctionType, Specialization, 9136251662Sdim Info, /*InOverloadResolution=*/true)) { 9137218893Sdim // FIXME: make a note of the failed deduction for diagnostics. 9138218893Sdim (void)Result; 9139218893Sdim return false; 9140218893Sdim } 9141218893Sdim 9142251662Sdim // Template argument deduction ensures that we have an exact match or 9143251662Sdim // compatible pointer-to-function arguments that would be adjusted by ICS. 9144218893Sdim // This function template specicalization works. 9145218893Sdim Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9146251662Sdim assert(S.isSameOrCompatibleFunctionType( 9147251662Sdim Context.getCanonicalType(Specialization->getType()), 9148251662Sdim Context.getCanonicalType(TargetFunctionType))); 9149218893Sdim Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9150218893Sdim return true; 9151218893Sdim } 9152218893Sdim 9153218893Sdim bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9154218893Sdim const DeclAccessPair& CurAccessFunPair) { 9155201361Srdivacky if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9156193326Sed // Skip non-static functions when converting to pointer, and static 9157193326Sed // when converting to member pointer. 9158218893Sdim if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9159218893Sdim return false; 9160218893Sdim } 9161218893Sdim else if (TargetTypeIsNonStaticMemberFunction) 9162218893Sdim return false; 9163193326Sed 9164201361Srdivacky if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9165234353Sdim if (S.getLangOpts().CUDA) 9166226633Sdim if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9167226633Sdim if (S.CheckCUDATarget(Caller, FunDecl)) 9168226633Sdim return false; 9169226633Sdim 9170251662Sdim // If any candidate has a placeholder return type, trigger its deduction 9171251662Sdim // now. 9172251662Sdim if (S.getLangOpts().CPlusPlus1y && 9173251662Sdim FunDecl->getResultType()->isUndeducedType() && 9174251662Sdim S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9175251662Sdim return false; 9176251662Sdim 9177200583Srdivacky QualType ResultTy; 9178218893Sdim if (Context.hasSameUnqualifiedType(TargetFunctionType, 9179218893Sdim FunDecl->getType()) || 9180224145Sdim S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9181224145Sdim ResultTy)) { 9182218893Sdim Matches.push_back(std::make_pair(CurAccessFunPair, 9183218893Sdim cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9184198092Srdivacky FoundNonTemplateFunction = true; 9185218893Sdim return true; 9186198092Srdivacky } 9187195099Sed } 9188218893Sdim 9189218893Sdim return false; 9190193326Sed } 9191218893Sdim 9192218893Sdim bool FindAllFunctionsThatMatchTargetTypeExactly() { 9193218893Sdim bool Ret = false; 9194218893Sdim 9195218893Sdim // If the overload expression doesn't have the form of a pointer to 9196218893Sdim // member, don't try to convert it to a pointer-to-member type. 9197218893Sdim if (IsInvalidFormOfPointerToMemberFunction()) 9198218893Sdim return false; 9199193326Sed 9200218893Sdim for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9201218893Sdim E = OvlExpr->decls_end(); 9202218893Sdim I != E; ++I) { 9203218893Sdim // Look through any using declarations to find the underlying function. 9204218893Sdim NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9205218893Sdim 9206218893Sdim // C++ [over.over]p3: 9207218893Sdim // Non-member functions and static member functions match 9208218893Sdim // targets of type "pointer-to-function" or "reference-to-function." 9209218893Sdim // Nonstatic member functions match targets of 9210218893Sdim // type "pointer-to-member-function." 9211218893Sdim // Note that according to DR 247, the containing class does not matter. 9212218893Sdim if (FunctionTemplateDecl *FunctionTemplate 9213218893Sdim = dyn_cast<FunctionTemplateDecl>(Fn)) { 9214218893Sdim if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9215218893Sdim Ret = true; 9216218893Sdim } 9217218893Sdim // If we have explicit template arguments supplied, skip non-templates. 9218218893Sdim else if (!OvlExpr->hasExplicitTemplateArgs() && 9219218893Sdim AddMatchingNonTemplateFunction(Fn, I.getPair())) 9220218893Sdim Ret = true; 9221207619Srdivacky } 9222218893Sdim assert(Ret || Matches.empty()); 9223218893Sdim return Ret; 9224198398Srdivacky } 9225198092Srdivacky 9226218893Sdim void EliminateAllExceptMostSpecializedTemplate() { 9227198092Srdivacky // [...] and any given function template specialization F1 is 9228198092Srdivacky // eliminated if the set contains a second function template 9229198092Srdivacky // specialization whose function template is more specialized 9230198092Srdivacky // than the function template of F1 according to the partial 9231198092Srdivacky // ordering rules of 14.5.5.2. 9232198092Srdivacky 9233198092Srdivacky // The algorithm specified above is quadratic. We instead use a 9234198092Srdivacky // two-pass algorithm (similar to the one used to identify the 9235198092Srdivacky // best viable function in an overload set) that identifies the 9236198092Srdivacky // best function template (if it exists). 9237205408Srdivacky 9238205408Srdivacky UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9239205408Srdivacky for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9240205408Srdivacky MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9241218893Sdim 9242203955Srdivacky UnresolvedSetIterator Result = 9243218893Sdim S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9244218893Sdim TPOC_Other, 0, SourceExpr->getLocStart(), 9245218893Sdim S.PDiag(), 9246218893Sdim S.PDiag(diag::err_addr_ovl_ambiguous) 9247218893Sdim << Matches[0].second->getDeclName(), 9248218893Sdim S.PDiag(diag::note_ovl_candidate) 9249218893Sdim << (unsigned) oc_function_template, 9250234353Sdim Complain, TargetFunctionType); 9251218893Sdim 9252218893Sdim if (Result != MatchesCopy.end()) { 9253218893Sdim // Make it the first and only element 9254218893Sdim Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9255218893Sdim Matches[0].second = cast<FunctionDecl>(*Result); 9256218893Sdim Matches.resize(1); 9257208600Srdivacky } 9258198092Srdivacky } 9259198092Srdivacky 9260218893Sdim void EliminateAllTemplateMatches() { 9261218893Sdim // [...] any function template specializations in the set are 9262218893Sdim // eliminated if the set also contains a non-template function, [...] 9263218893Sdim for (unsigned I = 0, N = Matches.size(); I != N; ) { 9264218893Sdim if (Matches[I].second->getPrimaryTemplate() == 0) 9265218893Sdim ++I; 9266218893Sdim else { 9267218893Sdim Matches[I] = Matches[--N]; 9268218893Sdim Matches.set_size(N); 9269218893Sdim } 9270203955Srdivacky } 9271203955Srdivacky } 9272218893Sdim 9273218893Sdimpublic: 9274218893Sdim void ComplainNoMatchesFound() const { 9275218893Sdim assert(Matches.empty()); 9276218893Sdim S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9277218893Sdim << OvlExpr->getName() << TargetFunctionType 9278218893Sdim << OvlExpr->getSourceRange(); 9279234353Sdim S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9280218893Sdim } 9281198092Srdivacky 9282218893Sdim bool IsInvalidFormOfPointerToMemberFunction() const { 9283218893Sdim return TargetTypeIsNonStaticMemberFunction && 9284218893Sdim !OvlExprInfo.HasFormOfMemberPointer; 9285198398Srdivacky } 9286218893Sdim 9287218893Sdim void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9288218893Sdim // TODO: Should we condition this on whether any functions might 9289218893Sdim // have matched, or is it more appropriate to do that in callers? 9290218893Sdim // TODO: a fixit wouldn't hurt. 9291218893Sdim S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9292218893Sdim << TargetType << OvlExpr->getSourceRange(); 9293218893Sdim } 9294218893Sdim 9295218893Sdim void ComplainOfInvalidConversion() const { 9296218893Sdim S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9297218893Sdim << OvlExpr->getName() << TargetType; 9298218893Sdim } 9299198092Srdivacky 9300218893Sdim void ComplainMultipleMatchesFound() const { 9301218893Sdim assert(Matches.size() > 1); 9302218893Sdim S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9303218893Sdim << OvlExpr->getName() 9304218893Sdim << OvlExpr->getSourceRange(); 9305234353Sdim S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9306218893Sdim } 9307234353Sdim 9308234353Sdim bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9309234353Sdim 9310218893Sdim int getNumMatches() const { return Matches.size(); } 9311218893Sdim 9312218893Sdim FunctionDecl* getMatchingFunctionDecl() const { 9313218893Sdim if (Matches.size() != 1) return 0; 9314218893Sdim return Matches[0].second; 9315218893Sdim } 9316218893Sdim 9317218893Sdim const DeclAccessPair* getMatchingFunctionAccessPair() const { 9318218893Sdim if (Matches.size() != 1) return 0; 9319218893Sdim return &Matches[0].first; 9320218893Sdim } 9321218893Sdim}; 9322218893Sdim 9323218893Sdim/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9324218893Sdim/// an overloaded function (C++ [over.over]), where @p From is an 9325218893Sdim/// expression with overloaded function type and @p ToType is the type 9326218893Sdim/// we're trying to resolve to. For example: 9327218893Sdim/// 9328218893Sdim/// @code 9329218893Sdim/// int f(double); 9330218893Sdim/// int f(int); 9331218893Sdim/// 9332218893Sdim/// int (*pfd)(double) = f; // selects f(double) 9333218893Sdim/// @endcode 9334218893Sdim/// 9335218893Sdim/// This routine returns the resulting FunctionDecl if it could be 9336218893Sdim/// resolved, and NULL otherwise. When @p Complain is true, this 9337218893Sdim/// routine will emit diagnostics if there is an error. 9338218893SdimFunctionDecl * 9339234353SdimSema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9340234353Sdim QualType TargetType, 9341234353Sdim bool Complain, 9342234353Sdim DeclAccessPair &FoundResult, 9343234353Sdim bool *pHadMultipleCandidates) { 9344234353Sdim assert(AddressOfExpr->getType() == Context.OverloadTy); 9345218893Sdim 9346234353Sdim AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9347234353Sdim Complain); 9348218893Sdim int NumMatches = Resolver.getNumMatches(); 9349218893Sdim FunctionDecl* Fn = 0; 9350234353Sdim if (NumMatches == 0 && Complain) { 9351218893Sdim if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9352218893Sdim Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9353218893Sdim else 9354218893Sdim Resolver.ComplainNoMatchesFound(); 9355218893Sdim } 9356218893Sdim else if (NumMatches > 1 && Complain) 9357218893Sdim Resolver.ComplainMultipleMatchesFound(); 9358218893Sdim else if (NumMatches == 1) { 9359218893Sdim Fn = Resolver.getMatchingFunctionDecl(); 9360218893Sdim assert(Fn); 9361218893Sdim FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9362218893Sdim if (Complain) 9363218893Sdim CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9364218893Sdim } 9365234353Sdim 9366234353Sdim if (pHadMultipleCandidates) 9367234353Sdim *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9368218893Sdim return Fn; 9369193326Sed} 9370193326Sed 9371218893Sdim/// \brief Given an expression that refers to an overloaded function, try to 9372201361Srdivacky/// resolve that overloaded function expression down to a single function. 9373201361Srdivacky/// 9374201361Srdivacky/// This routine can only resolve template-ids that refer to a single function 9375201361Srdivacky/// template, where that template-id refers to a single template whose template 9376218893Sdim/// arguments are either provided by the template-id or have defaults, 9377201361Srdivacky/// as described in C++0x [temp.arg.explicit]p3. 9378221345SdimFunctionDecl * 9379221345SdimSema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9380221345Sdim bool Complain, 9381221345Sdim DeclAccessPair *FoundResult) { 9382201361Srdivacky // C++ [over.over]p1: 9383201361Srdivacky // [...] [Note: any redundant set of parentheses surrounding the 9384201361Srdivacky // overloaded function name is ignored (5.1). ] 9385201361Srdivacky // C++ [over.over]p1: 9386201361Srdivacky // [...] The overloaded function name can be preceded by the & 9387201361Srdivacky // operator. 9388203955Srdivacky 9389201361Srdivacky // If we didn't actually find any template-ids, we're done. 9390221345Sdim if (!ovl->hasExplicitTemplateArgs()) 9391201361Srdivacky return 0; 9392203955Srdivacky 9393203955Srdivacky TemplateArgumentListInfo ExplicitTemplateArgs; 9394221345Sdim ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9395218893Sdim 9396201361Srdivacky // Look through all of the overloaded functions, searching for one 9397201361Srdivacky // whose type matches exactly. 9398201361Srdivacky FunctionDecl *Matched = 0; 9399221345Sdim for (UnresolvedSetIterator I = ovl->decls_begin(), 9400221345Sdim E = ovl->decls_end(); I != E; ++I) { 9401201361Srdivacky // C++0x [temp.arg.explicit]p3: 9402201361Srdivacky // [...] In contexts where deduction is done and fails, or in contexts 9403218893Sdim // where deduction is not done, if a template argument list is 9404218893Sdim // specified and it, along with any default template arguments, 9405218893Sdim // identifies a single function template specialization, then the 9406201361Srdivacky // template-id is an lvalue for the function template specialization. 9407210299Sed FunctionTemplateDecl *FunctionTemplate 9408210299Sed = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9409218893Sdim 9410201361Srdivacky // C++ [over.over]p2: 9411201361Srdivacky // If the name is a function template, template argument deduction is 9412201361Srdivacky // done (14.8.2.2), and if the argument deduction succeeds, the 9413201361Srdivacky // resulting template argument list is used to generate a single 9414201361Srdivacky // function template specialization, which is added to the set of 9415201361Srdivacky // overloaded functions considered. 9416201361Srdivacky FunctionDecl *Specialization = 0; 9417243830Sdim TemplateDeductionInfo Info(ovl->getNameLoc()); 9418201361Srdivacky if (TemplateDeductionResult Result 9419201361Srdivacky = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9420251662Sdim Specialization, Info, 9421251662Sdim /*InOverloadResolution=*/true)) { 9422201361Srdivacky // FIXME: make a note of the failed deduction for diagnostics. 9423201361Srdivacky (void)Result; 9424201361Srdivacky continue; 9425218893Sdim } 9426218893Sdim 9427221345Sdim assert(Specialization && "no specialization and no error?"); 9428221345Sdim 9429201361Srdivacky // Multiple matches; we can't resolve to a single declaration. 9430218893Sdim if (Matched) { 9431218893Sdim if (Complain) { 9432221345Sdim Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9433221345Sdim << ovl->getName(); 9434221345Sdim NoteAllOverloadCandidates(ovl); 9435218893Sdim } 9436201361Srdivacky return 0; 9437221345Sdim } 9438218893Sdim 9439221345Sdim Matched = Specialization; 9440221345Sdim if (FoundResult) *FoundResult = I.getPair(); 9441201361Srdivacky } 9442201361Srdivacky 9443251662Sdim if (Matched && getLangOpts().CPlusPlus1y && 9444251662Sdim Matched->getResultType()->isUndeducedType() && 9445251662Sdim DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 9446251662Sdim return 0; 9447251662Sdim 9448201361Srdivacky return Matched; 9449201361Srdivacky} 9450218893Sdim 9451221345Sdim 9452221345Sdim 9453221345Sdim 9454226633Sdim// Resolve and fix an overloaded expression that can be resolved 9455226633Sdim// because it identifies a single function template specialization. 9456226633Sdim// 9457221345Sdim// Last three arguments should only be supplied if Complain = true 9458226633Sdim// 9459226633Sdim// Return true if it was logically possible to so resolve the 9460226633Sdim// expression, regardless of whether or not it succeeded. Always 9461226633Sdim// returns true if 'complain' is set. 9462226633Sdimbool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9463226633Sdim ExprResult &SrcExpr, bool doFunctionPointerConverion, 9464226633Sdim bool complain, const SourceRange& OpRangeForComplaining, 9465221345Sdim QualType DestTypeForComplaining, 9466221345Sdim unsigned DiagIDForComplaining) { 9467226633Sdim assert(SrcExpr.get()->getType() == Context.OverloadTy); 9468221345Sdim 9469226633Sdim OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9470221345Sdim 9471221345Sdim DeclAccessPair found; 9472221345Sdim ExprResult SingleFunctionExpression; 9473221345Sdim if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9474221345Sdim ovl.Expression, /*complain*/ false, &found)) { 9475234353Sdim if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9476226633Sdim SrcExpr = ExprError(); 9477226633Sdim return true; 9478226633Sdim } 9479221345Sdim 9480221345Sdim // It is only correct to resolve to an instance method if we're 9481221345Sdim // resolving a form that's permitted to be a pointer to member. 9482221345Sdim // Otherwise we'll end up making a bound member expression, which 9483221345Sdim // is illegal in all the contexts we resolve like this. 9484221345Sdim if (!ovl.HasFormOfMemberPointer && 9485221345Sdim isa<CXXMethodDecl>(fn) && 9486221345Sdim cast<CXXMethodDecl>(fn)->isInstance()) { 9487226633Sdim if (!complain) return false; 9488226633Sdim 9489226633Sdim Diag(ovl.Expression->getExprLoc(), 9490226633Sdim diag::err_bound_member_function) 9491226633Sdim << 0 << ovl.Expression->getSourceRange(); 9492226633Sdim 9493226633Sdim // TODO: I believe we only end up here if there's a mix of 9494226633Sdim // static and non-static candidates (otherwise the expression 9495226633Sdim // would have 'bound member' type, not 'overload' type). 9496226633Sdim // Ideally we would note which candidate was chosen and why 9497226633Sdim // the static candidates were rejected. 9498226633Sdim SrcExpr = ExprError(); 9499226633Sdim return true; 9500221345Sdim } 9501221345Sdim 9502239462Sdim // Fix the expression to refer to 'fn'. 9503221345Sdim SingleFunctionExpression = 9504226633Sdim Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9505221345Sdim 9506221345Sdim // If desired, do function-to-pointer decay. 9507226633Sdim if (doFunctionPointerConverion) { 9508221345Sdim SingleFunctionExpression = 9509221345Sdim DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9510226633Sdim if (SingleFunctionExpression.isInvalid()) { 9511226633Sdim SrcExpr = ExprError(); 9512226633Sdim return true; 9513226633Sdim } 9514226633Sdim } 9515221345Sdim } 9516221345Sdim 9517221345Sdim if (!SingleFunctionExpression.isUsable()) { 9518221345Sdim if (complain) { 9519221345Sdim Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9520221345Sdim << ovl.Expression->getName() 9521221345Sdim << DestTypeForComplaining 9522221345Sdim << OpRangeForComplaining 9523221345Sdim << ovl.Expression->getQualifierLoc().getSourceRange(); 9524226633Sdim NoteAllOverloadCandidates(SrcExpr.get()); 9525226633Sdim 9526226633Sdim SrcExpr = ExprError(); 9527226633Sdim return true; 9528226633Sdim } 9529226633Sdim 9530226633Sdim return false; 9531221345Sdim } 9532221345Sdim 9533226633Sdim SrcExpr = SingleFunctionExpression; 9534226633Sdim return true; 9535221345Sdim} 9536221345Sdim 9537198092Srdivacky/// \brief Add a single candidate to the overload set. 9538198092Srdivackystatic void AddOverloadedCallCandidate(Sema &S, 9539205408Srdivacky DeclAccessPair FoundDecl, 9540221345Sdim TemplateArgumentListInfo *ExplicitTemplateArgs, 9541249423Sdim ArrayRef<Expr *> Args, 9542198092Srdivacky OverloadCandidateSet &CandidateSet, 9543224145Sdim bool PartialOverloading, 9544224145Sdim bool KnownValid) { 9545205408Srdivacky NamedDecl *Callee = FoundDecl.getDecl(); 9546199990Srdivacky if (isa<UsingShadowDecl>(Callee)) 9547199990Srdivacky Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9548199990Srdivacky 9549198092Srdivacky if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9550224145Sdim if (ExplicitTemplateArgs) { 9551224145Sdim assert(!KnownValid && "Explicit template arguments?"); 9552224145Sdim return; 9553224145Sdim } 9554234353Sdim S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9555234353Sdim PartialOverloading); 9556198092Srdivacky return; 9557199990Srdivacky } 9558199990Srdivacky 9559199990Srdivacky if (FunctionTemplateDecl *FuncTemplate 9560199990Srdivacky = dyn_cast<FunctionTemplateDecl>(Callee)) { 9561205408Srdivacky S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9562234353Sdim ExplicitTemplateArgs, Args, CandidateSet); 9563199990Srdivacky return; 9564199990Srdivacky } 9565199990Srdivacky 9566224145Sdim assert(!KnownValid && "unhandled case in overloaded call candidate"); 9567198092Srdivacky} 9568218893Sdim 9569198092Srdivacky/// \brief Add the overload candidates named by callee and/or found by argument 9570198092Srdivacky/// dependent lookup to the given overload set. 9571201361Srdivackyvoid Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9572249423Sdim ArrayRef<Expr *> Args, 9573198092Srdivacky OverloadCandidateSet &CandidateSet, 9574198092Srdivacky bool PartialOverloading) { 9575199990Srdivacky 9576199990Srdivacky#ifndef NDEBUG 9577199990Srdivacky // Verify that ArgumentDependentLookup is consistent with the rules 9578199990Srdivacky // in C++0x [basic.lookup.argdep]p3: 9579193326Sed // 9580193326Sed // Let X be the lookup set produced by unqualified lookup (3.4.1) 9581193326Sed // and let Y be the lookup set produced by argument dependent 9582193326Sed // lookup (defined as follows). If X contains 9583193326Sed // 9584198092Srdivacky // -- a declaration of a class member, or 9585193326Sed // 9586193326Sed // -- a block-scope function declaration that is not a 9587199990Srdivacky // using-declaration, or 9588198092Srdivacky // 9589193326Sed // -- a declaration that is neither a function or a function 9590193326Sed // template 9591193326Sed // 9592198092Srdivacky // then Y is empty. 9593199990Srdivacky 9594201361Srdivacky if (ULE->requiresADL()) { 9595201361Srdivacky for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9596201361Srdivacky E = ULE->decls_end(); I != E; ++I) { 9597201361Srdivacky assert(!(*I)->getDeclContext()->isRecord()); 9598201361Srdivacky assert(isa<UsingShadowDecl>(*I) || 9599201361Srdivacky !(*I)->getDeclContext()->isFunctionOrMethod()); 9600201361Srdivacky assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9601199990Srdivacky } 9602199990Srdivacky } 9603199990Srdivacky#endif 9604199990Srdivacky 9605201361Srdivacky // It would be nice to avoid this copy. 9606201361Srdivacky TemplateArgumentListInfo TABuffer; 9607221345Sdim TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9608201361Srdivacky if (ULE->hasExplicitTemplateArgs()) { 9609201361Srdivacky ULE->copyTemplateArgumentsInto(TABuffer); 9610201361Srdivacky ExplicitTemplateArgs = &TABuffer; 9611201361Srdivacky } 9612201361Srdivacky 9613201361Srdivacky for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9614201361Srdivacky E = ULE->decls_end(); I != E; ++I) 9615234353Sdim AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9616234353Sdim CandidateSet, PartialOverloading, 9617234353Sdim /*KnownValid*/ true); 9618199990Srdivacky 9619201361Srdivacky if (ULE->requiresADL()) 9620203955Srdivacky AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9621234353Sdim ULE->getExprLoc(), 9622234353Sdim Args, ExplicitTemplateArgs, 9623243830Sdim CandidateSet, PartialOverloading); 9624198092Srdivacky} 9625201361Srdivacky 9626223017Sdim/// Attempt to recover from an ill-formed use of a non-dependent name in a 9627223017Sdim/// template, where the non-dependent name was declared after the template 9628223017Sdim/// was defined. This is common in code written for a compilers which do not 9629223017Sdim/// correctly implement two-stage name lookup. 9630223017Sdim/// 9631223017Sdim/// Returns true if a viable candidate was found and a diagnostic was issued. 9632223017Sdimstatic bool 9633223017SdimDiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9634223017Sdim const CXXScopeSpec &SS, LookupResult &R, 9635223017Sdim TemplateArgumentListInfo *ExplicitTemplateArgs, 9636249423Sdim ArrayRef<Expr *> Args) { 9637223017Sdim if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9638223017Sdim return false; 9639223017Sdim 9640223017Sdim for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9641234353Sdim if (DC->isTransparentContext()) 9642234353Sdim continue; 9643234353Sdim 9644223017Sdim SemaRef.LookupQualifiedName(R, DC); 9645223017Sdim 9646223017Sdim if (!R.empty()) { 9647223017Sdim R.suppressDiagnostics(); 9648223017Sdim 9649223017Sdim if (isa<CXXRecordDecl>(DC)) { 9650223017Sdim // Don't diagnose names we find in classes; we get much better 9651223017Sdim // diagnostics for these from DiagnoseEmptyLookup. 9652223017Sdim R.clear(); 9653223017Sdim return false; 9654223017Sdim } 9655223017Sdim 9656223017Sdim OverloadCandidateSet Candidates(FnLoc); 9657223017Sdim for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9658223017Sdim AddOverloadedCallCandidate(SemaRef, I.getPair(), 9659234353Sdim ExplicitTemplateArgs, Args, 9660224145Sdim Candidates, false, /*KnownValid*/ false); 9661223017Sdim 9662223017Sdim OverloadCandidateSet::iterator Best; 9663224145Sdim if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9664223017Sdim // No viable functions. Don't bother the user with notes for functions 9665223017Sdim // which don't work and shouldn't be found anyway. 9666224145Sdim R.clear(); 9667223017Sdim return false; 9668224145Sdim } 9669223017Sdim 9670223017Sdim // Find the namespaces where ADL would have looked, and suggest 9671223017Sdim // declaring the function there instead. 9672223017Sdim Sema::AssociatedNamespaceSet AssociatedNamespaces; 9673223017Sdim Sema::AssociatedClassSet AssociatedClasses; 9674243830Sdim SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9675223017Sdim AssociatedNamespaces, 9676223017Sdim AssociatedClasses); 9677223017Sdim Sema::AssociatedNamespaceSet SuggestedNamespaces; 9678249423Sdim DeclContext *Std = SemaRef.getStdNamespace(); 9679249423Sdim for (Sema::AssociatedNamespaceSet::iterator 9680249423Sdim it = AssociatedNamespaces.begin(), 9681249423Sdim end = AssociatedNamespaces.end(); it != end; ++it) { 9682249423Sdim // Never suggest declaring a function within namespace 'std'. 9683249423Sdim if (Std && Std->Encloses(*it)) 9684249423Sdim continue; 9685249423Sdim 9686249423Sdim // Never suggest declaring a function within a namespace with a reserved 9687249423Sdim // name, like __gnu_cxx. 9688249423Sdim NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9689249423Sdim if (NS && 9690249423Sdim NS->getQualifiedNameAsString().find("__") != std::string::npos) 9691249423Sdim continue; 9692249423Sdim 9693249423Sdim SuggestedNamespaces.insert(*it); 9694223017Sdim } 9695223017Sdim 9696223017Sdim SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9697223017Sdim << R.getLookupName(); 9698223017Sdim if (SuggestedNamespaces.empty()) { 9699223017Sdim SemaRef.Diag(Best->Function->getLocation(), 9700223017Sdim diag::note_not_found_by_two_phase_lookup) 9701223017Sdim << R.getLookupName() << 0; 9702223017Sdim } else if (SuggestedNamespaces.size() == 1) { 9703223017Sdim SemaRef.Diag(Best->Function->getLocation(), 9704223017Sdim diag::note_not_found_by_two_phase_lookup) 9705223017Sdim << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9706223017Sdim } else { 9707223017Sdim // FIXME: It would be useful to list the associated namespaces here, 9708223017Sdim // but the diagnostics infrastructure doesn't provide a way to produce 9709223017Sdim // a localized representation of a list of items. 9710223017Sdim SemaRef.Diag(Best->Function->getLocation(), 9711223017Sdim diag::note_not_found_by_two_phase_lookup) 9712223017Sdim << R.getLookupName() << 2; 9713223017Sdim } 9714223017Sdim 9715223017Sdim // Try to recover by calling this function. 9716223017Sdim return true; 9717223017Sdim } 9718223017Sdim 9719223017Sdim R.clear(); 9720223017Sdim } 9721223017Sdim 9722223017Sdim return false; 9723223017Sdim} 9724223017Sdim 9725223017Sdim/// Attempt to recover from ill-formed use of a non-dependent operator in a 9726223017Sdim/// template, where the non-dependent operator was declared after the template 9727223017Sdim/// was defined. 9728223017Sdim/// 9729223017Sdim/// Returns true if a viable candidate was found and a diagnostic was issued. 9730223017Sdimstatic bool 9731223017SdimDiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9732223017Sdim SourceLocation OpLoc, 9733249423Sdim ArrayRef<Expr *> Args) { 9734223017Sdim DeclarationName OpName = 9735223017Sdim SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9736223017Sdim LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9737223017Sdim return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9738234353Sdim /*ExplicitTemplateArgs=*/0, Args); 9739223017Sdim} 9740223017Sdim 9741234353Sdimnamespace { 9742234353Sdim// Callback to limit the allowed keywords and to only accept typo corrections 9743234353Sdim// that are keywords or whose decls refer to functions (or template functions) 9744234353Sdim// that accept the given number of arguments. 9745234353Sdimclass RecoveryCallCCC : public CorrectionCandidateCallback { 9746234353Sdim public: 9747234353Sdim RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9748234353Sdim : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9749234353Sdim WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9750234353Sdim WantRemainingKeywords = false; 9751234353Sdim } 9752234353Sdim 9753234353Sdim virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9754234353Sdim if (!candidate.getCorrectionDecl()) 9755234353Sdim return candidate.isKeyword(); 9756234353Sdim 9757234353Sdim for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9758234353Sdim DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9759234353Sdim FunctionDecl *FD = 0; 9760234353Sdim NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9761234353Sdim if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9762234353Sdim FD = FTD->getTemplatedDecl(); 9763234353Sdim if (!HasExplicitTemplateArgs && !FD) { 9764234353Sdim if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9765234353Sdim // If the Decl is neither a function nor a template function, 9766234353Sdim // determine if it is a pointer or reference to a function. If so, 9767234353Sdim // check against the number of arguments expected for the pointee. 9768234353Sdim QualType ValType = cast<ValueDecl>(ND)->getType(); 9769234353Sdim if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9770234353Sdim ValType = ValType->getPointeeType(); 9771234353Sdim if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9772234353Sdim if (FPT->getNumArgs() == NumArgs) 9773234353Sdim return true; 9774234353Sdim } 9775234353Sdim } 9776234353Sdim if (FD && FD->getNumParams() >= NumArgs && 9777234353Sdim FD->getMinRequiredArguments() <= NumArgs) 9778234353Sdim return true; 9779234353Sdim } 9780234353Sdim return false; 9781234353Sdim } 9782234353Sdim 9783234353Sdim private: 9784234353Sdim unsigned NumArgs; 9785234353Sdim bool HasExplicitTemplateArgs; 9786234353Sdim}; 9787234353Sdim 9788234353Sdim// Callback that effectively disabled typo correction 9789234353Sdimclass NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9790234353Sdim public: 9791234353Sdim NoTypoCorrectionCCC() { 9792234353Sdim WantTypeSpecifiers = false; 9793234353Sdim WantExpressionKeywords = false; 9794234353Sdim WantCXXNamedCasts = false; 9795234353Sdim WantRemainingKeywords = false; 9796234353Sdim } 9797234353Sdim 9798234353Sdim virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9799234353Sdim return false; 9800234353Sdim } 9801234353Sdim}; 9802243830Sdim 9803243830Sdimclass BuildRecoveryCallExprRAII { 9804243830Sdim Sema &SemaRef; 9805243830Sdimpublic: 9806243830Sdim BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9807243830Sdim assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9808243830Sdim SemaRef.IsBuildingRecoveryCallExpr = true; 9809243830Sdim } 9810243830Sdim 9811243830Sdim ~BuildRecoveryCallExprRAII() { 9812243830Sdim SemaRef.IsBuildingRecoveryCallExpr = false; 9813243830Sdim } 9814243830Sdim}; 9815243830Sdim 9816234353Sdim} 9817234353Sdim 9818201361Srdivacky/// Attempts to recover from a call where no functions were found. 9819201361Srdivacky/// 9820201361Srdivacky/// Returns true if new candidates were found. 9821212904Sdimstatic ExprResult 9822207619SrdivackyBuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9823201361Srdivacky UnresolvedLookupExpr *ULE, 9824201361Srdivacky SourceLocation LParenLoc, 9825234353Sdim llvm::MutableArrayRef<Expr *> Args, 9826223017Sdim SourceLocation RParenLoc, 9827234353Sdim bool EmptyLookup, bool AllowTypoCorrection) { 9828243830Sdim // Do not try to recover if it is already building a recovery call. 9829243830Sdim // This stops infinite loops for template instantiations like 9830243830Sdim // 9831243830Sdim // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9832243830Sdim // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9833243830Sdim // 9834243830Sdim if (SemaRef.IsBuildingRecoveryCallExpr) 9835243830Sdim return ExprError(); 9836243830Sdim BuildRecoveryCallExprRAII RCE(SemaRef); 9837201361Srdivacky 9838201361Srdivacky CXXScopeSpec SS; 9839221345Sdim SS.Adopt(ULE->getQualifierLoc()); 9840234353Sdim SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9841201361Srdivacky 9842201361Srdivacky TemplateArgumentListInfo TABuffer; 9843223017Sdim TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9844201361Srdivacky if (ULE->hasExplicitTemplateArgs()) { 9845201361Srdivacky ULE->copyTemplateArgumentsInto(TABuffer); 9846201361Srdivacky ExplicitTemplateArgs = &TABuffer; 9847201361Srdivacky } 9848201361Srdivacky 9849201361Srdivacky LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9850201361Srdivacky Sema::LookupOrdinaryName); 9851234353Sdim RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9852234353Sdim NoTypoCorrectionCCC RejectAll; 9853234353Sdim CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9854234353Sdim (CorrectionCandidateCallback*)&Validator : 9855234353Sdim (CorrectionCandidateCallback*)&RejectAll; 9856223017Sdim if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9857234353Sdim ExplicitTemplateArgs, Args) && 9858223017Sdim (!EmptyLookup || 9859234353Sdim SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9860234353Sdim ExplicitTemplateArgs, Args))) 9861212904Sdim return ExprError(); 9862201361Srdivacky 9863201361Srdivacky assert(!R.empty() && "lookup results empty despite recovery"); 9864201361Srdivacky 9865201361Srdivacky // Build an implicit member call if appropriate. Just drop the 9866201361Srdivacky // casts and such from the call, we don't really care. 9867212904Sdim ExprResult NewFn = ExprError(); 9868201361Srdivacky if ((*R.begin())->isCXXClassMember()) 9869234353Sdim NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9870234353Sdim R, ExplicitTemplateArgs); 9871234353Sdim else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9872234353Sdim NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9873234353Sdim ExplicitTemplateArgs); 9874201361Srdivacky else 9875201361Srdivacky NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9876201361Srdivacky 9877201361Srdivacky if (NewFn.isInvalid()) 9878212904Sdim return ExprError(); 9879201361Srdivacky 9880201361Srdivacky // This shouldn't cause an infinite loop because we're giving it 9881223017Sdim // an expression with viable lookup results, which should never 9882201361Srdivacky // end up here. 9883212904Sdim return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9884234353Sdim MultiExprArg(Args.data(), Args.size()), 9885234353Sdim RParenLoc); 9886201361Srdivacky} 9887210299Sed 9888243830Sdim/// \brief Constructs and populates an OverloadedCandidateSet from 9889243830Sdim/// the given function. 9890243830Sdim/// \returns true when an the ExprResult output parameter has been set. 9891243830Sdimbool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9892243830Sdim UnresolvedLookupExpr *ULE, 9893243830Sdim Expr **Args, unsigned NumArgs, 9894243830Sdim SourceLocation RParenLoc, 9895243830Sdim OverloadCandidateSet *CandidateSet, 9896243830Sdim ExprResult *Result) { 9897201361Srdivacky#ifndef NDEBUG 9898201361Srdivacky if (ULE->requiresADL()) { 9899201361Srdivacky // To do ADL, we must have found an unqualified name. 9900201361Srdivacky assert(!ULE->getQualifier() && "qualified name with ADL"); 9901201361Srdivacky 9902201361Srdivacky // We don't perform ADL for implicit declarations of builtins. 9903201361Srdivacky // Verify that this was correctly set up. 9904201361Srdivacky FunctionDecl *F; 9905201361Srdivacky if (ULE->decls_begin() + 1 == ULE->decls_end() && 9906201361Srdivacky (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9907201361Srdivacky F->getBuiltinID() && F->isImplicit()) 9908226633Sdim llvm_unreachable("performing ADL for builtin"); 9909218893Sdim 9910201361Srdivacky // We don't perform ADL in C. 9911234353Sdim assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9912243830Sdim } 9913201361Srdivacky#endif 9914201361Srdivacky 9915234353Sdim UnbridgedCastsSet UnbridgedCasts; 9916243830Sdim if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9917243830Sdim *Result = ExprError(); 9918243830Sdim return true; 9919243830Sdim } 9920234353Sdim 9921201361Srdivacky // Add the functions denoted by the callee to the set of candidate 9922201361Srdivacky // functions, including those from argument-dependent lookup. 9923234353Sdim AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9924243830Sdim *CandidateSet); 9925201361Srdivacky 9926201361Srdivacky // If we found nothing, try to recover. 9927223017Sdim // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9928223017Sdim // out if it fails. 9929243830Sdim if (CandidateSet->empty()) { 9930226633Sdim // In Microsoft mode, if we are inside a template class member function then 9931226633Sdim // create a type dependent CallExpr. The goal is to postpone name lookup 9932226633Sdim // to instantiation time to be able to search into type dependent base 9933226633Sdim // classes. 9934234353Sdim if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9935234353Sdim (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9936243830Sdim CallExpr *CE = new (Context) CallExpr(Context, Fn, 9937243830Sdim llvm::makeArrayRef(Args, NumArgs), 9938243830Sdim Context.DependentTy, VK_RValue, 9939243830Sdim RParenLoc); 9940226633Sdim CE->setTypeDependent(true); 9941243830Sdim *Result = Owned(CE); 9942243830Sdim return true; 9943226633Sdim } 9944243830Sdim return false; 9945243830Sdim } 9946243830Sdim 9947243830Sdim UnbridgedCasts.restore(); 9948243830Sdim return false; 9949243830Sdim} 9950243830Sdim 9951243830Sdim/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9952243830Sdim/// the completed call expression. If overload resolution fails, emits 9953243830Sdim/// diagnostics and returns ExprError() 9954243830Sdimstatic ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9955243830Sdim UnresolvedLookupExpr *ULE, 9956243830Sdim SourceLocation LParenLoc, 9957243830Sdim Expr **Args, unsigned NumArgs, 9958243830Sdim SourceLocation RParenLoc, 9959243830Sdim Expr *ExecConfig, 9960243830Sdim OverloadCandidateSet *CandidateSet, 9961243830Sdim OverloadCandidateSet::iterator *Best, 9962243830Sdim OverloadingResult OverloadResult, 9963243830Sdim bool AllowTypoCorrection) { 9964243830Sdim if (CandidateSet->empty()) 9965243830Sdim return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9966234353Sdim llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9967234353Sdim RParenLoc, /*EmptyLookup=*/true, 9968234353Sdim AllowTypoCorrection); 9969201361Srdivacky 9970243830Sdim switch (OverloadResult) { 9971201361Srdivacky case OR_Success: { 9972243830Sdim FunctionDecl *FDecl = (*Best)->Function; 9973243830Sdim SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9974251662Sdim if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 9975251662Sdim return ExprError(); 9976243830Sdim Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9977243830Sdim return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9978243830Sdim RParenLoc, ExecConfig); 9979201361Srdivacky } 9980193326Sed 9981223017Sdim case OR_No_Viable_Function: { 9982223017Sdim // Try to recover by looking for viable functions which the user might 9983223017Sdim // have meant to call. 9984243830Sdim ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9985234353Sdim llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9986234353Sdim RParenLoc, 9987234353Sdim /*EmptyLookup=*/false, 9988234353Sdim AllowTypoCorrection); 9989223017Sdim if (!Recovery.isInvalid()) 9990223017Sdim return Recovery; 9991223017Sdim 9992243830Sdim SemaRef.Diag(Fn->getLocStart(), 9993193326Sed diag::err_ovl_no_viable_function_in_call) 9994201361Srdivacky << ULE->getName() << Fn->getSourceRange(); 9995243830Sdim CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9996243830Sdim llvm::makeArrayRef(Args, NumArgs)); 9997193326Sed break; 9998223017Sdim } 9999193326Sed 10000193326Sed case OR_Ambiguous: 10001243830Sdim SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10002201361Srdivacky << ULE->getName() << Fn->getSourceRange(); 10003243830Sdim CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 10004243830Sdim llvm::makeArrayRef(Args, NumArgs)); 10005193326Sed break; 10006193326Sed 10007243830Sdim case OR_Deleted: { 10008243830Sdim SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10009243830Sdim << (*Best)->Function->isDeleted() 10010243830Sdim << ULE->getName() 10011243830Sdim << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10012243830Sdim << Fn->getSourceRange(); 10013243830Sdim CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 10014243830Sdim llvm::makeArrayRef(Args, NumArgs)); 10015234353Sdim 10016243830Sdim // We emitted an error for the unvailable/deleted function call but keep 10017243830Sdim // the call in the AST. 10018243830Sdim FunctionDecl *FDecl = (*Best)->Function; 10019243830Sdim Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10020243830Sdim return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 10021243830Sdim RParenLoc, ExecConfig); 10022193326Sed } 10023243830Sdim } 10024193326Sed 10025212904Sdim // Overload resolution failed. 10026201361Srdivacky return ExprError(); 10027193326Sed} 10028193326Sed 10029243830Sdim/// BuildOverloadedCallExpr - Given the call expression that calls Fn 10030243830Sdim/// (which eventually refers to the declaration Func) and the call 10031243830Sdim/// arguments Args/NumArgs, attempt to resolve the function call down 10032243830Sdim/// to a specific function. If overload resolution succeeds, returns 10033243830Sdim/// the call expression produced by overload resolution. 10034243830Sdim/// Otherwise, emits diagnostics and returns ExprError. 10035243830SdimExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10036243830Sdim UnresolvedLookupExpr *ULE, 10037243830Sdim SourceLocation LParenLoc, 10038243830Sdim Expr **Args, unsigned NumArgs, 10039243830Sdim SourceLocation RParenLoc, 10040243830Sdim Expr *ExecConfig, 10041243830Sdim bool AllowTypoCorrection) { 10042243830Sdim OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10043243830Sdim ExprResult result; 10044243830Sdim 10045243830Sdim if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 10046243830Sdim &CandidateSet, &result)) 10047243830Sdim return result; 10048243830Sdim 10049243830Sdim OverloadCandidateSet::iterator Best; 10050243830Sdim OverloadingResult OverloadResult = 10051243830Sdim CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10052243830Sdim 10053243830Sdim return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 10054243830Sdim RParenLoc, ExecConfig, &CandidateSet, 10055243830Sdim &Best, OverloadResult, 10056243830Sdim AllowTypoCorrection); 10057243830Sdim} 10058243830Sdim 10059203955Srdivackystatic bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10060199990Srdivacky return Functions.size() > 1 || 10061199990Srdivacky (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10062199990Srdivacky} 10063199990Srdivacky 10064193326Sed/// \brief Create a unary operation that may resolve to an overloaded 10065193326Sed/// operator. 10066193326Sed/// 10067193326Sed/// \param OpLoc The location of the operator itself (e.g., '*'). 10068193326Sed/// 10069193326Sed/// \param OpcIn The UnaryOperator::Opcode that describes this 10070193326Sed/// operator. 10071193326Sed/// 10072239462Sdim/// \param Fns The set of non-member functions that will be 10073193326Sed/// considered by overload resolution. The caller needs to build this 10074193326Sed/// set based on the context using, e.g., 10075193326Sed/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10076193326Sed/// set should not contain any member functions; those will be added 10077193326Sed/// by CreateOverloadedUnaryOp(). 10078193326Sed/// 10079239462Sdim/// \param Input The input argument. 10080212904SdimExprResult 10081203955SrdivackySema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10082203955Srdivacky const UnresolvedSetImpl &Fns, 10083212904Sdim Expr *Input) { 10084193326Sed UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10085193326Sed 10086193326Sed OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10087193326Sed assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10088193326Sed DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10089212904Sdim // TODO: provide better source location info. 10090212904Sdim DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10091193326Sed 10092234353Sdim if (checkPlaceholderForOverload(*this, Input)) 10093234353Sdim return ExprError(); 10094218893Sdim 10095193326Sed Expr *Args[2] = { Input, 0 }; 10096193326Sed unsigned NumArgs = 1; 10097198092Srdivacky 10098193326Sed // For post-increment and post-decrement, add the implicit '0' as 10099193326Sed // the second argument, so that we know this is a post-increment or 10100193326Sed // post-decrement. 10101212904Sdim if (Opc == UO_PostInc || Opc == UO_PostDec) { 10102193326Sed llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10103212904Sdim Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10104212904Sdim SourceLocation()); 10105193326Sed NumArgs = 2; 10106193326Sed } 10107193326Sed 10108251662Sdim ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10109251662Sdim 10110193326Sed if (Input->isTypeDependent()) { 10111210299Sed if (Fns.empty()) 10112212904Sdim return Owned(new (Context) UnaryOperator(Input, 10113218893Sdim Opc, 10114210299Sed Context.DependentTy, 10115218893Sdim VK_RValue, OK_Ordinary, 10116210299Sed OpLoc)); 10117218893Sdim 10118203955Srdivacky CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10119199990Srdivacky UnresolvedLookupExpr *Fn 10120218893Sdim = UnresolvedLookupExpr::Create(Context, NamingClass, 10121221345Sdim NestedNameSpecifierLoc(), OpNameInfo, 10122208600Srdivacky /*ADL*/ true, IsOverloaded(Fns), 10123208600Srdivacky Fns.begin(), Fns.end()); 10124251662Sdim return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10125193326Sed Context.DependentTy, 10126218893Sdim VK_RValue, 10127243830Sdim OpLoc, false)); 10128193326Sed } 10129193326Sed 10130193326Sed // Build an empty overload set. 10131203955Srdivacky OverloadCandidateSet CandidateSet(OpLoc); 10132193326Sed 10133193326Sed // Add the candidates from the given function set. 10134251662Sdim AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10135193326Sed 10136193326Sed // Add operator candidates that are member functions. 10137251662Sdim AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10138193326Sed 10139203955Srdivacky // Add candidates from ADL. 10140251662Sdim AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10141251662Sdim ArgsArray, /*ExplicitTemplateArgs*/ 0, 10142203955Srdivacky CandidateSet); 10143203955Srdivacky 10144193326Sed // Add builtin operator candidates. 10145251662Sdim AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10146193326Sed 10147226633Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 10148226633Sdim 10149193326Sed // Perform overload resolution. 10150193326Sed OverloadCandidateSet::iterator Best; 10151212904Sdim switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10152193326Sed case OR_Success: { 10153193326Sed // We found a built-in operator or an overloaded operator. 10154193326Sed FunctionDecl *FnDecl = Best->Function; 10155198092Srdivacky 10156193326Sed if (FnDecl) { 10157193326Sed // We matched an overloaded operator. Build a call to that 10158193326Sed // operator. 10159198092Srdivacky 10160193326Sed // Convert the arguments. 10161193326Sed if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10162205408Srdivacky CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10163203955Srdivacky 10164221345Sdim ExprResult InputRes = 10165221345Sdim PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10166221345Sdim Best->FoundDecl, Method); 10167221345Sdim if (InputRes.isInvalid()) 10168193326Sed return ExprError(); 10169221345Sdim Input = InputRes.take(); 10170193326Sed } else { 10171193326Sed // Convert the arguments. 10172212904Sdim ExprResult InputInit 10173201361Srdivacky = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10174218893Sdim Context, 10175201361Srdivacky FnDecl->getParamDecl(0)), 10176218893Sdim SourceLocation(), 10177212904Sdim Input); 10178201361Srdivacky if (InputInit.isInvalid()) 10179193326Sed return ExprError(); 10180212904Sdim Input = InputInit.take(); 10181193326Sed } 10182193326Sed 10183218893Sdim // Determine the result type. 10184218893Sdim QualType ResultTy = FnDecl->getResultType(); 10185218893Sdim ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10186218893Sdim ResultTy = ResultTy.getNonLValueExprType(Context); 10187198092Srdivacky 10188193326Sed // Build the actual expression node. 10189249423Sdim ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10190234353Sdim HadMultipleCandidates, OpLoc); 10191221345Sdim if (FnExpr.isInvalid()) 10192221345Sdim return ExprError(); 10193198092Srdivacky 10194199482Srdivacky Args[0] = Input; 10195212904Sdim CallExpr *TheCall = 10196251662Sdim new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10197243830Sdim ResultTy, VK, OpLoc, false); 10198208600Srdivacky 10199218893Sdim if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10200198092Srdivacky FnDecl)) 10201198092Srdivacky return ExprError(); 10202198092Srdivacky 10203212904Sdim return MaybeBindToTemporary(TheCall); 10204193326Sed } else { 10205193326Sed // We matched a built-in operator. Convert the arguments, then 10206193326Sed // break out so that we will build the appropriate built-in 10207193326Sed // operator node. 10208221345Sdim ExprResult InputRes = 10209221345Sdim PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10210221345Sdim Best->Conversions[0], AA_Passing); 10211221345Sdim if (InputRes.isInvalid()) 10212221345Sdim return ExprError(); 10213221345Sdim Input = InputRes.take(); 10214221345Sdim break; 10215193326Sed } 10216221345Sdim } 10217193326Sed 10218221345Sdim case OR_No_Viable_Function: 10219223017Sdim // This is an erroneous use of an operator which can be overloaded by 10220223017Sdim // a non-member function. Check for non-member operators which were 10221223017Sdim // defined too late to be candidates. 10222251662Sdim if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10223223017Sdim // FIXME: Recover by calling the found function. 10224223017Sdim return ExprError(); 10225223017Sdim 10226221345Sdim // No viable function; fall through to handling this as a 10227221345Sdim // built-in operator, which will produce an error message for us. 10228221345Sdim break; 10229193326Sed 10230221345Sdim case OR_Ambiguous: 10231221345Sdim Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10232193326Sed << UnaryOperator::getOpcodeStr(Opc) 10233221345Sdim << Input->getType() 10234193326Sed << Input->getSourceRange(); 10235251662Sdim CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10236221345Sdim UnaryOperator::getOpcodeStr(Opc), OpLoc); 10237221345Sdim return ExprError(); 10238193326Sed 10239221345Sdim case OR_Deleted: 10240221345Sdim Diag(OpLoc, diag::err_ovl_deleted_oper) 10241221345Sdim << Best->Function->isDeleted() 10242221345Sdim << UnaryOperator::getOpcodeStr(Opc) 10243221345Sdim << getDeletedOrUnavailableSuffix(Best->Function) 10244221345Sdim << Input->getSourceRange(); 10245251662Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10246226633Sdim UnaryOperator::getOpcodeStr(Opc), OpLoc); 10247221345Sdim return ExprError(); 10248221345Sdim } 10249221345Sdim 10250193326Sed // Either we found no viable overloaded operator or we matched a 10251193326Sed // built-in operator. In either case, fall through to trying to 10252193326Sed // build a built-in operation. 10253212904Sdim return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10254193326Sed} 10255193326Sed 10256193326Sed/// \brief Create a binary operation that may resolve to an overloaded 10257193326Sed/// operator. 10258193326Sed/// 10259193326Sed/// \param OpLoc The location of the operator itself (e.g., '+'). 10260193326Sed/// 10261193326Sed/// \param OpcIn The BinaryOperator::Opcode that describes this 10262193326Sed/// operator. 10263193326Sed/// 10264239462Sdim/// \param Fns The set of non-member functions that will be 10265193326Sed/// considered by overload resolution. The caller needs to build this 10266193326Sed/// set based on the context using, e.g., 10267193326Sed/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10268193326Sed/// set should not contain any member functions; those will be added 10269193326Sed/// by CreateOverloadedBinOp(). 10270193326Sed/// 10271193326Sed/// \param LHS Left-hand argument. 10272193326Sed/// \param RHS Right-hand argument. 10273212904SdimExprResult 10274193326SedSema::CreateOverloadedBinOp(SourceLocation OpLoc, 10275198092Srdivacky unsigned OpcIn, 10276203955Srdivacky const UnresolvedSetImpl &Fns, 10277193326Sed Expr *LHS, Expr *RHS) { 10278193326Sed Expr *Args[2] = { LHS, RHS }; 10279198092Srdivacky LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10280193326Sed 10281193326Sed BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10282193326Sed OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10283193326Sed DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10284193326Sed 10285193326Sed // If either side is type-dependent, create an appropriate dependent 10286193326Sed // expression. 10287198092Srdivacky if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10288203955Srdivacky if (Fns.empty()) { 10289218893Sdim // If there are no functions to store, just build a dependent 10290198954Srdivacky // BinaryOperator or CompoundAssignment. 10291212904Sdim if (Opc <= BO_Assign || Opc > BO_OrAssign) 10292198954Srdivacky return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10293218893Sdim Context.DependentTy, 10294218893Sdim VK_RValue, OK_Ordinary, 10295243830Sdim OpLoc, 10296243830Sdim FPFeatures.fp_contract)); 10297218893Sdim 10298198954Srdivacky return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10299198954Srdivacky Context.DependentTy, 10300218893Sdim VK_LValue, 10301218893Sdim OK_Ordinary, 10302198954Srdivacky Context.DependentTy, 10303198954Srdivacky Context.DependentTy, 10304243830Sdim OpLoc, 10305243830Sdim FPFeatures.fp_contract)); 10306198954Srdivacky } 10307203955Srdivacky 10308203955Srdivacky // FIXME: save results of ADL from here? 10309203955Srdivacky CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10310212904Sdim // TODO: provide better source location info in DNLoc component. 10311212904Sdim DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10312199990Srdivacky UnresolvedLookupExpr *Fn 10313221345Sdim = UnresolvedLookupExpr::Create(Context, NamingClass, 10314221345Sdim NestedNameSpecifierLoc(), OpNameInfo, 10315221345Sdim /*ADL*/ true, IsOverloaded(Fns), 10316208600Srdivacky Fns.begin(), Fns.end()); 10317243830Sdim return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10318243830Sdim Context.DependentTy, VK_RValue, 10319243830Sdim OpLoc, FPFeatures.fp_contract)); 10320193326Sed } 10321193326Sed 10322234353Sdim // Always do placeholder-like conversions on the RHS. 10323234353Sdim if (checkPlaceholderForOverload(*this, Args[1])) 10324234353Sdim return ExprError(); 10325193326Sed 10326234353Sdim // Do placeholder-like conversion on the LHS; note that we should 10327234353Sdim // not get here with a PseudoObject LHS. 10328234353Sdim assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10329234353Sdim if (checkPlaceholderForOverload(*this, Args[0])) 10330234353Sdim return ExprError(); 10331218893Sdim 10332199512Srdivacky // If this is the assignment operator, we only perform overload resolution 10333199512Srdivacky // if the left-hand side is a class or enumeration type. This is actually 10334199512Srdivacky // a hack. The standard requires that we do overload resolution between the 10335199512Srdivacky // various built-in candidates, but as DR507 points out, this can lead to 10336199512Srdivacky // problems. So we do it this way, which pretty much follows what GCC does. 10337199512Srdivacky // Note that we go the traditional code path for compound assignment forms. 10338212904Sdim if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10339198092Srdivacky return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10340193326Sed 10341218893Sdim // If this is the .* operator, which is not overloadable, just 10342218893Sdim // create a built-in binary operator. 10343218893Sdim if (Opc == BO_PtrMemD) 10344218893Sdim return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10345218893Sdim 10346193326Sed // Build an empty overload set. 10347203955Srdivacky OverloadCandidateSet CandidateSet(OpLoc); 10348193326Sed 10349193326Sed // Add the candidates from the given function set. 10350234353Sdim AddFunctionCandidates(Fns, Args, CandidateSet, false); 10351193326Sed 10352193326Sed // Add operator candidates that are member functions. 10353251662Sdim AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10354193326Sed 10355203955Srdivacky // Add candidates from ADL. 10356203955Srdivacky AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10357234353Sdim OpLoc, Args, 10358203955Srdivacky /*ExplicitTemplateArgs*/ 0, 10359203955Srdivacky CandidateSet); 10360203955Srdivacky 10361193326Sed // Add builtin operator candidates. 10362251662Sdim AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10363193326Sed 10364226633Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 10365226633Sdim 10366193326Sed // Perform overload resolution. 10367193326Sed OverloadCandidateSet::iterator Best; 10368212904Sdim switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10369193326Sed case OR_Success: { 10370193326Sed // We found a built-in operator or an overloaded operator. 10371193326Sed FunctionDecl *FnDecl = Best->Function; 10372193326Sed 10373193326Sed if (FnDecl) { 10374193326Sed // We matched an overloaded operator. Build a call to that 10375193326Sed // operator. 10376193326Sed 10377193326Sed // Convert the arguments. 10378193326Sed if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10379203955Srdivacky // Best->Access is only meaningful for class members. 10380205408Srdivacky CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10381203955Srdivacky 10382218893Sdim ExprResult Arg1 = 10383218893Sdim PerformCopyInitialization( 10384218893Sdim InitializedEntity::InitializeParameter(Context, 10385218893Sdim FnDecl->getParamDecl(0)), 10386218893Sdim SourceLocation(), Owned(Args[1])); 10387201361Srdivacky if (Arg1.isInvalid()) 10388193326Sed return ExprError(); 10389201361Srdivacky 10390221345Sdim ExprResult Arg0 = 10391221345Sdim PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10392221345Sdim Best->FoundDecl, Method); 10393221345Sdim if (Arg0.isInvalid()) 10394201361Srdivacky return ExprError(); 10395221345Sdim Args[0] = Arg0.takeAs<Expr>(); 10396201361Srdivacky Args[1] = RHS = Arg1.takeAs<Expr>(); 10397193326Sed } else { 10398193326Sed // Convert the arguments. 10399218893Sdim ExprResult Arg0 = PerformCopyInitialization( 10400218893Sdim InitializedEntity::InitializeParameter(Context, 10401218893Sdim FnDecl->getParamDecl(0)), 10402218893Sdim SourceLocation(), Owned(Args[0])); 10403201361Srdivacky if (Arg0.isInvalid()) 10404193326Sed return ExprError(); 10405201361Srdivacky 10406218893Sdim ExprResult Arg1 = 10407218893Sdim PerformCopyInitialization( 10408218893Sdim InitializedEntity::InitializeParameter(Context, 10409218893Sdim FnDecl->getParamDecl(1)), 10410218893Sdim SourceLocation(), Owned(Args[1])); 10411201361Srdivacky if (Arg1.isInvalid()) 10412201361Srdivacky return ExprError(); 10413201361Srdivacky Args[0] = LHS = Arg0.takeAs<Expr>(); 10414201361Srdivacky Args[1] = RHS = Arg1.takeAs<Expr>(); 10415193326Sed } 10416193326Sed 10417218893Sdim // Determine the result type. 10418218893Sdim QualType ResultTy = FnDecl->getResultType(); 10419218893Sdim ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10420218893Sdim ResultTy = ResultTy.getNonLValueExprType(Context); 10421193326Sed 10422193326Sed // Build the actual expression node. 10423226633Sdim ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10424249423Sdim Best->FoundDecl, 10425226633Sdim HadMultipleCandidates, OpLoc); 10426221345Sdim if (FnExpr.isInvalid()) 10427221345Sdim return ExprError(); 10428193326Sed 10429212904Sdim CXXOperatorCallExpr *TheCall = 10430221345Sdim new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10431243830Sdim Args, ResultTy, VK, OpLoc, 10432243830Sdim FPFeatures.fp_contract); 10433218893Sdim 10434218893Sdim if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10435198092Srdivacky FnDecl)) 10436198092Srdivacky return ExprError(); 10437198092Srdivacky 10438249423Sdim ArrayRef<const Expr *> ArgsArray(Args, 2); 10439249423Sdim // Cut off the implicit 'this'. 10440249423Sdim if (isa<CXXMethodDecl>(FnDecl)) 10441249423Sdim ArgsArray = ArgsArray.slice(1); 10442249423Sdim checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10443249423Sdim TheCall->getSourceRange(), VariadicDoesNotApply); 10444249423Sdim 10445212904Sdim return MaybeBindToTemporary(TheCall); 10446193326Sed } else { 10447193326Sed // We matched a built-in operator. Convert the arguments, then 10448193326Sed // break out so that we will build the appropriate built-in 10449193326Sed // operator node. 10450221345Sdim ExprResult ArgsRes0 = 10451221345Sdim PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10452221345Sdim Best->Conversions[0], AA_Passing); 10453221345Sdim if (ArgsRes0.isInvalid()) 10454193326Sed return ExprError(); 10455221345Sdim Args[0] = ArgsRes0.take(); 10456193326Sed 10457221345Sdim ExprResult ArgsRes1 = 10458221345Sdim PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10459221345Sdim Best->Conversions[1], AA_Passing); 10460221345Sdim if (ArgsRes1.isInvalid()) 10461221345Sdim return ExprError(); 10462221345Sdim Args[1] = ArgsRes1.take(); 10463193326Sed break; 10464193326Sed } 10465193326Sed } 10466193326Sed 10467198092Srdivacky case OR_No_Viable_Function: { 10468198092Srdivacky // C++ [over.match.oper]p9: 10469198092Srdivacky // If the operator is the operator , [...] and there are no 10470198092Srdivacky // viable functions, then the operator is assumed to be the 10471198092Srdivacky // built-in operator and interpreted according to clause 5. 10472212904Sdim if (Opc == BO_Comma) 10473198092Srdivacky break; 10474198092Srdivacky 10475218893Sdim // For class as left operand for assignment or compound assigment 10476218893Sdim // operator do not fall through to handling in built-in, but report that 10477218893Sdim // no overloaded assignment operator found 10478212904Sdim ExprResult Result = ExprError(); 10479218893Sdim if (Args[0]->getType()->isRecordType() && 10480212904Sdim Opc >= BO_Assign && Opc <= BO_OrAssign) { 10481193326Sed Diag(OpLoc, diag::err_ovl_no_viable_oper) 10482193326Sed << BinaryOperator::getOpcodeStr(Opc) 10483198092Srdivacky << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10484198092Srdivacky } else { 10485223017Sdim // This is an erroneous use of an operator which can be overloaded by 10486223017Sdim // a non-member function. Check for non-member operators which were 10487223017Sdim // defined too late to be candidates. 10488234353Sdim if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10489223017Sdim // FIXME: Recover by calling the found function. 10490223017Sdim return ExprError(); 10491223017Sdim 10492198092Srdivacky // No viable function; try to create a built-in operation, which will 10493198092Srdivacky // produce an error. Then, show the non-viable candidates. 10494198092Srdivacky Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10495193326Sed } 10496218893Sdim assert(Result.isInvalid() && 10497198092Srdivacky "C++ binary operator overloading is missing candidates!"); 10498198092Srdivacky if (Result.isInvalid()) 10499234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10500212904Sdim BinaryOperator::getOpcodeStr(Opc), OpLoc); 10501243830Sdim return Result; 10502198092Srdivacky } 10503193326Sed 10504193326Sed case OR_Ambiguous: 10505218893Sdim Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10506193326Sed << BinaryOperator::getOpcodeStr(Opc) 10507218893Sdim << Args[0]->getType() << Args[1]->getType() 10508198092Srdivacky << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10509234353Sdim CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10510212904Sdim BinaryOperator::getOpcodeStr(Opc), OpLoc); 10511193326Sed return ExprError(); 10512193326Sed 10513193326Sed case OR_Deleted: 10514234353Sdim if (isImplicitlyDeleted(Best->Function)) { 10515234353Sdim CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10516234353Sdim Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10517249423Sdim << Context.getRecordType(Method->getParent()) 10518249423Sdim << getSpecialMember(Method); 10519234353Sdim 10520249423Sdim // The user probably meant to call this special member. Just 10521249423Sdim // explain why it's deleted. 10522249423Sdim NoteDeletedFunction(Method); 10523249423Sdim return ExprError(); 10524234353Sdim } else { 10525234353Sdim Diag(OpLoc, diag::err_ovl_deleted_oper) 10526234353Sdim << Best->Function->isDeleted() 10527234353Sdim << BinaryOperator::getOpcodeStr(Opc) 10528234353Sdim << getDeletedOrUnavailableSuffix(Best->Function) 10529234353Sdim << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10530234353Sdim } 10531234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10532226633Sdim BinaryOperator::getOpcodeStr(Opc), OpLoc); 10533193326Sed return ExprError(); 10534202379Srdivacky } 10535193326Sed 10536198092Srdivacky // We matched a built-in operator; build it. 10537198092Srdivacky return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10538193326Sed} 10539193326Sed 10540212904SdimExprResult 10541198893SrdivackySema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10542198893Srdivacky SourceLocation RLoc, 10543212904Sdim Expr *Base, Expr *Idx) { 10544212904Sdim Expr *Args[2] = { Base, Idx }; 10545198893Srdivacky DeclarationName OpName = 10546198893Srdivacky Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10547198893Srdivacky 10548198893Srdivacky // If either side is type-dependent, create an appropriate dependent 10549198893Srdivacky // expression. 10550198893Srdivacky if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10551198893Srdivacky 10552203955Srdivacky CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10553212904Sdim // CHECKME: no 'operator' keyword? 10554212904Sdim DeclarationNameInfo OpNameInfo(OpName, LLoc); 10555212904Sdim OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10556199990Srdivacky UnresolvedLookupExpr *Fn 10557218893Sdim = UnresolvedLookupExpr::Create(Context, NamingClass, 10558221345Sdim NestedNameSpecifierLoc(), OpNameInfo, 10559208600Srdivacky /*ADL*/ true, /*Overloaded*/ false, 10560208600Srdivacky UnresolvedSetIterator(), 10561208600Srdivacky UnresolvedSetIterator()); 10562199990Srdivacky // Can't add any actual overloads yet 10563198893Srdivacky 10564198893Srdivacky return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10565243830Sdim Args, 10566198893Srdivacky Context.DependentTy, 10567218893Sdim VK_RValue, 10568243830Sdim RLoc, false)); 10569198893Srdivacky } 10570198893Srdivacky 10571234353Sdim // Handle placeholders on both operands. 10572234353Sdim if (checkPlaceholderForOverload(*this, Args[0])) 10573234353Sdim return ExprError(); 10574234353Sdim if (checkPlaceholderForOverload(*this, Args[1])) 10575234353Sdim return ExprError(); 10576218893Sdim 10577198893Srdivacky // Build an empty overload set. 10578203955Srdivacky OverloadCandidateSet CandidateSet(LLoc); 10579198893Srdivacky 10580198893Srdivacky // Subscript can only be overloaded as a member function. 10581198893Srdivacky 10582198893Srdivacky // Add operator candidates that are member functions. 10583251662Sdim AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10584198893Srdivacky 10585198893Srdivacky // Add builtin operator candidates. 10586251662Sdim AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10587198893Srdivacky 10588226633Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 10589226633Sdim 10590198893Srdivacky // Perform overload resolution. 10591198893Srdivacky OverloadCandidateSet::iterator Best; 10592212904Sdim switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10593198893Srdivacky case OR_Success: { 10594198893Srdivacky // We found a built-in operator or an overloaded operator. 10595198893Srdivacky FunctionDecl *FnDecl = Best->Function; 10596198893Srdivacky 10597198893Srdivacky if (FnDecl) { 10598198893Srdivacky // We matched an overloaded operator. Build a call to that 10599198893Srdivacky // operator. 10600198893Srdivacky 10601205408Srdivacky CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10602203955Srdivacky 10603198893Srdivacky // Convert the arguments. 10604198893Srdivacky CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10605221345Sdim ExprResult Arg0 = 10606221345Sdim PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10607221345Sdim Best->FoundDecl, Method); 10608221345Sdim if (Arg0.isInvalid()) 10609198893Srdivacky return ExprError(); 10610221345Sdim Args[0] = Arg0.take(); 10611198893Srdivacky 10612203955Srdivacky // Convert the arguments. 10613212904Sdim ExprResult InputInit 10614203955Srdivacky = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10615218893Sdim Context, 10616203955Srdivacky FnDecl->getParamDecl(0)), 10617218893Sdim SourceLocation(), 10618203955Srdivacky Owned(Args[1])); 10619203955Srdivacky if (InputInit.isInvalid()) 10620203955Srdivacky return ExprError(); 10621203955Srdivacky 10622203955Srdivacky Args[1] = InputInit.takeAs<Expr>(); 10623203955Srdivacky 10624198893Srdivacky // Determine the result type 10625218893Sdim QualType ResultTy = FnDecl->getResultType(); 10626218893Sdim ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10627218893Sdim ResultTy = ResultTy.getNonLValueExprType(Context); 10628198893Srdivacky 10629198893Srdivacky // Build the actual expression node. 10630234353Sdim DeclarationNameInfo OpLocInfo(OpName, LLoc); 10631234353Sdim OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10632226633Sdim ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10633249423Sdim Best->FoundDecl, 10634226633Sdim HadMultipleCandidates, 10635234353Sdim OpLocInfo.getLoc(), 10636234353Sdim OpLocInfo.getInfo()); 10637221345Sdim if (FnExpr.isInvalid()) 10638221345Sdim return ExprError(); 10639198893Srdivacky 10640212904Sdim CXXOperatorCallExpr *TheCall = 10641212904Sdim new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10642243830Sdim FnExpr.take(), Args, 10643243830Sdim ResultTy, VK, RLoc, 10644243830Sdim false); 10645198893Srdivacky 10646212904Sdim if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10647198893Srdivacky FnDecl)) 10648198893Srdivacky return ExprError(); 10649198893Srdivacky 10650212904Sdim return MaybeBindToTemporary(TheCall); 10651198893Srdivacky } else { 10652198893Srdivacky // We matched a built-in operator. Convert the arguments, then 10653198893Srdivacky // break out so that we will build the appropriate built-in 10654198893Srdivacky // operator node. 10655221345Sdim ExprResult ArgsRes0 = 10656221345Sdim PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10657221345Sdim Best->Conversions[0], AA_Passing); 10658221345Sdim if (ArgsRes0.isInvalid()) 10659198893Srdivacky return ExprError(); 10660221345Sdim Args[0] = ArgsRes0.take(); 10661198893Srdivacky 10662221345Sdim ExprResult ArgsRes1 = 10663221345Sdim PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10664221345Sdim Best->Conversions[1], AA_Passing); 10665221345Sdim if (ArgsRes1.isInvalid()) 10666221345Sdim return ExprError(); 10667221345Sdim Args[1] = ArgsRes1.take(); 10668221345Sdim 10669198893Srdivacky break; 10670198893Srdivacky } 10671198893Srdivacky } 10672198893Srdivacky 10673198893Srdivacky case OR_No_Viable_Function: { 10674202379Srdivacky if (CandidateSet.empty()) 10675202379Srdivacky Diag(LLoc, diag::err_ovl_no_oper) 10676202379Srdivacky << Args[0]->getType() << /*subscript*/ 0 10677202379Srdivacky << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10678202379Srdivacky else 10679202379Srdivacky Diag(LLoc, diag::err_ovl_no_viable_subscript) 10680202379Srdivacky << Args[0]->getType() 10681202379Srdivacky << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10682234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10683212904Sdim "[]", LLoc); 10684202379Srdivacky return ExprError(); 10685198893Srdivacky } 10686198893Srdivacky 10687198893Srdivacky case OR_Ambiguous: 10688218893Sdim Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10689218893Sdim << "[]" 10690218893Sdim << Args[0]->getType() << Args[1]->getType() 10691218893Sdim << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10692234353Sdim CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10693212904Sdim "[]", LLoc); 10694198893Srdivacky return ExprError(); 10695198893Srdivacky 10696198893Srdivacky case OR_Deleted: 10697198893Srdivacky Diag(LLoc, diag::err_ovl_deleted_oper) 10698198893Srdivacky << Best->Function->isDeleted() << "[]" 10699221345Sdim << getDeletedOrUnavailableSuffix(Best->Function) 10700198893Srdivacky << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10701234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10702212904Sdim "[]", LLoc); 10703198893Srdivacky return ExprError(); 10704198893Srdivacky } 10705198893Srdivacky 10706198893Srdivacky // We matched a built-in operator; build it. 10707212904Sdim return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10708198893Srdivacky} 10709198893Srdivacky 10710193326Sed/// BuildCallToMemberFunction - Build a call to a member 10711193326Sed/// function. MemExpr is the expression that refers to the member 10712193326Sed/// function (and includes the object parameter), Args/NumArgs are the 10713193326Sed/// arguments to the function call (not including the object 10714193326Sed/// parameter). The caller needs to validate that the member 10715221345Sdim/// expression refers to a non-static member function or an overloaded 10716221345Sdim/// member function. 10717212904SdimExprResult 10718198092SrdivackySema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10719198092Srdivacky SourceLocation LParenLoc, Expr **Args, 10720218893Sdim unsigned NumArgs, SourceLocation RParenLoc) { 10721221345Sdim assert(MemExprE->getType() == Context.BoundMemberTy || 10722221345Sdim MemExprE->getType() == Context.OverloadTy); 10723221345Sdim 10724193326Sed // Dig out the member expression. This holds both the object 10725193326Sed // argument and the member function we're referring to. 10726199990Srdivacky Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10727218893Sdim 10728221345Sdim // Determine whether this is a call to a pointer-to-member function. 10729221345Sdim if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10730221345Sdim assert(op->getType() == Context.BoundMemberTy); 10731221345Sdim assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10732221345Sdim 10733221345Sdim QualType fnType = 10734221345Sdim op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10735221345Sdim 10736221345Sdim const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10737221345Sdim QualType resultType = proto->getCallResultType(Context); 10738221345Sdim ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10739221345Sdim 10740221345Sdim // Check that the object type isn't more qualified than the 10741221345Sdim // member function we're calling. 10742221345Sdim Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10743221345Sdim 10744221345Sdim QualType objectType = op->getLHS()->getType(); 10745221345Sdim if (op->getOpcode() == BO_PtrMemI) 10746221345Sdim objectType = objectType->castAs<PointerType>()->getPointeeType(); 10747221345Sdim Qualifiers objectQuals = objectType.getQualifiers(); 10748221345Sdim 10749221345Sdim Qualifiers difference = objectQuals - funcQuals; 10750221345Sdim difference.removeObjCGCAttr(); 10751221345Sdim difference.removeAddressSpace(); 10752221345Sdim if (difference) { 10753221345Sdim std::string qualsString = difference.getAsString(); 10754221345Sdim Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10755221345Sdim << fnType.getUnqualifiedType() 10756221345Sdim << qualsString 10757221345Sdim << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10758221345Sdim } 10759221345Sdim 10760221345Sdim CXXMemberCallExpr *call 10761243830Sdim = new (Context) CXXMemberCallExpr(Context, MemExprE, 10762243830Sdim llvm::makeArrayRef(Args, NumArgs), 10763221345Sdim resultType, valueKind, RParenLoc); 10764221345Sdim 10765221345Sdim if (CheckCallReturnType(proto->getResultType(), 10766234353Sdim op->getRHS()->getLocStart(), 10767221345Sdim call, 0)) 10768221345Sdim return ExprError(); 10769221345Sdim 10770221345Sdim if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10771221345Sdim return ExprError(); 10772221345Sdim 10773221345Sdim return MaybeBindToTemporary(call); 10774221345Sdim } 10775221345Sdim 10776234353Sdim UnbridgedCastsSet UnbridgedCasts; 10777234353Sdim if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10778234353Sdim return ExprError(); 10779234353Sdim 10780199990Srdivacky MemberExpr *MemExpr; 10781193326Sed CXXMethodDecl *Method = 0; 10782207619Srdivacky DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10783204793Srdivacky NestedNameSpecifier *Qualifier = 0; 10784199990Srdivacky if (isa<MemberExpr>(NakedMemExpr)) { 10785199990Srdivacky MemExpr = cast<MemberExpr>(NakedMemExpr); 10786199990Srdivacky Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10787206084Srdivacky FoundDecl = MemExpr->getFoundDecl(); 10788204793Srdivacky Qualifier = MemExpr->getQualifier(); 10789234353Sdim UnbridgedCasts.restore(); 10790199990Srdivacky } else { 10791199990Srdivacky UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10792204793Srdivacky Qualifier = UnresExpr->getQualifier(); 10793218893Sdim 10794200583Srdivacky QualType ObjectType = UnresExpr->getBaseType(); 10795218893Sdim Expr::Classification ObjectClassification 10796218893Sdim = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10797218893Sdim : UnresExpr->getBase()->Classify(Context); 10798200583Srdivacky 10799193326Sed // Add overload candidates 10800203955Srdivacky OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10801198092Srdivacky 10802200583Srdivacky // FIXME: avoid copy. 10803200583Srdivacky TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10804200583Srdivacky if (UnresExpr->hasExplicitTemplateArgs()) { 10805200583Srdivacky UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10806200583Srdivacky TemplateArgs = &TemplateArgsBuffer; 10807200583Srdivacky } 10808200583Srdivacky 10809199990Srdivacky for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10810199990Srdivacky E = UnresExpr->decls_end(); I != E; ++I) { 10811199990Srdivacky 10812200583Srdivacky NamedDecl *Func = *I; 10813200583Srdivacky CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10814200583Srdivacky if (isa<UsingShadowDecl>(Func)) 10815200583Srdivacky Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10816200583Srdivacky 10817218893Sdim 10818218893Sdim // Microsoft supports direct constructor calls. 10819234353Sdim if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10820234353Sdim AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10821234353Sdim llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10822218893Sdim } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10823198893Srdivacky // If explicit template arguments were provided, we can't call a 10824198893Srdivacky // non-template member function. 10825200583Srdivacky if (TemplateArgs) 10826198893Srdivacky continue; 10827218893Sdim 10828205408Srdivacky AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10829218893Sdim ObjectClassification, 10830234353Sdim llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10831218893Sdim /*SuppressUserConversions=*/false); 10832199990Srdivacky } else { 10833199990Srdivacky AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10834205408Srdivacky I.getPair(), ActingDC, TemplateArgs, 10835218893Sdim ObjectType, ObjectClassification, 10836234353Sdim llvm::makeArrayRef(Args, NumArgs), 10837234353Sdim CandidateSet, 10838198092Srdivacky /*SuppressUsedConversions=*/false); 10839199990Srdivacky } 10840193326Sed } 10841193326Sed 10842199990Srdivacky DeclarationName DeclName = UnresExpr->getMemberName(); 10843199990Srdivacky 10844234353Sdim UnbridgedCasts.restore(); 10845234353Sdim 10846193326Sed OverloadCandidateSet::iterator Best; 10847212904Sdim switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10848218893Sdim Best)) { 10849193326Sed case OR_Success: 10850193326Sed Method = cast<CXXMethodDecl>(Best->Function); 10851206084Srdivacky FoundDecl = Best->FoundDecl; 10852205408Srdivacky CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10853251662Sdim if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 10854251662Sdim return ExprError(); 10855193326Sed break; 10856193326Sed 10857193326Sed case OR_No_Viable_Function: 10858199990Srdivacky Diag(UnresExpr->getMemberLoc(), 10859193326Sed diag::err_ovl_no_viable_member_function_in_call) 10860198092Srdivacky << DeclName << MemExprE->getSourceRange(); 10861234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10862234353Sdim llvm::makeArrayRef(Args, NumArgs)); 10863193326Sed // FIXME: Leaking incoming expressions! 10864200583Srdivacky return ExprError(); 10865193326Sed 10866193326Sed case OR_Ambiguous: 10867199990Srdivacky Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10868198092Srdivacky << DeclName << MemExprE->getSourceRange(); 10869234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10870234353Sdim llvm::makeArrayRef(Args, NumArgs)); 10871193326Sed // FIXME: Leaking incoming expressions! 10872200583Srdivacky return ExprError(); 10873193326Sed 10874193326Sed case OR_Deleted: 10875199990Srdivacky Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10876193326Sed << Best->Function->isDeleted() 10877219077Sdim << DeclName 10878221345Sdim << getDeletedOrUnavailableSuffix(Best->Function) 10879219077Sdim << MemExprE->getSourceRange(); 10880234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10881234353Sdim llvm::makeArrayRef(Args, NumArgs)); 10882193326Sed // FIXME: Leaking incoming expressions! 10883200583Srdivacky return ExprError(); 10884193326Sed } 10885193326Sed 10886206084Srdivacky MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10887200583Srdivacky 10888200583Srdivacky // If overload resolution picked a static member, build a 10889200583Srdivacky // non-member call based on that function. 10890200583Srdivacky if (Method->isStatic()) { 10891200583Srdivacky return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10892200583Srdivacky Args, NumArgs, RParenLoc); 10893200583Srdivacky } 10894200583Srdivacky 10895199990Srdivacky MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10896193326Sed } 10897193326Sed 10898218893Sdim QualType ResultType = Method->getResultType(); 10899218893Sdim ExprValueKind VK = Expr::getValueKindForType(ResultType); 10900218893Sdim ResultType = ResultType.getNonLValueExprType(Context); 10901218893Sdim 10902193326Sed assert(Method && "Member call to something that isn't a method?"); 10903218893Sdim CXXMemberCallExpr *TheCall = 10904243830Sdim new (Context) CXXMemberCallExpr(Context, MemExprE, 10905243830Sdim llvm::makeArrayRef(Args, NumArgs), 10906218893Sdim ResultType, VK, RParenLoc); 10907193326Sed 10908198092Srdivacky // Check for a valid return type. 10909218893Sdim if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10910212904Sdim TheCall, Method)) 10911200583Srdivacky return ExprError(); 10912218893Sdim 10913193326Sed // Convert the object argument (for a non-static member function call). 10914206084Srdivacky // We only need to do this if there was actually an overload; otherwise 10915206084Srdivacky // it was done at lookup. 10916221345Sdim if (!Method->isStatic()) { 10917221345Sdim ExprResult ObjectArg = 10918221345Sdim PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10919221345Sdim FoundDecl, Method); 10920221345Sdim if (ObjectArg.isInvalid()) 10921221345Sdim return ExprError(); 10922221345Sdim MemExpr->setBase(ObjectArg.take()); 10923221345Sdim } 10924193326Sed 10925193326Sed // Convert the rest of the arguments 10926218893Sdim const FunctionProtoType *Proto = 10927218893Sdim Method->getType()->getAs<FunctionProtoType>(); 10928212904Sdim if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10929193326Sed RParenLoc)) 10930200583Srdivacky return ExprError(); 10931193326Sed 10932234353Sdim DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10933234353Sdim 10934239462Sdim if (CheckFunctionCall(Method, TheCall, Proto)) 10935200583Srdivacky return ExprError(); 10936198092Srdivacky 10937223017Sdim if ((isa<CXXConstructorDecl>(CurContext) || 10938223017Sdim isa<CXXDestructorDecl>(CurContext)) && 10939223017Sdim TheCall->getMethodDecl()->isPure()) { 10940223017Sdim const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10941223017Sdim 10942224145Sdim if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10943223017Sdim Diag(MemExpr->getLocStart(), 10944223017Sdim diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10945223017Sdim << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10946223017Sdim << MD->getParent()->getDeclName(); 10947223017Sdim 10948223017Sdim Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10949224145Sdim } 10950223017Sdim } 10951212904Sdim return MaybeBindToTemporary(TheCall); 10952193326Sed} 10953193326Sed 10954193326Sed/// BuildCallToObjectOfClassType - Build a call to an object of class 10955193326Sed/// type (C++ [over.call.object]), which can end up invoking an 10956193326Sed/// overloaded function call operator (@c operator()) or performing a 10957193326Sed/// user-defined conversion on the object argument. 10958212904SdimExprResult 10959221345SdimSema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10960193326Sed SourceLocation LParenLoc, 10961193326Sed Expr **Args, unsigned NumArgs, 10962193326Sed SourceLocation RParenLoc) { 10963234353Sdim if (checkPlaceholderForOverload(*this, Obj)) 10964234353Sdim return ExprError(); 10965221345Sdim ExprResult Object = Owned(Obj); 10966218893Sdim 10967234353Sdim UnbridgedCastsSet UnbridgedCasts; 10968234353Sdim if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10969234353Sdim return ExprError(); 10970234353Sdim 10971221345Sdim assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10972221345Sdim const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10973198092Srdivacky 10974193326Sed // C++ [over.call.object]p1: 10975193326Sed // If the primary-expression E in the function call syntax 10976198092Srdivacky // evaluates to a class object of type "cv T", then the set of 10977193326Sed // candidate functions includes at least the function call 10978193326Sed // operators of T. The function call operators of T are obtained by 10979193326Sed // ordinary lookup of the name operator() in the context of 10980193326Sed // (E).operator(). 10981203955Srdivacky OverloadCandidateSet CandidateSet(LParenLoc); 10982193326Sed DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10983193326Sed 10984221345Sdim if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10985239462Sdim diag::err_incomplete_object_call, Object.get())) 10986198398Srdivacky return true; 10987218893Sdim 10988199482Srdivacky LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10989199482Srdivacky LookupQualifiedName(R, Record->getDecl()); 10990199482Srdivacky R.suppressDiagnostics(); 10991199482Srdivacky 10992199482Srdivacky for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10993199482Srdivacky Oper != OperEnd; ++Oper) { 10994221345Sdim AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10995251662Sdim Object.get()->Classify(Context), 10996251662Sdim llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10997199482Srdivacky /*SuppressUserConversions=*/ false); 10998199482Srdivacky } 10999218893Sdim 11000193326Sed // C++ [over.call.object]p2: 11001226633Sdim // In addition, for each (non-explicit in C++0x) conversion function 11002226633Sdim // declared in T of the form 11003193326Sed // 11004193326Sed // operator conversion-type-id () cv-qualifier; 11005193326Sed // 11006193326Sed // where cv-qualifier is the same cv-qualification as, or a 11007193326Sed // greater cv-qualification than, cv, and where conversion-type-id 11008193326Sed // denotes the type "pointer to function of (P1,...,Pn) returning 11009193326Sed // R", or the type "reference to pointer to function of 11010193326Sed // (P1,...,Pn) returning R", or the type "reference to function 11011193326Sed // of (P1,...,Pn) returning R", a surrogate call function [...] 11012193326Sed // is also considered as a candidate function. Similarly, 11013193326Sed // surrogate call functions are added to the set of candidate 11014193326Sed // functions for each conversion function declared in an 11015193326Sed // accessible base class provided the function is not hidden 11016193326Sed // within T by another intervening declaration. 11017249423Sdim std::pair<CXXRecordDecl::conversion_iterator, 11018249423Sdim CXXRecordDecl::conversion_iterator> Conversions 11019202379Srdivacky = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11020249423Sdim for (CXXRecordDecl::conversion_iterator 11021249423Sdim I = Conversions.first, E = Conversions.second; I != E; ++I) { 11022200583Srdivacky NamedDecl *D = *I; 11023200583Srdivacky CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11024200583Srdivacky if (isa<UsingShadowDecl>(D)) 11025200583Srdivacky D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11026218893Sdim 11027198398Srdivacky // Skip over templated conversion functions; they aren't 11028198398Srdivacky // surrogates. 11029200583Srdivacky if (isa<FunctionTemplateDecl>(D)) 11030198398Srdivacky continue; 11031193326Sed 11032200583Srdivacky CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11033226633Sdim if (!Conv->isExplicit()) { 11034226633Sdim // Strip the reference type (if any) and then the pointer type (if 11035226633Sdim // any) to get down to what might be a function type. 11036226633Sdim QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11037226633Sdim if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11038226633Sdim ConvType = ConvPtrType->getPointeeType(); 11039199990Srdivacky 11040226633Sdim if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11041226633Sdim { 11042226633Sdim AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11043234353Sdim Object.get(), llvm::makeArrayRef(Args, NumArgs), 11044234353Sdim CandidateSet); 11045226633Sdim } 11046226633Sdim } 11047193326Sed } 11048193326Sed 11049226633Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 11050226633Sdim 11051193326Sed // Perform overload resolution. 11052193326Sed OverloadCandidateSet::iterator Best; 11053221345Sdim switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11054212904Sdim Best)) { 11055193326Sed case OR_Success: 11056193326Sed // Overload resolution succeeded; we'll build the appropriate call 11057193326Sed // below. 11058193326Sed break; 11059193326Sed 11060193326Sed case OR_No_Viable_Function: 11061202379Srdivacky if (CandidateSet.empty()) 11062234353Sdim Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11063221345Sdim << Object.get()->getType() << /*call*/ 1 11064221345Sdim << Object.get()->getSourceRange(); 11065202379Srdivacky else 11066234353Sdim Diag(Object.get()->getLocStart(), 11067202379Srdivacky diag::err_ovl_no_viable_object_call) 11068221345Sdim << Object.get()->getType() << Object.get()->getSourceRange(); 11069234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11070234353Sdim llvm::makeArrayRef(Args, NumArgs)); 11071193326Sed break; 11072193326Sed 11073193326Sed case OR_Ambiguous: 11074234353Sdim Diag(Object.get()->getLocStart(), 11075193326Sed diag::err_ovl_ambiguous_object_call) 11076221345Sdim << Object.get()->getType() << Object.get()->getSourceRange(); 11077234353Sdim CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 11078234353Sdim llvm::makeArrayRef(Args, NumArgs)); 11079193326Sed break; 11080193326Sed 11081193326Sed case OR_Deleted: 11082234353Sdim Diag(Object.get()->getLocStart(), 11083193326Sed diag::err_ovl_deleted_object_call) 11084193326Sed << Best->Function->isDeleted() 11085221345Sdim << Object.get()->getType() 11086221345Sdim << getDeletedOrUnavailableSuffix(Best->Function) 11087221345Sdim << Object.get()->getSourceRange(); 11088234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11089234353Sdim llvm::makeArrayRef(Args, NumArgs)); 11090193326Sed break; 11091198092Srdivacky } 11092193326Sed 11093212904Sdim if (Best == CandidateSet.end()) 11094193326Sed return true; 11095193326Sed 11096234353Sdim UnbridgedCasts.restore(); 11097234353Sdim 11098193326Sed if (Best->Function == 0) { 11099193326Sed // Since there is no function declaration, this is one of the 11100193326Sed // surrogate candidates. Dig out the conversion function. 11101198092Srdivacky CXXConversionDecl *Conv 11102193326Sed = cast<CXXConversionDecl>( 11103193326Sed Best->Conversions[0].UserDefined.ConversionFunction); 11104193326Sed 11105221345Sdim CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11106251662Sdim if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11107251662Sdim return ExprError(); 11108203955Srdivacky 11109193326Sed // We selected one of the surrogate functions that converts the 11110193326Sed // object parameter to a function pointer. Perform the conversion 11111193326Sed // on the object argument, then let ActOnCallExpr finish the job. 11112218893Sdim 11113198092Srdivacky // Create an implicit member expr to refer to the conversion operator. 11114198092Srdivacky // and then call it. 11115226633Sdim ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11116226633Sdim Conv, HadMultipleCandidates); 11117218893Sdim if (Call.isInvalid()) 11118218893Sdim return ExprError(); 11119234353Sdim // Record usage of conversion in an implicit cast. 11120234353Sdim Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11121234353Sdim CK_UserDefinedConversion, 11122234353Sdim Call.get(), 0, VK_RValue)); 11123218893Sdim 11124218893Sdim return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 11125218893Sdim RParenLoc); 11126193326Sed } 11127193326Sed 11128221345Sdim CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11129203955Srdivacky 11130193326Sed // We found an overloaded operator(). Build a CXXOperatorCallExpr 11131193326Sed // that calls this method, using Object for the implicit object 11132193326Sed // parameter and passing along the remaining arguments. 11133193326Sed CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11134243830Sdim 11135243830Sdim // An error diagnostic has already been printed when parsing the declaration. 11136243830Sdim if (Method->isInvalidDecl()) 11137243830Sdim return ExprError(); 11138243830Sdim 11139218893Sdim const FunctionProtoType *Proto = 11140218893Sdim Method->getType()->getAs<FunctionProtoType>(); 11141193326Sed 11142193326Sed unsigned NumArgsInProto = Proto->getNumArgs(); 11143193326Sed unsigned NumArgsToCheck = NumArgs; 11144193326Sed 11145193326Sed // Build the full argument list for the method call (the 11146193326Sed // implicit object parameter is placed at the beginning of the 11147193326Sed // list). 11148193326Sed Expr **MethodArgs; 11149193326Sed if (NumArgs < NumArgsInProto) { 11150193326Sed NumArgsToCheck = NumArgsInProto; 11151193326Sed MethodArgs = new Expr*[NumArgsInProto + 1]; 11152193326Sed } else { 11153193326Sed MethodArgs = new Expr*[NumArgs + 1]; 11154193326Sed } 11155221345Sdim MethodArgs[0] = Object.get(); 11156193326Sed for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11157193326Sed MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11158198092Srdivacky 11159234353Sdim DeclarationNameInfo OpLocInfo( 11160234353Sdim Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11161234353Sdim OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11162249423Sdim ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11163234353Sdim HadMultipleCandidates, 11164234353Sdim OpLocInfo.getLoc(), 11165234353Sdim OpLocInfo.getInfo()); 11166221345Sdim if (NewFn.isInvalid()) 11167221345Sdim return true; 11168193326Sed 11169193326Sed // Once we've built TheCall, all of the expressions are properly 11170193326Sed // owned. 11171218893Sdim QualType ResultTy = Method->getResultType(); 11172218893Sdim ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11173218893Sdim ResultTy = ResultTy.getNonLValueExprType(Context); 11174218893Sdim 11175212904Sdim CXXOperatorCallExpr *TheCall = 11176221345Sdim new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11177243830Sdim llvm::makeArrayRef(MethodArgs, NumArgs+1), 11178243830Sdim ResultTy, VK, RParenLoc, false); 11179193326Sed delete [] MethodArgs; 11180193326Sed 11181218893Sdim if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11182198092Srdivacky Method)) 11183198092Srdivacky return true; 11184218893Sdim 11185193326Sed // We may have default arguments. If so, we need to allocate more 11186193326Sed // slots in the call for them. 11187193326Sed if (NumArgs < NumArgsInProto) 11188193326Sed TheCall->setNumArgs(Context, NumArgsInProto + 1); 11189193326Sed else if (NumArgs > NumArgsInProto) 11190193326Sed NumArgsToCheck = NumArgsInProto; 11191193326Sed 11192193326Sed bool IsError = false; 11193193326Sed 11194193326Sed // Initialize the implicit object parameter. 11195221345Sdim ExprResult ObjRes = 11196221345Sdim PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11197221345Sdim Best->FoundDecl, Method); 11198221345Sdim if (ObjRes.isInvalid()) 11199221345Sdim IsError = true; 11200221345Sdim else 11201243830Sdim Object = ObjRes; 11202221345Sdim TheCall->setArg(0, Object.take()); 11203193326Sed 11204193326Sed // Check the argument types. 11205193326Sed for (unsigned i = 0; i != NumArgsToCheck; i++) { 11206193326Sed Expr *Arg; 11207193326Sed if (i < NumArgs) { 11208193326Sed Arg = Args[i]; 11209198092Srdivacky 11210193326Sed // Pass the argument. 11211203955Srdivacky 11212212904Sdim ExprResult InputInit 11213203955Srdivacky = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11214218893Sdim Context, 11215203955Srdivacky Method->getParamDecl(i)), 11216212904Sdim SourceLocation(), Arg); 11217218893Sdim 11218203955Srdivacky IsError |= InputInit.isInvalid(); 11219203955Srdivacky Arg = InputInit.takeAs<Expr>(); 11220193326Sed } else { 11221212904Sdim ExprResult DefArg 11222199482Srdivacky = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11223199482Srdivacky if (DefArg.isInvalid()) { 11224199482Srdivacky IsError = true; 11225199482Srdivacky break; 11226199482Srdivacky } 11227218893Sdim 11228199482Srdivacky Arg = DefArg.takeAs<Expr>(); 11229193326Sed } 11230193326Sed 11231193326Sed TheCall->setArg(i + 1, Arg); 11232193326Sed } 11233193326Sed 11234193326Sed // If this is a variadic call, handle args passed through "...". 11235193326Sed if (Proto->isVariadic()) { 11236193326Sed // Promote the arguments (C99 6.5.2.2p7). 11237239462Sdim for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11238221345Sdim ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11239221345Sdim IsError |= Arg.isInvalid(); 11240221345Sdim TheCall->setArg(i + 1, Arg.take()); 11241193326Sed } 11242193326Sed } 11243193326Sed 11244193326Sed if (IsError) return true; 11245193326Sed 11246234353Sdim DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11247234353Sdim 11248239462Sdim if (CheckFunctionCall(Method, TheCall, Proto)) 11249198092Srdivacky return true; 11250198092Srdivacky 11251212904Sdim return MaybeBindToTemporary(TheCall); 11252193326Sed} 11253193326Sed 11254193326Sed/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11255198092Srdivacky/// (if one exists), where @c Base is an expression of class type and 11256193326Sed/// @c Member is the name of the member we're trying to find. 11257212904SdimExprResult 11258212904SdimSema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11259218893Sdim assert(Base->getType()->isRecordType() && 11260218893Sdim "left-hand side must have class type"); 11261198092Srdivacky 11262234353Sdim if (checkPlaceholderForOverload(*this, Base)) 11263234353Sdim return ExprError(); 11264218893Sdim 11265203955Srdivacky SourceLocation Loc = Base->getExprLoc(); 11266203955Srdivacky 11267193326Sed // C++ [over.ref]p1: 11268193326Sed // 11269193326Sed // [...] An expression x->m is interpreted as (x.operator->())->m 11270193326Sed // for a class object x of type T if T::operator->() exists and if 11271193326Sed // the operator is selected as the best match function by the 11272193326Sed // overload resolution mechanism (13.3). 11273218893Sdim DeclarationName OpName = 11274218893Sdim Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11275203955Srdivacky OverloadCandidateSet CandidateSet(Loc); 11276198092Srdivacky const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11277198092Srdivacky 11278203955Srdivacky if (RequireCompleteType(Loc, Base->getType(), 11279239462Sdim diag::err_typecheck_incomplete_tag, Base)) 11280199482Srdivacky return ExprError(); 11281198092Srdivacky 11282199482Srdivacky LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11283199482Srdivacky LookupQualifiedName(R, BaseRecord->getDecl()); 11284199482Srdivacky R.suppressDiagnostics(); 11285199482Srdivacky 11286198092Srdivacky for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11287200583Srdivacky Oper != OperEnd; ++Oper) { 11288218893Sdim AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11289251662Sdim None, CandidateSet, /*SuppressUserConversions=*/false); 11290200583Srdivacky } 11291193326Sed 11292226633Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 11293226633Sdim 11294193326Sed // Perform overload resolution. 11295193326Sed OverloadCandidateSet::iterator Best; 11296212904Sdim switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11297193326Sed case OR_Success: 11298193326Sed // Overload resolution succeeded; we'll build the call below. 11299193326Sed break; 11300193326Sed 11301193326Sed case OR_No_Viable_Function: 11302193326Sed if (CandidateSet.empty()) 11303193326Sed Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11304198092Srdivacky << Base->getType() << Base->getSourceRange(); 11305193326Sed else 11306193326Sed Diag(OpLoc, diag::err_ovl_no_viable_oper) 11307198092Srdivacky << "operator->" << Base->getSourceRange(); 11308234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11309198092Srdivacky return ExprError(); 11310193326Sed 11311193326Sed case OR_Ambiguous: 11312218893Sdim Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11313218893Sdim << "->" << Base->getType() << Base->getSourceRange(); 11314234353Sdim CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11315198092Srdivacky return ExprError(); 11316193326Sed 11317193326Sed case OR_Deleted: 11318193326Sed Diag(OpLoc, diag::err_ovl_deleted_oper) 11319193326Sed << Best->Function->isDeleted() 11320219077Sdim << "->" 11321221345Sdim << getDeletedOrUnavailableSuffix(Best->Function) 11322219077Sdim << Base->getSourceRange(); 11323234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11324198092Srdivacky return ExprError(); 11325193326Sed } 11326193326Sed 11327205408Srdivacky CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11328205408Srdivacky 11329193326Sed // Convert the object parameter. 11330193326Sed CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11331221345Sdim ExprResult BaseResult = 11332221345Sdim PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11333221345Sdim Best->FoundDecl, Method); 11334221345Sdim if (BaseResult.isInvalid()) 11335198092Srdivacky return ExprError(); 11336221345Sdim Base = BaseResult.take(); 11337193326Sed 11338193326Sed // Build the operator call. 11339249423Sdim ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11340234353Sdim HadMultipleCandidates, OpLoc); 11341221345Sdim if (FnExpr.isInvalid()) 11342221345Sdim return ExprError(); 11343218893Sdim 11344218893Sdim QualType ResultTy = Method->getResultType(); 11345218893Sdim ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11346218893Sdim ResultTy = ResultTy.getNonLValueExprType(Context); 11347212904Sdim CXXOperatorCallExpr *TheCall = 11348221345Sdim new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11349243830Sdim Base, ResultTy, VK, OpLoc, false); 11350198092Srdivacky 11351218893Sdim if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11352198092Srdivacky Method)) 11353198092Srdivacky return ExprError(); 11354221345Sdim 11355221345Sdim return MaybeBindToTemporary(TheCall); 11356193326Sed} 11357193326Sed 11358234353Sdim/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11359234353Sdim/// a literal operator described by the provided lookup results. 11360234353SdimExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11361234353Sdim DeclarationNameInfo &SuffixInfo, 11362234353Sdim ArrayRef<Expr*> Args, 11363234353Sdim SourceLocation LitEndLoc, 11364234353Sdim TemplateArgumentListInfo *TemplateArgs) { 11365234353Sdim SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11366234353Sdim 11367234353Sdim OverloadCandidateSet CandidateSet(UDSuffixLoc); 11368234353Sdim AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11369234353Sdim TemplateArgs); 11370234353Sdim 11371234353Sdim bool HadMultipleCandidates = (CandidateSet.size() > 1); 11372234353Sdim 11373234353Sdim // Perform overload resolution. This will usually be trivial, but might need 11374234353Sdim // to perform substitutions for a literal operator template. 11375234353Sdim OverloadCandidateSet::iterator Best; 11376234353Sdim switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11377234353Sdim case OR_Success: 11378234353Sdim case OR_Deleted: 11379234353Sdim break; 11380234353Sdim 11381234353Sdim case OR_No_Viable_Function: 11382234353Sdim Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11383234353Sdim << R.getLookupName(); 11384234353Sdim CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11385234353Sdim return ExprError(); 11386234353Sdim 11387234353Sdim case OR_Ambiguous: 11388234353Sdim Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11389234353Sdim CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11390234353Sdim return ExprError(); 11391234353Sdim } 11392234353Sdim 11393234353Sdim FunctionDecl *FD = Best->Function; 11394249423Sdim ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11395249423Sdim HadMultipleCandidates, 11396234353Sdim SuffixInfo.getLoc(), 11397234353Sdim SuffixInfo.getInfo()); 11398234353Sdim if (Fn.isInvalid()) 11399234353Sdim return true; 11400234353Sdim 11401234353Sdim // Check the argument types. This should almost always be a no-op, except 11402234353Sdim // that array-to-pointer decay is applied to string literals. 11403234353Sdim Expr *ConvArgs[2]; 11404251662Sdim for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11405234353Sdim ExprResult InputInit = PerformCopyInitialization( 11406234353Sdim InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11407234353Sdim SourceLocation(), Args[ArgIdx]); 11408234353Sdim if (InputInit.isInvalid()) 11409234353Sdim return true; 11410234353Sdim ConvArgs[ArgIdx] = InputInit.take(); 11411234353Sdim } 11412234353Sdim 11413234353Sdim QualType ResultTy = FD->getResultType(); 11414234353Sdim ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11415234353Sdim ResultTy = ResultTy.getNonLValueExprType(Context); 11416234353Sdim 11417234353Sdim UserDefinedLiteral *UDL = 11418243830Sdim new (Context) UserDefinedLiteral(Context, Fn.take(), 11419243830Sdim llvm::makeArrayRef(ConvArgs, Args.size()), 11420234353Sdim ResultTy, VK, LitEndLoc, UDSuffixLoc); 11421234353Sdim 11422234353Sdim if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11423234353Sdim return ExprError(); 11424234353Sdim 11425239462Sdim if (CheckFunctionCall(FD, UDL, NULL)) 11426234353Sdim return ExprError(); 11427234353Sdim 11428234353Sdim return MaybeBindToTemporary(UDL); 11429234353Sdim} 11430234353Sdim 11431243830Sdim/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11432243830Sdim/// given LookupResult is non-empty, it is assumed to describe a member which 11433243830Sdim/// will be invoked. Otherwise, the function will be found via argument 11434243830Sdim/// dependent lookup. 11435243830Sdim/// CallExpr is set to a valid expression and FRS_Success returned on success, 11436243830Sdim/// otherwise CallExpr is set to ExprError() and some non-success value 11437243830Sdim/// is returned. 11438243830SdimSema::ForRangeStatus 11439243830SdimSema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11440243830Sdim SourceLocation RangeLoc, VarDecl *Decl, 11441243830Sdim BeginEndFunction BEF, 11442243830Sdim const DeclarationNameInfo &NameInfo, 11443243830Sdim LookupResult &MemberLookup, 11444243830Sdim OverloadCandidateSet *CandidateSet, 11445243830Sdim Expr *Range, ExprResult *CallExpr) { 11446243830Sdim CandidateSet->clear(); 11447243830Sdim if (!MemberLookup.empty()) { 11448243830Sdim ExprResult MemberRef = 11449243830Sdim BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11450243830Sdim /*IsPtr=*/false, CXXScopeSpec(), 11451243830Sdim /*TemplateKWLoc=*/SourceLocation(), 11452243830Sdim /*FirstQualifierInScope=*/0, 11453243830Sdim MemberLookup, 11454243830Sdim /*TemplateArgs=*/0); 11455243830Sdim if (MemberRef.isInvalid()) { 11456243830Sdim *CallExpr = ExprError(); 11457243830Sdim Diag(Range->getLocStart(), diag::note_in_for_range) 11458243830Sdim << RangeLoc << BEF << Range->getType(); 11459243830Sdim return FRS_DiagnosticIssued; 11460243830Sdim } 11461251662Sdim *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11462243830Sdim if (CallExpr->isInvalid()) { 11463243830Sdim *CallExpr = ExprError(); 11464243830Sdim Diag(Range->getLocStart(), diag::note_in_for_range) 11465243830Sdim << RangeLoc << BEF << Range->getType(); 11466243830Sdim return FRS_DiagnosticIssued; 11467243830Sdim } 11468243830Sdim } else { 11469243830Sdim UnresolvedSet<0> FoundNames; 11470243830Sdim UnresolvedLookupExpr *Fn = 11471243830Sdim UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11472243830Sdim NestedNameSpecifierLoc(), NameInfo, 11473243830Sdim /*NeedsADL=*/true, /*Overloaded=*/false, 11474243830Sdim FoundNames.begin(), FoundNames.end()); 11475243830Sdim 11476243830Sdim bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11477243830Sdim CandidateSet, CallExpr); 11478243830Sdim if (CandidateSet->empty() || CandidateSetError) { 11479243830Sdim *CallExpr = ExprError(); 11480243830Sdim return FRS_NoViableFunction; 11481243830Sdim } 11482243830Sdim OverloadCandidateSet::iterator Best; 11483243830Sdim OverloadingResult OverloadResult = 11484243830Sdim CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11485243830Sdim 11486243830Sdim if (OverloadResult == OR_No_Viable_Function) { 11487243830Sdim *CallExpr = ExprError(); 11488243830Sdim return FRS_NoViableFunction; 11489243830Sdim } 11490243830Sdim *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11491243830Sdim Loc, 0, CandidateSet, &Best, 11492243830Sdim OverloadResult, 11493243830Sdim /*AllowTypoCorrection=*/false); 11494243830Sdim if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11495243830Sdim *CallExpr = ExprError(); 11496243830Sdim Diag(Range->getLocStart(), diag::note_in_for_range) 11497243830Sdim << RangeLoc << BEF << Range->getType(); 11498243830Sdim return FRS_DiagnosticIssued; 11499243830Sdim } 11500243830Sdim } 11501243830Sdim return FRS_Success; 11502243830Sdim} 11503243830Sdim 11504243830Sdim 11505193326Sed/// FixOverloadedFunctionReference - E is an expression that refers to 11506193326Sed/// a C++ overloaded function (possibly with some parentheses and 11507193326Sed/// perhaps a '&' around it). We have resolved the overloaded function 11508193326Sed/// to the function declaration Fn, so patch up the expression E to 11509198398Srdivacky/// refer (possibly indirectly) to Fn. Returns the new expr. 11510207619SrdivackyExpr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11511206084Srdivacky FunctionDecl *Fn) { 11512193326Sed if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11513206084Srdivacky Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11514206084Srdivacky Found, Fn); 11515199990Srdivacky if (SubExpr == PE->getSubExpr()) 11516218893Sdim return PE; 11517218893Sdim 11518199990Srdivacky return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11519218893Sdim } 11520218893Sdim 11521199990Srdivacky if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11522206084Srdivacky Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11523206084Srdivacky Found, Fn); 11524218893Sdim assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11525199990Srdivacky SubExpr->getType()) && 11526198893Srdivacky "Implicit cast type cannot be determined from overload"); 11527212904Sdim assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11528199990Srdivacky if (SubExpr == ICE->getSubExpr()) 11529218893Sdim return ICE; 11530218893Sdim 11531218893Sdim return ImplicitCastExpr::Create(Context, ICE->getType(), 11532212904Sdim ICE->getCastKind(), 11533212904Sdim SubExpr, 0, 11534212904Sdim ICE->getValueKind()); 11535218893Sdim } 11536218893Sdim 11537199990Srdivacky if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11538212904Sdim assert(UnOp->getOpcode() == UO_AddrOf && 11539193326Sed "Can only take the address of an overloaded function"); 11540193326Sed if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11541193326Sed if (Method->isStatic()) { 11542193326Sed // Do nothing: static member functions aren't any different 11543193326Sed // from non-member functions. 11544199990Srdivacky } else { 11545199990Srdivacky // Fix the sub expression, which really has to be an 11546199990Srdivacky // UnresolvedLookupExpr holding an overloaded member function 11547199990Srdivacky // or template. 11548206084Srdivacky Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11549206084Srdivacky Found, Fn); 11550199990Srdivacky if (SubExpr == UnOp->getSubExpr()) 11551218893Sdim return UnOp; 11552199990Srdivacky 11553199990Srdivacky assert(isa<DeclRefExpr>(SubExpr) 11554199990Srdivacky && "fixed to something other than a decl ref"); 11555199990Srdivacky assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11556199990Srdivacky && "fixed to a member ref with no nested name qualifier"); 11557199990Srdivacky 11558199990Srdivacky // We have taken the address of a pointer to member 11559199990Srdivacky // function. Perform the computation here so that we get the 11560199990Srdivacky // appropriate pointer to member type. 11561199990Srdivacky QualType ClassType 11562199990Srdivacky = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11563199990Srdivacky QualType MemPtrType 11564199990Srdivacky = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11565199990Srdivacky 11566218893Sdim return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11567218893Sdim VK_RValue, OK_Ordinary, 11568218893Sdim UnOp->getOperatorLoc()); 11569193326Sed } 11570193326Sed } 11571206084Srdivacky Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11572206084Srdivacky Found, Fn); 11573199990Srdivacky if (SubExpr == UnOp->getSubExpr()) 11574218893Sdim return UnOp; 11575218893Sdim 11576212904Sdim return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11577199990Srdivacky Context.getPointerType(SubExpr->getType()), 11578218893Sdim VK_RValue, OK_Ordinary, 11579199990Srdivacky UnOp->getOperatorLoc()); 11580218893Sdim } 11581199990Srdivacky 11582199990Srdivacky if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11583200583Srdivacky // FIXME: avoid copy. 11584200583Srdivacky TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11585199990Srdivacky if (ULE->hasExplicitTemplateArgs()) { 11586200583Srdivacky ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11587200583Srdivacky TemplateArgs = &TemplateArgsBuffer; 11588199990Srdivacky } 11589199990Srdivacky 11590226633Sdim DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11591226633Sdim ULE->getQualifierLoc(), 11592234353Sdim ULE->getTemplateKeywordLoc(), 11593226633Sdim Fn, 11594234353Sdim /*enclosing*/ false, // FIXME? 11595226633Sdim ULE->getNameLoc(), 11596226633Sdim Fn->getType(), 11597226633Sdim VK_LValue, 11598226633Sdim Found.getDecl(), 11599226633Sdim TemplateArgs); 11600234982Sdim MarkDeclRefReferenced(DRE); 11601226633Sdim DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11602226633Sdim return DRE; 11603193326Sed } 11604199990Srdivacky 11605199990Srdivacky if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11606199990Srdivacky // FIXME: avoid copy. 11607200583Srdivacky TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11608200583Srdivacky if (MemExpr->hasExplicitTemplateArgs()) { 11609200583Srdivacky MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11610200583Srdivacky TemplateArgs = &TemplateArgsBuffer; 11611200583Srdivacky } 11612199990Srdivacky 11613200583Srdivacky Expr *Base; 11614200583Srdivacky 11615218893Sdim // If we're filling in a static method where we used to have an 11616218893Sdim // implicit member access, rewrite to a simple decl ref. 11617200583Srdivacky if (MemExpr->isImplicitAccess()) { 11618200583Srdivacky if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11619226633Sdim DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11620226633Sdim MemExpr->getQualifierLoc(), 11621234353Sdim MemExpr->getTemplateKeywordLoc(), 11622226633Sdim Fn, 11623234353Sdim /*enclosing*/ false, 11624226633Sdim MemExpr->getMemberLoc(), 11625226633Sdim Fn->getType(), 11626226633Sdim VK_LValue, 11627226633Sdim Found.getDecl(), 11628226633Sdim TemplateArgs); 11629234982Sdim MarkDeclRefReferenced(DRE); 11630226633Sdim DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11631226633Sdim return DRE; 11632202379Srdivacky } else { 11633202379Srdivacky SourceLocation Loc = MemExpr->getMemberLoc(); 11634202379Srdivacky if (MemExpr->getQualifier()) 11635221345Sdim Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11636234353Sdim CheckCXXThisCapture(Loc); 11637202379Srdivacky Base = new (Context) CXXThisExpr(Loc, 11638202379Srdivacky MemExpr->getBaseType(), 11639202379Srdivacky /*isImplicit=*/true); 11640202379Srdivacky } 11641200583Srdivacky } else 11642218893Sdim Base = MemExpr->getBase(); 11643200583Srdivacky 11644221345Sdim ExprValueKind valueKind; 11645221345Sdim QualType type; 11646221345Sdim if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11647221345Sdim valueKind = VK_LValue; 11648221345Sdim type = Fn->getType(); 11649221345Sdim } else { 11650221345Sdim valueKind = VK_RValue; 11651221345Sdim type = Context.BoundMemberTy; 11652221345Sdim } 11653221345Sdim 11654226633Sdim MemberExpr *ME = MemberExpr::Create(Context, Base, 11655226633Sdim MemExpr->isArrow(), 11656226633Sdim MemExpr->getQualifierLoc(), 11657234353Sdim MemExpr->getTemplateKeywordLoc(), 11658226633Sdim Fn, 11659226633Sdim Found, 11660226633Sdim MemExpr->getMemberNameInfo(), 11661226633Sdim TemplateArgs, 11662226633Sdim type, valueKind, OK_Ordinary); 11663226633Sdim ME->setHadMultipleCandidates(true); 11664243830Sdim MarkMemberReferenced(ME); 11665226633Sdim return ME; 11666199990Srdivacky } 11667218893Sdim 11668218893Sdim llvm_unreachable("Invalid reference to overloaded function"); 11669193326Sed} 11670193326Sed 11671218893SdimExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11672212904Sdim DeclAccessPair Found, 11673212904Sdim FunctionDecl *Fn) { 11674206084Srdivacky return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11675200583Srdivacky} 11676200583Srdivacky 11677193326Sed} // end namespace clang 11678