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