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/ASTMutationListener.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"
20 #include "clang/AST/DeclContextInternals.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"
25 #include "clang/AST/DependentDiagnostic.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/Type.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/ObjCRuntime.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceLocation.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"
52 using namespace clang;
54 //===----------------------------------------------------------------------===//
56 //===----------------------------------------------------------------------===//
58 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
59 #define ABSTRACT_DECL(DECL)
60 #include "clang/AST/DeclNodes.inc"
62 void Decl::updateOutOfDate(IdentifierInfo &II) const {
63 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
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"
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;
81 unsigned *PrefixPtr = (unsigned *)Result - 2;
83 // Zero out the first 4 bytes; this is used to store the owning module ID.
86 // Store the global declaration ID in the second 4 bytes.
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.
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;
107 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
108 return new (Buffer) Module*(ParentModule) + 1;
110 return ::operator new(Size + Extra, Ctx);
113 Module *Decl::getOwningModuleSlow() const {
114 assert(isFromASTFile() && "Not from AST file?");
115 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
118 bool Decl::hasLocalOwningModuleStorage() const {
119 return getASTContext().getLangOpts().trackLocalOwningModule();
122 const char *Decl::getDeclKindName() const {
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"
131 void Decl::setInvalidDecl(bool Invalid) {
132 InvalidDecl = Invalid;
133 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
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.
142 setAccess(AS_public);
145 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
147 if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
148 for (auto *Binding : DD->bindings()) {
149 Binding->setInvalidDecl();
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"
160 llvm_unreachable("Declaration context not in DeclNodes.inc!");
163 bool Decl::StatisticsEnabled = false;
164 void Decl::EnableStatistics() {
165 StatisticsEnabled = true;
168 void Decl::PrintStats() {
169 llvm::errs() << "\n*** Decl Stats:\n";
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";
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) \
186 #define ABSTRACT_DECL(DECL)
187 #include "clang/AST/DeclNodes.inc"
189 llvm::errs() << "Total bytes = " << totalBytes << "\n";
192 void Decl::add(Kind k) {
194 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
195 #define ABSTRACT_DECL(DECL)
196 #include "clang/AST/DeclNodes.inc"
200 bool Decl::isTemplateParameterPack() const {
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();
210 bool Decl::isParameterPack() const {
211 if (const auto *Var = dyn_cast<VarDecl>(this))
212 return Var->isParameterPack();
214 return isTemplateParameterPack();
217 FunctionDecl *Decl::getAsFunction() {
218 if (auto *FD = dyn_cast<FunctionDecl>(this))
220 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
221 return FTD->getTemplatedDecl();
225 bool Decl::isTemplateDecl() const {
226 return isa<TemplateDecl>(this);
229 TemplateDecl *Decl::getDescribedTemplate() const {
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();
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
246 // FIXME: Should local extern declarations be treated like friends?
247 if (auto *AsDC = dyn_cast<DeclContext>(this))
248 return AsDC->isDependentContext();
249 auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
250 return DC->isDependentContext() || isTemplateDecl() || getDescribedTemplate();
253 const DeclContext *Decl::getParentFunctionOrMethod() const {
254 for (const DeclContext *DC = getDeclContext();
255 DC && !DC->isTranslationUnit() && !DC->isNamespace();
256 DC = DC->getParent())
257 if (DC->isFunctionOrMethod())
263 //===----------------------------------------------------------------------===//
264 // PrettyStackTraceDecl Implementation
265 //===----------------------------------------------------------------------===//
267 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
268 SourceLocation TheLoc = Loc;
269 if (TheLoc.isInvalid() && TheDecl)
270 TheLoc = TheDecl->getLocation();
272 if (TheLoc.isValid()) {
273 TheLoc.print(OS, SM);
279 if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
281 DN->printQualifiedName(OS);
287 //===----------------------------------------------------------------------===//
288 // Decl Implementation
289 //===----------------------------------------------------------------------===//
291 // Out-of-line virtual method providing a home for Decl.
292 Decl::~Decl() = default;
294 void Decl::setDeclContext(DeclContext *DC) {
298 void Decl::setLexicalDeclContext(DeclContext *DC) {
299 if (DC == getLexicalDeclContext())
303 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
305 getMultipleDC()->LexicalDC = DC;
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());
317 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
318 getOwningModule()) &&
319 "hidden declaration has no owning module");
322 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
324 if (SemaDC == LexicalDC) {
327 auto *MDC = new (Ctx) Decl::MultipleDC();
328 MDC->SemanticDC = SemaDC;
329 MDC->LexicalDC = LexicalDC;
334 bool Decl::isLexicallyWithinFunctionOrMethod() const {
335 const DeclContext *LDC = getLexicalDeclContext();
337 if (LDC->isFunctionOrMethod())
339 if (!isa<TagDecl>(LDC))
341 LDC = LDC->getLexicalParent();
346 bool Decl::isInAnonymousNamespace() const {
347 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
348 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
349 if (ND->isAnonymousNamespace())
356 bool Decl::isInStdNamespace() const {
357 const DeclContext *DC = getDeclContext();
358 return DC && DC->isStdNamespace();
361 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
362 if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
365 DeclContext *DC = getDeclContext();
366 assert(DC && "This decl is not contained in a translation unit!");
368 while (!DC->isTranslationUnit()) {
369 DC = DC->getParent();
370 assert(DC && "This decl is not contained in a translation unit!");
373 return cast<TranslationUnitDecl>(DC);
376 ASTContext &Decl::getASTContext() const {
377 return getTranslationUnitDecl()->getASTContext();
380 ASTMutationListener *Decl::getASTMutationListener() const {
381 return getASTContext().getASTMutationListener();
384 unsigned Decl::getMaxAlignment() const {
389 const AttrVec &V = getAttrs();
390 ASTContext &Ctx = getASTContext();
391 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
393 Align = std::max(Align, I->getAlignment(Ctx));
397 bool Decl::isUsed(bool CheckUsedAttr) const {
398 const Decl *CanonD = getCanonicalDecl();
402 // Check for used attribute.
403 // Ask the most recent decl, since attributes accumulate in the redecl chain.
404 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
407 // The information may have not been deserialized yet. Force deserialization
408 // to complete the needed information.
409 return getMostRecentDecl()->getCanonicalDecl()->Used;
412 void Decl::markUsed(ASTContext &C) {
416 if (C.getASTMutationListener())
417 C.getASTMutationListener()->DeclarationMarkedUsed(this);
422 bool Decl::isReferenced() const {
426 // Check redeclarations.
427 for (const auto *I : redecls())
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();
446 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
448 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
449 return dcd->getAttr<ExternalSourceSymbolAttr>();
455 bool Decl::hasDefiningAttr() const {
456 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
459 const Attr *Decl::getDefiningAttr() const {
460 if (auto *AA = getAttr<AliasAttr>())
462 if (auto *IFA = getAttr<IFuncAttr>())
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;
480 /// Determine the availability of the given declaration based on
481 /// the target platform.
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.
487 /// FIXME: Make these strings localizable, since they end up in
489 static AvailabilityResult CheckAvailability(ASTContext &Context,
490 const AvailabilityAttr *A,
491 std::string *Message,
492 VersionTuple EnclosingVersion) {
493 if (EnclosingVersion.empty())
494 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
496 if (EnclosingVersion.empty())
499 StringRef ActualPlatform = A->getPlatform()->getName();
500 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
502 // Match the platform name.
503 if (getRealizedPlatform(A, Context) != TargetPlatform)
506 StringRef PrettyPlatformName
507 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
509 if (PrettyPlatformName.empty())
510 PrettyPlatformName = ActualPlatform;
512 std::string HintMessage;
513 if (!A->getMessage().empty()) {
515 HintMessage += A->getMessage();
518 // Make sure that this declaration has not been marked 'unavailable'.
519 if (A->getUnavailable()) {
522 llvm::raw_string_ostream Out(*Message);
523 Out << "not available on " << PrettyPlatformName
527 return AR_Unavailable;
530 // Make sure that this declaration has already been introduced.
531 if (!A->getIntroduced().empty() &&
532 EnclosingVersion < A->getIntroduced()) {
535 llvm::raw_string_ostream Out(*Message);
536 VersionTuple VTI(A->getIntroduced());
537 Out << "introduced in " << PrettyPlatformName << ' '
538 << VTI << HintMessage;
541 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
544 // Make sure that this declaration hasn't been obsoleted.
545 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
548 llvm::raw_string_ostream Out(*Message);
549 VersionTuple VTO(A->getObsoleted());
550 Out << "obsoleted in " << PrettyPlatformName << ' '
551 << VTO << HintMessage;
554 return AR_Unavailable;
557 // Make sure that this declaration hasn't been deprecated.
558 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
561 llvm::raw_string_ostream Out(*Message);
562 VersionTuple VTD(A->getDeprecated());
563 Out << "first deprecated in " << PrettyPlatformName << ' '
564 << VTD << HintMessage;
567 return AR_Deprecated;
573 AvailabilityResult Decl::getAvailability(std::string *Message,
574 VersionTuple EnclosingVersion,
575 StringRef *RealizedPlatform) const {
576 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
577 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
580 AvailabilityResult Result = AR_Available;
581 std::string ResultMessage;
583 for (const auto *A : attrs()) {
584 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
585 if (Result >= AR_Deprecated)
589 ResultMessage = Deprecated->getMessage();
591 Result = AR_Deprecated;
595 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
597 *Message = Unavailable->getMessage();
598 return AR_Unavailable;
601 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
602 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
603 Message, EnclosingVersion);
605 if (AR == AR_Unavailable) {
606 if (RealizedPlatform)
607 *RealizedPlatform = Availability->getPlatform()->getName();
608 return AR_Unavailable;
614 ResultMessage.swap(*Message);
621 Message->swap(ResultMessage);
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)
632 if (!Availability->getIntroduced().empty())
633 return Availability->getIntroduced();
639 bool Decl::canBeWeakImported(bool &IsDefinition) const {
640 IsDefinition = false;
642 // Variables, if they aren't definitions.
643 if (const auto *Var = dyn_cast<VarDecl>(this)) {
644 if (Var->isThisDeclarationADefinition()) {
650 // Functions, if they aren't definitions.
651 } else if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
658 // Objective-C classes, if this is the non-fragile runtime.
659 } else if (isa<ObjCInterfaceDecl>(this) &&
660 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
669 bool Decl::isWeakImported() const {
671 if (!canBeWeakImported(IsDefinition))
674 for (const auto *A : attrs()) {
675 if (isa<WeakImportAttr>(A))
678 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
679 if (CheckAvailability(getASTContext(), Availability, nullptr,
680 VersionTuple()) == AR_NotYetIntroduced)
688 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
691 case CXXDeductionGuide:
694 case ConstructorUsingShadow:
704 return IDNS_Ordinary;
708 return IDNS_Ordinary | IDNS_Member;
711 case NonTypeTemplateParm:
714 // These (C++-only) declarations are found by redeclaration lookup for
715 // tag types, so we include them in the tag namespace.
716 return IDNS_Ordinary | IDNS_Tag;
718 case ObjCCompatibleAlias:
720 return IDNS_Ordinary | IDNS_Type;
724 case TemplateTypeParm:
726 return IDNS_Ordinary | IDNS_Type;
728 case UnresolvedUsingTypename:
729 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
732 return 0; // we'll actually overwrite this later
734 case UnresolvedUsingValue:
735 return IDNS_Ordinary | IDNS_Using;
742 return IDNS_ObjCProtocol;
745 case ObjCAtDefsField:
752 return IDNS_Tag | IDNS_Type;
756 return IDNS_Namespace;
758 case FunctionTemplate:
759 return IDNS_Ordinary;
762 case TemplateTemplateParm:
763 case TypeAliasTemplate:
764 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
766 case OMPDeclareReduction:
767 return IDNS_OMPReduction;
769 case OMPDeclareMapper:
770 return IDNS_OMPMapper;
780 case ObjCPropertyImpl:
782 case PragmaDetectMismatch:
785 case TranslationUnit:
790 case BuiltinTemplate:
791 case ClassTemplateSpecialization:
792 case ClassTemplatePartialSpecialization:
793 case ClassScopeFunctionSpecialization:
794 case VarTemplateSpecialization:
795 case VarTemplatePartialSpecialization:
796 case ObjCImplementation:
798 case ObjCCategoryImpl:
800 case OMPThreadPrivate:
803 case OMPCapturedExpr:
805 // Never looked up by name.
809 llvm_unreachable("Invalid DeclKind!");
812 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
813 assert(!HasAttrs && "Decl already contains attrs.");
815 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
816 assert(AttrBlank.empty() && "HasAttrs was wrong?");
822 void Decl::dropAttrs() {
823 if (!HasAttrs) return;
826 getASTContext().eraseDeclAttrs(this);
829 void Decl::addAttr(Attr *A) {
831 setAttrs(AttrVec(1, A));
835 AttrVec &Attrs = getAttrs();
836 if (!A->isInherited()) {
841 // Attribute inheritance is processed after attribute parsing. To keep the
842 // order as in the source code, add inherited attributes before non-inherited
844 auto I = Attrs.begin(), E = Attrs.end();
845 for (; I != E; ++I) {
846 if (!(*I)->isInherited())
852 const AttrVec &Decl::getAttrs() const {
853 assert(HasAttrs && "No attrs to get!");
854 return getASTContext().getDeclAttrs(this);
857 Decl *Decl::castFromDeclContext (const DeclContext *D) {
858 Decl::Kind DK = D->getDeclKind();
860 #define DECL(NAME, BASE)
861 #define DECL_CONTEXT(NAME) \
863 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
864 #define DECL_CONTEXT_BASE(NAME)
865 #include "clang/AST/DeclNodes.inc"
867 #define DECL(NAME, BASE)
868 #define DECL_CONTEXT_BASE(NAME) \
869 if (DK >= first##NAME && DK <= last##NAME) \
870 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
871 #include "clang/AST/DeclNodes.inc"
872 llvm_unreachable("a decl that inherits DeclContext isn't handled");
876 DeclContext *Decl::castToDeclContext(const Decl *D) {
877 Decl::Kind DK = D->getKind();
879 #define DECL(NAME, BASE)
880 #define DECL_CONTEXT(NAME) \
882 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
883 #define DECL_CONTEXT_BASE(NAME)
884 #include "clang/AST/DeclNodes.inc"
886 #define DECL(NAME, BASE)
887 #define DECL_CONTEXT_BASE(NAME) \
888 if (DK >= first##NAME && DK <= last##NAME) \
889 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
890 #include "clang/AST/DeclNodes.inc"
891 llvm_unreachable("a decl that inherits DeclContext isn't handled");
895 SourceLocation Decl::getBodyRBrace() const {
896 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
897 // FunctionDecl stores EndRangeLoc for this purpose.
898 if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
899 const FunctionDecl *Definition;
900 if (FD->hasBody(Definition))
901 return Definition->getSourceRange().getEnd();
905 if (Stmt *Body = getBody())
906 return Body->getSourceRange().getEnd();
911 bool Decl::AccessDeclContextSanity() const {
913 // Suppress this check if any of the following hold:
914 // 1. this is the translation unit (and thus has no parent)
915 // 2. this is a template parameter (and thus doesn't belong to its context)
916 // 3. this is a non-type template parameter
917 // 4. the context is not a record
919 // 6. it's a C++0x static_assert.
920 // 7. it's a block literal declaration
921 if (isa<TranslationUnitDecl>(this) ||
922 isa<TemplateTypeParmDecl>(this) ||
923 isa<NonTypeTemplateParmDecl>(this) ||
925 !isa<CXXRecordDecl>(getDeclContext()) ||
927 isa<StaticAssertDecl>(this) ||
928 isa<BlockDecl>(this) ||
929 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
930 // as DeclContext (?).
931 isa<ParmVarDecl>(this) ||
932 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
933 // AS_none as access specifier.
934 isa<CXXRecordDecl>(this) ||
935 isa<ClassScopeFunctionSpecializationDecl>(this))
938 assert(Access != AS_none &&
939 "Access specifier is AS_none inside a record decl");
944 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
945 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
947 int64_t Decl::getID() const {
948 return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
951 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
953 if (const auto *D = dyn_cast<ValueDecl>(this))
955 else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
956 Ty = D->getUnderlyingType();
960 if (Ty->isFunctionPointerType())
961 Ty = Ty->getAs<PointerType>()->getPointeeType();
962 else if (Ty->isFunctionReferenceType())
963 Ty = Ty->getAs<ReferenceType>()->getPointeeType();
964 else if (BlocksToo && Ty->isBlockPointerType())
965 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
967 return Ty->getAs<FunctionType>();
970 /// Starting at a given context (a Decl or DeclContext), look for a
971 /// code context that is not a closure (a lambda, block, etc.).
972 template <class T> static Decl *getNonClosureContext(T *D) {
973 if (getKind(D) == Decl::CXXMethod) {
974 auto *MD = cast<CXXMethodDecl>(D);
975 if (MD->getOverloadedOperator() == OO_Call &&
976 MD->getParent()->isLambda())
977 return getNonClosureContext(MD->getParent()->getParent());
979 } else if (auto *FD = dyn_cast<FunctionDecl>(D))
981 else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
983 else if (auto *BD = dyn_cast<BlockDecl>(D))
984 return getNonClosureContext(BD->getParent());
985 else if (auto *CD = dyn_cast<CapturedDecl>(D))
986 return getNonClosureContext(CD->getParent());
991 Decl *Decl::getNonClosureContext() {
992 return ::getNonClosureContext(this);
995 Decl *DeclContext::getNonClosureAncestor() {
996 return ::getNonClosureContext(this);
999 //===----------------------------------------------------------------------===//
1000 // DeclContext Implementation
1001 //===----------------------------------------------------------------------===//
1003 DeclContext::DeclContext(Decl::Kind K) {
1004 DeclContextBits.DeclKind = K;
1005 setHasExternalLexicalStorage(false);
1006 setHasExternalVisibleStorage(false);
1007 setNeedToReconcileExternalVisibleStorage(false);
1008 setHasLazyLocalLexicalLookups(false);
1009 setHasLazyExternalLexicalLookups(false);
1010 setUseQualifiedLookup(false);
1013 bool DeclContext::classof(const Decl *D) {
1014 switch (D->getKind()) {
1015 #define DECL(NAME, BASE)
1016 #define DECL_CONTEXT(NAME) case Decl::NAME:
1017 #define DECL_CONTEXT_BASE(NAME)
1018 #include "clang/AST/DeclNodes.inc"
1021 #define DECL(NAME, BASE)
1022 #define DECL_CONTEXT_BASE(NAME) \
1023 if (D->getKind() >= Decl::first##NAME && \
1024 D->getKind() <= Decl::last##NAME) \
1026 #include "clang/AST/DeclNodes.inc"
1031 DeclContext::~DeclContext() = default;
1033 /// Find the parent context of this context that will be
1034 /// used for unqualified name lookup.
1036 /// Generally, the parent lookup context is the semantic context. However, for
1037 /// a friend function the parent lookup context is the lexical context, which
1038 /// is the class in which the friend is declared.
1039 DeclContext *DeclContext::getLookupParent() {
1040 // FIXME: Find a better way to identify friends.
1041 if (isa<FunctionDecl>(this))
1042 if (getParent()->getRedeclContext()->isFileContext() &&
1043 getLexicalParent()->getRedeclContext()->isRecord())
1044 return getLexicalParent();
1049 const BlockDecl *DeclContext::getInnermostBlockDecl() const {
1050 const DeclContext *Ctx = this;
1053 if (Ctx->isClosure())
1054 return cast<BlockDecl>(Ctx);
1055 Ctx = Ctx->getParent();
1061 bool DeclContext::isInlineNamespace() const {
1062 return isNamespace() &&
1063 cast<NamespaceDecl>(this)->isInline();
1066 bool DeclContext::isStdNamespace() const {
1070 const auto *ND = cast<NamespaceDecl>(this);
1071 if (ND->isInline()) {
1072 return ND->getParent()->isStdNamespace();
1075 if (!getParent()->getRedeclContext()->isTranslationUnit())
1078 const IdentifierInfo *II = ND->getIdentifier();
1079 return II && II->isStr("std");
1082 bool DeclContext::isDependentContext() const {
1083 if (isFileContext())
1086 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1089 if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1090 if (Record->getDescribedClassTemplate())
1093 if (Record->isDependentLambda())
1097 if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1098 if (Function->getDescribedFunctionTemplate())
1101 // Friend function declarations are dependent if their *lexical*
1102 // context is dependent.
1103 if (cast<Decl>(this)->getFriendObjectKind())
1104 return getLexicalParent()->isDependentContext();
1107 // FIXME: A variable template is a dependent context, but is not a
1108 // DeclContext. A context within it (such as a lambda-expression)
1109 // should be considered dependent.
1111 return getParent() && getParent()->isDependentContext();
1114 bool DeclContext::isTransparentContext() const {
1115 if (getDeclKind() == Decl::Enum)
1116 return !cast<EnumDecl>(this)->isScoped();
1117 else if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1123 static bool isLinkageSpecContext(const DeclContext *DC,
1124 LinkageSpecDecl::LanguageIDs ID) {
1125 while (DC->getDeclKind() != Decl::TranslationUnit) {
1126 if (DC->getDeclKind() == Decl::LinkageSpec)
1127 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1128 DC = DC->getLexicalParent();
1133 bool DeclContext::isExternCContext() const {
1134 return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1137 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1138 const DeclContext *DC = this;
1139 while (DC->getDeclKind() != Decl::TranslationUnit) {
1140 if (DC->getDeclKind() == Decl::LinkageSpec &&
1141 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1142 return cast<LinkageSpecDecl>(DC);
1143 DC = DC->getLexicalParent();
1148 bool DeclContext::isExternCXXContext() const {
1149 return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1152 bool DeclContext::Encloses(const DeclContext *DC) const {
1153 if (getPrimaryContext() != this)
1154 return getPrimaryContext()->Encloses(DC);
1156 for (; DC; DC = DC->getParent())
1157 if (DC->getPrimaryContext() == this)
1162 DeclContext *DeclContext::getPrimaryContext() {
1163 switch (getDeclKind()) {
1164 case Decl::TranslationUnit:
1165 case Decl::ExternCContext:
1166 case Decl::LinkageSpec:
1169 case Decl::Captured:
1170 case Decl::OMPDeclareReduction:
1171 case Decl::OMPDeclareMapper:
1172 // There is only one DeclContext for these entities.
1175 case Decl::Namespace:
1176 // The original namespace is our primary context.
1177 return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1179 case Decl::ObjCMethod:
1182 case Decl::ObjCInterface:
1183 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1184 if (auto *Def = OID->getDefinition())
1188 case Decl::ObjCProtocol:
1189 if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1190 if (auto *Def = OPD->getDefinition())
1194 case Decl::ObjCCategory:
1197 case Decl::ObjCImplementation:
1198 case Decl::ObjCCategoryImpl:
1202 if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1203 // If this is a tag type that has a definition or is currently
1204 // being defined, that definition is our primary context.
1205 auto *Tag = cast<TagDecl>(this);
1207 if (TagDecl *Def = Tag->getDefinition())
1210 if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1211 // Note, TagType::getDecl returns the (partial) definition one exists.
1212 TagDecl *PossiblePartialDef = TagTy->getDecl();
1213 if (PossiblePartialDef->isBeingDefined())
1214 return PossiblePartialDef;
1216 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1222 assert(getDeclKind() >= Decl::firstFunction &&
1223 getDeclKind() <= Decl::lastFunction &&
1224 "Unknown DeclContext kind");
1230 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1233 if (getDeclKind() != Decl::Namespace) {
1234 Contexts.push_back(this);
1238 auto *Self = static_cast<NamespaceDecl *>(this);
1239 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1240 N = N->getPreviousDecl())
1241 Contexts.push_back(N);
1243 std::reverse(Contexts.begin(), Contexts.end());
1246 std::pair<Decl *, Decl *>
1247 DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1248 bool FieldsAlreadyLoaded) {
1249 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1250 Decl *FirstNewDecl = nullptr;
1251 Decl *PrevDecl = nullptr;
1252 for (auto *D : Decls) {
1253 if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1257 PrevDecl->NextInContextAndBits.setPointer(D);
1264 return std::make_pair(FirstNewDecl, PrevDecl);
1267 /// We have just acquired external visible storage, and we already have
1268 /// built a lookup map. For every name in the map, pull in the new names from
1269 /// the external storage.
1270 void DeclContext::reconcileExternalVisibleStorage() const {
1271 assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1272 setNeedToReconcileExternalVisibleStorage(false);
1274 for (auto &Lookup : *LookupPtr)
1275 Lookup.second.setHasExternalDecls();
1278 /// Load the declarations within this lexical storage from an
1279 /// external source.
1280 /// \return \c true if any declarations were added.
1282 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1283 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1284 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1286 // Notify that we have a DeclContext that is initializing.
1287 ExternalASTSource::Deserializing ADeclContext(Source);
1289 // Load the external declarations, if any.
1290 SmallVector<Decl*, 64> Decls;
1291 setHasExternalLexicalStorage(false);
1292 Source->FindExternalLexicalDecls(this, Decls);
1297 // We may have already loaded just the fields of this record, in which case
1298 // we need to ignore them.
1299 bool FieldsAlreadyLoaded = false;
1300 if (const auto *RD = dyn_cast<RecordDecl>(this))
1301 FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1303 // Splice the newly-read declarations into the beginning of the list
1305 Decl *ExternalFirst, *ExternalLast;
1306 std::tie(ExternalFirst, ExternalLast) =
1307 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1308 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1309 FirstDecl = ExternalFirst;
1311 LastDecl = ExternalLast;
1315 DeclContext::lookup_result
1316 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1317 DeclarationName Name) {
1318 ASTContext &Context = DC->getParentASTContext();
1319 StoredDeclsMap *Map;
1320 if (!(Map = DC->LookupPtr))
1321 Map = DC->CreateStoredDeclsMap(Context);
1322 if (DC->hasNeedToReconcileExternalVisibleStorage())
1323 DC->reconcileExternalVisibleStorage();
1325 (*Map)[Name].removeExternalDecls();
1327 return DeclContext::lookup_result();
1330 DeclContext::lookup_result
1331 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1332 DeclarationName Name,
1333 ArrayRef<NamedDecl*> Decls) {
1334 ASTContext &Context = DC->getParentASTContext();
1335 StoredDeclsMap *Map;
1336 if (!(Map = DC->LookupPtr))
1337 Map = DC->CreateStoredDeclsMap(Context);
1338 if (DC->hasNeedToReconcileExternalVisibleStorage())
1339 DC->reconcileExternalVisibleStorage();
1341 StoredDeclsList &List = (*Map)[Name];
1343 // Clear out any old external visible declarations, to avoid quadratic
1344 // performance in the redeclaration checks below.
1345 List.removeExternalDecls();
1347 if (!List.isNull()) {
1348 // We have both existing declarations and new declarations for this name.
1349 // Some of the declarations may simply replace existing ones. Handle those
1351 llvm::SmallVector<unsigned, 8> Skip;
1352 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1353 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1355 Skip.push_back(Decls.size());
1357 // Add in any new declarations.
1358 unsigned SkipPos = 0;
1359 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1360 if (I == Skip[SkipPos])
1363 List.AddSubsequentDecl(Decls[I]);
1366 // Convert the array to a StoredDeclsList.
1367 for (auto *D : Decls) {
1369 List.setOnlyValue(D);
1371 List.AddSubsequentDecl(D);
1375 return List.getLookupResult();
1378 DeclContext::decl_iterator DeclContext::decls_begin() const {
1379 if (hasExternalLexicalStorage())
1380 LoadLexicalDeclsFromExternalStorage();
1381 return decl_iterator(FirstDecl);
1384 bool DeclContext::decls_empty() const {
1385 if (hasExternalLexicalStorage())
1386 LoadLexicalDeclsFromExternalStorage();
1391 bool DeclContext::containsDecl(Decl *D) const {
1392 return (D->getLexicalDeclContext() == this &&
1393 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1396 bool DeclContext::containsDeclAndLoad(Decl *D) const {
1397 if (hasExternalLexicalStorage())
1398 LoadLexicalDeclsFromExternalStorage();
1399 return containsDecl(D);
1402 /// shouldBeHidden - Determine whether a declaration which was declared
1403 /// within its semantic context should be invisible to qualified name lookup.
1404 static bool shouldBeHidden(NamedDecl *D) {
1405 // Skip unnamed declarations.
1406 if (!D->getDeclName())
1409 // Skip entities that can't be found by name lookup into a particular
1411 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1412 D->isTemplateParameter())
1415 // Skip friends and local extern declarations unless they're the first
1416 // declaration of the entity.
1417 if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1418 D != D->getCanonicalDecl())
1421 // Skip template specializations.
1422 // FIXME: This feels like a hack. Should DeclarationName support
1423 // template-ids, or is there a better way to keep specializations
1424 // from being visible?
1425 if (isa<ClassTemplateSpecializationDecl>(D))
1427 if (auto *FD = dyn_cast<FunctionDecl>(D))
1428 if (FD->isFunctionTemplateSpecialization())
1434 void DeclContext::removeDecl(Decl *D) {
1435 assert(D->getLexicalDeclContext() == this &&
1436 "decl being removed from non-lexical context");
1437 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1438 "decl is not in decls list");
1440 // Remove D from the decl chain. This is O(n) but hopefully rare.
1441 if (D == FirstDecl) {
1443 FirstDecl = LastDecl = nullptr;
1445 FirstDecl = D->NextInContextAndBits.getPointer();
1447 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1448 assert(I && "decl not found in linked list");
1449 if (I->NextInContextAndBits.getPointer() == D) {
1450 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1451 if (D == LastDecl) LastDecl = I;
1457 // Mark that D is no longer in the decl chain.
1458 D->NextInContextAndBits.setPointer(nullptr);
1460 // Remove D from the lookup table if necessary.
1461 if (isa<NamedDecl>(D)) {
1462 auto *ND = cast<NamedDecl>(D);
1464 // Do not try to remove the declaration if that is invisible to qualified
1465 // lookup. E.g. template specializations are skipped.
1466 if (shouldBeHidden(ND))
1469 // Remove only decls that have a name
1470 if (!ND->getDeclName())
1473 auto *DC = D->getDeclContext();
1475 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1477 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1478 assert(Pos != Map->end() && "no lookup entry for decl");
1479 // Remove the decl only if it is contained.
1480 StoredDeclsList::DeclsTy *Vec = Pos->second.getAsVector();
1481 if ((Vec && is_contained(*Vec, ND)) || Pos->second.getAsDecl() == ND)
1482 Pos->second.remove(ND);
1484 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1488 void DeclContext::addHiddenDecl(Decl *D) {
1489 assert(D->getLexicalDeclContext() == this &&
1490 "Decl inserted into wrong lexical context");
1491 assert(!D->getNextDeclInContext() && D != LastDecl &&
1492 "Decl already inserted into a DeclContext");
1495 LastDecl->NextInContextAndBits.setPointer(D);
1498 FirstDecl = LastDecl = D;
1501 // Notify a C++ record declaration that we've added a member, so it can
1502 // update its class-specific state.
1503 if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1504 Record->addedMember(D);
1506 // If this is a newly-created (not de-serialized) import declaration, wire
1507 // it in to the list of local import declarations.
1508 if (!D->isFromASTFile()) {
1509 if (auto *Import = dyn_cast<ImportDecl>(D))
1510 D->getASTContext().addedLocalImportDecl(Import);
1514 void DeclContext::addDecl(Decl *D) {
1517 if (auto *ND = dyn_cast<NamedDecl>(D))
1518 ND->getDeclContext()->getPrimaryContext()->
1519 makeDeclVisibleInContextWithFlags(ND, false, true);
1522 void DeclContext::addDeclInternal(Decl *D) {
1525 if (auto *ND = dyn_cast<NamedDecl>(D))
1526 ND->getDeclContext()->getPrimaryContext()->
1527 makeDeclVisibleInContextWithFlags(ND, true, true);
1530 /// buildLookup - Build the lookup data structure with all of the
1531 /// declarations in this DeclContext (and any other contexts linked
1532 /// to it or transparent contexts nested within it) and return it.
1534 /// Note that the produced map may miss out declarations from an
1535 /// external source. If it does, those entries will be marked with
1536 /// the 'hasExternalDecls' flag.
1537 StoredDeclsMap *DeclContext::buildLookup() {
1538 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1540 if (!hasLazyLocalLexicalLookups() &&
1541 !hasLazyExternalLexicalLookups())
1544 SmallVector<DeclContext *, 2> Contexts;
1545 collectAllContexts(Contexts);
1547 if (hasLazyExternalLexicalLookups()) {
1548 setHasLazyExternalLexicalLookups(false);
1549 for (auto *DC : Contexts) {
1550 if (DC->hasExternalLexicalStorage()) {
1551 bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1552 setHasLazyLocalLexicalLookups(
1553 hasLazyLocalLexicalLookups() | LoadedDecls );
1557 if (!hasLazyLocalLexicalLookups())
1561 for (auto *DC : Contexts)
1562 buildLookupImpl(DC, hasExternalVisibleStorage());
1564 // We no longer have any lazy decls.
1565 setHasLazyLocalLexicalLookups(false);
1569 /// buildLookupImpl - Build part of the lookup data structure for the
1570 /// declarations contained within DCtx, which will either be this
1571 /// DeclContext, a DeclContext linked to it, or a transparent context
1572 /// nested within it.
1573 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1574 for (auto *D : DCtx->noload_decls()) {
1575 // Insert this declaration into the lookup structure, but only if
1576 // it's semantically within its decl context. Any other decls which
1577 // should be found in this context are added eagerly.
1579 // If it's from an AST file, don't add it now. It'll get handled by
1580 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1581 // in C++, we do not track external visible decls for the TU, so in
1582 // that case we need to collect them all here.
1583 if (auto *ND = dyn_cast<NamedDecl>(D))
1584 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1585 (!ND->isFromASTFile() ||
1586 (isTranslationUnit() &&
1587 !getParentASTContext().getLangOpts().CPlusPlus)))
1588 makeDeclVisibleInContextImpl(ND, Internal);
1590 // If this declaration is itself a transparent declaration context
1591 // or inline namespace, add the members of this declaration of that
1592 // context (recursively).
1593 if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1594 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1595 buildLookupImpl(InnerCtx, Internal);
1599 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1601 DeclContext::lookup_result
1602 DeclContext::lookup(DeclarationName Name) const {
1603 assert(getDeclKind() != Decl::LinkageSpec &&
1604 getDeclKind() != Decl::Export &&
1605 "should not perform lookups into transparent contexts");
1607 const DeclContext *PrimaryContext = getPrimaryContext();
1608 if (PrimaryContext != this)
1609 return PrimaryContext->lookup(Name);
1611 // If we have an external source, ensure that any later redeclarations of this
1612 // context have been loaded, since they may add names to the result of this
1613 // lookup (or add external visible storage).
1614 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1616 (void)cast<Decl>(this)->getMostRecentDecl();
1618 if (hasExternalVisibleStorage()) {
1619 assert(Source && "external visible storage but no external source?");
1621 if (hasNeedToReconcileExternalVisibleStorage())
1622 reconcileExternalVisibleStorage();
1624 StoredDeclsMap *Map = LookupPtr;
1626 if (hasLazyLocalLexicalLookups() ||
1627 hasLazyExternalLexicalLookups())
1628 // FIXME: Make buildLookup const?
1629 Map = const_cast<DeclContext*>(this)->buildLookup();
1632 Map = CreateStoredDeclsMap(getParentASTContext());
1634 // If we have a lookup result with no external decls, we are done.
1635 std::pair<StoredDeclsMap::iterator, bool> R =
1636 Map->insert(std::make_pair(Name, StoredDeclsList()));
1637 if (!R.second && !R.first->second.hasExternalDecls())
1638 return R.first->second.getLookupResult();
1640 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1641 if (StoredDeclsMap *Map = LookupPtr) {
1642 StoredDeclsMap::iterator I = Map->find(Name);
1643 if (I != Map->end())
1644 return I->second.getLookupResult();
1651 StoredDeclsMap *Map = LookupPtr;
1652 if (hasLazyLocalLexicalLookups() ||
1653 hasLazyExternalLexicalLookups())
1654 Map = const_cast<DeclContext*>(this)->buildLookup();
1659 StoredDeclsMap::iterator I = Map->find(Name);
1660 if (I == Map->end())
1663 return I->second.getLookupResult();
1666 DeclContext::lookup_result
1667 DeclContext::noload_lookup(DeclarationName Name) {
1668 assert(getDeclKind() != Decl::LinkageSpec &&
1669 getDeclKind() != Decl::Export &&
1670 "should not perform lookups into transparent contexts");
1672 DeclContext *PrimaryContext = getPrimaryContext();
1673 if (PrimaryContext != this)
1674 return PrimaryContext->noload_lookup(Name);
1676 loadLazyLocalLexicalLookups();
1677 StoredDeclsMap *Map = LookupPtr;
1681 StoredDeclsMap::iterator I = Map->find(Name);
1682 return I != Map->end() ? I->second.getLookupResult()
1686 // If we have any lazy lexical declarations not in our lookup map, add them
1687 // now. Don't import any external declarations, not even if we know we have
1688 // some missing from the external visible lookups.
1689 void DeclContext::loadLazyLocalLexicalLookups() {
1690 if (hasLazyLocalLexicalLookups()) {
1691 SmallVector<DeclContext *, 2> Contexts;
1692 collectAllContexts(Contexts);
1693 for (auto *Context : Contexts)
1694 buildLookupImpl(Context, hasExternalVisibleStorage());
1695 setHasLazyLocalLexicalLookups(false);
1699 void DeclContext::localUncachedLookup(DeclarationName Name,
1700 SmallVectorImpl<NamedDecl *> &Results) {
1703 // If there's no external storage, just perform a normal lookup and copy
1705 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1706 lookup_result LookupResults = lookup(Name);
1707 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1711 // If we have a lookup table, check there first. Maybe we'll get lucky.
1712 // FIXME: Should we be checking these flags on the primary context?
1713 if (Name && !hasLazyLocalLexicalLookups() &&
1714 !hasLazyExternalLexicalLookups()) {
1715 if (StoredDeclsMap *Map = LookupPtr) {
1716 StoredDeclsMap::iterator Pos = Map->find(Name);
1717 if (Pos != Map->end()) {
1718 Results.insert(Results.end(),
1719 Pos->second.getLookupResult().begin(),
1720 Pos->second.getLookupResult().end());
1726 // Slow case: grovel through the declarations in our chain looking for
1728 // FIXME: If we have lazy external declarations, this will not find them!
1729 // FIXME: Should we CollectAllContexts and walk them all here?
1730 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1731 if (auto *ND = dyn_cast<NamedDecl>(D))
1732 if (ND->getDeclName() == Name)
1733 Results.push_back(ND);
1737 DeclContext *DeclContext::getRedeclContext() {
1738 DeclContext *Ctx = this;
1740 // In C, a record type is the redeclaration context for its fields only. If
1741 // we arrive at a record context after skipping anything else, we should skip
1742 // the record as well. Currently, this means skipping enumerations because
1743 // they're the only transparent context that can exist within a struct or
1745 bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1746 !getParentASTContext().getLangOpts().CPlusPlus;
1748 // Skip through contexts to get to the redeclaration context. Transparent
1749 // contexts are always skipped.
1750 while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1751 Ctx = Ctx->getParent();
1755 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1756 DeclContext *Ctx = this;
1757 // Skip through non-namespace, non-translation-unit contexts.
1758 while (!Ctx->isFileContext())
1759 Ctx = Ctx->getParent();
1760 return Ctx->getPrimaryContext();
1763 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1764 // Loop until we find a non-record context.
1765 RecordDecl *OutermostRD = nullptr;
1766 DeclContext *DC = this;
1767 while (DC->isRecord()) {
1768 OutermostRD = cast<RecordDecl>(DC);
1769 DC = DC->getLexicalParent();
1774 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1775 // For non-file contexts, this is equivalent to Equals.
1776 if (!isFileContext())
1777 return O->Equals(this);
1780 if (O->Equals(this))
1783 const auto *NS = dyn_cast<NamespaceDecl>(O);
1784 if (!NS || !NS->isInline())
1786 O = NS->getParent();
1792 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1793 DeclContext *PrimaryDC = this->getPrimaryContext();
1794 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1795 // If the decl is being added outside of its semantic decl context, we
1796 // need to ensure that we eagerly build the lookup information for it.
1797 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1800 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1802 assert(this == getPrimaryContext() && "expected a primary DC");
1804 if (!isLookupContext()) {
1805 if (isTransparentContext())
1806 getParent()->getPrimaryContext()
1807 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1811 // Skip declarations which should be invisible to name lookup.
1812 if (shouldBeHidden(D))
1815 // If we already have a lookup data structure, perform the insertion into
1816 // it. If we might have externally-stored decls with this name, look them
1817 // up and perform the insertion. If this decl was declared outside its
1818 // semantic context, buildLookup won't add it, so add it now.
1820 // FIXME: As a performance hack, don't add such decls into the translation
1821 // unit unless we're in C++, since qualified lookup into the TU is never
1823 if (LookupPtr || hasExternalVisibleStorage() ||
1824 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1825 (getParentASTContext().getLangOpts().CPlusPlus ||
1826 !isTranslationUnit()))) {
1827 // If we have lazily omitted any decls, they might have the same name as
1828 // the decl which we are adding, so build a full lookup table before adding
1831 makeDeclVisibleInContextImpl(D, Internal);
1833 setHasLazyLocalLexicalLookups(true);
1836 // If we are a transparent context or inline namespace, insert into our
1837 // parent context, too. This operation is recursive.
1838 if (isTransparentContext() || isInlineNamespace())
1839 getParent()->getPrimaryContext()->
1840 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1842 auto *DCAsDecl = cast<Decl>(this);
1843 // Notify that a decl was made visible unless we are a Tag being defined.
1844 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1845 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1846 L->AddedVisibleDecl(this, D);
1849 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1850 // Find or create the stored declaration map.
1851 StoredDeclsMap *Map = LookupPtr;
1853 ASTContext *C = &getParentASTContext();
1854 Map = CreateStoredDeclsMap(*C);
1857 // If there is an external AST source, load any declarations it knows about
1858 // with this declaration's name.
1859 // If the lookup table contains an entry about this name it means that we
1860 // have already checked the external source.
1862 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1863 if (hasExternalVisibleStorage() &&
1864 Map->find(D->getDeclName()) == Map->end())
1865 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1867 // Insert this declaration into the map.
1868 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1871 // If this is being added as part of loading an external declaration,
1872 // this may not be the only external declaration with this name.
1873 // In this case, we never try to replace an existing declaration; we'll
1874 // handle that when we finalize the list of declarations for this name.
1875 DeclNameEntries.setHasExternalDecls();
1876 DeclNameEntries.AddSubsequentDecl(D);
1880 if (DeclNameEntries.isNull()) {
1881 DeclNameEntries.setOnlyValue(D);
1885 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1886 // This declaration has replaced an existing one for which
1887 // declarationReplaces returns true.
1891 // Put this declaration into the appropriate slot.
1892 DeclNameEntries.AddSubsequentDecl(D);
1895 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1896 return cast<UsingDirectiveDecl>(*I);
1899 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1901 DeclContext::udir_range DeclContext::using_directives() const {
1902 // FIXME: Use something more efficient than normal lookup for using
1903 // directives. In C++, using directives are looked up more than anything else.
1904 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1905 return udir_range(Result.begin(), Result.end());
1908 //===----------------------------------------------------------------------===//
1909 // Creation and Destruction of StoredDeclsMaps. //
1910 //===----------------------------------------------------------------------===//
1912 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1913 assert(!LookupPtr && "context already has a decls map");
1914 assert(getPrimaryContext() == this &&
1915 "creating decls map on non-primary context");
1918 bool Dependent = isDependentContext();
1920 M = new DependentStoredDeclsMap();
1922 M = new StoredDeclsMap();
1923 M->Previous = C.LastSDM;
1924 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1929 void ASTContext::ReleaseDeclContextMaps() {
1930 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1931 // pointer because the subclass doesn't add anything that needs to
1933 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1936 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1938 // Advance the iteration before we invalidate memory.
1939 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1942 delete static_cast<DependentStoredDeclsMap*>(Map);
1946 Map = Next.getPointer();
1947 Dependent = Next.getInt();
1951 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1952 DeclContext *Parent,
1953 const PartialDiagnostic &PDiag) {
1954 assert(Parent->isDependentContext()
1955 && "cannot iterate dependent diagnostics of non-dependent context");
1956 Parent = Parent->getPrimaryContext();
1957 if (!Parent->LookupPtr)
1958 Parent->CreateStoredDeclsMap(C);
1960 auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1962 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1963 // BumpPtrAllocator, rather than the ASTContext itself.
1964 PartialDiagnostic::Storage *DiagStorage = nullptr;
1965 if (PDiag.hasStorage())
1966 DiagStorage = new (C) PartialDiagnostic::Storage;
1968 auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1970 // TODO: Maybe we shouldn't reverse the order during insertion.
1971 DD->NextDiagnostic = Map->FirstDiagnostic;
1972 Map->FirstDiagnostic = DD;