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