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