clang  9.0.0svn
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  bool addClassTransitive(CXXRecordDecl *RD) {
2421  Classes.insert(RD);
2422  return ClassesTransitive.insert(RD);
2423  }
2424 
2425  Sema &S;
2426  Sema::AssociatedNamespaceSet &Namespaces;
2427  Sema::AssociatedClassSet &Classes;
2428  SourceLocation InstantiationLoc;
2429 
2430  private:
2431  Sema::AssociatedClassSet ClassesTransitive;
2432  };
2433 } // end anonymous namespace
2434 
2435 static void
2436 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2437 
2439  DeclContext *Ctx) {
2440  // Add the associated namespace for this class.
2441 
2442  // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2443  // be a locally scoped record.
2444 
2445  // We skip out of inline namespaces. The innermost non-inline namespace
2446  // contains all names of all its nested inline namespaces anyway, so we can
2447  // replace the entire inline namespace tree with its root.
2448  while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2449  Ctx->isInlineNamespace())
2450  Ctx = Ctx->getParent();
2451 
2452  if (Ctx->isFileContext())
2453  Namespaces.insert(Ctx->getPrimaryContext());
2454 }
2455 
2456 // Add the associated classes and namespaces for argument-dependent
2457 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
2458 static void
2459 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2460  const TemplateArgument &Arg) {
2461  // C++ [basic.lookup.koenig]p2, last bullet:
2462  // -- [...] ;
2463  switch (Arg.getKind()) {
2465  break;
2466 
2468  // [...] the namespaces and classes associated with the types of the
2469  // template arguments provided for template type parameters (excluding
2470  // template template parameters)
2472  break;
2473 
2476  // [...] the namespaces in which any template template arguments are
2477  // defined; and the classes in which any member templates used as
2478  // template template arguments are defined.
2480  if (ClassTemplateDecl *ClassTemplate
2481  = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2482  DeclContext *Ctx = ClassTemplate->getDeclContext();
2483  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2484  Result.Classes.insert(EnclosingClass);
2485  // Add the associated namespace for this class.
2486  CollectEnclosingNamespace(Result.Namespaces, Ctx);
2487  }
2488  break;
2489  }
2490 
2495  // [Note: non-type template arguments do not contribute to the set of
2496  // associated namespaces. ]
2497  break;
2498 
2500  for (const auto &P : Arg.pack_elements())
2502  break;
2503  }
2504 }
2505 
2506 // Add the associated classes and namespaces for
2507 // argument-dependent lookup with an argument of class type
2508 // (C++ [basic.lookup.koenig]p2).
2509 static void
2510 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2511  CXXRecordDecl *Class) {
2512 
2513  // Just silently ignore anything whose name is __va_list_tag.
2514  if (Class->getDeclName() == Result.S.VAListTagName)
2515  return;
2516 
2517  // C++ [basic.lookup.koenig]p2:
2518  // [...]
2519  // -- If T is a class type (including unions), its associated
2520  // classes are: the class itself; the class of which it is a
2521  // member, if any; and its direct and indirect base
2522  // classes. Its associated namespaces are the namespaces in
2523  // which its associated classes are defined.
2524 
2525  // Add the class of which it is a member, if any.
2526  DeclContext *Ctx = Class->getDeclContext();
2527  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2528  Result.Classes.insert(EnclosingClass);
2529  // Add the associated namespace for this class.
2530  CollectEnclosingNamespace(Result.Namespaces, Ctx);
2531 
2532  // -- If T is a template-id, its associated namespaces and classes are
2533  // the namespace in which the template is defined; for member
2534  // templates, the member template's class; the namespaces and classes
2535  // associated with the types of the template arguments provided for
2536  // template type parameters (excluding template template parameters); the
2537  // namespaces in which any template template arguments are defined; and
2538  // the classes in which any member templates used as template template
2539  // arguments are defined. [Note: non-type template arguments do not
2540  // contribute to the set of associated namespaces. ]
2542  = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2543  DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2544  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2545  Result.Classes.insert(EnclosingClass);
2546  // Add the associated namespace for this class.
2547  CollectEnclosingNamespace(Result.Namespaces, Ctx);
2548 
2549  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2550  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2551  addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2552  }
2553 
2554  // Add the class itself. If we've already transitively visited this class,
2555  // we don't need to visit base classes.
2556  if (!Result.addClassTransitive(Class))
2557  return;
2558 
2559  // Only recurse into base classes for complete types.
2560  if (!Result.S.isCompleteType(Result.InstantiationLoc,
2561  Result.S.Context.getRecordType(Class)))
2562  return;
2563 
2564  // Add direct and indirect base classes along with their associated
2565  // namespaces.
2567  Bases.push_back(Class);
2568  while (!Bases.empty()) {
2569  // Pop this class off the stack.
2570  Class = Bases.pop_back_val();
2571 
2572  // Visit the base classes.
2573  for (const auto &Base : Class->bases()) {
2574  const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2575  // In dependent contexts, we do ADL twice, and the first time around,
2576  // the base type might be a dependent TemplateSpecializationType, or a
2577  // TemplateTypeParmType. If that happens, simply ignore it.
2578  // FIXME: If we want to support export, we probably need to add the
2579  // namespace of the template in a TemplateSpecializationType, or even
2580  // the classes and namespaces of known non-dependent arguments.
2581  if (!BaseType)
2582  continue;
2583  CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2584  if (Result.addClassTransitive(BaseDecl)) {
2585  // Find the associated namespace for this base class.
2586  DeclContext *BaseCtx = BaseDecl->getDeclContext();
2587  CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2588 
2589  // Make sure we visit the bases of this base class.
2590  if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2591  Bases.push_back(BaseDecl);
2592  }
2593  }
2594  }
2595 }
2596 
2597 // Add the associated classes and namespaces for
2598 // argument-dependent lookup with an argument of type T
2599 // (C++ [basic.lookup.koenig]p2).
2600 static void
2601 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2602  // C++ [basic.lookup.koenig]p2:
2603  //
2604  // For each argument type T in the function call, there is a set
2605  // of zero or more associated namespaces and a set of zero or more
2606  // associated classes to be considered. The sets of namespaces and
2607  // classes is determined entirely by the types of the function
2608  // arguments (and the namespace of any template template
2609  // argument). Typedef names and using-declarations used to specify
2610  // the types do not contribute to this set. The sets of namespaces
2611  // and classes are determined in the following way:
2612 
2614  const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2615 
2616  while (true) {
2617  switch (T->getTypeClass()) {
2618 
2619 #define TYPE(Class, Base)
2620 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2621 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2622 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2623 #define ABSTRACT_TYPE(Class, Base)
2624 #include "clang/AST/TypeNodes.def"
2625  // T is canonical. We can also ignore dependent types because
2626  // we don't need to do ADL at the definition point, but if we
2627  // wanted to implement template export (or if we find some other
2628  // use for associated classes and namespaces...) this would be
2629  // wrong.
2630  break;
2631 
2632  // -- If T is a pointer to U or an array of U, its associated
2633  // namespaces and classes are those associated with U.
2634  case Type::Pointer:
2635  T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2636  continue;
2637  case Type::ConstantArray:
2638  case Type::IncompleteArray:
2639  case Type::VariableArray:
2640  T = cast<ArrayType>(T)->getElementType().getTypePtr();
2641  continue;
2642 
2643  // -- If T is a fundamental type, its associated sets of
2644  // namespaces and classes are both empty.
2645  case Type::Builtin:
2646  break;
2647 
2648  // -- If T is a class type (including unions), its associated
2649  // classes are: the class itself; the class of which it is a
2650  // member, if any; and its direct and indirect base
2651  // classes. Its associated namespaces are the namespaces in
2652  // which its associated classes are defined.
2653  case Type::Record: {
2654  CXXRecordDecl *Class =
2655  cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2656  addAssociatedClassesAndNamespaces(Result, Class);
2657  break;
2658  }
2659 
2660  // -- If T is an enumeration type, its associated namespace is
2661  // the namespace in which it is defined. If it is class
2662  // member, its associated class is the member's class; else
2663  // it has no associated class.
2664  case Type::Enum: {
2665  EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2666 
2667  DeclContext *Ctx = Enum->getDeclContext();
2668  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2669  Result.Classes.insert(EnclosingClass);
2670 
2671  // Add the associated namespace for this class.
2672  CollectEnclosingNamespace(Result.Namespaces, Ctx);
2673 
2674  break;
2675  }
2676 
2677  // -- If T is a function type, its associated namespaces and
2678  // classes are those associated with the function parameter
2679  // types and those associated with the return type.
2680  case Type::FunctionProto: {
2681  const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2682  for (const auto &Arg : Proto->param_types())
2683  Queue.push_back(Arg.getTypePtr());
2684  // fallthrough
2685  LLVM_FALLTHROUGH;
2686  }
2687  case Type::FunctionNoProto: {
2688  const FunctionType *FnType = cast<FunctionType>(T);
2689  T = FnType->getReturnType().getTypePtr();
2690  continue;
2691  }
2692 
2693  // -- If T is a pointer to a member function of a class X, its
2694  // associated namespaces and classes are those associated
2695  // with the function parameter types and return type,
2696  // together with those associated with X.
2697  //
2698  // -- If T is a pointer to a data member of class X, its
2699  // associated namespaces and classes are those associated
2700  // with the member type together with those associated with
2701  // X.
2702  case Type::MemberPointer: {
2703  const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2704 
2705  // Queue up the class type into which this points.
2706  Queue.push_back(MemberPtr->getClass());
2707 
2708  // And directly continue with the pointee type.
2709  T = MemberPtr->getPointeeType().getTypePtr();
2710  continue;
2711  }
2712 
2713  // As an extension, treat this like a normal pointer.
2714  case Type::BlockPointer:
2715  T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2716  continue;
2717 
2718  // References aren't covered by the standard, but that's such an
2719  // obvious defect that we cover them anyway.
2720  case Type::LValueReference:
2721  case Type::RValueReference:
2722  T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2723  continue;
2724 
2725  // These are fundamental types.
2726  case Type::Vector:
2727  case Type::ExtVector:
2728  case Type::Complex:
2729  break;
2730 
2731  // Non-deduced auto types only get here for error cases.
2732  case Type::Auto:
2733  case Type::DeducedTemplateSpecialization:
2734  break;
2735 
2736  // If T is an Objective-C object or interface type, or a pointer to an
2737  // object or interface type, the associated namespace is the global
2738  // namespace.
2739  case Type::ObjCObject:
2740  case Type::ObjCInterface:
2741  case Type::ObjCObjectPointer:
2742  Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2743  break;
2744 
2745  // Atomic types are just wrappers; use the associations of the
2746  // contained type.
2747  case Type::Atomic:
2748  T = cast<AtomicType>(T)->getValueType().getTypePtr();
2749  continue;
2750  case Type::Pipe:
2751  T = cast<PipeType>(T)->getElementType().getTypePtr();
2752  continue;
2753  }
2754 
2755  if (Queue.empty())
2756  break;
2757  T = Queue.pop_back_val();
2758  }
2759 }
2760 
2761 /// Find the associated classes and namespaces for
2762 /// argument-dependent lookup for a call with the given set of
2763 /// arguments.
2764 ///
2765 /// This routine computes the sets of associated classes and associated
2766 /// namespaces searched by argument-dependent lookup
2767 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
2769  SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2770  AssociatedNamespaceSet &AssociatedNamespaces,
2771  AssociatedClassSet &AssociatedClasses) {
2772  AssociatedNamespaces.clear();
2773  AssociatedClasses.clear();
2774 
2775  AssociatedLookup Result(*this, InstantiationLoc,
2776  AssociatedNamespaces, AssociatedClasses);
2777 
2778  // C++ [basic.lookup.koenig]p2:
2779  // For each argument type T in the function call, there is a set
2780  // of zero or more associated namespaces and a set of zero or more
2781  // associated classes to be considered. The sets of namespaces and
2782  // classes is determined entirely by the types of the function
2783  // arguments (and the namespace of any template template
2784  // argument).
2785  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2786  Expr *Arg = Args[ArgIdx];
2787 
2788  if (Arg->getType() != Context.OverloadTy) {
2790  continue;
2791  }
2792 
2793  // [...] In addition, if the argument is the name or address of a
2794  // set of overloaded functions and/or function templates, its
2795  // associated classes and namespaces are the union of those
2796  // associated with each of the members of the set: the namespace
2797  // in which the function or function template is defined and the
2798  // classes and namespaces associated with its (non-dependent)
2799  // parameter types and return type.
2801 
2802  for (const NamedDecl *D : OE->decls()) {
2803  // Look through any using declarations to find the underlying function.
2804  const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
2805 
2806  // Add the classes and namespaces associated with the parameter
2807  // types and return type of this function.
2808  addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2809  }
2810  }
2811 }
2812 
2814  SourceLocation Loc,
2815  LookupNameKind NameKind,
2816  RedeclarationKind Redecl) {
2817  LookupResult R(*this, Name, Loc, NameKind, Redecl);
2818  LookupName(R, S);
2819  return R.getAsSingle<NamedDecl>();
2820 }
2821 
2822 /// Find the protocol with the given name, if any.
2824  SourceLocation IdLoc,
2825  RedeclarationKind Redecl) {
2826  Decl *D = LookupSingleName(TUScope, II, IdLoc,
2827  LookupObjCProtocolName, Redecl);
2828  return cast_or_null<ObjCProtocolDecl>(D);
2829 }
2830 
2832  QualType T1, QualType T2,
2833  UnresolvedSetImpl &Functions) {
2834  // C++ [over.match.oper]p3:
2835  // -- The set of non-member candidates is the result of the
2836  // unqualified lookup of operator@ in the context of the
2837  // expression according to the usual rules for name lookup in
2838  // unqualified function calls (3.4.2) except that all member
2839  // functions are ignored.
2841  LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2842  LookupName(Operators, S);
2843 
2844  assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2845  Functions.append(Operators.begin(), Operators.end());
2846 }
2847 
2850  bool ConstArg,
2851  bool VolatileArg,
2852  bool RValueThis,
2853  bool ConstThis,
2854  bool VolatileThis) {
2855  assert(CanDeclareSpecialMemberFunction(RD) &&
2856  "doing special member lookup into record that isn't fully complete");
2857  RD = RD->getDefinition();
2858  if (RValueThis || ConstThis || VolatileThis)
2859  assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2860  "constructors and destructors always have unqualified lvalue this");
2861  if (ConstArg || VolatileArg)
2862  assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2863  "parameter-less special members can't have qualified arguments");
2864 
2865  // FIXME: Get the caller to pass in a location for the lookup.
2866  SourceLocation LookupLoc = RD->getLocation();
2867 
2868  llvm::FoldingSetNodeID ID;
2869  ID.AddPointer(RD);
2870  ID.AddInteger(SM);
2871  ID.AddInteger(ConstArg);
2872  ID.AddInteger(VolatileArg);
2873  ID.AddInteger(RValueThis);
2874  ID.AddInteger(ConstThis);
2875  ID.AddInteger(VolatileThis);
2876 
2877  void *InsertPoint;
2879  SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2880 
2881  // This was already cached
2882  if (Result)
2883  return *Result;
2884 
2885  Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
2886  Result = new (Result) SpecialMemberOverloadResultEntry(ID);
2887  SpecialMemberCache.InsertNode(Result, InsertPoint);
2888 
2889  if (SM == CXXDestructor) {
2890  if (RD->needsImplicitDestructor())
2891  DeclareImplicitDestructor(RD);
2892  CXXDestructorDecl *DD = RD->getDestructor();
2893  assert(DD && "record without a destructor");
2894  Result->setMethod(DD);
2895  Result->setKind(DD->isDeleted() ?
2896  SpecialMemberOverloadResult::NoMemberOrDeleted :
2897  SpecialMemberOverloadResult::Success);
2898  return *Result;
2899  }
2900 
2901  // Prepare for overload resolution. Here we construct a synthetic argument
2902  // if necessary and make sure that implicit functions are declared.
2903  CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2904  DeclarationName Name;
2905  Expr *Arg = nullptr;
2906  unsigned NumArgs;
2907 
2908  QualType ArgType = CanTy;
2909  ExprValueKind VK = VK_LValue;
2910 
2911  if (SM == CXXDefaultConstructor) {
2912  Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2913  NumArgs = 0;
2915  DeclareImplicitDefaultConstructor(RD);
2916  } else {
2917  if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2918  Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2919  if (RD->needsImplicitCopyConstructor())
2920  DeclareImplicitCopyConstructor(RD);
2921  if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
2922  DeclareImplicitMoveConstructor(RD);
2923  } else {
2924  Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2925  if (RD->needsImplicitCopyAssignment())
2926  DeclareImplicitCopyAssignment(RD);
2927  if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
2928  DeclareImplicitMoveAssignment(RD);
2929  }
2930 
2931  if (ConstArg)
2932  ArgType.addConst();
2933  if (VolatileArg)
2934  ArgType.addVolatile();
2935 
2936  // This isn't /really/ specified by the standard, but it's implied
2937  // we should be working from an RValue in the case of move to ensure
2938  // that we prefer to bind to rvalue references, and an LValue in the
2939  // case of copy to ensure we don't bind to rvalue references.
2940  // Possibly an XValue is actually correct in the case of move, but
2941  // there is no semantic difference for class types in this restricted
2942  // case.
2943  if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2944  VK = VK_LValue;
2945  else
2946  VK = VK_RValue;
2947  }
2948 
2949  OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
2950 
2951  if (SM != CXXDefaultConstructor) {
2952  NumArgs = 1;
2953  Arg = &FakeArg;
2954  }
2955 
2956  // Create the object argument
2957  QualType ThisTy = CanTy;
2958  if (ConstThis)
2959  ThisTy.addConst();
2960  if (VolatileThis)
2961  ThisTy.addVolatile();
2962  Expr::Classification Classification =
2963  OpaqueValueExpr(LookupLoc, ThisTy,
2964  RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2965 
2966  // Now we perform lookup on the name we computed earlier and do overload
2967  // resolution. Lookup is only performed directly into the class since there
2968  // will always be a (possibly implicit) declaration to shadow any others.
2970  DeclContext::lookup_result R = RD->lookup(Name);
2971 
2972  if (R.empty()) {
2973  // We might have no default constructor because we have a lambda's closure
2974  // type, rather than because there's some other declared constructor.
2975  // Every class has a copy/move constructor, copy/move assignment, and
2976  // destructor.
2977  assert(SM == CXXDefaultConstructor &&
2978  "lookup for a constructor or assignment operator was empty");
2979  Result->setMethod(nullptr);
2980  Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2981  return *Result;
2982  }
2983 
2984  // Copy the candidates as our processing of them may load new declarations
2985  // from an external source and invalidate lookup_result.
2986  SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2987 
2988  for (NamedDecl *CandDecl : Candidates) {
2989  if (CandDecl->isInvalidDecl())
2990  continue;
2991 
2992  DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
2993  auto CtorInfo = getConstructorInfo(Cand);
2994  if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
2995  if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2996  AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
2997  llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2998  else if (CtorInfo)
2999  AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3000  llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3001  else
3002  AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3003  true);
3004  } else if (FunctionTemplateDecl *Tmpl =
3005  dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3006  if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3007  AddMethodTemplateCandidate(
3008  Tmpl, Cand, RD, nullptr, ThisTy, Classification,
3009  llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3010  else if (CtorInfo)
3011  AddTemplateOverloadCandidate(
3012  CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3013  llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3014  else
3015  AddTemplateOverloadCandidate(
3016  Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3017  } else {
3018  assert(isa<UsingDecl>(Cand.getDecl()) &&
3019  "illegal Kind of operator = Decl");
3020  }
3021  }
3022 
3024  switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3025  case OR_Success:
3026  Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3027  Result->setKind(SpecialMemberOverloadResult::Success);
3028  break;
3029 
3030  case OR_Deleted:
3031  Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3032  Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3033  break;
3034 
3035  case OR_Ambiguous:
3036  Result->setMethod(nullptr);
3037  Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3038  break;
3039 
3040  case OR_No_Viable_Function:
3041  Result->setMethod(nullptr);
3042  Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3043  break;
3044  }
3045 
3046  return *Result;
3047 }
3048 
3049 /// Look up the default constructor for the given class.
3052  LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3053  false, false);
3054 
3055  return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3056 }
3057 
3058 /// Look up the copying constructor for the given class.
3060  unsigned Quals) {
3061  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3062  "non-const, non-volatile qualifiers for copy ctor arg");
3064  LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3065  Quals & Qualifiers::Volatile, false, false, false);
3066 
3067  return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3068 }
3069 
3070 /// Look up the moving constructor for the given class.
3072  unsigned Quals) {
3074  LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3075  Quals & Qualifiers::Volatile, false, false, false);
3076 
3077  return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3078 }
3079 
3080 /// Look up the constructors for the given class.
3082  // If the implicit constructors have not yet been declared, do so now.
3083  if (CanDeclareSpecialMemberFunction(Class)) {
3084  if (Class->needsImplicitDefaultConstructor())
3085  DeclareImplicitDefaultConstructor(Class);
3086  if (Class->needsImplicitCopyConstructor())
3087  DeclareImplicitCopyConstructor(Class);
3088  if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3089  DeclareImplicitMoveConstructor(Class);
3090  }
3091 
3092  CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3094  return Class->lookup(Name);
3095 }
3096 
3097 /// Look up the copying assignment operator for the given class.
3099  unsigned Quals, bool RValueThis,
3100  unsigned ThisQuals) {
3101  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3102  "non-const, non-volatile qualifiers for copy assignment arg");
3103  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3104  "non-const, non-volatile qualifiers for copy assignment this");
3106  LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3107  Quals & Qualifiers::Volatile, RValueThis,
3108  ThisQuals & Qualifiers::Const,
3109  ThisQuals & Qualifiers::Volatile);
3110 
3111  return Result.getMethod();
3112 }
3113 
3114 /// Look up the moving assignment operator for the given class.
3116  unsigned Quals,
3117  bool RValueThis,
3118  unsigned ThisQuals) {
3119  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3120  "non-const, non-volatile qualifiers for copy assignment this");
3122  LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3123  Quals & Qualifiers::Volatile, RValueThis,
3124  ThisQuals & Qualifiers::Const,
3125  ThisQuals & Qualifiers::Volatile);
3126 
3127  return Result.getMethod();
3128 }
3129 
3130 /// Look for the destructor of the given class.
3131 ///
3132 /// During semantic analysis, this routine should be used in lieu of
3133 /// CXXRecordDecl::getDestructor().
3134 ///
3135 /// \returns The destructor for this class.
3137  return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3138  false, false, false,
3139  false, false).getMethod());
3140 }
3141 
3142 /// LookupLiteralOperator - Determine which literal operator should be used for
3143 /// a user-defined literal, per C++11 [lex.ext].
3144 ///
3145 /// Normal overload resolution is not used to select which literal operator to
3146 /// call for a user-defined literal. Look up the provided literal operator name,
3147 /// and filter the results to the appropriate set for the given argument types.
3150  ArrayRef<QualType> ArgTys,
3151  bool AllowRaw, bool AllowTemplate,
3152  bool AllowStringTemplate, bool DiagnoseMissing) {
3153  LookupName(R, S);
3154  assert(R.getResultKind() != LookupResult::Ambiguous &&
3155  "literal operator lookup can't be ambiguous");
3156 
3157  // Filter the lookup results appropriately.
3159 
3160  bool FoundRaw = false;
3161  bool FoundTemplate = false;
3162  bool FoundStringTemplate = false;
3163  bool FoundExactMatch = false;
3164 
3165  while (F.hasNext()) {
3166  Decl *D = F.next();
3167  if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3168  D = USD->getTargetDecl();
3169 
3170  // If the declaration we found is invalid, skip it.
3171  if (D->isInvalidDecl()) {
3172  F.erase();
3173  continue;
3174  }
3175 
3176  bool IsRaw = false;
3177  bool IsTemplate = false;
3178  bool IsStringTemplate = false;
3179  bool IsExactMatch = false;
3180 
3181  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3182  if (FD->getNumParams() == 1 &&
3183  FD->getParamDecl(0)->getType()->getAs<PointerType>())
3184  IsRaw = true;
3185  else if (FD->getNumParams() == ArgTys.size()) {
3186  IsExactMatch = true;
3187  for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3188  QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3189  if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3190  IsExactMatch = false;
3191  break;
3192  }
3193  }
3194  }
3195  }
3196  if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3197  TemplateParameterList *Params = FD->getTemplateParameters();
3198  if (Params->size() == 1)
3199  IsTemplate = true;
3200  else
3201  IsStringTemplate = true;
3202  }
3203 
3204  if (IsExactMatch) {
3205  FoundExactMatch = true;
3206  AllowRaw = false;
3207  AllowTemplate = false;
3208  AllowStringTemplate = false;
3209  if (FoundRaw || FoundTemplate || FoundStringTemplate) {
3210  // Go through again and remove the raw and template decls we've
3211  // already found.
3212  F.restart();
3213  FoundRaw = FoundTemplate = FoundStringTemplate = false;
3214  }
3215  } else if (AllowRaw && IsRaw) {
3216  FoundRaw = true;
3217  } else if (AllowTemplate && IsTemplate) {
3218  FoundTemplate = true;
3219  } else if (AllowStringTemplate && IsStringTemplate) {
3220  FoundStringTemplate = true;
3221  } else {
3222  F.erase();
3223  }
3224  }
3225 
3226  F.done();
3227 
3228  // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3229  // parameter type, that is used in preference to a raw literal operator
3230  // or literal operator template.
3231  if (FoundExactMatch)
3232  return LOLR_Cooked;
3233 
3234  // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3235  // operator template, but not both.
3236  if (FoundRaw && FoundTemplate) {
3237  Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3238  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3239  NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
3240  return LOLR_Error;
3241  }
3242 
3243  if (FoundRaw)
3244  return LOLR_Raw;
3245 
3246  if (FoundTemplate)
3247  return LOLR_Template;
3248 
3249  if (FoundStringTemplate)
3250  return LOLR_StringTemplate;
3251 
3252  // Didn't find anything we could use.
3253  if (DiagnoseMissing) {
3254  Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3255  << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3256  << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3257  << (AllowTemplate || AllowStringTemplate);
3258  return LOLR_Error;
3259  }
3260 
3261  return LOLR_ErrorNoDiagnostic;
3262 }
3263 
3265  NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3266 
3267  // If we haven't yet seen a decl for this key, or the last decl
3268  // was exactly this one, we're done.
3269  if (Old == nullptr || Old == New) {
3270  Old = New;
3271  return;
3272  }
3273 
3274  // Otherwise, decide which is a more recent redeclaration.
3275  FunctionDecl *OldFD = Old->getAsFunction();
3276  FunctionDecl *NewFD = New->getAsFunction();
3277 
3278  FunctionDecl *Cursor = NewFD;
3279  while (true) {
3280  Cursor = Cursor->getPreviousDecl();
3281 
3282  // If we got to the end without finding OldFD, OldFD is the newer
3283  // declaration; leave things as they are.
3284  if (!Cursor) return;
3285 
3286  // If we do find OldFD, then NewFD is newer.
3287  if (Cursor == OldFD) break;
3288 
3289  // Otherwise, keep looking.
3290  }
3291 
3292  Old = New;
3293 }
3294 
3296  ArrayRef<Expr *> Args, ADLResult &Result) {
3297  // Find all of the associated namespaces and classes based on the
3298  // arguments we have.
3299  AssociatedNamespaceSet AssociatedNamespaces;
3300  AssociatedClassSet AssociatedClasses;
3301  FindAssociatedClassesAndNamespaces(Loc, Args,
3302  AssociatedNamespaces,
3303  AssociatedClasses);
3304 
3305  // C++ [basic.lookup.argdep]p3:
3306  // Let X be the lookup set produced by unqualified lookup (3.4.1)
3307  // and let Y be the lookup set produced by argument dependent
3308  // lookup (defined as follows). If X contains [...] then Y is
3309  // empty. Otherwise Y is the set of declarations found in the
3310  // namespaces associated with the argument types as described
3311  // below. The set of declarations found by the lookup of the name
3312  // is the union of X and Y.
3313  //
3314  // Here, we compute Y and add its members to the overloaded
3315  // candidate set.
3316  for (auto *NS : AssociatedNamespaces) {
3317  // When considering an associated namespace, the lookup is the
3318  // same as the lookup performed when the associated namespace is
3319  // used as a qualifier (3.4.3.2) except that:
3320  //
3321  // -- Any using-directives in the associated namespace are
3322  // ignored.
3323  //
3324  // -- Any namespace-scope friend functions declared in
3325  // associated classes are visible within their respective
3326  // namespaces even if they are not visible during an ordinary
3327  // lookup (11.4).
3328  DeclContext::lookup_result R = NS->lookup(Name);
3329  for (auto *D : R) {
3330  auto *Underlying = D;
3331  if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3332  Underlying = USD->getTargetDecl();
3333 
3334  if (!isa<FunctionDecl>(Underlying) &&
3335  !isa<FunctionTemplateDecl>(Underlying))
3336  continue;
3337 
3338  // The declaration is visible to argument-dependent lookup if either
3339  // it's ordinarily visible or declared as a friend in an associated
3340  // class.
3341  bool Visible = false;
3342  for (D = D->getMostRecentDecl(); D;
3343  D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3345  if (isVisible(D)) {
3346  Visible = true;
3347  break;
3348  }
3349  } else if (D->getFriendObjectKind()) {
3350  auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3351  if (AssociatedClasses.count(RD) && isVisible(D)) {
3352  Visible = true;
3353  break;
3354  }
3355  }
3356  }
3357 
3358  // FIXME: Preserve D as the FoundDecl.
3359  if (Visible)
3360  Result.insert(Underlying);
3361  }
3362  }
3363 }
3364 
3365 //----------------------------------------------------------------------------
3366 // Search for all visible declarations.
3367 //----------------------------------------------------------------------------
3369 
3370 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3371 
3372 namespace {
3373 
3374 class ShadowContextRAII;
3375 
3376 class VisibleDeclsRecord {
3377 public:
3378  /// An entry in the shadow map, which is optimized to store a
3379  /// single declaration (the common case) but can also store a list
3380  /// of declarations.
3381  typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3382 
3383 private:
3384  /// A mapping from declaration names to the declarations that have
3385  /// this name within a particular scope.
3386  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3387 
3388  /// A list of shadow maps, which is used to model name hiding.
3389  std::list<ShadowMap> ShadowMaps;
3390 
3391  /// The declaration contexts we have already visited.
3392  llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3393 
3394  friend class ShadowContextRAII;
3395 
3396 public:
3397  /// Determine whether we have already visited this context
3398  /// (and, if not, note that we are going to visit that context now).
3399  bool visitedContext(DeclContext *Ctx) {
3400  return !VisitedContexts.insert(Ctx).second;
3401  }
3402 
3403  bool alreadyVisitedContext(DeclContext *Ctx) {
3404  return VisitedContexts.count(Ctx);
3405  }
3406 
3407  /// Determine whether the given declaration is hidden in the
3408  /// current scope.
3409  ///
3410  /// \returns the declaration that hides the given declaration, or
3411  /// NULL if no such declaration exists.
3412  NamedDecl *checkHidden(NamedDecl *ND);
3413 
3414  /// Add a declaration to the current shadow map.
3415  void add(NamedDecl *ND) {
3416  ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3417  }
3418 };
3419 
3420 /// RAII object that records when we've entered a shadow context.
3421 class ShadowContextRAII {
3422  VisibleDeclsRecord &Visible;
3423 
3424  typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3425 
3426 public:
3427  ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3428  Visible.ShadowMaps.emplace_back();
3429  }
3430 
3431  ~ShadowContextRAII() {
3432  Visible.ShadowMaps.pop_back();
3433  }
3434 };
3435 
3436 } // end anonymous namespace
3437 
3438 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3439  unsigned IDNS = ND->getIdentifierNamespace();
3440  std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3441  for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3442  SM != SMEnd; ++SM) {
3443  ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3444  if (Pos == SM->end())
3445  continue;
3446 
3447  for (auto *D : Pos->second) {
3448  // A tag declaration does not hide a non-tag declaration.
3449  if (D->hasTagIdentifierNamespace() &&
3452  continue;
3453 
3454  // Protocols are in distinct namespaces from everything else.
3456  || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3457  D->getIdentifierNamespace() != IDNS)
3458  continue;
3459 
3460  // Functions and function templates in the same scope overload
3461  // rather than hide. FIXME: Look for hiding based on function
3462  // signatures!
3465  SM == ShadowMaps.rbegin())
3466  continue;
3467 
3468  // A shadow declaration that's created by a resolved using declaration
3469  // is not hidden by the same using declaration.
3470  if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3471  cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3472  continue;
3473 
3474  // We've found a declaration that hides this one.
3475  return D;
3476  }
3477  }
3478 
3479  return nullptr;
3480 }
3481 
3482 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3483  bool QualifiedNameLookup,
3484  bool InBaseClass,
3485  VisibleDeclConsumer &Consumer,
3486  VisibleDeclsRecord &Visited,
3487  bool IncludeDependentBases,
3488  bool LoadExternal) {
3489  if (!Ctx)
3490  return;
3491 
3492  // Make sure we don't visit the same context twice.
3493  if (Visited.visitedContext(Ctx->getPrimaryContext()))
3494  return;
3495 
3496  Consumer.EnteredContext(Ctx);
3497 
3498  // Outside C++, lookup results for the TU live on identifiers.
3499  if (isa<TranslationUnitDecl>(Ctx) &&
3500  !Result.getSema().getLangOpts().CPlusPlus) {
3501  auto &S = Result.getSema();
3502  auto &Idents = S.Context.Idents;
3503 
3504  // Ensure all external identifiers are in the identifier table.
3505  if (LoadExternal)
3506  if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3507  std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3508  for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3509  Idents.get(Name);
3510  }
3511 
3512  // Walk all lookup results in the TU for each identifier.
3513  for (const auto &Ident : Idents) {
3514  for (auto I = S.IdResolver.begin(Ident.getValue()),
3515  E = S.IdResolver.end();
3516  I != E; ++I) {
3517  if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3518  if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3519  Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3520  Visited.add(ND);
3521  }
3522  }
3523  }
3524  }
3525 
3526  return;
3527  }
3528 
3529  if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3531 
3532  // We sometimes skip loading namespace-level results (they tend to be huge).
3533  bool Load = LoadExternal ||
3534  !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
3535  // Enumerate all of the results in this context.
3536  for (DeclContextLookupResult R :
3537  Load ? Ctx->lookups()
3538  : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
3539  for (auto *D : R) {
3540  if (auto *ND = Result.getAcceptableDecl(D)) {
3541  Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3542  Visited.add(ND);
3543  }
3544  }
3545  }
3546 
3547  // Traverse using directives for qualified name lookup.
3548  if (QualifiedNameLookup) {
3549  ShadowContextRAII Shadow(Visited);
3550  for (auto I : Ctx->using_directives()) {
3551  if (!Result.getSema().isVisible(I))
3552  continue;
3553  LookupVisibleDecls(I->getNominatedNamespace(), Result,
3554  QualifiedNameLookup, InBaseClass, Consumer, Visited,
3555  IncludeDependentBases, LoadExternal);
3556  }
3557  }
3558 
3559  // Traverse the contexts of inherited C++ classes.
3560  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3561  if (!Record->hasDefinition())
3562  return;
3563 
3564  for (const auto &B : Record->bases()) {
3565  QualType BaseType = B.getType();
3566 
3567  RecordDecl *RD;
3568  if (BaseType->isDependentType()) {
3569  if (!IncludeDependentBases) {
3570  // Don't look into dependent bases, because name lookup can't look
3571  // there anyway.
3572  continue;
3573  }
3574  const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3575  if (!TST)
3576  continue;
3577  TemplateName TN = TST->getTemplateName();
3578  const auto *TD =
3579  dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3580  if (!TD)
3581  continue;
3582  RD = TD->getTemplatedDecl();
3583  } else {
3584  const auto *Record = BaseType->getAs<RecordType>();
3585  if (!Record)
3586  continue;
3587  RD = Record->getDecl();
3588  }
3589 
3590  // FIXME: It would be nice to be able to determine whether referencing
3591  // a particular member would be ambiguous. For example, given
3592  //
3593  // struct A { int member; };
3594  // struct B { int member; };
3595  // struct C : A, B { };
3596  //
3597  // void f(C *c) { c->### }
3598  //
3599  // accessing 'member' would result in an ambiguity. However, we
3600  // could be smart enough to qualify the member with the base
3601  // class, e.g.,
3602  //
3603  // c->B::member
3604  //
3605  // or
3606  //
3607  // c->A::member
3608 
3609  // Find results in this base class (and its bases).
3610  ShadowContextRAII Shadow(Visited);
3611  LookupVisibleDecls(RD, Result, QualifiedNameLookup, /*InBaseClass=*/true,
3612  Consumer, Visited, IncludeDependentBases,
3613  LoadExternal);
3614  }
3615  }
3616 
3617  // Traverse the contexts of Objective-C classes.
3618  if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3619  // Traverse categories.
3620  for (auto *Cat : IFace->visible_categories()) {
3621  ShadowContextRAII Shadow(Visited);
3622  LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer,
3623  Visited, IncludeDependentBases, LoadExternal);
3624  }
3625 
3626  // Traverse protocols.
3627  for (auto *I : IFace->all_referenced_protocols()) {
3628  ShadowContextRAII Shadow(Visited);
3629  LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3630  Visited, IncludeDependentBases, LoadExternal);
3631  }
3632 
3633  // Traverse the superclass.
3634  if (IFace->getSuperClass()) {
3635  ShadowContextRAII Shadow(Visited);
3636  LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
3637  true, Consumer, Visited, IncludeDependentBases,
3638  LoadExternal);
3639  }
3640 
3641  // If there is an implementation, traverse it. We do this to find
3642  // synthesized ivars.
3643  if (IFace->getImplementation()) {
3644  ShadowContextRAII Shadow(Visited);
3645  LookupVisibleDecls(IFace->getImplementation(), Result,
3646  QualifiedNameLookup, InBaseClass, Consumer, Visited,
3647  IncludeDependentBases, LoadExternal);
3648  }
3649  } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3650  for (auto *I : Protocol->protocols()) {
3651  ShadowContextRAII Shadow(Visited);
3652  LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3653  Visited, IncludeDependentBases, LoadExternal);
3654  }
3655  } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3656  for (auto *I : Category->protocols()) {
3657  ShadowContextRAII Shadow(Visited);
3658  LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3659  Visited, IncludeDependentBases, LoadExternal);
3660  }
3661 
3662  // If there is an implementation, traverse it.
3663  if (Category->getImplementation()) {
3664  ShadowContextRAII Shadow(Visited);
3665  LookupVisibleDecls(Category->getImplementation(), Result,
3666  QualifiedNameLookup, true, Consumer, Visited,
3667  IncludeDependentBases, LoadExternal);
3668  }
3669  }
3670 }
3671 
3672 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3673  UnqualUsingDirectiveSet &UDirs,
3674  VisibleDeclConsumer &Consumer,
3675  VisibleDeclsRecord &Visited,
3676  bool LoadExternal) {
3677  if (!S)
3678  return;
3679 
3680  if (!S->getEntity() ||
3681  (!S->getParent() &&
3682  !Visited.alreadyVisitedContext(S->getEntity())) ||
3683  (S->getEntity())->isFunctionOrMethod()) {
3684  FindLocalExternScope FindLocals(Result);
3685  // Walk through the declarations in this Scope. The consumer might add new
3686  // decls to the scope as part of deserialization, so make a copy first.
3687  SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3688  for (Decl *D : ScopeDecls) {
3689  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3690  if ((ND = Result.getAcceptableDecl(ND))) {
3691  Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
3692  Visited.add(ND);
3693  }
3694  }
3695  }
3696 
3697  // FIXME: C++ [temp.local]p8
3698  DeclContext *Entity = nullptr;
3699  if (S->getEntity()) {
3700  // Look into this scope's declaration context, along with any of its
3701  // parent lookup contexts (e.g., enclosing classes), up to the point
3702  // where we hit the context stored in the next outer scope.
3703  Entity = S->getEntity();
3704  DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3705 
3706  for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3707  Ctx = Ctx->getLookupParent()) {
3708  if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3709  if (Method->isInstanceMethod()) {
3710  // For instance methods, look for ivars in the method's interface.
3711  LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3713  if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3714  LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3715  /*InBaseClass=*/false, Consumer, Visited,
3716  /*IncludeDependentBases=*/false, LoadExternal);
3717  }
3718  }
3719 
3720  // We've already performed all of the name lookup that we need
3721  // to for Objective-C methods; the next context will be the
3722  // outer scope.
3723  break;
3724  }
3725 
3726  if (Ctx->isFunctionOrMethod())
3727  continue;
3728 
3729  LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3730  /*InBaseClass=*/false, Consumer, Visited,
3731  /*IncludeDependentBases=*/false, LoadExternal);
3732  }
3733  } else if (!S->getParent()) {
3734  // Look into the translation unit scope. We walk through the translation
3735  // unit's declaration context, because the Scope itself won't have all of
3736  // the declarations if we loaded a precompiled header.
3737  // FIXME: We would like the translation unit's Scope object to point to the
3738  // translation unit, so we don't need this special "if" branch. However,
3739  // doing so would force the normal C++ name-lookup code to look into the
3740  // translation unit decl when the IdentifierInfo chains would suffice.
3741  // Once we fix that problem (which is part of a more general "don't look
3742  // in DeclContexts unless we have to" optimization), we can eliminate this.
3743  Entity = Result.getSema().Context.getTranslationUnitDecl();
3744  LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3745  /*InBaseClass=*/false, Consumer, Visited,
3746  /*IncludeDependentBases=*/false, LoadExternal);
3747  }
3748 
3749  if (Entity) {
3750  // Lookup visible declarations in any namespaces found by using
3751  // directives.
3752  for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3753  LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
3754  Result, /*QualifiedNameLookup=*/false,
3755  /*InBaseClass=*/false, Consumer, Visited,
3756  /*IncludeDependentBases=*/false, LoadExternal);
3757  }
3758 
3759  // Lookup names in the parent scope.
3760  ShadowContextRAII Shadow(Visited);
3761  LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited,
3762  LoadExternal);
3763 }
3764 
3766  VisibleDeclConsumer &Consumer,
3767  bool IncludeGlobalScope, bool LoadExternal) {
3768  // Determine the set of using directives available during
3769  // unqualified name lookup.
3770  Scope *Initial = S;
3771  UnqualUsingDirectiveSet UDirs(*this);
3772  if (getLangOpts().CPlusPlus) {
3773  // Find the first namespace or translation-unit scope.
3774  while (S && !isNamespaceOrTranslationUnitScope(S))
3775  S = S->getParent();
3776 
3777  UDirs.visitScopeChain(Initial, S);
3778  }
3779  UDirs.done();
3780 
3781  // Look for visible declarations.
3782  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3783  Result.setAllowHidden(Consumer.includeHiddenDecls());
3784  VisibleDeclsRecord Visited;
3785  if (!IncludeGlobalScope)
3786  Visited.visitedContext(Context.getTranslationUnitDecl());
3787  ShadowContextRAII Shadow(Visited);
3788  ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal);
3789 }
3790 
3792  VisibleDeclConsumer &Consumer,
3793  bool IncludeGlobalScope,
3794  bool IncludeDependentBases, bool LoadExternal) {
3795  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3796  Result.setAllowHidden(Consumer.includeHiddenDecls());
3797  VisibleDeclsRecord Visited;
3798  if (!IncludeGlobalScope)
3799  Visited.visitedContext(Context.getTranslationUnitDecl());
3800  ShadowContextRAII Shadow(Visited);
3801  ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3802  /*InBaseClass=*/false, Consumer, Visited,
3803  IncludeDependentBases, LoadExternal);
3804 }
3805 
3806 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3807 /// If GnuLabelLoc is a valid source location, then this is a definition
3808 /// of an __label__ label name, otherwise it is a normal label definition
3809 /// or use.
3811  SourceLocation GnuLabelLoc) {
3812  // Do a lookup to see if we have a label with this name already.
3813  NamedDecl *Res = nullptr;
3814 
3815  if (GnuLabelLoc.isValid()) {
3816  // Local label definitions always shadow existing labels.
3817  Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3818  Scope *S = CurScope;
3819  PushOnScopeChains(Res, S, true);
3820  return cast<LabelDecl>(Res);
3821  }
3822 
3823  // Not a GNU local label.
3824  Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3825  // If we found a label, check to see if it is in the same context as us.
3826  // When in a Block, we don't want to reuse a label in an enclosing function.
3827  if (Res && Res->getDeclContext() != CurContext)
3828  Res = nullptr;
3829  if (!Res) {
3830  // If not forward referenced or defined already, create the backing decl.
3831  Res = LabelDecl::Create(Context, CurContext, Loc, II);
3832  Scope *S = CurScope->getFnParent();
3833  assert(S && "Not in a function?");
3834  PushOnScopeChains(Res, S, true);
3835  }
3836  return cast<LabelDecl>(Res);
3837 }
3838 
3839 //===----------------------------------------------------------------------===//
3840 // Typo correction
3841 //===----------------------------------------------------------------------===//
3842 
3844  TypoCorrection &Candidate) {
3845  Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3846  return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3847 }
3848 
3849 static void LookupPotentialTypoResult(Sema &SemaRef,
3850  LookupResult &Res,
3851  IdentifierInfo *Name,
3852  Scope *S, CXXScopeSpec *SS,
3854  bool EnteringContext,
3855  bool isObjCIvarLookup,
3856  bool FindHidden);
3857 
3858 /// Check whether the declarations found for a typo correction are
3859 /// visible. Set the correction's RequiresImport flag to true if none of the
3860 /// declarations are visible, false otherwise.
3861 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3862  TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3863 
3864  for (/**/; DI != DE; ++DI)
3865  if (!LookupResult::isVisible(SemaRef, *DI))
3866  break;
3867  // No filtering needed if all decls are visible.
3868  if (DI == DE) {
3869  TC.setRequiresImport(false);
3870  return;
3871  }
3872 
3873  llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3874  bool AnyVisibleDecls = !NewDecls.empty();
3875 
3876  for (/**/; DI != DE; ++DI) {
3877  if (LookupResult::isVisible(SemaRef, *DI)) {
3878  if (!AnyVisibleDecls) {
3879  // Found a visible decl, discard all hidden ones.
3880  AnyVisibleDecls = true;
3881  NewDecls.clear();
3882  }
3883  NewDecls.push_back(*DI);
3884  } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3885  NewDecls.push_back(*DI);
3886  }
3887 
3888  if (NewDecls.empty())
3889  TC = TypoCorrection();
3890  else {
3891  TC.setCorrectionDecls(NewDecls);
3892  TC.setRequiresImport(!AnyVisibleDecls);
3893  }
3894 }
3895 
3896 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
3897 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3898 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3900  NestedNameSpecifier *NNS,
3902  if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3903  getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3904  else
3905  Identifiers.clear();
3906 
3907  const IdentifierInfo *II = nullptr;
3908 
3909  switch (NNS->getKind()) {
3911  II = NNS->getAsIdentifier();
3912  break;
3913 
3915  if (NNS->getAsNamespace()->isAnonymousNamespace())
3916  return;
3917  II = NNS->getAsNamespace()->getIdentifier();
3918  break;
3919 
3921  II = NNS->getAsNamespaceAlias()->getIdentifier();
3922  break;
3923 
3926  II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3927  break;
3928 
3931  return;
3932  }
3933 
3934  if (II)
3935  Identifiers.push_back(II);
3936 }
3937 
3939  DeclContext *Ctx, bool InBaseClass) {
3940  // Don't consider hidden names for typo correction.
3941  if (Hiding)
3942  return;
3943 
3944  // Only consider entities with identifiers for names, ignoring
3945  // special names (constructors, overloaded operators, selectors,
3946  // etc.).
3947  IdentifierInfo *Name = ND->getIdentifier();
3948  if (!Name)
3949  return;
3950 
3951  // Only consider visible declarations and declarations from modules with
3952  // names that exactly match.
3953  if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
3954  return;
3955 
3956  FoundName(Name->getName());
3957 }
3958 
3960  // Compute the edit distance between the typo and the name of this
3961  // entity, and add the identifier to the list of results.
3962  addName(Name, nullptr);
3963 }
3964 
3966  // Compute the edit distance between the typo and this keyword,
3967  // and add the keyword to the list of results.
3968  addName(Keyword, nullptr, nullptr, true);
3969 }
3970 
3971 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3972  NestedNameSpecifier *NNS, bool isKeyword) {
3973  // Use a simple length-based heuristic to determine the minimum possible
3974  // edit distance. If the minimum isn't good enough, bail out early.
3975  StringRef TypoStr = Typo->getName();
3976  unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3977  if (MinED && TypoStr.size() / MinED < 3)
3978  return;
3979 
3980  // Compute an upper bound on the allowable edit distance, so that the
3981  // edit-distance algorithm can short-circuit.
3982  unsigned UpperBound = (TypoStr.size() + 2) / 3;
3983  unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
3984  if (ED > UpperBound) return;
3985 
3986  TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
3987  if (isKeyword) TC.makeKeyword();
3988  TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
3989  addCorrection(TC);
3990 }
3991 
3992 static const unsigned MaxTypoDistanceResultSets = 5;
3993 
3995  StringRef TypoStr = Typo->getName();
3996  StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3997 
3998  // For very short typos, ignore potential corrections that have a different
3999  // base identifier from the typo or which have a normalized edit distance
4000  // longer than the typo itself.
4001  if (TypoStr.size() < 3 &&
4002  (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4003  return;
4004 
4005  // If the correction is resolved but is not viable, ignore it.
4006  if (Correction.isResolved()) {
4007  checkCorrectionVisibility(SemaRef, Correction);
4008  if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4009  return;
4010  }
4011 
4012  TypoResultList &CList =
4013  CorrectionResults[Correction.getEditDistance(false)][Name];
4014 
4015  if (!CList.empty() && !CList.back().isResolved())
4016  CList.pop_back();
4017  if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4018  std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4019  for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4020  RI != RIEnd; ++RI) {
4021  // If the Correction refers to a decl already in the result list,
4022  // replace the existing result if the string representation of Correction
4023  // comes before the current result alphabetically, then stop as there is
4024  // nothing more to be done to add Correction to the candidate set.
4025  if (RI->getCorrectionDecl() == NewND) {
4026  if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4027  *RI = Correction;
4028  return;
4029  }
4030  }
4031  }
4032  if (CList.empty() || Correction.isResolved())
4033  CList.push_back(Correction);
4034 
4035  while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4036  CorrectionResults.erase(std::prev(CorrectionResults.end()));
4037 }
4038 
4040  const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4041  SearchNamespaces = true;
4042 
4043  for (auto KNPair : KnownNamespaces)
4044  Namespaces.addNameSpecifier(KNPair.first);
4045 
4046  bool SSIsTemplate = false;
4047  if (NestedNameSpecifier *NNS =
4048  (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4049  if (const Type *T = NNS->getAsType())
4050  SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4051  }
4052  // Do not transform this into an iterator-based loop. The loop body can
4053  // trigger the creation of further types (through lazy deserialization) and
4054  // invalid iterators into this list.
4055  auto &Types = SemaRef.getASTContext().getTypes();
4056  for (unsigned I = 0; I != Types.size(); ++I) {
4057  const auto *TI = Types[I];
4058  if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4059  CD = CD->getCanonicalDecl();
4060  if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4061  !CD->isUnion() && CD->getIdentifier() &&
4062  (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4063  (CD->isBeingDefined() || CD->isCompleteDefinition()))
4064  Namespaces.addNameSpecifier(CD);
4065  }
4066  }
4067 }
4068 
4070  if (++CurrentTCIndex < ValidatedCorrections.size())
4071  return ValidatedCorrections[CurrentTCIndex];
4072 
4073  CurrentTCIndex = ValidatedCorrections.size();
4074  while (!CorrectionResults.empty()) {
4075  auto DI = CorrectionResults.begin();
4076  if (DI->second.empty()) {
4077  CorrectionResults.erase(DI);
4078  continue;
4079  }
4080 
4081  auto RI = DI->second.begin();
4082  if (RI->second.empty()) {
4083  DI->second.erase(RI);
4084  performQualifiedLookups();
4085  continue;
4086  }
4087 
4088  TypoCorrection TC = RI->second.pop_back_val();
4089  if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4090  ValidatedCorrections.push_back(TC);
4091  return ValidatedCorrections[CurrentTCIndex];
4092  }
4093  }
4094  return ValidatedCorrections[0]; // The empty correction.
4095 }
4096 
4097 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4098  IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4099  DeclContext *TempMemberContext = MemberContext;
4100  CXXScopeSpec *TempSS = SS.get();
4101 retry_lookup:
4102  LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4103  EnteringContext,
4104  CorrectionValidator->IsObjCIvarLookup,
4105  Name == Typo && !Candidate.WillReplaceSpecifier());
4106  switch (Result.getResultKind()) {
4110  if (TempSS) {
4111  // Immediately retry the lookup without the given CXXScopeSpec
4112  TempSS = nullptr;
4113  Candidate.WillReplaceSpecifier(true);
4114  goto retry_lookup;
4115  }
4116  if (TempMemberContext) {
4117  if (SS && !TempSS)
4118  TempSS = SS.get();
4119  TempMemberContext = nullptr;
4120  goto retry_lookup;
4121  }
4122  if (SearchNamespaces)
4123  QualifiedResults.push_back(Candidate);
4124  break;
4125 
4127  // We don't deal with ambiguities.
4128  break;
4129 
4130  case LookupResult::Found:
4132  // Store all of the Decls for overloaded symbols
4133  for (auto *TRD : Result)
4134  Candidate.addCorrectionDecl(TRD);
4135  checkCorrectionVisibility(SemaRef, Candidate);
4136  if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4137  if (SearchNamespaces)
4138  QualifiedResults.push_back(Candidate);
4139  break;
4140  }
4141  Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4142  return true;
4143  }
4144  return false;
4145 }
4146 
4147 void TypoCorrectionConsumer::performQualifiedLookups() {
4148  unsigned TypoLen = Typo->getName().size();
4149  for (const TypoCorrection &QR : QualifiedResults) {
4150  for (const auto &NSI : Namespaces) {
4151  DeclContext *Ctx = NSI.DeclCtx;
4152  const Type *NSType = NSI.NameSpecifier->getAsType();
4153 
4154  // If the current NestedNameSpecifier refers to a class and the
4155  // current correction candidate is the name of that class, then skip
4156  // it as it is unlikely a qualified version of the class' constructor
4157  // is an appropriate correction.
4158  if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4159  nullptr) {
4160  if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4161  continue;
4162  }
4163 
4164  TypoCorrection TC(QR);
4165  TC.ClearCorrectionDecls();
4166  TC.setCorrectionSpecifier(NSI.NameSpecifier);
4167  TC.setQualifierDistance(NSI.EditDistance);
4168  TC.setCallbackDistance(0); // Reset the callback distance
4169 
4170  // If the current correction candidate and namespace combination are
4171  // too far away from the original typo based on the normalized edit
4172  // distance, then skip performing a qualified name lookup.
4173  unsigned TmpED = TC.getEditDistance(true);
4174  if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4175  TypoLen / TmpED < 3)
4176  continue;
4177 
4178  Result.clear();
4179  Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4180  if (!SemaRef.LookupQualifiedName(Result, Ctx))
4181  continue;
4182 
4183  // Any corrections added below will be validated in subsequent
4184  // iterations of the main while() loop over the Consumer's contents.
4185  switch (Result.getResultKind()) {
4186  case LookupResult::Found:
4188  if (SS && SS->isValid()) {
4189  std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4190  std::string OldQualified;
4191  llvm::raw_string_ostream OldOStream(OldQualified);
4192  SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4193  OldOStream << Typo->getName();
4194  // If correction candidate would be an identical written qualified
4195  // identifier, then the existing CXXScopeSpec probably included a
4196  // typedef that didn't get accounted for properly.
4197  if (OldOStream.str() == NewQualified)
4198  break;
4199  }
4200  for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4201  TRD != TRDEnd; ++TRD) {
4202  if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4203  NSType ? NSType->getAsCXXRecordDecl()
4204  : nullptr,
4205  TRD.getPair()) == Sema::AR_accessible)
4206  TC.addCorrectionDecl(*TRD);
4207  }
4208  if (TC.isResolved()) {
4209  TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4210  addCorrection(TC);
4211  }
4212  break;
4213  }
4218  break;
4219  }
4220  }
4221  }
4222  QualifiedResults.clear();
4223 }
4224 
4225 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4226  ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4227  : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4228  if (NestedNameSpecifier *NNS =
4229  CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4230  llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4231  NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4232 
4233  getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4234  }
4235  // Build the list of identifiers that would be used for an absolute
4236  // (from the global context) NestedNameSpecifier referring to the current
4237  // context.
4238  for (DeclContext *C : llvm::reverse(CurContextChain)) {
4239  if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4240  CurContextIdentifiers.push_back(ND->getIdentifier());
4241  }
4242 
4243  // Add the global context as a NestedNameSpecifier
4244  SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4246  DistanceMap[1].push_back(SI);
4247 }
4248 
4249 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4250  DeclContext *Start) -> DeclContextList {
4251  assert(Start && "Building a context chain from a null context");
4252  DeclContextList Chain;
4253  for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4254  DC = DC->getLookupParent()) {
4255  NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4256  if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4257  !(ND && ND->isAnonymousNamespace()))
4258  Chain.push_back(DC->getPrimaryContext());
4259  }
4260  return Chain;
4261 }
4262 
4263 unsigned
4264 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4265  DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4266  unsigned NumSpecifiers = 0;
4267  for (DeclContext *C : llvm::reverse(DeclChain)) {
4268  if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4269  NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4270  ++NumSpecifiers;
4271  } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4272  NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4273  RD->getTypeForDecl());
4274  ++NumSpecifiers;
4275  }
4276  }
4277  return NumSpecifiers;
4278 }
4279 
4280 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4281  DeclContext *Ctx) {
4282  NestedNameSpecifier *NNS = nullptr;
4283  unsigned NumSpecifiers = 0;
4284  DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4285  DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4286 
4287  // Eliminate common elements from the two DeclContext chains.
4288  for (DeclContext *C : llvm::reverse(CurContextChain)) {
4289  if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4290  break;
4291  NamespaceDeclChain.pop_back();
4292  }
4293 
4294  // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4295  NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4296 
4297  // Add an explicit leading '::' specifier if needed.
4298  if (NamespaceDeclChain.empty()) {
4299  // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4300  NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4301  NumSpecifiers =
4302  buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4303  } else if (NamedDecl *ND =
4304  dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4305  IdentifierInfo *Name = ND->getIdentifier();
4306  bool SameNameSpecifier = false;
4307  if (std::find(CurNameSpecifierIdentifiers.begin(),
4308  CurNameSpecifierIdentifiers.end(),
4309  Name) != CurNameSpecifierIdentifiers.end()) {
4310  std::string NewNameSpecifier;
4311  llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4312  SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4313  getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4314  NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4315  SpecifierOStream.flush();
4316  SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4317  }
4318  if (SameNameSpecifier ||
4319  std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4320  Name) != CurContextIdentifiers.end()) {
4321  // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4322  NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4323  NumSpecifiers =
4324  buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4325  }
4326  }
4327 
4328  // If the built NestedNameSpecifier would be replacing an existing
4329  // NestedNameSpecifier, use the number of component identifiers that
4330  // would need to be changed as the edit distance instead of the number
4331  // of components in the built NestedNameSpecifier.
4332  if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4333  SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4334  getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4335  NumSpecifiers = llvm::ComputeEditDistance(
4336  llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4337  llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4338  }
4339 
4340  SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4341  DistanceMap[NumSpecifiers].push_back(SI);
4342 }
4343 
4344 /// Perform name lookup for a possible result for typo correction.
4345 static void LookupPotentialTypoResult(Sema &SemaRef,
4346  LookupResult &Res,
4347  IdentifierInfo *Name,
4348  Scope *S, CXXScopeSpec *SS,
4349  DeclContext *MemberContext,
4350  bool EnteringContext,
4351  bool isObjCIvarLookup,
4352  bool FindHidden) {
4353  Res.suppressDiagnostics();
4354  Res.clear();
4355  Res.setLookupName(Name);
4356  Res.setAllowHidden(FindHidden);
4357  if (MemberContext) {
4358  if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4359  if (isObjCIvarLookup) {
4360  if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4361  Res.addDecl(Ivar);
4362  Res.resolveKind();
4363  return;
4364  }
4365  }
4366 
4367  if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4369  Res.addDecl(Prop);
4370  Res.resolveKind();
4371  return;
4372  }
4373  }
4374 
4375  SemaRef.LookupQualifiedName(Res, MemberContext);
4376  return;
4377  }
4378 
4379  SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4380  EnteringContext);
4381 
4382  // Fake ivar lookup; this should really be part of
4383  // LookupParsedName.
4384  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4385  if (Method->isInstanceMethod() && Method->getClassInterface() &&
4386  (Res.empty() ||
4387  (Res.isSingleResult() &&
4389  if (ObjCIvarDecl *IV
4390  = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4391  Res.addDecl(IV);
4392  Res.resolveKind();
4393  }
4394  }
4395  }
4396 }
4397 
4398 /// Add keywords to the consumer as possible typo corrections.
4399 static void AddKeywordsToConsumer(Sema &SemaRef,
4400  TypoCorrectionConsumer &Consumer,
4402  bool AfterNestedNameSpecifier) {
4403  if (AfterNestedNameSpecifier) {
4404  // For 'X::', we know exactly which keywords can appear next.
4405  Consumer.addKeywordResult("template");
4406  if (CCC.WantExpressionKeywords)
4407  Consumer.addKeywordResult("operator");
4408  return;
4409  }
4410 
4411  if (CCC.WantObjCSuper)
4412  Consumer.addKeywordResult("super");
4413 
4414  if (CCC.WantTypeSpecifiers) {
4415  // Add type-specifier keywords to the set of results.
4416  static const char *const CTypeSpecs[] = {
4417  "char", "const", "double", "enum", "float", "int", "long", "short",
4418  "signed", "struct", "union", "unsigned", "void", "volatile",
4419  "_Complex", "_Imaginary",
4420  // storage-specifiers as well
4421  "extern", "inline", "static", "typedef"
4422  };
4423 
4424  const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4425  for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4426  Consumer.addKeywordResult(CTypeSpecs[I]);
4427 
4428  if (SemaRef.getLangOpts().C99)
4429  Consumer.addKeywordResult("restrict");
4430  if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
4431  Consumer.addKeywordResult("bool");
4432  else if (SemaRef.getLangOpts().C99)
4433  Consumer.addKeywordResult("_Bool");
4434 
4435  if (SemaRef.getLangOpts().CPlusPlus) {
4436  Consumer.addKeywordResult("class");
4437  Consumer.addKeywordResult("typename");
4438  Consumer.addKeywordResult("wchar_t");
4439 
4440  if (SemaRef.getLangOpts().CPlusPlus11) {
4441  Consumer.addKeywordResult("char16_t");
4442  Consumer.addKeywordResult("char32_t");
4443  Consumer.addKeywordResult("constexpr");
4444  Consumer.addKeywordResult("decltype");
4445  Consumer.addKeywordResult("thread_local");
4446  }
4447  }
4448 
4449  if (SemaRef.getLangOpts().GNUKeywords)
4450  Consumer.addKeywordResult("typeof");
4451  } else if (CCC.WantFunctionLikeCasts) {
4452  static const char *const CastableTypeSpecs[] = {
4453  "char", "double", "float", "int", "long", "short",
4454  "signed", "unsigned", "void"
4455  };
4456  for (auto *kw : CastableTypeSpecs)
4457  Consumer.addKeywordResult(kw);
4458  }
4459 
4460  if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
4461  Consumer.addKeywordResult("const_cast");
4462  Consumer.addKeywordResult("dynamic_cast");
4463  Consumer.addKeywordResult("reinterpret_cast");
4464  Consumer.addKeywordResult("static_cast");
4465  }
4466 
4467  if (CCC.WantExpressionKeywords) {
4468  Consumer.addKeywordResult("sizeof");
4469  if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
4470  Consumer.addKeywordResult("false");
4471  Consumer.addKeywordResult("true");
4472  }
4473 
4474  if (SemaRef.getLangOpts().CPlusPlus) {
4475  static const char *const CXXExprs[] = {
4476  "delete", "new", "operator", "throw", "typeid"
4477  };
4478  const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4479  for (unsigned I = 0; I != NumCXXExprs; ++I)
4480  Consumer.addKeywordResult(CXXExprs[I]);
4481 
4482  if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4483  cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4484  Consumer.addKeywordResult("this");
4485 
4486  if (SemaRef.getLangOpts().CPlusPlus11) {
4487  Consumer.addKeywordResult("alignof");
4488  Consumer.addKeywordResult("nullptr");
4489  }
4490  }
4491 
4492  if (SemaRef.getLangOpts().C11) {
4493  // FIXME: We should not suggest _Alignof if the alignof macro
4494  // is present.
4495  Consumer.addKeywordResult("_Alignof");
4496  }
4497  }
4498 
4499  if (CCC.WantRemainingKeywords) {
4500  if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4501  // Statements.
4502  static const char *const CStmts[] = {
4503  "do", "else", "for", "goto", "if", "return", "switch", "while" };
4504  const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4505  for (unsigned I = 0; I != NumCStmts; ++I)
4506  Consumer.addKeywordResult(CStmts[I]);
4507 
4508  if (SemaRef.getLangOpts().CPlusPlus) {
4509  Consumer.addKeywordResult("catch");
4510  Consumer.addKeywordResult("try");
4511  }
4512 
4513  if (S && S->getBreakParent())
4514  Consumer.addKeywordResult("break");
4515 
4516  if (S && S->getContinueParent())
4517  Consumer.addKeywordResult("continue");
4518 
4519  if (SemaRef.getCurFunction() &&
4520  !SemaRef.getCurFunction()->SwitchStack.empty()) {
4521  Consumer.addKeywordResult("case");
4522  Consumer.addKeywordResult("default");
4523  }
4524  } else {
4525  if (SemaRef.getLangOpts().CPlusPlus) {
4526  Consumer.addKeywordResult("namespace");
4527  Consumer.addKeywordResult("template");
4528  }
4529 
4530  if (S && S->isClassScope()) {
4531  Consumer.addKeywordResult("explicit");
4532  Consumer.addKeywordResult("friend");
4533  Consumer.addKeywordResult("mutable");
4534  Consumer.addKeywordResult("private");
4535  Consumer.addKeywordResult("protected");
4536  Consumer.addKeywordResult("public");
4537  Consumer.addKeywordResult("virtual");
4538  }
4539  }
4540 
4541  if (SemaRef.getLangOpts().CPlusPlus) {
4542  Consumer.addKeywordResult("using");
4543 
4544  if (SemaRef.getLangOpts().CPlusPlus11)
4545  Consumer.addKeywordResult("static_assert");
4546  }
4547  }
4548 }
4549 
4550 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4551  const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4552  Scope *S, CXXScopeSpec *SS,
4553  std::unique_ptr<CorrectionCandidateCallback> CCC,
4554  DeclContext *MemberContext, bool EnteringContext,
4555  const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
4556 
4557  if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4558  DisableTypoCorrection)
4559  return nullptr;
4560 
4561  // In Microsoft mode, don't perform typo correction in a template member
4562  // function dependent context because it interferes with the "lookup into
4563  // dependent bases of class templates" feature.
4564  if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4565  isa<CXXMethodDecl>(CurContext))
4566  return nullptr;
4567 
4568  // We only attempt to correct typos for identifiers.
4569  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4570  if (!Typo)
4571  return nullptr;
4572 
4573  // If the scope specifier itself was invalid, don't try to correct
4574  // typos.
4575  if (SS && SS->isInvalid())
4576  return nullptr;
4577 
4578  // Never try to correct typos during any kind of code synthesis.
4579  if (!CodeSynthesisContexts.empty())
4580  return nullptr;
4581 
4582  // Don't try to correct 'super'.
4583  if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4584  return nullptr;
4585 
4586  // Abort if typo correction already failed for this specific typo.
4587  IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4588  if (locs != TypoCorrectionFailures.end() &&
4589  locs->second.count(TypoName.getLoc()))
4590  return nullptr;
4591 
4592  // Don't try to correct the identifier "vector" when in AltiVec mode.
4593  // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4594  // remove this workaround.
4595  if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
4596  return nullptr;
4597 
4598  // Provide a stop gap for files that are just seriously broken. Trying
4599  // to correct all typos can turn into a HUGE performance penalty, causing
4600  // some files to take minutes to get rejected by the parser.
4601  unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4602  if (Limit && TyposCorrected >= Limit)
4603  return nullptr;
4604  ++TyposCorrected;
4605 
4606  // If we're handling a missing symbol error, using modules, and the
4607  // special search all modules option is used, look for a missing import.
4608  if (ErrorRecovery && getLangOpts().Modules &&
4609  getLangOpts().ModulesSearchAll) {
4610  // The following has the side effect of loading the missing module.
4611  getModuleLoader().lookupMissingImports(Typo->getName(),
4612  TypoName.getBeginLoc());
4613  }
4614 
4615  CorrectionCandidateCallback &CCCRef = *CCC;
4616  auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4617  *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4618  EnteringContext);
4619 
4620  // Perform name lookup to find visible, similarly-named entities.
4621  bool IsUnqualifiedLookup = false;
4622  DeclContext *QualifiedDC = MemberContext;
4623  if (MemberContext) {
4624  LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4625 
4626  // Look in qualified interfaces.
4627  if (OPT) {
4628  for (auto *I : OPT->quals())
4629  LookupVisibleDecls(I, LookupKind, *Consumer);
4630  }
4631  } else if (SS && SS->isSet()) {
4632  QualifiedDC = computeDeclContext(*SS, EnteringContext);
4633  if (!QualifiedDC)
4634  return nullptr;
4635 
4636  LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4637  } else {
4638  IsUnqualifiedLookup = true;
4639  }
4640 
4641  // Determine whether we are going to search in the various namespaces for
4642  // corrections.
4643  bool SearchNamespaces
4644  = getLangOpts().CPlusPlus &&
4645  (IsUnqualifiedLookup || (SS && SS->isSet()));
4646 
4647  if (IsUnqualifiedLookup || SearchNamespaces) {
4648  // For unqualified lookup, look through all of the names that we have
4649  // seen in this translation unit.
4650  // FIXME: Re-add the ability to skip very unlikely potential corrections.
4651  for (const auto &I : Context.Idents)
4652  Consumer->FoundName(I.getKey());
4653 
4654  // Walk through identifiers in external identifier sources.
4655  // FIXME: Re-add the ability to skip very unlikely potential corrections.
4656  if (IdentifierInfoLookup *External
4657  = Context.Idents.getExternalIdentifierLookup()) {
4658  std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4659  do {
4660  StringRef Name = Iter->Next();
4661  if (Name.empty())
4662  break;
4663 
4664  Consumer->FoundName(Name);
4665  } while (true);
4666  }
4667  }
4668 
4669  AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4670 
4671  // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4672  // to search those namespaces.
4673  if (SearchNamespaces) {
4674  // Load any externally-known namespaces.
4675  if (ExternalSource && !LoadedExternalKnownNamespaces) {
4676  SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4677  LoadedExternalKnownNamespaces = true;
4678  ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4679  for (auto *N : ExternalKnownNamespaces)
4680  KnownNamespaces[N] = true;
4681  }
4682 
4683  Consumer->addNamespaces(KnownNamespaces);
4684  }
4685 
4686  return Consumer;
4687 }
4688 
4689 /// Try to "correct" a typo in the source code by finding
4690 /// visible declarations whose names are similar to the name that was
4691 /// present in the source code.
4692 ///
4693 /// \param TypoName the \c DeclarationNameInfo structure that contains
4694 /// the name that was present in the source code along with its location.
4695 ///
4696 /// \param LookupKind the name-lookup criteria used to search for the name.
4697 ///
4698 /// \param S the scope in which name lookup occurs.
4699 ///
4700 /// \param SS the nested-name-specifier that precedes the name we're
4701 /// looking for, if present.
4702 ///
4703 /// \param CCC A CorrectionCandidateCallback object that provides further
4704 /// validation of typo correction candidates. It also provides flags for
4705 /// determining the set of keywords permitted.
4706 ///
4707 /// \param MemberContext if non-NULL, the context in which to look for
4708 /// a member access expression.
4709 ///
4710 /// \param EnteringContext whether we're entering the context described by
4711 /// the nested-name-specifier SS.
4712 ///
4713 /// \param OPT when non-NULL, the search for visible declarations will
4714 /// also walk the protocols in the qualified interfaces of \p OPT.
4715 ///
4716 /// \returns a \c TypoCorrection containing the corrected name if the typo
4717 /// along with information such as the \c NamedDecl where the corrected name
4718 /// was declared, and any additional \c NestedNameSpecifier needed to access
4719 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4721  Sema::LookupNameKind LookupKind,
4722  Scope *S, CXXScopeSpec *SS,
4723  std::unique_ptr<CorrectionCandidateCallback> CCC,
4724  CorrectTypoKind Mode,
4725  DeclContext *MemberContext,
4726  bool EnteringContext,
4727  const ObjCObjectPointerType *OPT,
4728  bool RecordFailure) {
4729  assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
4730 
4731  // Always let the ExternalSource have the first chance at correction, even
4732  // if we would otherwise have given up.
4733  if (ExternalSource) {
4734  if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4735  TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
4736  return Correction;
4737  }
4738 
4739  // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4740  // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4741  // some instances of CTC_Unknown, while WantRemainingKeywords is true
4742  // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4743  bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
4744 
4745  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4746  auto Consumer = makeTypoCorrectionConsumer(
4747  TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4748  EnteringContext, OPT, Mode == CTK_ErrorRecovery);
4749 
4750  if (!Consumer)
4751  return TypoCorrection();
4752 
4753  // If we haven't found anything, we're done.
4754  if (Consumer->empty())
4755  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4756 
4757  // Make sure the best edit distance (prior to adding any namespace qualifiers)
4758  // is not more that about a third of the length of the typo's identifier.
4759  unsigned ED = Consumer->getBestEditDistance(true);
4760  unsigned TypoLen = Typo->getName().size();
4761  if (ED > 0 && TypoLen / ED < 3)
4762  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4763 
4764  TypoCorrection BestTC = Consumer->getNextCorrection();
4765  TypoCorrection SecondBestTC = Consumer->getNextCorrection();
4766  if (!BestTC)
4767  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4768 
4769  ED = BestTC.getEditDistance();
4770 
4771  if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
4772  // If this was an unqualified lookup and we believe the callback
4773  // object wouldn't have filtered out possible corrections, note
4774  // that no correction was found.
4775  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4776  }
4777 
4778  // If only a single name remains, return that result.
4779  if (!SecondBestTC ||
4780  SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4781  const TypoCorrection &Result = BestTC;
4782 
4783  // Don't correct to a keyword that's the same as the typo; the keyword
4784  // wasn't actually in scope.
4785  if (ED == 0 && Result.isKeyword())
4786  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4787 
4788  TypoCorrection TC = Result;
4789  TC.setCorrectionRange(SS, TypoName);
4790  checkCorrectionVisibility(*this, TC);
4791  return TC;
4792  } else if (SecondBestTC && ObjCMessageReceiver) {
4793  // Prefer 'super' when we're completing in a message-receiver
4794  // context.
4795 
4796  if (BestTC.getCorrection().getAsString() != "super") {
4797  if (SecondBestTC.getCorrection().getAsString() == "super")
4798  BestTC = SecondBestTC;
4799  else if ((*Consumer)["super"].front().isKeyword())
4800  BestTC = (*Consumer)["super"].front();
4801  }
4802  // Don't correct to a keyword that's the same as the typo; the keyword
4803  // wasn't actually in scope.
4804  if (BestTC.getEditDistance() == 0 ||
4805  BestTC.getCorrection().getAsString() != "super")
4806  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4807 
4808  BestTC.setCorrectionRange(SS, TypoName);
4809  return BestTC;
4810  }
4811 
4812  // Record the failure's location if needed and return an empty correction. If
4813  // this was an unqualified lookup and we believe the callback object did not
4814  // filter out possible corrections, also cache the failure for the typo.
4815  return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
4816 }
4817 
4818 /// Try to "correct" a typo in the source code by finding
4819 /// visible declarations whose names are similar to the name that was
4820 /// present in the source code.
4821 ///
4822 /// \param TypoName the \c DeclarationNameInfo structure that contains
4823 /// the name that was present in the source code along with its location.
4824 ///
4825 /// \param LookupKind the name-lookup criteria used to search for the name.
4826 ///
4827 /// \param S the scope in which name lookup occurs.
4828 ///
4829 /// \param SS the nested-name-specifier that precedes the name we're
4830 /// looking for, if present.
4831 ///
4832 /// \param CCC A CorrectionCandidateCallback object that provides further
4833 /// validation of typo correction candidates. It also provides flags for
4834 /// determining the set of keywords permitted.
4835 ///
4836 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4837 /// diagnostics when the actual typo correction is attempted.
4838 ///
4839 /// \param TRC A TypoRecoveryCallback functor that will be used to build an
4840 /// Expr from a typo correction candidate.
4841 ///
4842 /// \param MemberContext if non-NULL, the context in which to look for
4843 /// a member access expression.
4844 ///
4845 /// \param EnteringContext whether we're entering the context described by
4846 /// the nested-name-specifier SS.
4847 ///
4848 /// \param OPT when non-NULL, the search for visible declarations will
4849 /// also walk the protocols in the qualified interfaces of \p OPT.
4850 ///
4851 /// \returns a new \c TypoExpr that will later be replaced in the AST with an
4852 /// Expr representing the result of performing typo correction, or nullptr if
4853 /// typo correction is not possible. If nullptr is returned, no diagnostics will
4854 /// be emitted and it is the responsibility of the caller to emit any that are
4855 /// needed.
4857  const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4858  Scope *S, CXXScopeSpec *SS,
4859  std::unique_ptr<CorrectionCandidateCallback> CCC,
4861  DeclContext *MemberContext, bool EnteringContext,
4862  const ObjCObjectPointerType *OPT) {
4863  assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
4864 
4865  auto Consumer = makeTypoCorrectionConsumer(
4866  TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4867  EnteringContext, OPT, Mode == CTK_ErrorRecovery);
4868 
4869  // Give the external sema source a chance to correct the typo.
4870  TypoCorrection ExternalTypo;
4871  if (ExternalSource && Consumer) {
4872  ExternalTypo = ExternalSource->CorrectTypo(
4873  TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4874  MemberContext, EnteringContext, OPT);
4875  if (ExternalTypo)
4876  Consumer->addCorrection(ExternalTypo);
4877  }
4878 
4879  if (!Consumer || Consumer->empty())
4880  return nullptr;
4881 
4882  // Make sure the best edit distance (prior to adding any namespace qualifiers)
4883  // is not more that about a third of the length of the typo's identifier.
4884  unsigned ED = Consumer->getBestEditDistance(true);
4885  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4886  if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
4887  return nullptr;
4888 
4889  ExprEvalContexts.back().NumTypos++;
4890  return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
4891 }
4892 
4894  if (!CDecl) return;
4895 
4896  if (isKeyword())
4897  CorrectionDecls.clear();
4898 
4899  CorrectionDecls.push_back(CDecl);
4900 
4901  if (!CorrectionName)
4902  CorrectionName = CDecl->getDeclName();
4903 }
4904 
4905 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4906  if (CorrectionNameSpec) {
4907  std::string tmpBuffer;
4908  llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4909  CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4910  PrefixOStream << CorrectionName;
4911  return PrefixOStream.str();
4912  }
4913 
4914  return CorrectionName.getAsString();
4915 }
4916 
4918  const TypoCorrection &candidate) {
4919  if (!candidate.isResolved())
4920  return true;
4921 
4922  if (candidate.isKeyword())
4923  return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4924  WantRemainingKeywords || WantObjCSuper;
4925 
4926  bool HasNonType = false;
4927  bool HasStaticMethod = false;
4928  bool HasNonStaticMethod = false;
4929  for (Decl *D : candidate) {
4930  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4931  D = FTD->getTemplatedDecl();
4932  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4933  if (Method->isStatic())
4934  HasStaticMethod = true;
4935  else
4936  HasNonStaticMethod = true;
4937  }
4938  if (!isa<TypeDecl>(D))
4939  HasNonType = true;
4940  }
4941 
4942  if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4943  !candidate.getCorrectionSpecifier())
4944  return false;
4945 
4946  return WantTypeSpecifiers || HasNonType;
4947 }
4948 
4950  bool HasExplicitTemplateArgs,
4951  MemberExpr *ME)
4952  : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
4953  CurContext(SemaRef.CurContext), MemberFn(ME) {
4954  WantTypeSpecifiers = false;
4955  WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
4956  WantRemainingKeywords = false;
4957 }
4958 
4960  if (!candidate.getCorrectionDecl())
4961  return candidate.isKeyword();
4962 
4963  for (auto *C : candidate) {
4964  FunctionDecl *FD = nullptr;
4965  NamedDecl *ND = C->getUnderlyingDecl();
4966  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4967  FD = FTD->getTemplatedDecl();
4968  if (!HasExplicitTemplateArgs && !FD) {
4969  if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4970  // If the Decl is neither a function nor a template function,
4971  // determine if it is a pointer or reference to a function. If so,
4972  // check against the number of arguments expected for the pointee.
4973  QualType ValType = cast<ValueDecl>(ND)->getType();
4974  if (ValType.isNull())
4975  continue;
4976  if (ValType->isAnyPointerType() || ValType->isReferenceType())
4977  ValType = ValType->getPointeeType();
4978  if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4979  if (FPT->getNumParams() == NumArgs)
4980  return true;
4981  }
4982  }
4983 
4984  // Skip the current candidate if it is not a FunctionDecl or does not accept
4985  // the current number of arguments.
4986  if (!FD || !(FD->getNumParams() >= NumArgs &&
4987  FD->getMinRequiredArguments() <= NumArgs))
4988  continue;
4989 
4990  // If the current candidate is a non-static C++ method, skip the candidate
4991  // unless the method being corrected--or the current DeclContext, if the
4992  // function being corrected is not a method--is a method in the same class
4993  // or a descendent class of the candidate's parent class.
4994  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4995  if (MemberFn || !MD->isStatic()) {
4996  CXXMethodDecl *CurMD =
4997  MemberFn
4998  ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4999  : dyn_cast_or_null<CXXMethodDecl>(CurContext);
5000  CXXRecordDecl *CurRD =
5001  CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5002  CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5003  if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5004  continue;
5005  }
5006  }
5007  return true;
5008  }
5009  return false;
5010 }
5011 
5012 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5013  const PartialDiagnostic &TypoDiag,
5014  bool ErrorRecovery) {
5015  diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5016  ErrorRecovery);
5017 }
5018 
5019 /// Find which declaration we should import to provide the definition of
5020 /// the given declaration.
5022  if (VarDecl *VD = dyn_cast<VarDecl>(D))
5023  return VD->getDefinition();
5024  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5025  return FD->getDefinition();
5026  if (TagDecl *TD = dyn_cast<TagDecl>(D))
5027  return TD->getDefinition();
5028  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
5029  return ID->getDefinition();
5030  if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
5031  return PD->getDefinition();
5032  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5033  return getDefinitionToImport(TD->getTemplatedDecl());
5034  return nullptr;
5035 }
5036 
5038  MissingImportKind MIK, bool Recover) {
5039  // Suggest importing a module providing the definition of this entity, if
5040  // possible.
5041  NamedDecl *Def = getDefinitionToImport(Decl);
5042  if (!Def)
5043  Def = Decl;
5044 
5045  Module *Owner = getOwningModule(Def);
5046  assert(Owner && "definition of hidden declaration is not in a module");
5047 
5048  llvm::SmallVector<Module*, 8> OwningModules;
5049  OwningModules.push_back(Owner);
5050  auto Merged = Context.getModulesWithMergedDefinition(Def);
5051  OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5052 
5053  diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
5054  Recover);
5055 }
5056 
5057 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5058 /// suggesting the addition of a #include of the specified file.
5060  const FileEntry *E) {
5061  bool IsSystem;
5062  auto Path =
5064  return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5065 }
5066 
5068  SourceLocation DeclLoc,
5069  ArrayRef<Module *> Modules,
5070  MissingImportKind MIK, bool Recover) {
5071  assert(!Modules.empty());
5072 
5073  // Weed out duplicates from module list.
5074  llvm::SmallVector<Module*, 8> UniqueModules;
5075  llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5076  for (auto *M : Modules)
5077  if (UniqueModuleSet.insert(M).second)
5078  UniqueModules.push_back(M);
5079  Modules = UniqueModules;
5080 
5081  if (Modules.size() > 1) {
5082  std::string ModuleList;
5083  unsigned N = 0;
5084  for (Module *M : Modules) {
5085  ModuleList += "\n ";
5086  if (++N == 5 && N != Modules.size()) {
5087  ModuleList += "[...]";
5088  break;
5089  }
5090  ModuleList += M->getFullModuleName();
5091  }
5092 
5093  Diag(UseLoc, diag::err_module_unimported_use_multiple)
5094  << (int)MIK << Decl << ModuleList;
5095  } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
5096  UseLoc, Modules[0], DeclLoc)) {
5097  // The right way to make the declaration visible is to include a header;
5098  // suggest doing so.
5099  //
5100  // FIXME: Find a smart place to suggest inserting a #include, and add
5101  // a FixItHint there.
5102  Diag(UseLoc, diag::err_module_unimported_use_header)
5103  << (int)MIK << Decl << Modules[0]->getFullModuleName()
5104  << getIncludeStringForHeader(PP, E);
5105  } else {
5106  // FIXME: Add a FixItHint that imports the corresponding module.
5107  Diag(UseLoc, diag::err_module_unimported_use)
5108  << (int)MIK << Decl << Modules[0]->getFullModuleName();
5109  }
5110 
5111  unsigned DiagID;
5112  switch (MIK) {
5113  case MissingImportKind::Declaration:
5114  DiagID = diag::note_previous_declaration;
5115  break;
5116  case MissingImportKind::Definition:
5117  DiagID = diag::note_previous_definition;
5118  break;
5119  case MissingImportKind::DefaultArgument:
5120  DiagID = diag::note_default_argument_declared_here;
5121  break;
5122  case MissingImportKind::ExplicitSpecialization:
5123  DiagID = diag::note_explicit_specialization_declared_here;
5124  break;
5125  case MissingImportKind::PartialSpecialization:
5126  DiagID = diag::note_partial_specialization_declared_here;
5127  break;
5128  }
5129  Diag(DeclLoc, DiagID);
5130 
5131  // Try to recover by implicitly importing this module.
5132  if (Recover)
5133  createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5134 }
5135 
5136 /// Diagnose a successfully-corrected typo. Separated from the correction
5137 /// itself to allow external validation of the result, etc.
5138 ///
5139 /// \param Correction The result of performing typo correction.
5140 /// \param TypoDiag The diagnostic to produce. This will have the corrected
5141 /// string added to it (and usually also a fixit).
5142 /// \param PrevNote A note to use when indicating the location of the entity to
5143 /// which we are correcting. Will have the correction string added to it.
5144 /// \param ErrorRecovery If \c true (the default), the caller is going to
5145 /// recover from the typo as if the corrected string had been typed.
5146 /// In this case, \c PDiag must be an error, and we will attach a fixit
5147 /// to it.
5148 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5149  const PartialDiagnostic &TypoDiag,
5150  const PartialDiagnostic &PrevNote,
5151  bool ErrorRecovery) {
5152  std::string CorrectedStr = Correction.getAsString(getLangOpts());
5153  std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5155  Correction.getCorrectionRange(), CorrectedStr);
5156 
5157  // Maybe we're just missing a module import.
5158  if (Correction.requiresImport()) {
5159  NamedDecl *Decl = Correction.getFoundDecl();
5160  assert(Decl && "import required but no declaration to import");
5161 
5162  diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5163  MissingImportKind::Declaration, ErrorRecovery);
5164  return;
5165  }
5166 
5167  Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5168  << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5169 
5170  NamedDecl *ChosenDecl =
5171  Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5172  if (PrevNote.getDiagID() && ChosenDecl)
5173  Diag(ChosenDecl->getLocation(), PrevNote)
5174  << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5175 
5176  // Add any extra diagnostics.
5177  for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5178  Diag(Correction.getCorrectionRange().getBegin(), PD);
5179 }
5180 
5181 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5183  TypoRecoveryCallback TRC) {
5184  assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5185  auto TE = new (Context) TypoExpr(Context.DependentTy);
5186  auto &State = DelayedTypos[TE];
5187  State.Consumer = std::move(TCC);
5188  State.DiagHandler = std::move(TDG);
5189  State.RecoveryHandler = std::move(TRC);
5190  return TE;
5191 }
5192 
5193 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5194  auto Entry = DelayedTypos.find(TE);
5195  assert(Entry != DelayedTypos.end() &&
5196  "Failed to get the state for a TypoExpr!");
5197  return Entry->second;
5198 }
5199 
5201  DelayedTypos.erase(TE);
5202 }
5203 
5205  DeclarationNameInfo Name(II, IILoc);
5206  LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5207  R.suppressDiagnostics();
5208  R.setHideTags(false);
5209  LookupName(R, S);
5210  R.dump();
5211 }
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:2540
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:3358
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)
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:6755
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:3770
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:3771
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:6311
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:2793
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:6075
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:3574
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:3690
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...
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2695
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...
Definition: