clang 17.0.0git
DeclBase.cpp
Go to the documentation of this file.
1//===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Decl and DeclContext classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/DeclBase.h"
15#include "clang/AST/ASTLambda.h"
17#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/Type.h"
31#include "clang/Basic/LLVM.h"
33#include "clang/Basic/Module.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/VersionTuple.h"
46#include "llvm/Support/raw_ostream.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <string>
51#include <tuple>
52#include <utility>
53
54using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Statistics
58//===----------------------------------------------------------------------===//
59
60#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
61#define ABSTRACT_DECL(DECL)
62#include "clang/AST/DeclNodes.inc"
63
66}
67
68#define DECL(DERIVED, BASE) \
69 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
70 "Alignment sufficient after objects prepended to " #DERIVED);
71#define ABSTRACT_DECL(DECL)
72#include "clang/AST/DeclNodes.inc"
73
74void *Decl::operator new(std::size_t Size, const ASTContext &Context,
75 unsigned ID, std::size_t Extra) {
76 // Allocate an extra 8 bytes worth of storage, which ensures that the
77 // resulting pointer will still be 8-byte aligned.
78 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
79 "Decl won't be misaligned");
80 void *Start = Context.Allocate(Size + Extra + 8);
81 void *Result = (char*)Start + 8;
82
83 unsigned *PrefixPtr = (unsigned *)Result - 2;
84
85 // Zero out the first 4 bytes; this is used to store the owning module ID.
86 PrefixPtr[0] = 0;
87
88 // Store the global declaration ID in the second 4 bytes.
89 PrefixPtr[1] = ID;
90
91 return Result;
92}
93
94void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
95 DeclContext *Parent, std::size_t Extra) {
96 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
97 // With local visibility enabled, we track the owning module even for local
98 // declarations. We create the TU decl early and may not yet know what the
99 // LangOpts are, so conservatively allocate the storage.
100 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
101 // Ensure required alignment of the resulting object by adding extra
102 // padding at the start if required.
103 size_t ExtraAlign =
104 llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl)));
105 auto *Buffer = reinterpret_cast<char *>(
106 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
107 Buffer += ExtraAlign;
108 auto *ParentModule =
109 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
110 return new (Buffer) Module*(ParentModule) + 1;
111 }
112 return ::operator new(Size + Extra, Ctx);
113}
114
115Module *Decl::getOwningModuleSlow() const {
116 assert(isFromASTFile() && "Not from AST file?");
118}
119
122}
123
124const char *Decl::getDeclKindName() const {
125 switch (DeclKind) {
126 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
127#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
128#define ABSTRACT_DECL(DECL)
129#include "clang/AST/DeclNodes.inc"
130 }
131}
132
134 InvalidDecl = Invalid;
135 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
136 if (!Invalid) {
137 return;
138 }
139
140 if (!isa<ParmVarDecl>(this)) {
141 // Defensive maneuver for ill-formed code: we're likely not to make it to
142 // a point where we set the access specifier, so default it to "public"
143 // to avoid triggering asserts elsewhere in the front end.
145 }
146
147 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
148 // are invalid too.
149 if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
150 for (auto *Binding : DD->bindings()) {
151 Binding->setInvalidDecl();
152 }
153 }
154}
155
157 switch (getDeclKind()) {
158#define DECL(DERIVED, BASE) case Decl::DERIVED: return true;
159#define ABSTRACT_DECL(DECL)
160#include "clang/AST/DeclNodes.inc"
161 }
162 return false;
163}
164
165const char *DeclContext::getDeclKindName() const {
166 switch (getDeclKind()) {
167#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
168#define ABSTRACT_DECL(DECL)
169#include "clang/AST/DeclNodes.inc"
170 }
171 llvm_unreachable("Declaration context not in DeclNodes.inc!");
172}
173
174bool Decl::StatisticsEnabled = false;
176 StatisticsEnabled = true;
177}
178
180 llvm::errs() << "\n*** Decl Stats:\n";
181
182 int totalDecls = 0;
183#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
184#define ABSTRACT_DECL(DECL)
185#include "clang/AST/DeclNodes.inc"
186 llvm::errs() << " " << totalDecls << " decls total.\n";
187
188 int totalBytes = 0;
189#define DECL(DERIVED, BASE) \
190 if (n##DERIVED##s > 0) { \
191 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
192 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
193 << sizeof(DERIVED##Decl) << " each (" \
194 << n##DERIVED##s * sizeof(DERIVED##Decl) \
195 << " bytes)\n"; \
196 }
197#define ABSTRACT_DECL(DECL)
198#include "clang/AST/DeclNodes.inc"
199
200 llvm::errs() << "Total bytes = " << totalBytes << "\n";
201}
202
204 switch (k) {
205#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
206#define ABSTRACT_DECL(DECL)
207#include "clang/AST/DeclNodes.inc"
208 }
209}
210
212 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
213 return TTP->isParameterPack();
214 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
215 return NTTP->isParameterPack();
216 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
217 return TTP->isParameterPack();
218 return false;
219}
220
222 if (const auto *Var = dyn_cast<VarDecl>(this))
223 return Var->isParameterPack();
224
226}
227
229 if (auto *FD = dyn_cast<FunctionDecl>(this))
230 return FD;
231 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
232 return FTD->getTemplatedDecl();
233 return nullptr;
234}
235
237 return isa<TemplateDecl>(this);
238}
239
241 if (auto *FD = dyn_cast<FunctionDecl>(this))
242 return FD->getDescribedFunctionTemplate();
243 if (auto *RD = dyn_cast<CXXRecordDecl>(this))
244 return RD->getDescribedClassTemplate();
245 if (auto *VD = dyn_cast<VarDecl>(this))
246 return VD->getDescribedVarTemplate();
247 if (auto *AD = dyn_cast<TypeAliasDecl>(this))
248 return AD->getDescribedAliasTemplate();
249
250 return nullptr;
251}
252
254 if (auto *TD = getDescribedTemplate())
255 return TD->getTemplateParameters();
256 if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))
257 return CTPSD->getTemplateParameters();
258 if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this))
259 return VTPSD->getTemplateParameters();
260 return nullptr;
261}
262
263bool Decl::isTemplated() const {
264 // A declaration is templated if it is a template or a template pattern, or
265 // is within (lexcially for a friend or local function declaration,
266 // semantically otherwise) a dependent context.
267 if (auto *AsDC = dyn_cast<DeclContext>(this))
268 return AsDC->isDependentContext();
269 auto *DC = getFriendObjectKind() || isLocalExternDecl()
271 return DC->isDependentContext() || isTemplateDecl() ||
273}
274
275unsigned Decl::getTemplateDepth() const {
276 if (auto *DC = dyn_cast<DeclContext>(this))
277 if (DC->isFileContext())
278 return 0;
279
280 if (auto *TPL = getDescribedTemplateParams())
281 return TPL->getDepth() + 1;
282
283 // If this is a dependent lambda, there might be an enclosing variable
284 // template. In this case, the next step is not the parent DeclContext (or
285 // even a DeclContext at all).
286 auto *RD = dyn_cast<CXXRecordDecl>(this);
287 if (RD && RD->isDependentLambda())
288 if (Decl *Context = RD->getLambdaContextDecl())
289 return Context->getTemplateDepth();
290
291 const DeclContext *DC =
293 return cast<Decl>(DC)->getTemplateDepth();
294}
295
296const DeclContext *Decl::getParentFunctionOrMethod(bool LexicalParent) const {
297 for (const DeclContext *DC = LexicalParent ? getLexicalDeclContext()
298 : getDeclContext();
299 DC && !DC->isFileContext(); DC = DC->getParent())
300 if (DC->isFunctionOrMethod())
301 return DC;
302
303 return nullptr;
304}
305
306//===----------------------------------------------------------------------===//
307// PrettyStackTraceDecl Implementation
308//===----------------------------------------------------------------------===//
309
310void PrettyStackTraceDecl::print(raw_ostream &OS) const {
311 SourceLocation TheLoc = Loc;
312 if (TheLoc.isInvalid() && TheDecl)
313 TheLoc = TheDecl->getLocation();
314
315 if (TheLoc.isValid()) {
316 TheLoc.print(OS, SM);
317 OS << ": ";
318 }
319
320 OS << Message;
321
322 if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
323 OS << " '";
324 DN->printQualifiedName(OS);
325 OS << '\'';
326 }
327 OS << '\n';
328}
329
330//===----------------------------------------------------------------------===//
331// Decl Implementation
332//===----------------------------------------------------------------------===//
333
334// Out-of-line virtual method providing a home for Decl.
335Decl::~Decl() = default;
336
338 DeclCtx = DC;
339}
340
342 if (DC == getLexicalDeclContext())
343 return;
344
345 if (isInSemaDC()) {
346 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
347 } else {
348 getMultipleDC()->LexicalDC = DC;
349 }
350
351 // FIXME: We shouldn't be changing the lexical context of declarations
352 // imported from AST files.
353 if (!isFromASTFile()) {
354 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
355 if (hasOwningModule())
356 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
357 }
358
359 assert(
361 getOwningModule()) &&
362 "hidden declaration has no owning module");
363}
364
365void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
366 ASTContext &Ctx) {
367 if (SemaDC == LexicalDC) {
368 DeclCtx = SemaDC;
369 } else {
370 auto *MDC = new (Ctx) Decl::MultipleDC();
371 MDC->SemanticDC = SemaDC;
372 MDC->LexicalDC = LexicalDC;
373 DeclCtx = MDC;
374 }
375}
376
378 const DeclContext *LDC = getLexicalDeclContext();
379 if (!LDC->isDependentContext())
380 return false;
381 while (true) {
382 if (LDC->isFunctionOrMethod())
383 return true;
384 if (!isa<TagDecl>(LDC))
385 return false;
386 if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
387 if (CRD->isLambda())
388 return true;
389 LDC = LDC->getLexicalParent();
390 }
391 return false;
392}
393
395 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
396 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
397 if (ND->isAnonymousNamespace())
398 return true;
399 }
400
401 return false;
402}
403
405 const DeclContext *DC = getDeclContext();
406 return DC && DC->isStdNamespace();
407}
408
410 const auto *DC = dyn_cast<DeclContext>(this);
411 return DC && DC->isFileContext();
412}
413
415 if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
416 return TUD;
417
419 assert(DC && "This decl is not contained in a translation unit!");
420
421 while (!DC->isTranslationUnit()) {
422 DC = DC->getParent();
423 assert(DC && "This decl is not contained in a translation unit!");
424 }
425
426 return cast<TranslationUnitDecl>(DC);
427}
428
431}
432
433/// Helper to get the language options from the ASTContext.
434/// Defined out of line to avoid depending on ASTContext.h.
436 return getASTContext().getLangOpts();
437}
438
441}
442
443unsigned Decl::getMaxAlignment() const {
444 if (!hasAttrs())
445 return 0;
446
447 unsigned Align = 0;
448 const AttrVec &V = getAttrs();
449 ASTContext &Ctx = getASTContext();
450 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
451 for (; I != E; ++I) {
452 if (!I->isAlignmentErrorDependent())
453 Align = std::max(Align, I->getAlignment(Ctx));
454 }
455 return Align;
456}
457
458bool Decl::isUsed(bool CheckUsedAttr) const {
459 const Decl *CanonD = getCanonicalDecl();
460 if (CanonD->Used)
461 return true;
462
463 // Check for used attribute.
464 // Ask the most recent decl, since attributes accumulate in the redecl chain.
465 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
466 return true;
467
468 // The information may have not been deserialized yet. Force deserialization
469 // to complete the needed information.
470 return getMostRecentDecl()->getCanonicalDecl()->Used;
471}
472
474 if (isUsed(false))
475 return;
476
477 if (C.getASTMutationListener())
478 C.getASTMutationListener()->DeclarationMarkedUsed(this);
479
480 setIsUsed();
481}
482
483bool Decl::isReferenced() const {
484 if (Referenced)
485 return true;
486
487 // Check redeclarations.
488 for (const auto *I : redecls())
489 if (I->Referenced)
490 return true;
491
492 return false;
493}
494
495ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
496 const Decl *Definition = nullptr;
497 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
498 Definition = ID->getDefinition();
499 } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
500 Definition = PD->getDefinition();
501 } else if (auto *TD = dyn_cast<TagDecl>(this)) {
502 Definition = TD->getDefinition();
503 }
504 if (!Definition)
505 Definition = this;
506
507 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
508 return attr;
509 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
510 return dcd->getAttr<ExternalSourceSymbolAttr>();
511 }
512
513 return nullptr;
514}
515
517 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>() ||
518 hasAttr<LoaderUninitializedAttr>();
519}
520
522 if (auto *AA = getAttr<AliasAttr>())
523 return AA;
524 if (auto *IFA = getAttr<IFuncAttr>())
525 return IFA;
526 if (auto *NZA = getAttr<LoaderUninitializedAttr>())
527 return NZA;
528 return nullptr;
529}
530
531static StringRef getRealizedPlatform(const AvailabilityAttr *A,
532 const ASTContext &Context) {
533 // Check if this is an App Extension "platform", and if so chop off
534 // the suffix for matching with the actual platform.
535 StringRef RealizedPlatform = A->getPlatform()->getName();
536 if (!Context.getLangOpts().AppExt)
537 return RealizedPlatform;
538 size_t suffix = RealizedPlatform.rfind("_app_extension");
539 if (suffix != StringRef::npos)
540 return RealizedPlatform.slice(0, suffix);
541 return RealizedPlatform;
542}
543
544/// Determine the availability of the given declaration based on
545/// the target platform.
546///
547/// When it returns an availability result other than \c AR_Available,
548/// if the \p Message parameter is non-NULL, it will be set to a
549/// string describing why the entity is unavailable.
550///
551/// FIXME: Make these strings localizable, since they end up in
552/// diagnostics.
554 const AvailabilityAttr *A,
555 std::string *Message,
556 VersionTuple EnclosingVersion) {
557 if (EnclosingVersion.empty())
558 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
559
560 if (EnclosingVersion.empty())
561 return AR_Available;
562
563 StringRef ActualPlatform = A->getPlatform()->getName();
564 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
565
566 // Match the platform name.
567 if (getRealizedPlatform(A, Context) != TargetPlatform)
568 return AR_Available;
569
570 StringRef PrettyPlatformName
571 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
572
573 if (PrettyPlatformName.empty())
574 PrettyPlatformName = ActualPlatform;
575
576 std::string HintMessage;
577 if (!A->getMessage().empty()) {
578 HintMessage = " - ";
579 HintMessage += A->getMessage();
580 }
581
582 // Make sure that this declaration has not been marked 'unavailable'.
583 if (A->getUnavailable()) {
584 if (Message) {
585 Message->clear();
586 llvm::raw_string_ostream Out(*Message);
587 Out << "not available on " << PrettyPlatformName
588 << HintMessage;
589 }
590
591 return AR_Unavailable;
592 }
593
594 // Make sure that this declaration has already been introduced.
595 if (!A->getIntroduced().empty() &&
596 EnclosingVersion < A->getIntroduced()) {
597 if (Message) {
598 Message->clear();
599 llvm::raw_string_ostream Out(*Message);
600 VersionTuple VTI(A->getIntroduced());
601 Out << "introduced in " << PrettyPlatformName << ' '
602 << VTI << HintMessage;
603 }
604
605 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
606 }
607
608 // Make sure that this declaration hasn't been obsoleted.
609 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
610 if (Message) {
611 Message->clear();
612 llvm::raw_string_ostream Out(*Message);
613 VersionTuple VTO(A->getObsoleted());
614 Out << "obsoleted in " << PrettyPlatformName << ' '
615 << VTO << HintMessage;
616 }
617
618 return AR_Unavailable;
619 }
620
621 // Make sure that this declaration hasn't been deprecated.
622 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
623 if (Message) {
624 Message->clear();
625 llvm::raw_string_ostream Out(*Message);
626 VersionTuple VTD(A->getDeprecated());
627 Out << "first deprecated in " << PrettyPlatformName << ' '
628 << VTD << HintMessage;
629 }
630
631 return AR_Deprecated;
632 }
633
634 return AR_Available;
635}
636
638 VersionTuple EnclosingVersion,
639 StringRef *RealizedPlatform) const {
640 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
641 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
642 RealizedPlatform);
643
645 std::string ResultMessage;
646
647 for (const auto *A : attrs()) {
648 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
649 if (Result >= AR_Deprecated)
650 continue;
651
652 if (Message)
653 ResultMessage = std::string(Deprecated->getMessage());
654
656 continue;
657 }
658
659 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
660 if (Message)
661 *Message = std::string(Unavailable->getMessage());
662 return AR_Unavailable;
663 }
664
665 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
667 Message, EnclosingVersion);
668
669 if (AR == AR_Unavailable) {
670 if (RealizedPlatform)
671 *RealizedPlatform = Availability->getPlatform()->getName();
672 return AR_Unavailable;
673 }
674
675 if (AR > Result) {
676 Result = AR;
677 if (Message)
678 ResultMessage.swap(*Message);
679 }
680 continue;
681 }
682 }
683
684 if (Message)
685 Message->swap(ResultMessage);
686 return Result;
687}
688
689VersionTuple Decl::getVersionIntroduced() const {
690 const ASTContext &Context = getASTContext();
691 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
692 for (const auto *A : attrs()) {
693 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
694 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
695 continue;
696 if (!Availability->getIntroduced().empty())
697 return Availability->getIntroduced();
698 }
699 }
700 return {};
701}
702
703bool Decl::canBeWeakImported(bool &IsDefinition) const {
704 IsDefinition = false;
705
706 // Variables, if they aren't definitions.
707 if (const auto *Var = dyn_cast<VarDecl>(this)) {
708 if (Var->isThisDeclarationADefinition()) {
709 IsDefinition = true;
710 return false;
711 }
712 return true;
713 }
714 // Functions, if they aren't definitions.
715 if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
716 if (FD->hasBody()) {
717 IsDefinition = true;
718 return false;
719 }
720 return true;
721
722 }
723 // Objective-C classes, if this is the non-fragile runtime.
724 if (isa<ObjCInterfaceDecl>(this) &&
726 return true;
727 }
728 // Nothing else.
729 return false;
730}
731
733 bool IsDefinition;
734 if (!canBeWeakImported(IsDefinition))
735 return false;
736
737 for (const auto *A : getMostRecentDecl()->attrs()) {
738 if (isa<WeakImportAttr>(A))
739 return true;
740
741 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
742 if (CheckAvailability(getASTContext(), Availability, nullptr,
743 VersionTuple()) == AR_NotYetIntroduced)
744 return true;
745 }
746 }
747
748 return false;
749}
750
752 switch (DeclKind) {
753 case Function:
754 case CXXDeductionGuide:
755 case CXXMethod:
756 case CXXConstructor:
757 case ConstructorUsingShadow:
758 case CXXDestructor:
759 case CXXConversion:
760 case EnumConstant:
761 case Var:
762 case ImplicitParam:
763 case ParmVar:
764 case ObjCMethod:
765 case ObjCProperty:
766 case MSProperty:
767 case HLSLBuffer:
768 return IDNS_Ordinary;
769 case Label:
770 return IDNS_Label;
771 case IndirectField:
772 return IDNS_Ordinary | IDNS_Member;
773
774 case Binding:
775 case NonTypeTemplateParm:
776 case VarTemplate:
777 case Concept:
778 // These (C++-only) declarations are found by redeclaration lookup for
779 // tag types, so we include them in the tag namespace.
780 return IDNS_Ordinary | IDNS_Tag;
781
782 case ObjCCompatibleAlias:
783 case ObjCInterface:
784 return IDNS_Ordinary | IDNS_Type;
785
786 case Typedef:
787 case TypeAlias:
788 case TemplateTypeParm:
789 case ObjCTypeParam:
790 return IDNS_Ordinary | IDNS_Type;
791
792 case UnresolvedUsingTypename:
794
795 case UsingShadow:
796 return 0; // we'll actually overwrite this later
797
798 case UnresolvedUsingValue:
799 return IDNS_Ordinary | IDNS_Using;
800
801 case Using:
802 case UsingPack:
803 case UsingEnum:
804 return IDNS_Using;
805
806 case ObjCProtocol:
807 return IDNS_ObjCProtocol;
808
809 case Field:
810 case ObjCAtDefsField:
811 case ObjCIvar:
812 return IDNS_Member;
813
814 case Record:
815 case CXXRecord:
816 case Enum:
817 return IDNS_Tag | IDNS_Type;
818
819 case Namespace:
820 case NamespaceAlias:
821 return IDNS_Namespace;
822
823 case FunctionTemplate:
824 return IDNS_Ordinary;
825
826 case ClassTemplate:
827 case TemplateTemplateParm:
828 case TypeAliasTemplate:
830
831 case UnresolvedUsingIfExists:
832 return IDNS_Type | IDNS_Ordinary;
833
834 case OMPDeclareReduction:
835 return IDNS_OMPReduction;
836
837 case OMPDeclareMapper:
838 return IDNS_OMPMapper;
839
840 // Never have names.
841 case Friend:
842 case FriendTemplate:
843 case AccessSpec:
844 case LinkageSpec:
845 case Export:
846 case FileScopeAsm:
847 case TopLevelStmt:
848 case StaticAssert:
849 case ObjCPropertyImpl:
850 case PragmaComment:
851 case PragmaDetectMismatch:
852 case Block:
853 case Captured:
854 case TranslationUnit:
855 case ExternCContext:
856 case Decomposition:
857 case MSGuid:
858 case UnnamedGlobalConstant:
859 case TemplateParamObject:
860
861 case UsingDirective:
862 case BuiltinTemplate:
863 case ClassTemplateSpecialization:
864 case ClassTemplatePartialSpecialization:
865 case ClassScopeFunctionSpecialization:
866 case VarTemplateSpecialization:
867 case VarTemplatePartialSpecialization:
868 case ObjCImplementation:
869 case ObjCCategory:
870 case ObjCCategoryImpl:
871 case Import:
872 case OMPThreadPrivate:
873 case OMPAllocate:
874 case OMPRequires:
875 case OMPCapturedExpr:
876 case Empty:
877 case LifetimeExtendedTemporary:
878 case RequiresExprBody:
879 case ImplicitConceptSpecialization:
880 // Never looked up by name.
881 return 0;
882 }
883
884 llvm_unreachable("Invalid DeclKind!");
885}
886
887void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
888 assert(!HasAttrs && "Decl already contains attrs.");
889
890 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
891 assert(AttrBlank.empty() && "HasAttrs was wrong?");
892
893 AttrBlank = attrs;
894 HasAttrs = true;
895}
896
898 if (!HasAttrs) return;
899
900 HasAttrs = false;
902}
903
905 if (!hasAttrs()) {
906 setAttrs(AttrVec(1, A));
907 return;
908 }
909
910 AttrVec &Attrs = getAttrs();
911 if (!A->isInherited()) {
912 Attrs.push_back(A);
913 return;
914 }
915
916 // Attribute inheritance is processed after attribute parsing. To keep the
917 // order as in the source code, add inherited attributes before non-inherited
918 // ones.
919 auto I = Attrs.begin(), E = Attrs.end();
920 for (; I != E; ++I) {
921 if (!(*I)->isInherited())
922 break;
923 }
924 Attrs.insert(I, A);
925}
926
927const AttrVec &Decl::getAttrs() const {
928 assert(HasAttrs && "No attrs to get!");
929 return getASTContext().getDeclAttrs(this);
930}
931
933 Decl::Kind DK = D->getDeclKind();
934 switch(DK) {
935#define DECL(NAME, BASE)
936#define DECL_CONTEXT(NAME) \
937 case Decl::NAME: \
938 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
939#define DECL_CONTEXT_BASE(NAME)
940#include "clang/AST/DeclNodes.inc"
941 default:
942#define DECL(NAME, BASE)
943#define DECL_CONTEXT_BASE(NAME) \
944 if (DK >= first##NAME && DK <= last##NAME) \
945 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
946#include "clang/AST/DeclNodes.inc"
947 llvm_unreachable("a decl that inherits DeclContext isn't handled");
948 }
949}
950
952 Decl::Kind DK = D->getKind();
953 switch(DK) {
954#define DECL(NAME, BASE)
955#define DECL_CONTEXT(NAME) \
956 case Decl::NAME: \
957 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
958#define DECL_CONTEXT_BASE(NAME)
959#include "clang/AST/DeclNodes.inc"
960 default:
961#define DECL(NAME, BASE)
962#define DECL_CONTEXT_BASE(NAME) \
963 if (DK >= first##NAME && DK <= last##NAME) \
964 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
965#include "clang/AST/DeclNodes.inc"
966 llvm_unreachable("a decl that inherits DeclContext isn't handled");
967 }
968}
969
971 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
972 // FunctionDecl stores EndRangeLoc for this purpose.
973 if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
975 if (FD->hasBody(Definition))
976 return Definition->getSourceRange().getEnd();
977 return {};
978 }
979
980 if (Stmt *Body = getBody())
981 return Body->getSourceRange().getEnd();
982
983 return {};
984}
985
986bool Decl::AccessDeclContextCheck() const {
987#ifndef NDEBUG
988 // Suppress this check if any of the following hold:
989 // 1. this is the translation unit (and thus has no parent)
990 // 2. this is a template parameter (and thus doesn't belong to its context)
991 // 3. this is a non-type template parameter
992 // 4. the context is not a record
993 // 5. it's invalid
994 // 6. it's a C++0x static_assert.
995 // 7. it's a block literal declaration
996 // 8. it's a temporary with lifetime extended due to being default value.
997 if (isa<TranslationUnitDecl>(this) || isa<TemplateTypeParmDecl>(this) ||
998 isa<NonTypeTemplateParmDecl>(this) || !getDeclContext() ||
999 !isa<CXXRecordDecl>(getDeclContext()) || isInvalidDecl() ||
1000 isa<StaticAssertDecl>(this) || isa<BlockDecl>(this) ||
1001 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
1002 // as DeclContext (?).
1003 isa<ParmVarDecl>(this) ||
1004 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
1005 // AS_none as access specifier.
1006 isa<CXXRecordDecl>(this) ||
1007 isa<ClassScopeFunctionSpecializationDecl>(this) ||
1008 isa<LifetimeExtendedTemporaryDecl>(this))
1009 return true;
1010
1011 assert(Access != AS_none &&
1012 "Access specifier is AS_none inside a record decl");
1013#endif
1014 return true;
1015}
1016
1018 const DeclContext *DC = getLexicalDeclContext();
1019
1020 while (DC && !isa<ExportDecl>(DC))
1021 DC = DC->getLexicalParent();
1022
1023 return DC && isa<ExportDecl>(DC);
1024}
1025
1027 auto *M = getOwningModule();
1028
1029 if (!M)
1030 return false;
1031
1032 M = M->getTopLevelModule();
1033 // FIXME: It is problematic if the header module lives in another module
1034 // unit. Consider to fix this by techniques like
1035 // ExternalASTSource::hasExternalDefinitions.
1036 if (M->isHeaderLikeModule())
1037 return false;
1038
1039 // A global module without parent implies that we're parsing the global
1040 // module. So it can't be in another module unit.
1041 if (M->isGlobalModule())
1042 return false;
1043
1044 assert(M->isModulePurview() && "New module kind?");
1045 return M != getASTContext().getCurrentNamedModule();
1046}
1047
1048static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
1049static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
1050
1051int64_t Decl::getID() const {
1052 return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
1053}
1054
1055const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
1056 QualType Ty;
1057 if (const auto *D = dyn_cast<ValueDecl>(this))
1058 Ty = D->getType();
1059 else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1060 Ty = D->getUnderlyingType();
1061 else
1062 return nullptr;
1063
1064 if (Ty->isFunctionPointerType())
1065 Ty = Ty->castAs<PointerType>()->getPointeeType();
1066 else if (Ty->isFunctionReferenceType())
1067 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1068 else if (BlocksToo && Ty->isBlockPointerType())
1069 Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
1070
1071 return Ty->getAs<FunctionType>();
1072}
1073
1075 QualType Ty;
1076 if (const auto *D = dyn_cast<ValueDecl>(this))
1077 Ty = D->getType();
1078 else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1079 Ty = D->getUnderlyingType();
1080 else
1081 return false;
1082
1084}
1085
1087 assert(getDeclContext());
1089}
1090
1091/// Starting at a given context (a Decl or DeclContext), look for a
1092/// code context that is not a closure (a lambda, block, etc.).
1093template <class T> static Decl *getNonClosureContext(T *D) {
1094 if (getKind(D) == Decl::CXXMethod) {
1095 auto *MD = cast<CXXMethodDecl>(D);
1096 if (MD->getOverloadedOperator() == OO_Call &&
1097 MD->getParent()->isLambda())
1098 return getNonClosureContext(MD->getParent()->getParent());
1099 return MD;
1100 }
1101 if (auto *FD = dyn_cast<FunctionDecl>(D))
1102 return FD;
1103 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1104 return MD;
1105 if (auto *BD = dyn_cast<BlockDecl>(D))
1106 return getNonClosureContext(BD->getParent());
1107 if (auto *CD = dyn_cast<CapturedDecl>(D))
1108 return getNonClosureContext(CD->getParent());
1109 return nullptr;
1110}
1111
1113 return ::getNonClosureContext(this);
1114}
1115
1117 return ::getNonClosureContext(this);
1118}
1119
1120//===----------------------------------------------------------------------===//
1121// DeclContext Implementation
1122//===----------------------------------------------------------------------===//
1123
1125 DeclContextBits.DeclKind = K;
1128 setNeedToReconcileExternalVisibleStorage(false);
1129 setHasLazyLocalLexicalLookups(false);
1130 setHasLazyExternalLexicalLookups(false);
1131 setUseQualifiedLookup(false);
1132}
1133
1135 switch (D->getKind()) {
1136#define DECL(NAME, BASE)
1137#define DECL_CONTEXT(NAME) case Decl::NAME:
1138#define DECL_CONTEXT_BASE(NAME)
1139#include "clang/AST/DeclNodes.inc"
1140 return true;
1141 default:
1142#define DECL(NAME, BASE)
1143#define DECL_CONTEXT_BASE(NAME) \
1144 if (D->getKind() >= Decl::first##NAME && \
1145 D->getKind() <= Decl::last##NAME) \
1146 return true;
1147#include "clang/AST/DeclNodes.inc"
1148 return false;
1149 }
1150}
1151
1152DeclContext::~DeclContext() = default;
1153
1154/// Find the parent context of this context that will be
1155/// used for unqualified name lookup.
1156///
1157/// Generally, the parent lookup context is the semantic context. However, for
1158/// a friend function the parent lookup context is the lexical context, which
1159/// is the class in which the friend is declared.
1161 // FIXME: Find a better way to identify friends.
1162 if (isa<FunctionDecl>(this))
1165 return getLexicalParent();
1166
1167 // A lookup within the call operator of a lambda never looks in the lambda
1168 // class; instead, skip to the context in which that closure type is
1169 // declared.
1170 if (isLambdaCallOperator(this))
1171 return getParent()->getParent();
1172
1173 return getParent();
1174}
1175
1177 const DeclContext *Ctx = this;
1178
1179 do {
1180 if (Ctx->isClosure())
1181 return cast<BlockDecl>(Ctx);
1182 Ctx = Ctx->getParent();
1183 } while (Ctx);
1184
1185 return nullptr;
1186}
1187
1189 return isNamespace() &&
1190 cast<NamespaceDecl>(this)->isInline();
1191}
1192
1194 if (!isNamespace())
1195 return false;
1196
1197 const auto *ND = cast<NamespaceDecl>(this);
1198 if (ND->isInline()) {
1199 return ND->getParent()->isStdNamespace();
1200 }
1201
1203 return false;
1204
1205 const IdentifierInfo *II = ND->getIdentifier();
1206 return II && II->isStr("std");
1207}
1208
1210 if (isFileContext())
1211 return false;
1212
1213 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1214 return true;
1215
1216 if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1217 if (Record->getDescribedClassTemplate())
1218 return true;
1219
1220 if (Record->isDependentLambda())
1221 return true;
1222 if (Record->isNeverDependentLambda())
1223 return false;
1224 }
1225
1226 if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1227 if (Function->getDescribedFunctionTemplate())
1228 return true;
1229
1230 // Friend function declarations are dependent if their *lexical*
1231 // context is dependent.
1232 if (cast<Decl>(this)->getFriendObjectKind())
1234 }
1235
1236 // FIXME: A variable template is a dependent context, but is not a
1237 // DeclContext. A context within it (such as a lambda-expression)
1238 // should be considered dependent.
1239
1240 return getParent() && getParent()->isDependentContext();
1241}
1242
1244 if (getDeclKind() == Decl::Enum)
1245 return !cast<EnumDecl>(this)->isScoped();
1246
1247 return isa<LinkageSpecDecl, ExportDecl, HLSLBufferDecl>(this);
1248}
1249
1250static bool isLinkageSpecContext(const DeclContext *DC,
1252 while (DC->getDeclKind() != Decl::TranslationUnit) {
1253 if (DC->getDeclKind() == Decl::LinkageSpec)
1254 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1255 DC = DC->getLexicalParent();
1256 }
1257 return false;
1258}
1259
1262}
1263
1265 const DeclContext *DC = this;
1266 while (DC->getDeclKind() != Decl::TranslationUnit) {
1267 if (DC->getDeclKind() == Decl::LinkageSpec &&
1268 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1269 return cast<LinkageSpecDecl>(DC);
1270 DC = DC->getLexicalParent();
1271 }
1272 return nullptr;
1273}
1274
1277}
1278
1279bool DeclContext::Encloses(const DeclContext *DC) const {
1280 if (getPrimaryContext() != this)
1281 return getPrimaryContext()->Encloses(DC);
1282
1283 for (; DC; DC = DC->getParent())
1284 if (!isa<LinkageSpecDecl>(DC) && !isa<ExportDecl>(DC) &&
1285 DC->getPrimaryContext() == this)
1286 return true;
1287 return false;
1288}
1289
1291 DeclContext *DC = this;
1292 while (DC->isTransparentContext()) {
1293 DC = DC->getParent();
1294 assert(DC && "All transparent contexts should have a parent!");
1295 }
1296 return DC;
1297}
1298
1300 switch (getDeclKind()) {
1301 case Decl::ExternCContext:
1302 case Decl::LinkageSpec:
1303 case Decl::Export:
1304 case Decl::Block:
1305 case Decl::Captured:
1306 case Decl::OMPDeclareReduction:
1307 case Decl::OMPDeclareMapper:
1308 case Decl::RequiresExprBody:
1309 // There is only one DeclContext for these entities.
1310 return this;
1311
1312 case Decl::HLSLBuffer:
1313 // Each buffer, even with the same name, is a distinct construct.
1314 // Multiple buffers with the same name are allowed for backward
1315 // compatibility.
1316 // As long as buffers have unique resource bindings the names don't matter.
1317 // The names get exposed via the CPU-side reflection API which
1318 // supports querying bindings, so we cannot remove them.
1319 return this;
1320
1321 case Decl::TranslationUnit:
1322 return static_cast<TranslationUnitDecl *>(this)->getFirstDecl();
1323 case Decl::Namespace:
1324 // The original namespace is our primary context.
1325 return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1326
1327 case Decl::ObjCMethod:
1328 return this;
1329
1330 case Decl::ObjCInterface:
1331 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1332 if (auto *Def = OID->getDefinition())
1333 return Def;
1334 return this;
1335
1336 case Decl::ObjCProtocol:
1337 if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1338 if (auto *Def = OPD->getDefinition())
1339 return Def;
1340 return this;
1341
1342 case Decl::ObjCCategory:
1343 return this;
1344
1345 case Decl::ObjCImplementation:
1346 case Decl::ObjCCategoryImpl:
1347 return this;
1348
1349 default:
1350 if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1351 // If this is a tag type that has a definition or is currently
1352 // being defined, that definition is our primary context.
1353 auto *Tag = cast<TagDecl>(this);
1354
1355 if (TagDecl *Def = Tag->getDefinition())
1356 return Def;
1357
1358 if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1359 // Note, TagType::getDecl returns the (partial) definition one exists.
1360 TagDecl *PossiblePartialDef = TagTy->getDecl();
1361 if (PossiblePartialDef->isBeingDefined())
1362 return PossiblePartialDef;
1363 } else {
1364 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1365 }
1366
1367 return Tag;
1368 }
1369
1370 assert(getDeclKind() >= Decl::firstFunction &&
1371 getDeclKind() <= Decl::lastFunction &&
1372 "Unknown DeclContext kind");
1373 return this;
1374 }
1375}
1376
1377template <typename T>
1379 for (T *D = Self->getMostRecentDecl(); D; D = D->getPreviousDecl())
1380 Contexts.push_back(D);
1381
1382 std::reverse(Contexts.begin(), Contexts.end());
1383}
1384
1386 Contexts.clear();
1387
1388 Decl::Kind Kind = getDeclKind();
1389
1390 if (Kind == Decl::TranslationUnit)
1391 collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts);
1392 else if (Kind == Decl::Namespace)
1393 collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts);
1394 else
1395 Contexts.push_back(this);
1396}
1397
1398std::pair<Decl *, Decl *>
1400 bool FieldsAlreadyLoaded) {
1401 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1402 Decl *FirstNewDecl = nullptr;
1403 Decl *PrevDecl = nullptr;
1404 for (auto *D : Decls) {
1405 if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1406 continue;
1407
1408 if (PrevDecl)
1409 PrevDecl->NextInContextAndBits.setPointer(D);
1410 else
1411 FirstNewDecl = D;
1412
1413 PrevDecl = D;
1414 }
1415
1416 return std::make_pair(FirstNewDecl, PrevDecl);
1417}
1418
1419/// We have just acquired external visible storage, and we already have
1420/// built a lookup map. For every name in the map, pull in the new names from
1421/// the external storage.
1422void DeclContext::reconcileExternalVisibleStorage() const {
1423 assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1424 setNeedToReconcileExternalVisibleStorage(false);
1425
1426 for (auto &Lookup : *LookupPtr)
1427 Lookup.second.setHasExternalDecls();
1428}
1429
1430/// Load the declarations within this lexical storage from an
1431/// external source.
1432/// \return \c true if any declarations were added.
1433bool
1434DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1436 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1437
1438 // Notify that we have a DeclContext that is initializing.
1439 ExternalASTSource::Deserializing ADeclContext(Source);
1440
1441 // Load the external declarations, if any.
1444 Source->FindExternalLexicalDecls(this, Decls);
1445
1446 if (Decls.empty())
1447 return false;
1448
1449 // We may have already loaded just the fields of this record, in which case
1450 // we need to ignore them.
1451 bool FieldsAlreadyLoaded = false;
1452 if (const auto *RD = dyn_cast<RecordDecl>(this))
1453 FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1454
1455 // Splice the newly-read declarations into the beginning of the list
1456 // of declarations.
1457 Decl *ExternalFirst, *ExternalLast;
1458 std::tie(ExternalFirst, ExternalLast) =
1459 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1460 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1461 FirstDecl = ExternalFirst;
1462 if (!LastDecl)
1463 LastDecl = ExternalLast;
1464 return true;
1465}
1466
1469 DeclarationName Name) {
1470 ASTContext &Context = DC->getParentASTContext();
1471 StoredDeclsMap *Map;
1472 if (!(Map = DC->LookupPtr))
1473 Map = DC->CreateStoredDeclsMap(Context);
1474 if (DC->hasNeedToReconcileExternalVisibleStorage())
1475 DC->reconcileExternalVisibleStorage();
1476
1477 (*Map)[Name].removeExternalDecls();
1478
1480}
1481
1484 DeclarationName Name,
1485 ArrayRef<NamedDecl*> Decls) {
1486 ASTContext &Context = DC->getParentASTContext();
1487 StoredDeclsMap *Map;
1488 if (!(Map = DC->LookupPtr))
1489 Map = DC->CreateStoredDeclsMap(Context);
1490 if (DC->hasNeedToReconcileExternalVisibleStorage())
1491 DC->reconcileExternalVisibleStorage();
1492
1493 StoredDeclsList &List = (*Map)[Name];
1494 List.replaceExternalDecls(Decls);
1495 return List.getLookupResult();
1496}
1497
1500 LoadLexicalDeclsFromExternalStorage();
1501 return decl_iterator(FirstDecl);
1502}
1503
1506 LoadLexicalDeclsFromExternalStorage();
1507
1508 return !FirstDecl;
1509}
1510
1512 return (D->getLexicalDeclContext() == this &&
1513 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1514}
1515
1518 LoadLexicalDeclsFromExternalStorage();
1519 return containsDecl(D);
1520}
1521
1522/// shouldBeHidden - Determine whether a declaration which was declared
1523/// within its semantic context should be invisible to qualified name lookup.
1524static bool shouldBeHidden(NamedDecl *D) {
1525 // Skip unnamed declarations.
1526 if (!D->getDeclName())
1527 return true;
1528
1529 // Skip entities that can't be found by name lookup into a particular
1530 // context.
1531 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1533 return true;
1534
1535 // Skip friends and local extern declarations unless they're the first
1536 // declaration of the entity.
1537 if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1538 D != D->getCanonicalDecl())
1539 return true;
1540
1541 // Skip template specializations.
1542 // FIXME: This feels like a hack. Should DeclarationName support
1543 // template-ids, or is there a better way to keep specializations
1544 // from being visible?
1545 if (isa<ClassTemplateSpecializationDecl>(D))
1546 return true;
1547 if (auto *FD = dyn_cast<FunctionDecl>(D))
1548 if (FD->isFunctionTemplateSpecialization())
1549 return true;
1550
1551 // Hide destructors that are invalid. There should always be one destructor,
1552 // but if it is an invalid decl, another one is created. We need to hide the
1553 // invalid one from places that expect exactly one destructor, like the
1554 // serialization code.
1555 if (isa<CXXDestructorDecl>(D) && D->isInvalidDecl())
1556 return true;
1557
1558 return false;
1559}
1560
1562 assert(D->getLexicalDeclContext() == this &&
1563 "decl being removed from non-lexical context");
1564 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1565 "decl is not in decls list");
1566
1567 // Remove D from the decl chain. This is O(n) but hopefully rare.
1568 if (D == FirstDecl) {
1569 if (D == LastDecl)
1570 FirstDecl = LastDecl = nullptr;
1571 else
1572 FirstDecl = D->NextInContextAndBits.getPointer();
1573 } else {
1574 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1575 assert(I && "decl not found in linked list");
1576 if (I->NextInContextAndBits.getPointer() == D) {
1577 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1578 if (D == LastDecl) LastDecl = I;
1579 break;
1580 }
1581 }
1582 }
1583
1584 // Mark that D is no longer in the decl chain.
1585 D->NextInContextAndBits.setPointer(nullptr);
1586
1587 // Remove D from the lookup table if necessary.
1588 if (isa<NamedDecl>(D)) {
1589 auto *ND = cast<NamedDecl>(D);
1590
1591 // Do not try to remove the declaration if that is invisible to qualified
1592 // lookup. E.g. template specializations are skipped.
1593 if (shouldBeHidden(ND))
1594 return;
1595
1596 // Remove only decls that have a name
1597 if (!ND->getDeclName())
1598 return;
1599
1600 auto *DC = D->getDeclContext();
1601 do {
1602 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1603 if (Map) {
1604 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1605 assert(Pos != Map->end() && "no lookup entry for decl");
1606 StoredDeclsList &List = Pos->second;
1607 List.remove(ND);
1608 // Clean up the entry if there are no more decls.
1609 if (List.isNull())
1610 Map->erase(Pos);
1611 }
1612 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1613 }
1614}
1615
1617 assert(D->getLexicalDeclContext() == this &&
1618 "Decl inserted into wrong lexical context");
1619 assert(!D->getNextDeclInContext() && D != LastDecl &&
1620 "Decl already inserted into a DeclContext");
1621
1622 if (FirstDecl) {
1623 LastDecl->NextInContextAndBits.setPointer(D);
1624 LastDecl = D;
1625 } else {
1626 FirstDecl = LastDecl = D;
1627 }
1628
1629 // Notify a C++ record declaration that we've added a member, so it can
1630 // update its class-specific state.
1631 if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1632 Record->addedMember(D);
1633
1634 // If this is a newly-created (not de-serialized) import declaration, wire
1635 // it in to the list of local import declarations.
1636 if (!D->isFromASTFile()) {
1637 if (auto *Import = dyn_cast<ImportDecl>(D))
1639 }
1640}
1641
1643 addHiddenDecl(D);
1644
1645 if (auto *ND = dyn_cast<NamedDecl>(D))
1646 ND->getDeclContext()->getPrimaryContext()->
1647 makeDeclVisibleInContextWithFlags(ND, false, true);
1648}
1649
1651 addHiddenDecl(D);
1652
1653 if (auto *ND = dyn_cast<NamedDecl>(D))
1654 ND->getDeclContext()->getPrimaryContext()->
1655 makeDeclVisibleInContextWithFlags(ND, true, true);
1656}
1657
1658/// buildLookup - Build the lookup data structure with all of the
1659/// declarations in this DeclContext (and any other contexts linked
1660/// to it or transparent contexts nested within it) and return it.
1661///
1662/// Note that the produced map may miss out declarations from an
1663/// external source. If it does, those entries will be marked with
1664/// the 'hasExternalDecls' flag.
1666 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1667
1668 if (!hasLazyLocalLexicalLookups() &&
1669 !hasLazyExternalLexicalLookups())
1670 return LookupPtr;
1671
1673 collectAllContexts(Contexts);
1674
1675 if (hasLazyExternalLexicalLookups()) {
1676 setHasLazyExternalLexicalLookups(false);
1677 for (auto *DC : Contexts) {
1678 if (DC->hasExternalLexicalStorage()) {
1679 bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1680 setHasLazyLocalLexicalLookups(
1681 hasLazyLocalLexicalLookups() | LoadedDecls );
1682 }
1683 }
1684
1685 if (!hasLazyLocalLexicalLookups())
1686 return LookupPtr;
1687 }
1688
1689 for (auto *DC : Contexts)
1690 buildLookupImpl(DC, hasExternalVisibleStorage());
1691
1692 // We no longer have any lazy decls.
1693 setHasLazyLocalLexicalLookups(false);
1694 return LookupPtr;
1695}
1696
1697/// buildLookupImpl - Build part of the lookup data structure for the
1698/// declarations contained within DCtx, which will either be this
1699/// DeclContext, a DeclContext linked to it, or a transparent context
1700/// nested within it.
1701void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1702 for (auto *D : DCtx->noload_decls()) {
1703 // Insert this declaration into the lookup structure, but only if
1704 // it's semantically within its decl context. Any other decls which
1705 // should be found in this context are added eagerly.
1706 //
1707 // If it's from an AST file, don't add it now. It'll get handled by
1708 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1709 // in C++, we do not track external visible decls for the TU, so in
1710 // that case we need to collect them all here.
1711 if (auto *ND = dyn_cast<NamedDecl>(D))
1712 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1713 (!ND->isFromASTFile() ||
1714 (isTranslationUnit() &&
1715 !getParentASTContext().getLangOpts().CPlusPlus)))
1716 makeDeclVisibleInContextImpl(ND, Internal);
1717
1718 // If this declaration is itself a transparent declaration context
1719 // or inline namespace, add the members of this declaration of that
1720 // context (recursively).
1721 if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1722 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1723 buildLookupImpl(InnerCtx, Internal);
1724 }
1725}
1726
1729 // For transparent DeclContext, we should lookup in their enclosing context.
1730 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1731 return getParent()->lookup(Name);
1732
1733 const DeclContext *PrimaryContext = getPrimaryContext();
1734 if (PrimaryContext != this)
1735 return PrimaryContext->lookup(Name);
1736
1737 // If we have an external source, ensure that any later redeclarations of this
1738 // context have been loaded, since they may add names to the result of this
1739 // lookup (or add external visible storage).
1741 if (Source)
1742 (void)cast<Decl>(this)->getMostRecentDecl();
1743
1745 assert(Source && "external visible storage but no external source?");
1746
1747 if (hasNeedToReconcileExternalVisibleStorage())
1748 reconcileExternalVisibleStorage();
1749
1750 StoredDeclsMap *Map = LookupPtr;
1751
1752 if (hasLazyLocalLexicalLookups() ||
1753 hasLazyExternalLexicalLookups())
1754 // FIXME: Make buildLookup const?
1755 Map = const_cast<DeclContext*>(this)->buildLookup();
1756
1757 if (!Map)
1758 Map = CreateStoredDeclsMap(getParentASTContext());
1759
1760 // If we have a lookup result with no external decls, we are done.
1761 std::pair<StoredDeclsMap::iterator, bool> R =
1762 Map->insert(std::make_pair(Name, StoredDeclsList()));
1763 if (!R.second && !R.first->second.hasExternalDecls())
1764 return R.first->second.getLookupResult();
1765
1766 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1767 if (StoredDeclsMap *Map = LookupPtr) {
1768 StoredDeclsMap::iterator I = Map->find(Name);
1769 if (I != Map->end())
1770 return I->second.getLookupResult();
1771 }
1772 }
1773
1774 return {};
1775 }
1776
1777 StoredDeclsMap *Map = LookupPtr;
1778 if (hasLazyLocalLexicalLookups() ||
1779 hasLazyExternalLexicalLookups())
1780 Map = const_cast<DeclContext*>(this)->buildLookup();
1781
1782 if (!Map)
1783 return {};
1784
1785 StoredDeclsMap::iterator I = Map->find(Name);
1786 if (I == Map->end())
1787 return {};
1788
1789 return I->second.getLookupResult();
1790}
1791
1794 assert(getDeclKind() != Decl::LinkageSpec &&
1795 getDeclKind() != Decl::Export &&
1796 "should not perform lookups into transparent contexts");
1797
1798 DeclContext *PrimaryContext = getPrimaryContext();
1799 if (PrimaryContext != this)
1800 return PrimaryContext->noload_lookup(Name);
1801
1802 loadLazyLocalLexicalLookups();
1803 StoredDeclsMap *Map = LookupPtr;
1804 if (!Map)
1805 return {};
1806
1807 StoredDeclsMap::iterator I = Map->find(Name);
1808 return I != Map->end() ? I->second.getLookupResult()
1809 : lookup_result();
1810}
1811
1812// If we have any lazy lexical declarations not in our lookup map, add them
1813// now. Don't import any external declarations, not even if we know we have
1814// some missing from the external visible lookups.
1815void DeclContext::loadLazyLocalLexicalLookups() {
1816 if (hasLazyLocalLexicalLookups()) {
1818 collectAllContexts(Contexts);
1819 for (auto *Context : Contexts)
1820 buildLookupImpl(Context, hasExternalVisibleStorage());
1821 setHasLazyLocalLexicalLookups(false);
1822 }
1823}
1824
1827 Results.clear();
1828
1829 // If there's no external storage, just perform a normal lookup and copy
1830 // the results.
1832 lookup_result LookupResults = lookup(Name);
1833 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1834 if (!Results.empty())
1835 return;
1836 }
1837
1838 // If we have a lookup table, check there first. Maybe we'll get lucky.
1839 // FIXME: Should we be checking these flags on the primary context?
1840 if (Name && !hasLazyLocalLexicalLookups() &&
1841 !hasLazyExternalLexicalLookups()) {
1842 if (StoredDeclsMap *Map = LookupPtr) {
1843 StoredDeclsMap::iterator Pos = Map->find(Name);
1844 if (Pos != Map->end()) {
1845 Results.insert(Results.end(),
1846 Pos->second.getLookupResult().begin(),
1847 Pos->second.getLookupResult().end());
1848 return;
1849 }
1850 }
1851 }
1852
1853 // Slow case: grovel through the declarations in our chain looking for
1854 // matches.
1855 // FIXME: If we have lazy external declarations, this will not find them!
1856 // FIXME: Should we CollectAllContexts and walk them all here?
1857 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1858 if (auto *ND = dyn_cast<NamedDecl>(D))
1859 if (ND->getDeclName() == Name)
1860 Results.push_back(ND);
1861 }
1862}
1863
1865 DeclContext *Ctx = this;
1866
1867 // In C, a record type is the redeclaration context for its fields only. If
1868 // we arrive at a record context after skipping anything else, we should skip
1869 // the record as well. Currently, this means skipping enumerations because
1870 // they're the only transparent context that can exist within a struct or
1871 // union.
1872 bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1873 !getParentASTContext().getLangOpts().CPlusPlus;
1874
1875 // Skip through contexts to get to the redeclaration context. Transparent
1876 // contexts are always skipped.
1877 while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1878 Ctx = Ctx->getParent();
1879 return Ctx;
1880}
1881
1883 DeclContext *Ctx = this;
1884 // Skip through non-namespace, non-translation-unit contexts.
1885 while (!Ctx->isFileContext())
1886 Ctx = Ctx->getParent();
1887 return Ctx->getPrimaryContext();
1888}
1889
1891 // Loop until we find a non-record context.
1892 RecordDecl *OutermostRD = nullptr;
1893 DeclContext *DC = this;
1894 while (DC->isRecord()) {
1895 OutermostRD = cast<RecordDecl>(DC);
1896 DC = DC->getLexicalParent();
1897 }
1898 return OutermostRD;
1899}
1900
1902 // For non-file contexts, this is equivalent to Equals.
1903 if (!isFileContext())
1904 return O->Equals(this);
1905
1906 do {
1907 if (O->Equals(this))
1908 return true;
1909
1910 const auto *NS = dyn_cast<NamespaceDecl>(O);
1911 if (!NS || !NS->isInline())
1912 break;
1913 O = NS->getParent();
1914 } while (O);
1915
1916 return false;
1917}
1918
1920 DeclContext *PrimaryDC = this->getPrimaryContext();
1922 // If the decl is being added outside of its semantic decl context, we
1923 // need to ensure that we eagerly build the lookup information for it.
1924 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1925}
1926
1927void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1928 bool Recoverable) {
1929 assert(this == getPrimaryContext() && "expected a primary DC");
1930
1931 if (!isLookupContext()) {
1934 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1935 return;
1936 }
1937
1938 // Skip declarations which should be invisible to name lookup.
1939 if (shouldBeHidden(D))
1940 return;
1941
1942 // If we already have a lookup data structure, perform the insertion into
1943 // it. If we might have externally-stored decls with this name, look them
1944 // up and perform the insertion. If this decl was declared outside its
1945 // semantic context, buildLookup won't add it, so add it now.
1946 //
1947 // FIXME: As a performance hack, don't add such decls into the translation
1948 // unit unless we're in C++, since qualified lookup into the TU is never
1949 // performed.
1950 if (LookupPtr || hasExternalVisibleStorage() ||
1951 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1952 (getParentASTContext().getLangOpts().CPlusPlus ||
1953 !isTranslationUnit()))) {
1954 // If we have lazily omitted any decls, they might have the same name as
1955 // the decl which we are adding, so build a full lookup table before adding
1956 // this decl.
1957 buildLookup();
1958 makeDeclVisibleInContextImpl(D, Internal);
1959 } else {
1960 setHasLazyLocalLexicalLookups(true);
1961 }
1962
1963 // If we are a transparent context or inline namespace, insert into our
1964 // parent context, too. This operation is recursive.
1967 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1968
1969 auto *DCAsDecl = cast<Decl>(this);
1970 // Notify that a decl was made visible unless we are a Tag being defined.
1971 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1972 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1973 L->AddedVisibleDecl(this, D);
1974}
1975
1976void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1977 // Find or create the stored declaration map.
1978 StoredDeclsMap *Map = LookupPtr;
1979 if (!Map) {
1981 Map = CreateStoredDeclsMap(*C);
1982 }
1983
1984 // If there is an external AST source, load any declarations it knows about
1985 // with this declaration's name.
1986 // If the lookup table contains an entry about this name it means that we
1987 // have already checked the external source.
1988 if (!Internal)
1989 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1991 Map->find(D->getDeclName()) == Map->end())
1992 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1993
1994 // Insert this declaration into the map.
1995 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1996
1997 if (Internal) {
1998 // If this is being added as part of loading an external declaration,
1999 // this may not be the only external declaration with this name.
2000 // In this case, we never try to replace an existing declaration; we'll
2001 // handle that when we finalize the list of declarations for this name.
2002 DeclNameEntries.setHasExternalDecls();
2003 DeclNameEntries.prependDeclNoReplace(D);
2004 return;
2005 }
2006
2007 DeclNameEntries.addOrReplaceDecl(D);
2008}
2009
2011 return cast<UsingDirectiveDecl>(*I);
2012}
2013
2014/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
2015/// this context.
2017 // FIXME: Use something more efficient than normal lookup for using
2018 // directives. In C++, using directives are looked up more than anything else.
2019 lookup_result Result = lookup(UsingDirectiveDecl::getName());
2020 return udir_range(Result.begin(), Result.end());
2021}
2022
2023//===----------------------------------------------------------------------===//
2024// Creation and Destruction of StoredDeclsMaps. //
2025//===----------------------------------------------------------------------===//
2026
2027StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
2028 assert(!LookupPtr && "context already has a decls map");
2029 assert(getPrimaryContext() == this &&
2030 "creating decls map on non-primary context");
2031
2032 StoredDeclsMap *M;
2033 bool Dependent = isDependentContext();
2034 if (Dependent)
2035 M = new DependentStoredDeclsMap();
2036 else
2037 M = new StoredDeclsMap();
2038 M->Previous = C.LastSDM;
2039 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
2040 LookupPtr = M;
2041 return M;
2042}
2043
2044void ASTContext::ReleaseDeclContextMaps() {
2045 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
2046 // pointer because the subclass doesn't add anything that needs to
2047 // be deleted.
2048 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
2049 LastSDM.setPointer(nullptr);
2050}
2051
2052void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
2053 while (Map) {
2054 // Advance the iteration before we invalidate memory.
2055 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
2056
2057 if (Dependent)
2058 delete static_cast<DependentStoredDeclsMap*>(Map);
2059 else
2060 delete Map;
2061
2062 Map = Next.getPointer();
2063 Dependent = Next.getInt();
2064 }
2065}
2066
2069 const PartialDiagnostic &PDiag) {
2070 assert(Parent->isDependentContext()
2071 && "cannot iterate dependent diagnostics of non-dependent context");
2072 Parent = Parent->getPrimaryContext();
2073 if (!Parent->LookupPtr)
2074 Parent->CreateStoredDeclsMap(C);
2075
2076 auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
2077
2078 // Allocate the copy of the PartialDiagnostic via the ASTContext's
2079 // BumpPtrAllocator, rather than the ASTContext itself.
2080 DiagnosticStorage *DiagStorage = nullptr;
2081 if (PDiag.hasStorage())
2082 DiagStorage = new (C) DiagnosticStorage;
2083
2084 auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
2085
2086 // TODO: Maybe we shouldn't reverse the order during insertion.
2087 DD->NextDiagnostic = Map->FirstDiagnostic;
2088 Map->FirstDiagnostic = DD;
2089
2090 return DD;
2091}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3230
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool shouldBeHidden(NamedDecl *D)
shouldBeHidden - Determine whether a declaration which was declared within its semantic context shoul...
Definition: DeclBase.cpp:1524
static bool isLinkageSpecContext(const DeclContext *DC, LinkageSpecDecl::LanguageIDs ID)
Definition: DeclBase.cpp:1250
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1048
static Decl * getNonClosureContext(T *D)
Starting at a given context (a Decl or DeclContext), look for a code context that is not a closure (a...
Definition: DeclBase.cpp:1093
static AvailabilityResult CheckAvailability(ASTContext &Context, const AvailabilityAttr *A, std::string *Message, VersionTuple EnclosingVersion)
Determine the availability of the given declaration based on the target platform.
Definition: DeclBase.cpp:553
void collectAllContextsImpl(T *Self, SmallVectorImpl< DeclContext * > &Contexts)
Definition: DeclBase.cpp:1378
static StringRef getRealizedPlatform(const AvailabilityAttr *A, const ASTContext &Context)
Definition: DeclBase.cpp:531
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::SourceLocation class and associated facilities.
C Language Family Type Representation.
std::string Label
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1181
const LangOptions & getLangOpts() const
Definition: ASTContext.h:761
llvm::BumpPtrAllocator & getAllocator() const
Definition: ASTContext.h:700
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:704
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:743
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1166
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Definition: ASTContext.h:1057
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Attr - This represents one attribute.
Definition: Attr.h:40
bool isInherited() const
Definition: Attr.h:89
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4355
Pointer to a block type.
Definition: Type.h:2880
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1347
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2154
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1402
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1942
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:2016
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2066
bool isFileContext() const
Definition: DeclBase.h:2012
void setHasExternalVisibleStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations visible in this context.
Definition: DeclBase.h:2530
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1919
DeclContextLookupResult lookup_result
Definition: DeclBase.h:2401
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl * > Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1399
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1243
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:1116
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1971
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1275
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1209
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1901
bool isClosure() const
Definition: DeclBase.h:1975
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1958
bool isNamespace() const
Definition: DeclBase.h:2026
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1728
bool isLookupContext() const
Test whether the context supports looking up names.
Definition: DeclBase.h:2007
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1176
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:2524
const char * getDeclKindName() const
Definition: DeclBase.cpp:165
bool isTranslationUnit() const
Definition: DeclBase.h:2017
bool isRecord() const
Definition: DeclBase.h:2021
void collectAllContexts(SmallVectorImpl< DeclContext * > &Contexts)
Collects all of the declaration contexts that are semantically connected to this declaration context.
Definition: DeclBase.cpp:1385
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1864
llvm::iterator_range< udir_iterator > udir_range
Definition: DeclBase.h:2478
Decl * FirstDecl
FirstDecl - The first declaration stored within this declaration context.
Definition: DeclBase.h:1912
DeclContext(Decl::Kind K)
Definition: DeclBase.cpp:1124
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
Definition: DeclBase.cpp:1650
bool containsDeclAndLoad(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1516
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1561
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1642
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1665
bool hasValidDeclKind() const
Definition: DeclBase.cpp:156
bool isStdNamespace() const
Definition: DeclBase.cpp:1193
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don't attempt to retr...
Definition: DeclBase.cpp:1793
static bool classof(const Decl *D)
Definition: DeclBase.cpp:1134
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1511
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2512
void setUseQualifiedLookup(bool use=true) const
Definition: DeclBase.h:2543
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1882
Decl * LastDecl
LastDecl - The last declaration stored within this declaration context.
Definition: DeclBase.h:1918
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition: DeclBase.h:2205
friend class DependentDiagnostic
For CreateStoredDeclsMap.
Definition: DeclBase.h:1411
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1299
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1890
bool decls_empty() const
Definition: DeclBase.cpp:1504
bool isInlineNamespace() const
Definition: DeclBase.cpp:1188
DeclContextBitfields DeclContextBits
Definition: DeclBase.h:1874
bool isFunctionOrMethod() const
Definition: DeclBase.h:1994
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2518
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1160
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1260
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1264
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1279
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1616
void localUncachedLookup(DeclarationName Name, SmallVectorImpl< NamedDecl * > &Results)
A simplistic name lookup mechanism that performs name lookup into this declaration context without co...
Definition: DeclBase.cpp:1825
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1935
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1290
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1498
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1044
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:296
bool isInStdNamespace() const
Definition: DeclBase.cpp:404
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:240
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:766
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:236
static void add(Kind k)
Definition: DeclBase.cpp:203
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1194
bool hasAttrs() const
Definition: DeclBase.h:502
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:429
void addAttr(Attr *A)
Definition: DeclBase.cpp:904
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:504
bool hasLocalOwningModuleStorage() const
Definition: DeclBase.cpp:120
bool isFunctionPointerType() const
Definition: DeclBase.cpp:1074
virtual ~Decl()
ExternalSourceSymbolAttr * getExternalSourceSymbolAttr() const
Looks on this and related declarations for an applicable external source symbol attribute.
Definition: DeclBase.cpp:495
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:732
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition: DeclBase.h:844
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:221
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:439
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:443
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:637
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:133
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:86
static unsigned getIdentifierNamespaceForKind(Kind DK)
Definition: DeclBase.cpp:751
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1055
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:473
bool isFileContextDecl() const
Definition: DeclBase.cpp:409
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:932
Decl * getNextDeclInContext()
Definition: DeclBase.h:438
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:263
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1017
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:970
int64_t getID() const
Definition: DeclBase.cpp:1051
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:483
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1055
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Definition: DeclBase.cpp:1026
llvm::PointerIntPair< Decl *, 3, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition: DeclBase.h:246
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:811
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:275
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:228
bool canBeWeakImported(bool &IsDefinition) const
Determines whether this symbol can be weak-imported, e.g., whether it would be well-formed to add the...
Definition: DeclBase.cpp:703
void dropAttrs()
Definition: DeclBase.cpp:897
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:951
const TemplateParameterList * getDescribedTemplateParams() const
If this is a declaration that describes some template or partial specialization, this returns the cor...
Definition: DeclBase.cpp:253
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:754
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition: DeclBase.cpp:377
const Attr * getDefiningAttr() const
Return this declaration's defining attribute if it has one.
Definition: DeclBase.cpp:521
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2622
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1086
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
Definition: DeclBase.cpp:1112
bool isInvalidDecl() const
Definition: DeclBase.h:571
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:857
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity,...
Definition: DeclBase.cpp:516
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1137
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:486
SourceLocation getLocation() const
Definition: DeclBase.h:432
const char * getDeclKindName() const
Definition: DeclBase.cpp:124
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:141
@ IDNS_Type
Types, declared with 'struct foo', typedefs, etc.
Definition: DeclBase.h:127
@ IDNS_OMPReduction
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:175
@ IDNS_Label
Labels, declared with 'x:' and referenced with 'goto x'.
Definition: DeclBase.h:114
@ IDNS_Member
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:133
@ IDNS_OMPMapper
This declaration is an OpenMP user defined mapper.
Definition: DeclBase.h:178
@ IDNS_ObjCProtocol
Objective C @protocol.
Definition: DeclBase.h:144
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
Definition: DeclBase.h:137
@ IDNS_Using
This declaration is a using declaration.
Definition: DeclBase.h:160
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:122
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:211
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:798
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1017
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:591
unsigned Access
Access - Used by C++ decls for the access specifier.
Definition: DeclBase.h:328
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:458
DeclContext * getDeclContext()
Definition: DeclBase.h:441
attr_range attrs() const
Definition: DeclBase.h:519
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:394
static void EnableStatistics()
Definition: DeclBase.cpp:175
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:414
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition: DeclBase.cpp:689
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:806
static void PrintStats()
Definition: DeclBase.cpp:179
void updateOutOfDate(IdentifierInfo &II) const
Update a potentially out-of-date declaration.
Definition: DeclBase.cpp:64
AttrVec & getAttrs()
Definition: DeclBase.h:508
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:337
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:886
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:341
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:946
Kind getKind() const
Definition: DeclBase.h:435
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:849
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition: DeclBase.cpp:435
The name of a declaration.
A dependently-generated diagnostic.
static DependentDiagnostic * Create(ASTContext &Context, DeclContext *Parent, AccessNonce _, SourceLocation Loc, bool IsMemberAccess, AccessSpecifier AS, NamedDecl *TargetDecl, CXXRecordDecl *NamingClass, QualType BaseObjectType, const PartialDiagnostic &PDiag)
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
Abstract interface for external sources of AST nodes.
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl * > Decls)
Definition: DeclBase.cpp:1483
static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name)
Definition: DeclBase.cpp:1468
virtual Module * getModule(unsigned ID)
Retrieve the module that corresponds to the given module ID.
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)
Update an out-of-date identifier.
virtual bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name)
Find all declarations with the given name in the given context, and add them to the context by callin...
virtual void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Result)
Finds all declarations lexically contained within the given DeclContext, after applying an optional f...
Represents a function declaration or definition.
Definition: Decl.h:1917
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3709
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:82
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
Definition: LangOptions.h:529
Represents a linkage specification.
Definition: DeclCXX.h:2884
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2893
Describes a module or submodule.
Definition: Module.h:98
This represents a decl that may have a name.
Definition: Decl.h:247
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:313
Represent a C++ namespace.
Definition: Decl.h:542
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool hasWeakClassImport() const
Does this runtime support weakly importing classes?
Definition: ObjCRuntime.h:362
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2800
void print(raw_ostream &OS) const override
Definition: DeclBase.cpp:310
A (possibly-)qualified type.
Definition: Type.h:736
QualType getCanonicalType() const
Definition: Type.h:6716
Represents a struct/union/class.
Definition: Decl.h:4012
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2911
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
void print(raw_ostream &OS, const SourceManager &SM) const
Stmt - This represents one statement.
Definition: Stmt.h:72
An array of decls optimized for the common case of only containing one entry.
void addOrReplaceDecl(NamedDecl *D)
If this is a redeclaration of an existing decl, replace the old one with D.
void prependDeclNoReplace(NamedDecl *D)
Add a declaration to the list without checking if it replaces anything.
static void DestroyAll(StoredDeclsMap *Map, bool Dependent)
Definition: DeclBase.cpp:2052
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3454
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3577
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:4550
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1545
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled.
Definition: TargetInfo.h:1549
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:409
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
The top declaration context.
Definition: Decl.h:82
ASTContext & getASTContext() const
Definition: Decl.h:118
bool isBlockPointerType() const
Definition: Type.h:6924
bool isFunctionReferenceType() const
Definition: Type.h:6957
bool isFunctionPointerType() const
Definition: Type.h:6950
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7497
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7430
Represents C++ using-directive.
Definition: DeclCXX.h:2969
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:33
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
@ CPlusPlus
Definition: LangStandard.h:53
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:28
@ C
Languages that the frontend can parse and compile.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:69
@ AR_NotYetIntroduced
Definition: DeclBase.h:71
@ AR_Available
Definition: DeclBase.h:70
@ AR_Deprecated
Definition: DeclBase.h:72
@ AR_Unavailable
Definition: DeclBase.h:73
@ AS_public
Definition: Specifiers.h:115
@ AS_none
Definition: Specifiers.h:118
UsingDirectiveDecl * operator*() const
Definition: DeclBase.cpp:2010