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