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