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