1193326Sed//===--------------------- SemaLookup.cpp - Name Lookup  ------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements name lookup for C, C++, Objective-C, and
11193326Sed//  Objective-C++.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14296417Sdim
15212904Sdim#include "clang/Sema/Lookup.h"
16193326Sed#include "clang/AST/ASTContext.h"
17288943Sdim#include "clang/AST/ASTMutationListener.h"
18198092Srdivacky#include "clang/AST/CXXInheritance.h"
19193326Sed#include "clang/AST/Decl.h"
20193326Sed#include "clang/AST/DeclCXX.h"
21234353Sdim#include "clang/AST/DeclLookups.h"
22193326Sed#include "clang/AST/DeclObjC.h"
23193326Sed#include "clang/AST/DeclTemplate.h"
24193326Sed#include "clang/AST/Expr.h"
25198092Srdivacky#include "clang/AST/ExprCXX.h"
26194179Sed#include "clang/Basic/Builtins.h"
27193326Sed#include "clang/Basic/LangOptions.h"
28288943Sdim#include "clang/Lex/HeaderSearch.h"
29276479Sdim#include "clang/Lex/ModuleLoader.h"
30288943Sdim#include "clang/Lex/Preprocessor.h"
31249423Sdim#include "clang/Sema/DeclSpec.h"
32249423Sdim#include "clang/Sema/ExternalSemaSource.h"
33249423Sdim#include "clang/Sema/Overload.h"
34249423Sdim#include "clang/Sema/Scope.h"
35249423Sdim#include "clang/Sema/ScopeInfo.h"
36249423Sdim#include "clang/Sema/Sema.h"
37249423Sdim#include "clang/Sema/SemaInternal.h"
38249423Sdim#include "clang/Sema/TemplateDeduction.h"
39249423Sdim#include "clang/Sema/TypoCorrection.h"
40249423Sdim#include "llvm/ADT/STLExtras.h"
41234353Sdim#include "llvm/ADT/SetVector.h"
42193326Sed#include "llvm/ADT/SmallPtrSet.h"
43218893Sdim#include "llvm/ADT/StringMap.h"
44226633Sdim#include "llvm/ADT/TinyPtrVector.h"
45234353Sdim#include "llvm/ADT/edit_distance.h"
46198092Srdivacky#include "llvm/Support/ErrorHandling.h"
47234353Sdim#include <algorithm>
48234353Sdim#include <iterator>
49218893Sdim#include <limits>
50201361Srdivacky#include <list>
51234353Sdim#include <map>
52193326Sed#include <set>
53234353Sdim#include <utility>
54193326Sed#include <vector>
55193326Sed
56193326Sedusing namespace clang;
57212904Sdimusing namespace sema;
58193326Sed
59199482Srdivackynamespace {
60199482Srdivacky  class UnqualUsingEntry {
61199482Srdivacky    const DeclContext *Nominated;
62199482Srdivacky    const DeclContext *CommonAncestor;
63193326Sed
64199482Srdivacky  public:
65199482Srdivacky    UnqualUsingEntry(const DeclContext *Nominated,
66199482Srdivacky                     const DeclContext *CommonAncestor)
67199482Srdivacky      : Nominated(Nominated), CommonAncestor(CommonAncestor) {
68199482Srdivacky    }
69193326Sed
70199482Srdivacky    const DeclContext *getCommonAncestor() const {
71199482Srdivacky      return CommonAncestor;
72199482Srdivacky    }
73193326Sed
74199482Srdivacky    const DeclContext *getNominatedNamespace() const {
75199482Srdivacky      return Nominated;
76199482Srdivacky    }
77193326Sed
78199482Srdivacky    // Sort by the pointer value of the common ancestor.
79199482Srdivacky    struct Comparator {
80199482Srdivacky      bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
81199482Srdivacky        return L.getCommonAncestor() < R.getCommonAncestor();
82199482Srdivacky      }
83193326Sed
84199482Srdivacky      bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
85199482Srdivacky        return E.getCommonAncestor() < DC;
86199482Srdivacky      }
87193326Sed
88199482Srdivacky      bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
89199482Srdivacky        return DC < E.getCommonAncestor();
90199482Srdivacky      }
91199482Srdivacky    };
92199482Srdivacky  };
93193326Sed
94199482Srdivacky  /// A collection of using directives, as used by C++ unqualified
95199482Srdivacky  /// lookup.
96199482Srdivacky  class UnqualUsingDirectiveSet {
97226633Sdim    typedef SmallVector<UnqualUsingEntry, 8> ListTy;
98193326Sed
99199482Srdivacky    ListTy list;
100199482Srdivacky    llvm::SmallPtrSet<DeclContext*, 8> visited;
101193326Sed
102199482Srdivacky  public:
103199482Srdivacky    UnqualUsingDirectiveSet() {}
104193326Sed
105199482Srdivacky    void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
106218893Sdim      // C++ [namespace.udir]p1:
107199482Srdivacky      //   During unqualified name lookup, the names appear as if they
108199482Srdivacky      //   were declared in the nearest enclosing namespace which contains
109199482Srdivacky      //   both the using-directive and the nominated namespace.
110261991Sdim      DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
111199482Srdivacky      assert(InnermostFileDC && InnermostFileDC->isFileContext());
112193326Sed
113199482Srdivacky      for (; S; S = S->getParent()) {
114234353Sdim        // C++ [namespace.udir]p1:
115234353Sdim        //   A using-directive shall not appear in class scope, but may
116234353Sdim        //   appear in namespace scope or in block scope.
117261991Sdim        DeclContext *Ctx = S->getEntity();
118234353Sdim        if (Ctx && Ctx->isFileContext()) {
119234353Sdim          visit(Ctx, Ctx);
120234353Sdim        } else if (!Ctx || Ctx->isFunctionOrMethod()) {
121276479Sdim          for (auto *I : S->using_directives())
122276479Sdim            visit(I, InnermostFileDC);
123199482Srdivacky        }
124199482Srdivacky      }
125199482Srdivacky    }
126193326Sed
127199482Srdivacky    // Visits a context and collect all of its using directives
128199482Srdivacky    // recursively.  Treats all using directives as if they were
129199482Srdivacky    // declared in the context.
130199482Srdivacky    //
131199482Srdivacky    // A given context is only every visited once, so it is important
132199482Srdivacky    // that contexts be visited from the inside out in order to get
133199482Srdivacky    // the effective DCs right.
134199482Srdivacky    void visit(DeclContext *DC, DeclContext *EffectiveDC) {
135280031Sdim      if (!visited.insert(DC).second)
136199482Srdivacky        return;
137193326Sed
138199482Srdivacky      addUsingDirectives(DC, EffectiveDC);
139199482Srdivacky    }
140199482Srdivacky
141199482Srdivacky    // Visits a using directive and collects all of its using
142199482Srdivacky    // directives recursively.  Treats all using directives as if they
143199482Srdivacky    // were declared in the effective DC.
144199482Srdivacky    void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
145199482Srdivacky      DeclContext *NS = UD->getNominatedNamespace();
146280031Sdim      if (!visited.insert(NS).second)
147199482Srdivacky        return;
148199482Srdivacky
149199482Srdivacky      addUsingDirective(UD, EffectiveDC);
150199482Srdivacky      addUsingDirectives(NS, EffectiveDC);
151199482Srdivacky    }
152199482Srdivacky
153199482Srdivacky    // Adds all the using directives in a context (and those nominated
154199482Srdivacky    // by its using directives, transitively) as if they appeared in
155199482Srdivacky    // the given effective context.
156199482Srdivacky    void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
157296417Sdim      SmallVector<DeclContext*, 4> queue;
158199482Srdivacky      while (true) {
159276479Sdim        for (auto UD : DC->using_directives()) {
160199482Srdivacky          DeclContext *NS = UD->getNominatedNamespace();
161280031Sdim          if (visited.insert(NS).second) {
162199482Srdivacky            addUsingDirective(UD, EffectiveDC);
163199482Srdivacky            queue.push_back(NS);
164199482Srdivacky          }
165199482Srdivacky        }
166199482Srdivacky
167199482Srdivacky        if (queue.empty())
168199482Srdivacky          return;
169199482Srdivacky
170261991Sdim        DC = queue.pop_back_val();
171193326Sed      }
172193326Sed    }
173199482Srdivacky
174199482Srdivacky    // Add a using directive as if it had been declared in the given
175199482Srdivacky    // context.  This helps implement C++ [namespace.udir]p3:
176199482Srdivacky    //   The using-directive is transitive: if a scope contains a
177199482Srdivacky    //   using-directive that nominates a second namespace that itself
178199482Srdivacky    //   contains using-directives, the effect is as if the
179199482Srdivacky    //   using-directives from the second namespace also appeared in
180199482Srdivacky    //   the first.
181199482Srdivacky    void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182199482Srdivacky      // Find the common ancestor between the effective context and
183199482Srdivacky      // the nominated namespace.
184199482Srdivacky      DeclContext *Common = UD->getNominatedNamespace();
185199482Srdivacky      while (!Common->Encloses(EffectiveDC))
186199482Srdivacky        Common = Common->getParent();
187199482Srdivacky      Common = Common->getPrimaryContext();
188218893Sdim
189199482Srdivacky      list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
190199482Srdivacky    }
191199482Srdivacky
192199482Srdivacky    void done() {
193199482Srdivacky      std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
194199482Srdivacky    }
195199482Srdivacky
196199482Srdivacky    typedef ListTy::const_iterator const_iterator;
197218893Sdim
198199482Srdivacky    const_iterator begin() const { return list.begin(); }
199199482Srdivacky    const_iterator end() const { return list.end(); }
200199482Srdivacky
201288943Sdim    llvm::iterator_range<const_iterator>
202199482Srdivacky    getNamespacesFor(DeclContext *DC) const {
203288943Sdim      return llvm::make_range(std::equal_range(begin(), end(),
204288943Sdim                                               DC->getPrimaryContext(),
205288943Sdim                                               UnqualUsingEntry::Comparator()));
206199482Srdivacky    }
207199482Srdivacky  };
208296417Sdim} // end anonymous namespace
209193326Sed
210193326Sed// Retrieve the set of identifier namespaces that correspond to a
211193326Sed// specific kind of name lookup.
212201361Srdivackystatic inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213201361Srdivacky                               bool CPlusPlus,
214201361Srdivacky                               bool Redeclaration) {
215193326Sed  unsigned IDNS = 0;
216193326Sed  switch (NameKind) {
217224145Sdim  case Sema::LookupObjCImplicitSelfParam:
218193326Sed  case Sema::LookupOrdinaryName:
219193326Sed  case Sema::LookupRedeclarationWithLinkage:
220261991Sdim  case Sema::LookupLocalFriendName:
221193326Sed    IDNS = Decl::IDNS_Ordinary;
222201361Srdivacky    if (CPlusPlus) {
223207619Srdivacky      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
224218893Sdim      if (Redeclaration)
225218893Sdim        IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
226201361Srdivacky    }
227261991Sdim    if (Redeclaration)
228261991Sdim      IDNS |= Decl::IDNS_LocalExtern;
229193326Sed    break;
230193326Sed
231207619Srdivacky  case Sema::LookupOperatorName:
232207619Srdivacky    // Operator lookup is its own crazy thing;  it is not the same
233207619Srdivacky    // as (e.g.) looking up an operator name for redeclaration.
234207619Srdivacky    assert(!Redeclaration && "cannot do redeclaration operator lookup");
235207619Srdivacky    IDNS = Decl::IDNS_NonMemberOperator;
236207619Srdivacky    break;
237207619Srdivacky
238193326Sed  case Sema::LookupTagName:
239207619Srdivacky    if (CPlusPlus) {
240207619Srdivacky      IDNS = Decl::IDNS_Type;
241207619Srdivacky
242207619Srdivacky      // When looking for a redeclaration of a tag name, we add:
243207619Srdivacky      // 1) TagFriend to find undeclared friend decls
244207619Srdivacky      // 2) Namespace because they can't "overload" with tag decls.
245207619Srdivacky      // 3) Tag because it includes class templates, which can't
246207619Srdivacky      //    "overload" with tag decls.
247207619Srdivacky      if (Redeclaration)
248207619Srdivacky        IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
249207619Srdivacky    } else {
250207619Srdivacky      IDNS = Decl::IDNS_Tag;
251207619Srdivacky    }
252193326Sed    break;
253276479Sdim
254218893Sdim  case Sema::LookupLabel:
255218893Sdim    IDNS = Decl::IDNS_Label;
256218893Sdim    break;
257276479Sdim
258193326Sed  case Sema::LookupMemberName:
259193326Sed    IDNS = Decl::IDNS_Member;
260193326Sed    if (CPlusPlus)
261198092Srdivacky      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
262193326Sed    break;
263193326Sed
264193326Sed  case Sema::LookupNestedNameSpecifierName:
265207619Srdivacky    IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
266207619Srdivacky    break;
267207619Srdivacky
268193326Sed  case Sema::LookupNamespaceName:
269207619Srdivacky    IDNS = Decl::IDNS_Namespace;
270193326Sed    break;
271193326Sed
272200583Srdivacky  case Sema::LookupUsingDeclName:
273276479Sdim    assert(Redeclaration && "should only be used for redecl lookup");
274276479Sdim    IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
275276479Sdim           Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
276276479Sdim           Decl::IDNS_LocalExtern;
277200583Srdivacky    break;
278200583Srdivacky
279193326Sed  case Sema::LookupObjCProtocolName:
280193326Sed    IDNS = Decl::IDNS_ObjCProtocol;
281193326Sed    break;
282218893Sdim
283212904Sdim  case Sema::LookupAnyName:
284218893Sdim    IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
285212904Sdim      | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
286212904Sdim      | Decl::IDNS_Type;
287212904Sdim    break;
288193326Sed  }
289193326Sed  return IDNS;
290193326Sed}
291193326Sed
292201361Srdivackyvoid LookupResult::configure() {
293280031Sdim  IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
294201361Srdivacky                 isForRedeclaration());
295206084Srdivacky
296276479Sdim  // If we're looking for one of the allocation or deallocation
297276479Sdim  // operators, make sure that the implicitly-declared new and delete
298276479Sdim  // operators can be found.
299276479Sdim  switch (NameInfo.getName().getCXXOverloadedOperator()) {
300276479Sdim  case OO_New:
301276479Sdim  case OO_Delete:
302276479Sdim  case OO_Array_New:
303276479Sdim  case OO_Array_Delete:
304280031Sdim    getSema().DeclareGlobalNewDelete();
305276479Sdim    break;
306206084Srdivacky
307276479Sdim  default:
308276479Sdim    break;
309276479Sdim  }
310249423Sdim
311276479Sdim  // Compiler builtins are always visible, regardless of where they end
312276479Sdim  // up being declared.
313276479Sdim  if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
314276479Sdim    if (unsigned BuiltinID = Id->getBuiltinID()) {
315280031Sdim      if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
316276479Sdim        AllowHidden = true;
317249423Sdim    }
318206084Srdivacky  }
319201361Srdivacky}
320201361Srdivacky
321276479Sdimbool LookupResult::sanity() const {
322276479Sdim  // This function is never called by NDEBUG builds.
323212904Sdim  assert(ResultKind != NotFound || Decls.size() == 0);
324212904Sdim  assert(ResultKind != Found || Decls.size() == 1);
325212904Sdim  assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
326212904Sdim         (Decls.size() == 1 &&
327212904Sdim          isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
328212904Sdim  assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
329212904Sdim  assert(ResultKind != Ambiguous || Decls.size() > 1 ||
330218893Sdim         (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
331218893Sdim                                Ambiguity == AmbiguousBaseSubobjectTypes)));
332276479Sdim  assert((Paths != nullptr) == (ResultKind == Ambiguous &&
333276479Sdim                                (Ambiguity == AmbiguousBaseSubobjectTypes ||
334276479Sdim                                 Ambiguity == AmbiguousBaseSubobjects)));
335276479Sdim  return true;
336212904Sdim}
337212904Sdim
338198092Srdivacky// Necessary because CXXBasePaths is not complete in Sema.h
339199482Srdivackyvoid LookupResult::deletePaths(CXXBasePaths *Paths) {
340198092Srdivacky  delete Paths;
341193326Sed}
342193326Sed
343261991Sdim/// Get a representative context for a declaration such that two declarations
344261991Sdim/// will have the same context if they were found within the same scope.
345261991Sdimstatic DeclContext *getContextForScopeMatching(Decl *D) {
346261991Sdim  // For function-local declarations, use that function as the context. This
347261991Sdim  // doesn't account for scopes within the function; the caller must deal with
348261991Sdim  // those.
349261991Sdim  DeclContext *DC = D->getLexicalDeclContext();
350261991Sdim  if (DC->isFunctionOrMethod())
351261991Sdim    return DC;
352234353Sdim
353261991Sdim  // Otherwise, look at the semantic context of the declaration. The
354261991Sdim  // declaration must have been found there.
355261991Sdim  return D->getDeclContext()->getRedeclContext();
356234353Sdim}
357234353Sdim
358296417Sdim/// \brief Determine whether \p D is a better lookup result than \p Existing,
359296417Sdim/// given that they declare the same entity.
360296417Sdimstatic bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
361296417Sdim                                    NamedDecl *D, NamedDecl *Existing) {
362296417Sdim  // When looking up redeclarations of a using declaration, prefer a using
363296417Sdim  // shadow declaration over any other declaration of the same entity.
364296417Sdim  if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
365296417Sdim      !isa<UsingShadowDecl>(Existing))
366296417Sdim    return true;
367296417Sdim
368296417Sdim  auto *DUnderlying = D->getUnderlyingDecl();
369296417Sdim  auto *EUnderlying = Existing->getUnderlyingDecl();
370296417Sdim
371296417Sdim  // If they have different underlying declarations, prefer a typedef over the
372296417Sdim  // original type (this happens when two type declarations denote the same
373296417Sdim  // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
374296417Sdim  // might carry additional semantic information, such as an alignment override.
375296417Sdim  // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
376296417Sdim  // declaration over a typedef.
377296417Sdim  if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
378296417Sdim    assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
379296417Sdim    bool HaveTag = isa<TagDecl>(EUnderlying);
380296417Sdim    bool WantTag = Kind == Sema::LookupTagName;
381296417Sdim    return HaveTag != WantTag;
382296417Sdim  }
383296417Sdim
384296417Sdim  // Pick the function with more default arguments.
385296417Sdim  // FIXME: In the presence of ambiguous default arguments, we should keep both,
386296417Sdim  //        so we can diagnose the ambiguity if the default argument is needed.
387296417Sdim  //        See C++ [over.match.best]p3.
388296417Sdim  if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
389296417Sdim    auto *EFD = cast<FunctionDecl>(EUnderlying);
390296417Sdim    unsigned DMin = DFD->getMinRequiredArguments();
391296417Sdim    unsigned EMin = EFD->getMinRequiredArguments();
392296417Sdim    // If D has more default arguments, it is preferred.
393296417Sdim    if (DMin != EMin)
394296417Sdim      return DMin < EMin;
395296417Sdim    // FIXME: When we track visibility for default function arguments, check
396296417Sdim    // that we pick the declaration with more visible default arguments.
397296417Sdim  }
398296417Sdim
399296417Sdim  // Pick the template with more default template arguments.
400296417Sdim  if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
401296417Sdim    auto *ETD = cast<TemplateDecl>(EUnderlying);
402296417Sdim    unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
403296417Sdim    unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
404296417Sdim    // If D has more default arguments, it is preferred. Note that default
405296417Sdim    // arguments (and their visibility) is monotonically increasing across the
406296417Sdim    // redeclaration chain, so this is a quick proxy for "is more recent".
407296417Sdim    if (DMin != EMin)
408296417Sdim      return DMin < EMin;
409296417Sdim    // If D has more *visible* default arguments, it is preferred. Note, an
410296417Sdim    // earlier default argument being visible does not imply that a later
411296417Sdim    // default argument is visible, so we can't just check the first one.
412296417Sdim    for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
413296417Sdim        I != N; ++I) {
414296417Sdim      if (!S.hasVisibleDefaultArgument(
415296417Sdim              ETD->getTemplateParameters()->getParam(I)) &&
416296417Sdim          S.hasVisibleDefaultArgument(
417296417Sdim              DTD->getTemplateParameters()->getParam(I)))
418296417Sdim        return true;
419296417Sdim    }
420296417Sdim  }
421296417Sdim
422296417Sdim  // For most kinds of declaration, it doesn't really matter which one we pick.
423296417Sdim  if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
424296417Sdim    // If the existing declaration is hidden, prefer the new one. Otherwise,
425296417Sdim    // keep what we've got.
426296417Sdim    return !S.isVisible(Existing);
427296417Sdim  }
428296417Sdim
429296417Sdim  // Pick the newer declaration; it might have a more precise type.
430296417Sdim  for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
431296417Sdim       Prev = Prev->getPreviousDecl())
432296417Sdim    if (Prev == EUnderlying)
433296417Sdim      return true;
434296417Sdim  return false;
435296417Sdim
436296417Sdim  // If the existing declaration is hidden, prefer the new one. Otherwise,
437296417Sdim  // keep what we've got.
438296417Sdim  return !S.isVisible(Existing);
439296417Sdim}
440296417Sdim
441296417Sdim/// Determine whether \p D can hide a tag declaration.
442296417Sdimstatic bool canHideTag(NamedDecl *D) {
443296417Sdim  // C++ [basic.scope.declarative]p4:
444296417Sdim  //   Given a set of declarations in a single declarative region [...]
445296417Sdim  //   exactly one declaration shall declare a class name or enumeration name
446296417Sdim  //   that is not a typedef name and the other declarations shall all refer to
447296417Sdim  //   the same variable or enumerator, or all refer to functions and function
448296417Sdim  //   templates; in this case the class name or enumeration name is hidden.
449296417Sdim  // C++ [basic.scope.hiding]p2:
450296417Sdim  //   A class name or enumeration name can be hidden by the name of a
451296417Sdim  //   variable, data member, function, or enumerator declared in the same
452296417Sdim  //   scope.
453296417Sdim  D = D->getUnderlyingDecl();
454296417Sdim  return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
455296417Sdim         isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D);
456296417Sdim}
457296417Sdim
458199990Srdivacky/// Resolves the result kind of this lookup.
459199482Srdivackyvoid LookupResult::resolveKind() {
460198092Srdivacky  unsigned N = Decls.size();
461218893Sdim
462198092Srdivacky  // Fast case: no possible ambiguity.
463199512Srdivacky  if (N == 0) {
464296417Sdim    assert(ResultKind == NotFound ||
465296417Sdim           ResultKind == NotFoundInCurrentInstantiation);
466199512Srdivacky    return;
467199512Srdivacky  }
468199512Srdivacky
469199990Srdivacky  // If there's a single decl, we need to examine it to decide what
470199990Srdivacky  // kind of lookup this is.
471199482Srdivacky  if (N == 1) {
472207619Srdivacky    NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
473207619Srdivacky    if (isa<FunctionTemplateDecl>(D))
474199990Srdivacky      ResultKind = FoundOverloaded;
475207619Srdivacky    else if (isa<UnresolvedUsingValueDecl>(D))
476199482Srdivacky      ResultKind = FoundUnresolvedValue;
477199482Srdivacky    return;
478199482Srdivacky  }
479193326Sed
480198092Srdivacky  // Don't do any extra resolution if we've already resolved as ambiguous.
481199482Srdivacky  if (ResultKind == Ambiguous) return;
482195099Sed
483296417Sdim  llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
484296417Sdim  llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
485218893Sdim
486198092Srdivacky  bool Ambiguous = false;
487296417Sdim  bool HasTag = false, HasFunction = false;
488199990Srdivacky  bool HasFunctionTemplate = false, HasUnresolved = false;
489296417Sdim  NamedDecl *HasNonFunction = nullptr;
490193326Sed
491296417Sdim  llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
492296417Sdim
493198092Srdivacky  unsigned UniqueTagIndex = 0;
494218893Sdim
495198092Srdivacky  unsigned I = 0;
496198092Srdivacky  while (I < N) {
497199482Srdivacky    NamedDecl *D = Decls[I]->getUnderlyingDecl();
498199482Srdivacky    D = cast<NamedDecl>(D->getCanonicalDecl());
499198092Srdivacky
500249423Sdim    // Ignore an invalid declaration unless it's the only one left.
501296417Sdim    if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
502249423Sdim      Decls[I] = Decls[--N];
503249423Sdim      continue;
504249423Sdim    }
505249423Sdim
506296417Sdim    llvm::Optional<unsigned> ExistingI;
507296417Sdim
508212904Sdim    // Redeclarations of types via typedef can occur both within a scope
509212904Sdim    // and, through using declarations and directives, across scopes. There is
510212904Sdim    // no ambiguity if they all refer to the same type, so unique based on the
511212904Sdim    // canonical type.
512212904Sdim    if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
513296417Sdim      QualType T = getSema().Context.getTypeDeclType(TD);
514296417Sdim      auto UniqueResult = UniqueTypes.insert(
515296417Sdim          std::make_pair(getSema().Context.getCanonicalType(T), I));
516296417Sdim      if (!UniqueResult.second) {
517296417Sdim        // The type is not unique.
518296417Sdim        ExistingI = UniqueResult.first->second;
519212904Sdim      }
520212904Sdim    }
521218893Sdim
522296417Sdim    // For non-type declarations, check for a prior lookup result naming this
523296417Sdim    // canonical declaration.
524296417Sdim    if (!ExistingI) {
525296417Sdim      auto UniqueResult = Unique.insert(std::make_pair(D, I));
526296417Sdim      if (!UniqueResult.second) {
527296417Sdim        // We've seen this entity before.
528296417Sdim        ExistingI = UniqueResult.first->second;
529296417Sdim      }
530296417Sdim    }
531296417Sdim
532296417Sdim    if (ExistingI) {
533296417Sdim      // This is not a unique lookup result. Pick one of the results and
534296417Sdim      // discard the other.
535296417Sdim      if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
536296417Sdim                                  Decls[*ExistingI]))
537296417Sdim        Decls[*ExistingI] = Decls[I];
538198092Srdivacky      Decls[I] = Decls[--N];
539212904Sdim      continue;
540218893Sdim    }
541218893Sdim
542212904Sdim    // Otherwise, do some decl type analysis and then continue.
543212904Sdim
544212904Sdim    if (isa<UnresolvedUsingValueDecl>(D)) {
545212904Sdim      HasUnresolved = true;
546212904Sdim    } else if (isa<TagDecl>(D)) {
547212904Sdim      if (HasTag)
548212904Sdim        Ambiguous = true;
549212904Sdim      UniqueTagIndex = I;
550212904Sdim      HasTag = true;
551212904Sdim    } else if (isa<FunctionTemplateDecl>(D)) {
552212904Sdim      HasFunction = true;
553212904Sdim      HasFunctionTemplate = true;
554212904Sdim    } else if (isa<FunctionDecl>(D)) {
555212904Sdim      HasFunction = true;
556198092Srdivacky    } else {
557296417Sdim      if (HasNonFunction) {
558296417Sdim        // If we're about to create an ambiguity between two declarations that
559296417Sdim        // are equivalent, but one is an internal linkage declaration from one
560296417Sdim        // module and the other is an internal linkage declaration from another
561296417Sdim        // module, just skip it.
562296417Sdim        if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
563296417Sdim                                                             D)) {
564296417Sdim          EquivalentNonFunctions.push_back(D);
565296417Sdim          Decls[I] = Decls[--N];
566296417Sdim          continue;
567296417Sdim        }
568296417Sdim
569212904Sdim        Ambiguous = true;
570296417Sdim      }
571296417Sdim      HasNonFunction = D;
572193326Sed    }
573212904Sdim    I++;
574193326Sed  }
575193326Sed
576198092Srdivacky  // C++ [basic.scope.hiding]p2:
577198092Srdivacky  //   A class name or enumeration name can be hidden by the name of
578198092Srdivacky  //   an object, function, or enumerator declared in the same
579198092Srdivacky  //   scope. If a class or enumeration name and an object, function,
580198092Srdivacky  //   or enumerator are declared in the same scope (in any order)
581198092Srdivacky  //   with the same name, the class or enumeration name is hidden
582198092Srdivacky  //   wherever the object, function, or enumerator name is visible.
583198092Srdivacky  // But it's still an error if there are distinct tag types found,
584198092Srdivacky  // even if they're not visible. (ref?)
585296417Sdim  if (N > 1 && HideTags && HasTag && !Ambiguous &&
586218893Sdim      (HasFunction || HasNonFunction || HasUnresolved)) {
587296417Sdim    NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
588296417Sdim    if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
589296417Sdim        getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
590296417Sdim            getContextForScopeMatching(OtherDecl)) &&
591296417Sdim        canHideTag(OtherDecl))
592218893Sdim      Decls[UniqueTagIndex] = Decls[--N];
593218893Sdim    else
594218893Sdim      Ambiguous = true;
595218893Sdim  }
596193326Sed
597296417Sdim  // FIXME: This diagnostic should really be delayed until we're done with
598296417Sdim  // the lookup result, in case the ambiguity is resolved by the caller.
599296417Sdim  if (!EquivalentNonFunctions.empty() && !Ambiguous)
600296417Sdim    getSema().diagnoseEquivalentInternalLinkageDeclarations(
601296417Sdim        getNameLoc(), HasNonFunction, EquivalentNonFunctions);
602296417Sdim
603198092Srdivacky  Decls.set_size(N);
604193326Sed
605200583Srdivacky  if (HasNonFunction && (HasFunction || HasUnresolved))
606198092Srdivacky    Ambiguous = true;
607193326Sed
608198092Srdivacky  if (Ambiguous)
609198092Srdivacky    setAmbiguous(LookupResult::AmbiguousReference);
610199482Srdivacky  else if (HasUnresolved)
611199482Srdivacky    ResultKind = LookupResult::FoundUnresolvedValue;
612199990Srdivacky  else if (N > 1 || HasFunctionTemplate)
613199482Srdivacky    ResultKind = LookupResult::FoundOverloaded;
614198092Srdivacky  else
615199482Srdivacky    ResultKind = LookupResult::Found;
616193326Sed}
617193326Sed
618199482Srdivackyvoid LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
619203955Srdivacky  CXXBasePaths::const_paths_iterator I, E;
620198092Srdivacky  for (I = P.begin(), E = P.end(); I != E; ++I)
621249423Sdim    for (DeclContext::lookup_iterator DI = I->Decls.begin(),
622249423Sdim         DE = I->Decls.end(); DI != DE; ++DI)
623198092Srdivacky      addDecl(*DI);
624193326Sed}
625193326Sed
626199482Srdivackyvoid LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
627198092Srdivacky  Paths = new CXXBasePaths;
628198092Srdivacky  Paths->swap(P);
629198092Srdivacky  addDeclsFromBasePaths(*Paths);
630198092Srdivacky  resolveKind();
631198092Srdivacky  setAmbiguous(AmbiguousBaseSubobjects);
632193326Sed}
633193326Sed
634199482Srdivackyvoid LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
635198092Srdivacky  Paths = new CXXBasePaths;
636198092Srdivacky  Paths->swap(P);
637198092Srdivacky  addDeclsFromBasePaths(*Paths);
638198092Srdivacky  resolveKind();
639198092Srdivacky  setAmbiguous(AmbiguousBaseSubobjectTypes);
640193326Sed}
641193326Sed
642226633Sdimvoid LookupResult::print(raw_ostream &Out) {
643198092Srdivacky  Out << Decls.size() << " result(s)";
644198092Srdivacky  if (isAmbiguous()) Out << ", ambiguous";
645198092Srdivacky  if (Paths) Out << ", base paths present";
646218893Sdim
647198092Srdivacky  for (iterator I = begin(), E = end(); I != E; ++I) {
648198092Srdivacky    Out << "\n";
649198092Srdivacky    (*I)->print(Out, 2);
650193326Sed  }
651193326Sed}
652193326Sed
653296417SdimLLVM_DUMP_METHOD void LookupResult::dump() {
654296417Sdim  llvm::errs() << "lookup results for " << getLookupName().getAsString()
655296417Sdim               << ":\n";
656296417Sdim  for (NamedDecl *D : *this)
657296417Sdim    D->dump();
658296417Sdim}
659296417Sdim
660203955Srdivacky/// \brief Lookup a builtin function, when name lookup would otherwise
661203955Srdivacky/// fail.
662203955Srdivackystatic bool LookupBuiltin(Sema &S, LookupResult &R) {
663203955Srdivacky  Sema::LookupNameKind NameKind = R.getLookupKind();
664203955Srdivacky
665203955Srdivacky  // If we didn't find a use of this identifier, and if the identifier
666203955Srdivacky  // corresponds to a compiler builtin, create the decl object for the builtin
667203955Srdivacky  // now, injecting it into translation unit scope, and return it.
668203955Srdivacky  if (NameKind == Sema::LookupOrdinaryName ||
669203955Srdivacky      NameKind == Sema::LookupRedeclarationWithLinkage) {
670203955Srdivacky    IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
671203955Srdivacky    if (II) {
672261991Sdim      if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
673261991Sdim          II == S.getFloat128Identifier()) {
674261991Sdim        // libstdc++4.7's type_traits expects type __float128 to exist, so
675261991Sdim        // insert a dummy type to make that header build in gnu++11 mode.
676261991Sdim        R.addDecl(S.getASTContext().getFloat128StubType());
677261991Sdim        return true;
678261991Sdim      }
679296417Sdim      if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName &&
680296417Sdim          II == S.getASTContext().getMakeIntegerSeqName()) {
681296417Sdim        R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
682296417Sdim        return true;
683296417Sdim      }
684261991Sdim
685203955Srdivacky      // If this is a builtin on this (or all) targets, create the decl.
686203955Srdivacky      if (unsigned BuiltinID = II->getBuiltinID()) {
687203955Srdivacky        // In C++, we don't have any predefined library functions like
688203955Srdivacky        // 'malloc'. Instead, we'll just error.
689234353Sdim        if (S.getLangOpts().CPlusPlus &&
690203955Srdivacky            S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
691203955Srdivacky          return false;
692203955Srdivacky
693218893Sdim        if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
694218893Sdim                                                 BuiltinID, S.TUScope,
695218893Sdim                                                 R.isForRedeclaration(),
696218893Sdim                                                 R.getNameLoc())) {
697203955Srdivacky          R.addDecl(D);
698218893Sdim          return true;
699218893Sdim        }
700203955Srdivacky      }
701203955Srdivacky    }
702203955Srdivacky  }
703203955Srdivacky
704203955Srdivacky  return false;
705203955Srdivacky}
706203955Srdivacky
707210299Sed/// \brief Determine whether we can declare a special member function within
708210299Sed/// the class at this point.
709249423Sdimstatic bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
710210299Sed  // We need to have a definition for the class.
711210299Sed  if (!Class->getDefinition() || Class->isDependentContext())
712210299Sed    return false;
713218893Sdim
714210299Sed  // We can't be in the middle of defining the class.
715249423Sdim  return !Class->isBeingDefined();
716210299Sed}
717210299Sed
718210299Sedvoid Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
719249423Sdim  if (!CanDeclareSpecialMemberFunction(Class))
720210299Sed    return;
721210299Sed
722210299Sed  // If the default constructor has not yet been declared, do so now.
723223017Sdim  if (Class->needsImplicitDefaultConstructor())
724210299Sed    DeclareImplicitDefaultConstructor(Class);
725218893Sdim
726210299Sed  // If the copy constructor has not yet been declared, do so now.
727249423Sdim  if (Class->needsImplicitCopyConstructor())
728210299Sed    DeclareImplicitCopyConstructor(Class);
729218893Sdim
730210299Sed  // If the copy assignment operator has not yet been declared, do so now.
731249423Sdim  if (Class->needsImplicitCopyAssignment())
732210299Sed    DeclareImplicitCopyAssignment(Class);
733210299Sed
734249423Sdim  if (getLangOpts().CPlusPlus11) {
735226633Sdim    // If the move constructor has not yet been declared, do so now.
736226633Sdim    if (Class->needsImplicitMoveConstructor())
737226633Sdim      DeclareImplicitMoveConstructor(Class); // might not actually do it
738226633Sdim
739226633Sdim    // If the move assignment operator has not yet been declared, do so now.
740226633Sdim    if (Class->needsImplicitMoveAssignment())
741226633Sdim      DeclareImplicitMoveAssignment(Class); // might not actually do it
742226633Sdim  }
743226633Sdim
744210299Sed  // If the destructor has not yet been declared, do so now.
745249423Sdim  if (Class->needsImplicitDestructor())
746218893Sdim    DeclareImplicitDestructor(Class);
747210299Sed}
748210299Sed
749218893Sdim/// \brief Determine whether this is the name of an implicitly-declared
750210299Sed/// special member function.
751210299Sedstatic bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
752210299Sed  switch (Name.getNameKind()) {
753210299Sed  case DeclarationName::CXXConstructorName:
754210299Sed  case DeclarationName::CXXDestructorName:
755210299Sed    return true;
756218893Sdim
757210299Sed  case DeclarationName::CXXOperatorName:
758210299Sed    return Name.getCXXOverloadedOperator() == OO_Equal;
759218893Sdim
760210299Sed  default:
761218893Sdim    break;
762210299Sed  }
763218893Sdim
764210299Sed  return false;
765210299Sed}
766210299Sed
767210299Sed/// \brief If there are any implicit member functions with the given name
768210299Sed/// that need to be declared in the given declaration context, do so.
769218893Sdimstatic void DeclareImplicitMemberFunctionsWithName(Sema &S,
770210299Sed                                                   DeclarationName Name,
771210299Sed                                                   const DeclContext *DC) {
772210299Sed  if (!DC)
773210299Sed    return;
774218893Sdim
775210299Sed  switch (Name.getNameKind()) {
776210299Sed  case DeclarationName::CXXConstructorName:
777210299Sed    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
778249423Sdim      if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
779226633Sdim        CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
780223017Sdim        if (Record->needsImplicitDefaultConstructor())
781226633Sdim          S.DeclareImplicitDefaultConstructor(Class);
782249423Sdim        if (Record->needsImplicitCopyConstructor())
783226633Sdim          S.DeclareImplicitCopyConstructor(Class);
784249423Sdim        if (S.getLangOpts().CPlusPlus11 &&
785226633Sdim            Record->needsImplicitMoveConstructor())
786226633Sdim          S.DeclareImplicitMoveConstructor(Class);
787210299Sed      }
788210299Sed    break;
789218893Sdim
790210299Sed  case DeclarationName::CXXDestructorName:
791210299Sed    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
792249423Sdim      if (Record->getDefinition() && Record->needsImplicitDestructor() &&
793249423Sdim          CanDeclareSpecialMemberFunction(Record))
794210299Sed        S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
795210299Sed    break;
796218893Sdim
797210299Sed  case DeclarationName::CXXOperatorName:
798210299Sed    if (Name.getCXXOverloadedOperator() != OO_Equal)
799210299Sed      break;
800218893Sdim
801226633Sdim    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
802249423Sdim      if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
803226633Sdim        CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
804249423Sdim        if (Record->needsImplicitCopyAssignment())
805226633Sdim          S.DeclareImplicitCopyAssignment(Class);
806249423Sdim        if (S.getLangOpts().CPlusPlus11 &&
807226633Sdim            Record->needsImplicitMoveAssignment())
808226633Sdim          S.DeclareImplicitMoveAssignment(Class);
809226633Sdim      }
810226633Sdim    }
811210299Sed    break;
812218893Sdim
813210299Sed  default:
814218893Sdim    break;
815210299Sed  }
816210299Sed}
817210299Sed
818198092Srdivacky// Adds all qualifying matches for a name within a decl context to the
819198092Srdivacky// given lookup result.  Returns true if any matches were found.
820203955Srdivackystatic bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
821198092Srdivacky  bool Found = false;
822193326Sed
823210299Sed  // Lazily declare C++ special member functions.
824234353Sdim  if (S.getLangOpts().CPlusPlus)
825210299Sed    DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
826218893Sdim
827210299Sed  // Perform lookup into this declaration context.
828288943Sdim  DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
829288943Sdim  for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
830249423Sdim       ++I) {
831202879Srdivacky    NamedDecl *D = *I;
832234353Sdim    if ((D = R.getAcceptableDecl(D))) {
833202879Srdivacky      R.addDecl(D);
834202379Srdivacky      Found = true;
835202379Srdivacky    }
836202379Srdivacky  }
837193326Sed
838203955Srdivacky  if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
839203955Srdivacky    return true;
840203955Srdivacky
841202379Srdivacky  if (R.getLookupName().getNameKind()
842203955Srdivacky        != DeclarationName::CXXConversionFunctionName ||
843203955Srdivacky      R.getLookupName().getCXXNameType()->isDependentType() ||
844203955Srdivacky      !isa<CXXRecordDecl>(DC))
845203955Srdivacky    return Found;
846202379Srdivacky
847203955Srdivacky  // C++ [temp.mem]p6:
848218893Sdim  //   A specialization of a conversion function template is not found by
849203955Srdivacky  //   name lookup. Instead, any conversion function templates visible in the
850203955Srdivacky  //   context of the use are considered. [...]
851203955Srdivacky  const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
852226633Sdim  if (!Record->isCompleteDefinition())
853203955Srdivacky    return Found;
854202379Srdivacky
855249423Sdim  for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
856249423Sdim         UEnd = Record->conversion_end(); U != UEnd; ++U) {
857203955Srdivacky    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
858203955Srdivacky    if (!ConvTemplate)
859203955Srdivacky      continue;
860218893Sdim
861203955Srdivacky    // When we're performing lookup for the purposes of redeclaration, just
862218893Sdim    // add the conversion function template. When we deduce template
863218893Sdim    // arguments for specializations, we'll end up unifying the return
864203955Srdivacky    // type of the new declaration with the type of the function template.
865203955Srdivacky    if (R.isForRedeclaration()) {
866203955Srdivacky      R.addDecl(ConvTemplate);
867203955Srdivacky      Found = true;
868203955Srdivacky      continue;
869202379Srdivacky    }
870218893Sdim
871203955Srdivacky    // C++ [temp.mem]p6:
872218893Sdim    //   [...] For each such operator, if argument deduction succeeds
873218893Sdim    //   (14.9.2.3), the resulting specialization is used as if found by
874203955Srdivacky    //   name lookup.
875203955Srdivacky    //
876203955Srdivacky    // When referencing a conversion function for any purpose other than
877203955Srdivacky    // a redeclaration (such that we'll be building an expression with the
878218893Sdim    // result), perform template argument deduction and place the
879203955Srdivacky    // specialization into the result set. We do this to avoid forcing all
880203955Srdivacky    // callers to perform special deduction for conversion functions.
881243830Sdim    TemplateDeductionInfo Info(R.getNameLoc());
882276479Sdim    FunctionDecl *Specialization = nullptr;
883218893Sdim
884218893Sdim    const FunctionProtoType *ConvProto
885203955Srdivacky      = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
886203955Srdivacky    assert(ConvProto && "Nonsensical conversion function template type");
887203955Srdivacky
888203955Srdivacky    // Compute the type of the function that we would expect the conversion
889203955Srdivacky    // function to have, if it were to match the name given.
890203955Srdivacky    // FIXME: Calling convention!
891218893Sdim    FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
892261991Sdim    EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
893280031Sdim    EPI.ExceptionSpec = EST_None;
894203955Srdivacky    QualType ExpectedType
895203955Srdivacky      = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
896251662Sdim                                            None, EPI);
897218893Sdim
898203955Srdivacky    // Perform template argument deduction against the type that we would
899203955Srdivacky    // expect the function to have.
900276479Sdim    if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
901203955Srdivacky                                            Specialization, Info)
902203955Srdivacky          == Sema::TDK_Success) {
903203955Srdivacky      R.addDecl(Specialization);
904203955Srdivacky      Found = true;
905203955Srdivacky    }
906202379Srdivacky  }
907203955Srdivacky
908198092Srdivacky  return Found;
909193326Sed}
910193326Sed
911199482Srdivacky// Performs C++ unqualified lookup into the given file context.
912198092Srdivackystatic bool
913218893SdimCppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
914203955Srdivacky                   DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
915193326Sed
916193326Sed  assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
917193326Sed
918199482Srdivacky  // Perform direct name lookup into the LookupCtx.
919203955Srdivacky  bool Found = LookupDirect(S, R, NS);
920193326Sed
921199482Srdivacky  // Perform direct name lookup into the namespaces nominated by the
922199482Srdivacky  // using directives whose common ancestor is this namespace.
923288943Sdim  for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
924288943Sdim    if (LookupDirect(S, R, UUE.getNominatedNamespace()))
925199482Srdivacky      Found = true;
926198092Srdivacky
927198092Srdivacky  R.resolveKind();
928198092Srdivacky
929198092Srdivacky  return Found;
930193326Sed}
931193326Sed
932193326Sedstatic bool isNamespaceOrTranslationUnitScope(Scope *S) {
933261991Sdim  if (DeclContext *Ctx = S->getEntity())
934193326Sed    return Ctx->isFileContext();
935193326Sed  return false;
936193326Sed}
937193326Sed
938205219Srdivacky// Find the next outer declaration context from this scope. This
939205219Srdivacky// routine actually returns the semantic outer context, which may
940205219Srdivacky// differ from the lexical context (encoded directly in the Scope
941205219Srdivacky// stack) when we are parsing a member of a class template. In this
942205219Srdivacky// case, the second element of the pair will be true, to indicate that
943205219Srdivacky// name lookup should continue searching in this semantic context when
944205219Srdivacky// it leaves the current template parameter scope.
945205219Srdivackystatic std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
946261991Sdim  DeclContext *DC = S->getEntity();
947276479Sdim  DeclContext *Lexical = nullptr;
948218893Sdim  for (Scope *OuterS = S->getParent(); OuterS;
949205219Srdivacky       OuterS = OuterS->getParent()) {
950205219Srdivacky    if (OuterS->getEntity()) {
951261991Sdim      Lexical = OuterS->getEntity();
952205219Srdivacky      break;
953205219Srdivacky    }
954205219Srdivacky  }
955205219Srdivacky
956205219Srdivacky  // C++ [temp.local]p8:
957205219Srdivacky  //   In the definition of a member of a class template that appears
958205219Srdivacky  //   outside of the namespace containing the class template
959205219Srdivacky  //   definition, the name of a template-parameter hides the name of
960205219Srdivacky  //   a member of this namespace.
961205219Srdivacky  //
962205219Srdivacky  // Example:
963205219Srdivacky  //
964218893Sdim  //   namespace N {
965218893Sdim  //     class C { };
966205219Srdivacky  //
967205219Srdivacky  //     template<class T> class B {
968205219Srdivacky  //       void f(T);
969218893Sdim  //     };
970205219Srdivacky  //   }
971205219Srdivacky  //
972205219Srdivacky  //   template<class C> void N::B<C>::f(C) {
973205219Srdivacky  //     C b;  // C is the template parameter, not N::C
974205219Srdivacky  //   }
975205219Srdivacky  //
976205219Srdivacky  // In this example, the lexical context we return is the
977205219Srdivacky  // TranslationUnit, while the semantic context is the namespace N.
978218893Sdim  if (!Lexical || !DC || !S->getParent() ||
979205219Srdivacky      !S->getParent()->isTemplateParamScope())
980205219Srdivacky    return std::make_pair(Lexical, false);
981205219Srdivacky
982218893Sdim  // Find the outermost template parameter scope.
983205219Srdivacky  // For the example, this is the scope for the template parameters of
984205219Srdivacky  // template<class C>.
985205219Srdivacky  Scope *OutermostTemplateScope = S->getParent();
986205219Srdivacky  while (OutermostTemplateScope->getParent() &&
987205219Srdivacky         OutermostTemplateScope->getParent()->isTemplateParamScope())
988205219Srdivacky    OutermostTemplateScope = OutermostTemplateScope->getParent();
989218893Sdim
990205219Srdivacky  // Find the namespace context in which the original scope occurs. In
991205219Srdivacky  // the example, this is namespace N.
992205219Srdivacky  DeclContext *Semantic = DC;
993205219Srdivacky  while (!Semantic->isFileContext())
994205219Srdivacky    Semantic = Semantic->getParent();
995218893Sdim
996205219Srdivacky  // Find the declaration context just outside of the template
997205219Srdivacky  // parameter scope. This is the context in which the template is
998205219Srdivacky  // being lexically declaration (a namespace context). In the
999205219Srdivacky  // example, this is the global scope.
1000205219Srdivacky  if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1001205219Srdivacky      Lexical->Encloses(Semantic))
1002205219Srdivacky    return std::make_pair(Semantic, true);
1003205219Srdivacky
1004205219Srdivacky  return std::make_pair(Lexical, false);
1005198092Srdivacky}
1006198092Srdivacky
1007261991Sdimnamespace {
1008261991Sdim/// An RAII object to specify that we want to find block scope extern
1009261991Sdim/// declarations.
1010261991Sdimstruct FindLocalExternScope {
1011261991Sdim  FindLocalExternScope(LookupResult &R)
1012261991Sdim      : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1013261991Sdim                                 Decl::IDNS_LocalExtern) {
1014261991Sdim    R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
1015261991Sdim  }
1016261991Sdim  void restore() {
1017261991Sdim    R.setFindLocalExtern(OldFindLocalExtern);
1018261991Sdim  }
1019261991Sdim  ~FindLocalExternScope() {
1020261991Sdim    restore();
1021261991Sdim  }
1022261991Sdim  LookupResult &R;
1023261991Sdim  bool OldFindLocalExtern;
1024261991Sdim};
1025296417Sdim} // end anonymous namespace
1026261991Sdim
1027199482Srdivackybool Sema::CppLookupName(LookupResult &R, Scope *S) {
1028234353Sdim  assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1029198092Srdivacky
1030199482Srdivacky  DeclarationName Name = R.getLookupName();
1031261991Sdim  Sema::LookupNameKind NameKind = R.getLookupKind();
1032199482Srdivacky
1033210299Sed  // If this is the name of an implicitly-declared special member function,
1034210299Sed  // go through the scope stack to implicitly declare
1035210299Sed  if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1036210299Sed    for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1037261991Sdim      if (DeclContext *DC = PreS->getEntity())
1038210299Sed        DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
1039210299Sed  }
1040218893Sdim
1041210299Sed  // Implicitly declare member functions with the name we're looking for, if in
1042210299Sed  // fact we are in a scope where it matters.
1043210299Sed
1044193326Sed  Scope *Initial = S;
1045198092Srdivacky  IdentifierResolver::iterator
1046193326Sed    I = IdResolver.begin(Name),
1047193326Sed    IEnd = IdResolver.end();
1048193326Sed
1049193326Sed  // First we lookup local scope.
1050193326Sed  // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1051193326Sed  // ...During unqualified name lookup (3.4.1), the names appear as if
1052193326Sed  // they were declared in the nearest enclosing namespace which contains
1053193326Sed  // both the using-directive and the nominated namespace.
1054198092Srdivacky  // [Note: in this context, "contains" means "contains directly or
1055198092Srdivacky  // indirectly".
1056193326Sed  //
1057193326Sed  // For example:
1058193326Sed  // namespace A { int i; }
1059193326Sed  // void foo() {
1060193326Sed  //   int i;
1061193326Sed  //   {
1062193326Sed  //     using namespace A;
1063193326Sed  //     ++i; // finds local 'i', A::i appears at global scope
1064193326Sed  //   }
1065193326Sed  // }
1066193326Sed  //
1067251662Sdim  UnqualUsingDirectiveSet UDirs;
1068251662Sdim  bool VisitedUsingDirectives = false;
1069261991Sdim  bool LeftStartingScope = false;
1070276479Sdim  DeclContext *OutsideOfTemplateParamDC = nullptr;
1071261991Sdim
1072261991Sdim  // When performing a scope lookup, we want to find local extern decls.
1073261991Sdim  FindLocalExternScope FindLocals(R);
1074261991Sdim
1075193326Sed  for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1076261991Sdim    DeclContext *Ctx = S->getEntity();
1077208600Srdivacky
1078193326Sed    // Check whether the IdResolver has anything in this scope.
1079198092Srdivacky    bool Found = false;
1080212904Sdim    for (; I != IEnd && S->isDeclScope(*I); ++I) {
1081234353Sdim      if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1082261991Sdim        if (NameKind == LookupRedeclarationWithLinkage) {
1083261991Sdim          // Determine whether this (or a previous) declaration is
1084261991Sdim          // out-of-scope.
1085261991Sdim          if (!LeftStartingScope && !Initial->isDeclScope(*I))
1086261991Sdim            LeftStartingScope = true;
1087261991Sdim
1088261991Sdim          // If we found something outside of our starting scope that
1089261991Sdim          // does not have linkage, skip it. If it's a template parameter,
1090261991Sdim          // we still find it, so we can diagnose the invalid redeclaration.
1091261991Sdim          if (LeftStartingScope && !((*I)->hasLinkage()) &&
1092261991Sdim              !(*I)->isTemplateParameter()) {
1093261991Sdim            R.setShadowed();
1094261991Sdim            continue;
1095261991Sdim          }
1096261991Sdim        }
1097261991Sdim
1098198092Srdivacky        Found = true;
1099234353Sdim        R.addDecl(ND);
1100193326Sed      }
1101193326Sed    }
1102198092Srdivacky    if (Found) {
1103198092Srdivacky      R.resolveKind();
1104208600Srdivacky      if (S->isClassScope())
1105208600Srdivacky        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1106208600Srdivacky          R.setNamingClass(Record);
1107198092Srdivacky      return true;
1108198092Srdivacky    }
1109198092Srdivacky
1110261991Sdim    if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1111261991Sdim      // C++11 [class.friend]p11:
1112261991Sdim      //   If a friend declaration appears in a local class and the name
1113261991Sdim      //   specified is an unqualified name, a prior declaration is
1114261991Sdim      //   looked up without considering scopes that are outside the
1115261991Sdim      //   innermost enclosing non-class scope.
1116261991Sdim      return false;
1117261991Sdim    }
1118261991Sdim
1119205219Srdivacky    if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1120205219Srdivacky        S->getParent() && !S->getParent()->isTemplateParamScope()) {
1121205219Srdivacky      // We've just searched the last template parameter scope and
1122239462Sdim      // found nothing, so look into the contexts between the
1123205219Srdivacky      // lexical and semantic declaration contexts returned by
1124205219Srdivacky      // findOuterContext(). This implements the name lookup behavior
1125205219Srdivacky      // of C++ [temp.local]p8.
1126205219Srdivacky      Ctx = OutsideOfTemplateParamDC;
1127276479Sdim      OutsideOfTemplateParamDC = nullptr;
1128205219Srdivacky    }
1129205219Srdivacky
1130205219Srdivacky    if (Ctx) {
1131205219Srdivacky      DeclContext *OuterCtx;
1132205219Srdivacky      bool SearchAfterTemplateScope;
1133276479Sdim      std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1134205219Srdivacky      if (SearchAfterTemplateScope)
1135205219Srdivacky        OutsideOfTemplateParamDC = OuterCtx;
1136205219Srdivacky
1137205219Srdivacky      for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1138204643Srdivacky        // We do not directly look into transparent contexts, since
1139204643Srdivacky        // those entities will be found in the nearest enclosing
1140204643Srdivacky        // non-transparent context.
1141204643Srdivacky        if (Ctx->isTransparentContext())
1142198092Srdivacky          continue;
1143204643Srdivacky
1144204643Srdivacky        // We do not look directly into function or method contexts,
1145204643Srdivacky        // since all of the local variables and parameters of the
1146204643Srdivacky        // function/method are present within the Scope.
1147204643Srdivacky        if (Ctx->isFunctionOrMethod()) {
1148204643Srdivacky          // If we have an Objective-C instance method, look for ivars
1149204643Srdivacky          // in the corresponding interface.
1150204643Srdivacky          if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1151204643Srdivacky            if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1152204643Srdivacky              if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1153204643Srdivacky                ObjCInterfaceDecl *ClassDeclared;
1154204643Srdivacky                if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1155218893Sdim                                                 Name.getAsIdentifierInfo(),
1156204643Srdivacky                                                             ClassDeclared)) {
1157234353Sdim                  if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1158234353Sdim                    R.addDecl(ND);
1159204643Srdivacky                    R.resolveKind();
1160204643Srdivacky                    return true;
1161204643Srdivacky                  }
1162204643Srdivacky                }
1163204643Srdivacky              }
1164204643Srdivacky          }
1165204643Srdivacky
1166204643Srdivacky          continue;
1167204643Srdivacky        }
1168204643Srdivacky
1169249423Sdim        // If this is a file context, we need to perform unqualified name
1170249423Sdim        // lookup considering using directives.
1171249423Sdim        if (Ctx->isFileContext()) {
1172251662Sdim          // If we haven't handled using directives yet, do so now.
1173251662Sdim          if (!VisitedUsingDirectives) {
1174251662Sdim            // Add using directives from this context up to the top level.
1175251662Sdim            for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1176251662Sdim              if (UCtx->isTransparentContext())
1177251662Sdim                continue;
1178249423Sdim
1179251662Sdim              UDirs.visit(UCtx, UCtx);
1180251662Sdim            }
1181251662Sdim
1182251662Sdim            // Find the innermost file scope, so we can add using directives
1183251662Sdim            // from local scopes.
1184251662Sdim            Scope *InnermostFileScope = S;
1185251662Sdim            while (InnermostFileScope &&
1186251662Sdim                   !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1187251662Sdim              InnermostFileScope = InnermostFileScope->getParent();
1188251662Sdim            UDirs.visitScopeChain(Initial, InnermostFileScope);
1189251662Sdim
1190251662Sdim            UDirs.done();
1191251662Sdim
1192251662Sdim            VisitedUsingDirectives = true;
1193251662Sdim          }
1194251662Sdim
1195249423Sdim          if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1196249423Sdim            R.resolveKind();
1197249423Sdim            return true;
1198249423Sdim          }
1199249423Sdim
1200249423Sdim          continue;
1201249423Sdim        }
1202249423Sdim
1203198092Srdivacky        // Perform qualified name lookup into this context.
1204198092Srdivacky        // FIXME: In some cases, we know that every name that could be found by
1205198092Srdivacky        // this qualified name lookup will also be on the identifier chain. For
1206198092Srdivacky        // example, inside a class without any base classes, we never need to
1207198092Srdivacky        // perform qualified lookup because all of the members are on top of the
1208198092Srdivacky        // identifier chain.
1209202379Srdivacky        if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1210198092Srdivacky          return true;
1211193326Sed      }
1212193326Sed    }
1213193326Sed  }
1214193326Sed
1215199482Srdivacky  // Stop if we ran out of scopes.
1216199482Srdivacky  // FIXME:  This really, really shouldn't be happening.
1217199482Srdivacky  if (!S) return false;
1218199482Srdivacky
1219218893Sdim  // If we are looking for members, no need to look into global/namespace scope.
1220261991Sdim  if (NameKind == LookupMemberName)
1221218893Sdim    return false;
1222218893Sdim
1223193326Sed  // Collect UsingDirectiveDecls in all scopes, and recursively all
1224193326Sed  // nominated namespaces by those using-directives.
1225199482Srdivacky  //
1226193326Sed  // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1227193326Sed  // don't build it for each lookup!
1228251662Sdim  if (!VisitedUsingDirectives) {
1229251662Sdim    UDirs.visitScopeChain(Initial, S);
1230251662Sdim    UDirs.done();
1231251662Sdim  }
1232261991Sdim
1233261991Sdim  // If we're not performing redeclaration lookup, do not look for local
1234261991Sdim  // extern declarations outside of a function scope.
1235261991Sdim  if (!R.isForRedeclaration())
1236261991Sdim    FindLocals.restore();
1237261991Sdim
1238193326Sed  // Lookup namespace scope, and global scope.
1239193326Sed  // Unqualified name lookup in C++ requires looking into scopes
1240193326Sed  // that aren't strictly lexical, and therefore we walk through the
1241193326Sed  // context as well as walking through the scopes.
1242193326Sed  for (; S; S = S->getParent()) {
1243193326Sed    // Check whether the IdResolver has anything in this scope.
1244198092Srdivacky    bool Found = false;
1245212904Sdim    for (; I != IEnd && S->isDeclScope(*I); ++I) {
1246234353Sdim      if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1247193326Sed        // We found something.  Look for anything else in our scope
1248193326Sed        // with this same name and in an acceptable identifier
1249193326Sed        // namespace, so that we can construct an overload set if we
1250193326Sed        // need to.
1251198092Srdivacky        Found = true;
1252234353Sdim        R.addDecl(ND);
1253193326Sed      }
1254193326Sed    }
1255193326Sed
1256208600Srdivacky    if (Found && S->isTemplateParamScope()) {
1257208600Srdivacky      R.resolveKind();
1258208600Srdivacky      return true;
1259208600Srdivacky    }
1260193326Sed
1261261991Sdim    DeclContext *Ctx = S->getEntity();
1262208600Srdivacky    if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1263208600Srdivacky        S->getParent() && !S->getParent()->isTemplateParamScope()) {
1264208600Srdivacky      // We've just searched the last template parameter scope and
1265239462Sdim      // found nothing, so look into the contexts between the
1266208600Srdivacky      // lexical and semantic declaration contexts returned by
1267208600Srdivacky      // findOuterContext(). This implements the name lookup behavior
1268208600Srdivacky      // of C++ [temp.local]p8.
1269208600Srdivacky      Ctx = OutsideOfTemplateParamDC;
1270276479Sdim      OutsideOfTemplateParamDC = nullptr;
1271203955Srdivacky    }
1272218893Sdim
1273208600Srdivacky    if (Ctx) {
1274208600Srdivacky      DeclContext *OuterCtx;
1275208600Srdivacky      bool SearchAfterTemplateScope;
1276276479Sdim      std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1277208600Srdivacky      if (SearchAfterTemplateScope)
1278208600Srdivacky        OutsideOfTemplateParamDC = OuterCtx;
1279203955Srdivacky
1280208600Srdivacky      for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1281208600Srdivacky        // We do not directly look into transparent contexts, since
1282208600Srdivacky        // those entities will be found in the nearest enclosing
1283208600Srdivacky        // non-transparent context.
1284208600Srdivacky        if (Ctx->isTransparentContext())
1285208600Srdivacky          continue;
1286218893Sdim
1287208600Srdivacky        // If we have a context, and it's not a context stashed in the
1288208600Srdivacky        // template parameter scope for an out-of-line definition, also
1289208600Srdivacky        // look into that context.
1290208600Srdivacky        if (!(Found && S && S->isTemplateParamScope())) {
1291208600Srdivacky          assert(Ctx->isFileContext() &&
1292208600Srdivacky              "We should have been looking only at file context here already.");
1293218893Sdim
1294208600Srdivacky          // Look into context considering using-directives.
1295208600Srdivacky          if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1296208600Srdivacky            Found = true;
1297208600Srdivacky        }
1298218893Sdim
1299208600Srdivacky        if (Found) {
1300208600Srdivacky          R.resolveKind();
1301208600Srdivacky          return true;
1302208600Srdivacky        }
1303218893Sdim
1304208600Srdivacky        if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1305208600Srdivacky          return false;
1306208600Srdivacky      }
1307198092Srdivacky    }
1308198092Srdivacky
1309203955Srdivacky    if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1310198092Srdivacky      return false;
1311193326Sed  }
1312193326Sed
1313198092Srdivacky  return !R.empty();
1314193326Sed}
1315193326Sed
1316261991Sdim/// \brief Find the declaration that a class temploid member specialization was
1317261991Sdim/// instantiated from, or the member itself if it is an explicit specialization.
1318261991Sdimstatic Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1319261991Sdim  return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1320261991Sdim}
1321261991Sdim
1322288943SdimModule *Sema::getOwningModule(Decl *Entity) {
1323288943Sdim  // If it's imported, grab its owning module.
1324288943Sdim  Module *M = Entity->getImportedOwningModule();
1325288943Sdim  if (M || !isa<NamedDecl>(Entity) || !cast<NamedDecl>(Entity)->isHidden())
1326288943Sdim    return M;
1327288943Sdim  assert(!Entity->isFromASTFile() &&
1328288943Sdim         "hidden entity from AST file has no owning module");
1329288943Sdim
1330288943Sdim  if (!getLangOpts().ModulesLocalVisibility) {
1331288943Sdim    // If we're not tracking visibility locally, the only way a declaration
1332288943Sdim    // can be hidden and local is if it's hidden because it's parent is (for
1333288943Sdim    // instance, maybe this is a lazily-declared special member of an imported
1334288943Sdim    // class).
1335288943Sdim    auto *Parent = cast<NamedDecl>(Entity->getDeclContext());
1336288943Sdim    assert(Parent->isHidden() && "unexpectedly hidden decl");
1337288943Sdim    return getOwningModule(Parent);
1338288943Sdim  }
1339288943Sdim
1340288943Sdim  // It's local and hidden; grab or compute its owning module.
1341288943Sdim  M = Entity->getLocalOwningModule();
1342288943Sdim  if (M)
1343288943Sdim    return M;
1344288943Sdim
1345288943Sdim  if (auto *Containing =
1346288943Sdim          PP.getModuleContainingLocation(Entity->getLocation())) {
1347288943Sdim    M = Containing;
1348288943Sdim  } else if (Entity->isInvalidDecl() || Entity->getLocation().isInvalid()) {
1349288943Sdim    // Don't bother tracking visibility for invalid declarations with broken
1350288943Sdim    // locations.
1351288943Sdim    cast<NamedDecl>(Entity)->setHidden(false);
1352288943Sdim  } else {
1353288943Sdim    // We need to assign a module to an entity that exists outside of any
1354288943Sdim    // module, so that we can hide it from modules that we textually enter.
1355288943Sdim    // Invent a fake module for all such entities.
1356288943Sdim    if (!CachedFakeTopLevelModule) {
1357288943Sdim      CachedFakeTopLevelModule =
1358288943Sdim          PP.getHeaderSearchInfo().getModuleMap().findOrCreateModule(
1359288943Sdim              "<top-level>", nullptr, false, false).first;
1360288943Sdim
1361288943Sdim      auto &SrcMgr = PP.getSourceManager();
1362288943Sdim      SourceLocation StartLoc =
1363288943Sdim          SrcMgr.getLocForStartOfFile(SrcMgr.getMainFileID());
1364288943Sdim      auto &TopLevel =
1365288943Sdim          VisibleModulesStack.empty() ? VisibleModules : VisibleModulesStack[0];
1366288943Sdim      TopLevel.setVisible(CachedFakeTopLevelModule, StartLoc);
1367288943Sdim    }
1368288943Sdim
1369288943Sdim    M = CachedFakeTopLevelModule;
1370288943Sdim  }
1371288943Sdim
1372288943Sdim  if (M)
1373288943Sdim    Entity->setLocalOwningModule(M);
1374288943Sdim  return M;
1375288943Sdim}
1376288943Sdim
1377288943Sdimvoid Sema::makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc) {
1378288943Sdim  if (auto *M = PP.getModuleContainingLocation(Loc))
1379288943Sdim    Context.mergeDefinitionIntoModule(ND, M);
1380288943Sdim  else
1381288943Sdim    // We're not building a module; just make the definition visible.
1382288943Sdim    ND->setHidden(false);
1383288943Sdim
1384288943Sdim  // If ND is a template declaration, make the template parameters
1385288943Sdim  // visible too. They're not (necessarily) within a mergeable DeclContext.
1386288943Sdim  if (auto *TD = dyn_cast<TemplateDecl>(ND))
1387288943Sdim    for (auto *Param : *TD->getTemplateParameters())
1388288943Sdim      makeMergedDefinitionVisible(Param, Loc);
1389288943Sdim}
1390288943Sdim
1391261991Sdim/// \brief Find the module in which the given declaration was defined.
1392288943Sdimstatic Module *getDefiningModule(Sema &S, Decl *Entity) {
1393261991Sdim  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1394261991Sdim    // If this function was instantiated from a template, the defining module is
1395261991Sdim    // the module containing the pattern.
1396261991Sdim    if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1397261991Sdim      Entity = Pattern;
1398261991Sdim  } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1399280031Sdim    if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1400280031Sdim      Entity = Pattern;
1401261991Sdim  } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1402261991Sdim    if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1403261991Sdim      Entity = getInstantiatedFrom(ED, MSInfo);
1404261991Sdim  } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1405261991Sdim    // FIXME: Map from variable template specializations back to the template.
1406261991Sdim    if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1407261991Sdim      Entity = getInstantiatedFrom(VD, MSInfo);
1408261991Sdim  }
1409261991Sdim
1410261991Sdim  // Walk up to the containing context. That might also have been instantiated
1411261991Sdim  // from a template.
1412261991Sdim  DeclContext *Context = Entity->getDeclContext();
1413261991Sdim  if (Context->isFileContext())
1414288943Sdim    return S.getOwningModule(Entity);
1415288943Sdim  return getDefiningModule(S, cast<Decl>(Context));
1416261991Sdim}
1417261991Sdim
1418261991Sdimllvm::DenseSet<Module*> &Sema::getLookupModules() {
1419261991Sdim  unsigned N = ActiveTemplateInstantiations.size();
1420261991Sdim  for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1421261991Sdim       I != N; ++I) {
1422288943Sdim    Module *M =
1423288943Sdim        getDefiningModule(*this, ActiveTemplateInstantiations[I].Entity);
1424261991Sdim    if (M && !LookupModulesCache.insert(M).second)
1425276479Sdim      M = nullptr;
1426261991Sdim    ActiveTemplateInstantiationLookupModules.push_back(M);
1427261991Sdim  }
1428261991Sdim  return LookupModulesCache;
1429261991Sdim}
1430261991Sdim
1431288943Sdimbool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1432288943Sdim  for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1433288943Sdim    if (isModuleVisible(Merged))
1434288943Sdim      return true;
1435288943Sdim  return false;
1436288943Sdim}
1437288943Sdim
1438288943Sdimtemplate<typename ParmDecl>
1439288943Sdimstatic bool
1440288943SdimhasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1441288943Sdim                          llvm::SmallVectorImpl<Module *> *Modules) {
1442288943Sdim  if (!D->hasDefaultArgument())
1443288943Sdim    return false;
1444288943Sdim
1445288943Sdim  while (D) {
1446288943Sdim    auto &DefaultArg = D->getDefaultArgStorage();
1447288943Sdim    if (!DefaultArg.isInherited() && S.isVisible(D))
1448288943Sdim      return true;
1449288943Sdim
1450288943Sdim    if (!DefaultArg.isInherited() && Modules) {
1451288943Sdim      auto *NonConstD = const_cast<ParmDecl*>(D);
1452288943Sdim      Modules->push_back(S.getOwningModule(NonConstD));
1453288943Sdim      const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1454288943Sdim      Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1455288943Sdim    }
1456288943Sdim
1457288943Sdim    // If there was a previous default argument, maybe its parameter is visible.
1458288943Sdim    D = DefaultArg.getInheritedFrom();
1459288943Sdim  }
1460288943Sdim  return false;
1461288943Sdim}
1462288943Sdim
1463288943Sdimbool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1464288943Sdim                                     llvm::SmallVectorImpl<Module *> *Modules) {
1465288943Sdim  if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1466288943Sdim    return ::hasVisibleDefaultArgument(*this, P, Modules);
1467288943Sdim  if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1468288943Sdim    return ::hasVisibleDefaultArgument(*this, P, Modules);
1469288943Sdim  return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1470288943Sdim                                     Modules);
1471288943Sdim}
1472288943Sdim
1473261991Sdim/// \brief Determine whether a declaration is visible to name lookup.
1474261991Sdim///
1475261991Sdim/// This routine determines whether the declaration D is visible in the current
1476261991Sdim/// lookup context, taking into account the current template instantiation
1477261991Sdim/// stack. During template instantiation, a declaration is visible if it is
1478261991Sdim/// visible from a module containing any entity on the template instantiation
1479261991Sdim/// path (by instantiating a template, you allow it to see the declarations that
1480261991Sdim/// your module can see, including those later on in your module).
1481261991Sdimbool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1482288943Sdim  assert(D->isHidden() && "should not call this: not in slow case");
1483296417Sdim  Module *DeclModule = nullptr;
1484296417Sdim
1485296417Sdim  if (SemaRef.getLangOpts().ModulesLocalVisibility) {
1486296417Sdim    DeclModule = SemaRef.getOwningModule(D);
1487296417Sdim    if (!DeclModule) {
1488296417Sdim      // getOwningModule() may have decided the declaration should not be hidden.
1489296417Sdim      assert(!D->isHidden() && "hidden decl not from a module");
1490296417Sdim      return true;
1491296417Sdim    }
1492261991Sdim
1493296417Sdim    // If the owning module is visible, and the decl is not module private,
1494296417Sdim    // then the decl is visible too. (Module private is ignored within the same
1495296417Sdim    // top-level module.)
1496296417Sdim    if ((!D->isFromASTFile() || !D->isModulePrivate()) &&
1497296417Sdim        (SemaRef.isModuleVisible(DeclModule) ||
1498296417Sdim         SemaRef.hasVisibleMergedDefinition(D)))
1499288943Sdim      return true;
1500288943Sdim  }
1501288943Sdim
1502288943Sdim  // If this declaration is not at namespace scope nor module-private,
1503288943Sdim  // then it is visible if its lexical parent has a visible definition.
1504288943Sdim  DeclContext *DC = D->getLexicalDeclContext();
1505288943Sdim  if (!D->isModulePrivate() &&
1506288943Sdim      DC && !DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) {
1507288943Sdim    // For a parameter, check whether our current template declaration's
1508288943Sdim    // lexical context is visible, not whether there's some other visible
1509288943Sdim    // definition of it, because parameters aren't "within" the definition.
1510288943Sdim    if ((D->isTemplateParameter() || isa<ParmVarDecl>(D))
1511288943Sdim            ? isVisible(SemaRef, cast<NamedDecl>(DC))
1512288943Sdim            : SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC))) {
1513288943Sdim      if (SemaRef.ActiveTemplateInstantiations.empty() &&
1514288943Sdim          // FIXME: Do something better in this case.
1515288943Sdim          !SemaRef.getLangOpts().ModulesLocalVisibility) {
1516288943Sdim        // Cache the fact that this declaration is implicitly visible because
1517288943Sdim        // its parent has a visible definition.
1518288943Sdim        D->setHidden(false);
1519288943Sdim      }
1520288943Sdim      return true;
1521288943Sdim    }
1522288943Sdim    return false;
1523288943Sdim  }
1524288943Sdim
1525261991Sdim  // Find the extra places where we need to look.
1526261991Sdim  llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1527261991Sdim  if (LookupModules.empty())
1528261991Sdim    return false;
1529261991Sdim
1530296417Sdim  if (!DeclModule) {
1531296417Sdim    DeclModule = SemaRef.getOwningModule(D);
1532296417Sdim    assert(DeclModule && "hidden decl not from a module");
1533296417Sdim  }
1534296417Sdim
1535261991Sdim  // If our lookup set contains the decl's module, it's visible.
1536261991Sdim  if (LookupModules.count(DeclModule))
1537261991Sdim    return true;
1538261991Sdim
1539261991Sdim  // If the declaration isn't exported, it's not visible in any other module.
1540261991Sdim  if (D->isModulePrivate())
1541261991Sdim    return false;
1542261991Sdim
1543261991Sdim  // Check whether DeclModule is transitively exported to an import of
1544261991Sdim  // the lookup set.
1545296417Sdim  return std::any_of(LookupModules.begin(), LookupModules.end(),
1546296417Sdim                     [&](Module *M) { return M->isModuleVisible(DeclModule); });
1547261991Sdim}
1548261991Sdim
1549288943Sdimbool Sema::isVisibleSlow(const NamedDecl *D) {
1550288943Sdim  return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1551288943Sdim}
1552288943Sdim
1553296417Sdimbool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1554296417Sdim  for (auto *D : R) {
1555296417Sdim    if (isVisible(D))
1556296417Sdim      return true;
1557296417Sdim  }
1558296417Sdim  return New->isExternallyVisible();
1559296417Sdim}
1560296417Sdim
1561234353Sdim/// \brief Retrieve the visible declaration corresponding to D, if any.
1562234353Sdim///
1563234353Sdim/// This routine determines whether the declaration D is visible in the current
1564234353Sdim/// module, with the current imports. If not, it checks whether any
1565234353Sdim/// redeclaration of D is visible, and if so, returns that declaration.
1566261991Sdim///
1567234353Sdim/// \returns D, or a visible previous declaration of D, whichever is more recent
1568234353Sdim/// and visible. If no declaration of D is visible, returns null.
1569261991Sdimstatic NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1570261991Sdim  assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
1571261991Sdim
1572276479Sdim  for (auto RD : D->redecls()) {
1573276479Sdim    if (auto ND = dyn_cast<NamedDecl>(RD)) {
1574288943Sdim      // FIXME: This is wrong in the case where the previous declaration is not
1575288943Sdim      // visible in the same scope as D. This needs to be done much more
1576288943Sdim      // carefully.
1577261991Sdim      if (LookupResult::isVisible(SemaRef, ND))
1578234353Sdim        return ND;
1579234353Sdim    }
1580234353Sdim  }
1581261991Sdim
1582276479Sdim  return nullptr;
1583234353Sdim}
1584234353Sdim
1585261991SdimNamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1586280031Sdim  return findAcceptableDecl(getSema(), D);
1587261991Sdim}
1588261991Sdim
1589193326Sed/// @brief Perform unqualified name lookup starting from a given
1590193326Sed/// scope.
1591193326Sed///
1592193326Sed/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1593193326Sed/// used to find names within the current scope. For example, 'x' in
1594193326Sed/// @code
1595193326Sed/// int x;
1596193326Sed/// int f() {
1597193326Sed///   return x; // unqualified name look finds 'x' in the global scope
1598193326Sed/// }
1599193326Sed/// @endcode
1600193326Sed///
1601193326Sed/// Different lookup criteria can find different names. For example, a
1602193326Sed/// particular scope can have both a struct and a function of the same
1603193326Sed/// name, and each can be found by certain lookup criteria. For more
1604193326Sed/// information about lookup criteria, see the documentation for the
1605193326Sed/// class LookupCriteria.
1606193326Sed///
1607193326Sed/// @param S        The scope from which unqualified name lookup will
1608193326Sed/// begin. If the lookup criteria permits, name lookup may also search
1609193326Sed/// in the parent scopes.
1610193326Sed///
1611239462Sdim/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1612239462Sdim/// look up and the lookup kind), and is updated with the results of lookup
1613239462Sdim/// including zero or more declarations and possibly additional information
1614239462Sdim/// used to diagnose ambiguities.
1615193326Sed///
1616239462Sdim/// @returns \c true if lookup succeeded and false otherwise.
1617199482Srdivackybool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1618199482Srdivacky  DeclarationName Name = R.getLookupName();
1619198092Srdivacky  if (!Name) return false;
1620193326Sed
1621199482Srdivacky  LookupNameKind NameKind = R.getLookupKind();
1622199482Srdivacky
1623234353Sdim  if (!getLangOpts().CPlusPlus) {
1624193326Sed    // Unqualified name lookup in C/Objective-C is purely lexical, so
1625193326Sed    // search in the declarations attached to the name.
1626201361Srdivacky    if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1627193326Sed      // Find the nearest non-transparent declaration scope.
1628193326Sed      while (!(S->getFlags() & Scope::DeclScope) ||
1629261991Sdim             (S->getEntity() && S->getEntity()->isTransparentContext()))
1630193326Sed        S = S->getParent();
1631201361Srdivacky    }
1632193326Sed
1633261991Sdim    // When performing a scope lookup, we want to find local extern decls.
1634261991Sdim    FindLocalExternScope FindLocals(R);
1635193326Sed
1636193326Sed    // Scan up the scope chain looking for a decl that matches this
1637193326Sed    // identifier that is in the appropriate namespace.  This search
1638193326Sed    // should not take long, as shadowing of names is uncommon, and
1639193326Sed    // deep shadowing is extremely uncommon.
1640193326Sed    bool LeftStartingScope = false;
1641193326Sed
1642193326Sed    for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1643198092Srdivacky                                   IEnd = IdResolver.end();
1644193326Sed         I != IEnd; ++I)
1645261991Sdim      if (NamedDecl *D = R.getAcceptableDecl(*I)) {
1646193326Sed        if (NameKind == LookupRedeclarationWithLinkage) {
1647193326Sed          // Determine whether this (or a previous) declaration is
1648193326Sed          // out-of-scope.
1649212904Sdim          if (!LeftStartingScope && !S->isDeclScope(*I))
1650193326Sed            LeftStartingScope = true;
1651193326Sed
1652193326Sed          // If we found something outside of our starting scope that
1653193326Sed          // does not have linkage, skip it.
1654261991Sdim          if (LeftStartingScope && !((*I)->hasLinkage())) {
1655261991Sdim            R.setShadowed();
1656193326Sed            continue;
1657261991Sdim          }
1658193326Sed        }
1659224145Sdim        else if (NameKind == LookupObjCImplicitSelfParam &&
1660224145Sdim                 !isa<ImplicitParamDecl>(*I))
1661224145Sdim          continue;
1662261991Sdim
1663234353Sdim        R.addDecl(D);
1664198092Srdivacky
1665234353Sdim        // Check whether there are any other declarations with the same name
1666234353Sdim        // and in the same scope.
1667234353Sdim        if (I != IEnd) {
1668234353Sdim          // Find the scope in which this declaration was declared (if it
1669234353Sdim          // actually exists in a Scope).
1670234353Sdim          while (S && !S->isDeclScope(D))
1671193326Sed            S = S->getParent();
1672234353Sdim
1673234353Sdim          // If the scope containing the declaration is the translation unit,
1674234353Sdim          // then we'll need to perform our checks based on the matching
1675234353Sdim          // DeclContexts rather than matching scopes.
1676234353Sdim          if (S && isNamespaceOrTranslationUnitScope(S))
1677276479Sdim            S = nullptr;
1678193326Sed
1679234353Sdim          // Compute the DeclContext, if we need it.
1680276479Sdim          DeclContext *DC = nullptr;
1681234353Sdim          if (!S)
1682234353Sdim            DC = (*I)->getDeclContext()->getRedeclContext();
1683234353Sdim
1684193326Sed          IdentifierResolver::iterator LastI = I;
1685193326Sed          for (++LastI; LastI != IEnd; ++LastI) {
1686234353Sdim            if (S) {
1687234353Sdim              // Match based on scope.
1688234353Sdim              if (!S->isDeclScope(*LastI))
1689234353Sdim                break;
1690234353Sdim            } else {
1691234353Sdim              // Match based on DeclContext.
1692234353Sdim              DeclContext *LastDC
1693234353Sdim                = (*LastI)->getDeclContext()->getRedeclContext();
1694234353Sdim              if (!LastDC->Equals(DC))
1695234353Sdim                break;
1696234353Sdim            }
1697261991Sdim
1698261991Sdim            // If the declaration is in the right namespace and visible, add it.
1699261991Sdim            if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1700261991Sdim              R.addDecl(LastD);
1701193326Sed          }
1702234353Sdim
1703234353Sdim          R.resolveKind();
1704193326Sed        }
1705261991Sdim
1706198092Srdivacky        return true;
1707193326Sed      }
1708193326Sed  } else {
1709193326Sed    // Perform C++ unqualified name lookup.
1710199482Srdivacky    if (CppLookupName(R, S))
1711198092Srdivacky      return true;
1712193326Sed  }
1713193326Sed
1714193326Sed  // If we didn't find a use of this identifier, and if the identifier
1715193326Sed  // corresponds to a compiler builtin, create the decl object for the builtin
1716193326Sed  // now, injecting it into translation unit scope, and return it.
1717221345Sdim  if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1718221345Sdim    return true;
1719193326Sed
1720219077Sdim  // If we didn't find a use of this identifier, the ExternalSource
1721219077Sdim  // may be able to handle the situation.
1722219077Sdim  // Note: some lookup failures are expected!
1723219077Sdim  // See e.g. R.isForRedeclaration().
1724219077Sdim  return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1725193326Sed}
1726193326Sed
1727198092Srdivacky/// @brief Perform qualified name lookup in the namespaces nominated by
1728198092Srdivacky/// using directives by the given context.
1729198092Srdivacky///
1730198092Srdivacky/// C++98 [namespace.qual]p2:
1731239462Sdim///   Given X::m (where X is a user-declared namespace), or given \::m
1732198092Srdivacky///   (where X is the global namespace), let S be the set of all
1733198092Srdivacky///   declarations of m in X and in the transitive closure of all
1734198092Srdivacky///   namespaces nominated by using-directives in X and its used
1735198092Srdivacky///   namespaces, except that using-directives are ignored in any
1736198092Srdivacky///   namespace, including X, directly containing one or more
1737198092Srdivacky///   declarations of m. No namespace is searched more than once in
1738198092Srdivacky///   the lookup of a name. If S is the empty set, the program is
1739198092Srdivacky///   ill-formed. Otherwise, if S has exactly one member, or if the
1740198092Srdivacky///   context of the reference is a using-declaration
1741198092Srdivacky///   (namespace.udecl), S is the required set of declarations of
1742198092Srdivacky///   m. Otherwise if the use of m is not one that allows a unique
1743198092Srdivacky///   declaration to be chosen from S, the program is ill-formed.
1744239462Sdim///
1745198092Srdivacky/// C++98 [namespace.qual]p5:
1746198092Srdivacky///   During the lookup of a qualified namespace member name, if the
1747198092Srdivacky///   lookup finds more than one declaration of the member, and if one
1748198092Srdivacky///   declaration introduces a class name or enumeration name and the
1749198092Srdivacky///   other declarations either introduce the same object, the same
1750198092Srdivacky///   enumerator or a set of functions, the non-type name hides the
1751198092Srdivacky///   class or enumeration name if and only if the declarations are
1752198092Srdivacky///   from the same namespace; otherwise (the declarations are from
1753198092Srdivacky///   different namespaces), the program is ill-formed.
1754203955Srdivackystatic bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1755199482Srdivacky                                                 DeclContext *StartDC) {
1756198092Srdivacky  assert(StartDC->isFileContext() && "start context is not a file context");
1757198092Srdivacky
1758276479Sdim  DeclContext::udir_range UsingDirectives = StartDC->using_directives();
1759276479Sdim  if (UsingDirectives.begin() == UsingDirectives.end()) return false;
1760198092Srdivacky
1761198092Srdivacky  // We have at least added all these contexts to the queue.
1762234353Sdim  llvm::SmallPtrSet<DeclContext*, 8> Visited;
1763198092Srdivacky  Visited.insert(StartDC);
1764198092Srdivacky
1765198092Srdivacky  // We have not yet looked into these namespaces, much less added
1766198092Srdivacky  // their "using-children" to the queue.
1767226633Sdim  SmallVector<NamespaceDecl*, 8> Queue;
1768198092Srdivacky
1769198092Srdivacky  // We have already looked into the initial namespace; seed the queue
1770198092Srdivacky  // with its using-children.
1771276479Sdim  for (auto *I : UsingDirectives) {
1772276479Sdim    NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
1773280031Sdim    if (Visited.insert(ND).second)
1774198092Srdivacky      Queue.push_back(ND);
1775198092Srdivacky  }
1776198092Srdivacky
1777198092Srdivacky  // The easiest way to implement the restriction in [namespace.qual]p5
1778198092Srdivacky  // is to check whether any of the individual results found a tag
1779198092Srdivacky  // and, if so, to declare an ambiguity if the final result is not
1780198092Srdivacky  // a tag.
1781198092Srdivacky  bool FoundTag = false;
1782198092Srdivacky  bool FoundNonTag = false;
1783198092Srdivacky
1784199482Srdivacky  LookupResult LocalR(LookupResult::Temporary, R);
1785198092Srdivacky
1786198092Srdivacky  bool Found = false;
1787198092Srdivacky  while (!Queue.empty()) {
1788261991Sdim    NamespaceDecl *ND = Queue.pop_back_val();
1789198092Srdivacky
1790198092Srdivacky    // We go through some convolutions here to avoid copying results
1791198092Srdivacky    // between LookupResults.
1792198092Srdivacky    bool UseLocal = !R.empty();
1793199482Srdivacky    LookupResult &DirectR = UseLocal ? LocalR : R;
1794203955Srdivacky    bool FoundDirect = LookupDirect(S, DirectR, ND);
1795198092Srdivacky
1796198092Srdivacky    if (FoundDirect) {
1797198092Srdivacky      // First do any local hiding.
1798198092Srdivacky      DirectR.resolveKind();
1799198092Srdivacky
1800198092Srdivacky      // If the local result is a tag, remember that.
1801198092Srdivacky      if (DirectR.isSingleTagDecl())
1802198092Srdivacky        FoundTag = true;
1803198092Srdivacky      else
1804198092Srdivacky        FoundNonTag = true;
1805198092Srdivacky
1806198092Srdivacky      // Append the local results to the total results if necessary.
1807198092Srdivacky      if (UseLocal) {
1808198092Srdivacky        R.addAllDecls(LocalR);
1809198092Srdivacky        LocalR.clear();
1810198092Srdivacky      }
1811198092Srdivacky    }
1812198092Srdivacky
1813198092Srdivacky    // If we find names in this namespace, ignore its using directives.
1814198092Srdivacky    if (FoundDirect) {
1815198092Srdivacky      Found = true;
1816198092Srdivacky      continue;
1817198092Srdivacky    }
1818198092Srdivacky
1819276479Sdim    for (auto I : ND->using_directives()) {
1820276479Sdim      NamespaceDecl *Nom = I->getNominatedNamespace();
1821280031Sdim      if (Visited.insert(Nom).second)
1822198092Srdivacky        Queue.push_back(Nom);
1823198092Srdivacky    }
1824198092Srdivacky  }
1825198092Srdivacky
1826198092Srdivacky  if (Found) {
1827198092Srdivacky    if (FoundTag && FoundNonTag)
1828198092Srdivacky      R.setAmbiguousQualifiedTagHiding();
1829198092Srdivacky    else
1830198092Srdivacky      R.resolveKind();
1831198092Srdivacky  }
1832198092Srdivacky
1833198092Srdivacky  return Found;
1834198092Srdivacky}
1835198092Srdivacky
1836212904Sdim/// \brief Callback that looks for any member of a class with the given name.
1837218893Sdimstatic bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1838296417Sdim                            CXXBasePath &Path, DeclarationName Name) {
1839212904Sdim  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1840218893Sdim
1841296417Sdim  Path.Decls = BaseRecord->lookup(Name);
1842249423Sdim  return !Path.Decls.empty();
1843212904Sdim}
1844212904Sdim
1845218893Sdim/// \brief Determine whether the given set of member declarations contains only
1846218893Sdim/// static members, nested types, and enumerators.
1847218893Sdimtemplate<typename InputIterator>
1848218893Sdimstatic bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1849218893Sdim  Decl *D = (*First)->getUnderlyingDecl();
1850218893Sdim  if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1851218893Sdim    return true;
1852218893Sdim
1853218893Sdim  if (isa<CXXMethodDecl>(D)) {
1854218893Sdim    // Determine whether all of the methods are static.
1855218893Sdim    bool AllMethodsAreStatic = true;
1856218893Sdim    for(; First != Last; ++First) {
1857218893Sdim      D = (*First)->getUnderlyingDecl();
1858218893Sdim
1859218893Sdim      if (!isa<CXXMethodDecl>(D)) {
1860218893Sdim        assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1861218893Sdim        break;
1862218893Sdim      }
1863218893Sdim
1864218893Sdim      if (!cast<CXXMethodDecl>(D)->isStatic()) {
1865218893Sdim        AllMethodsAreStatic = false;
1866218893Sdim        break;
1867218893Sdim      }
1868218893Sdim    }
1869218893Sdim
1870218893Sdim    if (AllMethodsAreStatic)
1871218893Sdim      return true;
1872218893Sdim  }
1873218893Sdim
1874218893Sdim  return false;
1875218893Sdim}
1876218893Sdim
1877202379Srdivacky/// \brief Perform qualified name lookup into a given context.
1878193326Sed///
1879193326Sed/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1880193326Sed/// names when the context of those names is explicit specified, e.g.,
1881202379Srdivacky/// "std::vector" or "x->member", or as part of unqualified name lookup.
1882193326Sed///
1883193326Sed/// Different lookup criteria can find different names. For example, a
1884193326Sed/// particular scope can have both a struct and a function of the same
1885193326Sed/// name, and each can be found by certain lookup criteria. For more
1886193326Sed/// information about lookup criteria, see the documentation for the
1887193326Sed/// class LookupCriteria.
1888193326Sed///
1889202379Srdivacky/// \param R captures both the lookup criteria and any lookup results found.
1890202379Srdivacky///
1891202379Srdivacky/// \param LookupCtx The context in which qualified name lookup will
1892193326Sed/// search. If the lookup criteria permits, name lookup may also search
1893193326Sed/// in the parent contexts or (for C++ classes) base classes.
1894193326Sed///
1895218893Sdim/// \param InUnqualifiedLookup true if this is qualified name lookup that
1896202379Srdivacky/// occurs as part of unqualified name lookup.
1897193326Sed///
1898202379Srdivacky/// \returns true if lookup succeeded, false if it failed.
1899202379Srdivackybool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1900202379Srdivacky                               bool InUnqualifiedLookup) {
1901193326Sed  assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1902193326Sed
1903199482Srdivacky  if (!R.getLookupName())
1904198092Srdivacky    return false;
1905198092Srdivacky
1906198092Srdivacky  // Make sure that the declaration context is complete.
1907198092Srdivacky  assert((!isa<TagDecl>(LookupCtx) ||
1908198092Srdivacky          LookupCtx->isDependentContext() ||
1909226633Sdim          cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1910234353Sdim          cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
1911198092Srdivacky         "Declaration context must already be complete!");
1912198092Srdivacky
1913296417Sdim  struct QualifiedLookupInScope {
1914296417Sdim    bool oldVal;
1915296417Sdim    DeclContext *Context;
1916296417Sdim    // Set flag in DeclContext informing debugger that we're looking for qualified name
1917296417Sdim    QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
1918296417Sdim      oldVal = ctx->setUseQualifiedLookup();
1919296417Sdim    }
1920296417Sdim    ~QualifiedLookupInScope() {
1921296417Sdim      Context->setUseQualifiedLookup(oldVal);
1922296417Sdim    }
1923296417Sdim  } QL(LookupCtx);
1924296417Sdim
1925203955Srdivacky  if (LookupDirect(*this, R, LookupCtx)) {
1926198092Srdivacky    R.resolveKind();
1927202879Srdivacky    if (isa<CXXRecordDecl>(LookupCtx))
1928202879Srdivacky      R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1929198092Srdivacky    return true;
1930198092Srdivacky  }
1931193326Sed
1932198092Srdivacky  // Don't descend into implied contexts for redeclarations.
1933198092Srdivacky  // C++98 [namespace.qual]p6:
1934198092Srdivacky  //   In a declaration for a namespace member in which the
1935198092Srdivacky  //   declarator-id is a qualified-id, given that the qualified-id
1936198092Srdivacky  //   for the namespace member has the form
1937198092Srdivacky  //     nested-name-specifier unqualified-id
1938198092Srdivacky  //   the unqualified-id shall name a member of the namespace
1939198092Srdivacky  //   designated by the nested-name-specifier.
1940198092Srdivacky  // See also [class.mfct]p5 and [class.static.data]p2.
1941199482Srdivacky  if (R.isForRedeclaration())
1942198092Srdivacky    return false;
1943198092Srdivacky
1944199482Srdivacky  // If this is a namespace, look it up in the implied namespaces.
1945198092Srdivacky  if (LookupCtx->isFileContext())
1946203955Srdivacky    return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1947198092Srdivacky
1948198092Srdivacky  // If this isn't a C++ class, we aren't allowed to look into base
1949193326Sed  // classes, we're done.
1950202379Srdivacky  CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1951210299Sed  if (!LookupRec || !LookupRec->getDefinition())
1952198092Srdivacky    return false;
1953193326Sed
1954202379Srdivacky  // If we're performing qualified name lookup into a dependent class,
1955202379Srdivacky  // then we are actually looking into a current instantiation. If we have any
1956218893Sdim  // dependent base classes, then we either have to delay lookup until
1957202379Srdivacky  // template instantiation time (at which point all bases will be available)
1958202379Srdivacky  // or we have to fail.
1959202379Srdivacky  if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1960202379Srdivacky      LookupRec->hasAnyDependentBases()) {
1961202379Srdivacky    R.setNotFoundInCurrentInstantiation();
1962202379Srdivacky    return false;
1963202379Srdivacky  }
1964218893Sdim
1965193326Sed  // Perform lookup into our base classes.
1966198092Srdivacky  CXXBasePaths Paths;
1967198092Srdivacky  Paths.setOrigin(LookupRec);
1968193326Sed
1969193326Sed  // Look for this member in our base classes
1970296417Sdim  bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
1971296417Sdim                       DeclarationName Name) = nullptr;
1972199482Srdivacky  switch (R.getLookupKind()) {
1973224145Sdim    case LookupObjCImplicitSelfParam:
1974198092Srdivacky    case LookupOrdinaryName:
1975198092Srdivacky    case LookupMemberName:
1976198092Srdivacky    case LookupRedeclarationWithLinkage:
1977261991Sdim    case LookupLocalFriendName:
1978198092Srdivacky      BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1979198092Srdivacky      break;
1980218893Sdim
1981198092Srdivacky    case LookupTagName:
1982198092Srdivacky      BaseCallback = &CXXRecordDecl::FindTagMember;
1983198092Srdivacky      break;
1984200583Srdivacky
1985212904Sdim    case LookupAnyName:
1986212904Sdim      BaseCallback = &LookupAnyMember;
1987212904Sdim      break;
1988218893Sdim
1989200583Srdivacky    case LookupUsingDeclName:
1990200583Srdivacky      // This lookup is for redeclarations only.
1991218893Sdim
1992198092Srdivacky    case LookupOperatorName:
1993198092Srdivacky    case LookupNamespaceName:
1994198092Srdivacky    case LookupObjCProtocolName:
1995218893Sdim    case LookupLabel:
1996198092Srdivacky      // These lookups will never find a member in a C++ class (or base class).
1997198092Srdivacky      return false;
1998218893Sdim
1999198092Srdivacky    case LookupNestedNameSpecifierName:
2000198092Srdivacky      BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2001198092Srdivacky      break;
2002198092Srdivacky  }
2003218893Sdim
2004296417Sdim  DeclarationName Name = R.getLookupName();
2005296417Sdim  if (!LookupRec->lookupInBases(
2006296417Sdim          [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2007296417Sdim            return BaseCallback(Specifier, Path, Name);
2008296417Sdim          },
2009296417Sdim          Paths))
2010198092Srdivacky    return false;
2011193326Sed
2012202879Srdivacky  R.setNamingClass(LookupRec);
2013202879Srdivacky
2014193326Sed  // C++ [class.member.lookup]p2:
2015193326Sed  //   [...] If the resulting set of declarations are not all from
2016193326Sed  //   sub-objects of the same type, or the set has a nonstatic member
2017193326Sed  //   and includes members from distinct sub-objects, there is an
2018193326Sed  //   ambiguity and the program is ill-formed. Otherwise that set is
2019193326Sed  //   the result of the lookup.
2020193326Sed  QualType SubobjectType;
2021193326Sed  int SubobjectNumber = 0;
2022205408Srdivacky  AccessSpecifier SubobjectAccess = AS_none;
2023218893Sdim
2024198092Srdivacky  for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2025193326Sed       Path != PathEnd; ++Path) {
2026198092Srdivacky    const CXXBasePathElement &PathElement = Path->back();
2027193326Sed
2028202879Srdivacky    // Pick the best (i.e. most permissive i.e. numerically lowest) access
2029202879Srdivacky    // across all paths.
2030202879Srdivacky    SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2031218893Sdim
2032193326Sed    // Determine whether we're looking at a distinct sub-object or not.
2033193326Sed    if (SubobjectType.isNull()) {
2034198092Srdivacky      // This is the first subobject we've looked at. Record its type.
2035193326Sed      SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2036193326Sed      SubobjectNumber = PathElement.SubobjectNumber;
2037218893Sdim      continue;
2038218893Sdim    }
2039218893Sdim
2040218893Sdim    if (SubobjectType
2041193326Sed                 != Context.getCanonicalType(PathElement.Base->getType())) {
2042193326Sed      // We found members of the given name in two subobjects of
2043218893Sdim      // different types. If the declaration sets aren't the same, this
2044276479Sdim      // lookup is ambiguous.
2045249423Sdim      if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
2046218893Sdim        CXXBasePaths::paths_iterator FirstPath = Paths.begin();
2047249423Sdim        DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2048249423Sdim        DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
2049218893Sdim
2050249423Sdim        while (FirstD != FirstPath->Decls.end() &&
2051249423Sdim               CurrentD != Path->Decls.end()) {
2052218893Sdim         if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2053218893Sdim             (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2054218893Sdim           break;
2055218893Sdim
2056218893Sdim          ++FirstD;
2057218893Sdim          ++CurrentD;
2058218893Sdim        }
2059218893Sdim
2060249423Sdim        if (FirstD == FirstPath->Decls.end() &&
2061249423Sdim            CurrentD == Path->Decls.end())
2062218893Sdim          continue;
2063218893Sdim      }
2064218893Sdim
2065198092Srdivacky      R.setAmbiguousBaseSubobjectTypes(Paths);
2066198092Srdivacky      return true;
2067218893Sdim    }
2068218893Sdim
2069218893Sdim    if (SubobjectNumber != PathElement.SubobjectNumber) {
2070193326Sed      // We have a different subobject of the same type.
2071193326Sed
2072193326Sed      // C++ [class.member.lookup]p5:
2073193326Sed      //   A static member, a nested type or an enumerator defined in
2074193326Sed      //   a base class T can unambiguously be found even if an object
2075198092Srdivacky      //   has more than one base class subobject of type T.
2076249423Sdim      if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
2077193326Sed        continue;
2078193326Sed
2079193326Sed      // We have found a nonstatic member name in multiple, distinct
2080193326Sed      // subobjects. Name lookup is ambiguous.
2081198092Srdivacky      R.setAmbiguousBaseSubobjects(Paths);
2082198092Srdivacky      return true;
2083193326Sed    }
2084193326Sed  }
2085193326Sed
2086193326Sed  // Lookup in a base class succeeded; return these results.
2087193326Sed
2088276479Sdim  for (auto *D : Paths.front().Decls) {
2089202879Srdivacky    AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2090202879Srdivacky                                                    D->getAccess());
2091202879Srdivacky    R.addDecl(D, AS);
2092202879Srdivacky  }
2093198092Srdivacky  R.resolveKind();
2094198092Srdivacky  return true;
2095193326Sed}
2096193326Sed
2097280031Sdim/// \brief Performs qualified name lookup or special type of lookup for
2098280031Sdim/// "__super::" scope specifier.
2099280031Sdim///
2100280031Sdim/// This routine is a convenience overload meant to be called from contexts
2101280031Sdim/// that need to perform a qualified name lookup with an optional C++ scope
2102280031Sdim/// specifier that might require special kind of lookup.
2103280031Sdim///
2104280031Sdim/// \param R captures both the lookup criteria and any lookup results found.
2105280031Sdim///
2106280031Sdim/// \param LookupCtx The context in which qualified name lookup will
2107280031Sdim/// search.
2108280031Sdim///
2109280031Sdim/// \param SS An optional C++ scope-specifier.
2110280031Sdim///
2111280031Sdim/// \returns true if lookup succeeded, false if it failed.
2112280031Sdimbool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2113280031Sdim                               CXXScopeSpec &SS) {
2114280031Sdim  auto *NNS = SS.getScopeRep();
2115280031Sdim  if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2116280031Sdim    return LookupInSuper(R, NNS->getAsRecordDecl());
2117280031Sdim  else
2118280031Sdim
2119280031Sdim    return LookupQualifiedName(R, LookupCtx);
2120280031Sdim}
2121280031Sdim
2122193326Sed/// @brief Performs name lookup for a name that was parsed in the
2123193326Sed/// source code, and may contain a C++ scope specifier.
2124193326Sed///
2125193326Sed/// This routine is a convenience routine meant to be called from
2126193326Sed/// contexts that receive a name and an optional C++ scope specifier
2127193326Sed/// (e.g., "N::M::x"). It will then perform either qualified or
2128193326Sed/// unqualified name lookup (with LookupQualifiedName or LookupName,
2129280031Sdim/// respectively) on the given name and return those results. It will
2130280031Sdim/// perform a special type of lookup for "__super::" scope specifier.
2131193326Sed///
2132193326Sed/// @param S        The scope from which unqualified name lookup will
2133193326Sed/// begin.
2134193326Sed///
2135198092Srdivacky/// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
2136198092Srdivacky///
2137198092Srdivacky/// @param EnteringContext Indicates whether we are going to enter the
2138198092Srdivacky/// context of the scope-specifier SS (if present).
2139198092Srdivacky///
2140198092Srdivacky/// @returns True if any decls were found (but possibly ambiguous)
2141207619Srdivackybool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2142199482Srdivacky                            bool AllowBuiltinCreation, bool EnteringContext) {
2143198092Srdivacky  if (SS && SS->isInvalid()) {
2144198092Srdivacky    // When the scope specifier is invalid, don't even look for
2145193326Sed    // anything.
2146198092Srdivacky    return false;
2147198092Srdivacky  }
2148193326Sed
2149198092Srdivacky  if (SS && SS->isSet()) {
2150280031Sdim    NestedNameSpecifier *NNS = SS->getScopeRep();
2151280031Sdim    if (NNS->getKind() == NestedNameSpecifier::Super)
2152280031Sdim      return LookupInSuper(R, NNS->getAsRecordDecl());
2153280031Sdim
2154198092Srdivacky    if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2155198092Srdivacky      // We have resolved the scope specifier to a particular declaration
2156198092Srdivacky      // contex, and will perform name lookup in that context.
2157207619Srdivacky      if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2158198092Srdivacky        return false;
2159193326Sed
2160199482Srdivacky      R.setContextRange(SS->getRange());
2161199482Srdivacky      return LookupQualifiedName(R, DC);
2162193326Sed    }
2163193326Sed
2164198092Srdivacky    // We could not resolve the scope specified to a specific declaration
2165198092Srdivacky    // context, which means that SS refers to an unknown specialization.
2166198092Srdivacky    // Name lookup can't find anything in this case.
2167234353Sdim    R.setNotFoundInCurrentInstantiation();
2168234353Sdim    R.setContextRange(SS->getRange());
2169198092Srdivacky    return false;
2170193326Sed  }
2171193326Sed
2172198092Srdivacky  // Perform unqualified name lookup starting in the given scope.
2173199482Srdivacky  return LookupName(R, S, AllowBuiltinCreation);
2174193326Sed}
2175193326Sed
2176280031Sdim/// \brief Perform qualified name lookup into all base classes of the given
2177280031Sdim/// class.
2178280031Sdim///
2179280031Sdim/// \param R captures both the lookup criteria and any lookup results found.
2180280031Sdim///
2181280031Sdim/// \param Class The context in which qualified name lookup will
2182280031Sdim/// search. Name lookup will search in all base classes merging the results.
2183280031Sdim///
2184280031Sdim/// @returns True if any decls were found (but possibly ambiguous)
2185280031Sdimbool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2186296417Sdim  // The access-control rules we use here are essentially the rules for
2187296417Sdim  // doing a lookup in Class that just magically skipped the direct
2188296417Sdim  // members of Class itself.  That is, the naming class is Class, and the
2189296417Sdim  // access includes the access of the base.
2190280031Sdim  for (const auto &BaseSpec : Class->bases()) {
2191280031Sdim    CXXRecordDecl *RD = cast<CXXRecordDecl>(
2192280031Sdim        BaseSpec.getType()->castAs<RecordType>()->getDecl());
2193280031Sdim    LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2194280031Sdim	Result.setBaseObjectType(Context.getRecordType(Class));
2195280031Sdim    LookupQualifiedName(Result, RD);
2196296417Sdim
2197296417Sdim    // Copy the lookup results into the target, merging the base's access into
2198296417Sdim    // the path access.
2199296417Sdim    for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2200296417Sdim      R.addDecl(I.getDecl(),
2201296417Sdim                CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2202296417Sdim                                           I.getAccess()));
2203296417Sdim    }
2204296417Sdim
2205296417Sdim    Result.suppressDiagnostics();
2206280031Sdim  }
2207193326Sed
2208280031Sdim  R.resolveKind();
2209296417Sdim  R.setNamingClass(Class);
2210280031Sdim
2211280031Sdim  return !R.empty();
2212280031Sdim}
2213280031Sdim
2214239462Sdim/// \brief Produce a diagnostic describing the ambiguity that resulted
2215193326Sed/// from name lookup.
2216193326Sed///
2217239462Sdim/// \param Result The result of the ambiguous lookup to be diagnosed.
2218261991Sdimvoid Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2219193326Sed  assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2220193326Sed
2221199482Srdivacky  DeclarationName Name = Result.getLookupName();
2222199482Srdivacky  SourceLocation NameLoc = Result.getNameLoc();
2223199482Srdivacky  SourceRange LookupRange = Result.getContextRange();
2224199482Srdivacky
2225198092Srdivacky  switch (Result.getAmbiguityKind()) {
2226198092Srdivacky  case LookupResult::AmbiguousBaseSubobjects: {
2227198092Srdivacky    CXXBasePaths *Paths = Result.getBasePaths();
2228198092Srdivacky    QualType SubobjectType = Paths->front().back().Base->getType();
2229198092Srdivacky    Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2230198092Srdivacky      << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2231198092Srdivacky      << LookupRange;
2232218893Sdim
2233249423Sdim    DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
2234198092Srdivacky    while (isa<CXXMethodDecl>(*Found) &&
2235198092Srdivacky           cast<CXXMethodDecl>(*Found)->isStatic())
2236198092Srdivacky      ++Found;
2237218893Sdim
2238198092Srdivacky    Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2239261991Sdim    break;
2240198092Srdivacky  }
2241193326Sed
2242198092Srdivacky  case LookupResult::AmbiguousBaseSubobjectTypes: {
2243193326Sed    Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2244193326Sed      << Name << LookupRange;
2245218893Sdim
2246198092Srdivacky    CXXBasePaths *Paths = Result.getBasePaths();
2247193326Sed    std::set<Decl *> DeclsPrinted;
2248198092Srdivacky    for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2249198092Srdivacky                                      PathEnd = Paths->end();
2250193326Sed         Path != PathEnd; ++Path) {
2251249423Sdim      Decl *D = Path->Decls.front();
2252193326Sed      if (DeclsPrinted.insert(D).second)
2253193326Sed        Diag(D->getLocation(), diag::note_ambiguous_member_found);
2254193326Sed    }
2255261991Sdim    break;
2256198092Srdivacky  }
2257193326Sed
2258198092Srdivacky  case LookupResult::AmbiguousTagHiding: {
2259198092Srdivacky    Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2260193326Sed
2261296417Sdim    llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2262198092Srdivacky
2263276479Sdim    for (auto *D : Result)
2264276479Sdim      if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2265198092Srdivacky        TagDecls.insert(TD);
2266198092Srdivacky        Diag(TD->getLocation(), diag::note_hidden_tag);
2267198092Srdivacky      }
2268198092Srdivacky
2269276479Sdim    for (auto *D : Result)
2270276479Sdim      if (!isa<TagDecl>(D))
2271276479Sdim        Diag(D->getLocation(), diag::note_hiding_object);
2272198092Srdivacky
2273198092Srdivacky    // For recovery purposes, go ahead and implement the hiding.
2274202879Srdivacky    LookupResult::Filter F = Result.makeFilter();
2275202879Srdivacky    while (F.hasNext()) {
2276202879Srdivacky      if (TagDecls.count(F.next()))
2277202879Srdivacky        F.erase();
2278202879Srdivacky    }
2279202879Srdivacky    F.done();
2280261991Sdim    break;
2281198092Srdivacky  }
2282198092Srdivacky
2283198092Srdivacky  case LookupResult::AmbiguousReference: {
2284198092Srdivacky    Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2285218893Sdim
2286276479Sdim    for (auto *D : Result)
2287276479Sdim      Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2288261991Sdim    break;
2289193326Sed  }
2290198092Srdivacky  }
2291193326Sed}
2292193326Sed
2293210299Sednamespace {
2294210299Sed  struct AssociatedLookup {
2295243830Sdim    AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2296210299Sed                     Sema::AssociatedNamespaceSet &Namespaces,
2297210299Sed                     Sema::AssociatedClassSet &Classes)
2298243830Sdim      : S(S), Namespaces(Namespaces), Classes(Classes),
2299243830Sdim        InstantiationLoc(InstantiationLoc) {
2300210299Sed    }
2301210299Sed
2302210299Sed    Sema &S;
2303210299Sed    Sema::AssociatedNamespaceSet &Namespaces;
2304210299Sed    Sema::AssociatedClassSet &Classes;
2305243830Sdim    SourceLocation InstantiationLoc;
2306210299Sed  };
2307296417Sdim} // end anonymous namespace
2308210299Sed
2309198092Srdivackystatic void
2310210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2311198092Srdivacky
2312207619Srdivackystatic void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2313207619Srdivacky                                      DeclContext *Ctx) {
2314207619Srdivacky  // Add the associated namespace for this class.
2315207619Srdivacky
2316207619Srdivacky  // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2317207619Srdivacky  // be a locally scoped record.
2318207619Srdivacky
2319212904Sdim  // We skip out of inline namespaces. The innermost non-inline namespace
2320212904Sdim  // contains all names of all its nested inline namespaces anyway, so we can
2321212904Sdim  // replace the entire inline namespace tree with its root.
2322212904Sdim  while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2323212904Sdim         Ctx->isInlineNamespace())
2324207619Srdivacky    Ctx = Ctx->getParent();
2325207619Srdivacky
2326198092Srdivacky  if (Ctx->isFileContext())
2327207619Srdivacky    Namespaces.insert(Ctx->getPrimaryContext());
2328198092Srdivacky}
2329198092Srdivacky
2330198092Srdivacky// \brief Add the associated classes and namespaces for argument-dependent
2331198092Srdivacky// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
2332198092Srdivackystatic void
2333210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2334210299Sed                                  const TemplateArgument &Arg) {
2335198092Srdivacky  // C++ [basic.lookup.koenig]p2, last bullet:
2336198092Srdivacky  //   -- [...] ;
2337198092Srdivacky  switch (Arg.getKind()) {
2338198092Srdivacky    case TemplateArgument::Null:
2339198092Srdivacky      break;
2340198092Srdivacky
2341198092Srdivacky    case TemplateArgument::Type:
2342198092Srdivacky      // [...] the namespaces and classes associated with the types of the
2343198092Srdivacky      // template arguments provided for template type parameters (excluding
2344198092Srdivacky      // template template parameters)
2345210299Sed      addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2346198092Srdivacky      break;
2347198092Srdivacky
2348218893Sdim    case TemplateArgument::Template:
2349218893Sdim    case TemplateArgument::TemplateExpansion: {
2350198092Srdivacky      // [...] the namespaces in which any template template arguments are
2351198092Srdivacky      // defined; and the classes in which any member templates used as
2352198092Srdivacky      // template template arguments are defined.
2353218893Sdim      TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2354198092Srdivacky      if (ClassTemplateDecl *ClassTemplate
2355199482Srdivacky                 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2356198092Srdivacky        DeclContext *Ctx = ClassTemplate->getDeclContext();
2357198092Srdivacky        if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2358210299Sed          Result.Classes.insert(EnclosingClass);
2359198092Srdivacky        // Add the associated namespace for this class.
2360210299Sed        CollectEnclosingNamespace(Result.Namespaces, Ctx);
2361198092Srdivacky      }
2362198092Srdivacky      break;
2363199482Srdivacky    }
2364218893Sdim
2365199482Srdivacky    case TemplateArgument::Declaration:
2366198092Srdivacky    case TemplateArgument::Integral:
2367198092Srdivacky    case TemplateArgument::Expression:
2368243830Sdim    case TemplateArgument::NullPtr:
2369198092Srdivacky      // [Note: non-type template arguments do not contribute to the set of
2370198092Srdivacky      //  associated namespaces. ]
2371198092Srdivacky      break;
2372198092Srdivacky
2373198092Srdivacky    case TemplateArgument::Pack:
2374276479Sdim      for (const auto &P : Arg.pack_elements())
2375276479Sdim        addAssociatedClassesAndNamespaces(Result, P);
2376198092Srdivacky      break;
2377198092Srdivacky  }
2378198092Srdivacky}
2379198092Srdivacky
2380193326Sed// \brief Add the associated classes and namespaces for
2381198092Srdivacky// argument-dependent lookup with an argument of class type
2382198092Srdivacky// (C++ [basic.lookup.koenig]p2).
2383198092Srdivackystatic void
2384210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2385210299Sed                                  CXXRecordDecl *Class) {
2386210299Sed
2387210299Sed  // Just silently ignore anything whose name is __va_list_tag.
2388210299Sed  if (Class->getDeclName() == Result.S.VAListTagName)
2389210299Sed    return;
2390210299Sed
2391193326Sed  // C++ [basic.lookup.koenig]p2:
2392193326Sed  //   [...]
2393193326Sed  //     -- If T is a class type (including unions), its associated
2394193326Sed  //        classes are: the class itself; the class of which it is a
2395193326Sed  //        member, if any; and its direct and indirect base
2396193326Sed  //        classes. Its associated namespaces are the namespaces in
2397198092Srdivacky  //        which its associated classes are defined.
2398193326Sed
2399193326Sed  // Add the class of which it is a member, if any.
2400193326Sed  DeclContext *Ctx = Class->getDeclContext();
2401193326Sed  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2402210299Sed    Result.Classes.insert(EnclosingClass);
2403193326Sed  // Add the associated namespace for this class.
2404210299Sed  CollectEnclosingNamespace(Result.Namespaces, Ctx);
2405198092Srdivacky
2406193326Sed  // Add the class itself. If we've already seen this class, we don't
2407193326Sed  // need to visit base classes.
2408276479Sdim  //
2409276479Sdim  // FIXME: That's not correct, we may have added this class only because it
2410276479Sdim  // was the enclosing class of another class, and in that case we won't have
2411276479Sdim  // added its base classes yet.
2412280031Sdim  if (!Result.Classes.insert(Class).second)
2413193326Sed    return;
2414193326Sed
2415198092Srdivacky  // -- If T is a template-id, its associated namespaces and classes are
2416198092Srdivacky  //    the namespace in which the template is defined; for member
2417218893Sdim  //    templates, the member template's class; the namespaces and classes
2418198092Srdivacky  //    associated with the types of the template arguments provided for
2419198092Srdivacky  //    template type parameters (excluding template template parameters); the
2420198092Srdivacky  //    namespaces in which any template template arguments are defined; and
2421198092Srdivacky  //    the classes in which any member templates used as template template
2422198092Srdivacky  //    arguments are defined. [Note: non-type template arguments do not
2423198092Srdivacky  //    contribute to the set of associated namespaces. ]
2424198092Srdivacky  if (ClassTemplateSpecializationDecl *Spec
2425198092Srdivacky        = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2426198092Srdivacky    DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2427198092Srdivacky    if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2428210299Sed      Result.Classes.insert(EnclosingClass);
2429198092Srdivacky    // Add the associated namespace for this class.
2430210299Sed    CollectEnclosingNamespace(Result.Namespaces, Ctx);
2431193326Sed
2432198092Srdivacky    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2433198092Srdivacky    for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2434210299Sed      addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2435198092Srdivacky  }
2436198092Srdivacky
2437203955Srdivacky  // Only recurse into base classes for complete types.
2438296417Sdim  if (!Result.S.isCompleteType(Result.InstantiationLoc,
2439296417Sdim                               Result.S.Context.getRecordType(Class)))
2440276479Sdim    return;
2441203955Srdivacky
2442193326Sed  // Add direct and indirect base classes along with their associated
2443193326Sed  // namespaces.
2444226633Sdim  SmallVector<CXXRecordDecl *, 32> Bases;
2445193326Sed  Bases.push_back(Class);
2446193326Sed  while (!Bases.empty()) {
2447193326Sed    // Pop this class off the stack.
2448261991Sdim    Class = Bases.pop_back_val();
2449193326Sed
2450193326Sed    // Visit the base classes.
2451276479Sdim    for (const auto &Base : Class->bases()) {
2452276479Sdim      const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2453198893Srdivacky      // In dependent contexts, we do ADL twice, and the first time around,
2454198893Srdivacky      // the base type might be a dependent TemplateSpecializationType, or a
2455198893Srdivacky      // TemplateTypeParmType. If that happens, simply ignore it.
2456198893Srdivacky      // FIXME: If we want to support export, we probably need to add the
2457198893Srdivacky      // namespace of the template in a TemplateSpecializationType, or even
2458198893Srdivacky      // the classes and namespaces of known non-dependent arguments.
2459198893Srdivacky      if (!BaseType)
2460198893Srdivacky        continue;
2461193326Sed      CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2462280031Sdim      if (Result.Classes.insert(BaseDecl).second) {
2463193326Sed        // Find the associated namespace for this base class.
2464193326Sed        DeclContext *BaseCtx = BaseDecl->getDeclContext();
2465210299Sed        CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2466193326Sed
2467193326Sed        // Make sure we visit the bases of this base class.
2468193326Sed        if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2469193326Sed          Bases.push_back(BaseDecl);
2470193326Sed      }
2471193326Sed    }
2472193326Sed  }
2473193326Sed}
2474193326Sed
2475193326Sed// \brief Add the associated classes and namespaces for
2476193326Sed// argument-dependent lookup with an argument of type T
2477198092Srdivacky// (C++ [basic.lookup.koenig]p2).
2478198092Srdivackystatic void
2479210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2480193326Sed  // C++ [basic.lookup.koenig]p2:
2481193326Sed  //
2482193326Sed  //   For each argument type T in the function call, there is a set
2483193326Sed  //   of zero or more associated namespaces and a set of zero or more
2484193326Sed  //   associated classes to be considered. The sets of namespaces and
2485193326Sed  //   classes is determined entirely by the types of the function
2486193326Sed  //   arguments (and the namespace of any template template
2487193326Sed  //   argument). Typedef names and using-declarations used to specify
2488193326Sed  //   the types do not contribute to this set. The sets of namespaces
2489193326Sed  //   and classes are determined in the following way:
2490193326Sed
2491226633Sdim  SmallVector<const Type *, 16> Queue;
2492210299Sed  const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2493210299Sed
2494193326Sed  while (true) {
2495210299Sed    switch (T->getTypeClass()) {
2496210299Sed
2497210299Sed#define TYPE(Class, Base)
2498210299Sed#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2499210299Sed#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2500210299Sed#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2501210299Sed#define ABSTRACT_TYPE(Class, Base)
2502210299Sed#include "clang/AST/TypeNodes.def"
2503210299Sed      // T is canonical.  We can also ignore dependent types because
2504210299Sed      // we don't need to do ADL at the definition point, but if we
2505210299Sed      // wanted to implement template export (or if we find some other
2506210299Sed      // use for associated classes and namespaces...) this would be
2507210299Sed      // wrong.
2508193326Sed      break;
2509193326Sed
2510210299Sed    //    -- If T is a pointer to U or an array of U, its associated
2511210299Sed    //       namespaces and classes are those associated with U.
2512210299Sed    case Type::Pointer:
2513210299Sed      T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2514210299Sed      continue;
2515210299Sed    case Type::ConstantArray:
2516210299Sed    case Type::IncompleteArray:
2517210299Sed    case Type::VariableArray:
2518210299Sed      T = cast<ArrayType>(T)->getElementType().getTypePtr();
2519210299Sed      continue;
2520193326Sed
2521210299Sed    //     -- If T is a fundamental type, its associated sets of
2522210299Sed    //        namespaces and classes are both empty.
2523210299Sed    case Type::Builtin:
2524210299Sed      break;
2525210299Sed
2526210299Sed    //     -- If T is a class type (including unions), its associated
2527210299Sed    //        classes are: the class itself; the class of which it is a
2528210299Sed    //        member, if any; and its direct and indirect base
2529210299Sed    //        classes. Its associated namespaces are the namespaces in
2530210299Sed    //        which its associated classes are defined.
2531210299Sed    case Type::Record: {
2532296417Sdim      CXXRecordDecl *Class =
2533296417Sdim          cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2534210299Sed      addAssociatedClassesAndNamespaces(Result, Class);
2535210299Sed      break;
2536193326Sed    }
2537193326Sed
2538210299Sed    //     -- If T is an enumeration type, its associated namespace is
2539210299Sed    //        the namespace in which it is defined. If it is class
2540218893Sdim    //        member, its associated class is the member's class; else
2541210299Sed    //        it has no associated class.
2542210299Sed    case Type::Enum: {
2543210299Sed      EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2544193326Sed
2545210299Sed      DeclContext *Ctx = Enum->getDeclContext();
2546210299Sed      if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2547210299Sed        Result.Classes.insert(EnclosingClass);
2548193326Sed
2549210299Sed      // Add the associated namespace for this class.
2550210299Sed      CollectEnclosingNamespace(Result.Namespaces, Ctx);
2551193326Sed
2552210299Sed      break;
2553210299Sed    }
2554193326Sed
2555210299Sed    //     -- If T is a function type, its associated namespaces and
2556210299Sed    //        classes are those associated with the function parameter
2557210299Sed    //        types and those associated with the return type.
2558210299Sed    case Type::FunctionProto: {
2559210299Sed      const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2560276479Sdim      for (const auto &Arg : Proto->param_types())
2561276479Sdim        Queue.push_back(Arg.getTypePtr());
2562210299Sed      // fallthrough
2563210299Sed    }
2564210299Sed    case Type::FunctionNoProto: {
2565210299Sed      const FunctionType *FnType = cast<FunctionType>(T);
2566276479Sdim      T = FnType->getReturnType().getTypePtr();
2567210299Sed      continue;
2568210299Sed    }
2569193326Sed
2570210299Sed    //     -- If T is a pointer to a member function of a class X, its
2571210299Sed    //        associated namespaces and classes are those associated
2572210299Sed    //        with the function parameter types and return type,
2573210299Sed    //        together with those associated with X.
2574210299Sed    //
2575210299Sed    //     -- If T is a pointer to a data member of class X, its
2576210299Sed    //        associated namespaces and classes are those associated
2577210299Sed    //        with the member type together with those associated with
2578210299Sed    //        X.
2579210299Sed    case Type::MemberPointer: {
2580210299Sed      const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2581193326Sed
2582210299Sed      // Queue up the class type into which this points.
2583210299Sed      Queue.push_back(MemberPtr->getClass());
2584198092Srdivacky
2585210299Sed      // And directly continue with the pointee type.
2586210299Sed      T = MemberPtr->getPointeeType().getTypePtr();
2587210299Sed      continue;
2588210299Sed    }
2589193326Sed
2590210299Sed    // As an extension, treat this like a normal pointer.
2591210299Sed    case Type::BlockPointer:
2592210299Sed      T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2593210299Sed      continue;
2594193326Sed
2595210299Sed    // References aren't covered by the standard, but that's such an
2596210299Sed    // obvious defect that we cover them anyway.
2597210299Sed    case Type::LValueReference:
2598210299Sed    case Type::RValueReference:
2599210299Sed      T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2600210299Sed      continue;
2601193326Sed
2602210299Sed    // These are fundamental types.
2603210299Sed    case Type::Vector:
2604210299Sed    case Type::ExtVector:
2605210299Sed    case Type::Complex:
2606210299Sed      break;
2607210299Sed
2608251662Sdim    // Non-deduced auto types only get here for error cases.
2609251662Sdim    case Type::Auto:
2610251662Sdim      break;
2611251662Sdim
2612221345Sdim    // If T is an Objective-C object or interface type, or a pointer to an
2613221345Sdim    // object or interface type, the associated namespace is the global
2614221345Sdim    // namespace.
2615210299Sed    case Type::ObjCObject:
2616210299Sed    case Type::ObjCInterface:
2617210299Sed    case Type::ObjCObjectPointer:
2618221345Sdim      Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2619210299Sed      break;
2620226633Sdim
2621226633Sdim    // Atomic types are just wrappers; use the associations of the
2622226633Sdim    // contained type.
2623226633Sdim    case Type::Atomic:
2624226633Sdim      T = cast<AtomicType>(T)->getValueType().getTypePtr();
2625226633Sdim      continue;
2626296417Sdim    case Type::Pipe:
2627296417Sdim      T = cast<PipeType>(T)->getElementType().getTypePtr();
2628296417Sdim      continue;
2629210299Sed    }
2630210299Sed
2631261991Sdim    if (Queue.empty())
2632261991Sdim      break;
2633261991Sdim    T = Queue.pop_back_val();
2634193326Sed  }
2635193326Sed}
2636193326Sed
2637193326Sed/// \brief Find the associated classes and namespaces for
2638193326Sed/// argument-dependent lookup for a call with the given set of
2639193326Sed/// arguments.
2640193326Sed///
2641193326Sed/// This routine computes the sets of associated classes and associated
2642198092Srdivacky/// namespaces searched by argument-dependent lookup
2643193326Sed/// (C++ [basic.lookup.argdep]) for a given set of arguments.
2644261991Sdimvoid Sema::FindAssociatedClassesAndNamespaces(
2645261991Sdim    SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2646261991Sdim    AssociatedNamespaceSet &AssociatedNamespaces,
2647261991Sdim    AssociatedClassSet &AssociatedClasses) {
2648193326Sed  AssociatedNamespaces.clear();
2649193326Sed  AssociatedClasses.clear();
2650193326Sed
2651243830Sdim  AssociatedLookup Result(*this, InstantiationLoc,
2652243830Sdim                          AssociatedNamespaces, AssociatedClasses);
2653210299Sed
2654193326Sed  // C++ [basic.lookup.koenig]p2:
2655193326Sed  //   For each argument type T in the function call, there is a set
2656193326Sed  //   of zero or more associated namespaces and a set of zero or more
2657193326Sed  //   associated classes to be considered. The sets of namespaces and
2658193326Sed  //   classes is determined entirely by the types of the function
2659193326Sed  //   arguments (and the namespace of any template template
2660198092Srdivacky  //   argument).
2661234353Sdim  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2662193326Sed    Expr *Arg = Args[ArgIdx];
2663193326Sed
2664193326Sed    if (Arg->getType() != Context.OverloadTy) {
2665210299Sed      addAssociatedClassesAndNamespaces(Result, Arg->getType());
2666193326Sed      continue;
2667193326Sed    }
2668193326Sed
2669193326Sed    // [...] In addition, if the argument is the name or address of a
2670193326Sed    // set of overloaded functions and/or function templates, its
2671193326Sed    // associated classes and namespaces are the union of those
2672193326Sed    // associated with each of the members of the set: the namespace
2673193326Sed    // in which the function or function template is defined and the
2674193326Sed    // classes and namespaces associated with its (non-dependent)
2675193326Sed    // parameter types and return type.
2676198092Srdivacky    Arg = Arg->IgnoreParens();
2677199990Srdivacky    if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2678212904Sdim      if (unaryOp->getOpcode() == UO_AddrOf)
2679199990Srdivacky        Arg = unaryOp->getSubExpr();
2680193326Sed
2681210299Sed    UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2682210299Sed    if (!ULE) continue;
2683199990Srdivacky
2684276479Sdim    for (const auto *D : ULE->decls()) {
2685201361Srdivacky      // Look through any using declarations to find the underlying function.
2686276479Sdim      const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
2687201361Srdivacky
2688193326Sed      // Add the classes and namespaces associated with the parameter
2689193326Sed      // types and return type of this function.
2690210299Sed      addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2691193326Sed    }
2692193326Sed  }
2693193326Sed}
2694193326Sed
2695199482SrdivackyNamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2696207619Srdivacky                                  SourceLocation Loc,
2697199482Srdivacky                                  LookupNameKind NameKind,
2698199482Srdivacky                                  RedeclarationKind Redecl) {
2699207619Srdivacky  LookupResult R(*this, Name, Loc, NameKind, Redecl);
2700199482Srdivacky  LookupName(R, S);
2701200583Srdivacky  return R.getAsSingle<NamedDecl>();
2702199482Srdivacky}
2703199482Srdivacky
2704193326Sed/// \brief Find the protocol with the given name, if any.
2705218893SdimObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2706234353Sdim                                       SourceLocation IdLoc,
2707234353Sdim                                       RedeclarationKind Redecl) {
2708207619Srdivacky  Decl *D = LookupSingleName(TUScope, II, IdLoc,
2709234353Sdim                             LookupObjCProtocolName, Redecl);
2710193326Sed  return cast_or_null<ObjCProtocolDecl>(D);
2711193326Sed}
2712193326Sed
2713193326Sedvoid Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2714198092Srdivacky                                        QualType T1, QualType T2,
2715203955Srdivacky                                        UnresolvedSetImpl &Functions) {
2716193326Sed  // C++ [over.match.oper]p3:
2717193326Sed  //     -- The set of non-member candidates is the result of the
2718193326Sed  //        unqualified lookup of operator@ in the context of the
2719193326Sed  //        expression according to the usual rules for name lookup in
2720193326Sed  //        unqualified function calls (3.4.2) except that all member
2721276479Sdim  //        functions are ignored.
2722193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2723199482Srdivacky  LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2724199482Srdivacky  LookupName(Operators, S);
2725198092Srdivacky
2726193326Sed  assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2727276479Sdim  Functions.append(Operators.begin(), Operators.end());
2728193326Sed}
2729193326Sed
2730224145SdimSema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2731223017Sdim                                                            CXXSpecialMember SM,
2732223017Sdim                                                            bool ConstArg,
2733223017Sdim                                                            bool VolatileArg,
2734223017Sdim                                                            bool RValueThis,
2735223017Sdim                                                            bool ConstThis,
2736223017Sdim                                                            bool VolatileThis) {
2737249423Sdim  assert(CanDeclareSpecialMemberFunction(RD) &&
2738249423Sdim         "doing special member lookup into record that isn't fully complete");
2739224145Sdim  RD = RD->getDefinition();
2740223017Sdim  if (RValueThis || ConstThis || VolatileThis)
2741223017Sdim    assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2742223017Sdim           "constructors and destructors always have unqualified lvalue this");
2743223017Sdim  if (ConstArg || VolatileArg)
2744223017Sdim    assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2745223017Sdim           "parameter-less special members can't have qualified arguments");
2746223017Sdim
2747223017Sdim  llvm::FoldingSetNodeID ID;
2748224145Sdim  ID.AddPointer(RD);
2749223017Sdim  ID.AddInteger(SM);
2750223017Sdim  ID.AddInteger(ConstArg);
2751223017Sdim  ID.AddInteger(VolatileArg);
2752223017Sdim  ID.AddInteger(RValueThis);
2753223017Sdim  ID.AddInteger(ConstThis);
2754223017Sdim  ID.AddInteger(VolatileThis);
2755223017Sdim
2756223017Sdim  void *InsertPoint;
2757223017Sdim  SpecialMemberOverloadResult *Result =
2758223017Sdim    SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2759223017Sdim
2760223017Sdim  // This was already cached
2761223017Sdim  if (Result)
2762223017Sdim    return Result;
2763223017Sdim
2764223017Sdim  Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2765223017Sdim  Result = new (Result) SpecialMemberOverloadResult(ID);
2766223017Sdim  SpecialMemberCache.InsertNode(Result, InsertPoint);
2767223017Sdim
2768223017Sdim  if (SM == CXXDestructor) {
2769249423Sdim    if (RD->needsImplicitDestructor())
2770224145Sdim      DeclareImplicitDestructor(RD);
2771224145Sdim    CXXDestructorDecl *DD = RD->getDestructor();
2772223017Sdim    assert(DD && "record without a destructor");
2773223017Sdim    Result->setMethod(DD);
2774234353Sdim    Result->setKind(DD->isDeleted() ?
2775234353Sdim                    SpecialMemberOverloadResult::NoMemberOrDeleted :
2776235864Sdim                    SpecialMemberOverloadResult::Success);
2777223017Sdim    return Result;
2778223017Sdim  }
2779223017Sdim
2780223017Sdim  // Prepare for overload resolution. Here we construct a synthetic argument
2781223017Sdim  // if necessary and make sure that implicit functions are declared.
2782224145Sdim  CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2783223017Sdim  DeclarationName Name;
2784276479Sdim  Expr *Arg = nullptr;
2785223017Sdim  unsigned NumArgs;
2786223017Sdim
2787235864Sdim  QualType ArgType = CanTy;
2788235864Sdim  ExprValueKind VK = VK_LValue;
2789235864Sdim
2790223017Sdim  if (SM == CXXDefaultConstructor) {
2791223017Sdim    Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2792223017Sdim    NumArgs = 0;
2793224145Sdim    if (RD->needsImplicitDefaultConstructor())
2794224145Sdim      DeclareImplicitDefaultConstructor(RD);
2795223017Sdim  } else {
2796223017Sdim    if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2797223017Sdim      Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2798249423Sdim      if (RD->needsImplicitCopyConstructor())
2799224145Sdim        DeclareImplicitCopyConstructor(RD);
2800249423Sdim      if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
2801226633Sdim        DeclareImplicitMoveConstructor(RD);
2802223017Sdim    } else {
2803223017Sdim      Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2804249423Sdim      if (RD->needsImplicitCopyAssignment())
2805224145Sdim        DeclareImplicitCopyAssignment(RD);
2806249423Sdim      if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
2807226633Sdim        DeclareImplicitMoveAssignment(RD);
2808223017Sdim    }
2809223017Sdim
2810223017Sdim    if (ConstArg)
2811223017Sdim      ArgType.addConst();
2812223017Sdim    if (VolatileArg)
2813223017Sdim      ArgType.addVolatile();
2814223017Sdim
2815223017Sdim    // This isn't /really/ specified by the standard, but it's implied
2816223017Sdim    // we should be working from an RValue in the case of move to ensure
2817223017Sdim    // that we prefer to bind to rvalue references, and an LValue in the
2818223017Sdim    // case of copy to ensure we don't bind to rvalue references.
2819223017Sdim    // Possibly an XValue is actually correct in the case of move, but
2820223017Sdim    // there is no semantic difference for class types in this restricted
2821223017Sdim    // case.
2822224145Sdim    if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2823223017Sdim      VK = VK_LValue;
2824223017Sdim    else
2825223017Sdim      VK = VK_RValue;
2826235864Sdim  }
2827223017Sdim
2828235864Sdim  OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2829235864Sdim
2830235864Sdim  if (SM != CXXDefaultConstructor) {
2831223017Sdim    NumArgs = 1;
2832235864Sdim    Arg = &FakeArg;
2833223017Sdim  }
2834223017Sdim
2835223017Sdim  // Create the object argument
2836223017Sdim  QualType ThisTy = CanTy;
2837223017Sdim  if (ConstThis)
2838223017Sdim    ThisTy.addConst();
2839223017Sdim  if (VolatileThis)
2840223017Sdim    ThisTy.addVolatile();
2841224145Sdim  Expr::Classification Classification =
2842235864Sdim    OpaqueValueExpr(SourceLocation(), ThisTy,
2843235864Sdim                    RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2844223017Sdim
2845223017Sdim  // Now we perform lookup on the name we computed earlier and do overload
2846223017Sdim  // resolution. Lookup is only performed directly into the class since there
2847223017Sdim  // will always be a (possibly implicit) declaration to shadow any others.
2848276479Sdim  OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
2849249423Sdim  DeclContext::lookup_result R = RD->lookup(Name);
2850224145Sdim
2851280031Sdim  if (R.empty()) {
2852280031Sdim    // We might have no default constructor because we have a lambda's closure
2853280031Sdim    // type, rather than because there's some other declared constructor.
2854280031Sdim    // Every class has a copy/move constructor, copy/move assignment, and
2855280031Sdim    // destructor.
2856280031Sdim    assert(SM == CXXDefaultConstructor &&
2857280031Sdim           "lookup for a constructor or assignment operator was empty");
2858280031Sdim    Result->setMethod(nullptr);
2859280031Sdim    Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2860280031Sdim    return Result;
2861280031Sdim  }
2862280031Sdim
2863261991Sdim  // Copy the candidates as our processing of them may load new declarations
2864261991Sdim  // from an external source and invalidate lookup_result.
2865261991Sdim  SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2866261991Sdim
2867276479Sdim  for (auto *Cand : Candidates) {
2868224145Sdim    if (Cand->isInvalidDecl())
2869223017Sdim      continue;
2870223017Sdim
2871224145Sdim    if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2872224145Sdim      // FIXME: [namespace.udecl]p15 says that we should only consider a
2873224145Sdim      // using declaration here if it does not match a declaration in the
2874224145Sdim      // derived class. We do not implement this correctly in other cases
2875224145Sdim      // either.
2876224145Sdim      Cand = U->getTargetDecl();
2877223017Sdim
2878224145Sdim      if (Cand->isInvalidDecl())
2879224145Sdim        continue;
2880224145Sdim    }
2881224145Sdim
2882224145Sdim    if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2883224145Sdim      if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2884224145Sdim        AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2885234353Sdim                           Classification, llvm::makeArrayRef(&Arg, NumArgs),
2886234353Sdim                           OCS, true);
2887224145Sdim      else
2888234353Sdim        AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2889234353Sdim                             llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2890224145Sdim    } else if (FunctionTemplateDecl *Tmpl =
2891224145Sdim                 dyn_cast<FunctionTemplateDecl>(Cand)) {
2892224145Sdim      if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2893224145Sdim        AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2894276479Sdim                                   RD, nullptr, ThisTy, Classification,
2895234353Sdim                                   llvm::makeArrayRef(&Arg, NumArgs),
2896224145Sdim                                   OCS, true);
2897224145Sdim      else
2898224145Sdim        AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2899276479Sdim                                     nullptr, llvm::makeArrayRef(&Arg, NumArgs),
2900234353Sdim                                     OCS, true);
2901223017Sdim    } else {
2902224145Sdim      assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2903223017Sdim    }
2904223017Sdim  }
2905223017Sdim
2906223017Sdim  OverloadCandidateSet::iterator Best;
2907223017Sdim  switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2908223017Sdim    case OR_Success:
2909223017Sdim      Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2910235864Sdim      Result->setKind(SpecialMemberOverloadResult::Success);
2911223017Sdim      break;
2912223017Sdim
2913223017Sdim    case OR_Deleted:
2914223017Sdim      Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2915234353Sdim      Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2916223017Sdim      break;
2917223017Sdim
2918223017Sdim    case OR_Ambiguous:
2919276479Sdim      Result->setMethod(nullptr);
2920234353Sdim      Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2921234353Sdim      break;
2922234353Sdim
2923223017Sdim    case OR_No_Viable_Function:
2924276479Sdim      Result->setMethod(nullptr);
2925234353Sdim      Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2926223017Sdim      break;
2927223017Sdim  }
2928223017Sdim
2929223017Sdim  return Result;
2930223017Sdim}
2931223017Sdim
2932223017Sdim/// \brief Look up the default constructor for the given class.
2933223017SdimCXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2934223017Sdim  SpecialMemberOverloadResult *Result =
2935223017Sdim    LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2936223017Sdim                        false, false);
2937223017Sdim
2938223017Sdim  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2939223017Sdim}
2940223017Sdim
2941224145Sdim/// \brief Look up the copying constructor for the given class.
2942224145SdimCXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2943235864Sdim                                                   unsigned Quals) {
2944223017Sdim  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2945223017Sdim         "non-const, non-volatile qualifiers for copy ctor arg");
2946223017Sdim  SpecialMemberOverloadResult *Result =
2947223017Sdim    LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2948223017Sdim                        Quals & Qualifiers::Volatile, false, false, false);
2949223017Sdim
2950223017Sdim  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2951223017Sdim}
2952223017Sdim
2953226633Sdim/// \brief Look up the moving constructor for the given class.
2954239462SdimCXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2955239462Sdim                                                  unsigned Quals) {
2956226633Sdim  SpecialMemberOverloadResult *Result =
2957239462Sdim    LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2958239462Sdim                        Quals & Qualifiers::Volatile, false, false, false);
2959226633Sdim
2960226633Sdim  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2961226633Sdim}
2962226633Sdim
2963210299Sed/// \brief Look up the constructors for the given class.
2964210299SedDeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2965223017Sdim  // If the implicit constructors have not yet been declared, do so now.
2966249423Sdim  if (CanDeclareSpecialMemberFunction(Class)) {
2967223017Sdim    if (Class->needsImplicitDefaultConstructor())
2968210299Sed      DeclareImplicitDefaultConstructor(Class);
2969249423Sdim    if (Class->needsImplicitCopyConstructor())
2970210299Sed      DeclareImplicitCopyConstructor(Class);
2971249423Sdim    if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
2972226633Sdim      DeclareImplicitMoveConstructor(Class);
2973210299Sed  }
2974218893Sdim
2975210299Sed  CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2976210299Sed  DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2977210299Sed  return Class->lookup(Name);
2978210299Sed}
2979210299Sed
2980224145Sdim/// \brief Look up the copying assignment operator for the given class.
2981224145SdimCXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2982224145Sdim                                             unsigned Quals, bool RValueThis,
2983235864Sdim                                             unsigned ThisQuals) {
2984224145Sdim  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2985224145Sdim         "non-const, non-volatile qualifiers for copy assignment arg");
2986224145Sdim  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2987224145Sdim         "non-const, non-volatile qualifiers for copy assignment this");
2988224145Sdim  SpecialMemberOverloadResult *Result =
2989224145Sdim    LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2990224145Sdim                        Quals & Qualifiers::Volatile, RValueThis,
2991224145Sdim                        ThisQuals & Qualifiers::Const,
2992224145Sdim                        ThisQuals & Qualifiers::Volatile);
2993224145Sdim
2994224145Sdim  return Result->getMethod();
2995224145Sdim}
2996224145Sdim
2997226633Sdim/// \brief Look up the moving assignment operator for the given class.
2998226633SdimCXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2999239462Sdim                                            unsigned Quals,
3000226633Sdim                                            bool RValueThis,
3001226633Sdim                                            unsigned ThisQuals) {
3002226633Sdim  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3003226633Sdim         "non-const, non-volatile qualifiers for copy assignment this");
3004226633Sdim  SpecialMemberOverloadResult *Result =
3005239462Sdim    LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3006239462Sdim                        Quals & Qualifiers::Volatile, RValueThis,
3007226633Sdim                        ThisQuals & Qualifiers::Const,
3008226633Sdim                        ThisQuals & Qualifiers::Volatile);
3009226633Sdim
3010226633Sdim  return Result->getMethod();
3011226633Sdim}
3012226633Sdim
3013210299Sed/// \brief Look for the destructor of the given class.
3014210299Sed///
3015218893Sdim/// During semantic analysis, this routine should be used in lieu of
3016210299Sed/// CXXRecordDecl::getDestructor().
3017210299Sed///
3018210299Sed/// \returns The destructor for this class.
3019210299SedCXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3020223017Sdim  return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3021223017Sdim                                                     false, false, false,
3022223017Sdim                                                     false, false)->getMethod());
3023210299Sed}
3024210299Sed
3025234353Sdim/// LookupLiteralOperator - Determine which literal operator should be used for
3026234353Sdim/// a user-defined literal, per C++11 [lex.ext].
3027234353Sdim///
3028234353Sdim/// Normal overload resolution is not used to select which literal operator to
3029234353Sdim/// call for a user-defined literal. Look up the provided literal operator name,
3030234353Sdim/// and filter the results to the appropriate set for the given argument types.
3031234353SdimSema::LiteralOperatorLookupResult
3032234353SdimSema::LookupLiteralOperator(Scope *S, LookupResult &R,
3033234353Sdim                            ArrayRef<QualType> ArgTys,
3034261991Sdim                            bool AllowRaw, bool AllowTemplate,
3035261991Sdim                            bool AllowStringTemplate) {
3036234353Sdim  LookupName(R, S);
3037234353Sdim  assert(R.getResultKind() != LookupResult::Ambiguous &&
3038234353Sdim         "literal operator lookup can't be ambiguous");
3039234353Sdim
3040234353Sdim  // Filter the lookup results appropriately.
3041234353Sdim  LookupResult::Filter F = R.makeFilter();
3042234353Sdim
3043261991Sdim  bool FoundRaw = false;
3044234353Sdim  bool FoundTemplate = false;
3045261991Sdim  bool FoundStringTemplate = false;
3046234353Sdim  bool FoundExactMatch = false;
3047234353Sdim
3048234353Sdim  while (F.hasNext()) {
3049234353Sdim    Decl *D = F.next();
3050234353Sdim    if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3051234353Sdim      D = USD->getTargetDecl();
3052234353Sdim
3053251662Sdim    // If the declaration we found is invalid, skip it.
3054251662Sdim    if (D->isInvalidDecl()) {
3055251662Sdim      F.erase();
3056251662Sdim      continue;
3057251662Sdim    }
3058251662Sdim
3059261991Sdim    bool IsRaw = false;
3060261991Sdim    bool IsTemplate = false;
3061261991Sdim    bool IsStringTemplate = false;
3062261991Sdim    bool IsExactMatch = false;
3063261991Sdim
3064234353Sdim    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3065234353Sdim      if (FD->getNumParams() == 1 &&
3066234353Sdim          FD->getParamDecl(0)->getType()->getAs<PointerType>())
3067234353Sdim        IsRaw = true;
3068249423Sdim      else if (FD->getNumParams() == ArgTys.size()) {
3069234353Sdim        IsExactMatch = true;
3070234353Sdim        for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3071234353Sdim          QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3072234353Sdim          if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3073234353Sdim            IsExactMatch = false;
3074234353Sdim            break;
3075234353Sdim          }
3076234353Sdim        }
3077234353Sdim      }
3078234353Sdim    }
3079261991Sdim    if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3080261991Sdim      TemplateParameterList *Params = FD->getTemplateParameters();
3081261991Sdim      if (Params->size() == 1)
3082261991Sdim        IsTemplate = true;
3083261991Sdim      else
3084261991Sdim        IsStringTemplate = true;
3085261991Sdim    }
3086234353Sdim
3087234353Sdim    if (IsExactMatch) {
3088234353Sdim      FoundExactMatch = true;
3089261991Sdim      AllowRaw = false;
3090261991Sdim      AllowTemplate = false;
3091261991Sdim      AllowStringTemplate = false;
3092261991Sdim      if (FoundRaw || FoundTemplate || FoundStringTemplate) {
3093234353Sdim        // Go through again and remove the raw and template decls we've
3094234353Sdim        // already found.
3095234353Sdim        F.restart();
3096261991Sdim        FoundRaw = FoundTemplate = FoundStringTemplate = false;
3097234353Sdim      }
3098261991Sdim    } else if (AllowRaw && IsRaw) {
3099261991Sdim      FoundRaw = true;
3100261991Sdim    } else if (AllowTemplate && IsTemplate) {
3101261991Sdim      FoundTemplate = true;
3102261991Sdim    } else if (AllowStringTemplate && IsStringTemplate) {
3103261991Sdim      FoundStringTemplate = true;
3104234353Sdim    } else {
3105234353Sdim      F.erase();
3106234353Sdim    }
3107234353Sdim  }
3108234353Sdim
3109234353Sdim  F.done();
3110234353Sdim
3111234353Sdim  // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3112234353Sdim  // parameter type, that is used in preference to a raw literal operator
3113234353Sdim  // or literal operator template.
3114234353Sdim  if (FoundExactMatch)
3115234353Sdim    return LOLR_Cooked;
3116234353Sdim
3117234353Sdim  // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3118234353Sdim  // operator template, but not both.
3119234353Sdim  if (FoundRaw && FoundTemplate) {
3120234353Sdim    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3121276479Sdim    for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3122276479Sdim      NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
3123234353Sdim    return LOLR_Error;
3124234353Sdim  }
3125234353Sdim
3126234353Sdim  if (FoundRaw)
3127234353Sdim    return LOLR_Raw;
3128234353Sdim
3129234353Sdim  if (FoundTemplate)
3130234353Sdim    return LOLR_Template;
3131234353Sdim
3132261991Sdim  if (FoundStringTemplate)
3133261991Sdim    return LOLR_StringTemplate;
3134261991Sdim
3135234353Sdim  // Didn't find anything we could use.
3136234353Sdim  Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3137234353Sdim    << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3138261991Sdim    << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3139261991Sdim    << (AllowTemplate || AllowStringTemplate);
3140234353Sdim  return LOLR_Error;
3141234353Sdim}
3142234353Sdim
3143203955Srdivackyvoid ADLResult::insert(NamedDecl *New) {
3144203955Srdivacky  NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3145203955Srdivacky
3146203955Srdivacky  // If we haven't yet seen a decl for this key, or the last decl
3147203955Srdivacky  // was exactly this one, we're done.
3148276479Sdim  if (Old == nullptr || Old == New) {
3149203955Srdivacky    Old = New;
3150203955Srdivacky    return;
3151203955Srdivacky  }
3152203955Srdivacky
3153203955Srdivacky  // Otherwise, decide which is a more recent redeclaration.
3154276479Sdim  FunctionDecl *OldFD = Old->getAsFunction();
3155276479Sdim  FunctionDecl *NewFD = New->getAsFunction();
3156203955Srdivacky
3157203955Srdivacky  FunctionDecl *Cursor = NewFD;
3158203955Srdivacky  while (true) {
3159234353Sdim    Cursor = Cursor->getPreviousDecl();
3160203955Srdivacky
3161203955Srdivacky    // If we got to the end without finding OldFD, OldFD is the newer
3162203955Srdivacky    // declaration;  leave things as they are.
3163203955Srdivacky    if (!Cursor) return;
3164203955Srdivacky
3165203955Srdivacky    // If we do find OldFD, then NewFD is newer.
3166203955Srdivacky    if (Cursor == OldFD) break;
3167203955Srdivacky
3168203955Srdivacky    // Otherwise, keep looking.
3169203955Srdivacky  }
3170203955Srdivacky
3171203955Srdivacky  Old = New;
3172198092Srdivacky}
3173198092Srdivacky
3174276479Sdimvoid Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3175276479Sdim                                   ArrayRef<Expr *> Args, ADLResult &Result) {
3176193326Sed  // Find all of the associated namespaces and classes based on the
3177193326Sed  // arguments we have.
3178193326Sed  AssociatedNamespaceSet AssociatedNamespaces;
3179193326Sed  AssociatedClassSet AssociatedClasses;
3180243830Sdim  FindAssociatedClassesAndNamespaces(Loc, Args,
3181198092Srdivacky                                     AssociatedNamespaces,
3182198092Srdivacky                                     AssociatedClasses);
3183193326Sed
3184193326Sed  // C++ [basic.lookup.argdep]p3:
3185193326Sed  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
3186193326Sed  //   and let Y be the lookup set produced by argument dependent
3187193326Sed  //   lookup (defined as follows). If X contains [...] then Y is
3188193326Sed  //   empty. Otherwise Y is the set of declarations found in the
3189193326Sed  //   namespaces associated with the argument types as described
3190193326Sed  //   below. The set of declarations found by the lookup of the name
3191193326Sed  //   is the union of X and Y.
3192193326Sed  //
3193193326Sed  // Here, we compute Y and add its members to the overloaded
3194193326Sed  // candidate set.
3195276479Sdim  for (auto *NS : AssociatedNamespaces) {
3196193326Sed    //   When considering an associated namespace, the lookup is the
3197193326Sed    //   same as the lookup performed when the associated namespace is
3198193326Sed    //   used as a qualifier (3.4.3.2) except that:
3199193326Sed    //
3200193326Sed    //     -- Any using-directives in the associated namespace are
3201193326Sed    //        ignored.
3202193326Sed    //
3203198092Srdivacky    //     -- Any namespace-scope friend functions declared in
3204193326Sed    //        associated classes are visible within their respective
3205193326Sed    //        namespaces even if they are not visible during an ordinary
3206193326Sed    //        lookup (11.4).
3207276479Sdim    DeclContext::lookup_result R = NS->lookup(Name);
3208276479Sdim    for (auto *D : R) {
3209198092Srdivacky      // If the only declaration here is an ordinary friend, consider
3210198092Srdivacky      // it only if it was declared in an associated classes.
3211261991Sdim      if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3212261991Sdim        // If it's neither ordinarily visible nor a friend, we can't find it.
3213261991Sdim        if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3214198092Srdivacky          continue;
3215261991Sdim
3216261991Sdim        bool DeclaredInAssociatedClass = false;
3217261991Sdim        for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3218261991Sdim          DeclContext *LexDC = DI->getLexicalDeclContext();
3219261991Sdim          if (isa<CXXRecordDecl>(LexDC) &&
3220296417Sdim              AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3221296417Sdim              isVisible(cast<NamedDecl>(DI))) {
3222261991Sdim            DeclaredInAssociatedClass = true;
3223261991Sdim            break;
3224261991Sdim          }
3225261991Sdim        }
3226261991Sdim        if (!DeclaredInAssociatedClass)
3227261991Sdim          continue;
3228198092Srdivacky      }
3229198092Srdivacky
3230203955Srdivacky      if (isa<UsingShadowDecl>(D))
3231203955Srdivacky        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3232203955Srdivacky
3233276479Sdim      if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
3234203955Srdivacky        continue;
3235203955Srdivacky
3236288943Sdim      if (!isVisible(D) && !(D = findAcceptableDecl(*this, D)))
3237288943Sdim        continue;
3238288943Sdim
3239203955Srdivacky      Result.insert(D);
3240193326Sed    }
3241193326Sed  }
3242193326Sed}
3243201361Srdivacky
3244201361Srdivacky//----------------------------------------------------------------------------
3245201361Srdivacky// Search for all visible declarations.
3246201361Srdivacky//----------------------------------------------------------------------------
3247201361SrdivackyVisibleDeclConsumer::~VisibleDeclConsumer() { }
3248201361Srdivacky
3249261991Sdimbool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3250261991Sdim
3251201361Srdivackynamespace {
3252201361Srdivacky
3253201361Srdivackyclass ShadowContextRAII;
3254201361Srdivacky
3255201361Srdivackyclass VisibleDeclsRecord {
3256201361Srdivackypublic:
3257201361Srdivacky  /// \brief An entry in the shadow map, which is optimized to store a
3258201361Srdivacky  /// single declaration (the common case) but can also store a list
3259201361Srdivacky  /// of declarations.
3260226633Sdim  typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3261218893Sdim
3262201361Srdivackyprivate:
3263201361Srdivacky  /// \brief A mapping from declaration names to the declarations that have
3264201361Srdivacky  /// this name within a particular scope.
3265201361Srdivacky  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3266201361Srdivacky
3267201361Srdivacky  /// \brief A list of shadow maps, which is used to model name hiding.
3268201361Srdivacky  std::list<ShadowMap> ShadowMaps;
3269201361Srdivacky
3270201361Srdivacky  /// \brief The declaration contexts we have already visited.
3271201361Srdivacky  llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3272201361Srdivacky
3273201361Srdivacky  friend class ShadowContextRAII;
3274201361Srdivacky
3275201361Srdivackypublic:
3276201361Srdivacky  /// \brief Determine whether we have already visited this context
3277201361Srdivacky  /// (and, if not, note that we are going to visit that context now).
3278201361Srdivacky  bool visitedContext(DeclContext *Ctx) {
3279280031Sdim    return !VisitedContexts.insert(Ctx).second;
3280201361Srdivacky  }
3281201361Srdivacky
3282212904Sdim  bool alreadyVisitedContext(DeclContext *Ctx) {
3283212904Sdim    return VisitedContexts.count(Ctx);
3284212904Sdim  }
3285212904Sdim
3286201361Srdivacky  /// \brief Determine whether the given declaration is hidden in the
3287201361Srdivacky  /// current scope.
3288201361Srdivacky  ///
3289201361Srdivacky  /// \returns the declaration that hides the given declaration, or
3290201361Srdivacky  /// NULL if no such declaration exists.
3291201361Srdivacky  NamedDecl *checkHidden(NamedDecl *ND);
3292201361Srdivacky
3293201361Srdivacky  /// \brief Add a declaration to the current shadow map.
3294226633Sdim  void add(NamedDecl *ND) {
3295226633Sdim    ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3296226633Sdim  }
3297201361Srdivacky};
3298201361Srdivacky
3299201361Srdivacky/// \brief RAII object that records when we've entered a shadow context.
3300201361Srdivackyclass ShadowContextRAII {
3301201361Srdivacky  VisibleDeclsRecord &Visible;
3302201361Srdivacky
3303201361Srdivacky  typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3304201361Srdivacky
3305201361Srdivackypublic:
3306201361Srdivacky  ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3307288943Sdim    Visible.ShadowMaps.emplace_back();
3308201361Srdivacky  }
3309201361Srdivacky
3310201361Srdivacky  ~ShadowContextRAII() {
3311201361Srdivacky    Visible.ShadowMaps.pop_back();
3312201361Srdivacky  }
3313201361Srdivacky};
3314201361Srdivacky
3315201361Srdivacky} // end anonymous namespace
3316201361Srdivacky
3317201361SrdivackyNamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3318201361Srdivacky  unsigned IDNS = ND->getIdentifierNamespace();
3319201361Srdivacky  std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3320201361Srdivacky  for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3321201361Srdivacky       SM != SMEnd; ++SM) {
3322201361Srdivacky    ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3323201361Srdivacky    if (Pos == SM->end())
3324201361Srdivacky      continue;
3325201361Srdivacky
3326276479Sdim    for (auto *D : Pos->second) {
3327201361Srdivacky      // A tag declaration does not hide a non-tag declaration.
3328276479Sdim      if (D->hasTagIdentifierNamespace() &&
3329218893Sdim          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3330201361Srdivacky                   Decl::IDNS_ObjCProtocol)))
3331201361Srdivacky        continue;
3332201361Srdivacky
3333201361Srdivacky      // Protocols are in distinct namespaces from everything else.
3334276479Sdim      if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3335201361Srdivacky           || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3336276479Sdim          D->getIdentifierNamespace() != IDNS)
3337201361Srdivacky        continue;
3338201361Srdivacky
3339202379Srdivacky      // Functions and function templates in the same scope overload
3340202379Srdivacky      // rather than hide.  FIXME: Look for hiding based on function
3341202379Srdivacky      // signatures!
3342276479Sdim      if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3343276479Sdim          ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3344202379Srdivacky          SM == ShadowMaps.rbegin())
3345202379Srdivacky        continue;
3346218893Sdim
3347201361Srdivacky      // We've found a declaration that hides this one.
3348276479Sdim      return D;
3349201361Srdivacky    }
3350201361Srdivacky  }
3351201361Srdivacky
3352276479Sdim  return nullptr;
3353201361Srdivacky}
3354201361Srdivacky
3355201361Srdivackystatic void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3356201361Srdivacky                               bool QualifiedNameLookup,
3357202379Srdivacky                               bool InBaseClass,
3358201361Srdivacky                               VisibleDeclConsumer &Consumer,
3359201361Srdivacky                               VisibleDeclsRecord &Visited) {
3360203955Srdivacky  if (!Ctx)
3361203955Srdivacky    return;
3362203955Srdivacky
3363201361Srdivacky  // Make sure we don't visit the same context twice.
3364201361Srdivacky  if (Visited.visitedContext(Ctx->getPrimaryContext()))
3365201361Srdivacky    return;
3366218893Sdim
3367288943Sdim  // Outside C++, lookup results for the TU live on identifiers.
3368288943Sdim  if (isa<TranslationUnitDecl>(Ctx) &&
3369288943Sdim      !Result.getSema().getLangOpts().CPlusPlus) {
3370288943Sdim    auto &S = Result.getSema();
3371288943Sdim    auto &Idents = S.Context.Idents;
3372288943Sdim
3373288943Sdim    // Ensure all external identifiers are in the identifier table.
3374288943Sdim    if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3375288943Sdim      std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3376288943Sdim      for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3377288943Sdim        Idents.get(Name);
3378288943Sdim    }
3379288943Sdim
3380288943Sdim    // Walk all lookup results in the TU for each identifier.
3381288943Sdim    for (const auto &Ident : Idents) {
3382288943Sdim      for (auto I = S.IdResolver.begin(Ident.getValue()),
3383288943Sdim                E = S.IdResolver.end();
3384288943Sdim           I != E; ++I) {
3385288943Sdim        if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3386288943Sdim          if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3387288943Sdim            Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3388288943Sdim            Visited.add(ND);
3389288943Sdim          }
3390288943Sdim        }
3391288943Sdim      }
3392288943Sdim    }
3393288943Sdim
3394288943Sdim    return;
3395288943Sdim  }
3396288943Sdim
3397210299Sed  if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3398210299Sed    Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3399210299Sed
3400201361Srdivacky  // Enumerate all of the results in this context.
3401288943Sdim  for (DeclContextLookupResult R : Ctx->lookups()) {
3402288943Sdim    for (auto *D : R) {
3403288943Sdim      if (auto *ND = Result.getAcceptableDecl(D)) {
3404288943Sdim        Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3405288943Sdim        Visited.add(ND);
3406218893Sdim      }
3407201361Srdivacky    }
3408201361Srdivacky  }
3409201361Srdivacky
3410201361Srdivacky  // Traverse using directives for qualified name lookup.
3411201361Srdivacky  if (QualifiedNameLookup) {
3412201361Srdivacky    ShadowContextRAII Shadow(Visited);
3413276479Sdim    for (auto I : Ctx->using_directives()) {
3414276479Sdim      LookupVisibleDecls(I->getNominatedNamespace(), Result,
3415202379Srdivacky                         QualifiedNameLookup, InBaseClass, Consumer, Visited);
3416201361Srdivacky    }
3417201361Srdivacky  }
3418201361Srdivacky
3419202379Srdivacky  // Traverse the contexts of inherited C++ classes.
3420201361Srdivacky  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3421203955Srdivacky    if (!Record->hasDefinition())
3422203955Srdivacky      return;
3423203955Srdivacky
3424276479Sdim    for (const auto &B : Record->bases()) {
3425276479Sdim      QualType BaseType = B.getType();
3426218893Sdim
3427201361Srdivacky      // Don't look into dependent bases, because name lookup can't look
3428201361Srdivacky      // there anyway.
3429201361Srdivacky      if (BaseType->isDependentType())
3430201361Srdivacky        continue;
3431218893Sdim
3432201361Srdivacky      const RecordType *Record = BaseType->getAs<RecordType>();
3433201361Srdivacky      if (!Record)
3434201361Srdivacky        continue;
3435218893Sdim
3436201361Srdivacky      // FIXME: It would be nice to be able to determine whether referencing
3437201361Srdivacky      // a particular member would be ambiguous. For example, given
3438201361Srdivacky      //
3439201361Srdivacky      //   struct A { int member; };
3440201361Srdivacky      //   struct B { int member; };
3441201361Srdivacky      //   struct C : A, B { };
3442201361Srdivacky      //
3443201361Srdivacky      //   void f(C *c) { c->### }
3444201361Srdivacky      //
3445201361Srdivacky      // accessing 'member' would result in an ambiguity. However, we
3446201361Srdivacky      // could be smart enough to qualify the member with the base
3447201361Srdivacky      // class, e.g.,
3448201361Srdivacky      //
3449201361Srdivacky      //   c->B::member
3450201361Srdivacky      //
3451201361Srdivacky      // or
3452201361Srdivacky      //
3453201361Srdivacky      //   c->A::member
3454218893Sdim
3455201361Srdivacky      // Find results in this base class (and its bases).
3456201361Srdivacky      ShadowContextRAII Shadow(Visited);
3457201361Srdivacky      LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
3458202379Srdivacky                         true, Consumer, Visited);
3459202379Srdivacky    }
3460202379Srdivacky  }
3461218893Sdim
3462202379Srdivacky  // Traverse the contexts of Objective-C classes.
3463202379Srdivacky  if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3464202379Srdivacky    // Traverse categories.
3465276479Sdim    for (auto *Cat : IFace->visible_categories()) {
3466202379Srdivacky      ShadowContextRAII Shadow(Visited);
3467276479Sdim      LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
3468201361Srdivacky                         Consumer, Visited);
3469201361Srdivacky    }
3470202379Srdivacky
3471202379Srdivacky    // Traverse protocols.
3472276479Sdim    for (auto *I : IFace->all_referenced_protocols()) {
3473202379Srdivacky      ShadowContextRAII Shadow(Visited);
3474276479Sdim      LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3475202379Srdivacky                         Visited);
3476202379Srdivacky    }
3477202379Srdivacky
3478202379Srdivacky    // Traverse the superclass.
3479202379Srdivacky    if (IFace->getSuperClass()) {
3480202379Srdivacky      ShadowContextRAII Shadow(Visited);
3481202379Srdivacky      LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
3482202379Srdivacky                         true, Consumer, Visited);
3483202379Srdivacky    }
3484218893Sdim
3485207619Srdivacky    // If there is an implementation, traverse it. We do this to find
3486207619Srdivacky    // synthesized ivars.
3487207619Srdivacky    if (IFace->getImplementation()) {
3488207619Srdivacky      ShadowContextRAII Shadow(Visited);
3489218893Sdim      LookupVisibleDecls(IFace->getImplementation(), Result,
3490234353Sdim                         QualifiedNameLookup, InBaseClass, Consumer, Visited);
3491207619Srdivacky    }
3492202379Srdivacky  } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3493276479Sdim    for (auto *I : Protocol->protocols()) {
3494202379Srdivacky      ShadowContextRAII Shadow(Visited);
3495276479Sdim      LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3496202379Srdivacky                         Visited);
3497202379Srdivacky    }
3498202379Srdivacky  } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3499276479Sdim    for (auto *I : Category->protocols()) {
3500202379Srdivacky      ShadowContextRAII Shadow(Visited);
3501276479Sdim      LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3502202379Srdivacky                         Visited);
3503202379Srdivacky    }
3504218893Sdim
3505207619Srdivacky    // If there is an implementation, traverse it.
3506207619Srdivacky    if (Category->getImplementation()) {
3507207619Srdivacky      ShadowContextRAII Shadow(Visited);
3508218893Sdim      LookupVisibleDecls(Category->getImplementation(), Result,
3509207619Srdivacky                         QualifiedNameLookup, true, Consumer, Visited);
3510218893Sdim    }
3511201361Srdivacky  }
3512201361Srdivacky}
3513201361Srdivacky
3514201361Srdivackystatic void LookupVisibleDecls(Scope *S, LookupResult &Result,
3515201361Srdivacky                               UnqualUsingDirectiveSet &UDirs,
3516201361Srdivacky                               VisibleDeclConsumer &Consumer,
3517201361Srdivacky                               VisibleDeclsRecord &Visited) {
3518201361Srdivacky  if (!S)
3519201361Srdivacky    return;
3520201361Srdivacky
3521218893Sdim  if (!S->getEntity() ||
3522218893Sdim      (!S->getParent() &&
3523261991Sdim       !Visited.alreadyVisitedContext(S->getEntity())) ||
3524261991Sdim      (S->getEntity())->isFunctionOrMethod()) {
3525261991Sdim    FindLocalExternScope FindLocals(Result);
3526202379Srdivacky    // Walk through the declarations in this Scope.
3527276479Sdim    for (auto *D : S->decls()) {
3528276479Sdim      if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3529234353Sdim        if ((ND = Result.getAcceptableDecl(ND))) {
3530276479Sdim          Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
3531202379Srdivacky          Visited.add(ND);
3532202379Srdivacky        }
3533202379Srdivacky    }
3534202379Srdivacky  }
3535218893Sdim
3536205219Srdivacky  // FIXME: C++ [temp.local]p8
3537276479Sdim  DeclContext *Entity = nullptr;
3538202379Srdivacky  if (S->getEntity()) {
3539201361Srdivacky    // Look into this scope's declaration context, along with any of its
3540201361Srdivacky    // parent lookup contexts (e.g., enclosing classes), up to the point
3541201361Srdivacky    // where we hit the context stored in the next outer scope.
3542261991Sdim    Entity = S->getEntity();
3543205219Srdivacky    DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3544218893Sdim
3545205219Srdivacky    for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3546201361Srdivacky         Ctx = Ctx->getLookupParent()) {
3547202379Srdivacky      if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3548202379Srdivacky        if (Method->isInstanceMethod()) {
3549202379Srdivacky          // For instance methods, look for ivars in the method's interface.
3550202379Srdivacky          LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3551202379Srdivacky                                  Result.getNameLoc(), Sema::LookupMemberName);
3552218893Sdim          if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3553218893Sdim            LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3554261991Sdim                               /*InBaseClass=*/false, Consumer, Visited);
3555218893Sdim          }
3556202379Srdivacky        }
3557202379Srdivacky
3558202379Srdivacky        // We've already performed all of the name lookup that we need
3559202379Srdivacky        // to for Objective-C methods; the next context will be the
3560202379Srdivacky        // outer scope.
3561202379Srdivacky        break;
3562202379Srdivacky      }
3563202379Srdivacky
3564201361Srdivacky      if (Ctx->isFunctionOrMethod())
3565201361Srdivacky        continue;
3566218893Sdim
3567218893Sdim      LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3568202379Srdivacky                         /*InBaseClass=*/false, Consumer, Visited);
3569201361Srdivacky    }
3570201361Srdivacky  } else if (!S->getParent()) {
3571201361Srdivacky    // Look into the translation unit scope. We walk through the translation
3572201361Srdivacky    // unit's declaration context, because the Scope itself won't have all of
3573201361Srdivacky    // the declarations if we loaded a precompiled header.
3574201361Srdivacky    // FIXME: We would like the translation unit's Scope object to point to the
3575201361Srdivacky    // translation unit, so we don't need this special "if" branch. However,
3576201361Srdivacky    // doing so would force the normal C++ name-lookup code to look into the
3577218893Sdim    // translation unit decl when the IdentifierInfo chains would suffice.
3578201361Srdivacky    // Once we fix that problem (which is part of a more general "don't look
3579202379Srdivacky    // in DeclContexts unless we have to" optimization), we can eliminate this.
3580201361Srdivacky    Entity = Result.getSema().Context.getTranslationUnitDecl();
3581218893Sdim    LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3582202379Srdivacky                       /*InBaseClass=*/false, Consumer, Visited);
3583218893Sdim  }
3584218893Sdim
3585201361Srdivacky  if (Entity) {
3586201361Srdivacky    // Lookup visible declarations in any namespaces found by using
3587201361Srdivacky    // directives.
3588288943Sdim    for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3589288943Sdim      LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
3590218893Sdim                         Result, /*QualifiedNameLookup=*/false,
3591202379Srdivacky                         /*InBaseClass=*/false, Consumer, Visited);
3592201361Srdivacky  }
3593201361Srdivacky
3594201361Srdivacky  // Lookup names in the parent scope.
3595201361Srdivacky  ShadowContextRAII Shadow(Visited);
3596201361Srdivacky  LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3597201361Srdivacky}
3598201361Srdivacky
3599201361Srdivackyvoid Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3600212904Sdim                              VisibleDeclConsumer &Consumer,
3601212904Sdim                              bool IncludeGlobalScope) {
3602201361Srdivacky  // Determine the set of using directives available during
3603201361Srdivacky  // unqualified name lookup.
3604201361Srdivacky  Scope *Initial = S;
3605201361Srdivacky  UnqualUsingDirectiveSet UDirs;
3606234353Sdim  if (getLangOpts().CPlusPlus) {
3607201361Srdivacky    // Find the first namespace or translation-unit scope.
3608201361Srdivacky    while (S && !isNamespaceOrTranslationUnitScope(S))
3609201361Srdivacky      S = S->getParent();
3610201361Srdivacky
3611201361Srdivacky    UDirs.visitScopeChain(Initial, S);
3612201361Srdivacky  }
3613201361Srdivacky  UDirs.done();
3614201361Srdivacky
3615201361Srdivacky  // Look for visible declarations.
3616201361Srdivacky  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3617261991Sdim  Result.setAllowHidden(Consumer.includeHiddenDecls());
3618201361Srdivacky  VisibleDeclsRecord Visited;
3619212904Sdim  if (!IncludeGlobalScope)
3620212904Sdim    Visited.visitedContext(Context.getTranslationUnitDecl());
3621201361Srdivacky  ShadowContextRAII Shadow(Visited);
3622201361Srdivacky  ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3623201361Srdivacky}
3624201361Srdivacky
3625201361Srdivackyvoid Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3626212904Sdim                              VisibleDeclConsumer &Consumer,
3627212904Sdim                              bool IncludeGlobalScope) {
3628201361Srdivacky  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3629261991Sdim  Result.setAllowHidden(Consumer.includeHiddenDecls());
3630201361Srdivacky  VisibleDeclsRecord Visited;
3631212904Sdim  if (!IncludeGlobalScope)
3632212904Sdim    Visited.visitedContext(Context.getTranslationUnitDecl());
3633201361Srdivacky  ShadowContextRAII Shadow(Visited);
3634218893Sdim  ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3635202379Srdivacky                       /*InBaseClass=*/false, Consumer, Visited);
3636201361Srdivacky}
3637201361Srdivacky
3638218893Sdim/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3639221345Sdim/// If GnuLabelLoc is a valid source location, then this is a definition
3640221345Sdim/// of an __label__ label name, otherwise it is a normal label definition
3641221345Sdim/// or use.
3642218893SdimLabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3643221345Sdim                                     SourceLocation GnuLabelLoc) {
3644218893Sdim  // Do a lookup to see if we have a label with this name already.
3645276479Sdim  NamedDecl *Res = nullptr;
3646221345Sdim
3647221345Sdim  if (GnuLabelLoc.isValid()) {
3648221345Sdim    // Local label definitions always shadow existing labels.
3649221345Sdim    Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3650221345Sdim    Scope *S = CurScope;
3651221345Sdim    PushOnScopeChains(Res, S, true);
3652221345Sdim    return cast<LabelDecl>(Res);
3653221345Sdim  }
3654221345Sdim
3655221345Sdim  // Not a GNU local label.
3656221345Sdim  Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3657221345Sdim  // If we found a label, check to see if it is in the same context as us.
3658221345Sdim  // When in a Block, we don't want to reuse a label in an enclosing function.
3659218893Sdim  if (Res && Res->getDeclContext() != CurContext)
3660276479Sdim    Res = nullptr;
3661276479Sdim  if (!Res) {
3662218893Sdim    // If not forward referenced or defined already, create the backing decl.
3663218893Sdim    Res = LabelDecl::Create(Context, CurContext, Loc, II);
3664221345Sdim    Scope *S = CurScope->getFnParent();
3665218893Sdim    assert(S && "Not in a function?");
3666218893Sdim    PushOnScopeChains(Res, S, true);
3667218893Sdim  }
3668218893Sdim  return cast<LabelDecl>(Res);
3669218893Sdim}
3670218893Sdim
3671218893Sdim//===----------------------------------------------------------------------===//
3672201361Srdivacky// Typo correction
3673218893Sdim//===----------------------------------------------------------------------===//
3674201361Srdivacky
3675276479Sdimstatic bool isCandidateViable(CorrectionCandidateCallback &CCC,
3676276479Sdim                              TypoCorrection &Candidate) {
3677276479Sdim  Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3678276479Sdim  return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3679276479Sdim}
3680276479Sdim
3681276479Sdimstatic void LookupPotentialTypoResult(Sema &SemaRef,
3682276479Sdim                                      LookupResult &Res,
3683276479Sdim                                      IdentifierInfo *Name,
3684276479Sdim                                      Scope *S, CXXScopeSpec *SS,
3685276479Sdim                                      DeclContext *MemberContext,
3686276479Sdim                                      bool EnteringContext,
3687276479Sdim                                      bool isObjCIvarLookup,
3688276479Sdim                                      bool FindHidden);
3689276479Sdim
3690280031Sdim/// \brief Check whether the declarations found for a typo correction are
3691280031Sdim/// visible, and if none of them are, convert the correction to an 'import
3692280031Sdim/// a module' correction.
3693280031Sdimstatic void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3694280031Sdim  if (TC.begin() == TC.end())
3695280031Sdim    return;
3696280031Sdim
3697280031Sdim  TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3698280031Sdim
3699280031Sdim  for (/**/; DI != DE; ++DI)
3700280031Sdim    if (!LookupResult::isVisible(SemaRef, *DI))
3701280031Sdim      break;
3702280031Sdim  // Nothing to do if all decls are visible.
3703280031Sdim  if (DI == DE)
3704280031Sdim    return;
3705280031Sdim
3706280031Sdim  llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3707280031Sdim  bool AnyVisibleDecls = !NewDecls.empty();
3708280031Sdim
3709280031Sdim  for (/**/; DI != DE; ++DI) {
3710280031Sdim    NamedDecl *VisibleDecl = *DI;
3711280031Sdim    if (!LookupResult::isVisible(SemaRef, *DI))
3712280031Sdim      VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3713280031Sdim
3714280031Sdim    if (VisibleDecl) {
3715280031Sdim      if (!AnyVisibleDecls) {
3716280031Sdim        // Found a visible decl, discard all hidden ones.
3717280031Sdim        AnyVisibleDecls = true;
3718280031Sdim        NewDecls.clear();
3719280031Sdim      }
3720280031Sdim      NewDecls.push_back(VisibleDecl);
3721280031Sdim    } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3722280031Sdim      NewDecls.push_back(*DI);
3723280031Sdim  }
3724280031Sdim
3725280031Sdim  if (NewDecls.empty())
3726280031Sdim    TC = TypoCorrection();
3727280031Sdim  else {
3728280031Sdim    TC.setCorrectionDecls(NewDecls);
3729280031Sdim    TC.setRequiresImport(!AnyVisibleDecls);
3730280031Sdim  }
3731280031Sdim}
3732280031Sdim
3733276479Sdim// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3734276479Sdim// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3735276479Sdim// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3736276479Sdimstatic void getNestedNameSpecifierIdentifiers(
3737276479Sdim    NestedNameSpecifier *NNS,
3738276479Sdim    SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3739276479Sdim  if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3740276479Sdim    getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3741276479Sdim  else
3742276479Sdim    Identifiers.clear();
3743276479Sdim
3744276479Sdim  const IdentifierInfo *II = nullptr;
3745276479Sdim
3746276479Sdim  switch (NNS->getKind()) {
3747276479Sdim  case NestedNameSpecifier::Identifier:
3748276479Sdim    II = NNS->getAsIdentifier();
3749276479Sdim    break;
3750276479Sdim
3751276479Sdim  case NestedNameSpecifier::Namespace:
3752276479Sdim    if (NNS->getAsNamespace()->isAnonymousNamespace())
3753276479Sdim      return;
3754276479Sdim    II = NNS->getAsNamespace()->getIdentifier();
3755276479Sdim    break;
3756276479Sdim
3757276479Sdim  case NestedNameSpecifier::NamespaceAlias:
3758276479Sdim    II = NNS->getAsNamespaceAlias()->getIdentifier();
3759276479Sdim    break;
3760276479Sdim
3761276479Sdim  case NestedNameSpecifier::TypeSpecWithTemplate:
3762276479Sdim  case NestedNameSpecifier::TypeSpec:
3763276479Sdim    II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3764276479Sdim    break;
3765276479Sdim
3766276479Sdim  case NestedNameSpecifier::Global:
3767280031Sdim  case NestedNameSpecifier::Super:
3768276479Sdim    return;
3769276479Sdim  }
3770276479Sdim
3771276479Sdim  if (II)
3772276479Sdim    Identifiers.push_back(II);
3773276479Sdim}
3774276479Sdim
3775218893Sdimvoid TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3776226633Sdim                                       DeclContext *Ctx, bool InBaseClass) {
3777201361Srdivacky  // Don't consider hidden names for typo correction.
3778201361Srdivacky  if (Hiding)
3779201361Srdivacky    return;
3780218893Sdim
3781201361Srdivacky  // Only consider entities with identifiers for names, ignoring
3782201361Srdivacky  // special names (constructors, overloaded operators, selectors,
3783201361Srdivacky  // etc.).
3784201361Srdivacky  IdentifierInfo *Name = ND->getIdentifier();
3785201361Srdivacky  if (!Name)
3786201361Srdivacky    return;
3787201361Srdivacky
3788261991Sdim  // Only consider visible declarations and declarations from modules with
3789261991Sdim  // names that exactly match.
3790276479Sdim  if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
3791261991Sdim      !findAcceptableDecl(SemaRef, ND))
3792261991Sdim    return;
3793261991Sdim
3794218893Sdim  FoundName(Name->getName());
3795218893Sdim}
3796218893Sdim
3797226633Sdimvoid TypoCorrectionConsumer::FoundName(StringRef Name) {
3798261991Sdim  // Compute the edit distance between the typo and the name of this
3799261991Sdim  // entity, and add the identifier to the list of results.
3800276479Sdim  addName(Name, nullptr);
3801261991Sdim}
3802261991Sdim
3803261991Sdimvoid TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3804261991Sdim  // Compute the edit distance between the typo and this keyword,
3805261991Sdim  // and add the keyword to the list of results.
3806276479Sdim  addName(Keyword, nullptr, nullptr, true);
3807261991Sdim}
3808261991Sdim
3809261991Sdimvoid TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3810261991Sdim                                     NestedNameSpecifier *NNS, bool isKeyword) {
3811218893Sdim  // Use a simple length-based heuristic to determine the minimum possible
3812218893Sdim  // edit distance. If the minimum isn't good enough, bail out early.
3813276479Sdim  StringRef TypoStr = Typo->getName();
3814276479Sdim  unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3815276479Sdim  if (MinED && TypoStr.size() / MinED < 3)
3816218893Sdim    return;
3817218893Sdim
3818218893Sdim  // Compute an upper bound on the allowable edit distance, so that the
3819218893Sdim  // edit-distance algorithm can short-circuit.
3820276479Sdim  unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3821276479Sdim  unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
3822261991Sdim  if (ED >= UpperBound) return;
3823218893Sdim
3824261991Sdim  TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
3825226633Sdim  if (isKeyword) TC.makeKeyword();
3826280031Sdim  TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
3827226633Sdim  addCorrection(TC);
3828224145Sdim}
3829224145Sdim
3830280031Sdimstatic const unsigned MaxTypoDistanceResultSets = 5;
3831280031Sdim
3832224145Sdimvoid TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3833276479Sdim  StringRef TypoStr = Typo->getName();
3834226633Sdim  StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3835276479Sdim
3836276479Sdim  // For very short typos, ignore potential corrections that have a different
3837276479Sdim  // base identifier from the typo or which have a normalized edit distance
3838276479Sdim  // longer than the typo itself.
3839276479Sdim  if (TypoStr.size() < 3 &&
3840276479Sdim      (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3841276479Sdim    return;
3842276479Sdim
3843276479Sdim  // If the correction is resolved but is not viable, ignore it.
3844280031Sdim  if (Correction.isResolved()) {
3845280031Sdim    checkCorrectionVisibility(SemaRef, Correction);
3846280031Sdim    if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
3847280031Sdim      return;
3848280031Sdim  }
3849276479Sdim
3850239462Sdim  TypoResultList &CList =
3851239462Sdim      CorrectionResults[Correction.getEditDistance(false)][Name];
3852224145Sdim
3853239462Sdim  if (!CList.empty() && !CList.back().isResolved())
3854239462Sdim    CList.pop_back();
3855239462Sdim  if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3856239462Sdim    std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3857239462Sdim    for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3858239462Sdim         RI != RIEnd; ++RI) {
3859239462Sdim      // If the Correction refers to a decl already in the result list,
3860239462Sdim      // replace the existing result if the string representation of Correction
3861239462Sdim      // comes before the current result alphabetically, then stop as there is
3862239462Sdim      // nothing more to be done to add Correction to the candidate set.
3863239462Sdim      if (RI->getCorrectionDecl() == NewND) {
3864239462Sdim        if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3865239462Sdim          *RI = Correction;
3866239462Sdim        return;
3867239462Sdim      }
3868239462Sdim    }
3869239462Sdim  }
3870239462Sdim  if (CList.empty() || Correction.isResolved())
3871239462Sdim    CList.push_back(Correction);
3872224145Sdim
3873239462Sdim  while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3874276479Sdim    CorrectionResults.erase(std::prev(CorrectionResults.end()));
3875224145Sdim}
3876224145Sdim
3877276479Sdimvoid TypoCorrectionConsumer::addNamespaces(
3878276479Sdim    const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
3879276479Sdim  SearchNamespaces = true;
3880234353Sdim
3881276479Sdim  for (auto KNPair : KnownNamespaces)
3882276479Sdim    Namespaces.addNameSpecifier(KNPair.first);
3883234353Sdim
3884276479Sdim  bool SSIsTemplate = false;
3885276479Sdim  if (NestedNameSpecifier *NNS =
3886276479Sdim          (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
3887276479Sdim    if (const Type *T = NNS->getAsType())
3888276479Sdim      SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
3889276479Sdim  }
3890296417Sdim  // Do not transform this into an iterator-based loop. The loop body can
3891296417Sdim  // trigger the creation of further types (through lazy deserialization) and
3892296417Sdim  // invalide iterators into this list.
3893296417Sdim  auto &Types = SemaRef.getASTContext().getTypes();
3894296417Sdim  for (unsigned I = 0; I != Types.size(); ++I) {
3895296417Sdim    const auto *TI = Types[I];
3896276479Sdim    if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
3897276479Sdim      CD = CD->getCanonicalDecl();
3898276479Sdim      if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
3899276479Sdim          !CD->isUnion() && CD->getIdentifier() &&
3900276479Sdim          (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
3901276479Sdim          (CD->isBeingDefined() || CD->isCompleteDefinition()))
3902276479Sdim        Namespaces.addNameSpecifier(CD);
3903276479Sdim    }
3904276479Sdim  }
3905276479Sdim}
3906234353Sdim
3907280031Sdimconst TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
3908280031Sdim  if (++CurrentTCIndex < ValidatedCorrections.size())
3909280031Sdim    return ValidatedCorrections[CurrentTCIndex];
3910280031Sdim
3911280031Sdim  CurrentTCIndex = ValidatedCorrections.size();
3912276479Sdim  while (!CorrectionResults.empty()) {
3913276479Sdim    auto DI = CorrectionResults.begin();
3914276479Sdim    if (DI->second.empty()) {
3915276479Sdim      CorrectionResults.erase(DI);
3916276479Sdim      continue;
3917276479Sdim    }
3918234353Sdim
3919276479Sdim    auto RI = DI->second.begin();
3920276479Sdim    if (RI->second.empty()) {
3921276479Sdim      DI->second.erase(RI);
3922276479Sdim      performQualifiedLookups();
3923276479Sdim      continue;
3924276479Sdim    }
3925276479Sdim
3926276479Sdim    TypoCorrection TC = RI->second.pop_back_val();
3927280031Sdim    if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
3928280031Sdim      ValidatedCorrections.push_back(TC);
3929280031Sdim      return ValidatedCorrections[CurrentTCIndex];
3930280031Sdim    }
3931276479Sdim  }
3932280031Sdim  return ValidatedCorrections[0];  // The empty correction.
3933276479Sdim}
3934276479Sdim
3935276479Sdimbool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
3936276479Sdim  IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3937276479Sdim  DeclContext *TempMemberContext = MemberContext;
3938280031Sdim  CXXScopeSpec *TempSS = SS.get();
3939276479Sdimretry_lookup:
3940276479Sdim  LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
3941276479Sdim                            EnteringContext,
3942280031Sdim                            CorrectionValidator->IsObjCIvarLookup,
3943276479Sdim                            Name == Typo && !Candidate.WillReplaceSpecifier());
3944276479Sdim  switch (Result.getResultKind()) {
3945276479Sdim  case LookupResult::NotFound:
3946276479Sdim  case LookupResult::NotFoundInCurrentInstantiation:
3947276479Sdim  case LookupResult::FoundUnresolvedValue:
3948276479Sdim    if (TempSS) {
3949276479Sdim      // Immediately retry the lookup without the given CXXScopeSpec
3950276479Sdim      TempSS = nullptr;
3951276479Sdim      Candidate.WillReplaceSpecifier(true);
3952276479Sdim      goto retry_lookup;
3953276479Sdim    }
3954276479Sdim    if (TempMemberContext) {
3955276479Sdim      if (SS && !TempSS)
3956280031Sdim        TempSS = SS.get();
3957276479Sdim      TempMemberContext = nullptr;
3958276479Sdim      goto retry_lookup;
3959276479Sdim    }
3960276479Sdim    if (SearchNamespaces)
3961276479Sdim      QualifiedResults.push_back(Candidate);
3962234353Sdim    break;
3963234353Sdim
3964276479Sdim  case LookupResult::Ambiguous:
3965276479Sdim    // We don't deal with ambiguities.
3966234353Sdim    break;
3967234353Sdim
3968276479Sdim  case LookupResult::Found:
3969276479Sdim  case LookupResult::FoundOverloaded:
3970276479Sdim    // Store all of the Decls for overloaded symbols
3971276479Sdim    for (auto *TRD : Result)
3972276479Sdim      Candidate.addCorrectionDecl(TRD);
3973280031Sdim    checkCorrectionVisibility(SemaRef, Candidate);
3974280031Sdim    if (!isCandidateViable(*CorrectionValidator, Candidate)) {
3975276479Sdim      if (SearchNamespaces)
3976276479Sdim        QualifiedResults.push_back(Candidate);
3977276479Sdim      break;
3978276479Sdim    }
3979280031Sdim    Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
3980276479Sdim    return true;
3981234353Sdim  }
3982276479Sdim  return false;
3983234353Sdim}
3984234353Sdim
3985276479Sdimvoid TypoCorrectionConsumer::performQualifiedLookups() {
3986276479Sdim  unsigned TypoLen = Typo->getName().size();
3987276479Sdim  for (auto QR : QualifiedResults) {
3988276479Sdim    for (auto NSI : Namespaces) {
3989276479Sdim      DeclContext *Ctx = NSI.DeclCtx;
3990276479Sdim      const Type *NSType = NSI.NameSpecifier->getAsType();
3991224145Sdim
3992276479Sdim      // If the current NestedNameSpecifier refers to a class and the
3993276479Sdim      // current correction candidate is the name of that class, then skip
3994276479Sdim      // it as it is unlikely a qualified version of the class' constructor
3995276479Sdim      // is an appropriate correction.
3996296417Sdim      if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
3997296417Sdim                                           nullptr) {
3998276479Sdim        if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
3999276479Sdim          continue;
4000276479Sdim      }
4001224145Sdim
4002276479Sdim      TypoCorrection TC(QR);
4003276479Sdim      TC.ClearCorrectionDecls();
4004276479Sdim      TC.setCorrectionSpecifier(NSI.NameSpecifier);
4005276479Sdim      TC.setQualifierDistance(NSI.EditDistance);
4006276479Sdim      TC.setCallbackDistance(0); // Reset the callback distance
4007224145Sdim
4008276479Sdim      // If the current correction candidate and namespace combination are
4009276479Sdim      // too far away from the original typo based on the normalized edit
4010276479Sdim      // distance, then skip performing a qualified name lookup.
4011276479Sdim      unsigned TmpED = TC.getEditDistance(true);
4012276479Sdim      if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4013276479Sdim          TypoLen / TmpED < 3)
4014276479Sdim        continue;
4015224145Sdim
4016276479Sdim      Result.clear();
4017276479Sdim      Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4018276479Sdim      if (!SemaRef.LookupQualifiedName(Result, Ctx))
4019276479Sdim        continue;
4020224145Sdim
4021276479Sdim      // Any corrections added below will be validated in subsequent
4022276479Sdim      // iterations of the main while() loop over the Consumer's contents.
4023276479Sdim      switch (Result.getResultKind()) {
4024276479Sdim      case LookupResult::Found:
4025276479Sdim      case LookupResult::FoundOverloaded: {
4026276479Sdim        if (SS && SS->isValid()) {
4027276479Sdim          std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4028276479Sdim          std::string OldQualified;
4029276479Sdim          llvm::raw_string_ostream OldOStream(OldQualified);
4030276479Sdim          SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4031276479Sdim          OldOStream << Typo->getName();
4032276479Sdim          // If correction candidate would be an identical written qualified
4033276479Sdim          // identifer, then the existing CXXScopeSpec probably included a
4034276479Sdim          // typedef that didn't get accounted for properly.
4035276479Sdim          if (OldOStream.str() == NewQualified)
4036276479Sdim            break;
4037276479Sdim        }
4038276479Sdim        for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4039276479Sdim             TRD != TRDEnd; ++TRD) {
4040276479Sdim          if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4041276479Sdim                                        NSType ? NSType->getAsCXXRecordDecl()
4042276479Sdim                                               : nullptr,
4043276479Sdim                                        TRD.getPair()) == Sema::AR_accessible)
4044276479Sdim            TC.addCorrectionDecl(*TRD);
4045276479Sdim        }
4046280031Sdim        if (TC.isResolved()) {
4047280031Sdim          TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4048276479Sdim          addCorrection(TC);
4049280031Sdim        }
4050276479Sdim        break;
4051276479Sdim      }
4052276479Sdim      case LookupResult::NotFound:
4053276479Sdim      case LookupResult::NotFoundInCurrentInstantiation:
4054276479Sdim      case LookupResult::Ambiguous:
4055276479Sdim      case LookupResult::FoundUnresolvedValue:
4056276479Sdim        break;
4057276479Sdim      }
4058261991Sdim    }
4059234353Sdim  }
4060276479Sdim  QualifiedResults.clear();
4061276479Sdim}
4062224145Sdim
4063276479SdimTypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4064276479Sdim    ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4065288943Sdim    : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4066276479Sdim  if (NestedNameSpecifier *NNS =
4067276479Sdim          CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4068276479Sdim    llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4069276479Sdim    NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4070224145Sdim
4071276479Sdim    getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4072224145Sdim  }
4073276479Sdim  // Build the list of identifiers that would be used for an absolute
4074276479Sdim  // (from the global context) NestedNameSpecifier referring to the current
4075276479Sdim  // context.
4076276479Sdim  for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4077276479Sdim                                         CEnd = CurContextChain.rend();
4078276479Sdim       C != CEnd; ++C) {
4079276479Sdim    if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
4080276479Sdim      CurContextIdentifiers.push_back(ND->getIdentifier());
4081276479Sdim  }
4082224145Sdim
4083276479Sdim  // Add the global context as a NestedNameSpecifier
4084276479Sdim  SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4085276479Sdim                      NestedNameSpecifier::GlobalSpecifier(Context), 1};
4086276479Sdim  DistanceMap[1].push_back(SI);
4087224145Sdim}
4088224145Sdim
4089276479Sdimauto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4090276479Sdim    DeclContext *Start) -> DeclContextList {
4091251662Sdim  assert(Start && "Building a context chain from a null context");
4092224145Sdim  DeclContextList Chain;
4093276479Sdim  for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4094224145Sdim       DC = DC->getLookupParent()) {
4095224145Sdim    NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4096224145Sdim    if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4097224145Sdim        !(ND && ND->isAnonymousNamespace()))
4098224145Sdim      Chain.push_back(DC->getPrimaryContext());
4099224145Sdim  }
4100224145Sdim  return Chain;
4101224145Sdim}
4102224145Sdim
4103276479Sdimunsigned
4104276479SdimTypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4105276479Sdim    DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4106261991Sdim  unsigned NumSpecifiers = 0;
4107261991Sdim  for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
4108261991Sdim                                      CEnd = DeclChain.rend();
4109261991Sdim       C != CEnd; ++C) {
4110261991Sdim    if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
4111261991Sdim      NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4112261991Sdim      ++NumSpecifiers;
4113261991Sdim    } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
4114261991Sdim      NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4115261991Sdim                                        RD->getTypeForDecl());
4116261991Sdim      ++NumSpecifiers;
4117261991Sdim    }
4118261991Sdim  }
4119261991Sdim  return NumSpecifiers;
4120261991Sdim}
4121261991Sdim
4122276479Sdimvoid TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4123276479Sdim    DeclContext *Ctx) {
4124276479Sdim  NestedNameSpecifier *NNS = nullptr;
4125224145Sdim  unsigned NumSpecifiers = 0;
4126276479Sdim  DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4127234353Sdim  DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4128224145Sdim
4129234353Sdim  // Eliminate common elements from the two DeclContext chains.
4130224145Sdim  for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
4131224145Sdim                                      CEnd = CurContextChain.rend();
4132224145Sdim       C != CEnd && !NamespaceDeclChain.empty() &&
4133224145Sdim       NamespaceDeclChain.back() == *C; ++C) {
4134224145Sdim    NamespaceDeclChain.pop_back();
4135224145Sdim  }
4136224145Sdim
4137261991Sdim  // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4138276479Sdim  NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4139261991Sdim
4140234353Sdim  // Add an explicit leading '::' specifier if needed.
4141261991Sdim  if (NamespaceDeclChain.empty()) {
4142261991Sdim    // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4143261991Sdim    NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4144261991Sdim    NumSpecifiers =
4145276479Sdim        buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4146261991Sdim  } else if (NamedDecl *ND =
4147261991Sdim                 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4148234353Sdim    IdentifierInfo *Name = ND->getIdentifier();
4149261991Sdim    bool SameNameSpecifier = false;
4150261991Sdim    if (std::find(CurNameSpecifierIdentifiers.begin(),
4151234353Sdim                  CurNameSpecifierIdentifiers.end(),
4152234353Sdim                  Name) != CurNameSpecifierIdentifiers.end()) {
4153261991Sdim      std::string NewNameSpecifier;
4154261991Sdim      llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4155261991Sdim      SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4156261991Sdim      getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4157261991Sdim      NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4158261991Sdim      SpecifierOStream.flush();
4159261991Sdim      SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4160261991Sdim    }
4161261991Sdim    if (SameNameSpecifier ||
4162261991Sdim        std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4163261991Sdim                  Name) != CurContextIdentifiers.end()) {
4164261991Sdim      // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4165234353Sdim      NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4166261991Sdim      NumSpecifiers =
4167276479Sdim          buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4168234353Sdim    }
4169234353Sdim  }
4170234353Sdim
4171234353Sdim  // If the built NestedNameSpecifier would be replacing an existing
4172234353Sdim  // NestedNameSpecifier, use the number of component identifiers that
4173234353Sdim  // would need to be changed as the edit distance instead of the number
4174234353Sdim  // of components in the built NestedNameSpecifier.
4175234353Sdim  if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4176234353Sdim    SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4177234353Sdim    getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4178234353Sdim    NumSpecifiers = llvm::ComputeEditDistance(
4179280031Sdim        llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4180280031Sdim        llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4181234353Sdim  }
4182234353Sdim
4183276479Sdim  SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4184276479Sdim  DistanceMap[NumSpecifiers].push_back(SI);
4185224145Sdim}
4186224145Sdim
4187218893Sdim/// \brief Perform name lookup for a possible result for typo correction.
4188218893Sdimstatic void LookupPotentialTypoResult(Sema &SemaRef,
4189218893Sdim                                      LookupResult &Res,
4190218893Sdim                                      IdentifierInfo *Name,
4191218893Sdim                                      Scope *S, CXXScopeSpec *SS,
4192218893Sdim                                      DeclContext *MemberContext,
4193218893Sdim                                      bool EnteringContext,
4194261991Sdim                                      bool isObjCIvarLookup,
4195261991Sdim                                      bool FindHidden) {
4196218893Sdim  Res.suppressDiagnostics();
4197218893Sdim  Res.clear();
4198218893Sdim  Res.setLookupName(Name);
4199261991Sdim  Res.setAllowHidden(FindHidden);
4200218893Sdim  if (MemberContext) {
4201218893Sdim    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4202234353Sdim      if (isObjCIvarLookup) {
4203218893Sdim        if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4204218893Sdim          Res.addDecl(Ivar);
4205218893Sdim          Res.resolveKind();
4206218893Sdim          return;
4207218893Sdim        }
4208218893Sdim      }
4209218893Sdim
4210218893Sdim      if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
4211218893Sdim        Res.addDecl(Prop);
4212218893Sdim        Res.resolveKind();
4213218893Sdim        return;
4214218893Sdim      }
4215218893Sdim    }
4216218893Sdim
4217218893Sdim    SemaRef.LookupQualifiedName(Res, MemberContext);
4218218893Sdim    return;
4219218893Sdim  }
4220218893Sdim
4221218893Sdim  SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4222218893Sdim                           EnteringContext);
4223218893Sdim
4224218893Sdim  // Fake ivar lookup; this should really be part of
4225218893Sdim  // LookupParsedName.
4226218893Sdim  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4227218893Sdim    if (Method->isInstanceMethod() && Method->getClassInterface() &&
4228218893Sdim        (Res.empty() ||
4229218893Sdim         (Res.isSingleResult() &&
4230218893Sdim          Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4231218893Sdim       if (ObjCIvarDecl *IV
4232218893Sdim             = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4233218893Sdim         Res.addDecl(IV);
4234218893Sdim         Res.resolveKind();
4235218893Sdim       }
4236218893Sdim     }
4237218893Sdim  }
4238218893Sdim}
4239218893Sdim
4240224145Sdim/// \brief Add keywords to the consumer as possible typo corrections.
4241224145Sdimstatic void AddKeywordsToConsumer(Sema &SemaRef,
4242224145Sdim                                  TypoCorrectionConsumer &Consumer,
4243239462Sdim                                  Scope *S, CorrectionCandidateCallback &CCC,
4244239462Sdim                                  bool AfterNestedNameSpecifier) {
4245239462Sdim  if (AfterNestedNameSpecifier) {
4246239462Sdim    // For 'X::', we know exactly which keywords can appear next.
4247239462Sdim    Consumer.addKeywordResult("template");
4248239462Sdim    if (CCC.WantExpressionKeywords)
4249239462Sdim      Consumer.addKeywordResult("operator");
4250239462Sdim    return;
4251239462Sdim  }
4252239462Sdim
4253234353Sdim  if (CCC.WantObjCSuper)
4254234353Sdim    Consumer.addKeywordResult("super");
4255224145Sdim
4256234353Sdim  if (CCC.WantTypeSpecifiers) {
4257224145Sdim    // Add type-specifier keywords to the set of results.
4258261991Sdim    static const char *const CTypeSpecs[] = {
4259224145Sdim      "char", "const", "double", "enum", "float", "int", "long", "short",
4260224145Sdim      "signed", "struct", "union", "unsigned", "void", "volatile",
4261224145Sdim      "_Complex", "_Imaginary",
4262224145Sdim      // storage-specifiers as well
4263224145Sdim      "extern", "inline", "static", "typedef"
4264224145Sdim    };
4265224145Sdim
4266261991Sdim    const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4267224145Sdim    for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4268224145Sdim      Consumer.addKeywordResult(CTypeSpecs[I]);
4269224145Sdim
4270234353Sdim    if (SemaRef.getLangOpts().C99)
4271224145Sdim      Consumer.addKeywordResult("restrict");
4272234353Sdim    if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
4273224145Sdim      Consumer.addKeywordResult("bool");
4274234353Sdim    else if (SemaRef.getLangOpts().C99)
4275224145Sdim      Consumer.addKeywordResult("_Bool");
4276224145Sdim
4277234353Sdim    if (SemaRef.getLangOpts().CPlusPlus) {
4278224145Sdim      Consumer.addKeywordResult("class");
4279224145Sdim      Consumer.addKeywordResult("typename");
4280224145Sdim      Consumer.addKeywordResult("wchar_t");
4281224145Sdim
4282249423Sdim      if (SemaRef.getLangOpts().CPlusPlus11) {
4283224145Sdim        Consumer.addKeywordResult("char16_t");
4284224145Sdim        Consumer.addKeywordResult("char32_t");
4285224145Sdim        Consumer.addKeywordResult("constexpr");
4286224145Sdim        Consumer.addKeywordResult("decltype");
4287224145Sdim        Consumer.addKeywordResult("thread_local");
4288224145Sdim      }
4289224145Sdim    }
4290224145Sdim
4291234353Sdim    if (SemaRef.getLangOpts().GNUMode)
4292224145Sdim      Consumer.addKeywordResult("typeof");
4293280031Sdim  } else if (CCC.WantFunctionLikeCasts) {
4294280031Sdim    static const char *const CastableTypeSpecs[] = {
4295280031Sdim      "char", "double", "float", "int", "long", "short",
4296280031Sdim      "signed", "unsigned", "void"
4297280031Sdim    };
4298280031Sdim    for (auto *kw : CastableTypeSpecs)
4299280031Sdim      Consumer.addKeywordResult(kw);
4300224145Sdim  }
4301224145Sdim
4302234353Sdim  if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
4303224145Sdim    Consumer.addKeywordResult("const_cast");
4304224145Sdim    Consumer.addKeywordResult("dynamic_cast");
4305224145Sdim    Consumer.addKeywordResult("reinterpret_cast");
4306224145Sdim    Consumer.addKeywordResult("static_cast");
4307224145Sdim  }
4308224145Sdim
4309234353Sdim  if (CCC.WantExpressionKeywords) {
4310224145Sdim    Consumer.addKeywordResult("sizeof");
4311234353Sdim    if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
4312224145Sdim      Consumer.addKeywordResult("false");
4313224145Sdim      Consumer.addKeywordResult("true");
4314224145Sdim    }
4315224145Sdim
4316234353Sdim    if (SemaRef.getLangOpts().CPlusPlus) {
4317261991Sdim      static const char *const CXXExprs[] = {
4318224145Sdim        "delete", "new", "operator", "throw", "typeid"
4319224145Sdim      };
4320261991Sdim      const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4321224145Sdim      for (unsigned I = 0; I != NumCXXExprs; ++I)
4322224145Sdim        Consumer.addKeywordResult(CXXExprs[I]);
4323224145Sdim
4324224145Sdim      if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4325224145Sdim          cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4326224145Sdim        Consumer.addKeywordResult("this");
4327224145Sdim
4328249423Sdim      if (SemaRef.getLangOpts().CPlusPlus11) {
4329224145Sdim        Consumer.addKeywordResult("alignof");
4330224145Sdim        Consumer.addKeywordResult("nullptr");
4331224145Sdim      }
4332224145Sdim    }
4333239462Sdim
4334239462Sdim    if (SemaRef.getLangOpts().C11) {
4335239462Sdim      // FIXME: We should not suggest _Alignof if the alignof macro
4336239462Sdim      // is present.
4337239462Sdim      Consumer.addKeywordResult("_Alignof");
4338239462Sdim    }
4339224145Sdim  }
4340224145Sdim
4341234353Sdim  if (CCC.WantRemainingKeywords) {
4342224145Sdim    if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4343224145Sdim      // Statements.
4344261991Sdim      static const char *const CStmts[] = {
4345224145Sdim        "do", "else", "for", "goto", "if", "return", "switch", "while" };
4346261991Sdim      const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4347224145Sdim      for (unsigned I = 0; I != NumCStmts; ++I)
4348224145Sdim        Consumer.addKeywordResult(CStmts[I]);
4349224145Sdim
4350234353Sdim      if (SemaRef.getLangOpts().CPlusPlus) {
4351224145Sdim        Consumer.addKeywordResult("catch");
4352224145Sdim        Consumer.addKeywordResult("try");
4353224145Sdim      }
4354224145Sdim
4355224145Sdim      if (S && S->getBreakParent())
4356224145Sdim        Consumer.addKeywordResult("break");
4357224145Sdim
4358224145Sdim      if (S && S->getContinueParent())
4359224145Sdim        Consumer.addKeywordResult("continue");
4360224145Sdim
4361224145Sdim      if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4362224145Sdim        Consumer.addKeywordResult("case");
4363224145Sdim        Consumer.addKeywordResult("default");
4364224145Sdim      }
4365224145Sdim    } else {
4366234353Sdim      if (SemaRef.getLangOpts().CPlusPlus) {
4367224145Sdim        Consumer.addKeywordResult("namespace");
4368224145Sdim        Consumer.addKeywordResult("template");
4369224145Sdim      }
4370224145Sdim
4371224145Sdim      if (S && S->isClassScope()) {
4372224145Sdim        Consumer.addKeywordResult("explicit");
4373224145Sdim        Consumer.addKeywordResult("friend");
4374224145Sdim        Consumer.addKeywordResult("mutable");
4375224145Sdim        Consumer.addKeywordResult("private");
4376224145Sdim        Consumer.addKeywordResult("protected");
4377224145Sdim        Consumer.addKeywordResult("public");
4378224145Sdim        Consumer.addKeywordResult("virtual");
4379224145Sdim      }
4380224145Sdim    }
4381224145Sdim
4382234353Sdim    if (SemaRef.getLangOpts().CPlusPlus) {
4383224145Sdim      Consumer.addKeywordResult("using");
4384224145Sdim
4385249423Sdim      if (SemaRef.getLangOpts().CPlusPlus11)
4386224145Sdim        Consumer.addKeywordResult("static_assert");
4387224145Sdim    }
4388224145Sdim  }
4389224145Sdim}
4390224145Sdim
4391280031Sdimstd::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4392280031Sdim    const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4393280031Sdim    Scope *S, CXXScopeSpec *SS,
4394280031Sdim    std::unique_ptr<CorrectionCandidateCallback> CCC,
4395280031Sdim    DeclContext *MemberContext, bool EnteringContext,
4396280031Sdim    const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
4397261991Sdim
4398261991Sdim  if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4399261991Sdim      DisableTypoCorrection)
4400280031Sdim    return nullptr;
4401203955Srdivacky
4402234353Sdim  // In Microsoft mode, don't perform typo correction in a template member
4403234353Sdim  // function dependent context because it interferes with the "lookup into
4404234353Sdim  // dependent bases of class templates" feature.
4405276479Sdim  if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4406234353Sdim      isa<CXXMethodDecl>(CurContext))
4407280031Sdim    return nullptr;
4408234353Sdim
4409201361Srdivacky  // We only attempt to correct typos for identifiers.
4410224145Sdim  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4411201361Srdivacky  if (!Typo)
4412280031Sdim    return nullptr;
4413201361Srdivacky
4414201361Srdivacky  // If the scope specifier itself was invalid, don't try to correct
4415201361Srdivacky  // typos.
4416201361Srdivacky  if (SS && SS->isInvalid())
4417280031Sdim    return nullptr;
4418201361Srdivacky
4419201361Srdivacky  // Never try to correct typos during template deduction or
4420201361Srdivacky  // instantiation.
4421201361Srdivacky  if (!ActiveTemplateInstantiations.empty())
4422280031Sdim    return nullptr;
4423218893Sdim
4424249423Sdim  // Don't try to correct 'super'.
4425249423Sdim  if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4426280031Sdim    return nullptr;
4427249423Sdim
4428261991Sdim  // Abort if typo correction already failed for this specific typo.
4429261991Sdim  IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4430261991Sdim  if (locs != TypoCorrectionFailures.end() &&
4431261991Sdim      locs->second.count(TypoName.getLoc()))
4432280031Sdim    return nullptr;
4433261991Sdim
4434261991Sdim  // Don't try to correct the identifier "vector" when in AltiVec mode.
4435261991Sdim  // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4436261991Sdim  // remove this workaround.
4437288943Sdim  if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
4438280031Sdim    return nullptr;
4439261991Sdim
4440280031Sdim  // Provide a stop gap for files that are just seriously broken.  Trying
4441280031Sdim  // to correct all typos can turn into a HUGE performance penalty, causing
4442280031Sdim  // some files to take minutes to get rejected by the parser.
4443280031Sdim  unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4444280031Sdim  if (Limit && TyposCorrected >= Limit)
4445280031Sdim    return nullptr;
4446280031Sdim  ++TyposCorrected;
4447280031Sdim
4448276479Sdim  // If we're handling a missing symbol error, using modules, and the
4449276479Sdim  // special search all modules option is used, look for a missing import.
4450280031Sdim  if (ErrorRecovery && getLangOpts().Modules &&
4451276479Sdim      getLangOpts().ModulesSearchAll) {
4452276479Sdim    // The following has the side effect of loading the missing module.
4453276479Sdim    getModuleLoader().lookupMissingImports(Typo->getName(),
4454276479Sdim                                           TypoName.getLocStart());
4455276479Sdim  }
4456218893Sdim
4457280031Sdim  CorrectionCandidateCallback &CCCRef = *CCC;
4458280031Sdim  auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4459280031Sdim      *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4460280031Sdim      EnteringContext);
4461224145Sdim
4462207619Srdivacky  // Perform name lookup to find visible, similarly-named entities.
4463218893Sdim  bool IsUnqualifiedLookup = false;
4464234353Sdim  DeclContext *QualifiedDC = MemberContext;
4465202379Srdivacky  if (MemberContext) {
4466280031Sdim    LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4467202379Srdivacky
4468202379Srdivacky    // Look in qualified interfaces.
4469202379Srdivacky    if (OPT) {
4470276479Sdim      for (auto *I : OPT->quals())
4471280031Sdim        LookupVisibleDecls(I, LookupKind, *Consumer);
4472202379Srdivacky    }
4473202379Srdivacky  } else if (SS && SS->isSet()) {
4474234353Sdim    QualifiedDC = computeDeclContext(*SS, EnteringContext);
4475234353Sdim    if (!QualifiedDC)
4476280031Sdim      return nullptr;
4477218893Sdim
4478280031Sdim    LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4479201361Srdivacky  } else {
4480218893Sdim    IsUnqualifiedLookup = true;
4481234353Sdim  }
4482218893Sdim
4483234353Sdim  // Determine whether we are going to search in the various namespaces for
4484234353Sdim  // corrections.
4485234353Sdim  bool SearchNamespaces
4486234353Sdim    = getLangOpts().CPlusPlus &&
4487261991Sdim      (IsUnqualifiedLookup || (SS && SS->isSet()));
4488261991Sdim
4489234353Sdim  if (IsUnqualifiedLookup || SearchNamespaces) {
4490234353Sdim    // For unqualified lookup, look through all of the names that we have
4491234353Sdim    // seen in this translation unit.
4492234353Sdim    // FIXME: Re-add the ability to skip very unlikely potential corrections.
4493276479Sdim    for (const auto &I : Context.Idents)
4494280031Sdim      Consumer->FoundName(I.getKey());
4495218893Sdim
4496234353Sdim    // Walk through identifiers in external identifier sources.
4497234353Sdim    // FIXME: Re-add the ability to skip very unlikely potential corrections.
4498234353Sdim    if (IdentifierInfoLookup *External
4499234353Sdim                            = Context.Idents.getExternalIdentifierLookup()) {
4500276479Sdim      std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4501234353Sdim      do {
4502234353Sdim        StringRef Name = Iter->Next();
4503234353Sdim        if (Name.empty())
4504234353Sdim          break;
4505218893Sdim
4506280031Sdim        Consumer->FoundName(Name);
4507234353Sdim      } while (true);
4508218893Sdim    }
4509201361Srdivacky  }
4510201361Srdivacky
4511280031Sdim  AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4512218893Sdim
4513234353Sdim  // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4514234353Sdim  // to search those namespaces.
4515234353Sdim  if (SearchNamespaces) {
4516224145Sdim    // Load any externally-known namespaces.
4517224145Sdim    if (ExternalSource && !LoadedExternalKnownNamespaces) {
4518226633Sdim      SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4519224145Sdim      LoadedExternalKnownNamespaces = true;
4520224145Sdim      ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4521276479Sdim      for (auto *N : ExternalKnownNamespaces)
4522276479Sdim        KnownNamespaces[N] = true;
4523207619Srdivacky    }
4524261991Sdim
4525280031Sdim    Consumer->addNamespaces(KnownNamespaces);
4526207619Srdivacky  }
4527218893Sdim
4528280031Sdim  return Consumer;
4529280031Sdim}
4530280031Sdim
4531280031Sdim/// \brief Try to "correct" a typo in the source code by finding
4532280031Sdim/// visible declarations whose names are similar to the name that was
4533280031Sdim/// present in the source code.
4534280031Sdim///
4535280031Sdim/// \param TypoName the \c DeclarationNameInfo structure that contains
4536280031Sdim/// the name that was present in the source code along with its location.
4537280031Sdim///
4538280031Sdim/// \param LookupKind the name-lookup criteria used to search for the name.
4539280031Sdim///
4540280031Sdim/// \param S the scope in which name lookup occurs.
4541280031Sdim///
4542280031Sdim/// \param SS the nested-name-specifier that precedes the name we're
4543280031Sdim/// looking for, if present.
4544280031Sdim///
4545280031Sdim/// \param CCC A CorrectionCandidateCallback object that provides further
4546280031Sdim/// validation of typo correction candidates. It also provides flags for
4547280031Sdim/// determining the set of keywords permitted.
4548280031Sdim///
4549280031Sdim/// \param MemberContext if non-NULL, the context in which to look for
4550280031Sdim/// a member access expression.
4551280031Sdim///
4552280031Sdim/// \param EnteringContext whether we're entering the context described by
4553280031Sdim/// the nested-name-specifier SS.
4554280031Sdim///
4555280031Sdim/// \param OPT when non-NULL, the search for visible declarations will
4556280031Sdim/// also walk the protocols in the qualified interfaces of \p OPT.
4557280031Sdim///
4558280031Sdim/// \returns a \c TypoCorrection containing the corrected name if the typo
4559280031Sdim/// along with information such as the \c NamedDecl where the corrected name
4560280031Sdim/// was declared, and any additional \c NestedNameSpecifier needed to access
4561280031Sdim/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4562280031SdimTypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4563280031Sdim                                 Sema::LookupNameKind LookupKind,
4564280031Sdim                                 Scope *S, CXXScopeSpec *SS,
4565280031Sdim                                 std::unique_ptr<CorrectionCandidateCallback> CCC,
4566280031Sdim                                 CorrectTypoKind Mode,
4567280031Sdim                                 DeclContext *MemberContext,
4568280031Sdim                                 bool EnteringContext,
4569280031Sdim                                 const ObjCObjectPointerType *OPT,
4570280031Sdim                                 bool RecordFailure) {
4571280031Sdim  assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4572280031Sdim
4573280031Sdim  // Always let the ExternalSource have the first chance at correction, even
4574280031Sdim  // if we would otherwise have given up.
4575280031Sdim  if (ExternalSource) {
4576280031Sdim    if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4577280031Sdim        TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
4578280031Sdim      return Correction;
4579280031Sdim  }
4580280031Sdim
4581280031Sdim  // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4582280031Sdim  // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4583280031Sdim  // some instances of CTC_Unknown, while WantRemainingKeywords is true
4584280031Sdim  // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4585280031Sdim  bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
4586280031Sdim
4587280031Sdim  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4588280031Sdim  auto Consumer = makeTypoCorrectionConsumer(
4589280031Sdim      TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4590280031Sdim      EnteringContext, OPT, Mode == CTK_ErrorRecovery);
4591280031Sdim
4592280031Sdim  if (!Consumer)
4593280031Sdim    return TypoCorrection();
4594280031Sdim
4595280031Sdim  // If we haven't found anything, we're done.
4596280031Sdim  if (Consumer->empty())
4597280031Sdim    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4598280031Sdim
4599280031Sdim  // Make sure the best edit distance (prior to adding any namespace qualifiers)
4600280031Sdim  // is not more that about a third of the length of the typo's identifier.
4601280031Sdim  unsigned ED = Consumer->getBestEditDistance(true);
4602280031Sdim  unsigned TypoLen = Typo->getName().size();
4603280031Sdim  if (ED > 0 && TypoLen / ED < 3)
4604280031Sdim    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4605280031Sdim
4606280031Sdim  TypoCorrection BestTC = Consumer->getNextCorrection();
4607280031Sdim  TypoCorrection SecondBestTC = Consumer->getNextCorrection();
4608276479Sdim  if (!BestTC)
4609261991Sdim    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4610218893Sdim
4611276479Sdim  ED = BestTC.getEditDistance();
4612201361Srdivacky
4613280031Sdim  if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
4614234353Sdim    // If this was an unqualified lookup and we believe the callback
4615234353Sdim    // object wouldn't have filtered out possible corrections, note
4616234353Sdim    // that no correction was found.
4617280031Sdim    return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4618218893Sdim  }
4619218893Sdim
4620218893Sdim  // If only a single name remains, return that result.
4621276479Sdim  if (!SecondBestTC ||
4622276479Sdim      SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4623276479Sdim    const TypoCorrection &Result = BestTC;
4624218893Sdim
4625224145Sdim    // Don't correct to a keyword that's the same as the typo; the keyword
4626224145Sdim    // wasn't actually in scope.
4627261991Sdim    if (ED == 0 && Result.isKeyword())
4628261991Sdim      return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4629218893Sdim
4630243830Sdim    TypoCorrection TC = Result;
4631243830Sdim    TC.setCorrectionRange(SS, TypoName);
4632276479Sdim    checkCorrectionVisibility(*this, TC);
4633243830Sdim    return TC;
4634280031Sdim  } else if (SecondBestTC && ObjCMessageReceiver) {
4635224145Sdim    // Prefer 'super' when we're completing in a message-receiver
4636218893Sdim    // context.
4637201361Srdivacky
4638276479Sdim    if (BestTC.getCorrection().getAsString() != "super") {
4639276479Sdim      if (SecondBestTC.getCorrection().getAsString() == "super")
4640276479Sdim        BestTC = SecondBestTC;
4641280031Sdim      else if ((*Consumer)["super"].front().isKeyword())
4642280031Sdim        BestTC = (*Consumer)["super"].front();
4643276479Sdim    }
4644218893Sdim    // Don't correct to a keyword that's the same as the typo; the keyword
4645218893Sdim    // wasn't actually in scope.
4646276479Sdim    if (BestTC.getEditDistance() == 0 ||
4647276479Sdim        BestTC.getCorrection().getAsString() != "super")
4648261991Sdim      return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4649202379Srdivacky
4650276479Sdim    BestTC.setCorrectionRange(SS, TypoName);
4651276479Sdim    return BestTC;
4652201361Srdivacky  }
4653201361Srdivacky
4654276479Sdim  // Record the failure's location if needed and return an empty correction. If
4655276479Sdim  // this was an unqualified lookup and we believe the callback object did not
4656276479Sdim  // filter out possible corrections, also cache the failure for the typo.
4657288943Sdim  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
4658201361Srdivacky}
4659224145Sdim
4660280031Sdim/// \brief Try to "correct" a typo in the source code by finding
4661280031Sdim/// visible declarations whose names are similar to the name that was
4662280031Sdim/// present in the source code.
4663280031Sdim///
4664280031Sdim/// \param TypoName the \c DeclarationNameInfo structure that contains
4665280031Sdim/// the name that was present in the source code along with its location.
4666280031Sdim///
4667280031Sdim/// \param LookupKind the name-lookup criteria used to search for the name.
4668280031Sdim///
4669280031Sdim/// \param S the scope in which name lookup occurs.
4670280031Sdim///
4671280031Sdim/// \param SS the nested-name-specifier that precedes the name we're
4672280031Sdim/// looking for, if present.
4673280031Sdim///
4674280031Sdim/// \param CCC A CorrectionCandidateCallback object that provides further
4675280031Sdim/// validation of typo correction candidates. It also provides flags for
4676280031Sdim/// determining the set of keywords permitted.
4677280031Sdim///
4678280031Sdim/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4679280031Sdim/// diagnostics when the actual typo correction is attempted.
4680280031Sdim///
4681280031Sdim/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4682280031Sdim/// Expr from a typo correction candidate.
4683280031Sdim///
4684280031Sdim/// \param MemberContext if non-NULL, the context in which to look for
4685280031Sdim/// a member access expression.
4686280031Sdim///
4687280031Sdim/// \param EnteringContext whether we're entering the context described by
4688280031Sdim/// the nested-name-specifier SS.
4689280031Sdim///
4690280031Sdim/// \param OPT when non-NULL, the search for visible declarations will
4691280031Sdim/// also walk the protocols in the qualified interfaces of \p OPT.
4692280031Sdim///
4693280031Sdim/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4694280031Sdim/// Expr representing the result of performing typo correction, or nullptr if
4695280031Sdim/// typo correction is not possible. If nullptr is returned, no diagnostics will
4696280031Sdim/// be emitted and it is the responsibility of the caller to emit any that are
4697280031Sdim/// needed.
4698280031SdimTypoExpr *Sema::CorrectTypoDelayed(
4699280031Sdim    const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4700280031Sdim    Scope *S, CXXScopeSpec *SS,
4701280031Sdim    std::unique_ptr<CorrectionCandidateCallback> CCC,
4702280031Sdim    TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4703280031Sdim    DeclContext *MemberContext, bool EnteringContext,
4704280031Sdim    const ObjCObjectPointerType *OPT) {
4705280031Sdim  assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4706280031Sdim
4707280031Sdim  TypoCorrection Empty;
4708280031Sdim  auto Consumer = makeTypoCorrectionConsumer(
4709280031Sdim      TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4710288943Sdim      EnteringContext, OPT, Mode == CTK_ErrorRecovery);
4711280031Sdim
4712280031Sdim  if (!Consumer || Consumer->empty())
4713280031Sdim    return nullptr;
4714280031Sdim
4715280031Sdim  // Make sure the best edit distance (prior to adding any namespace qualifiers)
4716280031Sdim  // is not more that about a third of the length of the typo's identifier.
4717280031Sdim  unsigned ED = Consumer->getBestEditDistance(true);
4718280031Sdim  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4719280031Sdim  if (ED > 0 && Typo->getName().size() / ED < 3)
4720280031Sdim    return nullptr;
4721280031Sdim
4722280031Sdim  ExprEvalContexts.back().NumTypos++;
4723280031Sdim  return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
4724280031Sdim}
4725280031Sdim
4726226633Sdimvoid TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4727226633Sdim  if (!CDecl) return;
4728226633Sdim
4729226633Sdim  if (isKeyword())
4730226633Sdim    CorrectionDecls.clear();
4731226633Sdim
4732296417Sdim  CorrectionDecls.push_back(CDecl);
4733226633Sdim
4734226633Sdim  if (!CorrectionName)
4735226633Sdim    CorrectionName = CDecl->getDeclName();
4736226633Sdim}
4737226633Sdim
4738224145Sdimstd::string TypoCorrection::getAsString(const LangOptions &LO) const {
4739224145Sdim  if (CorrectionNameSpec) {
4740224145Sdim    std::string tmpBuffer;
4741224145Sdim    llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4742224145Sdim    CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4743261991Sdim    PrefixOStream << CorrectionName;
4744234982Sdim    return PrefixOStream.str();
4745224145Sdim  }
4746224145Sdim
4747224145Sdim  return CorrectionName.getAsString();
4748224145Sdim}
4749249423Sdim
4750280031Sdimbool CorrectionCandidateCallback::ValidateCandidate(
4751280031Sdim    const TypoCorrection &candidate) {
4752249423Sdim  if (!candidate.isResolved())
4753249423Sdim    return true;
4754249423Sdim
4755249423Sdim  if (candidate.isKeyword())
4756249423Sdim    return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4757249423Sdim           WantRemainingKeywords || WantObjCSuper;
4758249423Sdim
4759276479Sdim  bool HasNonType = false;
4760276479Sdim  bool HasStaticMethod = false;
4761276479Sdim  bool HasNonStaticMethod = false;
4762276479Sdim  for (Decl *D : candidate) {
4763276479Sdim    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4764276479Sdim      D = FTD->getTemplatedDecl();
4765276479Sdim    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4766276479Sdim      if (Method->isStatic())
4767276479Sdim        HasStaticMethod = true;
4768276479Sdim      else
4769276479Sdim        HasNonStaticMethod = true;
4770276479Sdim    }
4771276479Sdim    if (!isa<TypeDecl>(D))
4772276479Sdim      HasNonType = true;
4773249423Sdim  }
4774249423Sdim
4775276479Sdim  if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4776276479Sdim      !candidate.getCorrectionSpecifier())
4777276479Sdim    return false;
4778276479Sdim
4779276479Sdim  return WantTypeSpecifiers || HasNonType;
4780249423Sdim}
4781261991Sdim
4782261991SdimFunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4783276479Sdim                                             bool HasExplicitTemplateArgs,
4784276479Sdim                                             MemberExpr *ME)
4785276479Sdim    : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
4786276479Sdim      CurContext(SemaRef.CurContext), MemberFn(ME) {
4787280031Sdim  WantTypeSpecifiers = false;
4788280031Sdim  WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
4789261991Sdim  WantRemainingKeywords = false;
4790261991Sdim}
4791261991Sdim
4792261991Sdimbool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4793261991Sdim  if (!candidate.getCorrectionDecl())
4794261991Sdim    return candidate.isKeyword();
4795261991Sdim
4796276479Sdim  for (auto *C : candidate) {
4797276479Sdim    FunctionDecl *FD = nullptr;
4798276479Sdim    NamedDecl *ND = C->getUnderlyingDecl();
4799261991Sdim    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4800261991Sdim      FD = FTD->getTemplatedDecl();
4801261991Sdim    if (!HasExplicitTemplateArgs && !FD) {
4802261991Sdim      if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4803261991Sdim        // If the Decl is neither a function nor a template function,
4804261991Sdim        // determine if it is a pointer or reference to a function. If so,
4805261991Sdim        // check against the number of arguments expected for the pointee.
4806261991Sdim        QualType ValType = cast<ValueDecl>(ND)->getType();
4807261991Sdim        if (ValType->isAnyPointerType() || ValType->isReferenceType())
4808261991Sdim          ValType = ValType->getPointeeType();
4809261991Sdim        if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4810276479Sdim          if (FPT->getNumParams() == NumArgs)
4811261991Sdim            return true;
4812261991Sdim      }
4813261991Sdim    }
4814276479Sdim
4815276479Sdim    // Skip the current candidate if it is not a FunctionDecl or does not accept
4816276479Sdim    // the current number of arguments.
4817276479Sdim    if (!FD || !(FD->getNumParams() >= NumArgs &&
4818276479Sdim                 FD->getMinRequiredArguments() <= NumArgs))
4819276479Sdim      continue;
4820276479Sdim
4821276479Sdim    // If the current candidate is a non-static C++ method, skip the candidate
4822276479Sdim    // unless the method being corrected--or the current DeclContext, if the
4823276479Sdim    // function being corrected is not a method--is a method in the same class
4824276479Sdim    // or a descendent class of the candidate's parent class.
4825276479Sdim    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4826276479Sdim      if (MemberFn || !MD->isStatic()) {
4827276479Sdim        CXXMethodDecl *CurMD =
4828276479Sdim            MemberFn
4829276479Sdim                ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4830276479Sdim                : dyn_cast_or_null<CXXMethodDecl>(CurContext);
4831276479Sdim        CXXRecordDecl *CurRD =
4832276479Sdim            CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
4833276479Sdim        CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4834276479Sdim        if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4835276479Sdim          continue;
4836276479Sdim      }
4837276479Sdim    }
4838276479Sdim    return true;
4839261991Sdim  }
4840261991Sdim  return false;
4841261991Sdim}
4842261991Sdim
4843261991Sdimvoid Sema::diagnoseTypo(const TypoCorrection &Correction,
4844261991Sdim                        const PartialDiagnostic &TypoDiag,
4845261991Sdim                        bool ErrorRecovery) {
4846261991Sdim  diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4847261991Sdim               ErrorRecovery);
4848261991Sdim}
4849261991Sdim
4850261991Sdim/// Find which declaration we should import to provide the definition of
4851261991Sdim/// the given declaration.
4852288943Sdimstatic NamedDecl *getDefinitionToImport(NamedDecl *D) {
4853288943Sdim  if (VarDecl *VD = dyn_cast<VarDecl>(D))
4854261991Sdim    return VD->getDefinition();
4855261991Sdim  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4856288943Sdim    return FD->isDefined(FD) ? const_cast<FunctionDecl*>(FD) : nullptr;
4857288943Sdim  if (TagDecl *TD = dyn_cast<TagDecl>(D))
4858261991Sdim    return TD->getDefinition();
4859288943Sdim  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4860261991Sdim    return ID->getDefinition();
4861288943Sdim  if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4862261991Sdim    return PD->getDefinition();
4863288943Sdim  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4864261991Sdim    return getDefinitionToImport(TD->getTemplatedDecl());
4865276479Sdim  return nullptr;
4866261991Sdim}
4867261991Sdim
4868288943Sdimvoid Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
4869288943Sdim                                 bool NeedDefinition, bool Recover) {
4870288943Sdim  assert(!isVisible(Decl) && "missing import for non-hidden decl?");
4871288943Sdim
4872288943Sdim  // Suggest importing a module providing the definition of this entity, if
4873288943Sdim  // possible.
4874288943Sdim  NamedDecl *Def = getDefinitionToImport(Decl);
4875288943Sdim  if (!Def)
4876288943Sdim    Def = Decl;
4877288943Sdim
4878288943Sdim  // FIXME: Add a Fix-It that imports the corresponding module or includes
4879288943Sdim  // the header.
4880288943Sdim  Module *Owner = getOwningModule(Decl);
4881288943Sdim  assert(Owner && "definition of hidden declaration is not in a module");
4882288943Sdim
4883288943Sdim  llvm::SmallVector<Module*, 8> OwningModules;
4884288943Sdim  OwningModules.push_back(Owner);
4885288943Sdim  auto Merged = Context.getModulesWithMergedDefinition(Decl);
4886288943Sdim  OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
4887288943Sdim
4888288943Sdim  diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules,
4889288943Sdim                        NeedDefinition ? MissingImportKind::Definition
4890288943Sdim                                       : MissingImportKind::Declaration,
4891288943Sdim                        Recover);
4892288943Sdim}
4893288943Sdim
4894288943Sdimvoid Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
4895288943Sdim                                 SourceLocation DeclLoc,
4896288943Sdim                                 ArrayRef<Module *> Modules,
4897288943Sdim                                 MissingImportKind MIK, bool Recover) {
4898288943Sdim  assert(!Modules.empty());
4899288943Sdim
4900288943Sdim  if (Modules.size() > 1) {
4901288943Sdim    std::string ModuleList;
4902288943Sdim    unsigned N = 0;
4903288943Sdim    for (Module *M : Modules) {
4904288943Sdim      ModuleList += "\n        ";
4905288943Sdim      if (++N == 5 && N != Modules.size()) {
4906288943Sdim        ModuleList += "[...]";
4907288943Sdim        break;
4908288943Sdim      }
4909288943Sdim      ModuleList += M->getFullModuleName();
4910288943Sdim    }
4911288943Sdim
4912288943Sdim    Diag(UseLoc, diag::err_module_unimported_use_multiple)
4913288943Sdim      << (int)MIK << Decl << ModuleList;
4914288943Sdim  } else {
4915288943Sdim    Diag(UseLoc, diag::err_module_unimported_use)
4916288943Sdim      << (int)MIK << Decl << Modules[0]->getFullModuleName();
4917288943Sdim  }
4918288943Sdim
4919288943Sdim  unsigned DiagID;
4920288943Sdim  switch (MIK) {
4921288943Sdim  case MissingImportKind::Declaration:
4922288943Sdim    DiagID = diag::note_previous_declaration;
4923288943Sdim    break;
4924288943Sdim  case MissingImportKind::Definition:
4925288943Sdim    DiagID = diag::note_previous_definition;
4926288943Sdim    break;
4927288943Sdim  case MissingImportKind::DefaultArgument:
4928288943Sdim    DiagID = diag::note_default_argument_declared_here;
4929288943Sdim    break;
4930288943Sdim  }
4931288943Sdim  Diag(DeclLoc, DiagID);
4932288943Sdim
4933288943Sdim  // Try to recover by implicitly importing this module.
4934288943Sdim  if (Recover)
4935288943Sdim    createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
4936288943Sdim}
4937288943Sdim
4938261991Sdim/// \brief Diagnose a successfully-corrected typo. Separated from the correction
4939261991Sdim/// itself to allow external validation of the result, etc.
4940261991Sdim///
4941261991Sdim/// \param Correction The result of performing typo correction.
4942261991Sdim/// \param TypoDiag The diagnostic to produce. This will have the corrected
4943261991Sdim///        string added to it (and usually also a fixit).
4944261991Sdim/// \param PrevNote A note to use when indicating the location of the entity to
4945261991Sdim///        which we are correcting. Will have the correction string added to it.
4946261991Sdim/// \param ErrorRecovery If \c true (the default), the caller is going to
4947261991Sdim///        recover from the typo as if the corrected string had been typed.
4948261991Sdim///        In this case, \c PDiag must be an error, and we will attach a fixit
4949261991Sdim///        to it.
4950261991Sdimvoid Sema::diagnoseTypo(const TypoCorrection &Correction,
4951261991Sdim                        const PartialDiagnostic &TypoDiag,
4952261991Sdim                        const PartialDiagnostic &PrevNote,
4953261991Sdim                        bool ErrorRecovery) {
4954261991Sdim  std::string CorrectedStr = Correction.getAsString(getLangOpts());
4955261991Sdim  std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4956261991Sdim  FixItHint FixTypo = FixItHint::CreateReplacement(
4957261991Sdim      Correction.getCorrectionRange(), CorrectedStr);
4958261991Sdim
4959261991Sdim  // Maybe we're just missing a module import.
4960261991Sdim  if (Correction.requiresImport()) {
4961296417Sdim    NamedDecl *Decl = Correction.getFoundDecl();
4962261991Sdim    assert(Decl && "import required but no declaration to import");
4963261991Sdim
4964288943Sdim    diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
4965288943Sdim                          /*NeedDefinition*/ false, ErrorRecovery);
4966261991Sdim    return;
4967261991Sdim  }
4968261991Sdim
4969261991Sdim  Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4970261991Sdim    << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4971261991Sdim
4972261991Sdim  NamedDecl *ChosenDecl =
4973296417Sdim      Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
4974261991Sdim  if (PrevNote.getDiagID() && ChosenDecl)
4975261991Sdim    Diag(ChosenDecl->getLocation(), PrevNote)
4976261991Sdim      << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
4977261991Sdim}
4978280031Sdim
4979280031SdimTypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4980280031Sdim                                  TypoDiagnosticGenerator TDG,
4981280031Sdim                                  TypoRecoveryCallback TRC) {
4982280031Sdim  assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
4983280031Sdim  auto TE = new (Context) TypoExpr(Context.DependentTy);
4984280031Sdim  auto &State = DelayedTypos[TE];
4985280031Sdim  State.Consumer = std::move(TCC);
4986280031Sdim  State.DiagHandler = std::move(TDG);
4987280031Sdim  State.RecoveryHandler = std::move(TRC);
4988280031Sdim  return TE;
4989280031Sdim}
4990280031Sdim
4991280031Sdimconst Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
4992280031Sdim  auto Entry = DelayedTypos.find(TE);
4993280031Sdim  assert(Entry != DelayedTypos.end() &&
4994280031Sdim         "Failed to get the state for a TypoExpr!");
4995280031Sdim  return Entry->second;
4996280031Sdim}
4997280031Sdim
4998280031Sdimvoid Sema::clearDelayedTypo(TypoExpr *TE) {
4999280031Sdim  DelayedTypos.erase(TE);
5000280031Sdim}
5001296417Sdim
5002296417Sdimvoid Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5003296417Sdim  DeclarationNameInfo Name(II, IILoc);
5004296417Sdim  LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5005296417Sdim  R.suppressDiagnostics();
5006296417Sdim  R.setHideTags(false);
5007296417Sdim  LookupName(R, S);
5008296417Sdim  R.dump();
5009296417Sdim}
5010