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/Decl.h"
16 #include "clang/AST/DeclContextInternals.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DependentDiagnostic.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/ASTMutationListener.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/Support/raw_ostream.h"
32 using namespace clang;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
39 #define ABSTRACT_DECL(DECL)
40 #include "clang/AST/DeclNodes.inc"
42 static bool StatSwitch = false;
44 const char *Decl::getDeclKindName() const {
46 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
47 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
48 #define ABSTRACT_DECL(DECL)
49 #include "clang/AST/DeclNodes.inc"
53 void Decl::setInvalidDecl(bool Invalid) {
54 InvalidDecl = Invalid;
56 // Defensive maneuver for ill-formed code: we're likely not to make it to
57 // a point where we set the access specifier, so default it to "public"
58 // to avoid triggering asserts elsewhere in the front end.
63 const char *DeclContext::getDeclKindName() const {
65 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
66 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
67 #define ABSTRACT_DECL(DECL)
68 #include "clang/AST/DeclNodes.inc"
72 bool Decl::CollectingStats(bool Enable) {
73 if (Enable) StatSwitch = true;
77 void Decl::PrintStats() {
78 llvm::errs() << "\n*** Decl Stats:\n";
81 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
82 #define ABSTRACT_DECL(DECL)
83 #include "clang/AST/DeclNodes.inc"
84 llvm::errs() << " " << totalDecls << " decls total.\n";
87 #define DECL(DERIVED, BASE) \
88 if (n##DERIVED##s > 0) { \
89 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
90 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
91 << sizeof(DERIVED##Decl) << " each (" \
92 << n##DERIVED##s * sizeof(DERIVED##Decl) \
95 #define ABSTRACT_DECL(DECL)
96 #include "clang/AST/DeclNodes.inc"
98 llvm::errs() << "Total bytes = " << totalBytes << "\n";
101 void Decl::add(Kind k) {
103 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
104 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
105 #define ABSTRACT_DECL(DECL)
106 #include "clang/AST/DeclNodes.inc"
110 bool Decl::isTemplateParameterPack() const {
111 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
112 return TTP->isParameterPack();
113 if (const NonTypeTemplateParmDecl *NTTP
114 = dyn_cast<NonTypeTemplateParmDecl>(this))
115 return NTTP->isParameterPack();
116 if (const TemplateTemplateParmDecl *TTP
117 = dyn_cast<TemplateTemplateParmDecl>(this))
118 return TTP->isParameterPack();
122 bool Decl::isParameterPack() const {
123 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
124 return Parm->isParameterPack();
126 return isTemplateParameterPack();
129 bool Decl::isFunctionOrFunctionTemplate() const {
130 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
131 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
133 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
136 bool Decl::isTemplateDecl() const {
137 return isa<TemplateDecl>(this);
140 const DeclContext *Decl::getParentFunctionOrMethod() const {
141 for (const DeclContext *DC = getDeclContext();
142 DC && !DC->isTranslationUnit() && !DC->isNamespace();
143 DC = DC->getParent())
144 if (DC->isFunctionOrMethod())
151 //===----------------------------------------------------------------------===//
152 // PrettyStackTraceDecl Implementation
153 //===----------------------------------------------------------------------===//
155 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
156 SourceLocation TheLoc = Loc;
157 if (TheLoc.isInvalid() && TheDecl)
158 TheLoc = TheDecl->getLocation();
160 if (TheLoc.isValid()) {
161 TheLoc.print(OS, SM);
167 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
168 OS << " '" << DN->getQualifiedNameAsString() << '\'';
172 //===----------------------------------------------------------------------===//
173 // Decl Implementation
174 //===----------------------------------------------------------------------===//
176 // Out-of-line virtual method providing a home for Decl.
179 void Decl::setDeclContext(DeclContext *DC) {
183 void Decl::setLexicalDeclContext(DeclContext *DC) {
184 if (DC == getLexicalDeclContext())
188 MultipleDC *MDC = new (getASTContext()) MultipleDC();
189 MDC->SemanticDC = getDeclContext();
193 getMultipleDC()->LexicalDC = DC;
197 bool Decl::isInAnonymousNamespace() const {
198 const DeclContext *DC = getDeclContext();
200 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
201 if (ND->isAnonymousNamespace())
203 } while ((DC = DC->getParent()));
208 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
209 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
212 DeclContext *DC = getDeclContext();
213 assert(DC && "This decl is not contained in a translation unit!");
215 while (!DC->isTranslationUnit()) {
216 DC = DC->getParent();
217 assert(DC && "This decl is not contained in a translation unit!");
220 return cast<TranslationUnitDecl>(DC);
223 ASTContext &Decl::getASTContext() const {
224 return getTranslationUnitDecl()->getASTContext();
227 ASTMutationListener *Decl::getASTMutationListener() const {
228 return getASTContext().getASTMutationListener();
231 bool Decl::isUsed(bool CheckUsedAttr) const {
235 // Check for used attribute.
236 if (CheckUsedAttr && hasAttr<UsedAttr>())
239 // Check redeclarations for used attribute.
240 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
241 if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used)
248 bool Decl::isReferenced() const {
252 // Check redeclarations.
253 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
260 /// \brief Determine the availability of the given declaration based on
261 /// the target platform.
263 /// When it returns an availability result other than \c AR_Available,
264 /// if the \p Message parameter is non-NULL, it will be set to a
265 /// string describing why the entity is unavailable.
267 /// FIXME: Make these strings localizable, since they end up in
269 static AvailabilityResult CheckAvailability(ASTContext &Context,
270 const AvailabilityAttr *A,
271 std::string *Message) {
272 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
273 StringRef PrettyPlatformName
274 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
275 if (PrettyPlatformName.empty())
276 PrettyPlatformName = TargetPlatform;
278 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
279 if (TargetMinVersion.empty())
282 // Match the platform name.
283 if (A->getPlatform()->getName() != TargetPlatform)
286 // Make sure that this declaration has not been marked 'unavailable'.
287 if (A->getUnavailable()) {
290 llvm::raw_string_ostream Out(*Message);
291 Out << "not available on " << PrettyPlatformName;
294 return AR_Unavailable;
297 // Make sure that this declaration has already been introduced.
298 if (!A->getIntroduced().empty() &&
299 TargetMinVersion < A->getIntroduced()) {
302 llvm::raw_string_ostream Out(*Message);
303 Out << "introduced in " << PrettyPlatformName << ' '
304 << A->getIntroduced();
307 return AR_NotYetIntroduced;
310 // Make sure that this declaration hasn't been obsoleted.
311 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
314 llvm::raw_string_ostream Out(*Message);
315 Out << "obsoleted in " << PrettyPlatformName << ' '
316 << A->getObsoleted();
319 return AR_Unavailable;
322 // Make sure that this declaration hasn't been deprecated.
323 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
326 llvm::raw_string_ostream Out(*Message);
327 Out << "first deprecated in " << PrettyPlatformName << ' '
328 << A->getDeprecated();
331 return AR_Deprecated;
337 AvailabilityResult Decl::getAvailability(std::string *Message) const {
338 AvailabilityResult Result = AR_Available;
339 std::string ResultMessage;
341 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
342 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
343 if (Result >= AR_Deprecated)
347 ResultMessage = Deprecated->getMessage();
349 Result = AR_Deprecated;
353 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
355 *Message = Unavailable->getMessage();
356 return AR_Unavailable;
359 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
360 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
363 if (AR == AR_Unavailable)
364 return AR_Unavailable;
369 ResultMessage.swap(*Message);
376 Message->swap(ResultMessage);
380 bool Decl::canBeWeakImported(bool &IsDefinition) const {
381 IsDefinition = false;
382 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
383 if (!Var->hasExternalStorage() || Var->getInit()) {
387 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
392 } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this))
394 else if (!(getASTContext().getLangOptions().ObjCNonFragileABI &&
395 isa<ObjCInterfaceDecl>(this)))
401 bool Decl::isWeakImported() const {
403 if (!canBeWeakImported(IsDefinition))
406 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
407 if (isa<WeakImportAttr>(*A))
410 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
411 if (CheckAvailability(getASTContext(), Availability, 0)
412 == AR_NotYetIntroduced)
420 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
431 case NonTypeTemplateParm:
434 return IDNS_Ordinary;
438 return IDNS_Ordinary | IDNS_Member;
440 case ObjCCompatibleAlias:
442 return IDNS_Ordinary | IDNS_Type;
446 case TypeAliasTemplate:
447 case UnresolvedUsingTypename:
448 case TemplateTypeParm:
449 return IDNS_Ordinary | IDNS_Type;
452 return 0; // we'll actually overwrite this later
454 case UnresolvedUsingValue:
455 return IDNS_Ordinary | IDNS_Using;
461 return IDNS_ObjCProtocol;
464 case ObjCAtDefsField:
471 return IDNS_Tag | IDNS_Type;
475 return IDNS_Namespace;
477 case FunctionTemplate:
478 return IDNS_Ordinary;
481 case TemplateTemplateParm:
482 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
492 case ObjCPropertyImpl:
493 case ObjCForwardProtocol:
495 case TranslationUnit:
498 case ClassTemplateSpecialization:
499 case ClassTemplatePartialSpecialization:
500 case ClassScopeFunctionSpecialization:
501 case ObjCImplementation:
503 case ObjCCategoryImpl:
504 // Never looked up by name.
511 void Decl::setAttrs(const AttrVec &attrs) {
512 assert(!HasAttrs && "Decl already contains attrs.");
514 AttrVec &AttrBlank = getASTContext().getDeclAttrs(this);
515 assert(AttrBlank.empty() && "HasAttrs was wrong?");
521 void Decl::dropAttrs() {
522 if (!HasAttrs) return;
525 getASTContext().eraseDeclAttrs(this);
528 const AttrVec &Decl::getAttrs() const {
529 assert(HasAttrs && "No attrs to get!");
530 return getASTContext().getDeclAttrs(this);
533 void Decl::swapAttrs(Decl *RHS) {
534 bool HasLHSAttr = this->HasAttrs;
535 bool HasRHSAttr = RHS->HasAttrs;
537 // Usually, neither decl has attrs, nothing to do.
538 if (!HasLHSAttr && !HasRHSAttr) return;
540 // If 'this' has no attrs, swap the other way.
542 return RHS->swapAttrs(this);
544 ASTContext &Context = getASTContext();
546 // Handle the case when both decls have attrs.
548 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
552 // Otherwise, LHS has an attr and RHS doesn't.
553 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
554 Context.eraseDeclAttrs(this);
555 this->HasAttrs = false;
556 RHS->HasAttrs = true;
559 Decl *Decl::castFromDeclContext (const DeclContext *D) {
560 Decl::Kind DK = D->getDeclKind();
562 #define DECL(NAME, BASE)
563 #define DECL_CONTEXT(NAME) \
565 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
566 #define DECL_CONTEXT_BASE(NAME)
567 #include "clang/AST/DeclNodes.inc"
569 #define DECL(NAME, BASE)
570 #define DECL_CONTEXT_BASE(NAME) \
571 if (DK >= first##NAME && DK <= last##NAME) \
572 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
573 #include "clang/AST/DeclNodes.inc"
574 llvm_unreachable("a decl that inherits DeclContext isn't handled");
578 DeclContext *Decl::castToDeclContext(const Decl *D) {
579 Decl::Kind DK = D->getKind();
581 #define DECL(NAME, BASE)
582 #define DECL_CONTEXT(NAME) \
584 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
585 #define DECL_CONTEXT_BASE(NAME)
586 #include "clang/AST/DeclNodes.inc"
588 #define DECL(NAME, BASE)
589 #define DECL_CONTEXT_BASE(NAME) \
590 if (DK >= first##NAME && DK <= last##NAME) \
591 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
592 #include "clang/AST/DeclNodes.inc"
593 llvm_unreachable("a decl that inherits DeclContext isn't handled");
597 SourceLocation Decl::getBodyRBrace() const {
598 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
599 // FunctionDecl stores EndRangeLoc for this purpose.
600 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
601 const FunctionDecl *Definition;
602 if (FD->hasBody(Definition))
603 return Definition->getSourceRange().getEnd();
604 return SourceLocation();
607 if (Stmt *Body = getBody())
608 return Body->getSourceRange().getEnd();
610 return SourceLocation();
613 void Decl::CheckAccessDeclContext() const {
615 // Suppress this check if any of the following hold:
616 // 1. this is the translation unit (and thus has no parent)
617 // 2. this is a template parameter (and thus doesn't belong to its context)
618 // 3. this is a non-type template parameter
619 // 4. the context is not a record
621 // 6. it's a C++0x static_assert.
622 if (isa<TranslationUnitDecl>(this) ||
623 isa<TemplateTypeParmDecl>(this) ||
624 isa<NonTypeTemplateParmDecl>(this) ||
625 !isa<CXXRecordDecl>(getDeclContext()) ||
627 isa<StaticAssertDecl>(this) ||
628 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
629 // as DeclContext (?).
630 isa<ParmVarDecl>(this) ||
631 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
632 // AS_none as access specifier.
633 isa<CXXRecordDecl>(this) ||
634 isa<ClassScopeFunctionSpecializationDecl>(this))
637 assert(Access != AS_none &&
638 "Access specifier is AS_none inside a record decl");
642 DeclContext *Decl::getNonClosureContext() {
643 DeclContext *DC = getDeclContext();
645 // This is basically "while (DC->isClosure()) DC = DC->getParent();"
646 // except that it's significantly more efficient to cast to a known
647 // decl type and call getDeclContext() than to call getParent().
648 while (isa<BlockDecl>(DC))
649 DC = cast<BlockDecl>(DC)->getDeclContext();
651 assert(!DC->isClosure());
655 //===----------------------------------------------------------------------===//
656 // DeclContext Implementation
657 //===----------------------------------------------------------------------===//
659 bool DeclContext::classof(const Decl *D) {
660 switch (D->getKind()) {
661 #define DECL(NAME, BASE)
662 #define DECL_CONTEXT(NAME) case Decl::NAME:
663 #define DECL_CONTEXT_BASE(NAME)
664 #include "clang/AST/DeclNodes.inc"
667 #define DECL(NAME, BASE)
668 #define DECL_CONTEXT_BASE(NAME) \
669 if (D->getKind() >= Decl::first##NAME && \
670 D->getKind() <= Decl::last##NAME) \
672 #include "clang/AST/DeclNodes.inc"
677 DeclContext::~DeclContext() { }
679 /// \brief Find the parent context of this context that will be
680 /// used for unqualified name lookup.
682 /// Generally, the parent lookup context is the semantic context. However, for
683 /// a friend function the parent lookup context is the lexical context, which
684 /// is the class in which the friend is declared.
685 DeclContext *DeclContext::getLookupParent() {
686 // FIXME: Find a better way to identify friends
687 if (isa<FunctionDecl>(this))
688 if (getParent()->getRedeclContext()->isFileContext() &&
689 getLexicalParent()->getRedeclContext()->isRecord())
690 return getLexicalParent();
695 bool DeclContext::isInlineNamespace() const {
696 return isNamespace() &&
697 cast<NamespaceDecl>(this)->isInline();
700 bool DeclContext::isDependentContext() const {
704 if (isa<ClassTemplatePartialSpecializationDecl>(this))
707 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
708 if (Record->getDescribedClassTemplate())
711 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
712 if (Function->getDescribedFunctionTemplate())
715 // Friend function declarations are dependent if their *lexical*
716 // context is dependent.
717 if (cast<Decl>(this)->getFriendObjectKind())
718 return getLexicalParent()->isDependentContext();
721 return getParent() && getParent()->isDependentContext();
724 bool DeclContext::isTransparentContext() const {
725 if (DeclKind == Decl::Enum)
726 return !cast<EnumDecl>(this)->isScoped();
727 else if (DeclKind == Decl::LinkageSpec)
733 bool DeclContext::isExternCContext() const {
734 const DeclContext *DC = this;
735 while (DC->DeclKind != Decl::TranslationUnit) {
736 if (DC->DeclKind == Decl::LinkageSpec)
737 return cast<LinkageSpecDecl>(DC)->getLanguage()
738 == LinkageSpecDecl::lang_c;
739 DC = DC->getParent();
744 bool DeclContext::Encloses(const DeclContext *DC) const {
745 if (getPrimaryContext() != this)
746 return getPrimaryContext()->Encloses(DC);
748 for (; DC; DC = DC->getParent())
749 if (DC->getPrimaryContext() == this)
754 DeclContext *DeclContext::getPrimaryContext() {
756 case Decl::TranslationUnit:
757 case Decl::LinkageSpec:
759 // There is only one DeclContext for these entities.
762 case Decl::Namespace:
763 // The original namespace is our primary context.
764 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
766 case Decl::ObjCMethod:
769 case Decl::ObjCInterface:
770 case Decl::ObjCProtocol:
771 case Decl::ObjCCategory:
772 // FIXME: Can Objective-C interfaces be forward-declared?
775 case Decl::ObjCImplementation:
776 case Decl::ObjCCategoryImpl:
780 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
781 // If this is a tag type that has a definition or is currently
782 // being defined, that definition is our primary context.
783 TagDecl *Tag = cast<TagDecl>(this);
784 assert(isa<TagType>(Tag->TypeForDecl) ||
785 isa<InjectedClassNameType>(Tag->TypeForDecl));
787 if (TagDecl *Def = Tag->getDefinition())
790 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
791 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
792 if (TagTy->isBeingDefined())
793 // FIXME: is it necessarily being defined in the decl
794 // that owns the type?
795 return TagTy->getDecl();
801 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
802 "Unknown DeclContext kind");
807 DeclContext *DeclContext::getNextContext() {
809 case Decl::Namespace:
810 // Return the next namespace
811 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
818 std::pair<Decl *, Decl *>
819 DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls,
820 bool FieldsAlreadyLoaded) {
821 // Build up a chain of declarations via the Decl::NextDeclInContext field.
822 Decl *FirstNewDecl = 0;
824 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
825 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
830 PrevDecl->NextDeclInContext = D;
837 return std::make_pair(FirstNewDecl, PrevDecl);
840 /// \brief Load the declarations within this lexical storage from an
843 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
844 ExternalASTSource *Source = getParentASTContext().getExternalSource();
845 assert(hasExternalLexicalStorage() && Source && "No external storage?");
847 // Notify that we have a DeclContext that is initializing.
848 ExternalASTSource::Deserializing ADeclContext(Source);
850 // Load the external declarations, if any.
851 SmallVector<Decl*, 64> Decls;
852 ExternalLexicalStorage = false;
853 switch (Source->FindExternalLexicalDecls(this, Decls)) {
858 case ELR_AlreadyLoaded:
865 // We may have already loaded just the fields of this record, in which case
866 // we need to ignore them.
867 bool FieldsAlreadyLoaded = false;
868 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
869 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
871 // Splice the newly-read declarations into the beginning of the list
873 Decl *ExternalFirst, *ExternalLast;
874 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
875 FieldsAlreadyLoaded);
876 ExternalLast->NextDeclInContext = FirstDecl;
877 FirstDecl = ExternalFirst;
879 LastDecl = ExternalLast;
882 DeclContext::lookup_result
883 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
884 DeclarationName Name) {
885 ASTContext &Context = DC->getParentASTContext();
887 if (!(Map = DC->LookupPtr))
888 Map = DC->CreateStoredDeclsMap(Context);
890 StoredDeclsList &List = (*Map)[Name];
891 assert(List.isNull());
894 return DeclContext::lookup_result();
897 DeclContext::lookup_result
898 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
899 DeclarationName Name,
900 ArrayRef<NamedDecl*> Decls) {
901 ASTContext &Context = DC->getParentASTContext();;
904 if (!(Map = DC->LookupPtr))
905 Map = DC->CreateStoredDeclsMap(Context);
907 StoredDeclsList &List = (*Map)[Name];
908 for (ArrayRef<NamedDecl*>::iterator
909 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
911 List.setOnlyValue(*I);
913 List.AddSubsequentDecl(*I);
916 return List.getLookupResult();
919 DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
920 return decl_iterator(FirstDecl);
923 DeclContext::decl_iterator DeclContext::noload_decls_end() const {
924 return decl_iterator();
927 DeclContext::decl_iterator DeclContext::decls_begin() const {
928 if (hasExternalLexicalStorage())
929 LoadLexicalDeclsFromExternalStorage();
931 return decl_iterator(FirstDecl);
934 DeclContext::decl_iterator DeclContext::decls_end() const {
935 if (hasExternalLexicalStorage())
936 LoadLexicalDeclsFromExternalStorage();
938 return decl_iterator();
941 bool DeclContext::decls_empty() const {
942 if (hasExternalLexicalStorage())
943 LoadLexicalDeclsFromExternalStorage();
948 void DeclContext::removeDecl(Decl *D) {
949 assert(D->getLexicalDeclContext() == this &&
950 "decl being removed from non-lexical context");
951 assert((D->NextDeclInContext || D == LastDecl) &&
952 "decl is not in decls list");
954 // Remove D from the decl chain. This is O(n) but hopefully rare.
955 if (D == FirstDecl) {
957 FirstDecl = LastDecl = 0;
959 FirstDecl = D->NextDeclInContext;
961 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) {
962 assert(I && "decl not found in linked list");
963 if (I->NextDeclInContext == D) {
964 I->NextDeclInContext = D->NextDeclInContext;
965 if (D == LastDecl) LastDecl = I;
971 // Mark that D is no longer in the decl chain.
972 D->NextDeclInContext = 0;
974 // Remove D from the lookup table if necessary.
975 if (isa<NamedDecl>(D)) {
976 NamedDecl *ND = cast<NamedDecl>(D);
978 // Remove only decls that have a name
979 if (!ND->getDeclName()) return;
981 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
984 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
985 assert(Pos != Map->end() && "no lookup entry for decl");
986 Pos->second.remove(ND);
990 void DeclContext::addHiddenDecl(Decl *D) {
991 assert(D->getLexicalDeclContext() == this &&
992 "Decl inserted into wrong lexical context");
993 assert(!D->getNextDeclInContext() && D != LastDecl &&
994 "Decl already inserted into a DeclContext");
997 LastDecl->NextDeclInContext = D;
1000 FirstDecl = LastDecl = D;
1003 // Notify a C++ record declaration that we've added a member, so it can
1004 // update it's class-specific state.
1005 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1006 Record->addedMember(D);
1009 void DeclContext::addDecl(Decl *D) {
1012 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1013 ND->getDeclContext()->makeDeclVisibleInContext(ND);
1016 /// buildLookup - Build the lookup data structure with all of the
1017 /// declarations in DCtx (and any other contexts linked to it or
1018 /// transparent contexts nested within it).
1019 void DeclContext::buildLookup(DeclContext *DCtx) {
1020 for (; DCtx; DCtx = DCtx->getNextContext()) {
1021 for (decl_iterator D = DCtx->decls_begin(),
1022 DEnd = DCtx->decls_end();
1024 // Insert this declaration into the lookup structure, but only
1025 // if it's semantically in its decl context. During non-lazy
1026 // lookup building, this is implicitly enforced by addDecl.
1027 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
1028 if (D->getDeclContext() == DCtx)
1029 makeDeclVisibleInContextImpl(ND);
1031 // Insert any forward-declared Objective-C interface into the lookup
1033 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D))
1034 makeDeclVisibleInContextImpl(Class->getForwardInterfaceDecl());
1036 // If this declaration is itself a transparent declaration context or
1037 // inline namespace, add its members (recursively).
1038 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
1039 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1040 buildLookup(InnerCtx->getPrimaryContext());
1045 DeclContext::lookup_result
1046 DeclContext::lookup(DeclarationName Name) {
1047 DeclContext *PrimaryContext = getPrimaryContext();
1048 if (PrimaryContext != this)
1049 return PrimaryContext->lookup(Name);
1051 if (hasExternalVisibleStorage()) {
1052 // Check to see if we've already cached the lookup results.
1054 StoredDeclsMap::iterator I = LookupPtr->find(Name);
1055 if (I != LookupPtr->end())
1056 return I->second.getLookupResult();
1059 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1060 return Source->FindExternalVisibleDeclsByName(this, Name);
1063 /// If there is no lookup data structure, build one now by walking
1064 /// all of the linked DeclContexts (in declaration order!) and
1065 /// inserting their values.
1070 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1073 StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1074 if (Pos == LookupPtr->end())
1075 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1076 return Pos->second.getLookupResult();
1079 DeclContext::lookup_const_result
1080 DeclContext::lookup(DeclarationName Name) const {
1081 return const_cast<DeclContext*>(this)->lookup(Name);
1084 void DeclContext::localUncachedLookup(DeclarationName Name,
1085 llvm::SmallVectorImpl<NamedDecl *> &Results) {
1088 // If there's no external storage, just perform a normal lookup and copy
1090 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage()) {
1091 lookup_result LookupResults = lookup(Name);
1092 Results.insert(Results.end(), LookupResults.first, LookupResults.second);
1096 // If we have a lookup table, check there first. Maybe we'll get lucky.
1098 StoredDeclsMap::iterator Pos = LookupPtr->find(Name);
1099 if (Pos != LookupPtr->end()) {
1100 Results.insert(Results.end(),
1101 Pos->second.getLookupResult().first,
1102 Pos->second.getLookupResult().second);
1107 // Slow case: grovel through the declarations in our chain looking for
1109 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1110 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1111 if (ND->getDeclName() == Name)
1112 Results.push_back(ND);
1116 DeclContext *DeclContext::getRedeclContext() {
1117 DeclContext *Ctx = this;
1118 // Skip through transparent contexts.
1119 while (Ctx->isTransparentContext())
1120 Ctx = Ctx->getParent();
1124 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1125 DeclContext *Ctx = this;
1126 // Skip through non-namespace, non-translation-unit contexts.
1127 while (!Ctx->isFileContext())
1128 Ctx = Ctx->getParent();
1129 return Ctx->getPrimaryContext();
1132 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1133 // For non-file contexts, this is equivalent to Equals.
1134 if (!isFileContext())
1135 return O->Equals(this);
1138 if (O->Equals(this))
1141 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1142 if (!NS || !NS->isInline())
1144 O = NS->getParent();
1150 void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) {
1151 // FIXME: This feels like a hack. Should DeclarationName support
1152 // template-ids, or is there a better way to keep specializations
1153 // from being visible?
1154 if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter())
1156 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1157 if (FD->isFunctionTemplateSpecialization())
1160 DeclContext *PrimaryContext = getPrimaryContext();
1161 if (PrimaryContext != this) {
1162 PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
1166 // If we already have a lookup data structure, perform the insertion
1167 // into it. If we haven't deserialized externally stored decls, deserialize
1168 // them so we can add the decl. Otherwise, be lazy and don't build that
1169 // structure until someone asks for it.
1170 if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
1171 makeDeclVisibleInContextImpl(D);
1173 // If we are a transparent context or inline namespace, insert into our
1174 // parent context, too. This operation is recursive.
1175 if (isTransparentContext() || isInlineNamespace())
1176 getParent()->makeDeclVisibleInContext(D, Recoverable);
1178 Decl *DCAsDecl = cast<Decl>(this);
1179 // Notify that a decl was made visible unless it's a Tag being defined.
1180 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1181 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1182 L->AddedVisibleDecl(this, D);
1185 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
1186 // Skip unnamed declarations.
1187 if (!D->getDeclName())
1190 // Skip entities that can't be found by name lookup into a particular
1192 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1193 D->isTemplateParameter())
1198 C = &getParentASTContext();
1199 CreateStoredDeclsMap(*C);
1202 // If there is an external AST source, load any declarations it knows about
1203 // with this declaration's name.
1204 // If the lookup table contains an entry about this name it means that we
1205 // have already checked the external source.
1206 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1207 if (hasExternalVisibleStorage() &&
1208 LookupPtr->find(D->getDeclName()) == LookupPtr->end())
1209 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1211 // Insert this declaration into the map.
1212 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()];
1213 if (DeclNameEntries.isNull()) {
1214 DeclNameEntries.setOnlyValue(D);
1218 // If it is possible that this is a redeclaration, check to see if there is
1219 // already a decl for which declarationReplaces returns true. If there is
1220 // one, just replace it and return.
1221 if (DeclNameEntries.HandleRedeclaration(D))
1224 // Put this declaration into the appropriate slot.
1225 DeclNameEntries.AddSubsequentDecl(D);
1228 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1230 DeclContext::udir_iterator_range
1231 DeclContext::getUsingDirectives() const {
1232 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1233 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1234 reinterpret_cast<udir_iterator>(Result.second));
1237 //===----------------------------------------------------------------------===//
1238 // Creation and Destruction of StoredDeclsMaps. //
1239 //===----------------------------------------------------------------------===//
1241 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1242 assert(!LookupPtr && "context already has a decls map");
1243 assert(getPrimaryContext() == this &&
1244 "creating decls map on non-primary context");
1247 bool Dependent = isDependentContext();
1249 M = new DependentStoredDeclsMap();
1251 M = new StoredDeclsMap();
1252 M->Previous = C.LastSDM;
1253 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1258 void ASTContext::ReleaseDeclContextMaps() {
1259 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1260 // pointer because the subclass doesn't add anything that needs to
1262 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1265 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1267 // Advance the iteration before we invalidate memory.
1268 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1271 delete static_cast<DependentStoredDeclsMap*>(Map);
1275 Map = Next.getPointer();
1276 Dependent = Next.getInt();
1280 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1281 DeclContext *Parent,
1282 const PartialDiagnostic &PDiag) {
1283 assert(Parent->isDependentContext()
1284 && "cannot iterate dependent diagnostics of non-dependent context");
1285 Parent = Parent->getPrimaryContext();
1286 if (!Parent->LookupPtr)
1287 Parent->CreateStoredDeclsMap(C);
1289 DependentStoredDeclsMap *Map
1290 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
1292 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1293 // BumpPtrAllocator, rather than the ASTContext itself.
1294 PartialDiagnostic::Storage *DiagStorage = 0;
1295 if (PDiag.hasStorage())
1296 DiagStorage = new (C) PartialDiagnostic::Storage;
1298 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1300 // TODO: Maybe we shouldn't reverse the order during insertion.
1301 DD->NextDiagnostic = Map->FirstDiagnostic;
1302 Map->FirstDiagnostic = DD;