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