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