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