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 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
49 unsigned ID, std::size_t Extra) {
50 // Allocate an extra 8 bytes worth of storage, which ensures that the
51 // resulting pointer will still be 8-byte aligned.
52 void *Start = Context.Allocate(Size + Extra + 8);
53 void *Result = (char*)Start + 8;
55 unsigned *PrefixPtr = (unsigned *)Result - 2;
57 // Zero out the first 4 bytes; this is used to store the owning module ID.
60 // Store the global declaration ID in the second 4 bytes.
66 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
67 DeclContext *Parent, std::size_t Extra) {
68 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
69 // With local visibility enabled, we track the owning module even for local
71 if (Ctx.getLangOpts().ModulesLocalVisibility) {
72 void *Buffer = ::operator new(sizeof(Module *) + Size + Extra, Ctx);
73 return new (Buffer) Module*(nullptr) + 1;
75 return ::operator new(Size + Extra, Ctx);
78 Module *Decl::getOwningModuleSlow() const {
79 assert(isFromASTFile() && "Not from AST file?");
80 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
83 bool Decl::hasLocalOwningModuleStorage() const {
84 return getASTContext().getLangOpts().ModulesLocalVisibility;
87 const char *Decl::getDeclKindName() const {
89 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
90 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
91 #define ABSTRACT_DECL(DECL)
92 #include "clang/AST/DeclNodes.inc"
96 void Decl::setInvalidDecl(bool Invalid) {
97 InvalidDecl = Invalid;
98 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
99 if (Invalid && !isa<ParmVarDecl>(this)) {
100 // Defensive maneuver for ill-formed code: we're likely not to make it to
101 // a point where we set the access specifier, so default it to "public"
102 // to avoid triggering asserts elsewhere in the front end.
103 setAccess(AS_public);
107 const char *DeclContext::getDeclKindName() const {
109 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
110 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
111 #define ABSTRACT_DECL(DECL)
112 #include "clang/AST/DeclNodes.inc"
116 bool Decl::StatisticsEnabled = false;
117 void Decl::EnableStatistics() {
118 StatisticsEnabled = true;
121 void Decl::PrintStats() {
122 llvm::errs() << "\n*** Decl Stats:\n";
125 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
126 #define ABSTRACT_DECL(DECL)
127 #include "clang/AST/DeclNodes.inc"
128 llvm::errs() << " " << totalDecls << " decls total.\n";
131 #define DECL(DERIVED, BASE) \
132 if (n##DERIVED##s > 0) { \
133 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
134 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
135 << sizeof(DERIVED##Decl) << " each (" \
136 << n##DERIVED##s * sizeof(DERIVED##Decl) \
139 #define ABSTRACT_DECL(DECL)
140 #include "clang/AST/DeclNodes.inc"
142 llvm::errs() << "Total bytes = " << totalBytes << "\n";
145 void Decl::add(Kind k) {
147 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
148 #define ABSTRACT_DECL(DECL)
149 #include "clang/AST/DeclNodes.inc"
153 bool Decl::isTemplateParameterPack() const {
154 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
155 return TTP->isParameterPack();
156 if (const NonTypeTemplateParmDecl *NTTP
157 = dyn_cast<NonTypeTemplateParmDecl>(this))
158 return NTTP->isParameterPack();
159 if (const TemplateTemplateParmDecl *TTP
160 = dyn_cast<TemplateTemplateParmDecl>(this))
161 return TTP->isParameterPack();
165 bool Decl::isParameterPack() const {
166 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
167 return Parm->isParameterPack();
169 return isTemplateParameterPack();
172 FunctionDecl *Decl::getAsFunction() {
173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
175 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
176 return FTD->getTemplatedDecl();
180 bool Decl::isTemplateDecl() const {
181 return isa<TemplateDecl>(this);
184 const DeclContext *Decl::getParentFunctionOrMethod() const {
185 for (const DeclContext *DC = getDeclContext();
186 DC && !DC->isTranslationUnit() && !DC->isNamespace();
187 DC = DC->getParent())
188 if (DC->isFunctionOrMethod())
195 //===----------------------------------------------------------------------===//
196 // PrettyStackTraceDecl Implementation
197 //===----------------------------------------------------------------------===//
199 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
200 SourceLocation TheLoc = Loc;
201 if (TheLoc.isInvalid() && TheDecl)
202 TheLoc = TheDecl->getLocation();
204 if (TheLoc.isValid()) {
205 TheLoc.print(OS, SM);
211 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
213 DN->printQualifiedName(OS);
219 //===----------------------------------------------------------------------===//
220 // Decl Implementation
221 //===----------------------------------------------------------------------===//
223 // Out-of-line virtual method providing a home for Decl.
226 void Decl::setDeclContext(DeclContext *DC) {
230 void Decl::setLexicalDeclContext(DeclContext *DC) {
231 if (DC == getLexicalDeclContext())
235 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
237 getMultipleDC()->LexicalDC = DC;
239 Hidden = cast<Decl>(DC)->Hidden;
242 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
244 if (SemaDC == LexicalDC) {
247 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
248 MDC->SemanticDC = SemaDC;
249 MDC->LexicalDC = LexicalDC;
254 bool Decl::isInAnonymousNamespace() const {
255 const DeclContext *DC = getDeclContext();
257 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
258 if (ND->isAnonymousNamespace())
260 } while ((DC = DC->getParent()));
265 bool Decl::isInStdNamespace() const {
266 return getDeclContext()->isStdNamespace();
269 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
270 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
273 DeclContext *DC = getDeclContext();
274 assert(DC && "This decl is not contained in a translation unit!");
276 while (!DC->isTranslationUnit()) {
277 DC = DC->getParent();
278 assert(DC && "This decl is not contained in a translation unit!");
281 return cast<TranslationUnitDecl>(DC);
284 ASTContext &Decl::getASTContext() const {
285 return getTranslationUnitDecl()->getASTContext();
288 ASTMutationListener *Decl::getASTMutationListener() const {
289 return getASTContext().getASTMutationListener();
292 unsigned Decl::getMaxAlignment() const {
297 const AttrVec &V = getAttrs();
298 ASTContext &Ctx = getASTContext();
299 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
301 Align = std::max(Align, I->getAlignment(Ctx));
305 bool Decl::isUsed(bool CheckUsedAttr) const {
309 // Check for used attribute.
310 if (CheckUsedAttr && hasAttr<UsedAttr>())
316 void Decl::markUsed(ASTContext &C) {
320 if (C.getASTMutationListener())
321 C.getASTMutationListener()->DeclarationMarkedUsed(this);
326 bool Decl::isReferenced() const {
330 // Check redeclarations.
331 for (auto I : redecls())
338 /// \brief Determine the availability of the given declaration based on
339 /// the target platform.
341 /// When it returns an availability result other than \c AR_Available,
342 /// if the \p Message parameter is non-NULL, it will be set to a
343 /// string describing why the entity is unavailable.
345 /// FIXME: Make these strings localizable, since they end up in
347 static AvailabilityResult CheckAvailability(ASTContext &Context,
348 const AvailabilityAttr *A,
349 std::string *Message) {
350 VersionTuple TargetMinVersion =
351 Context.getTargetInfo().getPlatformMinVersion();
353 if (TargetMinVersion.empty())
356 // Check if this is an App Extension "platform", and if so chop off
357 // the suffix for matching with the actual platform.
358 StringRef ActualPlatform = A->getPlatform()->getName();
359 StringRef RealizedPlatform = ActualPlatform;
360 if (Context.getLangOpts().AppExt) {
361 size_t suffix = RealizedPlatform.rfind("_app_extension");
362 if (suffix != StringRef::npos)
363 RealizedPlatform = RealizedPlatform.slice(0, suffix);
366 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
368 // Match the platform name.
369 if (RealizedPlatform != TargetPlatform)
372 StringRef PrettyPlatformName
373 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
375 if (PrettyPlatformName.empty())
376 PrettyPlatformName = ActualPlatform;
378 std::string HintMessage;
379 if (!A->getMessage().empty()) {
381 HintMessage += A->getMessage();
384 // Make sure that this declaration has not been marked 'unavailable'.
385 if (A->getUnavailable()) {
388 llvm::raw_string_ostream Out(*Message);
389 Out << "not available on " << PrettyPlatformName
393 return AR_Unavailable;
396 // Make sure that this declaration has already been introduced.
397 if (!A->getIntroduced().empty() &&
398 TargetMinVersion < A->getIntroduced()) {
401 llvm::raw_string_ostream Out(*Message);
402 VersionTuple VTI(A->getIntroduced());
403 VTI.UseDotAsSeparator();
404 Out << "introduced in " << PrettyPlatformName << ' '
405 << VTI << HintMessage;
408 return AR_NotYetIntroduced;
411 // Make sure that this declaration hasn't been obsoleted.
412 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
415 llvm::raw_string_ostream Out(*Message);
416 VersionTuple VTO(A->getObsoleted());
417 VTO.UseDotAsSeparator();
418 Out << "obsoleted in " << PrettyPlatformName << ' '
419 << VTO << HintMessage;
422 return AR_Unavailable;
425 // Make sure that this declaration hasn't been deprecated.
426 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
429 llvm::raw_string_ostream Out(*Message);
430 VersionTuple VTD(A->getDeprecated());
431 VTD.UseDotAsSeparator();
432 Out << "first deprecated in " << PrettyPlatformName << ' '
433 << VTD << HintMessage;
436 return AR_Deprecated;
442 AvailabilityResult Decl::getAvailability(std::string *Message) const {
443 AvailabilityResult Result = AR_Available;
444 std::string ResultMessage;
446 for (const auto *A : attrs()) {
447 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
448 if (Result >= AR_Deprecated)
452 ResultMessage = Deprecated->getMessage();
454 Result = AR_Deprecated;
458 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
460 *Message = Unavailable->getMessage();
461 return AR_Unavailable;
464 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
465 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
468 if (AR == AR_Unavailable)
469 return AR_Unavailable;
474 ResultMessage.swap(*Message);
481 Message->swap(ResultMessage);
485 bool Decl::canBeWeakImported(bool &IsDefinition) const {
486 IsDefinition = false;
488 // Variables, if they aren't definitions.
489 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
490 if (Var->isThisDeclarationADefinition()) {
496 // Functions, if they aren't definitions.
497 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
504 // Objective-C classes, if this is the non-fragile runtime.
505 } else if (isa<ObjCInterfaceDecl>(this) &&
506 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
515 bool Decl::isWeakImported() const {
517 if (!canBeWeakImported(IsDefinition))
520 for (const auto *A : attrs()) {
521 if (isa<WeakImportAttr>(A))
524 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
525 if (CheckAvailability(getASTContext(), Availability,
526 nullptr) == AR_NotYetIntroduced)
534 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
545 case NonTypeTemplateParm:
549 return IDNS_Ordinary;
553 return IDNS_Ordinary | IDNS_Member;
555 case ObjCCompatibleAlias:
557 return IDNS_Ordinary | IDNS_Type;
561 case TypeAliasTemplate:
562 case UnresolvedUsingTypename:
563 case TemplateTypeParm:
565 return IDNS_Ordinary | IDNS_Type;
568 return 0; // we'll actually overwrite this later
570 case UnresolvedUsingValue:
571 return IDNS_Ordinary | IDNS_Using;
577 return IDNS_ObjCProtocol;
580 case ObjCAtDefsField:
587 return IDNS_Tag | IDNS_Type;
591 return IDNS_Namespace;
593 case FunctionTemplate:
595 return IDNS_Ordinary;
598 case TemplateTemplateParm:
599 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
608 case ObjCPropertyImpl:
611 case TranslationUnit:
615 case ClassTemplateSpecialization:
616 case ClassTemplatePartialSpecialization:
617 case ClassScopeFunctionSpecialization:
618 case VarTemplateSpecialization:
619 case VarTemplatePartialSpecialization:
620 case ObjCImplementation:
622 case ObjCCategoryImpl:
624 case OMPThreadPrivate:
626 // Never looked up by name.
630 llvm_unreachable("Invalid DeclKind!");
633 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
634 assert(!HasAttrs && "Decl already contains attrs.");
636 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
637 assert(AttrBlank.empty() && "HasAttrs was wrong?");
643 void Decl::dropAttrs() {
644 if (!HasAttrs) return;
647 getASTContext().eraseDeclAttrs(this);
650 const AttrVec &Decl::getAttrs() const {
651 assert(HasAttrs && "No attrs to get!");
652 return getASTContext().getDeclAttrs(this);
655 Decl *Decl::castFromDeclContext (const DeclContext *D) {
656 Decl::Kind DK = D->getDeclKind();
658 #define DECL(NAME, BASE)
659 #define DECL_CONTEXT(NAME) \
661 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
662 #define DECL_CONTEXT_BASE(NAME)
663 #include "clang/AST/DeclNodes.inc"
665 #define DECL(NAME, BASE)
666 #define DECL_CONTEXT_BASE(NAME) \
667 if (DK >= first##NAME && DK <= last##NAME) \
668 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
669 #include "clang/AST/DeclNodes.inc"
670 llvm_unreachable("a decl that inherits DeclContext isn't handled");
674 DeclContext *Decl::castToDeclContext(const Decl *D) {
675 Decl::Kind DK = D->getKind();
677 #define DECL(NAME, BASE)
678 #define DECL_CONTEXT(NAME) \
680 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
681 #define DECL_CONTEXT_BASE(NAME)
682 #include "clang/AST/DeclNodes.inc"
684 #define DECL(NAME, BASE)
685 #define DECL_CONTEXT_BASE(NAME) \
686 if (DK >= first##NAME && DK <= last##NAME) \
687 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
688 #include "clang/AST/DeclNodes.inc"
689 llvm_unreachable("a decl that inherits DeclContext isn't handled");
693 SourceLocation Decl::getBodyRBrace() const {
694 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
695 // FunctionDecl stores EndRangeLoc for this purpose.
696 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
697 const FunctionDecl *Definition;
698 if (FD->hasBody(Definition))
699 return Definition->getSourceRange().getEnd();
700 return SourceLocation();
703 if (Stmt *Body = getBody())
704 return Body->getSourceRange().getEnd();
706 return SourceLocation();
709 bool Decl::AccessDeclContextSanity() const {
711 // Suppress this check if any of the following hold:
712 // 1. this is the translation unit (and thus has no parent)
713 // 2. this is a template parameter (and thus doesn't belong to its context)
714 // 3. this is a non-type template parameter
715 // 4. the context is not a record
717 // 6. it's a C++0x static_assert.
718 if (isa<TranslationUnitDecl>(this) ||
719 isa<TemplateTypeParmDecl>(this) ||
720 isa<NonTypeTemplateParmDecl>(this) ||
721 !isa<CXXRecordDecl>(getDeclContext()) ||
723 isa<StaticAssertDecl>(this) ||
724 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
725 // as DeclContext (?).
726 isa<ParmVarDecl>(this) ||
727 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
728 // AS_none as access specifier.
729 isa<CXXRecordDecl>(this) ||
730 isa<ClassScopeFunctionSpecializationDecl>(this))
733 assert(Access != AS_none &&
734 "Access specifier is AS_none inside a record decl");
739 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
740 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
742 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
744 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
746 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
747 Ty = D->getUnderlyingType();
751 if (Ty->isFunctionPointerType())
752 Ty = Ty->getAs<PointerType>()->getPointeeType();
753 else if (BlocksToo && Ty->isBlockPointerType())
754 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
756 return Ty->getAs<FunctionType>();
760 /// Starting at a given context (a Decl or DeclContext), look for a
761 /// code context that is not a closure (a lambda, block, etc.).
762 template <class T> static Decl *getNonClosureContext(T *D) {
763 if (getKind(D) == Decl::CXXMethod) {
764 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
765 if (MD->getOverloadedOperator() == OO_Call &&
766 MD->getParent()->isLambda())
767 return getNonClosureContext(MD->getParent()->getParent());
769 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
771 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
773 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
774 return getNonClosureContext(BD->getParent());
775 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
776 return getNonClosureContext(CD->getParent());
782 Decl *Decl::getNonClosureContext() {
783 return ::getNonClosureContext(this);
786 Decl *DeclContext::getNonClosureAncestor() {
787 return ::getNonClosureContext(this);
790 //===----------------------------------------------------------------------===//
791 // DeclContext Implementation
792 //===----------------------------------------------------------------------===//
794 bool DeclContext::classof(const Decl *D) {
795 switch (D->getKind()) {
796 #define DECL(NAME, BASE)
797 #define DECL_CONTEXT(NAME) case Decl::NAME:
798 #define DECL_CONTEXT_BASE(NAME)
799 #include "clang/AST/DeclNodes.inc"
802 #define DECL(NAME, BASE)
803 #define DECL_CONTEXT_BASE(NAME) \
804 if (D->getKind() >= Decl::first##NAME && \
805 D->getKind() <= Decl::last##NAME) \
807 #include "clang/AST/DeclNodes.inc"
812 DeclContext::~DeclContext() { }
814 /// \brief Find the parent context of this context that will be
815 /// used for unqualified name lookup.
817 /// Generally, the parent lookup context is the semantic context. However, for
818 /// a friend function the parent lookup context is the lexical context, which
819 /// is the class in which the friend is declared.
820 DeclContext *DeclContext::getLookupParent() {
821 // FIXME: Find a better way to identify friends
822 if (isa<FunctionDecl>(this))
823 if (getParent()->getRedeclContext()->isFileContext() &&
824 getLexicalParent()->getRedeclContext()->isRecord())
825 return getLexicalParent();
830 bool DeclContext::isInlineNamespace() const {
831 return isNamespace() &&
832 cast<NamespaceDecl>(this)->isInline();
835 bool DeclContext::isStdNamespace() const {
839 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
840 if (ND->isInline()) {
841 return ND->getParent()->isStdNamespace();
844 if (!getParent()->getRedeclContext()->isTranslationUnit())
847 const IdentifierInfo *II = ND->getIdentifier();
848 return II && II->isStr("std");
851 bool DeclContext::isDependentContext() const {
855 if (isa<ClassTemplatePartialSpecializationDecl>(this))
858 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
859 if (Record->getDescribedClassTemplate())
862 if (Record->isDependentLambda())
866 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
867 if (Function->getDescribedFunctionTemplate())
870 // Friend function declarations are dependent if their *lexical*
871 // context is dependent.
872 if (cast<Decl>(this)->getFriendObjectKind())
873 return getLexicalParent()->isDependentContext();
876 // FIXME: A variable template is a dependent context, but is not a
877 // DeclContext. A context within it (such as a lambda-expression)
878 // should be considered dependent.
880 return getParent() && getParent()->isDependentContext();
883 bool DeclContext::isTransparentContext() const {
884 if (DeclKind == Decl::Enum)
885 return !cast<EnumDecl>(this)->isScoped();
886 else if (DeclKind == Decl::LinkageSpec)
892 static bool isLinkageSpecContext(const DeclContext *DC,
893 LinkageSpecDecl::LanguageIDs ID) {
894 while (DC->getDeclKind() != Decl::TranslationUnit) {
895 if (DC->getDeclKind() == Decl::LinkageSpec)
896 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
897 DC = DC->getLexicalParent();
902 bool DeclContext::isExternCContext() const {
903 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
906 bool DeclContext::isExternCXXContext() const {
907 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
910 bool DeclContext::Encloses(const DeclContext *DC) const {
911 if (getPrimaryContext() != this)
912 return getPrimaryContext()->Encloses(DC);
914 for (; DC; DC = DC->getParent())
915 if (DC->getPrimaryContext() == this)
920 DeclContext *DeclContext::getPrimaryContext() {
922 case Decl::TranslationUnit:
923 case Decl::ExternCContext:
924 case Decl::LinkageSpec:
927 // There is only one DeclContext for these entities.
930 case Decl::Namespace:
931 // The original namespace is our primary context.
932 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
934 case Decl::ObjCMethod:
937 case Decl::ObjCInterface:
938 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
943 case Decl::ObjCProtocol:
944 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
949 case Decl::ObjCCategory:
952 case Decl::ObjCImplementation:
953 case Decl::ObjCCategoryImpl:
957 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
958 // If this is a tag type that has a definition or is currently
959 // being defined, that definition is our primary context.
960 TagDecl *Tag = cast<TagDecl>(this);
962 if (TagDecl *Def = Tag->getDefinition())
965 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
966 // Note, TagType::getDecl returns the (partial) definition one exists.
967 TagDecl *PossiblePartialDef = TagTy->getDecl();
968 if (PossiblePartialDef->isBeingDefined())
969 return PossiblePartialDef;
971 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
977 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
978 "Unknown DeclContext kind");
984 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
987 if (DeclKind != Decl::Namespace) {
988 Contexts.push_back(this);
992 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
993 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
994 N = N->getPreviousDecl())
995 Contexts.push_back(N);
997 std::reverse(Contexts.begin(), Contexts.end());
1000 std::pair<Decl *, Decl *>
1001 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1002 bool FieldsAlreadyLoaded) {
1003 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1004 Decl *FirstNewDecl = nullptr;
1005 Decl *PrevDecl = nullptr;
1006 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1007 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1012 PrevDecl->NextInContextAndBits.setPointer(D);
1019 return std::make_pair(FirstNewDecl, PrevDecl);
1022 /// \brief We have just acquired external visible storage, and we already have
1023 /// built a lookup map. For every name in the map, pull in the new names from
1024 /// the external storage.
1025 void DeclContext::reconcileExternalVisibleStorage() const {
1026 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1027 NeedToReconcileExternalVisibleStorage = false;
1029 for (auto &Lookup : *LookupPtr)
1030 Lookup.second.setHasExternalDecls();
1033 /// \brief Load the declarations within this lexical storage from an
1034 /// external source.
1035 /// \return \c true if any declarations were added.
1037 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1038 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1039 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1041 // Notify that we have a DeclContext that is initializing.
1042 ExternalASTSource::Deserializing ADeclContext(Source);
1044 // Load the external declarations, if any.
1045 SmallVector<Decl*, 64> Decls;
1046 ExternalLexicalStorage = false;
1047 switch (Source->FindExternalLexicalDecls(this, Decls)) {
1052 case ELR_AlreadyLoaded:
1059 // We may have already loaded just the fields of this record, in which case
1060 // we need to ignore them.
1061 bool FieldsAlreadyLoaded = false;
1062 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1063 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1065 // Splice the newly-read declarations into the beginning of the list
1067 Decl *ExternalFirst, *ExternalLast;
1068 std::tie(ExternalFirst, ExternalLast) =
1069 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1070 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1071 FirstDecl = ExternalFirst;
1073 LastDecl = ExternalLast;
1077 DeclContext::lookup_result
1078 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1079 DeclarationName Name) {
1080 ASTContext &Context = DC->getParentASTContext();
1081 StoredDeclsMap *Map;
1082 if (!(Map = DC->LookupPtr))
1083 Map = DC->CreateStoredDeclsMap(Context);
1084 if (DC->NeedToReconcileExternalVisibleStorage)
1085 DC->reconcileExternalVisibleStorage();
1087 (*Map)[Name].removeExternalDecls();
1089 return DeclContext::lookup_result();
1092 DeclContext::lookup_result
1093 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1094 DeclarationName Name,
1095 ArrayRef<NamedDecl*> Decls) {
1096 ASTContext &Context = DC->getParentASTContext();
1097 StoredDeclsMap *Map;
1098 if (!(Map = DC->LookupPtr))
1099 Map = DC->CreateStoredDeclsMap(Context);
1100 if (DC->NeedToReconcileExternalVisibleStorage)
1101 DC->reconcileExternalVisibleStorage();
1103 StoredDeclsList &List = (*Map)[Name];
1105 // Clear out any old external visible declarations, to avoid quadratic
1106 // performance in the redeclaration checks below.
1107 List.removeExternalDecls();
1109 if (!List.isNull()) {
1110 // We have both existing declarations and new declarations for this name.
1111 // Some of the declarations may simply replace existing ones. Handle those
1113 llvm::SmallVector<unsigned, 8> Skip;
1114 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1115 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1117 Skip.push_back(Decls.size());
1119 // Add in any new declarations.
1120 unsigned SkipPos = 0;
1121 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1122 if (I == Skip[SkipPos])
1125 List.AddSubsequentDecl(Decls[I]);
1128 // Convert the array to a StoredDeclsList.
1129 for (ArrayRef<NamedDecl*>::iterator
1130 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1132 List.setOnlyValue(*I);
1134 List.AddSubsequentDecl(*I);
1138 return List.getLookupResult();
1141 DeclContext::decl_iterator DeclContext::decls_begin() const {
1142 if (hasExternalLexicalStorage())
1143 LoadLexicalDeclsFromExternalStorage();
1144 return decl_iterator(FirstDecl);
1147 bool DeclContext::decls_empty() const {
1148 if (hasExternalLexicalStorage())
1149 LoadLexicalDeclsFromExternalStorage();
1154 bool DeclContext::containsDecl(Decl *D) const {
1155 return (D->getLexicalDeclContext() == this &&
1156 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1159 void DeclContext::removeDecl(Decl *D) {
1160 assert(D->getLexicalDeclContext() == this &&
1161 "decl being removed from non-lexical context");
1162 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1163 "decl is not in decls list");
1165 // Remove D from the decl chain. This is O(n) but hopefully rare.
1166 if (D == FirstDecl) {
1168 FirstDecl = LastDecl = nullptr;
1170 FirstDecl = D->NextInContextAndBits.getPointer();
1172 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1173 assert(I && "decl not found in linked list");
1174 if (I->NextInContextAndBits.getPointer() == D) {
1175 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1176 if (D == LastDecl) LastDecl = I;
1182 // Mark that D is no longer in the decl chain.
1183 D->NextInContextAndBits.setPointer(nullptr);
1185 // Remove D from the lookup table if necessary.
1186 if (isa<NamedDecl>(D)) {
1187 NamedDecl *ND = cast<NamedDecl>(D);
1189 // Remove only decls that have a name
1190 if (!ND->getDeclName()) return;
1192 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
1195 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1196 assert(Pos != Map->end() && "no lookup entry for decl");
1197 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1198 Pos->second.remove(ND);
1202 void DeclContext::addHiddenDecl(Decl *D) {
1203 assert(D->getLexicalDeclContext() == this &&
1204 "Decl inserted into wrong lexical context");
1205 assert(!D->getNextDeclInContext() && D != LastDecl &&
1206 "Decl already inserted into a DeclContext");
1209 LastDecl->NextInContextAndBits.setPointer(D);
1212 FirstDecl = LastDecl = D;
1215 // Notify a C++ record declaration that we've added a member, so it can
1216 // update it's class-specific state.
1217 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1218 Record->addedMember(D);
1220 // If this is a newly-created (not de-serialized) import declaration, wire
1221 // it in to the list of local import declarations.
1222 if (!D->isFromASTFile()) {
1223 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1224 D->getASTContext().addedLocalImportDecl(Import);
1228 void DeclContext::addDecl(Decl *D) {
1231 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1232 ND->getDeclContext()->getPrimaryContext()->
1233 makeDeclVisibleInContextWithFlags(ND, false, true);
1236 void DeclContext::addDeclInternal(Decl *D) {
1239 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1240 ND->getDeclContext()->getPrimaryContext()->
1241 makeDeclVisibleInContextWithFlags(ND, true, true);
1244 /// shouldBeHidden - Determine whether a declaration which was declared
1245 /// within its semantic context should be invisible to qualified name lookup.
1246 static bool shouldBeHidden(NamedDecl *D) {
1247 // Skip unnamed declarations.
1248 if (!D->getDeclName())
1251 // Skip entities that can't be found by name lookup into a particular
1253 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1254 D->isTemplateParameter())
1257 // Skip template specializations.
1258 // FIXME: This feels like a hack. Should DeclarationName support
1259 // template-ids, or is there a better way to keep specializations
1260 // from being visible?
1261 if (isa<ClassTemplateSpecializationDecl>(D))
1263 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1264 if (FD->isFunctionTemplateSpecialization())
1270 /// buildLookup - Build the lookup data structure with all of the
1271 /// declarations in this DeclContext (and any other contexts linked
1272 /// to it or transparent contexts nested within it) and return it.
1274 /// Note that the produced map may miss out declarations from an
1275 /// external source. If it does, those entries will be marked with
1276 /// the 'hasExternalDecls' flag.
1277 StoredDeclsMap *DeclContext::buildLookup() {
1278 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1280 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1283 SmallVector<DeclContext *, 2> Contexts;
1284 collectAllContexts(Contexts);
1286 if (HasLazyExternalLexicalLookups) {
1287 HasLazyExternalLexicalLookups = false;
1288 for (auto *DC : Contexts) {
1289 if (DC->hasExternalLexicalStorage())
1290 HasLazyLocalLexicalLookups |=
1291 DC->LoadLexicalDeclsFromExternalStorage();
1294 if (!HasLazyLocalLexicalLookups)
1298 for (auto *DC : Contexts)
1299 buildLookupImpl(DC, hasExternalVisibleStorage());
1301 // We no longer have any lazy decls.
1302 HasLazyLocalLexicalLookups = false;
1306 /// buildLookupImpl - Build part of the lookup data structure for the
1307 /// declarations contained within DCtx, which will either be this
1308 /// DeclContext, a DeclContext linked to it, or a transparent context
1309 /// nested within it.
1310 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1311 for (Decl *D : DCtx->noload_decls()) {
1312 // Insert this declaration into the lookup structure, but only if
1313 // it's semantically within its decl context. Any other decls which
1314 // should be found in this context are added eagerly.
1316 // If it's from an AST file, don't add it now. It'll get handled by
1317 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1318 // in C++, we do not track external visible decls for the TU, so in
1319 // that case we need to collect them all here.
1320 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1321 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1322 (!ND->isFromASTFile() ||
1323 (isTranslationUnit() &&
1324 !getParentASTContext().getLangOpts().CPlusPlus)))
1325 makeDeclVisibleInContextImpl(ND, Internal);
1327 // If this declaration is itself a transparent declaration context
1328 // or inline namespace, add the members of this declaration of that
1329 // context (recursively).
1330 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1331 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1332 buildLookupImpl(InnerCtx, Internal);
1336 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1338 DeclContext::lookup_result
1339 DeclContext::lookup(DeclarationName Name) const {
1340 assert(DeclKind != Decl::LinkageSpec &&
1341 "Should not perform lookups into linkage specs!");
1343 const DeclContext *PrimaryContext = getPrimaryContext();
1344 if (PrimaryContext != this)
1345 return PrimaryContext->lookup(Name);
1347 // If we have an external source, ensure that any later redeclarations of this
1348 // context have been loaded, since they may add names to the result of this
1349 // lookup (or add external visible storage).
1350 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1352 (void)cast<Decl>(this)->getMostRecentDecl();
1354 if (hasExternalVisibleStorage()) {
1355 assert(Source && "external visible storage but no external source?");
1357 if (NeedToReconcileExternalVisibleStorage)
1358 reconcileExternalVisibleStorage();
1360 StoredDeclsMap *Map = LookupPtr;
1362 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1363 // FIXME: Make buildLookup const?
1364 Map = const_cast<DeclContext*>(this)->buildLookup();
1367 Map = CreateStoredDeclsMap(getParentASTContext());
1369 // If we have a lookup result with no external decls, we are done.
1370 std::pair<StoredDeclsMap::iterator, bool> R =
1371 Map->insert(std::make_pair(Name, StoredDeclsList()));
1372 if (!R.second && !R.first->second.hasExternalDecls())
1373 return R.first->second.getLookupResult();
1375 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1376 if (StoredDeclsMap *Map = LookupPtr) {
1377 StoredDeclsMap::iterator I = Map->find(Name);
1378 if (I != Map->end())
1379 return I->second.getLookupResult();
1383 return lookup_result();
1386 StoredDeclsMap *Map = LookupPtr;
1387 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1388 Map = const_cast<DeclContext*>(this)->buildLookup();
1391 return lookup_result();
1393 StoredDeclsMap::iterator I = Map->find(Name);
1394 if (I == Map->end())
1395 return lookup_result();
1397 return I->second.getLookupResult();
1400 DeclContext::lookup_result
1401 DeclContext::noload_lookup(DeclarationName Name) {
1402 assert(DeclKind != Decl::LinkageSpec &&
1403 "Should not perform lookups into linkage specs!");
1405 DeclContext *PrimaryContext = getPrimaryContext();
1406 if (PrimaryContext != this)
1407 return PrimaryContext->noload_lookup(Name);
1409 // If we have any lazy lexical declarations not in our lookup map, add them
1410 // now. Don't import any external declarations, not even if we know we have
1411 // some missing from the external visible lookups.
1412 if (HasLazyLocalLexicalLookups) {
1413 SmallVector<DeclContext *, 2> Contexts;
1414 collectAllContexts(Contexts);
1415 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1416 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1417 HasLazyLocalLexicalLookups = false;
1420 StoredDeclsMap *Map = LookupPtr;
1422 return lookup_result();
1424 StoredDeclsMap::iterator I = Map->find(Name);
1425 return I != Map->end() ? I->second.getLookupResult()
1429 void DeclContext::localUncachedLookup(DeclarationName Name,
1430 SmallVectorImpl<NamedDecl *> &Results) {
1433 // If there's no external storage, just perform a normal lookup and copy
1435 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1436 lookup_result LookupResults = lookup(Name);
1437 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1441 // If we have a lookup table, check there first. Maybe we'll get lucky.
1442 // FIXME: Should we be checking these flags on the primary context?
1443 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1444 if (StoredDeclsMap *Map = LookupPtr) {
1445 StoredDeclsMap::iterator Pos = Map->find(Name);
1446 if (Pos != Map->end()) {
1447 Results.insert(Results.end(),
1448 Pos->second.getLookupResult().begin(),
1449 Pos->second.getLookupResult().end());
1455 // Slow case: grovel through the declarations in our chain looking for
1457 // FIXME: If we have lazy external declarations, this will not find them!
1458 // FIXME: Should we CollectAllContexts and walk them all here?
1459 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1460 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1461 if (ND->getDeclName() == Name)
1462 Results.push_back(ND);
1466 DeclContext *DeclContext::getRedeclContext() {
1467 DeclContext *Ctx = this;
1468 // Skip through transparent contexts.
1469 while (Ctx->isTransparentContext())
1470 Ctx = Ctx->getParent();
1474 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1475 DeclContext *Ctx = this;
1476 // Skip through non-namespace, non-translation-unit contexts.
1477 while (!Ctx->isFileContext())
1478 Ctx = Ctx->getParent();
1479 return Ctx->getPrimaryContext();
1482 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1483 // Loop until we find a non-record context.
1484 RecordDecl *OutermostRD = nullptr;
1485 DeclContext *DC = this;
1486 while (DC->isRecord()) {
1487 OutermostRD = cast<RecordDecl>(DC);
1488 DC = DC->getLexicalParent();
1493 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1494 // For non-file contexts, this is equivalent to Equals.
1495 if (!isFileContext())
1496 return O->Equals(this);
1499 if (O->Equals(this))
1502 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1503 if (!NS || !NS->isInline())
1505 O = NS->getParent();
1511 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1512 DeclContext *PrimaryDC = this->getPrimaryContext();
1513 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1514 // If the decl is being added outside of its semantic decl context, we
1515 // need to ensure that we eagerly build the lookup information for it.
1516 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1519 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1521 assert(this == getPrimaryContext() && "expected a primary DC");
1523 // Skip declarations within functions.
1524 if (isFunctionOrMethod())
1527 // Skip declarations which should be invisible to name lookup.
1528 if (shouldBeHidden(D))
1531 // If we already have a lookup data structure, perform the insertion into
1532 // it. If we might have externally-stored decls with this name, look them
1533 // up and perform the insertion. If this decl was declared outside its
1534 // semantic context, buildLookup won't add it, so add it now.
1536 // FIXME: As a performance hack, don't add such decls into the translation
1537 // unit unless we're in C++, since qualified lookup into the TU is never
1539 if (LookupPtr || hasExternalVisibleStorage() ||
1540 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1541 (getParentASTContext().getLangOpts().CPlusPlus ||
1542 !isTranslationUnit()))) {
1543 // If we have lazily omitted any decls, they might have the same name as
1544 // the decl which we are adding, so build a full lookup table before adding
1547 makeDeclVisibleInContextImpl(D, Internal);
1549 HasLazyLocalLexicalLookups = true;
1552 // If we are a transparent context or inline namespace, insert into our
1553 // parent context, too. This operation is recursive.
1554 if (isTransparentContext() || isInlineNamespace())
1555 getParent()->getPrimaryContext()->
1556 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1558 Decl *DCAsDecl = cast<Decl>(this);
1559 // Notify that a decl was made visible unless we are a Tag being defined.
1560 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1561 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1562 L->AddedVisibleDecl(this, D);
1565 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1566 // Find or create the stored declaration map.
1567 StoredDeclsMap *Map = LookupPtr;
1569 ASTContext *C = &getParentASTContext();
1570 Map = CreateStoredDeclsMap(*C);
1573 // If there is an external AST source, load any declarations it knows about
1574 // with this declaration's name.
1575 // If the lookup table contains an entry about this name it means that we
1576 // have already checked the external source.
1578 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1579 if (hasExternalVisibleStorage() &&
1580 Map->find(D->getDeclName()) == Map->end())
1581 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1583 // Insert this declaration into the map.
1584 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1587 // If this is being added as part of loading an external declaration,
1588 // this may not be the only external declaration with this name.
1589 // In this case, we never try to replace an existing declaration; we'll
1590 // handle that when we finalize the list of declarations for this name.
1591 DeclNameEntries.setHasExternalDecls();
1592 DeclNameEntries.AddSubsequentDecl(D);
1596 if (DeclNameEntries.isNull()) {
1597 DeclNameEntries.setOnlyValue(D);
1601 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1602 // This declaration has replaced an existing one for which
1603 // declarationReplaces returns true.
1607 // Put this declaration into the appropriate slot.
1608 DeclNameEntries.AddSubsequentDecl(D);
1611 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1612 return cast<UsingDirectiveDecl>(*I);
1615 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1617 DeclContext::udir_range DeclContext::using_directives() const {
1618 // FIXME: Use something more efficient than normal lookup for using
1619 // directives. In C++, using directives are looked up more than anything else.
1620 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1621 return udir_range(Result.begin(), Result.end());
1624 //===----------------------------------------------------------------------===//
1625 // Creation and Destruction of StoredDeclsMaps. //
1626 //===----------------------------------------------------------------------===//
1628 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1629 assert(!LookupPtr && "context already has a decls map");
1630 assert(getPrimaryContext() == this &&
1631 "creating decls map on non-primary context");
1634 bool Dependent = isDependentContext();
1636 M = new DependentStoredDeclsMap();
1638 M = new StoredDeclsMap();
1639 M->Previous = C.LastSDM;
1640 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1645 void ASTContext::ReleaseDeclContextMaps() {
1646 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1647 // pointer because the subclass doesn't add anything that needs to
1649 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1652 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1654 // Advance the iteration before we invalidate memory.
1655 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1658 delete static_cast<DependentStoredDeclsMap*>(Map);
1662 Map = Next.getPointer();
1663 Dependent = Next.getInt();
1667 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1668 DeclContext *Parent,
1669 const PartialDiagnostic &PDiag) {
1670 assert(Parent->isDependentContext()
1671 && "cannot iterate dependent diagnostics of non-dependent context");
1672 Parent = Parent->getPrimaryContext();
1673 if (!Parent->LookupPtr)
1674 Parent->CreateStoredDeclsMap(C);
1676 DependentStoredDeclsMap *Map =
1677 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1679 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1680 // BumpPtrAllocator, rather than the ASTContext itself.
1681 PartialDiagnostic::Storage *DiagStorage = nullptr;
1682 if (PDiag.hasStorage())
1683 DiagStorage = new (C) PartialDiagnostic::Storage;
1685 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1687 // TODO: Maybe we shouldn't reverse the order during insertion.
1688 DD->NextDiagnostic = Map->FirstDiagnostic;
1689 Map->FirstDiagnostic = DD;