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