Home | History | Annotate | Download | only in Sema
      1 //===--------------------- SemaLookup.cpp - Name Lookup  ------------------===//
      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 implements name lookup for C, C++, Objective-C, and
     11 //  Objective-C++.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 #include "clang/Sema/Sema.h"
     15 #include "clang/Sema/SemaInternal.h"
     16 #include "clang/Sema/Lookup.h"
     17 #include "clang/Sema/Overload.h"
     18 #include "clang/Sema/DeclSpec.h"
     19 #include "clang/Sema/Scope.h"
     20 #include "clang/Sema/ScopeInfo.h"
     21 #include "clang/Sema/TemplateDeduction.h"
     22 #include "clang/Sema/ExternalSemaSource.h"
     23 #include "clang/Sema/TypoCorrection.h"
     24 #include "clang/AST/ASTContext.h"
     25 #include "clang/AST/CXXInheritance.h"
     26 #include "clang/AST/Decl.h"
     27 #include "clang/AST/DeclCXX.h"
     28 #include "clang/AST/DeclLookups.h"
     29 #include "clang/AST/DeclObjC.h"
     30 #include "clang/AST/DeclTemplate.h"
     31 #include "clang/AST/Expr.h"
     32 #include "clang/AST/ExprCXX.h"
     33 #include "clang/Basic/Builtins.h"
     34 #include "clang/Basic/LangOptions.h"
     35 #include "llvm/ADT/SetVector.h"
     36 #include "llvm/ADT/STLExtras.h"
     37 #include "llvm/ADT/SmallPtrSet.h"
     38 #include "llvm/ADT/StringMap.h"
     39 #include "llvm/ADT/TinyPtrVector.h"
     40 #include "llvm/ADT/edit_distance.h"
     41 #include "llvm/Support/ErrorHandling.h"
     42 #include <algorithm>
     43 #include <iterator>
     44 #include <limits>
     45 #include <list>
     46 #include <map>
     47 #include <set>
     48 #include <utility>
     49 #include <vector>
     50 
     51 using namespace clang;
     52 using namespace sema;
     53 
     54 namespace {
     55   class UnqualUsingEntry {
     56     const DeclContext *Nominated;
     57     const DeclContext *CommonAncestor;
     58 
     59   public:
     60     UnqualUsingEntry(const DeclContext *Nominated,
     61                      const DeclContext *CommonAncestor)
     62       : Nominated(Nominated), CommonAncestor(CommonAncestor) {
     63     }
     64 
     65     const DeclContext *getCommonAncestor() const {
     66       return CommonAncestor;
     67     }
     68 
     69     const DeclContext *getNominatedNamespace() const {
     70       return Nominated;
     71     }
     72 
     73     // Sort by the pointer value of the common ancestor.
     74     struct Comparator {
     75       bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
     76         return L.getCommonAncestor() < R.getCommonAncestor();
     77       }
     78 
     79       bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
     80         return E.getCommonAncestor() < DC;
     81       }
     82 
     83       bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
     84         return DC < E.getCommonAncestor();
     85       }
     86     };
     87   };
     88 
     89   /// A collection of using directives, as used by C++ unqualified
     90   /// lookup.
     91   class UnqualUsingDirectiveSet {
     92     typedef SmallVector<UnqualUsingEntry, 8> ListTy;
     93 
     94     ListTy list;
     95     llvm::SmallPtrSet<DeclContext*, 8> visited;
     96 
     97   public:
     98     UnqualUsingDirectiveSet() {}
     99 
    100     void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
    101       // C++ [namespace.udir]p1:
    102       //   During unqualified name lookup, the names appear as if they
    103       //   were declared in the nearest enclosing namespace which contains
    104       //   both the using-directive and the nominated namespace.
    105       DeclContext *InnermostFileDC
    106         = static_cast<DeclContext*>(InnermostFileScope->getEntity());
    107       assert(InnermostFileDC && InnermostFileDC->isFileContext());
    108 
    109       for (; S; S = S->getParent()) {
    110         // C++ [namespace.udir]p1:
    111         //   A using-directive shall not appear in class scope, but may
    112         //   appear in namespace scope or in block scope.
    113         DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
    114         if (Ctx && Ctx->isFileContext()) {
    115           visit(Ctx, Ctx);
    116         } else if (!Ctx || Ctx->isFunctionOrMethod()) {
    117           Scope::udir_iterator I = S->using_directives_begin(),
    118                              End = S->using_directives_end();
    119           for (; I != End; ++I)
    120             visit(*I, InnermostFileDC);
    121         }
    122       }
    123     }
    124 
    125     // Visits a context and collect all of its using directives
    126     // recursively.  Treats all using directives as if they were
    127     // declared in the context.
    128     //
    129     // A given context is only every visited once, so it is important
    130     // that contexts be visited from the inside out in order to get
    131     // the effective DCs right.
    132     void visit(DeclContext *DC, DeclContext *EffectiveDC) {
    133       if (!visited.insert(DC))
    134         return;
    135 
    136       addUsingDirectives(DC, EffectiveDC);
    137     }
    138 
    139     // Visits a using directive and collects all of its using
    140     // directives recursively.  Treats all using directives as if they
    141     // were declared in the effective DC.
    142     void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
    143       DeclContext *NS = UD->getNominatedNamespace();
    144       if (!visited.insert(NS))
    145         return;
    146 
    147       addUsingDirective(UD, EffectiveDC);
    148       addUsingDirectives(NS, EffectiveDC);
    149     }
    150 
    151     // Adds all the using directives in a context (and those nominated
    152     // by its using directives, transitively) as if they appeared in
    153     // the given effective context.
    154     void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
    155       SmallVector<DeclContext*,4> queue;
    156       while (true) {
    157         DeclContext::udir_iterator I, End;
    158         for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
    159           UsingDirectiveDecl *UD = *I;
    160           DeclContext *NS = UD->getNominatedNamespace();
    161           if (visited.insert(NS)) {
    162             addUsingDirective(UD, EffectiveDC);
    163             queue.push_back(NS);
    164           }
    165         }
    166 
    167         if (queue.empty())
    168           return;
    169 
    170         DC = queue.back();
    171         queue.pop_back();
    172       }
    173     }
    174 
    175     // Add a using directive as if it had been declared in the given
    176     // context.  This helps implement C++ [namespace.udir]p3:
    177     //   The using-directive is transitive: if a scope contains a
    178     //   using-directive that nominates a second namespace that itself
    179     //   contains using-directives, the effect is as if the
    180     //   using-directives from the second namespace also appeared in
    181     //   the first.
    182     void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
    183       // Find the common ancestor between the effective context and
    184       // the nominated namespace.
    185       DeclContext *Common = UD->getNominatedNamespace();
    186       while (!Common->Encloses(EffectiveDC))
    187         Common = Common->getParent();
    188       Common = Common->getPrimaryContext();
    189 
    190       list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
    191     }
    192 
    193     void done() {
    194       std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
    195     }
    196 
    197     typedef ListTy::const_iterator const_iterator;
    198 
    199     const_iterator begin() const { return list.begin(); }
    200     const_iterator end() const { return list.end(); }
    201 
    202     std::pair<const_iterator,const_iterator>
    203     getNamespacesFor(DeclContext *DC) const {
    204       return std::equal_range(begin(), end(), DC->getPrimaryContext(),
    205                               UnqualUsingEntry::Comparator());
    206     }
    207   };
    208 }
    209 
    210 // Retrieve the set of identifier namespaces that correspond to a
    211 // specific kind of name lookup.
    212 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
    213                                bool CPlusPlus,
    214                                bool Redeclaration) {
    215   unsigned IDNS = 0;
    216   switch (NameKind) {
    217   case Sema::LookupObjCImplicitSelfParam:
    218   case Sema::LookupOrdinaryName:
    219   case Sema::LookupRedeclarationWithLinkage:
    220     IDNS = Decl::IDNS_Ordinary;
    221     if (CPlusPlus) {
    222       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
    223       if (Redeclaration)
    224         IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
    225     }
    226     break;
    227 
    228   case Sema::LookupOperatorName:
    229     // Operator lookup is its own crazy thing;  it is not the same
    230     // as (e.g.) looking up an operator name for redeclaration.
    231     assert(!Redeclaration && "cannot do redeclaration operator lookup");
    232     IDNS = Decl::IDNS_NonMemberOperator;
    233     break;
    234 
    235   case Sema::LookupTagName:
    236     if (CPlusPlus) {
    237       IDNS = Decl::IDNS_Type;
    238 
    239       // When looking for a redeclaration of a tag name, we add:
    240       // 1) TagFriend to find undeclared friend decls
    241       // 2) Namespace because they can't "overload" with tag decls.
    242       // 3) Tag because it includes class templates, which can't
    243       //    "overload" with tag decls.
    244       if (Redeclaration)
    245         IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
    246     } else {
    247       IDNS = Decl::IDNS_Tag;
    248     }
    249     break;
    250   case Sema::LookupLabel:
    251     IDNS = Decl::IDNS_Label;
    252     break;
    253 
    254   case Sema::LookupMemberName:
    255     IDNS = Decl::IDNS_Member;
    256     if (CPlusPlus)
    257       IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
    258     break;
    259 
    260   case Sema::LookupNestedNameSpecifierName:
    261     IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
    262     break;
    263 
    264   case Sema::LookupNamespaceName:
    265     IDNS = Decl::IDNS_Namespace;
    266     break;
    267 
    268   case Sema::LookupUsingDeclName:
    269     IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
    270          | Decl::IDNS_Member | Decl::IDNS_Using;
    271     break;
    272 
    273   case Sema::LookupObjCProtocolName:
    274     IDNS = Decl::IDNS_ObjCProtocol;
    275     break;
    276 
    277   case Sema::LookupAnyName:
    278     IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
    279       | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
    280       | Decl::IDNS_Type;
    281     break;
    282   }
    283   return IDNS;
    284 }
    285 
    286 void LookupResult::configure() {
    287   IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
    288                  isForRedeclaration());
    289 
    290   // If we're looking for one of the allocation or deallocation
    291   // operators, make sure that the implicitly-declared new and delete
    292   // operators can be found.
    293   if (!isForRedeclaration()) {
    294     switch (NameInfo.getName().getCXXOverloadedOperator()) {
    295     case OO_New:
    296     case OO_Delete:
    297     case OO_Array_New:
    298     case OO_Array_Delete:
    299       SemaRef.DeclareGlobalNewDelete();
    300       break;
    301 
    302     default:
    303       break;
    304     }
    305   }
    306 }
    307 
    308 void LookupResult::sanityImpl() const {
    309   // Note that this function is never called by NDEBUG builds. See
    310   // LookupResult::sanity().
    311   assert(ResultKind != NotFound || Decls.size() == 0);
    312   assert(ResultKind != Found || Decls.size() == 1);
    313   assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
    314          (Decls.size() == 1 &&
    315           isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
    316   assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
    317   assert(ResultKind != Ambiguous || Decls.size() > 1 ||
    318          (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
    319                                 Ambiguity == AmbiguousBaseSubobjectTypes)));
    320   assert((Paths != NULL) == (ResultKind == Ambiguous &&
    321                              (Ambiguity == AmbiguousBaseSubobjectTypes ||
    322                               Ambiguity == AmbiguousBaseSubobjects)));
    323 }
    324 
    325 // Necessary because CXXBasePaths is not complete in Sema.h
    326 void LookupResult::deletePaths(CXXBasePaths *Paths) {
    327   delete Paths;
    328 }
    329 
    330 static NamedDecl *getVisibleDecl(NamedDecl *D);
    331 
    332 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
    333   return getVisibleDecl(D);
    334 }
    335 
    336 /// Resolves the result kind of this lookup.
    337 void LookupResult::resolveKind() {
    338   unsigned N = Decls.size();
    339 
    340   // Fast case: no possible ambiguity.
    341   if (N == 0) {
    342     assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
    343     return;
    344   }
    345 
    346   // If there's a single decl, we need to examine it to decide what
    347   // kind of lookup this is.
    348   if (N == 1) {
    349     NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
    350     if (isa<FunctionTemplateDecl>(D))
    351       ResultKind = FoundOverloaded;
    352     else if (isa<UnresolvedUsingValueDecl>(D))
    353       ResultKind = FoundUnresolvedValue;
    354     return;
    355   }
    356 
    357   // Don't do any extra resolution if we've already resolved as ambiguous.
    358   if (ResultKind == Ambiguous) return;
    359 
    360   llvm::SmallPtrSet<NamedDecl*, 16> Unique;
    361   llvm::SmallPtrSet<QualType, 16> UniqueTypes;
    362 
    363   bool Ambiguous = false;
    364   bool HasTag = false, HasFunction = false, HasNonFunction = false;
    365   bool HasFunctionTemplate = false, HasUnresolved = false;
    366 
    367   unsigned UniqueTagIndex = 0;
    368 
    369   unsigned I = 0;
    370   while (I < N) {
    371     NamedDecl *D = Decls[I]->getUnderlyingDecl();
    372     D = cast<NamedDecl>(D->getCanonicalDecl());
    373 
    374     // Redeclarations of types via typedef can occur both within a scope
    375     // and, through using declarations and directives, across scopes. There is
    376     // no ambiguity if they all refer to the same type, so unique based on the
    377     // canonical type.
    378     if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
    379       if (!TD->getDeclContext()->isRecord()) {
    380         QualType T = SemaRef.Context.getTypeDeclType(TD);
    381         if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
    382           // The type is not unique; pull something off the back and continue
    383           // at this index.
    384           Decls[I] = Decls[--N];
    385           continue;
    386         }
    387       }
    388     }
    389 
    390     if (!Unique.insert(D)) {
    391       // If it's not unique, pull something off the back (and
    392       // continue at this index).
    393       Decls[I] = Decls[--N];
    394       continue;
    395     }
    396 
    397     // Otherwise, do some decl type analysis and then continue.
    398 
    399     if (isa<UnresolvedUsingValueDecl>(D)) {
    400       HasUnresolved = true;
    401     } else if (isa<TagDecl>(D)) {
    402       if (HasTag)
    403         Ambiguous = true;
    404       UniqueTagIndex = I;
    405       HasTag = true;
    406     } else if (isa<FunctionTemplateDecl>(D)) {
    407       HasFunction = true;
    408       HasFunctionTemplate = true;
    409     } else if (isa<FunctionDecl>(D)) {
    410       HasFunction = true;
    411     } else {
    412       if (HasNonFunction)
    413         Ambiguous = true;
    414       HasNonFunction = true;
    415     }
    416     I++;
    417   }
    418 
    419   // C++ [basic.scope.hiding]p2:
    420   //   A class name or enumeration name can be hidden by the name of
    421   //   an object, function, or enumerator declared in the same
    422   //   scope. If a class or enumeration name and an object, function,
    423   //   or enumerator are declared in the same scope (in any order)
    424   //   with the same name, the class or enumeration name is hidden
    425   //   wherever the object, function, or enumerator name is visible.
    426   // But it's still an error if there are distinct tag types found,
    427   // even if they're not visible. (ref?)
    428   if (HideTags && HasTag && !Ambiguous &&
    429       (HasFunction || HasNonFunction || HasUnresolved)) {
    430     if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
    431          Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
    432       Decls[UniqueTagIndex] = Decls[--N];
    433     else
    434       Ambiguous = true;
    435   }
    436 
    437   Decls.set_size(N);
    438 
    439   if (HasNonFunction && (HasFunction || HasUnresolved))
    440     Ambiguous = true;
    441 
    442   if (Ambiguous)
    443     setAmbiguous(LookupResult::AmbiguousReference);
    444   else if (HasUnresolved)
    445     ResultKind = LookupResult::FoundUnresolvedValue;
    446   else if (N > 1 || HasFunctionTemplate)
    447     ResultKind = LookupResult::FoundOverloaded;
    448   else
    449     ResultKind = LookupResult::Found;
    450 }
    451 
    452 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
    453   CXXBasePaths::const_paths_iterator I, E;
    454   DeclContext::lookup_iterator DI, DE;
    455   for (I = P.begin(), E = P.end(); I != E; ++I)
    456     for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
    457       addDecl(*DI);
    458 }
    459 
    460 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
    461   Paths = new CXXBasePaths;
    462   Paths->swap(P);
    463   addDeclsFromBasePaths(*Paths);
    464   resolveKind();
    465   setAmbiguous(AmbiguousBaseSubobjects);
    466 }
    467 
    468 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
    469   Paths = new CXXBasePaths;
    470   Paths->swap(P);
    471   addDeclsFromBasePaths(*Paths);
    472   resolveKind();
    473   setAmbiguous(AmbiguousBaseSubobjectTypes);
    474 }
    475 
    476 void LookupResult::print(raw_ostream &Out) {
    477   Out << Decls.size() << " result(s)";
    478   if (isAmbiguous()) Out << ", ambiguous";
    479   if (Paths) Out << ", base paths present";
    480 
    481   for (iterator I = begin(), E = end(); I != E; ++I) {
    482     Out << "\n";
    483     (*I)->print(Out, 2);
    484   }
    485 }
    486 
    487 /// \brief Lookup a builtin function, when name lookup would otherwise
    488 /// fail.
    489 static bool LookupBuiltin(Sema &S, LookupResult &R) {
    490   Sema::LookupNameKind NameKind = R.getLookupKind();
    491 
    492   // If we didn't find a use of this identifier, and if the identifier
    493   // corresponds to a compiler builtin, create the decl object for the builtin
    494   // now, injecting it into translation unit scope, and return it.
    495   if (NameKind == Sema::LookupOrdinaryName ||
    496       NameKind == Sema::LookupRedeclarationWithLinkage) {
    497     IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
    498     if (II) {
    499       // If this is a builtin on this (or all) targets, create the decl.
    500       if (unsigned BuiltinID = II->getBuiltinID()) {
    501         // In C++, we don't have any predefined library functions like
    502         // 'malloc'. Instead, we'll just error.
    503         if (S.getLangOpts().CPlusPlus &&
    504             S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
    505           return false;
    506 
    507         if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
    508                                                  BuiltinID, S.TUScope,
    509                                                  R.isForRedeclaration(),
    510                                                  R.getNameLoc())) {
    511           R.addDecl(D);
    512           return true;
    513         }
    514 
    515         if (R.isForRedeclaration()) {
    516           // If we're redeclaring this function anyway, forget that
    517           // this was a builtin at all.
    518           S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
    519         }
    520 
    521         return false;
    522       }
    523     }
    524   }
    525 
    526   return false;
    527 }
    528 
    529 /// \brief Determine whether we can declare a special member function within
    530 /// the class at this point.
    531 static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
    532                                             const CXXRecordDecl *Class) {
    533   // We need to have a definition for the class.
    534   if (!Class->getDefinition() || Class->isDependentContext())
    535     return false;
    536 
    537   // We can't be in the middle of defining the class.
    538   if (const RecordType *RecordTy
    539                         = Context.getTypeDeclType(Class)->getAs<RecordType>())
    540     return !RecordTy->isBeingDefined();
    541 
    542   return false;
    543 }
    544 
    545 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
    546   if (!CanDeclareSpecialMemberFunction(Context, Class))
    547     return;
    548 
    549   // If the default constructor has not yet been declared, do so now.
    550   if (Class->needsImplicitDefaultConstructor())
    551     DeclareImplicitDefaultConstructor(Class);
    552 
    553   // If the copy constructor has not yet been declared, do so now.
    554   if (!Class->hasDeclaredCopyConstructor())
    555     DeclareImplicitCopyConstructor(Class);
    556 
    557   // If the copy assignment operator has not yet been declared, do so now.
    558   if (!Class->hasDeclaredCopyAssignment())
    559     DeclareImplicitCopyAssignment(Class);
    560 
    561   if (getLangOpts().CPlusPlus0x) {
    562     // If the move constructor has not yet been declared, do so now.
    563     if (Class->needsImplicitMoveConstructor())
    564       DeclareImplicitMoveConstructor(Class); // might not actually do it
    565 
    566     // If the move assignment operator has not yet been declared, do so now.
    567     if (Class->needsImplicitMoveAssignment())
    568       DeclareImplicitMoveAssignment(Class); // might not actually do it
    569   }
    570 
    571   // If the destructor has not yet been declared, do so now.
    572   if (!Class->hasDeclaredDestructor())
    573     DeclareImplicitDestructor(Class);
    574 }
    575 
    576 /// \brief Determine whether this is the name of an implicitly-declared
    577 /// special member function.
    578 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
    579   switch (Name.getNameKind()) {
    580   case DeclarationName::CXXConstructorName:
    581   case DeclarationName::CXXDestructorName:
    582     return true;
    583 
    584   case DeclarationName::CXXOperatorName:
    585     return Name.getCXXOverloadedOperator() == OO_Equal;
    586 
    587   default:
    588     break;
    589   }
    590 
    591   return false;
    592 }
    593 
    594 /// \brief If there are any implicit member functions with the given name
    595 /// that need to be declared in the given declaration context, do so.
    596 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
    597                                                    DeclarationName Name,
    598                                                    const DeclContext *DC) {
    599   if (!DC)
    600     return;
    601 
    602   switch (Name.getNameKind()) {
    603   case DeclarationName::CXXConstructorName:
    604     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
    605       if (Record->getDefinition() &&
    606           CanDeclareSpecialMemberFunction(S.Context, Record)) {
    607         CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
    608         if (Record->needsImplicitDefaultConstructor())
    609           S.DeclareImplicitDefaultConstructor(Class);
    610         if (!Record->hasDeclaredCopyConstructor())
    611           S.DeclareImplicitCopyConstructor(Class);
    612         if (S.getLangOpts().CPlusPlus0x &&
    613             Record->needsImplicitMoveConstructor())
    614           S.DeclareImplicitMoveConstructor(Class);
    615       }
    616     break;
    617 
    618   case DeclarationName::CXXDestructorName:
    619     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
    620       if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
    621           CanDeclareSpecialMemberFunction(S.Context, Record))
    622         S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
    623     break;
    624 
    625   case DeclarationName::CXXOperatorName:
    626     if (Name.getCXXOverloadedOperator() != OO_Equal)
    627       break;
    628 
    629     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
    630       if (Record->getDefinition() &&
    631           CanDeclareSpecialMemberFunction(S.Context, Record)) {
    632         CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
    633         if (!Record->hasDeclaredCopyAssignment())
    634           S.DeclareImplicitCopyAssignment(Class);
    635         if (S.getLangOpts().CPlusPlus0x &&
    636             Record->needsImplicitMoveAssignment())
    637           S.DeclareImplicitMoveAssignment(Class);
    638       }
    639     }
    640     break;
    641 
    642   default:
    643     break;
    644   }
    645 }
    646 
    647 // Adds all qualifying matches for a name within a decl context to the
    648 // given lookup result.  Returns true if any matches were found.
    649 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
    650   bool Found = false;
    651 
    652   // Lazily declare C++ special member functions.
    653   if (S.getLangOpts().CPlusPlus)
    654     DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
    655 
    656   // Perform lookup into this declaration context.
    657   DeclContext::lookup_const_iterator I, E;
    658   for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
    659     NamedDecl *D = *I;
    660     if ((D = R.getAcceptableDecl(D))) {
    661       R.addDecl(D);
    662       Found = true;
    663     }
    664   }
    665 
    666   if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
    667     return true;
    668 
    669   if (R.getLookupName().getNameKind()
    670         != DeclarationName::CXXConversionFunctionName ||
    671       R.getLookupName().getCXXNameType()->isDependentType() ||
    672       !isa<CXXRecordDecl>(DC))
    673     return Found;
    674 
    675   // C++ [temp.mem]p6:
    676   //   A specialization of a conversion function template is not found by
    677   //   name lookup. Instead, any conversion function templates visible in the
    678   //   context of the use are considered. [...]
    679   const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
    680   if (!Record->isCompleteDefinition())
    681     return Found;
    682 
    683   const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
    684   for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
    685          UEnd = Unresolved->end(); U != UEnd; ++U) {
    686     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
    687     if (!ConvTemplate)
    688       continue;
    689 
    690     // When we're performing lookup for the purposes of redeclaration, just
    691     // add the conversion function template. When we deduce template
    692     // arguments for specializations, we'll end up unifying the return
    693     // type of the new declaration with the type of the function template.
    694     if (R.isForRedeclaration()) {
    695       R.addDecl(ConvTemplate);
    696       Found = true;
    697       continue;
    698     }
    699 
    700     // C++ [temp.mem]p6:
    701     //   [...] For each such operator, if argument deduction succeeds
    702     //   (14.9.2.3), the resulting specialization is used as if found by
    703     //   name lookup.
    704     //
    705     // When referencing a conversion function for any purpose other than
    706     // a redeclaration (such that we'll be building an expression with the
    707     // result), perform template argument deduction and place the
    708     // specialization into the result set. We do this to avoid forcing all
    709     // callers to perform special deduction for conversion functions.
    710     TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
    711     FunctionDecl *Specialization = 0;
    712 
    713     const FunctionProtoType *ConvProto
    714       = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
    715     assert(ConvProto && "Nonsensical conversion function template type");
    716 
    717     // Compute the type of the function that we would expect the conversion
    718     // function to have, if it were to match the name given.
    719     // FIXME: Calling convention!
    720     FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
    721     EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
    722     EPI.ExceptionSpecType = EST_None;
    723     EPI.NumExceptions = 0;
    724     QualType ExpectedType
    725       = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
    726                                             0, 0, EPI);
    727 
    728     // Perform template argument deduction against the type that we would
    729     // expect the function to have.
    730     if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
    731                                             Specialization, Info)
    732           == Sema::TDK_Success) {
    733       R.addDecl(Specialization);
    734       Found = true;
    735     }
    736   }
    737 
    738   return Found;
    739 }
    740 
    741 // Performs C++ unqualified lookup into the given file context.
    742 static bool
    743 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
    744                    DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
    745 
    746   assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
    747 
    748   // Perform direct name lookup into the LookupCtx.
    749   bool Found = LookupDirect(S, R, NS);
    750 
    751   // Perform direct name lookup into the namespaces nominated by the
    752   // using directives whose common ancestor is this namespace.
    753   UnqualUsingDirectiveSet::const_iterator UI, UEnd;
    754   llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
    755 
    756   for (; UI != UEnd; ++UI)
    757     if (LookupDirect(S, R, UI->getNominatedNamespace()))
    758       Found = true;
    759 
    760   R.resolveKind();
    761 
    762   return Found;
    763 }
    764 
    765 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
    766   if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
    767     return Ctx->isFileContext();
    768   return false;
    769 }
    770 
    771 // Find the next outer declaration context from this scope. This
    772 // routine actually returns the semantic outer context, which may
    773 // differ from the lexical context (encoded directly in the Scope
    774 // stack) when we are parsing a member of a class template. In this
    775 // case, the second element of the pair will be true, to indicate that
    776 // name lookup should continue searching in this semantic context when
    777 // it leaves the current template parameter scope.
    778 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
    779   DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
    780   DeclContext *Lexical = 0;
    781   for (Scope *OuterS = S->getParent(); OuterS;
    782        OuterS = OuterS->getParent()) {
    783     if (OuterS->getEntity()) {
    784       Lexical = static_cast<DeclContext *>(OuterS->getEntity());
    785       break;
    786     }
    787   }
    788 
    789   // C++ [temp.local]p8:
    790   //   In the definition of a member of a class template that appears
    791   //   outside of the namespace containing the class template
    792   //   definition, the name of a template-parameter hides the name of
    793   //   a member of this namespace.
    794   //
    795   // Example:
    796   //
    797   //   namespace N {
    798   //     class C { };
    799   //
    800   //     template<class T> class B {
    801   //       void f(T);
    802   //     };
    803   //   }
    804   //
    805   //   template<class C> void N::B<C>::f(C) {
    806   //     C b;  // C is the template parameter, not N::C
    807   //   }
    808   //
    809   // In this example, the lexical context we return is the
    810   // TranslationUnit, while the semantic context is the namespace N.
    811   if (!Lexical || !DC || !S->getParent() ||
    812       !S->getParent()->isTemplateParamScope())
    813     return std::make_pair(Lexical, false);
    814 
    815   // Find the outermost template parameter scope.
    816   // For the example, this is the scope for the template parameters of
    817   // template<class C>.
    818   Scope *OutermostTemplateScope = S->getParent();
    819   while (OutermostTemplateScope->getParent() &&
    820          OutermostTemplateScope->getParent()->isTemplateParamScope())
    821     OutermostTemplateScope = OutermostTemplateScope->getParent();
    822 
    823   // Find the namespace context in which the original scope occurs. In
    824   // the example, this is namespace N.
    825   DeclContext *Semantic = DC;
    826   while (!Semantic->isFileContext())
    827     Semantic = Semantic->getParent();
    828 
    829   // Find the declaration context just outside of the template
    830   // parameter scope. This is the context in which the template is
    831   // being lexically declaration (a namespace context). In the
    832   // example, this is the global scope.
    833   if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
    834       Lexical->Encloses(Semantic))
    835     return std::make_pair(Semantic, true);
    836 
    837   return std::make_pair(Lexical, false);
    838 }
    839 
    840 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
    841   assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
    842 
    843   DeclarationName Name = R.getLookupName();
    844 
    845   // If this is the name of an implicitly-declared special member function,
    846   // go through the scope stack to implicitly declare
    847   if (isImplicitlyDeclaredMemberFunctionName(Name)) {
    848     for (Scope *PreS = S; PreS; PreS = PreS->getParent())
    849       if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
    850         DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
    851   }
    852 
    853   // Implicitly declare member functions with the name we're looking for, if in
    854   // fact we are in a scope where it matters.
    855 
    856   Scope *Initial = S;
    857   IdentifierResolver::iterator
    858     I = IdResolver.begin(Name),
    859     IEnd = IdResolver.end();
    860 
    861   // First we lookup local scope.
    862   // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
    863   // ...During unqualified name lookup (3.4.1), the names appear as if
    864   // they were declared in the nearest enclosing namespace which contains
    865   // both the using-directive and the nominated namespace.
    866   // [Note: in this context, "contains" means "contains directly or
    867   // indirectly".
    868   //
    869   // For example:
    870   // namespace A { int i; }
    871   // void foo() {
    872   //   int i;
    873   //   {
    874   //     using namespace A;
    875   //     ++i; // finds local 'i', A::i appears at global scope
    876   //   }
    877   // }
    878   //
    879   DeclContext *OutsideOfTemplateParamDC = 0;
    880   for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
    881     DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
    882 
    883     // Check whether the IdResolver has anything in this scope.
    884     bool Found = false;
    885     for (; I != IEnd && S->isDeclScope(*I); ++I) {
    886       if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
    887         Found = true;
    888         R.addDecl(ND);
    889       }
    890     }
    891     if (Found) {
    892       R.resolveKind();
    893       if (S->isClassScope())
    894         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
    895           R.setNamingClass(Record);
    896       return true;
    897     }
    898 
    899     if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
    900         S->getParent() && !S->getParent()->isTemplateParamScope()) {
    901       // We've just searched the last template parameter scope and
    902       // found nothing, so look into the the contexts between the
    903       // lexical and semantic declaration contexts returned by
    904       // findOuterContext(). This implements the name lookup behavior
    905       // of C++ [temp.local]p8.
    906       Ctx = OutsideOfTemplateParamDC;
    907       OutsideOfTemplateParamDC = 0;
    908     }
    909 
    910     if (Ctx) {
    911       DeclContext *OuterCtx;
    912       bool SearchAfterTemplateScope;
    913       llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
    914       if (SearchAfterTemplateScope)
    915         OutsideOfTemplateParamDC = OuterCtx;
    916 
    917       for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
    918         // We do not directly look into transparent contexts, since
    919         // those entities will be found in the nearest enclosing
    920         // non-transparent context.
    921         if (Ctx->isTransparentContext())
    922           continue;
    923 
    924         // We do not look directly into function or method contexts,
    925         // since all of the local variables and parameters of the
    926         // function/method are present within the Scope.
    927         if (Ctx->isFunctionOrMethod()) {
    928           // If we have an Objective-C instance method, look for ivars
    929           // in the corresponding interface.
    930           if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
    931             if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
    932               if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
    933                 ObjCInterfaceDecl *ClassDeclared;
    934                 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
    935                                                  Name.getAsIdentifierInfo(),
    936                                                              ClassDeclared)) {
    937                   if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
    938                     R.addDecl(ND);
    939                     R.resolveKind();
    940                     return true;
    941                   }
    942                 }
    943               }
    944           }
    945 
    946           continue;
    947         }
    948 
    949         // Perform qualified name lookup into this context.
    950         // FIXME: In some cases, we know that every name that could be found by
    951         // this qualified name lookup will also be on the identifier chain. For
    952         // example, inside a class without any base classes, we never need to
    953         // perform qualified lookup because all of the members are on top of the
    954         // identifier chain.
    955         if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
    956           return true;
    957       }
    958     }
    959   }
    960 
    961   // Stop if we ran out of scopes.
    962   // FIXME:  This really, really shouldn't be happening.
    963   if (!S) return false;
    964 
    965   // If we are looking for members, no need to look into global/namespace scope.
    966   if (R.getLookupKind() == LookupMemberName)
    967     return false;
    968 
    969   // Collect UsingDirectiveDecls in all scopes, and recursively all
    970   // nominated namespaces by those using-directives.
    971   //
    972   // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
    973   // don't build it for each lookup!
    974 
    975   UnqualUsingDirectiveSet UDirs;
    976   UDirs.visitScopeChain(Initial, S);
    977   UDirs.done();
    978 
    979   // Lookup namespace scope, and global scope.
    980   // Unqualified name lookup in C++ requires looking into scopes
    981   // that aren't strictly lexical, and therefore we walk through the
    982   // context as well as walking through the scopes.
    983 
    984   for (; S; S = S->getParent()) {
    985     // Check whether the IdResolver has anything in this scope.
    986     bool Found = false;
    987     for (; I != IEnd && S->isDeclScope(*I); ++I) {
    988       if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
    989         // We found something.  Look for anything else in our scope
    990         // with this same name and in an acceptable identifier
    991         // namespace, so that we can construct an overload set if we
    992         // need to.
    993         Found = true;
    994         R.addDecl(ND);
    995       }
    996     }
    997 
    998     if (Found && S->isTemplateParamScope()) {
    999       R.resolveKind();
   1000       return true;
   1001     }
   1002 
   1003     DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
   1004     if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
   1005         S->getParent() && !S->getParent()->isTemplateParamScope()) {
   1006       // We've just searched the last template parameter scope and
   1007       // found nothing, so look into the the contexts between the
   1008       // lexical and semantic declaration contexts returned by
   1009       // findOuterContext(). This implements the name lookup behavior
   1010       // of C++ [temp.local]p8.
   1011       Ctx = OutsideOfTemplateParamDC;
   1012       OutsideOfTemplateParamDC = 0;
   1013     }
   1014 
   1015     if (Ctx) {
   1016       DeclContext *OuterCtx;
   1017       bool SearchAfterTemplateScope;
   1018       llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
   1019       if (SearchAfterTemplateScope)
   1020         OutsideOfTemplateParamDC = OuterCtx;
   1021 
   1022       for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
   1023         // We do not directly look into transparent contexts, since
   1024         // those entities will be found in the nearest enclosing
   1025         // non-transparent context.
   1026         if (Ctx->isTransparentContext())
   1027           continue;
   1028 
   1029         // If we have a context, and it's not a context stashed in the
   1030         // template parameter scope for an out-of-line definition, also
   1031         // look into that context.
   1032         if (!(Found && S && S->isTemplateParamScope())) {
   1033           assert(Ctx->isFileContext() &&
   1034               "We should have been looking only at file context here already.");
   1035 
   1036           // Look into context considering using-directives.
   1037           if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
   1038             Found = true;
   1039         }
   1040 
   1041         if (Found) {
   1042           R.resolveKind();
   1043           return true;
   1044         }
   1045 
   1046         if (R.isForRedeclaration() && !Ctx->isTransparentContext())
   1047           return false;
   1048       }
   1049     }
   1050 
   1051     if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
   1052       return false;
   1053   }
   1054 
   1055   return !R.empty();
   1056 }
   1057 
   1058 /// \brief Retrieve the visible declaration corresponding to D, if any.
   1059 ///
   1060 /// This routine determines whether the declaration D is visible in the current
   1061 /// module, with the current imports. If not, it checks whether any
   1062 /// redeclaration of D is visible, and if so, returns that declaration.
   1063 ///
   1064 /// \returns D, or a visible previous declaration of D, whichever is more recent
   1065 /// and visible. If no declaration of D is visible, returns null.
   1066 static NamedDecl *getVisibleDecl(NamedDecl *D) {
   1067   if (LookupResult::isVisible(D))
   1068     return D;
   1069 
   1070   for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
   1071        RD != RDEnd; ++RD) {
   1072     if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
   1073       if (LookupResult::isVisible(ND))
   1074         return ND;
   1075     }
   1076   }
   1077 
   1078   return 0;
   1079 }
   1080 
   1081 /// @brief Perform unqualified name lookup starting from a given
   1082 /// scope.
   1083 ///
   1084 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
   1085 /// used to find names within the current scope. For example, 'x' in
   1086 /// @code
   1087 /// int x;
   1088 /// int f() {
   1089 ///   return x; // unqualified name look finds 'x' in the global scope
   1090 /// }
   1091 /// @endcode
   1092 ///
   1093 /// Different lookup criteria can find different names. For example, a
   1094 /// particular scope can have both a struct and a function of the same
   1095 /// name, and each can be found by certain lookup criteria. For more
   1096 /// information about lookup criteria, see the documentation for the
   1097 /// class LookupCriteria.
   1098 ///
   1099 /// @param S        The scope from which unqualified name lookup will
   1100 /// begin. If the lookup criteria permits, name lookup may also search
   1101 /// in the parent scopes.
   1102 ///
   1103 /// @param Name     The name of the entity that we are searching for.
   1104 ///
   1105 /// @param Loc      If provided, the source location where we're performing
   1106 /// name lookup. At present, this is only used to produce diagnostics when
   1107 /// C library functions (like "malloc") are implicitly declared.
   1108 ///
   1109 /// @returns The result of name lookup, which includes zero or more
   1110 /// declarations and possibly additional information used to diagnose
   1111 /// ambiguities.
   1112 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
   1113   DeclarationName Name = R.getLookupName();
   1114   if (!Name) return false;
   1115 
   1116   LookupNameKind NameKind = R.getLookupKind();
   1117 
   1118   if (!getLangOpts().CPlusPlus) {
   1119     // Unqualified name lookup in C/Objective-C is purely lexical, so
   1120     // search in the declarations attached to the name.
   1121     if (NameKind == Sema::LookupRedeclarationWithLinkage) {
   1122       // Find the nearest non-transparent declaration scope.
   1123       while (!(S->getFlags() & Scope::DeclScope) ||
   1124              (S->getEntity() &&
   1125               static_cast<DeclContext *>(S->getEntity())
   1126                 ->isTransparentContext()))
   1127         S = S->getParent();
   1128     }
   1129 
   1130     unsigned IDNS = R.getIdentifierNamespace();
   1131 
   1132     // Scan up the scope chain looking for a decl that matches this
   1133     // identifier that is in the appropriate namespace.  This search
   1134     // should not take long, as shadowing of names is uncommon, and
   1135     // deep shadowing is extremely uncommon.
   1136     bool LeftStartingScope = false;
   1137 
   1138     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
   1139                                    IEnd = IdResolver.end();
   1140          I != IEnd; ++I)
   1141       if ((*I)->isInIdentifierNamespace(IDNS)) {
   1142         if (NameKind == LookupRedeclarationWithLinkage) {
   1143           // Determine whether this (or a previous) declaration is
   1144           // out-of-scope.
   1145           if (!LeftStartingScope && !S->isDeclScope(*I))
   1146             LeftStartingScope = true;
   1147 
   1148           // If we found something outside of our starting scope that
   1149           // does not have linkage, skip it.
   1150           if (LeftStartingScope && !((*I)->hasLinkage()))
   1151             continue;
   1152         }
   1153         else if (NameKind == LookupObjCImplicitSelfParam &&
   1154                  !isa<ImplicitParamDecl>(*I))
   1155           continue;
   1156 
   1157         // If this declaration is module-private and it came from an AST
   1158         // file, we can't see it.
   1159         NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
   1160         if (!D)
   1161           continue;
   1162 
   1163         R.addDecl(D);
   1164 
   1165         // Check whether there are any other declarations with the same name
   1166         // and in the same scope.
   1167         if (I != IEnd) {
   1168           // Find the scope in which this declaration was declared (if it
   1169           // actually exists in a Scope).
   1170           while (S && !S->isDeclScope(D))
   1171             S = S->getParent();
   1172 
   1173           // If the scope containing the declaration is the translation unit,
   1174           // then we'll need to perform our checks based on the matching
   1175           // DeclContexts rather than matching scopes.
   1176           if (S && isNamespaceOrTranslationUnitScope(S))
   1177             S = 0;
   1178 
   1179           // Compute the DeclContext, if we need it.
   1180           DeclContext *DC = 0;
   1181           if (!S)
   1182             DC = (*I)->getDeclContext()->getRedeclContext();
   1183 
   1184           IdentifierResolver::iterator LastI = I;
   1185           for (++LastI; LastI != IEnd; ++LastI) {
   1186             if (S) {
   1187               // Match based on scope.
   1188               if (!S->isDeclScope(*LastI))
   1189                 break;
   1190             } else {
   1191               // Match based on DeclContext.
   1192               DeclContext *LastDC
   1193                 = (*LastI)->getDeclContext()->getRedeclContext();
   1194               if (!LastDC->Equals(DC))
   1195                 break;
   1196             }
   1197 
   1198             // If the declaration isn't in the right namespace, skip it.
   1199             if (!(*LastI)->isInIdentifierNamespace(IDNS))
   1200               continue;
   1201 
   1202             D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
   1203             if (D)
   1204               R.addDecl(D);
   1205           }
   1206 
   1207           R.resolveKind();
   1208         }
   1209         return true;
   1210       }
   1211   } else {
   1212     // Perform C++ unqualified name lookup.
   1213     if (CppLookupName(R, S))
   1214       return true;
   1215   }
   1216 
   1217   // If we didn't find a use of this identifier, and if the identifier
   1218   // corresponds to a compiler builtin, create the decl object for the builtin
   1219   // now, injecting it into translation unit scope, and return it.
   1220   if (AllowBuiltinCreation && LookupBuiltin(*this, R))
   1221     return true;
   1222 
   1223   // If we didn't find a use of this identifier, the ExternalSource
   1224   // may be able to handle the situation.
   1225   // Note: some lookup failures are expected!
   1226   // See e.g. R.isForRedeclaration().
   1227   return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
   1228 }
   1229 
   1230 /// @brief Perform qualified name lookup in the namespaces nominated by
   1231 /// using directives by the given context.
   1232 ///
   1233 /// C++98 [namespace.qual]p2:
   1234 ///   Given X::m (where X is a user-declared namespace), or given ::m
   1235 ///   (where X is the global namespace), let S be the set of all
   1236 ///   declarations of m in X and in the transitive closure of all
   1237 ///   namespaces nominated by using-directives in X and its used
   1238 ///   namespaces, except that using-directives are ignored in any
   1239 ///   namespace, including X, directly containing one or more
   1240 ///   declarations of m. No namespace is searched more than once in
   1241 ///   the lookup of a name. If S is the empty set, the program is
   1242 ///   ill-formed. Otherwise, if S has exactly one member, or if the
   1243 ///   context of the reference is a using-declaration
   1244 ///   (namespace.udecl), S is the required set of declarations of
   1245 ///   m. Otherwise if the use of m is not one that allows a unique
   1246 ///   declaration to be chosen from S, the program is ill-formed.
   1247 /// C++98 [namespace.qual]p5:
   1248 ///   During the lookup of a qualified namespace member name, if the
   1249 ///   lookup finds more than one declaration of the member, and if one
   1250 ///   declaration introduces a class name or enumeration name and the
   1251 ///   other declarations either introduce the same object, the same
   1252 ///   enumerator or a set of functions, the non-type name hides the
   1253 ///   class or enumeration name if and only if the declarations are
   1254 ///   from the same namespace; otherwise (the declarations are from
   1255 ///   different namespaces), the program is ill-formed.
   1256 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
   1257                                                  DeclContext *StartDC) {
   1258   assert(StartDC->isFileContext() && "start context is not a file context");
   1259 
   1260   DeclContext::udir_iterator I = StartDC->using_directives_begin();
   1261   DeclContext::udir_iterator E = StartDC->using_directives_end();
   1262 
   1263   if (I == E) return false;
   1264 
   1265   // We have at least added all these contexts to the queue.
   1266   llvm::SmallPtrSet<DeclContext*, 8> Visited;
   1267   Visited.insert(StartDC);
   1268 
   1269   // We have not yet looked into these namespaces, much less added
   1270   // their "using-children" to the queue.
   1271   SmallVector<NamespaceDecl*, 8> Queue;
   1272 
   1273   // We have already looked into the initial namespace; seed the queue
   1274   // with its using-children.
   1275   for (; I != E; ++I) {
   1276     NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
   1277     if (Visited.insert(ND))
   1278       Queue.push_back(ND);
   1279   }
   1280 
   1281   // The easiest way to implement the restriction in [namespace.qual]p5
   1282   // is to check whether any of the individual results found a tag
   1283   // and, if so, to declare an ambiguity if the final result is not
   1284   // a tag.
   1285   bool FoundTag = false;
   1286   bool FoundNonTag = false;
   1287 
   1288   LookupResult LocalR(LookupResult::Temporary, R);
   1289 
   1290   bool Found = false;
   1291   while (!Queue.empty()) {
   1292     NamespaceDecl *ND = Queue.back();
   1293     Queue.pop_back();
   1294 
   1295     // We go through some convolutions here to avoid copying results
   1296     // between LookupResults.
   1297     bool UseLocal = !R.empty();
   1298     LookupResult &DirectR = UseLocal ? LocalR : R;
   1299     bool FoundDirect = LookupDirect(S, DirectR, ND);
   1300 
   1301     if (FoundDirect) {
   1302       // First do any local hiding.
   1303       DirectR.resolveKind();
   1304 
   1305       // If the local result is a tag, remember that.
   1306       if (DirectR.isSingleTagDecl())
   1307         FoundTag = true;
   1308       else
   1309         FoundNonTag = true;
   1310 
   1311       // Append the local results to the total results if necessary.
   1312       if (UseLocal) {
   1313         R.addAllDecls(LocalR);
   1314         LocalR.clear();
   1315       }
   1316     }
   1317 
   1318     // If we find names in this namespace, ignore its using directives.
   1319     if (FoundDirect) {
   1320       Found = true;
   1321       continue;
   1322     }
   1323 
   1324     for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
   1325       NamespaceDecl *Nom = (*I)->getNominatedNamespace();
   1326       if (Visited.insert(Nom))
   1327         Queue.push_back(Nom);
   1328     }
   1329   }
   1330 
   1331   if (Found) {
   1332     if (FoundTag && FoundNonTag)
   1333       R.setAmbiguousQualifiedTagHiding();
   1334     else
   1335       R.resolveKind();
   1336   }
   1337 
   1338   return Found;
   1339 }
   1340 
   1341 /// \brief Callback that looks for any member of a class with the given name.
   1342 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
   1343                             CXXBasePath &Path,
   1344                             void *Name) {
   1345   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
   1346 
   1347   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
   1348   Path.Decls = BaseRecord->lookup(N);
   1349   return Path.Decls.first != Path.Decls.second;
   1350 }
   1351 
   1352 /// \brief Determine whether the given set of member declarations contains only
   1353 /// static members, nested types, and enumerators.
   1354 template<typename InputIterator>
   1355 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
   1356   Decl *D = (*First)->getUnderlyingDecl();
   1357   if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
   1358     return true;
   1359 
   1360   if (isa<CXXMethodDecl>(D)) {
   1361     // Determine whether all of the methods are static.
   1362     bool AllMethodsAreStatic = true;
   1363     for(; First != Last; ++First) {
   1364       D = (*First)->getUnderlyingDecl();
   1365 
   1366       if (!isa<CXXMethodDecl>(D)) {
   1367         assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
   1368         break;
   1369       }
   1370 
   1371       if (!cast<CXXMethodDecl>(D)->isStatic()) {
   1372         AllMethodsAreStatic = false;
   1373         break;
   1374       }
   1375     }
   1376 
   1377     if (AllMethodsAreStatic)
   1378       return true;
   1379   }
   1380 
   1381   return false;
   1382 }
   1383 
   1384 /// \brief Perform qualified name lookup into a given context.
   1385 ///
   1386 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
   1387 /// names when the context of those names is explicit specified, e.g.,
   1388 /// "std::vector" or "x->member", or as part of unqualified name lookup.
   1389 ///
   1390 /// Different lookup criteria can find different names. For example, a
   1391 /// particular scope can have both a struct and a function of the same
   1392 /// name, and each can be found by certain lookup criteria. For more
   1393 /// information about lookup criteria, see the documentation for the
   1394 /// class LookupCriteria.
   1395 ///
   1396 /// \param R captures both the lookup criteria and any lookup results found.
   1397 ///
   1398 /// \param LookupCtx The context in which qualified name lookup will
   1399 /// search. If the lookup criteria permits, name lookup may also search
   1400 /// in the parent contexts or (for C++ classes) base classes.
   1401 ///
   1402 /// \param InUnqualifiedLookup true if this is qualified name lookup that
   1403 /// occurs as part of unqualified name lookup.
   1404 ///
   1405 /// \returns true if lookup succeeded, false if it failed.
   1406 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
   1407                                bool InUnqualifiedLookup) {
   1408   assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
   1409 
   1410   if (!R.getLookupName())
   1411     return false;
   1412 
   1413   // Make sure that the declaration context is complete.
   1414   assert((!isa<TagDecl>(LookupCtx) ||
   1415           LookupCtx->isDependentContext() ||
   1416           cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
   1417           cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
   1418          "Declaration context must already be complete!");
   1419 
   1420   // Perform qualified name lookup into the LookupCtx.
   1421   if (LookupDirect(*this, R, LookupCtx)) {
   1422     R.resolveKind();
   1423     if (isa<CXXRecordDecl>(LookupCtx))
   1424       R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
   1425     return true;
   1426   }
   1427 
   1428   // Don't descend into implied contexts for redeclarations.
   1429   // C++98 [namespace.qual]p6:
   1430   //   In a declaration for a namespace member in which the
   1431   //   declarator-id is a qualified-id, given that the qualified-id
   1432   //   for the namespace member has the form
   1433   //     nested-name-specifier unqualified-id
   1434   //   the unqualified-id shall name a member of the namespace
   1435   //   designated by the nested-name-specifier.
   1436   // See also [class.mfct]p5 and [class.static.data]p2.
   1437   if (R.isForRedeclaration())
   1438     return false;
   1439 
   1440   // If this is a namespace, look it up in the implied namespaces.
   1441   if (LookupCtx->isFileContext())
   1442     return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
   1443 
   1444   // If this isn't a C++ class, we aren't allowed to look into base
   1445   // classes, we're done.
   1446   CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
   1447   if (!LookupRec || !LookupRec->getDefinition())
   1448     return false;
   1449 
   1450   // If we're performing qualified name lookup into a dependent class,
   1451   // then we are actually looking into a current instantiation. If we have any
   1452   // dependent base classes, then we either have to delay lookup until
   1453   // template instantiation time (at which point all bases will be available)
   1454   // or we have to fail.
   1455   if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
   1456       LookupRec->hasAnyDependentBases()) {
   1457     R.setNotFoundInCurrentInstantiation();
   1458     return false;
   1459   }
   1460 
   1461   // Perform lookup into our base classes.
   1462   CXXBasePaths Paths;
   1463   Paths.setOrigin(LookupRec);
   1464 
   1465   // Look for this member in our base classes
   1466   CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
   1467   switch (R.getLookupKind()) {
   1468     case LookupObjCImplicitSelfParam:
   1469     case LookupOrdinaryName:
   1470     case LookupMemberName:
   1471     case LookupRedeclarationWithLinkage:
   1472       BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
   1473       break;
   1474 
   1475     case LookupTagName:
   1476       BaseCallback = &CXXRecordDecl::FindTagMember;
   1477       break;
   1478 
   1479     case LookupAnyName:
   1480       BaseCallback = &LookupAnyMember;
   1481       break;
   1482 
   1483     case LookupUsingDeclName:
   1484       // This lookup is for redeclarations only.
   1485 
   1486     case LookupOperatorName:
   1487     case LookupNamespaceName:
   1488     case LookupObjCProtocolName:
   1489     case LookupLabel:
   1490       // These lookups will never find a member in a C++ class (or base class).
   1491       return false;
   1492 
   1493     case LookupNestedNameSpecifierName:
   1494       BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
   1495       break;
   1496   }
   1497 
   1498   if (!LookupRec->lookupInBases(BaseCallback,
   1499                                 R.getLookupName().getAsOpaquePtr(), Paths))
   1500     return false;
   1501 
   1502   R.setNamingClass(LookupRec);
   1503 
   1504   // C++ [class.member.lookup]p2:
   1505   //   [...] If the resulting set of declarations are not all from
   1506   //   sub-objects of the same type, or the set has a nonstatic member
   1507   //   and includes members from distinct sub-objects, there is an
   1508   //   ambiguity and the program is ill-formed. Otherwise that set is
   1509   //   the result of the lookup.
   1510   QualType SubobjectType;
   1511   int SubobjectNumber = 0;
   1512   AccessSpecifier SubobjectAccess = AS_none;
   1513 
   1514   for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
   1515        Path != PathEnd; ++Path) {
   1516     const CXXBasePathElement &PathElement = Path->back();
   1517 
   1518     // Pick the best (i.e. most permissive i.e. numerically lowest) access
   1519     // across all paths.
   1520     SubobjectAccess = std::min(SubobjectAccess, Path->Access);
   1521 
   1522     // Determine whether we're looking at a distinct sub-object or not.
   1523     if (SubobjectType.isNull()) {
   1524       // This is the first subobject we've looked at. Record its type.
   1525       SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
   1526       SubobjectNumber = PathElement.SubobjectNumber;
   1527       continue;
   1528     }
   1529 
   1530     if (SubobjectType
   1531                  != Context.getCanonicalType(PathElement.Base->getType())) {
   1532       // We found members of the given name in two subobjects of
   1533       // different types. If the declaration sets aren't the same, this
   1534       // this lookup is ambiguous.
   1535       if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
   1536         CXXBasePaths::paths_iterator FirstPath = Paths.begin();
   1537         DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
   1538         DeclContext::lookup_iterator CurrentD = Path->Decls.first;
   1539 
   1540         while (FirstD != FirstPath->Decls.second &&
   1541                CurrentD != Path->Decls.second) {
   1542          if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
   1543              (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
   1544            break;
   1545 
   1546           ++FirstD;
   1547           ++CurrentD;
   1548         }
   1549 
   1550         if (FirstD == FirstPath->Decls.second &&
   1551             CurrentD == Path->Decls.second)
   1552           continue;
   1553       }
   1554 
   1555       R.setAmbiguousBaseSubobjectTypes(Paths);
   1556       return true;
   1557     }
   1558 
   1559     if (SubobjectNumber != PathElement.SubobjectNumber) {
   1560       // We have a different subobject of the same type.
   1561 
   1562       // C++ [class.member.lookup]p5:
   1563       //   A static member, a nested type or an enumerator defined in
   1564       //   a base class T can unambiguously be found even if an object
   1565       //   has more than one base class subobject of type T.
   1566       if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
   1567         continue;
   1568 
   1569       // We have found a nonstatic member name in multiple, distinct
   1570       // subobjects. Name lookup is ambiguous.
   1571       R.setAmbiguousBaseSubobjects(Paths);
   1572       return true;
   1573     }
   1574   }
   1575 
   1576   // Lookup in a base class succeeded; return these results.
   1577 
   1578   DeclContext::lookup_iterator I, E;
   1579   for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
   1580     NamedDecl *D = *I;
   1581     AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
   1582                                                     D->getAccess());
   1583     R.addDecl(D, AS);
   1584   }
   1585   R.resolveKind();
   1586   return true;
   1587 }
   1588 
   1589 /// @brief Performs name lookup for a name that was parsed in the
   1590 /// source code, and may contain a C++ scope specifier.
   1591 ///
   1592 /// This routine is a convenience routine meant to be called from
   1593 /// contexts that receive a name and an optional C++ scope specifier
   1594 /// (e.g., "N::M::x"). It will then perform either qualified or
   1595 /// unqualified name lookup (with LookupQualifiedName or LookupName,
   1596 /// respectively) on the given name and return those results.
   1597 ///
   1598 /// @param S        The scope from which unqualified name lookup will
   1599 /// begin.
   1600 ///
   1601 /// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
   1602 ///
   1603 /// @param EnteringContext Indicates whether we are going to enter the
   1604 /// context of the scope-specifier SS (if present).
   1605 ///
   1606 /// @returns True if any decls were found (but possibly ambiguous)
   1607 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
   1608                             bool AllowBuiltinCreation, bool EnteringContext) {
   1609   if (SS && SS->isInvalid()) {
   1610     // When the scope specifier is invalid, don't even look for
   1611     // anything.
   1612     return false;
   1613   }
   1614 
   1615   if (SS && SS->isSet()) {
   1616     if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
   1617       // We have resolved the scope specifier to a particular declaration
   1618       // contex, and will perform name lookup in that context.
   1619       if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
   1620         return false;
   1621 
   1622       R.setContextRange(SS->getRange());
   1623       return LookupQualifiedName(R, DC);
   1624     }
   1625 
   1626     // We could not resolve the scope specified to a specific declaration
   1627     // context, which means that SS refers to an unknown specialization.
   1628     // Name lookup can't find anything in this case.
   1629     R.setNotFoundInCurrentInstantiation();
   1630     R.setContextRange(SS->getRange());
   1631     return false;
   1632   }
   1633 
   1634   // Perform unqualified name lookup starting in the given scope.
   1635   return LookupName(R, S, AllowBuiltinCreation);
   1636 }
   1637 
   1638 
   1639 /// @brief Produce a diagnostic describing the ambiguity that resulted
   1640 /// from name lookup.
   1641 ///
   1642 /// @param Result       The ambiguous name lookup result.
   1643 ///
   1644 /// @param Name         The name of the entity that name lookup was
   1645 /// searching for.
   1646 ///
   1647 /// @param NameLoc      The location of the name within the source code.
   1648 ///
   1649 /// @param LookupRange  A source range that provides more
   1650 /// source-location information concerning the lookup itself. For
   1651 /// example, this range might highlight a nested-name-specifier that
   1652 /// precedes the name.
   1653 ///
   1654 /// @returns true
   1655 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
   1656   assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
   1657 
   1658   DeclarationName Name = Result.getLookupName();
   1659   SourceLocation NameLoc = Result.getNameLoc();
   1660   SourceRange LookupRange = Result.getContextRange();
   1661 
   1662   switch (Result.getAmbiguityKind()) {
   1663   case LookupResult::AmbiguousBaseSubobjects: {
   1664     CXXBasePaths *Paths = Result.getBasePaths();
   1665     QualType SubobjectType = Paths->front().back().Base->getType();
   1666     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
   1667       << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
   1668       << LookupRange;
   1669 
   1670     DeclContext::lookup_iterator Found = Paths->front().Decls.first;
   1671     while (isa<CXXMethodDecl>(*Found) &&
   1672            cast<CXXMethodDecl>(*Found)->isStatic())
   1673       ++Found;
   1674 
   1675     Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
   1676 
   1677     return true;
   1678   }
   1679 
   1680   case LookupResult::AmbiguousBaseSubobjectTypes: {
   1681     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
   1682       << Name << LookupRange;
   1683 
   1684     CXXBasePaths *Paths = Result.getBasePaths();
   1685     std::set<Decl *> DeclsPrinted;
   1686     for (CXXBasePaths::paths_iterator Path = Paths->begin(),
   1687                                       PathEnd = Paths->end();
   1688          Path != PathEnd; ++Path) {
   1689       Decl *D = *Path->Decls.first;
   1690       if (DeclsPrinted.insert(D).second)
   1691         Diag(D->getLocation(), diag::note_ambiguous_member_found);
   1692     }
   1693 
   1694     return true;
   1695   }
   1696 
   1697   case LookupResult::AmbiguousTagHiding: {
   1698     Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
   1699 
   1700     llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
   1701 
   1702     LookupResult::iterator DI, DE = Result.end();
   1703     for (DI = Result.begin(); DI != DE; ++DI)
   1704       if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
   1705         TagDecls.insert(TD);
   1706         Diag(TD->getLocation(), diag::note_hidden_tag);
   1707       }
   1708 
   1709     for (DI = Result.begin(); DI != DE; ++DI)
   1710       if (!isa<TagDecl>(*DI))
   1711         Diag((*DI)->getLocation(), diag::note_hiding_object);
   1712 
   1713     // For recovery purposes, go ahead and implement the hiding.
   1714     LookupResult::Filter F = Result.makeFilter();
   1715     while (F.hasNext()) {
   1716       if (TagDecls.count(F.next()))
   1717         F.erase();
   1718     }
   1719     F.done();
   1720 
   1721     return true;
   1722   }
   1723 
   1724   case LookupResult::AmbiguousReference: {
   1725     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
   1726 
   1727     LookupResult::iterator DI = Result.begin(), DE = Result.end();
   1728     for (; DI != DE; ++DI)
   1729       Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
   1730 
   1731     return true;
   1732   }
   1733   }
   1734 
   1735   llvm_unreachable("unknown ambiguity kind");
   1736 }
   1737 
   1738 namespace {
   1739   struct AssociatedLookup {
   1740     AssociatedLookup(Sema &S,
   1741                      Sema::AssociatedNamespaceSet &Namespaces,
   1742                      Sema::AssociatedClassSet &Classes)
   1743       : S(S), Namespaces(Namespaces), Classes(Classes) {
   1744     }
   1745 
   1746     Sema &S;
   1747     Sema::AssociatedNamespaceSet &Namespaces;
   1748     Sema::AssociatedClassSet &Classes;
   1749   };
   1750 }
   1751 
   1752 static void
   1753 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
   1754 
   1755 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
   1756                                       DeclContext *Ctx) {
   1757   // Add the associated namespace for this class.
   1758 
   1759   // We don't use DeclContext::getEnclosingNamespaceContext() as this may
   1760   // be a locally scoped record.
   1761 
   1762   // We skip out of inline namespaces. The innermost non-inline namespace
   1763   // contains all names of all its nested inline namespaces anyway, so we can
   1764   // replace the entire inline namespace tree with its root.
   1765   while (Ctx->isRecord() || Ctx->isTransparentContext() ||
   1766          Ctx->isInlineNamespace())
   1767     Ctx = Ctx->getParent();
   1768 
   1769   if (Ctx->isFileContext())
   1770     Namespaces.insert(Ctx->getPrimaryContext());
   1771 }
   1772 
   1773 // \brief Add the associated classes and namespaces for argument-dependent
   1774 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
   1775 static void
   1776 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
   1777                                   const TemplateArgument &Arg) {
   1778   // C++ [basic.lookup.koenig]p2, last bullet:
   1779   //   -- [...] ;
   1780   switch (Arg.getKind()) {
   1781     case TemplateArgument::Null:
   1782       break;
   1783 
   1784     case TemplateArgument::Type:
   1785       // [...] the namespaces and classes associated with the types of the
   1786       // template arguments provided for template type parameters (excluding
   1787       // template template parameters)
   1788       addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
   1789       break;
   1790 
   1791     case TemplateArgument::Template:
   1792     case TemplateArgument::TemplateExpansion: {
   1793       // [...] the namespaces in which any template template arguments are
   1794       // defined; and the classes in which any member templates used as
   1795       // template template arguments are defined.
   1796       TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
   1797       if (ClassTemplateDecl *ClassTemplate
   1798                  = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
   1799         DeclContext *Ctx = ClassTemplate->getDeclContext();
   1800         if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1801           Result.Classes.insert(EnclosingClass);
   1802         // Add the associated namespace for this class.
   1803         CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1804       }
   1805       break;
   1806     }
   1807 
   1808     case TemplateArgument::Declaration:
   1809     case TemplateArgument::Integral:
   1810     case TemplateArgument::Expression:
   1811       // [Note: non-type template arguments do not contribute to the set of
   1812       //  associated namespaces. ]
   1813       break;
   1814 
   1815     case TemplateArgument::Pack:
   1816       for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
   1817                                         PEnd = Arg.pack_end();
   1818            P != PEnd; ++P)
   1819         addAssociatedClassesAndNamespaces(Result, *P);
   1820       break;
   1821   }
   1822 }
   1823 
   1824 // \brief Add the associated classes and namespaces for
   1825 // argument-dependent lookup with an argument of class type
   1826 // (C++ [basic.lookup.koenig]p2).
   1827 static void
   1828 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
   1829                                   CXXRecordDecl *Class) {
   1830 
   1831   // Just silently ignore anything whose name is __va_list_tag.
   1832   if (Class->getDeclName() == Result.S.VAListTagName)
   1833     return;
   1834 
   1835   // C++ [basic.lookup.koenig]p2:
   1836   //   [...]
   1837   //     -- If T is a class type (including unions), its associated
   1838   //        classes are: the class itself; the class of which it is a
   1839   //        member, if any; and its direct and indirect base
   1840   //        classes. Its associated namespaces are the namespaces in
   1841   //        which its associated classes are defined.
   1842 
   1843   // Add the class of which it is a member, if any.
   1844   DeclContext *Ctx = Class->getDeclContext();
   1845   if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1846     Result.Classes.insert(EnclosingClass);
   1847   // Add the associated namespace for this class.
   1848   CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1849 
   1850   // Add the class itself. If we've already seen this class, we don't
   1851   // need to visit base classes.
   1852   if (!Result.Classes.insert(Class))
   1853     return;
   1854 
   1855   // -- If T is a template-id, its associated namespaces and classes are
   1856   //    the namespace in which the template is defined; for member
   1857   //    templates, the member template's class; the namespaces and classes
   1858   //    associated with the types of the template arguments provided for
   1859   //    template type parameters (excluding template template parameters); the
   1860   //    namespaces in which any template template arguments are defined; and
   1861   //    the classes in which any member templates used as template template
   1862   //    arguments are defined. [Note: non-type template arguments do not
   1863   //    contribute to the set of associated namespaces. ]
   1864   if (ClassTemplateSpecializationDecl *Spec
   1865         = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
   1866     DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
   1867     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1868       Result.Classes.insert(EnclosingClass);
   1869     // Add the associated namespace for this class.
   1870     CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1871 
   1872     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
   1873     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
   1874       addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
   1875   }
   1876 
   1877   // Only recurse into base classes for complete types.
   1878   if (!Class->hasDefinition()) {
   1879     // FIXME: we might need to instantiate templates here
   1880     return;
   1881   }
   1882 
   1883   // Add direct and indirect base classes along with their associated
   1884   // namespaces.
   1885   SmallVector<CXXRecordDecl *, 32> Bases;
   1886   Bases.push_back(Class);
   1887   while (!Bases.empty()) {
   1888     // Pop this class off the stack.
   1889     Class = Bases.back();
   1890     Bases.pop_back();
   1891 
   1892     // Visit the base classes.
   1893     for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
   1894                                          BaseEnd = Class->bases_end();
   1895          Base != BaseEnd; ++Base) {
   1896       const RecordType *BaseType = Base->getType()->getAs<RecordType>();
   1897       // In dependent contexts, we do ADL twice, and the first time around,
   1898       // the base type might be a dependent TemplateSpecializationType, or a
   1899       // TemplateTypeParmType. If that happens, simply ignore it.
   1900       // FIXME: If we want to support export, we probably need to add the
   1901       // namespace of the template in a TemplateSpecializationType, or even
   1902       // the classes and namespaces of known non-dependent arguments.
   1903       if (!BaseType)
   1904         continue;
   1905       CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   1906       if (Result.Classes.insert(BaseDecl)) {
   1907         // Find the associated namespace for this base class.
   1908         DeclContext *BaseCtx = BaseDecl->getDeclContext();
   1909         CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
   1910 
   1911         // Make sure we visit the bases of this base class.
   1912         if (BaseDecl->bases_begin() != BaseDecl->bases_end())
   1913           Bases.push_back(BaseDecl);
   1914       }
   1915     }
   1916   }
   1917 }
   1918 
   1919 // \brief Add the associated classes and namespaces for
   1920 // argument-dependent lookup with an argument of type T
   1921 // (C++ [basic.lookup.koenig]p2).
   1922 static void
   1923 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
   1924   // C++ [basic.lookup.koenig]p2:
   1925   //
   1926   //   For each argument type T in the function call, there is a set
   1927   //   of zero or more associated namespaces and a set of zero or more
   1928   //   associated classes to be considered. The sets of namespaces and
   1929   //   classes is determined entirely by the types of the function
   1930   //   arguments (and the namespace of any template template
   1931   //   argument). Typedef names and using-declarations used to specify
   1932   //   the types do not contribute to this set. The sets of namespaces
   1933   //   and classes are determined in the following way:
   1934 
   1935   SmallVector<const Type *, 16> Queue;
   1936   const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
   1937 
   1938   while (true) {
   1939     switch (T->getTypeClass()) {
   1940 
   1941 #define TYPE(Class, Base)
   1942 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
   1943 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
   1944 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
   1945 #define ABSTRACT_TYPE(Class, Base)
   1946 #include "clang/AST/TypeNodes.def"
   1947       // T is canonical.  We can also ignore dependent types because
   1948       // we don't need to do ADL at the definition point, but if we
   1949       // wanted to implement template export (or if we find some other
   1950       // use for associated classes and namespaces...) this would be
   1951       // wrong.
   1952       break;
   1953 
   1954     //    -- If T is a pointer to U or an array of U, its associated
   1955     //       namespaces and classes are those associated with U.
   1956     case Type::Pointer:
   1957       T = cast<PointerType>(T)->getPointeeType().getTypePtr();
   1958       continue;
   1959     case Type::ConstantArray:
   1960     case Type::IncompleteArray:
   1961     case Type::VariableArray:
   1962       T = cast<ArrayType>(T)->getElementType().getTypePtr();
   1963       continue;
   1964 
   1965     //     -- If T is a fundamental type, its associated sets of
   1966     //        namespaces and classes are both empty.
   1967     case Type::Builtin:
   1968       break;
   1969 
   1970     //     -- If T is a class type (including unions), its associated
   1971     //        classes are: the class itself; the class of which it is a
   1972     //        member, if any; and its direct and indirect base
   1973     //        classes. Its associated namespaces are the namespaces in
   1974     //        which its associated classes are defined.
   1975     case Type::Record: {
   1976       CXXRecordDecl *Class
   1977         = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
   1978       addAssociatedClassesAndNamespaces(Result, Class);
   1979       break;
   1980     }
   1981 
   1982     //     -- If T is an enumeration type, its associated namespace is
   1983     //        the namespace in which it is defined. If it is class
   1984     //        member, its associated class is the member's class; else
   1985     //        it has no associated class.
   1986     case Type::Enum: {
   1987       EnumDecl *Enum = cast<EnumType>(T)->getDecl();
   1988 
   1989       DeclContext *Ctx = Enum->getDeclContext();
   1990       if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
   1991         Result.Classes.insert(EnclosingClass);
   1992 
   1993       // Add the associated namespace for this class.
   1994       CollectEnclosingNamespace(Result.Namespaces, Ctx);
   1995 
   1996       break;
   1997     }
   1998 
   1999     //     -- If T is a function type, its associated namespaces and
   2000     //        classes are those associated with the function parameter
   2001     //        types and those associated with the return type.
   2002     case Type::FunctionProto: {
   2003       const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
   2004       for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
   2005                                              ArgEnd = Proto->arg_type_end();
   2006              Arg != ArgEnd; ++Arg)
   2007         Queue.push_back(Arg->getTypePtr());
   2008       // fallthrough
   2009     }
   2010     case Type::FunctionNoProto: {
   2011       const FunctionType *FnType = cast<FunctionType>(T);
   2012       T = FnType->getResultType().getTypePtr();
   2013       continue;
   2014     }
   2015 
   2016     //     -- If T is a pointer to a member function of a class X, its
   2017     //        associated namespaces and classes are those associated
   2018     //        with the function parameter types and return type,
   2019     //        together with those associated with X.
   2020     //
   2021     //     -- If T is a pointer to a data member of class X, its
   2022     //        associated namespaces and classes are those associated
   2023     //        with the member type together with those associated with
   2024     //        X.
   2025     case Type::MemberPointer: {
   2026       const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
   2027 
   2028       // Queue up the class type into which this points.
   2029       Queue.push_back(MemberPtr->getClass());
   2030 
   2031       // And directly continue with the pointee type.
   2032       T = MemberPtr->getPointeeType().getTypePtr();
   2033       continue;
   2034     }
   2035 
   2036     // As an extension, treat this like a normal pointer.
   2037     case Type::BlockPointer:
   2038       T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
   2039       continue;
   2040 
   2041     // References aren't covered by the standard, but that's such an
   2042     // obvious defect that we cover them anyway.
   2043     case Type::LValueReference:
   2044     case Type::RValueReference:
   2045       T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
   2046       continue;
   2047 
   2048     // These are fundamental types.
   2049     case Type::Vector:
   2050     case Type::ExtVector:
   2051     case Type::Complex:
   2052       break;
   2053 
   2054     // If T is an Objective-C object or interface type, or a pointer to an
   2055     // object or interface type, the associated namespace is the global
   2056     // namespace.
   2057     case Type::ObjCObject:
   2058     case Type::ObjCInterface:
   2059     case Type::ObjCObjectPointer:
   2060       Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
   2061       break;
   2062 
   2063     // Atomic types are just wrappers; use the associations of the
   2064     // contained type.
   2065     case Type::Atomic:
   2066       T = cast<AtomicType>(T)->getValueType().getTypePtr();
   2067       continue;
   2068     }
   2069 
   2070     if (Queue.empty()) break;
   2071     T = Queue.back();
   2072     Queue.pop_back();
   2073   }
   2074 }
   2075 
   2076 /// \brief Find the associated classes and namespaces for
   2077 /// argument-dependent lookup for a call with the given set of
   2078 /// arguments.
   2079 ///
   2080 /// This routine computes the sets of associated classes and associated
   2081 /// namespaces searched by argument-dependent lookup
   2082 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
   2083 void
   2084 Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
   2085                                  AssociatedNamespaceSet &AssociatedNamespaces,
   2086                                  AssociatedClassSet &AssociatedClasses) {
   2087   AssociatedNamespaces.clear();
   2088   AssociatedClasses.clear();
   2089 
   2090   AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
   2091 
   2092   // C++ [basic.lookup.koenig]p2:
   2093   //   For each argument type T in the function call, there is a set
   2094   //   of zero or more associated namespaces and a set of zero or more
   2095   //   associated classes to be considered. The sets of namespaces and
   2096   //   classes is determined entirely by the types of the function
   2097   //   arguments (and the namespace of any template template
   2098   //   argument).
   2099   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
   2100     Expr *Arg = Args[ArgIdx];
   2101 
   2102     if (Arg->getType() != Context.OverloadTy) {
   2103       addAssociatedClassesAndNamespaces(Result, Arg->getType());
   2104       continue;
   2105     }
   2106 
   2107     // [...] In addition, if the argument is the name or address of a
   2108     // set of overloaded functions and/or function templates, its
   2109     // associated classes and namespaces are the union of those
   2110     // associated with each of the members of the set: the namespace
   2111     // in which the function or function template is defined and the
   2112     // classes and namespaces associated with its (non-dependent)
   2113     // parameter types and return type.
   2114     Arg = Arg->IgnoreParens();
   2115     if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
   2116       if (unaryOp->getOpcode() == UO_AddrOf)
   2117         Arg = unaryOp->getSubExpr();
   2118 
   2119     UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
   2120     if (!ULE) continue;
   2121 
   2122     for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
   2123            I != E; ++I) {
   2124       // Look through any using declarations to find the underlying function.
   2125       NamedDecl *Fn = (*I)->getUnderlyingDecl();
   2126 
   2127       FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
   2128       if (!FDecl)
   2129         FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
   2130 
   2131       // Add the classes and namespaces associated with the parameter
   2132       // types and return type of this function.
   2133       addAssociatedClassesAndNamespaces(Result, FDecl->getType());
   2134     }
   2135   }
   2136 }
   2137 
   2138 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
   2139 /// an acceptable non-member overloaded operator for a call whose
   2140 /// arguments have types T1 (and, if non-empty, T2). This routine
   2141 /// implements the check in C++ [over.match.oper]p3b2 concerning
   2142 /// enumeration types.
   2143 static bool
   2144 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
   2145                                        QualType T1, QualType T2,
   2146                                        ASTContext &Context) {
   2147   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
   2148     return true;
   2149 
   2150   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
   2151     return true;
   2152 
   2153   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
   2154   if (Proto->getNumArgs() < 1)
   2155     return false;
   2156 
   2157   if (T1->isEnumeralType()) {
   2158     QualType ArgType = Proto->getArgType(0).getNonReferenceType();
   2159     if (Context.hasSameUnqualifiedType(T1, ArgType))
   2160       return true;
   2161   }
   2162 
   2163   if (Proto->getNumArgs() < 2)
   2164     return false;
   2165 
   2166   if (!T2.isNull() && T2->isEnumeralType()) {
   2167     QualType ArgType = Proto->getArgType(1).getNonReferenceType();
   2168     if (Context.hasSameUnqualifiedType(T2, ArgType))
   2169       return true;
   2170   }
   2171 
   2172   return false;
   2173 }
   2174 
   2175 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
   2176                                   SourceLocation Loc,
   2177                                   LookupNameKind NameKind,
   2178                                   RedeclarationKind Redecl) {
   2179   LookupResult R(*this, Name, Loc, NameKind, Redecl);
   2180   LookupName(R, S);
   2181   return R.getAsSingle<NamedDecl>();
   2182 }
   2183 
   2184 /// \brief Find the protocol with the given name, if any.
   2185 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
   2186                                        SourceLocation IdLoc,
   2187                                        RedeclarationKind Redecl) {
   2188   Decl *D = LookupSingleName(TUScope, II, IdLoc,
   2189                              LookupObjCProtocolName, Redecl);
   2190   return cast_or_null<ObjCProtocolDecl>(D);
   2191 }
   2192 
   2193 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
   2194                                         QualType T1, QualType T2,
   2195                                         UnresolvedSetImpl &Functions) {
   2196   // C++ [over.match.oper]p3:
   2197   //     -- The set of non-member candidates is the result of the
   2198   //        unqualified lookup of operator@ in the context of the
   2199   //        expression according to the usual rules for name lookup in
   2200   //        unqualified function calls (3.4.2) except that all member
   2201   //        functions are ignored. However, if no operand has a class
   2202   //        type, only those non-member functions in the lookup set
   2203   //        that have a first parameter of type T1 or "reference to
   2204   //        (possibly cv-qualified) T1", when T1 is an enumeration
   2205   //        type, or (if there is a right operand) a second parameter
   2206   //        of type T2 or "reference to (possibly cv-qualified) T2",
   2207   //        when T2 is an enumeration type, are candidate functions.
   2208   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
   2209   LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
   2210   LookupName(Operators, S);
   2211 
   2212   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
   2213 
   2214   if (Operators.empty())
   2215     return;
   2216 
   2217   for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
   2218        Op != OpEnd; ++Op) {
   2219     NamedDecl *Found = (*Op)->getUnderlyingDecl();
   2220     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
   2221       if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
   2222         Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
   2223     } else if (FunctionTemplateDecl *FunTmpl
   2224                  = dyn_cast<FunctionTemplateDecl>(Found)) {
   2225       // FIXME: friend operators?
   2226       // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
   2227       // later?
   2228       if (!FunTmpl->getDeclContext()->isRecord())
   2229         Functions.addDecl(*Op, Op.getAccess());
   2230     }
   2231   }
   2232 }
   2233 
   2234 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
   2235                                                             CXXSpecialMember SM,
   2236                                                             bool ConstArg,
   2237                                                             bool VolatileArg,
   2238                                                             bool RValueThis,
   2239                                                             bool ConstThis,
   2240                                                             bool VolatileThis) {
   2241   RD = RD->getDefinition();
   2242   assert((RD && !RD->isBeingDefined()) &&
   2243          "doing special member lookup into record that isn't fully complete");
   2244   if (RValueThis || ConstThis || VolatileThis)
   2245     assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
   2246            "constructors and destructors always have unqualified lvalue this");
   2247   if (ConstArg || VolatileArg)
   2248     assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
   2249            "parameter-less special members can't have qualified arguments");
   2250 
   2251   llvm::FoldingSetNodeID ID;
   2252   ID.AddPointer(RD);
   2253   ID.AddInteger(SM);
   2254   ID.AddInteger(ConstArg);
   2255   ID.AddInteger(VolatileArg);
   2256   ID.AddInteger(RValueThis);
   2257   ID.AddInteger(ConstThis);
   2258   ID.AddInteger(VolatileThis);
   2259 
   2260   void *InsertPoint;
   2261   SpecialMemberOverloadResult *Result =
   2262     SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
   2263 
   2264   // This was already cached
   2265   if (Result)
   2266     return Result;
   2267 
   2268   Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
   2269   Result = new (Result) SpecialMemberOverloadResult(ID);
   2270   SpecialMemberCache.InsertNode(Result, InsertPoint);
   2271 
   2272   if (SM == CXXDestructor) {
   2273     if (!RD->hasDeclaredDestructor())
   2274       DeclareImplicitDestructor(RD);
   2275     CXXDestructorDecl *DD = RD->getDestructor();
   2276     assert(DD && "record without a destructor");
   2277     Result->setMethod(DD);
   2278     Result->setKind(DD->isDeleted() ?
   2279                     SpecialMemberOverloadResult::NoMemberOrDeleted :
   2280                     SpecialMemberOverloadResult::SuccessNonConst);
   2281     return Result;
   2282   }
   2283 
   2284   // Prepare for overload resolution. Here we construct a synthetic argument
   2285   // if necessary and make sure that implicit functions are declared.
   2286   CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
   2287   DeclarationName Name;
   2288   Expr *Arg = 0;
   2289   unsigned NumArgs;
   2290 
   2291   if (SM == CXXDefaultConstructor) {
   2292     Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
   2293     NumArgs = 0;
   2294     if (RD->needsImplicitDefaultConstructor())
   2295       DeclareImplicitDefaultConstructor(RD);
   2296   } else {
   2297     if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
   2298       Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
   2299       if (!RD->hasDeclaredCopyConstructor())
   2300         DeclareImplicitCopyConstructor(RD);
   2301       if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
   2302         DeclareImplicitMoveConstructor(RD);
   2303     } else {
   2304       Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   2305       if (!RD->hasDeclaredCopyAssignment())
   2306         DeclareImplicitCopyAssignment(RD);
   2307       if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
   2308         DeclareImplicitMoveAssignment(RD);
   2309     }
   2310 
   2311     QualType ArgType = CanTy;
   2312     if (ConstArg)
   2313       ArgType.addConst();
   2314     if (VolatileArg)
   2315       ArgType.addVolatile();
   2316 
   2317     // This isn't /really/ specified by the standard, but it's implied
   2318     // we should be working from an RValue in the case of move to ensure
   2319     // that we prefer to bind to rvalue references, and an LValue in the
   2320     // case of copy to ensure we don't bind to rvalue references.
   2321     // Possibly an XValue is actually correct in the case of move, but
   2322     // there is no semantic difference for class types in this restricted
   2323     // case.
   2324     ExprValueKind VK;
   2325     if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
   2326       VK = VK_LValue;
   2327     else
   2328       VK = VK_RValue;
   2329 
   2330     NumArgs = 1;
   2331     Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
   2332   }
   2333 
   2334   // Create the object argument
   2335   QualType ThisTy = CanTy;
   2336   if (ConstThis)
   2337     ThisTy.addConst();
   2338   if (VolatileThis)
   2339     ThisTy.addVolatile();
   2340   Expr::Classification Classification =
   2341     (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
   2342                                    RValueThis ? VK_RValue : VK_LValue))->
   2343         Classify(Context);
   2344 
   2345   // Now we perform lookup on the name we computed earlier and do overload
   2346   // resolution. Lookup is only performed directly into the class since there
   2347   // will always be a (possibly implicit) declaration to shadow any others.
   2348   OverloadCandidateSet OCS((SourceLocation()));
   2349   DeclContext::lookup_iterator I, E;
   2350   SpecialMemberOverloadResult::Kind SuccessKind =
   2351       SpecialMemberOverloadResult::SuccessNonConst;
   2352 
   2353   llvm::tie(I, E) = RD->lookup(Name);
   2354   assert((I != E) &&
   2355          "lookup for a constructor or assignment operator was empty");
   2356   for ( ; I != E; ++I) {
   2357     Decl *Cand = *I;
   2358 
   2359     if (Cand->isInvalidDecl())
   2360       continue;
   2361 
   2362     if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
   2363       // FIXME: [namespace.udecl]p15 says that we should only consider a
   2364       // using declaration here if it does not match a declaration in the
   2365       // derived class. We do not implement this correctly in other cases
   2366       // either.
   2367       Cand = U->getTargetDecl();
   2368 
   2369       if (Cand->isInvalidDecl())
   2370         continue;
   2371     }
   2372 
   2373     if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
   2374       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
   2375         AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
   2376                            Classification, llvm::makeArrayRef(&Arg, NumArgs),
   2377                            OCS, true);
   2378       else
   2379         AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
   2380                              llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
   2381 
   2382       // Here we're looking for a const parameter to speed up creation of
   2383       // implicit copy methods.
   2384       if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
   2385           (SM == CXXCopyConstructor &&
   2386             cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
   2387         QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
   2388         if (!ArgType->isReferenceType() ||
   2389             ArgType->getPointeeType().isConstQualified())
   2390           SuccessKind = SpecialMemberOverloadResult::SuccessConst;
   2391       }
   2392     } else if (FunctionTemplateDecl *Tmpl =
   2393                  dyn_cast<FunctionTemplateDecl>(Cand)) {
   2394       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
   2395         AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
   2396                                    RD, 0, ThisTy, Classification,
   2397                                    llvm::makeArrayRef(&Arg, NumArgs),
   2398                                    OCS, true);
   2399       else
   2400         AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
   2401                                      0, llvm::makeArrayRef(&Arg, NumArgs),
   2402                                      OCS, true);
   2403     } else {
   2404       assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
   2405     }
   2406   }
   2407 
   2408   OverloadCandidateSet::iterator Best;
   2409   switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
   2410     case OR_Success:
   2411       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
   2412       Result->setKind(SuccessKind);
   2413       break;
   2414 
   2415     case OR_Deleted:
   2416       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
   2417       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
   2418       break;
   2419 
   2420     case OR_Ambiguous:
   2421       Result->setMethod(0);
   2422       Result->setKind(SpecialMemberOverloadResult::Ambiguous);
   2423       break;
   2424 
   2425     case OR_No_Viable_Function:
   2426       Result->setMethod(0);
   2427       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
   2428       break;
   2429   }
   2430 
   2431   return Result;
   2432 }
   2433 
   2434 /// \brief Look up the default constructor for the given class.
   2435 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
   2436   SpecialMemberOverloadResult *Result =
   2437     LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
   2438                         false, false);
   2439 
   2440   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
   2441 }
   2442 
   2443 /// \brief Look up the copying constructor for the given class.
   2444 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
   2445                                                    unsigned Quals,
   2446                                                    bool *ConstParamMatch) {
   2447   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2448          "non-const, non-volatile qualifiers for copy ctor arg");
   2449   SpecialMemberOverloadResult *Result =
   2450     LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
   2451                         Quals & Qualifiers::Volatile, false, false, false);
   2452 
   2453   if (ConstParamMatch)
   2454     *ConstParamMatch = Result->hasConstParamMatch();
   2455 
   2456   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
   2457 }
   2458 
   2459 /// \brief Look up the moving constructor for the given class.
   2460 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
   2461   SpecialMemberOverloadResult *Result =
   2462     LookupSpecialMember(Class, CXXMoveConstructor, false,
   2463                         false, false, false, false);
   2464 
   2465   return cast_or_null<CXXConstructorDecl>(Result->getMethod());
   2466 }
   2467 
   2468 /// \brief Look up the constructors for the given class.
   2469 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
   2470   // If the implicit constructors have not yet been declared, do so now.
   2471   if (CanDeclareSpecialMemberFunction(Context, Class)) {
   2472     if (Class->needsImplicitDefaultConstructor())
   2473       DeclareImplicitDefaultConstructor(Class);
   2474     if (!Class->hasDeclaredCopyConstructor())
   2475       DeclareImplicitCopyConstructor(Class);
   2476     if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
   2477       DeclareImplicitMoveConstructor(Class);
   2478   }
   2479 
   2480   CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
   2481   DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
   2482   return Class->lookup(Name);
   2483 }
   2484 
   2485 /// \brief Look up the copying assignment operator for the given class.
   2486 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
   2487                                              unsigned Quals, bool RValueThis,
   2488                                              unsigned ThisQuals,
   2489                                              bool *ConstParamMatch) {
   2490   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2491          "non-const, non-volatile qualifiers for copy assignment arg");
   2492   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2493          "non-const, non-volatile qualifiers for copy assignment this");
   2494   SpecialMemberOverloadResult *Result =
   2495     LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
   2496                         Quals & Qualifiers::Volatile, RValueThis,
   2497                         ThisQuals & Qualifiers::Const,
   2498                         ThisQuals & Qualifiers::Volatile);
   2499 
   2500   if (ConstParamMatch)
   2501     *ConstParamMatch = Result->hasConstParamMatch();
   2502 
   2503   return Result->getMethod();
   2504 }
   2505 
   2506 /// \brief Look up the moving assignment operator for the given class.
   2507 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
   2508                                             bool RValueThis,
   2509                                             unsigned ThisQuals) {
   2510   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
   2511          "non-const, non-volatile qualifiers for copy assignment this");
   2512   SpecialMemberOverloadResult *Result =
   2513     LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
   2514                         ThisQuals & Qualifiers::Const,
   2515                         ThisQuals & Qualifiers::Volatile);
   2516 
   2517   return Result->getMethod();
   2518 }
   2519 
   2520 /// \brief Look for the destructor of the given class.
   2521 ///
   2522 /// During semantic analysis, this routine should be used in lieu of
   2523 /// CXXRecordDecl::getDestructor().
   2524 ///
   2525 /// \returns The destructor for this class.
   2526 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
   2527   return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
   2528                                                      false, false, false,
   2529                                                      false, false)->getMethod());
   2530 }
   2531 
   2532 /// LookupLiteralOperator - Determine which literal operator should be used for
   2533 /// a user-defined literal, per C++11 [lex.ext].
   2534 ///
   2535 /// Normal overload resolution is not used to select which literal operator to
   2536 /// call for a user-defined literal. Look up the provided literal operator name,
   2537 /// and filter the results to the appropriate set for the given argument types.
   2538 Sema::LiteralOperatorLookupResult
   2539 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
   2540                             ArrayRef<QualType> ArgTys,
   2541                             bool AllowRawAndTemplate) {
   2542   LookupName(R, S);
   2543   assert(R.getResultKind() != LookupResult::Ambiguous &&
   2544          "literal operator lookup can't be ambiguous");
   2545 
   2546   // Filter the lookup results appropriately.
   2547   LookupResult::Filter F = R.makeFilter();
   2548 
   2549   bool FoundTemplate = false;
   2550   bool FoundRaw = false;
   2551   bool FoundExactMatch = false;
   2552 
   2553   while (F.hasNext()) {
   2554     Decl *D = F.next();
   2555     if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
   2556       D = USD->getTargetDecl();
   2557 
   2558     bool IsTemplate = isa<FunctionTemplateDecl>(D);
   2559     bool IsRaw = false;
   2560     bool IsExactMatch = false;
   2561 
   2562     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   2563       if (FD->getNumParams() == 1 &&
   2564           FD->getParamDecl(0)->getType()->getAs<PointerType>())
   2565         IsRaw = true;
   2566       else {
   2567         IsExactMatch = true;
   2568         for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
   2569           QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
   2570           if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
   2571             IsExactMatch = false;
   2572             break;
   2573           }
   2574         }
   2575       }
   2576     }
   2577 
   2578     if (IsExactMatch) {
   2579       FoundExactMatch = true;
   2580       AllowRawAndTemplate = false;
   2581       if (FoundRaw || FoundTemplate) {
   2582         // Go through again and remove the raw and template decls we've
   2583         // already found.
   2584         F.restart();
   2585         FoundRaw = FoundTemplate = false;
   2586       }
   2587     } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
   2588       FoundTemplate |= IsTemplate;
   2589       FoundRaw |= IsRaw;
   2590     } else {
   2591       F.erase();
   2592     }
   2593   }
   2594 
   2595   F.done();
   2596 
   2597   // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
   2598   // parameter type, that is used in preference to a raw literal operator
   2599   // or literal operator template.
   2600   if (FoundExactMatch)
   2601     return LOLR_Cooked;
   2602 
   2603   // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
   2604   // operator template, but not both.
   2605   if (FoundRaw && FoundTemplate) {
   2606     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
   2607     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
   2608       Decl *D = *I;
   2609       if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
   2610         D = USD->getTargetDecl();
   2611       if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
   2612         D = FunTmpl->getTemplatedDecl();
   2613       NoteOverloadCandidate(cast<FunctionDecl>(D));
   2614     }
   2615     return LOLR_Error;
   2616   }
   2617 
   2618   if (FoundRaw)
   2619     return LOLR_Raw;
   2620 
   2621   if (FoundTemplate)
   2622     return LOLR_Template;
   2623 
   2624   // Didn't find anything we could use.
   2625   Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
   2626     << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
   2627     << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
   2628   return LOLR_Error;
   2629 }
   2630 
   2631 void ADLResult::insert(NamedDecl *New) {
   2632   NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
   2633 
   2634   // If we haven't yet seen a decl for this key, or the last decl
   2635   // was exactly this one, we're done.
   2636   if (Old == 0 || Old == New) {
   2637     Old = New;
   2638     return;
   2639   }
   2640 
   2641   // Otherwise, decide which is a more recent redeclaration.
   2642   FunctionDecl *OldFD, *NewFD;
   2643   if (isa<FunctionTemplateDecl>(New)) {
   2644     OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
   2645     NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
   2646   } else {
   2647     OldFD = cast<FunctionDecl>(Old);
   2648     NewFD = cast<FunctionDecl>(New);
   2649   }
   2650 
   2651   FunctionDecl *Cursor = NewFD;
   2652   while (true) {
   2653     Cursor = Cursor->getPreviousDecl();
   2654 
   2655     // If we got to the end without finding OldFD, OldFD is the newer
   2656     // declaration;  leave things as they are.
   2657     if (!Cursor) return;
   2658 
   2659     // If we do find OldFD, then NewFD is newer.
   2660     if (Cursor == OldFD) break;
   2661 
   2662     // Otherwise, keep looking.
   2663   }
   2664 
   2665   Old = New;
   2666 }
   2667 
   2668 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
   2669                                    SourceLocation Loc,
   2670                                    llvm::ArrayRef<Expr *> Args,
   2671                                    ADLResult &Result,
   2672                                    bool StdNamespaceIsAssociated) {
   2673   // Find all of the associated namespaces and classes based on the
   2674   // arguments we have.
   2675   AssociatedNamespaceSet AssociatedNamespaces;
   2676   AssociatedClassSet AssociatedClasses;
   2677   FindAssociatedClassesAndNamespaces(Args,
   2678                                      AssociatedNamespaces,
   2679                                      AssociatedClasses);
   2680   if (StdNamespaceIsAssociated && StdNamespace)
   2681     AssociatedNamespaces.insert(getStdNamespace());
   2682 
   2683   QualType T1, T2;
   2684   if (Operator) {
   2685     T1 = Args[0]->getType();
   2686     if (Args.size() >= 2)
   2687       T2 = Args[1]->getType();
   2688   }
   2689 
   2690   // Try to complete all associated classes, in case they contain a
   2691   // declaration of a friend function.
   2692   for (AssociatedClassSet::iterator C = AssociatedClasses.begin(),
   2693                                     CEnd = AssociatedClasses.end();
   2694        C != CEnd; ++C)
   2695     RequireCompleteType(Loc, Context.getRecordType(*C), 0);
   2696 
   2697   // C++ [basic.lookup.argdep]p3:
   2698   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
   2699   //   and let Y be the lookup set produced by argument dependent
   2700   //   lookup (defined as follows). If X contains [...] then Y is
   2701   //   empty. Otherwise Y is the set of declarations found in the
   2702   //   namespaces associated with the argument types as described
   2703   //   below. The set of declarations found by the lookup of the name
   2704   //   is the union of X and Y.
   2705   //
   2706   // Here, we compute Y and add its members to the overloaded
   2707   // candidate set.
   2708   for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
   2709                                      NSEnd = AssociatedNamespaces.end();
   2710        NS != NSEnd; ++NS) {
   2711     //   When considering an associated namespace, the lookup is the
   2712     //   same as the lookup performed when the associated namespace is
   2713     //   used as a qualifier (3.4.3.2) except that:
   2714     //
   2715     //     -- Any using-directives in the associated namespace are
   2716     //        ignored.
   2717     //
   2718     //     -- Any namespace-scope friend functions declared in
   2719     //        associated classes are visible within their respective
   2720     //        namespaces even if they are not visible during an ordinary
   2721     //        lookup (11.4).
   2722     DeclContext::lookup_iterator I, E;
   2723     for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
   2724       NamedDecl *D = *I;
   2725       // If the only declaration here is an ordinary friend, consider
   2726       // it only if it was declared in an associated classes.
   2727       if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
   2728         DeclContext *LexDC = D->getLexicalDeclContext();
   2729         if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
   2730           continue;
   2731       }
   2732 
   2733       if (isa<UsingShadowDecl>(D))
   2734         D = cast<UsingShadowDecl>(D)->getTargetDecl();
   2735 
   2736       if (isa<FunctionDecl>(D)) {
   2737         if (Operator &&
   2738             !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
   2739                                                     T1, T2, Context))
   2740           continue;
   2741       } else if (!isa<FunctionTemplateDecl>(D))
   2742         continue;
   2743 
   2744       Result.insert(D);
   2745     }
   2746   }
   2747 }
   2748 
   2749 //----------------------------------------------------------------------------
   2750 // Search for all visible declarations.
   2751 //----------------------------------------------------------------------------
   2752 VisibleDeclConsumer::~VisibleDeclConsumer() { }
   2753 
   2754 namespace {
   2755 
   2756 class ShadowContextRAII;
   2757 
   2758 class VisibleDeclsRecord {
   2759 public:
   2760   /// \brief An entry in the shadow map, which is optimized to store a
   2761   /// single declaration (the common case) but can also store a list
   2762   /// of declarations.
   2763   typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
   2764 
   2765 private:
   2766   /// \brief A mapping from declaration names to the declarations that have
   2767   /// this name within a particular scope.
   2768   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
   2769 
   2770   /// \brief A list of shadow maps, which is used to model name hiding.
   2771   std::list<ShadowMap> ShadowMaps;
   2772 
   2773   /// \brief The declaration contexts we have already visited.
   2774   llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
   2775 
   2776   friend class ShadowContextRAII;
   2777 
   2778 public:
   2779   /// \brief Determine whether we have already visited this context
   2780   /// (and, if not, note that we are going to visit that context now).
   2781   bool visitedContext(DeclContext *Ctx) {
   2782     return !VisitedContexts.insert(Ctx);
   2783   }
   2784 
   2785   bool alreadyVisitedContext(DeclContext *Ctx) {
   2786     return VisitedContexts.count(Ctx);
   2787   }
   2788 
   2789   /// \brief Determine whether the given declaration is hidden in the
   2790   /// current scope.
   2791   ///
   2792   /// \returns the declaration that hides the given declaration, or
   2793   /// NULL if no such declaration exists.
   2794   NamedDecl *checkHidden(NamedDecl *ND);
   2795 
   2796   /// \brief Add a declaration to the current shadow map.
   2797   void add(NamedDecl *ND) {
   2798     ShadowMaps.back()[ND->getDeclName()].push_back(ND);
   2799   }
   2800 };
   2801 
   2802 /// \brief RAII object that records when we've entered a shadow context.
   2803 class ShadowContextRAII {
   2804   VisibleDeclsRecord &Visible;
   2805 
   2806   typedef VisibleDeclsRecord::ShadowMap ShadowMap;
   2807 
   2808 public:
   2809   ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
   2810     Visible.ShadowMaps.push_back(ShadowMap());
   2811   }
   2812 
   2813   ~ShadowContextRAII() {
   2814     Visible.ShadowMaps.pop_back();
   2815   }
   2816 };
   2817 
   2818 } // end anonymous namespace
   2819 
   2820 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
   2821   // Look through using declarations.
   2822   ND = ND->getUnderlyingDecl();
   2823 
   2824   unsigned IDNS = ND->getIdentifierNamespace();
   2825   std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
   2826   for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
   2827        SM != SMEnd; ++SM) {
   2828     ShadowMap::iterator Pos = SM->find(ND->getDeclName());
   2829     if (Pos == SM->end())
   2830       continue;
   2831 
   2832     for (ShadowMapEntry::iterator I = Pos->second.begin(),
   2833                                IEnd = Pos->second.end();
   2834          I != IEnd; ++I) {
   2835       // A tag declaration does not hide a non-tag declaration.
   2836       if ((*I)->hasTagIdentifierNamespace() &&
   2837           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
   2838                    Decl::IDNS_ObjCProtocol)))
   2839         continue;
   2840 
   2841       // Protocols are in distinct namespaces from everything else.
   2842       if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
   2843            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
   2844           (*I)->getIdentifierNamespace() != IDNS)
   2845         continue;
   2846 
   2847       // Functions and function templates in the same scope overload
   2848       // rather than hide.  FIXME: Look for hiding based on function
   2849       // signatures!
   2850       if ((*I)->isFunctionOrFunctionTemplate() &&
   2851           ND->isFunctionOrFunctionTemplate() &&
   2852           SM == ShadowMaps.rbegin())
   2853         continue;
   2854 
   2855       // We've found a declaration that hides this one.
   2856       return *I;
   2857     }
   2858   }
   2859 
   2860   return 0;
   2861 }
   2862 
   2863 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
   2864                                bool QualifiedNameLookup,
   2865                                bool InBaseClass,
   2866                                VisibleDeclConsumer &Consumer,
   2867                                VisibleDeclsRecord &Visited) {
   2868   if (!Ctx)
   2869     return;
   2870 
   2871   // Make sure we don't visit the same context twice.
   2872   if (Visited.visitedContext(Ctx->getPrimaryContext()))
   2873     return;
   2874 
   2875   if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
   2876     Result.getSema().ForceDeclarationOfImplicitMembers(Class);
   2877 
   2878   // Enumerate all of the results in this context.
   2879   for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
   2880                                       LEnd = Ctx->lookups_end();
   2881        L != LEnd; ++L) {
   2882     for (DeclContext::lookup_result R = *L; R.first != R.second; ++R.first) {
   2883       if (NamedDecl *ND = dyn_cast<NamedDecl>(*R.first)) {
   2884         if ((ND = Result.getAcceptableDecl(ND))) {
   2885           Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
   2886           Visited.add(ND);
   2887         }
   2888       }
   2889     }
   2890   }
   2891 
   2892   // Traverse using directives for qualified name lookup.
   2893   if (QualifiedNameLookup) {
   2894     ShadowContextRAII Shadow(Visited);
   2895     DeclContext::udir_iterator I, E;
   2896     for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
   2897       LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
   2898                          QualifiedNameLookup, InBaseClass, Consumer, Visited);
   2899     }
   2900   }
   2901 
   2902   // Traverse the contexts of inherited C++ classes.
   2903   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
   2904     if (!Record->hasDefinition())
   2905       return;
   2906 
   2907     for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
   2908                                          BEnd = Record->bases_end();
   2909          B != BEnd; ++B) {
   2910       QualType BaseType = B->getType();
   2911 
   2912       // Don't look into dependent bases, because name lookup can't look
   2913       // there anyway.
   2914       if (BaseType->isDependentType())
   2915         continue;
   2916 
   2917       const RecordType *Record = BaseType->getAs<RecordType>();
   2918       if (!Record)
   2919         continue;
   2920 
   2921       // FIXME: It would be nice to be able to determine whether referencing
   2922       // a particular member would be ambiguous. For example, given
   2923       //
   2924       //   struct A { int member; };
   2925       //   struct B { int member; };
   2926       //   struct C : A, B { };
   2927       //
   2928       //   void f(C *c) { c->### }
   2929       //
   2930       // accessing 'member' would result in an ambiguity. However, we
   2931       // could be smart enough to qualify the member with the base
   2932       // class, e.g.,
   2933       //
   2934       //   c->B::member
   2935       //
   2936       // or
   2937       //
   2938       //   c->A::member
   2939 
   2940       // Find results in this base class (and its bases).
   2941       ShadowContextRAII Shadow(Visited);
   2942       LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
   2943                          true, Consumer, Visited);
   2944     }
   2945   }
   2946 
   2947   // Traverse the contexts of Objective-C classes.
   2948   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
   2949     // Traverse categories.
   2950     for (ObjCCategoryDecl *Category = IFace->getCategoryList();
   2951          Category; Category = Category->getNextClassCategory()) {
   2952       ShadowContextRAII Shadow(Visited);
   2953       LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
   2954                          Consumer, Visited);
   2955     }
   2956 
   2957     // Traverse protocols.
   2958     for (ObjCInterfaceDecl::all_protocol_iterator
   2959          I = IFace->all_referenced_protocol_begin(),
   2960          E = IFace->all_referenced_protocol_end(); I != E; ++I) {
   2961       ShadowContextRAII Shadow(Visited);
   2962       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
   2963                          Visited);
   2964     }
   2965 
   2966     // Traverse the superclass.
   2967     if (IFace->getSuperClass()) {
   2968       ShadowContextRAII Shadow(Visited);
   2969       LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
   2970                          true, Consumer, Visited);
   2971     }
   2972 
   2973     // If there is an implementation, traverse it. We do this to find
   2974     // synthesized ivars.
   2975     if (IFace->getImplementation()) {
   2976       ShadowContextRAII Shadow(Visited);
   2977       LookupVisibleDecls(IFace->getImplementation(), Result,
   2978                          QualifiedNameLookup, InBaseClass, Consumer, Visited);
   2979     }
   2980   } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
   2981     for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
   2982            E = Protocol->protocol_end(); I != E; ++I) {
   2983       ShadowContextRAII Shadow(Visited);
   2984       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
   2985                          Visited);
   2986     }
   2987   } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
   2988     for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
   2989            E = Category->protocol_end(); I != E; ++I) {
   2990       ShadowContextRAII Shadow(Visited);
   2991       LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
   2992                          Visited);
   2993     }
   2994 
   2995     // If there is an implementation, traverse it.
   2996     if (Category->getImplementation()) {
   2997       ShadowContextRAII Shadow(Visited);
   2998       LookupVisibleDecls(Category->getImplementation(), Result,
   2999                          QualifiedNameLookup, true, Consumer, Visited);
   3000     }
   3001   }
   3002 }
   3003 
   3004 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
   3005                                UnqualUsingDirectiveSet &UDirs,
   3006                                VisibleDeclConsumer &Consumer,
   3007                                VisibleDeclsRecord &Visited) {
   3008   if (!S)
   3009     return;
   3010 
   3011   if (!S->getEntity() ||
   3012       (!S->getParent() &&
   3013        !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
   3014       ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
   3015     // Walk through the declarations in this Scope.
   3016     for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
   3017          D != DEnd; ++D) {
   3018       if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
   3019         if ((ND = Result.getAcceptableDecl(ND))) {
   3020           Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
   3021           Visited.add(ND);
   3022         }
   3023     }
   3024   }
   3025 
   3026   // FIXME: C++ [temp.local]p8
   3027   DeclContext *Entity = 0;
   3028   if (S->getEntity()) {
   3029     // Look into this scope's declaration context, along with any of its
   3030     // parent lookup contexts (e.g., enclosing classes), up to the point
   3031     // where we hit the context stored in the next outer scope.
   3032     Entity = (DeclContext *)S->getEntity();
   3033     DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
   3034 
   3035     for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
   3036          Ctx = Ctx->getLookupParent()) {
   3037       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
   3038         if (Method->isInstanceMethod()) {
   3039           // For instance methods, look for ivars in the method's interface.
   3040           LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
   3041                                   Result.getNameLoc(), Sema::LookupMemberName);
   3042           if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
   3043             LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
   3044                                /*InBaseClass=*/false, Consumer, Visited);
   3045           }
   3046         }
   3047 
   3048         // We've already performed all of the name lookup that we need
   3049         // to for Objective-C methods; the next context will be the
   3050         // outer scope.
   3051         break;
   3052       }
   3053 
   3054       if (Ctx->isFunctionOrMethod())
   3055         continue;
   3056 
   3057       LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
   3058                          /*InBaseClass=*/false, Consumer, Visited);
   3059     }
   3060   } else if (!S->getParent()) {
   3061     // Look into the translation unit scope. We walk through the translation
   3062     // unit's declaration context, because the Scope itself won't have all of
   3063     // the declarations if we loaded a precompiled header.
   3064     // FIXME: We would like the translation unit's Scope object to point to the
   3065     // translation unit, so we don't need this special "if" branch. However,
   3066     // doing so would force the normal C++ name-lookup code to look into the
   3067     // translation unit decl when the IdentifierInfo chains would suffice.
   3068     // Once we fix that problem (which is part of a more general "don't look
   3069     // in DeclContexts unless we have to" optimization), we can eliminate this.
   3070     Entity = Result.getSema().Context.getTranslationUnitDecl();
   3071     LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
   3072                        /*InBaseClass=*/false, Consumer, Visited);
   3073   }
   3074 
   3075   if (Entity) {
   3076     // Lookup visible declarations in any namespaces found by using
   3077     // directives.
   3078     UnqualUsingDirectiveSet::const_iterator UI, UEnd;
   3079     llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
   3080     for (; UI != UEnd; ++UI)
   3081       LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
   3082                          Result, /*QualifiedNameLookup=*/false,
   3083                          /*InBaseClass=*/false, Consumer, Visited);
   3084   }
   3085 
   3086   // Lookup names in the parent scope.
   3087   ShadowContextRAII Shadow(Visited);
   3088   LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
   3089 }
   3090 
   3091 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
   3092                               VisibleDeclConsumer &Consumer,
   3093                               bool IncludeGlobalScope) {
   3094   // Determine the set of using directives available during
   3095   // unqualified name lookup.
   3096   Scope *Initial = S;
   3097   UnqualUsingDirectiveSet UDirs;
   3098   if (getLangOpts().CPlusPlus) {
   3099     // Find the first namespace or translation-unit scope.
   3100     while (S && !isNamespaceOrTranslationUnitScope(S))
   3101       S = S->getParent();
   3102 
   3103     UDirs.visitScopeChain(Initial, S);
   3104   }
   3105   UDirs.done();
   3106 
   3107   // Look for visible declarations.
   3108   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
   3109   VisibleDeclsRecord Visited;
   3110   if (!IncludeGlobalScope)
   3111     Visited.visitedContext(Context.getTranslationUnitDecl());
   3112   ShadowContextRAII Shadow(Visited);
   3113   ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
   3114 }
   3115 
   3116 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
   3117                               VisibleDeclConsumer &Consumer,
   3118                               bool IncludeGlobalScope) {
   3119   LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
   3120   VisibleDeclsRecord Visited;
   3121   if (!IncludeGlobalScope)
   3122     Visited.visitedContext(Context.getTranslationUnitDecl());
   3123   ShadowContextRAII Shadow(Visited);
   3124   ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
   3125                        /*InBaseClass=*/false, Consumer, Visited);
   3126 }
   3127 
   3128 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
   3129 /// If GnuLabelLoc is a valid source location, then this is a definition
   3130 /// of an __label__ label name, otherwise it is a normal label definition
   3131 /// or use.
   3132 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
   3133                                      SourceLocation GnuLabelLoc) {
   3134   // Do a lookup to see if we have a label with this name already.
   3135   NamedDecl *Res = 0;
   3136 
   3137   if (GnuLabelLoc.isValid()) {
   3138     // Local label definitions always shadow existing labels.
   3139     Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
   3140     Scope *S = CurScope;
   3141     PushOnScopeChains(Res, S, true);
   3142     return cast<LabelDecl>(Res);
   3143   }
   3144 
   3145   // Not a GNU local label.
   3146   Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
   3147   // If we found a label, check to see if it is in the same context as us.
   3148   // When in a Block, we don't want to reuse a label in an enclosing function.
   3149   if (Res && Res->getDeclContext() != CurContext)
   3150     Res = 0;
   3151   if (Res == 0) {
   3152     // If not forward referenced or defined already, create the backing decl.
   3153     Res = LabelDecl::Create(Context, CurContext, Loc, II);
   3154     Scope *S = CurScope->getFnParent();
   3155     assert(S && "Not in a function?");
   3156     PushOnScopeChains(Res, S, true);
   3157   }
   3158   return cast<LabelDecl>(Res);
   3159 }
   3160 
   3161 //===----------------------------------------------------------------------===//
   3162 // Typo correction
   3163 //===----------------------------------------------------------------------===//
   3164 
   3165 namespace {
   3166 
   3167 typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
   3168 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
   3169 
   3170 static const unsigned MaxTypoDistanceResultSets = 5;
   3171 
   3172 class TypoCorrectionConsumer : public VisibleDeclConsumer {
   3173   /// \brief The name written that is a typo in the source.
   3174   StringRef Typo;
   3175 
   3176   /// \brief The results found that have the smallest edit distance
   3177   /// found (so far) with the typo name.
   3178   ///
   3179   /// The pointer value being set to the current DeclContext indicates
   3180   /// whether there is a keyword with this name.
   3181   TypoEditDistanceMap BestResults;
   3182 
   3183   Sema &SemaRef;
   3184 
   3185 public:
   3186   explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
   3187     : Typo(Typo->getName()),
   3188       SemaRef(SemaRef) { }
   3189 
   3190   virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
   3191                          bool InBaseClass);
   3192   void FoundName(StringRef Name);
   3193   void addKeywordResult(StringRef Keyword);
   3194   void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
   3195                NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
   3196   void addCorrection(TypoCorrection Correction);
   3197 
   3198   typedef TypoResultsMap::iterator result_iterator;
   3199   typedef TypoEditDistanceMap::iterator distance_iterator;
   3200   distance_iterator begin() { return BestResults.begin(); }
   3201   distance_iterator end()  { return BestResults.end(); }
   3202   void erase(distance_iterator I) { BestResults.erase(I); }
   3203   unsigned size() const { return BestResults.size(); }
   3204   bool empty() const { return BestResults.empty(); }
   3205 
   3206   TypoCorrection &operator[](StringRef Name) {
   3207     return BestResults.begin()->second[Name];
   3208   }
   3209 
   3210   unsigned getBestEditDistance(bool Normalized) {
   3211     if (BestResults.empty())
   3212       return (std::numeric_limits<unsigned>::max)();
   3213 
   3214     unsigned BestED = BestResults.begin()->first;
   3215     return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
   3216   }
   3217 };
   3218 
   3219 }
   3220 
   3221 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
   3222                                        DeclContext *Ctx, bool InBaseClass) {
   3223   // Don't consider hidden names for typo correction.
   3224   if (Hiding)
   3225     return;
   3226 
   3227   // Only consider entities with identifiers for names, ignoring
   3228   // special names (constructors, overloaded operators, selectors,
   3229   // etc.).
   3230   IdentifierInfo *Name = ND->getIdentifier();
   3231   if (!Name)
   3232     return;
   3233 
   3234   FoundName(Name->getName());
   3235 }
   3236 
   3237 void TypoCorrectionConsumer::FoundName(StringRef Name) {
   3238   // Use a simple length-based heuristic to determine the minimum possible
   3239   // edit distance. If the minimum isn't good enough, bail out early.
   3240   unsigned MinED = abs((int)Name.size() - (int)Typo.size());
   3241   if (MinED && Typo.size() / MinED < 3)
   3242     return;
   3243 
   3244   // Compute an upper bound on the allowable edit distance, so that the
   3245   // edit-distance algorithm can short-circuit.
   3246   unsigned UpperBound = (Typo.size() + 2) / 3;
   3247 
   3248   // Compute the edit distance between the typo and the name of this
   3249   // entity, and add the identifier to the list of results.
   3250   addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
   3251 }
   3252 
   3253 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
   3254   // Compute the edit distance between the typo and this keyword,
   3255   // and add the keyword to the list of results.
   3256   addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
   3257 }
   3258 
   3259 void TypoCorrectionConsumer::addName(StringRef Name,
   3260                                      NamedDecl *ND,
   3261                                      unsigned Distance,
   3262                                      NestedNameSpecifier *NNS,
   3263                                      bool isKeyword) {
   3264   TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
   3265   if (isKeyword) TC.makeKeyword();
   3266   addCorrection(TC);
   3267 }
   3268 
   3269 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
   3270   StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
   3271   TypoResultsMap &Map = BestResults[Correction.getEditDistance(false)];
   3272 
   3273   TypoCorrection &CurrentCorrection = Map[Name];
   3274   if (!CurrentCorrection ||
   3275       // FIXME: The following should be rolled up into an operator< on
   3276       // TypoCorrection with a more principled definition.
   3277       CurrentCorrection.isKeyword() < Correction.isKeyword() ||
   3278       Correction.getAsString(SemaRef.getLangOpts()) <
   3279       CurrentCorrection.getAsString(SemaRef.getLangOpts()))
   3280     CurrentCorrection = Correction;
   3281 
   3282   while (BestResults.size() > MaxTypoDistanceResultSets)
   3283     erase(llvm::prior(BestResults.end()));
   3284 }
   3285 
   3286 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
   3287 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
   3288 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
   3289 static void getNestedNameSpecifierIdentifiers(
   3290     NestedNameSpecifier *NNS,
   3291     SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
   3292   if (NestedNameSpecifier *Prefix = NNS->getPrefix())
   3293     getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
   3294   else
   3295     Identifiers.clear();
   3296 
   3297   const IdentifierInfo *II = NULL;
   3298 
   3299   switch (NNS->getKind()) {
   3300   case NestedNameSpecifier::Identifier:
   3301     II = NNS->getAsIdentifier();
   3302     break;
   3303 
   3304   case NestedNameSpecifier::Namespace:
   3305     if (NNS->getAsNamespace()->isAnonymousNamespace())
   3306       return;
   3307     II = NNS->getAsNamespace()->getIdentifier();
   3308     break;
   3309 
   3310   case NestedNameSpecifier::NamespaceAlias:
   3311     II = NNS->getAsNamespaceAlias()->getIdentifier();
   3312     break;
   3313 
   3314   case NestedNameSpecifier::TypeSpecWithTemplate:
   3315   case NestedNameSpecifier::TypeSpec:
   3316     II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
   3317     break;
   3318 
   3319   case NestedNameSpecifier::Global:
   3320     return;
   3321   }
   3322 
   3323   if (II)
   3324     Identifiers.push_back(II);
   3325 }
   3326 
   3327 namespace {
   3328 
   3329 class SpecifierInfo {
   3330  public:
   3331   DeclContext* DeclCtx;
   3332   NestedNameSpecifier* NameSpecifier;
   3333   unsigned EditDistance;
   3334 
   3335   SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
   3336       : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
   3337 };
   3338 
   3339 typedef SmallVector<DeclContext*, 4> DeclContextList;
   3340 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
   3341 
   3342 class NamespaceSpecifierSet {
   3343   ASTContext &Context;
   3344   DeclContextList CurContextChain;
   3345   SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
   3346   SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
   3347   bool isSorted;
   3348 
   3349   SpecifierInfoList Specifiers;
   3350   llvm::SmallSetVector<unsigned, 4> Distances;
   3351   llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
   3352 
   3353   /// \brief Helper for building the list of DeclContexts between the current
   3354   /// context and the top of the translation unit
   3355   static DeclContextList BuildContextChain(DeclContext *Start);
   3356 
   3357   void SortNamespaces();
   3358 
   3359  public:
   3360   NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
   3361                         CXXScopeSpec *CurScopeSpec)
   3362       : Context(Context), CurContextChain(BuildContextChain(CurContext)),
   3363         isSorted(true) {
   3364     if (CurScopeSpec && CurScopeSpec->getScopeRep())
   3365       getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
   3366                                         CurNameSpecifierIdentifiers);
   3367     // Build the list of identifiers that would be used for an absolute
   3368     // (from the global context) NestedNameSpecifier refering to the current
   3369     // context.
   3370     for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
   3371                                         CEnd = CurContextChain.rend();
   3372          C != CEnd; ++C) {
   3373       if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
   3374         CurContextIdentifiers.push_back(ND->getIdentifier());
   3375     }
   3376   }
   3377 
   3378   /// \brief Add the namespace to the set, computing the corresponding
   3379   /// NestedNameSpecifier and its distance in the process.
   3380   void AddNamespace(NamespaceDecl *ND);
   3381 
   3382   typedef SpecifierInfoList::iterator iterator;
   3383   iterator begin() {
   3384     if (!isSorted) SortNamespaces();
   3385     return Specifiers.begin();
   3386   }
   3387   iterator end() { return Specifiers.end(); }
   3388 };
   3389 
   3390 }
   3391 
   3392 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
   3393   assert(Start && "Bulding a context chain from a null context");
   3394   DeclContextList Chain;
   3395   for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
   3396        DC = DC->getLookupParent()) {
   3397     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
   3398     if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
   3399         !(ND && ND->isAnonymousNamespace()))
   3400       Chain.push_back(DC->getPrimaryContext());
   3401   }
   3402   return Chain;
   3403 }
   3404 
   3405 void NamespaceSpecifierSet::SortNamespaces() {
   3406   SmallVector<unsigned, 4> sortedDistances;
   3407   sortedDistances.append(Distances.begin(), Distances.end());
   3408 
   3409   if (sortedDistances.size() > 1)
   3410     std::sort(sortedDistances.begin(), sortedDistances.end());
   3411 
   3412   Specifiers.clear();
   3413   for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
   3414                                        DIEnd = sortedDistances.end();
   3415        DI != DIEnd; ++DI) {
   3416     SpecifierInfoList &SpecList = DistanceMap[*DI];
   3417     Specifiers.append(SpecList.begin(), SpecList.end());
   3418   }
   3419 
   3420   isSorted = true;
   3421 }
   3422 
   3423 void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
   3424   DeclContext *Ctx = cast<DeclContext>(ND);
   3425   NestedNameSpecifier *NNS = NULL;
   3426   unsigned NumSpecifiers = 0;
   3427   DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
   3428   DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
   3429 
   3430   // Eliminate common elements from the two DeclContext chains.
   3431   for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
   3432                                       CEnd = CurContextChain.rend();
   3433        C != CEnd && !NamespaceDeclChain.empty() &&
   3434        NamespaceDeclChain.back() == *C; ++C) {
   3435     NamespaceDeclChain.pop_back();
   3436   }
   3437 
   3438   // Add an explicit leading '::' specifier if needed.
   3439   if (NamespaceDecl *ND =
   3440         NamespaceDeclChain.empty() ? NULL :
   3441           dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
   3442     IdentifierInfo *Name = ND->getIdentifier();
   3443     if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
   3444                   Name) != CurContextIdentifiers.end() ||
   3445         std::find(CurNameSpecifierIdentifiers.begin(),
   3446                   CurNameSpecifierIdentifiers.end(),
   3447                   Name) != CurNameSpecifierIdentifiers.end()) {
   3448       NamespaceDeclChain = FullNamespaceDeclChain;
   3449       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
   3450     }
   3451   }
   3452 
   3453   // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
   3454   for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
   3455                                       CEnd = NamespaceDeclChain.rend();
   3456        C != CEnd; ++C) {
   3457     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
   3458     if (ND) {
   3459       NNS = NestedNameSpecifier::Create(Context, NNS, ND);
   3460       ++NumSpecifiers;
   3461     }
   3462   }
   3463 
   3464   // If the built NestedNameSpecifier would be replacing an existing
   3465   // NestedNameSpecifier, use the number of component identifiers that
   3466   // would need to be changed as the edit distance instead of the number
   3467   // of components in the built NestedNameSpecifier.
   3468   if (NNS && !CurNameSpecifierIdentifiers.empty()) {
   3469     SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
   3470     getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
   3471     NumSpecifiers = llvm::ComputeEditDistance(
   3472       llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
   3473       llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
   3474   }
   3475 
   3476   isSorted = false;
   3477   Distances.insert(NumSpecifiers);
   3478   DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
   3479 }
   3480 
   3481 /// \brief Perform name lookup for a possible result for typo correction.
   3482 static void LookupPotentialTypoResult(Sema &SemaRef,
   3483                                       LookupResult &Res,
   3484                                       IdentifierInfo *Name,
   3485                                       Scope *S, CXXScopeSpec *SS,
   3486                                       DeclContext *MemberContext,
   3487                                       bool EnteringContext,
   3488                                       bool isObjCIvarLookup) {
   3489   Res.suppressDiagnostics();
   3490   Res.clear();
   3491   Res.setLookupName(Name);
   3492   if (MemberContext) {
   3493     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
   3494       if (isObjCIvarLookup) {
   3495         if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
   3496           Res.addDecl(Ivar);
   3497           Res.resolveKind();
   3498           return;
   3499         }
   3500       }
   3501 
   3502       if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
   3503         Res.addDecl(Prop);
   3504         Res.resolveKind();
   3505         return;
   3506       }
   3507     }
   3508 
   3509     SemaRef.LookupQualifiedName(Res, MemberContext);
   3510     return;
   3511   }
   3512 
   3513   SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
   3514                            EnteringContext);
   3515 
   3516   // Fake ivar lookup; this should really be part of
   3517   // LookupParsedName.
   3518   if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
   3519     if (Method->isInstanceMethod() && Method->getClassInterface() &&
   3520         (Res.empty() ||
   3521          (Res.isSingleResult() &&
   3522           Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
   3523        if (ObjCIvarDecl *IV
   3524              = Method->getClassInterface()->lookupInstanceVariable(Name)) {
   3525          Res.addDecl(IV);
   3526          Res.resolveKind();
   3527        }
   3528      }
   3529   }
   3530 }
   3531 
   3532 /// \brief Add keywords to the consumer as possible typo corrections.
   3533 static void AddKeywordsToConsumer(Sema &SemaRef,
   3534                                   TypoCorrectionConsumer &Consumer,
   3535                                   Scope *S, CorrectionCandidateCallback &CCC) {
   3536   if (CCC.WantObjCSuper)
   3537     Consumer.addKeywordResult("super");
   3538 
   3539   if (CCC.WantTypeSpecifiers) {
   3540     // Add type-specifier keywords to the set of results.
   3541     const char *CTypeSpecs[] = {
   3542       "char", "const", "double", "enum", "float", "int", "long", "short",
   3543       "signed", "struct", "union", "unsigned", "void", "volatile",
   3544       "_Complex", "_Imaginary",
   3545       // storage-specifiers as well
   3546       "extern", "inline", "static", "typedef"
   3547     };
   3548 
   3549     const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
   3550     for (unsigned I = 0; I != NumCTypeSpecs; ++I)
   3551       Consumer.addKeywordResult(CTypeSpecs[I]);
   3552 
   3553     if (SemaRef.getLangOpts().C99)
   3554       Consumer.addKeywordResult("restrict");
   3555     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
   3556       Consumer.addKeywordResult("bool");
   3557     else if (SemaRef.getLangOpts().C99)
   3558       Consumer.addKeywordResult("_Bool");
   3559 
   3560     if (SemaRef.getLangOpts().CPlusPlus) {
   3561       Consumer.addKeywordResult("class");
   3562       Consumer.addKeywordResult("typename");
   3563       Consumer.addKeywordResult("wchar_t");
   3564 
   3565       if (SemaRef.getLangOpts().CPlusPlus0x) {
   3566         Consumer.addKeywordResult("char16_t");
   3567         Consumer.addKeywordResult("char32_t");
   3568         Consumer.addKeywordResult("constexpr");
   3569         Consumer.addKeywordResult("decltype");
   3570         Consumer.addKeywordResult("thread_local");
   3571       }
   3572     }
   3573 
   3574     if (SemaRef.getLangOpts().GNUMode)
   3575       Consumer.addKeywordResult("typeof");
   3576   }
   3577 
   3578   if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
   3579     Consumer.addKeywordResult("const_cast");
   3580     Consumer.addKeywordResult("dynamic_cast");
   3581     Consumer.addKeywordResult("reinterpret_cast");
   3582     Consumer.addKeywordResult("static_cast");
   3583   }
   3584 
   3585   if (CCC.WantExpressionKeywords) {
   3586     Consumer.addKeywordResult("sizeof");
   3587     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
   3588       Consumer.addKeywordResult("false");
   3589       Consumer.addKeywordResult("true");
   3590     }
   3591 
   3592     if (SemaRef.getLangOpts().CPlusPlus) {
   3593       const char *CXXExprs[] = {
   3594         "delete", "new", "operator", "throw", "typeid"
   3595       };
   3596       const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
   3597       for (unsigned I = 0; I != NumCXXExprs; ++I)
   3598         Consumer.addKeywordResult(CXXExprs[I]);
   3599 
   3600       if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
   3601           cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
   3602         Consumer.addKeywordResult("this");
   3603 
   3604       if (SemaRef.getLangOpts().CPlusPlus0x) {
   3605         Consumer.addKeywordResult("alignof");
   3606         Consumer.addKeywordResult("nullptr");
   3607       }
   3608     }
   3609   }
   3610 
   3611   if (CCC.WantRemainingKeywords) {
   3612     if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
   3613       // Statements.
   3614       const char *CStmts[] = {
   3615         "do", "else", "for", "goto", "if", "return", "switch", "while" };
   3616       const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
   3617       for (unsigned I = 0; I != NumCStmts; ++I)
   3618         Consumer.addKeywordResult(CStmts[I]);
   3619 
   3620       if (SemaRef.getLangOpts().CPlusPlus) {
   3621         Consumer.addKeywordResult("catch");
   3622         Consumer.addKeywordResult("try");
   3623       }
   3624 
   3625       if (S && S->getBreakParent())
   3626         Consumer.addKeywordResult("break");
   3627 
   3628       if (S && S->getContinueParent())
   3629         Consumer.addKeywordResult("continue");
   3630 
   3631       if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
   3632         Consumer.addKeywordResult("case");
   3633         Consumer.addKeywordResult("default");
   3634       }
   3635     } else {
   3636       if (SemaRef.getLangOpts().CPlusPlus) {
   3637         Consumer.addKeywordResult("namespace");
   3638         Consumer.addKeywordResult("template");
   3639       }
   3640 
   3641       if (S && S->isClassScope()) {
   3642         Consumer.addKeywordResult("explicit");
   3643         Consumer.addKeywordResult("friend");
   3644         Consumer.addKeywordResult("mutable");
   3645         Consumer.addKeywordResult("private");
   3646         Consumer.addKeywordResult("protected");
   3647         Consumer.addKeywordResult("public");
   3648         Consumer.addKeywordResult("virtual");
   3649       }
   3650     }
   3651 
   3652     if (SemaRef.getLangOpts().CPlusPlus) {
   3653       Consumer.addKeywordResult("using");
   3654 
   3655       if (SemaRef.getLangOpts().CPlusPlus0x)
   3656         Consumer.addKeywordResult("static_assert");
   3657     }
   3658   }
   3659 }
   3660 
   3661 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
   3662                               TypoCorrection &Candidate) {
   3663   Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
   3664   return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
   3665 }
   3666 
   3667 /// \brief Try to "correct" a typo in the source code by finding
   3668 /// visible declarations whose names are similar to the name that was
   3669 /// present in the source code.
   3670 ///
   3671 /// \param TypoName the \c DeclarationNameInfo structure that contains
   3672 /// the name that was present in the source code along with its location.
   3673 ///
   3674 /// \param LookupKind the name-lookup criteria used to search for the name.
   3675 ///
   3676 /// \param S the scope in which name lookup occurs.
   3677 ///
   3678 /// \param SS the nested-name-specifier that precedes the name we're
   3679 /// looking for, if present.
   3680 ///
   3681 /// \param CCC A CorrectionCandidateCallback object that provides further
   3682 /// validation of typo correction candidates. It also provides flags for
   3683 /// determining the set of keywords permitted.
   3684 ///
   3685 /// \param MemberContext if non-NULL, the context in which to look for
   3686 /// a member access expression.
   3687 ///
   3688 /// \param EnteringContext whether we're entering the context described by
   3689 /// the nested-name-specifier SS.
   3690 ///
   3691 /// \param OPT when non-NULL, the search for visible declarations will
   3692 /// also walk the protocols in the qualified interfaces of \p OPT.
   3693 ///
   3694 /// \returns a \c TypoCorrection containing the corrected name if the typo
   3695 /// along with information such as the \c NamedDecl where the corrected name
   3696 /// was declared, and any additional \c NestedNameSpecifier needed to access
   3697 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
   3698 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
   3699                                  Sema::LookupNameKind LookupKind,
   3700                                  Scope *S, CXXScopeSpec *SS,
   3701                                  CorrectionCandidateCallback &CCC,
   3702                                  DeclContext *MemberContext,
   3703                                  bool EnteringContext,
   3704                                  const ObjCObjectPointerType *OPT) {
   3705   if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
   3706     return TypoCorrection();
   3707 
   3708   // In Microsoft mode, don't perform typo correction in a template member
   3709   // function dependent context because it interferes with the "lookup into
   3710   // dependent bases of class templates" feature.
   3711   if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
   3712       isa<CXXMethodDecl>(CurContext))
   3713     return TypoCorrection();
   3714 
   3715   // We only attempt to correct typos for identifiers.
   3716   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
   3717   if (!Typo)
   3718     return TypoCorrection();
   3719 
   3720   // If the scope specifier itself was invalid, don't try to correct
   3721   // typos.
   3722   if (SS && SS->isInvalid())
   3723     return TypoCorrection();
   3724 
   3725   // Never try to correct typos during template deduction or
   3726   // instantiation.
   3727   if (!ActiveTemplateInstantiations.empty())
   3728     return TypoCorrection();
   3729 
   3730   NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
   3731 
   3732   TypoCorrectionConsumer Consumer(*this, Typo);
   3733 
   3734   // If a callback object considers an empty typo correction candidate to be
   3735   // viable, assume it does not do any actual validation of the candidates.
   3736   TypoCorrection EmptyCorrection;
   3737   bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
   3738 
   3739   // Perform name lookup to find visible, similarly-named entities.
   3740   bool IsUnqualifiedLookup = false;
   3741   DeclContext *QualifiedDC = MemberContext;
   3742   if (MemberContext) {
   3743     LookupVisibleDecls(MemberContext, LookupKind, Consumer);
   3744 
   3745     // Look in qualified interfaces.
   3746     if (OPT) {
   3747       for (ObjCObjectPointerType::qual_iterator
   3748              I = OPT->qual_begin(), E = OPT->qual_end();
   3749            I != E; ++I)
   3750         LookupVisibleDecls(*I, LookupKind, Consumer);
   3751     }
   3752   } else if (SS && SS->isSet()) {
   3753     QualifiedDC = computeDeclContext(*SS, EnteringContext);
   3754     if (!QualifiedDC)
   3755       return TypoCorrection();
   3756 
   3757     // Provide a stop gap for files that are just seriously broken.  Trying
   3758     // to correct all typos can turn into a HUGE performance penalty, causing
   3759     // some files to take minutes to get rejected by the parser.
   3760     if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
   3761       return TypoCorrection();
   3762     ++TyposCorrected;
   3763 
   3764     LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
   3765   } else {
   3766     IsUnqualifiedLookup = true;
   3767     UnqualifiedTyposCorrectedMap::iterator Cached
   3768       = UnqualifiedTyposCorrected.find(Typo);
   3769     if (Cached != UnqualifiedTyposCorrected.end()) {
   3770       // Add the cached value, unless it's a keyword or fails validation. In the
   3771       // keyword case, we'll end up adding the keyword below.
   3772       if (Cached->second) {
   3773         if (!Cached->second.isKeyword() &&
   3774             isCandidateViable(CCC, Cached->second))
   3775           Consumer.addCorrection(Cached->second);
   3776       } else {
   3777         // Only honor no-correction cache hits when a callback that will validate
   3778         // correction candidates is not being used.
   3779         if (!ValidatingCallback)
   3780           return TypoCorrection();
   3781       }
   3782     }
   3783     if (Cached == UnqualifiedTyposCorrected.end()) {
   3784       // Provide a stop gap for files that are just seriously broken.  Trying
   3785       // to correct all typos can turn into a HUGE performance penalty, causing
   3786       // some files to take minutes to get rejected by the parser.
   3787       if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
   3788         return TypoCorrection();
   3789     }
   3790   }
   3791 
   3792   // Determine whether we are going to search in the various namespaces for
   3793   // corrections.
   3794   bool SearchNamespaces
   3795     = getLangOpts().CPlusPlus &&
   3796       (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
   3797 
   3798   if (IsUnqualifiedLookup || SearchNamespaces) {
   3799     // For unqualified lookup, look through all of the names that we have
   3800     // seen in this translation unit.
   3801     // FIXME: Re-add the ability to skip very unlikely potential corrections.
   3802     for (IdentifierTable::iterator I = Context.Idents.begin(),
   3803                                 IEnd = Context.Idents.end();
   3804          I != IEnd; ++I)
   3805       Consumer.FoundName(I->getKey());
   3806 
   3807     // Walk through identifiers in external identifier sources.
   3808     // FIXME: Re-add the ability to skip very unlikely potential corrections.
   3809     if (IdentifierInfoLookup *External
   3810                             = Context.Idents.getExternalIdentifierLookup()) {
   3811       OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
   3812       do {
   3813         StringRef Name = Iter->Next();
   3814         if (Name.empty())
   3815           break;
   3816 
   3817         Consumer.FoundName(Name);
   3818       } while (true);
   3819     }
   3820   }
   3821 
   3822   AddKeywordsToConsumer(*this, Consumer, S, CCC);
   3823 
   3824   // If we haven't found anything, we're done.
   3825   if (Consumer.empty()) {
   3826     // If this was an unqualified lookup, note that no correction was found.
   3827     if (IsUnqualifiedLookup)
   3828       (void)UnqualifiedTyposCorrected[Typo];
   3829 
   3830     return TypoCorrection();
   3831   }
   3832 
   3833   // Make sure that the user typed at least 3 characters for each correction
   3834   // made. Otherwise, we don't even both looking at the results.
   3835   unsigned ED = Consumer.getBestEditDistance(true);
   3836   if (ED > 0 && Typo->getName().size() / ED < 3) {
   3837     // If this was an unqualified lookup, note that no correction was found.
   3838     if (IsUnqualifiedLookup)
   3839       (void)UnqualifiedTyposCorrected[Typo];
   3840 
   3841     return TypoCorrection();
   3842   }
   3843 
   3844   // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
   3845   // to search those namespaces.
   3846   if (SearchNamespaces) {
   3847     // Load any externally-known namespaces.
   3848     if (ExternalSource && !LoadedExternalKnownNamespaces) {
   3849       SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
   3850       LoadedExternalKnownNamespaces = true;
   3851       ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
   3852       for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
   3853         KnownNamespaces[ExternalKnownNamespaces[I]] = true;
   3854     }
   3855 
   3856     for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
   3857            KNI = KnownNamespaces.begin(),
   3858            KNIEnd = KnownNamespaces.end();
   3859          KNI != KNIEnd; ++KNI)
   3860       Namespaces.AddNamespace(KNI->first);
   3861   }
   3862 
   3863   // Weed out any names that could not be found by name lookup or, if a
   3864   // CorrectionCandidateCallback object was provided, failed validation.
   3865   llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
   3866   LookupResult TmpRes(*this, TypoName, LookupKind);
   3867   TmpRes.suppressDiagnostics();
   3868   while (!Consumer.empty()) {
   3869     TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
   3870     unsigned ED = DI->first;
   3871     for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
   3872                                               IEnd = DI->second.end();
   3873          I != IEnd; /* Increment in loop. */) {
   3874       // If the item already has been looked up or is a keyword, keep it.
   3875       // If a validator callback object was given, drop the correction
   3876       // unless it passes validation.
   3877       if (I->second.isResolved()) {
   3878         TypoCorrectionConsumer::result_iterator Prev = I;
   3879         ++I;
   3880         if (!isCandidateViable(CCC, Prev->second))
   3881           DI->second.erase(Prev);
   3882         continue;
   3883       }
   3884 
   3885       // Perform name lookup on this name.
   3886       IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
   3887       LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
   3888                                 EnteringContext, CCC.IsObjCIvarLookup);
   3889 
   3890       switch (TmpRes.getResultKind()) {
   3891       case LookupResult::NotFound:
   3892       case LookupResult::NotFoundInCurrentInstantiation:
   3893       case LookupResult::FoundUnresolvedValue:
   3894         QualifiedResults.push_back(I->second);
   3895         // We didn't find this name in our scope, or didn't like what we found;
   3896         // ignore it.
   3897         {
   3898           TypoCorrectionConsumer::result_iterator Next = I;
   3899           ++Next;
   3900           DI->second.erase(I);
   3901           I = Next;
   3902         }
   3903         break;
   3904 
   3905       case LookupResult::Ambiguous:
   3906         // We don't deal with ambiguities.
   3907         return TypoCorrection();
   3908 
   3909       case LookupResult::FoundOverloaded: {
   3910         TypoCorrectionConsumer::result_iterator Prev = I;
   3911         // Store all of the Decls for overloaded symbols
   3912         for (LookupResult::iterator TRD = TmpRes.begin(),
   3913                                  TRDEnd = TmpRes.end();
   3914              TRD != TRDEnd; ++TRD)
   3915           I->second.addCorrectionDecl(*TRD);
   3916         ++I;
   3917         if (!isCandidateViable(CCC, Prev->second))
   3918           DI->second.erase(Prev);
   3919         break;
   3920       }
   3921 
   3922       case LookupResult::Found: {
   3923         TypoCorrectionConsumer::result_iterator Prev = I;
   3924         I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
   3925         ++I;
   3926         if (!isCandidateViable(CCC, Prev->second))
   3927           DI->second.erase(Prev);
   3928         break;
   3929       }
   3930 
   3931       }
   3932     }
   3933 
   3934     if (DI->second.empty())
   3935       Consumer.erase(DI);
   3936     else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
   3937       // If there are results in the closest possible bucket, stop
   3938       break;
   3939 
   3940     // Only perform the qualified lookups for C++
   3941     if (SearchNamespaces) {
   3942       TmpRes.suppressDiagnostics();
   3943       for (llvm::SmallVector<TypoCorrection,
   3944                              16>::iterator QRI = QualifiedResults.begin(),
   3945                                         QRIEnd = QualifiedResults.end();
   3946            QRI != QRIEnd; ++QRI) {
   3947         for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
   3948                                           NIEnd = Namespaces.end();
   3949              NI != NIEnd; ++NI) {
   3950           DeclContext *Ctx = NI->DeclCtx;
   3951 
   3952           // FIXME: Stop searching once the namespaces are too far away to create
   3953           // acceptable corrections for this identifier (since the namespaces
   3954           // are sorted in ascending order by edit distance).
   3955 
   3956           TmpRes.clear();
   3957           TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
   3958           if (!LookupQualifiedName(TmpRes, Ctx)) continue;
   3959 
   3960           // Any corrections added below will be validated in subsequent
   3961           // iterations of the main while() loop over the Consumer's contents.
   3962           switch (TmpRes.getResultKind()) {
   3963           case LookupResult::Found: {
   3964             TypoCorrection TC(*QRI);
   3965             TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
   3966             TC.setCorrectionSpecifier(NI->NameSpecifier);
   3967             TC.setQualifierDistance(NI->EditDistance);
   3968             Consumer.addCorrection(TC);
   3969             break;
   3970           }
   3971           case LookupResult::FoundOverloaded: {
   3972             TypoCorrection TC(*QRI);
   3973             TC.setCorrectionSpecifier(NI->NameSpecifier);
   3974             TC.setQualifierDistance(NI->EditDistance);
   3975             for (LookupResult::iterator TRD = TmpRes.begin(),
   3976                                      TRDEnd = TmpRes.end();
   3977                  TRD != TRDEnd; ++TRD)
   3978               TC.addCorrectionDecl(*TRD);
   3979             Consumer.addCorrection(TC);
   3980             break;
   3981           }
   3982           case LookupResult::NotFound:
   3983           case LookupResult::NotFoundInCurrentInstantiation:
   3984           case LookupResult::Ambiguous:
   3985           case LookupResult::FoundUnresolvedValue:
   3986             break;
   3987           }
   3988         }
   3989       }
   3990     }
   3991 
   3992     QualifiedResults.clear();
   3993   }
   3994 
   3995   // No corrections remain...
   3996   if (Consumer.empty()) return TypoCorrection();
   3997 
   3998   TypoResultsMap &BestResults = Consumer.begin()->second;
   3999   ED = TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
   4000 
   4001   if (ED > 0 && Typo->getName().size() / ED < 3) {
   4002     // If this was an unqualified lookup and we believe the callback
   4003     // object wouldn't have filtered out possible corrections, note
   4004     // that no correction was found.
   4005     if (IsUnqualifiedLookup && !ValidatingCallback)
   4006       (void)UnqualifiedTyposCorrected[Typo];
   4007 
   4008     return TypoCorrection();
   4009   }
   4010 
   4011   // If only a single name remains, return that result.
   4012   if (BestResults.size() == 1) {
   4013     const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
   4014     const TypoCorrection &Result = Correction.second;
   4015 
   4016     // Don't correct to a keyword that's the same as the typo; the keyword
   4017     // wasn't actually in scope.
   4018     if (ED == 0 && Result.isKeyword()) return TypoCorrection();
   4019 
   4020     // Record the correction for unqualified lookup.
   4021     if (IsUnqualifiedLookup)
   4022       UnqualifiedTyposCorrected[Typo] = Result;
   4023 
   4024     return Result;
   4025   }
   4026   else if (BestResults.size() > 1
   4027            // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
   4028            // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
   4029            // some instances of CTC_Unknown, while WantRemainingKeywords is true
   4030            // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
   4031            && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
   4032            && BestResults["super"].isKeyword()) {
   4033     // Prefer 'super' when we're completing in a message-receiver
   4034     // context.
   4035 
   4036     // Don't correct to a keyword that's the same as the typo; the keyword
   4037     // wasn't actually in scope.
   4038     if (ED == 0) return TypoCorrection();
   4039 
   4040     // Record the correction for unqualified lookup.
   4041     if (IsUnqualifiedLookup)
   4042       UnqualifiedTyposCorrected[Typo] = BestResults["super"];
   4043 
   4044     return BestResults["super"];
   4045   }
   4046 
   4047   // If this was an unqualified lookup and we believe the callback object did
   4048   // not filter out possible corrections, note that no correction was found.
   4049   if (IsUnqualifiedLookup && !ValidatingCallback)
   4050     (void)UnqualifiedTyposCorrected[Typo];
   4051 
   4052   return TypoCorrection();
   4053 }
   4054 
   4055 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
   4056   if (!CDecl) return;
   4057 
   4058   if (isKeyword())
   4059     CorrectionDecls.clear();
   4060 
   4061   CorrectionDecls.push_back(CDecl);
   4062 
   4063   if (!CorrectionName)
   4064     CorrectionName = CDecl->getDeclName();
   4065 }
   4066 
   4067 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
   4068   if (CorrectionNameSpec) {
   4069     std::string tmpBuffer;
   4070     llvm::raw_string_ostream PrefixOStream(tmpBuffer);
   4071     CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
   4072     CorrectionName.printName(PrefixOStream);
   4073     return PrefixOStream.str();
   4074   }
   4075 
   4076   return CorrectionName.getAsString();
   4077 }
   4078