clang 24.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"
29#include "clang/AST/Stmt.h"
30#include "clang/AST/Type.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/Module.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/VersionTuple.h"
43#include "llvm/Support/raw_ostream.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <string>
48#include <tuple>
49#include <utility>
50
51using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// Statistics
55//===----------------------------------------------------------------------===//
56
57#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
58#define ABSTRACT_DECL(DECL)
59#include "clang/AST/DeclNodes.inc"
60
61#define DECL(DERIVED, BASE) \
62 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
63 "Alignment sufficient after objects prepended to " #DERIVED);
64#define ABSTRACT_DECL(DECL)
65#include "clang/AST/DeclNodes.inc"
66
67void *Decl::operator new(std::size_t Size, const ASTContext &Context,
68 GlobalDeclID ID, std::size_t Extra) {
69 // Allocate an extra 8 bytes worth of storage, which ensures that the
70 // resulting pointer will still be 8-byte aligned.
71 static_assert(sizeof(uint64_t) >= alignof(Decl), "Decl won't be misaligned");
72 void *Start = Context.Allocate(Size + Extra + 8);
73 void *Result = (char*)Start + 8;
74
75 uint64_t *PrefixPtr = (uint64_t *)Result - 1;
76
77 *PrefixPtr = ID.getRawValue();
78
79 // We leave the upper 16 bits to store the module IDs. 48 bits should be
80 // sufficient to store a declaration ID. See the comments in setOwningModuleID
81 // for details.
82 assert((*PrefixPtr < llvm::maskTrailingOnes<uint64_t>(48)) &&
83 "Current Implementation limits the number of module files to not "
84 "exceed 2^16. Contact Clang Developers to remove the limitation.");
85
86 return Result;
87}
88
89void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
90 DeclContext *Parent, std::size_t Extra) {
91 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
92 // With local visibility enabled, we track the owning module even for local
93 // declarations. We create the TU decl early and may not yet know what the
94 // LangOpts are, so conservatively allocate the storage.
95 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
96 // Ensure required alignment of the resulting object by adding extra
97 // padding at the start if required.
98 size_t ExtraAlign =
99 llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl)));
100 auto *Buffer = reinterpret_cast<char *>(
101 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
102 Buffer += ExtraAlign;
103 auto *ParentModule =
104 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
105 return new (Buffer) Module*(ParentModule) + 1;
106 }
107 return ::operator new(Size + Extra, Ctx);
108}
109
111 if (!isFromASTFile())
112 return GlobalDeclID();
113 // See the comments in `Decl::operator new` for details.
114 uint64_t ID = *((const uint64_t *)this - 1);
115 return GlobalDeclID(ID & llvm::maskTrailingOnes<uint64_t>(48));
116}
117
118unsigned Decl::getOwningModuleID() const {
119 if (!isFromASTFile())
120 return 0;
121
122 uint64_t ID = *((const uint64_t *)this - 1);
123 return ID >> 48;
124}
125
126void Decl::setOwningModuleID(unsigned ID) {
127 assert(isFromASTFile() && "Only works on a deserialized declaration");
128 // Currently, we use 64 bits to store the GlobalDeclID and the module ID
129 // to save the space. See `Decl::operator new` for details. To make it,
130 // we split the higher 32 bits to 2 16bits for the module file index of
131 // GlobalDeclID and the module ID. This introduces a limitation that the
132 // number of modules can't exceed 2^16. (The number of module files should be
133 // less than the number of modules).
134 //
135 // It is counter-intuitive to store both the module file index and the
136 // module ID as it seems redundant. However, this is not true.
137 // The module ID may be different from the module file where it is serialized
138 // from for implicit template instantiations. See
139 // https://github.com/llvm/llvm-project/issues/101939
140 //
141 // If we reach the limitation, we have to remove the limitation by asking
142 // every deserialized declaration to pay for yet another 32 bits, or we have
143 // to review the above issue to decide what we should do for it.
144 assert((ID < llvm::maskTrailingOnes<unsigned>(16)) &&
145 "Current Implementation limits the number of modules to not exceed "
146 "2^16. Contact Clang Developers to remove the limitation.");
147 uint64_t *IDAddress = (uint64_t *)this - 1;
148 *IDAddress &= llvm::maskTrailingOnes<uint64_t>(48);
149 *IDAddress |= (uint64_t)ID << 48;
150}
151
153 if (getOwningModule() &&
154 getOwningModule()->getTopLevelModule()->isNamedModule())
156
157 return nullptr;
158}
159
160Module *Decl::getOwningModuleSlow() const {
161 assert(isFromASTFile() && "Not from AST file?");
163}
164
168
169const char *Decl::getDeclKindName() const {
170 switch (DeclKind) {
171 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
172#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
173#define ABSTRACT_DECL(DECL)
174#include "clang/AST/DeclNodes.inc"
175 }
176}
177
179 InvalidDecl = Invalid;
180 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
181 if (!Invalid) {
182 return;
183 }
184
185 if (!isa<ParmVarDecl>(this)) {
186 // Defensive maneuver for ill-formed code: we're likely not to make it to
187 // a point where we set the access specifier, so default it to "public"
188 // to avoid triggering asserts elsewhere in the front end.
190 }
191
192 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
193 // are invalid too.
194 if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
195 for (auto *Binding : DD->bindings()) {
196 Binding->setInvalidDecl();
197 }
198 }
199}
200
202 switch (getDeclKind()) {
203#define DECL(DERIVED, BASE) case Decl::DERIVED: return true;
204#define ABSTRACT_DECL(DECL)
205#include "clang/AST/DeclNodes.inc"
206 }
207 return false;
208}
209
210const char *DeclContext::getDeclKindName() const {
211 switch (getDeclKind()) {
212#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
213#define ABSTRACT_DECL(DECL)
214#include "clang/AST/DeclNodes.inc"
215 }
216 llvm_unreachable("Declaration context not in DeclNodes.inc!");
217}
218
219bool Decl::StatisticsEnabled = false;
221 StatisticsEnabled = true;
222}
223
225 llvm::errs() << "\n*** Decl Stats:\n";
226
227 int totalDecls = 0;
228#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
229#define ABSTRACT_DECL(DECL)
230#include "clang/AST/DeclNodes.inc"
231 llvm::errs() << " " << totalDecls << " decls total.\n";
232
233 int totalBytes = 0;
234#define DECL(DERIVED, BASE) \
235 if (n##DERIVED##s > 0) { \
236 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
237 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
238 << sizeof(DERIVED##Decl) << " each (" \
239 << n##DERIVED##s * sizeof(DERIVED##Decl) \
240 << " bytes)\n"; \
241 }
242#define ABSTRACT_DECL(DECL)
243#include "clang/AST/DeclNodes.inc"
244
245 llvm::errs() << "Total bytes = " << totalBytes << "\n";
246}
247
249 switch (k) {
250#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
251#define ABSTRACT_DECL(DECL)
252#include "clang/AST/DeclNodes.inc"
253 }
254}
255
257 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
258 return TTP->isParameterPack();
259 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
260 return NTTP->isParameterPack();
261 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
262 return TTP->isParameterPack();
263 return false;
264}
265
267 if (const auto *Var = dyn_cast<ValueDecl>(this))
268 return Var->isParameterPack();
269
271}
272
274 if (auto *FD = dyn_cast<FunctionDecl>(this))
275 return FD;
276 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
277 return FTD->getTemplatedDecl();
278 return nullptr;
279}
280
282 return isa<TemplateDecl>(this);
283}
284
286 if (auto *FD = dyn_cast<FunctionDecl>(this))
287 return FD->getDescribedFunctionTemplate();
288 if (auto *RD = dyn_cast<CXXRecordDecl>(this))
289 return RD->getDescribedClassTemplate();
290 if (auto *VD = dyn_cast<VarDecl>(this))
291 return VD->getDescribedVarTemplate();
292 if (auto *AD = dyn_cast<TypeAliasDecl>(this))
293 return AD->getDescribedAliasTemplate();
294
295 return nullptr;
296}
297
299 if (auto *TD = getDescribedTemplate())
300 return TD->getTemplateParameters();
301 if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))
302 return CTPSD->getTemplateParameters();
303 if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this))
304 return VTPSD->getTemplateParameters();
305 return nullptr;
306}
307
308bool Decl::isTemplated() const {
309 // A declaration is templated if it is a template or a template pattern, or
310 // is within (lexcially for a friend or local function declaration,
311 // semantically otherwise) a dependent context.
312 if (auto *AsDC = dyn_cast<DeclContext>(this))
313 return AsDC->isDependentContext();
314 auto *DC = getFriendObjectKind() || isLocalExternDecl()
316 return DC->isDependentContext() || isTemplateDecl() ||
318}
319
320unsigned Decl::getTemplateDepth() const {
321 if (auto *DC = dyn_cast<DeclContext>(this))
322 if (DC->isFileContext())
323 return 0;
324
325 if (auto *TPL = getDescribedTemplateParams())
326 return TPL->getDepth() + 1;
327
328 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(this))
329 return ESD->getIndexTemplateParm()->getDepth() + 1;
330
331 // If this is a dependent lambda, there might be an enclosing variable
332 // template. In this case, the next step is not the parent DeclContext (or
333 // even a DeclContext at all).
334 auto *RD = dyn_cast<CXXRecordDecl>(this);
335 if (RD && RD->isDependentLambda())
336 if (Decl *Context = RD->getLambdaContextDecl())
337 return Context->getTemplateDepth();
338
339 const DeclContext *DC =
341 return cast<Decl>(DC)->getTemplateDepth();
342}
343
344const DeclContext *Decl::getParentFunctionOrMethod(bool LexicalParent) const {
345 for (const DeclContext *DC = LexicalParent ? getLexicalDeclContext()
346 : getDeclContext();
347 DC && !DC->isFileContext(); DC = DC->getParent())
348 if (DC->isFunctionOrMethod())
349 return DC;
350
351 return nullptr;
352}
353
354//===----------------------------------------------------------------------===//
355// PrettyStackTraceDecl Implementation
356//===----------------------------------------------------------------------===//
357
358void PrettyStackTraceDecl::print(raw_ostream &OS) const {
359 SourceLocation TheLoc = Loc;
360 if (TheLoc.isInvalid() && TheDecl)
361 TheLoc = TheDecl->getLocation();
362
363 if (TheLoc.isValid()) {
364 TheLoc.print(OS, SM);
365 OS << ": ";
366 }
367
368 OS << Message;
369
370 if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
371 OS << " '";
372 DN->printQualifiedName(OS);
373 OS << '\'';
374 }
375 OS << '\n';
376}
377
378//===----------------------------------------------------------------------===//
379// Decl Implementation
380//===----------------------------------------------------------------------===//
381
382// Out-of-line virtual method providing a home for Decl.
383Decl::~Decl() = default;
384
386 DeclCtx = DC;
387}
388
390 if (DC == getLexicalDeclContext())
391 return;
392
393 if (isInSemaDC()) {
394 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
395 } else {
396 getMultipleDC()->LexicalDC = DC;
397 }
398
399 // FIXME: We shouldn't be changing the lexical context of declarations
400 // imported from AST files.
401 if (!isFromASTFile()) {
402 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
403 if (hasOwningModule())
405 }
406
407 assert(
410 getOwningModule()) &&
411 "hidden declaration has no owning module");
412}
413
414void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
415 ASTContext &Ctx) {
416 if (SemaDC == LexicalDC) {
417 DeclCtx = SemaDC;
418 } else {
419 auto *MDC = new (Ctx) Decl::MultipleDC();
420 MDC->SemanticDC = SemaDC;
421 MDC->LexicalDC = LexicalDC;
422 DeclCtx = MDC;
423 }
424}
425
427 const DeclContext *LDC = getLexicalDeclContext();
428 if (!LDC->isDependentContext())
429 return false;
430 while (true) {
431 if (LDC->isFunctionOrMethod())
432 return true;
433 if (!isa<TagDecl>(LDC))
434 return false;
435 if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
436 if (CRD->isLambda())
437 return true;
438 LDC = LDC->getLexicalParent();
439 }
440 return false;
441}
442
444 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
445 if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
446 if (ND->isAnonymousNamespace())
447 return true;
448 }
449
450 return false;
451}
452
454 const DeclContext *DC = getDeclContext();
455 return DC && DC->getNonTransparentContext()->isStdNamespace();
456}
457
459 const auto *DC = dyn_cast<DeclContext>(this);
460 return DC && DC->isFileContext();
461}
462
464 const ASTContext &Ctx, const Decl *D, QualType Ty,
465 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
466 bool IgnoreTemplateOrMacroSubstitution) {
467 // For compatibility with existing code, we treat arrays of length 0 or
468 // 1 as flexible array members.
469 const auto *CAT = Ctx.getAsConstantArrayType(Ty);
470 if (CAT) {
472
473 llvm::APInt Size = CAT->getSize();
474 if (StrictFlexArraysLevel == FAMKind::IncompleteOnly)
475 return false;
476
477 // GCC extension, only allowed to represent a FAM.
478 if (Size.isZero())
479 return true;
480
481 if (StrictFlexArraysLevel == FAMKind::ZeroOrIncomplete && Size.uge(1))
482 return false;
483
484 if (StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete && Size.uge(2))
485 return false;
486 } else if (!Ctx.getAsIncompleteArrayType(Ty)) {
487 return false;
488 }
489
490 if (const auto *OID = dyn_cast_if_present<ObjCIvarDecl>(D))
491 return OID->getNextIvar() == nullptr;
492
493 const auto *FD = dyn_cast_if_present<FieldDecl>(D);
494 if (!FD)
495 return false;
496
497 if (CAT) {
498 // GCC treats an array memeber of a union as an FAM if the size is one or
499 // zero.
500 llvm::APInt Size = CAT->getSize();
501 if (FD->getParent()->isUnion() && (Size.isZero() || Size.isOne()))
502 return true;
503 }
504
505 // Don't consider sizes resulting from macro expansions or template argument
506 // substitution to form C89 tail-padded arrays.
507 if (IgnoreTemplateOrMacroSubstitution) {
508 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
509 while (TInfo) {
510 TypeLoc TL = TInfo->getTypeLoc();
511
512 // Look through typedefs.
514 TInfo = TTL.getDecl()->getTypeSourceInfo();
515 continue;
516 }
517
518 if (auto CTL = TL.getAs<ConstantArrayTypeLoc>()) {
519 if (const Expr *SizeExpr =
520 dyn_cast_if_present<IntegerLiteral>(CTL.getSizeExpr());
521 !SizeExpr || SizeExpr->getExprLoc().isMacroID())
522 return false;
523 }
524
525 break;
526 }
527 }
528
529 // Test that the field is the last in the structure.
531 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
532 return ++FI == FD->getParent()->field_end();
533}
534
536 if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
537 return TUD;
538
540 assert(DC && "This decl is not contained in a translation unit!");
541
542 while (!DC->isTranslationUnit()) {
543 DC = DC->getParent();
544 assert(DC && "This decl is not contained in a translation unit!");
545 }
546
547 return cast<TranslationUnitDecl>(DC);
548}
549
551 if (const auto *TUD = dyn_cast<TranslationUnitDecl>(this))
552 return TUD->getASTContext();
553
554 // This is called a lot, e.g. by every DeclContext::lookup(). Only walk up to
555 // the TranslationUnitDecl once per DeclContext.
556 const DeclContext *DC = getDeclContext();
557 if (!DC->CachedASTContext)
559 return *DC->CachedASTContext;
560}
561
562/// Helper to get the language options from the ASTContext.
563/// Defined out of line to avoid depending on ASTContext.h.
565 return getASTContext().getLangOpts();
566}
567
571
572unsigned Decl::getMaxAlignment() const {
573 if (!hasAttrs())
574 return 0;
575
576 unsigned Align = 0;
577 const AttrVec &V = getAttrs();
578 ASTContext &Ctx = getASTContext();
579 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
580 for (; I != E; ++I) {
581 if (!I->isAlignmentErrorDependent())
582 Align = std::max(Align, I->getAlignment(Ctx));
583 }
584 return Align;
585}
586
587bool Decl::isUsed(bool CheckUsedAttr) const {
588 const Decl *CanonD = getCanonicalDecl();
589 if (CanonD->Used)
590 return true;
591
592 // Check for used attribute.
593 // Ask the most recent decl, since attributes accumulate in the redecl chain.
594 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
595 return true;
596
597 // The information may have not been deserialized yet. Force deserialization
598 // to complete the needed information.
599 return getMostRecentDecl()->getCanonicalDecl()->Used;
600}
601
603 if (isUsed(false))
604 return;
605
606 if (C.getASTMutationListener())
607 C.getASTMutationListener()->DeclarationMarkedUsed(this);
608
609 setIsUsed();
610}
611
612bool Decl::isReferenced() const {
613 if (Referenced)
614 return true;
615
616 // Check redeclarations.
617 for (const auto *I : redecls())
618 if (I->Referenced)
619 return true;
620
621 return false;
622}
623
624ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
625 const Decl *Definition = nullptr;
626 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
627 Definition = ID->getDefinition();
628 } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
629 Definition = PD->getDefinition();
630 } else if (auto *TD = dyn_cast<TagDecl>(this)) {
631 Definition = TD->getDefinition();
632 }
633 if (!Definition)
634 Definition = this;
635
636 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
637 return attr;
638 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
639 return dcd->getAttr<ExternalSourceSymbolAttr>();
640 }
641
642 return nullptr;
643}
644
649
651 if (auto *AA = getAttr<AliasAttr>())
652 return AA;
653 if (auto *IFA = getAttr<IFuncAttr>())
654 return IFA;
655 if (auto *NZA = getAttr<LoaderUninitializedAttr>())
656 return NZA;
657 return nullptr;
658}
659
660static StringRef getRealizedPlatform(const AvailabilityAttr *A,
661 const ASTContext &Context) {
662 // Check if this is an App Extension "platform", and if so chop off
663 // the suffix for matching with the actual platform.
664 StringRef RealizedPlatform = A->getPlatform()->getName();
665 if (!Context.getLangOpts().AppExt)
666 return RealizedPlatform;
667 size_t suffix = RealizedPlatform.rfind("_app_extension");
668 if (suffix != StringRef::npos)
669 return RealizedPlatform.slice(0, suffix);
670 return RealizedPlatform;
671}
672
673/// Determine the availability of the given declaration based on
674/// the target platform.
675///
676/// When it returns an availability result other than \c AR_Available,
677/// if the \p Message parameter is non-NULL, it will be set to a
678/// string describing why the entity is unavailable.
679///
680/// FIXME: Make these strings localizable, since they end up in
681/// diagnostics.
683 const AvailabilityAttr *A,
684 std::string *Message,
685 VersionTuple EnclosingVersion) {
686 if (EnclosingVersion.empty())
687 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
688
689 if (EnclosingVersion.empty())
690 return AR_Available;
691
692 StringRef ActualPlatform = A->getPlatform()->getName();
693 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
694
695 // Match the platform name.
696 if (getRealizedPlatform(A, Context) != TargetPlatform)
697 return AR_Available;
698
699 StringRef PrettyPlatformName
700 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
701
702 if (PrettyPlatformName.empty())
703 PrettyPlatformName = ActualPlatform;
704
705 std::string HintMessage;
706 if (!A->getMessage().empty()) {
707 HintMessage = " - ";
708 HintMessage += A->getMessage();
709 }
710
711 // Make sure that this declaration has not been marked 'unavailable'.
712 if (A->getUnavailable()) {
713 if (Message) {
714 Message->clear();
715 llvm::raw_string_ostream Out(*Message);
716 Out << "not available on " << PrettyPlatformName
717 << HintMessage;
718 }
719
720 return AR_Unavailable;
721 }
722
723 // Make sure that this declaration has already been introduced.
724 if (!A->getIntroduced().empty() &&
725 EnclosingVersion < A->getIntroduced()) {
726 const IdentifierInfo *IIEnv = A->getEnvironment();
727 auto &Triple = Context.getTargetInfo().getTriple();
728 StringRef TargetEnv = Triple.getEnvironmentName();
729 StringRef EnvName =
730 llvm::Triple::getEnvironmentTypeName(Triple.getEnvironment());
731 // Matching environment or no environment on attribute.
732 if (!IIEnv || (Triple.hasEnvironment() && IIEnv->getName() == TargetEnv)) {
733 if (Message) {
734 Message->clear();
735 llvm::raw_string_ostream Out(*Message);
736 VersionTuple VTI(A->getIntroduced());
737 Out << "introduced in " << PrettyPlatformName << " " << VTI;
738 if (Triple.hasEnvironment())
739 Out << " " << EnvName;
740 Out << HintMessage;
741 }
742 }
743 // Non-matching environment or no environment on target.
744 else {
745 if (Message) {
746 Message->clear();
747 llvm::raw_string_ostream Out(*Message);
748 Out << "not available on " << PrettyPlatformName;
749 if (Triple.hasEnvironment())
750 Out << " " << EnvName;
751 Out << HintMessage;
752 }
753 }
754
755 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
756 }
757
758 // Make sure that this declaration hasn't been obsoleted.
759 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
760 if (Message) {
761 Message->clear();
762 llvm::raw_string_ostream Out(*Message);
763 VersionTuple VTO(A->getObsoleted());
764 Out << "obsoleted in " << PrettyPlatformName << ' '
765 << VTO << HintMessage;
766 }
767
768 return AR_Unavailable;
769 }
770
771 // Make sure that this declaration hasn't been deprecated.
772 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
773 if (Message) {
774 Message->clear();
775 llvm::raw_string_ostream Out(*Message);
776 VersionTuple VTD(A->getDeprecated());
777 Out << "first deprecated in " << PrettyPlatformName << ' '
778 << VTD << HintMessage;
779 }
780
781 return AR_Deprecated;
782 }
783
784 return AR_Available;
785}
786
788 VersionTuple EnclosingVersion,
789 StringRef *RealizedPlatform) const {
790 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
791 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
792 RealizedPlatform);
793
795 std::string ResultMessage;
796
797 for (const auto *A : attrs()) {
798 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
799 if (Result >= AR_Deprecated)
800 continue;
801
802 if (Message)
803 ResultMessage = std::string(Deprecated->getMessage());
804
806 continue;
807 }
808
809 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
810 if (Message)
811 *Message = std::string(Unavailable->getMessage());
812 return AR_Unavailable;
813 }
814
815 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
816 Availability = Availability->getEffectiveAttr();
818 Message, EnclosingVersion);
819
820 if (AR == AR_Unavailable) {
821 if (RealizedPlatform)
822 *RealizedPlatform = Availability->getPlatform()->getName();
823 return AR_Unavailable;
824 }
825
826 if (AR > Result) {
827 Result = AR;
828 if (Message)
829 ResultMessage.swap(*Message);
830 }
831 continue;
832 }
833 }
834
835 if (Message)
836 Message->swap(ResultMessage);
837 return Result;
838}
839
840VersionTuple Decl::getVersionIntroduced() const {
841 const ASTContext &Context = getASTContext();
842 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
843 for (const auto *A : attrs()) {
844 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
845 Availability = Availability->getEffectiveAttr();
846 if (getRealizedPlatform(Availability, Context) == TargetPlatform) {
847 if (!Availability->getIntroduced().empty())
848 return Availability->getIntroduced();
849 }
850 }
851 }
852 return {};
853}
854
855bool Decl::canBeWeakImported(bool &IsDefinition) const {
856 IsDefinition = false;
857
858 // Variables, if they aren't definitions.
859 if (const auto *Var = dyn_cast<VarDecl>(this)) {
860 if (Var->isThisDeclarationADefinition()) {
861 IsDefinition = true;
862 return false;
863 }
864 return true;
865 }
866 // Functions, if they aren't definitions.
867 if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
868 if (FD->hasBody()) {
869 IsDefinition = true;
870 return false;
871 }
872 return true;
873
874 }
875 // Objective-C classes, if this is the non-fragile runtime.
876 if (isa<ObjCInterfaceDecl>(this) &&
878 return true;
879 }
880 // Nothing else.
881 return false;
882}
883
885 const Decl *MostRecentDecl = getMostRecentDecl();
886 if (!MostRecentDecl->hasAttrs())
887 return false;
888
889 bool IsDefinition;
890 if (!canBeWeakImported(IsDefinition))
891 return false;
892
893 for (const auto *A : MostRecentDecl->attrs()) {
894 if (isa<WeakImportAttr>(A))
895 return true;
896
897 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
898 Availability = Availability->getEffectiveAttr();
899 if (CheckAvailability(getASTContext(), Availability, nullptr,
900 VersionTuple()) == AR_NotYetIntroduced)
901 return true;
902 }
903 }
904
905 return false;
906}
907
909 switch (DeclKind) {
910 case Function:
911 case CXXDeductionGuide:
912 case CXXMethod:
913 case CXXConstructor:
914 case ConstructorUsingShadow:
915 case CXXDestructor:
916 case CXXConversion:
917 case EnumConstant:
918 case Var:
919 case ImplicitParam:
920 case ParmVar:
921 case ObjCMethod:
922 case ObjCProperty:
923 case MSProperty:
924 case HLSLBuffer:
925 case HLSLRootSignature:
926 return IDNS_Ordinary;
927 case Label:
928 return IDNS_Label;
929
930 case Binding:
931 case NonTypeTemplateParm:
932 case VarTemplate:
933 case Concept:
934 // These (C++-only) declarations are found by redeclaration lookup for
935 // tag types, so we include them in the tag namespace.
936 return IDNS_Ordinary | IDNS_Tag;
937
938 case ObjCCompatibleAlias:
939 case ObjCInterface:
940 return IDNS_Ordinary | IDNS_Type;
941
942 case Typedef:
943 case TypeAlias:
944 case TemplateTypeParm:
945 case ObjCTypeParam:
946 return IDNS_Ordinary | IDNS_Type;
947
948 case UnresolvedUsingTypename:
950
951 case UsingShadow:
952 return 0; // we'll actually overwrite this later
953
954 case UnresolvedUsingValue:
955 return IDNS_Ordinary | IDNS_Using;
956
957 case Using:
958 case UsingPack:
959 case UsingEnum:
960 return IDNS_Using;
961
962 case ObjCProtocol:
963 return IDNS_ObjCProtocol;
964
965 case Field:
966 case IndirectField:
967 case ObjCAtDefsField:
968 case ObjCIvar:
969 return IDNS_Member;
970
971 case Record:
972 case CXXRecord:
973 case Enum:
974 return IDNS_Tag | IDNS_Type;
975
976 case Namespace:
977 case NamespaceAlias:
978 return IDNS_Namespace;
979
980 case FunctionTemplate:
981 return IDNS_Ordinary;
982
983 case ClassTemplate:
984 case TemplateTemplateParm:
987
988 case UnresolvedUsingIfExists:
989 return IDNS_Type | IDNS_Ordinary;
990
991 case OMPDeclareReduction:
992 return IDNS_OMPReduction;
993
994 case OMPDeclareMapper:
995 return IDNS_OMPMapper;
996
997 // Never have names.
998 case Friend:
999 case FriendTemplate:
1000 case AccessSpec:
1001 case LinkageSpec:
1002 case Export:
1003 case FileScopeAsm:
1004 case TopLevelStmt:
1005 case StaticAssert:
1006 case ObjCPropertyImpl:
1007 case PragmaComment:
1008 case PragmaDetectMismatch:
1009 case Block:
1010 case Captured:
1011 case OutlinedFunction:
1012 case TranslationUnit:
1013 case ExternCContext:
1014 case Decomposition:
1015 case MSGuid:
1016 case UnnamedGlobalConstant:
1017 case TemplateParamObject:
1018
1019 case UsingDirective:
1020 case BuiltinTemplate:
1021 case ClassTemplateSpecialization:
1022 case ClassTemplatePartialSpecialization:
1023 case VarTemplateSpecialization:
1024 case VarTemplatePartialSpecialization:
1025 case ObjCImplementation:
1026 case ObjCCategory:
1027 case ObjCCategoryImpl:
1028 case Import:
1029 case OMPThreadPrivate:
1030 case OMPGroupPrivate:
1031 case OMPAllocate:
1032 case OMPRequires:
1033 case OMPCapturedExpr:
1034 case Empty:
1035 case LifetimeExtendedTemporary:
1036 case RequiresExprBody:
1037 case ImplicitConceptSpecialization:
1038 case OpenACCDeclare:
1039 case OpenACCRoutine:
1041 case CXXExpansionStmt:
1042 // Never looked up by name.
1043 return 0;
1044 }
1045
1046 llvm_unreachable("Invalid DeclKind!");
1047}
1048
1049void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
1050 assert(!Attrs && "Decl already contains attrs.");
1051
1052 Attrs = Ctx.allocateAttrVec();
1053 *Attrs = attrs;
1054}
1055
1057 if (!Attrs)
1058 return;
1059
1060 // The vector itself belongs to the ASTContext's allocator and is destroyed
1061 // when the context dies; only the pointer is dropped here.
1062 Attrs->clear();
1063 Attrs = nullptr;
1064}
1065
1067 if (!hasAttrs()) {
1068 setAttrs(AttrVec(1, A));
1069 return;
1070 }
1071
1072 AttrVec &Attrs = getAttrs();
1073 if (!A->isInherited()) {
1074 Attrs.push_back(A);
1075 return;
1076 }
1077
1078 // Attribute inheritance is processed after attribute parsing. To keep the
1079 // order as in the source code, add inherited attributes before non-inherited
1080 // ones.
1081 auto I = Attrs.begin(), E = Attrs.end();
1082 for (; I != E; ++I) {
1083 if (!(*I)->isInherited())
1084 break;
1085 }
1086 Attrs.insert(I, A);
1087}
1088
1089const AttrVec &Decl::getAttrs() const {
1090 assert(Attrs && "No attrs to get!");
1091 return *Attrs;
1092}
1093
1095 Decl::Kind DK = D->getDeclKind();
1096 switch (DK) {
1097#define DECL(NAME, BASE)
1098#define DECL_CONTEXT(NAME) \
1099 case Decl::NAME: \
1100 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
1101#include "clang/AST/DeclNodes.inc"
1102 default:
1103 llvm_unreachable("a decl that inherits DeclContext isn't handled");
1104 }
1105}
1106
1108 Decl::Kind DK = D->getKind();
1109 switch(DK) {
1110#define DECL(NAME, BASE)
1111#define DECL_CONTEXT(NAME) \
1112 case Decl::NAME: \
1113 return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
1114#include "clang/AST/DeclNodes.inc"
1115 default:
1116 llvm_unreachable("a decl that inherits DeclContext isn't handled");
1117 }
1118}
1119
1121 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
1122 // FunctionDecl stores EndRangeLoc for this purpose.
1123 if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
1124 const FunctionDecl *Definition;
1125 if (FD->hasBody(Definition))
1126 return Definition->getSourceRange().getEnd();
1127 return {};
1128 }
1129
1130 if (Stmt *Body = getBody())
1131 return Body->getSourceRange().getEnd();
1132
1133 return {};
1134}
1135
1136bool Decl::AccessDeclContextCheck() const {
1137#ifndef NDEBUG
1138 // Suppress this check if any of the following hold:
1139 // 1. this is the translation unit (and thus has no parent)
1140 // 2. this is a template parameter (and thus doesn't belong to its context)
1141 // 3. this is a non-type template parameter
1142 // 4. the context is not a record
1143 // 5. it's invalid
1144 // 6. it's a C++0x static_assert.
1145 // 7. it's a block literal declaration
1146 // 8. it's a temporary with lifetime extended due to being default value.
1150 isa<StaticAssertDecl>(this) || isa<BlockDecl>(this) ||
1151 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
1152 // as DeclContext (?).
1153 isa<ParmVarDecl>(this) ||
1154 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
1155 // AS_none as access specifier.
1157 return true;
1158
1159 assert(Access != AS_none &&
1160 "Access specifier is AS_none inside a record decl");
1161#endif
1162 return true;
1163}
1164
1166 const DeclContext *DC = getLexicalDeclContext();
1167
1168 while (DC && !isa<ExportDecl>(DC))
1169 DC = DC->getLexicalParent();
1170
1171 return isa_and_nonnull<ExportDecl>(DC);
1172}
1173
1176 return false;
1177 auto *M = getOwningModule();
1178 return M && M->isNamedModule() &&
1180}
1181
1183 auto *M = getOwningModule();
1184
1185 if (!M)
1186 return false;
1187
1188 // FIXME or NOTE: maybe we need to be clear about the semantics
1189 // of clang header modules. e.g., if this lives in a clang header
1190 // module included by the current unit, should we return false
1191 // here?
1192 //
1193 // This is clear for header units as the specification says the
1194 // header units live in a synthesised translation unit. So we
1195 // can return false here.
1196 M = M->getTopLevelModule();
1197 if (!M->isNamedModule())
1198 return false;
1199
1200 return M != getASTContext().getCurrentNamedModule();
1201}
1202
1204 auto *M = getOwningModule();
1205
1206 if (!M || !M->isNamedModule())
1207 return false;
1208
1209 return M == getASTContext().getCurrentNamedModule();
1210}
1211
1214 if (!Source)
1215 return false;
1216
1218}
1219
1223
1227
1230}
1231
1234}
1235
1236static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
1237static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
1238
1239int64_t Decl::getID() const {
1240 return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
1241}
1242
1243const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
1244 QualType Ty;
1245 if (const auto *D = dyn_cast<ValueDecl>(this))
1246 Ty = D->getType();
1247 else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1248 Ty = D->getUnderlyingType();
1249 else
1250 return nullptr;
1251
1252 if (Ty.isNull()) {
1253 // BindingDecls do not have types during parsing, so return nullptr. This is
1254 // the only known case where `Ty` is null.
1255 assert(isa<BindingDecl>(this));
1256 return nullptr;
1257 }
1258
1259 if (Ty->isFunctionPointerType())
1260 Ty = Ty->castAs<PointerType>()->getPointeeType();
1261 else if (Ty->isMemberFunctionPointerType())
1263 else if (Ty->isFunctionReferenceType())
1264 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1265 else if (BlocksToo && Ty->isBlockPointerType())
1266 Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
1267
1268 return Ty->getAs<FunctionType>();
1269}
1270
1272 QualType Ty;
1273 if (const auto *D = dyn_cast<ValueDecl>(this))
1274 Ty = D->getType();
1275 else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1276 Ty = D->getUnderlyingType();
1277 else
1278 return false;
1279
1281}
1282
1287
1288/// Starting at a given context (a Decl or DeclContext), look for a
1289/// code context that is not a closure (a lambda, block, etc.).
1290template <class T> static Decl *getNonClosureContext(T *D) {
1291 if (getKind(D) == Decl::CXXMethod) {
1292 auto *MD = cast<CXXMethodDecl>(D);
1293 if (MD->getOverloadedOperator() == OO_Call &&
1294 MD->getParent()->isLambda())
1295 return getNonClosureContext(MD->getParent()->getParent());
1296 return MD;
1297 }
1298 if (auto *FD = dyn_cast<FunctionDecl>(D))
1299 return FD;
1300 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1301 return MD;
1302 if (auto *BD = dyn_cast<BlockDecl>(D))
1303 return getNonClosureContext(BD->getParent());
1304 if (auto *CD = dyn_cast<CapturedDecl>(D))
1305 return getNonClosureContext(CD->getParent());
1306 if (auto *OFD = dyn_cast<OutlinedFunctionDecl>(D))
1307 return getNonClosureContext(OFD->getParent());
1308 return nullptr;
1309}
1310
1312 return ::getNonClosureContext(this);
1313}
1314
1316 return ::getNonClosureContext(this);
1317}
1318
1319//===----------------------------------------------------------------------===//
1320// DeclContext Implementation
1321//===----------------------------------------------------------------------===//
1322
1324 DeclContextBits.DeclKind = K;
1327 setNeedToReconcileExternalVisibleStorage(false);
1328 setHasLazyLocalLexicalLookups(false);
1329 setHasLazyExternalLexicalLookups(false);
1330}
1331
1333 Decl::Kind DK = D->getKind();
1334 switch (DK) {
1335#define DECL(NAME, BASE)
1336#define DECL_CONTEXT(NAME) case Decl::NAME:
1337#include "clang/AST/DeclNodes.inc"
1338 return true;
1339 default:
1340 return false;
1341 }
1342}
1343
1344DeclContext::~DeclContext() = default;
1345
1346/// Find the parent context of this context that will be
1347/// used for unqualified name lookup.
1348///
1349/// Generally, the parent lookup context is the semantic context. However, for
1350/// a friend function the parent lookup context is the lexical context, which
1351/// is the class in which the friend is declared.
1353 // FIXME: Find a better way to identify friends.
1354 if (isa<FunctionDecl>(this))
1357 return getLexicalParent();
1358
1359 // A lookup within the call operator of a lambda never looks in the lambda
1360 // class; instead, skip to the context in which that closure type is
1361 // declared.
1362 if (isLambdaCallOperator(this))
1363 return getParent()->getParent();
1364
1365 return getParent();
1366}
1367
1369 const DeclContext *Ctx = this;
1370
1371 do {
1372 if (Ctx->isClosure())
1373 return cast<BlockDecl>(Ctx);
1374 Ctx = Ctx->getParent();
1375 } while (Ctx);
1376
1377 return nullptr;
1378}
1379
1381 return isNamespace() &&
1382 cast<NamespaceDecl>(this)->isInline();
1383}
1384
1386 if (!isNamespace())
1387 return false;
1388
1389 const auto *ND = cast<NamespaceDecl>(this);
1390 if (ND->isInline()) {
1391 return ND->getParent()->isStdNamespace();
1392 }
1393
1395 return false;
1396
1397 const IdentifierInfo *II = ND->getIdentifier();
1398 return II && II->isStr("std");
1399}
1400
1402 if (isFileContext())
1403 return false;
1404
1406 return true;
1407
1408 if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1409 if (Record->getDescribedClassTemplate())
1410 return true;
1411
1412 if (Record->isDependentLambda())
1413 return true;
1414 if (Record->isNeverDependentLambda())
1415 return false;
1416 }
1417
1418 if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1419 if (Function->getDescribedFunctionTemplate())
1420 return true;
1421
1422 // Friend function declarations are dependent if their *lexical*
1423 // context is dependent.
1424 if (cast<Decl>(this)->getFriendObjectKind())
1426 }
1427
1428 // FIXME: A variable template is a dependent context, but is not a
1429 // DeclContext. A context within it (such as a lambda-expression)
1430 // should be considered dependent.
1431
1432 return getParent() && getParent()->isDependentContext();
1433}
1434
1436 if (getDeclKind() == Decl::Enum)
1437 return !cast<EnumDecl>(this)->isScoped();
1438
1440}
1441
1442static bool isLinkageSpecContext(const DeclContext *DC,
1444 while (DC->getDeclKind() != Decl::TranslationUnit) {
1445 if (DC->getDeclKind() == Decl::LinkageSpec)
1446 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1447 DC = DC->getLexicalParent();
1448 }
1449 return false;
1450}
1451
1455
1457 const DeclContext *DC = this;
1458 while (DC->getDeclKind() != Decl::TranslationUnit) {
1459 if (DC->getDeclKind() == Decl::LinkageSpec &&
1461 return cast<LinkageSpecDecl>(DC);
1462 DC = DC->getLexicalParent();
1463 }
1464 return nullptr;
1465}
1466
1470
1471bool DeclContext::Encloses(const DeclContext *DC) const {
1472 if (getPrimaryContext() != this)
1473 return getPrimaryContext()->Encloses(DC);
1474
1475 for (; DC; DC = DC->getParent())
1477 DC->getPrimaryContext() == this)
1478 return true;
1479 return false;
1480}
1481
1483 if (getPrimaryContext() != this)
1485
1486 for (; DC; DC = DC->getLexicalParent())
1488 DC->getPrimaryContext() == this)
1489 return true;
1490 return false;
1491}
1492
1494 DeclContext *DC = this;
1495 while (DC->isTransparentContext()) {
1496 DC = DC->getParent();
1497 assert(DC && "All transparent contexts should have a parent!");
1498 }
1499 return DC;
1500}
1501
1503 switch (getDeclKind()) {
1504 case Decl::ExternCContext:
1505 case Decl::LinkageSpec:
1506 case Decl::Export:
1507 case Decl::TopLevelStmt:
1508 case Decl::Block:
1509 case Decl::Captured:
1510 case Decl::OutlinedFunction:
1511 case Decl::OMPDeclareReduction:
1512 case Decl::OMPDeclareMapper:
1513 case Decl::RequiresExprBody:
1514 case Decl::CXXExpansionStmt:
1515 // There is only one DeclContext for these entities.
1516 return this;
1517
1518 case Decl::HLSLBuffer:
1519 // Each buffer, even with the same name, is a distinct construct.
1520 // Multiple buffers with the same name are allowed for backward
1521 // compatibility.
1522 // As long as buffers have unique resource bindings the names don't matter.
1523 // The names get exposed via the CPU-side reflection API which
1524 // supports querying bindings, so we cannot remove them.
1525 return this;
1526
1527 case Decl::TranslationUnit:
1528 return static_cast<TranslationUnitDecl *>(this)->getFirstDecl();
1529 case Decl::Namespace:
1530 return static_cast<NamespaceDecl *>(this)->getFirstDecl();
1531
1532 case Decl::ObjCMethod:
1533 return this;
1534
1535 case Decl::ObjCInterface:
1536 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1537 if (auto *Def = OID->getDefinition())
1538 return Def;
1539 return this;
1540
1541 case Decl::ObjCProtocol:
1542 if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1543 if (auto *Def = OPD->getDefinition())
1544 return Def;
1545 return this;
1546
1547 case Decl::ObjCCategory:
1548 return this;
1549
1550 case Decl::ObjCImplementation:
1551 case Decl::ObjCCategoryImpl:
1552 return this;
1553
1554 // If this is a tag type that has a definition or is currently
1555 // being defined, that definition is our primary context.
1556 case Decl::ClassTemplatePartialSpecialization:
1557 case Decl::ClassTemplateSpecialization:
1558 case Decl::CXXRecord:
1559 return cast<CXXRecordDecl>(this)->getDefinitionOrSelf();
1560 case Decl::Record:
1561 case Decl::Enum:
1562 return cast<TagDecl>(this)->getDefinitionOrSelf();
1563
1564 default:
1565 assert(getDeclKind() >= Decl::firstFunction &&
1566 getDeclKind() <= Decl::lastFunction && "Unknown DeclContext kind");
1567 return this;
1568 }
1569}
1570
1571template <typename T>
1574 for (T *D = Self->getMostRecentDecl(); D; D = D->getPreviousDecl())
1575 Contexts.push_back(D);
1576
1577 std::reverse(Contexts.begin(), Contexts.end());
1578}
1579
1581 Contexts.clear();
1582
1583 Decl::Kind Kind = getDeclKind();
1584
1585 if (Kind == Decl::TranslationUnit)
1586 collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts);
1587 else if (Kind == Decl::Namespace)
1588 collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts);
1589 else
1590 Contexts.push_back(this);
1591}
1592
1593std::pair<Decl *, Decl *>
1595 bool FieldsAlreadyLoaded) {
1596 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1597 Decl *FirstNewDecl = nullptr;
1598 Decl *PrevDecl = nullptr;
1599 for (auto *D : Decls) {
1600 if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1601 continue;
1602
1603 if (PrevDecl)
1604 PrevDecl->NextInContextAndBits.setPointer(D);
1605 else
1606 FirstNewDecl = D;
1607
1608 PrevDecl = D;
1609 }
1610
1611 return std::make_pair(FirstNewDecl, PrevDecl);
1612}
1613
1614/// We have just acquired external visible storage, and we already have
1615/// built a lookup map. For every name in the map, pull in the new names from
1616/// the external storage.
1617void DeclContext::reconcileExternalVisibleStorage() const {
1618 assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1619 setNeedToReconcileExternalVisibleStorage(false);
1620
1621 for (auto &Lookup : *LookupPtr)
1622 Lookup.second.setHasExternalDecls();
1623}
1624
1625/// Load the declarations within this lexical storage from an
1626/// external source.
1627/// \return \c true if any declarations were added.
1628bool
1629DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1631 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1632
1633 // Notify that we have a DeclContext that is initializing.
1634 ExternalASTSource::Deserializing ADeclContext(Source);
1635
1636 // Load the external declarations, if any.
1639 Source->FindExternalLexicalDecls(this, Decls);
1640
1641 if (Decls.empty())
1642 return false;
1643
1644 // We may have already loaded just the fields of this record, in which case
1645 // we need to ignore them.
1646 bool FieldsAlreadyLoaded = false;
1647 if (const auto *RD = dyn_cast<RecordDecl>(this))
1648 FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1649
1650 // Splice the newly-read declarations into the beginning of the list
1651 // of declarations.
1652 Decl *ExternalFirst, *ExternalLast;
1653 std::tie(ExternalFirst, ExternalLast) =
1654 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1655 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1656 FirstDecl = ExternalFirst;
1657 if (!LastDecl)
1658 LastDecl = ExternalLast;
1659 return true;
1660}
1661
1664 DeclarationName Name) {
1665 ASTContext &Context = DC->getParentASTContext();
1666 StoredDeclsMap *Map;
1667 if (!(Map = DC->LookupPtr))
1668 Map = DC->CreateStoredDeclsMap(Context);
1669 if (DC->hasNeedToReconcileExternalVisibleStorage())
1670 DC->reconcileExternalVisibleStorage();
1671
1672 (*Map)[Name].removeExternalDecls();
1673
1675}
1676
1679 DeclarationName Name,
1680 ArrayRef<NamedDecl*> Decls) {
1681 ASTContext &Context = DC->getParentASTContext();
1682 StoredDeclsMap *Map;
1683 if (!(Map = DC->LookupPtr))
1684 Map = DC->CreateStoredDeclsMap(Context);
1685 if (DC->hasNeedToReconcileExternalVisibleStorage())
1686 DC->reconcileExternalVisibleStorage();
1687
1688 StoredDeclsList &List = (*Map)[Name];
1689 List.replaceExternalDecls(Decls);
1690 return List.getLookupResult();
1691}
1692
1695 LoadLexicalDeclsFromExternalStorage();
1696 return decl_iterator(FirstDecl);
1697}
1698
1701 LoadLexicalDeclsFromExternalStorage();
1702
1703 return !FirstDecl;
1704}
1705
1707 return (D->getLexicalDeclContext() == this &&
1708 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1709}
1710
1713 LoadLexicalDeclsFromExternalStorage();
1714 return containsDecl(D);
1715}
1716
1717/// shouldBeHidden - Determine whether a declaration which was declared
1718/// within its semantic context should be invisible to qualified name lookup.
1719static bool shouldBeHidden(NamedDecl *D) {
1720 // Skip unnamed declarations.
1721 if (!D->getDeclName())
1722 return true;
1723
1724 // Skip entities that can't be found by name lookup into a particular
1725 // context.
1726 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1728 return true;
1729
1730 // Skip friends and local extern declarations unless they're the first
1731 // declaration of the entity.
1732 if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1733 D != D->getCanonicalDecl())
1734 return true;
1735
1736 // Skip template specializations.
1737 // FIXME: This feels like a hack. Should DeclarationName support
1738 // template-ids, or is there a better way to keep specializations
1739 // from being visible?
1741 return true;
1742 if (auto *FD = dyn_cast<FunctionDecl>(D))
1743 if (FD->isFunctionTemplateSpecialization())
1744 return true;
1745
1746 // Hide destructors that are invalid. There should always be one destructor,
1747 // but if it is an invalid decl, another one is created. We need to hide the
1748 // invalid one from places that expect exactly one destructor, like the
1749 // serialization code.
1751 return true;
1752
1753 return false;
1754}
1755
1757 assert(D->getLexicalDeclContext() == this &&
1758 "decl being removed from non-lexical context");
1759 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1760 "decl is not in decls list");
1761
1762 // Remove D from the decl chain. This is O(n) but hopefully rare.
1763 if (D == FirstDecl) {
1764 if (D == LastDecl)
1765 FirstDecl = LastDecl = nullptr;
1766 else
1767 FirstDecl = D->NextInContextAndBits.getPointer();
1768 } else {
1769 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1770 assert(I && "decl not found in linked list");
1771 if (I->NextInContextAndBits.getPointer() == D) {
1772 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1773 if (D == LastDecl) LastDecl = I;
1774 break;
1775 }
1776 }
1777 }
1778
1779 // Mark that D is no longer in the decl chain.
1780 D->NextInContextAndBits.setPointer(nullptr);
1781
1782 // Remove D from the lookup table if necessary.
1783 if (isa<NamedDecl>(D)) {
1784 auto *ND = cast<NamedDecl>(D);
1785
1786 // Do not try to remove the declaration if that is invisible to qualified
1787 // lookup. E.g. template specializations are skipped.
1788 if (shouldBeHidden(ND))
1789 return;
1790
1791 // Remove only decls that have a name
1792 if (!ND->getDeclName())
1793 return;
1794
1795 auto *DC = D->getDeclContext();
1796 do {
1797 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1798 if (Map) {
1799 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1800 // In C, the lookup table of the translation unit can miss a declaration
1801 // that was declared outside of it, like a structure declared in
1802 // another one (see makeDeclVisibleInContextWithFlags).
1803 assert((Pos != Map->end() ||
1804 (DC->isTranslationUnit() &&
1805 !getParentASTContext().getLangOpts().CPlusPlus)) &&
1806 "no lookup entry for decl");
1807 if (Pos != Map->end()) {
1808 StoredDeclsList &List = Pos->second;
1809 List.remove(ND);
1810 // Clean up the entry if there are no more decls.
1811 if (List.isNull())
1812 Map->erase(Pos);
1813 }
1814 }
1815 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1816 }
1817}
1818
1820 assert(D->getLexicalDeclContext() == this &&
1821 "Decl inserted into wrong lexical context");
1822 assert(!D->getNextDeclInContext() && D != LastDecl &&
1823 "Decl already inserted into a DeclContext");
1824
1825 if (FirstDecl) {
1826 LastDecl->NextInContextAndBits.setPointer(D);
1827 LastDecl = D;
1828 } else {
1829 FirstDecl = LastDecl = D;
1830 }
1831
1832 // Notify a C++ record declaration that we've added a member, so it can
1833 // update its class-specific state.
1834 if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1835 Record->addedMember(D);
1836
1837 // If this is a newly-created (not de-serialized) import declaration, wire
1838 // it in to the list of local import declarations.
1839 if (!D->isFromASTFile()) {
1840 if (auto *Import = dyn_cast<ImportDecl>(D))
1842 }
1843}
1844
1846 addHiddenDecl(D);
1847
1848 if (auto *ND = dyn_cast<NamedDecl>(D))
1849 ND->getDeclContext()->getPrimaryContext()->
1850 makeDeclVisibleInContextWithFlags(ND, false, true);
1851}
1852
1854 addHiddenDecl(D);
1855
1856 if (auto *ND = dyn_cast<NamedDecl>(D))
1857 ND->getDeclContext()->getPrimaryContext()->
1858 makeDeclVisibleInContextWithFlags(ND, true, true);
1859}
1860
1861/// buildLookup - Build the lookup data structure with all of the
1862/// declarations in this DeclContext (and any other contexts linked
1863/// to it or transparent contexts nested within it) and return it.
1864///
1865/// Note that the produced map may miss out declarations from an
1866/// external source. If it does, those entries will be marked with
1867/// the 'hasExternalDecls' flag.
1869 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1870
1871 if (!hasLazyLocalLexicalLookups() &&
1872 !hasLazyExternalLexicalLookups())
1873 return LookupPtr;
1874
1876 collectAllContexts(Contexts);
1877
1878 if (hasLazyExternalLexicalLookups()) {
1879 setHasLazyExternalLexicalLookups(false);
1880 for (auto *DC : Contexts) {
1881 if (DC->hasExternalLexicalStorage()) {
1882 bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1883 setHasLazyLocalLexicalLookups(
1884 hasLazyLocalLexicalLookups() | LoadedDecls );
1885 }
1886 }
1887
1888 if (!hasLazyLocalLexicalLookups())
1889 return LookupPtr;
1890 }
1891
1892 for (auto *DC : Contexts)
1893 buildLookupImpl(DC, hasExternalVisibleStorage());
1894
1895 // We no longer have any lazy decls.
1896 setHasLazyLocalLexicalLookups(false);
1897 return LookupPtr;
1898}
1899
1900/// buildLookupImpl - Build part of the lookup data structure for the
1901/// declarations contained within DCtx, which will either be this
1902/// DeclContext, a DeclContext linked to it, or a transparent context
1903/// nested within it.
1904void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1905 for (auto *D : DCtx->noload_decls()) {
1906 // Insert this declaration into the lookup structure, but only if
1907 // it's semantically within its decl context. Any other decls which
1908 // should be found in this context are added eagerly.
1909 //
1910 // If it's from an AST file, don't add it now. It'll get handled by
1911 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1912 // in C++, we do not track external visible decls for the TU, so in
1913 // that case we need to collect them all here.
1914 if (auto *ND = dyn_cast<NamedDecl>(D))
1915 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1916 (!ND->isFromASTFile() ||
1917 (isTranslationUnit() &&
1918 !getParentASTContext().getLangOpts().CPlusPlus)))
1919 makeDeclVisibleInContextImpl(ND, Internal);
1920
1921 // If this declaration is itself a transparent declaration context
1922 // or inline namespace, add the members of this declaration of that
1923 // context (recursively).
1924 if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1925 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1926 buildLookupImpl(InnerCtx, Internal);
1927 }
1928}
1929
1932 // For transparent DeclContext, we should lookup in their enclosing context.
1933 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1934 return getParent()->lookup(Name);
1935
1936 return getPrimaryContext()->lookupImpl(Name, this);
1937}
1938
1940DeclContext::lookupImpl(DeclarationName Name,
1941 const DeclContext *OriginalLookupDC) const {
1942 assert(this == getPrimaryContext() &&
1943 "lookupImpl should only be called with primary DC!");
1944 assert(getDeclKind() != Decl::LinkageSpec && getDeclKind() != Decl::Export &&
1945 "We shouldn't lookup in transparent DC.");
1946
1947 // If we have an external source, ensure that any later redeclarations of this
1948 // context have been loaded, since they may add names to the result of this
1949 // lookup (or add external visible storage).
1951 if (Source)
1952 (void)cast<Decl>(this)->getMostRecentDecl();
1953
1955 assert(Source && "external visible storage but no external source?");
1956
1957 if (hasNeedToReconcileExternalVisibleStorage())
1958 reconcileExternalVisibleStorage();
1959
1961
1962 if (hasLazyLocalLexicalLookups() ||
1963 hasLazyExternalLexicalLookups())
1964 // FIXME: Make buildLookup const?
1965 Map = const_cast<DeclContext*>(this)->buildLookup();
1966
1967 if (!Map)
1968 Map = CreateStoredDeclsMap(getParentASTContext());
1969
1970 // If we have a lookup result with no external decls, we are done.
1971 std::pair<StoredDeclsMap::iterator, bool> R = Map->try_emplace(Name);
1972 if (!R.second && !R.first->second.hasExternalDecls())
1973 return R.first->second.getLookupResult();
1974
1975 if (Source->FindExternalVisibleDeclsByName(this, Name, OriginalLookupDC) ||
1976 !R.second) {
1977 if (StoredDeclsMap *Map = LookupPtr) {
1978 StoredDeclsMap::iterator I = Map->find(Name);
1979 if (I != Map->end())
1980 return I->second.getLookupResult();
1981 }
1982 }
1983
1984 return {};
1985 }
1986
1987 StoredDeclsMap *Map = LookupPtr;
1988 if (hasLazyLocalLexicalLookups() ||
1989 hasLazyExternalLexicalLookups())
1990 Map = const_cast<DeclContext*>(this)->buildLookup();
1991
1992 if (!Map)
1993 return {};
1994
1995 StoredDeclsMap::iterator I = Map->find(Name);
1996 if (I == Map->end())
1997 return {};
1998
1999 return I->second.getLookupResult();
2000}
2001
2004 // For transparent DeclContext, we should lookup in their enclosing context.
2005 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
2006 return getParent()->noload_lookup(Name);
2007
2008 DeclContext *PrimaryContext = getPrimaryContext();
2009 if (PrimaryContext != this)
2010 return PrimaryContext->noload_lookup(Name);
2011
2012 loadLazyLocalLexicalLookups();
2014 if (!Map)
2015 return {};
2016
2017 StoredDeclsMap::iterator I = Map->find(Name);
2018 return I != Map->end() ? I->second.getLookupResult()
2019 : lookup_result();
2020}
2021
2022// If we have any lazy lexical declarations not in our lookup map, add them
2023// now. Don't import any external declarations, not even if we know we have
2024// some missing from the external visible lookups.
2025void DeclContext::loadLazyLocalLexicalLookups() {
2026 if (hasLazyLocalLexicalLookups()) {
2028 collectAllContexts(Contexts);
2029 for (auto *Context : Contexts)
2030 buildLookupImpl(Context, hasExternalVisibleStorage());
2031 setHasLazyLocalLexicalLookups(false);
2032 }
2033}
2034
2037 Results.clear();
2038
2039 // If there's no external storage, just perform a normal lookup and copy
2040 // the results.
2042 lookup_result LookupResults = lookup(Name);
2043 llvm::append_range(Results, LookupResults);
2044 if (!Results.empty())
2045 return;
2046 }
2047
2048 // If we have a lookup table, check there first. Maybe we'll get lucky.
2049 // FIXME: Should we be checking these flags on the primary context?
2050 if (Name && !hasLazyLocalLexicalLookups() &&
2051 !hasLazyExternalLexicalLookups()) {
2052 if (StoredDeclsMap *Map = LookupPtr) {
2053 StoredDeclsMap::iterator Pos = Map->find(Name);
2054 if (Pos != Map->end()) {
2055 Results.insert(Results.end(),
2056 Pos->second.getLookupResult().begin(),
2057 Pos->second.getLookupResult().end());
2058 return;
2059 }
2060 }
2061 }
2062
2063 // Slow case: grovel through the declarations in our chain looking for
2064 // matches.
2065 // FIXME: If we have lazy external declarations, this will not find them!
2066 // FIXME: Should we CollectAllContexts and walk them all here?
2067 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
2068 if (auto *ND = dyn_cast<NamedDecl>(D))
2069 if (ND->getDeclName() == Name)
2070 Results.push_back(ND);
2071 }
2072}
2073
2075 DeclContext *Ctx = this;
2076
2077 // In C, a record type is the redeclaration context for its fields only. If
2078 // we arrive at a record context after skipping anything else, we should skip
2079 // the record as well. Currently, this means skipping enumerations because
2080 // they're the only transparent context that can exist within a struct or
2081 // union.
2082 bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
2083 !getParentASTContext().getLangOpts().CPlusPlus;
2084
2085 // Skip through contexts to get to the redeclaration context. Transparent
2086 // contexts are always skipped.
2087 while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
2088 Ctx = Ctx->getParent();
2089 return Ctx;
2090}
2091
2093 DeclContext *Ctx = this;
2094 // Skip through non-namespace, non-translation-unit contexts.
2095 while (!Ctx->isFileContext())
2096 Ctx = Ctx->getParent();
2097 return Ctx->getPrimaryContext();
2098}
2099
2101 // Loop until we find a non-record context.
2102 RecordDecl *OutermostRD = nullptr;
2103 DeclContext *DC = this;
2104 while (DC->isRecord()) {
2105 OutermostRD = cast<RecordDecl>(DC);
2106 DC = DC->getLexicalParent();
2107 }
2108 return OutermostRD;
2109}
2110
2112 DeclContext *DC = this;
2113 while (isa<CXXExpansionStmtDecl>(DC))
2114 DC = DC->getParent();
2115 return DC;
2116}
2117
2121
2125
2127 // For non-file contexts, this is equivalent to Equals.
2128 if (!isFileContext())
2129 return O->Equals(this);
2130
2131 do {
2132 if (O->Equals(this))
2133 return true;
2134
2135 const auto *NS = dyn_cast<NamespaceDecl>(O);
2136 if (!NS || !NS->isInline())
2137 break;
2138 O = NS->getParent();
2139 } while (O);
2140
2141 return false;
2142}
2143
2145 DeclContext *PrimaryDC = this->getPrimaryContext();
2147 // If the decl is being added outside of its semantic decl context, we
2148 // need to ensure that we eagerly build the lookup information for it.
2149 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
2150}
2151
2152void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2153 bool Recoverable) {
2154 assert(this == getPrimaryContext() && "expected a primary DC");
2155
2156 if (!isLookupContext()) {
2159 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
2160 return;
2161 }
2162
2163 // Skip declarations which should be invisible to name lookup.
2164 if (shouldBeHidden(D))
2165 return;
2166
2167 // If we already have a lookup data structure, perform the insertion into
2168 // it. If we might have externally-stored decls with this name, look them
2169 // up and perform the insertion. If this decl was declared outside its
2170 // semantic context, buildLookup won't add it, so add it now.
2171 //
2172 // FIXME: As a performance hack, don't add such decls into the translation
2173 // unit unless we're in C++, since qualified lookup into the TU is never
2174 // performed.
2176 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
2177 (getParentASTContext().getLangOpts().CPlusPlus ||
2178 !isTranslationUnit()))) {
2179 // If we have lazily omitted any decls, they might have the same name as
2180 // the decl which we are adding, so build a full lookup table before adding
2181 // this decl.
2182 buildLookup();
2183 makeDeclVisibleInContextImpl(D, Internal);
2184 } else {
2185 setHasLazyLocalLexicalLookups(true);
2186 }
2187
2188 // If we are a transparent context or inline namespace, insert into our
2189 // parent context, too. This operation is recursive.
2192 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
2193
2194 auto *DCAsDecl = cast<Decl>(this);
2195 // Notify that a decl was made visible unless we are a Tag being defined.
2196 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
2197 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
2198 L->AddedVisibleDecl(this, D);
2199}
2200
2201void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
2202 // Find or create the stored declaration map.
2203 StoredDeclsMap *Map = LookupPtr;
2204 if (!Map) {
2205 ASTContext *C = &getParentASTContext();
2206 Map = CreateStoredDeclsMap(*C);
2207 }
2208
2209 // If there is an external AST source, load any declarations it knows about
2210 // with this declaration's name.
2211 // If the lookup table contains an entry about this name it means that we
2212 // have already checked the external source.
2213 if (!Internal)
2214 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
2215 if (hasExternalVisibleStorage() && !Map->contains(D->getDeclName()))
2217 D->getDeclContext());
2218
2219 // Insert this declaration into the map.
2220 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
2221
2222 if (Internal) {
2223 // If this is being added as part of loading an external declaration,
2224 // this may not be the only external declaration with this name.
2225 // In this case, we never try to replace an existing declaration; we'll
2226 // handle that when we finalize the list of declarations for this name.
2227 DeclNameEntries.setHasExternalDecls();
2228 DeclNameEntries.prependDeclNoReplace(D);
2229 return;
2230 }
2231
2232 DeclNameEntries.addOrReplaceDecl(D);
2233}
2234
2238
2239/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
2240/// this context.
2242 // FIXME: Use something more efficient than normal lookup for using
2243 // directives. In C++, using directives are looked up more than anything else.
2244 lookup_result Result = lookup(UsingDirectiveDecl::getName());
2245 return udir_range(Result.begin(), Result.end());
2246}
2247
2248//===----------------------------------------------------------------------===//
2249// Creation and Destruction of StoredDeclsMaps. //
2250//===----------------------------------------------------------------------===//
2251
2252StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
2253 assert(!LookupPtr && "context already has a decls map");
2254 assert(getPrimaryContext() == this &&
2255 "creating decls map on non-primary context");
2256
2257 StoredDeclsMap *M;
2259 if (Dependent)
2260 M = new DependentStoredDeclsMap();
2261 else
2262 M = new StoredDeclsMap();
2263 M->Previous = C.LastSDM;
2264 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
2265 LookupPtr = M;
2266 return M;
2267}
2268
2269void ASTContext::ReleaseDeclContextMaps() {
2270 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
2271 // pointer because the subclass doesn't add anything that needs to
2272 // be deleted.
2273 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
2274 LastSDM.setPointer(nullptr);
2275}
2276
2278 while (Map) {
2279 // Advance the iteration before we invalidate memory.
2280 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
2281
2282 if (Dependent)
2283 delete static_cast<DependentStoredDeclsMap*>(Map);
2284 else
2285 delete Map;
2286
2287 Map = Next.getPointer();
2288 Dependent = Next.getInt();
2289 }
2290}
2291
2293 DeclContext *Parent,
2294 const PartialDiagnostic &PDiag) {
2295 assert(Parent->isDependentContext()
2296 && "cannot iterate dependent diagnostics of non-dependent context");
2297 Parent = Parent->getPrimaryContext();
2298 if (!Parent->LookupPtr)
2299 Parent->CreateStoredDeclsMap(C);
2300
2301 auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
2302
2303 // Allocate the copy of the PartialDiagnostic via the ASTContext's
2304 // BumpPtrAllocator, rather than the ASTContext itself.
2305 DiagnosticStorage *DiagStorage = nullptr;
2306 if (PDiag.hasStorage())
2307 DiagStorage = new (C) DiagnosticStorage;
2308
2309 auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
2310
2311 // TODO: Maybe we shouldn't reverse the order during insertion.
2312 DD->NextDiagnostic = Map->FirstDiagnostic;
2313 Map->FirstDiagnostic = DD;
2314
2315 return DD;
2316}
2317
2319 return ID & llvm::maskTrailingOnes<DeclID>(32);
2320}
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:504
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...
static void collectAllContextsImpl(T *Self, SmallVectorImpl< DeclContext * > &Contexts)
static bool isLinkageSpecContext(const DeclContext *DC, LinkageSpecLanguageIDs ID)
static Decl::Kind getKind(const Decl *D)
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...
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:682
static StringRef getRealizedPlatform(const AvailabilityAttr *A, const ASTContext &Context)
Definition DeclBase.cpp:660
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenACC nodes for declarative directives.
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::MachO::Record Record
Definition MachO.h:31
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.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
const LangOptions & getLangOpts() const
llvm::BumpPtrAllocator & getAllocator() const
Definition ASTContext.h:925
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
AttrVec * allocateAttrVec()
Allocate an empty attribute vector with the lifetime of this context.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
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:47
bool isInherited() const
Definition Attr.h:102
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4856
Pointer to a block type.
Definition TypeBase.h:3653
decl_iterator - Iterates through the declarations stored within this context.
Definition DeclBase.h:2364
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2263
bool isFileContext() const
Definition DeclBase.h:2201
void setHasExternalVisibleStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations visible in this context.
Definition DeclBase.h:2730
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2611
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl * > Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
ASTContext & getParentASTContext() const
Definition DeclBase.h:2139
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
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...
bool isClosure() const
Definition DeclBase.h:2143
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2126
bool isNamespace() const
Definition DeclBase.h:2223
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isLookupContext() const
Test whether the context supports looking up names.
Definition DeclBase.h:2196
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition DeclBase.h:2724
const char * getDeclKindName() const
Definition DeclBase.cpp:210
bool isTranslationUnit() const
Definition DeclBase.h:2206
bool isRecord() const
Definition DeclBase.h:2210
void collectAllContexts(SmallVectorImpl< DeclContext * > &Contexts)
Collects all of the declaration contexts that are semantically connected to this declaration context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
llvm::iterator_range< udir_iterator > udir_range
Definition DeclBase.h:2678
Decl * FirstDecl
FirstDecl - The first declaration stored within this declaration context.
Definition DeclBase.h:2076
DeclContext(Decl::Kind K)
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
bool containsDeclAndLoad(Decl *D) const
Checks whether a declaration is in this context.
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
bool hasValidDeclKind() const
Definition DeclBase.cpp:201
bool isStdNamespace() const
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don't attempt to retr...
static bool classof(const Decl *D)
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2712
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
friend class ExternalASTSource
For reconcileExternalVisibleStorage, CreateStoredDeclsMap, hasNeedToReconcileExternalVisibleStorage.
Definition DeclBase.h:1474
Decl * LastDecl
LastDecl - The last declaration stored within this declaration context.
Definition DeclBase.h:2082
friend class Decl
All declarations that can appear in a module declaration.
Definition DeclBase.h:2086
FunctionDecl * getEnclosingFunction()
Cast this to a FunctionDecl if it is one, ignoring any intervening expansion statements.
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition DeclBase.h:2415
FunctionDecl * castEnclosingFunction()
friend class DependentDiagnostic
For CreateStoredDeclsMap.
Definition DeclBase.h:1476
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
bool decls_empty() const
bool isInlineNamespace() const
DeclContextBitfields DeclContextBits
Definition DeclBase.h:2035
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2165
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition DeclBase.h:2718
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
StoredDeclsMap * LookupPtr
Pointer to the data structure used to lookup declarations within this context (or a DependentStoredDe...
Definition DeclBase.h:2023
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
ASTContext * CachedASTContext
Caches DeclContext's ASTContext. Used by Decl::getASTContext().
Definition DeclBase.h:2085
void localUncachedLookup(DeclarationName Name, SmallVectorImpl< NamedDecl * > &Results)
A simplistic name lookup mechanism that performs name lookup into this declaration context without co...
Decl::Kind getDeclKind() const
Definition DeclBase.h:2103
DeclContext * getNonTransparentContext()
decl_iterator decls_begin() const
bool LexicallyEncloses(const DeclContext *DC) const
Determine whether this declaration context lexically encloses the declaration context DC.
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
unsigned getLocalDeclIndex() const
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl()=delete
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1094
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:344
bool isInStdNamespace() const
Definition DeclBase.cpp:453
bool isInCurrentModuleUnit() const
Whether this declaration comes from the same module unit being compiled.
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
bool isTemplateDecl() const
returns true if this declaration is a template
Definition DeclBase.cpp:281
static void add(Kind k)
Definition DeclBase.cpp:248
Module * getTopLevelOwningNamedModule() const
Get the top level owning named module that owns this declaration if any.
Definition DeclBase.cpp:152
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1244
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:582
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition DeclBase.cpp:463
bool hasAttrs() const
Definition DeclBase.h:527
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void setOwningModuleID(unsigned ID)
Set the owning module ID.
Definition DeclBase.cpp:126
void addAttr(Attr *A)
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:529
bool hasLocalOwningModuleStorage() const
Definition DeclBase.cpp:165
bool isFunctionPointerType() const
bool isInNamedModule() const
Whether this declaration comes from a named module.
virtual ~Decl()
ExternalSourceSymbolAttr * getExternalSourceSymbolAttr() const
Looks on this and related declarations for an applicable external source symbol attribute.
Definition DeclBase.cpp:624
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition DeclBase.cpp:884
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition DeclBase.h:894
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
ASTMutationListener * getASTMutationListener() const
Definition DeclBase.cpp:568
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:572
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:787
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
Kind
Lists the kind of concrete classes of Decl.
Definition DeclBase.h:89
static unsigned getIdentifierNamespaceForKind(Kind DK)
Definition DeclBase.cpp:908
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:1105
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:602
bool isFileContextDecl() const
Definition DeclBase.cpp:458
static Decl * castFromDeclContext(const DeclContext *)
Decl * getNextDeclInContext()
Definition DeclBase.h:454
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
int64_t getID() const
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:612
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
llvm::PointerIntPair< Decl *, 3, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition DeclBase.h:257
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition DeclBase.cpp:320
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
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:855
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
const TemplateParameterList * getDescribedTemplateParams() const
If this is a declaration that describes some template or partial specialization, this returns the cor...
Definition DeclBase.cpp:298
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:806
bool isInLocalScopeForInstantiation() const
Determine whether a substitution into this declaration would occur as part of a substitution into a d...
Definition DeclBase.cpp:426
const Attr * getDefiningAttr() const
Return this declaration's defining attribute if it has one.
Definition DeclBase.cpp:650
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2809
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
bool isInvalidDecl() const
Definition DeclBase.h:597
unsigned getIdentifierNamespace() const
Definition DeclBase.h:907
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity,...
Definition DeclBase.cpp:645
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1187
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
const char * getDeclKindName() const
Definition DeclBase.cpp:169
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
@ IDNS_Type
Types, declared with 'struct foo', typedefs, etc.
Definition DeclBase.h:130
@ IDNS_OMPReduction
This declaration is an OpenMP user defined reduction construction.
Definition DeclBase.h:178
@ IDNS_Label
Labels, declared with 'x:' and referenced with 'goto x'.
Definition DeclBase.h:117
@ IDNS_Member
Members, declared with object declarations within tag definitions.
Definition DeclBase.h:136
@ IDNS_OMPMapper
This declaration is an OpenMP user defined mapper.
Definition DeclBase.h:181
@ IDNS_ObjCProtocol
Objective C @protocol.
Definition DeclBase.h:147
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
Definition DeclBase.h:140
@ IDNS_Using
This declaration is a using declaration.
Definition DeclBase.h:163
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition DeclBase.h:125
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
void setLocalOwningModule(Module *M)
Definition DeclBase.h:842
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1067
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition DeclBase.h:617
unsigned Access
Access - Used by C++ decls for the access specifier.
Definition DeclBase.h:339
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:587
DeclContext * getDeclContext()
Definition DeclBase.h:457
attr_range attrs() const
Definition DeclBase.h:544
bool isInAnonymousNamespace() const
Definition DeclBase.cpp:443
static void EnableStatistics()
Definition DeclBase.cpp:220
TranslationUnitDecl * getTranslationUnitDecl()
Definition DeclBase.cpp:535
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition DeclBase.cpp:840
bool hasOwningModule() const
Is this declaration owned by some module?
Definition DeclBase.h:850
bool isFromHeaderUnit() const
Whether this declaration comes from a header unit.
static void PrintStats()
Definition DeclBase.cpp:224
AttrVec & getAttrs()
Definition DeclBase.h:533
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
friend class DeclContext
Definition DeclBase.h:260
AttrVec * Attrs
The attributes attached to this declaration, or null if it has none.
Definition DeclBase.h:358
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
@ VisiblePromoted
This declaration has an owning module, and is not visible to the current TU but we promoted it to be ...
Definition DeclBase.h:237
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
Definition DeclBase.h:229
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
Definition DeclBase.h:242
Kind getKind() const
Definition DeclBase.h:451
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:899
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition DeclBase.cpp:564
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition DeclBase.cpp:110
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition DeclBase.cpp:118
bool shouldEmitInExternalSource() const
Whether the definition of the declaration should be emitted in external sources.
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)
This represents one expression.
Definition Expr.h:114
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl * > Decls)
static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name)
virtual Module * getModule(unsigned ID)
Retrieve the module that corresponds to the given module ID.
virtual bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name, const DeclContext *OriginalDC)
Find all declarations with the given name in the given context, and add them to the context by callin...
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a function declaration or definition.
Definition Decl.h:2082
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
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.
StringRef getName() const
Return the actual identifier string.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
Represents a linkage specification.
Definition DeclCXX.h:3062
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Describes a module or submodule.
Definition Module.h:340
bool isExplicitGlobalModule() const
Definition Module.h:444
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:441
bool isHeaderUnit() const
Is this module a header unit.
Definition Module.h:890
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:426
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
This represents a decl that may have a name.
Definition Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represent a C++ namespace.
Definition Decl.h:594
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool hasWeakClassImport() const
Does this runtime support weakly importing classes?
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
void print(raw_ostream &OS) const override
Definition DeclBase.cpp:358
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getCanonicalType() const
Definition TypeBase.h:8630
Represents a struct/union/class.
Definition Decl.h:4506
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4706
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
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:85
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.
void replaceExternalDecls(ArrayRef< NamedDecl * > Decls)
DeclContext::lookup_result getLookupResult() const
Return the list of all the decls.
static void DestroyAll(StoredDeclsMap *Map, bool Dependent)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Stores a list of template parameters for a TemplateDecl and its derived classes.
The top declaration context.
Definition Decl.h:107
ASTContext & getASTContext() const
Definition Decl.h:143
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2787
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isFunctionReferenceType() const
Definition TypeBase.h:8889
bool isFunctionPointerType() const
Definition TypeBase.h:8882
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8900
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Represents C++ using-directive.
Definition DeclCXX.h:3143
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
LinkageSpecLanguageIDs
Represents the language in a linkage specification.
Definition DeclCXX.h:3054
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ AS_public
Definition Specifiers.h:128
@ AS_none
Definition Specifiers.h:131
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
@ ExplicitInstantiation
We are parsing an explicit instantiation.
Definition Parser.h:85
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:581
@ Concept
The name was classified as a concept name.
Definition Sema.h:585
@ VarTemplate
The name was classified as a variable template name.
Definition Sema.h:579
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition DeclBase.h:72
@ AR_NotYetIntroduced
Definition DeclBase.h:74
@ AR_Available
Definition DeclBase.h:73
@ AR_Deprecated
Definition DeclBase.h:75
@ AR_Unavailable
Definition DeclBase.h:76
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
UsingDirectiveDecl * operator*() const