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