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 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
411 const Decl *Definition = nullptr;
412 if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
413 Definition = ID->getDefinition();
414 } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
415 Definition = PD->getDefinition();
416 } else if (auto TD = dyn_cast<TagDecl>(this)) {
417 Definition = TD->getDefinition();
422 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
424 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
425 return dcd->getAttr<ExternalSourceSymbolAttr>();
431 bool Decl::hasDefiningAttr() const {
432 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
435 const Attr *Decl::getDefiningAttr() const {
436 if (AliasAttr *AA = getAttr<AliasAttr>())
438 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
443 StringRef getRealizedPlatform(const AvailabilityAttr *A,
444 const ASTContext &Context) {
445 // Check if this is an App Extension "platform", and if so chop off
446 // the suffix for matching with the actual platform.
447 StringRef RealizedPlatform = A->getPlatform()->getName();
448 if (!Context.getLangOpts().AppExt)
449 return RealizedPlatform;
450 size_t suffix = RealizedPlatform.rfind("_app_extension");
451 if (suffix != StringRef::npos)
452 return RealizedPlatform.slice(0, suffix);
453 return RealizedPlatform;
456 /// \brief Determine the availability of the given declaration based on
457 /// the target platform.
459 /// When it returns an availability result other than \c AR_Available,
460 /// if the \p Message parameter is non-NULL, it will be set to a
461 /// string describing why the entity is unavailable.
463 /// FIXME: Make these strings localizable, since they end up in
465 static AvailabilityResult CheckAvailability(ASTContext &Context,
466 const AvailabilityAttr *A,
467 std::string *Message,
468 VersionTuple EnclosingVersion) {
469 if (EnclosingVersion.empty())
470 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
472 if (EnclosingVersion.empty())
475 StringRef ActualPlatform = A->getPlatform()->getName();
476 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
478 // Match the platform name.
479 if (getRealizedPlatform(A, Context) != TargetPlatform)
482 StringRef PrettyPlatformName
483 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
485 if (PrettyPlatformName.empty())
486 PrettyPlatformName = ActualPlatform;
488 std::string HintMessage;
489 if (!A->getMessage().empty()) {
491 HintMessage += A->getMessage();
494 // Make sure that this declaration has not been marked 'unavailable'.
495 if (A->getUnavailable()) {
498 llvm::raw_string_ostream Out(*Message);
499 Out << "not available on " << PrettyPlatformName
503 return AR_Unavailable;
506 // Make sure that this declaration has already been introduced.
507 if (!A->getIntroduced().empty() &&
508 EnclosingVersion < A->getIntroduced()) {
511 llvm::raw_string_ostream Out(*Message);
512 VersionTuple VTI(A->getIntroduced());
513 VTI.UseDotAsSeparator();
514 Out << "introduced in " << PrettyPlatformName << ' '
515 << VTI << HintMessage;
518 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
521 // Make sure that this declaration hasn't been obsoleted.
522 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
525 llvm::raw_string_ostream Out(*Message);
526 VersionTuple VTO(A->getObsoleted());
527 VTO.UseDotAsSeparator();
528 Out << "obsoleted in " << PrettyPlatformName << ' '
529 << VTO << HintMessage;
532 return AR_Unavailable;
535 // Make sure that this declaration hasn't been deprecated.
536 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
539 llvm::raw_string_ostream Out(*Message);
540 VersionTuple VTD(A->getDeprecated());
541 VTD.UseDotAsSeparator();
542 Out << "first deprecated in " << PrettyPlatformName << ' '
543 << VTD << HintMessage;
546 return AR_Deprecated;
552 AvailabilityResult Decl::getAvailability(std::string *Message,
553 VersionTuple EnclosingVersion) const {
554 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
555 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
557 AvailabilityResult Result = AR_Available;
558 std::string ResultMessage;
560 for (const auto *A : attrs()) {
561 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
562 if (Result >= AR_Deprecated)
566 ResultMessage = Deprecated->getMessage();
568 Result = AR_Deprecated;
572 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
574 *Message = Unavailable->getMessage();
575 return AR_Unavailable;
578 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
579 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
580 Message, EnclosingVersion);
582 if (AR == AR_Unavailable)
583 return AR_Unavailable;
588 ResultMessage.swap(*Message);
595 Message->swap(ResultMessage);
599 VersionTuple Decl::getVersionIntroduced() const {
600 const ASTContext &Context = getASTContext();
601 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
602 for (const auto *A : attrs()) {
603 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
604 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
606 if (!Availability->getIntroduced().empty())
607 return Availability->getIntroduced();
610 return VersionTuple();
613 bool Decl::canBeWeakImported(bool &IsDefinition) const {
614 IsDefinition = false;
616 // Variables, if they aren't definitions.
617 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
618 if (Var->isThisDeclarationADefinition()) {
624 // Functions, if they aren't definitions.
625 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
632 // Objective-C classes, if this is the non-fragile runtime.
633 } else if (isa<ObjCInterfaceDecl>(this) &&
634 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
643 bool Decl::isWeakImported() const {
645 if (!canBeWeakImported(IsDefinition))
648 for (const auto *A : attrs()) {
649 if (isa<WeakImportAttr>(A))
652 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
653 if (CheckAvailability(getASTContext(), Availability, nullptr,
654 VersionTuple()) == AR_NotYetIntroduced)
662 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
665 case CXXDeductionGuide:
668 case ConstructorUsingShadow:
679 return IDNS_Ordinary;
683 return IDNS_Ordinary | IDNS_Member;
685 case NonTypeTemplateParm:
686 // Non-type template parameters are not found by lookups that ignore
687 // non-types, but they are found by redeclaration lookups for tag types,
688 // so we include them in the tag namespace.
689 return IDNS_Ordinary | IDNS_Tag;
691 case ObjCCompatibleAlias:
693 return IDNS_Ordinary | IDNS_Type;
697 case TypeAliasTemplate:
698 case TemplateTypeParm:
700 return IDNS_Ordinary | IDNS_Type;
702 case UnresolvedUsingTypename:
703 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
706 return 0; // we'll actually overwrite this later
708 case UnresolvedUsingValue:
709 return IDNS_Ordinary | IDNS_Using;
716 return IDNS_ObjCProtocol;
719 case ObjCAtDefsField:
726 return IDNS_Tag | IDNS_Type;
730 return IDNS_Namespace;
732 case FunctionTemplate:
734 return IDNS_Ordinary;
737 case TemplateTemplateParm:
738 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
740 case OMPDeclareReduction:
741 return IDNS_OMPReduction;
751 case ObjCPropertyImpl:
753 case PragmaDetectMismatch:
756 case TranslationUnit:
761 case BuiltinTemplate:
762 case ClassTemplateSpecialization:
763 case ClassTemplatePartialSpecialization:
764 case ClassScopeFunctionSpecialization:
765 case VarTemplateSpecialization:
766 case VarTemplatePartialSpecialization:
767 case ObjCImplementation:
769 case ObjCCategoryImpl:
771 case OMPThreadPrivate:
772 case OMPCapturedExpr:
774 // Never looked up by name.
778 llvm_unreachable("Invalid DeclKind!");
781 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
782 assert(!HasAttrs && "Decl already contains attrs.");
784 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
785 assert(AttrBlank.empty() && "HasAttrs was wrong?");
791 void Decl::dropAttrs() {
792 if (!HasAttrs) return;
795 getASTContext().eraseDeclAttrs(this);
798 const AttrVec &Decl::getAttrs() const {
799 assert(HasAttrs && "No attrs to get!");
800 return getASTContext().getDeclAttrs(this);
803 Decl *Decl::castFromDeclContext (const DeclContext *D) {
804 Decl::Kind DK = D->getDeclKind();
806 #define DECL(NAME, BASE)
807 #define DECL_CONTEXT(NAME) \
809 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
810 #define DECL_CONTEXT_BASE(NAME)
811 #include "clang/AST/DeclNodes.inc"
813 #define DECL(NAME, BASE)
814 #define DECL_CONTEXT_BASE(NAME) \
815 if (DK >= first##NAME && DK <= last##NAME) \
816 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
817 #include "clang/AST/DeclNodes.inc"
818 llvm_unreachable("a decl that inherits DeclContext isn't handled");
822 DeclContext *Decl::castToDeclContext(const Decl *D) {
823 Decl::Kind DK = D->getKind();
825 #define DECL(NAME, BASE)
826 #define DECL_CONTEXT(NAME) \
828 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
829 #define DECL_CONTEXT_BASE(NAME)
830 #include "clang/AST/DeclNodes.inc"
832 #define DECL(NAME, BASE)
833 #define DECL_CONTEXT_BASE(NAME) \
834 if (DK >= first##NAME && DK <= last##NAME) \
835 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
836 #include "clang/AST/DeclNodes.inc"
837 llvm_unreachable("a decl that inherits DeclContext isn't handled");
841 SourceLocation Decl::getBodyRBrace() const {
842 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
843 // FunctionDecl stores EndRangeLoc for this purpose.
844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
845 const FunctionDecl *Definition;
846 if (FD->hasBody(Definition))
847 return Definition->getSourceRange().getEnd();
848 return SourceLocation();
851 if (Stmt *Body = getBody())
852 return Body->getSourceRange().getEnd();
854 return SourceLocation();
857 bool Decl::AccessDeclContextSanity() const {
859 // Suppress this check if any of the following hold:
860 // 1. this is the translation unit (and thus has no parent)
861 // 2. this is a template parameter (and thus doesn't belong to its context)
862 // 3. this is a non-type template parameter
863 // 4. the context is not a record
865 // 6. it's a C++0x static_assert.
866 if (isa<TranslationUnitDecl>(this) ||
867 isa<TemplateTypeParmDecl>(this) ||
868 isa<NonTypeTemplateParmDecl>(this) ||
869 !isa<CXXRecordDecl>(getDeclContext()) ||
871 isa<StaticAssertDecl>(this) ||
872 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
873 // as DeclContext (?).
874 isa<ParmVarDecl>(this) ||
875 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
876 // AS_none as access specifier.
877 isa<CXXRecordDecl>(this) ||
878 isa<ClassScopeFunctionSpecializationDecl>(this))
881 assert(Access != AS_none &&
882 "Access specifier is AS_none inside a record decl");
887 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
888 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
890 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
892 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
894 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
895 Ty = D->getUnderlyingType();
899 if (Ty->isFunctionPointerType())
900 Ty = Ty->getAs<PointerType>()->getPointeeType();
901 else if (BlocksToo && Ty->isBlockPointerType())
902 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
904 return Ty->getAs<FunctionType>();
908 /// Starting at a given context (a Decl or DeclContext), look for a
909 /// code context that is not a closure (a lambda, block, etc.).
910 template <class T> static Decl *getNonClosureContext(T *D) {
911 if (getKind(D) == Decl::CXXMethod) {
912 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
913 if (MD->getOverloadedOperator() == OO_Call &&
914 MD->getParent()->isLambda())
915 return getNonClosureContext(MD->getParent()->getParent());
917 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
919 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
921 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
922 return getNonClosureContext(BD->getParent());
923 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
924 return getNonClosureContext(CD->getParent());
930 Decl *Decl::getNonClosureContext() {
931 return ::getNonClosureContext(this);
934 Decl *DeclContext::getNonClosureAncestor() {
935 return ::getNonClosureContext(this);
938 //===----------------------------------------------------------------------===//
939 // DeclContext Implementation
940 //===----------------------------------------------------------------------===//
942 bool DeclContext::classof(const Decl *D) {
943 switch (D->getKind()) {
944 #define DECL(NAME, BASE)
945 #define DECL_CONTEXT(NAME) case Decl::NAME:
946 #define DECL_CONTEXT_BASE(NAME)
947 #include "clang/AST/DeclNodes.inc"
950 #define DECL(NAME, BASE)
951 #define DECL_CONTEXT_BASE(NAME) \
952 if (D->getKind() >= Decl::first##NAME && \
953 D->getKind() <= Decl::last##NAME) \
955 #include "clang/AST/DeclNodes.inc"
960 DeclContext::~DeclContext() { }
962 /// \brief Find the parent context of this context that will be
963 /// used for unqualified name lookup.
965 /// Generally, the parent lookup context is the semantic context. However, for
966 /// a friend function the parent lookup context is the lexical context, which
967 /// is the class in which the friend is declared.
968 DeclContext *DeclContext::getLookupParent() {
969 // FIXME: Find a better way to identify friends
970 if (isa<FunctionDecl>(this))
971 if (getParent()->getRedeclContext()->isFileContext() &&
972 getLexicalParent()->getRedeclContext()->isRecord())
973 return getLexicalParent();
978 bool DeclContext::isInlineNamespace() const {
979 return isNamespace() &&
980 cast<NamespaceDecl>(this)->isInline();
983 bool DeclContext::isStdNamespace() const {
987 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
988 if (ND->isInline()) {
989 return ND->getParent()->isStdNamespace();
992 if (!getParent()->getRedeclContext()->isTranslationUnit())
995 const IdentifierInfo *II = ND->getIdentifier();
996 return II && II->isStr("std");
999 bool DeclContext::isDependentContext() const {
1000 if (isFileContext())
1003 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1006 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1007 if (Record->getDescribedClassTemplate())
1010 if (Record->isDependentLambda())
1014 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1015 if (Function->getDescribedFunctionTemplate())
1018 // Friend function declarations are dependent if their *lexical*
1019 // context is dependent.
1020 if (cast<Decl>(this)->getFriendObjectKind())
1021 return getLexicalParent()->isDependentContext();
1024 // FIXME: A variable template is a dependent context, but is not a
1025 // DeclContext. A context within it (such as a lambda-expression)
1026 // should be considered dependent.
1028 return getParent() && getParent()->isDependentContext();
1031 bool DeclContext::isTransparentContext() const {
1032 if (DeclKind == Decl::Enum)
1033 return !cast<EnumDecl>(this)->isScoped();
1034 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1040 static bool isLinkageSpecContext(const DeclContext *DC,
1041 LinkageSpecDecl::LanguageIDs ID) {
1042 while (DC->getDeclKind() != Decl::TranslationUnit) {
1043 if (DC->getDeclKind() == Decl::LinkageSpec)
1044 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1045 DC = DC->getLexicalParent();
1050 bool DeclContext::isExternCContext() const {
1051 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1054 const LinkageSpecDecl *DeclContext::getExternCContext() const {
1055 const DeclContext *DC = this;
1056 while (DC->getDeclKind() != Decl::TranslationUnit) {
1057 if (DC->getDeclKind() == Decl::LinkageSpec &&
1058 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1059 clang::LinkageSpecDecl::lang_c)
1060 return cast<LinkageSpecDecl>(DC);
1061 DC = DC->getLexicalParent();
1066 bool DeclContext::isExternCXXContext() const {
1067 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1070 bool DeclContext::Encloses(const DeclContext *DC) const {
1071 if (getPrimaryContext() != this)
1072 return getPrimaryContext()->Encloses(DC);
1074 for (; DC; DC = DC->getParent())
1075 if (DC->getPrimaryContext() == this)
1080 DeclContext *DeclContext::getPrimaryContext() {
1082 case Decl::TranslationUnit:
1083 case Decl::ExternCContext:
1084 case Decl::LinkageSpec:
1087 case Decl::Captured:
1088 case Decl::OMPDeclareReduction:
1089 // There is only one DeclContext for these entities.
1092 case Decl::Namespace:
1093 // The original namespace is our primary context.
1094 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1096 case Decl::ObjCMethod:
1099 case Decl::ObjCInterface:
1100 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1105 case Decl::ObjCProtocol:
1106 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1111 case Decl::ObjCCategory:
1114 case Decl::ObjCImplementation:
1115 case Decl::ObjCCategoryImpl:
1119 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1120 // If this is a tag type that has a definition or is currently
1121 // being defined, that definition is our primary context.
1122 TagDecl *Tag = cast<TagDecl>(this);
1124 if (TagDecl *Def = Tag->getDefinition())
1127 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1128 // Note, TagType::getDecl returns the (partial) definition one exists.
1129 TagDecl *PossiblePartialDef = TagTy->getDecl();
1130 if (PossiblePartialDef->isBeingDefined())
1131 return PossiblePartialDef;
1133 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1139 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1140 "Unknown DeclContext kind");
1146 DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1149 if (DeclKind != Decl::Namespace) {
1150 Contexts.push_back(this);
1154 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1155 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1156 N = N->getPreviousDecl())
1157 Contexts.push_back(N);
1159 std::reverse(Contexts.begin(), Contexts.end());
1162 std::pair<Decl *, Decl *>
1163 DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1164 bool FieldsAlreadyLoaded) {
1165 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1166 Decl *FirstNewDecl = nullptr;
1167 Decl *PrevDecl = nullptr;
1168 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1169 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1174 PrevDecl->NextInContextAndBits.setPointer(D);
1181 return std::make_pair(FirstNewDecl, PrevDecl);
1184 /// \brief We have just acquired external visible storage, and we already have
1185 /// built a lookup map. For every name in the map, pull in the new names from
1186 /// the external storage.
1187 void DeclContext::reconcileExternalVisibleStorage() const {
1188 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1189 NeedToReconcileExternalVisibleStorage = false;
1191 for (auto &Lookup : *LookupPtr)
1192 Lookup.second.setHasExternalDecls();
1195 /// \brief Load the declarations within this lexical storage from an
1196 /// external source.
1197 /// \return \c true if any declarations were added.
1199 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1200 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1201 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1203 // Notify that we have a DeclContext that is initializing.
1204 ExternalASTSource::Deserializing ADeclContext(Source);
1206 // Load the external declarations, if any.
1207 SmallVector<Decl*, 64> Decls;
1208 ExternalLexicalStorage = false;
1209 Source->FindExternalLexicalDecls(this, Decls);
1214 // We may have already loaded just the fields of this record, in which case
1215 // we need to ignore them.
1216 bool FieldsAlreadyLoaded = false;
1217 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1218 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1220 // Splice the newly-read declarations into the beginning of the list
1222 Decl *ExternalFirst, *ExternalLast;
1223 std::tie(ExternalFirst, ExternalLast) =
1224 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1225 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1226 FirstDecl = ExternalFirst;
1228 LastDecl = ExternalLast;
1232 DeclContext::lookup_result
1233 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1234 DeclarationName Name) {
1235 ASTContext &Context = DC->getParentASTContext();
1236 StoredDeclsMap *Map;
1237 if (!(Map = DC->LookupPtr))
1238 Map = DC->CreateStoredDeclsMap(Context);
1239 if (DC->NeedToReconcileExternalVisibleStorage)
1240 DC->reconcileExternalVisibleStorage();
1242 (*Map)[Name].removeExternalDecls();
1244 return DeclContext::lookup_result();
1247 DeclContext::lookup_result
1248 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1249 DeclarationName Name,
1250 ArrayRef<NamedDecl*> Decls) {
1251 ASTContext &Context = DC->getParentASTContext();
1252 StoredDeclsMap *Map;
1253 if (!(Map = DC->LookupPtr))
1254 Map = DC->CreateStoredDeclsMap(Context);
1255 if (DC->NeedToReconcileExternalVisibleStorage)
1256 DC->reconcileExternalVisibleStorage();
1258 StoredDeclsList &List = (*Map)[Name];
1260 // Clear out any old external visible declarations, to avoid quadratic
1261 // performance in the redeclaration checks below.
1262 List.removeExternalDecls();
1264 if (!List.isNull()) {
1265 // We have both existing declarations and new declarations for this name.
1266 // Some of the declarations may simply replace existing ones. Handle those
1268 llvm::SmallVector<unsigned, 8> Skip;
1269 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1270 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1272 Skip.push_back(Decls.size());
1274 // Add in any new declarations.
1275 unsigned SkipPos = 0;
1276 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1277 if (I == Skip[SkipPos])
1280 List.AddSubsequentDecl(Decls[I]);
1283 // Convert the array to a StoredDeclsList.
1284 for (ArrayRef<NamedDecl*>::iterator
1285 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1287 List.setOnlyValue(*I);
1289 List.AddSubsequentDecl(*I);
1293 return List.getLookupResult();
1296 DeclContext::decl_iterator DeclContext::decls_begin() const {
1297 if (hasExternalLexicalStorage())
1298 LoadLexicalDeclsFromExternalStorage();
1299 return decl_iterator(FirstDecl);
1302 bool DeclContext::decls_empty() const {
1303 if (hasExternalLexicalStorage())
1304 LoadLexicalDeclsFromExternalStorage();
1309 bool DeclContext::containsDecl(Decl *D) const {
1310 return (D->getLexicalDeclContext() == this &&
1311 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1314 void DeclContext::removeDecl(Decl *D) {
1315 assert(D->getLexicalDeclContext() == this &&
1316 "decl being removed from non-lexical context");
1317 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1318 "decl is not in decls list");
1320 // Remove D from the decl chain. This is O(n) but hopefully rare.
1321 if (D == FirstDecl) {
1323 FirstDecl = LastDecl = nullptr;
1325 FirstDecl = D->NextInContextAndBits.getPointer();
1327 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1328 assert(I && "decl not found in linked list");
1329 if (I->NextInContextAndBits.getPointer() == D) {
1330 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1331 if (D == LastDecl) LastDecl = I;
1337 // Mark that D is no longer in the decl chain.
1338 D->NextInContextAndBits.setPointer(nullptr);
1340 // Remove D from the lookup table if necessary.
1341 if (isa<NamedDecl>(D)) {
1342 NamedDecl *ND = cast<NamedDecl>(D);
1344 // Remove only decls that have a name
1345 if (!ND->getDeclName()) return;
1349 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1351 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1352 assert(Pos != Map->end() && "no lookup entry for decl");
1353 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1354 Pos->second.remove(ND);
1356 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1360 void DeclContext::addHiddenDecl(Decl *D) {
1361 assert(D->getLexicalDeclContext() == this &&
1362 "Decl inserted into wrong lexical context");
1363 assert(!D->getNextDeclInContext() && D != LastDecl &&
1364 "Decl already inserted into a DeclContext");
1367 LastDecl->NextInContextAndBits.setPointer(D);
1370 FirstDecl = LastDecl = D;
1373 // Notify a C++ record declaration that we've added a member, so it can
1374 // update its class-specific state.
1375 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1376 Record->addedMember(D);
1378 // If this is a newly-created (not de-serialized) import declaration, wire
1379 // it in to the list of local import declarations.
1380 if (!D->isFromASTFile()) {
1381 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1382 D->getASTContext().addedLocalImportDecl(Import);
1386 void DeclContext::addDecl(Decl *D) {
1389 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1390 ND->getDeclContext()->getPrimaryContext()->
1391 makeDeclVisibleInContextWithFlags(ND, false, true);
1394 void DeclContext::addDeclInternal(Decl *D) {
1397 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1398 ND->getDeclContext()->getPrimaryContext()->
1399 makeDeclVisibleInContextWithFlags(ND, true, true);
1402 /// shouldBeHidden - Determine whether a declaration which was declared
1403 /// within its semantic context should be invisible to qualified name lookup.
1404 static bool shouldBeHidden(NamedDecl *D) {
1405 // Skip unnamed declarations.
1406 if (!D->getDeclName())
1409 // Skip entities that can't be found by name lookup into a particular
1411 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1412 D->isTemplateParameter())
1415 // Skip template specializations.
1416 // FIXME: This feels like a hack. Should DeclarationName support
1417 // template-ids, or is there a better way to keep specializations
1418 // from being visible?
1419 if (isa<ClassTemplateSpecializationDecl>(D))
1421 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1422 if (FD->isFunctionTemplateSpecialization())
1428 /// buildLookup - Build the lookup data structure with all of the
1429 /// declarations in this DeclContext (and any other contexts linked
1430 /// to it or transparent contexts nested within it) and return it.
1432 /// Note that the produced map may miss out declarations from an
1433 /// external source. If it does, those entries will be marked with
1434 /// the 'hasExternalDecls' flag.
1435 StoredDeclsMap *DeclContext::buildLookup() {
1436 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1438 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1441 SmallVector<DeclContext *, 2> Contexts;
1442 collectAllContexts(Contexts);
1444 if (HasLazyExternalLexicalLookups) {
1445 HasLazyExternalLexicalLookups = false;
1446 for (auto *DC : Contexts) {
1447 if (DC->hasExternalLexicalStorage())
1448 HasLazyLocalLexicalLookups |=
1449 DC->LoadLexicalDeclsFromExternalStorage();
1452 if (!HasLazyLocalLexicalLookups)
1456 for (auto *DC : Contexts)
1457 buildLookupImpl(DC, hasExternalVisibleStorage());
1459 // We no longer have any lazy decls.
1460 HasLazyLocalLexicalLookups = false;
1464 /// buildLookupImpl - Build part of the lookup data structure for the
1465 /// declarations contained within DCtx, which will either be this
1466 /// DeclContext, a DeclContext linked to it, or a transparent context
1467 /// nested within it.
1468 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1469 for (Decl *D : DCtx->noload_decls()) {
1470 // Insert this declaration into the lookup structure, but only if
1471 // it's semantically within its decl context. Any other decls which
1472 // should be found in this context are added eagerly.
1474 // If it's from an AST file, don't add it now. It'll get handled by
1475 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1476 // in C++, we do not track external visible decls for the TU, so in
1477 // that case we need to collect them all here.
1478 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1479 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1480 (!ND->isFromASTFile() ||
1481 (isTranslationUnit() &&
1482 !getParentASTContext().getLangOpts().CPlusPlus)))
1483 makeDeclVisibleInContextImpl(ND, Internal);
1485 // If this declaration is itself a transparent declaration context
1486 // or inline namespace, add the members of this declaration of that
1487 // context (recursively).
1488 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1489 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1490 buildLookupImpl(InnerCtx, Internal);
1494 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1496 DeclContext::lookup_result
1497 DeclContext::lookup(DeclarationName Name) const {
1498 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1499 "should not perform lookups into transparent contexts");
1501 const DeclContext *PrimaryContext = getPrimaryContext();
1502 if (PrimaryContext != this)
1503 return PrimaryContext->lookup(Name);
1505 // If we have an external source, ensure that any later redeclarations of this
1506 // context have been loaded, since they may add names to the result of this
1507 // lookup (or add external visible storage).
1508 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1510 (void)cast<Decl>(this)->getMostRecentDecl();
1512 if (hasExternalVisibleStorage()) {
1513 assert(Source && "external visible storage but no external source?");
1515 if (NeedToReconcileExternalVisibleStorage)
1516 reconcileExternalVisibleStorage();
1518 StoredDeclsMap *Map = LookupPtr;
1520 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1521 // FIXME: Make buildLookup const?
1522 Map = const_cast<DeclContext*>(this)->buildLookup();
1525 Map = CreateStoredDeclsMap(getParentASTContext());
1527 // If we have a lookup result with no external decls, we are done.
1528 std::pair<StoredDeclsMap::iterator, bool> R =
1529 Map->insert(std::make_pair(Name, StoredDeclsList()));
1530 if (!R.second && !R.first->second.hasExternalDecls())
1531 return R.first->second.getLookupResult();
1533 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1534 if (StoredDeclsMap *Map = LookupPtr) {
1535 StoredDeclsMap::iterator I = Map->find(Name);
1536 if (I != Map->end())
1537 return I->second.getLookupResult();
1541 return lookup_result();
1544 StoredDeclsMap *Map = LookupPtr;
1545 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1546 Map = const_cast<DeclContext*>(this)->buildLookup();
1549 return lookup_result();
1551 StoredDeclsMap::iterator I = Map->find(Name);
1552 if (I == Map->end())
1553 return lookup_result();
1555 return I->second.getLookupResult();
1558 DeclContext::lookup_result
1559 DeclContext::noload_lookup(DeclarationName Name) {
1560 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1561 "should not perform lookups into transparent contexts");
1563 DeclContext *PrimaryContext = getPrimaryContext();
1564 if (PrimaryContext != this)
1565 return PrimaryContext->noload_lookup(Name);
1567 // If we have any lazy lexical declarations not in our lookup map, add them
1568 // now. Don't import any external declarations, not even if we know we have
1569 // some missing from the external visible lookups.
1570 if (HasLazyLocalLexicalLookups) {
1571 SmallVector<DeclContext *, 2> Contexts;
1572 collectAllContexts(Contexts);
1573 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1574 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1575 HasLazyLocalLexicalLookups = false;
1578 StoredDeclsMap *Map = LookupPtr;
1580 return lookup_result();
1582 StoredDeclsMap::iterator I = Map->find(Name);
1583 return I != Map->end() ? I->second.getLookupResult()
1587 void DeclContext::localUncachedLookup(DeclarationName Name,
1588 SmallVectorImpl<NamedDecl *> &Results) {
1591 // If there's no external storage, just perform a normal lookup and copy
1593 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1594 lookup_result LookupResults = lookup(Name);
1595 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1599 // If we have a lookup table, check there first. Maybe we'll get lucky.
1600 // FIXME: Should we be checking these flags on the primary context?
1601 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1602 if (StoredDeclsMap *Map = LookupPtr) {
1603 StoredDeclsMap::iterator Pos = Map->find(Name);
1604 if (Pos != Map->end()) {
1605 Results.insert(Results.end(),
1606 Pos->second.getLookupResult().begin(),
1607 Pos->second.getLookupResult().end());
1613 // Slow case: grovel through the declarations in our chain looking for
1615 // FIXME: If we have lazy external declarations, this will not find them!
1616 // FIXME: Should we CollectAllContexts and walk them all here?
1617 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1618 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1619 if (ND->getDeclName() == Name)
1620 Results.push_back(ND);
1624 DeclContext *DeclContext::getRedeclContext() {
1625 DeclContext *Ctx = this;
1626 // Skip through transparent contexts.
1627 while (Ctx->isTransparentContext())
1628 Ctx = Ctx->getParent();
1632 DeclContext *DeclContext::getEnclosingNamespaceContext() {
1633 DeclContext *Ctx = this;
1634 // Skip through non-namespace, non-translation-unit contexts.
1635 while (!Ctx->isFileContext())
1636 Ctx = Ctx->getParent();
1637 return Ctx->getPrimaryContext();
1640 RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1641 // Loop until we find a non-record context.
1642 RecordDecl *OutermostRD = nullptr;
1643 DeclContext *DC = this;
1644 while (DC->isRecord()) {
1645 OutermostRD = cast<RecordDecl>(DC);
1646 DC = DC->getLexicalParent();
1651 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1652 // For non-file contexts, this is equivalent to Equals.
1653 if (!isFileContext())
1654 return O->Equals(this);
1657 if (O->Equals(this))
1660 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1661 if (!NS || !NS->isInline())
1663 O = NS->getParent();
1669 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1670 DeclContext *PrimaryDC = this->getPrimaryContext();
1671 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1672 // If the decl is being added outside of its semantic decl context, we
1673 // need to ensure that we eagerly build the lookup information for it.
1674 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1677 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1679 assert(this == getPrimaryContext() && "expected a primary DC");
1681 if (!isLookupContext()) {
1682 if (isTransparentContext())
1683 getParent()->getPrimaryContext()
1684 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1688 // Skip declarations which should be invisible to name lookup.
1689 if (shouldBeHidden(D))
1692 // If we already have a lookup data structure, perform the insertion into
1693 // it. If we might have externally-stored decls with this name, look them
1694 // up and perform the insertion. If this decl was declared outside its
1695 // semantic context, buildLookup won't add it, so add it now.
1697 // FIXME: As a performance hack, don't add such decls into the translation
1698 // unit unless we're in C++, since qualified lookup into the TU is never
1700 if (LookupPtr || hasExternalVisibleStorage() ||
1701 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1702 (getParentASTContext().getLangOpts().CPlusPlus ||
1703 !isTranslationUnit()))) {
1704 // If we have lazily omitted any decls, they might have the same name as
1705 // the decl which we are adding, so build a full lookup table before adding
1708 makeDeclVisibleInContextImpl(D, Internal);
1710 HasLazyLocalLexicalLookups = true;
1713 // If we are a transparent context or inline namespace, insert into our
1714 // parent context, too. This operation is recursive.
1715 if (isTransparentContext() || isInlineNamespace())
1716 getParent()->getPrimaryContext()->
1717 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1719 Decl *DCAsDecl = cast<Decl>(this);
1720 // Notify that a decl was made visible unless we are a Tag being defined.
1721 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1722 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1723 L->AddedVisibleDecl(this, D);
1726 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1727 // Find or create the stored declaration map.
1728 StoredDeclsMap *Map = LookupPtr;
1730 ASTContext *C = &getParentASTContext();
1731 Map = CreateStoredDeclsMap(*C);
1734 // If there is an external AST source, load any declarations it knows about
1735 // with this declaration's name.
1736 // If the lookup table contains an entry about this name it means that we
1737 // have already checked the external source.
1739 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1740 if (hasExternalVisibleStorage() &&
1741 Map->find(D->getDeclName()) == Map->end())
1742 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1744 // Insert this declaration into the map.
1745 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1748 // If this is being added as part of loading an external declaration,
1749 // this may not be the only external declaration with this name.
1750 // In this case, we never try to replace an existing declaration; we'll
1751 // handle that when we finalize the list of declarations for this name.
1752 DeclNameEntries.setHasExternalDecls();
1753 DeclNameEntries.AddSubsequentDecl(D);
1757 if (DeclNameEntries.isNull()) {
1758 DeclNameEntries.setOnlyValue(D);
1762 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1763 // This declaration has replaced an existing one for which
1764 // declarationReplaces returns true.
1768 // Put this declaration into the appropriate slot.
1769 DeclNameEntries.AddSubsequentDecl(D);
1772 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1773 return cast<UsingDirectiveDecl>(*I);
1776 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1778 DeclContext::udir_range DeclContext::using_directives() const {
1779 // FIXME: Use something more efficient than normal lookup for using
1780 // directives. In C++, using directives are looked up more than anything else.
1781 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1782 return udir_range(Result.begin(), Result.end());
1785 //===----------------------------------------------------------------------===//
1786 // Creation and Destruction of StoredDeclsMaps. //
1787 //===----------------------------------------------------------------------===//
1789 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1790 assert(!LookupPtr && "context already has a decls map");
1791 assert(getPrimaryContext() == this &&
1792 "creating decls map on non-primary context");
1795 bool Dependent = isDependentContext();
1797 M = new DependentStoredDeclsMap();
1799 M = new StoredDeclsMap();
1800 M->Previous = C.LastSDM;
1801 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1806 void ASTContext::ReleaseDeclContextMaps() {
1807 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1808 // pointer because the subclass doesn't add anything that needs to
1810 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1813 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1815 // Advance the iteration before we invalidate memory.
1816 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1819 delete static_cast<DependentStoredDeclsMap*>(Map);
1823 Map = Next.getPointer();
1824 Dependent = Next.getInt();
1828 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1829 DeclContext *Parent,
1830 const PartialDiagnostic &PDiag) {
1831 assert(Parent->isDependentContext()
1832 && "cannot iterate dependent diagnostics of non-dependent context");
1833 Parent = Parent->getPrimaryContext();
1834 if (!Parent->LookupPtr)
1835 Parent->CreateStoredDeclsMap(C);
1837 DependentStoredDeclsMap *Map =
1838 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1840 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1841 // BumpPtrAllocator, rather than the ASTContext itself.
1842 PartialDiagnostic::Storage *DiagStorage = nullptr;
1843 if (PDiag.hasStorage())
1844 DiagStorage = new (C) PartialDiagnostic::Storage;
1846 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1848 // TODO: Maybe we shouldn't reverse the order during insertion.
1849 DD->NextDiagnostic = Map->FirstDiagnostic;
1850 Map->FirstDiagnostic = DD;