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 void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
45 // Allocate an extra 8 bytes worth of storage, which ensures that the
46 // resulting pointer will still be 8-byte aligned.
47 void *Start = Context.Allocate(Size + 8);
48 void *Result = (char*)Start + 8;
50 unsigned *PrefixPtr = (unsigned *)Result - 2;
52 // Zero out the first 4 bytes; this is used to store the owning module ID.
55 // Store the global declaration ID in the second 4 bytes.
61 const char *Decl::getDeclKindName() const {
63 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
64 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
65 #define ABSTRACT_DECL(DECL)
66 #include "clang/AST/DeclNodes.inc"
70 void Decl::setInvalidDecl(bool Invalid) {
71 InvalidDecl = Invalid;
72 if (Invalid && !isa<ParmVarDecl>(this)) {
73 // Defensive maneuver for ill-formed code: we're likely not to make it to
74 // a point where we set the access specifier, so default it to "public"
75 // to avoid triggering asserts elsewhere in the front end.
80 const char *DeclContext::getDeclKindName() const {
82 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
83 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
84 #define ABSTRACT_DECL(DECL)
85 #include "clang/AST/DeclNodes.inc"
89 bool Decl::StatisticsEnabled = false;
90 void Decl::EnableStatistics() {
91 StatisticsEnabled = true;
94 void Decl::PrintStats() {
95 llvm::errs() << "\n*** Decl Stats:\n";
98 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
99 #define ABSTRACT_DECL(DECL)
100 #include "clang/AST/DeclNodes.inc"
101 llvm::errs() << " " << totalDecls << " decls total.\n";
104 #define DECL(DERIVED, BASE) \
105 if (n##DERIVED##s > 0) { \
106 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
107 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
108 << sizeof(DERIVED##Decl) << " each (" \
109 << n##DERIVED##s * sizeof(DERIVED##Decl) \
112 #define ABSTRACT_DECL(DECL)
113 #include "clang/AST/DeclNodes.inc"
115 llvm::errs() << "Total bytes = " << totalBytes << "\n";
118 void Decl::add(Kind k) {
120 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
121 #define ABSTRACT_DECL(DECL)
122 #include "clang/AST/DeclNodes.inc"
126 bool Decl::isTemplateParameterPack() const {
127 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
128 return TTP->isParameterPack();
129 if (const NonTypeTemplateParmDecl *NTTP
130 = dyn_cast<NonTypeTemplateParmDecl>(this))
131 return NTTP->isParameterPack();
132 if (const TemplateTemplateParmDecl *TTP
133 = dyn_cast<TemplateTemplateParmDecl>(this))
134 return TTP->isParameterPack();
138 bool Decl::isParameterPack() const {
139 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
140 return Parm->isParameterPack();
142 return isTemplateParameterPack();
145 bool Decl::isFunctionOrFunctionTemplate() const {
146 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
147 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
149 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
152 bool Decl::isTemplateDecl() const {
153 return isa<TemplateDecl>(this);
156 const DeclContext *Decl::getParentFunctionOrMethod() const {
157 for (const DeclContext *DC = getDeclContext();
158 DC && !DC->isTranslationUnit() && !DC->isNamespace();
159 DC = DC->getParent())
160 if (DC->isFunctionOrMethod())
167 //===----------------------------------------------------------------------===//
168 // PrettyStackTraceDecl Implementation
169 //===----------------------------------------------------------------------===//
171 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
172 SourceLocation TheLoc = Loc;
173 if (TheLoc.isInvalid() && TheDecl)
174 TheLoc = TheDecl->getLocation();
176 if (TheLoc.isValid()) {
177 TheLoc.print(OS, SM);
183 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
184 OS << " '" << DN->getQualifiedNameAsString() << '\'';
188 //===----------------------------------------------------------------------===//
189 // Decl Implementation
190 //===----------------------------------------------------------------------===//
192 // Out-of-line virtual method providing a home for Decl.
195 void Decl::setDeclContext(DeclContext *DC) {
199 void Decl::setLexicalDeclContext(DeclContext *DC) {
200 if (DC == getLexicalDeclContext())
204 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
206 getMultipleDC()->LexicalDC = DC;
210 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
212 if (SemaDC == LexicalDC) {
215 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
216 MDC->SemanticDC = SemaDC;
217 MDC->LexicalDC = LexicalDC;
222 bool Decl::isInAnonymousNamespace() const {
223 const DeclContext *DC = getDeclContext();
225 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
226 if (ND->isAnonymousNamespace())
228 } while ((DC = DC->getParent()));
233 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
234 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
237 DeclContext *DC = getDeclContext();
238 assert(DC && "This decl is not contained in a translation unit!");
240 while (!DC->isTranslationUnit()) {
241 DC = DC->getParent();
242 assert(DC && "This decl is not contained in a translation unit!");
245 return cast<TranslationUnitDecl>(DC);
248 ASTContext &Decl::getASTContext() const {
249 return getTranslationUnitDecl()->getASTContext();
252 ASTMutationListener *Decl::getASTMutationListener() const {
253 return getASTContext().getASTMutationListener();
256 bool Decl::isUsed(bool CheckUsedAttr) const {
260 // Check for used attribute.
261 if (CheckUsedAttr && hasAttr<UsedAttr>())
264 // Check redeclarations for used attribute.
265 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
266 if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used)
273 bool Decl::isReferenced() const {
277 // Check redeclarations.
278 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
285 /// \brief Determine the availability of the given declaration based on
286 /// the target platform.
288 /// When it returns an availability result other than \c AR_Available,
289 /// if the \p Message parameter is non-NULL, it will be set to a
290 /// string describing why the entity is unavailable.
292 /// FIXME: Make these strings localizable, since they end up in
294 static AvailabilityResult CheckAvailability(ASTContext &Context,
295 const AvailabilityAttr *A,
296 std::string *Message) {
297 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
298 StringRef PrettyPlatformName
299 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
300 if (PrettyPlatformName.empty())
301 PrettyPlatformName = TargetPlatform;
303 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
304 if (TargetMinVersion.empty())
307 // Match the platform name.
308 if (A->getPlatform()->getName() != TargetPlatform)
311 std::string HintMessage;
312 if (!A->getMessage().empty()) {
314 HintMessage += A->getMessage();
317 // Make sure that this declaration has not been marked 'unavailable'.
318 if (A->getUnavailable()) {
321 llvm::raw_string_ostream Out(*Message);
322 Out << "not available on " << PrettyPlatformName
326 return AR_Unavailable;
329 // Make sure that this declaration has already been introduced.
330 if (!A->getIntroduced().empty() &&
331 TargetMinVersion < A->getIntroduced()) {
334 llvm::raw_string_ostream Out(*Message);
335 Out << "introduced in " << PrettyPlatformName << ' '
336 << A->getIntroduced() << HintMessage;
339 return AR_NotYetIntroduced;
342 // Make sure that this declaration hasn't been obsoleted.
343 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
346 llvm::raw_string_ostream Out(*Message);
347 Out << "obsoleted in " << PrettyPlatformName << ' '
348 << A->getObsoleted() << HintMessage;
351 return AR_Unavailable;
354 // Make sure that this declaration hasn't been deprecated.
355 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
358 llvm::raw_string_ostream Out(*Message);
359 Out << "first deprecated in " << PrettyPlatformName << ' '
360 << A->getDeprecated() << HintMessage;
363 return AR_Deprecated;
369 AvailabilityResult Decl::getAvailability(std::string *Message) const {
370 AvailabilityResult Result = AR_Available;
371 std::string ResultMessage;
373 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
374 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
375 if (Result >= AR_Deprecated)
379 ResultMessage = Deprecated->getMessage();
381 Result = AR_Deprecated;
385 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
387 *Message = Unavailable->getMessage();
388 return AR_Unavailable;
391 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
392 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
395 if (AR == AR_Unavailable)
396 return AR_Unavailable;
401 ResultMessage.swap(*Message);
408 Message->swap(ResultMessage);
412 bool Decl::canBeWeakImported(bool &IsDefinition) const {
413 IsDefinition = false;
415 // Variables, if they aren't definitions.
416 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
417 if (!Var->hasExternalStorage() || Var->getInit()) {
423 // Functions, if they aren't definitions.
424 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
431 // Objective-C classes, if this is the non-fragile runtime.
432 } else if (isa<ObjCInterfaceDecl>(this) &&
433 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
442 bool Decl::isWeakImported() const {
444 if (!canBeWeakImported(IsDefinition))
447 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
448 if (isa<WeakImportAttr>(*A))
451 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
452 if (CheckAvailability(getASTContext(), Availability, 0)
453 == AR_NotYetIntroduced)
461 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
472 case NonTypeTemplateParm:
475 return IDNS_Ordinary;
479 return IDNS_Ordinary | IDNS_Member;
481 case ObjCCompatibleAlias:
483 return IDNS_Ordinary | IDNS_Type;
487 case TypeAliasTemplate:
488 case UnresolvedUsingTypename:
489 case TemplateTypeParm:
490 return IDNS_Ordinary | IDNS_Type;
493 return 0; // we'll actually overwrite this later
495 case UnresolvedUsingValue:
496 return IDNS_Ordinary | IDNS_Using;
502 return IDNS_ObjCProtocol;
505 case ObjCAtDefsField:
512 return IDNS_Tag | IDNS_Type;
516 return IDNS_Namespace;
518 case FunctionTemplate:
519 return IDNS_Ordinary;
522 case TemplateTemplateParm:
523 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
532 case ObjCPropertyImpl:
534 case TranslationUnit:
537 case ClassTemplateSpecialization:
538 case ClassTemplatePartialSpecialization:
539 case ClassScopeFunctionSpecialization:
540 case ObjCImplementation:
542 case ObjCCategoryImpl:
544 // Never looked up by name.
548 llvm_unreachable("Invalid DeclKind!");
551 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
552 assert(!HasAttrs && "Decl already contains attrs.");
554 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
555 assert(AttrBlank.empty() && "HasAttrs was wrong?");
561 void Decl::dropAttrs() {
562 if (!HasAttrs) return;
565 getASTContext().eraseDeclAttrs(this);
568 const AttrVec &Decl::getAttrs() const {
569 assert(HasAttrs && "No attrs to get!");
570 return getASTContext().getDeclAttrs(this);
573 void Decl::swapAttrs(Decl *RHS) {
574 bool HasLHSAttr = this->HasAttrs;
575 bool HasRHSAttr = RHS->HasAttrs;
577 // Usually, neither decl has attrs, nothing to do.
578 if (!HasLHSAttr && !HasRHSAttr) return;
580 // If 'this' has no attrs, swap the other way.
582 return RHS->swapAttrs(this);
584 ASTContext &Context = getASTContext();
586 // Handle the case when both decls have attrs.
588 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
592 // Otherwise, LHS has an attr and RHS doesn't.
593 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
594 Context.eraseDeclAttrs(this);
595 this->HasAttrs = false;
596 RHS->HasAttrs = true;
599 Decl *Decl::castFromDeclContext (const DeclContext *D) {
600 Decl::Kind DK = D->getDeclKind();
602 #define DECL(NAME, BASE)
603 #define DECL_CONTEXT(NAME) \
605 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
606 #define DECL_CONTEXT_BASE(NAME)
607 #include "clang/AST/DeclNodes.inc"
609 #define DECL(NAME, BASE)
610 #define DECL_CONTEXT_BASE(NAME) \
611 if (DK >= first##NAME && DK <= last##NAME) \
612 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
613 #include "clang/AST/DeclNodes.inc"
614 llvm_unreachable("a decl that inherits DeclContext isn't handled");
618 DeclContext *Decl::castToDeclContext(const Decl *D) {
619 Decl::Kind DK = D->getKind();
621 #define DECL(NAME, BASE)
622 #define DECL_CONTEXT(NAME) \
624 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
625 #define DECL_CONTEXT_BASE(NAME)
626 #include "clang/AST/DeclNodes.inc"
628 #define DECL(NAME, BASE)
629 #define DECL_CONTEXT_BASE(NAME) \
630 if (DK >= first##NAME && DK <= last##NAME) \
631 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
632 #include "clang/AST/DeclNodes.inc"
633 llvm_unreachable("a decl that inherits DeclContext isn't handled");
637 SourceLocation Decl::getBodyRBrace() const {
638 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
639 // FunctionDecl stores EndRangeLoc for this purpose.
640 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
641 const FunctionDecl *Definition;
642 if (FD->hasBody(Definition))
643 return Definition->getSourceRange().getEnd();
644 return SourceLocation();
647 if (Stmt *Body = getBody())
648 return Body->getSourceRange().getEnd();
650 return SourceLocation();
653 void Decl::CheckAccessDeclContext() const {
655 // Suppress this check if any of the following hold:
656 // 1. this is the translation unit (and thus has no parent)
657 // 2. this is a template parameter (and thus doesn't belong to its context)
658 // 3. this is a non-type template parameter
659 // 4. the context is not a record
661 // 6. it's a C++0x static_assert.
662 if (isa<TranslationUnitDecl>(this) ||
663 isa<TemplateTypeParmDecl>(this) ||
664 isa<NonTypeTemplateParmDecl>(this) ||
665 !isa<CXXRecordDecl>(getDeclContext()) ||
667 isa<StaticAssertDecl>(this) ||
668 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
669 // as DeclContext (?).
670 isa<ParmVarDecl>(this) ||
671 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
672 // AS_none as access specifier.
673 isa<CXXRecordDecl>(this) ||
674 isa<ClassScopeFunctionSpecializationDecl>(this))
677 assert(Access != AS_none &&
678 "Access specifier is AS_none inside a record decl");
682 DeclContext *Decl::getNonClosureContext() {
683 return getDeclContext()->getNonClosureAncestor();
686 DeclContext *DeclContext::getNonClosureAncestor() {
687 DeclContext *DC = this;
689 // This is basically "while (DC->isClosure()) DC = DC->getParent();"
690 // except that it's significantly more efficient to cast to a known
691 // decl type and call getDeclContext() than to call getParent().
692 while (isa<BlockDecl>(DC))
693 DC = cast<BlockDecl>(DC)->getDeclContext();
695 assert(!DC->isClosure());
699 //===----------------------------------------------------------------------===//
700 // DeclContext Implementation
701 //===----------------------------------------------------------------------===//
703 bool DeclContext::classof(const Decl *D) {
704 switch (D->getKind()) {
705 #define DECL(NAME, BASE)
706 #define DECL_CONTEXT(NAME) case Decl::NAME:
707 #define DECL_CONTEXT_BASE(NAME)
708 #include "clang/AST/DeclNodes.inc"
711 #define DECL(NAME, BASE)
712 #define DECL_CONTEXT_BASE(NAME) \
713 if (D->getKind() >= Decl::first##NAME && \
714 D->getKind() <= Decl::last##NAME) \
716 #include "clang/AST/DeclNodes.inc"
721 DeclContext::~DeclContext() { }
723 /// \brief Find the parent context of this context that will be
724 /// used for unqualified name lookup.
726 /// Generally, the parent lookup context is the semantic context. However, for
727 /// a friend function the parent lookup context is the lexical context, which
728 /// is the class in which the friend is declared.
729 DeclContext *DeclContext::getLookupParent() {
730 // FIXME: Find a better way to identify friends
731 if (isa<FunctionDecl>(this))
732 if (getParent()->getRedeclContext()->isFileContext() &&
733 getLexicalParent()->getRedeclContext()->isRecord())
734 return getLexicalParent();
739 bool DeclContext::isInlineNamespace() const {
740 return isNamespace() &&
741 cast<NamespaceDecl>(this)->isInline();
744 bool DeclContext::isDependentContext() const {
748 if (isa<ClassTemplatePartialSpecializationDecl>(this))
751 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
752 if (Record->getDescribedClassTemplate())
755 if (Record->isDependentLambda())
759 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
760 if (Function->getDescribedFunctionTemplate())
763 // Friend function declarations are dependent if their *lexical*
764 // context is dependent.
765 if (cast<Decl>(this)->getFriendObjectKind())
766 return getLexicalParent()->isDependentContext();
769 return getParent() && getParent()->isDependentContext();
772 bool DeclContext::isTransparentContext() const {
773 if (DeclKind == Decl::Enum)
774 return !cast<EnumDecl>(this)->isScoped();
775 else if (DeclKind == Decl::LinkageSpec)
781 bool DeclContext::isExternCContext() const {
782 const DeclContext *DC = this;
783 while (DC->DeclKind != Decl::TranslationUnit) {
784 if (DC->DeclKind == Decl::LinkageSpec)
785 return cast<LinkageSpecDecl>(DC)->getLanguage()
786 == LinkageSpecDecl::lang_c;
787 DC = DC->getParent();
792 bool DeclContext::Encloses(const DeclContext *DC) const {
793 if (getPrimaryContext() != this)
794 return getPrimaryContext()->Encloses(DC);
796 for (; DC; DC = DC->getParent())
797 if (DC->getPrimaryContext() == this)
802 DeclContext *DeclContext::getPrimaryContext() {
804 case Decl::TranslationUnit:
805 case Decl::LinkageSpec:
807 // There is only one DeclContext for these entities.
810 case Decl::Namespace:
811 // The original namespace is our primary context.
812 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
814 case Decl::ObjCMethod:
817 case Decl::ObjCInterface:
818 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
823 case Decl::ObjCProtocol:
824 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
829 case Decl::ObjCCategory:
832 case Decl::ObjCImplementation:
833 case Decl::ObjCCategoryImpl:
837 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
838 // If this is a tag type that has a definition or is currently
839 // being defined, that definition is our primary context.
840 TagDecl *Tag = cast<TagDecl>(this);
841 assert(isa<TagType>(Tag->TypeForDecl) ||
842 isa<InjectedClassNameType>(Tag->TypeForDecl));
844 if (TagDecl *Def = Tag->getDefinition())
847 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
848 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
849 if (TagTy->isBeingDefined())
850 // FIXME: is it necessarily being defined in the decl
851 // that owns the type?
852 return TagTy->getDecl();
858 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
859 "Unknown DeclContext kind");
865 DeclContext::collectAllContexts(llvm::SmallVectorImpl<DeclContext *> &Contexts){
868 if (DeclKind != Decl::Namespace) {
869 Contexts.push_back(this);
873 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
874 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
875 N = N->getPreviousDecl())
876 Contexts.push_back(N);
878 std::reverse(Contexts.begin(), Contexts.end());
881 std::pair<Decl *, Decl *>
882 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
883 bool FieldsAlreadyLoaded) {
884 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
885 Decl *FirstNewDecl = 0;
887 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
888 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
893 PrevDecl->NextInContextAndBits.setPointer(D);
900 return std::make_pair(FirstNewDecl, PrevDecl);
903 /// \brief Load the declarations within this lexical storage from an
906 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
907 ExternalASTSource *Source = getParentASTContext().getExternalSource();
908 assert(hasExternalLexicalStorage() && Source && "No external storage?");
910 // Notify that we have a DeclContext that is initializing.
911 ExternalASTSource::Deserializing ADeclContext(Source);
913 // Load the external declarations, if any.
914 SmallVector<Decl*, 64> Decls;
915 ExternalLexicalStorage = false;
916 switch (Source->FindExternalLexicalDecls(this, Decls)) {
921 case ELR_AlreadyLoaded:
928 // We may have already loaded just the fields of this record, in which case
929 // we need to ignore them.
930 bool FieldsAlreadyLoaded = false;
931 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
932 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
934 // Splice the newly-read declarations into the beginning of the list
936 Decl *ExternalFirst, *ExternalLast;
937 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
938 FieldsAlreadyLoaded);
939 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
940 FirstDecl = ExternalFirst;
942 LastDecl = ExternalLast;
945 DeclContext::lookup_result
946 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
947 DeclarationName Name) {
948 ASTContext &Context = DC->getParentASTContext();
950 if (!(Map = DC->LookupPtr.getPointer()))
951 Map = DC->CreateStoredDeclsMap(Context);
953 StoredDeclsList &List = (*Map)[Name];
954 assert(List.isNull());
957 return DeclContext::lookup_result();
960 DeclContext::lookup_result
961 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
962 DeclarationName Name,
963 ArrayRef<NamedDecl*> Decls) {
964 ASTContext &Context = DC->getParentASTContext();
967 if (!(Map = DC->LookupPtr.getPointer()))
968 Map = DC->CreateStoredDeclsMap(Context);
970 StoredDeclsList &List = (*Map)[Name];
971 for (ArrayRef<NamedDecl*>::iterator
972 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
974 List.setOnlyValue(*I);
976 List.AddSubsequentDecl(*I);
979 return List.getLookupResult();
982 DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
983 return decl_iterator(FirstDecl);
986 DeclContext::decl_iterator DeclContext::decls_begin() const {
987 if (hasExternalLexicalStorage())
988 LoadLexicalDeclsFromExternalStorage();
990 return decl_iterator(FirstDecl);
993 bool DeclContext::decls_empty() const {
994 if (hasExternalLexicalStorage())
995 LoadLexicalDeclsFromExternalStorage();
1000 void DeclContext::removeDecl(Decl *D) {
1001 assert(D->getLexicalDeclContext() == this &&
1002 "decl being removed from non-lexical context");
1003 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1004 "decl is not in decls list");
1006 // Remove D from the decl chain. This is O(n) but hopefully rare.
1007 if (D == FirstDecl) {
1009 FirstDecl = LastDecl = 0;
1011 FirstDecl = D->NextInContextAndBits.getPointer();
1013 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1014 assert(I && "decl not found in linked list");
1015 if (I->NextInContextAndBits.getPointer() == D) {
1016 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1017 if (D == LastDecl) LastDecl = I;
1023 // Mark that D is no longer in the decl chain.
1024 D->NextInContextAndBits.setPointer(0);
1026 // Remove D from the lookup table if necessary.
1027 if (isa<NamedDecl>(D)) {
1028 NamedDecl *ND = cast<NamedDecl>(D);
1030 // Remove only decls that have a name
1031 if (!ND->getDeclName()) return;
1033 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
1036 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1037 assert(Pos != Map->end() && "no lookup entry for decl");
1038 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1039 Pos->second.remove(ND);
1043 void DeclContext::addHiddenDecl(Decl *D) {
1044 assert(D->getLexicalDeclContext() == this &&
1045 "Decl inserted into wrong lexical context");
1046 assert(!D->getNextDeclInContext() && D != LastDecl &&
1047 "Decl already inserted into a DeclContext");
1050 LastDecl->NextInContextAndBits.setPointer(D);
1053 FirstDecl = LastDecl = D;
1056 // Notify a C++ record declaration that we've added a member, so it can
1057 // update it's class-specific state.
1058 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1059 Record->addedMember(D);
1061 // If this is a newly-created (not de-serialized) import declaration, wire
1062 // it in to the list of local import declarations.
1063 if (!D->isFromASTFile()) {
1064 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1065 D->getASTContext().addedLocalImportDecl(Import);
1069 void DeclContext::addDecl(Decl *D) {
1072 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1073 ND->getDeclContext()->getPrimaryContext()->
1074 makeDeclVisibleInContextWithFlags(ND, false, true);
1077 void DeclContext::addDeclInternal(Decl *D) {
1080 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1081 ND->getDeclContext()->getPrimaryContext()->
1082 makeDeclVisibleInContextWithFlags(ND, true, true);
1085 /// shouldBeHidden - Determine whether a declaration which was declared
1086 /// within its semantic context should be invisible to qualified name lookup.
1087 static bool shouldBeHidden(NamedDecl *D) {
1088 // Skip unnamed declarations.
1089 if (!D->getDeclName())
1092 // Skip entities that can't be found by name lookup into a particular
1094 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1095 D->isTemplateParameter())
1098 // Skip template specializations.
1099 // FIXME: This feels like a hack. Should DeclarationName support
1100 // template-ids, or is there a better way to keep specializations
1101 // from being visible?
1102 if (isa<ClassTemplateSpecializationDecl>(D))
1104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1105 if (FD->isFunctionTemplateSpecialization())
1111 /// buildLookup - Build the lookup data structure with all of the
1112 /// declarations in this DeclContext (and any other contexts linked
1113 /// to it or transparent contexts nested within it) and return it.
1114 StoredDeclsMap *DeclContext::buildLookup() {
1115 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1117 if (!LookupPtr.getInt())
1118 return LookupPtr.getPointer();
1120 llvm::SmallVector<DeclContext *, 2> Contexts;
1121 collectAllContexts(Contexts);
1122 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1123 buildLookupImpl(Contexts[I]);
1125 // We no longer have any lazy decls.
1126 LookupPtr.setInt(false);
1127 return LookupPtr.getPointer();
1130 /// buildLookupImpl - Build part of the lookup data structure for the
1131 /// declarations contained within DCtx, which will either be this
1132 /// DeclContext, a DeclContext linked to it, or a transparent context
1133 /// nested within it.
1134 void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1135 for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1139 // Insert this declaration into the lookup structure, but only if
1140 // it's semantically within its decl context. Any other decls which
1141 // should be found in this context are added eagerly.
1142 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1143 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1144 makeDeclVisibleInContextImpl(ND, false);
1146 // If this declaration is itself a transparent declaration context
1147 // or inline namespace, add the members of this declaration of that
1148 // context (recursively).
1149 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1150 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1151 buildLookupImpl(InnerCtx);
1155 DeclContext::lookup_result
1156 DeclContext::lookup(DeclarationName Name) {
1157 assert(DeclKind != Decl::LinkageSpec &&
1158 "Should not perform lookups into linkage specs!");
1160 DeclContext *PrimaryContext = getPrimaryContext();
1161 if (PrimaryContext != this)
1162 return PrimaryContext->lookup(Name);
1164 if (hasExternalVisibleStorage()) {
1165 // If a PCH has a result for this name, and we have a local declaration, we
1166 // will have imported the PCH result when adding the local declaration.
1167 // FIXME: For modules, we could have had more declarations added by module
1168 // imoprts since we saw the declaration of the local name.
1169 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1170 StoredDeclsMap::iterator I = Map->find(Name);
1171 if (I != Map->end())
1172 return I->second.getLookupResult();
1175 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1176 return Source->FindExternalVisibleDeclsByName(this, Name);
1179 StoredDeclsMap *Map = LookupPtr.getPointer();
1180 if (LookupPtr.getInt())
1181 Map = buildLookup();
1184 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1186 StoredDeclsMap::iterator I = Map->find(Name);
1187 if (I == Map->end())
1188 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1190 return I->second.getLookupResult();
1193 void DeclContext::localUncachedLookup(DeclarationName Name,
1194 llvm::SmallVectorImpl<NamedDecl *> &Results) {
1197 // If there's no external storage, just perform a normal lookup and copy
1199 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1200 lookup_result LookupResults = lookup(Name);
1201 Results.insert(Results.end(), LookupResults.first, LookupResults.second);
1205 // If we have a lookup table, check there first. Maybe we'll get lucky.
1207 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1208 StoredDeclsMap::iterator Pos = Map->find(Name);
1209 if (Pos != Map->end()) {
1210 Results.insert(Results.end(),
1211 Pos->second.getLookupResult().first,
1212 Pos->second.getLookupResult().second);
1218 // Slow case: grovel through the declarations in our chain looking for
1220 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1221 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1222 if (ND->getDeclName() == Name)
1223 Results.push_back(ND);
1227 DeclContext *DeclContext::getRedeclContext() {
1228 DeclContext *Ctx = this;
1229 // Skip through transparent contexts.
1230 while (Ctx->isTransparentContext())
1231 Ctx = Ctx->getParent();
1235 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1236 DeclContext *Ctx = this;
1237 // Skip through non-namespace, non-translation-unit contexts.
1238 while (!Ctx->isFileContext())
1239 Ctx = Ctx->getParent();
1240 return Ctx->getPrimaryContext();
1243 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1244 // For non-file contexts, this is equivalent to Equals.
1245 if (!isFileContext())
1246 return O->Equals(this);
1249 if (O->Equals(this))
1252 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1253 if (!NS || !NS->isInline())
1255 O = NS->getParent();
1261 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1262 DeclContext *PrimaryDC = this->getPrimaryContext();
1263 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1264 // If the decl is being added outside of its semantic decl context, we
1265 // need to ensure that we eagerly build the lookup information for it.
1266 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1269 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1271 assert(this == getPrimaryContext() && "expected a primary DC");
1273 // Skip declarations within functions.
1274 // FIXME: We shouldn't need to build lookup tables for function declarations
1275 // ever, and we can't do so correctly because we can't model the nesting of
1276 // scopes which occurs within functions. We use "qualified" lookup into
1277 // function declarations when handling friend declarations inside nested
1278 // classes, and consequently accept the following invalid code:
1280 // void f() { void g(); { int g; struct S { friend void g(); }; } }
1281 if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1284 // Skip declarations which should be invisible to name lookup.
1285 if (shouldBeHidden(D))
1288 // If we already have a lookup data structure, perform the insertion into
1289 // it. If we might have externally-stored decls with this name, look them
1290 // up and perform the insertion. If this decl was declared outside its
1291 // semantic context, buildLookup won't add it, so add it now.
1293 // FIXME: As a performance hack, don't add such decls into the translation
1294 // unit unless we're in C++, since qualified lookup into the TU is never
1296 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1297 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1298 (getParentASTContext().getLangOpts().CPlusPlus ||
1299 !isTranslationUnit()))) {
1300 // If we have lazily omitted any decls, they might have the same name as
1301 // the decl which we are adding, so build a full lookup table before adding
1304 makeDeclVisibleInContextImpl(D, Internal);
1306 LookupPtr.setInt(true);
1309 // If we are a transparent context or inline namespace, insert into our
1310 // parent context, too. This operation is recursive.
1311 if (isTransparentContext() || isInlineNamespace())
1312 getParent()->getPrimaryContext()->
1313 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1315 Decl *DCAsDecl = cast<Decl>(this);
1316 // Notify that a decl was made visible unless we are a Tag being defined.
1317 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1318 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1319 L->AddedVisibleDecl(this, D);
1322 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1323 // Find or create the stored declaration map.
1324 StoredDeclsMap *Map = LookupPtr.getPointer();
1326 ASTContext *C = &getParentASTContext();
1327 Map = CreateStoredDeclsMap(*C);
1330 // If there is an external AST source, load any declarations it knows about
1331 // with this declaration's name.
1332 // If the lookup table contains an entry about this name it means that we
1333 // have already checked the external source.
1335 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1336 if (hasExternalVisibleStorage() &&
1337 Map->find(D->getDeclName()) == Map->end())
1338 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1340 // Insert this declaration into the map.
1341 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1342 if (DeclNameEntries.isNull()) {
1343 DeclNameEntries.setOnlyValue(D);
1347 if (DeclNameEntries.HandleRedeclaration(D)) {
1348 // This declaration has replaced an existing one for which
1349 // declarationReplaces returns true.
1353 // Put this declaration into the appropriate slot.
1354 DeclNameEntries.AddSubsequentDecl(D);
1357 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1359 DeclContext::udir_iterator_range
1360 DeclContext::getUsingDirectives() const {
1361 // FIXME: Use something more efficient than normal lookup for using
1362 // directives. In C++, using directives are looked up more than anything else.
1363 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
1364 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
1365 reinterpret_cast<udir_iterator>(Result.second));
1368 //===----------------------------------------------------------------------===//
1369 // Creation and Destruction of StoredDeclsMaps. //
1370 //===----------------------------------------------------------------------===//
1372 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1373 assert(!LookupPtr.getPointer() && "context already has a decls map");
1374 assert(getPrimaryContext() == this &&
1375 "creating decls map on non-primary context");
1378 bool Dependent = isDependentContext();
1380 M = new DependentStoredDeclsMap();
1382 M = new StoredDeclsMap();
1383 M->Previous = C.LastSDM;
1384 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1385 LookupPtr.setPointer(M);
1389 void ASTContext::ReleaseDeclContextMaps() {
1390 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1391 // pointer because the subclass doesn't add anything that needs to
1393 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1396 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1398 // Advance the iteration before we invalidate memory.
1399 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1402 delete static_cast<DependentStoredDeclsMap*>(Map);
1406 Map = Next.getPointer();
1407 Dependent = Next.getInt();
1411 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1412 DeclContext *Parent,
1413 const PartialDiagnostic &PDiag) {
1414 assert(Parent->isDependentContext()
1415 && "cannot iterate dependent diagnostics of non-dependent context");
1416 Parent = Parent->getPrimaryContext();
1417 if (!Parent->LookupPtr.getPointer())
1418 Parent->CreateStoredDeclsMap(C);
1420 DependentStoredDeclsMap *Map
1421 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
1423 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1424 // BumpPtrAllocator, rather than the ASTContext itself.
1425 PartialDiagnostic::Storage *DiagStorage = 0;
1426 if (PDiag.hasStorage())
1427 DiagStorage = new (C) PartialDiagnostic::Storage;
1429 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1431 // TODO: Maybe we shouldn't reverse the order during insertion.
1432 DD->NextDiagnostic = Map->FirstDiagnostic;
1433 Map->FirstDiagnostic = DD;