1 //===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl and DeclContext classes.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.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/StmtCXX.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
41 #define ABSTRACT_DECL(DECL)
42 #include "clang/AST/DeclNodes.inc"
44 void Decl::updateOutOfDate(IdentifierInfo &II) const {
45 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
48 #define DECL(DERIVED, BASE) \
49 static_assert(llvm::AlignOf<Decl>::Alignment >= \
50 llvm::AlignOf<DERIVED##Decl>::Alignment, \
51 "Alignment sufficient after objects prepended to " #DERIVED);
52 #define ABSTRACT_DECL(DECL)
53 #include "clang/AST/DeclNodes.inc"
55 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
56 unsigned ID, std::size_t Extra) {
57 // Allocate an extra 8 bytes worth of storage, which ensures that the
58 // resulting pointer will still be 8-byte aligned.
59 static_assert(sizeof(unsigned) * 2 >= llvm::AlignOf<Decl>::Alignment,
60 "Decl won't be misaligned");
61 void *Start = Context.Allocate(Size + Extra + 8);
62 void *Result = (char*)Start + 8;
64 unsigned *PrefixPtr = (unsigned *)Result - 2;
66 // Zero out the first 4 bytes; this is used to store the owning module ID.
69 // Store the global declaration ID in the second 4 bytes.
75 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
76 DeclContext *Parent, std::size_t Extra) {
77 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
78 // With local visibility enabled, we track the owning module even for local
80 if (Ctx.getLangOpts().ModulesLocalVisibility) {
81 // Ensure required alignment of the resulting object by adding extra
82 // padding at the start if required.
84 llvm::OffsetToAlignment(sizeof(Module *),
85 llvm::AlignOf<Decl>::Alignment);
86 char *Buffer = reinterpret_cast<char *>(
87 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
89 return new (Buffer) Module*(nullptr) + 1;
91 return ::operator new(Size + Extra, Ctx);
94 Module *Decl::getOwningModuleSlow() const {
95 assert(isFromASTFile() && "Not from AST file?");
96 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
99 bool Decl::hasLocalOwningModuleStorage() const {
100 return getASTContext().getLangOpts().ModulesLocalVisibility;
103 const char *Decl::getDeclKindName() const {
105 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
106 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
107 #define ABSTRACT_DECL(DECL)
108 #include "clang/AST/DeclNodes.inc"
112 void Decl::setInvalidDecl(bool Invalid) {
113 InvalidDecl = Invalid;
114 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
115 if (Invalid && !isa<ParmVarDecl>(this)) {
116 // Defensive maneuver for ill-formed code: we're likely not to make it to
117 // a point where we set the access specifier, so default it to "public"
118 // to avoid triggering asserts elsewhere in the front end.
119 setAccess(AS_public);
123 const char *DeclContext::getDeclKindName() const {
125 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
126 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
127 #define ABSTRACT_DECL(DECL)
128 #include "clang/AST/DeclNodes.inc"
132 bool Decl::StatisticsEnabled = false;
133 void Decl::EnableStatistics() {
134 StatisticsEnabled = true;
137 void Decl::PrintStats() {
138 llvm::errs() << "\n*** Decl Stats:\n";
141 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
142 #define ABSTRACT_DECL(DECL)
143 #include "clang/AST/DeclNodes.inc"
144 llvm::errs() << " " << totalDecls << " decls total.\n";
147 #define DECL(DERIVED, BASE) \
148 if (n##DERIVED##s > 0) { \
149 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
150 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
151 << sizeof(DERIVED##Decl) << " each (" \
152 << n##DERIVED##s * sizeof(DERIVED##Decl) \
155 #define ABSTRACT_DECL(DECL)
156 #include "clang/AST/DeclNodes.inc"
158 llvm::errs() << "Total bytes = " << totalBytes << "\n";
161 void Decl::add(Kind k) {
163 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
164 #define ABSTRACT_DECL(DECL)
165 #include "clang/AST/DeclNodes.inc"
169 bool Decl::isTemplateParameterPack() const {
170 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
171 return TTP->isParameterPack();
172 if (const NonTypeTemplateParmDecl *NTTP
173 = dyn_cast<NonTypeTemplateParmDecl>(this))
174 return NTTP->isParameterPack();
175 if (const TemplateTemplateParmDecl *TTP
176 = dyn_cast<TemplateTemplateParmDecl>(this))
177 return TTP->isParameterPack();
181 bool Decl::isParameterPack() const {
182 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
183 return Parm->isParameterPack();
185 return isTemplateParameterPack();
188 FunctionDecl *Decl::getAsFunction() {
189 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
191 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
192 return FTD->getTemplatedDecl();
196 bool Decl::isTemplateDecl() const {
197 return isa<TemplateDecl>(this);
200 TemplateDecl *Decl::getDescribedTemplate() const {
201 if (auto *FD = dyn_cast<FunctionDecl>(this))
202 return FD->getDescribedFunctionTemplate();
203 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
204 return RD->getDescribedClassTemplate();
205 else if (auto *VD = dyn_cast<VarDecl>(this))
206 return VD->getDescribedVarTemplate();
211 const DeclContext *Decl::getParentFunctionOrMethod() const {
212 for (const DeclContext *DC = getDeclContext();
213 DC && !DC->isTranslationUnit() && !DC->isNamespace();
214 DC = DC->getParent())
215 if (DC->isFunctionOrMethod())
222 //===----------------------------------------------------------------------===//
223 // PrettyStackTraceDecl Implementation
224 //===----------------------------------------------------------------------===//
226 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
227 SourceLocation TheLoc = Loc;
228 if (TheLoc.isInvalid() && TheDecl)
229 TheLoc = TheDecl->getLocation();
231 if (TheLoc.isValid()) {
232 TheLoc.print(OS, SM);
238 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
240 DN->printQualifiedName(OS);
246 //===----------------------------------------------------------------------===//
247 // Decl Implementation
248 //===----------------------------------------------------------------------===//
250 // Out-of-line virtual method providing a home for Decl.
253 void Decl::setDeclContext(DeclContext *DC) {
257 void Decl::setLexicalDeclContext(DeclContext *DC) {
258 if (DC == getLexicalDeclContext())
262 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
264 getMultipleDC()->LexicalDC = DC;
266 Hidden = cast<Decl>(DC)->Hidden;
269 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
271 if (SemaDC == LexicalDC) {
274 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
275 MDC->SemanticDC = SemaDC;
276 MDC->LexicalDC = LexicalDC;
281 bool Decl::isLexicallyWithinFunctionOrMethod() const {
282 const DeclContext *LDC = getLexicalDeclContext();
284 if (LDC->isFunctionOrMethod())
286 if (!isa<TagDecl>(LDC))
288 LDC = LDC->getLexicalParent();
293 bool Decl::isInAnonymousNamespace() const {
294 const DeclContext *DC = getDeclContext();
296 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
297 if (ND->isAnonymousNamespace())
299 } while ((DC = DC->getParent()));
304 bool Decl::isInStdNamespace() const {
305 return getDeclContext()->isStdNamespace();
308 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
309 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
312 DeclContext *DC = getDeclContext();
313 assert(DC && "This decl is not contained in a translation unit!");
315 while (!DC->isTranslationUnit()) {
316 DC = DC->getParent();
317 assert(DC && "This decl is not contained in a translation unit!");
320 return cast<TranslationUnitDecl>(DC);
323 ASTContext &Decl::getASTContext() const {
324 return getTranslationUnitDecl()->getASTContext();
327 ASTMutationListener *Decl::getASTMutationListener() const {
328 return getASTContext().getASTMutationListener();
331 unsigned Decl::getMaxAlignment() const {
336 const AttrVec &V = getAttrs();
337 ASTContext &Ctx = getASTContext();
338 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
340 Align = std::max(Align, I->getAlignment(Ctx));
344 bool Decl::isUsed(bool CheckUsedAttr) const {
345 const Decl *CanonD = getCanonicalDecl();
349 // Check for used attribute.
350 // Ask the most recent decl, since attributes accumulate in the redecl chain.
351 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
354 // The information may have not been deserialized yet. Force deserialization
355 // to complete the needed information.
356 return getMostRecentDecl()->getCanonicalDecl()->Used;
359 void Decl::markUsed(ASTContext &C) {
363 if (C.getASTMutationListener())
364 C.getASTMutationListener()->DeclarationMarkedUsed(this);
369 bool Decl::isReferenced() const {
373 // Check redeclarations.
374 for (auto I : redecls())
381 bool Decl::hasDefiningAttr() const {
382 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
385 const Attr *Decl::getDefiningAttr() const {
386 if (AliasAttr *AA = getAttr<AliasAttr>())
388 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
393 /// \brief Determine the availability of the given declaration based on
394 /// the target platform.
396 /// When it returns an availability result other than \c AR_Available,
397 /// if the \p Message parameter is non-NULL, it will be set to a
398 /// string describing why the entity is unavailable.
400 /// FIXME: Make these strings localizable, since they end up in
402 static AvailabilityResult CheckAvailability(ASTContext &Context,
403 const AvailabilityAttr *A,
404 std::string *Message) {
405 VersionTuple TargetMinVersion =
406 Context.getTargetInfo().getPlatformMinVersion();
408 if (TargetMinVersion.empty())
411 // Check if this is an App Extension "platform", and if so chop off
412 // the suffix for matching with the actual platform.
413 StringRef ActualPlatform = A->getPlatform()->getName();
414 StringRef RealizedPlatform = ActualPlatform;
415 if (Context.getLangOpts().AppExt) {
416 size_t suffix = RealizedPlatform.rfind("_app_extension");
417 if (suffix != StringRef::npos)
418 RealizedPlatform = RealizedPlatform.slice(0, suffix);
421 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
423 // Match the platform name.
424 if (RealizedPlatform != TargetPlatform)
427 StringRef PrettyPlatformName
428 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
430 if (PrettyPlatformName.empty())
431 PrettyPlatformName = ActualPlatform;
433 std::string HintMessage;
434 if (!A->getMessage().empty()) {
436 HintMessage += A->getMessage();
439 // Make sure that this declaration has not been marked 'unavailable'.
440 if (A->getUnavailable()) {
443 llvm::raw_string_ostream Out(*Message);
444 Out << "not available on " << PrettyPlatformName
448 return AR_Unavailable;
451 // Make sure that this declaration has already been introduced.
452 if (!A->getIntroduced().empty() &&
453 TargetMinVersion < A->getIntroduced()) {
456 llvm::raw_string_ostream Out(*Message);
457 VersionTuple VTI(A->getIntroduced());
458 VTI.UseDotAsSeparator();
459 Out << "introduced in " << PrettyPlatformName << ' '
460 << VTI << HintMessage;
463 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
466 // Make sure that this declaration hasn't been obsoleted.
467 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
470 llvm::raw_string_ostream Out(*Message);
471 VersionTuple VTO(A->getObsoleted());
472 VTO.UseDotAsSeparator();
473 Out << "obsoleted in " << PrettyPlatformName << ' '
474 << VTO << HintMessage;
477 return AR_Unavailable;
480 // Make sure that this declaration hasn't been deprecated.
481 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
484 llvm::raw_string_ostream Out(*Message);
485 VersionTuple VTD(A->getDeprecated());
486 VTD.UseDotAsSeparator();
487 Out << "first deprecated in " << PrettyPlatformName << ' '
488 << VTD << HintMessage;
491 return AR_Deprecated;
497 AvailabilityResult Decl::getAvailability(std::string *Message) const {
498 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
499 return FTD->getTemplatedDecl()->getAvailability(Message);
501 AvailabilityResult Result = AR_Available;
502 std::string ResultMessage;
504 for (const auto *A : attrs()) {
505 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
506 if (Result >= AR_Deprecated)
510 ResultMessage = Deprecated->getMessage();
512 Result = AR_Deprecated;
516 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
518 *Message = Unavailable->getMessage();
519 return AR_Unavailable;
522 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
523 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
526 if (AR == AR_Unavailable)
527 return AR_Unavailable;
532 ResultMessage.swap(*Message);
539 Message->swap(ResultMessage);
543 bool Decl::canBeWeakImported(bool &IsDefinition) const {
544 IsDefinition = false;
546 // Variables, if they aren't definitions.
547 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
548 if (Var->isThisDeclarationADefinition()) {
554 // Functions, if they aren't definitions.
555 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
562 // Objective-C classes, if this is the non-fragile runtime.
563 } else if (isa<ObjCInterfaceDecl>(this) &&
564 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
573 bool Decl::isWeakImported() const {
575 if (!canBeWeakImported(IsDefinition))
578 for (const auto *A : attrs()) {
579 if (isa<WeakImportAttr>(A))
582 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
583 if (CheckAvailability(getASTContext(), Availability,
584 nullptr) == AR_NotYetIntroduced)
592 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
597 case ConstructorUsingShadow:
607 return IDNS_Ordinary;
611 return IDNS_Ordinary | IDNS_Member;
613 case NonTypeTemplateParm:
614 // Non-type template parameters are not found by lookups that ignore
615 // non-types, but they are found by redeclaration lookups for tag types,
616 // so we include them in the tag namespace.
617 return IDNS_Ordinary | IDNS_Tag;
619 case ObjCCompatibleAlias:
621 return IDNS_Ordinary | IDNS_Type;
625 case TypeAliasTemplate:
626 case UnresolvedUsingTypename:
627 case TemplateTypeParm:
629 return IDNS_Ordinary | IDNS_Type;
632 return 0; // we'll actually overwrite this later
634 case UnresolvedUsingValue:
635 return IDNS_Ordinary | IDNS_Using;
641 return IDNS_ObjCProtocol;
644 case ObjCAtDefsField:
651 return IDNS_Tag | IDNS_Type;
655 return IDNS_Namespace;
657 case FunctionTemplate:
659 return IDNS_Ordinary;
662 case TemplateTemplateParm:
663 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
665 case OMPDeclareReduction:
666 return IDNS_OMPReduction;
675 case ObjCPropertyImpl:
677 case PragmaDetectMismatch:
680 case TranslationUnit:
684 case BuiltinTemplate:
685 case ClassTemplateSpecialization:
686 case ClassTemplatePartialSpecialization:
687 case ClassScopeFunctionSpecialization:
688 case VarTemplateSpecialization:
689 case VarTemplatePartialSpecialization:
690 case ObjCImplementation:
692 case ObjCCategoryImpl:
694 case OMPThreadPrivate:
695 case OMPCapturedExpr:
697 // Never looked up by name.
701 llvm_unreachable("Invalid DeclKind!");
704 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
705 assert(!HasAttrs && "Decl already contains attrs.");
707 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
708 assert(AttrBlank.empty() && "HasAttrs was wrong?");
714 void Decl::dropAttrs() {
715 if (!HasAttrs) return;
718 getASTContext().eraseDeclAttrs(this);
721 const AttrVec &Decl::getAttrs() const {
722 assert(HasAttrs && "No attrs to get!");
723 return getASTContext().getDeclAttrs(this);
726 Decl *Decl::castFromDeclContext (const DeclContext *D) {
727 Decl::Kind DK = D->getDeclKind();
729 #define DECL(NAME, BASE)
730 #define DECL_CONTEXT(NAME) \
732 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
733 #define DECL_CONTEXT_BASE(NAME)
734 #include "clang/AST/DeclNodes.inc"
736 #define DECL(NAME, BASE)
737 #define DECL_CONTEXT_BASE(NAME) \
738 if (DK >= first##NAME && DK <= last##NAME) \
739 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
740 #include "clang/AST/DeclNodes.inc"
741 llvm_unreachable("a decl that inherits DeclContext isn't handled");
745 DeclContext *Decl::castToDeclContext(const Decl *D) {
746 Decl::Kind DK = D->getKind();
748 #define DECL(NAME, BASE)
749 #define DECL_CONTEXT(NAME) \
751 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
752 #define DECL_CONTEXT_BASE(NAME)
753 #include "clang/AST/DeclNodes.inc"
755 #define DECL(NAME, BASE)
756 #define DECL_CONTEXT_BASE(NAME) \
757 if (DK >= first##NAME && DK <= last##NAME) \
758 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
759 #include "clang/AST/DeclNodes.inc"
760 llvm_unreachable("a decl that inherits DeclContext isn't handled");
764 SourceLocation Decl::getBodyRBrace() const {
765 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
766 // FunctionDecl stores EndRangeLoc for this purpose.
767 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
768 const FunctionDecl *Definition;
769 if (FD->hasBody(Definition))
770 return Definition->getSourceRange().getEnd();
771 return SourceLocation();
774 if (Stmt *Body = getBody())
775 return Body->getSourceRange().getEnd();
777 return SourceLocation();
780 bool Decl::AccessDeclContextSanity() const {
782 // Suppress this check if any of the following hold:
783 // 1. this is the translation unit (and thus has no parent)
784 // 2. this is a template parameter (and thus doesn't belong to its context)
785 // 3. this is a non-type template parameter
786 // 4. the context is not a record
788 // 6. it's a C++0x static_assert.
789 if (isa<TranslationUnitDecl>(this) ||
790 isa<TemplateTypeParmDecl>(this) ||
791 isa<NonTypeTemplateParmDecl>(this) ||
792 !isa<CXXRecordDecl>(getDeclContext()) ||
794 isa<StaticAssertDecl>(this) ||
795 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
796 // as DeclContext (?).
797 isa<ParmVarDecl>(this) ||
798 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
799 // AS_none as access specifier.
800 isa<CXXRecordDecl>(this) ||
801 isa<ClassScopeFunctionSpecializationDecl>(this))
804 assert(Access != AS_none &&
805 "Access specifier is AS_none inside a record decl");
810 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
811 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
813 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
815 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
817 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
818 Ty = D->getUnderlyingType();
822 if (Ty->isFunctionPointerType())
823 Ty = Ty->getAs<PointerType>()->getPointeeType();
824 else if (BlocksToo && Ty->isBlockPointerType())
825 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
827 return Ty->getAs<FunctionType>();
831 /// Starting at a given context (a Decl or DeclContext), look for a
832 /// code context that is not a closure (a lambda, block, etc.).
833 template <class T> static Decl *getNonClosureContext(T *D) {
834 if (getKind(D) == Decl::CXXMethod) {
835 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
836 if (MD->getOverloadedOperator() == OO_Call &&
837 MD->getParent()->isLambda())
838 return getNonClosureContext(MD->getParent()->getParent());
840 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
842 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
844 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
845 return getNonClosureContext(BD->getParent());
846 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
847 return getNonClosureContext(CD->getParent());
853 Decl *Decl::getNonClosureContext() {
854 return ::getNonClosureContext(this);
857 Decl *DeclContext::getNonClosureAncestor() {
858 return ::getNonClosureContext(this);
861 //===----------------------------------------------------------------------===//
862 // DeclContext Implementation
863 //===----------------------------------------------------------------------===//
865 bool DeclContext::classof(const Decl *D) {
866 switch (D->getKind()) {
867 #define DECL(NAME, BASE)
868 #define DECL_CONTEXT(NAME) case Decl::NAME:
869 #define DECL_CONTEXT_BASE(NAME)
870 #include "clang/AST/DeclNodes.inc"
873 #define DECL(NAME, BASE)
874 #define DECL_CONTEXT_BASE(NAME) \
875 if (D->getKind() >= Decl::first##NAME && \
876 D->getKind() <= Decl::last##NAME) \
878 #include "clang/AST/DeclNodes.inc"
883 DeclContext::~DeclContext() { }
885 /// \brief Find the parent context of this context that will be
886 /// used for unqualified name lookup.
888 /// Generally, the parent lookup context is the semantic context. However, for
889 /// a friend function the parent lookup context is the lexical context, which
890 /// is the class in which the friend is declared.
891 DeclContext *DeclContext::getLookupParent() {
892 // FIXME: Find a better way to identify friends
893 if (isa<FunctionDecl>(this))
894 if (getParent()->getRedeclContext()->isFileContext() &&
895 getLexicalParent()->getRedeclContext()->isRecord())
896 return getLexicalParent();
901 bool DeclContext::isInlineNamespace() const {
902 return isNamespace() &&
903 cast<NamespaceDecl>(this)->isInline();
906 bool DeclContext::isStdNamespace() const {
910 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
911 if (ND->isInline()) {
912 return ND->getParent()->isStdNamespace();
915 if (!getParent()->getRedeclContext()->isTranslationUnit())
918 const IdentifierInfo *II = ND->getIdentifier();
919 return II && II->isStr("std");
922 bool DeclContext::isDependentContext() const {
926 if (isa<ClassTemplatePartialSpecializationDecl>(this))
929 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
930 if (Record->getDescribedClassTemplate())
933 if (Record->isDependentLambda())
937 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
938 if (Function->getDescribedFunctionTemplate())
941 // Friend function declarations are dependent if their *lexical*
942 // context is dependent.
943 if (cast<Decl>(this)->getFriendObjectKind())
944 return getLexicalParent()->isDependentContext();
947 // FIXME: A variable template is a dependent context, but is not a
948 // DeclContext. A context within it (such as a lambda-expression)
949 // should be considered dependent.
951 return getParent() && getParent()->isDependentContext();
954 bool DeclContext::isTransparentContext() const {
955 if (DeclKind == Decl::Enum)
956 return !cast<EnumDecl>(this)->isScoped();
957 else if (DeclKind == Decl::LinkageSpec)
963 static bool isLinkageSpecContext(const DeclContext *DC,
964 LinkageSpecDecl::LanguageIDs ID) {
965 while (DC->getDeclKind() != Decl::TranslationUnit) {
966 if (DC->getDeclKind() == Decl::LinkageSpec)
967 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
968 DC = DC->getLexicalParent();
973 bool DeclContext::isExternCContext() const {
974 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
977 bool DeclContext::isExternCXXContext() const {
978 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
981 bool DeclContext::Encloses(const DeclContext *DC) const {
982 if (getPrimaryContext() != this)
983 return getPrimaryContext()->Encloses(DC);
985 for (; DC; DC = DC->getParent())
986 if (DC->getPrimaryContext() == this)
991 DeclContext *DeclContext::getPrimaryContext() {
993 case Decl::TranslationUnit:
994 case Decl::ExternCContext:
995 case Decl::LinkageSpec:
998 case Decl::OMPDeclareReduction:
999 // There is only one DeclContext for these entities.
1002 case Decl::Namespace:
1003 // The original namespace is our primary context.
1004 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1006 case Decl::ObjCMethod:
1009 case Decl::ObjCInterface:
1010 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1015 case Decl::ObjCProtocol:
1016 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1021 case Decl::ObjCCategory:
1024 case Decl::ObjCImplementation:
1025 case Decl::ObjCCategoryImpl:
1029 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1030 // If this is a tag type that has a definition or is currently
1031 // being defined, that definition is our primary context.
1032 TagDecl *Tag = cast<TagDecl>(this);
1034 if (TagDecl *Def = Tag->getDefinition())
1037 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1038 // Note, TagType::getDecl returns the (partial) definition one exists.
1039 TagDecl *PossiblePartialDef = TagTy->getDecl();
1040 if (PossiblePartialDef->isBeingDefined())
1041 return PossiblePartialDef;
1043 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1049 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1050 "Unknown DeclContext kind");
1056 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1059 if (DeclKind != Decl::Namespace) {
1060 Contexts.push_back(this);
1064 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1065 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1066 N = N->getPreviousDecl())
1067 Contexts.push_back(N);
1069 std::reverse(Contexts.begin(), Contexts.end());
1072 std::pair<Decl *, Decl *>
1073 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1074 bool FieldsAlreadyLoaded) {
1075 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1076 Decl *FirstNewDecl = nullptr;
1077 Decl *PrevDecl = nullptr;
1078 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1079 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1084 PrevDecl->NextInContextAndBits.setPointer(D);
1091 return std::make_pair(FirstNewDecl, PrevDecl);
1094 /// \brief We have just acquired external visible storage, and we already have
1095 /// built a lookup map. For every name in the map, pull in the new names from
1096 /// the external storage.
1097 void DeclContext::reconcileExternalVisibleStorage() const {
1098 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1099 NeedToReconcileExternalVisibleStorage = false;
1101 for (auto &Lookup : *LookupPtr)
1102 Lookup.second.setHasExternalDecls();
1105 /// \brief Load the declarations within this lexical storage from an
1106 /// external source.
1107 /// \return \c true if any declarations were added.
1109 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1110 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1111 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1113 // Notify that we have a DeclContext that is initializing.
1114 ExternalASTSource::Deserializing ADeclContext(Source);
1116 // Load the external declarations, if any.
1117 SmallVector<Decl*, 64> Decls;
1118 ExternalLexicalStorage = false;
1119 Source->FindExternalLexicalDecls(this, Decls);
1124 // We may have already loaded just the fields of this record, in which case
1125 // we need to ignore them.
1126 bool FieldsAlreadyLoaded = false;
1127 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1128 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1130 // Splice the newly-read declarations into the beginning of the list
1132 Decl *ExternalFirst, *ExternalLast;
1133 std::tie(ExternalFirst, ExternalLast) =
1134 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1135 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1136 FirstDecl = ExternalFirst;
1138 LastDecl = ExternalLast;
1142 DeclContext::lookup_result
1143 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1144 DeclarationName Name) {
1145 ASTContext &Context = DC->getParentASTContext();
1146 StoredDeclsMap *Map;
1147 if (!(Map = DC->LookupPtr))
1148 Map = DC->CreateStoredDeclsMap(Context);
1149 if (DC->NeedToReconcileExternalVisibleStorage)
1150 DC->reconcileExternalVisibleStorage();
1152 (*Map)[Name].removeExternalDecls();
1154 return DeclContext::lookup_result();
1157 DeclContext::lookup_result
1158 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1159 DeclarationName Name,
1160 ArrayRef<NamedDecl*> Decls) {
1161 ASTContext &Context = DC->getParentASTContext();
1162 StoredDeclsMap *Map;
1163 if (!(Map = DC->LookupPtr))
1164 Map = DC->CreateStoredDeclsMap(Context);
1165 if (DC->NeedToReconcileExternalVisibleStorage)
1166 DC->reconcileExternalVisibleStorage();
1168 StoredDeclsList &List = (*Map)[Name];
1170 // Clear out any old external visible declarations, to avoid quadratic
1171 // performance in the redeclaration checks below.
1172 List.removeExternalDecls();
1174 if (!List.isNull()) {
1175 // We have both existing declarations and new declarations for this name.
1176 // Some of the declarations may simply replace existing ones. Handle those
1178 llvm::SmallVector<unsigned, 8> Skip;
1179 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1180 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1182 Skip.push_back(Decls.size());
1184 // Add in any new declarations.
1185 unsigned SkipPos = 0;
1186 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1187 if (I == Skip[SkipPos])
1190 List.AddSubsequentDecl(Decls[I]);
1193 // Convert the array to a StoredDeclsList.
1194 for (ArrayRef<NamedDecl*>::iterator
1195 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1197 List.setOnlyValue(*I);
1199 List.AddSubsequentDecl(*I);
1203 return List.getLookupResult();
1206 DeclContext::decl_iterator DeclContext::decls_begin() const {
1207 if (hasExternalLexicalStorage())
1208 LoadLexicalDeclsFromExternalStorage();
1209 return decl_iterator(FirstDecl);
1212 bool DeclContext::decls_empty() const {
1213 if (hasExternalLexicalStorage())
1214 LoadLexicalDeclsFromExternalStorage();
1219 bool DeclContext::containsDecl(Decl *D) const {
1220 return (D->getLexicalDeclContext() == this &&
1221 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1224 void DeclContext::removeDecl(Decl *D) {
1225 assert(D->getLexicalDeclContext() == this &&
1226 "decl being removed from non-lexical context");
1227 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1228 "decl is not in decls list");
1230 // Remove D from the decl chain. This is O(n) but hopefully rare.
1231 if (D == FirstDecl) {
1233 FirstDecl = LastDecl = nullptr;
1235 FirstDecl = D->NextInContextAndBits.getPointer();
1237 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1238 assert(I && "decl not found in linked list");
1239 if (I->NextInContextAndBits.getPointer() == D) {
1240 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1241 if (D == LastDecl) LastDecl = I;
1247 // Mark that D is no longer in the decl chain.
1248 D->NextInContextAndBits.setPointer(nullptr);
1250 // Remove D from the lookup table if necessary.
1251 if (isa<NamedDecl>(D)) {
1252 NamedDecl *ND = cast<NamedDecl>(D);
1254 // Remove only decls that have a name
1255 if (!ND->getDeclName()) return;
1259 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1261 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1262 assert(Pos != Map->end() && "no lookup entry for decl");
1263 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1264 Pos->second.remove(ND);
1266 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1270 void DeclContext::addHiddenDecl(Decl *D) {
1271 assert(D->getLexicalDeclContext() == this &&
1272 "Decl inserted into wrong lexical context");
1273 assert(!D->getNextDeclInContext() && D != LastDecl &&
1274 "Decl already inserted into a DeclContext");
1277 LastDecl->NextInContextAndBits.setPointer(D);
1280 FirstDecl = LastDecl = D;
1283 // Notify a C++ record declaration that we've added a member, so it can
1284 // update its class-specific state.
1285 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1286 Record->addedMember(D);
1288 // If this is a newly-created (not de-serialized) import declaration, wire
1289 // it in to the list of local import declarations.
1290 if (!D->isFromASTFile()) {
1291 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1292 D->getASTContext().addedLocalImportDecl(Import);
1296 void DeclContext::addDecl(Decl *D) {
1299 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1300 ND->getDeclContext()->getPrimaryContext()->
1301 makeDeclVisibleInContextWithFlags(ND, false, true);
1304 void DeclContext::addDeclInternal(Decl *D) {
1307 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1308 ND->getDeclContext()->getPrimaryContext()->
1309 makeDeclVisibleInContextWithFlags(ND, true, true);
1312 /// shouldBeHidden - Determine whether a declaration which was declared
1313 /// within its semantic context should be invisible to qualified name lookup.
1314 static bool shouldBeHidden(NamedDecl *D) {
1315 // Skip unnamed declarations.
1316 if (!D->getDeclName())
1319 // Skip entities that can't be found by name lookup into a particular
1321 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1322 D->isTemplateParameter())
1325 // Skip template specializations.
1326 // FIXME: This feels like a hack. Should DeclarationName support
1327 // template-ids, or is there a better way to keep specializations
1328 // from being visible?
1329 if (isa<ClassTemplateSpecializationDecl>(D))
1331 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1332 if (FD->isFunctionTemplateSpecialization())
1338 /// buildLookup - Build the lookup data structure with all of the
1339 /// declarations in this DeclContext (and any other contexts linked
1340 /// to it or transparent contexts nested within it) and return it.
1342 /// Note that the produced map may miss out declarations from an
1343 /// external source. If it does, those entries will be marked with
1344 /// the 'hasExternalDecls' flag.
1345 StoredDeclsMap *DeclContext::buildLookup() {
1346 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1348 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1351 SmallVector<DeclContext *, 2> Contexts;
1352 collectAllContexts(Contexts);
1354 if (HasLazyExternalLexicalLookups) {
1355 HasLazyExternalLexicalLookups = false;
1356 for (auto *DC : Contexts) {
1357 if (DC->hasExternalLexicalStorage())
1358 HasLazyLocalLexicalLookups |=
1359 DC->LoadLexicalDeclsFromExternalStorage();
1362 if (!HasLazyLocalLexicalLookups)
1366 for (auto *DC : Contexts)
1367 buildLookupImpl(DC, hasExternalVisibleStorage());
1369 // We no longer have any lazy decls.
1370 HasLazyLocalLexicalLookups = false;
1374 /// buildLookupImpl - Build part of the lookup data structure for the
1375 /// declarations contained within DCtx, which will either be this
1376 /// DeclContext, a DeclContext linked to it, or a transparent context
1377 /// nested within it.
1378 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1379 for (Decl *D : DCtx->noload_decls()) {
1380 // Insert this declaration into the lookup structure, but only if
1381 // it's semantically within its decl context. Any other decls which
1382 // should be found in this context are added eagerly.
1384 // If it's from an AST file, don't add it now. It'll get handled by
1385 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1386 // in C++, we do not track external visible decls for the TU, so in
1387 // that case we need to collect them all here.
1388 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1389 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1390 (!ND->isFromASTFile() ||
1391 (isTranslationUnit() &&
1392 !getParentASTContext().getLangOpts().CPlusPlus)))
1393 makeDeclVisibleInContextImpl(ND, Internal);
1395 // If this declaration is itself a transparent declaration context
1396 // or inline namespace, add the members of this declaration of that
1397 // context (recursively).
1398 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1399 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1400 buildLookupImpl(InnerCtx, Internal);
1404 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1406 DeclContext::lookup_result
1407 DeclContext::lookup(DeclarationName Name) const {
1408 assert(DeclKind != Decl::LinkageSpec &&
1409 "Should not perform lookups into linkage specs!");
1411 const DeclContext *PrimaryContext = getPrimaryContext();
1412 if (PrimaryContext != this)
1413 return PrimaryContext->lookup(Name);
1415 // If we have an external source, ensure that any later redeclarations of this
1416 // context have been loaded, since they may add names to the result of this
1417 // lookup (or add external visible storage).
1418 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1420 (void)cast<Decl>(this)->getMostRecentDecl();
1422 if (hasExternalVisibleStorage()) {
1423 assert(Source && "external visible storage but no external source?");
1425 if (NeedToReconcileExternalVisibleStorage)
1426 reconcileExternalVisibleStorage();
1428 StoredDeclsMap *Map = LookupPtr;
1430 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1431 // FIXME: Make buildLookup const?
1432 Map = const_cast<DeclContext*>(this)->buildLookup();
1435 Map = CreateStoredDeclsMap(getParentASTContext());
1437 // If we have a lookup result with no external decls, we are done.
1438 std::pair<StoredDeclsMap::iterator, bool> R =
1439 Map->insert(std::make_pair(Name, StoredDeclsList()));
1440 if (!R.second && !R.first->second.hasExternalDecls())
1441 return R.first->second.getLookupResult();
1443 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1444 if (StoredDeclsMap *Map = LookupPtr) {
1445 StoredDeclsMap::iterator I = Map->find(Name);
1446 if (I != Map->end())
1447 return I->second.getLookupResult();
1451 return lookup_result();
1454 StoredDeclsMap *Map = LookupPtr;
1455 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1456 Map = const_cast<DeclContext*>(this)->buildLookup();
1459 return lookup_result();
1461 StoredDeclsMap::iterator I = Map->find(Name);
1462 if (I == Map->end())
1463 return lookup_result();
1465 return I->second.getLookupResult();
1468 DeclContext::lookup_result
1469 DeclContext::noload_lookup(DeclarationName Name) {
1470 assert(DeclKind != Decl::LinkageSpec &&
1471 "Should not perform lookups into linkage specs!");
1473 DeclContext *PrimaryContext = getPrimaryContext();
1474 if (PrimaryContext != this)
1475 return PrimaryContext->noload_lookup(Name);
1477 // If we have any lazy lexical declarations not in our lookup map, add them
1478 // now. Don't import any external declarations, not even if we know we have
1479 // some missing from the external visible lookups.
1480 if (HasLazyLocalLexicalLookups) {
1481 SmallVector<DeclContext *, 2> Contexts;
1482 collectAllContexts(Contexts);
1483 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1484 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1485 HasLazyLocalLexicalLookups = false;
1488 StoredDeclsMap *Map = LookupPtr;
1490 return lookup_result();
1492 StoredDeclsMap::iterator I = Map->find(Name);
1493 return I != Map->end() ? I->second.getLookupResult()
1497 void DeclContext::localUncachedLookup(DeclarationName Name,
1498 SmallVectorImpl<NamedDecl *> &Results) {
1501 // If there's no external storage, just perform a normal lookup and copy
1503 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1504 lookup_result LookupResults = lookup(Name);
1505 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1509 // If we have a lookup table, check there first. Maybe we'll get lucky.
1510 // FIXME: Should we be checking these flags on the primary context?
1511 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1512 if (StoredDeclsMap *Map = LookupPtr) {
1513 StoredDeclsMap::iterator Pos = Map->find(Name);
1514 if (Pos != Map->end()) {
1515 Results.insert(Results.end(),
1516 Pos->second.getLookupResult().begin(),
1517 Pos->second.getLookupResult().end());
1523 // Slow case: grovel through the declarations in our chain looking for
1525 // FIXME: If we have lazy external declarations, this will not find them!
1526 // FIXME: Should we CollectAllContexts and walk them all here?
1527 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1528 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1529 if (ND->getDeclName() == Name)
1530 Results.push_back(ND);
1534 DeclContext *DeclContext::getRedeclContext() {
1535 DeclContext *Ctx = this;
1536 // Skip through transparent contexts.
1537 while (Ctx->isTransparentContext())
1538 Ctx = Ctx->getParent();
1542 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1543 DeclContext *Ctx = this;
1544 // Skip through non-namespace, non-translation-unit contexts.
1545 while (!Ctx->isFileContext())
1546 Ctx = Ctx->getParent();
1547 return Ctx->getPrimaryContext();
1550 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1551 // Loop until we find a non-record context.
1552 RecordDecl *OutermostRD = nullptr;
1553 DeclContext *DC = this;
1554 while (DC->isRecord()) {
1555 OutermostRD = cast<RecordDecl>(DC);
1556 DC = DC->getLexicalParent();
1561 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1562 // For non-file contexts, this is equivalent to Equals.
1563 if (!isFileContext())
1564 return O->Equals(this);
1567 if (O->Equals(this))
1570 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1571 if (!NS || !NS->isInline())
1573 O = NS->getParent();
1579 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1580 DeclContext *PrimaryDC = this->getPrimaryContext();
1581 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1582 // If the decl is being added outside of its semantic decl context, we
1583 // need to ensure that we eagerly build the lookup information for it.
1584 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1587 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1589 assert(this == getPrimaryContext() && "expected a primary DC");
1591 if (!isLookupContext()) {
1592 if (isTransparentContext())
1593 getParent()->getPrimaryContext()
1594 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1598 // Skip declarations which should be invisible to name lookup.
1599 if (shouldBeHidden(D))
1602 // If we already have a lookup data structure, perform the insertion into
1603 // it. If we might have externally-stored decls with this name, look them
1604 // up and perform the insertion. If this decl was declared outside its
1605 // semantic context, buildLookup won't add it, so add it now.
1607 // FIXME: As a performance hack, don't add such decls into the translation
1608 // unit unless we're in C++, since qualified lookup into the TU is never
1610 if (LookupPtr || hasExternalVisibleStorage() ||
1611 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1612 (getParentASTContext().getLangOpts().CPlusPlus ||
1613 !isTranslationUnit()))) {
1614 // If we have lazily omitted any decls, they might have the same name as
1615 // the decl which we are adding, so build a full lookup table before adding
1618 makeDeclVisibleInContextImpl(D, Internal);
1620 HasLazyLocalLexicalLookups = true;
1623 // If we are a transparent context or inline namespace, insert into our
1624 // parent context, too. This operation is recursive.
1625 if (isTransparentContext() || isInlineNamespace())
1626 getParent()->getPrimaryContext()->
1627 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1629 Decl *DCAsDecl = cast<Decl>(this);
1630 // Notify that a decl was made visible unless we are a Tag being defined.
1631 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1632 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1633 L->AddedVisibleDecl(this, D);
1636 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1637 // Find or create the stored declaration map.
1638 StoredDeclsMap *Map = LookupPtr;
1640 ASTContext *C = &getParentASTContext();
1641 Map = CreateStoredDeclsMap(*C);
1644 // If there is an external AST source, load any declarations it knows about
1645 // with this declaration's name.
1646 // If the lookup table contains an entry about this name it means that we
1647 // have already checked the external source.
1649 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1650 if (hasExternalVisibleStorage() &&
1651 Map->find(D->getDeclName()) == Map->end())
1652 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1654 // Insert this declaration into the map.
1655 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1658 // If this is being added as part of loading an external declaration,
1659 // this may not be the only external declaration with this name.
1660 // In this case, we never try to replace an existing declaration; we'll
1661 // handle that when we finalize the list of declarations for this name.
1662 DeclNameEntries.setHasExternalDecls();
1663 DeclNameEntries.AddSubsequentDecl(D);
1667 if (DeclNameEntries.isNull()) {
1668 DeclNameEntries.setOnlyValue(D);
1672 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1673 // This declaration has replaced an existing one for which
1674 // declarationReplaces returns true.
1678 // Put this declaration into the appropriate slot.
1679 DeclNameEntries.AddSubsequentDecl(D);
1682 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1683 return cast<UsingDirectiveDecl>(*I);
1686 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1688 DeclContext::udir_range DeclContext::using_directives() const {
1689 // FIXME: Use something more efficient than normal lookup for using
1690 // directives. In C++, using directives are looked up more than anything else.
1691 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1692 return udir_range(Result.begin(), Result.end());
1695 //===----------------------------------------------------------------------===//
1696 // Creation and Destruction of StoredDeclsMaps. //
1697 //===----------------------------------------------------------------------===//
1699 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1700 assert(!LookupPtr && "context already has a decls map");
1701 assert(getPrimaryContext() == this &&
1702 "creating decls map on non-primary context");
1705 bool Dependent = isDependentContext();
1707 M = new DependentStoredDeclsMap();
1709 M = new StoredDeclsMap();
1710 M->Previous = C.LastSDM;
1711 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1716 void ASTContext::ReleaseDeclContextMaps() {
1717 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1718 // pointer because the subclass doesn't add anything that needs to
1720 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1723 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1725 // Advance the iteration before we invalidate memory.
1726 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1729 delete static_cast<DependentStoredDeclsMap*>(Map);
1733 Map = Next.getPointer();
1734 Dependent = Next.getInt();
1738 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1739 DeclContext *Parent,
1740 const PartialDiagnostic &PDiag) {
1741 assert(Parent->isDependentContext()
1742 && "cannot iterate dependent diagnostics of non-dependent context");
1743 Parent = Parent->getPrimaryContext();
1744 if (!Parent->LookupPtr)
1745 Parent->CreateStoredDeclsMap(C);
1747 DependentStoredDeclsMap *Map =
1748 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1750 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1751 // BumpPtrAllocator, rather than the ASTContext itself.
1752 PartialDiagnostic::Storage *DiagStorage = nullptr;
1753 if (PDiag.hasStorage())
1754 DiagStorage = new (C) PartialDiagnostic::Storage;
1756 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1758 // TODO: Maybe we shouldn't reverse the order during insertion.
1759 DD->NextDiagnostic = Map->FirstDiagnostic;
1760 Map->FirstDiagnostic = DD;