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