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