1 //===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Decl and DeclContext classes.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/DeclBase.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DependentDiagnostic.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/Stmt.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/IdentifierTable.h"
31 #include "clang/Basic/LLVM.h"
32 #include "clang/Basic/LangOptions.h"
33 #include "clang/Basic/ObjCRuntime.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/VersionTuple.h"
45 #include "llvm/Support/raw_ostream.h"
53 using namespace clang;
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
60 #define ABSTRACT_DECL(DECL)
61 #include "clang/AST/DeclNodes.inc"
63 void Decl::updateOutOfDate(IdentifierInfo &II) const {
64 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
67 #define DECL(DERIVED, BASE) \
68 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
69 "Alignment sufficient after objects prepended to " #DERIVED);
70 #define ABSTRACT_DECL(DECL)
71 #include "clang/AST/DeclNodes.inc"
73 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
74 unsigned ID, std::size_t Extra) {
75 // Allocate an extra 8 bytes worth of storage, which ensures that the
76 // resulting pointer will still be 8-byte aligned.
77 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
78 "Decl won't be misaligned");
79 void *Start = Context.Allocate(Size + Extra + 8);
80 void *Result = (char*)Start + 8;
82 unsigned *PrefixPtr = (unsigned *)Result - 2;
84 // Zero out the first 4 bytes; this is used to store the owning module ID.
87 // Store the global declaration ID in the second 4 bytes.
93 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94 DeclContext *Parent, std::size_t Extra) {
95 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
96 // With local visibility enabled, we track the owning module even for local
97 // declarations. We create the TU decl early and may not yet know what the
98 // LangOpts are, so conservatively allocate the storage.
99 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
100 // Ensure required alignment of the resulting object by adding extra
101 // padding at the start if required.
103 llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl)));
104 auto *Buffer = reinterpret_cast<char *>(
105 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
106 Buffer += ExtraAlign;
108 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
109 return new (Buffer) Module*(ParentModule) + 1;
111 return ::operator new(Size + Extra, Ctx);
114 Module *Decl::getOwningModuleSlow() const {
115 assert(isFromASTFile() && "Not from AST file?");
116 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
119 bool Decl::hasLocalOwningModuleStorage() const {
120 return getASTContext().getLangOpts().trackLocalOwningModule();
123 const char *Decl::getDeclKindName() const {
125 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
126 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127 #define ABSTRACT_DECL(DECL)
128 #include "clang/AST/DeclNodes.inc"
132 void Decl::setInvalidDecl(bool Invalid) {
133 InvalidDecl = Invalid;
134 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
139 if (!isa<ParmVarDecl>(this)) {
140 // Defensive maneuver for ill-formed code: we're likely not to make it to
141 // a point where we set the access specifier, so default it to "public"
142 // to avoid triggering asserts elsewhere in the front end.
143 setAccess(AS_public);
146 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
148 if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
149 for (auto *Binding : DD->bindings()) {
150 Binding->setInvalidDecl();
155 const char *DeclContext::getDeclKindName() const {
156 switch (getDeclKind()) {
157 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
158 #define ABSTRACT_DECL(DECL)
159 #include "clang/AST/DeclNodes.inc"
161 llvm_unreachable("Declaration context not in DeclNodes.inc!");
164 bool Decl::StatisticsEnabled = false;
165 void Decl::EnableStatistics() {
166 StatisticsEnabled = true;
169 void Decl::PrintStats() {
170 llvm::errs() << "\n*** Decl Stats:\n";
173 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
174 #define ABSTRACT_DECL(DECL)
175 #include "clang/AST/DeclNodes.inc"
176 llvm::errs() << " " << totalDecls << " decls total.\n";
179 #define DECL(DERIVED, BASE) \
180 if (n##DERIVED##s > 0) { \
181 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
182 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
183 << sizeof(DERIVED##Decl) << " each (" \
184 << n##DERIVED##s * sizeof(DERIVED##Decl) \
187 #define ABSTRACT_DECL(DECL)
188 #include "clang/AST/DeclNodes.inc"
190 llvm::errs() << "Total bytes = " << totalBytes << "\n";
193 void Decl::add(Kind k) {
195 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
196 #define ABSTRACT_DECL(DECL)
197 #include "clang/AST/DeclNodes.inc"
201 bool Decl::isTemplateParameterPack() const {
202 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
203 return TTP->isParameterPack();
204 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
205 return NTTP->isParameterPack();
206 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
207 return TTP->isParameterPack();
211 bool Decl::isParameterPack() const {
212 if (const auto *Var = dyn_cast<VarDecl>(this))
213 return Var->isParameterPack();
215 return isTemplateParameterPack();
218 FunctionDecl *Decl::getAsFunction() {
219 if (auto *FD = dyn_cast<FunctionDecl>(this))
221 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
222 return FTD->getTemplatedDecl();
226 bool Decl::isTemplateDecl() const {
227 return isa<TemplateDecl>(this);
230 TemplateDecl *Decl::getDescribedTemplate() const {
231 if (auto *FD = dyn_cast<FunctionDecl>(this))
232 return FD->getDescribedFunctionTemplate();
233 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
234 return RD->getDescribedClassTemplate();
235 else if (auto *VD = dyn_cast<VarDecl>(this))
236 return VD->getDescribedVarTemplate();
237 else if (auto *AD = dyn_cast<TypeAliasDecl>(this))
238 return AD->getDescribedAliasTemplate();
243 const TemplateParameterList *Decl::getDescribedTemplateParams() const {
244 if (auto *TD = getDescribedTemplate())
245 return TD->getTemplateParameters();
246 if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))
247 return CTPSD->getTemplateParameters();
248 if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this))
249 return VTPSD->getTemplateParameters();
253 bool Decl::isTemplated() const {
254 // A declaration is templated if it is a template or a template pattern, or
255 // is within (lexcially for a friend, semantically otherwise) a dependent
257 // FIXME: Should local extern declarations be treated like friends?
258 if (auto *AsDC = dyn_cast<DeclContext>(this))
259 return AsDC->isDependentContext();
260 auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
261 return DC->isDependentContext() || isTemplateDecl() ||
262 getDescribedTemplateParams();
265 unsigned Decl::getTemplateDepth() const {
266 if (auto *DC = dyn_cast<DeclContext>(this))
267 if (DC->isFileContext())
270 if (auto *TPL = getDescribedTemplateParams())
271 return TPL->getDepth() + 1;
273 // If this is a dependent lambda, there might be an enclosing variable
274 // template. In this case, the next step is not the parent DeclContext (or
275 // even a DeclContext at all).
276 auto *RD = dyn_cast<CXXRecordDecl>(this);
277 if (RD && RD->isDependentLambda())
278 if (Decl *Context = RD->getLambdaContextDecl())
279 return Context->getTemplateDepth();
281 const DeclContext *DC =
282 getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
283 return cast<Decl>(DC)->getTemplateDepth();
286 const DeclContext *Decl::getParentFunctionOrMethod() const {
287 for (const DeclContext *DC = getDeclContext();
288 DC && !DC->isTranslationUnit() && !DC->isNamespace();
289 DC = DC->getParent())
290 if (DC->isFunctionOrMethod())
296 //===----------------------------------------------------------------------===//
297 // PrettyStackTraceDecl Implementation
298 //===----------------------------------------------------------------------===//
300 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
301 SourceLocation TheLoc = Loc;
302 if (TheLoc.isInvalid() && TheDecl)
303 TheLoc = TheDecl->getLocation();
305 if (TheLoc.isValid()) {
306 TheLoc.print(OS, SM);
312 if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
314 DN->printQualifiedName(OS);
320 //===----------------------------------------------------------------------===//
321 // Decl Implementation
322 //===----------------------------------------------------------------------===//
324 // Out-of-line virtual method providing a home for Decl.
325 Decl::~Decl() = default;
327 void Decl::setDeclContext(DeclContext *DC) {
331 void Decl::setLexicalDeclContext(DeclContext *DC) {
332 if (DC == getLexicalDeclContext())
336 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
338 getMultipleDC()->LexicalDC = DC;
341 // FIXME: We shouldn't be changing the lexical context of declarations
342 // imported from AST files.
343 if (!isFromASTFile()) {
344 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
345 if (hasOwningModule())
346 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
350 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
351 getOwningModule()) &&
352 "hidden declaration has no owning module");
355 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
357 if (SemaDC == LexicalDC) {
360 auto *MDC = new (Ctx) Decl::MultipleDC();
361 MDC->SemanticDC = SemaDC;
362 MDC->LexicalDC = LexicalDC;
367 bool Decl::isInLocalScopeForInstantiation() const {
368 const DeclContext *LDC = getLexicalDeclContext();
369 if (!LDC->isDependentContext())
372 if (LDC->isFunctionOrMethod())
374 if (!isa<TagDecl>(LDC))
376 if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
379 LDC = LDC->getLexicalParent();
384 bool Decl::isInAnonymousNamespace() const {
385 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
386 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
387 if (ND->isAnonymousNamespace())
394 bool Decl::isInStdNamespace() const {
395 const DeclContext *DC = getDeclContext();
396 return DC && DC->isStdNamespace();
399 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
400 if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
403 DeclContext *DC = getDeclContext();
404 assert(DC && "This decl is not contained in a translation unit!");
406 while (!DC->isTranslationUnit()) {
407 DC = DC->getParent();
408 assert(DC && "This decl is not contained in a translation unit!");
411 return cast<TranslationUnitDecl>(DC);
414 ASTContext &Decl::getASTContext() const {
415 return getTranslationUnitDecl()->getASTContext();
418 /// Helper to get the language options from the ASTContext.
419 /// Defined out of line to avoid depending on ASTContext.h.
420 const LangOptions &Decl::getLangOpts() const {
421 return getASTContext().getLangOpts();
424 ASTMutationListener *Decl::getASTMutationListener() const {
425 return getASTContext().getASTMutationListener();
428 unsigned Decl::getMaxAlignment() const {
433 const AttrVec &V = getAttrs();
434 ASTContext &Ctx = getASTContext();
435 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
436 for (; I != E; ++I) {
437 if (!I->isAlignmentErrorDependent())
438 Align = std::max(Align, I->getAlignment(Ctx));
443 bool Decl::isUsed(bool CheckUsedAttr) const {
444 const Decl *CanonD = getCanonicalDecl();
448 // Check for used attribute.
449 // Ask the most recent decl, since attributes accumulate in the redecl chain.
450 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
453 // The information may have not been deserialized yet. Force deserialization
454 // to complete the needed information.
455 return getMostRecentDecl()->getCanonicalDecl()->Used;
458 void Decl::markUsed(ASTContext &C) {
462 if (C.getASTMutationListener())
463 C.getASTMutationListener()->DeclarationMarkedUsed(this);
468 bool Decl::isReferenced() const {
472 // Check redeclarations.
473 for (const auto *I : redecls())
480 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
481 const Decl *Definition = nullptr;
482 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
483 Definition = ID->getDefinition();
484 } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
485 Definition = PD->getDefinition();
486 } else if (auto *TD = dyn_cast<TagDecl>(this)) {
487 Definition = TD->getDefinition();
492 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
494 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
495 return dcd->getAttr<ExternalSourceSymbolAttr>();
501 bool Decl::hasDefiningAttr() const {
502 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>() ||
503 hasAttr<LoaderUninitializedAttr>();
506 const Attr *Decl::getDefiningAttr() const {
507 if (auto *AA = getAttr<AliasAttr>())
509 if (auto *IFA = getAttr<IFuncAttr>())
511 if (auto *NZA = getAttr<LoaderUninitializedAttr>())
516 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
517 const ASTContext &Context) {
518 // Check if this is an App Extension "platform", and if so chop off
519 // the suffix for matching with the actual platform.
520 StringRef RealizedPlatform = A->getPlatform()->getName();
521 if (!Context.getLangOpts().AppExt)
522 return RealizedPlatform;
523 size_t suffix = RealizedPlatform.rfind("_app_extension");
524 if (suffix != StringRef::npos)
525 return RealizedPlatform.slice(0, suffix);
526 return RealizedPlatform;
529 /// Determine the availability of the given declaration based on
530 /// the target platform.
532 /// When it returns an availability result other than \c AR_Available,
533 /// if the \p Message parameter is non-NULL, it will be set to a
534 /// string describing why the entity is unavailable.
536 /// FIXME: Make these strings localizable, since they end up in
538 static AvailabilityResult CheckAvailability(ASTContext &Context,
539 const AvailabilityAttr *A,
540 std::string *Message,
541 VersionTuple EnclosingVersion) {
542 if (EnclosingVersion.empty())
543 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
545 if (EnclosingVersion.empty())
548 StringRef ActualPlatform = A->getPlatform()->getName();
549 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
551 // Match the platform name.
552 if (getRealizedPlatform(A, Context) != TargetPlatform)
555 StringRef PrettyPlatformName
556 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
558 if (PrettyPlatformName.empty())
559 PrettyPlatformName = ActualPlatform;
561 std::string HintMessage;
562 if (!A->getMessage().empty()) {
564 HintMessage += A->getMessage();
567 // Make sure that this declaration has not been marked 'unavailable'.
568 if (A->getUnavailable()) {
571 llvm::raw_string_ostream Out(*Message);
572 Out << "not available on " << PrettyPlatformName
576 return AR_Unavailable;
579 // Make sure that this declaration has already been introduced.
580 if (!A->getIntroduced().empty() &&
581 EnclosingVersion < A->getIntroduced()) {
584 llvm::raw_string_ostream Out(*Message);
585 VersionTuple VTI(A->getIntroduced());
586 Out << "introduced in " << PrettyPlatformName << ' '
587 << VTI << HintMessage;
590 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
593 // Make sure that this declaration hasn't been obsoleted.
594 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
597 llvm::raw_string_ostream Out(*Message);
598 VersionTuple VTO(A->getObsoleted());
599 Out << "obsoleted in " << PrettyPlatformName << ' '
600 << VTO << HintMessage;
603 return AR_Unavailable;
606 // Make sure that this declaration hasn't been deprecated.
607 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
610 llvm::raw_string_ostream Out(*Message);
611 VersionTuple VTD(A->getDeprecated());
612 Out << "first deprecated in " << PrettyPlatformName << ' '
613 << VTD << HintMessage;
616 return AR_Deprecated;
622 AvailabilityResult Decl::getAvailability(std::string *Message,
623 VersionTuple EnclosingVersion,
624 StringRef *RealizedPlatform) const {
625 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
626 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
629 AvailabilityResult Result = AR_Available;
630 std::string ResultMessage;
632 for (const auto *A : attrs()) {
633 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
634 if (Result >= AR_Deprecated)
638 ResultMessage = std::string(Deprecated->getMessage());
640 Result = AR_Deprecated;
644 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
646 *Message = std::string(Unavailable->getMessage());
647 return AR_Unavailable;
650 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
651 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
652 Message, EnclosingVersion);
654 if (AR == AR_Unavailable) {
655 if (RealizedPlatform)
656 *RealizedPlatform = Availability->getPlatform()->getName();
657 return AR_Unavailable;
663 ResultMessage.swap(*Message);
670 Message->swap(ResultMessage);
674 VersionTuple Decl::getVersionIntroduced() const {
675 const ASTContext &Context = getASTContext();
676 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
677 for (const auto *A : attrs()) {
678 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
679 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
681 if (!Availability->getIntroduced().empty())
682 return Availability->getIntroduced();
688 bool Decl::canBeWeakImported(bool &IsDefinition) const {
689 IsDefinition = false;
691 // Variables, if they aren't definitions.
692 if (const auto *Var = dyn_cast<VarDecl>(this)) {
693 if (Var->isThisDeclarationADefinition()) {
699 // Functions, if they aren't definitions.
700 } else if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
707 // Objective-C classes, if this is the non-fragile runtime.
708 } else if (isa<ObjCInterfaceDecl>(this) &&
709 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
718 bool Decl::isWeakImported() const {
720 if (!canBeWeakImported(IsDefinition))
723 for (const auto *A : attrs()) {
724 if (isa<WeakImportAttr>(A))
727 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
728 if (CheckAvailability(getASTContext(), Availability, nullptr,
729 VersionTuple()) == AR_NotYetIntroduced)
737 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
740 case CXXDeductionGuide:
743 case ConstructorUsingShadow:
753 return IDNS_Ordinary;
757 return IDNS_Ordinary | IDNS_Member;
760 case NonTypeTemplateParm:
763 // These (C++-only) declarations are found by redeclaration lookup for
764 // tag types, so we include them in the tag namespace.
765 return IDNS_Ordinary | IDNS_Tag;
767 case ObjCCompatibleAlias:
769 return IDNS_Ordinary | IDNS_Type;
773 case TemplateTypeParm:
775 return IDNS_Ordinary | IDNS_Type;
777 case UnresolvedUsingTypename:
778 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
781 return 0; // we'll actually overwrite this later
783 case UnresolvedUsingValue:
784 return IDNS_Ordinary | IDNS_Using;
791 return IDNS_ObjCProtocol;
794 case ObjCAtDefsField:
801 return IDNS_Tag | IDNS_Type;
805 return IDNS_Namespace;
807 case FunctionTemplate:
808 return IDNS_Ordinary;
811 case TemplateTemplateParm:
812 case TypeAliasTemplate:
813 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
815 case OMPDeclareReduction:
816 return IDNS_OMPReduction;
818 case OMPDeclareMapper:
819 return IDNS_OMPMapper;
829 case ObjCPropertyImpl:
831 case PragmaDetectMismatch:
834 case TranslationUnit:
840 case BuiltinTemplate:
841 case ClassTemplateSpecialization:
842 case ClassTemplatePartialSpecialization:
843 case ClassScopeFunctionSpecialization:
844 case VarTemplateSpecialization:
845 case VarTemplatePartialSpecialization:
846 case ObjCImplementation:
848 case ObjCCategoryImpl:
850 case OMPThreadPrivate:
853 case OMPCapturedExpr:
855 case LifetimeExtendedTemporary:
856 case RequiresExprBody:
857 // Never looked up by name.
861 llvm_unreachable("Invalid DeclKind!");
864 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
865 assert(!HasAttrs && "Decl already contains attrs.");
867 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
868 assert(AttrBlank.empty() && "HasAttrs was wrong?");
874 void Decl::dropAttrs() {
875 if (!HasAttrs) return;
878 getASTContext().eraseDeclAttrs(this);
881 void Decl::addAttr(Attr *A) {
883 setAttrs(AttrVec(1, A));
887 AttrVec &Attrs = getAttrs();
888 if (!A->isInherited()) {
893 // Attribute inheritance is processed after attribute parsing. To keep the
894 // order as in the source code, add inherited attributes before non-inherited
896 auto I = Attrs.begin(), E = Attrs.end();
897 for (; I != E; ++I) {
898 if (!(*I)->isInherited())
904 const AttrVec &Decl::getAttrs() const {
905 assert(HasAttrs && "No attrs to get!");
906 return getASTContext().getDeclAttrs(this);
909 Decl *Decl::castFromDeclContext (const DeclContext *D) {
910 Decl::Kind DK = D->getDeclKind();
912 #define DECL(NAME, BASE)
913 #define DECL_CONTEXT(NAME) \
915 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
916 #define DECL_CONTEXT_BASE(NAME)
917 #include "clang/AST/DeclNodes.inc"
919 #define DECL(NAME, BASE)
920 #define DECL_CONTEXT_BASE(NAME) \
921 if (DK >= first##NAME && DK <= last##NAME) \
922 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
923 #include "clang/AST/DeclNodes.inc"
924 llvm_unreachable("a decl that inherits DeclContext isn't handled");
928 DeclContext *Decl::castToDeclContext(const Decl *D) {
929 Decl::Kind DK = D->getKind();
931 #define DECL(NAME, BASE)
932 #define DECL_CONTEXT(NAME) \
934 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
935 #define DECL_CONTEXT_BASE(NAME)
936 #include "clang/AST/DeclNodes.inc"
938 #define DECL(NAME, BASE)
939 #define DECL_CONTEXT_BASE(NAME) \
940 if (DK >= first##NAME && DK <= last##NAME) \
941 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
942 #include "clang/AST/DeclNodes.inc"
943 llvm_unreachable("a decl that inherits DeclContext isn't handled");
947 SourceLocation Decl::getBodyRBrace() const {
948 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
949 // FunctionDecl stores EndRangeLoc for this purpose.
950 if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
951 const FunctionDecl *Definition;
952 if (FD->hasBody(Definition))
953 return Definition->getSourceRange().getEnd();
957 if (Stmt *Body = getBody())
958 return Body->getSourceRange().getEnd();
963 bool Decl::AccessDeclContextSanity() const {
965 // Suppress this check if any of the following hold:
966 // 1. this is the translation unit (and thus has no parent)
967 // 2. this is a template parameter (and thus doesn't belong to its context)
968 // 3. this is a non-type template parameter
969 // 4. the context is not a record
971 // 6. it's a C++0x static_assert.
972 // 7. it's a block literal declaration
973 if (isa<TranslationUnitDecl>(this) ||
974 isa<TemplateTypeParmDecl>(this) ||
975 isa<NonTypeTemplateParmDecl>(this) ||
977 !isa<CXXRecordDecl>(getDeclContext()) ||
979 isa<StaticAssertDecl>(this) ||
980 isa<BlockDecl>(this) ||
981 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
982 // as DeclContext (?).
983 isa<ParmVarDecl>(this) ||
984 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
985 // AS_none as access specifier.
986 isa<CXXRecordDecl>(this) ||
987 isa<ClassScopeFunctionSpecializationDecl>(this))
990 assert(Access != AS_none &&
991 "Access specifier is AS_none inside a record decl");
996 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
997 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
999 int64_t Decl::getID() const {
1000 return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
1003 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
1005 if (const auto *D = dyn_cast<ValueDecl>(this))
1007 else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1008 Ty = D->getUnderlyingType();
1012 if (Ty->isFunctionPointerType())
1013 Ty = Ty->castAs<PointerType>()->getPointeeType();
1014 else if (Ty->isFunctionReferenceType())
1015 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1016 else if (BlocksToo && Ty->isBlockPointerType())
1017 Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
1019 return Ty->getAs<FunctionType>();
1022 /// Starting at a given context (a Decl or DeclContext), look for a
1023 /// code context that is not a closure (a lambda, block, etc.).
1024 template <class T> static Decl *getNonClosureContext(T *D) {
1025 if (getKind(D) == Decl::CXXMethod) {
1026 auto *MD = cast<CXXMethodDecl>(D);
1027 if (MD->getOverloadedOperator() == OO_Call &&
1028 MD->getParent()->isLambda())
1029 return getNonClosureContext(MD->getParent()->getParent());
1031 } else if (auto *FD = dyn_cast<FunctionDecl>(D))
1033 else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1035 else if (auto *BD = dyn_cast<BlockDecl>(D))
1036 return getNonClosureContext(BD->getParent());
1037 else if (auto *CD = dyn_cast<CapturedDecl>(D))
1038 return getNonClosureContext(CD->getParent());
1043 Decl *Decl::getNonClosureContext() {
1044 return ::getNonClosureContext(this);
1047 Decl *DeclContext::getNonClosureAncestor() {
1048 return ::getNonClosureContext(this);
1051 //===----------------------------------------------------------------------===//
1052 // DeclContext Implementation
1053 //===----------------------------------------------------------------------===//
1055 DeclContext::DeclContext(Decl::Kind K) {
1056 DeclContextBits.DeclKind = K;
1057 setHasExternalLexicalStorage(false);
1058 setHasExternalVisibleStorage(false);
1059 setNeedToReconcileExternalVisibleStorage(false);
1060 setHasLazyLocalLexicalLookups(false);
1061 setHasLazyExternalLexicalLookups(false);
1062 setUseQualifiedLookup(false);
1065 bool DeclContext::classof(const Decl *D) {
1066 switch (D->getKind()) {
1067 #define DECL(NAME, BASE)
1068 #define DECL_CONTEXT(NAME) case Decl::NAME:
1069 #define DECL_CONTEXT_BASE(NAME)
1070 #include "clang/AST/DeclNodes.inc"
1073 #define DECL(NAME, BASE)
1074 #define DECL_CONTEXT_BASE(NAME) \
1075 if (D->getKind() >= Decl::first##NAME && \
1076 D->getKind() <= Decl::last##NAME) \
1078 #include "clang/AST/DeclNodes.inc"
1083 DeclContext::~DeclContext() = default;
1085 /// Find the parent context of this context that will be
1086 /// used for unqualified name lookup.
1088 /// Generally, the parent lookup context is the semantic context. However, for
1089 /// a friend function the parent lookup context is the lexical context, which
1090 /// is the class in which the friend is declared.
1091 DeclContext *DeclContext::getLookupParent() {
1092 // FIXME: Find a better way to identify friends.
1093 if (isa<FunctionDecl>(this))
1094 if (getParent()->getRedeclContext()->isFileContext() &&
1095 getLexicalParent()->getRedeclContext()->isRecord())
1096 return getLexicalParent();
1098 // A lookup within the call operator of a lambda never looks in the lambda
1099 // class; instead, skip to the context in which that closure type is
1101 if (isLambdaCallOperator(this))
1102 return getParent()->getParent();
1107 const BlockDecl *DeclContext::getInnermostBlockDecl() const {
1108 const DeclContext *Ctx = this;
1111 if (Ctx->isClosure())
1112 return cast<BlockDecl>(Ctx);
1113 Ctx = Ctx->getParent();
1119 bool DeclContext::isInlineNamespace() const {
1120 return isNamespace() &&
1121 cast<NamespaceDecl>(this)->isInline();
1124 bool DeclContext::isStdNamespace() const {
1128 const auto *ND = cast<NamespaceDecl>(this);
1129 if (ND->isInline()) {
1130 return ND->getParent()->isStdNamespace();
1133 if (!getParent()->getRedeclContext()->isTranslationUnit())
1136 const IdentifierInfo *II = ND->getIdentifier();
1137 return II && II->isStr("std");
1140 bool DeclContext::isDependentContext() const {
1141 if (isFileContext())
1144 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1147 if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1148 if (Record->getDescribedClassTemplate())
1151 if (Record->isDependentLambda())
1155 if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1156 if (Function->getDescribedFunctionTemplate())
1159 // Friend function declarations are dependent if their *lexical*
1160 // context is dependent.
1161 if (cast<Decl>(this)->getFriendObjectKind())
1162 return getLexicalParent()->isDependentContext();
1165 // FIXME: A variable template is a dependent context, but is not a
1166 // DeclContext. A context within it (such as a lambda-expression)
1167 // should be considered dependent.
1169 return getParent() && getParent()->isDependentContext();
1172 bool DeclContext::isTransparentContext() const {
1173 if (getDeclKind() == Decl::Enum)
1174 return !cast<EnumDecl>(this)->isScoped();
1175 else if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1181 static bool isLinkageSpecContext(const DeclContext *DC,
1182 LinkageSpecDecl::LanguageIDs ID) {
1183 while (DC->getDeclKind() != Decl::TranslationUnit) {
1184 if (DC->getDeclKind() == Decl::LinkageSpec)
1185 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1186 DC = DC->getLexicalParent();
1191 bool DeclContext::isExternCContext() const {
1192 return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1195 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1196 const DeclContext *DC = this;
1197 while (DC->getDeclKind() != Decl::TranslationUnit) {
1198 if (DC->getDeclKind() == Decl::LinkageSpec &&
1199 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1200 return cast<LinkageSpecDecl>(DC);
1201 DC = DC->getLexicalParent();
1206 bool DeclContext::isExternCXXContext() const {
1207 return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1210 bool DeclContext::Encloses(const DeclContext *DC) const {
1211 if (getPrimaryContext() != this)
1212 return getPrimaryContext()->Encloses(DC);
1214 for (; DC; DC = DC->getParent())
1215 if (DC->getPrimaryContext() == this)
1220 DeclContext *DeclContext::getPrimaryContext() {
1221 switch (getDeclKind()) {
1222 case Decl::TranslationUnit:
1223 case Decl::ExternCContext:
1224 case Decl::LinkageSpec:
1227 case Decl::Captured:
1228 case Decl::OMPDeclareReduction:
1229 case Decl::OMPDeclareMapper:
1230 case Decl::RequiresExprBody:
1231 // There is only one DeclContext for these entities.
1234 case Decl::Namespace:
1235 // The original namespace is our primary context.
1236 return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1238 case Decl::ObjCMethod:
1241 case Decl::ObjCInterface:
1242 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1243 if (auto *Def = OID->getDefinition())
1247 case Decl::ObjCProtocol:
1248 if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1249 if (auto *Def = OPD->getDefinition())
1253 case Decl::ObjCCategory:
1256 case Decl::ObjCImplementation:
1257 case Decl::ObjCCategoryImpl:
1261 if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1262 // If this is a tag type that has a definition or is currently
1263 // being defined, that definition is our primary context.
1264 auto *Tag = cast<TagDecl>(this);
1266 if (TagDecl *Def = Tag->getDefinition())
1269 if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1270 // Note, TagType::getDecl returns the (partial) definition one exists.
1271 TagDecl *PossiblePartialDef = TagTy->getDecl();
1272 if (PossiblePartialDef->isBeingDefined())
1273 return PossiblePartialDef;
1275 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1281 assert(getDeclKind() >= Decl::firstFunction &&
1282 getDeclKind() <= Decl::lastFunction &&
1283 "Unknown DeclContext kind");
1289 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1292 if (getDeclKind() != Decl::Namespace) {
1293 Contexts.push_back(this);
1297 auto *Self = static_cast<NamespaceDecl *>(this);
1298 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1299 N = N->getPreviousDecl())
1300 Contexts.push_back(N);
1302 std::reverse(Contexts.begin(), Contexts.end());
1305 std::pair<Decl *, Decl *>
1306 DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1307 bool FieldsAlreadyLoaded) {
1308 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1309 Decl *FirstNewDecl = nullptr;
1310 Decl *PrevDecl = nullptr;
1311 for (auto *D : Decls) {
1312 if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1316 PrevDecl->NextInContextAndBits.setPointer(D);
1323 return std::make_pair(FirstNewDecl, PrevDecl);
1326 /// We have just acquired external visible storage, and we already have
1327 /// built a lookup map. For every name in the map, pull in the new names from
1328 /// the external storage.
1329 void DeclContext::reconcileExternalVisibleStorage() const {
1330 assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1331 setNeedToReconcileExternalVisibleStorage(false);
1333 for (auto &Lookup : *LookupPtr)
1334 Lookup.second.setHasExternalDecls();
1337 /// Load the declarations within this lexical storage from an
1338 /// external source.
1339 /// \return \c true if any declarations were added.
1341 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1342 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1343 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1345 // Notify that we have a DeclContext that is initializing.
1346 ExternalASTSource::Deserializing ADeclContext(Source);
1348 // Load the external declarations, if any.
1349 SmallVector<Decl*, 64> Decls;
1350 setHasExternalLexicalStorage(false);
1351 Source->FindExternalLexicalDecls(this, Decls);
1356 // We may have already loaded just the fields of this record, in which case
1357 // we need to ignore them.
1358 bool FieldsAlreadyLoaded = false;
1359 if (const auto *RD = dyn_cast<RecordDecl>(this))
1360 FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1362 // Splice the newly-read declarations into the beginning of the list
1364 Decl *ExternalFirst, *ExternalLast;
1365 std::tie(ExternalFirst, ExternalLast) =
1366 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1367 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1368 FirstDecl = ExternalFirst;
1370 LastDecl = ExternalLast;
1374 DeclContext::lookup_result
1375 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1376 DeclarationName Name) {
1377 ASTContext &Context = DC->getParentASTContext();
1378 StoredDeclsMap *Map;
1379 if (!(Map = DC->LookupPtr))
1380 Map = DC->CreateStoredDeclsMap(Context);
1381 if (DC->hasNeedToReconcileExternalVisibleStorage())
1382 DC->reconcileExternalVisibleStorage();
1384 (*Map)[Name].removeExternalDecls();
1386 return DeclContext::lookup_result();
1389 DeclContext::lookup_result
1390 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1391 DeclarationName Name,
1392 ArrayRef<NamedDecl*> Decls) {
1393 ASTContext &Context = DC->getParentASTContext();
1394 StoredDeclsMap *Map;
1395 if (!(Map = DC->LookupPtr))
1396 Map = DC->CreateStoredDeclsMap(Context);
1397 if (DC->hasNeedToReconcileExternalVisibleStorage())
1398 DC->reconcileExternalVisibleStorage();
1400 StoredDeclsList &List = (*Map)[Name];
1402 // Clear out any old external visible declarations, to avoid quadratic
1403 // performance in the redeclaration checks below.
1404 List.removeExternalDecls();
1406 if (!List.isNull()) {
1407 // We have both existing declarations and new declarations for this name.
1408 // Some of the declarations may simply replace existing ones. Handle those
1410 llvm::SmallVector<unsigned, 8> Skip;
1411 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1412 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1414 Skip.push_back(Decls.size());
1416 // Add in any new declarations.
1417 unsigned SkipPos = 0;
1418 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1419 if (I == Skip[SkipPos])
1422 List.AddSubsequentDecl(Decls[I]);
1425 // Convert the array to a StoredDeclsList.
1426 for (auto *D : Decls) {
1428 List.setOnlyValue(D);
1430 List.AddSubsequentDecl(D);
1434 return List.getLookupResult();
1437 DeclContext::decl_iterator DeclContext::decls_begin() const {
1438 if (hasExternalLexicalStorage())
1439 LoadLexicalDeclsFromExternalStorage();
1440 return decl_iterator(FirstDecl);
1443 bool DeclContext::decls_empty() const {
1444 if (hasExternalLexicalStorage())
1445 LoadLexicalDeclsFromExternalStorage();
1450 bool DeclContext::containsDecl(Decl *D) const {
1451 return (D->getLexicalDeclContext() == this &&
1452 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1455 bool DeclContext::containsDeclAndLoad(Decl *D) const {
1456 if (hasExternalLexicalStorage())
1457 LoadLexicalDeclsFromExternalStorage();
1458 return containsDecl(D);
1461 /// shouldBeHidden - Determine whether a declaration which was declared
1462 /// within its semantic context should be invisible to qualified name lookup.
1463 static bool shouldBeHidden(NamedDecl *D) {
1464 // Skip unnamed declarations.
1465 if (!D->getDeclName())
1468 // Skip entities that can't be found by name lookup into a particular
1470 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1471 D->isTemplateParameter())
1474 // Skip friends and local extern declarations unless they're the first
1475 // declaration of the entity.
1476 if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1477 D != D->getCanonicalDecl())
1480 // Skip template specializations.
1481 // FIXME: This feels like a hack. Should DeclarationName support
1482 // template-ids, or is there a better way to keep specializations
1483 // from being visible?
1484 if (isa<ClassTemplateSpecializationDecl>(D))
1486 if (auto *FD = dyn_cast<FunctionDecl>(D))
1487 if (FD->isFunctionTemplateSpecialization())
1493 void DeclContext::removeDecl(Decl *D) {
1494 assert(D->getLexicalDeclContext() == this &&
1495 "decl being removed from non-lexical context");
1496 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1497 "decl is not in decls list");
1499 // Remove D from the decl chain. This is O(n) but hopefully rare.
1500 if (D == FirstDecl) {
1502 FirstDecl = LastDecl = nullptr;
1504 FirstDecl = D->NextInContextAndBits.getPointer();
1506 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1507 assert(I && "decl not found in linked list");
1508 if (I->NextInContextAndBits.getPointer() == D) {
1509 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1510 if (D == LastDecl) LastDecl = I;
1516 // Mark that D is no longer in the decl chain.
1517 D->NextInContextAndBits.setPointer(nullptr);
1519 // Remove D from the lookup table if necessary.
1520 if (isa<NamedDecl>(D)) {
1521 auto *ND = cast<NamedDecl>(D);
1523 // Do not try to remove the declaration if that is invisible to qualified
1524 // lookup. E.g. template specializations are skipped.
1525 if (shouldBeHidden(ND))
1528 // Remove only decls that have a name
1529 if (!ND->getDeclName())
1532 auto *DC = D->getDeclContext();
1534 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1536 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1537 assert(Pos != Map->end() && "no lookup entry for decl");
1538 // Remove the decl only if it is contained.
1539 StoredDeclsList::DeclsTy *Vec = Pos->second.getAsVector();
1540 if ((Vec && is_contained(*Vec, ND)) || Pos->second.getAsDecl() == ND)
1541 Pos->second.remove(ND);
1543 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1547 void DeclContext::addHiddenDecl(Decl *D) {
1548 assert(D->getLexicalDeclContext() == this &&
1549 "Decl inserted into wrong lexical context");
1550 assert(!D->getNextDeclInContext() && D != LastDecl &&
1551 "Decl already inserted into a DeclContext");
1554 LastDecl->NextInContextAndBits.setPointer(D);
1557 FirstDecl = LastDecl = D;
1560 // Notify a C++ record declaration that we've added a member, so it can
1561 // update its class-specific state.
1562 if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1563 Record->addedMember(D);
1565 // If this is a newly-created (not de-serialized) import declaration, wire
1566 // it in to the list of local import declarations.
1567 if (!D->isFromASTFile()) {
1568 if (auto *Import = dyn_cast<ImportDecl>(D))
1569 D->getASTContext().addedLocalImportDecl(Import);
1573 void DeclContext::addDecl(Decl *D) {
1576 if (auto *ND = dyn_cast<NamedDecl>(D))
1577 ND->getDeclContext()->getPrimaryContext()->
1578 makeDeclVisibleInContextWithFlags(ND, false, true);
1581 void DeclContext::addDeclInternal(Decl *D) {
1584 if (auto *ND = dyn_cast<NamedDecl>(D))
1585 ND->getDeclContext()->getPrimaryContext()->
1586 makeDeclVisibleInContextWithFlags(ND, true, true);
1589 /// buildLookup - Build the lookup data structure with all of the
1590 /// declarations in this DeclContext (and any other contexts linked
1591 /// to it or transparent contexts nested within it) and return it.
1593 /// Note that the produced map may miss out declarations from an
1594 /// external source. If it does, those entries will be marked with
1595 /// the 'hasExternalDecls' flag.
1596 StoredDeclsMap *DeclContext::buildLookup() {
1597 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1599 if (!hasLazyLocalLexicalLookups() &&
1600 !hasLazyExternalLexicalLookups())
1603 SmallVector<DeclContext *, 2> Contexts;
1604 collectAllContexts(Contexts);
1606 if (hasLazyExternalLexicalLookups()) {
1607 setHasLazyExternalLexicalLookups(false);
1608 for (auto *DC : Contexts) {
1609 if (DC->hasExternalLexicalStorage()) {
1610 bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1611 setHasLazyLocalLexicalLookups(
1612 hasLazyLocalLexicalLookups() | LoadedDecls );
1616 if (!hasLazyLocalLexicalLookups())
1620 for (auto *DC : Contexts)
1621 buildLookupImpl(DC, hasExternalVisibleStorage());
1623 // We no longer have any lazy decls.
1624 setHasLazyLocalLexicalLookups(false);
1628 /// buildLookupImpl - Build part of the lookup data structure for the
1629 /// declarations contained within DCtx, which will either be this
1630 /// DeclContext, a DeclContext linked to it, or a transparent context
1631 /// nested within it.
1632 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1633 for (auto *D : DCtx->noload_decls()) {
1634 // Insert this declaration into the lookup structure, but only if
1635 // it's semantically within its decl context. Any other decls which
1636 // should be found in this context are added eagerly.
1638 // If it's from an AST file, don't add it now. It'll get handled by
1639 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1640 // in C++, we do not track external visible decls for the TU, so in
1641 // that case we need to collect them all here.
1642 if (auto *ND = dyn_cast<NamedDecl>(D))
1643 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1644 (!ND->isFromASTFile() ||
1645 (isTranslationUnit() &&
1646 !getParentASTContext().getLangOpts().CPlusPlus)))
1647 makeDeclVisibleInContextImpl(ND, Internal);
1649 // If this declaration is itself a transparent declaration context
1650 // or inline namespace, add the members of this declaration of that
1651 // context (recursively).
1652 if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1653 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1654 buildLookupImpl(InnerCtx, Internal);
1658 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1660 DeclContext::lookup_result
1661 DeclContext::lookup(DeclarationName Name) const {
1662 assert(getDeclKind() != Decl::LinkageSpec &&
1663 getDeclKind() != Decl::Export &&
1664 "should not perform lookups into transparent contexts");
1666 const DeclContext *PrimaryContext = getPrimaryContext();
1667 if (PrimaryContext != this)
1668 return PrimaryContext->lookup(Name);
1670 // If we have an external source, ensure that any later redeclarations of this
1671 // context have been loaded, since they may add names to the result of this
1672 // lookup (or add external visible storage).
1673 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1675 (void)cast<Decl>(this)->getMostRecentDecl();
1677 if (hasExternalVisibleStorage()) {
1678 assert(Source && "external visible storage but no external source?");
1680 if (hasNeedToReconcileExternalVisibleStorage())
1681 reconcileExternalVisibleStorage();
1683 StoredDeclsMap *Map = LookupPtr;
1685 if (hasLazyLocalLexicalLookups() ||
1686 hasLazyExternalLexicalLookups())
1687 // FIXME: Make buildLookup const?
1688 Map = const_cast<DeclContext*>(this)->buildLookup();
1691 Map = CreateStoredDeclsMap(getParentASTContext());
1693 // If we have a lookup result with no external decls, we are done.
1694 std::pair<StoredDeclsMap::iterator, bool> R =
1695 Map->insert(std::make_pair(Name, StoredDeclsList()));
1696 if (!R.second && !R.first->second.hasExternalDecls())
1697 return R.first->second.getLookupResult();
1699 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1700 if (StoredDeclsMap *Map = LookupPtr) {
1701 StoredDeclsMap::iterator I = Map->find(Name);
1702 if (I != Map->end())
1703 return I->second.getLookupResult();
1710 StoredDeclsMap *Map = LookupPtr;
1711 if (hasLazyLocalLexicalLookups() ||
1712 hasLazyExternalLexicalLookups())
1713 Map = const_cast<DeclContext*>(this)->buildLookup();
1718 StoredDeclsMap::iterator I = Map->find(Name);
1719 if (I == Map->end())
1722 return I->second.getLookupResult();
1725 DeclContext::lookup_result
1726 DeclContext::noload_lookup(DeclarationName Name) {
1727 assert(getDeclKind() != Decl::LinkageSpec &&
1728 getDeclKind() != Decl::Export &&
1729 "should not perform lookups into transparent contexts");
1731 DeclContext *PrimaryContext = getPrimaryContext();
1732 if (PrimaryContext != this)
1733 return PrimaryContext->noload_lookup(Name);
1735 loadLazyLocalLexicalLookups();
1736 StoredDeclsMap *Map = LookupPtr;
1740 StoredDeclsMap::iterator I = Map->find(Name);
1741 return I != Map->end() ? I->second.getLookupResult()
1745 // If we have any lazy lexical declarations not in our lookup map, add them
1746 // now. Don't import any external declarations, not even if we know we have
1747 // some missing from the external visible lookups.
1748 void DeclContext::loadLazyLocalLexicalLookups() {
1749 if (hasLazyLocalLexicalLookups()) {
1750 SmallVector<DeclContext *, 2> Contexts;
1751 collectAllContexts(Contexts);
1752 for (auto *Context : Contexts)
1753 buildLookupImpl(Context, hasExternalVisibleStorage());
1754 setHasLazyLocalLexicalLookups(false);
1758 void DeclContext::localUncachedLookup(DeclarationName Name,
1759 SmallVectorImpl<NamedDecl *> &Results) {
1762 // If there's no external storage, just perform a normal lookup and copy
1764 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1765 lookup_result LookupResults = lookup(Name);
1766 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1770 // If we have a lookup table, check there first. Maybe we'll get lucky.
1771 // FIXME: Should we be checking these flags on the primary context?
1772 if (Name && !hasLazyLocalLexicalLookups() &&
1773 !hasLazyExternalLexicalLookups()) {
1774 if (StoredDeclsMap *Map = LookupPtr) {
1775 StoredDeclsMap::iterator Pos = Map->find(Name);
1776 if (Pos != Map->end()) {
1777 Results.insert(Results.end(),
1778 Pos->second.getLookupResult().begin(),
1779 Pos->second.getLookupResult().end());
1785 // Slow case: grovel through the declarations in our chain looking for
1787 // FIXME: If we have lazy external declarations, this will not find them!
1788 // FIXME: Should we CollectAllContexts and walk them all here?
1789 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1790 if (auto *ND = dyn_cast<NamedDecl>(D))
1791 if (ND->getDeclName() == Name)
1792 Results.push_back(ND);
1796 DeclContext *DeclContext::getRedeclContext() {
1797 DeclContext *Ctx = this;
1799 // In C, a record type is the redeclaration context for its fields only. If
1800 // we arrive at a record context after skipping anything else, we should skip
1801 // the record as well. Currently, this means skipping enumerations because
1802 // they're the only transparent context that can exist within a struct or
1804 bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1805 !getParentASTContext().getLangOpts().CPlusPlus;
1807 // Skip through contexts to get to the redeclaration context. Transparent
1808 // contexts are always skipped.
1809 while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1810 Ctx = Ctx->getParent();
1814 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1815 DeclContext *Ctx = this;
1816 // Skip through non-namespace, non-translation-unit contexts.
1817 while (!Ctx->isFileContext())
1818 Ctx = Ctx->getParent();
1819 return Ctx->getPrimaryContext();
1822 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1823 // Loop until we find a non-record context.
1824 RecordDecl *OutermostRD = nullptr;
1825 DeclContext *DC = this;
1826 while (DC->isRecord()) {
1827 OutermostRD = cast<RecordDecl>(DC);
1828 DC = DC->getLexicalParent();
1833 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1834 // For non-file contexts, this is equivalent to Equals.
1835 if (!isFileContext())
1836 return O->Equals(this);
1839 if (O->Equals(this))
1842 const auto *NS = dyn_cast<NamespaceDecl>(O);
1843 if (!NS || !NS->isInline())
1845 O = NS->getParent();
1851 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1852 DeclContext *PrimaryDC = this->getPrimaryContext();
1853 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1854 // If the decl is being added outside of its semantic decl context, we
1855 // need to ensure that we eagerly build the lookup information for it.
1856 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1859 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1861 assert(this == getPrimaryContext() && "expected a primary DC");
1863 if (!isLookupContext()) {
1864 if (isTransparentContext())
1865 getParent()->getPrimaryContext()
1866 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1870 // Skip declarations which should be invisible to name lookup.
1871 if (shouldBeHidden(D))
1874 // If we already have a lookup data structure, perform the insertion into
1875 // it. If we might have externally-stored decls with this name, look them
1876 // up and perform the insertion. If this decl was declared outside its
1877 // semantic context, buildLookup won't add it, so add it now.
1879 // FIXME: As a performance hack, don't add such decls into the translation
1880 // unit unless we're in C++, since qualified lookup into the TU is never
1882 if (LookupPtr || hasExternalVisibleStorage() ||
1883 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1884 (getParentASTContext().getLangOpts().CPlusPlus ||
1885 !isTranslationUnit()))) {
1886 // If we have lazily omitted any decls, they might have the same name as
1887 // the decl which we are adding, so build a full lookup table before adding
1890 makeDeclVisibleInContextImpl(D, Internal);
1892 setHasLazyLocalLexicalLookups(true);
1895 // If we are a transparent context or inline namespace, insert into our
1896 // parent context, too. This operation is recursive.
1897 if (isTransparentContext() || isInlineNamespace())
1898 getParent()->getPrimaryContext()->
1899 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1901 auto *DCAsDecl = cast<Decl>(this);
1902 // Notify that a decl was made visible unless we are a Tag being defined.
1903 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1904 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1905 L->AddedVisibleDecl(this, D);
1908 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1909 // Find or create the stored declaration map.
1910 StoredDeclsMap *Map = LookupPtr;
1912 ASTContext *C = &getParentASTContext();
1913 Map = CreateStoredDeclsMap(*C);
1916 // If there is an external AST source, load any declarations it knows about
1917 // with this declaration's name.
1918 // If the lookup table contains an entry about this name it means that we
1919 // have already checked the external source.
1921 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1922 if (hasExternalVisibleStorage() &&
1923 Map->find(D->getDeclName()) == Map->end())
1924 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1926 // Insert this declaration into the map.
1927 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1930 // If this is being added as part of loading an external declaration,
1931 // this may not be the only external declaration with this name.
1932 // In this case, we never try to replace an existing declaration; we'll
1933 // handle that when we finalize the list of declarations for this name.
1934 DeclNameEntries.setHasExternalDecls();
1935 DeclNameEntries.AddSubsequentDecl(D);
1939 if (DeclNameEntries.isNull()) {
1940 DeclNameEntries.setOnlyValue(D);
1944 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1945 // This declaration has replaced an existing one for which
1946 // declarationReplaces returns true.
1950 // Put this declaration into the appropriate slot.
1951 DeclNameEntries.AddSubsequentDecl(D);
1954 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1955 return cast<UsingDirectiveDecl>(*I);
1958 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1960 DeclContext::udir_range DeclContext::using_directives() const {
1961 // FIXME: Use something more efficient than normal lookup for using
1962 // directives. In C++, using directives are looked up more than anything else.
1963 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1964 return udir_range(Result.begin(), Result.end());
1967 //===----------------------------------------------------------------------===//
1968 // Creation and Destruction of StoredDeclsMaps. //
1969 //===----------------------------------------------------------------------===//
1971 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1972 assert(!LookupPtr && "context already has a decls map");
1973 assert(getPrimaryContext() == this &&
1974 "creating decls map on non-primary context");
1977 bool Dependent = isDependentContext();
1979 M = new DependentStoredDeclsMap();
1981 M = new StoredDeclsMap();
1982 M->Previous = C.LastSDM;
1983 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1988 void ASTContext::ReleaseDeclContextMaps() {
1989 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1990 // pointer because the subclass doesn't add anything that needs to
1992 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1995 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1997 // Advance the iteration before we invalidate memory.
1998 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
2001 delete static_cast<DependentStoredDeclsMap*>(Map);
2005 Map = Next.getPointer();
2006 Dependent = Next.getInt();
2010 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
2011 DeclContext *Parent,
2012 const PartialDiagnostic &PDiag) {
2013 assert(Parent->isDependentContext()
2014 && "cannot iterate dependent diagnostics of non-dependent context");
2015 Parent = Parent->getPrimaryContext();
2016 if (!Parent->LookupPtr)
2017 Parent->CreateStoredDeclsMap(C);
2019 auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
2021 // Allocate the copy of the PartialDiagnostic via the ASTContext's
2022 // BumpPtrAllocator, rather than the ASTContext itself.
2023 PartialDiagnostic::Storage *DiagStorage = nullptr;
2024 if (PDiag.hasStorage())
2025 DiagStorage = new (C) PartialDiagnostic::Storage;
2027 auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
2029 // TODO: Maybe we shouldn't reverse the order during insertion.
2030 DD->NextDiagnostic = Map->FirstDiagnostic;
2031 Map->FirstDiagnostic = DD;