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