Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:31

0001 //===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 //  This file defines the Decl and DeclContext interfaces.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_CLANG_AST_DECLBASE_H
0014 #define LLVM_CLANG_AST_DECLBASE_H
0015 
0016 #include "clang/AST/ASTDumperUtils.h"
0017 #include "clang/AST/AttrIterator.h"
0018 #include "clang/AST/DeclID.h"
0019 #include "clang/AST/DeclarationName.h"
0020 #include "clang/AST/SelectorLocationsKind.h"
0021 #include "clang/Basic/IdentifierTable.h"
0022 #include "clang/Basic/LLVM.h"
0023 #include "clang/Basic/LangOptions.h"
0024 #include "clang/Basic/SourceLocation.h"
0025 #include "clang/Basic/Specifiers.h"
0026 #include "llvm/ADT/ArrayRef.h"
0027 #include "llvm/ADT/PointerIntPair.h"
0028 #include "llvm/ADT/PointerUnion.h"
0029 #include "llvm/ADT/iterator.h"
0030 #include "llvm/ADT/iterator_range.h"
0031 #include "llvm/Support/Casting.h"
0032 #include "llvm/Support/Compiler.h"
0033 #include "llvm/Support/PrettyStackTrace.h"
0034 #include "llvm/Support/VersionTuple.h"
0035 #include <algorithm>
0036 #include <cassert>
0037 #include <cstddef>
0038 #include <iterator>
0039 #include <string>
0040 #include <type_traits>
0041 #include <utility>
0042 
0043 namespace clang {
0044 
0045 class ASTContext;
0046 class ASTMutationListener;
0047 class Attr;
0048 class BlockDecl;
0049 class DeclContext;
0050 class ExternalSourceSymbolAttr;
0051 class FunctionDecl;
0052 class FunctionType;
0053 class IdentifierInfo;
0054 enum class Linkage : unsigned char;
0055 class LinkageSpecDecl;
0056 class Module;
0057 class NamedDecl;
0058 class ObjCContainerDecl;
0059 class ObjCMethodDecl;
0060 struct PrintingPolicy;
0061 class RecordDecl;
0062 class SourceManager;
0063 class Stmt;
0064 class StoredDeclsMap;
0065 class TemplateDecl;
0066 class TemplateParameterList;
0067 class TranslationUnitDecl;
0068 class UsingDirectiveDecl;
0069 
0070 /// Captures the result of checking the availability of a
0071 /// declaration.
0072 enum AvailabilityResult {
0073   AR_Available = 0,
0074   AR_NotYetIntroduced,
0075   AR_Deprecated,
0076   AR_Unavailable
0077 };
0078 
0079 /// Decl - This represents one declaration (or definition), e.g. a variable,
0080 /// typedef, function, struct, etc.
0081 ///
0082 /// Note: There are objects tacked on before the *beginning* of Decl
0083 /// (and its subclasses) in its Decl::operator new(). Proper alignment
0084 /// of all subclasses (not requiring more than the alignment of Decl) is
0085 /// asserted in DeclBase.cpp.
0086 class alignas(8) Decl {
0087 public:
0088   /// Lists the kind of concrete classes of Decl.
0089   enum Kind {
0090 #define DECL(DERIVED, BASE) DERIVED,
0091 #define ABSTRACT_DECL(DECL)
0092 #define DECL_RANGE(BASE, START, END) \
0093         first##BASE = START, last##BASE = END,
0094 #define LAST_DECL_RANGE(BASE, START, END) \
0095         first##BASE = START, last##BASE = END
0096 #include "clang/AST/DeclNodes.inc"
0097   };
0098 
0099   /// A placeholder type used to construct an empty shell of a
0100   /// decl-derived type that will be filled in later (e.g., by some
0101   /// deserialization method).
0102   struct EmptyShell {};
0103 
0104   /// IdentifierNamespace - The different namespaces in which
0105   /// declarations may appear.  According to C99 6.2.3, there are
0106   /// four namespaces, labels, tags, members and ordinary
0107   /// identifiers.  C++ describes lookup completely differently:
0108   /// certain lookups merely "ignore" certain kinds of declarations,
0109   /// usually based on whether the declaration is of a type, etc.
0110   ///
0111   /// These are meant as bitmasks, so that searches in
0112   /// C++ can look into the "tag" namespace during ordinary lookup.
0113   ///
0114   /// Decl currently provides 15 bits of IDNS bits.
0115   enum IdentifierNamespace {
0116     /// Labels, declared with 'x:' and referenced with 'goto x'.
0117     IDNS_Label               = 0x0001,
0118 
0119     /// Tags, declared with 'struct foo;' and referenced with
0120     /// 'struct foo'.  All tags are also types.  This is what
0121     /// elaborated-type-specifiers look for in C.
0122     /// This also contains names that conflict with tags in the
0123     /// same scope but that are otherwise ordinary names (non-type
0124     /// template parameters and indirect field declarations).
0125     IDNS_Tag                 = 0x0002,
0126 
0127     /// Types, declared with 'struct foo', typedefs, etc.
0128     /// This is what elaborated-type-specifiers look for in C++,
0129     /// but note that it's ill-formed to find a non-tag.
0130     IDNS_Type                = 0x0004,
0131 
0132     /// Members, declared with object declarations within tag
0133     /// definitions.  In C, these can only be found by "qualified"
0134     /// lookup in member expressions.  In C++, they're found by
0135     /// normal lookup.
0136     IDNS_Member              = 0x0008,
0137 
0138     /// Namespaces, declared with 'namespace foo {}'.
0139     /// Lookup for nested-name-specifiers find these.
0140     IDNS_Namespace           = 0x0010,
0141 
0142     /// Ordinary names.  In C, everything that's not a label, tag,
0143     /// member, or function-local extern ends up here.
0144     IDNS_Ordinary            = 0x0020,
0145 
0146     /// Objective C \@protocol.
0147     IDNS_ObjCProtocol        = 0x0040,
0148 
0149     /// This declaration is a friend function.  A friend function
0150     /// declaration is always in this namespace but may also be in
0151     /// IDNS_Ordinary if it was previously declared.
0152     IDNS_OrdinaryFriend      = 0x0080,
0153 
0154     /// This declaration is a friend class.  A friend class
0155     /// declaration is always in this namespace but may also be in
0156     /// IDNS_Tag|IDNS_Type if it was previously declared.
0157     IDNS_TagFriend           = 0x0100,
0158 
0159     /// This declaration is a using declaration.  A using declaration
0160     /// *introduces* a number of other declarations into the current
0161     /// scope, and those declarations use the IDNS of their targets,
0162     /// but the actual using declarations go in this namespace.
0163     IDNS_Using               = 0x0200,
0164 
0165     /// This declaration is a C++ operator declared in a non-class
0166     /// context.  All such operators are also in IDNS_Ordinary.
0167     /// C++ lexical operator lookup looks for these.
0168     IDNS_NonMemberOperator   = 0x0400,
0169 
0170     /// This declaration is a function-local extern declaration of a
0171     /// variable or function. This may also be IDNS_Ordinary if it
0172     /// has been declared outside any function. These act mostly like
0173     /// invisible friend declarations, but are also visible to unqualified
0174     /// lookup within the scope of the declaring function.
0175     IDNS_LocalExtern         = 0x0800,
0176 
0177     /// This declaration is an OpenMP user defined reduction construction.
0178     IDNS_OMPReduction        = 0x1000,
0179 
0180     /// This declaration is an OpenMP user defined mapper.
0181     IDNS_OMPMapper           = 0x2000,
0182   };
0183 
0184   /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
0185   /// parameter types in method declarations.  Other than remembering
0186   /// them and mangling them into the method's signature string, these
0187   /// are ignored by the compiler; they are consumed by certain
0188   /// remote-messaging frameworks.
0189   ///
0190   /// in, inout, and out are mutually exclusive and apply only to
0191   /// method parameters.  bycopy and byref are mutually exclusive and
0192   /// apply only to method parameters (?).  oneway applies only to
0193   /// results.  All of these expect their corresponding parameter to
0194   /// have a particular type.  None of this is currently enforced by
0195   /// clang.
0196   ///
0197   /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
0198   enum ObjCDeclQualifier {
0199     OBJC_TQ_None = 0x0,
0200     OBJC_TQ_In = 0x1,
0201     OBJC_TQ_Inout = 0x2,
0202     OBJC_TQ_Out = 0x4,
0203     OBJC_TQ_Bycopy = 0x8,
0204     OBJC_TQ_Byref = 0x10,
0205     OBJC_TQ_Oneway = 0x20,
0206 
0207     /// The nullability qualifier is set when the nullability of the
0208     /// result or parameter was expressed via a context-sensitive
0209     /// keyword.
0210     OBJC_TQ_CSNullability = 0x40
0211   };
0212 
0213   /// The kind of ownership a declaration has, for visibility purposes.
0214   /// This enumeration is designed such that higher values represent higher
0215   /// levels of name hiding.
0216   enum class ModuleOwnershipKind : unsigned char {
0217     /// This declaration is not owned by a module.
0218     Unowned,
0219 
0220     /// This declaration has an owning module, but is globally visible
0221     /// (typically because its owning module is visible and we know that
0222     /// modules cannot later become hidden in this compilation).
0223     /// After serialization and deserialization, this will be converted
0224     /// to VisibleWhenImported.
0225     Visible,
0226 
0227     /// This declaration has an owning module, and is visible when that
0228     /// module is imported.
0229     VisibleWhenImported,
0230 
0231     /// This declaration has an owning module, and is visible to lookups
0232     /// that occurs within that module. And it is reachable in other module
0233     /// when the owning module is transitively imported.
0234     ReachableWhenImported,
0235 
0236     /// This declaration has an owning module, but is only visible to
0237     /// lookups that occur within that module.
0238     /// The discarded declarations in global module fragment belongs
0239     /// to this group too.
0240     ModulePrivate
0241   };
0242 
0243 protected:
0244   /// The next declaration within the same lexical
0245   /// DeclContext. These pointers form the linked list that is
0246   /// traversed via DeclContext's decls_begin()/decls_end().
0247   ///
0248   /// The extra three bits are used for the ModuleOwnershipKind.
0249   llvm::PointerIntPair<Decl *, 3, ModuleOwnershipKind> NextInContextAndBits;
0250 
0251 private:
0252   friend class DeclContext;
0253 
0254   struct MultipleDC {
0255     DeclContext *SemanticDC;
0256     DeclContext *LexicalDC;
0257   };
0258 
0259   /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
0260   /// For declarations that don't contain C++ scope specifiers, it contains
0261   /// the DeclContext where the Decl was declared.
0262   /// For declarations with C++ scope specifiers, it contains a MultipleDC*
0263   /// with the context where it semantically belongs (SemanticDC) and the
0264   /// context where it was lexically declared (LexicalDC).
0265   /// e.g.:
0266   ///
0267   ///   namespace A {
0268   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
0269   ///   }
0270   ///   void A::f(); // SemanticDC == namespace 'A'
0271   ///                // LexicalDC == global namespace
0272   llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
0273 
0274   bool isInSemaDC() const { return isa<DeclContext *>(DeclCtx); }
0275   bool isOutOfSemaDC() const { return isa<MultipleDC *>(DeclCtx); }
0276 
0277   MultipleDC *getMultipleDC() const { return cast<MultipleDC *>(DeclCtx); }
0278 
0279   DeclContext *getSemanticDC() const { return cast<DeclContext *>(DeclCtx); }
0280 
0281   /// Loc - The location of this decl.
0282   SourceLocation Loc;
0283 
0284   /// DeclKind - This indicates which class this is.
0285   LLVM_PREFERRED_TYPE(Kind)
0286   unsigned DeclKind : 7;
0287 
0288   /// InvalidDecl - This indicates a semantic error occurred.
0289   LLVM_PREFERRED_TYPE(bool)
0290   unsigned InvalidDecl :  1;
0291 
0292   /// HasAttrs - This indicates whether the decl has attributes or not.
0293   LLVM_PREFERRED_TYPE(bool)
0294   unsigned HasAttrs : 1;
0295 
0296   /// Implicit - Whether this declaration was implicitly generated by
0297   /// the implementation rather than explicitly written by the user.
0298   LLVM_PREFERRED_TYPE(bool)
0299   unsigned Implicit : 1;
0300 
0301   /// Whether this declaration was "used", meaning that a definition is
0302   /// required.
0303   LLVM_PREFERRED_TYPE(bool)
0304   unsigned Used : 1;
0305 
0306   /// Whether this declaration was "referenced".
0307   /// The difference with 'Used' is whether the reference appears in a
0308   /// evaluated context or not, e.g. functions used in uninstantiated templates
0309   /// are regarded as "referenced" but not "used".
0310   LLVM_PREFERRED_TYPE(bool)
0311   unsigned Referenced : 1;
0312 
0313   /// Whether this declaration is a top-level declaration (function,
0314   /// global variable, etc.) that is lexically inside an objc container
0315   /// definition.
0316   LLVM_PREFERRED_TYPE(bool)
0317   unsigned TopLevelDeclInObjCContainer : 1;
0318 
0319   /// Whether statistic collection is enabled.
0320   static bool StatisticsEnabled;
0321 
0322 protected:
0323   friend class ASTDeclMerger;
0324   friend class ASTDeclReader;
0325   friend class ASTDeclWriter;
0326   friend class ASTNodeImporter;
0327   friend class ASTReader;
0328   friend class CXXClassMemberWrapper;
0329   friend class LinkageComputer;
0330   friend class RecordDecl;
0331   template<typename decl_type> friend class Redeclarable;
0332 
0333   /// Access - Used by C++ decls for the access specifier.
0334   // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
0335   LLVM_PREFERRED_TYPE(AccessSpecifier)
0336   unsigned Access : 2;
0337 
0338   /// Whether this declaration was loaded from an AST file.
0339   LLVM_PREFERRED_TYPE(bool)
0340   unsigned FromASTFile : 1;
0341 
0342   /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
0343   LLVM_PREFERRED_TYPE(IdentifierNamespace)
0344   unsigned IdentifierNamespace : 14;
0345 
0346   /// If 0, we have not computed the linkage of this declaration.
0347   LLVM_PREFERRED_TYPE(Linkage)
0348   mutable unsigned CacheValidAndLinkage : 3;
0349 
0350   /// Allocate memory for a deserialized declaration.
0351   ///
0352   /// This routine must be used to allocate memory for any declaration that is
0353   /// deserialized from a module file.
0354   ///
0355   /// \param Size The size of the allocated object.
0356   /// \param Ctx The context in which we will allocate memory.
0357   /// \param ID The global ID of the deserialized declaration.
0358   /// \param Extra The amount of extra space to allocate after the object.
0359   void *operator new(std::size_t Size, const ASTContext &Ctx, GlobalDeclID ID,
0360                      std::size_t Extra = 0);
0361 
0362   /// Allocate memory for a non-deserialized declaration.
0363   void *operator new(std::size_t Size, const ASTContext &Ctx,
0364                      DeclContext *Parent, std::size_t Extra = 0);
0365 
0366 private:
0367   bool AccessDeclContextCheck() const;
0368 
0369   /// Get the module ownership kind to use for a local lexical child of \p DC,
0370   /// which may be either a local or (rarely) an imported declaration.
0371   static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
0372     if (DC) {
0373       auto *D = cast<Decl>(DC);
0374       auto MOK = D->getModuleOwnershipKind();
0375       if (MOK != ModuleOwnershipKind::Unowned &&
0376           (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
0377         return MOK;
0378       // If D is not local and we have no local module storage, then we don't
0379       // need to track module ownership at all.
0380     }
0381     return ModuleOwnershipKind::Unowned;
0382   }
0383 
0384 public:
0385   Decl() = delete;
0386   Decl(const Decl&) = delete;
0387   Decl(Decl &&) = delete;
0388   Decl &operator=(const Decl&) = delete;
0389   Decl &operator=(Decl&&) = delete;
0390 
0391 protected:
0392   Decl(Kind DK, DeclContext *DC, SourceLocation L)
0393       : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
0394         DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
0395         Implicit(false), Used(false), Referenced(false),
0396         TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
0397         IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
0398         CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)) {
0399     if (StatisticsEnabled) add(DK);
0400   }
0401 
0402   Decl(Kind DK, EmptyShell Empty)
0403       : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
0404         Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
0405         Access(AS_none), FromASTFile(0),
0406         IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
0407         CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)) {
0408     if (StatisticsEnabled) add(DK);
0409   }
0410 
0411   virtual ~Decl();
0412 
0413   /// Update a potentially out-of-date declaration.
0414   void updateOutOfDate(IdentifierInfo &II) const;
0415 
0416   Linkage getCachedLinkage() const {
0417     return static_cast<Linkage>(CacheValidAndLinkage);
0418   }
0419 
0420   void setCachedLinkage(Linkage L) const {
0421     CacheValidAndLinkage = llvm::to_underlying(L);
0422   }
0423 
0424   bool hasCachedLinkage() const {
0425     return CacheValidAndLinkage;
0426   }
0427 
0428 public:
0429   /// Source range that this declaration covers.
0430   virtual SourceRange getSourceRange() const LLVM_READONLY {
0431     return SourceRange(getLocation(), getLocation());
0432   }
0433 
0434   SourceLocation getBeginLoc() const LLVM_READONLY {
0435     return getSourceRange().getBegin();
0436   }
0437 
0438   SourceLocation getEndLoc() const LLVM_READONLY {
0439     return getSourceRange().getEnd();
0440   }
0441 
0442   SourceLocation getLocation() const { return Loc; }
0443   void setLocation(SourceLocation L) { Loc = L; }
0444 
0445   Kind getKind() const { return static_cast<Kind>(DeclKind); }
0446   const char *getDeclKindName() const;
0447 
0448   Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
0449   const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
0450 
0451   DeclContext *getDeclContext() {
0452     if (isInSemaDC())
0453       return getSemanticDC();
0454     return getMultipleDC()->SemanticDC;
0455   }
0456   const DeclContext *getDeclContext() const {
0457     return const_cast<Decl*>(this)->getDeclContext();
0458   }
0459 
0460   /// Return the non transparent context.
0461   /// See the comment of `DeclContext::isTransparentContext()` for the
0462   /// definition of transparent context.
0463   DeclContext *getNonTransparentDeclContext();
0464   const DeclContext *getNonTransparentDeclContext() const {
0465     return const_cast<Decl *>(this)->getNonTransparentDeclContext();
0466   }
0467 
0468   /// Find the innermost non-closure ancestor of this declaration,
0469   /// walking up through blocks, lambdas, etc.  If that ancestor is
0470   /// not a code context (!isFunctionOrMethod()), returns null.
0471   ///
0472   /// A declaration may be its own non-closure context.
0473   Decl *getNonClosureContext();
0474   const Decl *getNonClosureContext() const {
0475     return const_cast<Decl*>(this)->getNonClosureContext();
0476   }
0477 
0478   TranslationUnitDecl *getTranslationUnitDecl();
0479   const TranslationUnitDecl *getTranslationUnitDecl() const {
0480     return const_cast<Decl*>(this)->getTranslationUnitDecl();
0481   }
0482 
0483   bool isInAnonymousNamespace() const;
0484 
0485   bool isInStdNamespace() const;
0486 
0487   // Return true if this is a FileContext Decl.
0488   bool isFileContextDecl() const;
0489 
0490   /// Whether it resembles a flexible array member. This is a static member
0491   /// because we want to be able to call it with a nullptr. That allows us to
0492   /// perform non-Decl specific checks based on the object's type and strict
0493   /// flex array level.
0494   static bool isFlexibleArrayMemberLike(
0495       ASTContext &Context, const Decl *D, QualType Ty,
0496       LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
0497       bool IgnoreTemplateOrMacroSubstitution);
0498 
0499   ASTContext &getASTContext() const LLVM_READONLY;
0500 
0501   /// Helper to get the language options from the ASTContext.
0502   /// Defined out of line to avoid depending on ASTContext.h.
0503   const LangOptions &getLangOpts() const LLVM_READONLY;
0504 
0505   void setAccess(AccessSpecifier AS) {
0506     Access = AS;
0507     assert(AccessDeclContextCheck());
0508   }
0509 
0510   AccessSpecifier getAccess() const {
0511     assert(AccessDeclContextCheck());
0512     return AccessSpecifier(Access);
0513   }
0514 
0515   /// Retrieve the access specifier for this declaration, even though
0516   /// it may not yet have been properly set.
0517   AccessSpecifier getAccessUnsafe() const {
0518     return AccessSpecifier(Access);
0519   }
0520 
0521   bool hasAttrs() const { return HasAttrs; }
0522 
0523   void setAttrs(const AttrVec& Attrs) {
0524     return setAttrsImpl(Attrs, getASTContext());
0525   }
0526 
0527   AttrVec &getAttrs() {
0528     return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
0529   }
0530 
0531   const AttrVec &getAttrs() const;
0532   void dropAttrs();
0533   void addAttr(Attr *A);
0534 
0535   using attr_iterator = AttrVec::const_iterator;
0536   using attr_range = llvm::iterator_range<attr_iterator>;
0537 
0538   attr_range attrs() const {
0539     return attr_range(attr_begin(), attr_end());
0540   }
0541 
0542   attr_iterator attr_begin() const {
0543     return hasAttrs() ? getAttrs().begin() : nullptr;
0544   }
0545   attr_iterator attr_end() const {
0546     return hasAttrs() ? getAttrs().end() : nullptr;
0547   }
0548 
0549   template <typename... Ts> void dropAttrs() {
0550     if (!HasAttrs) return;
0551 
0552     AttrVec &Vec = getAttrs();
0553     llvm::erase_if(Vec, [](Attr *A) { return isa<Ts...>(A); });
0554 
0555     if (Vec.empty())
0556       HasAttrs = false;
0557   }
0558 
0559   template <typename T> void dropAttr() { dropAttrs<T>(); }
0560 
0561   template <typename T>
0562   llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
0563     return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
0564   }
0565 
0566   template <typename T>
0567   specific_attr_iterator<T> specific_attr_begin() const {
0568     return specific_attr_iterator<T>(attr_begin());
0569   }
0570 
0571   template <typename T>
0572   specific_attr_iterator<T> specific_attr_end() const {
0573     return specific_attr_iterator<T>(attr_end());
0574   }
0575 
0576   template<typename T> T *getAttr() const {
0577     return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
0578   }
0579 
0580   template<typename T> bool hasAttr() const {
0581     return hasAttrs() && hasSpecificAttr<T>(getAttrs());
0582   }
0583 
0584   /// getMaxAlignment - return the maximum alignment specified by attributes
0585   /// on this decl, 0 if there are none.
0586   unsigned getMaxAlignment() const;
0587 
0588   /// setInvalidDecl - Indicates the Decl had a semantic error. This
0589   /// allows for graceful error recovery.
0590   void setInvalidDecl(bool Invalid = true);
0591   bool isInvalidDecl() const { return (bool) InvalidDecl; }
0592 
0593   /// isImplicit - Indicates whether the declaration was implicitly
0594   /// generated by the implementation. If false, this declaration
0595   /// was written explicitly in the source code.
0596   bool isImplicit() const { return Implicit; }
0597   void setImplicit(bool I = true) { Implicit = I; }
0598 
0599   /// Whether *any* (re-)declaration of the entity was used, meaning that
0600   /// a definition is required.
0601   ///
0602   /// \param CheckUsedAttr When true, also consider the "used" attribute
0603   /// (in addition to the "used" bit set by \c setUsed()) when determining
0604   /// whether the function is used.
0605   bool isUsed(bool CheckUsedAttr = true) const;
0606 
0607   /// Set whether the declaration is used, in the sense of odr-use.
0608   ///
0609   /// This should only be used immediately after creating a declaration.
0610   /// It intentionally doesn't notify any listeners.
0611   void setIsUsed() { getCanonicalDecl()->Used = true; }
0612 
0613   /// Mark the declaration used, in the sense of odr-use.
0614   ///
0615   /// This notifies any mutation listeners in addition to setting a bit
0616   /// indicating the declaration is used.
0617   void markUsed(ASTContext &C);
0618 
0619   /// Whether any declaration of this entity was referenced.
0620   bool isReferenced() const;
0621 
0622   /// Whether this declaration was referenced. This should not be relied
0623   /// upon for anything other than debugging.
0624   bool isThisDeclarationReferenced() const { return Referenced; }
0625 
0626   void setReferenced(bool R = true) { Referenced = R; }
0627 
0628   /// Whether this declaration is a top-level declaration (function,
0629   /// global variable, etc.) that is lexically inside an objc container
0630   /// definition.
0631   bool isTopLevelDeclInObjCContainer() const {
0632     return TopLevelDeclInObjCContainer;
0633   }
0634 
0635   void setTopLevelDeclInObjCContainer(bool V = true) {
0636     TopLevelDeclInObjCContainer = V;
0637   }
0638 
0639   /// Looks on this and related declarations for an applicable
0640   /// external source symbol attribute.
0641   ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
0642 
0643   /// Whether this declaration was marked as being private to the
0644   /// module in which it was defined.
0645   bool isModulePrivate() const {
0646     return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
0647   }
0648 
0649   /// Whether this declaration was exported in a lexical context.
0650   /// e.g.:
0651   ///
0652   ///   export namespace A {
0653   ///      void f1();        // isInExportDeclContext() == true
0654   ///   }
0655   ///   void A::f1();        // isInExportDeclContext() == false
0656   ///
0657   ///   namespace B {
0658   ///      void f2();        // isInExportDeclContext() == false
0659   ///   }
0660   ///   export void B::f2(); // isInExportDeclContext() == true
0661   bool isInExportDeclContext() const;
0662 
0663   bool isInvisibleOutsideTheOwningModule() const {
0664     return getModuleOwnershipKind() > ModuleOwnershipKind::VisibleWhenImported;
0665   }
0666 
0667   /// Whether this declaration comes from another module unit.
0668   bool isInAnotherModuleUnit() const;
0669 
0670   /// Whether this declaration comes from the same module unit being compiled.
0671   bool isInCurrentModuleUnit() const;
0672 
0673   /// Whether the definition of the declaration should be emitted in external
0674   /// sources.
0675   bool shouldEmitInExternalSource() const;
0676 
0677   /// Whether this declaration comes from explicit global module.
0678   bool isFromExplicitGlobalModule() const;
0679 
0680   /// Whether this declaration comes from global module.
0681   bool isFromGlobalModule() const;
0682 
0683   /// Whether this declaration comes from a named module.
0684   bool isInNamedModule() const;
0685 
0686   /// Whether this declaration comes from a header unit.
0687   bool isFromHeaderUnit() const;
0688 
0689   /// Return true if this declaration has an attribute which acts as
0690   /// definition of the entity, such as 'alias' or 'ifunc'.
0691   bool hasDefiningAttr() const;
0692 
0693   /// Return this declaration's defining attribute if it has one.
0694   const Attr *getDefiningAttr() const;
0695 
0696 protected:
0697   /// Specify that this declaration was marked as being private
0698   /// to the module in which it was defined.
0699   void setModulePrivate() {
0700     // The module-private specifier has no effect on unowned declarations.
0701     // FIXME: We should track this in some way for source fidelity.
0702     if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
0703       return;
0704     setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
0705   }
0706 
0707 public:
0708   /// Set the FromASTFile flag. This indicates that this declaration
0709   /// was deserialized and not parsed from source code and enables
0710   /// features such as module ownership information.
0711   void setFromASTFile() {
0712     FromASTFile = true;
0713   }
0714 
0715   /// Set the owning module ID.  This may only be called for
0716   /// deserialized Decls.
0717   void setOwningModuleID(unsigned ID);
0718 
0719 public:
0720   /// Determine the availability of the given declaration.
0721   ///
0722   /// This routine will determine the most restrictive availability of
0723   /// the given declaration (e.g., preferring 'unavailable' to
0724   /// 'deprecated').
0725   ///
0726   /// \param Message If non-NULL and the result is not \c
0727   /// AR_Available, will be set to a (possibly empty) message
0728   /// describing why the declaration has not been introduced, is
0729   /// deprecated, or is unavailable.
0730   ///
0731   /// \param EnclosingVersion The version to compare with. If empty, assume the
0732   /// deployment target version.
0733   ///
0734   /// \param RealizedPlatform If non-NULL and the availability result is found
0735   /// in an available attribute it will set to the platform which is written in
0736   /// the available attribute.
0737   AvailabilityResult
0738   getAvailability(std::string *Message = nullptr,
0739                   VersionTuple EnclosingVersion = VersionTuple(),
0740                   StringRef *RealizedPlatform = nullptr) const;
0741 
0742   /// Retrieve the version of the target platform in which this
0743   /// declaration was introduced.
0744   ///
0745   /// \returns An empty version tuple if this declaration has no 'introduced'
0746   /// availability attributes, or the version tuple that's specified in the
0747   /// attribute otherwise.
0748   VersionTuple getVersionIntroduced() const;
0749 
0750   /// Determine whether this declaration is marked 'deprecated'.
0751   ///
0752   /// \param Message If non-NULL and the declaration is deprecated,
0753   /// this will be set to the message describing why the declaration
0754   /// was deprecated (which may be empty).
0755   bool isDeprecated(std::string *Message = nullptr) const {
0756     return getAvailability(Message) == AR_Deprecated;
0757   }
0758 
0759   /// Determine whether this declaration is marked 'unavailable'.
0760   ///
0761   /// \param Message If non-NULL and the declaration is unavailable,
0762   /// this will be set to the message describing why the declaration
0763   /// was made unavailable (which may be empty).
0764   bool isUnavailable(std::string *Message = nullptr) const {
0765     return getAvailability(Message) == AR_Unavailable;
0766   }
0767 
0768   /// Determine whether this is a weak-imported symbol.
0769   ///
0770   /// Weak-imported symbols are typically marked with the
0771   /// 'weak_import' attribute, but may also be marked with an
0772   /// 'availability' attribute where we're targing a platform prior to
0773   /// the introduction of this feature.
0774   bool isWeakImported() const;
0775 
0776   /// Determines whether this symbol can be weak-imported,
0777   /// e.g., whether it would be well-formed to add the weak_import
0778   /// attribute.
0779   ///
0780   /// \param IsDefinition Set to \c true to indicate that this
0781   /// declaration cannot be weak-imported because it has a definition.
0782   bool canBeWeakImported(bool &IsDefinition) const;
0783 
0784   /// Determine whether this declaration came from an AST file (such as
0785   /// a precompiled header or module) rather than having been parsed.
0786   bool isFromASTFile() const { return FromASTFile; }
0787 
0788   /// Retrieve the global declaration ID associated with this
0789   /// declaration, which specifies where this Decl was loaded from.
0790   GlobalDeclID getGlobalID() const;
0791 
0792   /// Retrieve the global ID of the module that owns this particular
0793   /// declaration.
0794   unsigned getOwningModuleID() const;
0795 
0796 private:
0797   Module *getOwningModuleSlow() const;
0798 
0799 protected:
0800   bool hasLocalOwningModuleStorage() const;
0801 
0802 public:
0803   /// Get the imported owning module, if this decl is from an imported
0804   /// (non-local) module.
0805   Module *getImportedOwningModule() const {
0806     if (!isFromASTFile() || !hasOwningModule())
0807       return nullptr;
0808 
0809     return getOwningModuleSlow();
0810   }
0811 
0812   /// Get the local owning module, if known. Returns nullptr if owner is
0813   /// not yet known or declaration is not from a module.
0814   Module *getLocalOwningModule() const {
0815     if (isFromASTFile() || !hasOwningModule())
0816       return nullptr;
0817 
0818     assert(hasLocalOwningModuleStorage() &&
0819            "owned local decl but no local module storage");
0820     return reinterpret_cast<Module *const *>(this)[-1];
0821   }
0822   void setLocalOwningModule(Module *M) {
0823     assert(!isFromASTFile() && hasOwningModule() &&
0824            hasLocalOwningModuleStorage() &&
0825            "should not have a cached owning module");
0826     reinterpret_cast<Module **>(this)[-1] = M;
0827   }
0828 
0829   /// Is this declaration owned by some module?
0830   bool hasOwningModule() const {
0831     return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
0832   }
0833 
0834   /// Get the module that owns this declaration (for visibility purposes).
0835   Module *getOwningModule() const {
0836     return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
0837   }
0838 
0839   /// Get the top level owning named module that owns this declaration if any.
0840   /// \returns nullptr if the declaration is not owned by a named module.
0841   Module *getTopLevelOwningNamedModule() const;
0842 
0843   /// Get the module that owns this declaration for linkage purposes.
0844   /// There only ever is such a standard C++ module.
0845   Module *getOwningModuleForLinkage() const;
0846 
0847   /// Determine whether this declaration is definitely visible to name lookup,
0848   /// independent of whether the owning module is visible.
0849   /// Note: The declaration may be visible even if this returns \c false if the
0850   /// owning module is visible within the query context. This is a low-level
0851   /// helper function; most code should be calling Sema::isVisible() instead.
0852   bool isUnconditionallyVisible() const {
0853     return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
0854   }
0855 
0856   bool isReachable() const {
0857     return (int)getModuleOwnershipKind() <=
0858            (int)ModuleOwnershipKind::ReachableWhenImported;
0859   }
0860 
0861   /// Set that this declaration is globally visible, even if it came from a
0862   /// module that is not visible.
0863   void setVisibleDespiteOwningModule() {
0864     if (!isUnconditionallyVisible())
0865       setModuleOwnershipKind(ModuleOwnershipKind::Visible);
0866   }
0867 
0868   /// Get the kind of module ownership for this declaration.
0869   ModuleOwnershipKind getModuleOwnershipKind() const {
0870     return NextInContextAndBits.getInt();
0871   }
0872 
0873   /// Set whether this declaration is hidden from name lookup.
0874   void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
0875     assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
0876              MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&
0877              !hasLocalOwningModuleStorage()) &&
0878            "no storage available for owning module for this declaration");
0879     NextInContextAndBits.setInt(MOK);
0880   }
0881 
0882   unsigned getIdentifierNamespace() const {
0883     return IdentifierNamespace;
0884   }
0885 
0886   bool isInIdentifierNamespace(unsigned NS) const {
0887     return getIdentifierNamespace() & NS;
0888   }
0889 
0890   static unsigned getIdentifierNamespaceForKind(Kind DK);
0891 
0892   bool hasTagIdentifierNamespace() const {
0893     return isTagIdentifierNamespace(getIdentifierNamespace());
0894   }
0895 
0896   static bool isTagIdentifierNamespace(unsigned NS) {
0897     // TagDecls have Tag and Type set and may also have TagFriend.
0898     return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
0899   }
0900 
0901   /// getLexicalDeclContext - The declaration context where this Decl was
0902   /// lexically declared (LexicalDC). May be different from
0903   /// getDeclContext() (SemanticDC).
0904   /// e.g.:
0905   ///
0906   ///   namespace A {
0907   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
0908   ///   }
0909   ///   void A::f(); // SemanticDC == namespace 'A'
0910   ///                // LexicalDC == global namespace
0911   DeclContext *getLexicalDeclContext() {
0912     if (isInSemaDC())
0913       return getSemanticDC();
0914     return getMultipleDC()->LexicalDC;
0915   }
0916   const DeclContext *getLexicalDeclContext() const {
0917     return const_cast<Decl*>(this)->getLexicalDeclContext();
0918   }
0919 
0920   /// Determine whether this declaration is declared out of line (outside its
0921   /// semantic context).
0922   virtual bool isOutOfLine() const;
0923 
0924   /// setDeclContext - Set both the semantic and lexical DeclContext
0925   /// to DC.
0926   void setDeclContext(DeclContext *DC);
0927 
0928   void setLexicalDeclContext(DeclContext *DC);
0929 
0930   /// Determine whether this declaration is a templated entity (whether it is
0931   // within the scope of a template parameter).
0932   bool isTemplated() const;
0933 
0934   /// Determine the number of levels of template parameter surrounding this
0935   /// declaration.
0936   unsigned getTemplateDepth() const;
0937 
0938   /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
0939   /// scoped decl is defined outside the current function or method.  This is
0940   /// roughly global variables and functions, but also handles enums (which
0941   /// could be defined inside or outside a function etc).
0942   bool isDefinedOutsideFunctionOrMethod() const {
0943     return getParentFunctionOrMethod() == nullptr;
0944   }
0945 
0946   /// Determine whether a substitution into this declaration would occur as
0947   /// part of a substitution into a dependent local scope. Such a substitution
0948   /// transitively substitutes into all constructs nested within this
0949   /// declaration.
0950   ///
0951   /// This recognizes non-defining declarations as well as members of local
0952   /// classes and lambdas:
0953   /// \code
0954   ///     template<typename T> void foo() { void bar(); }
0955   ///     template<typename T> void foo2() { class ABC { void bar(); }; }
0956   ///     template<typename T> inline int x = [](){ return 0; }();
0957   /// \endcode
0958   bool isInLocalScopeForInstantiation() const;
0959 
0960   /// If this decl is defined inside a function/method/block it returns
0961   /// the corresponding DeclContext, otherwise it returns null.
0962   const DeclContext *
0963   getParentFunctionOrMethod(bool LexicalParent = false) const;
0964   DeclContext *getParentFunctionOrMethod(bool LexicalParent = false) {
0965     return const_cast<DeclContext *>(
0966         const_cast<const Decl *>(this)->getParentFunctionOrMethod(
0967             LexicalParent));
0968   }
0969 
0970   /// Retrieves the "canonical" declaration of the given declaration.
0971   virtual Decl *getCanonicalDecl() { return this; }
0972   const Decl *getCanonicalDecl() const {
0973     return const_cast<Decl*>(this)->getCanonicalDecl();
0974   }
0975 
0976   /// Whether this particular Decl is a canonical one.
0977   bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
0978 
0979 protected:
0980   /// Returns the next redeclaration or itself if this is the only decl.
0981   ///
0982   /// Decl subclasses that can be redeclared should override this method so that
0983   /// Decl::redecl_iterator can iterate over them.
0984   virtual Decl *getNextRedeclarationImpl() { return this; }
0985 
0986   /// Implementation of getPreviousDecl(), to be overridden by any
0987   /// subclass that has a redeclaration chain.
0988   virtual Decl *getPreviousDeclImpl() { return nullptr; }
0989 
0990   /// Implementation of getMostRecentDecl(), to be overridden by any
0991   /// subclass that has a redeclaration chain.
0992   virtual Decl *getMostRecentDeclImpl() { return this; }
0993 
0994 public:
0995   /// Iterates through all the redeclarations of the same decl.
0996   class redecl_iterator {
0997     /// Current - The current declaration.
0998     Decl *Current = nullptr;
0999     Decl *Starter;
1000 
1001   public:
1002     using value_type = Decl *;
1003     using reference = const value_type &;
1004     using pointer = const value_type *;
1005     using iterator_category = std::forward_iterator_tag;
1006     using difference_type = std::ptrdiff_t;
1007 
1008     redecl_iterator() = default;
1009     explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
1010 
1011     reference operator*() const { return Current; }
1012     value_type operator->() const { return Current; }
1013 
1014     redecl_iterator& operator++() {
1015       assert(Current && "Advancing while iterator has reached end");
1016       // Get either previous decl or latest decl.
1017       Decl *Next = Current->getNextRedeclarationImpl();
1018       assert(Next && "Should return next redeclaration or itself, never null!");
1019       Current = (Next != Starter) ? Next : nullptr;
1020       return *this;
1021     }
1022 
1023     redecl_iterator operator++(int) {
1024       redecl_iterator tmp(*this);
1025       ++(*this);
1026       return tmp;
1027     }
1028 
1029     friend bool operator==(redecl_iterator x, redecl_iterator y) {
1030       return x.Current == y.Current;
1031     }
1032 
1033     friend bool operator!=(redecl_iterator x, redecl_iterator y) {
1034       return x.Current != y.Current;
1035     }
1036   };
1037 
1038   using redecl_range = llvm::iterator_range<redecl_iterator>;
1039 
1040   /// Returns an iterator range for all the redeclarations of the same
1041   /// decl. It will iterate at least once (when this decl is the only one).
1042   redecl_range redecls() const {
1043     return redecl_range(redecls_begin(), redecls_end());
1044   }
1045 
1046   redecl_iterator redecls_begin() const {
1047     return redecl_iterator(const_cast<Decl *>(this));
1048   }
1049 
1050   redecl_iterator redecls_end() const { return redecl_iterator(); }
1051 
1052   /// Retrieve the previous declaration that declares the same entity
1053   /// as this declaration, or NULL if there is no previous declaration.
1054   Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
1055 
1056   /// Retrieve the previous declaration that declares the same entity
1057   /// as this declaration, or NULL if there is no previous declaration.
1058   const Decl *getPreviousDecl() const {
1059     return const_cast<Decl *>(this)->getPreviousDeclImpl();
1060   }
1061 
1062   /// True if this is the first declaration in its redeclaration chain.
1063   bool isFirstDecl() const {
1064     return getPreviousDecl() == nullptr;
1065   }
1066 
1067   /// Retrieve the most recent declaration that declares the same entity
1068   /// as this declaration (which may be this declaration).
1069   Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1070 
1071   /// Retrieve the most recent declaration that declares the same entity
1072   /// as this declaration (which may be this declaration).
1073   const Decl *getMostRecentDecl() const {
1074     return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1075   }
1076 
1077   /// getBody - If this Decl represents a declaration for a body of code,
1078   ///  such as a function or method definition, this method returns the
1079   ///  top-level Stmt* of that body.  Otherwise this method returns null.
1080   virtual Stmt* getBody() const { return nullptr; }
1081 
1082   /// Returns true if this \c Decl represents a declaration for a body of
1083   /// code, such as a function or method definition.
1084   /// Note that \c hasBody can also return true if any redeclaration of this
1085   /// \c Decl represents a declaration for a body of code.
1086   virtual bool hasBody() const { return getBody() != nullptr; }
1087 
1088   /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1089   /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1090   SourceLocation getBodyRBrace() const;
1091 
1092   // global temp stats (until we have a per-module visitor)
1093   static void add(Kind k);
1094   static void EnableStatistics();
1095   static void PrintStats();
1096 
1097   /// isTemplateParameter - Determines whether this declaration is a
1098   /// template parameter.
1099   bool isTemplateParameter() const;
1100 
1101   /// isTemplateParameter - Determines whether this declaration is a
1102   /// template parameter pack.
1103   bool isTemplateParameterPack() const;
1104 
1105   /// Whether this declaration is a parameter pack.
1106   bool isParameterPack() const;
1107 
1108   /// returns true if this declaration is a template
1109   bool isTemplateDecl() const;
1110 
1111   /// Whether this declaration is a function or function template.
1112   bool isFunctionOrFunctionTemplate() const {
1113     return (DeclKind >= Decl::firstFunction &&
1114             DeclKind <= Decl::lastFunction) ||
1115            DeclKind == FunctionTemplate;
1116   }
1117 
1118   /// If this is a declaration that describes some template, this
1119   /// method returns that template declaration.
1120   ///
1121   /// Note that this returns nullptr for partial specializations, because they
1122   /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1123   /// those cases.
1124   TemplateDecl *getDescribedTemplate() const;
1125 
1126   /// If this is a declaration that describes some template or partial
1127   /// specialization, this returns the corresponding template parameter list.
1128   const TemplateParameterList *getDescribedTemplateParams() const;
1129 
1130   /// Returns the function itself, or the templated function if this is a
1131   /// function template.
1132   FunctionDecl *getAsFunction() LLVM_READONLY;
1133 
1134   const FunctionDecl *getAsFunction() const {
1135     return const_cast<Decl *>(this)->getAsFunction();
1136   }
1137 
1138   /// Changes the namespace of this declaration to reflect that it's
1139   /// a function-local extern declaration.
1140   ///
1141   /// These declarations appear in the lexical context of the extern
1142   /// declaration, but in the semantic context of the enclosing namespace
1143   /// scope.
1144   void setLocalExternDecl() {
1145     Decl *Prev = getPreviousDecl();
1146     IdentifierNamespace &= ~IDNS_Ordinary;
1147 
1148     // It's OK for the declaration to still have the "invisible friend" flag or
1149     // the "conflicts with tag declarations in this scope" flag for the outer
1150     // scope.
1151     assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&
1152            "namespace is not ordinary");
1153 
1154     IdentifierNamespace |= IDNS_LocalExtern;
1155     if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1156       IdentifierNamespace |= IDNS_Ordinary;
1157   }
1158 
1159   /// Determine whether this is a block-scope declaration with linkage.
1160   /// This will either be a local variable declaration declared 'extern', or a
1161   /// local function declaration.
1162   bool isLocalExternDecl() const {
1163     return IdentifierNamespace & IDNS_LocalExtern;
1164   }
1165 
1166   /// Changes the namespace of this declaration to reflect that it's
1167   /// the object of a friend declaration.
1168   ///
1169   /// These declarations appear in the lexical context of the friending
1170   /// class, but in the semantic context of the actual entity.  This property
1171   /// applies only to a specific decl object;  other redeclarations of the
1172   /// same entity may not (and probably don't) share this property.
1173   void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1174     unsigned OldNS = IdentifierNamespace;
1175     assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
1176                      IDNS_TagFriend | IDNS_OrdinaryFriend |
1177                      IDNS_LocalExtern | IDNS_NonMemberOperator)) &&
1178            "namespace includes neither ordinary nor tag");
1179     assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
1180                        IDNS_TagFriend | IDNS_OrdinaryFriend |
1181                        IDNS_LocalExtern | IDNS_NonMemberOperator)) &&
1182            "namespace includes other than ordinary or tag");
1183 
1184     Decl *Prev = getPreviousDecl();
1185     IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1186 
1187     if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1188       IdentifierNamespace |= IDNS_TagFriend;
1189       if (PerformFriendInjection ||
1190           (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1191         IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1192     }
1193 
1194     if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1195                  IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1196       IdentifierNamespace |= IDNS_OrdinaryFriend;
1197       if (PerformFriendInjection ||
1198           (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1199         IdentifierNamespace |= IDNS_Ordinary;
1200     }
1201   }
1202 
1203   /// Clears the namespace of this declaration.
1204   ///
1205   /// This is useful if we want this declaration to be available for
1206   /// redeclaration lookup but otherwise hidden for ordinary name lookups.
1207   void clearIdentifierNamespace() { IdentifierNamespace = 0; }
1208 
1209   enum FriendObjectKind {
1210     FOK_None,      ///< Not a friend object.
1211     FOK_Declared,  ///< A friend of a previously-declared entity.
1212     FOK_Undeclared ///< A friend of a previously-undeclared entity.
1213   };
1214 
1215   /// Determines whether this declaration is the object of a
1216   /// friend declaration and, if so, what kind.
1217   ///
1218   /// There is currently no direct way to find the associated FriendDecl.
1219   FriendObjectKind getFriendObjectKind() const {
1220     unsigned mask =
1221         (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1222     if (!mask) return FOK_None;
1223     return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1224                                                              : FOK_Undeclared);
1225   }
1226 
1227   /// Specifies that this declaration is a C++ overloaded non-member.
1228   void setNonMemberOperator() {
1229     assert(getKind() == Function || getKind() == FunctionTemplate);
1230     assert((IdentifierNamespace & IDNS_Ordinary) &&
1231            "visible non-member operators should be in ordinary namespace");
1232     IdentifierNamespace |= IDNS_NonMemberOperator;
1233   }
1234 
1235   static bool classofKind(Kind K) { return true; }
1236   static DeclContext *castToDeclContext(const Decl *);
1237   static Decl *castFromDeclContext(const DeclContext *);
1238 
1239   void print(raw_ostream &Out, unsigned Indentation = 0,
1240              bool PrintInstantiation = false) const;
1241   void print(raw_ostream &Out, const PrintingPolicy &Policy,
1242              unsigned Indentation = 0, bool PrintInstantiation = false) const;
1243   static void printGroup(Decl** Begin, unsigned NumDecls,
1244                          raw_ostream &Out, const PrintingPolicy &Policy,
1245                          unsigned Indentation = 0);
1246 
1247   // Debuggers don't usually respect default arguments.
1248   void dump() const;
1249 
1250   // Same as dump(), but forces color printing.
1251   void dumpColor() const;
1252 
1253   void dump(raw_ostream &Out, bool Deserialize = false,
1254             ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1255 
1256   /// \return Unique reproducible object identifier
1257   int64_t getID() const;
1258 
1259   /// Looks through the Decl's underlying type to extract a FunctionType
1260   /// when possible. This includes direct FunctionDecls, along with various
1261   /// function types and typedefs. This includes function pointers/references,
1262   /// member function pointers, and optionally if \p BlocksToo is set
1263   /// Objective-C block pointers. Returns nullptr if the type underlying the
1264   /// Decl does not have a FunctionType.
1265   const FunctionType *getFunctionType(bool BlocksToo = true) const;
1266 
1267   // Looks through the Decl's underlying type to determine if it's a
1268   // function pointer type.
1269   bool isFunctionPointerType() const;
1270 
1271 private:
1272   void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1273   void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1274                            ASTContext &Ctx);
1275 
1276 protected:
1277   ASTMutationListener *getASTMutationListener() const;
1278 };
1279 
1280 /// Determine whether two declarations declare the same entity.
1281 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1282   if (!D1 || !D2)
1283     return false;
1284 
1285   if (D1 == D2)
1286     return true;
1287 
1288   return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1289 }
1290 
1291 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1292 /// doing something to a specific decl.
1293 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1294   const Decl *TheDecl;
1295   SourceLocation Loc;
1296   SourceManager &SM;
1297   const char *Message;
1298 
1299 public:
1300   PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1301                        SourceManager &sm, const char *Msg)
1302       : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1303 
1304   void print(raw_ostream &OS) const override;
1305 };
1306 } // namespace clang
1307 
1308 // Required to determine the layout of the PointerUnion<NamedDecl*> before
1309 // seeing the NamedDecl definition being first used in DeclListNode::operator*.
1310 namespace llvm {
1311   template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
1312     static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
1313     static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
1314       return static_cast<::clang::NamedDecl *>(P);
1315     }
1316     static constexpr int NumLowBitsAvailable = 3;
1317   };
1318 }
1319 
1320 namespace clang {
1321 /// A list storing NamedDecls in the lookup tables.
1322 class DeclListNode {
1323   friend class ASTContext; // allocate, deallocate nodes.
1324   friend class StoredDeclsList;
1325 public:
1326   using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
1327   class iterator {
1328     friend class DeclContextLookupResult;
1329     friend class StoredDeclsList;
1330 
1331     Decls Ptr;
1332     iterator(Decls Node) : Ptr(Node) { }
1333   public:
1334     using difference_type = ptrdiff_t;
1335     using value_type = NamedDecl*;
1336     using pointer = void;
1337     using reference = value_type;
1338     using iterator_category = std::forward_iterator_tag;
1339 
1340     iterator() = default;
1341 
1342     reference operator*() const {
1343       assert(Ptr && "dereferencing end() iterator");
1344       if (DeclListNode *CurNode = dyn_cast<DeclListNode *>(Ptr))
1345         return CurNode->D;
1346       return cast<NamedDecl *>(Ptr);
1347     }
1348     void operator->() const { } // Unsupported.
1349     bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
1350     bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
1351     inline iterator &operator++() { // ++It
1352       assert(!Ptr.isNull() && "Advancing empty iterator");
1353 
1354       if (DeclListNode *CurNode = dyn_cast<DeclListNode *>(Ptr))
1355         Ptr = CurNode->Rest;
1356       else
1357         Ptr = nullptr;
1358       return *this;
1359     }
1360     iterator operator++(int) { // It++
1361       iterator temp = *this;
1362       ++(*this);
1363       return temp;
1364     }
1365     // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
1366     iterator end() { return iterator(); }
1367   };
1368 private:
1369   NamedDecl *D = nullptr;
1370   Decls Rest = nullptr;
1371   DeclListNode(NamedDecl *ND) : D(ND) {}
1372 };
1373 
1374 /// The results of name lookup within a DeclContext.
1375 class DeclContextLookupResult {
1376   using Decls = DeclListNode::Decls;
1377 
1378   /// When in collection form, this is what the Data pointer points to.
1379   Decls Result;
1380 
1381 public:
1382   DeclContextLookupResult() = default;
1383   DeclContextLookupResult(Decls Result) : Result(Result) {}
1384 
1385   using iterator = DeclListNode::iterator;
1386   using const_iterator = iterator;
1387   using reference = iterator::reference;
1388 
1389   iterator begin() { return iterator(Result); }
1390   iterator end() { return iterator(); }
1391   const_iterator begin() const {
1392     return const_cast<DeclContextLookupResult*>(this)->begin();
1393   }
1394   const_iterator end() const { return iterator(); }
1395 
1396   bool empty() const { return Result.isNull();  }
1397   bool isSingleResult() const { return isa_and_present<NamedDecl *>(Result); }
1398   reference front() const { return *begin(); }
1399 
1400   // Find the first declaration of the given type in the list. Note that this
1401   // is not in general the earliest-declared declaration, and should only be
1402   // used when it's not possible for there to be more than one match or where
1403   // it doesn't matter which one is found.
1404   template<class T> T *find_first() const {
1405     for (auto *D : *this)
1406       if (T *Decl = dyn_cast<T>(D))
1407         return Decl;
1408 
1409     return nullptr;
1410   }
1411 };
1412 
1413 /// Only used by CXXDeductionGuideDecl.
1414 enum class DeductionCandidate : unsigned char {
1415   Normal,
1416   Copy,
1417   Aggregate,
1418 };
1419 
1420 enum class RecordArgPassingKind;
1421 enum class OMPDeclareReductionInitKind;
1422 enum class ObjCImplementationControl;
1423 enum class LinkageSpecLanguageIDs;
1424 
1425 /// DeclContext - This is used only as base class of specific decl types that
1426 /// can act as declaration contexts. These decls are (only the top classes
1427 /// that directly derive from DeclContext are mentioned, not their subclasses):
1428 ///
1429 ///   TranslationUnitDecl
1430 ///   ExternCContext
1431 ///   NamespaceDecl
1432 ///   TagDecl
1433 ///   OMPDeclareReductionDecl
1434 ///   OMPDeclareMapperDecl
1435 ///   FunctionDecl
1436 ///   ObjCMethodDecl
1437 ///   ObjCContainerDecl
1438 ///   LinkageSpecDecl
1439 ///   ExportDecl
1440 ///   BlockDecl
1441 ///   CapturedDecl
1442 class DeclContext {
1443   /// For makeDeclVisibleInContextImpl
1444   friend class ASTDeclReader;
1445   /// For checking the new bits in the Serialization part.
1446   friend class ASTDeclWriter;
1447   /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1448   /// hasNeedToReconcileExternalVisibleStorage
1449   friend class ExternalASTSource;
1450   /// For CreateStoredDeclsMap
1451   friend class DependentDiagnostic;
1452   /// For hasNeedToReconcileExternalVisibleStorage,
1453   /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1454   friend class ASTWriter;
1455 
1456 protected:
1457   enum { NumOdrHashBits = 25 };
1458 
1459   // We use uint64_t in the bit-fields below since some bit-fields
1460   // cross the unsigned boundary and this breaks the packing.
1461 
1462   /// Stores the bits used by DeclContext.
1463   /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1464   /// methods in DeclContext should be updated appropriately.
1465   class DeclContextBitfields {
1466     friend class DeclContext;
1467     /// DeclKind - This indicates which class this is.
1468     LLVM_PREFERRED_TYPE(Decl::Kind)
1469     uint64_t DeclKind : 7;
1470 
1471     /// Whether this declaration context also has some external
1472     /// storage that contains additional declarations that are lexically
1473     /// part of this context.
1474     LLVM_PREFERRED_TYPE(bool)
1475     mutable uint64_t ExternalLexicalStorage : 1;
1476 
1477     /// Whether this declaration context also has some external
1478     /// storage that contains additional declarations that are visible
1479     /// in this context.
1480     LLVM_PREFERRED_TYPE(bool)
1481     mutable uint64_t ExternalVisibleStorage : 1;
1482 
1483     /// Whether this declaration context has had externally visible
1484     /// storage added since the last lookup. In this case, \c LookupPtr's
1485     /// invariant may not hold and needs to be fixed before we perform
1486     /// another lookup.
1487     LLVM_PREFERRED_TYPE(bool)
1488     mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1489 
1490     /// If \c true, this context may have local lexical declarations
1491     /// that are missing from the lookup table.
1492     LLVM_PREFERRED_TYPE(bool)
1493     mutable uint64_t HasLazyLocalLexicalLookups : 1;
1494 
1495     /// If \c true, the external source may have lexical declarations
1496     /// that are missing from the lookup table.
1497     LLVM_PREFERRED_TYPE(bool)
1498     mutable uint64_t HasLazyExternalLexicalLookups : 1;
1499 
1500     /// If \c true, lookups should only return identifier from
1501     /// DeclContext scope (for example TranslationUnit). Used in
1502     /// LookupQualifiedName()
1503     LLVM_PREFERRED_TYPE(bool)
1504     mutable uint64_t UseQualifiedLookup : 1;
1505   };
1506 
1507   /// Number of bits in DeclContextBitfields.
1508   enum { NumDeclContextBits = 13 };
1509 
1510   /// Stores the bits used by NamespaceDecl.
1511   /// If modified NumNamespaceDeclBits and the accessor
1512   /// methods in NamespaceDecl should be updated appropriately.
1513   class NamespaceDeclBitfields {
1514     friend class NamespaceDecl;
1515     /// For the bits in DeclContextBitfields
1516     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1517     uint64_t : NumDeclContextBits;
1518 
1519     /// True if this is an inline namespace.
1520     LLVM_PREFERRED_TYPE(bool)
1521     uint64_t IsInline : 1;
1522 
1523     /// True if this is a nested-namespace-definition.
1524     LLVM_PREFERRED_TYPE(bool)
1525     uint64_t IsNested : 1;
1526   };
1527 
1528   /// Number of inherited and non-inherited bits in NamespaceDeclBitfields.
1529   enum { NumNamespaceDeclBits = NumDeclContextBits + 2 };
1530 
1531   /// Stores the bits used by TagDecl.
1532   /// If modified NumTagDeclBits and the accessor
1533   /// methods in TagDecl should be updated appropriately.
1534   class TagDeclBitfields {
1535     friend class TagDecl;
1536     /// For the bits in DeclContextBitfields
1537     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1538     uint64_t : NumDeclContextBits;
1539 
1540     /// The TagKind enum.
1541     LLVM_PREFERRED_TYPE(TagTypeKind)
1542     uint64_t TagDeclKind : 3;
1543 
1544     /// True if this is a definition ("struct foo {};"), false if it is a
1545     /// declaration ("struct foo;").  It is not considered a definition
1546     /// until the definition has been fully processed.
1547     LLVM_PREFERRED_TYPE(bool)
1548     uint64_t IsCompleteDefinition : 1;
1549 
1550     /// True if this is currently being defined.
1551     LLVM_PREFERRED_TYPE(bool)
1552     uint64_t IsBeingDefined : 1;
1553 
1554     /// True if this tag declaration is "embedded" (i.e., defined or declared
1555     /// for the very first time) in the syntax of a declarator.
1556     LLVM_PREFERRED_TYPE(bool)
1557     uint64_t IsEmbeddedInDeclarator : 1;
1558 
1559     /// True if this tag is free standing, e.g. "struct foo;".
1560     LLVM_PREFERRED_TYPE(bool)
1561     uint64_t IsFreeStanding : 1;
1562 
1563     /// Indicates whether it is possible for declarations of this kind
1564     /// to have an out-of-date definition.
1565     ///
1566     /// This option is only enabled when modules are enabled.
1567     LLVM_PREFERRED_TYPE(bool)
1568     uint64_t MayHaveOutOfDateDef : 1;
1569 
1570     /// Has the full definition of this type been required by a use somewhere in
1571     /// the TU.
1572     LLVM_PREFERRED_TYPE(bool)
1573     uint64_t IsCompleteDefinitionRequired : 1;
1574 
1575     /// Whether this tag is a definition which was demoted due to
1576     /// a module merge.
1577     LLVM_PREFERRED_TYPE(bool)
1578     uint64_t IsThisDeclarationADemotedDefinition : 1;
1579   };
1580 
1581   /// Number of inherited and non-inherited bits in TagDeclBitfields.
1582   enum { NumTagDeclBits = NumDeclContextBits + 10 };
1583 
1584   /// Stores the bits used by EnumDecl.
1585   /// If modified NumEnumDeclBit and the accessor
1586   /// methods in EnumDecl should be updated appropriately.
1587   class EnumDeclBitfields {
1588     friend class EnumDecl;
1589     /// For the bits in TagDeclBitfields.
1590     LLVM_PREFERRED_TYPE(TagDeclBitfields)
1591     uint64_t : NumTagDeclBits;
1592 
1593     /// Width in bits required to store all the non-negative
1594     /// enumerators of this enum.
1595     uint64_t NumPositiveBits : 8;
1596 
1597     /// Width in bits required to store all the negative
1598     /// enumerators of this enum.
1599     uint64_t NumNegativeBits : 8;
1600 
1601     /// True if this tag declaration is a scoped enumeration. Only
1602     /// possible in C++11 mode.
1603     LLVM_PREFERRED_TYPE(bool)
1604     uint64_t IsScoped : 1;
1605 
1606     /// If this tag declaration is a scoped enum,
1607     /// then this is true if the scoped enum was declared using the class
1608     /// tag, false if it was declared with the struct tag. No meaning is
1609     /// associated if this tag declaration is not a scoped enum.
1610     LLVM_PREFERRED_TYPE(bool)
1611     uint64_t IsScopedUsingClassTag : 1;
1612 
1613     /// True if this is an enumeration with fixed underlying type. Only
1614     /// possible in C++11, Microsoft extensions, or Objective C mode.
1615     LLVM_PREFERRED_TYPE(bool)
1616     uint64_t IsFixed : 1;
1617 
1618     /// True if a valid hash is stored in ODRHash.
1619     LLVM_PREFERRED_TYPE(bool)
1620     uint64_t HasODRHash : 1;
1621   };
1622 
1623   /// Number of inherited and non-inherited bits in EnumDeclBitfields.
1624   enum { NumEnumDeclBits = NumTagDeclBits + 20 };
1625 
1626   /// Stores the bits used by RecordDecl.
1627   /// If modified NumRecordDeclBits and the accessor
1628   /// methods in RecordDecl should be updated appropriately.
1629   class RecordDeclBitfields {
1630     friend class RecordDecl;
1631     /// For the bits in TagDeclBitfields.
1632     LLVM_PREFERRED_TYPE(TagDeclBitfields)
1633     uint64_t : NumTagDeclBits;
1634 
1635     /// This is true if this struct ends with a flexible
1636     /// array member (e.g. int X[]) or if this union contains a struct that does.
1637     /// If so, this cannot be contained in arrays or other structs as a member.
1638     LLVM_PREFERRED_TYPE(bool)
1639     uint64_t HasFlexibleArrayMember : 1;
1640 
1641     /// Whether this is the type of an anonymous struct or union.
1642     LLVM_PREFERRED_TYPE(bool)
1643     uint64_t AnonymousStructOrUnion : 1;
1644 
1645     /// This is true if this struct has at least one member
1646     /// containing an Objective-C object pointer type.
1647     LLVM_PREFERRED_TYPE(bool)
1648     uint64_t HasObjectMember : 1;
1649 
1650     /// This is true if struct has at least one member of
1651     /// 'volatile' type.
1652     LLVM_PREFERRED_TYPE(bool)
1653     uint64_t HasVolatileMember : 1;
1654 
1655     /// Whether the field declarations of this record have been loaded
1656     /// from external storage. To avoid unnecessary deserialization of
1657     /// methods/nested types we allow deserialization of just the fields
1658     /// when needed.
1659     LLVM_PREFERRED_TYPE(bool)
1660     mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1661 
1662     /// Basic properties of non-trivial C structs.
1663     LLVM_PREFERRED_TYPE(bool)
1664     uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1665     LLVM_PREFERRED_TYPE(bool)
1666     uint64_t NonTrivialToPrimitiveCopy : 1;
1667     LLVM_PREFERRED_TYPE(bool)
1668     uint64_t NonTrivialToPrimitiveDestroy : 1;
1669 
1670     /// The following bits indicate whether this is or contains a C union that
1671     /// is non-trivial to default-initialize, destruct, or copy. These bits
1672     /// imply the associated basic non-triviality predicates declared above.
1673     LLVM_PREFERRED_TYPE(bool)
1674     uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1675     LLVM_PREFERRED_TYPE(bool)
1676     uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1677     LLVM_PREFERRED_TYPE(bool)
1678     uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1679 
1680     /// True if any field is marked as requiring explicit initialization with
1681     /// [[clang::require_explicit_initialization]].
1682     /// In C++, this is also set for types without a user-provided default
1683     /// constructor, and is propagated from any base classes and/or member
1684     /// variables whose types are aggregates.
1685     LLVM_PREFERRED_TYPE(bool)
1686     uint64_t HasUninitializedExplicitInitFields : 1;
1687 
1688     /// Indicates whether this struct is destroyed in the callee.
1689     LLVM_PREFERRED_TYPE(bool)
1690     uint64_t ParamDestroyedInCallee : 1;
1691 
1692     /// Represents the way this type is passed to a function.
1693     LLVM_PREFERRED_TYPE(RecordArgPassingKind)
1694     uint64_t ArgPassingRestrictions : 2;
1695 
1696     /// Indicates whether this struct has had its field layout randomized.
1697     LLVM_PREFERRED_TYPE(bool)
1698     uint64_t IsRandomized : 1;
1699 
1700     /// True if a valid hash is stored in ODRHash. This should shave off some
1701     /// extra storage and prevent CXXRecordDecl to store unused bits.
1702     uint64_t ODRHash : NumOdrHashBits;
1703   };
1704 
1705   /// Number of inherited and non-inherited bits in RecordDeclBitfields.
1706   enum { NumRecordDeclBits = NumTagDeclBits + 41 };
1707 
1708   /// Stores the bits used by OMPDeclareReductionDecl.
1709   /// If modified NumOMPDeclareReductionDeclBits and the accessor
1710   /// methods in OMPDeclareReductionDecl should be updated appropriately.
1711   class OMPDeclareReductionDeclBitfields {
1712     friend class OMPDeclareReductionDecl;
1713     /// For the bits in DeclContextBitfields
1714     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1715     uint64_t : NumDeclContextBits;
1716 
1717     /// Kind of initializer,
1718     /// function call or omp_priv<init_expr> initialization.
1719     LLVM_PREFERRED_TYPE(OMPDeclareReductionInitKind)
1720     uint64_t InitializerKind : 2;
1721   };
1722 
1723   /// Number of inherited and non-inherited bits in
1724   /// OMPDeclareReductionDeclBitfields.
1725   enum { NumOMPDeclareReductionDeclBits = NumDeclContextBits + 2 };
1726 
1727   /// Stores the bits used by FunctionDecl.
1728   /// If modified NumFunctionDeclBits and the accessor
1729   /// methods in FunctionDecl and CXXDeductionGuideDecl
1730   /// (for DeductionCandidateKind) should be updated appropriately.
1731   class FunctionDeclBitfields {
1732     friend class FunctionDecl;
1733     /// For DeductionCandidateKind
1734     friend class CXXDeductionGuideDecl;
1735     /// For the bits in DeclContextBitfields.
1736     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1737     uint64_t : NumDeclContextBits;
1738 
1739     LLVM_PREFERRED_TYPE(StorageClass)
1740     uint64_t SClass : 3;
1741     LLVM_PREFERRED_TYPE(bool)
1742     uint64_t IsInline : 1;
1743     LLVM_PREFERRED_TYPE(bool)
1744     uint64_t IsInlineSpecified : 1;
1745 
1746     LLVM_PREFERRED_TYPE(bool)
1747     uint64_t IsVirtualAsWritten : 1;
1748     LLVM_PREFERRED_TYPE(bool)
1749     uint64_t IsPureVirtual : 1;
1750     LLVM_PREFERRED_TYPE(bool)
1751     uint64_t HasInheritedPrototype : 1;
1752     LLVM_PREFERRED_TYPE(bool)
1753     uint64_t HasWrittenPrototype : 1;
1754     LLVM_PREFERRED_TYPE(bool)
1755     uint64_t IsDeleted : 1;
1756     /// Used by CXXMethodDecl
1757     LLVM_PREFERRED_TYPE(bool)
1758     uint64_t IsTrivial : 1;
1759 
1760     /// This flag indicates whether this function is trivial for the purpose of
1761     /// calls. This is meaningful only when this function is a copy/move
1762     /// constructor or a destructor.
1763     LLVM_PREFERRED_TYPE(bool)
1764     uint64_t IsTrivialForCall : 1;
1765 
1766     LLVM_PREFERRED_TYPE(bool)
1767     uint64_t IsDefaulted : 1;
1768     LLVM_PREFERRED_TYPE(bool)
1769     uint64_t IsExplicitlyDefaulted : 1;
1770     LLVM_PREFERRED_TYPE(bool)
1771     uint64_t HasDefaultedOrDeletedInfo : 1;
1772 
1773     /// For member functions of complete types, whether this is an ineligible
1774     /// special member function or an unselected destructor. See
1775     /// [class.mem.special].
1776     LLVM_PREFERRED_TYPE(bool)
1777     uint64_t IsIneligibleOrNotSelected : 1;
1778 
1779     LLVM_PREFERRED_TYPE(bool)
1780     uint64_t HasImplicitReturnZero : 1;
1781     LLVM_PREFERRED_TYPE(bool)
1782     uint64_t IsLateTemplateParsed : 1;
1783     LLVM_PREFERRED_TYPE(bool)
1784     uint64_t IsInstantiatedFromMemberTemplate : 1;
1785 
1786     /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1787     LLVM_PREFERRED_TYPE(ConstexprSpecKind)
1788     uint64_t ConstexprKind : 2;
1789     LLVM_PREFERRED_TYPE(bool)
1790     uint64_t BodyContainsImmediateEscalatingExpression : 1;
1791 
1792     LLVM_PREFERRED_TYPE(bool)
1793     uint64_t InstantiationIsPending : 1;
1794 
1795     /// Indicates if the function uses __try.
1796     LLVM_PREFERRED_TYPE(bool)
1797     uint64_t UsesSEHTry : 1;
1798 
1799     /// Indicates if the function was a definition
1800     /// but its body was skipped.
1801     LLVM_PREFERRED_TYPE(bool)
1802     uint64_t HasSkippedBody : 1;
1803 
1804     /// Indicates if the function declaration will
1805     /// have a body, once we're done parsing it.
1806     LLVM_PREFERRED_TYPE(bool)
1807     uint64_t WillHaveBody : 1;
1808 
1809     /// Indicates that this function is a multiversioned
1810     /// function using attribute 'target'.
1811     LLVM_PREFERRED_TYPE(bool)
1812     uint64_t IsMultiVersion : 1;
1813 
1814     /// Only used by CXXDeductionGuideDecl. Indicates the kind
1815     /// of the Deduction Guide that is implicitly generated
1816     /// (used during overload resolution).
1817     LLVM_PREFERRED_TYPE(DeductionCandidate)
1818     uint64_t DeductionCandidateKind : 2;
1819 
1820     /// Store the ODRHash after first calculation.
1821     LLVM_PREFERRED_TYPE(bool)
1822     uint64_t HasODRHash : 1;
1823 
1824     /// Indicates if the function uses Floating Point Constrained Intrinsics
1825     LLVM_PREFERRED_TYPE(bool)
1826     uint64_t UsesFPIntrin : 1;
1827 
1828     // Indicates this function is a constrained friend, where the constraint
1829     // refers to an enclosing template for hte purposes of [temp.friend]p9.
1830     LLVM_PREFERRED_TYPE(bool)
1831     uint64_t FriendConstraintRefersToEnclosingTemplate : 1;
1832   };
1833 
1834   /// Number of inherited and non-inherited bits in FunctionDeclBitfields.
1835   enum { NumFunctionDeclBits = NumDeclContextBits + 32 };
1836 
1837   /// Stores the bits used by CXXConstructorDecl. If modified
1838   /// NumCXXConstructorDeclBits and the accessor
1839   /// methods in CXXConstructorDecl should be updated appropriately.
1840   class CXXConstructorDeclBitfields {
1841     friend class CXXConstructorDecl;
1842     /// For the bits in FunctionDeclBitfields.
1843     LLVM_PREFERRED_TYPE(FunctionDeclBitfields)
1844     uint64_t : NumFunctionDeclBits;
1845 
1846     /// 19 bits to fit in the remaining available space.
1847     /// Note that this makes CXXConstructorDeclBitfields take
1848     /// exactly 64 bits and thus the width of NumCtorInitializers
1849     /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1850     /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1851     uint64_t NumCtorInitializers : 16;
1852     LLVM_PREFERRED_TYPE(bool)
1853     uint64_t IsInheritingConstructor : 1;
1854 
1855     /// Whether this constructor has a trail-allocated explicit specifier.
1856     LLVM_PREFERRED_TYPE(bool)
1857     uint64_t HasTrailingExplicitSpecifier : 1;
1858     /// If this constructor does't have a trail-allocated explicit specifier.
1859     /// Whether this constructor is explicit specified.
1860     LLVM_PREFERRED_TYPE(bool)
1861     uint64_t IsSimpleExplicit : 1;
1862   };
1863 
1864   /// Number of inherited and non-inherited bits in CXXConstructorDeclBitfields.
1865   enum { NumCXXConstructorDeclBits = NumFunctionDeclBits + 19 };
1866 
1867   /// Stores the bits used by ObjCMethodDecl.
1868   /// If modified NumObjCMethodDeclBits and the accessor
1869   /// methods in ObjCMethodDecl should be updated appropriately.
1870   class ObjCMethodDeclBitfields {
1871     friend class ObjCMethodDecl;
1872 
1873     /// For the bits in DeclContextBitfields.
1874     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1875     uint64_t : NumDeclContextBits;
1876 
1877     /// The conventional meaning of this method; an ObjCMethodFamily.
1878     /// This is not serialized; instead, it is computed on demand and
1879     /// cached.
1880     LLVM_PREFERRED_TYPE(ObjCMethodFamily)
1881     mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1882 
1883     /// instance (true) or class (false) method.
1884     LLVM_PREFERRED_TYPE(bool)
1885     uint64_t IsInstance : 1;
1886     LLVM_PREFERRED_TYPE(bool)
1887     uint64_t IsVariadic : 1;
1888 
1889     /// True if this method is the getter or setter for an explicit property.
1890     LLVM_PREFERRED_TYPE(bool)
1891     uint64_t IsPropertyAccessor : 1;
1892 
1893     /// True if this method is a synthesized property accessor stub.
1894     LLVM_PREFERRED_TYPE(bool)
1895     uint64_t IsSynthesizedAccessorStub : 1;
1896 
1897     /// Method has a definition.
1898     LLVM_PREFERRED_TYPE(bool)
1899     uint64_t IsDefined : 1;
1900 
1901     /// Method redeclaration in the same interface.
1902     LLVM_PREFERRED_TYPE(bool)
1903     uint64_t IsRedeclaration : 1;
1904 
1905     /// Is redeclared in the same interface.
1906     LLVM_PREFERRED_TYPE(bool)
1907     mutable uint64_t HasRedeclaration : 1;
1908 
1909     /// \@required/\@optional
1910     LLVM_PREFERRED_TYPE(ObjCImplementationControl)
1911     uint64_t DeclImplementation : 2;
1912 
1913     /// in, inout, etc.
1914     LLVM_PREFERRED_TYPE(Decl::ObjCDeclQualifier)
1915     uint64_t objcDeclQualifier : 7;
1916 
1917     /// Indicates whether this method has a related result type.
1918     LLVM_PREFERRED_TYPE(bool)
1919     uint64_t RelatedResultType : 1;
1920 
1921     /// Whether the locations of the selector identifiers are in a
1922     /// "standard" position, a enum SelectorLocationsKind.
1923     LLVM_PREFERRED_TYPE(SelectorLocationsKind)
1924     uint64_t SelLocsKind : 2;
1925 
1926     /// Whether this method overrides any other in the class hierarchy.
1927     ///
1928     /// A method is said to override any method in the class's
1929     /// base classes, its protocols, or its categories' protocols, that has
1930     /// the same selector and is of the same kind (class or instance).
1931     /// A method in an implementation is not considered as overriding the same
1932     /// method in the interface or its categories.
1933     LLVM_PREFERRED_TYPE(bool)
1934     uint64_t IsOverriding : 1;
1935 
1936     /// Indicates if the method was a definition but its body was skipped.
1937     LLVM_PREFERRED_TYPE(bool)
1938     uint64_t HasSkippedBody : 1;
1939   };
1940 
1941   /// Number of inherited and non-inherited bits in ObjCMethodDeclBitfields.
1942   enum { NumObjCMethodDeclBits = NumDeclContextBits + 24 };
1943 
1944   /// Stores the bits used by ObjCContainerDecl.
1945   /// If modified NumObjCContainerDeclBits and the accessor
1946   /// methods in ObjCContainerDecl should be updated appropriately.
1947   class ObjCContainerDeclBitfields {
1948     friend class ObjCContainerDecl;
1949     /// For the bits in DeclContextBitfields
1950     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1951     uint32_t : NumDeclContextBits;
1952 
1953     // Not a bitfield but this saves space.
1954     // Note that ObjCContainerDeclBitfields is full.
1955     SourceLocation AtStart;
1956   };
1957 
1958   /// Number of inherited and non-inherited bits in ObjCContainerDeclBitfields.
1959   /// Note that here we rely on the fact that SourceLocation is 32 bits
1960   /// wide. We check this with the static_assert in the ctor of DeclContext.
1961   enum { NumObjCContainerDeclBits = 64 };
1962 
1963   /// Stores the bits used by LinkageSpecDecl.
1964   /// If modified NumLinkageSpecDeclBits and the accessor
1965   /// methods in LinkageSpecDecl should be updated appropriately.
1966   class LinkageSpecDeclBitfields {
1967     friend class LinkageSpecDecl;
1968     /// For the bits in DeclContextBitfields.
1969     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1970     uint64_t : NumDeclContextBits;
1971 
1972     /// The language for this linkage specification.
1973     LLVM_PREFERRED_TYPE(LinkageSpecLanguageIDs)
1974     uint64_t Language : 3;
1975 
1976     /// True if this linkage spec has braces.
1977     /// This is needed so that hasBraces() returns the correct result while the
1978     /// linkage spec body is being parsed.  Once RBraceLoc has been set this is
1979     /// not used, so it doesn't need to be serialized.
1980     LLVM_PREFERRED_TYPE(bool)
1981     uint64_t HasBraces : 1;
1982   };
1983 
1984   /// Number of inherited and non-inherited bits in LinkageSpecDeclBitfields.
1985   enum { NumLinkageSpecDeclBits = NumDeclContextBits + 4 };
1986 
1987   /// Stores the bits used by BlockDecl.
1988   /// If modified NumBlockDeclBits and the accessor
1989   /// methods in BlockDecl should be updated appropriately.
1990   class BlockDeclBitfields {
1991     friend class BlockDecl;
1992     /// For the bits in DeclContextBitfields.
1993     LLVM_PREFERRED_TYPE(DeclContextBitfields)
1994     uint64_t : NumDeclContextBits;
1995 
1996     LLVM_PREFERRED_TYPE(bool)
1997     uint64_t IsVariadic : 1;
1998     LLVM_PREFERRED_TYPE(bool)
1999     uint64_t CapturesCXXThis : 1;
2000     LLVM_PREFERRED_TYPE(bool)
2001     uint64_t BlockMissingReturnType : 1;
2002     LLVM_PREFERRED_TYPE(bool)
2003     uint64_t IsConversionFromLambda : 1;
2004 
2005     /// A bit that indicates this block is passed directly to a function as a
2006     /// non-escaping parameter.
2007     LLVM_PREFERRED_TYPE(bool)
2008     uint64_t DoesNotEscape : 1;
2009 
2010     /// A bit that indicates whether it's possible to avoid coying this block to
2011     /// the heap when it initializes or is assigned to a local variable with
2012     /// automatic storage.
2013     LLVM_PREFERRED_TYPE(bool)
2014     uint64_t CanAvoidCopyToHeap : 1;
2015   };
2016 
2017   /// Number of inherited and non-inherited bits in BlockDeclBitfields.
2018   enum { NumBlockDeclBits = NumDeclContextBits + 5 };
2019 
2020   /// Pointer to the data structure used to lookup declarations
2021   /// within this context (or a DependentStoredDeclsMap if this is a
2022   /// dependent context). We maintain the invariant that, if the map
2023   /// contains an entry for a DeclarationName (and we haven't lazily
2024   /// omitted anything), then it contains all relevant entries for that
2025   /// name (modulo the hasExternalDecls() flag).
2026   mutable StoredDeclsMap *LookupPtr = nullptr;
2027 
2028 protected:
2029   /// This anonymous union stores the bits belonging to DeclContext and classes
2030   /// deriving from it. The goal is to use otherwise wasted
2031   /// space in DeclContext to store data belonging to derived classes.
2032   /// The space saved is especially significient when pointers are aligned
2033   /// to 8 bytes. In this case due to alignment requirements we have a
2034   /// little less than 8 bytes free in DeclContext which we can use.
2035   /// We check that none of the classes in this union is larger than
2036   /// 8 bytes with static_asserts in the ctor of DeclContext.
2037   union {
2038     DeclContextBitfields DeclContextBits;
2039     NamespaceDeclBitfields NamespaceDeclBits;
2040     TagDeclBitfields TagDeclBits;
2041     EnumDeclBitfields EnumDeclBits;
2042     RecordDeclBitfields RecordDeclBits;
2043     OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
2044     FunctionDeclBitfields FunctionDeclBits;
2045     CXXConstructorDeclBitfields CXXConstructorDeclBits;
2046     ObjCMethodDeclBitfields ObjCMethodDeclBits;
2047     ObjCContainerDeclBitfields ObjCContainerDeclBits;
2048     LinkageSpecDeclBitfields LinkageSpecDeclBits;
2049     BlockDeclBitfields BlockDeclBits;
2050 
2051     static_assert(sizeof(DeclContextBitfields) <= 8,
2052                   "DeclContextBitfields is larger than 8 bytes!");
2053     static_assert(sizeof(NamespaceDeclBitfields) <= 8,
2054                   "NamespaceDeclBitfields is larger than 8 bytes!");
2055     static_assert(sizeof(TagDeclBitfields) <= 8,
2056                   "TagDeclBitfields is larger than 8 bytes!");
2057     static_assert(sizeof(EnumDeclBitfields) <= 8,
2058                   "EnumDeclBitfields is larger than 8 bytes!");
2059     static_assert(sizeof(RecordDeclBitfields) <= 8,
2060                   "RecordDeclBitfields is larger than 8 bytes!");
2061     static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
2062                   "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
2063     static_assert(sizeof(FunctionDeclBitfields) <= 8,
2064                   "FunctionDeclBitfields is larger than 8 bytes!");
2065     static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
2066                   "CXXConstructorDeclBitfields is larger than 8 bytes!");
2067     static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
2068                   "ObjCMethodDeclBitfields is larger than 8 bytes!");
2069     static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
2070                   "ObjCContainerDeclBitfields is larger than 8 bytes!");
2071     static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
2072                   "LinkageSpecDeclBitfields is larger than 8 bytes!");
2073     static_assert(sizeof(BlockDeclBitfields) <= 8,
2074                   "BlockDeclBitfields is larger than 8 bytes!");
2075   };
2076 
2077   /// FirstDecl - The first declaration stored within this declaration
2078   /// context.
2079   mutable Decl *FirstDecl = nullptr;
2080 
2081   /// LastDecl - The last declaration stored within this declaration
2082   /// context. FIXME: We could probably cache this value somewhere
2083   /// outside of the DeclContext, to reduce the size of DeclContext by
2084   /// another pointer.
2085   mutable Decl *LastDecl = nullptr;
2086 
2087   /// Build up a chain of declarations.
2088   ///
2089   /// \returns the first/last pair of declarations.
2090   static std::pair<Decl *, Decl *>
2091   BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
2092 
2093   DeclContext(Decl::Kind K);
2094 
2095 public:
2096   ~DeclContext();
2097 
2098   // For use when debugging; hasValidDeclKind() will always return true for
2099   // a correctly constructed object within its lifetime.
2100   bool hasValidDeclKind() const;
2101 
2102   Decl::Kind getDeclKind() const {
2103     return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
2104   }
2105 
2106   const char *getDeclKindName() const;
2107 
2108   /// getParent - Returns the containing DeclContext.
2109   DeclContext *getParent() {
2110     return cast<Decl>(this)->getDeclContext();
2111   }
2112   const DeclContext *getParent() const {
2113     return const_cast<DeclContext*>(this)->getParent();
2114   }
2115 
2116   /// getLexicalParent - Returns the containing lexical DeclContext. May be
2117   /// different from getParent, e.g.:
2118   ///
2119   ///   namespace A {
2120   ///      struct S;
2121   ///   }
2122   ///   struct A::S {}; // getParent() == namespace 'A'
2123   ///                   // getLexicalParent() == translation unit
2124   ///
2125   DeclContext *getLexicalParent() {
2126     return cast<Decl>(this)->getLexicalDeclContext();
2127   }
2128   const DeclContext *getLexicalParent() const {
2129     return const_cast<DeclContext*>(this)->getLexicalParent();
2130   }
2131 
2132   DeclContext *getLookupParent();
2133 
2134   const DeclContext *getLookupParent() const {
2135     return const_cast<DeclContext*>(this)->getLookupParent();
2136   }
2137 
2138   ASTContext &getParentASTContext() const {
2139     return cast<Decl>(this)->getASTContext();
2140   }
2141 
2142   bool isClosure() const { return getDeclKind() == Decl::Block; }
2143 
2144   /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
2145   /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
2146   const BlockDecl *getInnermostBlockDecl() const;
2147 
2148   bool isObjCContainer() const {
2149     switch (getDeclKind()) {
2150     case Decl::ObjCCategory:
2151     case Decl::ObjCCategoryImpl:
2152     case Decl::ObjCImplementation:
2153     case Decl::ObjCInterface:
2154     case Decl::ObjCProtocol:
2155       return true;
2156     default:
2157       return false;
2158     }
2159   }
2160 
2161   bool isFunctionOrMethod() const {
2162     switch (getDeclKind()) {
2163     case Decl::Block:
2164     case Decl::Captured:
2165     case Decl::ObjCMethod:
2166     case Decl::TopLevelStmt:
2167       return true;
2168     default:
2169       return getDeclKind() >= Decl::firstFunction &&
2170              getDeclKind() <= Decl::lastFunction;
2171     }
2172   }
2173 
2174   /// Test whether the context supports looking up names.
2175   bool isLookupContext() const {
2176     return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
2177            getDeclKind() != Decl::Export;
2178   }
2179 
2180   bool isFileContext() const {
2181     return getDeclKind() == Decl::TranslationUnit ||
2182            getDeclKind() == Decl::Namespace;
2183   }
2184 
2185   bool isTranslationUnit() const {
2186     return getDeclKind() == Decl::TranslationUnit;
2187   }
2188 
2189   bool isRecord() const {
2190     return getDeclKind() >= Decl::firstRecord &&
2191            getDeclKind() <= Decl::lastRecord;
2192   }
2193 
2194   bool isRequiresExprBody() const {
2195     return getDeclKind() == Decl::RequiresExprBody;
2196   }
2197 
2198   bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
2199 
2200   bool isStdNamespace() const;
2201 
2202   bool isInlineNamespace() const;
2203 
2204   /// Determines whether this context is dependent on a
2205   /// template parameter.
2206   bool isDependentContext() const;
2207 
2208   /// isTransparentContext - Determines whether this context is a
2209   /// "transparent" context, meaning that the members declared in this
2210   /// context are semantically declared in the nearest enclosing
2211   /// non-transparent (opaque) context but are lexically declared in
2212   /// this context. For example, consider the enumerators of an
2213   /// enumeration type:
2214   /// @code
2215   /// enum E {
2216   ///   Val1
2217   /// };
2218   /// @endcode
2219   /// Here, E is a transparent context, so its enumerator (Val1) will
2220   /// appear (semantically) that it is in the same context of E.
2221   /// Examples of transparent contexts include: enumerations (except for
2222   /// C++0x scoped enums), C++ linkage specifications and export declaration.
2223   bool isTransparentContext() const;
2224 
2225   /// Determines whether this context or some of its ancestors is a
2226   /// linkage specification context that specifies C linkage.
2227   bool isExternCContext() const;
2228 
2229   /// Retrieve the nearest enclosing C linkage specification context.
2230   const LinkageSpecDecl *getExternCContext() const;
2231 
2232   /// Determines whether this context or some of its ancestors is a
2233   /// linkage specification context that specifies C++ linkage.
2234   bool isExternCXXContext() const;
2235 
2236   /// Determine whether this declaration context is equivalent
2237   /// to the declaration context DC.
2238   bool Equals(const DeclContext *DC) const {
2239     return DC && this->getPrimaryContext() == DC->getPrimaryContext();
2240   }
2241 
2242   /// Determine whether this declaration context encloses the
2243   /// declaration context DC.
2244   bool Encloses(const DeclContext *DC) const;
2245 
2246   /// Find the nearest non-closure ancestor of this context,
2247   /// i.e. the innermost semantic parent of this context which is not
2248   /// a closure.  A context may be its own non-closure ancestor.
2249   Decl *getNonClosureAncestor();
2250   const Decl *getNonClosureAncestor() const {
2251     return const_cast<DeclContext*>(this)->getNonClosureAncestor();
2252   }
2253 
2254   // Retrieve the nearest context that is not a transparent context.
2255   DeclContext *getNonTransparentContext();
2256   const DeclContext *getNonTransparentContext() const {
2257     return const_cast<DeclContext *>(this)->getNonTransparentContext();
2258   }
2259 
2260   /// getPrimaryContext - There may be many different
2261   /// declarations of the same entity (including forward declarations
2262   /// of classes, multiple definitions of namespaces, etc.), each with
2263   /// a different set of declarations. This routine returns the
2264   /// "primary" DeclContext structure, which will contain the
2265   /// information needed to perform name lookup into this context.
2266   DeclContext *getPrimaryContext();
2267   const DeclContext *getPrimaryContext() const {
2268     return const_cast<DeclContext*>(this)->getPrimaryContext();
2269   }
2270 
2271   /// getRedeclContext - Retrieve the context in which an entity conflicts with
2272   /// other entities of the same name, or where it is a redeclaration if the
2273   /// two entities are compatible. This skips through transparent contexts.
2274   DeclContext *getRedeclContext();
2275   const DeclContext *getRedeclContext() const {
2276     return const_cast<DeclContext *>(this)->getRedeclContext();
2277   }
2278 
2279   /// Retrieve the nearest enclosing namespace context.
2280   DeclContext *getEnclosingNamespaceContext();
2281   const DeclContext *getEnclosingNamespaceContext() const {
2282     return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2283   }
2284 
2285   /// Retrieve the outermost lexically enclosing record context.
2286   RecordDecl *getOuterLexicalRecordContext();
2287   const RecordDecl *getOuterLexicalRecordContext() const {
2288     return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2289   }
2290 
2291   /// Test if this context is part of the enclosing namespace set of
2292   /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2293   /// isn't a namespace, this is equivalent to Equals().
2294   ///
2295   /// The enclosing namespace set of a namespace is the namespace and, if it is
2296   /// inline, its enclosing namespace, recursively.
2297   bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2298 
2299   /// Collects all of the declaration contexts that are semantically
2300   /// connected to this declaration context.
2301   ///
2302   /// For declaration contexts that have multiple semantically connected but
2303   /// syntactically distinct contexts, such as C++ namespaces, this routine
2304   /// retrieves the complete set of such declaration contexts in source order.
2305   /// For example, given:
2306   ///
2307   /// \code
2308   /// namespace N {
2309   ///   int x;
2310   /// }
2311   /// namespace N {
2312   ///   int y;
2313   /// }
2314   /// \endcode
2315   ///
2316   /// The \c Contexts parameter will contain both definitions of N.
2317   ///
2318   /// \param Contexts Will be cleared and set to the set of declaration
2319   /// contexts that are semanticaly connected to this declaration context,
2320   /// in source order, including this context (which may be the only result,
2321   /// for non-namespace contexts).
2322   void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2323 
2324   /// decl_iterator - Iterates through the declarations stored
2325   /// within this context.
2326   class decl_iterator {
2327     /// Current - The current declaration.
2328     Decl *Current = nullptr;
2329 
2330   public:
2331     using value_type = Decl *;
2332     using reference = const value_type &;
2333     using pointer = const value_type *;
2334     using iterator_category = std::forward_iterator_tag;
2335     using difference_type = std::ptrdiff_t;
2336 
2337     decl_iterator() = default;
2338     explicit decl_iterator(Decl *C) : Current(C) {}
2339 
2340     reference operator*() const { return Current; }
2341 
2342     // This doesn't meet the iterator requirements, but it's convenient
2343     value_type operator->() const { return Current; }
2344 
2345     decl_iterator& operator++() {
2346       Current = Current->getNextDeclInContext();
2347       return *this;
2348     }
2349 
2350     decl_iterator operator++(int) {
2351       decl_iterator tmp(*this);
2352       ++(*this);
2353       return tmp;
2354     }
2355 
2356     friend bool operator==(decl_iterator x, decl_iterator y) {
2357       return x.Current == y.Current;
2358     }
2359 
2360     friend bool operator!=(decl_iterator x, decl_iterator y) {
2361       return x.Current != y.Current;
2362     }
2363   };
2364 
2365   using decl_range = llvm::iterator_range<decl_iterator>;
2366 
2367   /// decls_begin/decls_end - Iterate over the declarations stored in
2368   /// this context.
2369   decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2370   decl_iterator decls_begin() const;
2371   decl_iterator decls_end() const { return decl_iterator(); }
2372   bool decls_empty() const;
2373 
2374   /// noload_decls_begin/end - Iterate over the declarations stored in this
2375   /// context that are currently loaded; don't attempt to retrieve anything
2376   /// from an external source.
2377   decl_range noload_decls() const {
2378     return decl_range(noload_decls_begin(), noload_decls_end());
2379   }
2380   decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2381   decl_iterator noload_decls_end() const { return decl_iterator(); }
2382 
2383   /// specific_decl_iterator - Iterates over a subrange of
2384   /// declarations stored in a DeclContext, providing only those that
2385   /// are of type SpecificDecl (or a class derived from it). This
2386   /// iterator is used, for example, to provide iteration over just
2387   /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2388   template<typename SpecificDecl>
2389   class specific_decl_iterator {
2390     /// Current - The current, underlying declaration iterator, which
2391     /// will either be NULL or will point to a declaration of
2392     /// type SpecificDecl.
2393     DeclContext::decl_iterator Current;
2394 
2395     /// SkipToNextDecl - Advances the current position up to the next
2396     /// declaration of type SpecificDecl that also meets the criteria
2397     /// required by Acceptable.
2398     void SkipToNextDecl() {
2399       while (*Current && !isa<SpecificDecl>(*Current))
2400         ++Current;
2401     }
2402 
2403   public:
2404     using value_type = SpecificDecl *;
2405     // TODO: Add reference and pointer types (with some appropriate proxy type)
2406     // if we ever have a need for them.
2407     using reference = void;
2408     using pointer = void;
2409     using difference_type =
2410         std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2411     using iterator_category = std::forward_iterator_tag;
2412 
2413     specific_decl_iterator() = default;
2414 
2415     /// specific_decl_iterator - Construct a new iterator over a
2416     /// subset of the declarations the range [C,
2417     /// end-of-declarations). If A is non-NULL, it is a pointer to a
2418     /// member function of SpecificDecl that should return true for
2419     /// all of the SpecificDecl instances that will be in the subset
2420     /// of iterators. For example, if you want Objective-C instance
2421     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2422     /// &ObjCMethodDecl::isInstanceMethod.
2423     explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2424       SkipToNextDecl();
2425     }
2426 
2427     value_type operator*() const { return cast<SpecificDecl>(*Current); }
2428 
2429     // This doesn't meet the iterator requirements, but it's convenient
2430     value_type operator->() const { return **this; }
2431 
2432     specific_decl_iterator& operator++() {
2433       ++Current;
2434       SkipToNextDecl();
2435       return *this;
2436     }
2437 
2438     specific_decl_iterator operator++(int) {
2439       specific_decl_iterator tmp(*this);
2440       ++(*this);
2441       return tmp;
2442     }
2443 
2444     friend bool operator==(const specific_decl_iterator& x,
2445                            const specific_decl_iterator& y) {
2446       return x.Current == y.Current;
2447     }
2448 
2449     friend bool operator!=(const specific_decl_iterator& x,
2450                            const specific_decl_iterator& y) {
2451       return x.Current != y.Current;
2452     }
2453   };
2454 
2455   /// Iterates over a filtered subrange of declarations stored
2456   /// in a DeclContext.
2457   ///
2458   /// This iterator visits only those declarations that are of type
2459   /// SpecificDecl (or a class derived from it) and that meet some
2460   /// additional run-time criteria. This iterator is used, for
2461   /// example, to provide access to the instance methods within an
2462   /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2463   /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2464   template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2465   class filtered_decl_iterator {
2466     /// Current - The current, underlying declaration iterator, which
2467     /// will either be NULL or will point to a declaration of
2468     /// type SpecificDecl.
2469     DeclContext::decl_iterator Current;
2470 
2471     /// SkipToNextDecl - Advances the current position up to the next
2472     /// declaration of type SpecificDecl that also meets the criteria
2473     /// required by Acceptable.
2474     void SkipToNextDecl() {
2475       while (*Current &&
2476              (!isa<SpecificDecl>(*Current) ||
2477               (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2478         ++Current;
2479     }
2480 
2481   public:
2482     using value_type = SpecificDecl *;
2483     // TODO: Add reference and pointer types (with some appropriate proxy type)
2484     // if we ever have a need for them.
2485     using reference = void;
2486     using pointer = void;
2487     using difference_type =
2488         std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2489     using iterator_category = std::forward_iterator_tag;
2490 
2491     filtered_decl_iterator() = default;
2492 
2493     /// filtered_decl_iterator - Construct a new iterator over a
2494     /// subset of the declarations the range [C,
2495     /// end-of-declarations). If A is non-NULL, it is a pointer to a
2496     /// member function of SpecificDecl that should return true for
2497     /// all of the SpecificDecl instances that will be in the subset
2498     /// of iterators. For example, if you want Objective-C instance
2499     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2500     /// &ObjCMethodDecl::isInstanceMethod.
2501     explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2502       SkipToNextDecl();
2503     }
2504 
2505     value_type operator*() const { return cast<SpecificDecl>(*Current); }
2506     value_type operator->() const { return cast<SpecificDecl>(*Current); }
2507 
2508     filtered_decl_iterator& operator++() {
2509       ++Current;
2510       SkipToNextDecl();
2511       return *this;
2512     }
2513 
2514     filtered_decl_iterator operator++(int) {
2515       filtered_decl_iterator tmp(*this);
2516       ++(*this);
2517       return tmp;
2518     }
2519 
2520     friend bool operator==(const filtered_decl_iterator& x,
2521                            const filtered_decl_iterator& y) {
2522       return x.Current == y.Current;
2523     }
2524 
2525     friend bool operator!=(const filtered_decl_iterator& x,
2526                            const filtered_decl_iterator& y) {
2527       return x.Current != y.Current;
2528     }
2529   };
2530 
2531   /// Add the declaration D into this context.
2532   ///
2533   /// This routine should be invoked when the declaration D has first
2534   /// been declared, to place D into the context where it was
2535   /// (lexically) defined. Every declaration must be added to one
2536   /// (and only one!) context, where it can be visited via
2537   /// [decls_begin(), decls_end()). Once a declaration has been added
2538   /// to its lexical context, the corresponding DeclContext owns the
2539   /// declaration.
2540   ///
2541   /// If D is also a NamedDecl, it will be made visible within its
2542   /// semantic context via makeDeclVisibleInContext.
2543   void addDecl(Decl *D);
2544 
2545   /// Add the declaration D into this context, but suppress
2546   /// searches for external declarations with the same name.
2547   ///
2548   /// Although analogous in function to addDecl, this removes an
2549   /// important check.  This is only useful if the Decl is being
2550   /// added in response to an external search; in all other cases,
2551   /// addDecl() is the right function to use.
2552   /// See the ASTImporter for use cases.
2553   void addDeclInternal(Decl *D);
2554 
2555   /// Add the declaration D to this context without modifying
2556   /// any lookup tables.
2557   ///
2558   /// This is useful for some operations in dependent contexts where
2559   /// the semantic context might not be dependent;  this basically
2560   /// only happens with friends.
2561   void addHiddenDecl(Decl *D);
2562 
2563   /// Removes a declaration from this context.
2564   void removeDecl(Decl *D);
2565 
2566   /// Checks whether a declaration is in this context.
2567   bool containsDecl(Decl *D) const;
2568 
2569   /// Checks whether a declaration is in this context.
2570   /// This also loads the Decls from the external source before the check.
2571   bool containsDeclAndLoad(Decl *D) const;
2572 
2573   using lookup_result = DeclContextLookupResult;
2574   using lookup_iterator = lookup_result::iterator;
2575 
2576   /// lookup - Find the declarations (if any) with the given Name in
2577   /// this context. Returns a range of iterators that contains all of
2578   /// the declarations with this name, with object, function, member,
2579   /// and enumerator names preceding any tag name. Note that this
2580   /// routine will not look into parent contexts.
2581   lookup_result lookup(DeclarationName Name) const;
2582 
2583   /// Find the declarations with the given name that are visible
2584   /// within this context; don't attempt to retrieve anything from an
2585   /// external source.
2586   lookup_result noload_lookup(DeclarationName Name);
2587 
2588   /// A simplistic name lookup mechanism that performs name lookup
2589   /// into this declaration context without consulting the external source.
2590   ///
2591   /// This function should almost never be used, because it subverts the
2592   /// usual relationship between a DeclContext and the external source.
2593   /// See the ASTImporter for the (few, but important) use cases.
2594   ///
2595   /// FIXME: This is very inefficient; replace uses of it with uses of
2596   /// noload_lookup.
2597   void localUncachedLookup(DeclarationName Name,
2598                            SmallVectorImpl<NamedDecl *> &Results);
2599 
2600   /// Makes a declaration visible within this context.
2601   ///
2602   /// This routine makes the declaration D visible to name lookup
2603   /// within this context and, if this is a transparent context,
2604   /// within its parent contexts up to the first enclosing
2605   /// non-transparent context. Making a declaration visible within a
2606   /// context does not transfer ownership of a declaration, and a
2607   /// declaration can be visible in many contexts that aren't its
2608   /// lexical context.
2609   ///
2610   /// If D is a redeclaration of an existing declaration that is
2611   /// visible from this context, as determined by
2612   /// NamedDecl::declarationReplaces, the previous declaration will be
2613   /// replaced with D.
2614   void makeDeclVisibleInContext(NamedDecl *D);
2615 
2616   /// all_lookups_iterator - An iterator that provides a view over the results
2617   /// of looking up every possible name.
2618   class all_lookups_iterator;
2619 
2620   using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2621 
2622   lookups_range lookups() const;
2623   // Like lookups(), but avoids loading external declarations.
2624   // If PreserveInternalState, avoids building lookup data structures too.
2625   lookups_range noload_lookups(bool PreserveInternalState) const;
2626 
2627   /// Iterators over all possible lookups within this context.
2628   all_lookups_iterator lookups_begin() const;
2629   all_lookups_iterator lookups_end() const;
2630 
2631   /// Iterators over all possible lookups within this context that are
2632   /// currently loaded; don't attempt to retrieve anything from an external
2633   /// source.
2634   all_lookups_iterator noload_lookups_begin() const;
2635   all_lookups_iterator noload_lookups_end() const;
2636 
2637   struct udir_iterator;
2638 
2639   using udir_iterator_base =
2640       llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2641                                   typename lookup_iterator::iterator_category,
2642                                   UsingDirectiveDecl *>;
2643 
2644   struct udir_iterator : udir_iterator_base {
2645     udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2646 
2647     UsingDirectiveDecl *operator*() const;
2648   };
2649 
2650   using udir_range = llvm::iterator_range<udir_iterator>;
2651 
2652   udir_range using_directives() const;
2653 
2654   // These are all defined in DependentDiagnostic.h.
2655   class ddiag_iterator;
2656 
2657   using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2658 
2659   inline ddiag_range ddiags() const;
2660 
2661   // Low-level accessors
2662 
2663   /// Mark that there are external lexical declarations that we need
2664   /// to include in our lookup table (and that are not available as external
2665   /// visible lookups). These extra lookup results will be found by walking
2666   /// the lexical declarations of this context. This should be used only if
2667   /// setHasExternalLexicalStorage() has been called on any decl context for
2668   /// which this is the primary context.
2669   void setMustBuildLookupTable() {
2670     assert(this == getPrimaryContext() &&
2671            "should only be called on primary context");
2672     DeclContextBits.HasLazyExternalLexicalLookups = true;
2673   }
2674 
2675   /// Retrieve the internal representation of the lookup structure.
2676   /// This may omit some names if we are lazily building the structure.
2677   StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2678 
2679   /// Ensure the lookup structure is fully-built and return it.
2680   StoredDeclsMap *buildLookup();
2681 
2682   /// Whether this DeclContext has external storage containing
2683   /// additional declarations that are lexically in this context.
2684   bool hasExternalLexicalStorage() const {
2685     return DeclContextBits.ExternalLexicalStorage;
2686   }
2687 
2688   /// State whether this DeclContext has external storage for
2689   /// declarations lexically in this context.
2690   void setHasExternalLexicalStorage(bool ES = true) const {
2691     DeclContextBits.ExternalLexicalStorage = ES;
2692   }
2693 
2694   /// Whether this DeclContext has external storage containing
2695   /// additional declarations that are visible in this context.
2696   bool hasExternalVisibleStorage() const {
2697     return DeclContextBits.ExternalVisibleStorage;
2698   }
2699 
2700   /// State whether this DeclContext has external storage for
2701   /// declarations visible in this context.
2702   void setHasExternalVisibleStorage(bool ES = true) const {
2703     DeclContextBits.ExternalVisibleStorage = ES;
2704     if (ES && LookupPtr)
2705       DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2706   }
2707 
2708   /// Determine whether the given declaration is stored in the list of
2709   /// declarations lexically within this context.
2710   bool isDeclInLexicalTraversal(const Decl *D) const {
2711     return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2712                  D == LastDecl);
2713   }
2714 
2715   void setUseQualifiedLookup(bool use = true) const {
2716     DeclContextBits.UseQualifiedLookup = use;
2717   }
2718 
2719   bool shouldUseQualifiedLookup() const {
2720     return DeclContextBits.UseQualifiedLookup;
2721   }
2722 
2723   static bool classof(const Decl *D);
2724   static bool classof(const DeclContext *D) { return true; }
2725 
2726   void dumpAsDecl() const;
2727   void dumpAsDecl(const ASTContext *Ctx) const;
2728   void dumpDeclContext() const;
2729   void dumpLookups() const;
2730   void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2731                    bool Deserialize = false) const;
2732 
2733 private:
2734   lookup_result lookupImpl(DeclarationName Name,
2735                            const DeclContext *OriginalLookupDC) const;
2736 
2737   /// Whether this declaration context has had externally visible
2738   /// storage added since the last lookup. In this case, \c LookupPtr's
2739   /// invariant may not hold and needs to be fixed before we perform
2740   /// another lookup.
2741   bool hasNeedToReconcileExternalVisibleStorage() const {
2742     return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2743   }
2744 
2745   /// State that this declaration context has had externally visible
2746   /// storage added since the last lookup. In this case, \c LookupPtr's
2747   /// invariant may not hold and needs to be fixed before we perform
2748   /// another lookup.
2749   void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2750     DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2751   }
2752 
2753   /// If \c true, this context may have local lexical declarations
2754   /// that are missing from the lookup table.
2755   bool hasLazyLocalLexicalLookups() const {
2756     return DeclContextBits.HasLazyLocalLexicalLookups;
2757   }
2758 
2759   /// If \c true, this context may have local lexical declarations
2760   /// that are missing from the lookup table.
2761   void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2762     DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2763   }
2764 
2765   /// If \c true, the external source may have lexical declarations
2766   /// that are missing from the lookup table.
2767   bool hasLazyExternalLexicalLookups() const {
2768     return DeclContextBits.HasLazyExternalLexicalLookups;
2769   }
2770 
2771   /// If \c true, the external source may have lexical declarations
2772   /// that are missing from the lookup table.
2773   void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2774     DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2775   }
2776 
2777   void reconcileExternalVisibleStorage() const;
2778   bool LoadLexicalDeclsFromExternalStorage() const;
2779 
2780   StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2781 
2782   void loadLazyLocalLexicalLookups();
2783   void buildLookupImpl(DeclContext *DCtx, bool Internal);
2784   void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2785                                          bool Rediscoverable);
2786   void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2787 };
2788 
2789 inline bool Decl::isTemplateParameter() const {
2790   return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2791          getKind() == TemplateTemplateParm;
2792 }
2793 
2794 // Specialization selected when ToTy is not a known subclass of DeclContext.
2795 template <class ToTy,
2796           bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2797 struct cast_convert_decl_context {
2798   static const ToTy *doit(const DeclContext *Val) {
2799     return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2800   }
2801 
2802   static ToTy *doit(DeclContext *Val) {
2803     return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2804   }
2805 };
2806 
2807 // Specialization selected when ToTy is a known subclass of DeclContext.
2808 template <class ToTy>
2809 struct cast_convert_decl_context<ToTy, true> {
2810   static const ToTy *doit(const DeclContext *Val) {
2811     return static_cast<const ToTy*>(Val);
2812   }
2813 
2814   static ToTy *doit(DeclContext *Val) {
2815     return static_cast<ToTy*>(Val);
2816   }
2817 };
2818 
2819 } // namespace clang
2820 
2821 namespace llvm {
2822 
2823 /// isa<T>(DeclContext*)
2824 template <typename To>
2825 struct isa_impl<To, ::clang::DeclContext> {
2826   static bool doit(const ::clang::DeclContext &Val) {
2827     return To::classofKind(Val.getDeclKind());
2828   }
2829 };
2830 
2831 /// cast<T>(DeclContext*)
2832 template<class ToTy>
2833 struct cast_convert_val<ToTy,
2834                         const ::clang::DeclContext,const ::clang::DeclContext> {
2835   static const ToTy &doit(const ::clang::DeclContext &Val) {
2836     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2837   }
2838 };
2839 
2840 template<class ToTy>
2841 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2842   static ToTy &doit(::clang::DeclContext &Val) {
2843     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2844   }
2845 };
2846 
2847 template<class ToTy>
2848 struct cast_convert_val<ToTy,
2849                      const ::clang::DeclContext*, const ::clang::DeclContext*> {
2850   static const ToTy *doit(const ::clang::DeclContext *Val) {
2851     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2852   }
2853 };
2854 
2855 template<class ToTy>
2856 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2857   static ToTy *doit(::clang::DeclContext *Val) {
2858     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2859   }
2860 };
2861 
2862 /// Implement cast_convert_val for Decl -> DeclContext conversions.
2863 template<class FromTy>
2864 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2865   static ::clang::DeclContext &doit(const FromTy &Val) {
2866     return *FromTy::castToDeclContext(&Val);
2867   }
2868 };
2869 
2870 template<class FromTy>
2871 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2872   static ::clang::DeclContext *doit(const FromTy *Val) {
2873     return FromTy::castToDeclContext(Val);
2874   }
2875 };
2876 
2877 template<class FromTy>
2878 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2879   static const ::clang::DeclContext &doit(const FromTy &Val) {
2880     return *FromTy::castToDeclContext(&Val);
2881   }
2882 };
2883 
2884 template<class FromTy>
2885 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2886   static const ::clang::DeclContext *doit(const FromTy *Val) {
2887     return FromTy::castToDeclContext(Val);
2888   }
2889 };
2890 
2891 } // namespace llvm
2892 
2893 #endif // LLVM_CLANG_AST_DECLBASE_H