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