Home | History | Annotate | Download | only in Sema
      1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file provides Sema routines for C++ overloading.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Sema/Overload.h"
     15 #include "clang/AST/ASTContext.h"
     16 #include "clang/AST/CXXInheritance.h"
     17 #include "clang/AST/DeclObjC.h"
     18 #include "clang/AST/Expr.h"
     19 #include "clang/AST/ExprCXX.h"
     20 #include "clang/AST/ExprObjC.h"
     21 #include "clang/AST/TypeOrdering.h"
     22 #include "clang/Basic/Diagnostic.h"
     23 #include "clang/Basic/DiagnosticOptions.h"
     24 #include "clang/Basic/PartialDiagnostic.h"
     25 #include "clang/Basic/TargetInfo.h"
     26 #include "clang/Sema/Initialization.h"
     27 #include "clang/Sema/Lookup.h"
     28 #include "clang/Sema/SemaInternal.h"
     29 #include "clang/Sema/Template.h"
     30 #include "clang/Sema/TemplateDeduction.h"
     31 #include "llvm/ADT/DenseSet.h"
     32 #include "llvm/ADT/STLExtras.h"
     33 #include "llvm/ADT/SmallPtrSet.h"
     34 #include "llvm/ADT/SmallString.h"
     35 #include <algorithm>
     36 #include <cstdlib>
     37 
     38 namespace clang {
     39 using namespace sema;
     40 
     41 /// A convenience routine for creating a decayed reference to a function.
     42 static ExprResult
     43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
     44                       bool HadMultipleCandidates,
     45                       SourceLocation Loc = SourceLocation(),
     46                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
     47   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
     48     return ExprError();
     49   // If FoundDecl is different from Fn (such as if one is a template
     50   // and the other a specialization), make sure DiagnoseUseOfDecl is
     51   // called on both.
     52   // FIXME: This would be more comprehensively addressed by modifying
     53   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
     54   // being used.
     55   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
     56     return ExprError();
     57   DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
     58                                                  VK_LValue, Loc, LocInfo);
     59   if (HadMultipleCandidates)
     60     DRE->setHadMultipleCandidates(true);
     61 
     62   S.MarkDeclRefReferenced(DRE);
     63 
     64   ExprResult E = DRE;
     65   E = S.DefaultFunctionArrayConversion(E.get());
     66   if (E.isInvalid())
     67     return ExprError();
     68   return E;
     69 }
     70 
     71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
     72                                  bool InOverloadResolution,
     73                                  StandardConversionSequence &SCS,
     74                                  bool CStyle,
     75                                  bool AllowObjCWritebackConversion);
     76 
     77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
     78                                                  QualType &ToType,
     79                                                  bool InOverloadResolution,
     80                                                  StandardConversionSequence &SCS,
     81                                                  bool CStyle);
     82 static OverloadingResult
     83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
     84                         UserDefinedConversionSequence& User,
     85                         OverloadCandidateSet& Conversions,
     86                         bool AllowExplicit,
     87                         bool AllowObjCConversionOnExplicit);
     88 
     89 
     90 static ImplicitConversionSequence::CompareKind
     91 CompareStandardConversionSequences(Sema &S,
     92                                    const StandardConversionSequence& SCS1,
     93                                    const StandardConversionSequence& SCS2);
     94 
     95 static ImplicitConversionSequence::CompareKind
     96 CompareQualificationConversions(Sema &S,
     97                                 const StandardConversionSequence& SCS1,
     98                                 const StandardConversionSequence& SCS2);
     99 
    100 static ImplicitConversionSequence::CompareKind
    101 CompareDerivedToBaseConversions(Sema &S,
    102                                 const StandardConversionSequence& SCS1,
    103                                 const StandardConversionSequence& SCS2);
    104 
    105 
    106 
    107 /// GetConversionCategory - Retrieve the implicit conversion
    108 /// category corresponding to the given implicit conversion kind.
    109 ImplicitConversionCategory
    110 GetConversionCategory(ImplicitConversionKind Kind) {
    111   static const ImplicitConversionCategory
    112     Category[(int)ICK_Num_Conversion_Kinds] = {
    113     ICC_Identity,
    114     ICC_Lvalue_Transformation,
    115     ICC_Lvalue_Transformation,
    116     ICC_Lvalue_Transformation,
    117     ICC_Identity,
    118     ICC_Qualification_Adjustment,
    119     ICC_Promotion,
    120     ICC_Promotion,
    121     ICC_Promotion,
    122     ICC_Conversion,
    123     ICC_Conversion,
    124     ICC_Conversion,
    125     ICC_Conversion,
    126     ICC_Conversion,
    127     ICC_Conversion,
    128     ICC_Conversion,
    129     ICC_Conversion,
    130     ICC_Conversion,
    131     ICC_Conversion,
    132     ICC_Conversion,
    133     ICC_Conversion,
    134     ICC_Conversion
    135   };
    136   return Category[(int)Kind];
    137 }
    138 
    139 /// GetConversionRank - Retrieve the implicit conversion rank
    140 /// corresponding to the given implicit conversion kind.
    141 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
    142   static const ImplicitConversionRank
    143     Rank[(int)ICK_Num_Conversion_Kinds] = {
    144     ICR_Exact_Match,
    145     ICR_Exact_Match,
    146     ICR_Exact_Match,
    147     ICR_Exact_Match,
    148     ICR_Exact_Match,
    149     ICR_Exact_Match,
    150     ICR_Promotion,
    151     ICR_Promotion,
    152     ICR_Promotion,
    153     ICR_Conversion,
    154     ICR_Conversion,
    155     ICR_Conversion,
    156     ICR_Conversion,
    157     ICR_Conversion,
    158     ICR_Conversion,
    159     ICR_Conversion,
    160     ICR_Conversion,
    161     ICR_Conversion,
    162     ICR_Conversion,
    163     ICR_Conversion,
    164     ICR_Complex_Real_Conversion,
    165     ICR_Conversion,
    166     ICR_Conversion,
    167     ICR_Writeback_Conversion
    168   };
    169   return Rank[(int)Kind];
    170 }
    171 
    172 /// GetImplicitConversionName - Return the name of this kind of
    173 /// implicit conversion.
    174 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
    175   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
    176     "No conversion",
    177     "Lvalue-to-rvalue",
    178     "Array-to-pointer",
    179     "Function-to-pointer",
    180     "Noreturn adjustment",
    181     "Qualification",
    182     "Integral promotion",
    183     "Floating point promotion",
    184     "Complex promotion",
    185     "Integral conversion",
    186     "Floating conversion",
    187     "Complex conversion",
    188     "Floating-integral conversion",
    189     "Pointer conversion",
    190     "Pointer-to-member conversion",
    191     "Boolean conversion",
    192     "Compatible-types conversion",
    193     "Derived-to-base conversion",
    194     "Vector conversion",
    195     "Vector splat",
    196     "Complex-real conversion",
    197     "Block Pointer conversion",
    198     "Transparent Union Conversion"
    199     "Writeback conversion"
    200   };
    201   return Name[Kind];
    202 }
    203 
    204 /// StandardConversionSequence - Set the standard conversion
    205 /// sequence to the identity conversion.
    206 void StandardConversionSequence::setAsIdentityConversion() {
    207   First = ICK_Identity;
    208   Second = ICK_Identity;
    209   Third = ICK_Identity;
    210   DeprecatedStringLiteralToCharPtr = false;
    211   QualificationIncludesObjCLifetime = false;
    212   ReferenceBinding = false;
    213   DirectBinding = false;
    214   IsLvalueReference = true;
    215   BindsToFunctionLvalue = false;
    216   BindsToRvalue = false;
    217   BindsImplicitObjectArgumentWithoutRefQualifier = false;
    218   ObjCLifetimeConversionBinding = false;
    219   CopyConstructor = nullptr;
    220 }
    221 
    222 /// getRank - Retrieve the rank of this standard conversion sequence
    223 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
    224 /// implicit conversions.
    225 ImplicitConversionRank StandardConversionSequence::getRank() const {
    226   ImplicitConversionRank Rank = ICR_Exact_Match;
    227   if  (GetConversionRank(First) > Rank)
    228     Rank = GetConversionRank(First);
    229   if  (GetConversionRank(Second) > Rank)
    230     Rank = GetConversionRank(Second);
    231   if  (GetConversionRank(Third) > Rank)
    232     Rank = GetConversionRank(Third);
    233   return Rank;
    234 }
    235 
    236 /// isPointerConversionToBool - Determines whether this conversion is
    237 /// a conversion of a pointer or pointer-to-member to bool. This is
    238 /// used as part of the ranking of standard conversion sequences
    239 /// (C++ 13.3.3.2p4).
    240 bool StandardConversionSequence::isPointerConversionToBool() const {
    241   // Note that FromType has not necessarily been transformed by the
    242   // array-to-pointer or function-to-pointer implicit conversions, so
    243   // check for their presence as well as checking whether FromType is
    244   // a pointer.
    245   if (getToType(1)->isBooleanType() &&
    246       (getFromType()->isPointerType() ||
    247        getFromType()->isObjCObjectPointerType() ||
    248        getFromType()->isBlockPointerType() ||
    249        getFromType()->isNullPtrType() ||
    250        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
    251     return true;
    252 
    253   return false;
    254 }
    255 
    256 /// isPointerConversionToVoidPointer - Determines whether this
    257 /// conversion is a conversion of a pointer to a void pointer. This is
    258 /// used as part of the ranking of standard conversion sequences (C++
    259 /// 13.3.3.2p4).
    260 bool
    261 StandardConversionSequence::
    262 isPointerConversionToVoidPointer(ASTContext& Context) const {
    263   QualType FromType = getFromType();
    264   QualType ToType = getToType(1);
    265 
    266   // Note that FromType has not necessarily been transformed by the
    267   // array-to-pointer implicit conversion, so check for its presence
    268   // and redo the conversion to get a pointer.
    269   if (First == ICK_Array_To_Pointer)
    270     FromType = Context.getArrayDecayedType(FromType);
    271 
    272   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
    273     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
    274       return ToPtrType->getPointeeType()->isVoidType();
    275 
    276   return false;
    277 }
    278 
    279 /// Skip any implicit casts which could be either part of a narrowing conversion
    280 /// or after one in an implicit conversion.
    281 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
    282   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
    283     switch (ICE->getCastKind()) {
    284     case CK_NoOp:
    285     case CK_IntegralCast:
    286     case CK_IntegralToBoolean:
    287     case CK_IntegralToFloating:
    288     case CK_FloatingToIntegral:
    289     case CK_FloatingToBoolean:
    290     case CK_FloatingCast:
    291       Converted = ICE->getSubExpr();
    292       continue;
    293 
    294     default:
    295       return Converted;
    296     }
    297   }
    298 
    299   return Converted;
    300 }
    301 
    302 /// Check if this standard conversion sequence represents a narrowing
    303 /// conversion, according to C++11 [dcl.init.list]p7.
    304 ///
    305 /// \param Ctx  The AST context.
    306 /// \param Converted  The result of applying this standard conversion sequence.
    307 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
    308 ///        value of the expression prior to the narrowing conversion.
    309 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
    310 ///        type of the expression prior to the narrowing conversion.
    311 NarrowingKind
    312 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
    313                                              const Expr *Converted,
    314                                              APValue &ConstantValue,
    315                                              QualType &ConstantType) const {
    316   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
    317 
    318   // C++11 [dcl.init.list]p7:
    319   //   A narrowing conversion is an implicit conversion ...
    320   QualType FromType = getToType(0);
    321   QualType ToType = getToType(1);
    322   switch (Second) {
    323   // -- from a floating-point type to an integer type, or
    324   //
    325   // -- from an integer type or unscoped enumeration type to a floating-point
    326   //    type, except where the source is a constant expression and the actual
    327   //    value after conversion will fit into the target type and will produce
    328   //    the original value when converted back to the original type, or
    329   case ICK_Floating_Integral:
    330     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
    331       return NK_Type_Narrowing;
    332     } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
    333       llvm::APSInt IntConstantValue;
    334       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
    335       if (Initializer &&
    336           Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
    337         // Convert the integer to the floating type.
    338         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
    339         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
    340                                 llvm::APFloat::rmNearestTiesToEven);
    341         // And back.
    342         llvm::APSInt ConvertedValue = IntConstantValue;
    343         bool ignored;
    344         Result.convertToInteger(ConvertedValue,
    345                                 llvm::APFloat::rmTowardZero, &ignored);
    346         // If the resulting value is different, this was a narrowing conversion.
    347         if (IntConstantValue != ConvertedValue) {
    348           ConstantValue = APValue(IntConstantValue);
    349           ConstantType = Initializer->getType();
    350           return NK_Constant_Narrowing;
    351         }
    352       } else {
    353         // Variables are always narrowings.
    354         return NK_Variable_Narrowing;
    355       }
    356     }
    357     return NK_Not_Narrowing;
    358 
    359   // -- from long double to double or float, or from double to float, except
    360   //    where the source is a constant expression and the actual value after
    361   //    conversion is within the range of values that can be represented (even
    362   //    if it cannot be represented exactly), or
    363   case ICK_Floating_Conversion:
    364     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
    365         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
    366       // FromType is larger than ToType.
    367       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
    368       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
    369         // Constant!
    370         assert(ConstantValue.isFloat());
    371         llvm::APFloat FloatVal = ConstantValue.getFloat();
    372         // Convert the source value into the target type.
    373         bool ignored;
    374         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
    375           Ctx.getFloatTypeSemantics(ToType),
    376           llvm::APFloat::rmNearestTiesToEven, &ignored);
    377         // If there was no overflow, the source value is within the range of
    378         // values that can be represented.
    379         if (ConvertStatus & llvm::APFloat::opOverflow) {
    380           ConstantType = Initializer->getType();
    381           return NK_Constant_Narrowing;
    382         }
    383       } else {
    384         return NK_Variable_Narrowing;
    385       }
    386     }
    387     return NK_Not_Narrowing;
    388 
    389   // -- from an integer type or unscoped enumeration type to an integer type
    390   //    that cannot represent all the values of the original type, except where
    391   //    the source is a constant expression and the actual value after
    392   //    conversion will fit into the target type and will produce the original
    393   //    value when converted back to the original type.
    394   case ICK_Boolean_Conversion:  // Bools are integers too.
    395     if (!FromType->isIntegralOrUnscopedEnumerationType()) {
    396       // Boolean conversions can be from pointers and pointers to members
    397       // [conv.bool], and those aren't considered narrowing conversions.
    398       return NK_Not_Narrowing;
    399     }  // Otherwise, fall through to the integral case.
    400   case ICK_Integral_Conversion: {
    401     assert(FromType->isIntegralOrUnscopedEnumerationType());
    402     assert(ToType->isIntegralOrUnscopedEnumerationType());
    403     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
    404     const unsigned FromWidth = Ctx.getIntWidth(FromType);
    405     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
    406     const unsigned ToWidth = Ctx.getIntWidth(ToType);
    407 
    408     if (FromWidth > ToWidth ||
    409         (FromWidth == ToWidth && FromSigned != ToSigned) ||
    410         (FromSigned && !ToSigned)) {
    411       // Not all values of FromType can be represented in ToType.
    412       llvm::APSInt InitializerValue;
    413       const Expr *Initializer = IgnoreNarrowingConversion(Converted);
    414       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
    415         // Such conversions on variables are always narrowing.
    416         return NK_Variable_Narrowing;
    417       }
    418       bool Narrowing = false;
    419       if (FromWidth < ToWidth) {
    420         // Negative -> unsigned is narrowing. Otherwise, more bits is never
    421         // narrowing.
    422         if (InitializerValue.isSigned() && InitializerValue.isNegative())
    423           Narrowing = true;
    424       } else {
    425         // Add a bit to the InitializerValue so we don't have to worry about
    426         // signed vs. unsigned comparisons.
    427         InitializerValue = InitializerValue.extend(
    428           InitializerValue.getBitWidth() + 1);
    429         // Convert the initializer to and from the target width and signed-ness.
    430         llvm::APSInt ConvertedValue = InitializerValue;
    431         ConvertedValue = ConvertedValue.trunc(ToWidth);
    432         ConvertedValue.setIsSigned(ToSigned);
    433         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
    434         ConvertedValue.setIsSigned(InitializerValue.isSigned());
    435         // If the result is different, this was a narrowing conversion.
    436         if (ConvertedValue != InitializerValue)
    437           Narrowing = true;
    438       }
    439       if (Narrowing) {
    440         ConstantType = Initializer->getType();
    441         ConstantValue = APValue(InitializerValue);
    442         return NK_Constant_Narrowing;
    443       }
    444     }
    445     return NK_Not_Narrowing;
    446   }
    447 
    448   default:
    449     // Other kinds of conversions are not narrowings.
    450     return NK_Not_Narrowing;
    451   }
    452 }
    453 
    454 /// dump - Print this standard conversion sequence to standard
    455 /// error. Useful for debugging overloading issues.
    456 void StandardConversionSequence::dump() const {
    457   raw_ostream &OS = llvm::errs();
    458   bool PrintedSomething = false;
    459   if (First != ICK_Identity) {
    460     OS << GetImplicitConversionName(First);
    461     PrintedSomething = true;
    462   }
    463 
    464   if (Second != ICK_Identity) {
    465     if (PrintedSomething) {
    466       OS << " -> ";
    467     }
    468     OS << GetImplicitConversionName(Second);
    469 
    470     if (CopyConstructor) {
    471       OS << " (by copy constructor)";
    472     } else if (DirectBinding) {
    473       OS << " (direct reference binding)";
    474     } else if (ReferenceBinding) {
    475       OS << " (reference binding)";
    476     }
    477     PrintedSomething = true;
    478   }
    479 
    480   if (Third != ICK_Identity) {
    481     if (PrintedSomething) {
    482       OS << " -> ";
    483     }
    484     OS << GetImplicitConversionName(Third);
    485     PrintedSomething = true;
    486   }
    487 
    488   if (!PrintedSomething) {
    489     OS << "No conversions required";
    490   }
    491 }
    492 
    493 /// dump - Print this user-defined conversion sequence to standard
    494 /// error. Useful for debugging overloading issues.
    495 void UserDefinedConversionSequence::dump() const {
    496   raw_ostream &OS = llvm::errs();
    497   if (Before.First || Before.Second || Before.Third) {
    498     Before.dump();
    499     OS << " -> ";
    500   }
    501   if (ConversionFunction)
    502     OS << '\'' << *ConversionFunction << '\'';
    503   else
    504     OS << "aggregate initialization";
    505   if (After.First || After.Second || After.Third) {
    506     OS << " -> ";
    507     After.dump();
    508   }
    509 }
    510 
    511 /// dump - Print this implicit conversion sequence to standard
    512 /// error. Useful for debugging overloading issues.
    513 void ImplicitConversionSequence::dump() const {
    514   raw_ostream &OS = llvm::errs();
    515   if (isStdInitializerListElement())
    516     OS << "Worst std::initializer_list element conversion: ";
    517   switch (ConversionKind) {
    518   case StandardConversion:
    519     OS << "Standard conversion: ";
    520     Standard.dump();
    521     break;
    522   case UserDefinedConversion:
    523     OS << "User-defined conversion: ";
    524     UserDefined.dump();
    525     break;
    526   case EllipsisConversion:
    527     OS << "Ellipsis conversion";
    528     break;
    529   case AmbiguousConversion:
    530     OS << "Ambiguous conversion";
    531     break;
    532   case BadConversion:
    533     OS << "Bad conversion";
    534     break;
    535   }
    536 
    537   OS << "\n";
    538 }
    539 
    540 void AmbiguousConversionSequence::construct() {
    541   new (&conversions()) ConversionSet();
    542 }
    543 
    544 void AmbiguousConversionSequence::destruct() {
    545   conversions().~ConversionSet();
    546 }
    547 
    548 void
    549 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
    550   FromTypePtr = O.FromTypePtr;
    551   ToTypePtr = O.ToTypePtr;
    552   new (&conversions()) ConversionSet(O.conversions());
    553 }
    554 
    555 namespace {
    556   // Structure used by DeductionFailureInfo to store
    557   // template argument information.
    558   struct DFIArguments {
    559     TemplateArgument FirstArg;
    560     TemplateArgument SecondArg;
    561   };
    562   // Structure used by DeductionFailureInfo to store
    563   // template parameter and template argument information.
    564   struct DFIParamWithArguments : DFIArguments {
    565     TemplateParameter Param;
    566   };
    567 }
    568 
    569 /// \brief Convert from Sema's representation of template deduction information
    570 /// to the form used in overload-candidate information.
    571 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
    572                                               Sema::TemplateDeductionResult TDK,
    573                                               TemplateDeductionInfo &Info) {
    574   DeductionFailureInfo Result;
    575   Result.Result = static_cast<unsigned>(TDK);
    576   Result.HasDiagnostic = false;
    577   Result.Data = nullptr;
    578   switch (TDK) {
    579   case Sema::TDK_Success:
    580   case Sema::TDK_Invalid:
    581   case Sema::TDK_InstantiationDepth:
    582   case Sema::TDK_TooManyArguments:
    583   case Sema::TDK_TooFewArguments:
    584     break;
    585 
    586   case Sema::TDK_Incomplete:
    587   case Sema::TDK_InvalidExplicitArguments:
    588     Result.Data = Info.Param.getOpaqueValue();
    589     break;
    590 
    591   case Sema::TDK_NonDeducedMismatch: {
    592     // FIXME: Should allocate from normal heap so that we can free this later.
    593     DFIArguments *Saved = new (Context) DFIArguments;
    594     Saved->FirstArg = Info.FirstArg;
    595     Saved->SecondArg = Info.SecondArg;
    596     Result.Data = Saved;
    597     break;
    598   }
    599 
    600   case Sema::TDK_Inconsistent:
    601   case Sema::TDK_Underqualified: {
    602     // FIXME: Should allocate from normal heap so that we can free this later.
    603     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
    604     Saved->Param = Info.Param;
    605     Saved->FirstArg = Info.FirstArg;
    606     Saved->SecondArg = Info.SecondArg;
    607     Result.Data = Saved;
    608     break;
    609   }
    610 
    611   case Sema::TDK_SubstitutionFailure:
    612     Result.Data = Info.take();
    613     if (Info.hasSFINAEDiagnostic()) {
    614       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
    615           SourceLocation(), PartialDiagnostic::NullDiagnostic());
    616       Info.takeSFINAEDiagnostic(*Diag);
    617       Result.HasDiagnostic = true;
    618     }
    619     break;
    620 
    621   case Sema::TDK_FailedOverloadResolution:
    622     Result.Data = Info.Expression;
    623     break;
    624 
    625   case Sema::TDK_MiscellaneousDeductionFailure:
    626     break;
    627   }
    628 
    629   return Result;
    630 }
    631 
    632 void DeductionFailureInfo::Destroy() {
    633   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
    634   case Sema::TDK_Success:
    635   case Sema::TDK_Invalid:
    636   case Sema::TDK_InstantiationDepth:
    637   case Sema::TDK_Incomplete:
    638   case Sema::TDK_TooManyArguments:
    639   case Sema::TDK_TooFewArguments:
    640   case Sema::TDK_InvalidExplicitArguments:
    641   case Sema::TDK_FailedOverloadResolution:
    642     break;
    643 
    644   case Sema::TDK_Inconsistent:
    645   case Sema::TDK_Underqualified:
    646   case Sema::TDK_NonDeducedMismatch:
    647     // FIXME: Destroy the data?
    648     Data = nullptr;
    649     break;
    650 
    651   case Sema::TDK_SubstitutionFailure:
    652     // FIXME: Destroy the template argument list?
    653     Data = nullptr;
    654     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
    655       Diag->~PartialDiagnosticAt();
    656       HasDiagnostic = false;
    657     }
    658     break;
    659 
    660   // Unhandled
    661   case Sema::TDK_MiscellaneousDeductionFailure:
    662     break;
    663   }
    664 }
    665 
    666 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
    667   if (HasDiagnostic)
    668     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
    669   return nullptr;
    670 }
    671 
    672 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
    673   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
    674   case Sema::TDK_Success:
    675   case Sema::TDK_Invalid:
    676   case Sema::TDK_InstantiationDepth:
    677   case Sema::TDK_TooManyArguments:
    678   case Sema::TDK_TooFewArguments:
    679   case Sema::TDK_SubstitutionFailure:
    680   case Sema::TDK_NonDeducedMismatch:
    681   case Sema::TDK_FailedOverloadResolution:
    682     return TemplateParameter();
    683 
    684   case Sema::TDK_Incomplete:
    685   case Sema::TDK_InvalidExplicitArguments:
    686     return TemplateParameter::getFromOpaqueValue(Data);
    687 
    688   case Sema::TDK_Inconsistent:
    689   case Sema::TDK_Underqualified:
    690     return static_cast<DFIParamWithArguments*>(Data)->Param;
    691 
    692   // Unhandled
    693   case Sema::TDK_MiscellaneousDeductionFailure:
    694     break;
    695   }
    696 
    697   return TemplateParameter();
    698 }
    699 
    700 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
    701   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
    702   case Sema::TDK_Success:
    703   case Sema::TDK_Invalid:
    704   case Sema::TDK_InstantiationDepth:
    705   case Sema::TDK_TooManyArguments:
    706   case Sema::TDK_TooFewArguments:
    707   case Sema::TDK_Incomplete:
    708   case Sema::TDK_InvalidExplicitArguments:
    709   case Sema::TDK_Inconsistent:
    710   case Sema::TDK_Underqualified:
    711   case Sema::TDK_NonDeducedMismatch:
    712   case Sema::TDK_FailedOverloadResolution:
    713     return nullptr;
    714 
    715   case Sema::TDK_SubstitutionFailure:
    716     return static_cast<TemplateArgumentList*>(Data);
    717 
    718   // Unhandled
    719   case Sema::TDK_MiscellaneousDeductionFailure:
    720     break;
    721   }
    722 
    723   return nullptr;
    724 }
    725 
    726 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
    727   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
    728   case Sema::TDK_Success:
    729   case Sema::TDK_Invalid:
    730   case Sema::TDK_InstantiationDepth:
    731   case Sema::TDK_Incomplete:
    732   case Sema::TDK_TooManyArguments:
    733   case Sema::TDK_TooFewArguments:
    734   case Sema::TDK_InvalidExplicitArguments:
    735   case Sema::TDK_SubstitutionFailure:
    736   case Sema::TDK_FailedOverloadResolution:
    737     return nullptr;
    738 
    739   case Sema::TDK_Inconsistent:
    740   case Sema::TDK_Underqualified:
    741   case Sema::TDK_NonDeducedMismatch:
    742     return &static_cast<DFIArguments*>(Data)->FirstArg;
    743 
    744   // Unhandled
    745   case Sema::TDK_MiscellaneousDeductionFailure:
    746     break;
    747   }
    748 
    749   return nullptr;
    750 }
    751 
    752 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
    753   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
    754   case Sema::TDK_Success:
    755   case Sema::TDK_Invalid:
    756   case Sema::TDK_InstantiationDepth:
    757   case Sema::TDK_Incomplete:
    758   case Sema::TDK_TooManyArguments:
    759   case Sema::TDK_TooFewArguments:
    760   case Sema::TDK_InvalidExplicitArguments:
    761   case Sema::TDK_SubstitutionFailure:
    762   case Sema::TDK_FailedOverloadResolution:
    763     return nullptr;
    764 
    765   case Sema::TDK_Inconsistent:
    766   case Sema::TDK_Underqualified:
    767   case Sema::TDK_NonDeducedMismatch:
    768     return &static_cast<DFIArguments*>(Data)->SecondArg;
    769 
    770   // Unhandled
    771   case Sema::TDK_MiscellaneousDeductionFailure:
    772     break;
    773   }
    774 
    775   return nullptr;
    776 }
    777 
    778 Expr *DeductionFailureInfo::getExpr() {
    779   if (static_cast<Sema::TemplateDeductionResult>(Result) ==
    780         Sema::TDK_FailedOverloadResolution)
    781     return static_cast<Expr*>(Data);
    782 
    783   return nullptr;
    784 }
    785 
    786 void OverloadCandidateSet::destroyCandidates() {
    787   for (iterator i = begin(), e = end(); i != e; ++i) {
    788     for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
    789       i->Conversions[ii].~ImplicitConversionSequence();
    790     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
    791       i->DeductionFailure.Destroy();
    792   }
    793 }
    794 
    795 void OverloadCandidateSet::clear() {
    796   destroyCandidates();
    797   NumInlineSequences = 0;
    798   Candidates.clear();
    799   Functions.clear();
    800 }
    801 
    802 namespace {
    803   class UnbridgedCastsSet {
    804     struct Entry {
    805       Expr **Addr;
    806       Expr *Saved;
    807     };
    808     SmallVector<Entry, 2> Entries;
    809 
    810   public:
    811     void save(Sema &S, Expr *&E) {
    812       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
    813       Entry entry = { &E, E };
    814       Entries.push_back(entry);
    815       E = S.stripARCUnbridgedCast(E);
    816     }
    817 
    818     void restore() {
    819       for (SmallVectorImpl<Entry>::iterator
    820              i = Entries.begin(), e = Entries.end(); i != e; ++i)
    821         *i->Addr = i->Saved;
    822     }
    823   };
    824 }
    825 
    826 /// checkPlaceholderForOverload - Do any interesting placeholder-like
    827 /// preprocessing on the given expression.
    828 ///
    829 /// \param unbridgedCasts a collection to which to add unbridged casts;
    830 ///   without this, they will be immediately diagnosed as errors
    831 ///
    832 /// Return true on unrecoverable error.
    833 static bool
    834 checkPlaceholderForOverload(Sema &S, Expr *&E,
    835                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
    836   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
    837     // We can't handle overloaded expressions here because overload
    838     // resolution might reasonably tweak them.
    839     if (placeholder->getKind() == BuiltinType::Overload) return false;
    840 
    841     // If the context potentially accepts unbridged ARC casts, strip
    842     // the unbridged cast and add it to the collection for later restoration.
    843     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
    844         unbridgedCasts) {
    845       unbridgedCasts->save(S, E);
    846       return false;
    847     }
    848 
    849     // Go ahead and check everything else.
    850     ExprResult result = S.CheckPlaceholderExpr(E);
    851     if (result.isInvalid())
    852       return true;
    853 
    854     E = result.get();
    855     return false;
    856   }
    857 
    858   // Nothing to do.
    859   return false;
    860 }
    861 
    862 /// checkArgPlaceholdersForOverload - Check a set of call operands for
    863 /// placeholders.
    864 static bool checkArgPlaceholdersForOverload(Sema &S,
    865                                             MultiExprArg Args,
    866                                             UnbridgedCastsSet &unbridged) {
    867   for (unsigned i = 0, e = Args.size(); i != e; ++i)
    868     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
    869       return true;
    870 
    871   return false;
    872 }
    873 
    874 // IsOverload - Determine whether the given New declaration is an
    875 // overload of the declarations in Old. This routine returns false if
    876 // New and Old cannot be overloaded, e.g., if New has the same
    877 // signature as some function in Old (C++ 1.3.10) or if the Old
    878 // declarations aren't functions (or function templates) at all. When
    879 // it does return false, MatchedDecl will point to the decl that New
    880 // cannot be overloaded with.  This decl may be a UsingShadowDecl on
    881 // top of the underlying declaration.
    882 //
    883 // Example: Given the following input:
    884 //
    885 //   void f(int, float); // #1
    886 //   void f(int, int); // #2
    887 //   int f(int, int); // #3
    888 //
    889 // When we process #1, there is no previous declaration of "f",
    890 // so IsOverload will not be used.
    891 //
    892 // When we process #2, Old contains only the FunctionDecl for #1.  By
    893 // comparing the parameter types, we see that #1 and #2 are overloaded
    894 // (since they have different signatures), so this routine returns
    895 // false; MatchedDecl is unchanged.
    896 //
    897 // When we process #3, Old is an overload set containing #1 and #2. We
    898 // compare the signatures of #3 to #1 (they're overloaded, so we do
    899 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
    900 // identical (return types of functions are not part of the
    901 // signature), IsOverload returns false and MatchedDecl will be set to
    902 // point to the FunctionDecl for #2.
    903 //
    904 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
    905 // into a class by a using declaration.  The rules for whether to hide
    906 // shadow declarations ignore some properties which otherwise figure
    907 // into a function template's signature.
    908 Sema::OverloadKind
    909 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
    910                     NamedDecl *&Match, bool NewIsUsingDecl) {
    911   for (LookupResult::iterator I = Old.begin(), E = Old.end();
    912          I != E; ++I) {
    913     NamedDecl *OldD = *I;
    914 
    915     bool OldIsUsingDecl = false;
    916     if (isa<UsingShadowDecl>(OldD)) {
    917       OldIsUsingDecl = true;
    918 
    919       // We can always introduce two using declarations into the same
    920       // context, even if they have identical signatures.
    921       if (NewIsUsingDecl) continue;
    922 
    923       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
    924     }
    925 
    926     // If either declaration was introduced by a using declaration,
    927     // we'll need to use slightly different rules for matching.
    928     // Essentially, these rules are the normal rules, except that
    929     // function templates hide function templates with different
    930     // return types or template parameter lists.
    931     bool UseMemberUsingDeclRules =
    932       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
    933       !New->getFriendObjectKind();
    934 
    935     if (FunctionDecl *OldF = OldD->getAsFunction()) {
    936       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
    937         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
    938           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
    939           continue;
    940         }
    941 
    942         if (!isa<FunctionTemplateDecl>(OldD) &&
    943             !shouldLinkPossiblyHiddenDecl(*I, New))
    944           continue;
    945 
    946         Match = *I;
    947         return Ovl_Match;
    948       }
    949     } else if (isa<UsingDecl>(OldD)) {
    950       // We can overload with these, which can show up when doing
    951       // redeclaration checks for UsingDecls.
    952       assert(Old.getLookupKind() == LookupUsingDeclName);
    953     } else if (isa<TagDecl>(OldD)) {
    954       // We can always overload with tags by hiding them.
    955     } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
    956       // Optimistically assume that an unresolved using decl will
    957       // overload; if it doesn't, we'll have to diagnose during
    958       // template instantiation.
    959     } else {
    960       // (C++ 13p1):
    961       //   Only function declarations can be overloaded; object and type
    962       //   declarations cannot be overloaded.
    963       Match = *I;
    964       return Ovl_NonFunction;
    965     }
    966   }
    967 
    968   return Ovl_Overload;
    969 }
    970 
    971 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
    972                       bool UseUsingDeclRules) {
    973   // C++ [basic.start.main]p2: This function shall not be overloaded.
    974   if (New->isMain())
    975     return false;
    976 
    977   // MSVCRT user defined entry points cannot be overloaded.
    978   if (New->isMSVCRTEntryPoint())
    979     return false;
    980 
    981   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
    982   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
    983 
    984   // C++ [temp.fct]p2:
    985   //   A function template can be overloaded with other function templates
    986   //   and with normal (non-template) functions.
    987   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
    988     return true;
    989 
    990   // Is the function New an overload of the function Old?
    991   QualType OldQType = Context.getCanonicalType(Old->getType());
    992   QualType NewQType = Context.getCanonicalType(New->getType());
    993 
    994   // Compare the signatures (C++ 1.3.10) of the two functions to
    995   // determine whether they are overloads. If we find any mismatch
    996   // in the signature, they are overloads.
    997 
    998   // If either of these functions is a K&R-style function (no
    999   // prototype), then we consider them to have matching signatures.
   1000   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
   1001       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
   1002     return false;
   1003 
   1004   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
   1005   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
   1006 
   1007   // The signature of a function includes the types of its
   1008   // parameters (C++ 1.3.10), which includes the presence or absence
   1009   // of the ellipsis; see C++ DR 357).
   1010   if (OldQType != NewQType &&
   1011       (OldType->getNumParams() != NewType->getNumParams() ||
   1012        OldType->isVariadic() != NewType->isVariadic() ||
   1013        !FunctionParamTypesAreEqual(OldType, NewType)))
   1014     return true;
   1015 
   1016   // C++ [temp.over.link]p4:
   1017   //   The signature of a function template consists of its function
   1018   //   signature, its return type and its template parameter list. The names
   1019   //   of the template parameters are significant only for establishing the
   1020   //   relationship between the template parameters and the rest of the
   1021   //   signature.
   1022   //
   1023   // We check the return type and template parameter lists for function
   1024   // templates first; the remaining checks follow.
   1025   //
   1026   // However, we don't consider either of these when deciding whether
   1027   // a member introduced by a shadow declaration is hidden.
   1028   if (!UseUsingDeclRules && NewTemplate &&
   1029       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
   1030                                        OldTemplate->getTemplateParameters(),
   1031                                        false, TPL_TemplateMatch) ||
   1032        OldType->getReturnType() != NewType->getReturnType()))
   1033     return true;
   1034 
   1035   // If the function is a class member, its signature includes the
   1036   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
   1037   //
   1038   // As part of this, also check whether one of the member functions
   1039   // is static, in which case they are not overloads (C++
   1040   // 13.1p2). While not part of the definition of the signature,
   1041   // this check is important to determine whether these functions
   1042   // can be overloaded.
   1043   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
   1044   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
   1045   if (OldMethod && NewMethod &&
   1046       !OldMethod->isStatic() && !NewMethod->isStatic()) {
   1047     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
   1048       if (!UseUsingDeclRules &&
   1049           (OldMethod->getRefQualifier() == RQ_None ||
   1050            NewMethod->getRefQualifier() == RQ_None)) {
   1051         // C++0x [over.load]p2:
   1052         //   - Member function declarations with the same name and the same
   1053         //     parameter-type-list as well as member function template
   1054         //     declarations with the same name, the same parameter-type-list, and
   1055         //     the same template parameter lists cannot be overloaded if any of
   1056         //     them, but not all, have a ref-qualifier (8.3.5).
   1057         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
   1058           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
   1059         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
   1060       }
   1061       return true;
   1062     }
   1063 
   1064     // We may not have applied the implicit const for a constexpr member
   1065     // function yet (because we haven't yet resolved whether this is a static
   1066     // or non-static member function). Add it now, on the assumption that this
   1067     // is a redeclaration of OldMethod.
   1068     unsigned OldQuals = OldMethod->getTypeQualifiers();
   1069     unsigned NewQuals = NewMethod->getTypeQualifiers();
   1070     if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
   1071         !isa<CXXConstructorDecl>(NewMethod))
   1072       NewQuals |= Qualifiers::Const;
   1073 
   1074     // We do not allow overloading based off of '__restrict'.
   1075     OldQuals &= ~Qualifiers::Restrict;
   1076     NewQuals &= ~Qualifiers::Restrict;
   1077     if (OldQuals != NewQuals)
   1078       return true;
   1079   }
   1080 
   1081   // enable_if attributes are an order-sensitive part of the signature.
   1082   for (specific_attr_iterator<EnableIfAttr>
   1083          NewI = New->specific_attr_begin<EnableIfAttr>(),
   1084          NewE = New->specific_attr_end<EnableIfAttr>(),
   1085          OldI = Old->specific_attr_begin<EnableIfAttr>(),
   1086          OldE = Old->specific_attr_end<EnableIfAttr>();
   1087        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
   1088     if (NewI == NewE || OldI == OldE)
   1089       return true;
   1090     llvm::FoldingSetNodeID NewID, OldID;
   1091     NewI->getCond()->Profile(NewID, Context, true);
   1092     OldI->getCond()->Profile(OldID, Context, true);
   1093     if (NewID != OldID)
   1094       return true;
   1095   }
   1096 
   1097   // The signatures match; this is not an overload.
   1098   return false;
   1099 }
   1100 
   1101 /// \brief Checks availability of the function depending on the current
   1102 /// function context. Inside an unavailable function, unavailability is ignored.
   1103 ///
   1104 /// \returns true if \arg FD is unavailable and current context is inside
   1105 /// an available function, false otherwise.
   1106 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
   1107   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
   1108 }
   1109 
   1110 /// \brief Tries a user-defined conversion from From to ToType.
   1111 ///
   1112 /// Produces an implicit conversion sequence for when a standard conversion
   1113 /// is not an option. See TryImplicitConversion for more information.
   1114 static ImplicitConversionSequence
   1115 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
   1116                          bool SuppressUserConversions,
   1117                          bool AllowExplicit,
   1118                          bool InOverloadResolution,
   1119                          bool CStyle,
   1120                          bool AllowObjCWritebackConversion,
   1121                          bool AllowObjCConversionOnExplicit) {
   1122   ImplicitConversionSequence ICS;
   1123 
   1124   if (SuppressUserConversions) {
   1125     // We're not in the case above, so there is no conversion that
   1126     // we can perform.
   1127     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
   1128     return ICS;
   1129   }
   1130 
   1131   // Attempt user-defined conversion.
   1132   OverloadCandidateSet Conversions(From->getExprLoc(),
   1133                                    OverloadCandidateSet::CSK_Normal);
   1134   OverloadingResult UserDefResult
   1135     = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
   1136                               AllowExplicit, AllowObjCConversionOnExplicit);
   1137 
   1138   if (UserDefResult == OR_Success) {
   1139     ICS.setUserDefined();
   1140     ICS.UserDefined.Before.setAsIdentityConversion();
   1141     // C++ [over.ics.user]p4:
   1142     //   A conversion of an expression of class type to the same class
   1143     //   type is given Exact Match rank, and a conversion of an
   1144     //   expression of class type to a base class of that type is
   1145     //   given Conversion rank, in spite of the fact that a copy
   1146     //   constructor (i.e., a user-defined conversion function) is
   1147     //   called for those cases.
   1148     if (CXXConstructorDecl *Constructor
   1149           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
   1150       QualType FromCanon
   1151         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
   1152       QualType ToCanon
   1153         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
   1154       if (Constructor->isCopyConstructor() &&
   1155           (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
   1156         // Turn this into a "standard" conversion sequence, so that it
   1157         // gets ranked with standard conversion sequences.
   1158         ICS.setStandard();
   1159         ICS.Standard.setAsIdentityConversion();
   1160         ICS.Standard.setFromType(From->getType());
   1161         ICS.Standard.setAllToTypes(ToType);
   1162         ICS.Standard.CopyConstructor = Constructor;
   1163         if (ToCanon != FromCanon)
   1164           ICS.Standard.Second = ICK_Derived_To_Base;
   1165       }
   1166     }
   1167 
   1168     // C++ [over.best.ics]p4:
   1169     //   However, when considering the argument of a user-defined
   1170     //   conversion function that is a candidate by 13.3.1.3 when
   1171     //   invoked for the copying of the temporary in the second step
   1172     //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
   1173     //   13.3.1.6 in all cases, only standard conversion sequences and
   1174     //   ellipsis conversion sequences are allowed.
   1175     if (SuppressUserConversions && ICS.isUserDefined()) {
   1176       ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
   1177     }
   1178   } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
   1179     ICS.setAmbiguous();
   1180     ICS.Ambiguous.setFromType(From->getType());
   1181     ICS.Ambiguous.setToType(ToType);
   1182     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
   1183          Cand != Conversions.end(); ++Cand)
   1184       if (Cand->Viable)
   1185         ICS.Ambiguous.addConversion(Cand->Function);
   1186   } else {
   1187     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
   1188   }
   1189 
   1190   return ICS;
   1191 }
   1192 
   1193 /// TryImplicitConversion - Attempt to perform an implicit conversion
   1194 /// from the given expression (Expr) to the given type (ToType). This
   1195 /// function returns an implicit conversion sequence that can be used
   1196 /// to perform the initialization. Given
   1197 ///
   1198 ///   void f(float f);
   1199 ///   void g(int i) { f(i); }
   1200 ///
   1201 /// this routine would produce an implicit conversion sequence to
   1202 /// describe the initialization of f from i, which will be a standard
   1203 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
   1204 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
   1205 //
   1206 /// Note that this routine only determines how the conversion can be
   1207 /// performed; it does not actually perform the conversion. As such,
   1208 /// it will not produce any diagnostics if no conversion is available,
   1209 /// but will instead return an implicit conversion sequence of kind
   1210 /// "BadConversion".
   1211 ///
   1212 /// If @p SuppressUserConversions, then user-defined conversions are
   1213 /// not permitted.
   1214 /// If @p AllowExplicit, then explicit user-defined conversions are
   1215 /// permitted.
   1216 ///
   1217 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
   1218 /// writeback conversion, which allows __autoreleasing id* parameters to
   1219 /// be initialized with __strong id* or __weak id* arguments.
   1220 static ImplicitConversionSequence
   1221 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
   1222                       bool SuppressUserConversions,
   1223                       bool AllowExplicit,
   1224                       bool InOverloadResolution,
   1225                       bool CStyle,
   1226                       bool AllowObjCWritebackConversion,
   1227                       bool AllowObjCConversionOnExplicit) {
   1228   ImplicitConversionSequence ICS;
   1229   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
   1230                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
   1231     ICS.setStandard();
   1232     return ICS;
   1233   }
   1234 
   1235   if (!S.getLangOpts().CPlusPlus) {
   1236     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
   1237     return ICS;
   1238   }
   1239 
   1240   // C++ [over.ics.user]p4:
   1241   //   A conversion of an expression of class type to the same class
   1242   //   type is given Exact Match rank, and a conversion of an
   1243   //   expression of class type to a base class of that type is
   1244   //   given Conversion rank, in spite of the fact that a copy/move
   1245   //   constructor (i.e., a user-defined conversion function) is
   1246   //   called for those cases.
   1247   QualType FromType = From->getType();
   1248   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
   1249       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
   1250        S.IsDerivedFrom(FromType, ToType))) {
   1251     ICS.setStandard();
   1252     ICS.Standard.setAsIdentityConversion();
   1253     ICS.Standard.setFromType(FromType);
   1254     ICS.Standard.setAllToTypes(ToType);
   1255 
   1256     // We don't actually check at this point whether there is a valid
   1257     // copy/move constructor, since overloading just assumes that it
   1258     // exists. When we actually perform initialization, we'll find the
   1259     // appropriate constructor to copy the returned object, if needed.
   1260     ICS.Standard.CopyConstructor = nullptr;
   1261 
   1262     // Determine whether this is considered a derived-to-base conversion.
   1263     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
   1264       ICS.Standard.Second = ICK_Derived_To_Base;
   1265 
   1266     return ICS;
   1267   }
   1268 
   1269   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
   1270                                   AllowExplicit, InOverloadResolution, CStyle,
   1271                                   AllowObjCWritebackConversion,
   1272                                   AllowObjCConversionOnExplicit);
   1273 }
   1274 
   1275 ImplicitConversionSequence
   1276 Sema::TryImplicitConversion(Expr *From, QualType ToType,
   1277                             bool SuppressUserConversions,
   1278                             bool AllowExplicit,
   1279                             bool InOverloadResolution,
   1280                             bool CStyle,
   1281                             bool AllowObjCWritebackConversion) {
   1282   return clang::TryImplicitConversion(*this, From, ToType,
   1283                                       SuppressUserConversions, AllowExplicit,
   1284                                       InOverloadResolution, CStyle,
   1285                                       AllowObjCWritebackConversion,
   1286                                       /*AllowObjCConversionOnExplicit=*/false);
   1287 }
   1288 
   1289 /// PerformImplicitConversion - Perform an implicit conversion of the
   1290 /// expression From to the type ToType. Returns the
   1291 /// converted expression. Flavor is the kind of conversion we're
   1292 /// performing, used in the error message. If @p AllowExplicit,
   1293 /// explicit user-defined conversions are permitted.
   1294 ExprResult
   1295 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
   1296                                 AssignmentAction Action, bool AllowExplicit) {
   1297   ImplicitConversionSequence ICS;
   1298   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
   1299 }
   1300 
   1301 ExprResult
   1302 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
   1303                                 AssignmentAction Action, bool AllowExplicit,
   1304                                 ImplicitConversionSequence& ICS) {
   1305   if (checkPlaceholderForOverload(*this, From))
   1306     return ExprError();
   1307 
   1308   // Objective-C ARC: Determine whether we will allow the writeback conversion.
   1309   bool AllowObjCWritebackConversion
   1310     = getLangOpts().ObjCAutoRefCount &&
   1311       (Action == AA_Passing || Action == AA_Sending);
   1312   if (getLangOpts().ObjC1)
   1313     CheckObjCBridgeRelatedConversions(From->getLocStart(),
   1314                                       ToType, From->getType(), From);
   1315   ICS = clang::TryImplicitConversion(*this, From, ToType,
   1316                                      /*SuppressUserConversions=*/false,
   1317                                      AllowExplicit,
   1318                                      /*InOverloadResolution=*/false,
   1319                                      /*CStyle=*/false,
   1320                                      AllowObjCWritebackConversion,
   1321                                      /*AllowObjCConversionOnExplicit=*/false);
   1322   return PerformImplicitConversion(From, ToType, ICS, Action);
   1323 }
   1324 
   1325 /// \brief Determine whether the conversion from FromType to ToType is a valid
   1326 /// conversion that strips "noreturn" off the nested function type.
   1327 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
   1328                                 QualType &ResultTy) {
   1329   if (Context.hasSameUnqualifiedType(FromType, ToType))
   1330     return false;
   1331 
   1332   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
   1333   // where F adds one of the following at most once:
   1334   //   - a pointer
   1335   //   - a member pointer
   1336   //   - a block pointer
   1337   CanQualType CanTo = Context.getCanonicalType(ToType);
   1338   CanQualType CanFrom = Context.getCanonicalType(FromType);
   1339   Type::TypeClass TyClass = CanTo->getTypeClass();
   1340   if (TyClass != CanFrom->getTypeClass()) return false;
   1341   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
   1342     if (TyClass == Type::Pointer) {
   1343       CanTo = CanTo.getAs<PointerType>()->getPointeeType();
   1344       CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
   1345     } else if (TyClass == Type::BlockPointer) {
   1346       CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
   1347       CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
   1348     } else if (TyClass == Type::MemberPointer) {
   1349       CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
   1350       CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
   1351     } else {
   1352       return false;
   1353     }
   1354 
   1355     TyClass = CanTo->getTypeClass();
   1356     if (TyClass != CanFrom->getTypeClass()) return false;
   1357     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
   1358       return false;
   1359   }
   1360 
   1361   const FunctionType *FromFn = cast<FunctionType>(CanFrom);
   1362   FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
   1363   if (!EInfo.getNoReturn()) return false;
   1364 
   1365   FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
   1366   assert(QualType(FromFn, 0).isCanonical());
   1367   if (QualType(FromFn, 0) != CanTo) return false;
   1368 
   1369   ResultTy = ToType;
   1370   return true;
   1371 }
   1372 
   1373 /// \brief Determine whether the conversion from FromType to ToType is a valid
   1374 /// vector conversion.
   1375 ///
   1376 /// \param ICK Will be set to the vector conversion kind, if this is a vector
   1377 /// conversion.
   1378 static bool IsVectorConversion(Sema &S, QualType FromType,
   1379                                QualType ToType, ImplicitConversionKind &ICK) {
   1380   // We need at least one of these types to be a vector type to have a vector
   1381   // conversion.
   1382   if (!ToType->isVectorType() && !FromType->isVectorType())
   1383     return false;
   1384 
   1385   // Identical types require no conversions.
   1386   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
   1387     return false;
   1388 
   1389   // There are no conversions between extended vector types, only identity.
   1390   if (ToType->isExtVectorType()) {
   1391     // There are no conversions between extended vector types other than the
   1392     // identity conversion.
   1393     if (FromType->isExtVectorType())
   1394       return false;
   1395 
   1396     // Vector splat from any arithmetic type to a vector.
   1397     if (FromType->isArithmeticType()) {
   1398       ICK = ICK_Vector_Splat;
   1399       return true;
   1400     }
   1401   }
   1402 
   1403   // We can perform the conversion between vector types in the following cases:
   1404   // 1)vector types are equivalent AltiVec and GCC vector types
   1405   // 2)lax vector conversions are permitted and the vector types are of the
   1406   //   same size
   1407   if (ToType->isVectorType() && FromType->isVectorType()) {
   1408     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
   1409         S.isLaxVectorConversion(FromType, ToType)) {
   1410       ICK = ICK_Vector_Conversion;
   1411       return true;
   1412     }
   1413   }
   1414 
   1415   return false;
   1416 }
   1417 
   1418 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
   1419                                 bool InOverloadResolution,
   1420                                 StandardConversionSequence &SCS,
   1421                                 bool CStyle);
   1422 
   1423 /// IsStandardConversion - Determines whether there is a standard
   1424 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
   1425 /// expression From to the type ToType. Standard conversion sequences
   1426 /// only consider non-class types; for conversions that involve class
   1427 /// types, use TryImplicitConversion. If a conversion exists, SCS will
   1428 /// contain the standard conversion sequence required to perform this
   1429 /// conversion and this routine will return true. Otherwise, this
   1430 /// routine will return false and the value of SCS is unspecified.
   1431 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
   1432                                  bool InOverloadResolution,
   1433                                  StandardConversionSequence &SCS,
   1434                                  bool CStyle,
   1435                                  bool AllowObjCWritebackConversion) {
   1436   QualType FromType = From->getType();
   1437 
   1438   // Standard conversions (C++ [conv])
   1439   SCS.setAsIdentityConversion();
   1440   SCS.IncompatibleObjC = false;
   1441   SCS.setFromType(FromType);
   1442   SCS.CopyConstructor = nullptr;
   1443 
   1444   // There are no standard conversions for class types in C++, so
   1445   // abort early. When overloading in C, however, we do permit
   1446   if (FromType->isRecordType() || ToType->isRecordType()) {
   1447     if (S.getLangOpts().CPlusPlus)
   1448       return false;
   1449 
   1450     // When we're overloading in C, we allow, as standard conversions,
   1451   }
   1452 
   1453   // The first conversion can be an lvalue-to-rvalue conversion,
   1454   // array-to-pointer conversion, or function-to-pointer conversion
   1455   // (C++ 4p1).
   1456 
   1457   if (FromType == S.Context.OverloadTy) {
   1458     DeclAccessPair AccessPair;
   1459     if (FunctionDecl *Fn
   1460           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
   1461                                                  AccessPair)) {
   1462       // We were able to resolve the address of the overloaded function,
   1463       // so we can convert to the type of that function.
   1464       FromType = Fn->getType();
   1465 
   1466       // we can sometimes resolve &foo<int> regardless of ToType, so check
   1467       // if the type matches (identity) or we are converting to bool
   1468       if (!S.Context.hasSameUnqualifiedType(
   1469                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
   1470         QualType resultTy;
   1471         // if the function type matches except for [[noreturn]], it's ok
   1472         if (!S.IsNoReturnConversion(FromType,
   1473               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
   1474           // otherwise, only a boolean conversion is standard
   1475           if (!ToType->isBooleanType())
   1476             return false;
   1477       }
   1478 
   1479       // Check if the "from" expression is taking the address of an overloaded
   1480       // function and recompute the FromType accordingly. Take advantage of the
   1481       // fact that non-static member functions *must* have such an address-of
   1482       // expression.
   1483       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
   1484       if (Method && !Method->isStatic()) {
   1485         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
   1486                "Non-unary operator on non-static member address");
   1487         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
   1488                == UO_AddrOf &&
   1489                "Non-address-of operator on non-static member address");
   1490         const Type *ClassType
   1491           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
   1492         FromType = S.Context.getMemberPointerType(FromType, ClassType);
   1493       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
   1494         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
   1495                UO_AddrOf &&
   1496                "Non-address-of operator for overloaded function expression");
   1497         FromType = S.Context.getPointerType(FromType);
   1498       }
   1499 
   1500       // Check that we've computed the proper type after overload resolution.
   1501       assert(S.Context.hasSameType(
   1502         FromType,
   1503         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
   1504     } else {
   1505       return false;
   1506     }
   1507   }
   1508   // Lvalue-to-rvalue conversion (C++11 4.1):
   1509   //   A glvalue (3.10) of a non-function, non-array type T can
   1510   //   be converted to a prvalue.
   1511   bool argIsLValue = From->isGLValue();
   1512   if (argIsLValue &&
   1513       !FromType->isFunctionType() && !FromType->isArrayType() &&
   1514       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
   1515     SCS.First = ICK_Lvalue_To_Rvalue;
   1516 
   1517     // C11 6.3.2.1p2:
   1518     //   ... if the lvalue has atomic type, the value has the non-atomic version
   1519     //   of the type of the lvalue ...
   1520     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
   1521       FromType = Atomic->getValueType();
   1522 
   1523     // If T is a non-class type, the type of the rvalue is the
   1524     // cv-unqualified version of T. Otherwise, the type of the rvalue
   1525     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
   1526     // just strip the qualifiers because they don't matter.
   1527     FromType = FromType.getUnqualifiedType();
   1528   } else if (FromType->isArrayType()) {
   1529     // Array-to-pointer conversion (C++ 4.2)
   1530     SCS.First = ICK_Array_To_Pointer;
   1531 
   1532     // An lvalue or rvalue of type "array of N T" or "array of unknown
   1533     // bound of T" can be converted to an rvalue of type "pointer to
   1534     // T" (C++ 4.2p1).
   1535     FromType = S.Context.getArrayDecayedType(FromType);
   1536 
   1537     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
   1538       // This conversion is deprecated in C++03 (D.4)
   1539       SCS.DeprecatedStringLiteralToCharPtr = true;
   1540 
   1541       // For the purpose of ranking in overload resolution
   1542       // (13.3.3.1.1), this conversion is considered an
   1543       // array-to-pointer conversion followed by a qualification
   1544       // conversion (4.4). (C++ 4.2p2)
   1545       SCS.Second = ICK_Identity;
   1546       SCS.Third = ICK_Qualification;
   1547       SCS.QualificationIncludesObjCLifetime = false;
   1548       SCS.setAllToTypes(FromType);
   1549       return true;
   1550     }
   1551   } else if (FromType->isFunctionType() && argIsLValue) {
   1552     // Function-to-pointer conversion (C++ 4.3).
   1553     SCS.First = ICK_Function_To_Pointer;
   1554 
   1555     // An lvalue of function type T can be converted to an rvalue of
   1556     // type "pointer to T." The result is a pointer to the
   1557     // function. (C++ 4.3p1).
   1558     FromType = S.Context.getPointerType(FromType);
   1559   } else {
   1560     // We don't require any conversions for the first step.
   1561     SCS.First = ICK_Identity;
   1562   }
   1563   SCS.setToType(0, FromType);
   1564 
   1565   // The second conversion can be an integral promotion, floating
   1566   // point promotion, integral conversion, floating point conversion,
   1567   // floating-integral conversion, pointer conversion,
   1568   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
   1569   // For overloading in C, this can also be a "compatible-type"
   1570   // conversion.
   1571   bool IncompatibleObjC = false;
   1572   ImplicitConversionKind SecondICK = ICK_Identity;
   1573   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
   1574     // The unqualified versions of the types are the same: there's no
   1575     // conversion to do.
   1576     SCS.Second = ICK_Identity;
   1577   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
   1578     // Integral promotion (C++ 4.5).
   1579     SCS.Second = ICK_Integral_Promotion;
   1580     FromType = ToType.getUnqualifiedType();
   1581   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
   1582     // Floating point promotion (C++ 4.6).
   1583     SCS.Second = ICK_Floating_Promotion;
   1584     FromType = ToType.getUnqualifiedType();
   1585   } else if (S.IsComplexPromotion(FromType, ToType)) {
   1586     // Complex promotion (Clang extension)
   1587     SCS.Second = ICK_Complex_Promotion;
   1588     FromType = ToType.getUnqualifiedType();
   1589   } else if (ToType->isBooleanType() &&
   1590              (FromType->isArithmeticType() ||
   1591               FromType->isAnyPointerType() ||
   1592               FromType->isBlockPointerType() ||
   1593               FromType->isMemberPointerType() ||
   1594               FromType->isNullPtrType())) {
   1595     // Boolean conversions (C++ 4.12).
   1596     SCS.Second = ICK_Boolean_Conversion;
   1597     FromType = S.Context.BoolTy;
   1598   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
   1599              ToType->isIntegralType(S.Context)) {
   1600     // Integral conversions (C++ 4.7).
   1601     SCS.Second = ICK_Integral_Conversion;
   1602     FromType = ToType.getUnqualifiedType();
   1603   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
   1604     // Complex conversions (C99 6.3.1.6)
   1605     SCS.Second = ICK_Complex_Conversion;
   1606     FromType = ToType.getUnqualifiedType();
   1607   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
   1608              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
   1609     // Complex-real conversions (C99 6.3.1.7)
   1610     SCS.Second = ICK_Complex_Real;
   1611     FromType = ToType.getUnqualifiedType();
   1612   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
   1613     // Floating point conversions (C++ 4.8).
   1614     SCS.Second = ICK_Floating_Conversion;
   1615     FromType = ToType.getUnqualifiedType();
   1616   } else if ((FromType->isRealFloatingType() &&
   1617               ToType->isIntegralType(S.Context)) ||
   1618              (FromType->isIntegralOrUnscopedEnumerationType() &&
   1619               ToType->isRealFloatingType())) {
   1620     // Floating-integral conversions (C++ 4.9).
   1621     SCS.Second = ICK_Floating_Integral;
   1622     FromType = ToType.getUnqualifiedType();
   1623   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
   1624     SCS.Second = ICK_Block_Pointer_Conversion;
   1625   } else if (AllowObjCWritebackConversion &&
   1626              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
   1627     SCS.Second = ICK_Writeback_Conversion;
   1628   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
   1629                                    FromType, IncompatibleObjC)) {
   1630     // Pointer conversions (C++ 4.10).
   1631     SCS.Second = ICK_Pointer_Conversion;
   1632     SCS.IncompatibleObjC = IncompatibleObjC;
   1633     FromType = FromType.getUnqualifiedType();
   1634   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
   1635                                          InOverloadResolution, FromType)) {
   1636     // Pointer to member conversions (4.11).
   1637     SCS.Second = ICK_Pointer_Member;
   1638   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
   1639     SCS.Second = SecondICK;
   1640     FromType = ToType.getUnqualifiedType();
   1641   } else if (!S.getLangOpts().CPlusPlus &&
   1642              S.Context.typesAreCompatible(ToType, FromType)) {
   1643     // Compatible conversions (Clang extension for C function overloading)
   1644     SCS.Second = ICK_Compatible_Conversion;
   1645     FromType = ToType.getUnqualifiedType();
   1646   } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
   1647     // Treat a conversion that strips "noreturn" as an identity conversion.
   1648     SCS.Second = ICK_NoReturn_Adjustment;
   1649   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
   1650                                              InOverloadResolution,
   1651                                              SCS, CStyle)) {
   1652     SCS.Second = ICK_TransparentUnionConversion;
   1653     FromType = ToType;
   1654   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
   1655                                  CStyle)) {
   1656     // tryAtomicConversion has updated the standard conversion sequence
   1657     // appropriately.
   1658     return true;
   1659   } else if (ToType->isEventT() &&
   1660              From->isIntegerConstantExpr(S.getASTContext()) &&
   1661              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
   1662     SCS.Second = ICK_Zero_Event_Conversion;
   1663     FromType = ToType;
   1664   } else {
   1665     // No second conversion required.
   1666     SCS.Second = ICK_Identity;
   1667   }
   1668   SCS.setToType(1, FromType);
   1669 
   1670   QualType CanonFrom;
   1671   QualType CanonTo;
   1672   // The third conversion can be a qualification conversion (C++ 4p1).
   1673   bool ObjCLifetimeConversion;
   1674   if (S.IsQualificationConversion(FromType, ToType, CStyle,
   1675                                   ObjCLifetimeConversion)) {
   1676     SCS.Third = ICK_Qualification;
   1677     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
   1678     FromType = ToType;
   1679     CanonFrom = S.Context.getCanonicalType(FromType);
   1680     CanonTo = S.Context.getCanonicalType(ToType);
   1681   } else {
   1682     // No conversion required
   1683     SCS.Third = ICK_Identity;
   1684 
   1685     // C++ [over.best.ics]p6:
   1686     //   [...] Any difference in top-level cv-qualification is
   1687     //   subsumed by the initialization itself and does not constitute
   1688     //   a conversion. [...]
   1689     CanonFrom = S.Context.getCanonicalType(FromType);
   1690     CanonTo = S.Context.getCanonicalType(ToType);
   1691     if (CanonFrom.getLocalUnqualifiedType()
   1692                                        == CanonTo.getLocalUnqualifiedType() &&
   1693         CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
   1694       FromType = ToType;
   1695       CanonFrom = CanonTo;
   1696     }
   1697   }
   1698   SCS.setToType(2, FromType);
   1699 
   1700   // If we have not converted the argument type to the parameter type,
   1701   // this is a bad conversion sequence.
   1702   if (CanonFrom != CanonTo)
   1703     return false;
   1704 
   1705   return true;
   1706 }
   1707 
   1708 static bool
   1709 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
   1710                                      QualType &ToType,
   1711                                      bool InOverloadResolution,
   1712                                      StandardConversionSequence &SCS,
   1713                                      bool CStyle) {
   1714 
   1715   const RecordType *UT = ToType->getAsUnionType();
   1716   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
   1717     return false;
   1718   // The field to initialize within the transparent union.
   1719   RecordDecl *UD = UT->getDecl();
   1720   // It's compatible if the expression matches any of the fields.
   1721   for (const auto *it : UD->fields()) {
   1722     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
   1723                              CStyle, /*ObjCWritebackConversion=*/false)) {
   1724       ToType = it->getType();
   1725       return true;
   1726     }
   1727   }
   1728   return false;
   1729 }
   1730 
   1731 /// IsIntegralPromotion - Determines whether the conversion from the
   1732 /// expression From (whose potentially-adjusted type is FromType) to
   1733 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
   1734 /// sets PromotedType to the promoted type.
   1735 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
   1736   const BuiltinType *To = ToType->getAs<BuiltinType>();
   1737   // All integers are built-in.
   1738   if (!To) {
   1739     return false;
   1740   }
   1741 
   1742   // An rvalue of type char, signed char, unsigned char, short int, or
   1743   // unsigned short int can be converted to an rvalue of type int if
   1744   // int can represent all the values of the source type; otherwise,
   1745   // the source rvalue can be converted to an rvalue of type unsigned
   1746   // int (C++ 4.5p1).
   1747   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
   1748       !FromType->isEnumeralType()) {
   1749     if (// We can promote any signed, promotable integer type to an int
   1750         (FromType->isSignedIntegerType() ||
   1751          // We can promote any unsigned integer type whose size is
   1752          // less than int to an int.
   1753          (!FromType->isSignedIntegerType() &&
   1754           Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
   1755       return To->getKind() == BuiltinType::Int;
   1756     }
   1757 
   1758     return To->getKind() == BuiltinType::UInt;
   1759   }
   1760 
   1761   // C++11 [conv.prom]p3:
   1762   //   A prvalue of an unscoped enumeration type whose underlying type is not
   1763   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
   1764   //   following types that can represent all the values of the enumeration
   1765   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
   1766   //   unsigned int, long int, unsigned long int, long long int, or unsigned
   1767   //   long long int. If none of the types in that list can represent all the
   1768   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
   1769   //   type can be converted to an rvalue a prvalue of the extended integer type
   1770   //   with lowest integer conversion rank (4.13) greater than the rank of long
   1771   //   long in which all the values of the enumeration can be represented. If
   1772   //   there are two such extended types, the signed one is chosen.
   1773   // C++11 [conv.prom]p4:
   1774   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
   1775   //   can be converted to a prvalue of its underlying type. Moreover, if
   1776   //   integral promotion can be applied to its underlying type, a prvalue of an
   1777   //   unscoped enumeration type whose underlying type is fixed can also be
   1778   //   converted to a prvalue of the promoted underlying type.
   1779   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
   1780     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
   1781     // provided for a scoped enumeration.
   1782     if (FromEnumType->getDecl()->isScoped())
   1783       return false;
   1784 
   1785     // We can perform an integral promotion to the underlying type of the enum,
   1786     // even if that's not the promoted type.
   1787     if (FromEnumType->getDecl()->isFixed()) {
   1788       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
   1789       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
   1790              IsIntegralPromotion(From, Underlying, ToType);
   1791     }
   1792 
   1793     // We have already pre-calculated the promotion type, so this is trivial.
   1794     if (ToType->isIntegerType() &&
   1795         !RequireCompleteType(From->getLocStart(), FromType, 0))
   1796       return Context.hasSameUnqualifiedType(ToType,
   1797                                 FromEnumType->getDecl()->getPromotionType());
   1798   }
   1799 
   1800   // C++0x [conv.prom]p2:
   1801   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
   1802   //   to an rvalue a prvalue of the first of the following types that can
   1803   //   represent all the values of its underlying type: int, unsigned int,
   1804   //   long int, unsigned long int, long long int, or unsigned long long int.
   1805   //   If none of the types in that list can represent all the values of its
   1806   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
   1807   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
   1808   //   type.
   1809   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
   1810       ToType->isIntegerType()) {
   1811     // Determine whether the type we're converting from is signed or
   1812     // unsigned.
   1813     bool FromIsSigned = FromType->isSignedIntegerType();
   1814     uint64_t FromSize = Context.getTypeSize(FromType);
   1815 
   1816     // The types we'll try to promote to, in the appropriate
   1817     // order. Try each of these types.
   1818     QualType PromoteTypes[6] = {
   1819       Context.IntTy, Context.UnsignedIntTy,
   1820       Context.LongTy, Context.UnsignedLongTy ,
   1821       Context.LongLongTy, Context.UnsignedLongLongTy
   1822     };
   1823     for (int Idx = 0; Idx < 6; ++Idx) {
   1824       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
   1825       if (FromSize < ToSize ||
   1826           (FromSize == ToSize &&
   1827            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
   1828         // We found the type that we can promote to. If this is the
   1829         // type we wanted, we have a promotion. Otherwise, no
   1830         // promotion.
   1831         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
   1832       }
   1833     }
   1834   }
   1835 
   1836   // An rvalue for an integral bit-field (9.6) can be converted to an
   1837   // rvalue of type int if int can represent all the values of the
   1838   // bit-field; otherwise, it can be converted to unsigned int if
   1839   // unsigned int can represent all the values of the bit-field. If
   1840   // the bit-field is larger yet, no integral promotion applies to
   1841   // it. If the bit-field has an enumerated type, it is treated as any
   1842   // other value of that type for promotion purposes (C++ 4.5p3).
   1843   // FIXME: We should delay checking of bit-fields until we actually perform the
   1844   // conversion.
   1845   using llvm::APSInt;
   1846   if (From)
   1847     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
   1848       APSInt BitWidth;
   1849       if (FromType->isIntegralType(Context) &&
   1850           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
   1851         APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
   1852         ToSize = Context.getTypeSize(ToType);
   1853 
   1854         // Are we promoting to an int from a bitfield that fits in an int?
   1855         if (BitWidth < ToSize ||
   1856             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
   1857           return To->getKind() == BuiltinType::Int;
   1858         }
   1859 
   1860         // Are we promoting to an unsigned int from an unsigned bitfield
   1861         // that fits into an unsigned int?
   1862         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
   1863           return To->getKind() == BuiltinType::UInt;
   1864         }
   1865 
   1866         return false;
   1867       }
   1868     }
   1869 
   1870   // An rvalue of type bool can be converted to an rvalue of type int,
   1871   // with false becoming zero and true becoming one (C++ 4.5p4).
   1872   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
   1873     return true;
   1874   }
   1875 
   1876   return false;
   1877 }
   1878 
   1879 /// IsFloatingPointPromotion - Determines whether the conversion from
   1880 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
   1881 /// returns true and sets PromotedType to the promoted type.
   1882 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
   1883   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
   1884     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
   1885       /// An rvalue of type float can be converted to an rvalue of type
   1886       /// double. (C++ 4.6p1).
   1887       if (FromBuiltin->getKind() == BuiltinType::Float &&
   1888           ToBuiltin->getKind() == BuiltinType::Double)
   1889         return true;
   1890 
   1891       // C99 6.3.1.5p1:
   1892       //   When a float is promoted to double or long double, or a
   1893       //   double is promoted to long double [...].
   1894       if (!getLangOpts().CPlusPlus &&
   1895           (FromBuiltin->getKind() == BuiltinType::Float ||
   1896            FromBuiltin->getKind() == BuiltinType::Double) &&
   1897           (ToBuiltin->getKind() == BuiltinType::LongDouble))
   1898         return true;
   1899 
   1900       // Half can be promoted to float.
   1901       if (!getLangOpts().NativeHalfType &&
   1902            FromBuiltin->getKind() == BuiltinType::Half &&
   1903           ToBuiltin->getKind() == BuiltinType::Float)
   1904         return true;
   1905     }
   1906 
   1907   return false;
   1908 }
   1909 
   1910 /// \brief Determine if a conversion is a complex promotion.
   1911 ///
   1912 /// A complex promotion is defined as a complex -> complex conversion
   1913 /// where the conversion between the underlying real types is a
   1914 /// floating-point or integral promotion.
   1915 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
   1916   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
   1917   if (!FromComplex)
   1918     return false;
   1919 
   1920   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
   1921   if (!ToComplex)
   1922     return false;
   1923 
   1924   return IsFloatingPointPromotion(FromComplex->getElementType(),
   1925                                   ToComplex->getElementType()) ||
   1926     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
   1927                         ToComplex->getElementType());
   1928 }
   1929 
   1930 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
   1931 /// the pointer type FromPtr to a pointer to type ToPointee, with the
   1932 /// same type qualifiers as FromPtr has on its pointee type. ToType,
   1933 /// if non-empty, will be a pointer to ToType that may or may not have
   1934 /// the right set of qualifiers on its pointee.
   1935 ///
   1936 static QualType
   1937 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
   1938                                    QualType ToPointee, QualType ToType,
   1939                                    ASTContext &Context,
   1940                                    bool StripObjCLifetime = false) {
   1941   assert((FromPtr->getTypeClass() == Type::Pointer ||
   1942           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
   1943          "Invalid similarly-qualified pointer type");
   1944 
   1945   /// Conversions to 'id' subsume cv-qualifier conversions.
   1946   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
   1947     return ToType.getUnqualifiedType();
   1948 
   1949   QualType CanonFromPointee
   1950     = Context.getCanonicalType(FromPtr->getPointeeType());
   1951   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
   1952   Qualifiers Quals = CanonFromPointee.getQualifiers();
   1953 
   1954   if (StripObjCLifetime)
   1955     Quals.removeObjCLifetime();
   1956 
   1957   // Exact qualifier match -> return the pointer type we're converting to.
   1958   if (CanonToPointee.getLocalQualifiers() == Quals) {
   1959     // ToType is exactly what we need. Return it.
   1960     if (!ToType.isNull())
   1961       return ToType.getUnqualifiedType();
   1962 
   1963     // Build a pointer to ToPointee. It has the right qualifiers
   1964     // already.
   1965     if (isa<ObjCObjectPointerType>(ToType))
   1966       return Context.getObjCObjectPointerType(ToPointee);
   1967     return Context.getPointerType(ToPointee);
   1968   }
   1969 
   1970   // Just build a canonical type that has the right qualifiers.
   1971   QualType QualifiedCanonToPointee
   1972     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
   1973 
   1974   if (isa<ObjCObjectPointerType>(ToType))
   1975     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
   1976   return Context.getPointerType(QualifiedCanonToPointee);
   1977 }
   1978 
   1979 static bool isNullPointerConstantForConversion(Expr *Expr,
   1980                                                bool InOverloadResolution,
   1981                                                ASTContext &Context) {
   1982   // Handle value-dependent integral null pointer constants correctly.
   1983   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
   1984   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
   1985       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
   1986     return !InOverloadResolution;
   1987 
   1988   return Expr->isNullPointerConstant(Context,
   1989                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
   1990                                         : Expr::NPC_ValueDependentIsNull);
   1991 }
   1992 
   1993 /// IsPointerConversion - Determines whether the conversion of the
   1994 /// expression From, which has the (possibly adjusted) type FromType,
   1995 /// can be converted to the type ToType via a pointer conversion (C++
   1996 /// 4.10). If so, returns true and places the converted type (that
   1997 /// might differ from ToType in its cv-qualifiers at some level) into
   1998 /// ConvertedType.
   1999 ///
   2000 /// This routine also supports conversions to and from block pointers
   2001 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
   2002 /// pointers to interfaces. FIXME: Once we've determined the
   2003 /// appropriate overloading rules for Objective-C, we may want to
   2004 /// split the Objective-C checks into a different routine; however,
   2005 /// GCC seems to consider all of these conversions to be pointer
   2006 /// conversions, so for now they live here. IncompatibleObjC will be
   2007 /// set if the conversion is an allowed Objective-C conversion that
   2008 /// should result in a warning.
   2009 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
   2010                                bool InOverloadResolution,
   2011                                QualType& ConvertedType,
   2012                                bool &IncompatibleObjC) {
   2013   IncompatibleObjC = false;
   2014   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
   2015                               IncompatibleObjC))
   2016     return true;
   2017 
   2018   // Conversion from a null pointer constant to any Objective-C pointer type.
   2019   if (ToType->isObjCObjectPointerType() &&
   2020       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
   2021     ConvertedType = ToType;
   2022     return true;
   2023   }
   2024 
   2025   // Blocks: Block pointers can be converted to void*.
   2026   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
   2027       ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
   2028     ConvertedType = ToType;
   2029     return true;
   2030   }
   2031   // Blocks: A null pointer constant can be converted to a block
   2032   // pointer type.
   2033   if (ToType->isBlockPointerType() &&
   2034       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
   2035     ConvertedType = ToType;
   2036     return true;
   2037   }
   2038 
   2039   // If the left-hand-side is nullptr_t, the right side can be a null
   2040   // pointer constant.
   2041   if (ToType->isNullPtrType() &&
   2042       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
   2043     ConvertedType = ToType;
   2044     return true;
   2045   }
   2046 
   2047   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
   2048   if (!ToTypePtr)
   2049     return false;
   2050 
   2051   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
   2052   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
   2053     ConvertedType = ToType;
   2054     return true;
   2055   }
   2056 
   2057   // Beyond this point, both types need to be pointers
   2058   // , including objective-c pointers.
   2059   QualType ToPointeeType = ToTypePtr->getPointeeType();
   2060   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
   2061       !getLangOpts().ObjCAutoRefCount) {
   2062     ConvertedType = BuildSimilarlyQualifiedPointerType(
   2063                                       FromType->getAs<ObjCObjectPointerType>(),
   2064                                                        ToPointeeType,
   2065                                                        ToType, Context);
   2066     return true;
   2067   }
   2068   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
   2069   if (!FromTypePtr)
   2070     return false;
   2071 
   2072   QualType FromPointeeType = FromTypePtr->getPointeeType();
   2073 
   2074   // If the unqualified pointee types are the same, this can't be a
   2075   // pointer conversion, so don't do all of the work below.
   2076   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
   2077     return false;
   2078 
   2079   // An rvalue of type "pointer to cv T," where T is an object type,
   2080   // can be converted to an rvalue of type "pointer to cv void" (C++
   2081   // 4.10p2).
   2082   if (FromPointeeType->isIncompleteOrObjectType() &&
   2083       ToPointeeType->isVoidType()) {
   2084     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
   2085                                                        ToPointeeType,
   2086                                                        ToType, Context,
   2087                                                    /*StripObjCLifetime=*/true);
   2088     return true;
   2089   }
   2090 
   2091   // MSVC allows implicit function to void* type conversion.
   2092   if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
   2093       ToPointeeType->isVoidType()) {
   2094     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
   2095                                                        ToPointeeType,
   2096                                                        ToType, Context);
   2097     return true;
   2098   }
   2099 
   2100   // When we're overloading in C, we allow a special kind of pointer
   2101   // conversion for compatible-but-not-identical pointee types.
   2102   if (!getLangOpts().CPlusPlus &&
   2103       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
   2104     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
   2105                                                        ToPointeeType,
   2106                                                        ToType, Context);
   2107     return true;
   2108   }
   2109 
   2110   // C++ [conv.ptr]p3:
   2111   //
   2112   //   An rvalue of type "pointer to cv D," where D is a class type,
   2113   //   can be converted to an rvalue of type "pointer to cv B," where
   2114   //   B is a base class (clause 10) of D. If B is an inaccessible
   2115   //   (clause 11) or ambiguous (10.2) base class of D, a program that
   2116   //   necessitates this conversion is ill-formed. The result of the
   2117   //   conversion is a pointer to the base class sub-object of the
   2118   //   derived class object. The null pointer value is converted to
   2119   //   the null pointer value of the destination type.
   2120   //
   2121   // Note that we do not check for ambiguity or inaccessibility
   2122   // here. That is handled by CheckPointerConversion.
   2123   if (getLangOpts().CPlusPlus &&
   2124       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
   2125       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
   2126       !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
   2127       IsDerivedFrom(FromPointeeType, ToPointeeType)) {
   2128     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
   2129                                                        ToPointeeType,
   2130                                                        ToType, Context);
   2131     return true;
   2132   }
   2133 
   2134   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
   2135       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
   2136     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
   2137                                                        ToPointeeType,
   2138                                                        ToType, Context);
   2139     return true;
   2140   }
   2141 
   2142   return false;
   2143 }
   2144 
   2145 /// \brief Adopt the given qualifiers for the given type.
   2146 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
   2147   Qualifiers TQs = T.getQualifiers();
   2148 
   2149   // Check whether qualifiers already match.
   2150   if (TQs == Qs)
   2151     return T;
   2152 
   2153   if (Qs.compatiblyIncludes(TQs))
   2154     return Context.getQualifiedType(T, Qs);
   2155 
   2156   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
   2157 }
   2158 
   2159 /// isObjCPointerConversion - Determines whether this is an
   2160 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
   2161 /// with the same arguments and return values.
   2162 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
   2163                                    QualType& ConvertedType,
   2164                                    bool &IncompatibleObjC) {
   2165   if (!getLangOpts().ObjC1)
   2166     return false;
   2167 
   2168   // The set of qualifiers on the type we're converting from.
   2169   Qualifiers FromQualifiers = FromType.getQualifiers();
   2170 
   2171   // First, we handle all conversions on ObjC object pointer types.
   2172   const ObjCObjectPointerType* ToObjCPtr =
   2173     ToType->getAs<ObjCObjectPointerType>();
   2174   const ObjCObjectPointerType *FromObjCPtr =
   2175     FromType->getAs<ObjCObjectPointerType>();
   2176 
   2177   if (ToObjCPtr && FromObjCPtr) {
   2178     // If the pointee types are the same (ignoring qualifications),
   2179     // then this is not a pointer conversion.
   2180     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
   2181                                        FromObjCPtr->getPointeeType()))
   2182       return false;
   2183 
   2184     // Check for compatible
   2185     // Objective C++: We're able to convert between "id" or "Class" and a
   2186     // pointer to any interface (in both directions).
   2187     if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
   2188       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
   2189       return true;
   2190     }
   2191     // Conversions with Objective-C's id<...>.
   2192     if ((FromObjCPtr->isObjCQualifiedIdType() ||
   2193          ToObjCPtr->isObjCQualifiedIdType()) &&
   2194         Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
   2195                                                   /*compare=*/false)) {
   2196       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
   2197       return true;
   2198     }
   2199     // Objective C++: We're able to convert from a pointer to an
   2200     // interface to a pointer to a different interface.
   2201     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
   2202       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
   2203       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
   2204       if (getLangOpts().CPlusPlus && LHS && RHS &&
   2205           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
   2206                                                 FromObjCPtr->getPointeeType()))
   2207         return false;
   2208       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
   2209                                                    ToObjCPtr->getPointeeType(),
   2210                                                          ToType, Context);
   2211       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
   2212       return true;
   2213     }
   2214 
   2215     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
   2216       // Okay: this is some kind of implicit downcast of Objective-C
   2217       // interfaces, which is permitted. However, we're going to
   2218       // complain about it.
   2219       IncompatibleObjC = true;
   2220       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
   2221                                                    ToObjCPtr->getPointeeType(),
   2222                                                          ToType, Context);
   2223       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
   2224       return true;
   2225     }
   2226   }
   2227   // Beyond this point, both types need to be C pointers or block pointers.
   2228   QualType ToPointeeType;
   2229   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
   2230     ToPointeeType = ToCPtr->getPointeeType();
   2231   else if (const BlockPointerType *ToBlockPtr =
   2232             ToType->getAs<BlockPointerType>()) {
   2233     // Objective C++: We're able to convert from a pointer to any object
   2234     // to a block pointer type.
   2235     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
   2236       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
   2237       return true;
   2238     }
   2239     ToPointeeType = ToBlockPtr->getPointeeType();
   2240   }
   2241   else if (FromType->getAs<BlockPointerType>() &&
   2242            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
   2243     // Objective C++: We're able to convert from a block pointer type to a
   2244     // pointer to any object.
   2245     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
   2246     return true;
   2247   }
   2248   else
   2249     return false;
   2250 
   2251   QualType FromPointeeType;
   2252   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
   2253     FromPointeeType = FromCPtr->getPointeeType();
   2254   else if (const BlockPointerType *FromBlockPtr =
   2255            FromType->getAs<BlockPointerType>())
   2256     FromPointeeType = FromBlockPtr->getPointeeType();
   2257   else
   2258     return false;
   2259 
   2260   // If we have pointers to pointers, recursively check whether this
   2261   // is an Objective-C conversion.
   2262   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
   2263       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
   2264                               IncompatibleObjC)) {
   2265     // We always complain about this conversion.
   2266     IncompatibleObjC = true;
   2267     ConvertedType = Context.getPointerType(ConvertedType);
   2268     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
   2269     return true;
   2270   }
   2271   // Allow conversion of pointee being objective-c pointer to another one;
   2272   // as in I* to id.
   2273   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
   2274       ToPointeeType->getAs<ObjCObjectPointerType>() &&
   2275       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
   2276                               IncompatibleObjC)) {
   2277 
   2278     ConvertedType = Context.getPointerType(ConvertedType);
   2279     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
   2280     return true;
   2281   }
   2282 
   2283   // If we have pointers to functions or blocks, check whether the only
   2284   // differences in the argument and result types are in Objective-C
   2285   // pointer conversions. If so, we permit the conversion (but
   2286   // complain about it).
   2287   const FunctionProtoType *FromFunctionType
   2288     = FromPointeeType->getAs<FunctionProtoType>();
   2289   const FunctionProtoType *ToFunctionType
   2290     = ToPointeeType->getAs<FunctionProtoType>();
   2291   if (FromFunctionType && ToFunctionType) {
   2292     // If the function types are exactly the same, this isn't an
   2293     // Objective-C pointer conversion.
   2294     if (Context.getCanonicalType(FromPointeeType)
   2295           == Context.getCanonicalType(ToPointeeType))
   2296       return false;
   2297 
   2298     // Perform the quick checks that will tell us whether these
   2299     // function types are obviously different.
   2300     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
   2301         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
   2302         FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
   2303       return false;
   2304 
   2305     bool HasObjCConversion = false;
   2306     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
   2307         Context.getCanonicalType(ToFunctionType->getReturnType())) {
   2308       // Okay, the types match exactly. Nothing to do.
   2309     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
   2310                                        ToFunctionType->getReturnType(),
   2311                                        ConvertedType, IncompatibleObjC)) {
   2312       // Okay, we have an Objective-C pointer conversion.
   2313       HasObjCConversion = true;
   2314     } else {
   2315       // Function types are too different. Abort.
   2316       return false;
   2317     }
   2318 
   2319     // Check argument types.
   2320     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
   2321          ArgIdx != NumArgs; ++ArgIdx) {
   2322       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
   2323       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
   2324       if (Context.getCanonicalType(FromArgType)
   2325             == Context.getCanonicalType(ToArgType)) {
   2326         // Okay, the types match exactly. Nothing to do.
   2327       } else if (isObjCPointerConversion(FromArgType, ToArgType,
   2328                                          ConvertedType, IncompatibleObjC)) {
   2329         // Okay, we have an Objective-C pointer conversion.
   2330         HasObjCConversion = true;
   2331       } else {
   2332         // Argument types are too different. Abort.
   2333         return false;
   2334       }
   2335     }
   2336 
   2337     if (HasObjCConversion) {
   2338       // We had an Objective-C conversion. Allow this pointer
   2339       // conversion, but complain about it.
   2340       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
   2341       IncompatibleObjC = true;
   2342       return true;
   2343     }
   2344   }
   2345 
   2346   return false;
   2347 }
   2348 
   2349 /// \brief Determine whether this is an Objective-C writeback conversion,
   2350 /// used for parameter passing when performing automatic reference counting.
   2351 ///
   2352 /// \param FromType The type we're converting form.
   2353 ///
   2354 /// \param ToType The type we're converting to.
   2355 ///
   2356 /// \param ConvertedType The type that will be produced after applying
   2357 /// this conversion.
   2358 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
   2359                                      QualType &ConvertedType) {
   2360   if (!getLangOpts().ObjCAutoRefCount ||
   2361       Context.hasSameUnqualifiedType(FromType, ToType))
   2362     return false;
   2363 
   2364   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
   2365   QualType ToPointee;
   2366   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
   2367     ToPointee = ToPointer->getPointeeType();
   2368   else
   2369     return false;
   2370 
   2371   Qualifiers ToQuals = ToPointee.getQualifiers();
   2372   if (!ToPointee->isObjCLifetimeType() ||
   2373       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
   2374       !ToQuals.withoutObjCLifetime().empty())
   2375     return false;
   2376 
   2377   // Argument must be a pointer to __strong to __weak.
   2378   QualType FromPointee;
   2379   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
   2380     FromPointee = FromPointer->getPointeeType();
   2381   else
   2382     return false;
   2383 
   2384   Qualifiers FromQuals = FromPointee.getQualifiers();
   2385   if (!FromPointee->isObjCLifetimeType() ||
   2386       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
   2387        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
   2388     return false;
   2389 
   2390   // Make sure that we have compatible qualifiers.
   2391   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
   2392   if (!ToQuals.compatiblyIncludes(FromQuals))
   2393     return false;
   2394 
   2395   // Remove qualifiers from the pointee type we're converting from; they
   2396   // aren't used in the compatibility check belong, and we'll be adding back
   2397   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
   2398   FromPointee = FromPointee.getUnqualifiedType();
   2399 
   2400   // The unqualified form of the pointee types must be compatible.
   2401   ToPointee = ToPointee.getUnqualifiedType();
   2402   bool IncompatibleObjC;
   2403   if (Context.typesAreCompatible(FromPointee, ToPointee))
   2404     FromPointee = ToPointee;
   2405   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
   2406                                     IncompatibleObjC))
   2407     return false;
   2408 
   2409   /// \brief Construct the type we're converting to, which is a pointer to
   2410   /// __autoreleasing pointee.
   2411   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
   2412   ConvertedType = Context.getPointerType(FromPointee);
   2413   return true;
   2414 }
   2415 
   2416 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
   2417                                     QualType& ConvertedType) {
   2418   QualType ToPointeeType;
   2419   if (const BlockPointerType *ToBlockPtr =
   2420         ToType->getAs<BlockPointerType>())
   2421     ToPointeeType = ToBlockPtr->getPointeeType();
   2422   else
   2423     return false;
   2424 
   2425   QualType FromPointeeType;
   2426   if (const BlockPointerType *FromBlockPtr =
   2427       FromType->getAs<BlockPointerType>())
   2428     FromPointeeType = FromBlockPtr->getPointeeType();
   2429   else
   2430     return false;
   2431   // We have pointer to blocks, check whether the only
   2432   // differences in the argument and result types are in Objective-C
   2433   // pointer conversions. If so, we permit the conversion.
   2434 
   2435   const FunctionProtoType *FromFunctionType
   2436     = FromPointeeType->getAs<FunctionProtoType>();
   2437   const FunctionProtoType *ToFunctionType
   2438     = ToPointeeType->getAs<FunctionProtoType>();
   2439 
   2440   if (!FromFunctionType || !ToFunctionType)
   2441     return false;
   2442 
   2443   if (Context.hasSameType(FromPointeeType, ToPointeeType))
   2444     return true;
   2445 
   2446   // Perform the quick checks that will tell us whether these
   2447   // function types are obviously different.
   2448   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
   2449       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
   2450     return false;
   2451 
   2452   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
   2453   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
   2454   if (FromEInfo != ToEInfo)
   2455     return false;
   2456 
   2457   bool IncompatibleObjC = false;
   2458   if (Context.hasSameType(FromFunctionType->getReturnType(),
   2459                           ToFunctionType->getReturnType())) {
   2460     // Okay, the types match exactly. Nothing to do.
   2461   } else {
   2462     QualType RHS = FromFunctionType->getReturnType();
   2463     QualType LHS = ToFunctionType->getReturnType();
   2464     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
   2465         !RHS.hasQualifiers() && LHS.hasQualifiers())
   2466        LHS = LHS.getUnqualifiedType();
   2467 
   2468      if (Context.hasSameType(RHS,LHS)) {
   2469        // OK exact match.
   2470      } else if (isObjCPointerConversion(RHS, LHS,
   2471                                         ConvertedType, IncompatibleObjC)) {
   2472      if (IncompatibleObjC)
   2473        return false;
   2474      // Okay, we have an Objective-C pointer conversion.
   2475      }
   2476      else
   2477        return false;
   2478    }
   2479 
   2480    // Check argument types.
   2481    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
   2482         ArgIdx != NumArgs; ++ArgIdx) {
   2483      IncompatibleObjC = false;
   2484      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
   2485      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
   2486      if (Context.hasSameType(FromArgType, ToArgType)) {
   2487        // Okay, the types match exactly. Nothing to do.
   2488      } else if (isObjCPointerConversion(ToArgType, FromArgType,
   2489                                         ConvertedType, IncompatibleObjC)) {
   2490        if (IncompatibleObjC)
   2491          return false;
   2492        // Okay, we have an Objective-C pointer conversion.
   2493      } else
   2494        // Argument types are too different. Abort.
   2495        return false;
   2496    }
   2497    if (LangOpts.ObjCAutoRefCount &&
   2498        !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
   2499                                                     ToFunctionType))
   2500      return false;
   2501 
   2502    ConvertedType = ToType;
   2503    return true;
   2504 }
   2505 
   2506 enum {
   2507   ft_default,
   2508   ft_different_class,
   2509   ft_parameter_arity,
   2510   ft_parameter_mismatch,
   2511   ft_return_type,
   2512   ft_qualifer_mismatch
   2513 };
   2514 
   2515 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
   2516 /// function types.  Catches different number of parameter, mismatch in
   2517 /// parameter types, and different return types.
   2518 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
   2519                                       QualType FromType, QualType ToType) {
   2520   // If either type is not valid, include no extra info.
   2521   if (FromType.isNull() || ToType.isNull()) {
   2522     PDiag << ft_default;
   2523     return;
   2524   }
   2525 
   2526   // Get the function type from the pointers.
   2527   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
   2528     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
   2529                             *ToMember = ToType->getAs<MemberPointerType>();
   2530     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
   2531       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
   2532             << QualType(FromMember->getClass(), 0);
   2533       return;
   2534     }
   2535     FromType = FromMember->getPointeeType();
   2536     ToType = ToMember->getPointeeType();
   2537   }
   2538 
   2539   if (FromType->isPointerType())
   2540     FromType = FromType->getPointeeType();
   2541   if (ToType->isPointerType())
   2542     ToType = ToType->getPointeeType();
   2543 
   2544   // Remove references.
   2545   FromType = FromType.getNonReferenceType();
   2546   ToType = ToType.getNonReferenceType();
   2547 
   2548   // Don't print extra info for non-specialized template functions.
   2549   if (FromType->isInstantiationDependentType() &&
   2550       !FromType->getAs<TemplateSpecializationType>()) {
   2551     PDiag << ft_default;
   2552     return;
   2553   }
   2554 
   2555   // No extra info for same types.
   2556   if (Context.hasSameType(FromType, ToType)) {
   2557     PDiag << ft_default;
   2558     return;
   2559   }
   2560 
   2561   const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
   2562                           *ToFunction = ToType->getAs<FunctionProtoType>();
   2563 
   2564   // Both types need to be function types.
   2565   if (!FromFunction || !ToFunction) {
   2566     PDiag << ft_default;
   2567     return;
   2568   }
   2569 
   2570   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
   2571     PDiag << ft_parameter_arity << ToFunction->getNumParams()
   2572           << FromFunction->getNumParams();
   2573     return;
   2574   }
   2575 
   2576   // Handle different parameter types.
   2577   unsigned ArgPos;
   2578   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
   2579     PDiag << ft_parameter_mismatch << ArgPos + 1
   2580           << ToFunction->getParamType(ArgPos)
   2581           << FromFunction->getParamType(ArgPos);
   2582     return;
   2583   }
   2584 
   2585   // Handle different return type.
   2586   if (!Context.hasSameType(FromFunction->getReturnType(),
   2587                            ToFunction->getReturnType())) {
   2588     PDiag << ft_return_type << ToFunction->getReturnType()
   2589           << FromFunction->getReturnType();
   2590     return;
   2591   }
   2592 
   2593   unsigned FromQuals = FromFunction->getTypeQuals(),
   2594            ToQuals = ToFunction->getTypeQuals();
   2595   if (FromQuals != ToQuals) {
   2596     PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
   2597     return;
   2598   }
   2599 
   2600   // Unable to find a difference, so add no extra info.
   2601   PDiag << ft_default;
   2602 }
   2603 
   2604 /// FunctionParamTypesAreEqual - This routine checks two function proto types
   2605 /// for equality of their argument types. Caller has already checked that
   2606 /// they have same number of arguments.  If the parameters are different,
   2607 /// ArgPos will have the parameter index of the first different parameter.
   2608 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
   2609                                       const FunctionProtoType *NewType,
   2610                                       unsigned *ArgPos) {
   2611   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
   2612                                               N = NewType->param_type_begin(),
   2613                                               E = OldType->param_type_end();
   2614        O && (O != E); ++O, ++N) {
   2615     if (!Context.hasSameType(O->getUnqualifiedType(),
   2616                              N->getUnqualifiedType())) {
   2617       if (ArgPos)
   2618         *ArgPos = O - OldType->param_type_begin();
   2619       return false;
   2620     }
   2621   }
   2622   return true;
   2623 }
   2624 
   2625 /// CheckPointerConversion - Check the pointer conversion from the
   2626 /// expression From to the type ToType. This routine checks for
   2627 /// ambiguous or inaccessible derived-to-base pointer
   2628 /// conversions for which IsPointerConversion has already returned
   2629 /// true. It returns true and produces a diagnostic if there was an
   2630 /// error, or returns false otherwise.
   2631 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
   2632                                   CastKind &Kind,
   2633                                   CXXCastPath& BasePath,
   2634                                   bool IgnoreBaseAccess) {
   2635   QualType FromType = From->getType();
   2636   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
   2637 
   2638   Kind = CK_BitCast;
   2639 
   2640   if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
   2641       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
   2642       Expr::NPCK_ZeroExpression) {
   2643     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
   2644       DiagRuntimeBehavior(From->getExprLoc(), From,
   2645                           PDiag(diag::warn_impcast_bool_to_null_pointer)
   2646                             << ToType << From->getSourceRange());
   2647     else if (!isUnevaluatedContext())
   2648       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
   2649         << ToType << From->getSourceRange();
   2650   }
   2651   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
   2652     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
   2653       QualType FromPointeeType = FromPtrType->getPointeeType(),
   2654                ToPointeeType   = ToPtrType->getPointeeType();
   2655 
   2656       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
   2657           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
   2658         // We must have a derived-to-base conversion. Check an
   2659         // ambiguous or inaccessible conversion.
   2660         if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
   2661                                          From->getExprLoc(),
   2662                                          From->getSourceRange(), &BasePath,
   2663                                          IgnoreBaseAccess))
   2664           return true;
   2665 
   2666         // The conversion was successful.
   2667         Kind = CK_DerivedToBase;
   2668       }
   2669     }
   2670   } else if (const ObjCObjectPointerType *ToPtrType =
   2671                ToType->getAs<ObjCObjectPointerType>()) {
   2672     if (const ObjCObjectPointerType *FromPtrType =
   2673           FromType->getAs<ObjCObjectPointerType>()) {
   2674       // Objective-C++ conversions are always okay.
   2675       // FIXME: We should have a different class of conversions for the
   2676       // Objective-C++ implicit conversions.
   2677       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
   2678         return false;
   2679     } else if (FromType->isBlockPointerType()) {
   2680       Kind = CK_BlockPointerToObjCPointerCast;
   2681     } else {
   2682       Kind = CK_CPointerToObjCPointerCast;
   2683     }
   2684   } else if (ToType->isBlockPointerType()) {
   2685     if (!FromType->isBlockPointerType())
   2686       Kind = CK_AnyPointerToBlockPointerCast;
   2687   }
   2688 
   2689   // We shouldn't fall into this case unless it's valid for other
   2690   // reasons.
   2691   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
   2692     Kind = CK_NullToPointer;
   2693 
   2694   return false;
   2695 }
   2696 
   2697 /// IsMemberPointerConversion - Determines whether the conversion of the
   2698 /// expression From, which has the (possibly adjusted) type FromType, can be
   2699 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
   2700 /// If so, returns true and places the converted type (that might differ from
   2701 /// ToType in its cv-qualifiers at some level) into ConvertedType.
   2702 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
   2703                                      QualType ToType,
   2704                                      bool InOverloadResolution,
   2705                                      QualType &ConvertedType) {
   2706   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
   2707   if (!ToTypePtr)
   2708     return false;
   2709 
   2710   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
   2711   if (From->isNullPointerConstant(Context,
   2712                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
   2713                                         : Expr::NPC_ValueDependentIsNull)) {
   2714     ConvertedType = ToType;
   2715     return true;
   2716   }
   2717 
   2718   // Otherwise, both types have to be member pointers.
   2719   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
   2720   if (!FromTypePtr)
   2721     return false;
   2722 
   2723   // A pointer to member of B can be converted to a pointer to member of D,
   2724   // where D is derived from B (C++ 4.11p2).
   2725   QualType FromClass(FromTypePtr->getClass(), 0);
   2726   QualType ToClass(ToTypePtr->getClass(), 0);
   2727 
   2728   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
   2729       !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
   2730       IsDerivedFrom(ToClass, FromClass)) {
   2731     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
   2732                                                  ToClass.getTypePtr());
   2733     return true;
   2734   }
   2735 
   2736   return false;
   2737 }
   2738 
   2739 /// CheckMemberPointerConversion - Check the member pointer conversion from the
   2740 /// expression From to the type ToType. This routine checks for ambiguous or
   2741 /// virtual or inaccessible base-to-derived member pointer conversions
   2742 /// for which IsMemberPointerConversion has already returned true. It returns
   2743 /// true and produces a diagnostic if there was an error, or returns false
   2744 /// otherwise.
   2745 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
   2746                                         CastKind &Kind,
   2747                                         CXXCastPath &BasePath,
   2748                                         bool IgnoreBaseAccess) {
   2749   QualType FromType = From->getType();
   2750   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
   2751   if (!FromPtrType) {
   2752     // This must be a null pointer to member pointer conversion
   2753     assert(From->isNullPointerConstant(Context,
   2754                                        Expr::NPC_ValueDependentIsNull) &&
   2755            "Expr must be null pointer constant!");
   2756     Kind = CK_NullToMemberPointer;
   2757     return false;
   2758   }
   2759 
   2760   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
   2761   assert(ToPtrType && "No member pointer cast has a target type "
   2762                       "that is not a member pointer.");
   2763 
   2764   QualType FromClass = QualType(FromPtrType->getClass(), 0);
   2765   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
   2766 
   2767   // FIXME: What about dependent types?
   2768   assert(FromClass->isRecordType() && "Pointer into non-class.");
   2769   assert(ToClass->isRecordType() && "Pointer into non-class.");
   2770 
   2771   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   2772                      /*DetectVirtual=*/true);
   2773   bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
   2774   assert(DerivationOkay &&
   2775          "Should not have been called if derivation isn't OK.");
   2776   (void)DerivationOkay;
   2777 
   2778   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
   2779                                   getUnqualifiedType())) {
   2780     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
   2781     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
   2782       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
   2783     return true;
   2784   }
   2785 
   2786   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
   2787     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
   2788       << FromClass << ToClass << QualType(VBase, 0)
   2789       << From->getSourceRange();
   2790     return true;
   2791   }
   2792 
   2793   if (!IgnoreBaseAccess)
   2794     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
   2795                          Paths.front(),
   2796                          diag::err_downcast_from_inaccessible_base);
   2797 
   2798   // Must be a base to derived member conversion.
   2799   BuildBasePathArray(Paths, BasePath);
   2800   Kind = CK_BaseToDerivedMemberPointer;
   2801   return false;
   2802 }
   2803 
   2804 /// Determine whether the lifetime conversion between the two given
   2805 /// qualifiers sets is nontrivial.
   2806 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
   2807                                                Qualifiers ToQuals) {
   2808   // Converting anything to const __unsafe_unretained is trivial.
   2809   if (ToQuals.hasConst() &&
   2810       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
   2811     return false;
   2812 
   2813   return true;
   2814 }
   2815 
   2816 /// IsQualificationConversion - Determines whether the conversion from
   2817 /// an rvalue of type FromType to ToType is a qualification conversion
   2818 /// (C++ 4.4).
   2819 ///
   2820 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
   2821 /// when the qualification conversion involves a change in the Objective-C
   2822 /// object lifetime.
   2823 bool
   2824 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
   2825                                 bool CStyle, bool &ObjCLifetimeConversion) {
   2826   FromType = Context.getCanonicalType(FromType);
   2827   ToType = Context.getCanonicalType(ToType);
   2828   ObjCLifetimeConversion = false;
   2829 
   2830   // If FromType and ToType are the same type, this is not a
   2831   // qualification conversion.
   2832   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
   2833     return false;
   2834 
   2835   // (C++ 4.4p4):
   2836   //   A conversion can add cv-qualifiers at levels other than the first
   2837   //   in multi-level pointers, subject to the following rules: [...]
   2838   bool PreviousToQualsIncludeConst = true;
   2839   bool UnwrappedAnyPointer = false;
   2840   while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
   2841     // Within each iteration of the loop, we check the qualifiers to
   2842     // determine if this still looks like a qualification
   2843     // conversion. Then, if all is well, we unwrap one more level of
   2844     // pointers or pointers-to-members and do it all again
   2845     // until there are no more pointers or pointers-to-members left to
   2846     // unwrap.
   2847     UnwrappedAnyPointer = true;
   2848 
   2849     Qualifiers FromQuals = FromType.getQualifiers();
   2850     Qualifiers ToQuals = ToType.getQualifiers();
   2851 
   2852     // Objective-C ARC:
   2853     //   Check Objective-C lifetime conversions.
   2854     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
   2855         UnwrappedAnyPointer) {
   2856       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
   2857         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
   2858           ObjCLifetimeConversion = true;
   2859         FromQuals.removeObjCLifetime();
   2860         ToQuals.removeObjCLifetime();
   2861       } else {
   2862         // Qualification conversions cannot cast between different
   2863         // Objective-C lifetime qualifiers.
   2864         return false;
   2865       }
   2866     }
   2867 
   2868     // Allow addition/removal of GC attributes but not changing GC attributes.
   2869     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
   2870         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
   2871       FromQuals.removeObjCGCAttr();
   2872       ToQuals.removeObjCGCAttr();
   2873     }
   2874 
   2875     //   -- for every j > 0, if const is in cv 1,j then const is in cv
   2876     //      2,j, and similarly for volatile.
   2877     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
   2878       return false;
   2879 
   2880     //   -- if the cv 1,j and cv 2,j are different, then const is in
   2881     //      every cv for 0 < k < j.
   2882     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
   2883         && !PreviousToQualsIncludeConst)
   2884       return false;
   2885 
   2886     // Keep track of whether all prior cv-qualifiers in the "to" type
   2887     // include const.
   2888     PreviousToQualsIncludeConst
   2889       = PreviousToQualsIncludeConst && ToQuals.hasConst();
   2890   }
   2891 
   2892   // We are left with FromType and ToType being the pointee types
   2893   // after unwrapping the original FromType and ToType the same number
   2894   // of types. If we unwrapped any pointers, and if FromType and
   2895   // ToType have the same unqualified type (since we checked
   2896   // qualifiers above), then this is a qualification conversion.
   2897   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
   2898 }
   2899 
   2900 /// \brief - Determine whether this is a conversion from a scalar type to an
   2901 /// atomic type.
   2902 ///
   2903 /// If successful, updates \c SCS's second and third steps in the conversion
   2904 /// sequence to finish the conversion.
   2905 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
   2906                                 bool InOverloadResolution,
   2907                                 StandardConversionSequence &SCS,
   2908                                 bool CStyle) {
   2909   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
   2910   if (!ToAtomic)
   2911     return false;
   2912 
   2913   StandardConversionSequence InnerSCS;
   2914   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
   2915                             InOverloadResolution, InnerSCS,
   2916                             CStyle, /*AllowObjCWritebackConversion=*/false))
   2917     return false;
   2918 
   2919   SCS.Second = InnerSCS.Second;
   2920   SCS.setToType(1, InnerSCS.getToType(1));
   2921   SCS.Third = InnerSCS.Third;
   2922   SCS.QualificationIncludesObjCLifetime
   2923     = InnerSCS.QualificationIncludesObjCLifetime;
   2924   SCS.setToType(2, InnerSCS.getToType(2));
   2925   return true;
   2926 }
   2927 
   2928 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
   2929                                               CXXConstructorDecl *Constructor,
   2930                                               QualType Type) {
   2931   const FunctionProtoType *CtorType =
   2932       Constructor->getType()->getAs<FunctionProtoType>();
   2933   if (CtorType->getNumParams() > 0) {
   2934     QualType FirstArg = CtorType->getParamType(0);
   2935     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
   2936       return true;
   2937   }
   2938   return false;
   2939 }
   2940 
   2941 static OverloadingResult
   2942 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
   2943                                        CXXRecordDecl *To,
   2944                                        UserDefinedConversionSequence &User,
   2945                                        OverloadCandidateSet &CandidateSet,
   2946                                        bool AllowExplicit) {
   2947   DeclContext::lookup_result R = S.LookupConstructors(To);
   2948   for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
   2949        Con != ConEnd; ++Con) {
   2950     NamedDecl *D = *Con;
   2951     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
   2952 
   2953     // Find the constructor (which may be a template).
   2954     CXXConstructorDecl *Constructor = nullptr;
   2955     FunctionTemplateDecl *ConstructorTmpl
   2956       = dyn_cast<FunctionTemplateDecl>(D);
   2957     if (ConstructorTmpl)
   2958       Constructor
   2959         = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
   2960     else
   2961       Constructor = cast<CXXConstructorDecl>(D);
   2962 
   2963     bool Usable = !Constructor->isInvalidDecl() &&
   2964                   S.isInitListConstructor(Constructor) &&
   2965                   (AllowExplicit || !Constructor->isExplicit());
   2966     if (Usable) {
   2967       // If the first argument is (a reference to) the target type,
   2968       // suppress conversions.
   2969       bool SuppressUserConversions =
   2970           isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
   2971       if (ConstructorTmpl)
   2972         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
   2973                                        /*ExplicitArgs*/ nullptr,
   2974                                        From, CandidateSet,
   2975                                        SuppressUserConversions);
   2976       else
   2977         S.AddOverloadCandidate(Constructor, FoundDecl,
   2978                                From, CandidateSet,
   2979                                SuppressUserConversions);
   2980     }
   2981   }
   2982 
   2983   bool HadMultipleCandidates = (CandidateSet.size() > 1);
   2984 
   2985   OverloadCandidateSet::iterator Best;
   2986   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
   2987   case OR_Success: {
   2988     // Record the standard conversion we used and the conversion function.
   2989     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
   2990     QualType ThisType = Constructor->getThisType(S.Context);
   2991     // Initializer lists don't have conversions as such.
   2992     User.Before.setAsIdentityConversion();
   2993     User.HadMultipleCandidates = HadMultipleCandidates;
   2994     User.ConversionFunction = Constructor;
   2995     User.FoundConversionFunction = Best->FoundDecl;
   2996     User.After.setAsIdentityConversion();
   2997     User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
   2998     User.After.setAllToTypes(ToType);
   2999     return OR_Success;
   3000   }
   3001 
   3002   case OR_No_Viable_Function:
   3003     return OR_No_Viable_Function;
   3004   case OR_Deleted:
   3005     return OR_Deleted;
   3006   case OR_Ambiguous:
   3007     return OR_Ambiguous;
   3008   }
   3009 
   3010   llvm_unreachable("Invalid OverloadResult!");
   3011 }
   3012 
   3013 /// Determines whether there is a user-defined conversion sequence
   3014 /// (C++ [over.ics.user]) that converts expression From to the type
   3015 /// ToType. If such a conversion exists, User will contain the
   3016 /// user-defined conversion sequence that performs such a conversion
   3017 /// and this routine will return true. Otherwise, this routine returns
   3018 /// false and User is unspecified.
   3019 ///
   3020 /// \param AllowExplicit  true if the conversion should consider C++0x
   3021 /// "explicit" conversion functions as well as non-explicit conversion
   3022 /// functions (C++0x [class.conv.fct]p2).
   3023 ///
   3024 /// \param AllowObjCConversionOnExplicit true if the conversion should
   3025 /// allow an extra Objective-C pointer conversion on uses of explicit
   3026 /// constructors. Requires \c AllowExplicit to also be set.
   3027 static OverloadingResult
   3028 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
   3029                         UserDefinedConversionSequence &User,
   3030                         OverloadCandidateSet &CandidateSet,
   3031                         bool AllowExplicit,
   3032                         bool AllowObjCConversionOnExplicit) {
   3033   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
   3034 
   3035   // Whether we will only visit constructors.
   3036   bool ConstructorsOnly = false;
   3037 
   3038   // If the type we are conversion to is a class type, enumerate its
   3039   // constructors.
   3040   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
   3041     // C++ [over.match.ctor]p1:
   3042     //   When objects of class type are direct-initialized (8.5), or
   3043     //   copy-initialized from an expression of the same or a
   3044     //   derived class type (8.5), overload resolution selects the
   3045     //   constructor. [...] For copy-initialization, the candidate
   3046     //   functions are all the converting constructors (12.3.1) of
   3047     //   that class. The argument list is the expression-list within
   3048     //   the parentheses of the initializer.
   3049     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
   3050         (From->getType()->getAs<RecordType>() &&
   3051          S.IsDerivedFrom(From->getType(), ToType)))
   3052       ConstructorsOnly = true;
   3053 
   3054     S.RequireCompleteType(From->getExprLoc(), ToType, 0);
   3055     // RequireCompleteType may have returned true due to some invalid decl
   3056     // during template instantiation, but ToType may be complete enough now
   3057     // to try to recover.
   3058     if (ToType->isIncompleteType()) {
   3059       // We're not going to find any constructors.
   3060     } else if (CXXRecordDecl *ToRecordDecl
   3061                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
   3062 
   3063       Expr **Args = &From;
   3064       unsigned NumArgs = 1;
   3065       bool ListInitializing = false;
   3066       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
   3067         // But first, see if there is an init-list-constructor that will work.
   3068         OverloadingResult Result = IsInitializerListConstructorConversion(
   3069             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
   3070         if (Result != OR_No_Viable_Function)
   3071           return Result;
   3072         // Never mind.
   3073         CandidateSet.clear();
   3074 
   3075         // If we're list-initializing, we pass the individual elements as
   3076         // arguments, not the entire list.
   3077         Args = InitList->getInits();
   3078         NumArgs = InitList->getNumInits();
   3079         ListInitializing = true;
   3080       }
   3081 
   3082       DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
   3083       for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
   3084            Con != ConEnd; ++Con) {
   3085         NamedDecl *D = *Con;
   3086         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
   3087 
   3088         // Find the constructor (which may be a template).
   3089         CXXConstructorDecl *Constructor = nullptr;
   3090         FunctionTemplateDecl *ConstructorTmpl
   3091           = dyn_cast<FunctionTemplateDecl>(D);
   3092         if (ConstructorTmpl)
   3093           Constructor
   3094             = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
   3095         else
   3096           Constructor = cast<CXXConstructorDecl>(D);
   3097 
   3098         bool Usable = !Constructor->isInvalidDecl();
   3099         if (ListInitializing)
   3100           Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
   3101         else
   3102           Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
   3103         if (Usable) {
   3104           bool SuppressUserConversions = !ConstructorsOnly;
   3105           if (SuppressUserConversions && ListInitializing) {
   3106             SuppressUserConversions = false;
   3107             if (NumArgs == 1) {
   3108               // If the first argument is (a reference to) the target type,
   3109               // suppress conversions.
   3110               SuppressUserConversions = isFirstArgumentCompatibleWithType(
   3111                                                 S.Context, Constructor, ToType);
   3112             }
   3113           }
   3114           if (ConstructorTmpl)
   3115             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
   3116                                            /*ExplicitArgs*/ nullptr,
   3117                                            llvm::makeArrayRef(Args, NumArgs),
   3118                                            CandidateSet, SuppressUserConversions);
   3119           else
   3120             // Allow one user-defined conversion when user specifies a
   3121             // From->ToType conversion via an static cast (c-style, etc).
   3122             S.AddOverloadCandidate(Constructor, FoundDecl,
   3123                                    llvm::makeArrayRef(Args, NumArgs),
   3124                                    CandidateSet, SuppressUserConversions);
   3125         }
   3126       }
   3127     }
   3128   }
   3129 
   3130   // Enumerate conversion functions, if we're allowed to.
   3131   if (ConstructorsOnly || isa<InitListExpr>(From)) {
   3132   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
   3133     // No conversion functions from incomplete types.
   3134   } else if (const RecordType *FromRecordType
   3135                                    = From->getType()->getAs<RecordType>()) {
   3136     if (CXXRecordDecl *FromRecordDecl
   3137          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
   3138       // Add all of the conversion functions as candidates.
   3139       std::pair<CXXRecordDecl::conversion_iterator,
   3140                 CXXRecordDecl::conversion_iterator>
   3141         Conversions = FromRecordDecl->getVisibleConversionFunctions();
   3142       for (CXXRecordDecl::conversion_iterator
   3143              I = Conversions.first, E = Conversions.second; I != E; ++I) {
   3144         DeclAccessPair FoundDecl = I.getPair();
   3145         NamedDecl *D = FoundDecl.getDecl();
   3146         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
   3147         if (isa<UsingShadowDecl>(D))
   3148           D = cast<UsingShadowDecl>(D)->getTargetDecl();
   3149 
   3150         CXXConversionDecl *Conv;
   3151         FunctionTemplateDecl *ConvTemplate;
   3152         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
   3153           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
   3154         else
   3155           Conv = cast<CXXConversionDecl>(D);
   3156 
   3157         if (AllowExplicit || !Conv->isExplicit()) {
   3158           if (ConvTemplate)
   3159             S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
   3160                                              ActingContext, From, ToType,
   3161                                              CandidateSet,
   3162                                              AllowObjCConversionOnExplicit);
   3163           else
   3164             S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
   3165                                      From, ToType, CandidateSet,
   3166                                      AllowObjCConversionOnExplicit);
   3167         }
   3168       }
   3169     }
   3170   }
   3171 
   3172   bool HadMultipleCandidates = (CandidateSet.size() > 1);
   3173 
   3174   OverloadCandidateSet::iterator Best;
   3175   switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
   3176   case OR_Success:
   3177     // Record the standard conversion we used and the conversion function.
   3178     if (CXXConstructorDecl *Constructor
   3179           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
   3180       // C++ [over.ics.user]p1:
   3181       //   If the user-defined conversion is specified by a
   3182       //   constructor (12.3.1), the initial standard conversion
   3183       //   sequence converts the source type to the type required by
   3184       //   the argument of the constructor.
   3185       //
   3186       QualType ThisType = Constructor->getThisType(S.Context);
   3187       if (isa<InitListExpr>(From)) {
   3188         // Initializer lists don't have conversions as such.
   3189         User.Before.setAsIdentityConversion();
   3190       } else {
   3191         if (Best->Conversions[0].isEllipsis())
   3192           User.EllipsisConversion = true;
   3193         else {
   3194           User.Before = Best->Conversions[0].Standard;
   3195           User.EllipsisConversion = false;
   3196         }
   3197       }
   3198       User.HadMultipleCandidates = HadMultipleCandidates;
   3199       User.ConversionFunction = Constructor;
   3200       User.FoundConversionFunction = Best->FoundDecl;
   3201       User.After.setAsIdentityConversion();
   3202       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
   3203       User.After.setAllToTypes(ToType);
   3204       return OR_Success;
   3205     }
   3206     if (CXXConversionDecl *Conversion
   3207                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
   3208       // C++ [over.ics.user]p1:
   3209       //
   3210       //   [...] If the user-defined conversion is specified by a
   3211       //   conversion function (12.3.2), the initial standard
   3212       //   conversion sequence converts the source type to the
   3213       //   implicit object parameter of the conversion function.
   3214       User.Before = Best->Conversions[0].Standard;
   3215       User.HadMultipleCandidates = HadMultipleCandidates;
   3216       User.ConversionFunction = Conversion;
   3217       User.FoundConversionFunction = Best->FoundDecl;
   3218       User.EllipsisConversion = false;
   3219 
   3220       // C++ [over.ics.user]p2:
   3221       //   The second standard conversion sequence converts the
   3222       //   result of the user-defined conversion to the target type
   3223       //   for the sequence. Since an implicit conversion sequence
   3224       //   is an initialization, the special rules for
   3225       //   initialization by user-defined conversion apply when
   3226       //   selecting the best user-defined conversion for a
   3227       //   user-defined conversion sequence (see 13.3.3 and
   3228       //   13.3.3.1).
   3229       User.After = Best->FinalConversion;
   3230       return OR_Success;
   3231     }
   3232     llvm_unreachable("Not a constructor or conversion function?");
   3233 
   3234   case OR_No_Viable_Function:
   3235     return OR_No_Viable_Function;
   3236   case OR_Deleted:
   3237     // No conversion here! We're done.
   3238     return OR_Deleted;
   3239 
   3240   case OR_Ambiguous:
   3241     return OR_Ambiguous;
   3242   }
   3243 
   3244   llvm_unreachable("Invalid OverloadResult!");
   3245 }
   3246 
   3247 bool
   3248 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
   3249   ImplicitConversionSequence ICS;
   3250   OverloadCandidateSet CandidateSet(From->getExprLoc(),
   3251                                     OverloadCandidateSet::CSK_Normal);
   3252   OverloadingResult OvResult =
   3253     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
   3254                             CandidateSet, false, false);
   3255   if (OvResult == OR_Ambiguous)
   3256     Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
   3257         << From->getType() << ToType << From->getSourceRange();
   3258   else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
   3259     if (!RequireCompleteType(From->getLocStart(), ToType,
   3260                              diag::err_typecheck_nonviable_condition_incomplete,
   3261                              From->getType(), From->getSourceRange()))
   3262       Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
   3263           << From->getType() << From->getSourceRange() << ToType;
   3264   } else
   3265     return false;
   3266   CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
   3267   return true;
   3268 }
   3269 
   3270 /// \brief Compare the user-defined conversion functions or constructors
   3271 /// of two user-defined conversion sequences to determine whether any ordering
   3272 /// is possible.
   3273 static ImplicitConversionSequence::CompareKind
   3274 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
   3275                            FunctionDecl *Function2) {
   3276   if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
   3277     return ImplicitConversionSequence::Indistinguishable;
   3278 
   3279   // Objective-C++:
   3280   //   If both conversion functions are implicitly-declared conversions from
   3281   //   a lambda closure type to a function pointer and a block pointer,
   3282   //   respectively, always prefer the conversion to a function pointer,
   3283   //   because the function pointer is more lightweight and is more likely
   3284   //   to keep code working.
   3285   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
   3286   if (!Conv1)
   3287     return ImplicitConversionSequence::Indistinguishable;
   3288 
   3289   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
   3290   if (!Conv2)
   3291     return ImplicitConversionSequence::Indistinguishable;
   3292 
   3293   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
   3294     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
   3295     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
   3296     if (Block1 != Block2)
   3297       return Block1 ? ImplicitConversionSequence::Worse
   3298                     : ImplicitConversionSequence::Better;
   3299   }
   3300 
   3301   return ImplicitConversionSequence::Indistinguishable;
   3302 }
   3303 
   3304 static bool hasDeprecatedStringLiteralToCharPtrConversion(
   3305     const ImplicitConversionSequence &ICS) {
   3306   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
   3307          (ICS.isUserDefined() &&
   3308           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
   3309 }
   3310 
   3311 /// CompareImplicitConversionSequences - Compare two implicit
   3312 /// conversion sequences to determine whether one is better than the
   3313 /// other or if they are indistinguishable (C++ 13.3.3.2).
   3314 static ImplicitConversionSequence::CompareKind
   3315 CompareImplicitConversionSequences(Sema &S,
   3316                                    const ImplicitConversionSequence& ICS1,
   3317                                    const ImplicitConversionSequence& ICS2)
   3318 {
   3319   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
   3320   // conversion sequences (as defined in 13.3.3.1)
   3321   //   -- a standard conversion sequence (13.3.3.1.1) is a better
   3322   //      conversion sequence than a user-defined conversion sequence or
   3323   //      an ellipsis conversion sequence, and
   3324   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
   3325   //      conversion sequence than an ellipsis conversion sequence
   3326   //      (13.3.3.1.3).
   3327   //
   3328   // C++0x [over.best.ics]p10:
   3329   //   For the purpose of ranking implicit conversion sequences as
   3330   //   described in 13.3.3.2, the ambiguous conversion sequence is
   3331   //   treated as a user-defined sequence that is indistinguishable
   3332   //   from any other user-defined conversion sequence.
   3333 
   3334   // String literal to 'char *' conversion has been deprecated in C++03. It has
   3335   // been removed from C++11. We still accept this conversion, if it happens at
   3336   // the best viable function. Otherwise, this conversion is considered worse
   3337   // than ellipsis conversion. Consider this as an extension; this is not in the
   3338   // standard. For example:
   3339   //
   3340   // int &f(...);    // #1
   3341   // void f(char*);  // #2
   3342   // void g() { int &r = f("foo"); }
   3343   //
   3344   // In C++03, we pick #2 as the best viable function.
   3345   // In C++11, we pick #1 as the best viable function, because ellipsis
   3346   // conversion is better than string-literal to char* conversion (since there
   3347   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
   3348   // convert arguments, #2 would be the best viable function in C++11.
   3349   // If the best viable function has this conversion, a warning will be issued
   3350   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
   3351 
   3352   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
   3353       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
   3354       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
   3355     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
   3356                ? ImplicitConversionSequence::Worse
   3357                : ImplicitConversionSequence::Better;
   3358 
   3359   if (ICS1.getKindRank() < ICS2.getKindRank())
   3360     return ImplicitConversionSequence::Better;
   3361   if (ICS2.getKindRank() < ICS1.getKindRank())
   3362     return ImplicitConversionSequence::Worse;
   3363 
   3364   // The following checks require both conversion sequences to be of
   3365   // the same kind.
   3366   if (ICS1.getKind() != ICS2.getKind())
   3367     return ImplicitConversionSequence::Indistinguishable;
   3368 
   3369   ImplicitConversionSequence::CompareKind Result =
   3370       ImplicitConversionSequence::Indistinguishable;
   3371 
   3372   // Two implicit conversion sequences of the same form are
   3373   // indistinguishable conversion sequences unless one of the
   3374   // following rules apply: (C++ 13.3.3.2p3):
   3375   if (ICS1.isStandard())
   3376     Result = CompareStandardConversionSequences(S,
   3377                                                 ICS1.Standard, ICS2.Standard);
   3378   else if (ICS1.isUserDefined()) {
   3379     // User-defined conversion sequence U1 is a better conversion
   3380     // sequence than another user-defined conversion sequence U2 if
   3381     // they contain the same user-defined conversion function or
   3382     // constructor and if the second standard conversion sequence of
   3383     // U1 is better than the second standard conversion sequence of
   3384     // U2 (C++ 13.3.3.2p3).
   3385     if (ICS1.UserDefined.ConversionFunction ==
   3386           ICS2.UserDefined.ConversionFunction)
   3387       Result = CompareStandardConversionSequences(S,
   3388                                                   ICS1.UserDefined.After,
   3389                                                   ICS2.UserDefined.After);
   3390     else
   3391       Result = compareConversionFunctions(S,
   3392                                           ICS1.UserDefined.ConversionFunction,
   3393                                           ICS2.UserDefined.ConversionFunction);
   3394   }
   3395 
   3396   // List-initialization sequence L1 is a better conversion sequence than
   3397   // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
   3398   // for some X and L2 does not.
   3399   if (Result == ImplicitConversionSequence::Indistinguishable &&
   3400       !ICS1.isBad()) {
   3401     if (ICS1.isStdInitializerListElement() &&
   3402         !ICS2.isStdInitializerListElement())
   3403       return ImplicitConversionSequence::Better;
   3404     if (!ICS1.isStdInitializerListElement() &&
   3405         ICS2.isStdInitializerListElement())
   3406       return ImplicitConversionSequence::Worse;
   3407   }
   3408 
   3409   return Result;
   3410 }
   3411 
   3412 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
   3413   while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
   3414     Qualifiers Quals;
   3415     T1 = Context.getUnqualifiedArrayType(T1, Quals);
   3416     T2 = Context.getUnqualifiedArrayType(T2, Quals);
   3417   }
   3418 
   3419   return Context.hasSameUnqualifiedType(T1, T2);
   3420 }
   3421 
   3422 // Per 13.3.3.2p3, compare the given standard conversion sequences to
   3423 // determine if one is a proper subset of the other.
   3424 static ImplicitConversionSequence::CompareKind
   3425 compareStandardConversionSubsets(ASTContext &Context,
   3426                                  const StandardConversionSequence& SCS1,
   3427                                  const StandardConversionSequence& SCS2) {
   3428   ImplicitConversionSequence::CompareKind Result
   3429     = ImplicitConversionSequence::Indistinguishable;
   3430 
   3431   // the identity conversion sequence is considered to be a subsequence of
   3432   // any non-identity conversion sequence
   3433   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
   3434     return ImplicitConversionSequence::Better;
   3435   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
   3436     return ImplicitConversionSequence::Worse;
   3437 
   3438   if (SCS1.Second != SCS2.Second) {
   3439     if (SCS1.Second == ICK_Identity)
   3440       Result = ImplicitConversionSequence::Better;
   3441     else if (SCS2.Second == ICK_Identity)
   3442       Result = ImplicitConversionSequence::Worse;
   3443     else
   3444       return ImplicitConversionSequence::Indistinguishable;
   3445   } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
   3446     return ImplicitConversionSequence::Indistinguishable;
   3447 
   3448   if (SCS1.Third == SCS2.Third) {
   3449     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
   3450                              : ImplicitConversionSequence::Indistinguishable;
   3451   }
   3452 
   3453   if (SCS1.Third == ICK_Identity)
   3454     return Result == ImplicitConversionSequence::Worse
   3455              ? ImplicitConversionSequence::Indistinguishable
   3456              : ImplicitConversionSequence::Better;
   3457 
   3458   if (SCS2.Third == ICK_Identity)
   3459     return Result == ImplicitConversionSequence::Better
   3460              ? ImplicitConversionSequence::Indistinguishable
   3461              : ImplicitConversionSequence::Worse;
   3462 
   3463   return ImplicitConversionSequence::Indistinguishable;
   3464 }
   3465 
   3466 /// \brief Determine whether one of the given reference bindings is better
   3467 /// than the other based on what kind of bindings they are.
   3468 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
   3469                                        const StandardConversionSequence &SCS2) {
   3470   // C++0x [over.ics.rank]p3b4:
   3471   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
   3472   //      implicit object parameter of a non-static member function declared
   3473   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
   3474   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
   3475   //      lvalue reference to a function lvalue and S2 binds an rvalue
   3476   //      reference*.
   3477   //
   3478   // FIXME: Rvalue references. We're going rogue with the above edits,
   3479   // because the semantics in the current C++0x working paper (N3225 at the
   3480   // time of this writing) break the standard definition of std::forward
   3481   // and std::reference_wrapper when dealing with references to functions.
   3482   // Proposed wording changes submitted to CWG for consideration.
   3483   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
   3484       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
   3485     return false;
   3486 
   3487   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
   3488           SCS2.IsLvalueReference) ||
   3489          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
   3490           !SCS2.IsLvalueReference);
   3491 }
   3492 
   3493 /// CompareStandardConversionSequences - Compare two standard
   3494 /// conversion sequences to determine whether one is better than the
   3495 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
   3496 static ImplicitConversionSequence::CompareKind
   3497 CompareStandardConversionSequences(Sema &S,
   3498                                    const StandardConversionSequence& SCS1,
   3499                                    const StandardConversionSequence& SCS2)
   3500 {
   3501   // Standard conversion sequence S1 is a better conversion sequence
   3502   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
   3503 
   3504   //  -- S1 is a proper subsequence of S2 (comparing the conversion
   3505   //     sequences in the canonical form defined by 13.3.3.1.1,
   3506   //     excluding any Lvalue Transformation; the identity conversion
   3507   //     sequence is considered to be a subsequence of any
   3508   //     non-identity conversion sequence) or, if not that,
   3509   if (ImplicitConversionSequence::CompareKind CK
   3510         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
   3511     return CK;
   3512 
   3513   //  -- the rank of S1 is better than the rank of S2 (by the rules
   3514   //     defined below), or, if not that,
   3515   ImplicitConversionRank Rank1 = SCS1.getRank();
   3516   ImplicitConversionRank Rank2 = SCS2.getRank();
   3517   if (Rank1 < Rank2)
   3518     return ImplicitConversionSequence::Better;
   3519   else if (Rank2 < Rank1)
   3520     return ImplicitConversionSequence::Worse;
   3521 
   3522   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
   3523   // are indistinguishable unless one of the following rules
   3524   // applies:
   3525 
   3526   //   A conversion that is not a conversion of a pointer, or
   3527   //   pointer to member, to bool is better than another conversion
   3528   //   that is such a conversion.
   3529   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
   3530     return SCS2.isPointerConversionToBool()
   3531              ? ImplicitConversionSequence::Better
   3532              : ImplicitConversionSequence::Worse;
   3533 
   3534   // C++ [over.ics.rank]p4b2:
   3535   //
   3536   //   If class B is derived directly or indirectly from class A,
   3537   //   conversion of B* to A* is better than conversion of B* to
   3538   //   void*, and conversion of A* to void* is better than conversion
   3539   //   of B* to void*.
   3540   bool SCS1ConvertsToVoid
   3541     = SCS1.isPointerConversionToVoidPointer(S.Context);
   3542   bool SCS2ConvertsToVoid
   3543     = SCS2.isPointerConversionToVoidPointer(S.Context);
   3544   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
   3545     // Exactly one of the conversion sequences is a conversion to
   3546     // a void pointer; it's the worse conversion.
   3547     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
   3548                               : ImplicitConversionSequence::Worse;
   3549   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
   3550     // Neither conversion sequence converts to a void pointer; compare
   3551     // their derived-to-base conversions.
   3552     if (ImplicitConversionSequence::CompareKind DerivedCK
   3553           = CompareDerivedToBaseConversions(S, SCS1, SCS2))
   3554       return DerivedCK;
   3555   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
   3556              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
   3557     // Both conversion sequences are conversions to void
   3558     // pointers. Compare the source types to determine if there's an
   3559     // inheritance relationship in their sources.
   3560     QualType FromType1 = SCS1.getFromType();
   3561     QualType FromType2 = SCS2.getFromType();
   3562 
   3563     // Adjust the types we're converting from via the array-to-pointer
   3564     // conversion, if we need to.
   3565     if (SCS1.First == ICK_Array_To_Pointer)
   3566       FromType1 = S.Context.getArrayDecayedType(FromType1);
   3567     if (SCS2.First == ICK_Array_To_Pointer)
   3568       FromType2 = S.Context.getArrayDecayedType(FromType2);
   3569 
   3570     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
   3571     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
   3572 
   3573     if (S.IsDerivedFrom(FromPointee2, FromPointee1))
   3574       return ImplicitConversionSequence::Better;
   3575     else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
   3576       return ImplicitConversionSequence::Worse;
   3577 
   3578     // Objective-C++: If one interface is more specific than the
   3579     // other, it is the better one.
   3580     const ObjCObjectPointerType* FromObjCPtr1
   3581       = FromType1->getAs<ObjCObjectPointerType>();
   3582     const ObjCObjectPointerType* FromObjCPtr2
   3583       = FromType2->getAs<ObjCObjectPointerType>();
   3584     if (FromObjCPtr1 && FromObjCPtr2) {
   3585       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
   3586                                                           FromObjCPtr2);
   3587       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
   3588                                                            FromObjCPtr1);
   3589       if (AssignLeft != AssignRight) {
   3590         return AssignLeft? ImplicitConversionSequence::Better
   3591                          : ImplicitConversionSequence::Worse;
   3592       }
   3593     }
   3594   }
   3595 
   3596   // Compare based on qualification conversions (C++ 13.3.3.2p3,
   3597   // bullet 3).
   3598   if (ImplicitConversionSequence::CompareKind QualCK
   3599         = CompareQualificationConversions(S, SCS1, SCS2))
   3600     return QualCK;
   3601 
   3602   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
   3603     // Check for a better reference binding based on the kind of bindings.
   3604     if (isBetterReferenceBindingKind(SCS1, SCS2))
   3605       return ImplicitConversionSequence::Better;
   3606     else if (isBetterReferenceBindingKind(SCS2, SCS1))
   3607       return ImplicitConversionSequence::Worse;
   3608 
   3609     // C++ [over.ics.rank]p3b4:
   3610     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
   3611     //      which the references refer are the same type except for
   3612     //      top-level cv-qualifiers, and the type to which the reference
   3613     //      initialized by S2 refers is more cv-qualified than the type
   3614     //      to which the reference initialized by S1 refers.
   3615     QualType T1 = SCS1.getToType(2);
   3616     QualType T2 = SCS2.getToType(2);
   3617     T1 = S.Context.getCanonicalType(T1);
   3618     T2 = S.Context.getCanonicalType(T2);
   3619     Qualifiers T1Quals, T2Quals;
   3620     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
   3621     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
   3622     if (UnqualT1 == UnqualT2) {
   3623       // Objective-C++ ARC: If the references refer to objects with different
   3624       // lifetimes, prefer bindings that don't change lifetime.
   3625       if (SCS1.ObjCLifetimeConversionBinding !=
   3626                                           SCS2.ObjCLifetimeConversionBinding) {
   3627         return SCS1.ObjCLifetimeConversionBinding
   3628                                            ? ImplicitConversionSequence::Worse
   3629                                            : ImplicitConversionSequence::Better;
   3630       }
   3631 
   3632       // If the type is an array type, promote the element qualifiers to the
   3633       // type for comparison.
   3634       if (isa<ArrayType>(T1) && T1Quals)
   3635         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
   3636       if (isa<ArrayType>(T2) && T2Quals)
   3637         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
   3638       if (T2.isMoreQualifiedThan(T1))
   3639         return ImplicitConversionSequence::Better;
   3640       else if (T1.isMoreQualifiedThan(T2))
   3641         return ImplicitConversionSequence::Worse;
   3642     }
   3643   }
   3644 
   3645   // In Microsoft mode, prefer an integral conversion to a
   3646   // floating-to-integral conversion if the integral conversion
   3647   // is between types of the same size.
   3648   // For example:
   3649   // void f(float);
   3650   // void f(int);
   3651   // int main {
   3652   //    long a;
   3653   //    f(a);
   3654   // }
   3655   // Here, MSVC will call f(int) instead of generating a compile error
   3656   // as clang will do in standard mode.
   3657   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
   3658       SCS2.Second == ICK_Floating_Integral &&
   3659       S.Context.getTypeSize(SCS1.getFromType()) ==
   3660           S.Context.getTypeSize(SCS1.getToType(2)))
   3661     return ImplicitConversionSequence::Better;
   3662 
   3663   return ImplicitConversionSequence::Indistinguishable;
   3664 }
   3665 
   3666 /// CompareQualificationConversions - Compares two standard conversion
   3667 /// sequences to determine whether they can be ranked based on their
   3668 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
   3669 ImplicitConversionSequence::CompareKind
   3670 CompareQualificationConversions(Sema &S,
   3671                                 const StandardConversionSequence& SCS1,
   3672                                 const StandardConversionSequence& SCS2) {
   3673   // C++ 13.3.3.2p3:
   3674   //  -- S1 and S2 differ only in their qualification conversion and
   3675   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
   3676   //     cv-qualification signature of type T1 is a proper subset of
   3677   //     the cv-qualification signature of type T2, and S1 is not the
   3678   //     deprecated string literal array-to-pointer conversion (4.2).
   3679   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
   3680       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
   3681     return ImplicitConversionSequence::Indistinguishable;
   3682 
   3683   // FIXME: the example in the standard doesn't use a qualification
   3684   // conversion (!)
   3685   QualType T1 = SCS1.getToType(2);
   3686   QualType T2 = SCS2.getToType(2);
   3687   T1 = S.Context.getCanonicalType(T1);
   3688   T2 = S.Context.getCanonicalType(T2);
   3689   Qualifiers T1Quals, T2Quals;
   3690   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
   3691   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
   3692 
   3693   // If the types are the same, we won't learn anything by unwrapped
   3694   // them.
   3695   if (UnqualT1 == UnqualT2)
   3696     return ImplicitConversionSequence::Indistinguishable;
   3697 
   3698   // If the type is an array type, promote the element qualifiers to the type
   3699   // for comparison.
   3700   if (isa<ArrayType>(T1) && T1Quals)
   3701     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
   3702   if (isa<ArrayType>(T2) && T2Quals)
   3703     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
   3704 
   3705   ImplicitConversionSequence::CompareKind Result
   3706     = ImplicitConversionSequence::Indistinguishable;
   3707 
   3708   // Objective-C++ ARC:
   3709   //   Prefer qualification conversions not involving a change in lifetime
   3710   //   to qualification conversions that do not change lifetime.
   3711   if (SCS1.QualificationIncludesObjCLifetime !=
   3712                                       SCS2.QualificationIncludesObjCLifetime) {
   3713     Result = SCS1.QualificationIncludesObjCLifetime
   3714                ? ImplicitConversionSequence::Worse
   3715                : ImplicitConversionSequence::Better;
   3716   }
   3717 
   3718   while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
   3719     // Within each iteration of the loop, we check the qualifiers to
   3720     // determine if this still looks like a qualification
   3721     // conversion. Then, if all is well, we unwrap one more level of
   3722     // pointers or pointers-to-members and do it all again
   3723     // until there are no more pointers or pointers-to-members left
   3724     // to unwrap. This essentially mimics what
   3725     // IsQualificationConversion does, but here we're checking for a
   3726     // strict subset of qualifiers.
   3727     if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
   3728       // The qualifiers are the same, so this doesn't tell us anything
   3729       // about how the sequences rank.
   3730       ;
   3731     else if (T2.isMoreQualifiedThan(T1)) {
   3732       // T1 has fewer qualifiers, so it could be the better sequence.
   3733       if (Result == ImplicitConversionSequence::Worse)
   3734         // Neither has qualifiers that are a subset of the other's
   3735         // qualifiers.
   3736         return ImplicitConversionSequence::Indistinguishable;
   3737 
   3738       Result = ImplicitConversionSequence::Better;
   3739     } else if (T1.isMoreQualifiedThan(T2)) {
   3740       // T2 has fewer qualifiers, so it could be the better sequence.
   3741       if (Result == ImplicitConversionSequence::Better)
   3742         // Neither has qualifiers that are a subset of the other's
   3743         // qualifiers.
   3744         return ImplicitConversionSequence::Indistinguishable;
   3745 
   3746       Result = ImplicitConversionSequence::Worse;
   3747     } else {
   3748       // Qualifiers are disjoint.
   3749       return ImplicitConversionSequence::Indistinguishable;
   3750     }
   3751 
   3752     // If the types after this point are equivalent, we're done.
   3753     if (S.Context.hasSameUnqualifiedType(T1, T2))
   3754       break;
   3755   }
   3756 
   3757   // Check that the winning standard conversion sequence isn't using
   3758   // the deprecated string literal array to pointer conversion.
   3759   switch (Result) {
   3760   case ImplicitConversionSequence::Better:
   3761     if (SCS1.DeprecatedStringLiteralToCharPtr)
   3762       Result = ImplicitConversionSequence::Indistinguishable;
   3763     break;
   3764 
   3765   case ImplicitConversionSequence::Indistinguishable:
   3766     break;
   3767 
   3768   case ImplicitConversionSequence::Worse:
   3769     if (SCS2.DeprecatedStringLiteralToCharPtr)
   3770       Result = ImplicitConversionSequence::Indistinguishable;
   3771     break;
   3772   }
   3773 
   3774   return Result;
   3775 }
   3776 
   3777 /// CompareDerivedToBaseConversions - Compares two standard conversion
   3778 /// sequences to determine whether they can be ranked based on their
   3779 /// various kinds of derived-to-base conversions (C++
   3780 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
   3781 /// conversions between Objective-C interface types.
   3782 ImplicitConversionSequence::CompareKind
   3783 CompareDerivedToBaseConversions(Sema &S,
   3784                                 const StandardConversionSequence& SCS1,
   3785                                 const StandardConversionSequence& SCS2) {
   3786   QualType FromType1 = SCS1.getFromType();
   3787   QualType ToType1 = SCS1.getToType(1);
   3788   QualType FromType2 = SCS2.getFromType();
   3789   QualType ToType2 = SCS2.getToType(1);
   3790 
   3791   // Adjust the types we're converting from via the array-to-pointer
   3792   // conversion, if we need to.
   3793   if (SCS1.First == ICK_Array_To_Pointer)
   3794     FromType1 = S.Context.getArrayDecayedType(FromType1);
   3795   if (SCS2.First == ICK_Array_To_Pointer)
   3796     FromType2 = S.Context.getArrayDecayedType(FromType2);
   3797 
   3798   // Canonicalize all of the types.
   3799   FromType1 = S.Context.getCanonicalType(FromType1);
   3800   ToType1 = S.Context.getCanonicalType(ToType1);
   3801   FromType2 = S.Context.getCanonicalType(FromType2);
   3802   ToType2 = S.Context.getCanonicalType(ToType2);
   3803 
   3804   // C++ [over.ics.rank]p4b3:
   3805   //
   3806   //   If class B is derived directly or indirectly from class A and
   3807   //   class C is derived directly or indirectly from B,
   3808   //
   3809   // Compare based on pointer conversions.
   3810   if (SCS1.Second == ICK_Pointer_Conversion &&
   3811       SCS2.Second == ICK_Pointer_Conversion &&
   3812       /*FIXME: Remove if Objective-C id conversions get their own rank*/
   3813       FromType1->isPointerType() && FromType2->isPointerType() &&
   3814       ToType1->isPointerType() && ToType2->isPointerType()) {
   3815     QualType FromPointee1
   3816       = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
   3817     QualType ToPointee1
   3818       = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
   3819     QualType FromPointee2
   3820       = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
   3821     QualType ToPointee2
   3822       = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
   3823 
   3824     //   -- conversion of C* to B* is better than conversion of C* to A*,
   3825     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
   3826       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
   3827         return ImplicitConversionSequence::Better;
   3828       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
   3829         return ImplicitConversionSequence::Worse;
   3830     }
   3831 
   3832     //   -- conversion of B* to A* is better than conversion of C* to A*,
   3833     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
   3834       if (S.IsDerivedFrom(FromPointee2, FromPointee1))
   3835         return ImplicitConversionSequence::Better;
   3836       else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
   3837         return ImplicitConversionSequence::Worse;
   3838     }
   3839   } else if (SCS1.Second == ICK_Pointer_Conversion &&
   3840              SCS2.Second == ICK_Pointer_Conversion) {
   3841     const ObjCObjectPointerType *FromPtr1
   3842       = FromType1->getAs<ObjCObjectPointerType>();
   3843     const ObjCObjectPointerType *FromPtr2
   3844       = FromType2->getAs<ObjCObjectPointerType>();
   3845     const ObjCObjectPointerType *ToPtr1
   3846       = ToType1->getAs<ObjCObjectPointerType>();
   3847     const ObjCObjectPointerType *ToPtr2
   3848       = ToType2->getAs<ObjCObjectPointerType>();
   3849 
   3850     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
   3851       // Apply the same conversion ranking rules for Objective-C pointer types
   3852       // that we do for C++ pointers to class types. However, we employ the
   3853       // Objective-C pseudo-subtyping relationship used for assignment of
   3854       // Objective-C pointer types.
   3855       bool FromAssignLeft
   3856         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
   3857       bool FromAssignRight
   3858         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
   3859       bool ToAssignLeft
   3860         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
   3861       bool ToAssignRight
   3862         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
   3863 
   3864       // A conversion to an a non-id object pointer type or qualified 'id'
   3865       // type is better than a conversion to 'id'.
   3866       if (ToPtr1->isObjCIdType() &&
   3867           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
   3868         return ImplicitConversionSequence::Worse;
   3869       if (ToPtr2->isObjCIdType() &&
   3870           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
   3871         return ImplicitConversionSequence::Better;
   3872 
   3873       // A conversion to a non-id object pointer type is better than a
   3874       // conversion to a qualified 'id' type
   3875       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
   3876         return ImplicitConversionSequence::Worse;
   3877       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
   3878         return ImplicitConversionSequence::Better;
   3879 
   3880       // A conversion to an a non-Class object pointer type or qualified 'Class'
   3881       // type is better than a conversion to 'Class'.
   3882       if (ToPtr1->isObjCClassType() &&
   3883           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
   3884         return ImplicitConversionSequence::Worse;
   3885       if (ToPtr2->isObjCClassType() &&
   3886           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
   3887         return ImplicitConversionSequence::Better;
   3888 
   3889       // A conversion to a non-Class object pointer type is better than a
   3890       // conversion to a qualified 'Class' type.
   3891       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
   3892         return ImplicitConversionSequence::Worse;
   3893       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
   3894         return ImplicitConversionSequence::Better;
   3895 
   3896       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
   3897       if (S.Context.hasSameType(FromType1, FromType2) &&
   3898           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
   3899           (ToAssignLeft != ToAssignRight))
   3900         return ToAssignLeft? ImplicitConversionSequence::Worse
   3901                            : ImplicitConversionSequence::Better;
   3902 
   3903       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
   3904       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
   3905           (FromAssignLeft != FromAssignRight))
   3906         return FromAssignLeft? ImplicitConversionSequence::Better
   3907         : ImplicitConversionSequence::Worse;
   3908     }
   3909   }
   3910 
   3911   // Ranking of member-pointer types.
   3912   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
   3913       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
   3914       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
   3915     const MemberPointerType * FromMemPointer1 =
   3916                                         FromType1->getAs<MemberPointerType>();
   3917     const MemberPointerType * ToMemPointer1 =
   3918                                           ToType1->getAs<MemberPointerType>();
   3919     const MemberPointerType * FromMemPointer2 =
   3920                                           FromType2->getAs<MemberPointerType>();
   3921     const MemberPointerType * ToMemPointer2 =
   3922                                           ToType2->getAs<MemberPointerType>();
   3923     const Type *FromPointeeType1 = FromMemPointer1->getClass();
   3924     const Type *ToPointeeType1 = ToMemPointer1->getClass();
   3925     const Type *FromPointeeType2 = FromMemPointer2->getClass();
   3926     const Type *ToPointeeType2 = ToMemPointer2->getClass();
   3927     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
   3928     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
   3929     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
   3930     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
   3931     // conversion of A::* to B::* is better than conversion of A::* to C::*,
   3932     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
   3933       if (S.IsDerivedFrom(ToPointee1, ToPointee2))
   3934         return ImplicitConversionSequence::Worse;
   3935       else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
   3936         return ImplicitConversionSequence::Better;
   3937     }
   3938     // conversion of B::* to C::* is better than conversion of A::* to C::*
   3939     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
   3940       if (S.IsDerivedFrom(FromPointee1, FromPointee2))
   3941         return ImplicitConversionSequence::Better;
   3942       else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
   3943         return ImplicitConversionSequence::Worse;
   3944     }
   3945   }
   3946 
   3947   if (SCS1.Second == ICK_Derived_To_Base) {
   3948     //   -- conversion of C to B is better than conversion of C to A,
   3949     //   -- binding of an expression of type C to a reference of type
   3950     //      B& is better than binding an expression of type C to a
   3951     //      reference of type A&,
   3952     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
   3953         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
   3954       if (S.IsDerivedFrom(ToType1, ToType2))
   3955         return ImplicitConversionSequence::Better;
   3956       else if (S.IsDerivedFrom(ToType2, ToType1))
   3957         return ImplicitConversionSequence::Worse;
   3958     }
   3959 
   3960     //   -- conversion of B to A is better than conversion of C to A.
   3961     //   -- binding of an expression of type B to a reference of type
   3962     //      A& is better than binding an expression of type C to a
   3963     //      reference of type A&,
   3964     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
   3965         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
   3966       if (S.IsDerivedFrom(FromType2, FromType1))
   3967         return ImplicitConversionSequence::Better;
   3968       else if (S.IsDerivedFrom(FromType1, FromType2))
   3969         return ImplicitConversionSequence::Worse;
   3970     }
   3971   }
   3972 
   3973   return ImplicitConversionSequence::Indistinguishable;
   3974 }
   3975 
   3976 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
   3977 /// C++ class.
   3978 static bool isTypeValid(QualType T) {
   3979   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
   3980     return !Record->isInvalidDecl();
   3981 
   3982   return true;
   3983 }
   3984 
   3985 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
   3986 /// determine whether they are reference-related,
   3987 /// reference-compatible, reference-compatible with added
   3988 /// qualification, or incompatible, for use in C++ initialization by
   3989 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
   3990 /// type, and the first type (T1) is the pointee type of the reference
   3991 /// type being initialized.
   3992 Sema::ReferenceCompareResult
   3993 Sema::CompareReferenceRelationship(SourceLocation Loc,
   3994                                    QualType OrigT1, QualType OrigT2,
   3995                                    bool &DerivedToBase,
   3996                                    bool &ObjCConversion,
   3997                                    bool &ObjCLifetimeConversion) {
   3998   assert(!OrigT1->isReferenceType() &&
   3999     "T1 must be the pointee type of the reference type");
   4000   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
   4001 
   4002   QualType T1 = Context.getCanonicalType(OrigT1);
   4003   QualType T2 = Context.getCanonicalType(OrigT2);
   4004   Qualifiers T1Quals, T2Quals;
   4005   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
   4006   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
   4007 
   4008   // C++ [dcl.init.ref]p4:
   4009   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
   4010   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
   4011   //   T1 is a base class of T2.
   4012   DerivedToBase = false;
   4013   ObjCConversion = false;
   4014   ObjCLifetimeConversion = false;
   4015   if (UnqualT1 == UnqualT2) {
   4016     // Nothing to do.
   4017   } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
   4018              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
   4019              IsDerivedFrom(UnqualT2, UnqualT1))
   4020     DerivedToBase = true;
   4021   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
   4022            UnqualT2->isObjCObjectOrInterfaceType() &&
   4023            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
   4024     ObjCConversion = true;
   4025   else
   4026     return Ref_Incompatible;
   4027 
   4028   // At this point, we know that T1 and T2 are reference-related (at
   4029   // least).
   4030 
   4031   // If the type is an array type, promote the element qualifiers to the type
   4032   // for comparison.
   4033   if (isa<ArrayType>(T1) && T1Quals)
   4034     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
   4035   if (isa<ArrayType>(T2) && T2Quals)
   4036     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
   4037 
   4038   // C++ [dcl.init.ref]p4:
   4039   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
   4040   //   reference-related to T2 and cv1 is the same cv-qualification
   4041   //   as, or greater cv-qualification than, cv2. For purposes of
   4042   //   overload resolution, cases for which cv1 is greater
   4043   //   cv-qualification than cv2 are identified as
   4044   //   reference-compatible with added qualification (see 13.3.3.2).
   4045   //
   4046   // Note that we also require equivalence of Objective-C GC and address-space
   4047   // qualifiers when performing these computations, so that e.g., an int in
   4048   // address space 1 is not reference-compatible with an int in address
   4049   // space 2.
   4050   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
   4051       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
   4052     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
   4053       ObjCLifetimeConversion = true;
   4054 
   4055     T1Quals.removeObjCLifetime();
   4056     T2Quals.removeObjCLifetime();
   4057   }
   4058 
   4059   if (T1Quals == T2Quals)
   4060     return Ref_Compatible;
   4061   else if (T1Quals.compatiblyIncludes(T2Quals))
   4062     return Ref_Compatible_With_Added_Qualification;
   4063   else
   4064     return Ref_Related;
   4065 }
   4066 
   4067 /// \brief Look for a user-defined conversion to an value reference-compatible
   4068 ///        with DeclType. Return true if something definite is found.
   4069 static bool
   4070 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
   4071                          QualType DeclType, SourceLocation DeclLoc,
   4072                          Expr *Init, QualType T2, bool AllowRvalues,
   4073                          bool AllowExplicit) {
   4074   assert(T2->isRecordType() && "Can only find conversions of record types.");
   4075   CXXRecordDecl *T2RecordDecl
   4076     = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
   4077 
   4078   OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
   4079   std::pair<CXXRecordDecl::conversion_iterator,
   4080             CXXRecordDecl::conversion_iterator>
   4081     Conversions = T2RecordDecl->getVisibleConversionFunctions();
   4082   for (CXXRecordDecl::conversion_iterator
   4083          I = Conversions.first, E = Conversions.second; I != E; ++I) {
   4084     NamedDecl *D = *I;
   4085     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
   4086     if (isa<UsingShadowDecl>(D))
   4087       D = cast<UsingShadowDecl>(D)->getTargetDecl();
   4088 
   4089     FunctionTemplateDecl *ConvTemplate
   4090       = dyn_cast<FunctionTemplateDecl>(D);
   4091     CXXConversionDecl *Conv;
   4092     if (ConvTemplate)
   4093       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
   4094     else
   4095       Conv = cast<CXXConversionDecl>(D);
   4096 
   4097     // If this is an explicit conversion, and we're not allowed to consider
   4098     // explicit conversions, skip it.
   4099     if (!AllowExplicit && Conv->isExplicit())
   4100       continue;
   4101 
   4102     if (AllowRvalues) {
   4103       bool DerivedToBase = false;
   4104       bool ObjCConversion = false;
   4105       bool ObjCLifetimeConversion = false;
   4106 
   4107       // If we are initializing an rvalue reference, don't permit conversion
   4108       // functions that return lvalues.
   4109       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
   4110         const ReferenceType *RefType
   4111           = Conv->getConversionType()->getAs<LValueReferenceType>();
   4112         if (RefType && !RefType->getPointeeType()->isFunctionType())
   4113           continue;
   4114       }
   4115 
   4116       if (!ConvTemplate &&
   4117           S.CompareReferenceRelationship(
   4118             DeclLoc,
   4119             Conv->getConversionType().getNonReferenceType()
   4120               .getUnqualifiedType(),
   4121             DeclType.getNonReferenceType().getUnqualifiedType(),
   4122             DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
   4123           Sema::Ref_Incompatible)
   4124         continue;
   4125     } else {
   4126       // If the conversion function doesn't return a reference type,
   4127       // it can't be considered for this conversion. An rvalue reference
   4128       // is only acceptable if its referencee is a function type.
   4129 
   4130       const ReferenceType *RefType =
   4131         Conv->getConversionType()->getAs<ReferenceType>();
   4132       if (!RefType ||
   4133           (!RefType->isLValueReferenceType() &&
   4134            !RefType->getPointeeType()->isFunctionType()))
   4135         continue;
   4136     }
   4137 
   4138     if (ConvTemplate)
   4139       S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
   4140                                        Init, DeclType, CandidateSet,
   4141                                        /*AllowObjCConversionOnExplicit=*/false);
   4142     else
   4143       S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
   4144                                DeclType, CandidateSet,
   4145                                /*AllowObjCConversionOnExplicit=*/false);
   4146   }
   4147 
   4148   bool HadMultipleCandidates = (CandidateSet.size() > 1);
   4149 
   4150   OverloadCandidateSet::iterator Best;
   4151   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
   4152   case OR_Success:
   4153     // C++ [over.ics.ref]p1:
   4154     //
   4155     //   [...] If the parameter binds directly to the result of
   4156     //   applying a conversion function to the argument
   4157     //   expression, the implicit conversion sequence is a
   4158     //   user-defined conversion sequence (13.3.3.1.2), with the
   4159     //   second standard conversion sequence either an identity
   4160     //   conversion or, if the conversion function returns an
   4161     //   entity of a type that is a derived class of the parameter
   4162     //   type, a derived-to-base Conversion.
   4163     if (!Best->FinalConversion.DirectBinding)
   4164       return false;
   4165 
   4166     ICS.setUserDefined();
   4167     ICS.UserDefined.Before = Best->Conversions[0].Standard;
   4168     ICS.UserDefined.After = Best->FinalConversion;
   4169     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
   4170     ICS.UserDefined.ConversionFunction = Best->Function;
   4171     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
   4172     ICS.UserDefined.EllipsisConversion = false;
   4173     assert(ICS.UserDefined.After.ReferenceBinding &&
   4174            ICS.UserDefined.After.DirectBinding &&
   4175            "Expected a direct reference binding!");
   4176     return true;
   4177 
   4178   case OR_Ambiguous:
   4179     ICS.setAmbiguous();
   4180     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
   4181          Cand != CandidateSet.end(); ++Cand)
   4182       if (Cand->Viable)
   4183         ICS.Ambiguous.addConversion(Cand->Function);
   4184     return true;
   4185 
   4186   case OR_No_Viable_Function:
   4187   case OR_Deleted:
   4188     // There was no suitable conversion, or we found a deleted
   4189     // conversion; continue with other checks.
   4190     return false;
   4191   }
   4192 
   4193   llvm_unreachable("Invalid OverloadResult!");
   4194 }
   4195 
   4196 /// \brief Compute an implicit conversion sequence for reference
   4197 /// initialization.
   4198 static ImplicitConversionSequence
   4199 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
   4200                  SourceLocation DeclLoc,
   4201                  bool SuppressUserConversions,
   4202                  bool AllowExplicit) {
   4203   assert(DeclType->isReferenceType() && "Reference init needs a reference");
   4204 
   4205   // Most paths end in a failed conversion.
   4206   ImplicitConversionSequence ICS;
   4207   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
   4208 
   4209   QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
   4210   QualType T2 = Init->getType();
   4211 
   4212   // If the initializer is the address of an overloaded function, try
   4213   // to resolve the overloaded function. If all goes well, T2 is the
   4214   // type of the resulting function.
   4215   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
   4216     DeclAccessPair Found;
   4217     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
   4218                                                                 false, Found))
   4219       T2 = Fn->getType();
   4220   }
   4221 
   4222   // Compute some basic properties of the types and the initializer.
   4223   bool isRValRef = DeclType->isRValueReferenceType();
   4224   bool DerivedToBase = false;
   4225   bool ObjCConversion = false;
   4226   bool ObjCLifetimeConversion = false;
   4227   Expr::Classification InitCategory = Init->Classify(S.Context);
   4228   Sema::ReferenceCompareResult RefRelationship
   4229     = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
   4230                                      ObjCConversion, ObjCLifetimeConversion);
   4231 
   4232 
   4233   // C++0x [dcl.init.ref]p5:
   4234   //   A reference to type "cv1 T1" is initialized by an expression
   4235   //   of type "cv2 T2" as follows:
   4236 
   4237   //     -- If reference is an lvalue reference and the initializer expression
   4238   if (!isRValRef) {
   4239     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
   4240     //        reference-compatible with "cv2 T2," or
   4241     //
   4242     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
   4243     if (InitCategory.isLValue() &&
   4244         RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
   4245       // C++ [over.ics.ref]p1:
   4246       //   When a parameter of reference type binds directly (8.5.3)
   4247       //   to an argument expression, the implicit conversion sequence
   4248       //   is the identity conversion, unless the argument expression
   4249       //   has a type that is a derived class of the parameter type,
   4250       //   in which case the implicit conversion sequence is a
   4251       //   derived-to-base Conversion (13.3.3.1).
   4252       ICS.setStandard();
   4253       ICS.Standard.First = ICK_Identity;
   4254       ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
   4255                          : ObjCConversion? ICK_Compatible_Conversion
   4256                          : ICK_Identity;
   4257       ICS.Standard.Third = ICK_Identity;
   4258       ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
   4259       ICS.Standard.setToType(0, T2);
   4260       ICS.Standard.setToType(1, T1);
   4261       ICS.Standard.setToType(2, T1);
   4262       ICS.Standard.ReferenceBinding = true;
   4263       ICS.Standard.DirectBinding = true;
   4264       ICS.Standard.IsLvalueReference = !isRValRef;
   4265       ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
   4266       ICS.Standard.BindsToRvalue = false;
   4267       ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
   4268       ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
   4269       ICS.Standard.CopyConstructor = nullptr;
   4270       ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
   4271 
   4272       // Nothing more to do: the inaccessibility/ambiguity check for
   4273       // derived-to-base conversions is suppressed when we're
   4274       // computing the implicit conversion sequence (C++
   4275       // [over.best.ics]p2).
   4276       return ICS;
   4277     }
   4278 
   4279     //       -- has a class type (i.e., T2 is a class type), where T1 is
   4280     //          not reference-related to T2, and can be implicitly
   4281     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
   4282     //          is reference-compatible with "cv3 T3" 92) (this
   4283     //          conversion is selected by enumerating the applicable
   4284     //          conversion functions (13.3.1.6) and choosing the best
   4285     //          one through overload resolution (13.3)),
   4286     if (!SuppressUserConversions && T2->isRecordType() &&
   4287         !S.RequireCompleteType(DeclLoc, T2, 0) &&
   4288         RefRelationship == Sema::Ref_Incompatible) {
   4289       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
   4290                                    Init, T2, /*AllowRvalues=*/false,
   4291                                    AllowExplicit))
   4292         return ICS;
   4293     }
   4294   }
   4295 
   4296   //     -- Otherwise, the reference shall be an lvalue reference to a
   4297   //        non-volatile const type (i.e., cv1 shall be const), or the reference
   4298   //        shall be an rvalue reference.
   4299   //
   4300   // We actually handle one oddity of C++ [over.ics.ref] at this
   4301   // point, which is that, due to p2 (which short-circuits reference
   4302   // binding by only attempting a simple conversion for non-direct
   4303   // bindings) and p3's strange wording, we allow a const volatile
   4304   // reference to bind to an rvalue. Hence the check for the presence
   4305   // of "const" rather than checking for "const" being the only
   4306   // qualifier.
   4307   // This is also the point where rvalue references and lvalue inits no longer
   4308   // go together.
   4309   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
   4310     return ICS;
   4311 
   4312   //       -- If the initializer expression
   4313   //
   4314   //            -- is an xvalue, class prvalue, array prvalue or function
   4315   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
   4316   if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
   4317       (InitCategory.isXValue() ||
   4318       (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
   4319       (InitCategory.isLValue() && T2->isFunctionType()))) {
   4320     ICS.setStandard();
   4321     ICS.Standard.First = ICK_Identity;
   4322     ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
   4323                       : ObjCConversion? ICK_Compatible_Conversion
   4324                       : ICK_Identity;
   4325     ICS.Standard.Third = ICK_Identity;
   4326     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
   4327     ICS.Standard.setToType(0, T2);
   4328     ICS.Standard.setToType(1, T1);
   4329     ICS.Standard.setToType(2, T1);
   4330     ICS.Standard.ReferenceBinding = true;
   4331     // In C++0x, this is always a direct binding. In C++98/03, it's a direct
   4332     // binding unless we're binding to a class prvalue.
   4333     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
   4334     // allow the use of rvalue references in C++98/03 for the benefit of
   4335     // standard library implementors; therefore, we need the xvalue check here.
   4336     ICS.Standard.DirectBinding =
   4337       S.getLangOpts().CPlusPlus11 ||
   4338       (InitCategory.isPRValue() && !T2->isRecordType());
   4339     ICS.Standard.IsLvalueReference = !isRValRef;
   4340     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
   4341     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
   4342     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
   4343     ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
   4344     ICS.Standard.CopyConstructor = nullptr;
   4345     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
   4346     return ICS;
   4347   }
   4348 
   4349   //            -- has a class type (i.e., T2 is a class type), where T1 is not
   4350   //               reference-related to T2, and can be implicitly converted to
   4351   //               an xvalue, class prvalue, or function lvalue of type
   4352   //               "cv3 T3", where "cv1 T1" is reference-compatible with
   4353   //               "cv3 T3",
   4354   //
   4355   //          then the reference is bound to the value of the initializer
   4356   //          expression in the first case and to the result of the conversion
   4357   //          in the second case (or, in either case, to an appropriate base
   4358   //          class subobject).
   4359   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
   4360       T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
   4361       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
   4362                                Init, T2, /*AllowRvalues=*/true,
   4363                                AllowExplicit)) {
   4364     // In the second case, if the reference is an rvalue reference
   4365     // and the second standard conversion sequence of the
   4366     // user-defined conversion sequence includes an lvalue-to-rvalue
   4367     // conversion, the program is ill-formed.
   4368     if (ICS.isUserDefined() && isRValRef &&
   4369         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
   4370       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
   4371 
   4372     return ICS;
   4373   }
   4374 
   4375   //       -- Otherwise, a temporary of type "cv1 T1" is created and
   4376   //          initialized from the initializer expression using the
   4377   //          rules for a non-reference copy initialization (8.5). The
   4378   //          reference is then bound to the temporary. If T1 is
   4379   //          reference-related to T2, cv1 must be the same
   4380   //          cv-qualification as, or greater cv-qualification than,
   4381   //          cv2; otherwise, the program is ill-formed.
   4382   if (RefRelationship == Sema::Ref_Related) {
   4383     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
   4384     // we would be reference-compatible or reference-compatible with
   4385     // added qualification. But that wasn't the case, so the reference
   4386     // initialization fails.
   4387     //
   4388     // Note that we only want to check address spaces and cvr-qualifiers here.
   4389     // ObjC GC and lifetime qualifiers aren't important.
   4390     Qualifiers T1Quals = T1.getQualifiers();
   4391     Qualifiers T2Quals = T2.getQualifiers();
   4392     T1Quals.removeObjCGCAttr();
   4393     T1Quals.removeObjCLifetime();
   4394     T2Quals.removeObjCGCAttr();
   4395     T2Quals.removeObjCLifetime();
   4396     if (!T1Quals.compatiblyIncludes(T2Quals))
   4397       return ICS;
   4398   }
   4399 
   4400   // If at least one of the types is a class type, the types are not
   4401   // related, and we aren't allowed any user conversions, the
   4402   // reference binding fails. This case is important for breaking
   4403   // recursion, since TryImplicitConversion below will attempt to
   4404   // create a temporary through the use of a copy constructor.
   4405   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
   4406       (T1->isRecordType() || T2->isRecordType()))
   4407     return ICS;
   4408 
   4409   // If T1 is reference-related to T2 and the reference is an rvalue
   4410   // reference, the initializer expression shall not be an lvalue.
   4411   if (RefRelationship >= Sema::Ref_Related &&
   4412       isRValRef && Init->Classify(S.Context).isLValue())
   4413     return ICS;
   4414 
   4415   // C++ [over.ics.ref]p2:
   4416   //   When a parameter of reference type is not bound directly to
   4417   //   an argument expression, the conversion sequence is the one
   4418   //   required to convert the argument expression to the
   4419   //   underlying type of the reference according to
   4420   //   13.3.3.1. Conceptually, this conversion sequence corresponds
   4421   //   to copy-initializing a temporary of the underlying type with
   4422   //   the argument expression. Any difference in top-level
   4423   //   cv-qualification is subsumed by the initialization itself
   4424   //   and does not constitute a conversion.
   4425   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
   4426                               /*AllowExplicit=*/false,
   4427                               /*InOverloadResolution=*/false,
   4428                               /*CStyle=*/false,
   4429                               /*AllowObjCWritebackConversion=*/false,
   4430                               /*AllowObjCConversionOnExplicit=*/false);
   4431 
   4432   // Of course, that's still a reference binding.
   4433   if (ICS.isStandard()) {
   4434     ICS.Standard.ReferenceBinding = true;
   4435     ICS.Standard.IsLvalueReference = !isRValRef;
   4436     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
   4437     ICS.Standard.BindsToRvalue = true;
   4438     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
   4439     ICS.Standard.ObjCLifetimeConversionBinding = false;
   4440   } else if (ICS.isUserDefined()) {
   4441     // Don't allow rvalue references to bind to lvalues.
   4442     if (DeclType->isRValueReferenceType()) {
   4443       if (const ReferenceType *RefType =
   4444               ICS.UserDefined.ConversionFunction->getReturnType()
   4445                   ->getAs<LValueReferenceType>()) {
   4446         if (!RefType->getPointeeType()->isFunctionType()) {
   4447           ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
   4448                      DeclType);
   4449           return ICS;
   4450         }
   4451       }
   4452     }
   4453     ICS.UserDefined.Before.setAsIdentityConversion();
   4454     ICS.UserDefined.After.ReferenceBinding = true;
   4455     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
   4456     ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
   4457     ICS.UserDefined.After.BindsToRvalue = true;
   4458     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
   4459     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
   4460   }
   4461 
   4462   return ICS;
   4463 }
   4464 
   4465 static ImplicitConversionSequence
   4466 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
   4467                       bool SuppressUserConversions,
   4468                       bool InOverloadResolution,
   4469                       bool AllowObjCWritebackConversion,
   4470                       bool AllowExplicit = false);
   4471 
   4472 /// TryListConversion - Try to copy-initialize a value of type ToType from the
   4473 /// initializer list From.
   4474 static ImplicitConversionSequence
   4475 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
   4476                   bool SuppressUserConversions,
   4477                   bool InOverloadResolution,
   4478                   bool AllowObjCWritebackConversion) {
   4479   // C++11 [over.ics.list]p1:
   4480   //   When an argument is an initializer list, it is not an expression and
   4481   //   special rules apply for converting it to a parameter type.
   4482 
   4483   ImplicitConversionSequence Result;
   4484   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
   4485 
   4486   // We need a complete type for what follows. Incomplete types can never be
   4487   // initialized from init lists.
   4488   if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
   4489     return Result;
   4490 
   4491   // C++11 [over.ics.list]p2:
   4492   //   If the parameter type is std::initializer_list<X> or "array of X" and
   4493   //   all the elements can be implicitly converted to X, the implicit
   4494   //   conversion sequence is the worst conversion necessary to convert an
   4495   //   element of the list to X.
   4496   bool toStdInitializerList = false;
   4497   QualType X;
   4498   if (ToType->isArrayType())
   4499     X = S.Context.getAsArrayType(ToType)->getElementType();
   4500   else
   4501     toStdInitializerList = S.isStdInitializerList(ToType, &X);
   4502   if (!X.isNull()) {
   4503     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
   4504       Expr *Init = From->getInit(i);
   4505       ImplicitConversionSequence ICS =
   4506           TryCopyInitialization(S, Init, X, SuppressUserConversions,
   4507                                 InOverloadResolution,
   4508                                 AllowObjCWritebackConversion);
   4509       // If a single element isn't convertible, fail.
   4510       if (ICS.isBad()) {
   4511         Result = ICS;
   4512         break;
   4513       }
   4514       // Otherwise, look for the worst conversion.
   4515       if (Result.isBad() ||
   4516           CompareImplicitConversionSequences(S, ICS, Result) ==
   4517               ImplicitConversionSequence::Worse)
   4518         Result = ICS;
   4519     }
   4520 
   4521     // For an empty list, we won't have computed any conversion sequence.
   4522     // Introduce the identity conversion sequence.
   4523     if (From->getNumInits() == 0) {
   4524       Result.setStandard();
   4525       Result.Standard.setAsIdentityConversion();
   4526       Result.Standard.setFromType(ToType);
   4527       Result.Standard.setAllToTypes(ToType);
   4528     }
   4529 
   4530     Result.setStdInitializerListElement(toStdInitializerList);
   4531     return Result;
   4532   }
   4533 
   4534   // C++11 [over.ics.list]p3:
   4535   //   Otherwise, if the parameter is a non-aggregate class X and overload
   4536   //   resolution chooses a single best constructor [...] the implicit
   4537   //   conversion sequence is a user-defined conversion sequence. If multiple
   4538   //   constructors are viable but none is better than the others, the
   4539   //   implicit conversion sequence is a user-defined conversion sequence.
   4540   if (ToType->isRecordType() && !ToType->isAggregateType()) {
   4541     // This function can deal with initializer lists.
   4542     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
   4543                                     /*AllowExplicit=*/false,
   4544                                     InOverloadResolution, /*CStyle=*/false,
   4545                                     AllowObjCWritebackConversion,
   4546                                     /*AllowObjCConversionOnExplicit=*/false);
   4547   }
   4548 
   4549   // C++11 [over.ics.list]p4:
   4550   //   Otherwise, if the parameter has an aggregate type which can be
   4551   //   initialized from the initializer list [...] the implicit conversion
   4552   //   sequence is a user-defined conversion sequence.
   4553   if (ToType->isAggregateType()) {
   4554     // Type is an aggregate, argument is an init list. At this point it comes
   4555     // down to checking whether the initialization works.
   4556     // FIXME: Find out whether this parameter is consumed or not.
   4557     InitializedEntity Entity =
   4558         InitializedEntity::InitializeParameter(S.Context, ToType,
   4559                                                /*Consumed=*/false);
   4560     if (S.CanPerformCopyInitialization(Entity, From)) {
   4561       Result.setUserDefined();
   4562       Result.UserDefined.Before.setAsIdentityConversion();
   4563       // Initializer lists don't have a type.
   4564       Result.UserDefined.Before.setFromType(QualType());
   4565       Result.UserDefined.Before.setAllToTypes(QualType());
   4566 
   4567       Result.UserDefined.After.setAsIdentityConversion();
   4568       Result.UserDefined.After.setFromType(ToType);
   4569       Result.UserDefined.After.setAllToTypes(ToType);
   4570       Result.UserDefined.ConversionFunction = nullptr;
   4571     }
   4572     return Result;
   4573   }
   4574 
   4575   // C++11 [over.ics.list]p5:
   4576   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
   4577   if (ToType->isReferenceType()) {
   4578     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
   4579     // mention initializer lists in any way. So we go by what list-
   4580     // initialization would do and try to extrapolate from that.
   4581 
   4582     QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
   4583 
   4584     // If the initializer list has a single element that is reference-related
   4585     // to the parameter type, we initialize the reference from that.
   4586     if (From->getNumInits() == 1) {
   4587       Expr *Init = From->getInit(0);
   4588 
   4589       QualType T2 = Init->getType();
   4590 
   4591       // If the initializer is the address of an overloaded function, try
   4592       // to resolve the overloaded function. If all goes well, T2 is the
   4593       // type of the resulting function.
   4594       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
   4595         DeclAccessPair Found;
   4596         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
   4597                                    Init, ToType, false, Found))
   4598           T2 = Fn->getType();
   4599       }
   4600 
   4601       // Compute some basic properties of the types and the initializer.
   4602       bool dummy1 = false;
   4603       bool dummy2 = false;
   4604       bool dummy3 = false;
   4605       Sema::ReferenceCompareResult RefRelationship
   4606         = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
   4607                                          dummy2, dummy3);
   4608 
   4609       if (RefRelationship >= Sema::Ref_Related) {
   4610         return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
   4611                                 SuppressUserConversions,
   4612                                 /*AllowExplicit=*/false);
   4613       }
   4614     }
   4615 
   4616     // Otherwise, we bind the reference to a temporary created from the
   4617     // initializer list.
   4618     Result = TryListConversion(S, From, T1, SuppressUserConversions,
   4619                                InOverloadResolution,
   4620                                AllowObjCWritebackConversion);
   4621     if (Result.isFailure())
   4622       return Result;
   4623     assert(!Result.isEllipsis() &&
   4624            "Sub-initialization cannot result in ellipsis conversion.");
   4625 
   4626     // Can we even bind to a temporary?
   4627     if (ToType->isRValueReferenceType() ||
   4628         (T1.isConstQualified() && !T1.isVolatileQualified())) {
   4629       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
   4630                                             Result.UserDefined.After;
   4631       SCS.ReferenceBinding = true;
   4632       SCS.IsLvalueReference = ToType->isLValueReferenceType();
   4633       SCS.BindsToRvalue = true;
   4634       SCS.BindsToFunctionLvalue = false;
   4635       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
   4636       SCS.ObjCLifetimeConversionBinding = false;
   4637     } else
   4638       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
   4639                     From, ToType);
   4640     return Result;
   4641   }
   4642 
   4643   // C++11 [over.ics.list]p6:
   4644   //   Otherwise, if the parameter type is not a class:
   4645   if (!ToType->isRecordType()) {
   4646     //    - if the initializer list has one element, the implicit conversion
   4647     //      sequence is the one required to convert the element to the
   4648     //      parameter type.
   4649     unsigned NumInits = From->getNumInits();
   4650     if (NumInits == 1)
   4651       Result = TryCopyInitialization(S, From->getInit(0), ToType,
   4652                                      SuppressUserConversions,
   4653                                      InOverloadResolution,
   4654                                      AllowObjCWritebackConversion);
   4655     //    - if the initializer list has no elements, the implicit conversion
   4656     //      sequence is the identity conversion.
   4657     else if (NumInits == 0) {
   4658       Result.setStandard();
   4659       Result.Standard.setAsIdentityConversion();
   4660       Result.Standard.setFromType(ToType);
   4661       Result.Standard.setAllToTypes(ToType);
   4662     }
   4663     return Result;
   4664   }
   4665 
   4666   // C++11 [over.ics.list]p7:
   4667   //   In all cases other than those enumerated above, no conversion is possible
   4668   return Result;
   4669 }
   4670 
   4671 /// TryCopyInitialization - Try to copy-initialize a value of type
   4672 /// ToType from the expression From. Return the implicit conversion
   4673 /// sequence required to pass this argument, which may be a bad
   4674 /// conversion sequence (meaning that the argument cannot be passed to
   4675 /// a parameter of this type). If @p SuppressUserConversions, then we
   4676 /// do not permit any user-defined conversion sequences.
   4677 static ImplicitConversionSequence
   4678 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
   4679                       bool SuppressUserConversions,
   4680                       bool InOverloadResolution,
   4681                       bool AllowObjCWritebackConversion,
   4682                       bool AllowExplicit) {
   4683   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
   4684     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
   4685                              InOverloadResolution,AllowObjCWritebackConversion);
   4686 
   4687   if (ToType->isReferenceType())
   4688     return TryReferenceInit(S, From, ToType,
   4689                             /*FIXME:*/From->getLocStart(),
   4690                             SuppressUserConversions,
   4691                             AllowExplicit);
   4692 
   4693   return TryImplicitConversion(S, From, ToType,
   4694                                SuppressUserConversions,
   4695                                /*AllowExplicit=*/false,
   4696                                InOverloadResolution,
   4697                                /*CStyle=*/false,
   4698                                AllowObjCWritebackConversion,
   4699                                /*AllowObjCConversionOnExplicit=*/false);
   4700 }
   4701 
   4702 static bool TryCopyInitialization(const CanQualType FromQTy,
   4703                                   const CanQualType ToQTy,
   4704                                   Sema &S,
   4705                                   SourceLocation Loc,
   4706                                   ExprValueKind FromVK) {
   4707   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
   4708   ImplicitConversionSequence ICS =
   4709     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
   4710 
   4711   return !ICS.isBad();
   4712 }
   4713 
   4714 /// TryObjectArgumentInitialization - Try to initialize the object
   4715 /// parameter of the given member function (@c Method) from the
   4716 /// expression @p From.
   4717 static ImplicitConversionSequence
   4718 TryObjectArgumentInitialization(Sema &S, QualType FromType,
   4719                                 Expr::Classification FromClassification,
   4720                                 CXXMethodDecl *Method,
   4721                                 CXXRecordDecl *ActingContext) {
   4722   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
   4723   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
   4724   //                 const volatile object.
   4725   unsigned Quals = isa<CXXDestructorDecl>(Method) ?
   4726     Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
   4727   QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
   4728 
   4729   // Set up the conversion sequence as a "bad" conversion, to allow us
   4730   // to exit early.
   4731   ImplicitConversionSequence ICS;
   4732 
   4733   // We need to have an object of class type.
   4734   if (const PointerType *PT = FromType->getAs<PointerType>()) {
   4735     FromType = PT->getPointeeType();
   4736 
   4737     // When we had a pointer, it's implicitly dereferenced, so we
   4738     // better have an lvalue.
   4739     assert(FromClassification.isLValue());
   4740   }
   4741 
   4742   assert(FromType->isRecordType());
   4743 
   4744   // C++0x [over.match.funcs]p4:
   4745   //   For non-static member functions, the type of the implicit object
   4746   //   parameter is
   4747   //
   4748   //     - "lvalue reference to cv X" for functions declared without a
   4749   //        ref-qualifier or with the & ref-qualifier
   4750   //     - "rvalue reference to cv X" for functions declared with the &&
   4751   //        ref-qualifier
   4752   //
   4753   // where X is the class of which the function is a member and cv is the
   4754   // cv-qualification on the member function declaration.
   4755   //
   4756   // However, when finding an implicit conversion sequence for the argument, we
   4757   // are not allowed to create temporaries or perform user-defined conversions
   4758   // (C++ [over.match.funcs]p5). We perform a simplified version of
   4759   // reference binding here, that allows class rvalues to bind to
   4760   // non-constant references.
   4761 
   4762   // First check the qualifiers.
   4763   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
   4764   if (ImplicitParamType.getCVRQualifiers()
   4765                                     != FromTypeCanon.getLocalCVRQualifiers() &&
   4766       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
   4767     ICS.setBad(BadConversionSequence::bad_qualifiers,
   4768                FromType, ImplicitParamType);
   4769     return ICS;
   4770   }
   4771 
   4772   // Check that we have either the same type or a derived type. It
   4773   // affects the conversion rank.
   4774   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
   4775   ImplicitConversionKind SecondKind;
   4776   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
   4777     SecondKind = ICK_Identity;
   4778   } else if (S.IsDerivedFrom(FromType, ClassType))
   4779     SecondKind = ICK_Derived_To_Base;
   4780   else {
   4781     ICS.setBad(BadConversionSequence::unrelated_class,
   4782                FromType, ImplicitParamType);
   4783     return ICS;
   4784   }
   4785 
   4786   // Check the ref-qualifier.
   4787   switch (Method->getRefQualifier()) {
   4788   case RQ_None:
   4789     // Do nothing; we don't care about lvalueness or rvalueness.
   4790     break;
   4791 
   4792   case RQ_LValue:
   4793     if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
   4794       // non-const lvalue reference cannot bind to an rvalue
   4795       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
   4796                  ImplicitParamType);
   4797       return ICS;
   4798     }
   4799     break;
   4800 
   4801   case RQ_RValue:
   4802     if (!FromClassification.isRValue()) {
   4803       // rvalue reference cannot bind to an lvalue
   4804       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
   4805                  ImplicitParamType);
   4806       return ICS;
   4807     }
   4808     break;
   4809   }
   4810 
   4811   // Success. Mark this as a reference binding.
   4812   ICS.setStandard();
   4813   ICS.Standard.setAsIdentityConversion();
   4814   ICS.Standard.Second = SecondKind;
   4815   ICS.Standard.setFromType(FromType);
   4816   ICS.Standard.setAllToTypes(ImplicitParamType);
   4817   ICS.Standard.ReferenceBinding = true;
   4818   ICS.Standard.DirectBinding = true;
   4819   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
   4820   ICS.Standard.BindsToFunctionLvalue = false;
   4821   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
   4822   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
   4823     = (Method->getRefQualifier() == RQ_None);
   4824   return ICS;
   4825 }
   4826 
   4827 /// PerformObjectArgumentInitialization - Perform initialization of
   4828 /// the implicit object parameter for the given Method with the given
   4829 /// expression.
   4830 ExprResult
   4831 Sema::PerformObjectArgumentInitialization(Expr *From,
   4832                                           NestedNameSpecifier *Qualifier,
   4833                                           NamedDecl *FoundDecl,
   4834                                           CXXMethodDecl *Method) {
   4835   QualType FromRecordType, DestType;
   4836   QualType ImplicitParamRecordType  =
   4837     Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
   4838 
   4839   Expr::Classification FromClassification;
   4840   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
   4841     FromRecordType = PT->getPointeeType();
   4842     DestType = Method->getThisType(Context);
   4843     FromClassification = Expr::Classification::makeSimpleLValue();
   4844   } else {
   4845     FromRecordType = From->getType();
   4846     DestType = ImplicitParamRecordType;
   4847     FromClassification = From->Classify(Context);
   4848   }
   4849 
   4850   // Note that we always use the true parent context when performing
   4851   // the actual argument initialization.
   4852   ImplicitConversionSequence ICS
   4853     = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
   4854                                       Method, Method->getParent());
   4855   if (ICS.isBad()) {
   4856     if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
   4857       Qualifiers FromQs = FromRecordType.getQualifiers();
   4858       Qualifiers ToQs = DestType.getQualifiers();
   4859       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
   4860       if (CVR) {
   4861         Diag(From->getLocStart(),
   4862              diag::err_member_function_call_bad_cvr)
   4863           << Method->getDeclName() << FromRecordType << (CVR - 1)
   4864           << From->getSourceRange();
   4865         Diag(Method->getLocation(), diag::note_previous_decl)
   4866           << Method->getDeclName();
   4867         return ExprError();
   4868       }
   4869     }
   4870 
   4871     return Diag(From->getLocStart(),
   4872                 diag::err_implicit_object_parameter_init)
   4873        << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
   4874   }
   4875 
   4876   if (ICS.Standard.Second == ICK_Derived_To_Base) {
   4877     ExprResult FromRes =
   4878       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
   4879     if (FromRes.isInvalid())
   4880       return ExprError();
   4881     From = FromRes.get();
   4882   }
   4883 
   4884   if (!Context.hasSameType(From->getType(), DestType))
   4885     From = ImpCastExprToType(From, DestType, CK_NoOp,
   4886                              From->getValueKind()).get();
   4887   return From;
   4888 }
   4889 
   4890 /// TryContextuallyConvertToBool - Attempt to contextually convert the
   4891 /// expression From to bool (C++0x [conv]p3).
   4892 static ImplicitConversionSequence
   4893 TryContextuallyConvertToBool(Sema &S, Expr *From) {
   4894   return TryImplicitConversion(S, From, S.Context.BoolTy,
   4895                                /*SuppressUserConversions=*/false,
   4896                                /*AllowExplicit=*/true,
   4897                                /*InOverloadResolution=*/false,
   4898                                /*CStyle=*/false,
   4899                                /*AllowObjCWritebackConversion=*/false,
   4900                                /*AllowObjCConversionOnExplicit=*/false);
   4901 }
   4902 
   4903 /// PerformContextuallyConvertToBool - Perform a contextual conversion
   4904 /// of the expression From to bool (C++0x [conv]p3).
   4905 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
   4906   if (checkPlaceholderForOverload(*this, From))
   4907     return ExprError();
   4908 
   4909   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
   4910   if (!ICS.isBad())
   4911     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
   4912 
   4913   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
   4914     return Diag(From->getLocStart(),
   4915                 diag::err_typecheck_bool_condition)
   4916                   << From->getType() << From->getSourceRange();
   4917   return ExprError();
   4918 }
   4919 
   4920 /// Check that the specified conversion is permitted in a converted constant
   4921 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
   4922 /// is acceptable.
   4923 static bool CheckConvertedConstantConversions(Sema &S,
   4924                                               StandardConversionSequence &SCS) {
   4925   // Since we know that the target type is an integral or unscoped enumeration
   4926   // type, most conversion kinds are impossible. All possible First and Third
   4927   // conversions are fine.
   4928   switch (SCS.Second) {
   4929   case ICK_Identity:
   4930   case ICK_Integral_Promotion:
   4931   case ICK_Integral_Conversion:
   4932   case ICK_Zero_Event_Conversion:
   4933     return true;
   4934 
   4935   case ICK_Boolean_Conversion:
   4936     // Conversion from an integral or unscoped enumeration type to bool is
   4937     // classified as ICK_Boolean_Conversion, but it's also an integral
   4938     // conversion, so it's permitted in a converted constant expression.
   4939     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
   4940            SCS.getToType(2)->isBooleanType();
   4941 
   4942   case ICK_Floating_Integral:
   4943   case ICK_Complex_Real:
   4944     return false;
   4945 
   4946   case ICK_Lvalue_To_Rvalue:
   4947   case ICK_Array_To_Pointer:
   4948   case ICK_Function_To_Pointer:
   4949   case ICK_NoReturn_Adjustment:
   4950   case ICK_Qualification:
   4951   case ICK_Compatible_Conversion:
   4952   case ICK_Vector_Conversion:
   4953   case ICK_Vector_Splat:
   4954   case ICK_Derived_To_Base:
   4955   case ICK_Pointer_Conversion:
   4956   case ICK_Pointer_Member:
   4957   case ICK_Block_Pointer_Conversion:
   4958   case ICK_Writeback_Conversion:
   4959   case ICK_Floating_Promotion:
   4960   case ICK_Complex_Promotion:
   4961   case ICK_Complex_Conversion:
   4962   case ICK_Floating_Conversion:
   4963   case ICK_TransparentUnionConversion:
   4964     llvm_unreachable("unexpected second conversion kind");
   4965 
   4966   case ICK_Num_Conversion_Kinds:
   4967     break;
   4968   }
   4969 
   4970   llvm_unreachable("unknown conversion kind");
   4971 }
   4972 
   4973 /// CheckConvertedConstantExpression - Check that the expression From is a
   4974 /// converted constant expression of type T, perform the conversion and produce
   4975 /// the converted expression, per C++11 [expr.const]p3.
   4976 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
   4977                                                   llvm::APSInt &Value,
   4978                                                   CCEKind CCE) {
   4979   assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
   4980   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
   4981 
   4982   if (checkPlaceholderForOverload(*this, From))
   4983     return ExprError();
   4984 
   4985   // C++11 [expr.const]p3 with proposed wording fixes:
   4986   //  A converted constant expression of type T is a core constant expression,
   4987   //  implicitly converted to a prvalue of type T, where the converted
   4988   //  expression is a literal constant expression and the implicit conversion
   4989   //  sequence contains only user-defined conversions, lvalue-to-rvalue
   4990   //  conversions, integral promotions, and integral conversions other than
   4991   //  narrowing conversions.
   4992   ImplicitConversionSequence ICS =
   4993     TryImplicitConversion(From, T,
   4994                           /*SuppressUserConversions=*/false,
   4995                           /*AllowExplicit=*/false,
   4996                           /*InOverloadResolution=*/false,
   4997                           /*CStyle=*/false,
   4998                           /*AllowObjcWritebackConversion=*/false);
   4999   StandardConversionSequence *SCS = nullptr;
   5000   switch (ICS.getKind()) {
   5001   case ImplicitConversionSequence::StandardConversion:
   5002     if (!CheckConvertedConstantConversions(*this, ICS.Standard))
   5003       return Diag(From->getLocStart(),
   5004                   diag::err_typecheck_converted_constant_expression_disallowed)
   5005                << From->getType() << From->getSourceRange() << T;
   5006     SCS = &ICS.Standard;
   5007     break;
   5008   case ImplicitConversionSequence::UserDefinedConversion:
   5009     // We are converting from class type to an integral or enumeration type, so
   5010     // the Before sequence must be trivial.
   5011     if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
   5012       return Diag(From->getLocStart(),
   5013                   diag::err_typecheck_converted_constant_expression_disallowed)
   5014                << From->getType() << From->getSourceRange() << T;
   5015     SCS = &ICS.UserDefined.After;
   5016     break;
   5017   case ImplicitConversionSequence::AmbiguousConversion:
   5018   case ImplicitConversionSequence::BadConversion:
   5019     if (!DiagnoseMultipleUserDefinedConversion(From, T))
   5020       return Diag(From->getLocStart(),
   5021                   diag::err_typecheck_converted_constant_expression)
   5022                     << From->getType() << From->getSourceRange() << T;
   5023     return ExprError();
   5024 
   5025   case ImplicitConversionSequence::EllipsisConversion:
   5026     llvm_unreachable("ellipsis conversion in converted constant expression");
   5027   }
   5028 
   5029   ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
   5030   if (Result.isInvalid())
   5031     return Result;
   5032 
   5033   // Check for a narrowing implicit conversion.
   5034   APValue PreNarrowingValue;
   5035   QualType PreNarrowingType;
   5036   switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
   5037                                 PreNarrowingType)) {
   5038   case NK_Variable_Narrowing:
   5039     // Implicit conversion to a narrower type, and the value is not a constant
   5040     // expression. We'll diagnose this in a moment.
   5041   case NK_Not_Narrowing:
   5042     break;
   5043 
   5044   case NK_Constant_Narrowing:
   5045     Diag(From->getLocStart(), diag::ext_cce_narrowing)
   5046       << CCE << /*Constant*/1
   5047       << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
   5048     break;
   5049 
   5050   case NK_Type_Narrowing:
   5051     Diag(From->getLocStart(), diag::ext_cce_narrowing)
   5052       << CCE << /*Constant*/0 << From->getType() << T;
   5053     break;
   5054   }
   5055 
   5056   // Check the expression is a constant expression.
   5057   SmallVector<PartialDiagnosticAt, 8> Notes;
   5058   Expr::EvalResult Eval;
   5059   Eval.Diag = &Notes;
   5060 
   5061   if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
   5062     // The expression can't be folded, so we can't keep it at this position in
   5063     // the AST.
   5064     Result = ExprError();
   5065   } else {
   5066     Value = Eval.Val.getInt();
   5067 
   5068     if (Notes.empty()) {
   5069       // It's a constant expression.
   5070       return Result;
   5071     }
   5072   }
   5073 
   5074   // It's not a constant expression. Produce an appropriate diagnostic.
   5075   if (Notes.size() == 1 &&
   5076       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
   5077     Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
   5078   else {
   5079     Diag(From->getLocStart(), diag::err_expr_not_cce)
   5080       << CCE << From->getSourceRange();
   5081     for (unsigned I = 0; I < Notes.size(); ++I)
   5082       Diag(Notes[I].first, Notes[I].second);
   5083   }
   5084   return Result;
   5085 }
   5086 
   5087 /// dropPointerConversions - If the given standard conversion sequence
   5088 /// involves any pointer conversions, remove them.  This may change
   5089 /// the result type of the conversion sequence.
   5090 static void dropPointerConversion(StandardConversionSequence &SCS) {
   5091   if (SCS.Second == ICK_Pointer_Conversion) {
   5092     SCS.Second = ICK_Identity;
   5093     SCS.Third = ICK_Identity;
   5094     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
   5095   }
   5096 }
   5097 
   5098 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
   5099 /// convert the expression From to an Objective-C pointer type.
   5100 static ImplicitConversionSequence
   5101 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
   5102   // Do an implicit conversion to 'id'.
   5103   QualType Ty = S.Context.getObjCIdType();
   5104   ImplicitConversionSequence ICS
   5105     = TryImplicitConversion(S, From, Ty,
   5106                             // FIXME: Are these flags correct?
   5107                             /*SuppressUserConversions=*/false,
   5108                             /*AllowExplicit=*/true,
   5109                             /*InOverloadResolution=*/false,
   5110                             /*CStyle=*/false,
   5111                             /*AllowObjCWritebackConversion=*/false,
   5112                             /*AllowObjCConversionOnExplicit=*/true);
   5113 
   5114   // Strip off any final conversions to 'id'.
   5115   switch (ICS.getKind()) {
   5116   case ImplicitConversionSequence::BadConversion:
   5117   case ImplicitConversionSequence::AmbiguousConversion:
   5118   case ImplicitConversionSequence::EllipsisConversion:
   5119     break;
   5120 
   5121   case ImplicitConversionSequence::UserDefinedConversion:
   5122     dropPointerConversion(ICS.UserDefined.After);
   5123     break;
   5124 
   5125   case ImplicitConversionSequence::StandardConversion:
   5126     dropPointerConversion(ICS.Standard);
   5127     break;
   5128   }
   5129 
   5130   return ICS;
   5131 }
   5132 
   5133 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
   5134 /// conversion of the expression From to an Objective-C pointer type.
   5135 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
   5136   if (checkPlaceholderForOverload(*this, From))
   5137     return ExprError();
   5138 
   5139   QualType Ty = Context.getObjCIdType();
   5140   ImplicitConversionSequence ICS =
   5141     TryContextuallyConvertToObjCPointer(*this, From);
   5142   if (!ICS.isBad())
   5143     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
   5144   return ExprError();
   5145 }
   5146 
   5147 /// Determine whether the provided type is an integral type, or an enumeration
   5148 /// type of a permitted flavor.
   5149 bool Sema::ICEConvertDiagnoser::match(QualType T) {
   5150   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
   5151                                  : T->isIntegralOrUnscopedEnumerationType();
   5152 }
   5153 
   5154 static ExprResult
   5155 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
   5156                             Sema::ContextualImplicitConverter &Converter,
   5157                             QualType T, UnresolvedSetImpl &ViableConversions) {
   5158 
   5159   if (Converter.Suppress)
   5160     return ExprError();
   5161 
   5162   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
   5163   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
   5164     CXXConversionDecl *Conv =
   5165         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
   5166     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
   5167     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
   5168   }
   5169   return From;
   5170 }
   5171 
   5172 static bool
   5173 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
   5174                            Sema::ContextualImplicitConverter &Converter,
   5175                            QualType T, bool HadMultipleCandidates,
   5176                            UnresolvedSetImpl &ExplicitConversions) {
   5177   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
   5178     DeclAccessPair Found = ExplicitConversions[0];
   5179     CXXConversionDecl *Conversion =
   5180         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
   5181 
   5182     // The user probably meant to invoke the given explicit
   5183     // conversion; use it.
   5184     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
   5185     std::string TypeStr;
   5186     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
   5187 
   5188     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
   5189         << FixItHint::CreateInsertion(From->getLocStart(),
   5190                                       "static_cast<" + TypeStr + ">(")
   5191         << FixItHint::CreateInsertion(
   5192                SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
   5193     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
   5194 
   5195     // If we aren't in a SFINAE context, build a call to the
   5196     // explicit conversion function.
   5197     if (SemaRef.isSFINAEContext())
   5198       return true;
   5199 
   5200     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
   5201     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
   5202                                                        HadMultipleCandidates);
   5203     if (Result.isInvalid())
   5204       return true;
   5205     // Record usage of conversion in an implicit cast.
   5206     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
   5207                                     CK_UserDefinedConversion, Result.get(),
   5208                                     nullptr, Result.get()->getValueKind());
   5209   }
   5210   return false;
   5211 }
   5212 
   5213 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
   5214                              Sema::ContextualImplicitConverter &Converter,
   5215                              QualType T, bool HadMultipleCandidates,
   5216                              DeclAccessPair &Found) {
   5217   CXXConversionDecl *Conversion =
   5218       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
   5219   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
   5220 
   5221   QualType ToType = Conversion->getConversionType().getNonReferenceType();
   5222   if (!Converter.SuppressConversion) {
   5223     if (SemaRef.isSFINAEContext())
   5224       return true;
   5225 
   5226     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
   5227         << From->getSourceRange();
   5228   }
   5229 
   5230   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
   5231                                                      HadMultipleCandidates);
   5232   if (Result.isInvalid())
   5233     return true;
   5234   // Record usage of conversion in an implicit cast.
   5235   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
   5236                                   CK_UserDefinedConversion, Result.get(),
   5237                                   nullptr, Result.get()->getValueKind());
   5238   return false;
   5239 }
   5240 
   5241 static ExprResult finishContextualImplicitConversion(
   5242     Sema &SemaRef, SourceLocation Loc, Expr *From,
   5243     Sema::ContextualImplicitConverter &Converter) {
   5244   if (!Converter.match(From->getType()) && !Converter.Suppress)
   5245     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
   5246         << From->getSourceRange();
   5247 
   5248   return SemaRef.DefaultLvalueConversion(From);
   5249 }
   5250 
   5251 static void
   5252 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
   5253                                   UnresolvedSetImpl &ViableConversions,
   5254                                   OverloadCandidateSet &CandidateSet) {
   5255   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
   5256     DeclAccessPair FoundDecl = ViableConversions[I];
   5257     NamedDecl *D = FoundDecl.getDecl();
   5258     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
   5259     if (isa<UsingShadowDecl>(D))
   5260       D = cast<UsingShadowDecl>(D)->getTargetDecl();
   5261 
   5262     CXXConversionDecl *Conv;
   5263     FunctionTemplateDecl *ConvTemplate;
   5264     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
   5265       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
   5266     else
   5267       Conv = cast<CXXConversionDecl>(D);
   5268 
   5269     if (ConvTemplate)
   5270       SemaRef.AddTemplateConversionCandidate(
   5271         ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
   5272         /*AllowObjCConversionOnExplicit=*/false);
   5273     else
   5274       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
   5275                                      ToType, CandidateSet,
   5276                                      /*AllowObjCConversionOnExplicit=*/false);
   5277   }
   5278 }
   5279 
   5280 /// \brief Attempt to convert the given expression to a type which is accepted
   5281 /// by the given converter.
   5282 ///
   5283 /// This routine will attempt to convert an expression of class type to a
   5284 /// type accepted by the specified converter. In C++11 and before, the class
   5285 /// must have a single non-explicit conversion function converting to a matching
   5286 /// type. In C++1y, there can be multiple such conversion functions, but only
   5287 /// one target type.
   5288 ///
   5289 /// \param Loc The source location of the construct that requires the
   5290 /// conversion.
   5291 ///
   5292 /// \param From The expression we're converting from.
   5293 ///
   5294 /// \param Converter Used to control and diagnose the conversion process.
   5295 ///
   5296 /// \returns The expression, converted to an integral or enumeration type if
   5297 /// successful.
   5298 ExprResult Sema::PerformContextualImplicitConversion(
   5299     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
   5300   // We can't perform any more checking for type-dependent expressions.
   5301   if (From->isTypeDependent())
   5302     return From;
   5303 
   5304   // Process placeholders immediately.
   5305   if (From->hasPlaceholderType()) {
   5306     ExprResult result = CheckPlaceholderExpr(From);
   5307     if (result.isInvalid())
   5308       return result;
   5309     From = result.get();
   5310   }
   5311 
   5312   // If the expression already has a matching type, we're golden.
   5313   QualType T = From->getType();
   5314   if (Converter.match(T))
   5315     return DefaultLvalueConversion(From);
   5316 
   5317   // FIXME: Check for missing '()' if T is a function type?
   5318 
   5319   // We can only perform contextual implicit conversions on objects of class
   5320   // type.
   5321   const RecordType *RecordTy = T->getAs<RecordType>();
   5322   if (!RecordTy || !getLangOpts().CPlusPlus) {
   5323     if (!Converter.Suppress)
   5324       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
   5325     return From;
   5326   }
   5327 
   5328   // We must have a complete class type.
   5329   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
   5330     ContextualImplicitConverter &Converter;
   5331     Expr *From;
   5332 
   5333     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
   5334         : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
   5335 
   5336     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
   5337       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
   5338     }
   5339   } IncompleteDiagnoser(Converter, From);
   5340 
   5341   if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
   5342     return From;
   5343 
   5344   // Look for a conversion to an integral or enumeration type.
   5345   UnresolvedSet<4>
   5346       ViableConversions; // These are *potentially* viable in C++1y.
   5347   UnresolvedSet<4> ExplicitConversions;
   5348   std::pair<CXXRecordDecl::conversion_iterator,
   5349             CXXRecordDecl::conversion_iterator> Conversions =
   5350       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
   5351 
   5352   bool HadMultipleCandidates =
   5353       (std::distance(Conversions.first, Conversions.second) > 1);
   5354 
   5355   // To check that there is only one target type, in C++1y:
   5356   QualType ToType;
   5357   bool HasUniqueTargetType = true;
   5358 
   5359   // Collect explicit or viable (potentially in C++1y) conversions.
   5360   for (CXXRecordDecl::conversion_iterator I = Conversions.first,
   5361                                           E = Conversions.second;
   5362        I != E; ++I) {
   5363     NamedDecl *D = (*I)->getUnderlyingDecl();
   5364     CXXConversionDecl *Conversion;
   5365     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
   5366     if (ConvTemplate) {
   5367       if (getLangOpts().CPlusPlus1y)
   5368         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
   5369       else
   5370         continue; // C++11 does not consider conversion operator templates(?).
   5371     } else
   5372       Conversion = cast<CXXConversionDecl>(D);
   5373 
   5374     assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
   5375            "Conversion operator templates are considered potentially "
   5376            "viable in C++1y");
   5377 
   5378     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
   5379     if (Converter.match(CurToType) || ConvTemplate) {
   5380 
   5381       if (Conversion->isExplicit()) {
   5382         // FIXME: For C++1y, do we need this restriction?
   5383         // cf. diagnoseNoViableConversion()
   5384         if (!ConvTemplate)
   5385           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
   5386       } else {
   5387         if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
   5388           if (ToType.isNull())
   5389             ToType = CurToType.getUnqualifiedType();
   5390           else if (HasUniqueTargetType &&
   5391                    (CurToType.getUnqualifiedType() != ToType))
   5392             HasUniqueTargetType = false;
   5393         }
   5394         ViableConversions.addDecl(I.getDecl(), I.getAccess());
   5395       }
   5396     }
   5397   }
   5398 
   5399   if (getLangOpts().CPlusPlus1y) {
   5400     // C++1y [conv]p6:
   5401     // ... An expression e of class type E appearing in such a context
   5402     // is said to be contextually implicitly converted to a specified
   5403     // type T and is well-formed if and only if e can be implicitly
   5404     // converted to a type T that is determined as follows: E is searched
   5405     // for conversion functions whose return type is cv T or reference to
   5406     // cv T such that T is allowed by the context. There shall be
   5407     // exactly one such T.
   5408 
   5409     // If no unique T is found:
   5410     if (ToType.isNull()) {
   5411       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
   5412                                      HadMultipleCandidates,
   5413                                      ExplicitConversions))
   5414         return ExprError();
   5415       return finishContextualImplicitConversion(*this, Loc, From, Converter);
   5416     }
   5417 
   5418     // If more than one unique Ts are found:
   5419     if (!HasUniqueTargetType)
   5420       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
   5421                                          ViableConversions);
   5422 
   5423     // If one unique T is found:
   5424     // First, build a candidate set from the previously recorded
   5425     // potentially viable conversions.
   5426     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
   5427     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
   5428                                       CandidateSet);
   5429 
   5430     // Then, perform overload resolution over the candidate set.
   5431     OverloadCandidateSet::iterator Best;
   5432     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
   5433     case OR_Success: {
   5434       // Apply this conversion.
   5435       DeclAccessPair Found =
   5436           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
   5437       if (recordConversion(*this, Loc, From, Converter, T,
   5438                            HadMultipleCandidates, Found))
   5439         return ExprError();
   5440       break;
   5441     }
   5442     case OR_Ambiguous:
   5443       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
   5444                                          ViableConversions);
   5445     case OR_No_Viable_Function:
   5446       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
   5447                                      HadMultipleCandidates,
   5448                                      ExplicitConversions))
   5449         return ExprError();
   5450     // fall through 'OR_Deleted' case.
   5451     case OR_Deleted:
   5452       // We'll complain below about a non-integral condition type.
   5453       break;
   5454     }
   5455   } else {
   5456     switch (ViableConversions.size()) {
   5457     case 0: {
   5458       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
   5459                                      HadMultipleCandidates,
   5460                                      ExplicitConversions))
   5461         return ExprError();
   5462 
   5463       // We'll complain below about a non-integral condition type.
   5464       break;
   5465     }
   5466     case 1: {
   5467       // Apply this conversion.
   5468       DeclAccessPair Found = ViableConversions[0];
   5469       if (recordConversion(*this, Loc, From, Converter, T,
   5470                            HadMultipleCandidates, Found))
   5471         return ExprError();
   5472       break;
   5473     }
   5474     default:
   5475       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
   5476                                          ViableConversions);
   5477     }
   5478   }
   5479 
   5480   return finishContextualImplicitConversion(*this, Loc, From, Converter);
   5481 }
   5482 
   5483 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
   5484 /// an acceptable non-member overloaded operator for a call whose
   5485 /// arguments have types T1 (and, if non-empty, T2). This routine
   5486 /// implements the check in C++ [over.match.oper]p3b2 concerning
   5487 /// enumeration types.
   5488 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
   5489                                                    FunctionDecl *Fn,
   5490                                                    ArrayRef<Expr *> Args) {
   5491   QualType T1 = Args[0]->getType();
   5492   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
   5493 
   5494   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
   5495     return true;
   5496 
   5497   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
   5498     return true;
   5499 
   5500   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
   5501   if (Proto->getNumParams() < 1)
   5502     return false;
   5503 
   5504   if (T1->isEnumeralType()) {
   5505     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
   5506     if (Context.hasSameUnqualifiedType(T1, ArgType))
   5507       return true;
   5508   }
   5509 
   5510   if (Proto->getNumParams() < 2)
   5511     return false;
   5512 
   5513   if (!T2.isNull() && T2->isEnumeralType()) {
   5514     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
   5515     if (Context.hasSameUnqualifiedType(T2, ArgType))
   5516       return true;
   5517   }
   5518 
   5519   return false;
   5520 }
   5521 
   5522 /// AddOverloadCandidate - Adds the given function to the set of
   5523 /// candidate functions, using the given function call arguments.  If
   5524 /// @p SuppressUserConversions, then don't allow user-defined
   5525 /// conversions via constructors or conversion operators.
   5526 ///
   5527 /// \param PartialOverloading true if we are performing "partial" overloading
   5528 /// based on an incomplete set of function arguments. This feature is used by
   5529 /// code completion.
   5530 void
   5531 Sema::AddOverloadCandidate(FunctionDecl *Function,
   5532                            DeclAccessPair FoundDecl,
   5533                            ArrayRef<Expr *> Args,
   5534                            OverloadCandidateSet &CandidateSet,
   5535                            bool SuppressUserConversions,
   5536                            bool PartialOverloading,
   5537                            bool AllowExplicit) {
   5538   const FunctionProtoType *Proto
   5539     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
   5540   assert(Proto && "Functions without a prototype cannot be overloaded");
   5541   assert(!Function->getDescribedFunctionTemplate() &&
   5542          "Use AddTemplateOverloadCandidate for function templates");
   5543 
   5544   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
   5545     if (!isa<CXXConstructorDecl>(Method)) {
   5546       // If we get here, it's because we're calling a member function
   5547       // that is named without a member access expression (e.g.,
   5548       // "this->f") that was either written explicitly or created
   5549       // implicitly. This can happen with a qualified call to a member
   5550       // function, e.g., X::f(). We use an empty type for the implied
   5551       // object argument (C++ [over.call.func]p3), and the acting context
   5552       // is irrelevant.
   5553       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
   5554                          QualType(), Expr::Classification::makeSimpleLValue(),
   5555                          Args, CandidateSet, SuppressUserConversions);
   5556       return;
   5557     }
   5558     // We treat a constructor like a non-member function, since its object
   5559     // argument doesn't participate in overload resolution.
   5560   }
   5561 
   5562   if (!CandidateSet.isNewCandidate(Function))
   5563     return;
   5564 
   5565   // C++ [over.match.oper]p3:
   5566   //   if no operand has a class type, only those non-member functions in the
   5567   //   lookup set that have a first parameter of type T1 or "reference to
   5568   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
   5569   //   is a right operand) a second parameter of type T2 or "reference to
   5570   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
   5571   //   candidate functions.
   5572   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
   5573       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
   5574     return;
   5575 
   5576   // C++11 [class.copy]p11: [DR1402]
   5577   //   A defaulted move constructor that is defined as deleted is ignored by
   5578   //   overload resolution.
   5579   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
   5580   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
   5581       Constructor->isMoveConstructor())
   5582     return;
   5583 
   5584   // Overload resolution is always an unevaluated context.
   5585   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   5586 
   5587   if (Constructor) {
   5588     // C++ [class.copy]p3:
   5589     //   A member function template is never instantiated to perform the copy
   5590     //   of a class object to an object of its class type.
   5591     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
   5592     if (Args.size() == 1 &&
   5593         Constructor->isSpecializationCopyingObject() &&
   5594         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
   5595          IsDerivedFrom(Args[0]->getType(), ClassType)))
   5596       return;
   5597   }
   5598 
   5599   // Add this candidate
   5600   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
   5601   Candidate.FoundDecl = FoundDecl;
   5602   Candidate.Function = Function;
   5603   Candidate.Viable = true;
   5604   Candidate.IsSurrogate = false;
   5605   Candidate.IgnoreObjectArgument = false;
   5606   Candidate.ExplicitCallArguments = Args.size();
   5607 
   5608   unsigned NumParams = Proto->getNumParams();
   5609 
   5610   // (C++ 13.3.2p2): A candidate function having fewer than m
   5611   // parameters is viable only if it has an ellipsis in its parameter
   5612   // list (8.3.5).
   5613   if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
   5614       !Proto->isVariadic()) {
   5615     Candidate.Viable = false;
   5616     Candidate.FailureKind = ovl_fail_too_many_arguments;
   5617     return;
   5618   }
   5619 
   5620   // (C++ 13.3.2p2): A candidate function having more than m parameters
   5621   // is viable only if the (m+1)st parameter has a default argument
   5622   // (8.3.6). For the purposes of overload resolution, the
   5623   // parameter list is truncated on the right, so that there are
   5624   // exactly m parameters.
   5625   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
   5626   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
   5627     // Not enough arguments.
   5628     Candidate.Viable = false;
   5629     Candidate.FailureKind = ovl_fail_too_few_arguments;
   5630     return;
   5631   }
   5632 
   5633   // (CUDA B.1): Check for invalid calls between targets.
   5634   if (getLangOpts().CUDA)
   5635     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
   5636       if (CheckCUDATarget(Caller, Function)) {
   5637         Candidate.Viable = false;
   5638         Candidate.FailureKind = ovl_fail_bad_target;
   5639         return;
   5640       }
   5641 
   5642   // Determine the implicit conversion sequences for each of the
   5643   // arguments.
   5644   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
   5645     if (ArgIdx < NumParams) {
   5646       // (C++ 13.3.2p3): for F to be a viable function, there shall
   5647       // exist for each argument an implicit conversion sequence
   5648       // (13.3.3.1) that converts that argument to the corresponding
   5649       // parameter of F.
   5650       QualType ParamType = Proto->getParamType(ArgIdx);
   5651       Candidate.Conversions[ArgIdx]
   5652         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
   5653                                 SuppressUserConversions,
   5654                                 /*InOverloadResolution=*/true,
   5655                                 /*AllowObjCWritebackConversion=*/
   5656                                   getLangOpts().ObjCAutoRefCount,
   5657                                 AllowExplicit);
   5658       if (Candidate.Conversions[ArgIdx].isBad()) {
   5659         Candidate.Viable = false;
   5660         Candidate.FailureKind = ovl_fail_bad_conversion;
   5661         return;
   5662       }
   5663     } else {
   5664       // (C++ 13.3.2p2): For the purposes of overload resolution, any
   5665       // argument for which there is no corresponding parameter is
   5666       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
   5667       Candidate.Conversions[ArgIdx].setEllipsis();
   5668     }
   5669   }
   5670 
   5671   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
   5672     Candidate.Viable = false;
   5673     Candidate.FailureKind = ovl_fail_enable_if;
   5674     Candidate.DeductionFailure.Data = FailedAttr;
   5675     return;
   5676   }
   5677 }
   5678 
   5679 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
   5680 
   5681 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
   5682                                   bool MissingImplicitThis) {
   5683   // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
   5684   // we need to find the first failing one.
   5685   if (!Function->hasAttrs())
   5686     return nullptr;
   5687   AttrVec Attrs = Function->getAttrs();
   5688   AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
   5689                                        IsNotEnableIfAttr);
   5690   if (Attrs.begin() == E)
   5691     return nullptr;
   5692   std::reverse(Attrs.begin(), E);
   5693 
   5694   SFINAETrap Trap(*this);
   5695 
   5696   // Convert the arguments.
   5697   SmallVector<Expr *, 16> ConvertedArgs;
   5698   bool InitializationFailed = false;
   5699   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
   5700     if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
   5701         !cast<CXXMethodDecl>(Function)->isStatic() &&
   5702         !isa<CXXConstructorDecl>(Function)) {
   5703       CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
   5704       ExprResult R =
   5705         PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
   5706                                             Method, Method);
   5707       if (R.isInvalid()) {
   5708         InitializationFailed = true;
   5709         break;
   5710       }
   5711       ConvertedArgs.push_back(R.get());
   5712     } else {
   5713       ExprResult R =
   5714         PerformCopyInitialization(InitializedEntity::InitializeParameter(
   5715                                                 Context,
   5716                                                 Function->getParamDecl(i)),
   5717                                   SourceLocation(),
   5718                                   Args[i]);
   5719       if (R.isInvalid()) {
   5720         InitializationFailed = true;
   5721         break;
   5722       }
   5723       ConvertedArgs.push_back(R.get());
   5724     }
   5725   }
   5726 
   5727   if (InitializationFailed || Trap.hasErrorOccurred())
   5728     return cast<EnableIfAttr>(Attrs[0]);
   5729 
   5730   for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
   5731     APValue Result;
   5732     EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
   5733     if (!EIA->getCond()->EvaluateWithSubstitution(
   5734             Result, Context, Function,
   5735             ArrayRef<const Expr*>(ConvertedArgs.data(),
   5736                                   ConvertedArgs.size())) ||
   5737         !Result.isInt() || !Result.getInt().getBoolValue()) {
   5738       return EIA;
   5739     }
   5740   }
   5741   return nullptr;
   5742 }
   5743 
   5744 /// \brief Add all of the function declarations in the given function set to
   5745 /// the overload candidate set.
   5746 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
   5747                                  ArrayRef<Expr *> Args,
   5748                                  OverloadCandidateSet& CandidateSet,
   5749                                  bool SuppressUserConversions,
   5750                                TemplateArgumentListInfo *ExplicitTemplateArgs) {
   5751   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
   5752     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
   5753     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   5754       if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
   5755         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
   5756                            cast<CXXMethodDecl>(FD)->getParent(),
   5757                            Args[0]->getType(), Args[0]->Classify(Context),
   5758                            Args.slice(1), CandidateSet,
   5759                            SuppressUserConversions);
   5760       else
   5761         AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
   5762                              SuppressUserConversions);
   5763     } else {
   5764       FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
   5765       if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
   5766           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
   5767         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
   5768                               cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
   5769                                    ExplicitTemplateArgs,
   5770                                    Args[0]->getType(),
   5771                                    Args[0]->Classify(Context), Args.slice(1),
   5772                                    CandidateSet, SuppressUserConversions);
   5773       else
   5774         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
   5775                                      ExplicitTemplateArgs, Args,
   5776                                      CandidateSet, SuppressUserConversions);
   5777     }
   5778   }
   5779 }
   5780 
   5781 /// AddMethodCandidate - Adds a named decl (which is some kind of
   5782 /// method) as a method candidate to the given overload set.
   5783 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
   5784                               QualType ObjectType,
   5785                               Expr::Classification ObjectClassification,
   5786                               ArrayRef<Expr *> Args,
   5787                               OverloadCandidateSet& CandidateSet,
   5788                               bool SuppressUserConversions) {
   5789   NamedDecl *Decl = FoundDecl.getDecl();
   5790   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
   5791 
   5792   if (isa<UsingShadowDecl>(Decl))
   5793     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
   5794 
   5795   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
   5796     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
   5797            "Expected a member function template");
   5798     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
   5799                                /*ExplicitArgs*/ nullptr,
   5800                                ObjectType, ObjectClassification,
   5801                                Args, CandidateSet,
   5802                                SuppressUserConversions);
   5803   } else {
   5804     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
   5805                        ObjectType, ObjectClassification,
   5806                        Args,
   5807                        CandidateSet, SuppressUserConversions);
   5808   }
   5809 }
   5810 
   5811 /// AddMethodCandidate - Adds the given C++ member function to the set
   5812 /// of candidate functions, using the given function call arguments
   5813 /// and the object argument (@c Object). For example, in a call
   5814 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
   5815 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
   5816 /// allow user-defined conversions via constructors or conversion
   5817 /// operators.
   5818 void
   5819 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
   5820                          CXXRecordDecl *ActingContext, QualType ObjectType,
   5821                          Expr::Classification ObjectClassification,
   5822                          ArrayRef<Expr *> Args,
   5823                          OverloadCandidateSet &CandidateSet,
   5824                          bool SuppressUserConversions) {
   5825   const FunctionProtoType *Proto
   5826     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
   5827   assert(Proto && "Methods without a prototype cannot be overloaded");
   5828   assert(!isa<CXXConstructorDecl>(Method) &&
   5829          "Use AddOverloadCandidate for constructors");
   5830 
   5831   if (!CandidateSet.isNewCandidate(Method))
   5832     return;
   5833 
   5834   // C++11 [class.copy]p23: [DR1402]
   5835   //   A defaulted move assignment operator that is defined as deleted is
   5836   //   ignored by overload resolution.
   5837   if (Method->isDefaulted() && Method->isDeleted() &&
   5838       Method->isMoveAssignmentOperator())
   5839     return;
   5840 
   5841   // Overload resolution is always an unevaluated context.
   5842   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   5843 
   5844   // Add this candidate
   5845   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
   5846   Candidate.FoundDecl = FoundDecl;
   5847   Candidate.Function = Method;
   5848   Candidate.IsSurrogate = false;
   5849   Candidate.IgnoreObjectArgument = false;
   5850   Candidate.ExplicitCallArguments = Args.size();
   5851 
   5852   unsigned NumParams = Proto->getNumParams();
   5853 
   5854   // (C++ 13.3.2p2): A candidate function having fewer than m
   5855   // parameters is viable only if it has an ellipsis in its parameter
   5856   // list (8.3.5).
   5857   if (Args.size() > NumParams && !Proto->isVariadic()) {
   5858     Candidate.Viable = false;
   5859     Candidate.FailureKind = ovl_fail_too_many_arguments;
   5860     return;
   5861   }
   5862 
   5863   // (C++ 13.3.2p2): A candidate function having more than m parameters
   5864   // is viable only if the (m+1)st parameter has a default argument
   5865   // (8.3.6). For the purposes of overload resolution, the
   5866   // parameter list is truncated on the right, so that there are
   5867   // exactly m parameters.
   5868   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
   5869   if (Args.size() < MinRequiredArgs) {
   5870     // Not enough arguments.
   5871     Candidate.Viable = false;
   5872     Candidate.FailureKind = ovl_fail_too_few_arguments;
   5873     return;
   5874   }
   5875 
   5876   Candidate.Viable = true;
   5877 
   5878   if (Method->isStatic() || ObjectType.isNull())
   5879     // The implicit object argument is ignored.
   5880     Candidate.IgnoreObjectArgument = true;
   5881   else {
   5882     // Determine the implicit conversion sequence for the object
   5883     // parameter.
   5884     Candidate.Conversions[0]
   5885       = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
   5886                                         Method, ActingContext);
   5887     if (Candidate.Conversions[0].isBad()) {
   5888       Candidate.Viable = false;
   5889       Candidate.FailureKind = ovl_fail_bad_conversion;
   5890       return;
   5891     }
   5892   }
   5893 
   5894   // Determine the implicit conversion sequences for each of the
   5895   // arguments.
   5896   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
   5897     if (ArgIdx < NumParams) {
   5898       // (C++ 13.3.2p3): for F to be a viable function, there shall
   5899       // exist for each argument an implicit conversion sequence
   5900       // (13.3.3.1) that converts that argument to the corresponding
   5901       // parameter of F.
   5902       QualType ParamType = Proto->getParamType(ArgIdx);
   5903       Candidate.Conversions[ArgIdx + 1]
   5904         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
   5905                                 SuppressUserConversions,
   5906                                 /*InOverloadResolution=*/true,
   5907                                 /*AllowObjCWritebackConversion=*/
   5908                                   getLangOpts().ObjCAutoRefCount);
   5909       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
   5910         Candidate.Viable = false;
   5911         Candidate.FailureKind = ovl_fail_bad_conversion;
   5912         return;
   5913       }
   5914     } else {
   5915       // (C++ 13.3.2p2): For the purposes of overload resolution, any
   5916       // argument for which there is no corresponding parameter is
   5917       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
   5918       Candidate.Conversions[ArgIdx + 1].setEllipsis();
   5919     }
   5920   }
   5921 
   5922   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
   5923     Candidate.Viable = false;
   5924     Candidate.FailureKind = ovl_fail_enable_if;
   5925     Candidate.DeductionFailure.Data = FailedAttr;
   5926     return;
   5927   }
   5928 }
   5929 
   5930 /// \brief Add a C++ member function template as a candidate to the candidate
   5931 /// set, using template argument deduction to produce an appropriate member
   5932 /// function template specialization.
   5933 void
   5934 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
   5935                                  DeclAccessPair FoundDecl,
   5936                                  CXXRecordDecl *ActingContext,
   5937                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
   5938                                  QualType ObjectType,
   5939                                  Expr::Classification ObjectClassification,
   5940                                  ArrayRef<Expr *> Args,
   5941                                  OverloadCandidateSet& CandidateSet,
   5942                                  bool SuppressUserConversions) {
   5943   if (!CandidateSet.isNewCandidate(MethodTmpl))
   5944     return;
   5945 
   5946   // C++ [over.match.funcs]p7:
   5947   //   In each case where a candidate is a function template, candidate
   5948   //   function template specializations are generated using template argument
   5949   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
   5950   //   candidate functions in the usual way.113) A given name can refer to one
   5951   //   or more function templates and also to a set of overloaded non-template
   5952   //   functions. In such a case, the candidate functions generated from each
   5953   //   function template are combined with the set of non-template candidate
   5954   //   functions.
   5955   TemplateDeductionInfo Info(CandidateSet.getLocation());
   5956   FunctionDecl *Specialization = nullptr;
   5957   if (TemplateDeductionResult Result
   5958       = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
   5959                                 Specialization, Info)) {
   5960     OverloadCandidate &Candidate = CandidateSet.addCandidate();
   5961     Candidate.FoundDecl = FoundDecl;
   5962     Candidate.Function = MethodTmpl->getTemplatedDecl();
   5963     Candidate.Viable = false;
   5964     Candidate.FailureKind = ovl_fail_bad_deduction;
   5965     Candidate.IsSurrogate = false;
   5966     Candidate.IgnoreObjectArgument = false;
   5967     Candidate.ExplicitCallArguments = Args.size();
   5968     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
   5969                                                           Info);
   5970     return;
   5971   }
   5972 
   5973   // Add the function template specialization produced by template argument
   5974   // deduction as a candidate.
   5975   assert(Specialization && "Missing member function template specialization?");
   5976   assert(isa<CXXMethodDecl>(Specialization) &&
   5977          "Specialization is not a member function?");
   5978   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
   5979                      ActingContext, ObjectType, ObjectClassification, Args,
   5980                      CandidateSet, SuppressUserConversions);
   5981 }
   5982 
   5983 /// \brief Add a C++ function template specialization as a candidate
   5984 /// in the candidate set, using template argument deduction to produce
   5985 /// an appropriate function template specialization.
   5986 void
   5987 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
   5988                                    DeclAccessPair FoundDecl,
   5989                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
   5990                                    ArrayRef<Expr *> Args,
   5991                                    OverloadCandidateSet& CandidateSet,
   5992                                    bool SuppressUserConversions) {
   5993   if (!CandidateSet.isNewCandidate(FunctionTemplate))
   5994     return;
   5995 
   5996   // C++ [over.match.funcs]p7:
   5997   //   In each case where a candidate is a function template, candidate
   5998   //   function template specializations are generated using template argument
   5999   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
   6000   //   candidate functions in the usual way.113) A given name can refer to one
   6001   //   or more function templates and also to a set of overloaded non-template
   6002   //   functions. In such a case, the candidate functions generated from each
   6003   //   function template are combined with the set of non-template candidate
   6004   //   functions.
   6005   TemplateDeductionInfo Info(CandidateSet.getLocation());
   6006   FunctionDecl *Specialization = nullptr;
   6007   if (TemplateDeductionResult Result
   6008         = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
   6009                                   Specialization, Info)) {
   6010     OverloadCandidate &Candidate = CandidateSet.addCandidate();
   6011     Candidate.FoundDecl = FoundDecl;
   6012     Candidate.Function = FunctionTemplate->getTemplatedDecl();
   6013     Candidate.Viable = false;
   6014     Candidate.FailureKind = ovl_fail_bad_deduction;
   6015     Candidate.IsSurrogate = false;
   6016     Candidate.IgnoreObjectArgument = false;
   6017     Candidate.ExplicitCallArguments = Args.size();
   6018     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
   6019                                                           Info);
   6020     return;
   6021   }
   6022 
   6023   // Add the function template specialization produced by template argument
   6024   // deduction as a candidate.
   6025   assert(Specialization && "Missing function template specialization?");
   6026   AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
   6027                        SuppressUserConversions);
   6028 }
   6029 
   6030 /// Determine whether this is an allowable conversion from the result
   6031 /// of an explicit conversion operator to the expected type, per C++
   6032 /// [over.match.conv]p1 and [over.match.ref]p1.
   6033 ///
   6034 /// \param ConvType The return type of the conversion function.
   6035 ///
   6036 /// \param ToType The type we are converting to.
   6037 ///
   6038 /// \param AllowObjCPointerConversion Allow a conversion from one
   6039 /// Objective-C pointer to another.
   6040 ///
   6041 /// \returns true if the conversion is allowable, false otherwise.
   6042 static bool isAllowableExplicitConversion(Sema &S,
   6043                                           QualType ConvType, QualType ToType,
   6044                                           bool AllowObjCPointerConversion) {
   6045   QualType ToNonRefType = ToType.getNonReferenceType();
   6046 
   6047   // Easy case: the types are the same.
   6048   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
   6049     return true;
   6050 
   6051   // Allow qualification conversions.
   6052   bool ObjCLifetimeConversion;
   6053   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
   6054                                   ObjCLifetimeConversion))
   6055     return true;
   6056 
   6057   // If we're not allowed to consider Objective-C pointer conversions,
   6058   // we're done.
   6059   if (!AllowObjCPointerConversion)
   6060     return false;
   6061 
   6062   // Is this an Objective-C pointer conversion?
   6063   bool IncompatibleObjC = false;
   6064   QualType ConvertedType;
   6065   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
   6066                                    IncompatibleObjC);
   6067 }
   6068 
   6069 /// AddConversionCandidate - Add a C++ conversion function as a
   6070 /// candidate in the candidate set (C++ [over.match.conv],
   6071 /// C++ [over.match.copy]). From is the expression we're converting from,
   6072 /// and ToType is the type that we're eventually trying to convert to
   6073 /// (which may or may not be the same type as the type that the
   6074 /// conversion function produces).
   6075 void
   6076 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
   6077                              DeclAccessPair FoundDecl,
   6078                              CXXRecordDecl *ActingContext,
   6079                              Expr *From, QualType ToType,
   6080                              OverloadCandidateSet& CandidateSet,
   6081                              bool AllowObjCConversionOnExplicit) {
   6082   assert(!Conversion->getDescribedFunctionTemplate() &&
   6083          "Conversion function templates use AddTemplateConversionCandidate");
   6084   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
   6085   if (!CandidateSet.isNewCandidate(Conversion))
   6086     return;
   6087 
   6088   // If the conversion function has an undeduced return type, trigger its
   6089   // deduction now.
   6090   if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
   6091     if (DeduceReturnType(Conversion, From->getExprLoc()))
   6092       return;
   6093     ConvType = Conversion->getConversionType().getNonReferenceType();
   6094   }
   6095 
   6096   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
   6097   // operator is only a candidate if its return type is the target type or
   6098   // can be converted to the target type with a qualification conversion.
   6099   if (Conversion->isExplicit() &&
   6100       !isAllowableExplicitConversion(*this, ConvType, ToType,
   6101                                      AllowObjCConversionOnExplicit))
   6102     return;
   6103 
   6104   // Overload resolution is always an unevaluated context.
   6105   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   6106 
   6107   // Add this candidate
   6108   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
   6109   Candidate.FoundDecl = FoundDecl;
   6110   Candidate.Function = Conversion;
   6111   Candidate.IsSurrogate = false;
   6112   Candidate.IgnoreObjectArgument = false;
   6113   Candidate.FinalConversion.setAsIdentityConversion();
   6114   Candidate.FinalConversion.setFromType(ConvType);
   6115   Candidate.FinalConversion.setAllToTypes(ToType);
   6116   Candidate.Viable = true;
   6117   Candidate.ExplicitCallArguments = 1;
   6118 
   6119   // C++ [over.match.funcs]p4:
   6120   //   For conversion functions, the function is considered to be a member of
   6121   //   the class of the implicit implied object argument for the purpose of
   6122   //   defining the type of the implicit object parameter.
   6123   //
   6124   // Determine the implicit conversion sequence for the implicit
   6125   // object parameter.
   6126   QualType ImplicitParamType = From->getType();
   6127   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
   6128     ImplicitParamType = FromPtrType->getPointeeType();
   6129   CXXRecordDecl *ConversionContext
   6130     = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
   6131 
   6132   Candidate.Conversions[0]
   6133     = TryObjectArgumentInitialization(*this, From->getType(),
   6134                                       From->Classify(Context),
   6135                                       Conversion, ConversionContext);
   6136 
   6137   if (Candidate.Conversions[0].isBad()) {
   6138     Candidate.Viable = false;
   6139     Candidate.FailureKind = ovl_fail_bad_conversion;
   6140     return;
   6141   }
   6142 
   6143   // We won't go through a user-defined type conversion function to convert a
   6144   // derived to base as such conversions are given Conversion Rank. They only
   6145   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
   6146   QualType FromCanon
   6147     = Context.getCanonicalType(From->getType().getUnqualifiedType());
   6148   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
   6149   if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
   6150     Candidate.Viable = false;
   6151     Candidate.FailureKind = ovl_fail_trivial_conversion;
   6152     return;
   6153   }
   6154 
   6155   // To determine what the conversion from the result of calling the
   6156   // conversion function to the type we're eventually trying to
   6157   // convert to (ToType), we need to synthesize a call to the
   6158   // conversion function and attempt copy initialization from it. This
   6159   // makes sure that we get the right semantics with respect to
   6160   // lvalues/rvalues and the type. Fortunately, we can allocate this
   6161   // call on the stack and we don't need its arguments to be
   6162   // well-formed.
   6163   DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
   6164                             VK_LValue, From->getLocStart());
   6165   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
   6166                                 Context.getPointerType(Conversion->getType()),
   6167                                 CK_FunctionToPointerDecay,
   6168                                 &ConversionRef, VK_RValue);
   6169 
   6170   QualType ConversionType = Conversion->getConversionType();
   6171   if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
   6172     Candidate.Viable = false;
   6173     Candidate.FailureKind = ovl_fail_bad_final_conversion;
   6174     return;
   6175   }
   6176 
   6177   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
   6178 
   6179   // Note that it is safe to allocate CallExpr on the stack here because
   6180   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
   6181   // allocator).
   6182   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
   6183   CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
   6184                 From->getLocStart());
   6185   ImplicitConversionSequence ICS =
   6186     TryCopyInitialization(*this, &Call, ToType,
   6187                           /*SuppressUserConversions=*/true,
   6188                           /*InOverloadResolution=*/false,
   6189                           /*AllowObjCWritebackConversion=*/false);
   6190 
   6191   switch (ICS.getKind()) {
   6192   case ImplicitConversionSequence::StandardConversion:
   6193     Candidate.FinalConversion = ICS.Standard;
   6194 
   6195     // C++ [over.ics.user]p3:
   6196     //   If the user-defined conversion is specified by a specialization of a
   6197     //   conversion function template, the second standard conversion sequence
   6198     //   shall have exact match rank.
   6199     if (Conversion->getPrimaryTemplate() &&
   6200         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
   6201       Candidate.Viable = false;
   6202       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
   6203       return;
   6204     }
   6205 
   6206     // C++0x [dcl.init.ref]p5:
   6207     //    In the second case, if the reference is an rvalue reference and
   6208     //    the second standard conversion sequence of the user-defined
   6209 </