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 a module that we've not yet finished
1569   // parsing, then M should be the global module fragment in current TU. So it
1570   // should be usable.
1571   // [module.global.frag]p1:
1572   //   The global module fragment can be used to provide declarations that are
1573   //   attached to the global module and usable within the module unit.
1574   if ((M->isGlobalModule() && !M->Parent) ||
1575       // If M is the private module fragment, it is usable only if it is within
1576       // the current module unit. And it must be the current parsing module unit
1577       // if it is within the current module unit according to the grammar of the
1578       // private module fragment.
1579       // NOTE: This is covered by the following condition. The intention of the
1580       // check is to avoid string comparison as much as possible.
1581       (M->isPrivateModule() && 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 hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1613                           llvm::SmallVectorImpl<Module *> *Modules) {
1614   if (!D->hasDefaultArgument())
1615     return false;
1616 
1617   while (D) {
1618     auto &DefaultArg = D->getDefaultArgStorage();
1619     if (!DefaultArg.isInherited() && S.isVisible(D))
1620       return true;
1621 
1622     if (!DefaultArg.isInherited() && Modules) {
1623       auto *NonConstD = const_cast<ParmDecl*>(D);
1624       Modules->push_back(S.getOwningModule(NonConstD));
1625     }
1626 
1627     // If there was a previous default argument, maybe its parameter is visible.
1628     D = DefaultArg.getInheritedFrom();
1629   }
1630   return false;
1631 }
1632 
1633 bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1634                                      llvm::SmallVectorImpl<Module *> *Modules) {
1635   if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1636     return ::hasVisibleDefaultArgument(*this, P, Modules);
1637   if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1638     return ::hasVisibleDefaultArgument(*this, P, Modules);
1639   return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1640                                      Modules);
1641 }
1642 
1643 template<typename Filter>
1644 static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1645                                       llvm::SmallVectorImpl<Module *> *Modules,
1646                                       Filter F) {
1647   bool HasFilteredRedecls = false;
1648 
1649   for (auto *Redecl : D->redecls()) {
1650     auto *R = cast<NamedDecl>(Redecl);
1651     if (!F(R))
1652       continue;
1653 
1654     if (S.isVisible(R))
1655       return true;
1656 
1657     HasFilteredRedecls = true;
1658 
1659     if (Modules)
1660       Modules->push_back(R->getOwningModule());
1661   }
1662 
1663   // Only return false if there is at least one redecl that is not filtered out.
1664   if (HasFilteredRedecls)
1665     return false;
1666 
1667   return true;
1668 }
1669 
1670 bool Sema::hasVisibleExplicitSpecialization(
1671     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1672   return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1673     if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1674       return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1675     if (auto *FD = dyn_cast<FunctionDecl>(D))
1676       return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1677     if (auto *VD = dyn_cast<VarDecl>(D))
1678       return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1679     llvm_unreachable("unknown explicit specialization kind");
1680   });
1681 }
1682 
1683 bool Sema::hasVisibleMemberSpecialization(
1684     const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1685   assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1686          "not a member specialization");
1687   return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1688     // If the specialization is declared at namespace scope, then it's a member
1689     // specialization declaration. If it's lexically inside the class
1690     // definition then it was instantiated.
1691     //
1692     // FIXME: This is a hack. There should be a better way to determine this.
1693     // FIXME: What about MS-style explicit specializations declared within a
1694     //        class definition?
1695     return D->getLexicalDeclContext()->isFileContext();
1696   });
1697 }
1698 
1699 /// Determine whether a declaration is visible to name lookup.
1700 ///
1701 /// This routine determines whether the declaration D is visible in the current
1702 /// lookup context, taking into account the current template instantiation
1703 /// stack. During template instantiation, a declaration is visible if it is
1704 /// visible from a module containing any entity on the template instantiation
1705 /// path (by instantiating a template, you allow it to see the declarations that
1706 /// your module can see, including those later on in your module).
1707 bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1708   assert(!D->isUnconditionallyVisible() &&
1709          "should not call this: not in slow case");
1710 
1711   Module *DeclModule = SemaRef.getOwningModule(D);
1712   assert(DeclModule && "hidden decl has no owning module");
1713 
1714   if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
1715     // If the owning module is visible, the decl is visible.
1716     return true;
1717 
1718   // Determine whether a decl context is a file context for the purpose of
1719   // visibility. This looks through some (export and linkage spec) transparent
1720   // contexts, but not others (enums).
1721   auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1722     return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1723            isa<ExportDecl>(DC);
1724   };
1725 
1726   // If this declaration is not at namespace scope
1727   // then it is visible if its lexical parent has a visible definition.
1728   DeclContext *DC = D->getLexicalDeclContext();
1729   if (DC && !IsEffectivelyFileContext(DC)) {
1730     // For a parameter, check whether our current template declaration's
1731     // lexical context is visible, not whether there's some other visible
1732     // definition of it, because parameters aren't "within" the definition.
1733     //
1734     // In C++ we need to check for a visible definition due to ODR merging,
1735     // and in C we must not because each declaration of a function gets its own
1736     // set of declarations for tags in prototype scope.
1737     bool VisibleWithinParent;
1738     if (D->isTemplateParameter()) {
1739       bool SearchDefinitions = true;
1740       if (const auto *DCD = dyn_cast<Decl>(DC)) {
1741         if (const auto *TD = DCD->getDescribedTemplate()) {
1742           TemplateParameterList *TPL = TD->getTemplateParameters();
1743           auto Index = getDepthAndIndex(D).second;
1744           SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1745         }
1746       }
1747       if (SearchDefinitions)
1748         VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1749       else
1750         VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1751     } else if (isa<ParmVarDecl>(D) ||
1752                (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1753       VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1754     else if (D->isModulePrivate()) {
1755       // A module-private declaration is only visible if an enclosing lexical
1756       // parent was merged with another definition in the current module.
1757       VisibleWithinParent = false;
1758       do {
1759         if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1760           VisibleWithinParent = true;
1761           break;
1762         }
1763         DC = DC->getLexicalParent();
1764       } while (!IsEffectivelyFileContext(DC));
1765     } else {
1766       VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1767     }
1768 
1769     if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1770         // FIXME: Do something better in this case.
1771         !SemaRef.getLangOpts().ModulesLocalVisibility) {
1772       // Cache the fact that this declaration is implicitly visible because
1773       // its parent has a visible definition.
1774       D->setVisibleDespiteOwningModule();
1775     }
1776     return VisibleWithinParent;
1777   }
1778 
1779   return false;
1780 }
1781 
1782 bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1783   // The module might be ordinarily visible. For a module-private query, that
1784   // means it is part of the current module. For any other query, that means it
1785   // is in our visible module set.
1786   if (ModulePrivate) {
1787     if (isUsableModule(M))
1788       return true;
1789     else if (M->Kind == Module::ModuleKind::ModulePartitionImplementation &&
1790              isModuleDirectlyImported(M))
1791       // Unless a partition implementation is directly imported it is not
1792       // counted as visible for lookup, although the contained decls might
1793       // still be reachable.  It's a partition, so it must be part of the
1794       // current module to be a valid import.
1795       return true;
1796     else if (getLangOpts().CPlusPlusModules && !ModuleScopes.empty() &&
1797              ModuleScopes[0].Module->Kind ==
1798                  Module::ModuleKind::ModulePartitionImplementation &&
1799              ModuleScopes[0].Module->getPrimaryModuleInterfaceName() ==
1800                  M->Name &&
1801              isModuleDirectlyImported(M))
1802       // We are building a module implementation partition and the TU imports
1803       // the primary module interface unit.
1804       return true;
1805   } else {
1806     if (VisibleModules.isVisible(M))
1807       return true;
1808   }
1809 
1810   // Otherwise, it might be visible by virtue of the query being within a
1811   // template instantiation or similar that is permitted to look inside M.
1812 
1813   // Find the extra places where we need to look.
1814   const auto &LookupModules = getLookupModules();
1815   if (LookupModules.empty())
1816     return false;
1817 
1818   // If our lookup set contains the module, it's visible.
1819   if (LookupModules.count(M))
1820     return true;
1821 
1822   // For a module-private query, that's everywhere we get to look.
1823   if (ModulePrivate)
1824     return false;
1825 
1826   // Check whether M is transitively exported to an import of the lookup set.
1827   return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1828     return LookupM->isModuleVisible(M);
1829   });
1830 }
1831 
1832 bool Sema::isVisibleSlow(const NamedDecl *D) {
1833   return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1834 }
1835 
1836 bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1837   // FIXME: If there are both visible and hidden declarations, we need to take
1838   // into account whether redeclaration is possible. Example:
1839   //
1840   // Non-imported module:
1841   //   int f(T);        // #1
1842   // Some TU:
1843   //   static int f(U); // #2, not a redeclaration of #1
1844   //   int f(T);        // #3, finds both, should link with #1 if T != U, but
1845   //                    // with #2 if T == U; neither should be ambiguous.
1846   for (auto *D : R) {
1847     if (isVisible(D))
1848       return true;
1849     assert(D->isExternallyDeclarable() &&
1850            "should not have hidden, non-externally-declarable result here");
1851   }
1852 
1853   // This function is called once "New" is essentially complete, but before a
1854   // previous declaration is attached. We can't query the linkage of "New" in
1855   // general, because attaching the previous declaration can change the
1856   // linkage of New to match the previous declaration.
1857   //
1858   // However, because we've just determined that there is no *visible* prior
1859   // declaration, we can compute the linkage here. There are two possibilities:
1860   //
1861   //  * This is not a redeclaration; it's safe to compute the linkage now.
1862   //
1863   //  * This is a redeclaration of a prior declaration that is externally
1864   //    redeclarable. In that case, the linkage of the declaration is not
1865   //    changed by attaching the prior declaration, because both are externally
1866   //    declarable (and thus ExternalLinkage or VisibleNoLinkage).
1867   //
1868   // FIXME: This is subtle and fragile.
1869   return New->isExternallyDeclarable();
1870 }
1871 
1872 /// Retrieve the visible declaration corresponding to D, if any.
1873 ///
1874 /// This routine determines whether the declaration D is visible in the current
1875 /// module, with the current imports. If not, it checks whether any
1876 /// redeclaration of D is visible, and if so, returns that declaration.
1877 ///
1878 /// \returns D, or a visible previous declaration of D, whichever is more recent
1879 /// and visible. If no declaration of D is visible, returns null.
1880 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
1881                                      unsigned IDNS) {
1882   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
1883 
1884   for (auto RD : D->redecls()) {
1885     // Don't bother with extra checks if we already know this one isn't visible.
1886     if (RD == D)
1887       continue;
1888 
1889     auto ND = cast<NamedDecl>(RD);
1890     // FIXME: This is wrong in the case where the previous declaration is not
1891     // visible in the same scope as D. This needs to be done much more
1892     // carefully.
1893     if (ND->isInIdentifierNamespace(IDNS) &&
1894         LookupResult::isVisible(SemaRef, ND))
1895       return ND;
1896   }
1897 
1898   return nullptr;
1899 }
1900 
1901 bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1902                                      llvm::SmallVectorImpl<Module *> *Modules) {
1903   assert(!isVisible(D) && "not in slow case");
1904   return hasVisibleDeclarationImpl(*this, D, Modules,
1905                                    [](const NamedDecl *) { return true; });
1906 }
1907 
1908 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1909   if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1910     // Namespaces are a bit of a special case: we expect there to be a lot of
1911     // redeclarations of some namespaces, all declarations of a namespace are
1912     // essentially interchangeable, all declarations are found by name lookup
1913     // if any is, and namespaces are never looked up during template
1914     // instantiation. So we benefit from caching the check in this case, and
1915     // it is correct to do so.
1916     auto *Key = ND->getCanonicalDecl();
1917     if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1918       return Acceptable;
1919     auto *Acceptable = isVisible(getSema(), Key)
1920                            ? Key
1921                            : findAcceptableDecl(getSema(), Key, IDNS);
1922     if (Acceptable)
1923       getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1924     return Acceptable;
1925   }
1926 
1927   return findAcceptableDecl(getSema(), D, IDNS);
1928 }
1929 
1930 /// Perform unqualified name lookup starting from a given
1931 /// scope.
1932 ///
1933 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1934 /// used to find names within the current scope. For example, 'x' in
1935 /// @code
1936 /// int x;
1937 /// int f() {
1938 ///   return x; // unqualified name look finds 'x' in the global scope
1939 /// }
1940 /// @endcode
1941 ///
1942 /// Different lookup criteria can find different names. For example, a
1943 /// particular scope can have both a struct and a function of the same
1944 /// name, and each can be found by certain lookup criteria. For more
1945 /// information about lookup criteria, see the documentation for the
1946 /// class LookupCriteria.
1947 ///
1948 /// @param S        The scope from which unqualified name lookup will
1949 /// begin. If the lookup criteria permits, name lookup may also search
1950 /// in the parent scopes.
1951 ///
1952 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1953 /// look up and the lookup kind), and is updated with the results of lookup
1954 /// including zero or more declarations and possibly additional information
1955 /// used to diagnose ambiguities.
1956 ///
1957 /// @returns \c true if lookup succeeded and false otherwise.
1958 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
1959                       bool ForceNoCPlusPlus) {
1960   DeclarationName Name = R.getLookupName();
1961   if (!Name) return false;
1962 
1963   LookupNameKind NameKind = R.getLookupKind();
1964 
1965   if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
1966     // Unqualified name lookup in C/Objective-C is purely lexical, so
1967     // search in the declarations attached to the name.
1968     if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1969       // Find the nearest non-transparent declaration scope.
1970       while (!(S->getFlags() & Scope::DeclScope) ||
1971              (S->getEntity() && S->getEntity()->isTransparentContext()))
1972         S = S->getParent();
1973     }
1974 
1975     // When performing a scope lookup, we want to find local extern decls.
1976     FindLocalExternScope FindLocals(R);
1977 
1978     // Scan up the scope chain looking for a decl that matches this
1979     // identifier that is in the appropriate namespace.  This search
1980     // should not take long, as shadowing of names is uncommon, and
1981     // deep shadowing is extremely uncommon.
1982     bool LeftStartingScope = false;
1983 
1984     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1985                                    IEnd = IdResolver.end();
1986          I != IEnd; ++I)
1987       if (NamedDecl *D = R.getAcceptableDecl(*I)) {
1988         if (NameKind == LookupRedeclarationWithLinkage) {
1989           // Determine whether this (or a previous) declaration is
1990           // out-of-scope.
1991           if (!LeftStartingScope && !S->isDeclScope(*I))
1992             LeftStartingScope = true;
1993 
1994           // If we found something outside of our starting scope that
1995           // does not have linkage, skip it.
1996           if (LeftStartingScope && !((*I)->hasLinkage())) {
1997             R.setShadowed();
1998             continue;
1999           }
2000         }
2001         else if (NameKind == LookupObjCImplicitSelfParam &&
2002                  !isa<ImplicitParamDecl>(*I))
2003           continue;
2004 
2005         R.addDecl(D);
2006 
2007         // Check whether there are any other declarations with the same name
2008         // and in the same scope.
2009         if (I != IEnd) {
2010           // Find the scope in which this declaration was declared (if it
2011           // actually exists in a Scope).
2012           while (S && !S->isDeclScope(D))
2013             S = S->getParent();
2014 
2015           // If the scope containing the declaration is the translation unit,
2016           // then we'll need to perform our checks based on the matching
2017           // DeclContexts rather than matching scopes.
2018           if (S && isNamespaceOrTranslationUnitScope(S))
2019             S = nullptr;
2020 
2021           // Compute the DeclContext, if we need it.
2022           DeclContext *DC = nullptr;
2023           if (!S)
2024             DC = (*I)->getDeclContext()->getRedeclContext();
2025 
2026           IdentifierResolver::iterator LastI = I;
2027           for (++LastI; LastI != IEnd; ++LastI) {
2028             if (S) {
2029               // Match based on scope.
2030               if (!S->isDeclScope(*LastI))
2031                 break;
2032             } else {
2033               // Match based on DeclContext.
2034               DeclContext *LastDC
2035                 = (*LastI)->getDeclContext()->getRedeclContext();
2036               if (!LastDC->Equals(DC))
2037                 break;
2038             }
2039 
2040             // If the declaration is in the right namespace and visible, add it.
2041             if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2042               R.addDecl(LastD);
2043           }
2044 
2045           R.resolveKind();
2046         }
2047 
2048         return true;
2049       }
2050   } else {
2051     // Perform C++ unqualified name lookup.
2052     if (CppLookupName(R, S))
2053       return true;
2054   }
2055 
2056   // If we didn't find a use of this identifier, and if the identifier
2057   // corresponds to a compiler builtin, create the decl object for the builtin
2058   // now, injecting it into translation unit scope, and return it.
2059   if (AllowBuiltinCreation && LookupBuiltin(R))
2060     return true;
2061 
2062   // If we didn't find a use of this identifier, the ExternalSource
2063   // may be able to handle the situation.
2064   // Note: some lookup failures are expected!
2065   // See e.g. R.isForRedeclaration().
2066   return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2067 }
2068 
2069 /// Perform qualified name lookup in the namespaces nominated by
2070 /// using directives by the given context.
2071 ///
2072 /// C++98 [namespace.qual]p2:
2073 ///   Given X::m (where X is a user-declared namespace), or given \::m
2074 ///   (where X is the global namespace), let S be the set of all
2075 ///   declarations of m in X and in the transitive closure of all
2076 ///   namespaces nominated by using-directives in X and its used
2077 ///   namespaces, except that using-directives are ignored in any
2078 ///   namespace, including X, directly containing one or more
2079 ///   declarations of m. No namespace is searched more than once in
2080 ///   the lookup of a name. If S is the empty set, the program is
2081 ///   ill-formed. Otherwise, if S has exactly one member, or if the
2082 ///   context of the reference is a using-declaration
2083 ///   (namespace.udecl), S is the required set of declarations of
2084 ///   m. Otherwise if the use of m is not one that allows a unique
2085 ///   declaration to be chosen from S, the program is ill-formed.
2086 ///
2087 /// C++98 [namespace.qual]p5:
2088 ///   During the lookup of a qualified namespace member name, if the
2089 ///   lookup finds more than one declaration of the member, and if one
2090 ///   declaration introduces a class name or enumeration name and the
2091 ///   other declarations either introduce the same object, the same
2092 ///   enumerator or a set of functions, the non-type name hides the
2093 ///   class or enumeration name if and only if the declarations are
2094 ///   from the same namespace; otherwise (the declarations are from
2095 ///   different namespaces), the program is ill-formed.
2096 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
2097                                                  DeclContext *StartDC) {
2098   assert(StartDC->isFileContext() && "start context is not a file context");
2099 
2100   // We have not yet looked into these namespaces, much less added
2101   // their "using-children" to the queue.
2102   SmallVector<NamespaceDecl*, 8> Queue;
2103 
2104   // We have at least added all these contexts to the queue.
2105   llvm::SmallPtrSet<DeclContext*, 8> Visited;
2106   Visited.insert(StartDC);
2107 
2108   // We have already looked into the initial namespace; seed the queue
2109   // with its using-children.
2110   for (auto *I : StartDC->using_directives()) {
2111     NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2112     if (S.isVisible(I) && Visited.insert(ND).second)
2113       Queue.push_back(ND);
2114   }
2115 
2116   // The easiest way to implement the restriction in [namespace.qual]p5
2117   // is to check whether any of the individual results found a tag
2118   // and, if so, to declare an ambiguity if the final result is not
2119   // a tag.
2120   bool FoundTag = false;
2121   bool FoundNonTag = false;
2122 
2123   LookupResult LocalR(LookupResult::Temporary, R);
2124 
2125   bool Found = false;
2126   while (!Queue.empty()) {
2127     NamespaceDecl *ND = Queue.pop_back_val();
2128 
2129     // We go through some convolutions here to avoid copying results
2130     // between LookupResults.
2131     bool UseLocal = !R.empty();
2132     LookupResult &DirectR = UseLocal ? LocalR : R;
2133     bool FoundDirect = LookupDirect(S, DirectR, ND);
2134 
2135     if (FoundDirect) {
2136       // First do any local hiding.
2137       DirectR.resolveKind();
2138 
2139       // If the local result is a tag, remember that.
2140       if (DirectR.isSingleTagDecl())
2141         FoundTag = true;
2142       else
2143         FoundNonTag = true;
2144 
2145       // Append the local results to the total results if necessary.
2146       if (UseLocal) {
2147         R.addAllDecls(LocalR);
2148         LocalR.clear();
2149       }
2150     }
2151 
2152     // If we find names in this namespace, ignore its using directives.
2153     if (FoundDirect) {
2154       Found = true;
2155       continue;
2156     }
2157 
2158     for (auto I : ND->using_directives()) {
2159       NamespaceDecl *Nom = I->getNominatedNamespace();
2160       if (S.isVisible(I) && Visited.insert(Nom).second)
2161         Queue.push_back(Nom);
2162     }
2163   }
2164 
2165   if (Found) {
2166     if (FoundTag && FoundNonTag)
2167       R.setAmbiguousQualifiedTagHiding();
2168     else
2169       R.resolveKind();
2170   }
2171 
2172   return Found;
2173 }
2174 
2175 /// Perform qualified name lookup into a given context.
2176 ///
2177 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2178 /// names when the context of those names is explicit specified, e.g.,
2179 /// "std::vector" or "x->member", or as part of unqualified name lookup.
2180 ///
2181 /// Different lookup criteria can find different names. For example, a
2182 /// particular scope can have both a struct and a function of the same
2183 /// name, and each can be found by certain lookup criteria. For more
2184 /// information about lookup criteria, see the documentation for the
2185 /// class LookupCriteria.
2186 ///
2187 /// \param R captures both the lookup criteria and any lookup results found.
2188 ///
2189 /// \param LookupCtx The context in which qualified name lookup will
2190 /// search. If the lookup criteria permits, name lookup may also search
2191 /// in the parent contexts or (for C++ classes) base classes.
2192 ///
2193 /// \param InUnqualifiedLookup true if this is qualified name lookup that
2194 /// occurs as part of unqualified name lookup.
2195 ///
2196 /// \returns true if lookup succeeded, false if it failed.
2197 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2198                                bool InUnqualifiedLookup) {
2199   assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2200 
2201   if (!R.getLookupName())
2202     return false;
2203 
2204   // Make sure that the declaration context is complete.
2205   assert((!isa<TagDecl>(LookupCtx) ||
2206           LookupCtx->isDependentContext() ||
2207           cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2208           cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2209          "Declaration context must already be complete!");
2210 
2211   struct QualifiedLookupInScope {
2212     bool oldVal;
2213     DeclContext *Context;
2214     // Set flag in DeclContext informing debugger that we're looking for qualified name
2215     QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2216       oldVal = ctx->setUseQualifiedLookup();
2217     }
2218     ~QualifiedLookupInScope() {
2219       Context->setUseQualifiedLookup(oldVal);
2220     }
2221   } QL(LookupCtx);
2222 
2223   if (LookupDirect(*this, R, LookupCtx)) {
2224     R.resolveKind();
2225     if (isa<CXXRecordDecl>(LookupCtx))
2226       R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2227     return true;
2228   }
2229 
2230   // Don't descend into implied contexts for redeclarations.
2231   // C++98 [namespace.qual]p6:
2232   //   In a declaration for a namespace member in which the
2233   //   declarator-id is a qualified-id, given that the qualified-id
2234   //   for the namespace member has the form
2235   //     nested-name-specifier unqualified-id
2236   //   the unqualified-id shall name a member of the namespace
2237   //   designated by the nested-name-specifier.
2238   // See also [class.mfct]p5 and [class.static.data]p2.
2239   if (R.isForRedeclaration())
2240     return false;
2241 
2242   // If this is a namespace, look it up in the implied namespaces.
2243   if (LookupCtx->isFileContext())
2244     return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2245 
2246   // If this isn't a C++ class, we aren't allowed to look into base
2247   // classes, we're done.
2248   CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2249   if (!LookupRec || !LookupRec->getDefinition())
2250     return false;
2251 
2252   // We're done for lookups that can never succeed for C++ classes.
2253   if (R.getLookupKind() == LookupOperatorName ||
2254       R.getLookupKind() == LookupNamespaceName ||
2255       R.getLookupKind() == LookupObjCProtocolName ||
2256       R.getLookupKind() == LookupLabel)
2257     return false;
2258 
2259   // If we're performing qualified name lookup into a dependent class,
2260   // then we are actually looking into a current instantiation. If we have any
2261   // dependent base classes, then we either have to delay lookup until
2262   // template instantiation time (at which point all bases will be available)
2263   // or we have to fail.
2264   if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2265       LookupRec->hasAnyDependentBases()) {
2266     R.setNotFoundInCurrentInstantiation();
2267     return false;
2268   }
2269 
2270   // Perform lookup into our base classes.
2271 
2272   DeclarationName Name = R.getLookupName();
2273   unsigned IDNS = R.getIdentifierNamespace();
2274 
2275   // Look for this member in our base classes.
2276   auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2277                                    CXXBasePath &Path) -> bool {
2278     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2279     // Drop leading non-matching lookup results from the declaration list so
2280     // we don't need to consider them again below.
2281     for (Path.Decls = BaseRecord->lookup(Name).begin();
2282          Path.Decls != Path.Decls.end(); ++Path.Decls) {
2283       if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2284         return true;
2285     }
2286     return false;
2287   };
2288 
2289   CXXBasePaths Paths;
2290   Paths.setOrigin(LookupRec);
2291   if (!LookupRec->lookupInBases(BaseCallback, Paths))
2292     return false;
2293 
2294   R.setNamingClass(LookupRec);
2295 
2296   // C++ [class.member.lookup]p2:
2297   //   [...] If the resulting set of declarations are not all from
2298   //   sub-objects of the same type, or the set has a nonstatic member
2299   //   and includes members from distinct sub-objects, there is an
2300   //   ambiguity and the program is ill-formed. Otherwise that set is
2301   //   the result of the lookup.
2302   QualType SubobjectType;
2303   int SubobjectNumber = 0;
2304   AccessSpecifier SubobjectAccess = AS_none;
2305 
2306   // Check whether the given lookup result contains only static members.
2307   auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2308     for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2309       if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2310         return false;
2311     return true;
2312   };
2313 
2314   bool TemplateNameLookup = R.isTemplateNameLookup();
2315 
2316   // Determine whether two sets of members contain the same members, as
2317   // required by C++ [class.member.lookup]p6.
2318   auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2319                                  DeclContext::lookup_iterator B) {
2320     using Iterator = DeclContextLookupResult::iterator;
2321     using Result = const void *;
2322 
2323     auto Next = [&](Iterator &It, Iterator End) -> Result {
2324       while (It != End) {
2325         NamedDecl *ND = *It++;
2326         if (!ND->isInIdentifierNamespace(IDNS))
2327           continue;
2328 
2329         // C++ [temp.local]p3:
2330         //   A lookup that finds an injected-class-name (10.2) can result in
2331         //   an ambiguity in certain cases (for example, if it is found in
2332         //   more than one base class). If all of the injected-class-names
2333         //   that are found refer to specializations of the same class
2334         //   template, and if the name is used as a template-name, the
2335         //   reference refers to the class template itself and not a
2336         //   specialization thereof, and is not ambiguous.
2337         if (TemplateNameLookup)
2338           if (auto *TD = getAsTemplateNameDecl(ND))
2339             ND = TD;
2340 
2341         // C++ [class.member.lookup]p3:
2342         //   type declarations (including injected-class-names) are replaced by
2343         //   the types they designate
2344         if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2345           QualType T = Context.getTypeDeclType(TD);
2346           return T.getCanonicalType().getAsOpaquePtr();
2347         }
2348 
2349         return ND->getUnderlyingDecl()->getCanonicalDecl();
2350       }
2351       return nullptr;
2352     };
2353 
2354     // We'll often find the declarations are in the same order. Handle this
2355     // case (and the special case of only one declaration) efficiently.
2356     Iterator AIt = A, BIt = B, AEnd, BEnd;
2357     while (true) {
2358       Result AResult = Next(AIt, AEnd);
2359       Result BResult = Next(BIt, BEnd);
2360       if (!AResult && !BResult)
2361         return true;
2362       if (!AResult || !BResult)
2363         return false;
2364       if (AResult != BResult) {
2365         // Found a mismatch; carefully check both lists, accounting for the
2366         // possibility of declarations appearing more than once.
2367         llvm::SmallDenseMap<Result, bool, 32> AResults;
2368         for (; AResult; AResult = Next(AIt, AEnd))
2369           AResults.insert({AResult, /*FoundInB*/false});
2370         unsigned Found = 0;
2371         for (; BResult; BResult = Next(BIt, BEnd)) {
2372           auto It = AResults.find(BResult);
2373           if (It == AResults.end())
2374             return false;
2375           if (!It->second) {
2376             It->second = true;
2377             ++Found;
2378           }
2379         }
2380         return AResults.size() == Found;
2381       }
2382     }
2383   };
2384 
2385   for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2386        Path != PathEnd; ++Path) {
2387     const CXXBasePathElement &PathElement = Path->back();
2388 
2389     // Pick the best (i.e. most permissive i.e. numerically lowest) access
2390     // across all paths.
2391     SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2392 
2393     // Determine whether we're looking at a distinct sub-object or not.
2394     if (SubobjectType.isNull()) {
2395       // This is the first subobject we've looked at. Record its type.
2396       SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2397       SubobjectNumber = PathElement.SubobjectNumber;
2398       continue;
2399     }
2400 
2401     if (SubobjectType !=
2402         Context.getCanonicalType(PathElement.Base->getType())) {
2403       // We found members of the given name in two subobjects of
2404       // different types. If the declaration sets aren't the same, this
2405       // lookup is ambiguous.
2406       //
2407       // FIXME: The language rule says that this applies irrespective of
2408       // whether the sets contain only static members.
2409       if (HasOnlyStaticMembers(Path->Decls) &&
2410           HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2411         continue;
2412 
2413       R.setAmbiguousBaseSubobjectTypes(Paths);
2414       return true;
2415     }
2416 
2417     // FIXME: This language rule no longer exists. Checking for ambiguous base
2418     // subobjects should be done as part of formation of a class member access
2419     // expression (when converting the object parameter to the member's type).
2420     if (SubobjectNumber != PathElement.SubobjectNumber) {
2421       // We have a different subobject of the same type.
2422 
2423       // C++ [class.member.lookup]p5:
2424       //   A static member, a nested type or an enumerator defined in
2425       //   a base class T can unambiguously be found even if an object
2426       //   has more than one base class subobject of type T.
2427       if (HasOnlyStaticMembers(Path->Decls))
2428         continue;
2429 
2430       // We have found a nonstatic member name in multiple, distinct
2431       // subobjects. Name lookup is ambiguous.
2432       R.setAmbiguousBaseSubobjects(Paths);
2433       return true;
2434     }
2435   }
2436 
2437   // Lookup in a base class succeeded; return these results.
2438 
2439   for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2440        I != E; ++I) {
2441     AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2442                                                     (*I)->getAccess());
2443     if (NamedDecl *ND = R.getAcceptableDecl(*I))
2444       R.addDecl(ND, AS);
2445   }
2446   R.resolveKind();
2447   return true;
2448 }
2449 
2450 /// Performs qualified name lookup or special type of lookup for
2451 /// "__super::" scope specifier.
2452 ///
2453 /// This routine is a convenience overload meant to be called from contexts
2454 /// that need to perform a qualified name lookup with an optional C++ scope
2455 /// specifier that might require special kind of lookup.
2456 ///
2457 /// \param R captures both the lookup criteria and any lookup results found.
2458 ///
2459 /// \param LookupCtx The context in which qualified name lookup will
2460 /// search.
2461 ///
2462 /// \param SS An optional C++ scope-specifier.
2463 ///
2464 /// \returns true if lookup succeeded, false if it failed.
2465 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2466                                CXXScopeSpec &SS) {
2467   auto *NNS = SS.getScopeRep();
2468   if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2469     return LookupInSuper(R, NNS->getAsRecordDecl());
2470   else
2471 
2472     return LookupQualifiedName(R, LookupCtx);
2473 }
2474 
2475 /// Performs name lookup for a name that was parsed in the
2476 /// source code, and may contain a C++ scope specifier.
2477 ///
2478 /// This routine is a convenience routine meant to be called from
2479 /// contexts that receive a name and an optional C++ scope specifier
2480 /// (e.g., "N::M::x"). It will then perform either qualified or
2481 /// unqualified name lookup (with LookupQualifiedName or LookupName,
2482 /// respectively) on the given name and return those results. It will
2483 /// perform a special type of lookup for "__super::" scope specifier.
2484 ///
2485 /// @param S        The scope from which unqualified name lookup will
2486 /// begin.
2487 ///
2488 /// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
2489 ///
2490 /// @param EnteringContext Indicates whether we are going to enter the
2491 /// context of the scope-specifier SS (if present).
2492 ///
2493 /// @returns True if any decls were found (but possibly ambiguous)
2494 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2495                             bool AllowBuiltinCreation, bool EnteringContext) {
2496   if (SS && SS->isInvalid()) {
2497     // When the scope specifier is invalid, don't even look for
2498     // anything.
2499     return false;
2500   }
2501 
2502   if (SS && SS->isSet()) {
2503     NestedNameSpecifier *NNS = SS->getScopeRep();
2504     if (NNS->getKind() == NestedNameSpecifier::Super)
2505       return LookupInSuper(R, NNS->getAsRecordDecl());
2506 
2507     if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2508       // We have resolved the scope specifier to a particular declaration
2509       // contex, and will perform name lookup in that context.
2510       if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2511         return false;
2512 
2513       R.setContextRange(SS->getRange());
2514       return LookupQualifiedName(R, DC);
2515     }
2516 
2517     // We could not resolve the scope specified to a specific declaration
2518     // context, which means that SS refers to an unknown specialization.
2519     // Name lookup can't find anything in this case.
2520     R.setNotFoundInCurrentInstantiation();
2521     R.setContextRange(SS->getRange());
2522     return false;
2523   }
2524 
2525   // Perform unqualified name lookup starting in the given scope.
2526   return LookupName(R, S, AllowBuiltinCreation);
2527 }
2528 
2529 /// Perform qualified name lookup into all base classes of the given
2530 /// class.
2531 ///
2532 /// \param R captures both the lookup criteria and any lookup results found.
2533 ///
2534 /// \param Class The context in which qualified name lookup will
2535 /// search. Name lookup will search in all base classes merging the results.
2536 ///
2537 /// @returns True if any decls were found (but possibly ambiguous)
2538 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2539   // The access-control rules we use here are essentially the rules for
2540   // doing a lookup in Class that just magically skipped the direct
2541   // members of Class itself.  That is, the naming class is Class, and the
2542   // access includes the access of the base.
2543   for (const auto &BaseSpec : Class->bases()) {
2544     CXXRecordDecl *RD = cast<CXXRecordDecl>(
2545         BaseSpec.getType()->castAs<RecordType>()->getDecl());
2546     LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2547     Result.setBaseObjectType(Context.getRecordType(Class));
2548     LookupQualifiedName(Result, RD);
2549 
2550     // Copy the lookup results into the target, merging the base's access into
2551     // the path access.
2552     for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2553       R.addDecl(I.getDecl(),
2554                 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2555                                            I.getAccess()));
2556     }
2557 
2558     Result.suppressDiagnostics();
2559   }
2560 
2561   R.resolveKind();
2562   R.setNamingClass(Class);
2563 
2564   return !R.empty();
2565 }
2566 
2567 /// Produce a diagnostic describing the ambiguity that resulted
2568 /// from name lookup.
2569 ///
2570 /// \param Result The result of the ambiguous lookup to be diagnosed.
2571 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2572   assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2573 
2574   DeclarationName Name = Result.getLookupName();
2575   SourceLocation NameLoc = Result.getNameLoc();
2576   SourceRange LookupRange = Result.getContextRange();
2577 
2578   switch (Result.getAmbiguityKind()) {
2579   case LookupResult::AmbiguousBaseSubobjects: {
2580     CXXBasePaths *Paths = Result.getBasePaths();
2581     QualType SubobjectType = Paths->front().back().Base->getType();
2582     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2583       << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2584       << LookupRange;
2585 
2586     DeclContext::lookup_iterator Found = Paths->front().Decls;
2587     while (isa<CXXMethodDecl>(*Found) &&
2588            cast<CXXMethodDecl>(*Found)->isStatic())
2589       ++Found;
2590 
2591     Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2592     break;
2593   }
2594 
2595   case LookupResult::AmbiguousBaseSubobjectTypes: {
2596     Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2597       << Name << LookupRange;
2598 
2599     CXXBasePaths *Paths = Result.getBasePaths();
2600     std::set<const NamedDecl *> DeclsPrinted;
2601     for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2602                                       PathEnd = Paths->end();
2603          Path != PathEnd; ++Path) {
2604       const NamedDecl *D = *Path->Decls;
2605       if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2606         continue;
2607       if (DeclsPrinted.insert(D).second) {
2608         if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2609           Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2610               << TD->getUnderlyingType();
2611         else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2612           Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2613               << Context.getTypeDeclType(TD);
2614         else
2615           Diag(D->getLocation(), diag::note_ambiguous_member_found);
2616       }
2617     }
2618     break;
2619   }
2620 
2621   case LookupResult::AmbiguousTagHiding: {
2622     Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2623 
2624     llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2625 
2626     for (auto *D : Result)
2627       if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2628         TagDecls.insert(TD);
2629         Diag(TD->getLocation(), diag::note_hidden_tag);
2630       }
2631 
2632     for (auto *D : Result)
2633       if (!isa<TagDecl>(D))
2634         Diag(D->getLocation(), diag::note_hiding_object);
2635 
2636     // For recovery purposes, go ahead and implement the hiding.
2637     LookupResult::Filter F = Result.makeFilter();
2638     while (F.hasNext()) {
2639       if (TagDecls.count(F.next()))
2640         F.erase();
2641     }
2642     F.done();
2643     break;
2644   }
2645 
2646   case LookupResult::AmbiguousReference: {
2647     Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2648 
2649     for (auto *D : Result)
2650       Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2651     break;
2652   }
2653   }
2654 }
2655 
2656 namespace {
2657   struct AssociatedLookup {
2658     AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2659                      Sema::AssociatedNamespaceSet &Namespaces,
2660                      Sema::AssociatedClassSet &Classes)
2661       : S(S), Namespaces(Namespaces), Classes(Classes),
2662         InstantiationLoc(InstantiationLoc) {
2663     }
2664 
2665     bool addClassTransitive(CXXRecordDecl *RD) {
2666       Classes.insert(RD);
2667       return ClassesTransitive.insert(RD);
2668     }
2669 
2670     Sema &S;
2671     Sema::AssociatedNamespaceSet &Namespaces;
2672     Sema::AssociatedClassSet &Classes;
2673     SourceLocation InstantiationLoc;
2674 
2675   private:
2676     Sema::AssociatedClassSet ClassesTransitive;
2677   };
2678 } // end anonymous namespace
2679 
2680 static void
2681 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2682 
2683 // Given the declaration context \param Ctx of a class, class template or
2684 // enumeration, add the associated namespaces to \param Namespaces as described
2685 // in [basic.lookup.argdep]p2.
2686 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2687                                       DeclContext *Ctx) {
2688   // The exact wording has been changed in C++14 as a result of
2689   // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2690   // to all language versions since it is possible to return a local type
2691   // from a lambda in C++11.
2692   //
2693   // C++14 [basic.lookup.argdep]p2:
2694   //   If T is a class type [...]. Its associated namespaces are the innermost
2695   //   enclosing namespaces of its associated classes. [...]
2696   //
2697   //   If T is an enumeration type, its associated namespace is the innermost
2698   //   enclosing namespace of its declaration. [...]
2699 
2700   // We additionally skip inline namespaces. The innermost non-inline namespace
2701   // contains all names of all its nested inline namespaces anyway, so we can
2702   // replace the entire inline namespace tree with its root.
2703   while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2704     Ctx = Ctx->getParent();
2705 
2706   Namespaces.insert(Ctx->getPrimaryContext());
2707 }
2708 
2709 // Add the associated classes and namespaces for argument-dependent
2710 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2711 static void
2712 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2713                                   const TemplateArgument &Arg) {
2714   // C++ [basic.lookup.argdep]p2, last bullet:
2715   //   -- [...] ;
2716   switch (Arg.getKind()) {
2717     case TemplateArgument::Null:
2718       break;
2719 
2720     case TemplateArgument::Type:
2721       // [...] the namespaces and classes associated with the types of the
2722       // template arguments provided for template type parameters (excluding
2723       // template template parameters)
2724       addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2725       break;
2726 
2727     case TemplateArgument::Template:
2728     case TemplateArgument::TemplateExpansion: {
2729       // [...] the namespaces in which any template template arguments are
2730       // defined; and the classes in which any member templates used as
2731       // template template arguments are defined.
2732       TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2733       if (ClassTemplateDecl *ClassTemplate
2734                  = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2735         DeclContext *Ctx = ClassTemplate->getDeclContext();
2736         if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2737           Result.Classes.insert(EnclosingClass);
2738         // Add the associated namespace for this class.
2739         CollectEnclosingNamespace(Result.Namespaces, Ctx);
2740       }
2741       break;
2742     }
2743 
2744     case TemplateArgument::Declaration:
2745     case TemplateArgument::Integral:
2746     case TemplateArgument::Expression:
2747     case TemplateArgument::NullPtr:
2748       // [Note: non-type template arguments do not contribute to the set of
2749       //  associated namespaces. ]
2750       break;
2751 
2752     case TemplateArgument::Pack:
2753       for (const auto &P : Arg.pack_elements())
2754         addAssociatedClassesAndNamespaces(Result, P);
2755       break;
2756   }
2757 }
2758 
2759 // Add the associated classes and namespaces for argument-dependent lookup
2760 // with an argument of class type (C++ [basic.lookup.argdep]p2).
2761 static void
2762 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2763                                   CXXRecordDecl *Class) {
2764 
2765   // Just silently ignore anything whose name is __va_list_tag.
2766   if (Class->getDeclName() == Result.S.VAListTagName)
2767     return;
2768 
2769   // C++ [basic.lookup.argdep]p2:
2770   //   [...]
2771   //     -- If T is a class type (including unions), its associated
2772   //        classes are: the class itself; the class of which it is a
2773   //        member, if any; and its direct and indirect base classes.
2774   //        Its associated namespaces are the innermost enclosing
2775   //        namespaces of its associated classes.
2776 
2777   // Add the class of which it is a member, if any.
2778   DeclContext *Ctx = Class->getDeclContext();
2779   if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2780     Result.Classes.insert(EnclosingClass);
2781 
2782   // Add the associated namespace for this class.
2783   CollectEnclosingNamespace(Result.Namespaces, Ctx);
2784 
2785   // -- If T is a template-id, its associated namespaces and classes are
2786   //    the namespace in which the template is defined; for member
2787   //    templates, the member template's class; the namespaces and classes
2788   //    associated with the types of the template arguments provided for
2789   //    template type parameters (excluding template template parameters); the
2790   //    namespaces in which any template template arguments are defined; and
2791   //    the classes in which any member templates used as template template
2792   //    arguments are defined. [Note: non-type template arguments do not
2793   //    contribute to the set of associated namespaces. ]
2794   if (ClassTemplateSpecializationDecl *Spec
2795         = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2796     DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2797     if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2798       Result.Classes.insert(EnclosingClass);
2799     // Add the associated namespace for this class.
2800     CollectEnclosingNamespace(Result.Namespaces, Ctx);
2801 
2802     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2803     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2804       addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2805   }
2806 
2807   // Add the class itself. If we've already transitively visited this class,
2808   // we don't need to visit base classes.
2809   if (!Result.addClassTransitive(Class))
2810     return;
2811 
2812   // Only recurse into base classes for complete types.
2813   if (!Result.S.isCompleteType(Result.InstantiationLoc,
2814                                Result.S.Context.getRecordType(Class)))
2815     return;
2816 
2817   // Add direct and indirect base classes along with their associated
2818   // namespaces.
2819   SmallVector<CXXRecordDecl *, 32> Bases;
2820   Bases.push_back(Class);
2821   while (!Bases.empty()) {
2822     // Pop this class off the stack.
2823     Class = Bases.pop_back_val();
2824 
2825     // Visit the base classes.
2826     for (const auto &Base : Class->bases()) {
2827       const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2828       // In dependent contexts, we do ADL twice, and the first time around,
2829       // the base type might be a dependent TemplateSpecializationType, or a
2830       // TemplateTypeParmType. If that happens, simply ignore it.
2831       // FIXME: If we want to support export, we probably need to add the
2832       // namespace of the template in a TemplateSpecializationType, or even
2833       // the classes and namespaces of known non-dependent arguments.
2834       if (!BaseType)
2835         continue;
2836       CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2837       if (Result.addClassTransitive(BaseDecl)) {
2838         // Find the associated namespace for this base class.
2839         DeclContext *BaseCtx = BaseDecl->getDeclContext();
2840         CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2841 
2842         // Make sure we visit the bases of this base class.
2843         if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2844           Bases.push_back(BaseDecl);
2845       }
2846     }
2847   }
2848 }
2849 
2850 // Add the associated classes and namespaces for
2851 // argument-dependent lookup with an argument of type T
2852 // (C++ [basic.lookup.koenig]p2).
2853 static void
2854 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2855   // C++ [basic.lookup.koenig]p2:
2856   //
2857   //   For each argument type T in the function call, there is a set
2858   //   of zero or more associated namespaces and a set of zero or more
2859   //   associated classes to be considered. The sets of namespaces and
2860   //   classes is determined entirely by the types of the function
2861   //   arguments (and the namespace of any template template
2862   //   argument). Typedef names and using-declarations used to specify
2863   //   the types do not contribute to this set. The sets of namespaces
2864   //   and classes are determined in the following way:
2865 
2866   SmallVector<const Type *, 16> Queue;
2867   const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2868 
2869   while (true) {
2870     switch (T->getTypeClass()) {
2871 
2872 #define TYPE(Class, Base)
2873 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2874 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2875 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2876 #define ABSTRACT_TYPE(Class, Base)
2877 #include "clang/AST/TypeNodes.inc"
2878       // T is canonical.  We can also ignore dependent types because
2879       // we don't need to do ADL at the definition point, but if we
2880       // wanted to implement template export (or if we find some other
2881       // use for associated classes and namespaces...) this would be
2882       // wrong.
2883       break;
2884 
2885     //    -- If T is a pointer to U or an array of U, its associated
2886     //       namespaces and classes are those associated with U.
2887     case Type::Pointer:
2888       T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2889       continue;
2890     case Type::ConstantArray:
2891     case Type::IncompleteArray:
2892     case Type::VariableArray:
2893       T = cast<ArrayType>(T)->getElementType().getTypePtr();
2894       continue;
2895 
2896     //     -- If T is a fundamental type, its associated sets of
2897     //        namespaces and classes are both empty.
2898     case Type::Builtin:
2899       break;
2900 
2901     //     -- If T is a class type (including unions), its associated
2902     //        classes are: the class itself; the class of which it is
2903     //        a member, if any; and its direct and indirect base classes.
2904     //        Its associated namespaces are the innermost enclosing
2905     //        namespaces of its associated classes.
2906     case Type::Record: {
2907       CXXRecordDecl *Class =
2908           cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2909       addAssociatedClassesAndNamespaces(Result, Class);
2910       break;
2911     }
2912 
2913     //     -- If T is an enumeration type, its associated namespace
2914     //        is the innermost enclosing namespace of its declaration.
2915     //        If it is a class member, its associated class is the
2916     //        member’s class; else it has no associated class.
2917     case Type::Enum: {
2918       EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2919 
2920       DeclContext *Ctx = Enum->getDeclContext();
2921       if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2922         Result.Classes.insert(EnclosingClass);
2923 
2924       // Add the associated namespace for this enumeration.
2925       CollectEnclosingNamespace(Result.Namespaces, Ctx);
2926 
2927       break;
2928     }
2929 
2930     //     -- If T is a function type, its associated namespaces and
2931     //        classes are those associated with the function parameter
2932     //        types and those associated with the return type.
2933     case Type::FunctionProto: {
2934       const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2935       for (const auto &Arg : Proto->param_types())
2936         Queue.push_back(Arg.getTypePtr());
2937       // fallthrough
2938       LLVM_FALLTHROUGH;
2939     }
2940     case Type::FunctionNoProto: {
2941       const FunctionType *FnType = cast<FunctionType>(T);
2942       T = FnType->getReturnType().getTypePtr();
2943       continue;
2944     }
2945 
2946     //     -- If T is a pointer to a member function of a class X, its
2947     //        associated namespaces and classes are those associated
2948     //        with the function parameter types and return type,
2949     //        together with those associated with X.
2950     //
2951     //     -- If T is a pointer to a data member of class X, its
2952     //        associated namespaces and classes are those associated
2953     //        with the member type together with those associated with
2954     //        X.
2955     case Type::MemberPointer: {
2956       const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2957 
2958       // Queue up the class type into which this points.
2959       Queue.push_back(MemberPtr->getClass());
2960 
2961       // And directly continue with the pointee type.
2962       T = MemberPtr->getPointeeType().getTypePtr();
2963       continue;
2964     }
2965 
2966     // As an extension, treat this like a normal pointer.
2967     case Type::BlockPointer:
2968       T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2969       continue;
2970 
2971     // References aren't covered by the standard, but that's such an
2972     // obvious defect that we cover them anyway.
2973     case Type::LValueReference:
2974     case Type::RValueReference:
2975       T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2976       continue;
2977 
2978     // These are fundamental types.
2979     case Type::Vector:
2980     case Type::ExtVector:
2981     case Type::ConstantMatrix:
2982     case Type::Complex:
2983     case Type::BitInt:
2984       break;
2985 
2986     // Non-deduced auto types only get here for error cases.
2987     case Type::Auto:
2988     case Type::DeducedTemplateSpecialization:
2989       break;
2990 
2991     // If T is an Objective-C object or interface type, or a pointer to an
2992     // object or interface type, the associated namespace is the global
2993     // namespace.
2994     case Type::ObjCObject:
2995     case Type::ObjCInterface:
2996     case Type::ObjCObjectPointer:
2997       Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2998       break;
2999 
3000     // Atomic types are just wrappers; use the associations of the
3001     // contained type.
3002     case Type::Atomic:
3003       T = cast<AtomicType>(T)->getValueType().getTypePtr();
3004       continue;
3005     case Type::Pipe:
3006       T = cast<PipeType>(T)->getElementType().getTypePtr();
3007       continue;
3008     }
3009 
3010     if (Queue.empty())
3011       break;
3012     T = Queue.pop_back_val();
3013   }
3014 }
3015 
3016 /// Find the associated classes and namespaces for
3017 /// argument-dependent lookup for a call with the given set of
3018 /// arguments.
3019 ///
3020 /// This routine computes the sets of associated classes and associated
3021 /// namespaces searched by argument-dependent lookup
3022 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
3023 void Sema::FindAssociatedClassesAndNamespaces(
3024     SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3025     AssociatedNamespaceSet &AssociatedNamespaces,
3026     AssociatedClassSet &AssociatedClasses) {
3027   AssociatedNamespaces.clear();
3028   AssociatedClasses.clear();
3029 
3030   AssociatedLookup Result(*this, InstantiationLoc,
3031                           AssociatedNamespaces, AssociatedClasses);
3032 
3033   // C++ [basic.lookup.koenig]p2:
3034   //   For each argument type T in the function call, there is a set
3035   //   of zero or more associated namespaces and a set of zero or more
3036   //   associated classes to be considered. The sets of namespaces and
3037   //   classes is determined entirely by the types of the function
3038   //   arguments (and the namespace of any template template
3039   //   argument).
3040   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3041     Expr *Arg = Args[ArgIdx];
3042 
3043     if (Arg->getType() != Context.OverloadTy) {
3044       addAssociatedClassesAndNamespaces(Result, Arg->getType());
3045       continue;
3046     }
3047 
3048     // [...] In addition, if the argument is the name or address of a
3049     // set of overloaded functions and/or function templates, its
3050     // associated classes and namespaces are the union of those
3051     // associated with each of the members of the set: the namespace
3052     // in which the function or function template is defined and the
3053     // classes and namespaces associated with its (non-dependent)
3054     // parameter types and return type.
3055     OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
3056 
3057     for (const NamedDecl *D : OE->decls()) {
3058       // Look through any using declarations to find the underlying function.
3059       const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3060 
3061       // Add the classes and namespaces associated with the parameter
3062       // types and return type of this function.
3063       addAssociatedClassesAndNamespaces(Result, FDecl->getType());
3064     }
3065   }
3066 }
3067 
3068 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
3069                                   SourceLocation Loc,
3070                                   LookupNameKind NameKind,
3071                                   RedeclarationKind Redecl) {
3072   LookupResult R(*this, Name, Loc, NameKind, Redecl);
3073   LookupName(R, S);
3074   return R.getAsSingle<NamedDecl>();
3075 }
3076 
3077 /// Find the protocol with the given name, if any.
3078 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
3079                                        SourceLocation IdLoc,
3080                                        RedeclarationKind Redecl) {
3081   Decl *D = LookupSingleName(TUScope, II, IdLoc,
3082                              LookupObjCProtocolName, Redecl);
3083   return cast_or_null<ObjCProtocolDecl>(D);
3084 }
3085 
3086 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3087                                         UnresolvedSetImpl &Functions) {
3088   // C++ [over.match.oper]p3:
3089   //     -- The set of non-member candidates is the result of the
3090   //        unqualified lookup of operator@ in the context of the
3091   //        expression according to the usual rules for name lookup in
3092   //        unqualified function calls (3.4.2) except that all member
3093   //        functions are ignored.
3094   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3095   LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3096   LookupName(Operators, S);
3097 
3098   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3099   Functions.append(Operators.begin(), Operators.end());
3100 }
3101 
3102 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
3103                                                            CXXSpecialMember SM,
3104                                                            bool ConstArg,
3105                                                            bool VolatileArg,
3106                                                            bool RValueThis,
3107                                                            bool ConstThis,
3108                                                            bool VolatileThis) {
3109   assert(CanDeclareSpecialMemberFunction(RD) &&
3110          "doing special member lookup into record that isn't fully complete");
3111   RD = RD->getDefinition();
3112   if (RValueThis || ConstThis || VolatileThis)
3113     assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
3114            "constructors and destructors always have unqualified lvalue this");
3115   if (ConstArg || VolatileArg)
3116     assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
3117            "parameter-less special members can't have qualified arguments");
3118 
3119   // FIXME: Get the caller to pass in a location for the lookup.
3120   SourceLocation LookupLoc = RD->getLocation();
3121 
3122   llvm::FoldingSetNodeID ID;
3123   ID.AddPointer(RD);
3124   ID.AddInteger(SM);
3125   ID.AddInteger(ConstArg);
3126   ID.AddInteger(VolatileArg);
3127   ID.AddInteger(RValueThis);
3128   ID.AddInteger(ConstThis);
3129   ID.AddInteger(VolatileThis);
3130 
3131   void *InsertPoint;
3132   SpecialMemberOverloadResultEntry *Result =
3133     SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3134 
3135   // This was already cached
3136   if (Result)
3137     return *Result;
3138 
3139   Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
3140   Result = new (Result) SpecialMemberOverloadResultEntry(ID);
3141   SpecialMemberCache.InsertNode(Result, InsertPoint);
3142 
3143   if (SM == CXXDestructor) {
3144     if (RD->needsImplicitDestructor()) {
3145       runWithSufficientStackSpace(RD->getLocation(), [&] {
3146         DeclareImplicitDestructor(RD);
3147       });
3148     }
3149     CXXDestructorDecl *DD = RD->getDestructor();
3150     Result->setMethod(DD);
3151     Result->setKind(DD && !DD->isDeleted()
3152                         ? SpecialMemberOverloadResult::Success
3153                         : SpecialMemberOverloadResult::NoMemberOrDeleted);
3154     return *Result;
3155   }
3156 
3157   // Prepare for overload resolution. Here we construct a synthetic argument
3158   // if necessary and make sure that implicit functions are declared.
3159   CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
3160   DeclarationName Name;
3161   Expr *Arg = nullptr;
3162   unsigned NumArgs;
3163 
3164   QualType ArgType = CanTy;
3165   ExprValueKind VK = VK_LValue;
3166 
3167   if (SM == CXXDefaultConstructor) {
3168     Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3169     NumArgs = 0;
3170     if (RD->needsImplicitDefaultConstructor()) {
3171       runWithSufficientStackSpace(RD->getLocation(), [&] {
3172         DeclareImplicitDefaultConstructor(RD);
3173       });
3174     }
3175   } else {
3176     if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
3177       Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3178       if (RD->needsImplicitCopyConstructor()) {
3179         runWithSufficientStackSpace(RD->getLocation(), [&] {
3180           DeclareImplicitCopyConstructor(RD);
3181         });
3182       }
3183       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
3184         runWithSufficientStackSpace(RD->getLocation(), [&] {
3185           DeclareImplicitMoveConstructor(RD);
3186         });
3187       }
3188     } else {
3189       Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3190       if (RD->needsImplicitCopyAssignment()) {
3191         runWithSufficientStackSpace(RD->getLocation(), [&] {
3192           DeclareImplicitCopyAssignment(RD);
3193         });
3194       }
3195       if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
3196         runWithSufficientStackSpace(RD->getLocation(), [&] {
3197           DeclareImplicitMoveAssignment(RD);
3198         });
3199       }
3200     }
3201 
3202     if (ConstArg)
3203       ArgType.addConst();
3204     if (VolatileArg)
3205       ArgType.addVolatile();
3206 
3207     // This isn't /really/ specified by the standard, but it's implied
3208     // we should be working from a PRValue in the case of move to ensure
3209     // that we prefer to bind to rvalue references, and an LValue in the
3210     // case of copy to ensure we don't bind to rvalue references.
3211     // Possibly an XValue is actually correct in the case of move, but
3212     // there is no semantic difference for class types in this restricted
3213     // case.
3214     if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
3215       VK = VK_LValue;
3216     else
3217       VK = VK_PRValue;
3218   }
3219 
3220   OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3221 
3222   if (SM != CXXDefaultConstructor) {
3223     NumArgs = 1;
3224     Arg = &FakeArg;
3225   }
3226 
3227   // Create the object argument
3228   QualType ThisTy = CanTy;
3229   if (ConstThis)
3230     ThisTy.addConst();
3231   if (VolatileThis)
3232     ThisTy.addVolatile();
3233   Expr::Classification Classification =
3234       OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3235           .Classify(Context);
3236 
3237   // Now we perform lookup on the name we computed earlier and do overload
3238   // resolution. Lookup is only performed directly into the class since there
3239   // will always be a (possibly implicit) declaration to shadow any others.
3240   OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
3241   DeclContext::lookup_result R = RD->lookup(Name);
3242 
3243   if (R.empty()) {
3244     // We might have no default constructor because we have a lambda's closure
3245     // type, rather than because there's some other declared constructor.
3246     // Every class has a copy/move constructor, copy/move assignment, and
3247     // destructor.
3248     assert(SM == CXXDefaultConstructor &&
3249            "lookup for a constructor or assignment operator was empty");
3250     Result->setMethod(nullptr);
3251     Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3252     return *Result;
3253   }
3254 
3255   // Copy the candidates as our processing of them may load new declarations
3256   // from an external source and invalidate lookup_result.
3257   SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3258 
3259   for (NamedDecl *CandDecl : Candidates) {
3260     if (CandDecl->isInvalidDecl())
3261       continue;
3262 
3263     DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3264     auto CtorInfo = getConstructorInfo(Cand);
3265     if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3266       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3267         AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3268                            llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3269       else if (CtorInfo)
3270         AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3271                              llvm::makeArrayRef(&Arg, NumArgs), OCS,
3272                              /*SuppressUserConversions*/ true);
3273       else
3274         AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3275                              /*SuppressUserConversions*/ true);
3276     } else if (FunctionTemplateDecl *Tmpl =
3277                  dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3278       if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3279         AddMethodTemplateCandidate(
3280             Tmpl, Cand, RD, nullptr, ThisTy, Classification,
3281             llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3282       else if (CtorInfo)
3283         AddTemplateOverloadCandidate(
3284             CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3285             llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3286       else
3287         AddTemplateOverloadCandidate(
3288             Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3289     } else {
3290       assert(isa<UsingDecl>(Cand.getDecl()) &&
3291              "illegal Kind of operator = Decl");
3292     }
3293   }
3294 
3295   OverloadCandidateSet::iterator Best;
3296   switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3297     case OR_Success:
3298       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3299       Result->setKind(SpecialMemberOverloadResult::Success);
3300       break;
3301 
3302     case OR_Deleted:
3303       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3304       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3305       break;
3306 
3307     case OR_Ambiguous:
3308       Result->setMethod(nullptr);
3309       Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3310       break;
3311 
3312     case OR_No_Viable_Function:
3313       Result->setMethod(nullptr);
3314       Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3315       break;
3316   }
3317 
3318   return *Result;
3319 }
3320 
3321 /// Look up the default constructor for the given class.
3322 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3323   SpecialMemberOverloadResult Result =
3324     LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3325                         false, false);
3326 
3327   return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3328 }
3329 
3330 /// Look up the copying constructor for the given class.
3331 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3332                                                    unsigned Quals) {
3333   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3334          "non-const, non-volatile qualifiers for copy ctor arg");
3335   SpecialMemberOverloadResult Result =
3336     LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3337                         Quals & Qualifiers::Volatile, false, false, false);
3338 
3339   return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3340 }
3341 
3342 /// Look up the moving constructor for the given class.
3343 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3344                                                   unsigned Quals) {
3345   SpecialMemberOverloadResult Result =
3346     LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3347                         Quals & Qualifiers::Volatile, false, false, false);
3348 
3349   return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3350 }
3351 
3352 /// Look up the constructors for the given class.
3353 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3354   // If the implicit constructors have not yet been declared, do so now.
3355   if (CanDeclareSpecialMemberFunction(Class)) {
3356     runWithSufficientStackSpace(Class->getLocation(), [&] {
3357       if (Class->needsImplicitDefaultConstructor())
3358         DeclareImplicitDefaultConstructor(Class);
3359       if (Class->needsImplicitCopyConstructor())
3360         DeclareImplicitCopyConstructor(Class);
3361       if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3362         DeclareImplicitMoveConstructor(Class);
3363     });
3364   }
3365 
3366   CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3367   DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3368   return Class->lookup(Name);
3369 }
3370 
3371 /// Look up the copying assignment operator for the given class.
3372 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3373                                              unsigned Quals, bool RValueThis,
3374                                              unsigned ThisQuals) {
3375   assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3376          "non-const, non-volatile qualifiers for copy assignment arg");
3377   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3378          "non-const, non-volatile qualifiers for copy assignment this");
3379   SpecialMemberOverloadResult Result =
3380     LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3381                         Quals & Qualifiers::Volatile, RValueThis,
3382                         ThisQuals & Qualifiers::Const,
3383                         ThisQuals & Qualifiers::Volatile);
3384 
3385   return Result.getMethod();
3386 }
3387 
3388 /// Look up the moving assignment operator for the given class.
3389 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3390                                             unsigned Quals,
3391                                             bool RValueThis,
3392                                             unsigned ThisQuals) {
3393   assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3394          "non-const, non-volatile qualifiers for copy assignment this");
3395   SpecialMemberOverloadResult Result =
3396     LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3397                         Quals & Qualifiers::Volatile, RValueThis,
3398                         ThisQuals & Qualifiers::Const,
3399                         ThisQuals & Qualifiers::Volatile);
3400 
3401   return Result.getMethod();
3402 }
3403 
3404 /// Look for the destructor of the given class.
3405 ///
3406 /// During semantic analysis, this routine should be used in lieu of
3407 /// CXXRecordDecl::getDestructor().
3408 ///
3409 /// \returns The destructor for this class.
3410 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3411   return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3412                                                      false, false, false,
3413                                                      false, false).getMethod());
3414 }
3415 
3416 /// LookupLiteralOperator - Determine which literal operator should be used for
3417 /// a user-defined literal, per C++11 [lex.ext].
3418 ///
3419 /// Normal overload resolution is not used to select which literal operator to
3420 /// call for a user-defined literal. Look up the provided literal operator name,
3421 /// and filter the results to the appropriate set for the given argument types.
3422 Sema::LiteralOperatorLookupResult
3423 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3424                             ArrayRef<QualType> ArgTys, bool AllowRaw,
3425                             bool AllowTemplate, bool AllowStringTemplatePack,
3426                             bool DiagnoseMissing, StringLiteral *StringLit) {
3427   LookupName(R, S);
3428   assert(R.getResultKind() != LookupResult::Ambiguous &&
3429          "literal operator lookup can't be ambiguous");
3430 
3431   // Filter the lookup results appropriately.
3432   LookupResult::Filter F = R.makeFilter();
3433 
3434   bool AllowCooked = true;
3435   bool FoundRaw = false;
3436   bool FoundTemplate = false;
3437   bool FoundStringTemplatePack = false;
3438   bool FoundCooked = false;
3439 
3440   while (F.hasNext()) {
3441     Decl *D = F.next();
3442     if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3443       D = USD->getTargetDecl();
3444 
3445     // If the declaration we found is invalid, skip it.
3446     if (D->isInvalidDecl()) {
3447       F.erase();
3448       continue;
3449     }
3450 
3451     bool IsRaw = false;
3452     bool IsTemplate = false;
3453     bool IsStringTemplatePack = false;
3454     bool IsCooked = false;
3455 
3456     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3457       if (FD->getNumParams() == 1 &&
3458           FD->getParamDecl(0)->getType()->getAs<PointerType>())
3459         IsRaw = true;
3460       else if (FD->getNumParams() == ArgTys.size()) {
3461         IsCooked = true;
3462         for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3463           QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3464           if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3465             IsCooked = false;
3466             break;
3467           }
3468         }
3469       }
3470     }
3471     if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3472       TemplateParameterList *Params = FD->getTemplateParameters();
3473       if (Params->size() == 1) {
3474         IsTemplate = true;
3475         if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3476           // Implied but not stated: user-defined integer and floating literals
3477           // only ever use numeric literal operator templates, not templates
3478           // taking a parameter of class type.
3479           F.erase();
3480           continue;
3481         }
3482 
3483         // A string literal template is only considered if the string literal
3484         // is a well-formed template argument for the template parameter.
3485         if (StringLit) {
3486           SFINAETrap Trap(*this);
3487           SmallVector<TemplateArgument, 1> Checked;
3488           TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3489           if (CheckTemplateArgument(Params->getParam(0), Arg, FD,
3490                                     R.getNameLoc(), R.getNameLoc(), 0,
3491                                     Checked) ||
3492               Trap.hasErrorOccurred())
3493             IsTemplate = false;
3494         }
3495       } else {
3496         IsStringTemplatePack = true;
3497       }
3498     }
3499 
3500     if (AllowTemplate && StringLit && IsTemplate) {
3501       FoundTemplate = true;
3502       AllowRaw = false;
3503       AllowCooked = false;
3504       AllowStringTemplatePack = false;
3505       if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3506         F.restart();
3507         FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3508       }
3509     } else if (AllowCooked && IsCooked) {
3510       FoundCooked = true;
3511       AllowRaw = false;
3512       AllowTemplate = StringLit;
3513       AllowStringTemplatePack = false;
3514       if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3515         // Go through again and remove the raw and template decls we've
3516         // already found.
3517         F.restart();
3518         FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3519       }
3520     } else if (AllowRaw && IsRaw) {
3521       FoundRaw = true;
3522     } else if (AllowTemplate && IsTemplate) {
3523       FoundTemplate = true;
3524     } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3525       FoundStringTemplatePack = true;
3526     } else {
3527       F.erase();
3528     }
3529   }
3530 
3531   F.done();
3532 
3533   // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3534   // form for string literal operator templates.
3535   if (StringLit && FoundTemplate)
3536     return LOLR_Template;
3537 
3538   // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3539   // parameter type, that is used in preference to a raw literal operator
3540   // or literal operator template.
3541   if (FoundCooked)
3542     return LOLR_Cooked;
3543 
3544   // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3545   // operator template, but not both.
3546   if (FoundRaw && FoundTemplate) {
3547     Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3548     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3549       NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
3550     return LOLR_Error;
3551   }
3552 
3553   if (FoundRaw)
3554     return LOLR_Raw;
3555 
3556   if (FoundTemplate)
3557     return LOLR_Template;
3558 
3559   if (FoundStringTemplatePack)
3560     return LOLR_StringTemplatePack;
3561 
3562   // Didn't find anything we could use.
3563   if (DiagnoseMissing) {
3564     Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3565         << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3566         << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3567         << (AllowTemplate || AllowStringTemplatePack);
3568     return LOLR_Error;
3569   }
3570 
3571   return LOLR_ErrorNoDiagnostic;
3572 }
3573 
3574 void ADLResult::insert(NamedDecl *New) {
3575   NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3576 
3577   // If we haven't yet seen a decl for this key, or the last decl
3578   // was exactly this one, we're done.
3579   if (Old == nullptr || Old == New) {
3580     Old = New;
3581     return;
3582   }
3583 
3584   // Otherwise, decide which is a more recent redeclaration.
3585   FunctionDecl *OldFD = Old->getAsFunction();
3586   FunctionDecl *NewFD = New->getAsFunction();
3587 
3588   FunctionDecl *Cursor = NewFD;
3589   while (true) {
3590     Cursor = Cursor->getPreviousDecl();
3591 
3592     // If we got to the end without finding OldFD, OldFD is the newer
3593     // declaration;  leave things as they are.
3594     if (!Cursor) return;
3595 
3596     // If we do find OldFD, then NewFD is newer.
3597     if (Cursor == OldFD) break;
3598 
3599     // Otherwise, keep looking.
3600   }
3601 
3602   Old = New;
3603 }
3604 
3605 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3606                                    ArrayRef<Expr *> Args, ADLResult &Result) {
3607   // Find all of the associated namespaces and classes based on the
3608   // arguments we have.
3609   AssociatedNamespaceSet AssociatedNamespaces;
3610   AssociatedClassSet AssociatedClasses;
3611   FindAssociatedClassesAndNamespaces(Loc, Args,
3612                                      AssociatedNamespaces,
3613                                      AssociatedClasses);
3614 
3615   // C++ [basic.lookup.argdep]p3:
3616   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
3617   //   and let Y be the lookup set produced by argument dependent
3618   //   lookup (defined as follows). If X contains [...] then Y is
3619   //   empty. Otherwise Y is the set of declarations found in the
3620   //   namespaces associated with the argument types as described
3621   //   below. The set of declarations found by the lookup of the name
3622   //   is the union of X and Y.
3623   //
3624   // Here, we compute Y and add its members to the overloaded
3625   // candidate set.
3626   for (auto *NS : AssociatedNamespaces) {
3627     //   When considering an associated namespace, the lookup is the
3628     //   same as the lookup performed when the associated namespace is
3629     //   used as a qualifier (3.4.3.2) except that:
3630     //
3631     //     -- Any using-directives in the associated namespace are
3632     //        ignored.
3633     //
3634     //     -- Any namespace-scope friend functions declared in
3635     //        associated classes are visible within their respective
3636     //        namespaces even if they are not visible during an ordinary
3637     //        lookup (11.4).
3638     DeclContext::lookup_result R = NS->lookup(Name);
3639     for (auto *D : R) {
3640       auto *Underlying = D;
3641       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3642         Underlying = USD->getTargetDecl();
3643 
3644       if (!isa<FunctionDecl>(Underlying) &&
3645           !isa<FunctionTemplateDecl>(Underlying))
3646         continue;
3647 
3648       // The declaration is visible to argument-dependent lookup if either
3649       // it's ordinarily visible or declared as a friend in an associated
3650       // class.
3651       bool Visible = false;
3652       for (D = D->getMostRecentDecl(); D;
3653            D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3654         if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3655           if (isVisible(D)) {
3656             Visible = true;
3657             break;
3658           }
3659         } else if (D->getFriendObjectKind()) {
3660           auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3661           if (AssociatedClasses.count(RD) && isVisible(D)) {
3662             Visible = true;
3663             break;
3664           }
3665         }
3666       }
3667 
3668       // FIXME: Preserve D as the FoundDecl.
3669       if (Visible)
3670         Result.insert(Underlying);
3671     }
3672   }
3673 }
3674 
3675 //----------------------------------------------------------------------------
3676 // Search for all visible declarations.
3677 //----------------------------------------------------------------------------
3678 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3679 
3680 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3681 
3682 namespace {
3683 
3684 class ShadowContextRAII;
3685 
3686 class VisibleDeclsRecord {
3687 public:
3688   /// An entry in the shadow map, which is optimized to store a
3689   /// single declaration (the common case) but can also store a list
3690   /// of declarations.
3691   typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3692 
3693 private:
3694   /// A mapping from declaration names to the declarations that have
3695   /// this name within a particular scope.
3696   typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3697 
3698   /// A list of shadow maps, which is used to model name hiding.
3699   std::list<ShadowMap> ShadowMaps;
3700 
3701   /// The declaration contexts we have already visited.
3702   llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3703 
3704   friend class ShadowContextRAII;
3705 
3706 public:
3707   /// Determine whether we have already visited this context
3708   /// (and, if not, note that we are going to visit that context now).
3709   bool visitedContext(DeclContext *Ctx) {
3710     return !VisitedContexts.insert(Ctx).second;
3711   }
3712 
3713   bool alreadyVisitedContext(DeclContext *Ctx) {
3714     return VisitedContexts.count(Ctx);
3715   }
3716 
3717   /// Determine whether the given declaration is hidden in the
3718   /// current scope.
3719   ///
3720   /// \returns the declaration that hides the given declaration, or
3721   /// NULL if no such declaration exists.
3722   NamedDecl *checkHidden(NamedDecl *ND);
3723 
3724   /// Add a declaration to the current shadow map.
3725   void add(NamedDecl *ND) {
3726     ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3727   }
3728 };
3729 
3730 /// RAII object that records when we've entered a shadow context.
3731 class ShadowContextRAII {
3732   VisibleDeclsRecord &Visible;
3733 
3734   typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3735 
3736 public:
3737   ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3738     Visible.ShadowMaps.emplace_back();
3739   }
3740 
3741   ~ShadowContextRAII() {
3742     Visible.ShadowMaps.pop_back();
3743   }
3744 };
3745 
3746 } // end anonymous namespace
3747 
3748 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3749   unsigned IDNS = ND->getIdentifierNamespace();
3750   std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3751   for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3752        SM != SMEnd; ++SM) {
3753     ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3754     if (Pos == SM->end())
3755       continue;
3756 
3757     for (auto *D : Pos->second) {
3758       // A tag declaration does not hide a non-tag declaration.
3759       if (D->hasTagIdentifierNamespace() &&
3760           (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3761                    Decl::IDNS_ObjCProtocol)))
3762         continue;
3763 
3764       // Protocols are in distinct namespaces from everything else.
3765       if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3766            || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3767           D->getIdentifierNamespace() != IDNS)
3768         continue;
3769 
3770       // Functions and function templates in the same scope overload
3771       // rather than hide.  FIXME: Look for hiding based on function
3772       // signatures!
3773       if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3774           ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3775           SM == ShadowMaps.rbegin())
3776         continue;
3777 
3778       // A shadow declaration that's created by a resolved using declaration
3779       // is not hidden by the same using declaration.
3780       if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3781           cast<UsingShadowDecl>(ND)->getIntroducer() == D)
3782         continue;
3783 
3784       // We've found a declaration that hides this one.
3785       return D;
3786     }
3787   }
3788 
3789   return nullptr;
3790 }
3791 
3792 namespace {
3793 class LookupVisibleHelper {
3794 public:
3795   LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
3796                       bool LoadExternal)
3797       : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
3798         LoadExternal(LoadExternal) {}
3799 
3800   void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
3801                           bool IncludeGlobalScope) {
3802     // Determine the set of using directives available during
3803     // unqualified name lookup.
3804     Scope *Initial = S;
3805     UnqualUsingDirectiveSet UDirs(SemaRef);
3806     if (SemaRef.getLangOpts().CPlusPlus) {
3807       // Find the first namespace or translation-unit scope.
3808       while (S && !isNamespaceOrTranslationUnitScope(S))
3809         S = S->getParent();
3810 
3811       UDirs.visitScopeChain(Initial, S);
3812     }
3813     UDirs.done();
3814 
3815     // Look for visible declarations.
3816     LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
3817     Result.setAllowHidden(Consumer.includeHiddenDecls());
3818     if (!IncludeGlobalScope)
3819       Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
3820     ShadowContextRAII Shadow(Visited);
3821     lookupInScope(Initial, Result, UDirs);
3822   }
3823 
3824   void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
3825                           Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
3826     LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
3827     Result.setAllowHidden(Consumer.includeHiddenDecls());
3828     if (!IncludeGlobalScope)
3829       Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
3830 
3831     ShadowContextRAII Shadow(Visited);
3832     lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
3833                         /*InBaseClass=*/false);
3834   }
3835 
3836 private:
3837   void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
3838                            bool QualifiedNameLookup, bool InBaseClass) {
3839     if (!Ctx)
3840       return;
3841 
3842     // Make sure we don't visit the same context twice.
3843     if (Visited.visitedContext(Ctx->getPrimaryContext()))
3844       return;
3845 
3846     Consumer.EnteredContext(Ctx);
3847 
3848     // Outside C++, lookup results for the TU live on identifiers.
3849     if (isa<TranslationUnitDecl>(Ctx) &&
3850         !Result.getSema().getLangOpts().CPlusPlus) {
3851       auto &S = Result.getSema();
3852       auto &Idents = S.Context.Idents;
3853 
3854       // Ensure all external identifiers are in the identifier table.
3855       if (LoadExternal)
3856         if (IdentifierInfoLookup *External =
3857                 Idents.getExternalIdentifierLookup()) {
3858           std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3859           for (StringRef Name = Iter->Next(); !Name.empty();
3860                Name = Iter->Next())
3861             Idents.get(Name);
3862         }
3863 
3864       // Walk all lookup results in the TU for each identifier.
3865       for (const auto &Ident : Idents) {
3866         for (auto I = S.IdResolver.begin(Ident.getValue()),
3867                   E = S.IdResolver.end();
3868              I != E; ++I) {
3869           if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3870             if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3871               Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3872               Visited.add(ND);
3873             }
3874           }
3875         }
3876       }
3877 
3878       return;
3879     }
3880 
3881     if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3882       Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3883 
3884     llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
3885     // We sometimes skip loading namespace-level results (they tend to be huge).
3886     bool Load = LoadExternal ||
3887                 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
3888     // Enumerate all of the results in this context.
3889     for (DeclContextLookupResult R :
3890          Load ? Ctx->lookups()
3891               : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
3892       for (auto *D : R) {
3893         if (auto *ND = Result.getAcceptableDecl(D)) {
3894           // Rather than visit immediately, we put ND into a vector and visit
3895           // all decls, in order, outside of this loop. The reason is that
3896           // Consumer.FoundDecl() may invalidate the iterators used in the two
3897           // loops above.
3898           DeclsToVisit.push_back(ND);
3899         }
3900       }
3901     }
3902 
3903     for (auto *ND : DeclsToVisit) {
3904       Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3905       Visited.add(ND);
3906     }
3907     DeclsToVisit.clear();
3908 
3909     // Traverse using directives for qualified name lookup.
3910     if (QualifiedNameLookup) {
3911       ShadowContextRAII Shadow(Visited);
3912       for (auto I : Ctx->using_directives()) {
3913         if (!Result.getSema().isVisible(I))
3914           continue;
3915         lookupInDeclContext(I->getNominatedNamespace(), Result,
3916                             QualifiedNameLookup, InBaseClass);
3917       }
3918     }
3919 
3920     // Traverse the contexts of inherited C++ classes.
3921     if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3922       if (!Record->hasDefinition())
3923         return;
3924 
3925       for (const auto &B : Record->bases()) {
3926         QualType BaseType = B.getType();
3927 
3928         RecordDecl *RD;
3929         if (BaseType->isDependentType()) {
3930           if (!IncludeDependentBases) {
3931             // Don't look into dependent bases, because name lookup can't look
3932             // there anyway.
3933             continue;
3934           }
3935           const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3936           if (!TST)
3937             continue;
3938           TemplateName TN = TST->getTemplateName();
3939           const auto *TD =
3940               dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3941           if (!TD)
3942             continue;
3943           RD = TD->getTemplatedDecl();
3944         } else {
3945           const auto *Record = BaseType->getAs<RecordType>();
3946           if (!Record)
3947             continue;
3948           RD = Record->getDecl();
3949         }
3950 
3951         // FIXME: It would be nice to be able to determine whether referencing
3952         // a particular member would be ambiguous. For example, given
3953         //
3954         //   struct A { int member; };
3955         //   struct B { int member; };
3956         //   struct C : A, B { };
3957         //
3958         //   void f(C *c) { c->### }
3959         //
3960         // accessing 'member' would result in an ambiguity. However, we
3961         // could be smart enough to qualify the member with the base
3962         // class, e.g.,
3963         //
3964         //   c->B::member
3965         //
3966         // or
3967         //
3968         //   c->A::member
3969 
3970         // Find results in this base class (and its bases).
3971         ShadowContextRAII Shadow(Visited);
3972         lookupInDeclContext(RD, Result, QualifiedNameLookup,
3973                             /*InBaseClass=*/true);
3974       }
3975     }
3976 
3977     // Traverse the contexts of Objective-C classes.
3978     if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3979       // Traverse categories.
3980       for (auto *Cat : IFace->visible_categories()) {
3981         ShadowContextRAII Shadow(Visited);
3982         lookupInDeclContext(Cat, Result, QualifiedNameLookup,
3983                             /*InBaseClass=*/false);
3984       }
3985 
3986       // Traverse protocols.
3987       for (auto *I : IFace->all_referenced_protocols()) {
3988         ShadowContextRAII Shadow(Visited);
3989         lookupInDeclContext(I, Result, QualifiedNameLookup,
3990                             /*InBaseClass=*/false);
3991       }
3992 
3993       // Traverse the superclass.
3994       if (IFace->getSuperClass()) {
3995         ShadowContextRAII Shadow(Visited);
3996         lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
3997                             /*InBaseClass=*/true);
3998       }
3999 
4000       // If there is an implementation, traverse it. We do this to find
4001       // synthesized ivars.
4002       if (IFace->getImplementation()) {
4003         ShadowContextRAII Shadow(Visited);
4004         lookupInDeclContext(IFace->getImplementation(), Result,
4005                             QualifiedNameLookup, InBaseClass);
4006       }
4007     } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4008       for (auto *I : Protocol->protocols()) {
4009         ShadowContextRAII Shadow(Visited);
4010         lookupInDeclContext(I, Result, QualifiedNameLookup,
4011                             /*InBaseClass=*/false);
4012       }
4013     } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4014       for (auto *I : Category->protocols()) {
4015         ShadowContextRAII Shadow(Visited);
4016         lookupInDeclContext(I, Result, QualifiedNameLookup,
4017                             /*InBaseClass=*/false);
4018       }
4019 
4020       // If there is an implementation, traverse it.
4021       if (Category->getImplementation()) {
4022         ShadowContextRAII Shadow(Visited);
4023         lookupInDeclContext(Category->getImplementation(), Result,
4024                             QualifiedNameLookup, /*InBaseClass=*/true);
4025       }
4026     }
4027   }
4028 
4029   void lookupInScope(Scope *S, LookupResult &Result,
4030                      UnqualUsingDirectiveSet &UDirs) {
4031     // No clients run in this mode and it's not supported. Please add tests and
4032     // remove the assertion if you start relying on it.
4033     assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4034 
4035     if (!S)
4036       return;
4037 
4038     if (!S->getEntity() ||
4039         (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4040         (S->getEntity())->isFunctionOrMethod()) {
4041       FindLocalExternScope FindLocals(Result);
4042       // Walk through the declarations in this Scope. The consumer might add new
4043       // decls to the scope as part of deserialization, so make a copy first.
4044       SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4045       for (Decl *D : ScopeDecls) {
4046         if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4047           if ((ND = Result.getAcceptableDecl(ND))) {
4048             Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4049             Visited.add(ND);
4050           }
4051       }
4052     }
4053 
4054     DeclContext *Entity = S->getLookupEntity();
4055     if (Entity) {
4056       // Look into this scope's declaration context, along with any of its
4057       // parent lookup contexts (e.g., enclosing classes), up to the point
4058       // where we hit the context stored in the next outer scope.
4059       DeclContext *OuterCtx = findOuterContext(S);
4060 
4061       for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4062            Ctx = Ctx->getLookupParent()) {
4063         if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4064           if (Method->isInstanceMethod()) {
4065             // For instance methods, look for ivars in the method's interface.
4066             LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4067                                     Result.getNameLoc(),
4068                                     Sema::LookupMemberName);
4069             if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4070               lookupInDeclContext(IFace, IvarResult,
4071                                   /*QualifiedNameLookup=*/false,
4072                                   /*InBaseClass=*/false);
4073             }
4074           }
4075 
4076           // We've already performed all of the name lookup that we need
4077           // to for Objective-C methods; the next context will be the
4078           // outer scope.
4079           break;
4080         }
4081 
4082         if (Ctx->isFunctionOrMethod())
4083           continue;
4084 
4085         lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4086                             /*InBaseClass=*/false);
4087       }
4088     } else if (!S->getParent()) {
4089       // Look into the translation unit scope. We walk through the translation
4090       // unit's declaration context, because the Scope itself won't have all of
4091       // the declarations if we loaded a precompiled header.
4092       // FIXME: We would like the translation unit's Scope object to point to
4093       // the translation unit, so we don't need this special "if" branch.
4094       // However, doing so would force the normal C++ name-lookup code to look
4095       // into the translation unit decl when the IdentifierInfo chains would
4096       // suffice. Once we fix that problem (which is part of a more general
4097       // "don't look in DeclContexts unless we have to" optimization), we can
4098       // eliminate this.
4099       Entity = Result.getSema().Context.getTranslationUnitDecl();
4100       lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4101                           /*InBaseClass=*/false);
4102     }
4103 
4104     if (Entity) {
4105       // Lookup visible declarations in any namespaces found by using
4106       // directives.
4107       for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4108         lookupInDeclContext(
4109             const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4110             /*QualifiedNameLookup=*/false,
4111             /*InBaseClass=*/false);
4112     }
4113 
4114     // Lookup names in the parent scope.
4115     ShadowContextRAII Shadow(Visited);
4116     lookupInScope(S->getParent(), Result, UDirs);
4117   }
4118 
4119 private:
4120   VisibleDeclsRecord Visited;
4121   VisibleDeclConsumer &Consumer;
4122   bool IncludeDependentBases;
4123   bool LoadExternal;
4124 };
4125 } // namespace
4126 
4127 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4128                               VisibleDeclConsumer &Consumer,
4129                               bool IncludeGlobalScope, bool LoadExternal) {
4130   LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4131                         LoadExternal);
4132   H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4133 }
4134 
4135 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4136                               VisibleDeclConsumer &Consumer,
4137                               bool IncludeGlobalScope,
4138                               bool IncludeDependentBases, bool LoadExternal) {
4139   LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4140   H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4141 }
4142 
4143 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
4144 /// If GnuLabelLoc is a valid source location, then this is a definition
4145 /// of an __label__ label name, otherwise it is a normal label definition
4146 /// or use.
4147 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
4148                                      SourceLocation GnuLabelLoc) {
4149   // Do a lookup to see if we have a label with this name already.
4150   NamedDecl *Res = nullptr;
4151 
4152   if (GnuLabelLoc.isValid()) {
4153     // Local label definitions always shadow existing labels.
4154     Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4155     Scope *S = CurScope;
4156     PushOnScopeChains(Res, S, true);
4157     return cast<LabelDecl>(Res);
4158   }
4159 
4160   // Not a GNU local label.
4161   Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
4162   // If we found a label, check to see if it is in the same context as us.
4163   // When in a Block, we don't want to reuse a label in an enclosing function.
4164   if (Res && Res->getDeclContext() != CurContext)
4165     Res = nullptr;
4166   if (!Res) {
4167     // If not forward referenced or defined already, create the backing decl.
4168     Res = LabelDecl::Create(Context, CurContext, Loc, II);
4169     Scope *S = CurScope->getFnParent();
4170     assert(S && "Not in a function?");
4171     PushOnScopeChains(Res, S, true);
4172   }
4173   return cast<LabelDecl>(Res);
4174 }
4175 
4176 //===----------------------------------------------------------------------===//
4177 // Typo correction
4178 //===----------------------------------------------------------------------===//
4179 
4180 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
4181                               TypoCorrection &Candidate) {
4182   Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4183   return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4184 }
4185 
4186 static void LookupPotentialTypoResult(Sema &SemaRef,
4187                                       LookupResult &Res,
4188                                       IdentifierInfo *Name,
4189                                       Scope *S, CXXScopeSpec *SS,
4190                                       DeclContext *MemberContext,
4191                                       bool EnteringContext,
4192                                       bool isObjCIvarLookup,
4193                                       bool FindHidden);
4194 
4195 /// Check whether the declarations found for a typo correction are
4196 /// visible. Set the correction's RequiresImport flag to true if none of the
4197 /// declarations are visible, false otherwise.
4198 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4199   TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4200 
4201   for (/**/; DI != DE; ++DI)
4202     if (!LookupResult::isVisible(SemaRef, *DI))
4203       break;
4204   // No filtering needed if all decls are visible.
4205   if (DI == DE) {
4206     TC.setRequiresImport(false);
4207     return;
4208   }
4209 
4210   llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4211   bool AnyVisibleDecls = !NewDecls.empty();
4212 
4213   for (/**/; DI != DE; ++DI) {
4214     if (LookupResult::isVisible(SemaRef, *DI)) {
4215       if (!AnyVisibleDecls) {
4216         // Found a visible decl, discard all hidden ones.
4217         AnyVisibleDecls = true;
4218         NewDecls.clear();
4219       }
4220       NewDecls.push_back(*DI);
4221     } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4222       NewDecls.push_back(*DI);
4223   }
4224 
4225   if (NewDecls.empty())
4226     TC = TypoCorrection();
4227   else {
4228     TC.setCorrectionDecls(NewDecls);
4229     TC.setRequiresImport(!AnyVisibleDecls);
4230   }
4231 }
4232 
4233 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4234 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4235 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4236 static void getNestedNameSpecifierIdentifiers(
4237     NestedNameSpecifier *NNS,
4238     SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4239   if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4240     getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4241   else
4242     Identifiers.clear();
4243 
4244   const IdentifierInfo *II = nullptr;
4245 
4246   switch (NNS->getKind()) {
4247   case NestedNameSpecifier::Identifier:
4248     II = NNS->getAsIdentifier();
4249     break;
4250 
4251   case NestedNameSpecifier::Namespace:
4252     if (NNS->getAsNamespace()->isAnonymousNamespace())
4253       return;
4254     II = NNS->getAsNamespace()->getIdentifier();
4255     break;
4256 
4257   case NestedNameSpecifier::NamespaceAlias:
4258     II = NNS->getAsNamespaceAlias()->getIdentifier();
4259     break;
4260 
4261   case NestedNameSpecifier::TypeSpecWithTemplate:
4262   case NestedNameSpecifier::TypeSpec:
4263     II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4264     break;
4265 
4266   case NestedNameSpecifier::Global:
4267   case NestedNameSpecifier::Super:
4268     return;
4269   }
4270 
4271   if (II)
4272     Identifiers.push_back(II);
4273 }
4274 
4275 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4276                                        DeclContext *Ctx, bool InBaseClass) {
4277   // Don't consider hidden names for typo correction.
4278   if (Hiding)
4279     return;
4280 
4281   // Only consider entities with identifiers for names, ignoring
4282   // special names (constructors, overloaded operators, selectors,
4283   // etc.).
4284   IdentifierInfo *Name = ND->getIdentifier();
4285   if (!Name)
4286     return;
4287 
4288   // Only consider visible declarations and declarations from modules with
4289   // names that exactly match.
4290   if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4291     return;
4292 
4293   FoundName(Name->getName());
4294 }
4295 
4296 void TypoCorrectionConsumer::FoundName(StringRef Name) {
4297   // Compute the edit distance between the typo and the name of this
4298   // entity, and add the identifier to the list of results.
4299   addName(Name, nullptr);
4300 }
4301 
4302 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4303   // Compute the edit distance between the typo and this keyword,
4304   // and add the keyword to the list of results.
4305   addName(Keyword, nullptr, nullptr, true);
4306 }
4307 
4308 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4309                                      NestedNameSpecifier *NNS, bool isKeyword) {
4310   // Use a simple length-based heuristic to determine the minimum possible
4311   // edit distance. If the minimum isn't good enough, bail out early.
4312   StringRef TypoStr = Typo->getName();
4313   unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4314   if (MinED && TypoStr.size() / MinED < 3)
4315     return;
4316 
4317   // Compute an upper bound on the allowable edit distance, so that the
4318   // edit-distance algorithm can short-circuit.
4319   unsigned UpperBound = (TypoStr.size() + 2) / 3;
4320   unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4321   if (ED > UpperBound) return;
4322 
4323   TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4324   if (isKeyword) TC.makeKeyword();
4325   TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4326   addCorrection(TC);
4327 }
4328 
4329 static const unsigned MaxTypoDistanceResultSets = 5;
4330 
4331 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4332   StringRef TypoStr = Typo->getName();
4333   StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4334 
4335   // For very short typos, ignore potential corrections that have a different
4336   // base identifier from the typo or which have a normalized edit distance
4337   // longer than the typo itself.
4338   if (TypoStr.size() < 3 &&
4339       (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4340     return;
4341 
4342   // If the correction is resolved but is not viable, ignore it.
4343   if (Correction.isResolved()) {
4344     checkCorrectionVisibility(SemaRef, Correction);
4345     if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4346       return;
4347   }
4348 
4349   TypoResultList &CList =
4350       CorrectionResults[Correction.getEditDistance(false)][Name];
4351 
4352   if (!CList.empty() && !CList.back().isResolved())
4353     CList.pop_back();
4354   if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4355     auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4356       return TypoCorr.getCorrectionDecl() == NewND;
4357     });
4358     if (RI != CList.end()) {
4359       // The Correction refers to a decl already in the list. No insertion is
4360       // necessary and all further cases will return.
4361 
4362       auto IsDeprecated = [](Decl *D) {
4363         while (D) {
4364           if (D->isDeprecated())
4365             return true;
4366           D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4367         }
4368         return false;
4369       };
4370 
4371       // Prefer non deprecated Corrections over deprecated and only then
4372       // sort using an alphabetical order.
4373       std::pair<bool, std::string> NewKey = {
4374           IsDeprecated(Correction.getFoundDecl()),
4375           Correction.getAsString(SemaRef.getLangOpts())};
4376 
4377       std::pair<bool, std::string> PrevKey = {
4378           IsDeprecated(RI->getFoundDecl()),
4379           RI->getAsString(SemaRef.getLangOpts())};
4380 
4381       if (NewKey < PrevKey)
4382         *RI = Correction;
4383       return;
4384     }
4385   }
4386   if (CList.empty() || Correction.isResolved())
4387     CList.push_back(Correction);
4388 
4389   while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4390     CorrectionResults.erase(std::prev(CorrectionResults.end()));
4391 }
4392 
4393 void TypoCorrectionConsumer::addNamespaces(
4394     const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4395   SearchNamespaces = true;
4396 
4397   for (auto KNPair : KnownNamespaces)
4398     Namespaces.addNameSpecifier(KNPair.first);
4399 
4400   bool SSIsTemplate = false;
4401   if (NestedNameSpecifier *NNS =
4402           (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4403     if (const Type *T = NNS->getAsType())
4404       SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4405   }
4406   // Do not transform this into an iterator-based loop. The loop body can
4407   // trigger the creation of further types (through lazy deserialization) and
4408   // invalid iterators into this list.
4409   auto &Types = SemaRef.getASTContext().getTypes();
4410   for (unsigned I = 0; I != Types.size(); ++I) {
4411     const auto *TI = Types[I];
4412     if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4413       CD = CD->getCanonicalDecl();
4414       if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4415           !CD->isUnion() && CD->getIdentifier() &&
4416           (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4417           (CD->isBeingDefined() || CD->isCompleteDefinition()))
4418         Namespaces.addNameSpecifier(CD);
4419     }
4420   }
4421 }
4422 
4423 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4424   if (++CurrentTCIndex < ValidatedCorrections.size())
4425     return ValidatedCorrections[CurrentTCIndex];
4426 
4427   CurrentTCIndex = ValidatedCorrections.size();
4428   while (!CorrectionResults.empty()) {
4429     auto DI = CorrectionResults.begin();
4430     if (DI->second.empty()) {
4431       CorrectionResults.erase(DI);
4432       continue;
4433     }
4434 
4435     auto RI = DI->second.begin();
4436     if (RI->second.empty()) {
4437       DI->second.erase(RI);
4438       performQualifiedLookups();
4439       continue;
4440     }
4441 
4442     TypoCorrection TC = RI->second.pop_back_val();
4443     if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4444       ValidatedCorrections.push_back(TC);
4445       return ValidatedCorrections[CurrentTCIndex];
4446     }
4447   }
4448   return ValidatedCorrections[0];  // The empty correction.
4449 }
4450 
4451 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4452   IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4453   DeclContext *TempMemberContext = MemberContext;
4454   CXXScopeSpec *TempSS = SS.get();
4455 retry_lookup:
4456   LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4457                             EnteringContext,
4458                             CorrectionValidator->IsObjCIvarLookup,
4459                             Name == Typo && !Candidate.WillReplaceSpecifier());
4460   switch (Result.getResultKind()) {
4461   case LookupResult::NotFound:
4462   case LookupResult::NotFoundInCurrentInstantiation:
4463   case LookupResult::FoundUnresolvedValue:
4464     if (TempSS) {
4465       // Immediately retry the lookup without the given CXXScopeSpec
4466       TempSS = nullptr;
4467       Candidate.WillReplaceSpecifier(true);
4468       goto retry_lookup;
4469     }
4470     if (TempMemberContext) {
4471       if (SS && !TempSS)
4472         TempSS = SS.get();
4473       TempMemberContext = nullptr;
4474       goto retry_lookup;
4475     }
4476     if (SearchNamespaces)
4477       QualifiedResults.push_back(Candidate);
4478     break;
4479 
4480   case LookupResult::Ambiguous:
4481     // We don't deal with ambiguities.
4482     break;
4483 
4484   case LookupResult::Found:
4485   case LookupResult::FoundOverloaded:
4486     // Store all of the Decls for overloaded symbols
4487     for (auto *TRD : Result)
4488       Candidate.addCorrectionDecl(TRD);
4489     checkCorrectionVisibility(SemaRef, Candidate);
4490     if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4491       if (SearchNamespaces)
4492         QualifiedResults.push_back(Candidate);
4493       break;
4494     }
4495     Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4496     return true;
4497   }
4498   return false;
4499 }
4500 
4501 void TypoCorrectionConsumer::performQualifiedLookups() {
4502   unsigned TypoLen = Typo->getName().size();
4503   for (const TypoCorrection &QR : QualifiedResults) {
4504     for (const auto &NSI : Namespaces) {
4505       DeclContext *Ctx = NSI.DeclCtx;
4506       const Type *NSType = NSI.NameSpecifier->getAsType();
4507 
4508       // If the current NestedNameSpecifier refers to a class and the
4509       // current correction candidate is the name of that class, then skip
4510       // it as it is unlikely a qualified version of the class' constructor
4511       // is an appropriate correction.
4512       if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4513                                            nullptr) {
4514         if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4515           continue;
4516       }
4517 
4518       TypoCorrection TC(QR);
4519       TC.ClearCorrectionDecls();
4520       TC.setCorrectionSpecifier(NSI.NameSpecifier);
4521       TC.setQualifierDistance(NSI.EditDistance);
4522       TC.setCallbackDistance(0); // Reset the callback distance
4523 
4524       // If the current correction candidate and namespace combination are
4525       // too far away from the original typo based on the normalized edit
4526       // distance, then skip performing a qualified name lookup.
4527       unsigned TmpED = TC.getEditDistance(true);
4528       if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4529           TypoLen / TmpED < 3)
4530         continue;
4531 
4532       Result.clear();
4533       Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4534       if (!SemaRef.LookupQualifiedName(Result, Ctx))
4535         continue;
4536 
4537       // Any corrections added below will be validated in subsequent
4538       // iterations of the main while() loop over the Consumer's contents.
4539       switch (Result.getResultKind()) {
4540       case LookupResult::Found:
4541       case LookupResult::FoundOverloaded: {
4542         if (SS && SS->isValid()) {
4543           std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4544           std::string OldQualified;
4545           llvm::raw_string_ostream OldOStream(OldQualified);
4546           SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4547           OldOStream << Typo->getName();
4548           // If correction candidate would be an identical written qualified
4549           // identifier, then the existing CXXScopeSpec probably included a
4550           // typedef that didn't get accounted for properly.
4551           if (OldOStream.str() == NewQualified)
4552             break;
4553         }
4554         for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4555              TRD != TRDEnd; ++TRD) {
4556           if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4557                                         NSType ? NSType->getAsCXXRecordDecl()
4558                                                : nullptr,
4559                                         TRD.getPair()) == Sema::AR_accessible)
4560             TC.addCorrectionDecl(*TRD);
4561         }
4562         if (TC.isResolved()) {
4563           TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4564           addCorrection(TC);
4565         }
4566         break;
4567       }
4568       case LookupResult::NotFound:
4569       case LookupResult::NotFoundInCurrentInstantiation:
4570       case LookupResult::Ambiguous:
4571       case LookupResult::FoundUnresolvedValue:
4572         break;
4573       }
4574     }
4575   }
4576   QualifiedResults.clear();
4577 }
4578 
4579 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4580     ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4581     : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4582   if (NestedNameSpecifier *NNS =
4583           CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4584     llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4585     NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4586 
4587     getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4588   }
4589   // Build the list of identifiers that would be used for an absolute
4590   // (from the global context) NestedNameSpecifier referring to the current
4591   // context.
4592   for (DeclContext *C : llvm::reverse(CurContextChain)) {
4593     if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4594       CurContextIdentifiers.push_back(ND->getIdentifier());
4595   }
4596 
4597   // Add the global context as a NestedNameSpecifier
4598   SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4599                       NestedNameSpecifier::GlobalSpecifier(Context), 1};
4600   DistanceMap[1].push_back(SI);
4601 }
4602 
4603 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4604     DeclContext *Start) -> DeclContextList {
4605   assert(Start && "Building a context chain from a null context");
4606   DeclContextList Chain;
4607   for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4608        DC = DC->getLookupParent()) {
4609     NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4610     if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4611         !(ND && ND->isAnonymousNamespace()))
4612       Chain.push_back(DC->getPrimaryContext());
4613   }
4614   return Chain;
4615 }
4616 
4617 unsigned
4618 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4619     DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4620   unsigned NumSpecifiers = 0;
4621   for (DeclContext *C : llvm::reverse(DeclChain)) {
4622     if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4623       NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4624       ++NumSpecifiers;
4625     } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4626       NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4627                                         RD->getTypeForDecl());
4628       ++NumSpecifiers;
4629     }
4630   }
4631   return NumSpecifiers;
4632 }
4633 
4634 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4635     DeclContext *Ctx) {
4636   NestedNameSpecifier *NNS = nullptr;
4637   unsigned NumSpecifiers = 0;
4638   DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4639   DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4640 
4641   // Eliminate common elements from the two DeclContext chains.
4642   for (DeclContext *C : llvm::reverse(CurContextChain)) {
4643     if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4644       break;
4645     NamespaceDeclChain.pop_back();
4646   }
4647 
4648   // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4649   NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4650 
4651   // Add an explicit leading '::' specifier if needed.
4652   if (NamespaceDeclChain.empty()) {
4653     // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4654     NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4655     NumSpecifiers =
4656         buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4657   } else if (NamedDecl *ND =
4658                  dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4659     IdentifierInfo *Name = ND->getIdentifier();
4660     bool SameNameSpecifier = false;
4661     if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4662       std::string NewNameSpecifier;
4663       llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4664       SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4665       getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4666       NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4667       SpecifierOStream.flush();
4668       SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4669     }
4670     if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
4671       // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4672       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4673       NumSpecifiers =
4674           buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4675     }
4676   }
4677 
4678   // If the built NestedNameSpecifier would be replacing an existing
4679   // NestedNameSpecifier, use the number of component identifiers that
4680   // would need to be changed as the edit distance instead of the number
4681   // of components in the built NestedNameSpecifier.
4682   if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4683     SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4684     getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4685     NumSpecifiers = llvm::ComputeEditDistance(
4686         llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4687         llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4688   }
4689 
4690   SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4691   DistanceMap[NumSpecifiers].push_back(SI);
4692 }
4693 
4694 /// Perform name lookup for a possible result for typo correction.
4695 static void LookupPotentialTypoResult(Sema &SemaRef,
4696                                       LookupResult &Res,
4697                                       IdentifierInfo *Name,
4698                                       Scope *S, CXXScopeSpec *SS,
4699                                       DeclContext *MemberContext,
4700                                       bool EnteringContext,
4701                                       bool isObjCIvarLookup,
4702                                       bool FindHidden) {
4703   Res.suppressDiagnostics();
4704   Res.clear();
4705   Res.setLookupName(Name);
4706   Res.setAllowHidden(FindHidden);
4707   if (MemberContext) {
4708     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4709       if (isObjCIvarLookup) {
4710         if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4711           Res.addDecl(Ivar);
4712           Res.resolveKind();
4713           return;
4714         }
4715       }
4716 
4717       if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4718               Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
4719         Res.addDecl(Prop);
4720         Res.resolveKind();
4721         return;
4722       }
4723     }
4724 
4725     SemaRef.LookupQualifiedName(Res, MemberContext);
4726     return;
4727   }
4728 
4729   SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4730                            EnteringContext);
4731 
4732   // Fake ivar lookup; this should really be part of
4733   // LookupParsedName.
4734   if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4735     if (Method->isInstanceMethod() && Method->getClassInterface() &&
4736         (Res.empty() ||
4737          (Res.isSingleResult() &&
4738           Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4739        if (ObjCIvarDecl *IV
4740              = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4741          Res.addDecl(IV);
4742          Res.resolveKind();
4743        }
4744      }
4745   }
4746 }
4747 
4748 /// Add keywords to the consumer as possible typo corrections.
4749 static void AddKeywordsToConsumer(Sema &SemaRef,
4750                                   TypoCorrectionConsumer &Consumer,
4751                                   Scope *S, CorrectionCandidateCallback &CCC,
4752                                   bool AfterNestedNameSpecifier) {
4753   if (AfterNestedNameSpecifier) {
4754     // For 'X::', we know exactly which keywords can appear next.
4755     Consumer.addKeywordResult("template");
4756     if (CCC.WantExpressionKeywords)
4757       Consumer.addKeywordResult("operator");
4758     return;
4759   }
4760 
4761   if (CCC.WantObjCSuper)
4762     Consumer.addKeywordResult("super");
4763 
4764   if (CCC.WantTypeSpecifiers) {
4765     // Add type-specifier keywords to the set of results.
4766     static const char *const CTypeSpecs[] = {
4767       "char", "const", "double", "enum", "float", "int", "long", "short",
4768       "signed", "struct", "union", "unsigned", "void", "volatile",
4769       "_Complex", "_Imaginary",
4770       // storage-specifiers as well
4771       "extern", "inline", "static", "typedef"
4772     };
4773 
4774     const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4775     for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4776       Consumer.addKeywordResult(CTypeSpecs[I]);
4777 
4778     if (SemaRef.getLangOpts().C99)
4779       Consumer.addKeywordResult("restrict");
4780     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
4781       Consumer.addKeywordResult("bool");
4782     else if (SemaRef.getLangOpts().C99)
4783       Consumer.addKeywordResult("_Bool");
4784 
4785     if (SemaRef.getLangOpts().CPlusPlus) {
4786       Consumer.addKeywordResult("class");
4787       Consumer.addKeywordResult("typename");
4788       Consumer.addKeywordResult("wchar_t");
4789 
4790       if (SemaRef.getLangOpts().CPlusPlus11) {
4791         Consumer.addKeywordResult("char16_t");
4792         Consumer.addKeywordResult("char32_t");
4793         Consumer.addKeywordResult("constexpr");
4794         Consumer.addKeywordResult("decltype");
4795         Consumer.addKeywordResult("thread_local");
4796       }
4797     }
4798 
4799     if (SemaRef.getLangOpts().GNUKeywords)
4800       Consumer.addKeywordResult("typeof");
4801   } else if (CCC.WantFunctionLikeCasts) {
4802     static const char *const CastableTypeSpecs[] = {
4803       "char", "double", "float", "int", "long", "short",
4804       "signed", "unsigned", "void"
4805     };
4806     for (auto *kw : CastableTypeSpecs)
4807       Consumer.addKeywordResult(kw);
4808   }
4809 
4810   if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
4811     Consumer.addKeywordResult("const_cast");
4812     Consumer.addKeywordResult("dynamic_cast");
4813     Consumer.addKeywordResult("reinterpret_cast");
4814     Consumer.addKeywordResult("static_cast");
4815   }
4816 
4817   if (CCC.WantExpressionKeywords) {
4818     Consumer.addKeywordResult("sizeof");
4819     if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
4820       Consumer.addKeywordResult("false");
4821       Consumer.addKeywordResult("true");
4822     }
4823 
4824     if (SemaRef.getLangOpts().CPlusPlus) {
4825       static const char *const CXXExprs[] = {
4826         "delete", "new", "operator", "throw", "typeid"
4827       };
4828       const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4829       for (unsigned I = 0; I != NumCXXExprs; ++I)
4830         Consumer.addKeywordResult(CXXExprs[I]);
4831 
4832       if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4833           cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4834         Consumer.addKeywordResult("this");
4835 
4836       if (SemaRef.getLangOpts().CPlusPlus11) {
4837         Consumer.addKeywordResult("alignof");
4838         Consumer.addKeywordResult("nullptr");
4839       }
4840     }
4841 
4842     if (SemaRef.getLangOpts().C11) {
4843       // FIXME: We should not suggest _Alignof if the alignof macro
4844       // is present.
4845       Consumer.addKeywordResult("_Alignof");
4846     }
4847   }
4848 
4849   if (CCC.WantRemainingKeywords) {
4850     if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4851       // Statements.
4852       static const char *const CStmts[] = {
4853         "do", "else", "for", "goto", "if", "return", "switch", "while" };
4854       const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4855       for (unsigned I = 0; I != NumCStmts; ++I)
4856         Consumer.addKeywordResult(CStmts[I]);
4857 
4858       if (SemaRef.getLangOpts().CPlusPlus) {
4859         Consumer.addKeywordResult("catch");
4860         Consumer.addKeywordResult("try");
4861       }
4862 
4863       if (S && S->getBreakParent())
4864         Consumer.addKeywordResult("break");
4865 
4866       if (S && S->getContinueParent())
4867         Consumer.addKeywordResult("continue");
4868 
4869       if (SemaRef.getCurFunction() &&
4870           !SemaRef.getCurFunction()->SwitchStack.empty()) {
4871         Consumer.addKeywordResult("case");
4872         Consumer.addKeywordResult("default");
4873       }
4874     } else {
4875       if (SemaRef.getLangOpts().CPlusPlus) {
4876         Consumer.addKeywordResult("namespace");
4877         Consumer.addKeywordResult("template");
4878       }
4879 
4880       if (S && S->isClassScope()) {
4881         Consumer.addKeywordResult("explicit");
4882         Consumer.addKeywordResult("friend");
4883         Consumer.addKeywordResult("mutable");
4884         Consumer.addKeywordResult("private");
4885         Consumer.addKeywordResult("protected");
4886         Consumer.addKeywordResult("public");
4887         Consumer.addKeywordResult("virtual");
4888       }
4889     }
4890 
4891     if (SemaRef.getLangOpts().CPlusPlus) {
4892       Consumer.addKeywordResult("using");
4893 
4894       if (SemaRef.getLangOpts().CPlusPlus11)
4895         Consumer.addKeywordResult("static_assert");
4896     }
4897   }
4898 }
4899 
4900 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4901     const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4902     Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
4903     DeclContext *MemberContext, bool EnteringContext,
4904     const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
4905 
4906   if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4907       DisableTypoCorrection)
4908     return nullptr;
4909 
4910   // In Microsoft mode, don't perform typo correction in a template member
4911   // function dependent context because it interferes with the "lookup into
4912   // dependent bases of class templates" feature.
4913   if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4914       isa<CXXMethodDecl>(CurContext))
4915     return nullptr;
4916 
4917   // We only attempt to correct typos for identifiers.
4918   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4919   if (!Typo)
4920     return nullptr;
4921 
4922   // If the scope specifier itself was invalid, don't try to correct
4923   // typos.
4924   if (SS && SS->isInvalid())
4925     return nullptr;
4926 
4927   // Never try to correct typos during any kind of code synthesis.
4928   if (!CodeSynthesisContexts.empty())
4929     return nullptr;
4930 
4931   // Don't try to correct 'super'.
4932   if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4933     return nullptr;
4934 
4935   // Abort if typo correction already failed for this specific typo.
4936   IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4937   if (locs != TypoCorrectionFailures.end() &&
4938       locs->second.count(TypoName.getLoc()))
4939     return nullptr;
4940 
4941   // Don't try to correct the identifier "vector" when in AltiVec mode.
4942   // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4943   // remove this workaround.
4944   if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
4945     return nullptr;
4946 
4947   // Provide a stop gap for files that are just seriously broken.  Trying
4948   // to correct all typos can turn into a HUGE performance penalty, causing
4949   // some files to take minutes to get rejected by the parser.
4950   unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4951   if (Limit && TyposCorrected >= Limit)
4952     return nullptr;
4953   ++TyposCorrected;
4954 
4955   // If we're handling a missing symbol error, using modules, and the
4956   // special search all modules option is used, look for a missing import.
4957   if (ErrorRecovery && getLangOpts().Modules &&
4958       getLangOpts().ModulesSearchAll) {
4959     // The following has the side effect of loading the missing module.
4960     getModuleLoader().lookupMissingImports(Typo->getName(),
4961                                            TypoName.getBeginLoc());
4962   }
4963 
4964   // Extend the lifetime of the callback. We delayed this until here
4965   // to avoid allocations in the hot path (which is where no typo correction
4966   // occurs). Note that CorrectionCandidateCallback is polymorphic and
4967   // initially stack-allocated.
4968   std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
4969   auto Consumer = std::make_unique<TypoCorrectionConsumer>(
4970       *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
4971       EnteringContext);
4972 
4973   // Perform name lookup to find visible, similarly-named entities.
4974   bool IsUnqualifiedLookup = false;
4975   DeclContext *QualifiedDC = MemberContext;
4976   if (MemberContext) {
4977     LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4978 
4979     // Look in qualified interfaces.
4980     if (OPT) {
4981       for (auto *I : OPT->quals())
4982         LookupVisibleDecls(I, LookupKind, *Consumer);
4983     }
4984   } else if (SS && SS->isSet()) {
4985     QualifiedDC = computeDeclContext(*SS, EnteringContext);
4986     if (!QualifiedDC)
4987       return nullptr;
4988 
4989     LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4990   } else {
4991     IsUnqualifiedLookup = true;
4992   }
4993 
4994   // Determine whether we are going to search in the various namespaces for
4995   // corrections.
4996   bool SearchNamespaces
4997     = getLangOpts().CPlusPlus &&
4998       (IsUnqualifiedLookup || (SS && SS->isSet()));
4999 
5000   if (IsUnqualifiedLookup || SearchNamespaces) {
5001     // For unqualified lookup, look through all of the names that we have
5002     // seen in this translation unit.
5003     // FIXME: Re-add the ability to skip very unlikely potential corrections.
5004     for (const auto &I : Context.Idents)
5005       Consumer->FoundName(I.getKey());
5006 
5007     // Walk through identifiers in external identifier sources.
5008     // FIXME: Re-add the ability to skip very unlikely potential corrections.
5009     if (IdentifierInfoLookup *External
5010                             = Context.Idents.getExternalIdentifierLookup()) {
5011       std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5012       do {
5013         StringRef Name = Iter->Next();
5014         if (Name.empty())
5015           break;
5016 
5017         Consumer->FoundName(Name);
5018       } while (true);
5019     }
5020   }
5021 
5022   AddKeywordsToConsumer(*this, *Consumer, S,
5023                         *Consumer->getCorrectionValidator(),
5024                         SS && SS->isNotEmpty());
5025 
5026   // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5027   // to search those namespaces.
5028   if (SearchNamespaces) {
5029     // Load any externally-known namespaces.
5030     if (ExternalSource && !LoadedExternalKnownNamespaces) {
5031       SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5032       LoadedExternalKnownNamespaces = true;
5033       ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5034       for (auto *N : ExternalKnownNamespaces)
5035         KnownNamespaces[N] = true;
5036     }
5037 
5038     Consumer->addNamespaces(KnownNamespaces);
5039   }
5040 
5041   return Consumer;
5042 }
5043 
5044 /// Try to "correct" a typo in the source code by finding
5045 /// visible declarations whose names are similar to the name that was
5046 /// present in the source code.
5047 ///
5048 /// \param TypoName the \c DeclarationNameInfo structure that contains
5049 /// the name that was present in the source code along with its location.
5050 ///
5051 /// \param LookupKind the name-lookup criteria used to search for the name.
5052 ///
5053 /// \param S the scope in which name lookup occurs.
5054 ///
5055 /// \param SS the nested-name-specifier that precedes the name we're
5056 /// looking for, if present.
5057 ///
5058 /// \param CCC A CorrectionCandidateCallback object that provides further
5059 /// validation of typo correction candidates. It also provides flags for
5060 /// determining the set of keywords permitted.
5061 ///
5062 /// \param MemberContext if non-NULL, the context in which to look for
5063 /// a member access expression.
5064 ///
5065 /// \param EnteringContext whether we're entering the context described by
5066 /// the nested-name-specifier SS.
5067 ///
5068 /// \param OPT when non-NULL, the search for visible declarations will
5069 /// also walk the protocols in the qualified interfaces of \p OPT.
5070 ///
5071 /// \returns a \c TypoCorrection containing the corrected name if the typo
5072 /// along with information such as the \c NamedDecl where the corrected name
5073 /// was declared, and any additional \c NestedNameSpecifier needed to access
5074 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
5075 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
5076                                  Sema::LookupNameKind LookupKind,
5077                                  Scope *S, CXXScopeSpec *SS,
5078                                  CorrectionCandidateCallback &CCC,
5079                                  CorrectTypoKind Mode,
5080                                  DeclContext *MemberContext,
5081                                  bool EnteringContext,
5082                                  const ObjCObjectPointerType *OPT,
5083                                  bool RecordFailure) {
5084   // Always let the ExternalSource have the first chance at correction, even
5085   // if we would otherwise have given up.
5086   if (ExternalSource) {
5087     if (TypoCorrection Correction =
5088             ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5089                                         MemberContext, EnteringContext, OPT))
5090       return Correction;
5091   }
5092 
5093   // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5094   // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5095   // some instances of CTC_Unknown, while WantRemainingKeywords is true
5096   // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5097   bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5098 
5099   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5100   auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5101                                              MemberContext, EnteringContext,
5102                                              OPT, Mode == CTK_ErrorRecovery);
5103 
5104   if (!Consumer)
5105     return TypoCorrection();
5106 
5107   // If we haven't found anything, we're done.
5108   if (Consumer->empty())
5109     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5110 
5111   // Make sure the best edit distance (prior to adding any namespace qualifiers)
5112   // is not more that about a third of the length of the typo's identifier.
5113   unsigned ED = Consumer->getBestEditDistance(true);
5114   unsigned TypoLen = Typo->getName().size();
5115   if (ED > 0 && TypoLen / ED < 3)
5116     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5117 
5118   TypoCorrection BestTC = Consumer->getNextCorrection();
5119   TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5120   if (!BestTC)
5121     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5122 
5123   ED = BestTC.getEditDistance();
5124 
5125   if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5126     // If this was an unqualified lookup and we believe the callback
5127     // object wouldn't have filtered out possible corrections, note
5128     // that no correction was found.
5129     return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5130   }
5131 
5132   // If only a single name remains, return that result.
5133   if (!SecondBestTC ||
5134       SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5135     const TypoCorrection &Result = BestTC;
5136 
5137     // Don't correct to a keyword that's the same as the typo; the keyword
5138     // wasn't actually in scope.
5139     if (ED == 0 && Result.isKeyword())
5140       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5141 
5142     TypoCorrection TC = Result;
5143     TC.setCorrectionRange(SS, TypoName);
5144     checkCorrectionVisibility(*this, TC);
5145     return TC;
5146   } else if (SecondBestTC && ObjCMessageReceiver) {
5147     // Prefer 'super' when we're completing in a message-receiver
5148     // context.
5149 
5150     if (BestTC.getCorrection().getAsString() != "super") {
5151       if (SecondBestTC.getCorrection().getAsString() == "super")
5152         BestTC = SecondBestTC;
5153       else if ((*Consumer)["super"].front().isKeyword())
5154         BestTC = (*Consumer)["super"].front();
5155     }
5156     // Don't correct to a keyword that's the same as the typo; the keyword
5157     // wasn't actually in scope.
5158     if (BestTC.getEditDistance() == 0 ||
5159         BestTC.getCorrection().getAsString() != "super")
5160       return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5161 
5162     BestTC.setCorrectionRange(SS, TypoName);
5163     return BestTC;
5164   }
5165 
5166   // Record the failure's location if needed and return an empty correction. If
5167   // this was an unqualified lookup and we believe the callback object did not
5168   // filter out possible corrections, also cache the failure for the typo.
5169   return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5170 }
5171 
5172 /// Try to "correct" a typo in the source code by finding
5173 /// visible declarations whose names are similar to the name that was
5174 /// present in the source code.
5175 ///
5176 /// \param TypoName the \c DeclarationNameInfo structure that contains
5177 /// the name that was present in the source code along with its location.
5178 ///
5179 /// \param LookupKind the name-lookup criteria used to search for the name.
5180 ///
5181 /// \param S the scope in which name lookup occurs.
5182 ///
5183 /// \param SS the nested-name-specifier that precedes the name we're
5184 /// looking for, if present.
5185 ///
5186 /// \param CCC A CorrectionCandidateCallback object that provides further
5187 /// validation of typo correction candidates. It also provides flags for
5188 /// determining the set of keywords permitted.
5189 ///
5190 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
5191 /// diagnostics when the actual typo correction is attempted.
5192 ///
5193 /// \param TRC A TypoRecoveryCallback functor that will be used to build an
5194 /// Expr from a typo correction candidate.
5195 ///
5196 /// \param MemberContext if non-NULL, the context in which to look for
5197 /// a member access expression.
5198 ///
5199 /// \param EnteringContext whether we're entering the context described by
5200 /// the nested-name-specifier SS.
5201 ///
5202 /// \param OPT when non-NULL, the search for visible declarations will
5203 /// also walk the protocols in the qualified interfaces of \p OPT.
5204 ///
5205 /// \returns a new \c TypoExpr that will later be replaced in the AST with an
5206 /// Expr representing the result of performing typo correction, or nullptr if
5207 /// typo correction is not possible. If nullptr is returned, no diagnostics will
5208 /// be emitted and it is the responsibility of the caller to emit any that are
5209 /// needed.
5210 TypoExpr *Sema::CorrectTypoDelayed(
5211     const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5212     Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5213     TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
5214     DeclContext *MemberContext, bool EnteringContext,
5215     const ObjCObjectPointerType *OPT) {
5216   auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5217                                              MemberContext, EnteringContext,
5218                                              OPT, Mode == CTK_ErrorRecovery);
5219 
5220   // Give the external sema source a chance to correct the typo.
5221   TypoCorrection ExternalTypo;
5222   if (ExternalSource && Consumer) {
5223     ExternalTypo = ExternalSource->CorrectTypo(
5224         TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5225         MemberContext, EnteringContext, OPT);
5226     if (ExternalTypo)
5227       Consumer->addCorrection(ExternalTypo);
5228   }
5229 
5230   if (!Consumer || Consumer->empty())
5231     return nullptr;
5232 
5233   // Make sure the best edit distance (prior to adding any namespace qualifiers)
5234   // is not more that about a third of the length of the typo's identifier.
5235   unsigned ED = Consumer->getBestEditDistance(true);
5236   IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5237   if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5238     return nullptr;
5239   ExprEvalContexts.back().NumTypos++;
5240   return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5241                            TypoName.getLoc());
5242 }
5243 
5244 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5245   if (!CDecl) return;
5246 
5247   if (isKeyword())
5248     CorrectionDecls.clear();
5249 
5250   CorrectionDecls.push_back(CDecl);
5251 
5252   if (!CorrectionName)
5253     CorrectionName = CDecl->getDeclName();
5254 }
5255 
5256 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5257   if (CorrectionNameSpec) {
5258     std::string tmpBuffer;
5259     llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5260     CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5261     PrefixOStream << CorrectionName;
5262     return PrefixOStream.str();
5263   }
5264 
5265   return CorrectionName.getAsString();
5266 }
5267 
5268 bool CorrectionCandidateCallback::ValidateCandidate(
5269     const TypoCorrection &candidate) {
5270   if (!candidate.isResolved())
5271     return true;
5272 
5273   if (candidate.isKeyword())
5274     return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5275            WantRemainingKeywords || WantObjCSuper;
5276 
5277   bool HasNonType = false;
5278   bool HasStaticMethod = false;
5279   bool HasNonStaticMethod = false;
5280   for (Decl *D : candidate) {
5281     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5282       D = FTD->getTemplatedDecl();
5283     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5284       if (Method->isStatic())
5285         HasStaticMethod = true;
5286       else
5287         HasNonStaticMethod = true;
5288     }
5289     if (!isa<TypeDecl>(D))
5290       HasNonType = true;
5291   }
5292 
5293   if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5294       !candidate.getCorrectionSpecifier())
5295     return false;
5296 
5297   return WantTypeSpecifiers || HasNonType;
5298 }
5299 
5300 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5301                                              bool HasExplicitTemplateArgs,
5302                                              MemberExpr *ME)
5303     : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5304       CurContext(SemaRef.CurContext), MemberFn(ME) {
5305   WantTypeSpecifiers = false;
5306   WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5307                           !HasExplicitTemplateArgs && NumArgs == 1;
5308   WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5309   WantRemainingKeywords = false;
5310 }
5311 
5312 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5313   if (!candidate.getCorrectionDecl())
5314     return candidate.isKeyword();
5315 
5316   for (auto *C : candidate) {
5317     FunctionDecl *FD = nullptr;
5318     NamedDecl *ND = C->getUnderlyingDecl();
5319     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5320       FD = FTD->getTemplatedDecl();
5321     if (!HasExplicitTemplateArgs && !FD) {
5322       if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5323         // If the Decl is neither a function nor a template function,
5324         // determine if it is a pointer or reference to a function. If so,
5325         // check against the number of arguments expected for the pointee.
5326         QualType ValType = cast<ValueDecl>(ND)->getType();
5327         if (ValType.isNull())
5328           continue;
5329         if (ValType->isAnyPointerType() || ValType->isReferenceType())
5330           ValType = ValType->getPointeeType();
5331         if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5332           if (FPT->getNumParams() == NumArgs)
5333             return true;
5334       }
5335     }
5336 
5337     // A typo for a function-style cast can look like a function call in C++.
5338     if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5339                                  : isa<TypeDecl>(ND)) &&
5340         CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5341       // Only a class or class template can take two or more arguments.
5342       return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5343 
5344     // Skip the current candidate if it is not a FunctionDecl or does not accept
5345     // the current number of arguments.
5346     if (!FD || !(FD->getNumParams() >= NumArgs &&
5347                  FD->getMinRequiredArguments() <= NumArgs))
5348       continue;
5349 
5350     // If the current candidate is a non-static C++ method, skip the candidate
5351     // unless the method being corrected--or the current DeclContext, if the
5352     // function being corrected is not a method--is a method in the same class
5353     // or a descendent class of the candidate's parent class.
5354     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5355       if (MemberFn || !MD->isStatic()) {
5356         CXXMethodDecl *CurMD =
5357             MemberFn
5358                 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5359                 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
5360         CXXRecordDecl *CurRD =
5361             CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5362         CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5363         if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5364           continue;
5365       }
5366     }
5367     return true;
5368   }
5369   return false;
5370 }
5371 
5372 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5373                         const PartialDiagnostic &TypoDiag,
5374                         bool ErrorRecovery) {
5375   diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5376                ErrorRecovery);
5377 }
5378 
5379 /// Find which declaration we should import to provide the definition of
5380 /// the given declaration.
5381 static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5382   if (VarDecl *VD = dyn_cast<VarDecl>(D))
5383     return VD->getDefinition();
5384   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5385     return FD->getDefinition();
5386   if (TagDecl *TD = dyn_cast<TagDecl>(D))
5387     return TD->getDefinition();
5388   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
5389     return ID->getDefinition();
5390   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
5391     return PD->getDefinition();
5392   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5393     if (NamedDecl *TTD = TD->getTemplatedDecl())
5394       return getDefinitionToImport(TTD);
5395   return nullptr;
5396 }
5397 
5398 void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
5399                                  MissingImportKind MIK, bool Recover) {
5400   // Suggest importing a module providing the definition of this entity, if
5401   // possible.
5402   NamedDecl *Def = getDefinitionToImport(Decl);
5403   if (!Def)
5404     Def = Decl;
5405 
5406   Module *Owner = getOwningModule(Def);
5407   assert(Owner && "definition of hidden declaration is not in a module");
5408 
5409   llvm::SmallVector<Module*, 8> OwningModules;
5410   OwningModules.push_back(Owner);
5411   auto Merged = Context.getModulesWithMergedDefinition(Def);
5412   OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5413 
5414   diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5415                         Recover);
5416 }
5417 
5418 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5419 /// suggesting the addition of a #include of the specified file.
5420 static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E,
5421                                           llvm::StringRef IncludingFile) {
5422   bool IsSystem = false;
5423   auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5424       E, IncludingFile, &IsSystem);
5425   return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5426 }
5427 
5428 void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5429                                  SourceLocation DeclLoc,
5430                                  ArrayRef<Module *> Modules,
5431                                  MissingImportKind MIK, bool Recover) {
5432   assert(!Modules.empty());
5433 
5434   auto NotePrevious = [&] {
5435     // FIXME: Suppress the note backtrace even under
5436     // -fdiagnostics-show-note-include-stack. We don't care how this
5437     // declaration was previously reached.
5438     Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5439   };
5440 
5441   // Weed out duplicates from module list.
5442   llvm::SmallVector<Module*, 8> UniqueModules;
5443   llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5444   for (auto *M : Modules) {
5445     if (M->Kind == Module::GlobalModuleFragment)
5446       continue;
5447     if (UniqueModuleSet.insert(M).second)
5448       UniqueModules.push_back(M);
5449   }
5450 
5451   // Try to find a suitable header-name to #include.
5452   std::string HeaderName;
5453   if (const FileEntry *Header =
5454           PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5455     if (const FileEntry *FE =
5456             SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5457       HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName());
5458   }
5459 
5460   // If we have a #include we should suggest, or if all definition locations
5461   // were in global module fragments, don't suggest an import.
5462   if (!HeaderName.empty() || UniqueModules.empty()) {
5463     // FIXME: Find a smart place to suggest inserting a #include, and add
5464     // a FixItHint there.
5465     Diag(UseLoc, diag::err_module_unimported_use_header)
5466         << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5467     // Produce a note showing where the entity was declared.
5468     NotePrevious();
5469     if (Recover)
5470       createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5471     return;
5472   }
5473 
5474   Modules = UniqueModules;
5475 
5476   if (Modules.size() > 1) {
5477     std::string ModuleList;
5478     unsigned N = 0;
5479     for (Module *M : Modules) {
5480       ModuleList += "\n        ";
5481       if (++N == 5 && N != Modules.size()) {
5482         ModuleList += "[...]";
5483         break;
5484       }
5485       ModuleList += M->getFullModuleName();
5486     }
5487 
5488     Diag(UseLoc, diag::err_module_unimported_use_multiple)
5489       << (int)MIK << Decl << ModuleList;
5490   } else {
5491     // FIXME: Add a FixItHint that imports the corresponding module.
5492     Diag(UseLoc, diag::err_module_unimported_use)
5493       << (int)MIK << Decl << Modules[0]->getFullModuleName();
5494   }
5495 
5496   NotePrevious();
5497 
5498   // Try to recover by implicitly importing this module.
5499   if (Recover)
5500     createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5501 }
5502 
5503 /// Diagnose a successfully-corrected typo. Separated from the correction
5504 /// itself to allow external validation of the result, etc.
5505 ///
5506 /// \param Correction The result of performing typo correction.
5507 /// \param TypoDiag The diagnostic to produce. This will have the corrected
5508 ///        string added to it (and usually also a fixit).
5509 /// \param PrevNote A note to use when indicating the location of the entity to
5510 ///        which we are correcting. Will have the correction string added to it.
5511 /// \param ErrorRecovery If \c true (the default), the caller is going to
5512 ///        recover from the typo as if the corrected string had been typed.
5513 ///        In this case, \c PDiag must be an error, and we will attach a fixit
5514 ///        to it.
5515 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5516                         const PartialDiagnostic &TypoDiag,
5517                         const PartialDiagnostic &PrevNote,
5518                         bool ErrorRecovery) {
5519   std::string CorrectedStr = Correction.getAsString(getLangOpts());
5520   std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5521   FixItHint FixTypo = FixItHint::CreateReplacement(
5522       Correction.getCorrectionRange(), CorrectedStr);
5523 
5524   // Maybe we're just missing a module import.
5525   if (Correction.requiresImport()) {
5526     NamedDecl *Decl = Correction.getFoundDecl();
5527     assert(Decl && "import required but no declaration to import");
5528 
5529     diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5530                           MissingImportKind::Declaration, ErrorRecovery);
5531     return;
5532   }
5533 
5534   Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5535     << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5536 
5537   NamedDecl *ChosenDecl =
5538       Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5539   if (PrevNote.getDiagID() && ChosenDecl)
5540     Diag(ChosenDecl->getLocation(), PrevNote)
5541       << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5542 
5543   // Add any extra diagnostics.
5544   for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5545     Diag(Correction.getCorrectionRange().getBegin(), PD);
5546 }
5547 
5548 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5549                                   TypoDiagnosticGenerator TDG,
5550                                   TypoRecoveryCallback TRC,
5551                                   SourceLocation TypoLoc) {
5552   assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5553   auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
5554   auto &State = DelayedTypos[TE];
5555   State.Consumer = std::move(TCC);
5556   State.DiagHandler = std::move(TDG);
5557   State.RecoveryHandler = std::move(TRC);
5558   if (TE)
5559     TypoExprs.push_back(TE);
5560   return TE;
5561 }
5562 
5563 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5564   auto Entry = DelayedTypos.find(TE);
5565   assert(Entry != DelayedTypos.end() &&
5566          "Failed to get the state for a TypoExpr!");
5567   return Entry->second;
5568 }
5569 
5570 void Sema::clearDelayedTypo(TypoExpr *TE) {
5571   DelayedTypos.erase(TE);
5572 }
5573 
5574 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5575   DeclarationNameInfo Name(II, IILoc);
5576   LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5577   R.suppressDiagnostics();
5578   R.setHideTags(false);
5579   LookupName(R, S);
5580   R.dump();
5581 }
5582