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