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