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