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