1 //===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
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 defines the Decl and DeclContext interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_CLANG_AST_DECLBASE_H
14 #define LLVM_CLANG_AST_DECLBASE_H
15
16 #include "clang/AST/ASTDumperUtils.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/Basic/IdentifierTable.h"
20 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/PointerUnion.h"
26 #include "llvm/ADT/iterator.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/VersionTuple.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstddef>
35 #include <iterator>
36 #include <string>
37 #include <type_traits>
38 #include <utility>
39
40 namespace clang {
41
42 class ASTContext;
43 class ASTMutationListener;
44 class Attr;
45 class BlockDecl;
46 class DeclContext;
47 class ExternalSourceSymbolAttr;
48 class FunctionDecl;
49 class FunctionType;
50 class IdentifierInfo;
51 enum Linkage : unsigned char;
52 class LinkageSpecDecl;
53 class Module;
54 class NamedDecl;
55 class ObjCCategoryDecl;
56 class ObjCCategoryImplDecl;
57 class ObjCContainerDecl;
58 class ObjCImplDecl;
59 class ObjCImplementationDecl;
60 class ObjCInterfaceDecl;
61 class ObjCMethodDecl;
62 class ObjCProtocolDecl;
63 struct PrintingPolicy;
64 class RecordDecl;
65 class SourceManager;
66 class Stmt;
67 class StoredDeclsMap;
68 class TemplateDecl;
69 class TranslationUnitDecl;
70 class UsingDirectiveDecl;
71
72 /// Captures the result of checking the availability of a
73 /// declaration.
74 enum AvailabilityResult {
75 AR_Available = 0,
76 AR_NotYetIntroduced,
77 AR_Deprecated,
78 AR_Unavailable
79 };
80
81 /// Decl - This represents one declaration (or definition), e.g. a variable,
82 /// typedef, function, struct, etc.
83 ///
84 /// Note: There are objects tacked on before the *beginning* of Decl
85 /// (and its subclasses) in its Decl::operator new(). Proper alignment
86 /// of all subclasses (not requiring more than the alignment of Decl) is
87 /// asserted in DeclBase.cpp.
88 class alignas(8) Decl {
89 public:
90 /// Lists the kind of concrete classes of Decl.
91 enum Kind {
92 #define DECL(DERIVED, BASE) DERIVED,
93 #define ABSTRACT_DECL(DECL)
94 #define DECL_RANGE(BASE, START, END) \
95 first##BASE = START, last##BASE = END,
96 #define LAST_DECL_RANGE(BASE, START, END) \
97 first##BASE = START, last##BASE = END
98 #include "clang/AST/DeclNodes.inc"
99 };
100
101 /// A placeholder type used to construct an empty shell of a
102 /// decl-derived type that will be filled in later (e.g., by some
103 /// deserialization method).
104 struct EmptyShell {};
105
106 /// IdentifierNamespace - The different namespaces in which
107 /// declarations may appear. According to C99 6.2.3, there are
108 /// four namespaces, labels, tags, members and ordinary
109 /// identifiers. C++ describes lookup completely differently:
110 /// certain lookups merely "ignore" certain kinds of declarations,
111 /// usually based on whether the declaration is of a type, etc.
112 ///
113 /// These are meant as bitmasks, so that searches in
114 /// C++ can look into the "tag" namespace during ordinary lookup.
115 ///
116 /// Decl currently provides 15 bits of IDNS bits.
117 enum IdentifierNamespace {
118 /// Labels, declared with 'x:' and referenced with 'goto x'.
119 IDNS_Label = 0x0001,
120
121 /// Tags, declared with 'struct foo;' and referenced with
122 /// 'struct foo'. All tags are also types. This is what
123 /// elaborated-type-specifiers look for in C.
124 /// This also contains names that conflict with tags in the
125 /// same scope but that are otherwise ordinary names (non-type
126 /// template parameters and indirect field declarations).
127 IDNS_Tag = 0x0002,
128
129 /// Types, declared with 'struct foo', typedefs, etc.
130 /// This is what elaborated-type-specifiers look for in C++,
131 /// but note that it's ill-formed to find a non-tag.
132 IDNS_Type = 0x0004,
133
134 /// Members, declared with object declarations within tag
135 /// definitions. In C, these can only be found by "qualified"
136 /// lookup in member expressions. In C++, they're found by
137 /// normal lookup.
138 IDNS_Member = 0x0008,
139
140 /// Namespaces, declared with 'namespace foo {}'.
141 /// Lookup for nested-name-specifiers find these.
142 IDNS_Namespace = 0x0010,
143
144 /// Ordinary names. In C, everything that's not a label, tag,
145 /// member, or function-local extern ends up here.
146 IDNS_Ordinary = 0x0020,
147
148 /// Objective C \@protocol.
149 IDNS_ObjCProtocol = 0x0040,
150
151 /// This declaration is a friend function. A friend function
152 /// declaration is always in this namespace but may also be in
153 /// IDNS_Ordinary if it was previously declared.
154 IDNS_OrdinaryFriend = 0x0080,
155
156 /// This declaration is a friend class. A friend class
157 /// declaration is always in this namespace but may also be in
158 /// IDNS_Tag|IDNS_Type if it was previously declared.
159 IDNS_TagFriend = 0x0100,
160
161 /// This declaration is a using declaration. A using declaration
162 /// *introduces* a number of other declarations into the current
163 /// scope, and those declarations use the IDNS of their targets,
164 /// but the actual using declarations go in this namespace.
165 IDNS_Using = 0x0200,
166
167 /// This declaration is a C++ operator declared in a non-class
168 /// context. All such operators are also in IDNS_Ordinary.
169 /// C++ lexical operator lookup looks for these.
170 IDNS_NonMemberOperator = 0x0400,
171
172 /// This declaration is a function-local extern declaration of a
173 /// variable or function. This may also be IDNS_Ordinary if it
174 /// has been declared outside any function. These act mostly like
175 /// invisible friend declarations, but are also visible to unqualified
176 /// lookup within the scope of the declaring function.
177 IDNS_LocalExtern = 0x0800,
178
179 /// This declaration is an OpenMP user defined reduction construction.
180 IDNS_OMPReduction = 0x1000,
181
182 /// This declaration is an OpenMP user defined mapper.
183 IDNS_OMPMapper = 0x2000,
184 };
185
186 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
187 /// parameter types in method declarations. Other than remembering
188 /// them and mangling them into the method's signature string, these
189 /// are ignored by the compiler; they are consumed by certain
190 /// remote-messaging frameworks.
191 ///
192 /// in, inout, and out are mutually exclusive and apply only to
193 /// method parameters. bycopy and byref are mutually exclusive and
194 /// apply only to method parameters (?). oneway applies only to
195 /// results. All of these expect their corresponding parameter to
196 /// have a particular type. None of this is currently enforced by
197 /// clang.
198 ///
199 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
200 enum ObjCDeclQualifier {
201 OBJC_TQ_None = 0x0,
202 OBJC_TQ_In = 0x1,
203 OBJC_TQ_Inout = 0x2,
204 OBJC_TQ_Out = 0x4,
205 OBJC_TQ_Bycopy = 0x8,
206 OBJC_TQ_Byref = 0x10,
207 OBJC_TQ_Oneway = 0x20,
208
209 /// The nullability qualifier is set when the nullability of the
210 /// result or parameter was expressed via a context-sensitive
211 /// keyword.
212 OBJC_TQ_CSNullability = 0x40
213 };
214
215 /// The kind of ownership a declaration has, for visibility purposes.
216 /// This enumeration is designed such that higher values represent higher
217 /// levels of name hiding.
218 enum class ModuleOwnershipKind : unsigned {
219 /// This declaration is not owned by a module.
220 Unowned,
221
222 /// This declaration has an owning module, but is globally visible
223 /// (typically because its owning module is visible and we know that
224 /// modules cannot later become hidden in this compilation).
225 /// After serialization and deserialization, this will be converted
226 /// to VisibleWhenImported.
227 Visible,
228
229 /// This declaration has an owning module, and is visible when that
230 /// module is imported.
231 VisibleWhenImported,
232
233 /// This declaration has an owning module, but is only visible to
234 /// lookups that occur within that module.
235 ModulePrivate
236 };
237
238 protected:
239 /// The next declaration within the same lexical
240 /// DeclContext. These pointers form the linked list that is
241 /// traversed via DeclContext's decls_begin()/decls_end().
242 ///
243 /// The extra two bits are used for the ModuleOwnershipKind.
244 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
245
246 private:
247 friend class DeclContext;
248
249 struct MultipleDC {
250 DeclContext *SemanticDC;
251 DeclContext *LexicalDC;
252 };
253
254 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
255 /// For declarations that don't contain C++ scope specifiers, it contains
256 /// the DeclContext where the Decl was declared.
257 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
258 /// with the context where it semantically belongs (SemanticDC) and the
259 /// context where it was lexically declared (LexicalDC).
260 /// e.g.:
261 ///
262 /// namespace A {
263 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
264 /// }
265 /// void A::f(); // SemanticDC == namespace 'A'
266 /// // LexicalDC == global namespace
267 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
268
isInSemaDC()269 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
isOutOfSemaDC()270 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
271
getMultipleDC()272 MultipleDC *getMultipleDC() const {
273 return DeclCtx.get<MultipleDC*>();
274 }
275
getSemanticDC()276 DeclContext *getSemanticDC() const {
277 return DeclCtx.get<DeclContext*>();
278 }
279
280 /// Loc - The location of this decl.
281 SourceLocation Loc;
282
283 /// DeclKind - This indicates which class this is.
284 unsigned DeclKind : 7;
285
286 /// InvalidDecl - This indicates a semantic error occurred.
287 unsigned InvalidDecl : 1;
288
289 /// HasAttrs - This indicates whether the decl has attributes or not.
290 unsigned HasAttrs : 1;
291
292 /// Implicit - Whether this declaration was implicitly generated by
293 /// the implementation rather than explicitly written by the user.
294 unsigned Implicit : 1;
295
296 /// Whether this declaration was "used", meaning that a definition is
297 /// required.
298 unsigned Used : 1;
299
300 /// Whether this declaration was "referenced".
301 /// The difference with 'Used' is whether the reference appears in a
302 /// evaluated context or not, e.g. functions used in uninstantiated templates
303 /// are regarded as "referenced" but not "used".
304 unsigned Referenced : 1;
305
306 /// Whether this declaration is a top-level declaration (function,
307 /// global variable, etc.) that is lexically inside an objc container
308 /// definition.
309 unsigned TopLevelDeclInObjCContainer : 1;
310
311 /// Whether statistic collection is enabled.
312 static bool StatisticsEnabled;
313
314 protected:
315 friend class ASTDeclReader;
316 friend class ASTDeclWriter;
317 friend class ASTNodeImporter;
318 friend class ASTReader;
319 friend class CXXClassMemberWrapper;
320 friend class LinkageComputer;
321 template<typename decl_type> friend class Redeclarable;
322
323 /// Access - Used by C++ decls for the access specifier.
324 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
325 unsigned Access : 2;
326
327 /// Whether this declaration was loaded from an AST file.
328 unsigned FromASTFile : 1;
329
330 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
331 unsigned IdentifierNamespace : 14;
332
333 /// If 0, we have not computed the linkage of this declaration.
334 /// Otherwise, it is the linkage + 1.
335 mutable unsigned CacheValidAndLinkage : 3;
336
337 /// Allocate memory for a deserialized declaration.
338 ///
339 /// This routine must be used to allocate memory for any declaration that is
340 /// deserialized from a module file.
341 ///
342 /// \param Size The size of the allocated object.
343 /// \param Ctx The context in which we will allocate memory.
344 /// \param ID The global ID of the deserialized declaration.
345 /// \param Extra The amount of extra space to allocate after the object.
346 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
347 std::size_t Extra = 0);
348
349 /// Allocate memory for a non-deserialized declaration.
350 void *operator new(std::size_t Size, const ASTContext &Ctx,
351 DeclContext *Parent, std::size_t Extra = 0);
352
353 private:
354 bool AccessDeclContextSanity() const;
355
356 /// Get the module ownership kind to use for a local lexical child of \p DC,
357 /// which may be either a local or (rarely) an imported declaration.
getModuleOwnershipKindForChildOf(DeclContext * DC)358 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
359 if (DC) {
360 auto *D = cast<Decl>(DC);
361 auto MOK = D->getModuleOwnershipKind();
362 if (MOK != ModuleOwnershipKind::Unowned &&
363 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
364 return MOK;
365 // If D is not local and we have no local module storage, then we don't
366 // need to track module ownership at all.
367 }
368 return ModuleOwnershipKind::Unowned;
369 }
370
371 public:
372 Decl() = delete;
373 Decl(const Decl&) = delete;
374 Decl(Decl &&) = delete;
375 Decl &operator=(const Decl&) = delete;
376 Decl &operator=(Decl&&) = delete;
377
378 protected:
Decl(Kind DK,DeclContext * DC,SourceLocation L)379 Decl(Kind DK, DeclContext *DC, SourceLocation L)
380 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
381 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
382 Implicit(false), Used(false), Referenced(false),
383 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
384 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
385 CacheValidAndLinkage(0) {
386 if (StatisticsEnabled) add(DK);
387 }
388
Decl(Kind DK,EmptyShell Empty)389 Decl(Kind DK, EmptyShell Empty)
390 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
391 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
392 Access(AS_none), FromASTFile(0),
393 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
394 CacheValidAndLinkage(0) {
395 if (StatisticsEnabled) add(DK);
396 }
397
398 virtual ~Decl();
399
400 /// Update a potentially out-of-date declaration.
401 void updateOutOfDate(IdentifierInfo &II) const;
402
getCachedLinkage()403 Linkage getCachedLinkage() const {
404 return Linkage(CacheValidAndLinkage - 1);
405 }
406
setCachedLinkage(Linkage L)407 void setCachedLinkage(Linkage L) const {
408 CacheValidAndLinkage = L + 1;
409 }
410
hasCachedLinkage()411 bool hasCachedLinkage() const {
412 return CacheValidAndLinkage;
413 }
414
415 public:
416 /// Source range that this declaration covers.
getSourceRange()417 virtual SourceRange getSourceRange() const LLVM_READONLY {
418 return SourceRange(getLocation(), getLocation());
419 }
420
getBeginLoc()421 SourceLocation getBeginLoc() const LLVM_READONLY {
422 return getSourceRange().getBegin();
423 }
424
getEndLoc()425 SourceLocation getEndLoc() const LLVM_READONLY {
426 return getSourceRange().getEnd();
427 }
428
getLocation()429 SourceLocation getLocation() const { return Loc; }
setLocation(SourceLocation L)430 void setLocation(SourceLocation L) { Loc = L; }
431
getKind()432 Kind getKind() const { return static_cast<Kind>(DeclKind); }
433 const char *getDeclKindName() const;
434
getNextDeclInContext()435 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
getNextDeclInContext()436 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
437
getDeclContext()438 DeclContext *getDeclContext() {
439 if (isInSemaDC())
440 return getSemanticDC();
441 return getMultipleDC()->SemanticDC;
442 }
getDeclContext()443 const DeclContext *getDeclContext() const {
444 return const_cast<Decl*>(this)->getDeclContext();
445 }
446
447 /// Find the innermost non-closure ancestor of this declaration,
448 /// walking up through blocks, lambdas, etc. If that ancestor is
449 /// not a code context (!isFunctionOrMethod()), returns null.
450 ///
451 /// A declaration may be its own non-closure context.
452 Decl *getNonClosureContext();
getNonClosureContext()453 const Decl *getNonClosureContext() const {
454 return const_cast<Decl*>(this)->getNonClosureContext();
455 }
456
457 TranslationUnitDecl *getTranslationUnitDecl();
getTranslationUnitDecl()458 const TranslationUnitDecl *getTranslationUnitDecl() const {
459 return const_cast<Decl*>(this)->getTranslationUnitDecl();
460 }
461
462 bool isInAnonymousNamespace() const;
463
464 bool isInStdNamespace() const;
465
466 ASTContext &getASTContext() const LLVM_READONLY;
467
setAccess(AccessSpecifier AS)468 void setAccess(AccessSpecifier AS) {
469 Access = AS;
470 assert(AccessDeclContextSanity());
471 }
472
getAccess()473 AccessSpecifier getAccess() const {
474 assert(AccessDeclContextSanity());
475 return AccessSpecifier(Access);
476 }
477
478 /// Retrieve the access specifier for this declaration, even though
479 /// it may not yet have been properly set.
getAccessUnsafe()480 AccessSpecifier getAccessUnsafe() const {
481 return AccessSpecifier(Access);
482 }
483
hasAttrs()484 bool hasAttrs() const { return HasAttrs; }
485
setAttrs(const AttrVec & Attrs)486 void setAttrs(const AttrVec& Attrs) {
487 return setAttrsImpl(Attrs, getASTContext());
488 }
489
getAttrs()490 AttrVec &getAttrs() {
491 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
492 }
493
494 const AttrVec &getAttrs() const;
495 void dropAttrs();
496 void addAttr(Attr *A);
497
498 using attr_iterator = AttrVec::const_iterator;
499 using attr_range = llvm::iterator_range<attr_iterator>;
500
attrs()501 attr_range attrs() const {
502 return attr_range(attr_begin(), attr_end());
503 }
504
attr_begin()505 attr_iterator attr_begin() const {
506 return hasAttrs() ? getAttrs().begin() : nullptr;
507 }
attr_end()508 attr_iterator attr_end() const {
509 return hasAttrs() ? getAttrs().end() : nullptr;
510 }
511
512 template <typename T>
dropAttr()513 void dropAttr() {
514 if (!HasAttrs) return;
515
516 AttrVec &Vec = getAttrs();
517 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
518
519 if (Vec.empty())
520 HasAttrs = false;
521 }
522
523 template <typename T>
specific_attrs()524 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
525 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
526 }
527
528 template <typename T>
specific_attr_begin()529 specific_attr_iterator<T> specific_attr_begin() const {
530 return specific_attr_iterator<T>(attr_begin());
531 }
532
533 template <typename T>
specific_attr_end()534 specific_attr_iterator<T> specific_attr_end() const {
535 return specific_attr_iterator<T>(attr_end());
536 }
537
getAttr()538 template<typename T> T *getAttr() const {
539 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
540 }
541
hasAttr()542 template<typename T> bool hasAttr() const {
543 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
544 }
545
546 /// getMaxAlignment - return the maximum alignment specified by attributes
547 /// on this decl, 0 if there are none.
548 unsigned getMaxAlignment() const;
549
550 /// setInvalidDecl - Indicates the Decl had a semantic error. This
551 /// allows for graceful error recovery.
552 void setInvalidDecl(bool Invalid = true);
isInvalidDecl()553 bool isInvalidDecl() const { return (bool) InvalidDecl; }
554
555 /// isImplicit - Indicates whether the declaration was implicitly
556 /// generated by the implementation. If false, this declaration
557 /// was written explicitly in the source code.
isImplicit()558 bool isImplicit() const { return Implicit; }
559 void setImplicit(bool I = true) { Implicit = I; }
560
561 /// Whether *any* (re-)declaration of the entity was used, meaning that
562 /// a definition is required.
563 ///
564 /// \param CheckUsedAttr When true, also consider the "used" attribute
565 /// (in addition to the "used" bit set by \c setUsed()) when determining
566 /// whether the function is used.
567 bool isUsed(bool CheckUsedAttr = true) const;
568
569 /// Set whether the declaration is used, in the sense of odr-use.
570 ///
571 /// This should only be used immediately after creating a declaration.
572 /// It intentionally doesn't notify any listeners.
setIsUsed()573 void setIsUsed() { getCanonicalDecl()->Used = true; }
574
575 /// Mark the declaration used, in the sense of odr-use.
576 ///
577 /// This notifies any mutation listeners in addition to setting a bit
578 /// indicating the declaration is used.
579 void markUsed(ASTContext &C);
580
581 /// Whether any declaration of this entity was referenced.
582 bool isReferenced() const;
583
584 /// Whether this declaration was referenced. This should not be relied
585 /// upon for anything other than debugging.
isThisDeclarationReferenced()586 bool isThisDeclarationReferenced() const { return Referenced; }
587
588 void setReferenced(bool R = true) { Referenced = R; }
589
590 /// Whether this declaration is a top-level declaration (function,
591 /// global variable, etc.) that is lexically inside an objc container
592 /// definition.
isTopLevelDeclInObjCContainer()593 bool isTopLevelDeclInObjCContainer() const {
594 return TopLevelDeclInObjCContainer;
595 }
596
597 void setTopLevelDeclInObjCContainer(bool V = true) {
598 TopLevelDeclInObjCContainer = V;
599 }
600
601 /// Looks on this and related declarations for an applicable
602 /// external source symbol attribute.
603 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
604
605 /// Whether this declaration was marked as being private to the
606 /// module in which it was defined.
isModulePrivate()607 bool isModulePrivate() const {
608 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
609 }
610
611 /// Return true if this declaration has an attribute which acts as
612 /// definition of the entity, such as 'alias' or 'ifunc'.
613 bool hasDefiningAttr() const;
614
615 /// Return this declaration's defining attribute if it has one.
616 const Attr *getDefiningAttr() const;
617
618 protected:
619 /// Specify that this declaration was marked as being private
620 /// to the module in which it was defined.
setModulePrivate()621 void setModulePrivate() {
622 // The module-private specifier has no effect on unowned declarations.
623 // FIXME: We should track this in some way for source fidelity.
624 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
625 return;
626 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
627 }
628
629 /// Set the owning module ID.
setOwningModuleID(unsigned ID)630 void setOwningModuleID(unsigned ID) {
631 assert(isFromASTFile() && "Only works on a deserialized declaration");
632 *((unsigned*)this - 2) = ID;
633 }
634
635 public:
636 /// Determine the availability of the given declaration.
637 ///
638 /// This routine will determine the most restrictive availability of
639 /// the given declaration (e.g., preferring 'unavailable' to
640 /// 'deprecated').
641 ///
642 /// \param Message If non-NULL and the result is not \c
643 /// AR_Available, will be set to a (possibly empty) message
644 /// describing why the declaration has not been introduced, is
645 /// deprecated, or is unavailable.
646 ///
647 /// \param EnclosingVersion The version to compare with. If empty, assume the
648 /// deployment target version.
649 ///
650 /// \param RealizedPlatform If non-NULL and the availability result is found
651 /// in an available attribute it will set to the platform which is written in
652 /// the available attribute.
653 AvailabilityResult
654 getAvailability(std::string *Message = nullptr,
655 VersionTuple EnclosingVersion = VersionTuple(),
656 StringRef *RealizedPlatform = nullptr) const;
657
658 /// Retrieve the version of the target platform in which this
659 /// declaration was introduced.
660 ///
661 /// \returns An empty version tuple if this declaration has no 'introduced'
662 /// availability attributes, or the version tuple that's specified in the
663 /// attribute otherwise.
664 VersionTuple getVersionIntroduced() const;
665
666 /// Determine whether this declaration is marked 'deprecated'.
667 ///
668 /// \param Message If non-NULL and the declaration is deprecated,
669 /// this will be set to the message describing why the declaration
670 /// was deprecated (which may be empty).
671 bool isDeprecated(std::string *Message = nullptr) const {
672 return getAvailability(Message) == AR_Deprecated;
673 }
674
675 /// Determine whether this declaration is marked 'unavailable'.
676 ///
677 /// \param Message If non-NULL and the declaration is unavailable,
678 /// this will be set to the message describing why the declaration
679 /// was made unavailable (which may be empty).
680 bool isUnavailable(std::string *Message = nullptr) const {
681 return getAvailability(Message) == AR_Unavailable;
682 }
683
684 /// Determine whether this is a weak-imported symbol.
685 ///
686 /// Weak-imported symbols are typically marked with the
687 /// 'weak_import' attribute, but may also be marked with an
688 /// 'availability' attribute where we're targing a platform prior to
689 /// the introduction of this feature.
690 bool isWeakImported() const;
691
692 /// Determines whether this symbol can be weak-imported,
693 /// e.g., whether it would be well-formed to add the weak_import
694 /// attribute.
695 ///
696 /// \param IsDefinition Set to \c true to indicate that this
697 /// declaration cannot be weak-imported because it has a definition.
698 bool canBeWeakImported(bool &IsDefinition) const;
699
700 /// Determine whether this declaration came from an AST file (such as
701 /// a precompiled header or module) rather than having been parsed.
isFromASTFile()702 bool isFromASTFile() const { return FromASTFile; }
703
704 /// Retrieve the global declaration ID associated with this
705 /// declaration, which specifies where this Decl was loaded from.
getGlobalID()706 unsigned getGlobalID() const {
707 if (isFromASTFile())
708 return *((const unsigned*)this - 1);
709 return 0;
710 }
711
712 /// Retrieve the global ID of the module that owns this particular
713 /// declaration.
getOwningModuleID()714 unsigned getOwningModuleID() const {
715 if (isFromASTFile())
716 return *((const unsigned*)this - 2);
717 return 0;
718 }
719
720 private:
721 Module *getOwningModuleSlow() const;
722
723 protected:
724 bool hasLocalOwningModuleStorage() const;
725
726 public:
727 /// Get the imported owning module, if this decl is from an imported
728 /// (non-local) module.
getImportedOwningModule()729 Module *getImportedOwningModule() const {
730 if (!isFromASTFile() || !hasOwningModule())
731 return nullptr;
732
733 return getOwningModuleSlow();
734 }
735
736 /// Get the local owning module, if known. Returns nullptr if owner is
737 /// not yet known or declaration is not from a module.
getLocalOwningModule()738 Module *getLocalOwningModule() const {
739 if (isFromASTFile() || !hasOwningModule())
740 return nullptr;
741
742 assert(hasLocalOwningModuleStorage() &&
743 "owned local decl but no local module storage");
744 return reinterpret_cast<Module *const *>(this)[-1];
745 }
setLocalOwningModule(Module * M)746 void setLocalOwningModule(Module *M) {
747 assert(!isFromASTFile() && hasOwningModule() &&
748 hasLocalOwningModuleStorage() &&
749 "should not have a cached owning module");
750 reinterpret_cast<Module **>(this)[-1] = M;
751 }
752
753 /// Is this declaration owned by some module?
hasOwningModule()754 bool hasOwningModule() const {
755 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
756 }
757
758 /// Get the module that owns this declaration (for visibility purposes).
getOwningModule()759 Module *getOwningModule() const {
760 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
761 }
762
763 /// Get the module that owns this declaration for linkage purposes.
764 /// There only ever is such a module under the C++ Modules TS.
765 ///
766 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
767 /// all declarations in a global module fragment are unowned.
768 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
769
770 /// Determine whether this declaration might be hidden from name
771 /// lookup. Note that the declaration might be visible even if this returns
772 /// \c false, if the owning module is visible within the query context.
773 // FIXME: Rename this to make it clearer what it does.
isHidden()774 bool isHidden() const {
775 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
776 }
777
778 /// Set that this declaration is globally visible, even if it came from a
779 /// module that is not visible.
setVisibleDespiteOwningModule()780 void setVisibleDespiteOwningModule() {
781 if (isHidden())
782 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
783 }
784
785 /// Get the kind of module ownership for this declaration.
getModuleOwnershipKind()786 ModuleOwnershipKind getModuleOwnershipKind() const {
787 return NextInContextAndBits.getInt();
788 }
789
790 /// Set whether this declaration is hidden from name lookup.
setModuleOwnershipKind(ModuleOwnershipKind MOK)791 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
792 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
793 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&
794 !hasLocalOwningModuleStorage()) &&
795 "no storage available for owning module for this declaration");
796 NextInContextAndBits.setInt(MOK);
797 }
798
getIdentifierNamespace()799 unsigned getIdentifierNamespace() const {
800 return IdentifierNamespace;
801 }
802
isInIdentifierNamespace(unsigned NS)803 bool isInIdentifierNamespace(unsigned NS) const {
804 return getIdentifierNamespace() & NS;
805 }
806
807 static unsigned getIdentifierNamespaceForKind(Kind DK);
808
hasTagIdentifierNamespace()809 bool hasTagIdentifierNamespace() const {
810 return isTagIdentifierNamespace(getIdentifierNamespace());
811 }
812
isTagIdentifierNamespace(unsigned NS)813 static bool isTagIdentifierNamespace(unsigned NS) {
814 // TagDecls have Tag and Type set and may also have TagFriend.
815 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
816 }
817
818 /// getLexicalDeclContext - The declaration context where this Decl was
819 /// lexically declared (LexicalDC). May be different from
820 /// getDeclContext() (SemanticDC).
821 /// e.g.:
822 ///
823 /// namespace A {
824 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
825 /// }
826 /// void A::f(); // SemanticDC == namespace 'A'
827 /// // LexicalDC == global namespace
getLexicalDeclContext()828 DeclContext *getLexicalDeclContext() {
829 if (isInSemaDC())
830 return getSemanticDC();
831 return getMultipleDC()->LexicalDC;
832 }
getLexicalDeclContext()833 const DeclContext *getLexicalDeclContext() const {
834 return const_cast<Decl*>(this)->getLexicalDeclContext();
835 }
836
837 /// Determine whether this declaration is declared out of line (outside its
838 /// semantic context).
839 virtual bool isOutOfLine() const;
840
841 /// setDeclContext - Set both the semantic and lexical DeclContext
842 /// to DC.
843 void setDeclContext(DeclContext *DC);
844
845 void setLexicalDeclContext(DeclContext *DC);
846
847 /// Determine whether this declaration is a templated entity (whether it is
848 // within the scope of a template parameter).
849 bool isTemplated() const;
850
851 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
852 /// scoped decl is defined outside the current function or method. This is
853 /// roughly global variables and functions, but also handles enums (which
854 /// could be defined inside or outside a function etc).
isDefinedOutsideFunctionOrMethod()855 bool isDefinedOutsideFunctionOrMethod() const {
856 return getParentFunctionOrMethod() == nullptr;
857 }
858
859 /// Returns true if this declaration is lexically inside a function or inside
860 /// a variable initializer. It recognizes non-defining declarations as well
861 /// as members of local classes:
862 /// \code
863 /// void foo() { void bar(); }
864 /// void foo2() { class ABC { void bar(); }; }
865 /// inline int x = [](){ return 0; };
866 /// \endcode
867 bool isInLocalScope() const;
868
869 /// If this decl is defined inside a function/method/block it returns
870 /// the corresponding DeclContext, otherwise it returns null.
871 const DeclContext *getParentFunctionOrMethod() const;
getParentFunctionOrMethod()872 DeclContext *getParentFunctionOrMethod() {
873 return const_cast<DeclContext*>(
874 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
875 }
876
877 /// Retrieves the "canonical" declaration of the given declaration.
getCanonicalDecl()878 virtual Decl *getCanonicalDecl() { return this; }
getCanonicalDecl()879 const Decl *getCanonicalDecl() const {
880 return const_cast<Decl*>(this)->getCanonicalDecl();
881 }
882
883 /// Whether this particular Decl is a canonical one.
isCanonicalDecl()884 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
885
886 protected:
887 /// Returns the next redeclaration or itself if this is the only decl.
888 ///
889 /// Decl subclasses that can be redeclared should override this method so that
890 /// Decl::redecl_iterator can iterate over them.
getNextRedeclarationImpl()891 virtual Decl *getNextRedeclarationImpl() { return this; }
892
893 /// Implementation of getPreviousDecl(), to be overridden by any
894 /// subclass that has a redeclaration chain.
getPreviousDeclImpl()895 virtual Decl *getPreviousDeclImpl() { return nullptr; }
896
897 /// Implementation of getMostRecentDecl(), to be overridden by any
898 /// subclass that has a redeclaration chain.
getMostRecentDeclImpl()899 virtual Decl *getMostRecentDeclImpl() { return this; }
900
901 public:
902 /// Iterates through all the redeclarations of the same decl.
903 class redecl_iterator {
904 /// Current - The current declaration.
905 Decl *Current = nullptr;
906 Decl *Starter;
907
908 public:
909 using value_type = Decl *;
910 using reference = const value_type &;
911 using pointer = const value_type *;
912 using iterator_category = std::forward_iterator_tag;
913 using difference_type = std::ptrdiff_t;
914
915 redecl_iterator() = default;
redecl_iterator(Decl * C)916 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
917
918 reference operator*() const { return Current; }
919 value_type operator->() const { return Current; }
920
921 redecl_iterator& operator++() {
922 assert(Current && "Advancing while iterator has reached end");
923 // Get either previous decl or latest decl.
924 Decl *Next = Current->getNextRedeclarationImpl();
925 assert(Next && "Should return next redeclaration or itself, never null!");
926 Current = (Next != Starter) ? Next : nullptr;
927 return *this;
928 }
929
930 redecl_iterator operator++(int) {
931 redecl_iterator tmp(*this);
932 ++(*this);
933 return tmp;
934 }
935
936 friend bool operator==(redecl_iterator x, redecl_iterator y) {
937 return x.Current == y.Current;
938 }
939
940 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
941 return x.Current != y.Current;
942 }
943 };
944
945 using redecl_range = llvm::iterator_range<redecl_iterator>;
946
947 /// Returns an iterator range for all the redeclarations of the same
948 /// decl. It will iterate at least once (when this decl is the only one).
redecls()949 redecl_range redecls() const {
950 return redecl_range(redecls_begin(), redecls_end());
951 }
952
redecls_begin()953 redecl_iterator redecls_begin() const {
954 return redecl_iterator(const_cast<Decl *>(this));
955 }
956
redecls_end()957 redecl_iterator redecls_end() const { return redecl_iterator(); }
958
959 /// Retrieve the previous declaration that declares the same entity
960 /// as this declaration, or NULL if there is no previous declaration.
getPreviousDecl()961 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
962
963 /// Retrieve the previous declaration that declares the same entity
964 /// as this declaration, or NULL if there is no previous declaration.
getPreviousDecl()965 const Decl *getPreviousDecl() const {
966 return const_cast<Decl *>(this)->getPreviousDeclImpl();
967 }
968
969 /// True if this is the first declaration in its redeclaration chain.
isFirstDecl()970 bool isFirstDecl() const {
971 return getPreviousDecl() == nullptr;
972 }
973
974 /// Retrieve the most recent declaration that declares the same entity
975 /// as this declaration (which may be this declaration).
getMostRecentDecl()976 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
977
978 /// Retrieve the most recent declaration that declares the same entity
979 /// as this declaration (which may be this declaration).
getMostRecentDecl()980 const Decl *getMostRecentDecl() const {
981 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
982 }
983
984 /// getBody - If this Decl represents a declaration for a body of code,
985 /// such as a function or method definition, this method returns the
986 /// top-level Stmt* of that body. Otherwise this method returns null.
getBody()987 virtual Stmt* getBody() const { return nullptr; }
988
989 /// Returns true if this \c Decl represents a declaration for a body of
990 /// code, such as a function or method definition.
991 /// Note that \c hasBody can also return true if any redeclaration of this
992 /// \c Decl represents a declaration for a body of code.
hasBody()993 virtual bool hasBody() const { return getBody() != nullptr; }
994
995 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
996 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
997 SourceLocation getBodyRBrace() const;
998
999 // global temp stats (until we have a per-module visitor)
1000 static void add(Kind k);
1001 static void EnableStatistics();
1002 static void PrintStats();
1003
1004 /// isTemplateParameter - Determines whether this declaration is a
1005 /// template parameter.
1006 bool isTemplateParameter() const;
1007
1008 /// isTemplateParameter - Determines whether this declaration is a
1009 /// template parameter pack.
1010 bool isTemplateParameterPack() const;
1011
1012 /// Whether this declaration is a parameter pack.
1013 bool isParameterPack() const;
1014
1015 /// returns true if this declaration is a template
1016 bool isTemplateDecl() const;
1017
1018 /// Whether this declaration is a function or function template.
isFunctionOrFunctionTemplate()1019 bool isFunctionOrFunctionTemplate() const {
1020 return (DeclKind >= Decl::firstFunction &&
1021 DeclKind <= Decl::lastFunction) ||
1022 DeclKind == FunctionTemplate;
1023 }
1024
1025 /// If this is a declaration that describes some template, this
1026 /// method returns that template declaration.
1027 TemplateDecl *getDescribedTemplate() const;
1028
1029 /// Returns the function itself, or the templated function if this is a
1030 /// function template.
1031 FunctionDecl *getAsFunction() LLVM_READONLY;
1032
getAsFunction()1033 const FunctionDecl *getAsFunction() const {
1034 return const_cast<Decl *>(this)->getAsFunction();
1035 }
1036
1037 /// Changes the namespace of this declaration to reflect that it's
1038 /// a function-local extern declaration.
1039 ///
1040 /// These declarations appear in the lexical context of the extern
1041 /// declaration, but in the semantic context of the enclosing namespace
1042 /// scope.
setLocalExternDecl()1043 void setLocalExternDecl() {
1044 Decl *Prev = getPreviousDecl();
1045 IdentifierNamespace &= ~IDNS_Ordinary;
1046
1047 // It's OK for the declaration to still have the "invisible friend" flag or
1048 // the "conflicts with tag declarations in this scope" flag for the outer
1049 // scope.
1050 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&
1051 "namespace is not ordinary");
1052
1053 IdentifierNamespace |= IDNS_LocalExtern;
1054 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1055 IdentifierNamespace |= IDNS_Ordinary;
1056 }
1057
1058 /// Determine whether this is a block-scope declaration with linkage.
1059 /// This will either be a local variable declaration declared 'extern', or a
1060 /// local function declaration.
isLocalExternDecl()1061 bool isLocalExternDecl() {
1062 return IdentifierNamespace & IDNS_LocalExtern;
1063 }
1064
1065 /// Changes the namespace of this declaration to reflect that it's
1066 /// the object of a friend declaration.
1067 ///
1068 /// These declarations appear in the lexical context of the friending
1069 /// class, but in the semantic context of the actual entity. This property
1070 /// applies only to a specific decl object; other redeclarations of the
1071 /// same entity may not (and probably don't) share this property.
1072 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1073 unsigned OldNS = IdentifierNamespace;
1074 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
1075 IDNS_TagFriend | IDNS_OrdinaryFriend |
1076 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&
1077 "namespace includes neither ordinary nor tag");
1078 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
1079 IDNS_TagFriend | IDNS_OrdinaryFriend |
1080 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&
1081 "namespace includes other than ordinary or tag");
1082
1083 Decl *Prev = getPreviousDecl();
1084 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1085
1086 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1087 IdentifierNamespace |= IDNS_TagFriend;
1088 if (PerformFriendInjection ||
1089 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1090 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1091 }
1092
1093 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1094 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1095 IdentifierNamespace |= IDNS_OrdinaryFriend;
1096 if (PerformFriendInjection ||
1097 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1098 IdentifierNamespace |= IDNS_Ordinary;
1099 }
1100 }
1101
1102 enum FriendObjectKind {
1103 FOK_None, ///< Not a friend object.
1104 FOK_Declared, ///< A friend of a previously-declared entity.
1105 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1106 };
1107
1108 /// Determines whether this declaration is the object of a
1109 /// friend declaration and, if so, what kind.
1110 ///
1111 /// There is currently no direct way to find the associated FriendDecl.
getFriendObjectKind()1112 FriendObjectKind getFriendObjectKind() const {
1113 unsigned mask =
1114 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1115 if (!mask) return FOK_None;
1116 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1117 : FOK_Undeclared);
1118 }
1119
1120 /// Specifies that this declaration is a C++ overloaded non-member.
setNonMemberOperator()1121 void setNonMemberOperator() {
1122 assert(getKind() == Function || getKind() == FunctionTemplate);
1123 assert((IdentifierNamespace & IDNS_Ordinary) &&
1124 "visible non-member operators should be in ordinary namespace");
1125 IdentifierNamespace |= IDNS_NonMemberOperator;
1126 }
1127
classofKind(Kind K)1128 static bool classofKind(Kind K) { return true; }
1129 static DeclContext *castToDeclContext(const Decl *);
1130 static Decl *castFromDeclContext(const DeclContext *);
1131
1132 void print(raw_ostream &Out, unsigned Indentation = 0,
1133 bool PrintInstantiation = false) const;
1134 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1135 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1136 static void printGroup(Decl** Begin, unsigned NumDecls,
1137 raw_ostream &Out, const PrintingPolicy &Policy,
1138 unsigned Indentation = 0);
1139
1140 // Debuggers don't usually respect default arguments.
1141 void dump() const;
1142
1143 // Same as dump(), but forces color printing.
1144 void dumpColor() const;
1145
1146 void dump(raw_ostream &Out, bool Deserialize = false,
1147 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1148
1149 /// \return Unique reproducible object identifier
1150 int64_t getID() const;
1151
1152 /// Looks through the Decl's underlying type to extract a FunctionType
1153 /// when possible. Will return null if the type underlying the Decl does not
1154 /// have a FunctionType.
1155 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1156
1157 private:
1158 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1159 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1160 ASTContext &Ctx);
1161
1162 protected:
1163 ASTMutationListener *getASTMutationListener() const;
1164 };
1165
1166 /// Determine whether two declarations declare the same entity.
declaresSameEntity(const Decl * D1,const Decl * D2)1167 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1168 if (!D1 || !D2)
1169 return false;
1170
1171 if (D1 == D2)
1172 return true;
1173
1174 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1175 }
1176
1177 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1178 /// doing something to a specific decl.
1179 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1180 const Decl *TheDecl;
1181 SourceLocation Loc;
1182 SourceManager &SM;
1183 const char *Message;
1184
1185 public:
PrettyStackTraceDecl(const Decl * theDecl,SourceLocation L,SourceManager & sm,const char * Msg)1186 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1187 SourceManager &sm, const char *Msg)
1188 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1189
1190 void print(raw_ostream &OS) const override;
1191 };
1192
1193 /// The results of name lookup within a DeclContext. This is either a
1194 /// single result (with no stable storage) or a collection of results (with
1195 /// stable storage provided by the lookup table).
1196 class DeclContextLookupResult {
1197 using ResultTy = ArrayRef<NamedDecl *>;
1198
1199 ResultTy Result;
1200
1201 // If there is only one lookup result, it would be invalidated by
1202 // reallocations of the name table, so store it separately.
1203 NamedDecl *Single = nullptr;
1204
1205 static NamedDecl *const SingleElementDummyList;
1206
1207 public:
1208 DeclContextLookupResult() = default;
DeclContextLookupResult(ArrayRef<NamedDecl * > Result)1209 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1210 : Result(Result) {}
DeclContextLookupResult(NamedDecl * Single)1211 DeclContextLookupResult(NamedDecl *Single)
1212 : Result(SingleElementDummyList), Single(Single) {}
1213
1214 class iterator;
1215
1216 using IteratorBase =
1217 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1218 std::random_access_iterator_tag,
1219 NamedDecl *const>;
1220
1221 class iterator : public IteratorBase {
1222 value_type SingleElement;
1223
1224 public:
1225 explicit iterator(pointer Pos, value_type Single = nullptr)
IteratorBase(Pos)1226 : IteratorBase(Pos), SingleElement(Single) {}
1227
1228 reference operator*() const {
1229 return SingleElement ? SingleElement : IteratorBase::operator*();
1230 }
1231 };
1232
1233 using const_iterator = iterator;
1234 using pointer = iterator::pointer;
1235 using reference = iterator::reference;
1236
begin()1237 iterator begin() const { return iterator(Result.begin(), Single); }
end()1238 iterator end() const { return iterator(Result.end(), Single); }
1239
empty()1240 bool empty() const { return Result.empty(); }
data()1241 pointer data() const { return Single ? &Single : Result.data(); }
size()1242 size_t size() const { return Single ? 1 : Result.size(); }
front()1243 reference front() const { return Single ? Single : Result.front(); }
back()1244 reference back() const { return Single ? Single : Result.back(); }
1245 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1246
1247 // FIXME: Remove this from the interface
slice(size_t N)1248 DeclContextLookupResult slice(size_t N) const {
1249 DeclContextLookupResult Sliced = Result.slice(N);
1250 Sliced.Single = Single;
1251 return Sliced;
1252 }
1253 };
1254
1255 /// DeclContext - This is used only as base class of specific decl types that
1256 /// can act as declaration contexts. These decls are (only the top classes
1257 /// that directly derive from DeclContext are mentioned, not their subclasses):
1258 ///
1259 /// TranslationUnitDecl
1260 /// ExternCContext
1261 /// NamespaceDecl
1262 /// TagDecl
1263 /// OMPDeclareReductionDecl
1264 /// OMPDeclareMapperDecl
1265 /// FunctionDecl
1266 /// ObjCMethodDecl
1267 /// ObjCContainerDecl
1268 /// LinkageSpecDecl
1269 /// ExportDecl
1270 /// BlockDecl
1271 /// CapturedDecl
1272 class DeclContext {
1273 /// For makeDeclVisibleInContextImpl
1274 friend class ASTDeclReader;
1275 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1276 /// hasNeedToReconcileExternalVisibleStorage
1277 friend class ExternalASTSource;
1278 /// For CreateStoredDeclsMap
1279 friend class DependentDiagnostic;
1280 /// For hasNeedToReconcileExternalVisibleStorage,
1281 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1282 friend class ASTWriter;
1283
1284 // We use uint64_t in the bit-fields below since some bit-fields
1285 // cross the unsigned boundary and this breaks the packing.
1286
1287 /// Stores the bits used by DeclContext.
1288 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1289 /// methods in DeclContext should be updated appropriately.
1290 class DeclContextBitfields {
1291 friend class DeclContext;
1292 /// DeclKind - This indicates which class this is.
1293 uint64_t DeclKind : 7;
1294
1295 /// Whether this declaration context also has some external
1296 /// storage that contains additional declarations that are lexically
1297 /// part of this context.
1298 mutable uint64_t ExternalLexicalStorage : 1;
1299
1300 /// Whether this declaration context also has some external
1301 /// storage that contains additional declarations that are visible
1302 /// in this context.
1303 mutable uint64_t ExternalVisibleStorage : 1;
1304
1305 /// Whether this declaration context has had externally visible
1306 /// storage added since the last lookup. In this case, \c LookupPtr's
1307 /// invariant may not hold and needs to be fixed before we perform
1308 /// another lookup.
1309 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1310
1311 /// If \c true, this context may have local lexical declarations
1312 /// that are missing from the lookup table.
1313 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1314
1315 /// If \c true, the external source may have lexical declarations
1316 /// that are missing from the lookup table.
1317 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1318
1319 /// If \c true, lookups should only return identifier from
1320 /// DeclContext scope (for example TranslationUnit). Used in
1321 /// LookupQualifiedName()
1322 mutable uint64_t UseQualifiedLookup : 1;
1323 };
1324
1325 /// Number of bits in DeclContextBitfields.
1326 enum { NumDeclContextBits = 13 };
1327
1328 /// Stores the bits used by TagDecl.
1329 /// If modified NumTagDeclBits and the accessor
1330 /// methods in TagDecl should be updated appropriately.
1331 class TagDeclBitfields {
1332 friend class TagDecl;
1333 /// For the bits in DeclContextBitfields
1334 uint64_t : NumDeclContextBits;
1335
1336 /// The TagKind enum.
1337 uint64_t TagDeclKind : 3;
1338
1339 /// True if this is a definition ("struct foo {};"), false if it is a
1340 /// declaration ("struct foo;"). It is not considered a definition
1341 /// until the definition has been fully processed.
1342 uint64_t IsCompleteDefinition : 1;
1343
1344 /// True if this is currently being defined.
1345 uint64_t IsBeingDefined : 1;
1346
1347 /// True if this tag declaration is "embedded" (i.e., defined or declared
1348 /// for the very first time) in the syntax of a declarator.
1349 uint64_t IsEmbeddedInDeclarator : 1;
1350
1351 /// True if this tag is free standing, e.g. "struct foo;".
1352 uint64_t IsFreeStanding : 1;
1353
1354 /// Indicates whether it is possible for declarations of this kind
1355 /// to have an out-of-date definition.
1356 ///
1357 /// This option is only enabled when modules are enabled.
1358 uint64_t MayHaveOutOfDateDef : 1;
1359
1360 /// Has the full definition of this type been required by a use somewhere in
1361 /// the TU.
1362 uint64_t IsCompleteDefinitionRequired : 1;
1363 };
1364
1365 /// Number of non-inherited bits in TagDeclBitfields.
1366 enum { NumTagDeclBits = 9 };
1367
1368 /// Stores the bits used by EnumDecl.
1369 /// If modified NumEnumDeclBit and the accessor
1370 /// methods in EnumDecl should be updated appropriately.
1371 class EnumDeclBitfields {
1372 friend class EnumDecl;
1373 /// For the bits in DeclContextBitfields.
1374 uint64_t : NumDeclContextBits;
1375 /// For the bits in TagDeclBitfields.
1376 uint64_t : NumTagDeclBits;
1377
1378 /// Width in bits required to store all the non-negative
1379 /// enumerators of this enum.
1380 uint64_t NumPositiveBits : 8;
1381
1382 /// Width in bits required to store all the negative
1383 /// enumerators of this enum.
1384 uint64_t NumNegativeBits : 8;
1385
1386 /// True if this tag declaration is a scoped enumeration. Only
1387 /// possible in C++11 mode.
1388 uint64_t IsScoped : 1;
1389
1390 /// If this tag declaration is a scoped enum,
1391 /// then this is true if the scoped enum was declared using the class
1392 /// tag, false if it was declared with the struct tag. No meaning is
1393 /// associated if this tag declaration is not a scoped enum.
1394 uint64_t IsScopedUsingClassTag : 1;
1395
1396 /// True if this is an enumeration with fixed underlying type. Only
1397 /// possible in C++11, Microsoft extensions, or Objective C mode.
1398 uint64_t IsFixed : 1;
1399
1400 /// True if a valid hash is stored in ODRHash.
1401 uint64_t HasODRHash : 1;
1402 };
1403
1404 /// Number of non-inherited bits in EnumDeclBitfields.
1405 enum { NumEnumDeclBits = 20 };
1406
1407 /// Stores the bits used by RecordDecl.
1408 /// If modified NumRecordDeclBits and the accessor
1409 /// methods in RecordDecl should be updated appropriately.
1410 class RecordDeclBitfields {
1411 friend class RecordDecl;
1412 /// For the bits in DeclContextBitfields.
1413 uint64_t : NumDeclContextBits;
1414 /// For the bits in TagDeclBitfields.
1415 uint64_t : NumTagDeclBits;
1416
1417 /// This is true if this struct ends with a flexible
1418 /// array member (e.g. int X[]) or if this union contains a struct that does.
1419 /// If so, this cannot be contained in arrays or other structs as a member.
1420 uint64_t HasFlexibleArrayMember : 1;
1421
1422 /// Whether this is the type of an anonymous struct or union.
1423 uint64_t AnonymousStructOrUnion : 1;
1424
1425 /// This is true if this struct has at least one member
1426 /// containing an Objective-C object pointer type.
1427 uint64_t HasObjectMember : 1;
1428
1429 /// This is true if struct has at least one member of
1430 /// 'volatile' type.
1431 uint64_t HasVolatileMember : 1;
1432
1433 /// Whether the field declarations of this record have been loaded
1434 /// from external storage. To avoid unnecessary deserialization of
1435 /// methods/nested types we allow deserialization of just the fields
1436 /// when needed.
1437 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1438
1439 /// Basic properties of non-trivial C structs.
1440 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1441 uint64_t NonTrivialToPrimitiveCopy : 1;
1442 uint64_t NonTrivialToPrimitiveDestroy : 1;
1443
1444 /// The following bits indicate whether this is or contains a C union that
1445 /// is non-trivial to default-initialize, destruct, or copy. These bits
1446 /// imply the associated basic non-triviality predicates declared above.
1447 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1448 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1449 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1450
1451 /// Indicates whether this struct is destroyed in the callee.
1452 uint64_t ParamDestroyedInCallee : 1;
1453
1454 /// Represents the way this type is passed to a function.
1455 uint64_t ArgPassingRestrictions : 2;
1456 };
1457
1458 /// Number of non-inherited bits in RecordDeclBitfields.
1459 enum { NumRecordDeclBits = 14 };
1460
1461 /// Stores the bits used by OMPDeclareReductionDecl.
1462 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1463 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1464 class OMPDeclareReductionDeclBitfields {
1465 friend class OMPDeclareReductionDecl;
1466 /// For the bits in DeclContextBitfields
1467 uint64_t : NumDeclContextBits;
1468
1469 /// Kind of initializer,
1470 /// function call or omp_priv<init_expr> initializtion.
1471 uint64_t InitializerKind : 2;
1472 };
1473
1474 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1475 enum { NumOMPDeclareReductionDeclBits = 2 };
1476
1477 /// Stores the bits used by FunctionDecl.
1478 /// If modified NumFunctionDeclBits and the accessor
1479 /// methods in FunctionDecl and CXXDeductionGuideDecl
1480 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1481 class FunctionDeclBitfields {
1482 friend class FunctionDecl;
1483 /// For IsCopyDeductionCandidate
1484 friend class CXXDeductionGuideDecl;
1485 /// For the bits in DeclContextBitfields.
1486 uint64_t : NumDeclContextBits;
1487
1488 uint64_t SClass : 3;
1489 uint64_t IsInline : 1;
1490 uint64_t IsInlineSpecified : 1;
1491
1492 uint64_t IsVirtualAsWritten : 1;
1493 uint64_t IsPure : 1;
1494 uint64_t HasInheritedPrototype : 1;
1495 uint64_t HasWrittenPrototype : 1;
1496 uint64_t IsDeleted : 1;
1497 /// Used by CXXMethodDecl
1498 uint64_t IsTrivial : 1;
1499
1500 /// This flag indicates whether this function is trivial for the purpose of
1501 /// calls. This is meaningful only when this function is a copy/move
1502 /// constructor or a destructor.
1503 uint64_t IsTrivialForCall : 1;
1504
1505 uint64_t IsDefaulted : 1;
1506 uint64_t IsExplicitlyDefaulted : 1;
1507 uint64_t HasDefaultedFunctionInfo : 1;
1508 uint64_t HasImplicitReturnZero : 1;
1509 uint64_t IsLateTemplateParsed : 1;
1510
1511 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1512 uint64_t ConstexprKind : 2;
1513 uint64_t InstantiationIsPending : 1;
1514
1515 /// Indicates if the function uses __try.
1516 uint64_t UsesSEHTry : 1;
1517
1518 /// Indicates if the function was a definition
1519 /// but its body was skipped.
1520 uint64_t HasSkippedBody : 1;
1521
1522 /// Indicates if the function declaration will
1523 /// have a body, once we're done parsing it.
1524 uint64_t WillHaveBody : 1;
1525
1526 /// Indicates that this function is a multiversioned
1527 /// function using attribute 'target'.
1528 uint64_t IsMultiVersion : 1;
1529
1530 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1531 /// the Deduction Guide is the implicitly generated 'copy
1532 /// deduction candidate' (is used during overload resolution).
1533 uint64_t IsCopyDeductionCandidate : 1;
1534
1535 /// Store the ODRHash after first calculation.
1536 uint64_t HasODRHash : 1;
1537
1538 /// Indicates if the function uses Floating Point Constrained Intrinsics
1539 uint64_t UsesFPIntrin : 1;
1540 };
1541
1542 /// Number of non-inherited bits in FunctionDeclBitfields.
1543 enum { NumFunctionDeclBits = 27 };
1544
1545 /// Stores the bits used by CXXConstructorDecl. If modified
1546 /// NumCXXConstructorDeclBits and the accessor
1547 /// methods in CXXConstructorDecl should be updated appropriately.
1548 class CXXConstructorDeclBitfields {
1549 friend class CXXConstructorDecl;
1550 /// For the bits in DeclContextBitfields.
1551 uint64_t : NumDeclContextBits;
1552 /// For the bits in FunctionDeclBitfields.
1553 uint64_t : NumFunctionDeclBits;
1554
1555 /// 24 bits to fit in the remaining available space.
1556 /// Note that this makes CXXConstructorDeclBitfields take
1557 /// exactly 64 bits and thus the width of NumCtorInitializers
1558 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1559 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1560 uint64_t NumCtorInitializers : 21;
1561 uint64_t IsInheritingConstructor : 1;
1562
1563 /// Whether this constructor has a trail-allocated explicit specifier.
1564 uint64_t HasTrailingExplicitSpecifier : 1;
1565 /// If this constructor does't have a trail-allocated explicit specifier.
1566 /// Whether this constructor is explicit specified.
1567 uint64_t IsSimpleExplicit : 1;
1568 };
1569
1570 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1571 enum {
1572 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1573 };
1574
1575 /// Stores the bits used by ObjCMethodDecl.
1576 /// If modified NumObjCMethodDeclBits and the accessor
1577 /// methods in ObjCMethodDecl should be updated appropriately.
1578 class ObjCMethodDeclBitfields {
1579 friend class ObjCMethodDecl;
1580
1581 /// For the bits in DeclContextBitfields.
1582 uint64_t : NumDeclContextBits;
1583
1584 /// The conventional meaning of this method; an ObjCMethodFamily.
1585 /// This is not serialized; instead, it is computed on demand and
1586 /// cached.
1587 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1588
1589 /// instance (true) or class (false) method.
1590 uint64_t IsInstance : 1;
1591 uint64_t IsVariadic : 1;
1592
1593 /// True if this method is the getter or setter for an explicit property.
1594 uint64_t IsPropertyAccessor : 1;
1595
1596 /// True if this method is a synthesized property accessor stub.
1597 uint64_t IsSynthesizedAccessorStub : 1;
1598
1599 /// Method has a definition.
1600 uint64_t IsDefined : 1;
1601
1602 /// Method redeclaration in the same interface.
1603 uint64_t IsRedeclaration : 1;
1604
1605 /// Is redeclared in the same interface.
1606 mutable uint64_t HasRedeclaration : 1;
1607
1608 /// \@required/\@optional
1609 uint64_t DeclImplementation : 2;
1610
1611 /// in, inout, etc.
1612 uint64_t objcDeclQualifier : 7;
1613
1614 /// Indicates whether this method has a related result type.
1615 uint64_t RelatedResultType : 1;
1616
1617 /// Whether the locations of the selector identifiers are in a
1618 /// "standard" position, a enum SelectorLocationsKind.
1619 uint64_t SelLocsKind : 2;
1620
1621 /// Whether this method overrides any other in the class hierarchy.
1622 ///
1623 /// A method is said to override any method in the class's
1624 /// base classes, its protocols, or its categories' protocols, that has
1625 /// the same selector and is of the same kind (class or instance).
1626 /// A method in an implementation is not considered as overriding the same
1627 /// method in the interface or its categories.
1628 uint64_t IsOverriding : 1;
1629
1630 /// Indicates if the method was a definition but its body was skipped.
1631 uint64_t HasSkippedBody : 1;
1632 };
1633
1634 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1635 enum { NumObjCMethodDeclBits = 24 };
1636
1637 /// Stores the bits used by ObjCContainerDecl.
1638 /// If modified NumObjCContainerDeclBits and the accessor
1639 /// methods in ObjCContainerDecl should be updated appropriately.
1640 class ObjCContainerDeclBitfields {
1641 friend class ObjCContainerDecl;
1642 /// For the bits in DeclContextBitfields
1643 uint32_t : NumDeclContextBits;
1644
1645 // Not a bitfield but this saves space.
1646 // Note that ObjCContainerDeclBitfields is full.
1647 SourceLocation AtStart;
1648 };
1649
1650 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1651 /// Note that here we rely on the fact that SourceLocation is 32 bits
1652 /// wide. We check this with the static_assert in the ctor of DeclContext.
1653 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1654
1655 /// Stores the bits used by LinkageSpecDecl.
1656 /// If modified NumLinkageSpecDeclBits and the accessor
1657 /// methods in LinkageSpecDecl should be updated appropriately.
1658 class LinkageSpecDeclBitfields {
1659 friend class LinkageSpecDecl;
1660 /// For the bits in DeclContextBitfields.
1661 uint64_t : NumDeclContextBits;
1662
1663 /// The language for this linkage specification with values
1664 /// in the enum LinkageSpecDecl::LanguageIDs.
1665 uint64_t Language : 3;
1666
1667 /// True if this linkage spec has braces.
1668 /// This is needed so that hasBraces() returns the correct result while the
1669 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1670 /// not used, so it doesn't need to be serialized.
1671 uint64_t HasBraces : 1;
1672 };
1673
1674 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1675 enum { NumLinkageSpecDeclBits = 4 };
1676
1677 /// Stores the bits used by BlockDecl.
1678 /// If modified NumBlockDeclBits and the accessor
1679 /// methods in BlockDecl should be updated appropriately.
1680 class BlockDeclBitfields {
1681 friend class BlockDecl;
1682 /// For the bits in DeclContextBitfields.
1683 uint64_t : NumDeclContextBits;
1684
1685 uint64_t IsVariadic : 1;
1686 uint64_t CapturesCXXThis : 1;
1687 uint64_t BlockMissingReturnType : 1;
1688 uint64_t IsConversionFromLambda : 1;
1689
1690 /// A bit that indicates this block is passed directly to a function as a
1691 /// non-escaping parameter.
1692 uint64_t DoesNotEscape : 1;
1693
1694 /// A bit that indicates whether it's possible to avoid coying this block to
1695 /// the heap when it initializes or is assigned to a local variable with
1696 /// automatic storage.
1697 uint64_t CanAvoidCopyToHeap : 1;
1698 };
1699
1700 /// Number of non-inherited bits in BlockDeclBitfields.
1701 enum { NumBlockDeclBits = 5 };
1702
1703 /// Pointer to the data structure used to lookup declarations
1704 /// within this context (or a DependentStoredDeclsMap if this is a
1705 /// dependent context). We maintain the invariant that, if the map
1706 /// contains an entry for a DeclarationName (and we haven't lazily
1707 /// omitted anything), then it contains all relevant entries for that
1708 /// name (modulo the hasExternalDecls() flag).
1709 mutable StoredDeclsMap *LookupPtr = nullptr;
1710
1711 protected:
1712 /// This anonymous union stores the bits belonging to DeclContext and classes
1713 /// deriving from it. The goal is to use otherwise wasted
1714 /// space in DeclContext to store data belonging to derived classes.
1715 /// The space saved is especially significient when pointers are aligned
1716 /// to 8 bytes. In this case due to alignment requirements we have a
1717 /// little less than 8 bytes free in DeclContext which we can use.
1718 /// We check that none of the classes in this union is larger than
1719 /// 8 bytes with static_asserts in the ctor of DeclContext.
1720 union {
1721 DeclContextBitfields DeclContextBits;
1722 TagDeclBitfields TagDeclBits;
1723 EnumDeclBitfields EnumDeclBits;
1724 RecordDeclBitfields RecordDeclBits;
1725 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1726 FunctionDeclBitfields FunctionDeclBits;
1727 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1728 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1729 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1730 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1731 BlockDeclBitfields BlockDeclBits;
1732
1733 static_assert(sizeof(DeclContextBitfields) <= 8,
1734 "DeclContextBitfields is larger than 8 bytes!");
1735 static_assert(sizeof(TagDeclBitfields) <= 8,
1736 "TagDeclBitfields is larger than 8 bytes!");
1737 static_assert(sizeof(EnumDeclBitfields) <= 8,
1738 "EnumDeclBitfields is larger than 8 bytes!");
1739 static_assert(sizeof(RecordDeclBitfields) <= 8,
1740 "RecordDeclBitfields is larger than 8 bytes!");
1741 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1742 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1743 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1744 "FunctionDeclBitfields is larger than 8 bytes!");
1745 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1746 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1747 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1748 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1749 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1750 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1751 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1752 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1753 static_assert(sizeof(BlockDeclBitfields) <= 8,
1754 "BlockDeclBitfields is larger than 8 bytes!");
1755 };
1756
1757 /// FirstDecl - The first declaration stored within this declaration
1758 /// context.
1759 mutable Decl *FirstDecl = nullptr;
1760
1761 /// LastDecl - The last declaration stored within this declaration
1762 /// context. FIXME: We could probably cache this value somewhere
1763 /// outside of the DeclContext, to reduce the size of DeclContext by
1764 /// another pointer.
1765 mutable Decl *LastDecl = nullptr;
1766
1767 /// Build up a chain of declarations.
1768 ///
1769 /// \returns the first/last pair of declarations.
1770 static std::pair<Decl *, Decl *>
1771 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1772
1773 DeclContext(Decl::Kind K);
1774
1775 public:
1776 ~DeclContext();
1777
getDeclKind()1778 Decl::Kind getDeclKind() const {
1779 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1780 }
1781
1782 const char *getDeclKindName() const;
1783
1784 /// getParent - Returns the containing DeclContext.
getParent()1785 DeclContext *getParent() {
1786 return cast<Decl>(this)->getDeclContext();
1787 }
getParent()1788 const DeclContext *getParent() const {
1789 return const_cast<DeclContext*>(this)->getParent();
1790 }
1791
1792 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1793 /// different from getParent, e.g.:
1794 ///
1795 /// namespace A {
1796 /// struct S;
1797 /// }
1798 /// struct A::S {}; // getParent() == namespace 'A'
1799 /// // getLexicalParent() == translation unit
1800 ///
getLexicalParent()1801 DeclContext *getLexicalParent() {
1802 return cast<Decl>(this)->getLexicalDeclContext();
1803 }
getLexicalParent()1804 const DeclContext *getLexicalParent() const {
1805 return const_cast<DeclContext*>(this)->getLexicalParent();
1806 }
1807
1808 DeclContext *getLookupParent();
1809
getLookupParent()1810 const DeclContext *getLookupParent() const {
1811 return const_cast<DeclContext*>(this)->getLookupParent();
1812 }
1813
getParentASTContext()1814 ASTContext &getParentASTContext() const {
1815 return cast<Decl>(this)->getASTContext();
1816 }
1817
isClosure()1818 bool isClosure() const { return getDeclKind() == Decl::Block; }
1819
1820 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1821 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1822 const BlockDecl *getInnermostBlockDecl() const;
1823
isObjCContainer()1824 bool isObjCContainer() const {
1825 switch (getDeclKind()) {
1826 case Decl::ObjCCategory:
1827 case Decl::ObjCCategoryImpl:
1828 case Decl::ObjCImplementation:
1829 case Decl::ObjCInterface:
1830 case Decl::ObjCProtocol:
1831 return true;
1832 default:
1833 return false;
1834 }
1835 }
1836
isFunctionOrMethod()1837 bool isFunctionOrMethod() const {
1838 switch (getDeclKind()) {
1839 case Decl::Block:
1840 case Decl::Captured:
1841 case Decl::ObjCMethod:
1842 return true;
1843 default:
1844 return getDeclKind() >= Decl::firstFunction &&
1845 getDeclKind() <= Decl::lastFunction;
1846 }
1847 }
1848
1849 /// Test whether the context supports looking up names.
isLookupContext()1850 bool isLookupContext() const {
1851 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1852 getDeclKind() != Decl::Export;
1853 }
1854
isFileContext()1855 bool isFileContext() const {
1856 return getDeclKind() == Decl::TranslationUnit ||
1857 getDeclKind() == Decl::Namespace;
1858 }
1859
isTranslationUnit()1860 bool isTranslationUnit() const {
1861 return getDeclKind() == Decl::TranslationUnit;
1862 }
1863
isRecord()1864 bool isRecord() const {
1865 return getDeclKind() >= Decl::firstRecord &&
1866 getDeclKind() <= Decl::lastRecord;
1867 }
1868
isNamespace()1869 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1870
1871 bool isStdNamespace() const;
1872
1873 bool isInlineNamespace() const;
1874
1875 /// Determines whether this context is dependent on a
1876 /// template parameter.
1877 bool isDependentContext() const;
1878
1879 /// isTransparentContext - Determines whether this context is a
1880 /// "transparent" context, meaning that the members declared in this
1881 /// context are semantically declared in the nearest enclosing
1882 /// non-transparent (opaque) context but are lexically declared in
1883 /// this context. For example, consider the enumerators of an
1884 /// enumeration type:
1885 /// @code
1886 /// enum E {
1887 /// Val1
1888 /// };
1889 /// @endcode
1890 /// Here, E is a transparent context, so its enumerator (Val1) will
1891 /// appear (semantically) that it is in the same context of E.
1892 /// Examples of transparent contexts include: enumerations (except for
1893 /// C++0x scoped enums), and C++ linkage specifications.
1894 bool isTransparentContext() const;
1895
1896 /// Determines whether this context or some of its ancestors is a
1897 /// linkage specification context that specifies C linkage.
1898 bool isExternCContext() const;
1899
1900 /// Retrieve the nearest enclosing C linkage specification context.
1901 const LinkageSpecDecl *getExternCContext() const;
1902
1903 /// Determines whether this context or some of its ancestors is a
1904 /// linkage specification context that specifies C++ linkage.
1905 bool isExternCXXContext() const;
1906
1907 /// Determine whether this declaration context is equivalent
1908 /// to the declaration context DC.
Equals(const DeclContext * DC)1909 bool Equals(const DeclContext *DC) const {
1910 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1911 }
1912
1913 /// Determine whether this declaration context encloses the
1914 /// declaration context DC.
1915 bool Encloses(const DeclContext *DC) const;
1916
1917 /// Find the nearest non-closure ancestor of this context,
1918 /// i.e. the innermost semantic parent of this context which is not
1919 /// a closure. A context may be its own non-closure ancestor.
1920 Decl *getNonClosureAncestor();
getNonClosureAncestor()1921 const Decl *getNonClosureAncestor() const {
1922 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1923 }
1924
1925 /// getPrimaryContext - There may be many different
1926 /// declarations of the same entity (including forward declarations
1927 /// of classes, multiple definitions of namespaces, etc.), each with
1928 /// a different set of declarations. This routine returns the
1929 /// "primary" DeclContext structure, which will contain the
1930 /// information needed to perform name lookup into this context.
1931 DeclContext *getPrimaryContext();
getPrimaryContext()1932 const DeclContext *getPrimaryContext() const {
1933 return const_cast<DeclContext*>(this)->getPrimaryContext();
1934 }
1935
1936 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1937 /// other entities of the same name, or where it is a redeclaration if the
1938 /// two entities are compatible. This skips through transparent contexts.
1939 DeclContext *getRedeclContext();
getRedeclContext()1940 const DeclContext *getRedeclContext() const {
1941 return const_cast<DeclContext *>(this)->getRedeclContext();
1942 }
1943
1944 /// Retrieve the nearest enclosing namespace context.
1945 DeclContext *getEnclosingNamespaceContext();
getEnclosingNamespaceContext()1946 const DeclContext *getEnclosingNamespaceContext() const {
1947 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1948 }
1949
1950 /// Retrieve the outermost lexically enclosing record context.
1951 RecordDecl *getOuterLexicalRecordContext();
getOuterLexicalRecordContext()1952 const RecordDecl *getOuterLexicalRecordContext() const {
1953 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1954 }
1955
1956 /// Test if this context is part of the enclosing namespace set of
1957 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1958 /// isn't a namespace, this is equivalent to Equals().
1959 ///
1960 /// The enclosing namespace set of a namespace is the namespace and, if it is
1961 /// inline, its enclosing namespace, recursively.
1962 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1963
1964 /// Collects all of the declaration contexts that are semantically
1965 /// connected to this declaration context.
1966 ///
1967 /// For declaration contexts that have multiple semantically connected but
1968 /// syntactically distinct contexts, such as C++ namespaces, this routine
1969 /// retrieves the complete set of such declaration contexts in source order.
1970 /// For example, given:
1971 ///
1972 /// \code
1973 /// namespace N {
1974 /// int x;
1975 /// }
1976 /// namespace N {
1977 /// int y;
1978 /// }
1979 /// \endcode
1980 ///
1981 /// The \c Contexts parameter will contain both definitions of N.
1982 ///
1983 /// \param Contexts Will be cleared and set to the set of declaration
1984 /// contexts that are semanticaly connected to this declaration context,
1985 /// in source order, including this context (which may be the only result,
1986 /// for non-namespace contexts).
1987 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1988
1989 /// decl_iterator - Iterates through the declarations stored
1990 /// within this context.
1991 class decl_iterator {
1992 /// Current - The current declaration.
1993 Decl *Current = nullptr;
1994
1995 public:
1996 using value_type = Decl *;
1997 using reference = const value_type &;
1998 using pointer = const value_type *;
1999 using iterator_category = std::forward_iterator_tag;
2000 using difference_type = std::ptrdiff_t;
2001
2002 decl_iterator() = default;
decl_iterator(Decl * C)2003 explicit decl_iterator(Decl *C) : Current(C) {}
2004
2005 reference operator*() const { return Current; }
2006
2007 // This doesn't meet the iterator requirements, but it's convenient
2008 value_type operator->() const { return Current; }
2009
2010 decl_iterator& operator++() {
2011 Current = Current->getNextDeclInContext();
2012 return *this;
2013 }
2014
2015 decl_iterator operator++(int) {
2016 decl_iterator tmp(*this);
2017 ++(*this);
2018 return tmp;
2019 }
2020
2021 friend bool operator==(decl_iterator x, decl_iterator y) {
2022 return x.Current == y.Current;
2023 }
2024
2025 friend bool operator!=(decl_iterator x, decl_iterator y) {
2026 return x.Current != y.Current;
2027 }
2028 };
2029
2030 using decl_range = llvm::iterator_range<decl_iterator>;
2031
2032 /// decls_begin/decls_end - Iterate over the declarations stored in
2033 /// this context.
decls()2034 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2035 decl_iterator decls_begin() const;
decls_end()2036 decl_iterator decls_end() const { return decl_iterator(); }
2037 bool decls_empty() const;
2038
2039 /// noload_decls_begin/end - Iterate over the declarations stored in this
2040 /// context that are currently loaded; don't attempt to retrieve anything
2041 /// from an external source.
noload_decls()2042 decl_range noload_decls() const {
2043 return decl_range(noload_decls_begin(), noload_decls_end());
2044 }
noload_decls_begin()2045 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
noload_decls_end()2046 decl_iterator noload_decls_end() const { return decl_iterator(); }
2047
2048 /// specific_decl_iterator - Iterates over a subrange of
2049 /// declarations stored in a DeclContext, providing only those that
2050 /// are of type SpecificDecl (or a class derived from it). This
2051 /// iterator is used, for example, to provide iteration over just
2052 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2053 template<typename SpecificDecl>
2054 class specific_decl_iterator {
2055 /// Current - The current, underlying declaration iterator, which
2056 /// will either be NULL or will point to a declaration of
2057 /// type SpecificDecl.
2058 DeclContext::decl_iterator Current;
2059
2060 /// SkipToNextDecl - Advances the current position up to the next
2061 /// declaration of type SpecificDecl that also meets the criteria
2062 /// required by Acceptable.
SkipToNextDecl()2063 void SkipToNextDecl() {
2064 while (*Current && !isa<SpecificDecl>(*Current))
2065 ++Current;
2066 }
2067
2068 public:
2069 using value_type = SpecificDecl *;
2070 // TODO: Add reference and pointer types (with some appropriate proxy type)
2071 // if we ever have a need for them.
2072 using reference = void;
2073 using pointer = void;
2074 using difference_type =
2075 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2076 using iterator_category = std::forward_iterator_tag;
2077
2078 specific_decl_iterator() = default;
2079
2080 /// specific_decl_iterator - Construct a new iterator over a
2081 /// subset of the declarations the range [C,
2082 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2083 /// member function of SpecificDecl that should return true for
2084 /// all of the SpecificDecl instances that will be in the subset
2085 /// of iterators. For example, if you want Objective-C instance
2086 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2087 /// &ObjCMethodDecl::isInstanceMethod.
specific_decl_iterator(DeclContext::decl_iterator C)2088 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2089 SkipToNextDecl();
2090 }
2091
2092 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2093
2094 // This doesn't meet the iterator requirements, but it's convenient
2095 value_type operator->() const { return **this; }
2096
2097 specific_decl_iterator& operator++() {
2098 ++Current;
2099 SkipToNextDecl();
2100 return *this;
2101 }
2102
2103 specific_decl_iterator operator++(int) {
2104 specific_decl_iterator tmp(*this);
2105 ++(*this);
2106 return tmp;
2107 }
2108
2109 friend bool operator==(const specific_decl_iterator& x,
2110 const specific_decl_iterator& y) {
2111 return x.Current == y.Current;
2112 }
2113
2114 friend bool operator!=(const specific_decl_iterator& x,
2115 const specific_decl_iterator& y) {
2116 return x.Current != y.Current;
2117 }
2118 };
2119
2120 /// Iterates over a filtered subrange of declarations stored
2121 /// in a DeclContext.
2122 ///
2123 /// This iterator visits only those declarations that are of type
2124 /// SpecificDecl (or a class derived from it) and that meet some
2125 /// additional run-time criteria. This iterator is used, for
2126 /// example, to provide access to the instance methods within an
2127 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2128 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2129 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2130 class filtered_decl_iterator {
2131 /// Current - The current, underlying declaration iterator, which
2132 /// will either be NULL or will point to a declaration of
2133 /// type SpecificDecl.
2134 DeclContext::decl_iterator Current;
2135
2136 /// SkipToNextDecl - Advances the current position up to the next
2137 /// declaration of type SpecificDecl that also meets the criteria
2138 /// required by Acceptable.
SkipToNextDecl()2139 void SkipToNextDecl() {
2140 while (*Current &&
2141 (!isa<SpecificDecl>(*Current) ||
2142 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2143 ++Current;
2144 }
2145
2146 public:
2147 using value_type = SpecificDecl *;
2148 // TODO: Add reference and pointer types (with some appropriate proxy type)
2149 // if we ever have a need for them.
2150 using reference = void;
2151 using pointer = void;
2152 using difference_type =
2153 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2154 using iterator_category = std::forward_iterator_tag;
2155
2156 filtered_decl_iterator() = default;
2157
2158 /// filtered_decl_iterator - Construct a new iterator over a
2159 /// subset of the declarations the range [C,
2160 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2161 /// member function of SpecificDecl that should return true for
2162 /// all of the SpecificDecl instances that will be in the subset
2163 /// of iterators. For example, if you want Objective-C instance
2164 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2165 /// &ObjCMethodDecl::isInstanceMethod.
filtered_decl_iterator(DeclContext::decl_iterator C)2166 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2167 SkipToNextDecl();
2168 }
2169
2170 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2171 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2172
2173 filtered_decl_iterator& operator++() {
2174 ++Current;
2175 SkipToNextDecl();
2176 return *this;
2177 }
2178
2179 filtered_decl_iterator operator++(int) {
2180 filtered_decl_iterator tmp(*this);
2181 ++(*this);
2182 return tmp;
2183 }
2184
2185 friend bool operator==(const filtered_decl_iterator& x,
2186 const filtered_decl_iterator& y) {
2187 return x.Current == y.Current;
2188 }
2189
2190 friend bool operator!=(const filtered_decl_iterator& x,
2191 const filtered_decl_iterator& y) {
2192 return x.Current != y.Current;
2193 }
2194 };
2195
2196 /// Add the declaration D into this context.
2197 ///
2198 /// This routine should be invoked when the declaration D has first
2199 /// been declared, to place D into the context where it was
2200 /// (lexically) defined. Every declaration must be added to one
2201 /// (and only one!) context, where it can be visited via
2202 /// [decls_begin(), decls_end()). Once a declaration has been added
2203 /// to its lexical context, the corresponding DeclContext owns the
2204 /// declaration.
2205 ///
2206 /// If D is also a NamedDecl, it will be made visible within its
2207 /// semantic context via makeDeclVisibleInContext.
2208 void addDecl(Decl *D);
2209
2210 /// Add the declaration D into this context, but suppress
2211 /// searches for external declarations with the same name.
2212 ///
2213 /// Although analogous in function to addDecl, this removes an
2214 /// important check. This is only useful if the Decl is being
2215 /// added in response to an external search; in all other cases,
2216 /// addDecl() is the right function to use.
2217 /// See the ASTImporter for use cases.
2218 void addDeclInternal(Decl *D);
2219
2220 /// Add the declaration D to this context without modifying
2221 /// any lookup tables.
2222 ///
2223 /// This is useful for some operations in dependent contexts where
2224 /// the semantic context might not be dependent; this basically
2225 /// only happens with friends.
2226 void addHiddenDecl(Decl *D);
2227
2228 /// Removes a declaration from this context.
2229 void removeDecl(Decl *D);
2230
2231 /// Checks whether a declaration is in this context.
2232 bool containsDecl(Decl *D) const;
2233
2234 /// Checks whether a declaration is in this context.
2235 /// This also loads the Decls from the external source before the check.
2236 bool containsDeclAndLoad(Decl *D) const;
2237
2238 using lookup_result = DeclContextLookupResult;
2239 using lookup_iterator = lookup_result::iterator;
2240
2241 /// lookup - Find the declarations (if any) with the given Name in
2242 /// this context. Returns a range of iterators that contains all of
2243 /// the declarations with this name, with object, function, member,
2244 /// and enumerator names preceding any tag name. Note that this
2245 /// routine will not look into parent contexts.
2246 lookup_result lookup(DeclarationName Name) const;
2247
2248 /// Find the declarations with the given name that are visible
2249 /// within this context; don't attempt to retrieve anything from an
2250 /// external source.
2251 lookup_result noload_lookup(DeclarationName Name);
2252
2253 /// A simplistic name lookup mechanism that performs name lookup
2254 /// into this declaration context without consulting the external source.
2255 ///
2256 /// This function should almost never be used, because it subverts the
2257 /// usual relationship between a DeclContext and the external source.
2258 /// See the ASTImporter for the (few, but important) use cases.
2259 ///
2260 /// FIXME: This is very inefficient; replace uses of it with uses of
2261 /// noload_lookup.
2262 void localUncachedLookup(DeclarationName Name,
2263 SmallVectorImpl<NamedDecl *> &Results);
2264
2265 /// Makes a declaration visible within this context.
2266 ///
2267 /// This routine makes the declaration D visible to name lookup
2268 /// within this context and, if this is a transparent context,
2269 /// within its parent contexts up to the first enclosing
2270 /// non-transparent context. Making a declaration visible within a
2271 /// context does not transfer ownership of a declaration, and a
2272 /// declaration can be visible in many contexts that aren't its
2273 /// lexical context.
2274 ///
2275 /// If D is a redeclaration of an existing declaration that is
2276 /// visible from this context, as determined by
2277 /// NamedDecl::declarationReplaces, the previous declaration will be
2278 /// replaced with D.
2279 void makeDeclVisibleInContext(NamedDecl *D);
2280
2281 /// all_lookups_iterator - An iterator that provides a view over the results
2282 /// of looking up every possible name.
2283 class all_lookups_iterator;
2284
2285 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2286
2287 lookups_range lookups() const;
2288 // Like lookups(), but avoids loading external declarations.
2289 // If PreserveInternalState, avoids building lookup data structures too.
2290 lookups_range noload_lookups(bool PreserveInternalState) const;
2291
2292 /// Iterators over all possible lookups within this context.
2293 all_lookups_iterator lookups_begin() const;
2294 all_lookups_iterator lookups_end() const;
2295
2296 /// Iterators over all possible lookups within this context that are
2297 /// currently loaded; don't attempt to retrieve anything from an external
2298 /// source.
2299 all_lookups_iterator noload_lookups_begin() const;
2300 all_lookups_iterator noload_lookups_end() const;
2301
2302 struct udir_iterator;
2303
2304 using udir_iterator_base =
2305 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2306 std::random_access_iterator_tag,
2307 UsingDirectiveDecl *>;
2308
2309 struct udir_iterator : udir_iterator_base {
udir_iteratorudir_iterator2310 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2311
2312 UsingDirectiveDecl *operator*() const;
2313 };
2314
2315 using udir_range = llvm::iterator_range<udir_iterator>;
2316
2317 udir_range using_directives() const;
2318
2319 // These are all defined in DependentDiagnostic.h.
2320 class ddiag_iterator;
2321
2322 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2323
2324 inline ddiag_range ddiags() const;
2325
2326 // Low-level accessors
2327
2328 /// Mark that there are external lexical declarations that we need
2329 /// to include in our lookup table (and that are not available as external
2330 /// visible lookups). These extra lookup results will be found by walking
2331 /// the lexical declarations of this context. This should be used only if
2332 /// setHasExternalLexicalStorage() has been called on any decl context for
2333 /// which this is the primary context.
setMustBuildLookupTable()2334 void setMustBuildLookupTable() {
2335 assert(this == getPrimaryContext() &&
2336 "should only be called on primary context");
2337 DeclContextBits.HasLazyExternalLexicalLookups = true;
2338 }
2339
2340 /// Retrieve the internal representation of the lookup structure.
2341 /// This may omit some names if we are lazily building the structure.
getLookupPtr()2342 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2343
2344 /// Ensure the lookup structure is fully-built and return it.
2345 StoredDeclsMap *buildLookup();
2346
2347 /// Whether this DeclContext has external storage containing
2348 /// additional declarations that are lexically in this context.
hasExternalLexicalStorage()2349 bool hasExternalLexicalStorage() const {
2350 return DeclContextBits.ExternalLexicalStorage;
2351 }
2352
2353 /// State whether this DeclContext has external storage for
2354 /// declarations lexically in this context.
2355 void setHasExternalLexicalStorage(bool ES = true) const {
2356 DeclContextBits.ExternalLexicalStorage = ES;
2357 }
2358
2359 /// Whether this DeclContext has external storage containing
2360 /// additional declarations that are visible in this context.
hasExternalVisibleStorage()2361 bool hasExternalVisibleStorage() const {
2362 return DeclContextBits.ExternalVisibleStorage;
2363 }
2364
2365 /// State whether this DeclContext has external storage for
2366 /// declarations visible in this context.
2367 void setHasExternalVisibleStorage(bool ES = true) const {
2368 DeclContextBits.ExternalVisibleStorage = ES;
2369 if (ES && LookupPtr)
2370 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2371 }
2372
2373 /// Determine whether the given declaration is stored in the list of
2374 /// declarations lexically within this context.
isDeclInLexicalTraversal(const Decl * D)2375 bool isDeclInLexicalTraversal(const Decl *D) const {
2376 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2377 D == LastDecl);
2378 }
2379
2380 bool setUseQualifiedLookup(bool use = true) const {
2381 bool old_value = DeclContextBits.UseQualifiedLookup;
2382 DeclContextBits.UseQualifiedLookup = use;
2383 return old_value;
2384 }
2385
shouldUseQualifiedLookup()2386 bool shouldUseQualifiedLookup() const {
2387 return DeclContextBits.UseQualifiedLookup;
2388 }
2389
2390 static bool classof(const Decl *D);
classof(const DeclContext * D)2391 static bool classof(const DeclContext *D) { return true; }
2392
2393 void dumpDeclContext() const;
2394 void dumpLookups() const;
2395 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2396 bool Deserialize = false) const;
2397
2398 private:
2399 /// Whether this declaration context has had externally visible
2400 /// storage added since the last lookup. In this case, \c LookupPtr's
2401 /// invariant may not hold and needs to be fixed before we perform
2402 /// another lookup.
hasNeedToReconcileExternalVisibleStorage()2403 bool hasNeedToReconcileExternalVisibleStorage() const {
2404 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2405 }
2406
2407 /// State that this declaration context has had externally visible
2408 /// storage added since the last lookup. In this case, \c LookupPtr's
2409 /// invariant may not hold and needs to be fixed before we perform
2410 /// another lookup.
2411 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2412 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2413 }
2414
2415 /// If \c true, this context may have local lexical declarations
2416 /// that are missing from the lookup table.
hasLazyLocalLexicalLookups()2417 bool hasLazyLocalLexicalLookups() const {
2418 return DeclContextBits.HasLazyLocalLexicalLookups;
2419 }
2420
2421 /// If \c true, this context may have local lexical declarations
2422 /// that are missing from the lookup table.
2423 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2424 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2425 }
2426
2427 /// If \c true, the external source may have lexical declarations
2428 /// that are missing from the lookup table.
hasLazyExternalLexicalLookups()2429 bool hasLazyExternalLexicalLookups() const {
2430 return DeclContextBits.HasLazyExternalLexicalLookups;
2431 }
2432
2433 /// If \c true, the external source may have lexical declarations
2434 /// that are missing from the lookup table.
2435 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2436 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2437 }
2438
2439 void reconcileExternalVisibleStorage() const;
2440 bool LoadLexicalDeclsFromExternalStorage() const;
2441
2442 /// Makes a declaration visible within this context, but
2443 /// suppresses searches for external declarations with the same
2444 /// name.
2445 ///
2446 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2447 /// use of addDeclInternal().
2448 void makeDeclVisibleInContextInternal(NamedDecl *D);
2449
2450 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2451
2452 void loadLazyLocalLexicalLookups();
2453 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2454 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2455 bool Rediscoverable);
2456 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2457 };
2458
isTemplateParameter()2459 inline bool Decl::isTemplateParameter() const {
2460 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2461 getKind() == TemplateTemplateParm;
2462 }
2463
2464 // Specialization selected when ToTy is not a known subclass of DeclContext.
2465 template <class ToTy,
2466 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2467 struct cast_convert_decl_context {
doitcast_convert_decl_context2468 static const ToTy *doit(const DeclContext *Val) {
2469 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2470 }
2471
doitcast_convert_decl_context2472 static ToTy *doit(DeclContext *Val) {
2473 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2474 }
2475 };
2476
2477 // Specialization selected when ToTy is a known subclass of DeclContext.
2478 template <class ToTy>
2479 struct cast_convert_decl_context<ToTy, true> {
2480 static const ToTy *doit(const DeclContext *Val) {
2481 return static_cast<const ToTy*>(Val);
2482 }
2483
2484 static ToTy *doit(DeclContext *Val) {
2485 return static_cast<ToTy*>(Val);
2486 }
2487 };
2488
2489 } // namespace clang
2490
2491 namespace llvm {
2492
2493 /// isa<T>(DeclContext*)
2494 template <typename To>
2495 struct isa_impl<To, ::clang::DeclContext> {
2496 static bool doit(const ::clang::DeclContext &Val) {
2497 return To::classofKind(Val.getDeclKind());
2498 }
2499 };
2500
2501 /// cast<T>(DeclContext*)
2502 template<class ToTy>
2503 struct cast_convert_val<ToTy,
2504 const ::clang::DeclContext,const ::clang::DeclContext> {
2505 static const ToTy &doit(const ::clang::DeclContext &Val) {
2506 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2507 }
2508 };
2509
2510 template<class ToTy>
2511 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2512 static ToTy &doit(::clang::DeclContext &Val) {
2513 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2514 }
2515 };
2516
2517 template<class ToTy>
2518 struct cast_convert_val<ToTy,
2519 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2520 static const ToTy *doit(const ::clang::DeclContext *Val) {
2521 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2522 }
2523 };
2524
2525 template<class ToTy>
2526 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2527 static ToTy *doit(::clang::DeclContext *Val) {
2528 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2529 }
2530 };
2531
2532 /// Implement cast_convert_val for Decl -> DeclContext conversions.
2533 template<class FromTy>
2534 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2535 static ::clang::DeclContext &doit(const FromTy &Val) {
2536 return *FromTy::castToDeclContext(&Val);
2537 }
2538 };
2539
2540 template<class FromTy>
2541 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2542 static ::clang::DeclContext *doit(const FromTy *Val) {
2543 return FromTy::castToDeclContext(Val);
2544 }
2545 };
2546
2547 template<class FromTy>
2548 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2549 static const ::clang::DeclContext &doit(const FromTy &Val) {
2550 return *FromTy::castToDeclContext(&Val);
2551 }
2552 };
2553
2554 template<class FromTy>
2555 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2556 static const ::clang::DeclContext *doit(const FromTy *Val) {
2557 return FromTy::castToDeclContext(Val);
2558 }
2559 };
2560
2561 } // namespace llvm
2562
2563 #endif // LLVM_CLANG_AST_DECLBASE_H
2564