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