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/Support/raw_ostream.h"
33 using namespace clang;
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
40 #define ABSTRACT_DECL(DECL)
41 #include "clang/AST/DeclNodes.inc"
43 void Decl::updateOutOfDate(IdentifierInfo &II) const {
44 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
47 #define DECL(DERIVED, BASE) \
48 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
49 "Alignment sufficient after objects prepended to " #DERIVED);
50 #define ABSTRACT_DECL(DECL)
51 #include "clang/AST/DeclNodes.inc"
53 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
54 unsigned ID, std::size_t Extra) {
55 // Allocate an extra 8 bytes worth of storage, which ensures that the
56 // resulting pointer will still be 8-byte aligned.
57 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
58 "Decl won't be misaligned");
59 void *Start = Context.Allocate(Size + Extra + 8);
60 void *Result = (char*)Start + 8;
62 unsigned *PrefixPtr = (unsigned *)Result - 2;
64 // Zero out the first 4 bytes; this is used to store the owning module ID.
67 // Store the global declaration ID in the second 4 bytes.
73 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
74 DeclContext *Parent, std::size_t Extra) {
75 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
76 // With local visibility enabled, we track the owning module even for local
78 if (Ctx.getLangOpts().trackLocalOwningModule()) {
79 // Ensure required alignment of the resulting object by adding extra
80 // padding at the start if required.
82 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
83 char *Buffer = reinterpret_cast<char *>(
84 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
87 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
88 return new (Buffer) Module*(ParentModule) + 1;
90 return ::operator new(Size + Extra, Ctx);
93 Module *Decl::getOwningModuleSlow() const {
94 assert(isFromASTFile() && "Not from AST file?");
95 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
98 bool Decl::hasLocalOwningModuleStorage() const {
99 return getASTContext().getLangOpts().trackLocalOwningModule();
102 const char *Decl::getDeclKindName() const {
104 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
105 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106 #define ABSTRACT_DECL(DECL)
107 #include "clang/AST/DeclNodes.inc"
111 void Decl::setInvalidDecl(bool Invalid) {
112 InvalidDecl = Invalid;
113 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
118 if (!isa<ParmVarDecl>(this)) {
119 // Defensive maneuver for ill-formed code: we're likely not to make it to
120 // a point where we set the access specifier, so default it to "public"
121 // to avoid triggering asserts elsewhere in the front end.
122 setAccess(AS_public);
125 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
127 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
128 for (BindingDecl *Binding : DD->bindings()) {
129 Binding->setInvalidDecl();
134 const char *DeclContext::getDeclKindName() const {
136 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
137 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
138 #define ABSTRACT_DECL(DECL)
139 #include "clang/AST/DeclNodes.inc"
143 bool Decl::StatisticsEnabled = false;
144 void Decl::EnableStatistics() {
145 StatisticsEnabled = true;
148 void Decl::PrintStats() {
149 llvm::errs() << "\n*** Decl Stats:\n";
152 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
153 #define ABSTRACT_DECL(DECL)
154 #include "clang/AST/DeclNodes.inc"
155 llvm::errs() << " " << totalDecls << " decls total.\n";
158 #define DECL(DERIVED, BASE) \
159 if (n##DERIVED##s > 0) { \
160 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
161 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
162 << sizeof(DERIVED##Decl) << " each (" \
163 << n##DERIVED##s * sizeof(DERIVED##Decl) \
166 #define ABSTRACT_DECL(DECL)
167 #include "clang/AST/DeclNodes.inc"
169 llvm::errs() << "Total bytes = " << totalBytes << "\n";
172 void Decl::add(Kind k) {
174 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
175 #define ABSTRACT_DECL(DECL)
176 #include "clang/AST/DeclNodes.inc"
180 bool Decl::isTemplateParameterPack() const {
181 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
182 return TTP->isParameterPack();
183 if (const NonTypeTemplateParmDecl *NTTP
184 = dyn_cast<NonTypeTemplateParmDecl>(this))
185 return NTTP->isParameterPack();
186 if (const TemplateTemplateParmDecl *TTP
187 = dyn_cast<TemplateTemplateParmDecl>(this))
188 return TTP->isParameterPack();
192 bool Decl::isParameterPack() const {
193 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
194 return Parm->isParameterPack();
196 return isTemplateParameterPack();
199 FunctionDecl *Decl::getAsFunction() {
200 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
202 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
203 return FTD->getTemplatedDecl();
207 bool Decl::isTemplateDecl() const {
208 return isa<TemplateDecl>(this);
211 TemplateDecl *Decl::getDescribedTemplate() const {
212 if (auto *FD = dyn_cast<FunctionDecl>(this))
213 return FD->getDescribedFunctionTemplate();
214 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
215 return RD->getDescribedClassTemplate();
216 else if (auto *VD = dyn_cast<VarDecl>(this))
217 return VD->getDescribedVarTemplate();
222 const DeclContext *Decl::getParentFunctionOrMethod() const {
223 for (const DeclContext *DC = getDeclContext();
224 DC && !DC->isTranslationUnit() && !DC->isNamespace();
225 DC = DC->getParent())
226 if (DC->isFunctionOrMethod())
233 //===----------------------------------------------------------------------===//
234 // PrettyStackTraceDecl Implementation
235 //===----------------------------------------------------------------------===//
237 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
238 SourceLocation TheLoc = Loc;
239 if (TheLoc.isInvalid() && TheDecl)
240 TheLoc = TheDecl->getLocation();
242 if (TheLoc.isValid()) {
243 TheLoc.print(OS, SM);
249 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
251 DN->printQualifiedName(OS);
257 //===----------------------------------------------------------------------===//
258 // Decl Implementation
259 //===----------------------------------------------------------------------===//
261 // Out-of-line virtual method providing a home for Decl.
264 void Decl::setDeclContext(DeclContext *DC) {
268 void Decl::setLexicalDeclContext(DeclContext *DC) {
269 if (DC == getLexicalDeclContext())
273 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
275 getMultipleDC()->LexicalDC = DC;
277 Hidden = cast<Decl>(DC)->Hidden;
278 if (Hidden && !isFromASTFile() && hasLocalOwningModuleStorage())
279 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
282 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
284 if (SemaDC == LexicalDC) {
287 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
288 MDC->SemanticDC = SemaDC;
289 MDC->LexicalDC = LexicalDC;
294 bool Decl::isLexicallyWithinFunctionOrMethod() const {
295 const DeclContext *LDC = getLexicalDeclContext();
297 if (LDC->isFunctionOrMethod())
299 if (!isa<TagDecl>(LDC))
301 LDC = LDC->getLexicalParent();
306 bool Decl::isInAnonymousNamespace() const {
307 const DeclContext *DC = getDeclContext();
309 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
310 if (ND->isAnonymousNamespace())
312 } while ((DC = DC->getParent()));
317 bool Decl::isInStdNamespace() const {
318 return getDeclContext()->isStdNamespace();
321 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
322 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
325 DeclContext *DC = getDeclContext();
326 assert(DC && "This decl is not contained in a translation unit!");
328 while (!DC->isTranslationUnit()) {
329 DC = DC->getParent();
330 assert(DC && "This decl is not contained in a translation unit!");
333 return cast<TranslationUnitDecl>(DC);
336 ASTContext &Decl::getASTContext() const {
337 return getTranslationUnitDecl()->getASTContext();
340 ASTMutationListener *Decl::getASTMutationListener() const {
341 return getASTContext().getASTMutationListener();
344 unsigned Decl::getMaxAlignment() const {
349 const AttrVec &V = getAttrs();
350 ASTContext &Ctx = getASTContext();
351 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
353 Align = std::max(Align, I->getAlignment(Ctx));
357 bool Decl::isUsed(bool CheckUsedAttr) const {
358 const Decl *CanonD = getCanonicalDecl();
362 // Check for used attribute.
363 // Ask the most recent decl, since attributes accumulate in the redecl chain.
364 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
367 // The information may have not been deserialized yet. Force deserialization
368 // to complete the needed information.
369 return getMostRecentDecl()->getCanonicalDecl()->Used;
372 void Decl::markUsed(ASTContext &C) {
376 if (C.getASTMutationListener())
377 C.getASTMutationListener()->DeclarationMarkedUsed(this);
382 bool Decl::isReferenced() const {
386 // Check redeclarations.
387 for (auto I : redecls())
394 bool Decl::isExported() const {
395 if (isModulePrivate())
397 // Namespaces are always exported.
398 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
400 // Otherwise, this is a strictly lexical check.
401 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
402 if (cast<Decl>(DC)->isModulePrivate())
404 if (isa<ExportDecl>(DC))
410 bool Decl::hasDefiningAttr() const {
411 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
414 const Attr *Decl::getDefiningAttr() const {
415 if (AliasAttr *AA = getAttr<AliasAttr>())
417 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
422 StringRef getRealizedPlatform(const AvailabilityAttr *A,
423 const ASTContext &Context) {
424 // Check if this is an App Extension "platform", and if so chop off
425 // the suffix for matching with the actual platform.
426 StringRef RealizedPlatform = A->getPlatform()->getName();
427 if (!Context.getLangOpts().AppExt)
428 return RealizedPlatform;
429 size_t suffix = RealizedPlatform.rfind("_app_extension");
430 if (suffix != StringRef::npos)
431 return RealizedPlatform.slice(0, suffix);
432 return RealizedPlatform;
435 /// \brief Determine the availability of the given declaration based on
436 /// the target platform.
438 /// When it returns an availability result other than \c AR_Available,
439 /// if the \p Message parameter is non-NULL, it will be set to a
440 /// string describing why the entity is unavailable.
442 /// FIXME: Make these strings localizable, since they end up in
444 static AvailabilityResult CheckAvailability(ASTContext &Context,
445 const AvailabilityAttr *A,
446 std::string *Message,
447 VersionTuple EnclosingVersion) {
448 if (EnclosingVersion.empty())
449 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
451 if (EnclosingVersion.empty())
454 StringRef ActualPlatform = A->getPlatform()->getName();
455 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
457 // Match the platform name.
458 if (getRealizedPlatform(A, Context) != TargetPlatform)
461 StringRef PrettyPlatformName
462 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
464 if (PrettyPlatformName.empty())
465 PrettyPlatformName = ActualPlatform;
467 std::string HintMessage;
468 if (!A->getMessage().empty()) {
470 HintMessage += A->getMessage();
473 // Make sure that this declaration has not been marked 'unavailable'.
474 if (A->getUnavailable()) {
477 llvm::raw_string_ostream Out(*Message);
478 Out << "not available on " << PrettyPlatformName
482 return AR_Unavailable;
485 // Make sure that this declaration has already been introduced.
486 if (!A->getIntroduced().empty() &&
487 EnclosingVersion < A->getIntroduced()) {
490 llvm::raw_string_ostream Out(*Message);
491 VersionTuple VTI(A->getIntroduced());
492 VTI.UseDotAsSeparator();
493 Out << "introduced in " << PrettyPlatformName << ' '
494 << VTI << HintMessage;
497 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
500 // Make sure that this declaration hasn't been obsoleted.
501 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
504 llvm::raw_string_ostream Out(*Message);
505 VersionTuple VTO(A->getObsoleted());
506 VTO.UseDotAsSeparator();
507 Out << "obsoleted in " << PrettyPlatformName << ' '
508 << VTO << HintMessage;
511 return AR_Unavailable;
514 // Make sure that this declaration hasn't been deprecated.
515 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
518 llvm::raw_string_ostream Out(*Message);
519 VersionTuple VTD(A->getDeprecated());
520 VTD.UseDotAsSeparator();
521 Out << "first deprecated in " << PrettyPlatformName << ' '
522 << VTD << HintMessage;
525 return AR_Deprecated;
531 AvailabilityResult Decl::getAvailability(std::string *Message,
532 VersionTuple EnclosingVersion) const {
533 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
534 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
536 AvailabilityResult Result = AR_Available;
537 std::string ResultMessage;
539 for (const auto *A : attrs()) {
540 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
541 if (Result >= AR_Deprecated)
545 ResultMessage = Deprecated->getMessage();
547 Result = AR_Deprecated;
551 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
553 *Message = Unavailable->getMessage();
554 return AR_Unavailable;
557 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
558 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
559 Message, EnclosingVersion);
561 if (AR == AR_Unavailable)
562 return AR_Unavailable;
567 ResultMessage.swap(*Message);
574 Message->swap(ResultMessage);
578 VersionTuple Decl::getVersionIntroduced() const {
579 const ASTContext &Context = getASTContext();
580 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
581 for (const auto *A : attrs()) {
582 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
583 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
585 if (!Availability->getIntroduced().empty())
586 return Availability->getIntroduced();
589 return VersionTuple();
592 bool Decl::canBeWeakImported(bool &IsDefinition) const {
593 IsDefinition = false;
595 // Variables, if they aren't definitions.
596 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
597 if (Var->isThisDeclarationADefinition()) {
603 // Functions, if they aren't definitions.
604 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
611 // Objective-C classes, if this is the non-fragile runtime.
612 } else if (isa<ObjCInterfaceDecl>(this) &&
613 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
622 bool Decl::isWeakImported() const {
624 if (!canBeWeakImported(IsDefinition))
627 for (const auto *A : attrs()) {
628 if (isa<WeakImportAttr>(A))
631 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
632 if (CheckAvailability(getASTContext(), Availability, nullptr,
633 VersionTuple()) == AR_NotYetIntroduced)
641 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
644 case CXXDeductionGuide:
647 case ConstructorUsingShadow:
658 return IDNS_Ordinary;
662 return IDNS_Ordinary | IDNS_Member;
664 case NonTypeTemplateParm:
665 // Non-type template parameters are not found by lookups that ignore
666 // non-types, but they are found by redeclaration lookups for tag types,
667 // so we include them in the tag namespace.
668 return IDNS_Ordinary | IDNS_Tag;
670 case ObjCCompatibleAlias:
672 return IDNS_Ordinary | IDNS_Type;
676 case TypeAliasTemplate:
677 case TemplateTypeParm:
679 return IDNS_Ordinary | IDNS_Type;
681 case UnresolvedUsingTypename:
682 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
685 return 0; // we'll actually overwrite this later
687 case UnresolvedUsingValue:
688 return IDNS_Ordinary | IDNS_Using;
695 return IDNS_ObjCProtocol;
698 case ObjCAtDefsField:
705 return IDNS_Tag | IDNS_Type;
709 return IDNS_Namespace;
711 case FunctionTemplate:
713 return IDNS_Ordinary;
716 case TemplateTemplateParm:
717 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
719 case OMPDeclareReduction:
720 return IDNS_OMPReduction;
730 case ObjCPropertyImpl:
732 case PragmaDetectMismatch:
735 case TranslationUnit:
740 case BuiltinTemplate:
741 case ClassTemplateSpecialization:
742 case ClassTemplatePartialSpecialization:
743 case ClassScopeFunctionSpecialization:
744 case VarTemplateSpecialization:
745 case VarTemplatePartialSpecialization:
746 case ObjCImplementation:
748 case ObjCCategoryImpl:
750 case OMPThreadPrivate:
751 case OMPCapturedExpr:
753 // Never looked up by name.
757 llvm_unreachable("Invalid DeclKind!");
760 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
761 assert(!HasAttrs && "Decl already contains attrs.");
763 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
764 assert(AttrBlank.empty() && "HasAttrs was wrong?");
770 void Decl::dropAttrs() {
771 if (!HasAttrs) return;
774 getASTContext().eraseDeclAttrs(this);
777 const AttrVec &Decl::getAttrs() const {
778 assert(HasAttrs && "No attrs to get!");
779 return getASTContext().getDeclAttrs(this);
782 Decl *Decl::castFromDeclContext (const DeclContext *D) {
783 Decl::Kind DK = D->getDeclKind();
785 #define DECL(NAME, BASE)
786 #define DECL_CONTEXT(NAME) \
788 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
789 #define DECL_CONTEXT_BASE(NAME)
790 #include "clang/AST/DeclNodes.inc"
792 #define DECL(NAME, BASE)
793 #define DECL_CONTEXT_BASE(NAME) \
794 if (DK >= first##NAME && DK <= last##NAME) \
795 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
796 #include "clang/AST/DeclNodes.inc"
797 llvm_unreachable("a decl that inherits DeclContext isn't handled");
801 DeclContext *Decl::castToDeclContext(const Decl *D) {
802 Decl::Kind DK = D->getKind();
804 #define DECL(NAME, BASE)
805 #define DECL_CONTEXT(NAME) \
807 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
808 #define DECL_CONTEXT_BASE(NAME)
809 #include "clang/AST/DeclNodes.inc"
811 #define DECL(NAME, BASE)
812 #define DECL_CONTEXT_BASE(NAME) \
813 if (DK >= first##NAME && DK <= last##NAME) \
814 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
815 #include "clang/AST/DeclNodes.inc"
816 llvm_unreachable("a decl that inherits DeclContext isn't handled");
820 SourceLocation Decl::getBodyRBrace() const {
821 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
822 // FunctionDecl stores EndRangeLoc for this purpose.
823 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
824 const FunctionDecl *Definition;
825 if (FD->hasBody(Definition))
826 return Definition->getSourceRange().getEnd();
827 return SourceLocation();
830 if (Stmt *Body = getBody())
831 return Body->getSourceRange().getEnd();
833 return SourceLocation();
836 bool Decl::AccessDeclContextSanity() const {
838 // Suppress this check if any of the following hold:
839 // 1. this is the translation unit (and thus has no parent)
840 // 2. this is a template parameter (and thus doesn't belong to its context)
841 // 3. this is a non-type template parameter
842 // 4. the context is not a record
844 // 6. it's a C++0x static_assert.
845 if (isa<TranslationUnitDecl>(this) ||
846 isa<TemplateTypeParmDecl>(this) ||
847 isa<NonTypeTemplateParmDecl>(this) ||
848 !isa<CXXRecordDecl>(getDeclContext()) ||
850 isa<StaticAssertDecl>(this) ||
851 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
852 // as DeclContext (?).
853 isa<ParmVarDecl>(this) ||
854 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
855 // AS_none as access specifier.
856 isa<CXXRecordDecl>(this) ||
857 isa<ClassScopeFunctionSpecializationDecl>(this))
860 assert(Access != AS_none &&
861 "Access specifier is AS_none inside a record decl");
866 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
867 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
869 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
871 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
873 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
874 Ty = D->getUnderlyingType();
878 if (Ty->isFunctionPointerType())
879 Ty = Ty->getAs<PointerType>()->getPointeeType();
880 else if (BlocksToo && Ty->isBlockPointerType())
881 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
883 return Ty->getAs<FunctionType>();
887 /// Starting at a given context (a Decl or DeclContext), look for a
888 /// code context that is not a closure (a lambda, block, etc.).
889 template <class T> static Decl *getNonClosureContext(T *D) {
890 if (getKind(D) == Decl::CXXMethod) {
891 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
892 if (MD->getOverloadedOperator() == OO_Call &&
893 MD->getParent()->isLambda())
894 return getNonClosureContext(MD->getParent()->getParent());
896 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
898 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
900 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
901 return getNonClosureContext(BD->getParent());
902 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
903 return getNonClosureContext(CD->getParent());
909 Decl *Decl::getNonClosureContext() {
910 return ::getNonClosureContext(this);
913 Decl *DeclContext::getNonClosureAncestor() {
914 return ::getNonClosureContext(this);
917 //===----------------------------------------------------------------------===//
918 // DeclContext Implementation
919 //===----------------------------------------------------------------------===//
921 bool DeclContext::classof(const Decl *D) {
922 switch (D->getKind()) {
923 #define DECL(NAME, BASE)
924 #define DECL_CONTEXT(NAME) case Decl::NAME:
925 #define DECL_CONTEXT_BASE(NAME)
926 #include "clang/AST/DeclNodes.inc"
929 #define DECL(NAME, BASE)
930 #define DECL_CONTEXT_BASE(NAME) \
931 if (D->getKind() >= Decl::first##NAME && \
932 D->getKind() <= Decl::last##NAME) \
934 #include "clang/AST/DeclNodes.inc"
939 DeclContext::~DeclContext() { }
941 /// \brief Find the parent context of this context that will be
942 /// used for unqualified name lookup.
944 /// Generally, the parent lookup context is the semantic context. However, for
945 /// a friend function the parent lookup context is the lexical context, which
946 /// is the class in which the friend is declared.
947 DeclContext *DeclContext::getLookupParent() {
948 // FIXME: Find a better way to identify friends
949 if (isa<FunctionDecl>(this))
950 if (getParent()->getRedeclContext()->isFileContext() &&
951 getLexicalParent()->getRedeclContext()->isRecord())
952 return getLexicalParent();
957 bool DeclContext::isInlineNamespace() const {
958 return isNamespace() &&
959 cast<NamespaceDecl>(this)->isInline();
962 bool DeclContext::isStdNamespace() const {
966 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
967 if (ND->isInline()) {
968 return ND->getParent()->isStdNamespace();
971 if (!getParent()->getRedeclContext()->isTranslationUnit())
974 const IdentifierInfo *II = ND->getIdentifier();
975 return II && II->isStr("std");
978 bool DeclContext::isDependentContext() const {
982 if (isa<ClassTemplatePartialSpecializationDecl>(this))
985 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
986 if (Record->getDescribedClassTemplate())
989 if (Record->isDependentLambda())
993 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
994 if (Function->getDescribedFunctionTemplate())
997 // Friend function declarations are dependent if their *lexical*
998 // context is dependent.
999 if (cast<Decl>(this)->getFriendObjectKind())
1000 return getLexicalParent()->isDependentContext();
1003 // FIXME: A variable template is a dependent context, but is not a
1004 // DeclContext. A context within it (such as a lambda-expression)
1005 // should be considered dependent.
1007 return getParent() && getParent()->isDependentContext();
1010 bool DeclContext::isTransparentContext() const {
1011 if (DeclKind == Decl::Enum)
1012 return !cast<EnumDecl>(this)->isScoped();
1013 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1019 static bool isLinkageSpecContext(const DeclContext *DC,
1020 LinkageSpecDecl::LanguageIDs ID) {
1021 while (DC->getDeclKind() != Decl::TranslationUnit) {
1022 if (DC->getDeclKind() == Decl::LinkageSpec)
1023 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1024 DC = DC->getLexicalParent();
1029 bool DeclContext::isExternCContext() const {
1030 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1033 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1034 const DeclContext *DC = this;
1035 while (DC->getDeclKind() != Decl::TranslationUnit) {
1036 if (DC->getDeclKind() == Decl::LinkageSpec &&
1037 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1038 clang::LinkageSpecDecl::lang_c)
1039 return cast<LinkageSpecDecl>(DC);
1040 DC = DC->getLexicalParent();
1045 bool DeclContext::isExternCXXContext() const {
1046 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1049 bool DeclContext::Encloses(const DeclContext *DC) const {
1050 if (getPrimaryContext() != this)
1051 return getPrimaryContext()->Encloses(DC);
1053 for (; DC; DC = DC->getParent())
1054 if (DC->getPrimaryContext() == this)
1059 DeclContext *DeclContext::getPrimaryContext() {
1061 case Decl::TranslationUnit:
1062 case Decl::ExternCContext:
1063 case Decl::LinkageSpec:
1066 case Decl::Captured:
1067 case Decl::OMPDeclareReduction:
1068 // There is only one DeclContext for these entities.
1071 case Decl::Namespace:
1072 // The original namespace is our primary context.
1073 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1075 case Decl::ObjCMethod:
1078 case Decl::ObjCInterface:
1079 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1084 case Decl::ObjCProtocol:
1085 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1090 case Decl::ObjCCategory:
1093 case Decl::ObjCImplementation:
1094 case Decl::ObjCCategoryImpl:
1098 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1099 // If this is a tag type that has a definition or is currently
1100 // being defined, that definition is our primary context.
1101 TagDecl *Tag = cast<TagDecl>(this);
1103 if (TagDecl *Def = Tag->getDefinition())
1106 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1107 // Note, TagType::getDecl returns the (partial) definition one exists.
1108 TagDecl *PossiblePartialDef = TagTy->getDecl();
1109 if (PossiblePartialDef->isBeingDefined())
1110 return PossiblePartialDef;
1112 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1118 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1119 "Unknown DeclContext kind");
1125 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1128 if (DeclKind != Decl::Namespace) {
1129 Contexts.push_back(this);
1133 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1134 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1135 N = N->getPreviousDecl())
1136 Contexts.push_back(N);
1138 std::reverse(Contexts.begin(), Contexts.end());
1141 std::pair<Decl *, Decl *>
1142 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1143 bool FieldsAlreadyLoaded) {
1144 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1145 Decl *FirstNewDecl = nullptr;
1146 Decl *PrevDecl = nullptr;
1147 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1148 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1153 PrevDecl->NextInContextAndBits.setPointer(D);
1160 return std::make_pair(FirstNewDecl, PrevDecl);
1163 /// \brief We have just acquired external visible storage, and we already have
1164 /// built a lookup map. For every name in the map, pull in the new names from
1165 /// the external storage.
1166 void DeclContext::reconcileExternalVisibleStorage() const {
1167 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1168 NeedToReconcileExternalVisibleStorage = false;
1170 for (auto &Lookup : *LookupPtr)
1171 Lookup.second.setHasExternalDecls();
1174 /// \brief Load the declarations within this lexical storage from an
1175 /// external source.
1176 /// \return \c true if any declarations were added.
1178 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1179 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1180 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1182 // Notify that we have a DeclContext that is initializing.
1183 ExternalASTSource::Deserializing ADeclContext(Source);
1185 // Load the external declarations, if any.
1186 SmallVector<Decl*, 64> Decls;
1187 ExternalLexicalStorage = false;
1188 Source->FindExternalLexicalDecls(this, Decls);
1193 // We may have already loaded just the fields of this record, in which case
1194 // we need to ignore them.
1195 bool FieldsAlreadyLoaded = false;
1196 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1197 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1199 // Splice the newly-read declarations into the beginning of the list
1201 Decl *ExternalFirst, *ExternalLast;
1202 std::tie(ExternalFirst, ExternalLast) =
1203 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1204 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1205 FirstDecl = ExternalFirst;
1207 LastDecl = ExternalLast;
1211 DeclContext::lookup_result
1212 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1213 DeclarationName Name) {
1214 ASTContext &Context = DC->getParentASTContext();
1215 StoredDeclsMap *Map;
1216 if (!(Map = DC->LookupPtr))
1217 Map = DC->CreateStoredDeclsMap(Context);
1218 if (DC->NeedToReconcileExternalVisibleStorage)
1219 DC->reconcileExternalVisibleStorage();
1221 (*Map)[Name].removeExternalDecls();
1223 return DeclContext::lookup_result();
1226 DeclContext::lookup_result
1227 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1228 DeclarationName Name,
1229 ArrayRef<NamedDecl*> Decls) {
1230 ASTContext &Context = DC->getParentASTContext();
1231 StoredDeclsMap *Map;
1232 if (!(Map = DC->LookupPtr))
1233 Map = DC->CreateStoredDeclsMap(Context);
1234 if (DC->NeedToReconcileExternalVisibleStorage)
1235 DC->reconcileExternalVisibleStorage();
1237 StoredDeclsList &List = (*Map)[Name];
1239 // Clear out any old external visible declarations, to avoid quadratic
1240 // performance in the redeclaration checks below.
1241 List.removeExternalDecls();
1243 if (!List.isNull()) {
1244 // We have both existing declarations and new declarations for this name.
1245 // Some of the declarations may simply replace existing ones. Handle those
1247 llvm::SmallVector<unsigned, 8> Skip;
1248 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1249 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1251 Skip.push_back(Decls.size());
1253 // Add in any new declarations.
1254 unsigned SkipPos = 0;
1255 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1256 if (I == Skip[SkipPos])
1259 List.AddSubsequentDecl(Decls[I]);
1262 // Convert the array to a StoredDeclsList.
1263 for (ArrayRef<NamedDecl*>::iterator
1264 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1266 List.setOnlyValue(*I);
1268 List.AddSubsequentDecl(*I);
1272 return List.getLookupResult();
1275 DeclContext::decl_iterator DeclContext::decls_begin() const {
1276 if (hasExternalLexicalStorage())
1277 LoadLexicalDeclsFromExternalStorage();
1278 return decl_iterator(FirstDecl);
1281 bool DeclContext::decls_empty() const {
1282 if (hasExternalLexicalStorage())
1283 LoadLexicalDeclsFromExternalStorage();
1288 bool DeclContext::containsDecl(Decl *D) const {
1289 return (D->getLexicalDeclContext() == this &&
1290 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1293 void DeclContext::removeDecl(Decl *D) {
1294 assert(D->getLexicalDeclContext() == this &&
1295 "decl being removed from non-lexical context");
1296 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1297 "decl is not in decls list");
1299 // Remove D from the decl chain. This is O(n) but hopefully rare.
1300 if (D == FirstDecl) {
1302 FirstDecl = LastDecl = nullptr;
1304 FirstDecl = D->NextInContextAndBits.getPointer();
1306 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1307 assert(I && "decl not found in linked list");
1308 if (I->NextInContextAndBits.getPointer() == D) {
1309 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1310 if (D == LastDecl) LastDecl = I;
1316 // Mark that D is no longer in the decl chain.
1317 D->NextInContextAndBits.setPointer(nullptr);
1319 // Remove D from the lookup table if necessary.
1320 if (isa<NamedDecl>(D)) {
1321 NamedDecl *ND = cast<NamedDecl>(D);
1323 // Remove only decls that have a name
1324 if (!ND->getDeclName()) return;
1328 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1330 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1331 assert(Pos != Map->end() && "no lookup entry for decl");
1332 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1333 Pos->second.remove(ND);
1335 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1339 void DeclContext::addHiddenDecl(Decl *D) {
1340 assert(D->getLexicalDeclContext() == this &&
1341 "Decl inserted into wrong lexical context");
1342 assert(!D->getNextDeclInContext() && D != LastDecl &&
1343 "Decl already inserted into a DeclContext");
1346 LastDecl->NextInContextAndBits.setPointer(D);
1349 FirstDecl = LastDecl = D;
1352 // Notify a C++ record declaration that we've added a member, so it can
1353 // update its class-specific state.
1354 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1355 Record->addedMember(D);
1357 // If this is a newly-created (not de-serialized) import declaration, wire
1358 // it in to the list of local import declarations.
1359 if (!D->isFromASTFile()) {
1360 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1361 D->getASTContext().addedLocalImportDecl(Import);
1365 void DeclContext::addDecl(Decl *D) {
1368 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1369 ND->getDeclContext()->getPrimaryContext()->
1370 makeDeclVisibleInContextWithFlags(ND, false, true);
1373 void DeclContext::addDeclInternal(Decl *D) {
1376 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1377 ND->getDeclContext()->getPrimaryContext()->
1378 makeDeclVisibleInContextWithFlags(ND, true, true);
1381 /// shouldBeHidden - Determine whether a declaration which was declared
1382 /// within its semantic context should be invisible to qualified name lookup.
1383 static bool shouldBeHidden(NamedDecl *D) {
1384 // Skip unnamed declarations.
1385 if (!D->getDeclName())
1388 // Skip entities that can't be found by name lookup into a particular
1390 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1391 D->isTemplateParameter())
1394 // Skip template specializations.
1395 // FIXME: This feels like a hack. Should DeclarationName support
1396 // template-ids, or is there a better way to keep specializations
1397 // from being visible?
1398 if (isa<ClassTemplateSpecializationDecl>(D))
1400 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1401 if (FD->isFunctionTemplateSpecialization())
1407 /// buildLookup - Build the lookup data structure with all of the
1408 /// declarations in this DeclContext (and any other contexts linked
1409 /// to it or transparent contexts nested within it) and return it.
1411 /// Note that the produced map may miss out declarations from an
1412 /// external source. If it does, those entries will be marked with
1413 /// the 'hasExternalDecls' flag.
1414 StoredDeclsMap *DeclContext::buildLookup() {
1415 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1417 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1420 SmallVector<DeclContext *, 2> Contexts;
1421 collectAllContexts(Contexts);
1423 if (HasLazyExternalLexicalLookups) {
1424 HasLazyExternalLexicalLookups = false;
1425 for (auto *DC : Contexts) {
1426 if (DC->hasExternalLexicalStorage())
1427 HasLazyLocalLexicalLookups |=
1428 DC->LoadLexicalDeclsFromExternalStorage();
1431 if (!HasLazyLocalLexicalLookups)
1435 for (auto *DC : Contexts)
1436 buildLookupImpl(DC, hasExternalVisibleStorage());
1438 // We no longer have any lazy decls.
1439 HasLazyLocalLexicalLookups = false;
1443 /// buildLookupImpl - Build part of the lookup data structure for the
1444 /// declarations contained within DCtx, which will either be this
1445 /// DeclContext, a DeclContext linked to it, or a transparent context
1446 /// nested within it.
1447 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1448 for (Decl *D : DCtx->noload_decls()) {
1449 // Insert this declaration into the lookup structure, but only if
1450 // it's semantically within its decl context. Any other decls which
1451 // should be found in this context are added eagerly.
1453 // If it's from an AST file, don't add it now. It'll get handled by
1454 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1455 // in C++, we do not track external visible decls for the TU, so in
1456 // that case we need to collect them all here.
1457 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1458 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1459 (!ND->isFromASTFile() ||
1460 (isTranslationUnit() &&
1461 !getParentASTContext().getLangOpts().CPlusPlus)))
1462 makeDeclVisibleInContextImpl(ND, Internal);
1464 // If this declaration is itself a transparent declaration context
1465 // or inline namespace, add the members of this declaration of that
1466 // context (recursively).
1467 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1468 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1469 buildLookupImpl(InnerCtx, Internal);
1473 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1475 DeclContext::lookup_result
1476 DeclContext::lookup(DeclarationName Name) const {
1477 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1478 "should not perform lookups into transparent contexts");
1480 const DeclContext *PrimaryContext = getPrimaryContext();
1481 if (PrimaryContext != this)
1482 return PrimaryContext->lookup(Name);
1484 // If we have an external source, ensure that any later redeclarations of this
1485 // context have been loaded, since they may add names to the result of this
1486 // lookup (or add external visible storage).
1487 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1489 (void)cast<Decl>(this)->getMostRecentDecl();
1491 if (hasExternalVisibleStorage()) {
1492 assert(Source && "external visible storage but no external source?");
1494 if (NeedToReconcileExternalVisibleStorage)
1495 reconcileExternalVisibleStorage();
1497 StoredDeclsMap *Map = LookupPtr;
1499 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1500 // FIXME: Make buildLookup const?
1501 Map = const_cast<DeclContext*>(this)->buildLookup();
1504 Map = CreateStoredDeclsMap(getParentASTContext());
1506 // If we have a lookup result with no external decls, we are done.
1507 std::pair<StoredDeclsMap::iterator, bool> R =
1508 Map->insert(std::make_pair(Name, StoredDeclsList()));
1509 if (!R.second && !R.first->second.hasExternalDecls())
1510 return R.first->second.getLookupResult();
1512 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1513 if (StoredDeclsMap *Map = LookupPtr) {
1514 StoredDeclsMap::iterator I = Map->find(Name);
1515 if (I != Map->end())
1516 return I->second.getLookupResult();
1520 return lookup_result();
1523 StoredDeclsMap *Map = LookupPtr;
1524 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1525 Map = const_cast<DeclContext*>(this)->buildLookup();
1528 return lookup_result();
1530 StoredDeclsMap::iterator I = Map->find(Name);
1531 if (I == Map->end())
1532 return lookup_result();
1534 return I->second.getLookupResult();
1537 DeclContext::lookup_result
1538 DeclContext::noload_lookup(DeclarationName Name) {
1539 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1540 "should not perform lookups into transparent contexts");
1542 DeclContext *PrimaryContext = getPrimaryContext();
1543 if (PrimaryContext != this)
1544 return PrimaryContext->noload_lookup(Name);
1546 // If we have any lazy lexical declarations not in our lookup map, add them
1547 // now. Don't import any external declarations, not even if we know we have
1548 // some missing from the external visible lookups.
1549 if (HasLazyLocalLexicalLookups) {
1550 SmallVector<DeclContext *, 2> Contexts;
1551 collectAllContexts(Contexts);
1552 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1553 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1554 HasLazyLocalLexicalLookups = false;
1557 StoredDeclsMap *Map = LookupPtr;
1559 return lookup_result();
1561 StoredDeclsMap::iterator I = Map->find(Name);
1562 return I != Map->end() ? I->second.getLookupResult()
1566 void DeclContext::localUncachedLookup(DeclarationName Name,
1567 SmallVectorImpl<NamedDecl *> &Results) {
1570 // If there's no external storage, just perform a normal lookup and copy
1572 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1573 lookup_result LookupResults = lookup(Name);
1574 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1578 // If we have a lookup table, check there first. Maybe we'll get lucky.
1579 // FIXME: Should we be checking these flags on the primary context?
1580 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1581 if (StoredDeclsMap *Map = LookupPtr) {
1582 StoredDeclsMap::iterator Pos = Map->find(Name);
1583 if (Pos != Map->end()) {
1584 Results.insert(Results.end(),
1585 Pos->second.getLookupResult().begin(),
1586 Pos->second.getLookupResult().end());
1592 // Slow case: grovel through the declarations in our chain looking for
1594 // FIXME: If we have lazy external declarations, this will not find them!
1595 // FIXME: Should we CollectAllContexts and walk them all here?
1596 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1597 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1598 if (ND->getDeclName() == Name)
1599 Results.push_back(ND);
1603 DeclContext *DeclContext::getRedeclContext() {
1604 DeclContext *Ctx = this;
1605 // Skip through transparent contexts.
1606 while (Ctx->isTransparentContext())
1607 Ctx = Ctx->getParent();
1611 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1612 DeclContext *Ctx = this;
1613 // Skip through non-namespace, non-translation-unit contexts.
1614 while (!Ctx->isFileContext())
1615 Ctx = Ctx->getParent();
1616 return Ctx->getPrimaryContext();
1619 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1620 // Loop until we find a non-record context.
1621 RecordDecl *OutermostRD = nullptr;
1622 DeclContext *DC = this;
1623 while (DC->isRecord()) {
1624 OutermostRD = cast<RecordDecl>(DC);
1625 DC = DC->getLexicalParent();
1630 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1631 // For non-file contexts, this is equivalent to Equals.
1632 if (!isFileContext())
1633 return O->Equals(this);
1636 if (O->Equals(this))
1639 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1640 if (!NS || !NS->isInline())
1642 O = NS->getParent();
1648 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1649 DeclContext *PrimaryDC = this->getPrimaryContext();
1650 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1651 // If the decl is being added outside of its semantic decl context, we
1652 // need to ensure that we eagerly build the lookup information for it.
1653 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1656 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1658 assert(this == getPrimaryContext() && "expected a primary DC");
1660 if (!isLookupContext()) {
1661 if (isTransparentContext())
1662 getParent()->getPrimaryContext()
1663 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1667 // Skip declarations which should be invisible to name lookup.
1668 if (shouldBeHidden(D))
1671 // If we already have a lookup data structure, perform the insertion into
1672 // it. If we might have externally-stored decls with this name, look them
1673 // up and perform the insertion. If this decl was declared outside its
1674 // semantic context, buildLookup won't add it, so add it now.
1676 // FIXME: As a performance hack, don't add such decls into the translation
1677 // unit unless we're in C++, since qualified lookup into the TU is never
1679 if (LookupPtr || hasExternalVisibleStorage() ||
1680 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1681 (getParentASTContext().getLangOpts().CPlusPlus ||
1682 !isTranslationUnit()))) {
1683 // If we have lazily omitted any decls, they might have the same name as
1684 // the decl which we are adding, so build a full lookup table before adding
1687 makeDeclVisibleInContextImpl(D, Internal);
1689 HasLazyLocalLexicalLookups = true;
1692 // If we are a transparent context or inline namespace, insert into our
1693 // parent context, too. This operation is recursive.
1694 if (isTransparentContext() || isInlineNamespace())
1695 getParent()->getPrimaryContext()->
1696 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1698 Decl *DCAsDecl = cast<Decl>(this);
1699 // Notify that a decl was made visible unless we are a Tag being defined.
1700 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1701 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1702 L->AddedVisibleDecl(this, D);
1705 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1706 // Find or create the stored declaration map.
1707 StoredDeclsMap *Map = LookupPtr;
1709 ASTContext *C = &getParentASTContext();
1710 Map = CreateStoredDeclsMap(*C);
1713 // If there is an external AST source, load any declarations it knows about
1714 // with this declaration's name.
1715 // If the lookup table contains an entry about this name it means that we
1716 // have already checked the external source.
1718 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1719 if (hasExternalVisibleStorage() &&
1720 Map->find(D->getDeclName()) == Map->end())
1721 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1723 // Insert this declaration into the map.
1724 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1727 // If this is being added as part of loading an external declaration,
1728 // this may not be the only external declaration with this name.
1729 // In this case, we never try to replace an existing declaration; we'll
1730 // handle that when we finalize the list of declarations for this name.
1731 DeclNameEntries.setHasExternalDecls();
1732 DeclNameEntries.AddSubsequentDecl(D);
1736 if (DeclNameEntries.isNull()) {
1737 DeclNameEntries.setOnlyValue(D);
1741 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1742 // This declaration has replaced an existing one for which
1743 // declarationReplaces returns true.
1747 // Put this declaration into the appropriate slot.
1748 DeclNameEntries.AddSubsequentDecl(D);
1751 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1752 return cast<UsingDirectiveDecl>(*I);
1755 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1757 DeclContext::udir_range DeclContext::using_directives() const {
1758 // FIXME: Use something more efficient than normal lookup for using
1759 // directives. In C++, using directives are looked up more than anything else.
1760 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1761 return udir_range(Result.begin(), Result.end());
1764 //===----------------------------------------------------------------------===//
1765 // Creation and Destruction of StoredDeclsMaps. //
1766 //===----------------------------------------------------------------------===//
1768 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1769 assert(!LookupPtr && "context already has a decls map");
1770 assert(getPrimaryContext() == this &&
1771 "creating decls map on non-primary context");
1774 bool Dependent = isDependentContext();
1776 M = new DependentStoredDeclsMap();
1778 M = new StoredDeclsMap();
1779 M->Previous = C.LastSDM;
1780 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1785 void ASTContext::ReleaseDeclContextMaps() {
1786 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1787 // pointer because the subclass doesn't add anything that needs to
1789 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1792 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1794 // Advance the iteration before we invalidate memory.
1795 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1798 delete static_cast<DependentStoredDeclsMap*>(Map);
1802 Map = Next.getPointer();
1803 Dependent = Next.getInt();
1807 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1808 DeclContext *Parent,
1809 const PartialDiagnostic &PDiag) {
1810 assert(Parent->isDependentContext()
1811 && "cannot iterate dependent diagnostics of non-dependent context");
1812 Parent = Parent->getPrimaryContext();
1813 if (!Parent->LookupPtr)
1814 Parent->CreateStoredDeclsMap(C);
1816 DependentStoredDeclsMap *Map =
1817 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1819 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1820 // BumpPtrAllocator, rather than the ASTContext itself.
1821 PartialDiagnostic::Storage *DiagStorage = nullptr;
1822 if (PDiag.hasStorage())
1823 DiagStorage = new (C) PartialDiagnostic::Storage;
1825 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1827 // TODO: Maybe we shouldn't reverse the order during insertion.
1828 DD->NextDiagnostic = Map->FirstDiagnostic;
1829 Map->FirstDiagnostic = DD;