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/AttrIterator.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DependentDiagnostic.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/Stmt.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/IdentifierTable.h"
31 #include "clang/Basic/LLVM.h"
32 #include "clang/Basic/LangOptions.h"
33 #include "clang/Basic/ObjCRuntime.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/VersionTuple.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/PointerIntPair.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
53 using namespace clang;
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
60 #define ABSTRACT_DECL(DECL)
61 #include "clang/AST/DeclNodes.inc"
63 void Decl::updateOutOfDate(IdentifierInfo &II) const {
64 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
67 #define DECL(DERIVED, BASE) \
68 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
69 "Alignment sufficient after objects prepended to " #DERIVED);
70 #define ABSTRACT_DECL(DECL)
71 #include "clang/AST/DeclNodes.inc"
73 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
74 unsigned ID, std::size_t Extra) {
75 // Allocate an extra 8 bytes worth of storage, which ensures that the
76 // resulting pointer will still be 8-byte aligned.
77 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
78 "Decl won't be misaligned");
79 void *Start = Context.Allocate(Size + Extra + 8);
80 void *Result = (char*)Start + 8;
82 unsigned *PrefixPtr = (unsigned *)Result - 2;
84 // Zero out the first 4 bytes; this is used to store the owning module ID.
87 // Store the global declaration ID in the second 4 bytes.
93 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94 DeclContext *Parent, std::size_t Extra) {
95 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
96 // With local visibility enabled, we track the owning module even for local
97 // declarations. We create the TU decl early and may not yet know what the
98 // LangOpts are, so conservatively allocate the storage.
99 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
100 // Ensure required alignment of the resulting object by adding extra
101 // padding at the start if required.
103 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
104 char *Buffer = reinterpret_cast<char *>(
105 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
106 Buffer += ExtraAlign;
108 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
109 return new (Buffer) Module*(ParentModule) + 1;
111 return ::operator new(Size + Extra, Ctx);
114 Module *Decl::getOwningModuleSlow() const {
115 assert(isFromASTFile() && "Not from AST file?");
116 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
119 bool Decl::hasLocalOwningModuleStorage() const {
120 return getASTContext().getLangOpts().trackLocalOwningModule();
123 const char *Decl::getDeclKindName() const {
125 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
126 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127 #define ABSTRACT_DECL(DECL)
128 #include "clang/AST/DeclNodes.inc"
132 void Decl::setInvalidDecl(bool Invalid) {
133 InvalidDecl = Invalid;
134 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
139 if (!isa<ParmVarDecl>(this)) {
140 // Defensive maneuver for ill-formed code: we're likely not to make it to
141 // a point where we set the access specifier, so default it to "public"
142 // to avoid triggering asserts elsewhere in the front end.
143 setAccess(AS_public);
146 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
148 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
149 for (BindingDecl *Binding : DD->bindings()) {
150 Binding->setInvalidDecl();
155 const char *DeclContext::getDeclKindName() const {
157 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
158 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
159 #define ABSTRACT_DECL(DECL)
160 #include "clang/AST/DeclNodes.inc"
164 bool Decl::StatisticsEnabled = false;
165 void Decl::EnableStatistics() {
166 StatisticsEnabled = true;
169 void Decl::PrintStats() {
170 llvm::errs() << "\n*** Decl Stats:\n";
173 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
174 #define ABSTRACT_DECL(DECL)
175 #include "clang/AST/DeclNodes.inc"
176 llvm::errs() << " " << totalDecls << " decls total.\n";
179 #define DECL(DERIVED, BASE) \
180 if (n##DERIVED##s > 0) { \
181 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
182 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
183 << sizeof(DERIVED##Decl) << " each (" \
184 << n##DERIVED##s * sizeof(DERIVED##Decl) \
187 #define ABSTRACT_DECL(DECL)
188 #include "clang/AST/DeclNodes.inc"
190 llvm::errs() << "Total bytes = " << totalBytes << "\n";
193 void Decl::add(Kind k) {
195 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
196 #define ABSTRACT_DECL(DECL)
197 #include "clang/AST/DeclNodes.inc"
201 bool Decl::isTemplateParameterPack() const {
202 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
203 return TTP->isParameterPack();
204 if (const NonTypeTemplateParmDecl *NTTP
205 = dyn_cast<NonTypeTemplateParmDecl>(this))
206 return NTTP->isParameterPack();
207 if (const TemplateTemplateParmDecl *TTP
208 = dyn_cast<TemplateTemplateParmDecl>(this))
209 return TTP->isParameterPack();
213 bool Decl::isParameterPack() const {
214 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
215 return Parm->isParameterPack();
217 return isTemplateParameterPack();
220 FunctionDecl *Decl::getAsFunction() {
221 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
223 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
224 return FTD->getTemplatedDecl();
228 bool Decl::isTemplateDecl() const {
229 return isa<TemplateDecl>(this);
232 TemplateDecl *Decl::getDescribedTemplate() const {
233 if (auto *FD = dyn_cast<FunctionDecl>(this))
234 return FD->getDescribedFunctionTemplate();
235 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
236 return RD->getDescribedClassTemplate();
237 else if (auto *VD = dyn_cast<VarDecl>(this))
238 return VD->getDescribedVarTemplate();
239 else if (auto *AD = dyn_cast<TypeAliasDecl>(this))
240 return AD->getDescribedAliasTemplate();
245 bool Decl::isTemplated() const {
246 // A declaration is dependent if it is a template or a template pattern, or
247 // is within (lexcially for a friend, semantically otherwise) a dependent
249 // FIXME: Should local extern declarations be treated like friends?
250 if (auto *AsDC = dyn_cast<DeclContext>(this))
251 return AsDC->isDependentContext();
252 auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
253 return DC->isDependentContext() || isTemplateDecl() || getDescribedTemplate();
256 const DeclContext *Decl::getParentFunctionOrMethod() const {
257 for (const DeclContext *DC = getDeclContext();
258 DC && !DC->isTranslationUnit() && !DC->isNamespace();
259 DC = DC->getParent())
260 if (DC->isFunctionOrMethod())
266 //===----------------------------------------------------------------------===//
267 // PrettyStackTraceDecl Implementation
268 //===----------------------------------------------------------------------===//
270 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
271 SourceLocation TheLoc = Loc;
272 if (TheLoc.isInvalid() && TheDecl)
273 TheLoc = TheDecl->getLocation();
275 if (TheLoc.isValid()) {
276 TheLoc.print(OS, SM);
282 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
284 DN->printQualifiedName(OS);
290 //===----------------------------------------------------------------------===//
291 // Decl Implementation
292 //===----------------------------------------------------------------------===//
294 // Out-of-line virtual method providing a home for Decl.
295 Decl::~Decl() = default;
297 void Decl::setDeclContext(DeclContext *DC) {
301 void Decl::setLexicalDeclContext(DeclContext *DC) {
302 if (DC == getLexicalDeclContext())
306 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
308 getMultipleDC()->LexicalDC = DC;
311 // FIXME: We shouldn't be changing the lexical context of declarations
312 // imported from AST files.
313 if (!isFromASTFile()) {
314 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
315 if (hasOwningModule())
316 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
320 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
321 getOwningModule()) &&
322 "hidden declaration has no owning module");
325 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
327 if (SemaDC == LexicalDC) {
330 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
331 MDC->SemanticDC = SemaDC;
332 MDC->LexicalDC = LexicalDC;
337 bool Decl::isLexicallyWithinFunctionOrMethod() const {
338 const DeclContext *LDC = getLexicalDeclContext();
340 if (LDC->isFunctionOrMethod())
342 if (!isa<TagDecl>(LDC))
344 LDC = LDC->getLexicalParent();
349 bool Decl::isInAnonymousNamespace() const {
350 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
351 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
352 if (ND->isAnonymousNamespace())
359 bool Decl::isInStdNamespace() const {
360 return getDeclContext()->isStdNamespace();
363 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
364 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
367 DeclContext *DC = getDeclContext();
368 assert(DC && "This decl is not contained in a translation unit!");
370 while (!DC->isTranslationUnit()) {
371 DC = DC->getParent();
372 assert(DC && "This decl is not contained in a translation unit!");
375 return cast<TranslationUnitDecl>(DC);
378 ASTContext &Decl::getASTContext() const {
379 return getTranslationUnitDecl()->getASTContext();
382 ASTMutationListener *Decl::getASTMutationListener() const {
383 return getASTContext().getASTMutationListener();
386 unsigned Decl::getMaxAlignment() const {
391 const AttrVec &V = getAttrs();
392 ASTContext &Ctx = getASTContext();
393 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
395 Align = std::max(Align, I->getAlignment(Ctx));
399 bool Decl::isUsed(bool CheckUsedAttr) const {
400 const Decl *CanonD = getCanonicalDecl();
404 // Check for used attribute.
405 // Ask the most recent decl, since attributes accumulate in the redecl chain.
406 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
409 // The information may have not been deserialized yet. Force deserialization
410 // to complete the needed information.
411 return getMostRecentDecl()->getCanonicalDecl()->Used;
414 void Decl::markUsed(ASTContext &C) {
418 if (C.getASTMutationListener())
419 C.getASTMutationListener()->DeclarationMarkedUsed(this);
424 bool Decl::isReferenced() const {
428 // Check redeclarations.
429 for (auto I : redecls())
436 bool Decl::isExported() const {
437 if (isModulePrivate())
439 // Namespaces are always exported.
440 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
442 // Otherwise, this is a strictly lexical check.
443 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
444 if (cast<Decl>(DC)->isModulePrivate())
446 if (isa<ExportDecl>(DC))
452 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
453 const Decl *Definition = nullptr;
454 if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
455 Definition = ID->getDefinition();
456 } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
457 Definition = PD->getDefinition();
458 } else if (auto TD = dyn_cast<TagDecl>(this)) {
459 Definition = TD->getDefinition();
464 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
466 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
467 return dcd->getAttr<ExternalSourceSymbolAttr>();
473 bool Decl::hasDefiningAttr() const {
474 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
477 const Attr *Decl::getDefiningAttr() const {
478 if (AliasAttr *AA = getAttr<AliasAttr>())
480 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
485 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
486 const ASTContext &Context) {
487 // Check if this is an App Extension "platform", and if so chop off
488 // the suffix for matching with the actual platform.
489 StringRef RealizedPlatform = A->getPlatform()->getName();
490 if (!Context.getLangOpts().AppExt)
491 return RealizedPlatform;
492 size_t suffix = RealizedPlatform.rfind("_app_extension");
493 if (suffix != StringRef::npos)
494 return RealizedPlatform.slice(0, suffix);
495 return RealizedPlatform;
498 /// \brief Determine the availability of the given declaration based on
499 /// the target platform.
501 /// When it returns an availability result other than \c AR_Available,
502 /// if the \p Message parameter is non-NULL, it will be set to a
503 /// string describing why the entity is unavailable.
505 /// FIXME: Make these strings localizable, since they end up in
507 static AvailabilityResult CheckAvailability(ASTContext &Context,
508 const AvailabilityAttr *A,
509 std::string *Message,
510 VersionTuple EnclosingVersion) {
511 if (EnclosingVersion.empty())
512 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
514 if (EnclosingVersion.empty())
517 StringRef ActualPlatform = A->getPlatform()->getName();
518 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
520 // Match the platform name.
521 if (getRealizedPlatform(A, Context) != TargetPlatform)
524 StringRef PrettyPlatformName
525 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
527 if (PrettyPlatformName.empty())
528 PrettyPlatformName = ActualPlatform;
530 std::string HintMessage;
531 if (!A->getMessage().empty()) {
533 HintMessage += A->getMessage();
536 // Make sure that this declaration has not been marked 'unavailable'.
537 if (A->getUnavailable()) {
540 llvm::raw_string_ostream Out(*Message);
541 Out << "not available on " << PrettyPlatformName
545 return AR_Unavailable;
548 // Make sure that this declaration has already been introduced.
549 if (!A->getIntroduced().empty() &&
550 EnclosingVersion < A->getIntroduced()) {
553 llvm::raw_string_ostream Out(*Message);
554 VersionTuple VTI(A->getIntroduced());
555 VTI.UseDotAsSeparator();
556 Out << "introduced in " << PrettyPlatformName << ' '
557 << VTI << HintMessage;
560 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
563 // Make sure that this declaration hasn't been obsoleted.
564 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
567 llvm::raw_string_ostream Out(*Message);
568 VersionTuple VTO(A->getObsoleted());
569 VTO.UseDotAsSeparator();
570 Out << "obsoleted in " << PrettyPlatformName << ' '
571 << VTO << HintMessage;
574 return AR_Unavailable;
577 // Make sure that this declaration hasn't been deprecated.
578 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
581 llvm::raw_string_ostream Out(*Message);
582 VersionTuple VTD(A->getDeprecated());
583 VTD.UseDotAsSeparator();
584 Out << "first deprecated in " << PrettyPlatformName << ' '
585 << VTD << HintMessage;
588 return AR_Deprecated;
594 AvailabilityResult Decl::getAvailability(std::string *Message,
595 VersionTuple EnclosingVersion) const {
596 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
597 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
599 AvailabilityResult Result = AR_Available;
600 std::string ResultMessage;
602 for (const auto *A : attrs()) {
603 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
604 if (Result >= AR_Deprecated)
608 ResultMessage = Deprecated->getMessage();
610 Result = AR_Deprecated;
614 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
616 *Message = Unavailable->getMessage();
617 return AR_Unavailable;
620 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
621 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
622 Message, EnclosingVersion);
624 if (AR == AR_Unavailable)
625 return AR_Unavailable;
630 ResultMessage.swap(*Message);
637 Message->swap(ResultMessage);
641 VersionTuple Decl::getVersionIntroduced() const {
642 const ASTContext &Context = getASTContext();
643 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
644 for (const auto *A : attrs()) {
645 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
646 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
648 if (!Availability->getIntroduced().empty())
649 return Availability->getIntroduced();
652 return VersionTuple();
655 bool Decl::canBeWeakImported(bool &IsDefinition) const {
656 IsDefinition = false;
658 // Variables, if they aren't definitions.
659 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
660 if (Var->isThisDeclarationADefinition()) {
666 // Functions, if they aren't definitions.
667 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
674 // Objective-C classes, if this is the non-fragile runtime.
675 } else if (isa<ObjCInterfaceDecl>(this) &&
676 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
685 bool Decl::isWeakImported() const {
687 if (!canBeWeakImported(IsDefinition))
690 for (const auto *A : attrs()) {
691 if (isa<WeakImportAttr>(A))
694 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
695 if (CheckAvailability(getASTContext(), Availability, nullptr,
696 VersionTuple()) == AR_NotYetIntroduced)
704 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
707 case CXXDeductionGuide:
710 case ConstructorUsingShadow:
720 return IDNS_Ordinary;
724 return IDNS_Ordinary | IDNS_Member;
727 case NonTypeTemplateParm:
729 // These (C++-only) declarations are found by redeclaration lookup for
730 // tag types, so we include them in the tag namespace.
731 return IDNS_Ordinary | IDNS_Tag;
733 case ObjCCompatibleAlias:
735 return IDNS_Ordinary | IDNS_Type;
739 case TemplateTypeParm:
741 return IDNS_Ordinary | IDNS_Type;
743 case UnresolvedUsingTypename:
744 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
747 return 0; // we'll actually overwrite this later
749 case UnresolvedUsingValue:
750 return IDNS_Ordinary | IDNS_Using;
757 return IDNS_ObjCProtocol;
760 case ObjCAtDefsField:
767 return IDNS_Tag | IDNS_Type;
771 return IDNS_Namespace;
773 case FunctionTemplate:
774 return IDNS_Ordinary;
777 case TemplateTemplateParm:
778 case TypeAliasTemplate:
779 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
781 case OMPDeclareReduction:
782 return IDNS_OMPReduction;
792 case ObjCPropertyImpl:
794 case PragmaDetectMismatch:
797 case TranslationUnit:
802 case BuiltinTemplate:
803 case ClassTemplateSpecialization:
804 case ClassTemplatePartialSpecialization:
805 case ClassScopeFunctionSpecialization:
806 case VarTemplateSpecialization:
807 case VarTemplatePartialSpecialization:
808 case ObjCImplementation:
810 case ObjCCategoryImpl:
812 case OMPThreadPrivate:
813 case OMPCapturedExpr:
815 // Never looked up by name.
819 llvm_unreachable("Invalid DeclKind!");
822 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
823 assert(!HasAttrs && "Decl already contains attrs.");
825 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
826 assert(AttrBlank.empty() && "HasAttrs was wrong?");
832 void Decl::dropAttrs() {
833 if (!HasAttrs) return;
836 getASTContext().eraseDeclAttrs(this);
839 const AttrVec &Decl::getAttrs() const {
840 assert(HasAttrs && "No attrs to get!");
841 return getASTContext().getDeclAttrs(this);
844 Decl *Decl::castFromDeclContext (const DeclContext *D) {
845 Decl::Kind DK = D->getDeclKind();
847 #define DECL(NAME, BASE)
848 #define DECL_CONTEXT(NAME) \
850 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
851 #define DECL_CONTEXT_BASE(NAME)
852 #include "clang/AST/DeclNodes.inc"
854 #define DECL(NAME, BASE)
855 #define DECL_CONTEXT_BASE(NAME) \
856 if (DK >= first##NAME && DK <= last##NAME) \
857 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
858 #include "clang/AST/DeclNodes.inc"
859 llvm_unreachable("a decl that inherits DeclContext isn't handled");
863 DeclContext *Decl::castToDeclContext(const Decl *D) {
864 Decl::Kind DK = D->getKind();
866 #define DECL(NAME, BASE)
867 #define DECL_CONTEXT(NAME) \
869 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
870 #define DECL_CONTEXT_BASE(NAME)
871 #include "clang/AST/DeclNodes.inc"
873 #define DECL(NAME, BASE)
874 #define DECL_CONTEXT_BASE(NAME) \
875 if (DK >= first##NAME && DK <= last##NAME) \
876 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
877 #include "clang/AST/DeclNodes.inc"
878 llvm_unreachable("a decl that inherits DeclContext isn't handled");
882 SourceLocation Decl::getBodyRBrace() const {
883 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
884 // FunctionDecl stores EndRangeLoc for this purpose.
885 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
886 const FunctionDecl *Definition;
887 if (FD->hasBody(Definition))
888 return Definition->getSourceRange().getEnd();
889 return SourceLocation();
892 if (Stmt *Body = getBody())
893 return Body->getSourceRange().getEnd();
895 return SourceLocation();
898 bool Decl::AccessDeclContextSanity() const {
900 // Suppress this check if any of the following hold:
901 // 1. this is the translation unit (and thus has no parent)
902 // 2. this is a template parameter (and thus doesn't belong to its context)
903 // 3. this is a non-type template parameter
904 // 4. the context is not a record
906 // 6. it's a C++0x static_assert.
907 // 7. it's a block literal declaration
908 if (isa<TranslationUnitDecl>(this) ||
909 isa<TemplateTypeParmDecl>(this) ||
910 isa<NonTypeTemplateParmDecl>(this) ||
911 !isa<CXXRecordDecl>(getDeclContext()) ||
913 isa<StaticAssertDecl>(this) ||
914 isa<BlockDecl>(this) ||
915 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
916 // as DeclContext (?).
917 isa<ParmVarDecl>(this) ||
918 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
919 // AS_none as access specifier.
920 isa<CXXRecordDecl>(this) ||
921 isa<ClassScopeFunctionSpecializationDecl>(this))
924 assert(Access != AS_none &&
925 "Access specifier is AS_none inside a record decl");
930 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
931 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
933 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
935 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
937 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
938 Ty = D->getUnderlyingType();
942 if (Ty->isFunctionPointerType())
943 Ty = Ty->getAs<PointerType>()->getPointeeType();
944 else if (BlocksToo && Ty->isBlockPointerType())
945 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
947 return Ty->getAs<FunctionType>();
950 /// Starting at a given context (a Decl or DeclContext), look for a
951 /// code context that is not a closure (a lambda, block, etc.).
952 template <class T> static Decl *getNonClosureContext(T *D) {
953 if (getKind(D) == Decl::CXXMethod) {
954 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
955 if (MD->getOverloadedOperator() == OO_Call &&
956 MD->getParent()->isLambda())
957 return getNonClosureContext(MD->getParent()->getParent());
959 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
961 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
963 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
964 return getNonClosureContext(BD->getParent());
965 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
966 return getNonClosureContext(CD->getParent());
972 Decl *Decl::getNonClosureContext() {
973 return ::getNonClosureContext(this);
976 Decl *DeclContext::getNonClosureAncestor() {
977 return ::getNonClosureContext(this);
980 //===----------------------------------------------------------------------===//
981 // DeclContext Implementation
982 //===----------------------------------------------------------------------===//
984 bool DeclContext::classof(const Decl *D) {
985 switch (D->getKind()) {
986 #define DECL(NAME, BASE)
987 #define DECL_CONTEXT(NAME) case Decl::NAME:
988 #define DECL_CONTEXT_BASE(NAME)
989 #include "clang/AST/DeclNodes.inc"
992 #define DECL(NAME, BASE)
993 #define DECL_CONTEXT_BASE(NAME) \
994 if (D->getKind() >= Decl::first##NAME && \
995 D->getKind() <= Decl::last##NAME) \
997 #include "clang/AST/DeclNodes.inc"
1002 DeclContext::~DeclContext() = default;
1004 /// \brief Find the parent context of this context that will be
1005 /// used for unqualified name lookup.
1007 /// Generally, the parent lookup context is the semantic context. However, for
1008 /// a friend function the parent lookup context is the lexical context, which
1009 /// is the class in which the friend is declared.
1010 DeclContext *DeclContext::getLookupParent() {
1011 // FIXME: Find a better way to identify friends
1012 if (isa<FunctionDecl>(this))
1013 if (getParent()->getRedeclContext()->isFileContext() &&
1014 getLexicalParent()->getRedeclContext()->isRecord())
1015 return getLexicalParent();
1020 bool DeclContext::isInlineNamespace() const {
1021 return isNamespace() &&
1022 cast<NamespaceDecl>(this)->isInline();
1025 bool DeclContext::isStdNamespace() const {
1029 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
1030 if (ND->isInline()) {
1031 return ND->getParent()->isStdNamespace();
1034 if (!getParent()->getRedeclContext()->isTranslationUnit())
1037 const IdentifierInfo *II = ND->getIdentifier();
1038 return II && II->isStr("std");
1041 bool DeclContext::isDependentContext() const {
1042 if (isFileContext())
1045 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1048 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1049 if (Record->getDescribedClassTemplate())
1052 if (Record->isDependentLambda())
1056 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1057 if (Function->getDescribedFunctionTemplate())
1060 // Friend function declarations are dependent if their *lexical*
1061 // context is dependent.
1062 if (cast<Decl>(this)->getFriendObjectKind())
1063 return getLexicalParent()->isDependentContext();
1066 // FIXME: A variable template is a dependent context, but is not a
1067 // DeclContext. A context within it (such as a lambda-expression)
1068 // should be considered dependent.
1070 return getParent() && getParent()->isDependentContext();
1073 bool DeclContext::isTransparentContext() const {
1074 if (DeclKind == Decl::Enum)
1075 return !cast<EnumDecl>(this)->isScoped();
1076 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1082 static bool isLinkageSpecContext(const DeclContext *DC,
1083 LinkageSpecDecl::LanguageIDs ID) {
1084 while (DC->getDeclKind() != Decl::TranslationUnit) {
1085 if (DC->getDeclKind() == Decl::LinkageSpec)
1086 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1087 DC = DC->getLexicalParent();
1092 bool DeclContext::isExternCContext() const {
1093 return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1096 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1097 const DeclContext *DC = this;
1098 while (DC->getDeclKind() != Decl::TranslationUnit) {
1099 if (DC->getDeclKind() == Decl::LinkageSpec &&
1100 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1101 return cast<LinkageSpecDecl>(DC);
1102 DC = DC->getLexicalParent();
1107 bool DeclContext::isExternCXXContext() const {
1108 return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1111 bool DeclContext::Encloses(const DeclContext *DC) const {
1112 if (getPrimaryContext() != this)
1113 return getPrimaryContext()->Encloses(DC);
1115 for (; DC; DC = DC->getParent())
1116 if (DC->getPrimaryContext() == this)
1121 DeclContext *DeclContext::getPrimaryContext() {
1123 case Decl::TranslationUnit:
1124 case Decl::ExternCContext:
1125 case Decl::LinkageSpec:
1128 case Decl::Captured:
1129 case Decl::OMPDeclareReduction:
1130 // There is only one DeclContext for these entities.
1133 case Decl::Namespace:
1134 // The original namespace is our primary context.
1135 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1137 case Decl::ObjCMethod:
1140 case Decl::ObjCInterface:
1141 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1145 case Decl::ObjCProtocol:
1146 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1150 case Decl::ObjCCategory:
1153 case Decl::ObjCImplementation:
1154 case Decl::ObjCCategoryImpl:
1158 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1159 // If this is a tag type that has a definition or is currently
1160 // being defined, that definition is our primary context.
1161 TagDecl *Tag = cast<TagDecl>(this);
1163 if (TagDecl *Def = Tag->getDefinition())
1166 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1167 // Note, TagType::getDecl returns the (partial) definition one exists.
1168 TagDecl *PossiblePartialDef = TagTy->getDecl();
1169 if (PossiblePartialDef->isBeingDefined())
1170 return PossiblePartialDef;
1172 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1178 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1179 "Unknown DeclContext kind");
1185 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1188 if (DeclKind != Decl::Namespace) {
1189 Contexts.push_back(this);
1193 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1194 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1195 N = N->getPreviousDecl())
1196 Contexts.push_back(N);
1198 std::reverse(Contexts.begin(), Contexts.end());
1201 std::pair<Decl *, Decl *>
1202 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1203 bool FieldsAlreadyLoaded) {
1204 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1205 Decl *FirstNewDecl = nullptr;
1206 Decl *PrevDecl = nullptr;
1207 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1208 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1213 PrevDecl->NextInContextAndBits.setPointer(D);
1220 return std::make_pair(FirstNewDecl, PrevDecl);
1223 /// \brief We have just acquired external visible storage, and we already have
1224 /// built a lookup map. For every name in the map, pull in the new names from
1225 /// the external storage.
1226 void DeclContext::reconcileExternalVisibleStorage() const {
1227 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1228 NeedToReconcileExternalVisibleStorage = false;
1230 for (auto &Lookup : *LookupPtr)
1231 Lookup.second.setHasExternalDecls();
1234 /// \brief Load the declarations within this lexical storage from an
1235 /// external source.
1236 /// \return \c true if any declarations were added.
1238 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1239 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1240 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1242 // Notify that we have a DeclContext that is initializing.
1243 ExternalASTSource::Deserializing ADeclContext(Source);
1245 // Load the external declarations, if any.
1246 SmallVector<Decl*, 64> Decls;
1247 ExternalLexicalStorage = false;
1248 Source->FindExternalLexicalDecls(this, Decls);
1253 // We may have already loaded just the fields of this record, in which case
1254 // we need to ignore them.
1255 bool FieldsAlreadyLoaded = false;
1256 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1257 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1259 // Splice the newly-read declarations into the beginning of the list
1261 Decl *ExternalFirst, *ExternalLast;
1262 std::tie(ExternalFirst, ExternalLast) =
1263 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1264 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1265 FirstDecl = ExternalFirst;
1267 LastDecl = ExternalLast;
1271 DeclContext::lookup_result
1272 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1273 DeclarationName Name) {
1274 ASTContext &Context = DC->getParentASTContext();
1275 StoredDeclsMap *Map;
1276 if (!(Map = DC->LookupPtr))
1277 Map = DC->CreateStoredDeclsMap(Context);
1278 if (DC->NeedToReconcileExternalVisibleStorage)
1279 DC->reconcileExternalVisibleStorage();
1281 (*Map)[Name].removeExternalDecls();
1283 return DeclContext::lookup_result();
1286 DeclContext::lookup_result
1287 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1288 DeclarationName Name,
1289 ArrayRef<NamedDecl*> Decls) {
1290 ASTContext &Context = DC->getParentASTContext();
1291 StoredDeclsMap *Map;
1292 if (!(Map = DC->LookupPtr))
1293 Map = DC->CreateStoredDeclsMap(Context);
1294 if (DC->NeedToReconcileExternalVisibleStorage)
1295 DC->reconcileExternalVisibleStorage();
1297 StoredDeclsList &List = (*Map)[Name];
1299 // Clear out any old external visible declarations, to avoid quadratic
1300 // performance in the redeclaration checks below.
1301 List.removeExternalDecls();
1303 if (!List.isNull()) {
1304 // We have both existing declarations and new declarations for this name.
1305 // Some of the declarations may simply replace existing ones. Handle those
1307 llvm::SmallVector<unsigned, 8> Skip;
1308 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1309 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1311 Skip.push_back(Decls.size());
1313 // Add in any new declarations.
1314 unsigned SkipPos = 0;
1315 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1316 if (I == Skip[SkipPos])
1319 List.AddSubsequentDecl(Decls[I]);
1322 // Convert the array to a StoredDeclsList.
1323 for (ArrayRef<NamedDecl*>::iterator
1324 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1326 List.setOnlyValue(*I);
1328 List.AddSubsequentDecl(*I);
1332 return List.getLookupResult();
1335 DeclContext::decl_iterator DeclContext::decls_begin() const {
1336 if (hasExternalLexicalStorage())
1337 LoadLexicalDeclsFromExternalStorage();
1338 return decl_iterator(FirstDecl);
1341 bool DeclContext::decls_empty() const {
1342 if (hasExternalLexicalStorage())
1343 LoadLexicalDeclsFromExternalStorage();
1348 bool DeclContext::containsDecl(Decl *D) const {
1349 return (D->getLexicalDeclContext() == this &&
1350 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1353 void DeclContext::removeDecl(Decl *D) {
1354 assert(D->getLexicalDeclContext() == this &&
1355 "decl being removed from non-lexical context");
1356 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1357 "decl is not in decls list");
1359 // Remove D from the decl chain. This is O(n) but hopefully rare.
1360 if (D == FirstDecl) {
1362 FirstDecl = LastDecl = nullptr;
1364 FirstDecl = D->NextInContextAndBits.getPointer();
1366 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1367 assert(I && "decl not found in linked list");
1368 if (I->NextInContextAndBits.getPointer() == D) {
1369 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1370 if (D == LastDecl) LastDecl = I;
1376 // Mark that D is no longer in the decl chain.
1377 D->NextInContextAndBits.setPointer(nullptr);
1379 // Remove D from the lookup table if necessary.
1380 if (isa<NamedDecl>(D)) {
1381 NamedDecl *ND = cast<NamedDecl>(D);
1383 // Remove only decls that have a name
1384 if (!ND->getDeclName()) return;
1386 auto *DC = D->getDeclContext();
1388 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1390 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1391 assert(Pos != Map->end() && "no lookup entry for decl");
1392 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1393 Pos->second.remove(ND);
1395 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1399 void DeclContext::addHiddenDecl(Decl *D) {
1400 assert(D->getLexicalDeclContext() == this &&
1401 "Decl inserted into wrong lexical context");
1402 assert(!D->getNextDeclInContext() && D != LastDecl &&
1403 "Decl already inserted into a DeclContext");
1406 LastDecl->NextInContextAndBits.setPointer(D);
1409 FirstDecl = LastDecl = D;
1412 // Notify a C++ record declaration that we've added a member, so it can
1413 // update its class-specific state.
1414 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1415 Record->addedMember(D);
1417 // If this is a newly-created (not de-serialized) import declaration, wire
1418 // it in to the list of local import declarations.
1419 if (!D->isFromASTFile()) {
1420 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1421 D->getASTContext().addedLocalImportDecl(Import);
1425 void DeclContext::addDecl(Decl *D) {
1428 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1429 ND->getDeclContext()->getPrimaryContext()->
1430 makeDeclVisibleInContextWithFlags(ND, false, true);
1433 void DeclContext::addDeclInternal(Decl *D) {
1436 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1437 ND->getDeclContext()->getPrimaryContext()->
1438 makeDeclVisibleInContextWithFlags(ND, true, true);
1441 /// shouldBeHidden - Determine whether a declaration which was declared
1442 /// within its semantic context should be invisible to qualified name lookup.
1443 static bool shouldBeHidden(NamedDecl *D) {
1444 // Skip unnamed declarations.
1445 if (!D->getDeclName())
1448 // Skip entities that can't be found by name lookup into a particular
1450 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1451 D->isTemplateParameter())
1454 // Skip template specializations.
1455 // FIXME: This feels like a hack. Should DeclarationName support
1456 // template-ids, or is there a better way to keep specializations
1457 // from being visible?
1458 if (isa<ClassTemplateSpecializationDecl>(D))
1460 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1461 if (FD->isFunctionTemplateSpecialization())
1467 /// buildLookup - Build the lookup data structure with all of the
1468 /// declarations in this DeclContext (and any other contexts linked
1469 /// to it or transparent contexts nested within it) and return it.
1471 /// Note that the produced map may miss out declarations from an
1472 /// external source. If it does, those entries will be marked with
1473 /// the 'hasExternalDecls' flag.
1474 StoredDeclsMap *DeclContext::buildLookup() {
1475 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1477 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1480 SmallVector<DeclContext *, 2> Contexts;
1481 collectAllContexts(Contexts);
1483 if (HasLazyExternalLexicalLookups) {
1484 HasLazyExternalLexicalLookups = false;
1485 for (auto *DC : Contexts) {
1486 if (DC->hasExternalLexicalStorage())
1487 HasLazyLocalLexicalLookups |=
1488 DC->LoadLexicalDeclsFromExternalStorage();
1491 if (!HasLazyLocalLexicalLookups)
1495 for (auto *DC : Contexts)
1496 buildLookupImpl(DC, hasExternalVisibleStorage());
1498 // We no longer have any lazy decls.
1499 HasLazyLocalLexicalLookups = false;
1503 /// buildLookupImpl - Build part of the lookup data structure for the
1504 /// declarations contained within DCtx, which will either be this
1505 /// DeclContext, a DeclContext linked to it, or a transparent context
1506 /// nested within it.
1507 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1508 for (Decl *D : DCtx->noload_decls()) {
1509 // Insert this declaration into the lookup structure, but only if
1510 // it's semantically within its decl context. Any other decls which
1511 // should be found in this context are added eagerly.
1513 // If it's from an AST file, don't add it now. It'll get handled by
1514 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1515 // in C++, we do not track external visible decls for the TU, so in
1516 // that case we need to collect them all here.
1517 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1518 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1519 (!ND->isFromASTFile() ||
1520 (isTranslationUnit() &&
1521 !getParentASTContext().getLangOpts().CPlusPlus)))
1522 makeDeclVisibleInContextImpl(ND, Internal);
1524 // If this declaration is itself a transparent declaration context
1525 // or inline namespace, add the members of this declaration of that
1526 // context (recursively).
1527 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1528 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1529 buildLookupImpl(InnerCtx, Internal);
1533 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1535 DeclContext::lookup_result
1536 DeclContext::lookup(DeclarationName Name) const {
1537 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1538 "should not perform lookups into transparent contexts");
1540 const DeclContext *PrimaryContext = getPrimaryContext();
1541 if (PrimaryContext != this)
1542 return PrimaryContext->lookup(Name);
1544 // If we have an external source, ensure that any later redeclarations of this
1545 // context have been loaded, since they may add names to the result of this
1546 // lookup (or add external visible storage).
1547 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1549 (void)cast<Decl>(this)->getMostRecentDecl();
1551 if (hasExternalVisibleStorage()) {
1552 assert(Source && "external visible storage but no external source?");
1554 if (NeedToReconcileExternalVisibleStorage)
1555 reconcileExternalVisibleStorage();
1557 StoredDeclsMap *Map = LookupPtr;
1559 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1560 // FIXME: Make buildLookup const?
1561 Map = const_cast<DeclContext*>(this)->buildLookup();
1564 Map = CreateStoredDeclsMap(getParentASTContext());
1566 // If we have a lookup result with no external decls, we are done.
1567 std::pair<StoredDeclsMap::iterator, bool> R =
1568 Map->insert(std::make_pair(Name, StoredDeclsList()));
1569 if (!R.second && !R.first->second.hasExternalDecls())
1570 return R.first->second.getLookupResult();
1572 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1573 if (StoredDeclsMap *Map = LookupPtr) {
1574 StoredDeclsMap::iterator I = Map->find(Name);
1575 if (I != Map->end())
1576 return I->second.getLookupResult();
1580 return lookup_result();
1583 StoredDeclsMap *Map = LookupPtr;
1584 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1585 Map = const_cast<DeclContext*>(this)->buildLookup();
1588 return lookup_result();
1590 StoredDeclsMap::iterator I = Map->find(Name);
1591 if (I == Map->end())
1592 return lookup_result();
1594 return I->second.getLookupResult();
1597 DeclContext::lookup_result
1598 DeclContext::noload_lookup(DeclarationName Name) {
1599 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1600 "should not perform lookups into transparent contexts");
1602 DeclContext *PrimaryContext = getPrimaryContext();
1603 if (PrimaryContext != this)
1604 return PrimaryContext->noload_lookup(Name);
1606 // If we have any lazy lexical declarations not in our lookup map, add them
1607 // now. Don't import any external declarations, not even if we know we have
1608 // some missing from the external visible lookups.
1609 if (HasLazyLocalLexicalLookups) {
1610 SmallVector<DeclContext *, 2> Contexts;
1611 collectAllContexts(Contexts);
1612 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1613 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1614 HasLazyLocalLexicalLookups = false;
1617 StoredDeclsMap *Map = LookupPtr;
1619 return lookup_result();
1621 StoredDeclsMap::iterator I = Map->find(Name);
1622 return I != Map->end() ? I->second.getLookupResult()
1626 void DeclContext::localUncachedLookup(DeclarationName Name,
1627 SmallVectorImpl<NamedDecl *> &Results) {
1630 // If there's no external storage, just perform a normal lookup and copy
1632 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1633 lookup_result LookupResults = lookup(Name);
1634 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1638 // If we have a lookup table, check there first. Maybe we'll get lucky.
1639 // FIXME: Should we be checking these flags on the primary context?
1640 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1641 if (StoredDeclsMap *Map = LookupPtr) {
1642 StoredDeclsMap::iterator Pos = Map->find(Name);
1643 if (Pos != Map->end()) {
1644 Results.insert(Results.end(),
1645 Pos->second.getLookupResult().begin(),
1646 Pos->second.getLookupResult().end());
1652 // Slow case: grovel through the declarations in our chain looking for
1654 // FIXME: If we have lazy external declarations, this will not find them!
1655 // FIXME: Should we CollectAllContexts and walk them all here?
1656 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1657 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1658 if (ND->getDeclName() == Name)
1659 Results.push_back(ND);
1663 DeclContext *DeclContext::getRedeclContext() {
1664 DeclContext *Ctx = this;
1665 // Skip through transparent contexts.
1666 while (Ctx->isTransparentContext())
1667 Ctx = Ctx->getParent();
1671 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1672 DeclContext *Ctx = this;
1673 // Skip through non-namespace, non-translation-unit contexts.
1674 while (!Ctx->isFileContext())
1675 Ctx = Ctx->getParent();
1676 return Ctx->getPrimaryContext();
1679 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1680 // Loop until we find a non-record context.
1681 RecordDecl *OutermostRD = nullptr;
1682 DeclContext *DC = this;
1683 while (DC->isRecord()) {
1684 OutermostRD = cast<RecordDecl>(DC);
1685 DC = DC->getLexicalParent();
1690 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1691 // For non-file contexts, this is equivalent to Equals.
1692 if (!isFileContext())
1693 return O->Equals(this);
1696 if (O->Equals(this))
1699 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1700 if (!NS || !NS->isInline())
1702 O = NS->getParent();
1708 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1709 DeclContext *PrimaryDC = this->getPrimaryContext();
1710 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1711 // If the decl is being added outside of its semantic decl context, we
1712 // need to ensure that we eagerly build the lookup information for it.
1713 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1716 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1718 assert(this == getPrimaryContext() && "expected a primary DC");
1720 if (!isLookupContext()) {
1721 if (isTransparentContext())
1722 getParent()->getPrimaryContext()
1723 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1727 // Skip declarations which should be invisible to name lookup.
1728 if (shouldBeHidden(D))
1731 // If we already have a lookup data structure, perform the insertion into
1732 // it. If we might have externally-stored decls with this name, look them
1733 // up and perform the insertion. If this decl was declared outside its
1734 // semantic context, buildLookup won't add it, so add it now.
1736 // FIXME: As a performance hack, don't add such decls into the translation
1737 // unit unless we're in C++, since qualified lookup into the TU is never
1739 if (LookupPtr || hasExternalVisibleStorage() ||
1740 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1741 (getParentASTContext().getLangOpts().CPlusPlus ||
1742 !isTranslationUnit()))) {
1743 // If we have lazily omitted any decls, they might have the same name as
1744 // the decl which we are adding, so build a full lookup table before adding
1747 makeDeclVisibleInContextImpl(D, Internal);
1749 HasLazyLocalLexicalLookups = true;
1752 // If we are a transparent context or inline namespace, insert into our
1753 // parent context, too. This operation is recursive.
1754 if (isTransparentContext() || isInlineNamespace())
1755 getParent()->getPrimaryContext()->
1756 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1758 Decl *DCAsDecl = cast<Decl>(this);
1759 // Notify that a decl was made visible unless we are a Tag being defined.
1760 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1761 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1762 L->AddedVisibleDecl(this, D);
1765 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1766 // Find or create the stored declaration map.
1767 StoredDeclsMap *Map = LookupPtr;
1769 ASTContext *C = &getParentASTContext();
1770 Map = CreateStoredDeclsMap(*C);
1773 // If there is an external AST source, load any declarations it knows about
1774 // with this declaration's name.
1775 // If the lookup table contains an entry about this name it means that we
1776 // have already checked the external source.
1778 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1779 if (hasExternalVisibleStorage() &&
1780 Map->find(D->getDeclName()) == Map->end())
1781 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1783 // Insert this declaration into the map.
1784 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1787 // If this is being added as part of loading an external declaration,
1788 // this may not be the only external declaration with this name.
1789 // In this case, we never try to replace an existing declaration; we'll
1790 // handle that when we finalize the list of declarations for this name.
1791 DeclNameEntries.setHasExternalDecls();
1792 DeclNameEntries.AddSubsequentDecl(D);
1796 if (DeclNameEntries.isNull()) {
1797 DeclNameEntries.setOnlyValue(D);
1801 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1802 // This declaration has replaced an existing one for which
1803 // declarationReplaces returns true.
1807 // Put this declaration into the appropriate slot.
1808 DeclNameEntries.AddSubsequentDecl(D);
1811 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1812 return cast<UsingDirectiveDecl>(*I);
1815 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1817 DeclContext::udir_range DeclContext::using_directives() const {
1818 // FIXME: Use something more efficient than normal lookup for using
1819 // directives. In C++, using directives are looked up more than anything else.
1820 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1821 return udir_range(Result.begin(), Result.end());
1824 //===----------------------------------------------------------------------===//
1825 // Creation and Destruction of StoredDeclsMaps. //
1826 //===----------------------------------------------------------------------===//
1828 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1829 assert(!LookupPtr && "context already has a decls map");
1830 assert(getPrimaryContext() == this &&
1831 "creating decls map on non-primary context");
1834 bool Dependent = isDependentContext();
1836 M = new DependentStoredDeclsMap();
1838 M = new StoredDeclsMap();
1839 M->Previous = C.LastSDM;
1840 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1845 void ASTContext::ReleaseDeclContextMaps() {
1846 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1847 // pointer because the subclass doesn't add anything that needs to
1849 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1852 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1854 // Advance the iteration before we invalidate memory.
1855 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1858 delete static_cast<DependentStoredDeclsMap*>(Map);
1862 Map = Next.getPointer();
1863 Dependent = Next.getInt();
1867 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1868 DeclContext *Parent,
1869 const PartialDiagnostic &PDiag) {
1870 assert(Parent->isDependentContext()
1871 && "cannot iterate dependent diagnostics of non-dependent context");
1872 Parent = Parent->getPrimaryContext();
1873 if (!Parent->LookupPtr)
1874 Parent->CreateStoredDeclsMap(C);
1876 DependentStoredDeclsMap *Map =
1877 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1879 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1880 // BumpPtrAllocator, rather than the ASTContext itself.
1881 PartialDiagnostic::Storage *DiagStorage = nullptr;
1882 if (PDiag.hasStorage())
1883 DiagStorage = new (C) PartialDiagnostic::Storage;
1885 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1887 // TODO: Maybe we shouldn't reverse the order during insertion.
1888 DD->NextDiagnostic = Map->FirstDiagnostic;
1889 Map->FirstDiagnostic = DD;