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