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