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