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