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