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