clang  9.0.0svn
DeclBase.cpp
Go to the documentation of this file.
1 //===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Decl and DeclContext classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/DeclBase.h"
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/Type.h"
30 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/PointerIntPair.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/VersionTuple.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstddef>
48 #include <string>
49 #include <tuple>
50 #include <utility>
51 
52 using namespace clang;
53 
54 //===----------------------------------------------------------------------===//
55 // Statistics
56 //===----------------------------------------------------------------------===//
57 
58 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
59 #define ABSTRACT_DECL(DECL)
60 #include "clang/AST/DeclNodes.inc"
61 
64 }
65 
66 #define DECL(DERIVED, BASE) \
67  static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
68  "Alignment sufficient after objects prepended to " #DERIVED);
69 #define ABSTRACT_DECL(DECL)
70 #include "clang/AST/DeclNodes.inc"
71 
72 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
73  unsigned ID, std::size_t Extra) {
74  // Allocate an extra 8 bytes worth of storage, which ensures that the
75  // resulting pointer will still be 8-byte aligned.
76  static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
77  "Decl won't be misaligned");
78  void *Start = Context.Allocate(Size + Extra + 8);
79  void *Result = (char*)Start + 8;
80 
81  unsigned *PrefixPtr = (unsigned *)Result - 2;
82 
83  // Zero out the first 4 bytes; this is used to store the owning module ID.
84  PrefixPtr[0] = 0;
85 
86  // Store the global declaration ID in the second 4 bytes.
87  PrefixPtr[1] = ID;
88 
89  return Result;
90 }
91 
92 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
93  DeclContext *Parent, std::size_t Extra) {
94  assert(!Parent || &Parent->getParentASTContext() == &Ctx);
95  // With local visibility enabled, we track the owning module even for local
96  // declarations. We create the TU decl early and may not yet know what the
97  // LangOpts are, so conservatively allocate the storage.
98  if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
99  // Ensure required alignment of the resulting object by adding extra
100  // padding at the start if required.
101  size_t ExtraAlign =
102  llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
103  auto *Buffer = reinterpret_cast<char *>(
104  ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
105  Buffer += ExtraAlign;
106  auto *ParentModule =
107  Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
108  return new (Buffer) Module*(ParentModule) + 1;
109  }
110  return ::operator new(Size + Extra, Ctx);
111 }
112 
113 Module *Decl::getOwningModuleSlow() const {
114  assert(isFromASTFile() && "Not from AST file?");
116 }
117 
120 }
121 
122 const char *Decl::getDeclKindName() const {
123  switch (DeclKind) {
124  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
125 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
126 #define ABSTRACT_DECL(DECL)
127 #include "clang/AST/DeclNodes.inc"
128  }
129 }
130 
131 void Decl::setInvalidDecl(bool Invalid) {
132  InvalidDecl = Invalid;
133  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
134  if (!Invalid) {
135  return;
136  }
137 
138  if (!isa<ParmVarDecl>(this)) {
139  // Defensive maneuver for ill-formed code: we're likely not to make it to
140  // a point where we set the access specifier, so default it to "public"
141  // to avoid triggering asserts elsewhere in the front end.
143  }
144 
145  // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
146  // are invalid too.
147  if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
148  for (auto *Binding : DD->bindings()) {
149  Binding->setInvalidDecl();
150  }
151  }
152 }
153 
154 const char *DeclContext::getDeclKindName() const {
155  switch (getDeclKind()) {
156 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
157 #define ABSTRACT_DECL(DECL)
158 #include "clang/AST/DeclNodes.inc"
159  }
160  llvm_unreachable("Declaration context not in DeclNodes.inc!");
161 }
162 
163 bool Decl::StatisticsEnabled = false;
165  StatisticsEnabled = true;
166 }
167 
169  llvm::errs() << "\n*** Decl Stats:\n";
170 
171  int totalDecls = 0;
172 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
173 #define ABSTRACT_DECL(DECL)
174 #include "clang/AST/DeclNodes.inc"
175  llvm::errs() << " " << totalDecls << " decls total.\n";
176 
177  int totalBytes = 0;
178 #define DECL(DERIVED, BASE) \
179  if (n##DERIVED##s > 0) { \
180  totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
181  llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
182  << sizeof(DERIVED##Decl) << " each (" \
183  << n##DERIVED##s * sizeof(DERIVED##Decl) \
184  << " bytes)\n"; \
185  }
186 #define ABSTRACT_DECL(DECL)
187 #include "clang/AST/DeclNodes.inc"
188 
189  llvm::errs() << "Total bytes = " << totalBytes << "\n";
190 }
191 
192 void Decl::add(Kind k) {
193  switch (k) {
194 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
195 #define ABSTRACT_DECL(DECL)
196 #include "clang/AST/DeclNodes.inc"
197  }
198 }
199 
201  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
202  return TTP->isParameterPack();
203  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
204  return NTTP->isParameterPack();
205  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
206  return TTP->isParameterPack();
207  return false;
208 }
209 
210 bool Decl::isParameterPack() const {
211  if (const auto *Var = dyn_cast<VarDecl>(this))
212  return Var->isParameterPack();
213 
214  return isTemplateParameterPack();
215 }
216 
218  if (auto *FD = dyn_cast<FunctionDecl>(this))
219  return FD;
220  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
221  return FTD->getTemplatedDecl();
222  return nullptr;
223 }
224 
225 bool Decl::isTemplateDecl() const {
226  return isa<TemplateDecl>(this);
227 }
228 
230  if (auto *FD = dyn_cast<FunctionDecl>(this))
231  return FD->getDescribedFunctionTemplate();
232  else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
233  return RD->getDescribedClassTemplate();
234  else if (auto *VD = dyn_cast<VarDecl>(this))
235  return VD->getDescribedVarTemplate();
236  else if (auto *AD = dyn_cast<TypeAliasDecl>(this))
237  return AD->getDescribedAliasTemplate();
238 
239  return nullptr;
240 }
241 
242 bool Decl::isTemplated() const {
243  // A declaration is dependent if it is a template or a template pattern, or
244  // is within (lexcially for a friend, semantically otherwise) a dependent
245  // context.
246  // FIXME: Should local extern declarations be treated like friends?
247  if (auto *AsDC = dyn_cast<DeclContext>(this))
248  return AsDC->isDependentContext();
250  return DC->isDependentContext() || isTemplateDecl() || getDescribedTemplate();
251 }
252 
254  for (const DeclContext *DC = getDeclContext();
255  DC && !DC->isTranslationUnit() && !DC->isNamespace();
256  DC = DC->getParent())
257  if (DC->isFunctionOrMethod())
258  return DC;
259 
260  return nullptr;
261 }
262 
263 //===----------------------------------------------------------------------===//
264 // PrettyStackTraceDecl Implementation
265 //===----------------------------------------------------------------------===//
266 
267 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
268  SourceLocation TheLoc = Loc;
269  if (TheLoc.isInvalid() && TheDecl)
270  TheLoc = TheDecl->getLocation();
271 
272  if (TheLoc.isValid()) {
273  TheLoc.print(OS, SM);
274  OS << ": ";
275  }
276 
277  OS << Message;
278 
279  if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
280  OS << " '";
281  DN->printQualifiedName(OS);
282  OS << '\'';
283  }
284  OS << '\n';
285 }
286 
287 //===----------------------------------------------------------------------===//
288 // Decl Implementation
289 //===----------------------------------------------------------------------===//
290 
291 // Out-of-line virtual method providing a home for Decl.
292 Decl::~Decl() = default;
293 
295  DeclCtx = DC;
296 }
297 
299  if (DC == getLexicalDeclContext())
300  return;
301 
302  if (isInSemaDC()) {
303  setDeclContextsImpl(getDeclContext(), DC, getASTContext());
304  } else {
305  getMultipleDC()->LexicalDC = DC;
306  }
307 
308  // FIXME: We shouldn't be changing the lexical context of declarations
309  // imported from AST files.
310  if (!isFromASTFile()) {
311  setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
312  if (hasOwningModule())
313  setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
314  }
315 
316  assert(
318  getOwningModule()) &&
319  "hidden declaration has no owning module");
320 }
321 
322 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
323  ASTContext &Ctx) {
324  if (SemaDC == LexicalDC) {
325  DeclCtx = SemaDC;
326  } else {
327  auto *MDC = new (Ctx) Decl::MultipleDC();
328  MDC->SemanticDC = SemaDC;
329  MDC->LexicalDC = LexicalDC;
330  DeclCtx = MDC;
331  }
332 }
333 
335  const DeclContext *LDC = getLexicalDeclContext();
336  while (true) {
337  if (LDC->isFunctionOrMethod())
338  return true;
339  if (!isa<TagDecl>(LDC))
340  return false;
341  LDC = LDC->getLexicalParent();
342  }
343  return false;
344 }
345 
347  for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
348  if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
349  if (ND->isAnonymousNamespace())
350  return true;
351  }
352 
353  return false;
354 }
355 
357  const DeclContext *DC = getDeclContext();
358  return DC && DC->isStdNamespace();
359 }
360 
362  if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
363  return TUD;
364 
365  DeclContext *DC = getDeclContext();
366  assert(DC && "This decl is not contained in a translation unit!");
367 
368  while (!DC->isTranslationUnit()) {
369  DC = DC->getParent();
370  assert(DC && "This decl is not contained in a translation unit!");
371  }
372 
373  return cast<TranslationUnitDecl>(DC);
374 }
375 
378 }
379 
382 }
383 
384 unsigned Decl::getMaxAlignment() const {
385  if (!hasAttrs())
386  return 0;
387 
388  unsigned Align = 0;
389  const AttrVec &V = getAttrs();
390  ASTContext &Ctx = getASTContext();
391  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
392  for (; I != E; ++I)
393  Align = std::max(Align, I->getAlignment(Ctx));
394  return Align;
395 }
396 
397 bool Decl::isUsed(bool CheckUsedAttr) const {
398  const Decl *CanonD = getCanonicalDecl();
399  if (CanonD->Used)
400  return true;
401 
402  // Check for used attribute.
403  // Ask the most recent decl, since attributes accumulate in the redecl chain.
404  if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
405  return true;
406 
407  // The information may have not been deserialized yet. Force deserialization
408  // to complete the needed information.
409  return getMostRecentDecl()->getCanonicalDecl()->Used;
410 }
411 
413  if (isUsed(false))
414  return;
415 
416  if (C.getASTMutationListener())
418 
419  setIsUsed();
420 }
421 
422 bool Decl::isReferenced() const {
423  if (Referenced)
424  return true;
425 
426  // Check redeclarations.
427  for (const auto *I : redecls())
428  if (I->Referenced)
429  return true;
430 
431  return false;
432 }
433 
434 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
435  const Decl *Definition = nullptr;
436  if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
437  Definition = ID->getDefinition();
438  } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
439  Definition = PD->getDefinition();
440  } else if (auto *TD = dyn_cast<TagDecl>(this)) {
441  Definition = TD->getDefinition();
442  }
443  if (!Definition)
444  Definition = this;
445 
446  if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
447  return attr;
448  if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
449  return dcd->getAttr<ExternalSourceSymbolAttr>();
450  }
451 
452  return nullptr;
453 }
454 
455 bool Decl::hasDefiningAttr() const {
456  return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
457 }
458 
459 const Attr *Decl::getDefiningAttr() const {
460  if (auto *AA = getAttr<AliasAttr>())
461  return AA;
462  if (auto *IFA = getAttr<IFuncAttr>())
463  return IFA;
464  return nullptr;
465 }
466 
467 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
468  const ASTContext &Context) {
469  // Check if this is an App Extension "platform", and if so chop off
470  // the suffix for matching with the actual platform.
471  StringRef RealizedPlatform = A->getPlatform()->getName();
472  if (!Context.getLangOpts().AppExt)
473  return RealizedPlatform;
474  size_t suffix = RealizedPlatform.rfind("_app_extension");
475  if (suffix != StringRef::npos)
476  return RealizedPlatform.slice(0, suffix);
477  return RealizedPlatform;
478 }
479 
480 /// Determine the availability of the given declaration based on
481 /// the target platform.
482 ///
483 /// When it returns an availability result other than \c AR_Available,
484 /// if the \p Message parameter is non-NULL, it will be set to a
485 /// string describing why the entity is unavailable.
486 ///
487 /// FIXME: Make these strings localizable, since they end up in
488 /// diagnostics.
490  const AvailabilityAttr *A,
491  std::string *Message,
492  VersionTuple EnclosingVersion) {
493  if (EnclosingVersion.empty())
494  EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
495 
496  if (EnclosingVersion.empty())
497  return AR_Available;
498 
499  StringRef ActualPlatform = A->getPlatform()->getName();
500  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
501 
502  // Match the platform name.
503  if (getRealizedPlatform(A, Context) != TargetPlatform)
504  return AR_Available;
505 
506  StringRef PrettyPlatformName
507  = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
508 
509  if (PrettyPlatformName.empty())
510  PrettyPlatformName = ActualPlatform;
511 
512  std::string HintMessage;
513  if (!A->getMessage().empty()) {
514  HintMessage = " - ";
515  HintMessage += A->getMessage();
516  }
517 
518  // Make sure that this declaration has not been marked 'unavailable'.
519  if (A->getUnavailable()) {
520  if (Message) {
521  Message->clear();
522  llvm::raw_string_ostream Out(*Message);
523  Out << "not available on " << PrettyPlatformName
524  << HintMessage;
525  }
526 
527  return AR_Unavailable;
528  }
529 
530  // Make sure that this declaration has already been introduced.
531  if (!A->getIntroduced().empty() &&
532  EnclosingVersion < A->getIntroduced()) {
533  if (Message) {
534  Message->clear();
535  llvm::raw_string_ostream Out(*Message);
536  VersionTuple VTI(A->getIntroduced());
537  Out << "introduced in " << PrettyPlatformName << ' '
538  << VTI << HintMessage;
539  }
540 
541  return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
542  }
543 
544  // Make sure that this declaration hasn't been obsoleted.
545  if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
546  if (Message) {
547  Message->clear();
548  llvm::raw_string_ostream Out(*Message);
549  VersionTuple VTO(A->getObsoleted());
550  Out << "obsoleted in " << PrettyPlatformName << ' '
551  << VTO << HintMessage;
552  }
553 
554  return AR_Unavailable;
555  }
556 
557  // Make sure that this declaration hasn't been deprecated.
558  if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
559  if (Message) {
560  Message->clear();
561  llvm::raw_string_ostream Out(*Message);
562  VersionTuple VTD(A->getDeprecated());
563  Out << "first deprecated in " << PrettyPlatformName << ' '
564  << VTD << HintMessage;
565  }
566 
567  return AR_Deprecated;
568  }
569 
570  return AR_Available;
571 }
572 
574  VersionTuple EnclosingVersion,
575  StringRef *RealizedPlatform) const {
576  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
577  return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
578  RealizedPlatform);
579 
581  std::string ResultMessage;
582 
583  for (const auto *A : attrs()) {
584  if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
585  if (Result >= AR_Deprecated)
586  continue;
587 
588  if (Message)
589  ResultMessage = Deprecated->getMessage();
590 
591  Result = AR_Deprecated;
592  continue;
593  }
594 
595  if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
596  if (Message)
597  *Message = Unavailable->getMessage();
598  return AR_Unavailable;
599  }
600 
601  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
603  Message, EnclosingVersion);
604 
605  if (AR == AR_Unavailable) {
606  if (RealizedPlatform)
607  *RealizedPlatform = Availability->getPlatform()->getName();
608  return AR_Unavailable;
609  }
610 
611  if (AR > Result) {
612  Result = AR;
613  if (Message)
614  ResultMessage.swap(*Message);
615  }
616  continue;
617  }
618  }
619 
620  if (Message)
621  Message->swap(ResultMessage);
622  return Result;
623 }
624 
625 VersionTuple Decl::getVersionIntroduced() const {
626  const ASTContext &Context = getASTContext();
627  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
628  for (const auto *A : attrs()) {
629  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
630  if (getRealizedPlatform(Availability, Context) != TargetPlatform)
631  continue;
632  if (!Availability->getIntroduced().empty())
633  return Availability->getIntroduced();
634  }
635  }
636  return {};
637 }
638 
639 bool Decl::canBeWeakImported(bool &IsDefinition) const {
640  IsDefinition = false;
641 
642  // Variables, if they aren't definitions.
643  if (const auto *Var = dyn_cast<VarDecl>(this)) {
644  if (Var->isThisDeclarationADefinition()) {
645  IsDefinition = true;
646  return false;
647  }
648  return true;
649 
650  // Functions, if they aren't definitions.
651  } else if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
652  if (FD->hasBody()) {
653  IsDefinition = true;
654  return false;
655  }
656  return true;
657 
658  // Objective-C classes, if this is the non-fragile runtime.
659  } else if (isa<ObjCInterfaceDecl>(this) &&
661  return true;
662 
663  // Nothing else.
664  } else {
665  return false;
666  }
667 }
668 
669 bool Decl::isWeakImported() const {
670  bool IsDefinition;
671  if (!canBeWeakImported(IsDefinition))
672  return false;
673 
674  for (const auto *A : attrs()) {
675  if (isa<WeakImportAttr>(A))
676  return true;
677 
678  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
679  if (CheckAvailability(getASTContext(), Availability, nullptr,
680  VersionTuple()) == AR_NotYetIntroduced)
681  return true;
682  }
683  }
684 
685  return false;
686 }
687 
689  switch (DeclKind) {
690  case Function:
691  case CXXDeductionGuide:
692  case CXXMethod:
693  case CXXConstructor:
694  case ConstructorUsingShadow:
695  case CXXDestructor:
696  case CXXConversion:
697  case EnumConstant:
698  case Var:
699  case ImplicitParam:
700  case ParmVar:
701  case ObjCMethod:
702  case ObjCProperty:
703  case MSProperty:
704  return IDNS_Ordinary;
705  case Label:
706  return IDNS_Label;
707  case IndirectField:
708  return IDNS_Ordinary | IDNS_Member;
709 
710  case Binding:
711  case NonTypeTemplateParm:
712  case VarTemplate:
713  // These (C++-only) declarations are found by redeclaration lookup for
714  // tag types, so we include them in the tag namespace.
715  return IDNS_Ordinary | IDNS_Tag;
716 
717  case ObjCCompatibleAlias:
718  case ObjCInterface:
719  return IDNS_Ordinary | IDNS_Type;
720 
721  case Typedef:
722  case TypeAlias:
723  case TemplateTypeParm:
724  case ObjCTypeParam:
725  return IDNS_Ordinary | IDNS_Type;
726 
727  case UnresolvedUsingTypename:
729 
730  case UsingShadow:
731  return 0; // we'll actually overwrite this later
732 
733  case UnresolvedUsingValue:
734  return IDNS_Ordinary | IDNS_Using;
735 
736  case Using:
737  case UsingPack:
738  return IDNS_Using;
739 
740  case ObjCProtocol:
741  return IDNS_ObjCProtocol;
742 
743  case Field:
744  case ObjCAtDefsField:
745  case ObjCIvar:
746  return IDNS_Member;
747 
748  case Record:
749  case CXXRecord:
750  case Enum:
751  return IDNS_Tag | IDNS_Type;
752 
753  case Namespace:
754  case NamespaceAlias:
755  return IDNS_Namespace;
756 
757  case FunctionTemplate:
758  return IDNS_Ordinary;
759 
760  case ClassTemplate:
761  case TemplateTemplateParm:
762  case TypeAliasTemplate:
763  return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
764 
765  case OMPDeclareReduction:
766  return IDNS_OMPReduction;
767 
768  case OMPDeclareMapper:
769  return IDNS_OMPMapper;
770 
771  // Never have names.
772  case Friend:
773  case FriendTemplate:
774  case AccessSpec:
775  case LinkageSpec:
776  case Export:
777  case FileScopeAsm:
778  case StaticAssert:
779  case ObjCPropertyImpl:
780  case PragmaComment:
781  case PragmaDetectMismatch:
782  case Block:
783  case Captured:
784  case TranslationUnit:
785  case ExternCContext:
786  case Decomposition:
787 
788  case UsingDirective:
789  case BuiltinTemplate:
790  case ClassTemplateSpecialization:
791  case ClassTemplatePartialSpecialization:
792  case ClassScopeFunctionSpecialization:
793  case VarTemplateSpecialization:
794  case VarTemplatePartialSpecialization:
795  case ObjCImplementation:
796  case ObjCCategory:
797  case ObjCCategoryImpl:
798  case Import:
799  case OMPThreadPrivate:
800  case OMPAllocate:
801  case OMPRequires:
802  case OMPCapturedExpr:
803  case Empty:
804  // Never looked up by name.
805  return 0;
806  }
807 
808  llvm_unreachable("Invalid DeclKind!");
809 }
810 
811 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
812  assert(!HasAttrs && "Decl already contains attrs.");
813 
814  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
815  assert(AttrBlank.empty() && "HasAttrs was wrong?");
816 
817  AttrBlank = attrs;
818  HasAttrs = true;
819 }
820 
822  if (!HasAttrs) return;
823 
824  HasAttrs = false;
826 }
827 
828 void Decl::addAttr(Attr *A) {
829  if (!hasAttrs()) {
830  setAttrs(AttrVec(1, A));
831  return;
832  }
833 
834  AttrVec &Attrs = getAttrs();
835  if (!A->isInherited()) {
836  Attrs.push_back(A);
837  return;
838  }
839 
840  // Attribute inheritance is processed after attribute parsing. To keep the
841  // order as in the source code, add inherited attributes before non-inherited
842  // ones.
843  auto I = Attrs.begin(), E = Attrs.end();
844  for (; I != E; ++I) {
845  if (!(*I)->isInherited())
846  break;
847  }
848  Attrs.insert(I, A);
849 }
850 
851 const AttrVec &Decl::getAttrs() const {
852  assert(HasAttrs && "No attrs to get!");
853  return getASTContext().getDeclAttrs(this);
854 }
855 
857  Decl::Kind DK = D->getDeclKind();
858  switch(DK) {
859 #define DECL(NAME, BASE)
860 #define DECL_CONTEXT(NAME) \
861  case Decl::NAME: \
862  return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
863 #define DECL_CONTEXT_BASE(NAME)
864 #include "clang/AST/DeclNodes.inc"
865  default:
866 #define DECL(NAME, BASE)
867 #define DECL_CONTEXT_BASE(NAME) \
868  if (DK >= first##NAME && DK <= last##NAME) \
869  return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
870 #include "clang/AST/DeclNodes.inc"
871  llvm_unreachable("a decl that inherits DeclContext isn't handled");
872  }
873 }
874 
876  Decl::Kind DK = D->getKind();
877  switch(DK) {
878 #define DECL(NAME, BASE)
879 #define DECL_CONTEXT(NAME) \
880  case Decl::NAME: \
881  return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
882 #define DECL_CONTEXT_BASE(NAME)
883 #include "clang/AST/DeclNodes.inc"
884  default:
885 #define DECL(NAME, BASE)
886 #define DECL_CONTEXT_BASE(NAME) \
887  if (DK >= first##NAME && DK <= last##NAME) \
888  return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
889 #include "clang/AST/DeclNodes.inc"
890  llvm_unreachable("a decl that inherits DeclContext isn't handled");
891  }
892 }
893 
895  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
896  // FunctionDecl stores EndRangeLoc for this purpose.
897  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
898  const FunctionDecl *Definition;
899  if (FD->hasBody(Definition))
900  return Definition->getSourceRange().getEnd();
901  return {};
902  }
903 
904  if (Stmt *Body = getBody())
905  return Body->getSourceRange().getEnd();
906 
907  return {};
908 }
909 
910 bool Decl::AccessDeclContextSanity() const {
911 #ifndef NDEBUG
912  // Suppress this check if any of the following hold:
913  // 1. this is the translation unit (and thus has no parent)
914  // 2. this is a template parameter (and thus doesn't belong to its context)
915  // 3. this is a non-type template parameter
916  // 4. the context is not a record
917  // 5. it's invalid
918  // 6. it's a C++0x static_assert.
919  // 7. it's a block literal declaration
920  if (isa<TranslationUnitDecl>(this) ||
921  isa<TemplateTypeParmDecl>(this) ||
922  isa<NonTypeTemplateParmDecl>(this) ||
923  !getDeclContext() ||
924  !isa<CXXRecordDecl>(getDeclContext()) ||
925  isInvalidDecl() ||
926  isa<StaticAssertDecl>(this) ||
927  isa<BlockDecl>(this) ||
928  // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
929  // as DeclContext (?).
930  isa<ParmVarDecl>(this) ||
931  // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
932  // AS_none as access specifier.
933  isa<CXXRecordDecl>(this) ||
934  isa<ClassScopeFunctionSpecializationDecl>(this))
935  return true;
936 
937  assert(Access != AS_none &&
938  "Access specifier is AS_none inside a record decl");
939 #endif
940  return true;
941 }
942 
943 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
944 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
945 
946 int64_t Decl::getID() const {
947  return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
948 }
949 
950 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
951  QualType Ty;
952  if (const auto *D = dyn_cast<ValueDecl>(this))
953  Ty = D->getType();
954  else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
955  Ty = D->getUnderlyingType();
956  else
957  return nullptr;
958 
959  if (Ty->isFunctionPointerType())
960  Ty = Ty->getAs<PointerType>()->getPointeeType();
961  else if (Ty->isFunctionReferenceType())
962  Ty = Ty->getAs<ReferenceType>()->getPointeeType();
963  else if (BlocksToo && Ty->isBlockPointerType())
964  Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
965 
966  return Ty->getAs<FunctionType>();
967 }
968 
969 /// Starting at a given context (a Decl or DeclContext), look for a
970 /// code context that is not a closure (a lambda, block, etc.).
971 template <class T> static Decl *getNonClosureContext(T *D) {
972  if (getKind(D) == Decl::CXXMethod) {
973  auto *MD = cast<CXXMethodDecl>(D);
974  if (MD->getOverloadedOperator() == OO_Call &&
975  MD->getParent()->isLambda())
976  return getNonClosureContext(MD->getParent()->getParent());
977  return MD;
978  } else if (auto *FD = dyn_cast<FunctionDecl>(D))
979  return FD;
980  else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
981  return MD;
982  else if (auto *BD = dyn_cast<BlockDecl>(D))
983  return getNonClosureContext(BD->getParent());
984  else if (auto *CD = dyn_cast<CapturedDecl>(D))
985  return getNonClosureContext(CD->getParent());
986  else
987  return nullptr;
988 }
989 
992 }
993 
996 }
997 
998 //===----------------------------------------------------------------------===//
999 // DeclContext Implementation
1000 //===----------------------------------------------------------------------===//
1001 
1003  DeclContextBits.DeclKind = K;
1004  setHasExternalLexicalStorage(false);
1005  setHasExternalVisibleStorage(false);
1006  setNeedToReconcileExternalVisibleStorage(false);
1007  setHasLazyLocalLexicalLookups(false);
1008  setHasLazyExternalLexicalLookups(false);
1009  setUseQualifiedLookup(false);
1010 }
1011 
1012 bool DeclContext::classof(const Decl *D) {
1013  switch (D->getKind()) {
1014 #define DECL(NAME, BASE)
1015 #define DECL_CONTEXT(NAME) case Decl::NAME:
1016 #define DECL_CONTEXT_BASE(NAME)
1017 #include "clang/AST/DeclNodes.inc"
1018  return true;
1019  default:
1020 #define DECL(NAME, BASE)
1021 #define DECL_CONTEXT_BASE(NAME) \
1022  if (D->getKind() >= Decl::first##NAME && \
1023  D->getKind() <= Decl::last##NAME) \
1024  return true;
1025 #include "clang/AST/DeclNodes.inc"
1026  return false;
1027  }
1028 }
1029 
1030 DeclContext::~DeclContext() = default;
1031 
1032 /// Find the parent context of this context that will be
1033 /// used for unqualified name lookup.
1034 ///
1035 /// Generally, the parent lookup context is the semantic context. However, for
1036 /// a friend function the parent lookup context is the lexical context, which
1037 /// is the class in which the friend is declared.
1039  // FIXME: Find a better way to identify friends.
1040  if (isa<FunctionDecl>(this))
1041  if (getParent()->getRedeclContext()->isFileContext() &&
1042  getLexicalParent()->getRedeclContext()->isRecord())
1043  return getLexicalParent();
1044 
1045  return getParent();
1046 }
1047 
1049  const DeclContext *Ctx = this;
1050 
1051  do {
1052  if (Ctx->isClosure())
1053  return cast<BlockDecl>(Ctx);
1054  Ctx = Ctx->getParent();
1055  } while (Ctx);
1056 
1057  return nullptr;
1058 }
1059 
1061  return isNamespace() &&
1062  cast<NamespaceDecl>(this)->isInline();
1063 }
1064 
1066  if (!isNamespace())
1067  return false;
1068 
1069  const auto *ND = cast<NamespaceDecl>(this);
1070  if (ND->isInline()) {
1071  return ND->getParent()->isStdNamespace();
1072  }
1073 
1074  if (!getParent()->getRedeclContext()->isTranslationUnit())
1075  return false;
1076 
1077  const IdentifierInfo *II = ND->getIdentifier();
1078  return II && II->isStr("std");
1079 }
1080 
1082  if (isFileContext())
1083  return false;
1084 
1085  if (isa<ClassTemplatePartialSpecializationDecl>(this))
1086  return true;
1087 
1088  if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1089  if (Record->getDescribedClassTemplate())
1090  return true;
1091 
1092  if (Record->isDependentLambda())
1093  return true;
1094  }
1095 
1096  if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1097  if (Function->getDescribedFunctionTemplate())
1098  return true;
1099 
1100  // Friend function declarations are dependent if their *lexical*
1101  // context is dependent.
1102  if (cast<Decl>(this)->getFriendObjectKind())
1103  return getLexicalParent()->isDependentContext();
1104  }
1105 
1106  // FIXME: A variable template is a dependent context, but is not a
1107  // DeclContext. A context within it (such as a lambda-expression)
1108  // should be considered dependent.
1109 
1110  return getParent() && getParent()->isDependentContext();
1111 }
1112 
1114  if (getDeclKind() == Decl::Enum)
1115  return !cast<EnumDecl>(this)->isScoped();
1116  else if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1117  return true;
1118 
1119  return false;
1120 }
1121 
1122 static bool isLinkageSpecContext(const DeclContext *DC,
1124  while (DC->getDeclKind() != Decl::TranslationUnit) {
1125  if (DC->getDeclKind() == Decl::LinkageSpec)
1126  return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1127  DC = DC->getLexicalParent();
1128  }
1129  return false;
1130 }
1131 
1134 }
1135 
1137  const DeclContext *DC = this;
1138  while (DC->getDeclKind() != Decl::TranslationUnit) {
1139  if (DC->getDeclKind() == Decl::LinkageSpec &&
1140  cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1141  return cast<LinkageSpecDecl>(DC);
1142  DC = DC->getLexicalParent();
1143  }
1144  return nullptr;
1145 }
1146 
1149 }
1150 
1151 bool DeclContext::Encloses(const DeclContext *DC) const {
1152  if (getPrimaryContext() != this)
1153  return getPrimaryContext()->Encloses(DC);
1154 
1155  for (; DC; DC = DC->getParent())
1156  if (DC->getPrimaryContext() == this)
1157  return true;
1158  return false;
1159 }
1160 
1162  switch (getDeclKind()) {
1163  case Decl::TranslationUnit:
1164  case Decl::ExternCContext:
1165  case Decl::LinkageSpec:
1166  case Decl::Export:
1167  case Decl::Block:
1168  case Decl::Captured:
1169  case Decl::OMPDeclareReduction:
1170  case Decl::OMPDeclareMapper:
1171  // There is only one DeclContext for these entities.
1172  return this;
1173 
1174  case Decl::Namespace:
1175  // The original namespace is our primary context.
1176  return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1177 
1178  case Decl::ObjCMethod:
1179  return this;
1180 
1181  case Decl::ObjCInterface:
1182  if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1183  if (auto *Def = OID->getDefinition())
1184  return Def;
1185  return this;
1186 
1187  case Decl::ObjCProtocol:
1188  if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1189  if (auto *Def = OPD->getDefinition())
1190  return Def;
1191  return this;
1192 
1193  case Decl::ObjCCategory:
1194  return this;
1195 
1196  case Decl::ObjCImplementation:
1197  case Decl::ObjCCategoryImpl:
1198  return this;
1199 
1200  default:
1201  if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1202  // If this is a tag type that has a definition or is currently
1203  // being defined, that definition is our primary context.
1204  auto *Tag = cast<TagDecl>(this);
1205 
1206  if (TagDecl *Def = Tag->getDefinition())
1207  return Def;
1208 
1209  if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1210  // Note, TagType::getDecl returns the (partial) definition one exists.
1211  TagDecl *PossiblePartialDef = TagTy->getDecl();
1212  if (PossiblePartialDef->isBeingDefined())
1213  return PossiblePartialDef;
1214  } else {
1215  assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1216  }
1217 
1218  return Tag;
1219  }
1220 
1221  assert(getDeclKind() >= Decl::firstFunction &&
1222  getDeclKind() <= Decl::lastFunction &&
1223  "Unknown DeclContext kind");
1224  return this;
1225  }
1226 }
1227 
1228 void
1230  Contexts.clear();
1231 
1232  if (getDeclKind() != Decl::Namespace) {
1233  Contexts.push_back(this);
1234  return;
1235  }
1236 
1237  auto *Self = static_cast<NamespaceDecl *>(this);
1238  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1239  N = N->getPreviousDecl())
1240  Contexts.push_back(N);
1241 
1242  std::reverse(Contexts.begin(), Contexts.end());
1243 }
1244 
1245 std::pair<Decl *, Decl *>
1247  bool FieldsAlreadyLoaded) {
1248  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1249  Decl *FirstNewDecl = nullptr;
1250  Decl *PrevDecl = nullptr;
1251  for (auto *D : Decls) {
1252  if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1253  continue;
1254 
1255  if (PrevDecl)
1256  PrevDecl->NextInContextAndBits.setPointer(D);
1257  else
1258  FirstNewDecl = D;
1259 
1260  PrevDecl = D;
1261  }
1262 
1263  return std::make_pair(FirstNewDecl, PrevDecl);
1264 }
1265 
1266 /// We have just acquired external visible storage, and we already have
1267 /// built a lookup map. For every name in the map, pull in the new names from
1268 /// the external storage.
1269 void DeclContext::reconcileExternalVisibleStorage() const {
1270  assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1271  setNeedToReconcileExternalVisibleStorage(false);
1272 
1273  for (auto &Lookup : *LookupPtr)
1274  Lookup.second.setHasExternalDecls();
1275 }
1276 
1277 /// Load the declarations within this lexical storage from an
1278 /// external source.
1279 /// \return \c true if any declarations were added.
1280 bool
1281 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1282  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1283  assert(hasExternalLexicalStorage() && Source && "No external storage?");
1284 
1285  // Notify that we have a DeclContext that is initializing.
1286  ExternalASTSource::Deserializing ADeclContext(Source);
1287 
1288  // Load the external declarations, if any.
1289  SmallVector<Decl*, 64> Decls;
1290  setHasExternalLexicalStorage(false);
1291  Source->FindExternalLexicalDecls(this, Decls);
1292 
1293  if (Decls.empty())
1294  return false;
1295 
1296  // We may have already loaded just the fields of this record, in which case
1297  // we need to ignore them.
1298  bool FieldsAlreadyLoaded = false;
1299  if (const auto *RD = dyn_cast<RecordDecl>(this))
1300  FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1301 
1302  // Splice the newly-read declarations into the beginning of the list
1303  // of declarations.
1304  Decl *ExternalFirst, *ExternalLast;
1305  std::tie(ExternalFirst, ExternalLast) =
1306  BuildDeclChain(Decls, FieldsAlreadyLoaded);
1307  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1308  FirstDecl = ExternalFirst;
1309  if (!LastDecl)
1310  LastDecl = ExternalLast;
1311  return true;
1312 }
1313 
1316  DeclarationName Name) {
1317  ASTContext &Context = DC->getParentASTContext();
1318  StoredDeclsMap *Map;
1319  if (!(Map = DC->LookupPtr))
1320  Map = DC->CreateStoredDeclsMap(Context);
1321  if (DC->hasNeedToReconcileExternalVisibleStorage())
1322  DC->reconcileExternalVisibleStorage();
1323 
1324  (*Map)[Name].removeExternalDecls();
1325 
1326  return DeclContext::lookup_result();
1327 }
1328 
1331  DeclarationName Name,
1332  ArrayRef<NamedDecl*> Decls) {
1333  ASTContext &Context = DC->getParentASTContext();
1334  StoredDeclsMap *Map;
1335  if (!(Map = DC->LookupPtr))
1336  Map = DC->CreateStoredDeclsMap(Context);
1337  if (DC->hasNeedToReconcileExternalVisibleStorage())
1338  DC->reconcileExternalVisibleStorage();
1339 
1340  StoredDeclsList &List = (*Map)[Name];
1341 
1342  // Clear out any old external visible declarations, to avoid quadratic
1343  // performance in the redeclaration checks below.
1344  List.removeExternalDecls();
1345 
1346  if (!List.isNull()) {
1347  // We have both existing declarations and new declarations for this name.
1348  // Some of the declarations may simply replace existing ones. Handle those
1349  // first.
1351  for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1352  if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1353  Skip.push_back(I);
1354  Skip.push_back(Decls.size());
1355 
1356  // Add in any new declarations.
1357  unsigned SkipPos = 0;
1358  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1359  if (I == Skip[SkipPos])
1360  ++SkipPos;
1361  else
1362  List.AddSubsequentDecl(Decls[I]);
1363  }
1364  } else {
1365  // Convert the array to a StoredDeclsList.
1366  for (auto *D : Decls) {
1367  if (List.isNull())
1368  List.setOnlyValue(D);
1369  else
1370  List.AddSubsequentDecl(D);
1371  }
1372  }
1373 
1374  return List.getLookupResult();
1375 }
1376 
1378  if (hasExternalLexicalStorage())
1379  LoadLexicalDeclsFromExternalStorage();
1380  return decl_iterator(FirstDecl);
1381 }
1382 
1384  if (hasExternalLexicalStorage())
1385  LoadLexicalDeclsFromExternalStorage();
1386 
1387  return !FirstDecl;
1388 }
1389 
1391  return (D->getLexicalDeclContext() == this &&
1392  (D->NextInContextAndBits.getPointer() || D == LastDecl));
1393 }
1394 
1396  if (hasExternalLexicalStorage())
1397  LoadLexicalDeclsFromExternalStorage();
1398  return containsDecl(D);
1399 }
1400 
1401 /// shouldBeHidden - Determine whether a declaration which was declared
1402 /// within its semantic context should be invisible to qualified name lookup.
1403 static bool shouldBeHidden(NamedDecl *D) {
1404  // Skip unnamed declarations.
1405  if (!D->getDeclName())
1406  return true;
1407 
1408  // Skip entities that can't be found by name lookup into a particular
1409  // context.
1410  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1411  D->isTemplateParameter())
1412  return true;
1413 
1414  // Skip friends and local extern declarations unless they're the first
1415  // declaration of the entity.
1416  if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1417  D != D->getCanonicalDecl())
1418  return true;
1419 
1420  // Skip template specializations.
1421  // FIXME: This feels like a hack. Should DeclarationName support
1422  // template-ids, or is there a better way to keep specializations
1423  // from being visible?
1424  if (isa<ClassTemplateSpecializationDecl>(D))
1425  return true;
1426  if (auto *FD = dyn_cast<FunctionDecl>(D))
1427  if (FD->isFunctionTemplateSpecialization())
1428  return true;
1429 
1430  return false;
1431 }
1432 
1434  assert(D->getLexicalDeclContext() == this &&
1435  "decl being removed from non-lexical context");
1436  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1437  "decl is not in decls list");
1438 
1439  // Remove D from the decl chain. This is O(n) but hopefully rare.
1440  if (D == FirstDecl) {
1441  if (D == LastDecl)
1442  FirstDecl = LastDecl = nullptr;
1443  else
1444  FirstDecl = D->NextInContextAndBits.getPointer();
1445  } else {
1446  for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1447  assert(I && "decl not found in linked list");
1448  if (I->NextInContextAndBits.getPointer() == D) {
1449  I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1450  if (D == LastDecl) LastDecl = I;
1451  break;
1452  }
1453  }
1454  }
1455 
1456  // Mark that D is no longer in the decl chain.
1457  D->NextInContextAndBits.setPointer(nullptr);
1458 
1459  // Remove D from the lookup table if necessary.
1460  if (isa<NamedDecl>(D)) {
1461  auto *ND = cast<NamedDecl>(D);
1462 
1463  // Do not try to remove the declaration if that is invisible to qualified
1464  // lookup. E.g. template specializations are skipped.
1465  if (shouldBeHidden(ND))
1466  return;
1467 
1468  // Remove only decls that have a name
1469  if (!ND->getDeclName())
1470  return;
1471 
1472  auto *DC = D->getDeclContext();
1473  do {
1474  StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1475  if (Map) {
1476  StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1477  assert(Pos != Map->end() && "no lookup entry for decl");
1478  // Remove the decl only if it is contained.
1479  StoredDeclsList::DeclsTy *Vec = Pos->second.getAsVector();
1480  if ((Vec && is_contained(*Vec, ND)) || Pos->second.getAsDecl() == ND)
1481  Pos->second.remove(ND);
1482  }
1483  } while (DC->isTransparentContext() && (DC = DC->getParent()));
1484  }
1485 }
1486 
1488  assert(D->getLexicalDeclContext() == this &&
1489  "Decl inserted into wrong lexical context");
1490  assert(!D->getNextDeclInContext() && D != LastDecl &&
1491  "Decl already inserted into a DeclContext");
1492 
1493  if (FirstDecl) {
1494  LastDecl->NextInContextAndBits.setPointer(D);
1495  LastDecl = D;
1496  } else {
1497  FirstDecl = LastDecl = D;
1498  }
1499 
1500  // Notify a C++ record declaration that we've added a member, so it can
1501  // update its class-specific state.
1502  if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1503  Record->addedMember(D);
1504 
1505  // If this is a newly-created (not de-serialized) import declaration, wire
1506  // it in to the list of local import declarations.
1507  if (!D->isFromASTFile()) {
1508  if (auto *Import = dyn_cast<ImportDecl>(D))
1509  D->getASTContext().addedLocalImportDecl(Import);
1510  }
1511 }
1512 
1514  addHiddenDecl(D);
1515 
1516  if (auto *ND = dyn_cast<NamedDecl>(D))
1517  ND->getDeclContext()->getPrimaryContext()->
1518  makeDeclVisibleInContextWithFlags(ND, false, true);
1519 }
1520 
1522  addHiddenDecl(D);
1523 
1524  if (auto *ND = dyn_cast<NamedDecl>(D))
1525  ND->getDeclContext()->getPrimaryContext()->
1526  makeDeclVisibleInContextWithFlags(ND, true, true);
1527 }
1528 
1529 /// buildLookup - Build the lookup data structure with all of the
1530 /// declarations in this DeclContext (and any other contexts linked
1531 /// to it or transparent contexts nested within it) and return it.
1532 ///
1533 /// Note that the produced map may miss out declarations from an
1534 /// external source. If it does, those entries will be marked with
1535 /// the 'hasExternalDecls' flag.
1537  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1538 
1539  if (!hasLazyLocalLexicalLookups() &&
1540  !hasLazyExternalLexicalLookups())
1541  return LookupPtr;
1542 
1544  collectAllContexts(Contexts);
1545 
1546  if (hasLazyExternalLexicalLookups()) {
1547  setHasLazyExternalLexicalLookups(false);
1548  for (auto *DC : Contexts) {
1549  if (DC->hasExternalLexicalStorage()) {
1550  bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1551  setHasLazyLocalLexicalLookups(
1552  hasLazyLocalLexicalLookups() | LoadedDecls );
1553  }
1554  }
1555 
1556  if (!hasLazyLocalLexicalLookups())
1557  return LookupPtr;
1558  }
1559 
1560  for (auto *DC : Contexts)
1561  buildLookupImpl(DC, hasExternalVisibleStorage());
1562 
1563  // We no longer have any lazy decls.
1564  setHasLazyLocalLexicalLookups(false);
1565  return LookupPtr;
1566 }
1567 
1568 /// buildLookupImpl - Build part of the lookup data structure for the
1569 /// declarations contained within DCtx, which will either be this
1570 /// DeclContext, a DeclContext linked to it, or a transparent context
1571 /// nested within it.
1572 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1573  for (auto *D : DCtx->noload_decls()) {
1574  // Insert this declaration into the lookup structure, but only if
1575  // it's semantically within its decl context. Any other decls which
1576  // should be found in this context are added eagerly.
1577  //
1578  // If it's from an AST file, don't add it now. It'll get handled by
1579  // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1580  // in C++, we do not track external visible decls for the TU, so in
1581  // that case we need to collect them all here.
1582  if (auto *ND = dyn_cast<NamedDecl>(D))
1583  if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1584  (!ND->isFromASTFile() ||
1585  (isTranslationUnit() &&
1586  !getParentASTContext().getLangOpts().CPlusPlus)))
1587  makeDeclVisibleInContextImpl(ND, Internal);
1588 
1589  // If this declaration is itself a transparent declaration context
1590  // or inline namespace, add the members of this declaration of that
1591  // context (recursively).
1592  if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1593  if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1594  buildLookupImpl(InnerCtx, Internal);
1595  }
1596 }
1597 
1598 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1599 
1602  assert(getDeclKind() != Decl::LinkageSpec &&
1603  getDeclKind() != Decl::Export &&
1604  "should not perform lookups into transparent contexts");
1605 
1606  const DeclContext *PrimaryContext = getPrimaryContext();
1607  if (PrimaryContext != this)
1608  return PrimaryContext->lookup(Name);
1609 
1610  // If we have an external source, ensure that any later redeclarations of this
1611  // context have been loaded, since they may add names to the result of this
1612  // lookup (or add external visible storage).
1613  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1614  if (Source)
1615  (void)cast<Decl>(this)->getMostRecentDecl();
1616 
1617  if (hasExternalVisibleStorage()) {
1618  assert(Source && "external visible storage but no external source?");
1619 
1620  if (hasNeedToReconcileExternalVisibleStorage())
1621  reconcileExternalVisibleStorage();
1622 
1623  StoredDeclsMap *Map = LookupPtr;
1624 
1625  if (hasLazyLocalLexicalLookups() ||
1626  hasLazyExternalLexicalLookups())
1627  // FIXME: Make buildLookup const?
1628  Map = const_cast<DeclContext*>(this)->buildLookup();
1629 
1630  if (!Map)
1631  Map = CreateStoredDeclsMap(getParentASTContext());
1632 
1633  // If we have a lookup result with no external decls, we are done.
1634  std::pair<StoredDeclsMap::iterator, bool> R =
1635  Map->insert(std::make_pair(Name, StoredDeclsList()));
1636  if (!R.second && !R.first->second.hasExternalDecls())
1637  return R.first->second.getLookupResult();
1638 
1639  if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1640  if (StoredDeclsMap *Map = LookupPtr) {
1641  StoredDeclsMap::iterator I = Map->find(Name);
1642  if (I != Map->end())
1643  return I->second.getLookupResult();
1644  }
1645  }
1646 
1647  return {};
1648  }
1649 
1650  StoredDeclsMap *Map = LookupPtr;
1651  if (hasLazyLocalLexicalLookups() ||
1652  hasLazyExternalLexicalLookups())
1653  Map = const_cast<DeclContext*>(this)->buildLookup();
1654 
1655  if (!Map)
1656  return {};
1657 
1658  StoredDeclsMap::iterator I = Map->find(Name);
1659  if (I == Map->end())
1660  return {};
1661 
1662  return I->second.getLookupResult();
1663 }
1664 
1667  assert(getDeclKind() != Decl::LinkageSpec &&
1668  getDeclKind() != Decl::Export &&
1669  "should not perform lookups into transparent contexts");
1670 
1671  DeclContext *PrimaryContext = getPrimaryContext();
1672  if (PrimaryContext != this)
1673  return PrimaryContext->noload_lookup(Name);
1674 
1675  loadLazyLocalLexicalLookups();
1676  StoredDeclsMap *Map = LookupPtr;
1677  if (!Map)
1678  return {};
1679 
1680  StoredDeclsMap::iterator I = Map->find(Name);
1681  return I != Map->end() ? I->second.getLookupResult()
1682  : lookup_result();
1683 }
1684 
1685 // If we have any lazy lexical declarations not in our lookup map, add them
1686 // now. Don't import any external declarations, not even if we know we have
1687 // some missing from the external visible lookups.
1688 void DeclContext::loadLazyLocalLexicalLookups() {
1689  if (hasLazyLocalLexicalLookups()) {
1691  collectAllContexts(Contexts);
1692  for (auto *Context : Contexts)
1693  buildLookupImpl(Context, hasExternalVisibleStorage());
1694  setHasLazyLocalLexicalLookups(false);
1695  }
1696 }
1697 
1699  SmallVectorImpl<NamedDecl *> &Results) {
1700  Results.clear();
1701 
1702  // If there's no external storage, just perform a normal lookup and copy
1703  // the results.
1704  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1705  lookup_result LookupResults = lookup(Name);
1706  Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1707  return;
1708  }
1709 
1710  // If we have a lookup table, check there first. Maybe we'll get lucky.
1711  // FIXME: Should we be checking these flags on the primary context?
1712  if (Name && !hasLazyLocalLexicalLookups() &&
1713  !hasLazyExternalLexicalLookups()) {
1714  if (StoredDeclsMap *Map = LookupPtr) {
1715  StoredDeclsMap::iterator Pos = Map->find(Name);
1716  if (Pos != Map->end()) {
1717  Results.insert(Results.end(),
1718  Pos->second.getLookupResult().begin(),
1719  Pos->second.getLookupResult().end());
1720  return;
1721  }
1722  }
1723  }
1724 
1725  // Slow case: grovel through the declarations in our chain looking for
1726  // matches.
1727  // FIXME: If we have lazy external declarations, this will not find them!
1728  // FIXME: Should we CollectAllContexts and walk them all here?
1729  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1730  if (auto *ND = dyn_cast<NamedDecl>(D))
1731  if (ND->getDeclName() == Name)
1732  Results.push_back(ND);
1733  }
1734 }
1735 
1737  DeclContext *Ctx = this;
1738 
1739  // In C, a record type is the redeclaration context for its fields only. If
1740  // we arrive at a record context after skipping anything else, we should skip
1741  // the record as well. Currently, this means skipping enumerations because
1742  // they're the only transparent context that can exist within a struct or
1743  // union.
1744  bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1745  !getParentASTContext().getLangOpts().CPlusPlus;
1746 
1747  // Skip through contexts to get to the redeclaration context. Transparent
1748  // contexts are always skipped.
1749  while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1750  Ctx = Ctx->getParent();
1751  return Ctx;
1752 }
1753 
1755  DeclContext *Ctx = this;
1756  // Skip through non-namespace, non-translation-unit contexts.
1757  while (!Ctx->isFileContext())
1758  Ctx = Ctx->getParent();
1759  return Ctx->getPrimaryContext();
1760 }
1761 
1763  // Loop until we find a non-record context.
1764  RecordDecl *OutermostRD = nullptr;
1765  DeclContext *DC = this;
1766  while (DC->isRecord()) {
1767  OutermostRD = cast<RecordDecl>(DC);
1768  DC = DC->getLexicalParent();
1769  }
1770  return OutermostRD;
1771 }
1772 
1774  // For non-file contexts, this is equivalent to Equals.
1775  if (!isFileContext())
1776  return O->Equals(this);
1777 
1778  do {
1779  if (O->Equals(this))
1780  return true;
1781 
1782  const auto *NS = dyn_cast<NamespaceDecl>(O);
1783  if (!NS || !NS->isInline())
1784  break;
1785  O = NS->getParent();
1786  } while (O);
1787 
1788  return false;
1789 }
1790 
1792  DeclContext *PrimaryDC = this->getPrimaryContext();
1793  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1794  // If the decl is being added outside of its semantic decl context, we
1795  // need to ensure that we eagerly build the lookup information for it.
1796  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1797 }
1798 
1799 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1800  bool Recoverable) {
1801  assert(this == getPrimaryContext() && "expected a primary DC");
1802 
1803  if (!isLookupContext()) {
1804  if (isTransparentContext())
1805  getParent()->getPrimaryContext()
1806  ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1807  return;
1808  }
1809 
1810  // Skip declarations which should be invisible to name lookup.
1811  if (shouldBeHidden(D))
1812  return;
1813 
1814  // If we already have a lookup data structure, perform the insertion into
1815  // it. If we might have externally-stored decls with this name, look them
1816  // up and perform the insertion. If this decl was declared outside its
1817  // semantic context, buildLookup won't add it, so add it now.
1818  //
1819  // FIXME: As a performance hack, don't add such decls into the translation
1820  // unit unless we're in C++, since qualified lookup into the TU is never
1821  // performed.
1822  if (LookupPtr || hasExternalVisibleStorage() ||
1823  ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1824  (getParentASTContext().getLangOpts().CPlusPlus ||
1825  !isTranslationUnit()))) {
1826  // If we have lazily omitted any decls, they might have the same name as
1827  // the decl which we are adding, so build a full lookup table before adding
1828  // this decl.
1829  buildLookup();
1830  makeDeclVisibleInContextImpl(D, Internal);
1831  } else {
1832  setHasLazyLocalLexicalLookups(true);
1833  }
1834 
1835  // If we are a transparent context or inline namespace, insert into our
1836  // parent context, too. This operation is recursive.
1837  if (isTransparentContext() || isInlineNamespace())
1838  getParent()->getPrimaryContext()->
1839  makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1840 
1841  auto *DCAsDecl = cast<Decl>(this);
1842  // Notify that a decl was made visible unless we are a Tag being defined.
1843  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1844  if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1845  L->AddedVisibleDecl(this, D);
1846 }
1847 
1848 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1849  // Find or create the stored declaration map.
1850  StoredDeclsMap *Map = LookupPtr;
1851  if (!Map) {
1852  ASTContext *C = &getParentASTContext();
1853  Map = CreateStoredDeclsMap(*C);
1854  }
1855 
1856  // If there is an external AST source, load any declarations it knows about
1857  // with this declaration's name.
1858  // If the lookup table contains an entry about this name it means that we
1859  // have already checked the external source.
1860  if (!Internal)
1861  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1862  if (hasExternalVisibleStorage() &&
1863  Map->find(D->getDeclName()) == Map->end())
1864  Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1865 
1866  // Insert this declaration into the map.
1867  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1868 
1869  if (Internal) {
1870  // If this is being added as part of loading an external declaration,
1871  // this may not be the only external declaration with this name.
1872  // In this case, we never try to replace an existing declaration; we'll
1873  // handle that when we finalize the list of declarations for this name.
1874  DeclNameEntries.setHasExternalDecls();
1875  DeclNameEntries.AddSubsequentDecl(D);
1876  return;
1877  }
1878 
1879  if (DeclNameEntries.isNull()) {
1880  DeclNameEntries.setOnlyValue(D);
1881  return;
1882  }
1883 
1884  if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1885  // This declaration has replaced an existing one for which
1886  // declarationReplaces returns true.
1887  return;
1888  }
1889 
1890  // Put this declaration into the appropriate slot.
1891  DeclNameEntries.AddSubsequentDecl(D);
1892 }
1893 
1895  return cast<UsingDirectiveDecl>(*I);
1896 }
1897 
1898 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1899 /// this context.
1901  // FIXME: Use something more efficient than normal lookup for using
1902  // directives. In C++, using directives are looked up more than anything else.
1903  lookup_result Result = lookup(UsingDirectiveDecl::getName());
1904  return udir_range(Result.begin(), Result.end());
1905 }
1906 
1907 //===----------------------------------------------------------------------===//
1908 // Creation and Destruction of StoredDeclsMaps. //
1909 //===----------------------------------------------------------------------===//
1910 
1911 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1912  assert(!LookupPtr && "context already has a decls map");
1913  assert(getPrimaryContext() == this &&
1914  "creating decls map on non-primary context");
1915 
1916  StoredDeclsMap *M;
1917  bool Dependent = isDependentContext();
1918  if (Dependent)
1919  M = new DependentStoredDeclsMap();
1920  else
1921  M = new StoredDeclsMap();
1922  M->Previous = C.LastSDM;
1923  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1924  LookupPtr = M;
1925  return M;
1926 }
1927 
1928 void ASTContext::ReleaseDeclContextMaps() {
1929  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1930  // pointer because the subclass doesn't add anything that needs to
1931  // be deleted.
1932  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1933 }
1934 
1935 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1936  while (Map) {
1937  // Advance the iteration before we invalidate memory.
1938  llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1939 
1940  if (Dependent)
1941  delete static_cast<DependentStoredDeclsMap*>(Map);
1942  else
1943  delete Map;
1944 
1945  Map = Next.getPointer();
1946  Dependent = Next.getInt();
1947  }
1948 }
1949 
1952  const PartialDiagnostic &PDiag) {
1953  assert(Parent->isDependentContext()
1954  && "cannot iterate dependent diagnostics of non-dependent context");
1955  Parent = Parent->getPrimaryContext();
1956  if (!Parent->LookupPtr)
1957  Parent->CreateStoredDeclsMap(C);
1958 
1959  auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1960 
1961  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1962  // BumpPtrAllocator, rather than the ASTContext itself.
1963  PartialDiagnostic::Storage *DiagStorage = nullptr;
1964  if (PDiag.hasStorage())
1965  DiagStorage = new (C) PartialDiagnostic::Storage;
1966 
1967  auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1968 
1969  // TODO: Maybe we shouldn't reverse the order during insertion.
1970  DD->NextDiagnostic = Map->FirstDiagnostic;
1971  Map->FirstDiagnostic = DD;
1972 
1973  return DD;
1974 }
static StringRef getRealizedPlatform(const AvailabilityAttr *A, const ASTContext &Context)
Definition: DeclBase.cpp:467
Defines the clang::ASTContext interface.
Represents a function declaration or definition.
Definition: Decl.h:1748
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
void localUncachedLookup(DeclarationName Name, SmallVectorImpl< NamedDecl *> &Results)
A simplistic name lookup mechanism that performs name lookup into this declaration context without co...
Definition: DeclBase.cpp:1698
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled...
Definition: TargetInfo.h:1245
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:875
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:759
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2554
QualType getPointeeType() const
Definition: Type.h:2567
static bool shouldBeHidden(NamedDecl *D)
shouldBeHidden - Determine whether a declaration which was declared within its semantic context shoul...
Definition: DeclBase.cpp:1403
A (possibly-)qualified type.
Definition: Type.h:643
bool isBlockPointerType() const
Definition: Type.h:6359
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:4052
const char * getDeclKindName() const
Definition: DeclBase.cpp:122
llvm::PointerIntPair< Decl *, 2, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition: DeclBase.h:244
void AddSubsequentDecl(NamedDecl *D)
AddSubsequentDecl - This is called on the second and later decl when it is not a redeclaration to mer...
virtual void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl *> &Result)
Finds all declarations lexically contained within the given DeclContext, after applying an optional f...
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:856
bool isClosure() const
Definition: DeclBase.h:1805
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:986
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:486
static bool isLinkageSpecContext(const DeclContext *DC, LinkageSpecDecl::LanguageIDs ID)
Definition: DeclBase.cpp:1122
Stmt - This represents one statement.
Definition: Stmt.h:66
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3372
C Language Family Type Representation.
const char * getDeclKindName() const
Definition: DeclBase.cpp:154
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:34
static void add(Kind k)
Definition: DeclBase.cpp:192
Defines the C++ template declaration subclasses.
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:960
Defines types useful for describing an Objective-C runtime.
Represent a C++ namespace.
Definition: Decl.h:514
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:693
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:799
static Decl * getNonClosureContext(T *D)
Starting at a given context (a Decl or DeclContext), look for a code context that is not a closure (a...
Definition: DeclBase.cpp:971
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:253
unsigned Access
Access - Used by C++ decls for the access specifier.
Definition: DeclBase.h:325
bool HandleRedeclaration(NamedDecl *D, bool IsKnownNewer)
HandleRedeclaration - If this is a redeclaration of an existing decl, replace the old one with D and ...
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:754
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:380
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6818
bool hasLocalOwningModuleStorage() const
Definition: DeclBase.cpp:118
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1132
bool isInvalidDecl() const
Definition: DeclBase.h:553
ExternalSourceSymbolAttr * getExternalSourceSymbolAttr() const
Looks on this and related declarations for an applicable external source symbol attribute.
Definition: DeclBase.cpp:434
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:210
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1433
bool hasWeakClassImport() const
Does this runtime support weakly importing classes?
Definition: ObjCRuntime.h:361
Types, declared with &#39;struct foo&#39;, typedefs, etc.
Definition: DeclBase.h:132
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:334
Represents a struct/union/class.
Definition: Decl.h:3624
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1151
One of these records is kept for each identifier that is lexed.
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:346
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl *> Decls)
Definition: DeclBase.cpp:1330
QualType getPointeeType() const
Definition: Type.h:2671
void print(raw_ostream &OS, const SourceManager &SM) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1195
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c-base.h:40
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1896
Describes a module or submodule.
Definition: Module.h:64
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)
Update an out-of-date identifier.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1754
virtual bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name)
Find all declarations with the given name in the given context, and add them to the context by callin...
Namespaces, declared with &#39;namespace foo {}&#39;.
Definition: DeclBase.h:142
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:422
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition: DeclBase.h:786
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1536
static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name)
Definition: DeclBase.cpp:1315
ASTContext & getASTContext() const
Definition: Decl.h:119
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:828
Labels, declared with &#39;x:&#39; and referenced with &#39;goto x&#39;.
Definition: DeclBase.h:119
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:746
Represents a linkage specification.
Definition: DeclCXX.h:2954
Ordinary names.
Definition: DeclBase.h:146
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
Definition: DeclBase.cpp:1521
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1601
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:74
NodeId Parent
Definition: ASTDiff.cpp:191
Decl * getNextDeclInContext()
Definition: DeclBase.h:435
bool canBeWeakImported(bool &IsDefinition) const
Determines whether this symbol can be weak-imported, e.g., whether it would be well-formed to add the...
Definition: DeclBase.cpp:639
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:1900
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:573
Objective C @protocol.
Definition: DeclBase.h:149
llvm::iterator_range< udir_iterator > udir_range
Definition: DeclBase.h:2302
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition: DeclBase.h:2029
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl&#39;s underlying type to extract a FunctionType when possible. ...
Definition: DeclBase.cpp:950
void removeExternalDecls()
Remove any declarations which were imported from an external AST source.
int64_t getID() const
Definition: DeclBase.cpp:946
bool isInlineNamespace() const
Definition: DeclBase.cpp:1060
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1788
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3889
const Attr * getDefiningAttr() const
Return this declaration&#39;s defining attribute if it has one.
Definition: DeclBase.cpp:459
Defines the clang::LangOptions interface.
QualType getPointeeType() const
Definition: Type.h:2711
std::string Label
static unsigned getIdentifierNamespaceForKind(Kind DK)
Definition: DeclBase.cpp:688
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1390
#define V(N, I)
Definition: ASTContext.h:2907
bool isFunctionReferenceType() const
Definition: Type.h:6382
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:131
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:180
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1773
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:975
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1060
bool isFileContext() const
Definition: DeclBase.h:1842
DeclContext * getDeclContext()
Definition: DeclBase.h:438
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don&#39;t attempt to retr...
Definition: DeclBase.cpp:1666
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:994
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2446
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:200
bool containsDeclAndLoad(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1395
This declaration is an OpenMP user defined mapper.
Definition: DeclBase.h:183
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
bool isFunctionOrMethod() const
Definition: DeclBase.h:1824
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:207
This declaration has an owning module, and is visible when that module is imported.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:384
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1772
void collectAllContexts(SmallVectorImpl< DeclContext *> &Contexts)
Collects all of the declaration contexts that are semantically connected to this declaration context...
Definition: DeclBase.cpp:1229
SourceLocation getEnd() const
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1081
The result type of a method or function.
const SourceManager & SM
Definition: Format.cpp:1570
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:294
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:29
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:1111
virtual void DeclarationMarkedUsed(const Decl *D)
A declaration is marked used which was not previously marked used.
bool decls_empty() const
Definition: DeclBase.cpp:1383
AttrVec & getAttrs()
Definition: DeclBase.h:490
bool hasAttrs() const
Definition: DeclBase.h:484
Abstract interface for external sources of AST nodes.
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:225
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1765
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1791
DeclContext::lookup_result getLookupResult()
getLookupResult - Return an array of all the decls that this list represents.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:217
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1241
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition: DeclBase.cpp:625
Encodes a location in the source.
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:138
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:791
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1377
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3095
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
bool isStdNamespace() const
Definition: DeclBase.cpp:1065
This file defines OpenMP nodes for declarative directives.
void print(raw_ostream &OS) const override
Definition: DeclBase.cpp:267
DeclContext(Decl::Kind K)
Definition: DeclBase.cpp:1002
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:702
UsingDirectiveDecl * operator*() const
Definition: DeclBase.cpp:1894
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:397
An array of decls optimized for the common case of only containing one entry.
void dropAttrs()
Definition: DeclBase.cpp:821
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:669
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:672
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1978
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:948
Dataflow Directional Tag Classes.
void updateOutOfDate(IdentifierInfo &II) const
Update a potentially out-of-date declaration.
Definition: DeclBase.cpp:62
bool isValid() const
Return true if this is a valid SourceLocation object.
virtual Module * getModule(unsigned ID)
Retrieve the module that corresponds to the given module ID.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:403
bool isRecord() const
Definition: DeclBase.h:1851
attr_range attrs() const
Definition: DeclBase.h:501
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1762
The name of a declaration.
Kind getKind() const
Definition: DeclBase.h:432
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:990
Tags, declared with &#39;struct foo;&#39; and referenced with &#39;struct foo&#39;.
Definition: DeclBase.h:127
llvm::BumpPtrAllocator & getAllocator() const
Definition: ASTContext.h:668
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1081
A dependently-generated diagnostic.
Pointer to a block type.
Definition: Type.h:2656
static DependentDiagnostic * Create(ASTContext &Context, DeclContext *Parent, AccessNonce _, SourceLocation Loc, bool IsMemberAccess, AccessSpecifier AS, NamedDecl *TargetDecl, CXXRecordDecl *NamingClass, QualType BaseObjectType, const PartialDiagnostic &PDiag)
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:573
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2965
T * getAttr() const
Definition: DeclBase.h:538
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:714
virtual ~Decl()
void setOnlyValue(NamedDecl *ND)
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2690
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1736
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1136
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1513
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:412
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1096
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Defines the clang::SourceLocation class and associated facilities.
DeclContextLookupResult lookup_result
Definition: DeclBase.h:2225
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1487
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl *> Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1246
bool isInherited() const
Definition: Attr.h:97
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1038
void addAttr(Attr *A)
Definition: DeclBase.cpp:828
static bool classof(const Decl *D)
Definition: DeclBase.cpp:1012
Defines the clang::TargetInfo interface.
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1801
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3750
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:91
__DEVICE__ int max(int __a, int __b)
The top declaration context.
Definition: Decl.h:107
static void DestroyAll(StoredDeclsMap *Map, bool Dependent)
Definition: DeclBase.cpp:1935
static void PrintStats()
Definition: DeclBase.cpp:168
NamedDecl * getMostRecentDecl()
Definition: Decl.h:445
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1161
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
Definition: LangOptions.h:268
static void EnableStatistics()
Definition: DeclBase.cpp:164
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:298
This represents a decl that may have a name.
Definition: Decl.h:248
bool isTranslationUnit() const
Definition: DeclBase.h:1847
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:468
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration...
Definition: DeclBase.cpp:229
Represents C++ using-directive.
Definition: DeclCXX.h:3044
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity, such as &#39;alias&#39; or &#39;ifunc&#39;.
Definition: DeclBase.cpp:455
bool isFunctionPointerType() const
Definition: Type.h:6375
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
bool isInStdNamespace() const
Definition: DeclBase.cpp:356
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:361
const LangOptions & getLangOpts() const
Definition: ASTContext.h:710
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1048
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1147
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:242
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:894
Attr - This represents one attribute.
Definition: Attr.h:43
static AvailabilityResult CheckAvailability(ASTContext &Context, const AvailabilityAttr *A, std::string *Message, VersionTuple EnclosingVersion)
Determine the availability of the given declaration based on the target platform. ...
Definition: DeclBase.cpp:489
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3220
This declaration is a using declaration.
Definition: DeclBase.h:165
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:1113