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(Decl::DeclObjAlignment >= \
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 >= DeclObjAlignment,
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 *), DeclObjAlignment);
85 char *Buffer = reinterpret_cast<char *>(
86 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
88 return new (Buffer) Module*(nullptr) + 1;
90 return ::operator new(Size + Extra, Ctx);
93 Module *Decl::getOwningModuleSlow() const {
94 assert(isFromASTFile() && "Not from AST file?");
95 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
98 bool Decl::hasLocalOwningModuleStorage() const {
99 return getASTContext().getLangOpts().ModulesLocalVisibility;
102 const char *Decl::getDeclKindName() const {
104 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
105 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106 #define ABSTRACT_DECL(DECL)
107 #include "clang/AST/DeclNodes.inc"
111 void Decl::setInvalidDecl(bool Invalid) {
112 InvalidDecl = Invalid;
113 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
114 if (Invalid && !isa<ParmVarDecl>(this)) {
115 // Defensive maneuver for ill-formed code: we're likely not to make it to
116 // a point where we set the access specifier, so default it to "public"
117 // to avoid triggering asserts elsewhere in the front end.
118 setAccess(AS_public);
122 const char *DeclContext::getDeclKindName() const {
124 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
125 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
126 #define ABSTRACT_DECL(DECL)
127 #include "clang/AST/DeclNodes.inc"
131 bool Decl::StatisticsEnabled = false;
132 void Decl::EnableStatistics() {
133 StatisticsEnabled = true;
136 void Decl::PrintStats() {
137 llvm::errs() << "\n*** Decl Stats:\n";
140 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
141 #define ABSTRACT_DECL(DECL)
142 #include "clang/AST/DeclNodes.inc"
143 llvm::errs() << " " << totalDecls << " decls total.\n";
146 #define DECL(DERIVED, BASE) \
147 if (n##DERIVED##s > 0) { \
148 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
149 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
150 << sizeof(DERIVED##Decl) << " each (" \
151 << n##DERIVED##s * sizeof(DERIVED##Decl) \
154 #define ABSTRACT_DECL(DECL)
155 #include "clang/AST/DeclNodes.inc"
157 llvm::errs() << "Total bytes = " << totalBytes << "\n";
160 void Decl::add(Kind k) {
162 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
163 #define ABSTRACT_DECL(DECL)
164 #include "clang/AST/DeclNodes.inc"
168 bool Decl::isTemplateParameterPack() const {
169 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
170 return TTP->isParameterPack();
171 if (const NonTypeTemplateParmDecl *NTTP
172 = dyn_cast<NonTypeTemplateParmDecl>(this))
173 return NTTP->isParameterPack();
174 if (const TemplateTemplateParmDecl *TTP
175 = dyn_cast<TemplateTemplateParmDecl>(this))
176 return TTP->isParameterPack();
180 bool Decl::isParameterPack() const {
181 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
182 return Parm->isParameterPack();
184 return isTemplateParameterPack();
187 FunctionDecl *Decl::getAsFunction() {
188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
190 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
191 return FTD->getTemplatedDecl();
195 bool Decl::isTemplateDecl() const {
196 return isa<TemplateDecl>(this);
199 const DeclContext *Decl::getParentFunctionOrMethod() const {
200 for (const DeclContext *DC = getDeclContext();
201 DC && !DC->isTranslationUnit() && !DC->isNamespace();
202 DC = DC->getParent())
203 if (DC->isFunctionOrMethod())
210 //===----------------------------------------------------------------------===//
211 // PrettyStackTraceDecl Implementation
212 //===----------------------------------------------------------------------===//
214 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
215 SourceLocation TheLoc = Loc;
216 if (TheLoc.isInvalid() && TheDecl)
217 TheLoc = TheDecl->getLocation();
219 if (TheLoc.isValid()) {
220 TheLoc.print(OS, SM);
226 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
228 DN->printQualifiedName(OS);
234 //===----------------------------------------------------------------------===//
235 // Decl Implementation
236 //===----------------------------------------------------------------------===//
238 // Out-of-line virtual method providing a home for Decl.
241 void Decl::setDeclContext(DeclContext *DC) {
245 void Decl::setLexicalDeclContext(DeclContext *DC) {
246 if (DC == getLexicalDeclContext())
250 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
252 getMultipleDC()->LexicalDC = DC;
254 Hidden = cast<Decl>(DC)->Hidden;
257 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
259 if (SemaDC == LexicalDC) {
262 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
263 MDC->SemanticDC = SemaDC;
264 MDC->LexicalDC = LexicalDC;
269 bool Decl::isLexicallyWithinFunctionOrMethod() const {
270 const DeclContext *LDC = getLexicalDeclContext();
272 if (LDC->isFunctionOrMethod())
274 if (!isa<TagDecl>(LDC))
276 LDC = LDC->getLexicalParent();
281 bool Decl::isInAnonymousNamespace() const {
282 const DeclContext *DC = getDeclContext();
284 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
285 if (ND->isAnonymousNamespace())
287 } while ((DC = DC->getParent()));
292 bool Decl::isInStdNamespace() const {
293 return getDeclContext()->isStdNamespace();
296 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
297 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
300 DeclContext *DC = getDeclContext();
301 assert(DC && "This decl is not contained in a translation unit!");
303 while (!DC->isTranslationUnit()) {
304 DC = DC->getParent();
305 assert(DC && "This decl is not contained in a translation unit!");
308 return cast<TranslationUnitDecl>(DC);
311 ASTContext &Decl::getASTContext() const {
312 return getTranslationUnitDecl()->getASTContext();
315 ASTMutationListener *Decl::getASTMutationListener() const {
316 return getASTContext().getASTMutationListener();
319 unsigned Decl::getMaxAlignment() const {
324 const AttrVec &V = getAttrs();
325 ASTContext &Ctx = getASTContext();
326 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
328 Align = std::max(Align, I->getAlignment(Ctx));
332 bool Decl::isUsed(bool CheckUsedAttr) const {
336 // Check for used attribute.
337 if (CheckUsedAttr && hasAttr<UsedAttr>())
343 void Decl::markUsed(ASTContext &C) {
347 if (C.getASTMutationListener())
348 C.getASTMutationListener()->DeclarationMarkedUsed(this);
353 bool Decl::isReferenced() const {
357 // Check redeclarations.
358 for (auto I : redecls())
365 /// \brief Determine the availability of the given declaration based on
366 /// the target platform.
368 /// When it returns an availability result other than \c AR_Available,
369 /// if the \p Message parameter is non-NULL, it will be set to a
370 /// string describing why the entity is unavailable.
372 /// FIXME: Make these strings localizable, since they end up in
374 static AvailabilityResult CheckAvailability(ASTContext &Context,
375 const AvailabilityAttr *A,
376 std::string *Message) {
377 VersionTuple TargetMinVersion =
378 Context.getTargetInfo().getPlatformMinVersion();
380 if (TargetMinVersion.empty())
383 // Check if this is an App Extension "platform", and if so chop off
384 // the suffix for matching with the actual platform.
385 StringRef ActualPlatform = A->getPlatform()->getName();
386 StringRef RealizedPlatform = ActualPlatform;
387 if (Context.getLangOpts().AppExt) {
388 size_t suffix = RealizedPlatform.rfind("_app_extension");
389 if (suffix != StringRef::npos)
390 RealizedPlatform = RealizedPlatform.slice(0, suffix);
393 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
395 // Match the platform name.
396 if (RealizedPlatform != TargetPlatform)
399 StringRef PrettyPlatformName
400 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
402 if (PrettyPlatformName.empty())
403 PrettyPlatformName = ActualPlatform;
405 std::string HintMessage;
406 if (!A->getMessage().empty()) {
408 HintMessage += A->getMessage();
411 // Make sure that this declaration has not been marked 'unavailable'.
412 if (A->getUnavailable()) {
415 llvm::raw_string_ostream Out(*Message);
416 Out << "not available on " << PrettyPlatformName
420 return AR_Unavailable;
423 // Make sure that this declaration has already been introduced.
424 if (!A->getIntroduced().empty() &&
425 TargetMinVersion < A->getIntroduced()) {
428 llvm::raw_string_ostream Out(*Message);
429 VersionTuple VTI(A->getIntroduced());
430 VTI.UseDotAsSeparator();
431 Out << "introduced in " << PrettyPlatformName << ' '
432 << VTI << HintMessage;
435 return AR_NotYetIntroduced;
438 // Make sure that this declaration hasn't been obsoleted.
439 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
442 llvm::raw_string_ostream Out(*Message);
443 VersionTuple VTO(A->getObsoleted());
444 VTO.UseDotAsSeparator();
445 Out << "obsoleted in " << PrettyPlatformName << ' '
446 << VTO << HintMessage;
449 return AR_Unavailable;
452 // Make sure that this declaration hasn't been deprecated.
453 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
456 llvm::raw_string_ostream Out(*Message);
457 VersionTuple VTD(A->getDeprecated());
458 VTD.UseDotAsSeparator();
459 Out << "first deprecated in " << PrettyPlatformName << ' '
460 << VTD << HintMessage;
463 return AR_Deprecated;
469 AvailabilityResult Decl::getAvailability(std::string *Message) const {
470 AvailabilityResult Result = AR_Available;
471 std::string ResultMessage;
473 for (const auto *A : attrs()) {
474 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
475 if (Result >= AR_Deprecated)
479 ResultMessage = Deprecated->getMessage();
481 Result = AR_Deprecated;
485 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
487 *Message = Unavailable->getMessage();
488 return AR_Unavailable;
491 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
492 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
495 if (AR == AR_Unavailable)
496 return AR_Unavailable;
501 ResultMessage.swap(*Message);
508 Message->swap(ResultMessage);
512 bool Decl::canBeWeakImported(bool &IsDefinition) const {
513 IsDefinition = false;
515 // Variables, if they aren't definitions.
516 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
517 if (Var->isThisDeclarationADefinition()) {
523 // Functions, if they aren't definitions.
524 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
531 // Objective-C classes, if this is the non-fragile runtime.
532 } else if (isa<ObjCInterfaceDecl>(this) &&
533 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
542 bool Decl::isWeakImported() const {
544 if (!canBeWeakImported(IsDefinition))
547 for (const auto *A : attrs()) {
548 if (isa<WeakImportAttr>(A))
551 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
552 if (CheckAvailability(getASTContext(), Availability,
553 nullptr) == AR_NotYetIntroduced)
561 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
572 case NonTypeTemplateParm:
576 return IDNS_Ordinary;
580 return IDNS_Ordinary | IDNS_Member;
582 case ObjCCompatibleAlias:
584 return IDNS_Ordinary | IDNS_Type;
588 case TypeAliasTemplate:
589 case UnresolvedUsingTypename:
590 case TemplateTypeParm:
592 return IDNS_Ordinary | IDNS_Type;
595 return 0; // we'll actually overwrite this later
597 case UnresolvedUsingValue:
598 return IDNS_Ordinary | IDNS_Using;
604 return IDNS_ObjCProtocol;
607 case ObjCAtDefsField:
614 return IDNS_Tag | IDNS_Type;
618 return IDNS_Namespace;
620 case FunctionTemplate:
622 return IDNS_Ordinary;
625 case TemplateTemplateParm:
626 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
635 case ObjCPropertyImpl:
638 case TranslationUnit:
642 case BuiltinTemplate:
643 case ClassTemplateSpecialization:
644 case ClassTemplatePartialSpecialization:
645 case ClassScopeFunctionSpecialization:
646 case VarTemplateSpecialization:
647 case VarTemplatePartialSpecialization:
648 case ObjCImplementation:
650 case ObjCCategoryImpl:
652 case OMPThreadPrivate:
654 // Never looked up by name.
658 llvm_unreachable("Invalid DeclKind!");
661 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
662 assert(!HasAttrs && "Decl already contains attrs.");
664 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
665 assert(AttrBlank.empty() && "HasAttrs was wrong?");
671 void Decl::dropAttrs() {
672 if (!HasAttrs) return;
675 getASTContext().eraseDeclAttrs(this);
678 const AttrVec &Decl::getAttrs() const {
679 assert(HasAttrs && "No attrs to get!");
680 return getASTContext().getDeclAttrs(this);
683 Decl *Decl::castFromDeclContext (const DeclContext *D) {
684 Decl::Kind DK = D->getDeclKind();
686 #define DECL(NAME, BASE)
687 #define DECL_CONTEXT(NAME) \
689 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
690 #define DECL_CONTEXT_BASE(NAME)
691 #include "clang/AST/DeclNodes.inc"
693 #define DECL(NAME, BASE)
694 #define DECL_CONTEXT_BASE(NAME) \
695 if (DK >= first##NAME && DK <= last##NAME) \
696 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
697 #include "clang/AST/DeclNodes.inc"
698 llvm_unreachable("a decl that inherits DeclContext isn't handled");
702 DeclContext *Decl::castToDeclContext(const Decl *D) {
703 Decl::Kind DK = D->getKind();
705 #define DECL(NAME, BASE)
706 #define DECL_CONTEXT(NAME) \
708 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
709 #define DECL_CONTEXT_BASE(NAME)
710 #include "clang/AST/DeclNodes.inc"
712 #define DECL(NAME, BASE)
713 #define DECL_CONTEXT_BASE(NAME) \
714 if (DK >= first##NAME && DK <= last##NAME) \
715 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
716 #include "clang/AST/DeclNodes.inc"
717 llvm_unreachable("a decl that inherits DeclContext isn't handled");
721 SourceLocation Decl::getBodyRBrace() const {
722 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
723 // FunctionDecl stores EndRangeLoc for this purpose.
724 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
725 const FunctionDecl *Definition;
726 if (FD->hasBody(Definition))
727 return Definition->getSourceRange().getEnd();
728 return SourceLocation();
731 if (Stmt *Body = getBody())
732 return Body->getSourceRange().getEnd();
734 return SourceLocation();
737 bool Decl::AccessDeclContextSanity() const {
739 // Suppress this check if any of the following hold:
740 // 1. this is the translation unit (and thus has no parent)
741 // 2. this is a template parameter (and thus doesn't belong to its context)
742 // 3. this is a non-type template parameter
743 // 4. the context is not a record
745 // 6. it's a C++0x static_assert.
746 if (isa<TranslationUnitDecl>(this) ||
747 isa<TemplateTypeParmDecl>(this) ||
748 isa<NonTypeTemplateParmDecl>(this) ||
749 !isa<CXXRecordDecl>(getDeclContext()) ||
751 isa<StaticAssertDecl>(this) ||
752 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
753 // as DeclContext (?).
754 isa<ParmVarDecl>(this) ||
755 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
756 // AS_none as access specifier.
757 isa<CXXRecordDecl>(this) ||
758 isa<ClassScopeFunctionSpecializationDecl>(this))
761 assert(Access != AS_none &&
762 "Access specifier is AS_none inside a record decl");
767 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
768 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
770 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
772 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
774 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
775 Ty = D->getUnderlyingType();
779 if (Ty->isFunctionPointerType())
780 Ty = Ty->getAs<PointerType>()->getPointeeType();
781 else if (BlocksToo && Ty->isBlockPointerType())
782 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
784 return Ty->getAs<FunctionType>();
788 /// Starting at a given context (a Decl or DeclContext), look for a
789 /// code context that is not a closure (a lambda, block, etc.).
790 template <class T> static Decl *getNonClosureContext(T *D) {
791 if (getKind(D) == Decl::CXXMethod) {
792 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
793 if (MD->getOverloadedOperator() == OO_Call &&
794 MD->getParent()->isLambda())
795 return getNonClosureContext(MD->getParent()->getParent());
797 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
799 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
801 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
802 return getNonClosureContext(BD->getParent());
803 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
804 return getNonClosureContext(CD->getParent());
810 Decl *Decl::getNonClosureContext() {
811 return ::getNonClosureContext(this);
814 Decl *DeclContext::getNonClosureAncestor() {
815 return ::getNonClosureContext(this);
818 //===----------------------------------------------------------------------===//
819 // DeclContext Implementation
820 //===----------------------------------------------------------------------===//
822 bool DeclContext::classof(const Decl *D) {
823 switch (D->getKind()) {
824 #define DECL(NAME, BASE)
825 #define DECL_CONTEXT(NAME) case Decl::NAME:
826 #define DECL_CONTEXT_BASE(NAME)
827 #include "clang/AST/DeclNodes.inc"
830 #define DECL(NAME, BASE)
831 #define DECL_CONTEXT_BASE(NAME) \
832 if (D->getKind() >= Decl::first##NAME && \
833 D->getKind() <= Decl::last##NAME) \
835 #include "clang/AST/DeclNodes.inc"
840 DeclContext::~DeclContext() { }
842 /// \brief Find the parent context of this context that will be
843 /// used for unqualified name lookup.
845 /// Generally, the parent lookup context is the semantic context. However, for
846 /// a friend function the parent lookup context is the lexical context, which
847 /// is the class in which the friend is declared.
848 DeclContext *DeclContext::getLookupParent() {
849 // FIXME: Find a better way to identify friends
850 if (isa<FunctionDecl>(this))
851 if (getParent()->getRedeclContext()->isFileContext() &&
852 getLexicalParent()->getRedeclContext()->isRecord())
853 return getLexicalParent();
858 bool DeclContext::isInlineNamespace() const {
859 return isNamespace() &&
860 cast<NamespaceDecl>(this)->isInline();
863 bool DeclContext::isStdNamespace() const {
867 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
868 if (ND->isInline()) {
869 return ND->getParent()->isStdNamespace();
872 if (!getParent()->getRedeclContext()->isTranslationUnit())
875 const IdentifierInfo *II = ND->getIdentifier();
876 return II && II->isStr("std");
879 bool DeclContext::isDependentContext() const {
883 if (isa<ClassTemplatePartialSpecializationDecl>(this))
886 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
887 if (Record->getDescribedClassTemplate())
890 if (Record->isDependentLambda())
894 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
895 if (Function->getDescribedFunctionTemplate())
898 // Friend function declarations are dependent if their *lexical*
899 // context is dependent.
900 if (cast<Decl>(this)->getFriendObjectKind())
901 return getLexicalParent()->isDependentContext();
904 // FIXME: A variable template is a dependent context, but is not a
905 // DeclContext. A context within it (such as a lambda-expression)
906 // should be considered dependent.
908 return getParent() && getParent()->isDependentContext();
911 bool DeclContext::isTransparentContext() const {
912 if (DeclKind == Decl::Enum)
913 return !cast<EnumDecl>(this)->isScoped();
914 else if (DeclKind == Decl::LinkageSpec)
920 static bool isLinkageSpecContext(const DeclContext *DC,
921 LinkageSpecDecl::LanguageIDs ID) {
922 while (DC->getDeclKind() != Decl::TranslationUnit) {
923 if (DC->getDeclKind() == Decl::LinkageSpec)
924 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
925 DC = DC->getLexicalParent();
930 bool DeclContext::isExternCContext() const {
931 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
934 bool DeclContext::isExternCXXContext() const {
935 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
938 bool DeclContext::Encloses(const DeclContext *DC) const {
939 if (getPrimaryContext() != this)
940 return getPrimaryContext()->Encloses(DC);
942 for (; DC; DC = DC->getParent())
943 if (DC->getPrimaryContext() == this)
948 DeclContext *DeclContext::getPrimaryContext() {
950 case Decl::TranslationUnit:
951 case Decl::ExternCContext:
952 case Decl::LinkageSpec:
955 // There is only one DeclContext for these entities.
958 case Decl::Namespace:
959 // The original namespace is our primary context.
960 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
962 case Decl::ObjCMethod:
965 case Decl::ObjCInterface:
966 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
971 case Decl::ObjCProtocol:
972 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
977 case Decl::ObjCCategory:
980 case Decl::ObjCImplementation:
981 case Decl::ObjCCategoryImpl:
985 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
986 // If this is a tag type that has a definition or is currently
987 // being defined, that definition is our primary context.
988 TagDecl *Tag = cast<TagDecl>(this);
990 if (TagDecl *Def = Tag->getDefinition())
993 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
994 // Note, TagType::getDecl returns the (partial) definition one exists.
995 TagDecl *PossiblePartialDef = TagTy->getDecl();
996 if (PossiblePartialDef->isBeingDefined())
997 return PossiblePartialDef;
999 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1005 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1006 "Unknown DeclContext kind");
1012 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1015 if (DeclKind != Decl::Namespace) {
1016 Contexts.push_back(this);
1020 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1021 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1022 N = N->getPreviousDecl())
1023 Contexts.push_back(N);
1025 std::reverse(Contexts.begin(), Contexts.end());
1028 std::pair<Decl *, Decl *>
1029 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1030 bool FieldsAlreadyLoaded) {
1031 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1032 Decl *FirstNewDecl = nullptr;
1033 Decl *PrevDecl = nullptr;
1034 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1035 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1040 PrevDecl->NextInContextAndBits.setPointer(D);
1047 return std::make_pair(FirstNewDecl, PrevDecl);
1050 /// \brief We have just acquired external visible storage, and we already have
1051 /// built a lookup map. For every name in the map, pull in the new names from
1052 /// the external storage.
1053 void DeclContext::reconcileExternalVisibleStorage() const {
1054 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1055 NeedToReconcileExternalVisibleStorage = false;
1057 for (auto &Lookup : *LookupPtr)
1058 Lookup.second.setHasExternalDecls();
1061 /// \brief Load the declarations within this lexical storage from an
1062 /// external source.
1063 /// \return \c true if any declarations were added.
1065 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1066 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1067 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1069 // Notify that we have a DeclContext that is initializing.
1070 ExternalASTSource::Deserializing ADeclContext(Source);
1072 // Load the external declarations, if any.
1073 SmallVector<Decl*, 64> Decls;
1074 ExternalLexicalStorage = false;
1075 Source->FindExternalLexicalDecls(this, Decls);
1080 // We may have already loaded just the fields of this record, in which case
1081 // we need to ignore them.
1082 bool FieldsAlreadyLoaded = false;
1083 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1084 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1086 // Splice the newly-read declarations into the beginning of the list
1088 Decl *ExternalFirst, *ExternalLast;
1089 std::tie(ExternalFirst, ExternalLast) =
1090 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1091 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1092 FirstDecl = ExternalFirst;
1094 LastDecl = ExternalLast;
1098 DeclContext::lookup_result
1099 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1100 DeclarationName Name) {
1101 ASTContext &Context = DC->getParentASTContext();
1102 StoredDeclsMap *Map;
1103 if (!(Map = DC->LookupPtr))
1104 Map = DC->CreateStoredDeclsMap(Context);
1105 if (DC->NeedToReconcileExternalVisibleStorage)
1106 DC->reconcileExternalVisibleStorage();
1108 (*Map)[Name].removeExternalDecls();
1110 return DeclContext::lookup_result();
1113 DeclContext::lookup_result
1114 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1115 DeclarationName Name,
1116 ArrayRef<NamedDecl*> Decls) {
1117 ASTContext &Context = DC->getParentASTContext();
1118 StoredDeclsMap *Map;
1119 if (!(Map = DC->LookupPtr))
1120 Map = DC->CreateStoredDeclsMap(Context);
1121 if (DC->NeedToReconcileExternalVisibleStorage)
1122 DC->reconcileExternalVisibleStorage();
1124 StoredDeclsList &List = (*Map)[Name];
1126 // Clear out any old external visible declarations, to avoid quadratic
1127 // performance in the redeclaration checks below.
1128 List.removeExternalDecls();
1130 if (!List.isNull()) {
1131 // We have both existing declarations and new declarations for this name.
1132 // Some of the declarations may simply replace existing ones. Handle those
1134 llvm::SmallVector<unsigned, 8> Skip;
1135 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1136 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1138 Skip.push_back(Decls.size());
1140 // Add in any new declarations.
1141 unsigned SkipPos = 0;
1142 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1143 if (I == Skip[SkipPos])
1146 List.AddSubsequentDecl(Decls[I]);
1149 // Convert the array to a StoredDeclsList.
1150 for (ArrayRef<NamedDecl*>::iterator
1151 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1153 List.setOnlyValue(*I);
1155 List.AddSubsequentDecl(*I);
1159 return List.getLookupResult();
1162 DeclContext::decl_iterator DeclContext::decls_begin() const {
1163 if (hasExternalLexicalStorage())
1164 LoadLexicalDeclsFromExternalStorage();
1165 return decl_iterator(FirstDecl);
1168 bool DeclContext::decls_empty() const {
1169 if (hasExternalLexicalStorage())
1170 LoadLexicalDeclsFromExternalStorage();
1175 bool DeclContext::containsDecl(Decl *D) const {
1176 return (D->getLexicalDeclContext() == this &&
1177 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1180 void DeclContext::removeDecl(Decl *D) {
1181 assert(D->getLexicalDeclContext() == this &&
1182 "decl being removed from non-lexical context");
1183 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1184 "decl is not in decls list");
1186 // Remove D from the decl chain. This is O(n) but hopefully rare.
1187 if (D == FirstDecl) {
1189 FirstDecl = LastDecl = nullptr;
1191 FirstDecl = D->NextInContextAndBits.getPointer();
1193 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1194 assert(I && "decl not found in linked list");
1195 if (I->NextInContextAndBits.getPointer() == D) {
1196 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1197 if (D == LastDecl) LastDecl = I;
1203 // Mark that D is no longer in the decl chain.
1204 D->NextInContextAndBits.setPointer(nullptr);
1206 // Remove D from the lookup table if necessary.
1207 if (isa<NamedDecl>(D)) {
1208 NamedDecl *ND = cast<NamedDecl>(D);
1210 // Remove only decls that have a name
1211 if (!ND->getDeclName()) return;
1215 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1217 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1218 assert(Pos != Map->end() && "no lookup entry for decl");
1219 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1220 Pos->second.remove(ND);
1222 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1226 void DeclContext::addHiddenDecl(Decl *D) {
1227 assert(D->getLexicalDeclContext() == this &&
1228 "Decl inserted into wrong lexical context");
1229 assert(!D->getNextDeclInContext() && D != LastDecl &&
1230 "Decl already inserted into a DeclContext");
1233 LastDecl->NextInContextAndBits.setPointer(D);
1236 FirstDecl = LastDecl = D;
1239 // Notify a C++ record declaration that we've added a member, so it can
1240 // update its class-specific state.
1241 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1242 Record->addedMember(D);
1244 // If this is a newly-created (not de-serialized) import declaration, wire
1245 // it in to the list of local import declarations.
1246 if (!D->isFromASTFile()) {
1247 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1248 D->getASTContext().addedLocalImportDecl(Import);
1252 void DeclContext::addDecl(Decl *D) {
1255 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1256 ND->getDeclContext()->getPrimaryContext()->
1257 makeDeclVisibleInContextWithFlags(ND, false, true);
1260 void DeclContext::addDeclInternal(Decl *D) {
1263 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1264 ND->getDeclContext()->getPrimaryContext()->
1265 makeDeclVisibleInContextWithFlags(ND, true, true);
1268 /// shouldBeHidden - Determine whether a declaration which was declared
1269 /// within its semantic context should be invisible to qualified name lookup.
1270 static bool shouldBeHidden(NamedDecl *D) {
1271 // Skip unnamed declarations.
1272 if (!D->getDeclName())
1275 // Skip entities that can't be found by name lookup into a particular
1277 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1278 D->isTemplateParameter())
1281 // Skip template specializations.
1282 // FIXME: This feels like a hack. Should DeclarationName support
1283 // template-ids, or is there a better way to keep specializations
1284 // from being visible?
1285 if (isa<ClassTemplateSpecializationDecl>(D))
1287 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1288 if (FD->isFunctionTemplateSpecialization())
1294 /// buildLookup - Build the lookup data structure with all of the
1295 /// declarations in this DeclContext (and any other contexts linked
1296 /// to it or transparent contexts nested within it) and return it.
1298 /// Note that the produced map may miss out declarations from an
1299 /// external source. If it does, those entries will be marked with
1300 /// the 'hasExternalDecls' flag.
1301 StoredDeclsMap *DeclContext::buildLookup() {
1302 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1304 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1307 SmallVector<DeclContext *, 2> Contexts;
1308 collectAllContexts(Contexts);
1310 if (HasLazyExternalLexicalLookups) {
1311 HasLazyExternalLexicalLookups = false;
1312 for (auto *DC : Contexts) {
1313 if (DC->hasExternalLexicalStorage())
1314 HasLazyLocalLexicalLookups |=
1315 DC->LoadLexicalDeclsFromExternalStorage();
1318 if (!HasLazyLocalLexicalLookups)
1322 for (auto *DC : Contexts)
1323 buildLookupImpl(DC, hasExternalVisibleStorage());
1325 // We no longer have any lazy decls.
1326 HasLazyLocalLexicalLookups = false;
1330 /// buildLookupImpl - Build part of the lookup data structure for the
1331 /// declarations contained within DCtx, which will either be this
1332 /// DeclContext, a DeclContext linked to it, or a transparent context
1333 /// nested within it.
1334 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1335 for (Decl *D : DCtx->noload_decls()) {
1336 // Insert this declaration into the lookup structure, but only if
1337 // it's semantically within its decl context. Any other decls which
1338 // should be found in this context are added eagerly.
1340 // If it's from an AST file, don't add it now. It'll get handled by
1341 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1342 // in C++, we do not track external visible decls for the TU, so in
1343 // that case we need to collect them all here.
1344 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1345 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1346 (!ND->isFromASTFile() ||
1347 (isTranslationUnit() &&
1348 !getParentASTContext().getLangOpts().CPlusPlus)))
1349 makeDeclVisibleInContextImpl(ND, Internal);
1351 // If this declaration is itself a transparent declaration context
1352 // or inline namespace, add the members of this declaration of that
1353 // context (recursively).
1354 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1355 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1356 buildLookupImpl(InnerCtx, Internal);
1360 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1362 DeclContext::lookup_result
1363 DeclContext::lookup(DeclarationName Name) const {
1364 assert(DeclKind != Decl::LinkageSpec &&
1365 "Should not perform lookups into linkage specs!");
1367 const DeclContext *PrimaryContext = getPrimaryContext();
1368 if (PrimaryContext != this)
1369 return PrimaryContext->lookup(Name);
1371 // If we have an external source, ensure that any later redeclarations of this
1372 // context have been loaded, since they may add names to the result of this
1373 // lookup (or add external visible storage).
1374 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1376 (void)cast<Decl>(this)->getMostRecentDecl();
1378 if (hasExternalVisibleStorage()) {
1379 assert(Source && "external visible storage but no external source?");
1381 if (NeedToReconcileExternalVisibleStorage)
1382 reconcileExternalVisibleStorage();
1384 StoredDeclsMap *Map = LookupPtr;
1386 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1387 // FIXME: Make buildLookup const?
1388 Map = const_cast<DeclContext*>(this)->buildLookup();
1391 Map = CreateStoredDeclsMap(getParentASTContext());
1393 // If we have a lookup result with no external decls, we are done.
1394 std::pair<StoredDeclsMap::iterator, bool> R =
1395 Map->insert(std::make_pair(Name, StoredDeclsList()));
1396 if (!R.second && !R.first->second.hasExternalDecls())
1397 return R.first->second.getLookupResult();
1399 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1400 if (StoredDeclsMap *Map = LookupPtr) {
1401 StoredDeclsMap::iterator I = Map->find(Name);
1402 if (I != Map->end())
1403 return I->second.getLookupResult();
1407 return lookup_result();
1410 StoredDeclsMap *Map = LookupPtr;
1411 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1412 Map = const_cast<DeclContext*>(this)->buildLookup();
1415 return lookup_result();
1417 StoredDeclsMap::iterator I = Map->find(Name);
1418 if (I == Map->end())
1419 return lookup_result();
1421 return I->second.getLookupResult();
1424 DeclContext::lookup_result
1425 DeclContext::noload_lookup(DeclarationName Name) {
1426 assert(DeclKind != Decl::LinkageSpec &&
1427 "Should not perform lookups into linkage specs!");
1429 DeclContext *PrimaryContext = getPrimaryContext();
1430 if (PrimaryContext != this)
1431 return PrimaryContext->noload_lookup(Name);
1433 // If we have any lazy lexical declarations not in our lookup map, add them
1434 // now. Don't import any external declarations, not even if we know we have
1435 // some missing from the external visible lookups.
1436 if (HasLazyLocalLexicalLookups) {
1437 SmallVector<DeclContext *, 2> Contexts;
1438 collectAllContexts(Contexts);
1439 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1440 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1441 HasLazyLocalLexicalLookups = false;
1444 StoredDeclsMap *Map = LookupPtr;
1446 return lookup_result();
1448 StoredDeclsMap::iterator I = Map->find(Name);
1449 return I != Map->end() ? I->second.getLookupResult()
1453 void DeclContext::localUncachedLookup(DeclarationName Name,
1454 SmallVectorImpl<NamedDecl *> &Results) {
1457 // If there's no external storage, just perform a normal lookup and copy
1459 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1460 lookup_result LookupResults = lookup(Name);
1461 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1465 // If we have a lookup table, check there first. Maybe we'll get lucky.
1466 // FIXME: Should we be checking these flags on the primary context?
1467 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1468 if (StoredDeclsMap *Map = LookupPtr) {
1469 StoredDeclsMap::iterator Pos = Map->find(Name);
1470 if (Pos != Map->end()) {
1471 Results.insert(Results.end(),
1472 Pos->second.getLookupResult().begin(),
1473 Pos->second.getLookupResult().end());
1479 // Slow case: grovel through the declarations in our chain looking for
1481 // FIXME: If we have lazy external declarations, this will not find them!
1482 // FIXME: Should we CollectAllContexts and walk them all here?
1483 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1484 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1485 if (ND->getDeclName() == Name)
1486 Results.push_back(ND);
1490 DeclContext *DeclContext::getRedeclContext() {
1491 DeclContext *Ctx = this;
1492 // Skip through transparent contexts.
1493 while (Ctx->isTransparentContext())
1494 Ctx = Ctx->getParent();
1498 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1499 DeclContext *Ctx = this;
1500 // Skip through non-namespace, non-translation-unit contexts.
1501 while (!Ctx->isFileContext())
1502 Ctx = Ctx->getParent();
1503 return Ctx->getPrimaryContext();
1506 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1507 // Loop until we find a non-record context.
1508 RecordDecl *OutermostRD = nullptr;
1509 DeclContext *DC = this;
1510 while (DC->isRecord()) {
1511 OutermostRD = cast<RecordDecl>(DC);
1512 DC = DC->getLexicalParent();
1517 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1518 // For non-file contexts, this is equivalent to Equals.
1519 if (!isFileContext())
1520 return O->Equals(this);
1523 if (O->Equals(this))
1526 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1527 if (!NS || !NS->isInline())
1529 O = NS->getParent();
1535 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1536 DeclContext *PrimaryDC = this->getPrimaryContext();
1537 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1538 // If the decl is being added outside of its semantic decl context, we
1539 // need to ensure that we eagerly build the lookup information for it.
1540 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1543 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1545 assert(this == getPrimaryContext() && "expected a primary DC");
1547 // Skip declarations within functions.
1548 if (isFunctionOrMethod())
1551 // Skip declarations which should be invisible to name lookup.
1552 if (shouldBeHidden(D))
1555 // If we already have a lookup data structure, perform the insertion into
1556 // it. If we might have externally-stored decls with this name, look them
1557 // up and perform the insertion. If this decl was declared outside its
1558 // semantic context, buildLookup won't add it, so add it now.
1560 // FIXME: As a performance hack, don't add such decls into the translation
1561 // unit unless we're in C++, since qualified lookup into the TU is never
1563 if (LookupPtr || hasExternalVisibleStorage() ||
1564 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1565 (getParentASTContext().getLangOpts().CPlusPlus ||
1566 !isTranslationUnit()))) {
1567 // If we have lazily omitted any decls, they might have the same name as
1568 // the decl which we are adding, so build a full lookup table before adding
1571 makeDeclVisibleInContextImpl(D, Internal);
1573 HasLazyLocalLexicalLookups = true;
1576 // If we are a transparent context or inline namespace, insert into our
1577 // parent context, too. This operation is recursive.
1578 if (isTransparentContext() || isInlineNamespace())
1579 getParent()->getPrimaryContext()->
1580 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1582 Decl *DCAsDecl = cast<Decl>(this);
1583 // Notify that a decl was made visible unless we are a Tag being defined.
1584 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1585 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1586 L->AddedVisibleDecl(this, D);
1589 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1590 // Find or create the stored declaration map.
1591 StoredDeclsMap *Map = LookupPtr;
1593 ASTContext *C = &getParentASTContext();
1594 Map = CreateStoredDeclsMap(*C);
1597 // If there is an external AST source, load any declarations it knows about
1598 // with this declaration's name.
1599 // If the lookup table contains an entry about this name it means that we
1600 // have already checked the external source.
1602 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1603 if (hasExternalVisibleStorage() &&
1604 Map->find(D->getDeclName()) == Map->end())
1605 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1607 // Insert this declaration into the map.
1608 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1611 // If this is being added as part of loading an external declaration,
1612 // this may not be the only external declaration with this name.
1613 // In this case, we never try to replace an existing declaration; we'll
1614 // handle that when we finalize the list of declarations for this name.
1615 DeclNameEntries.setHasExternalDecls();
1616 DeclNameEntries.AddSubsequentDecl(D);
1620 if (DeclNameEntries.isNull()) {
1621 DeclNameEntries.setOnlyValue(D);
1625 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1626 // This declaration has replaced an existing one for which
1627 // declarationReplaces returns true.
1631 // Put this declaration into the appropriate slot.
1632 DeclNameEntries.AddSubsequentDecl(D);
1635 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1636 return cast<UsingDirectiveDecl>(*I);
1639 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1641 DeclContext::udir_range DeclContext::using_directives() const {
1642 // FIXME: Use something more efficient than normal lookup for using
1643 // directives. In C++, using directives are looked up more than anything else.
1644 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1645 return udir_range(Result.begin(), Result.end());
1648 //===----------------------------------------------------------------------===//
1649 // Creation and Destruction of StoredDeclsMaps. //
1650 //===----------------------------------------------------------------------===//
1652 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1653 assert(!LookupPtr && "context already has a decls map");
1654 assert(getPrimaryContext() == this &&
1655 "creating decls map on non-primary context");
1658 bool Dependent = isDependentContext();
1660 M = new DependentStoredDeclsMap();
1662 M = new StoredDeclsMap();
1663 M->Previous = C.LastSDM;
1664 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1669 void ASTContext::ReleaseDeclContextMaps() {
1670 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1671 // pointer because the subclass doesn't add anything that needs to
1673 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1676 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1678 // Advance the iteration before we invalidate memory.
1679 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1682 delete static_cast<DependentStoredDeclsMap*>(Map);
1686 Map = Next.getPointer();
1687 Dependent = Next.getInt();
1691 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1692 DeclContext *Parent,
1693 const PartialDiagnostic &PDiag) {
1694 assert(Parent->isDependentContext()
1695 && "cannot iterate dependent diagnostics of non-dependent context");
1696 Parent = Parent->getPrimaryContext();
1697 if (!Parent->LookupPtr)
1698 Parent->CreateStoredDeclsMap(C);
1700 DependentStoredDeclsMap *Map =
1701 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1703 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1704 // BumpPtrAllocator, rather than the ASTContext itself.
1705 PartialDiagnostic::Storage *DiagStorage = nullptr;
1706 if (PDiag.hasStorage())
1707 DiagStorage = new (C) PartialDiagnostic::Storage;
1709 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1711 // TODO: Maybe we shouldn't reverse the order during insertion.
1712 DD->NextDiagnostic = Map->FirstDiagnostic;
1713 Map->FirstDiagnostic = DD;