Home | History | Annotate | Download | only in AST
      1 //===-- DeclBase.h - Base Classes for representing declarations -*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file defines the Decl and DeclContext interfaces.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_AST_DECLBASE_H
     15 #define LLVM_CLANG_AST_DECLBASE_H
     16 
     17 #include "clang/AST/AttrIterator.h"
     18 #include "clang/AST/DeclarationName.h"
     19 #include "clang/Basic/Specifiers.h"
     20 #include "clang/Basic/VersionTuple.h"
     21 #include "llvm/ADT/PointerUnion.h"
     22 #include "llvm/ADT/iterator.h"
     23 #include "llvm/ADT/iterator_range.h"
     24 #include "llvm/Support/Compiler.h"
     25 #include "llvm/Support/PrettyStackTrace.h"
     26 
     27 namespace clang {
     28 class ASTMutationListener;
     29 class BlockDecl;
     30 class CXXRecordDecl;
     31 class CompoundStmt;
     32 class DeclContext;
     33 class DeclarationName;
     34 class DependentDiagnostic;
     35 class EnumDecl;
     36 class ExportDecl;
     37 class FunctionDecl;
     38 class FunctionType;
     39 enum Linkage : unsigned char;
     40 class LinkageComputer;
     41 class LinkageSpecDecl;
     42 class Module;
     43 class NamedDecl;
     44 class NamespaceDecl;
     45 class ObjCCategoryDecl;
     46 class ObjCCategoryImplDecl;
     47 class ObjCContainerDecl;
     48 class ObjCImplDecl;
     49 class ObjCImplementationDecl;
     50 class ObjCInterfaceDecl;
     51 class ObjCMethodDecl;
     52 class ObjCProtocolDecl;
     53 struct PrintingPolicy;
     54 class RecordDecl;
     55 class Stmt;
     56 class StoredDeclsMap;
     57 class TemplateDecl;
     58 class TranslationUnitDecl;
     59 class UsingDirectiveDecl;
     60 }
     61 
     62 namespace clang {
     63 
     64   /// \brief Captures the result of checking the availability of a
     65   /// declaration.
     66   enum AvailabilityResult {
     67     AR_Available = 0,
     68     AR_NotYetIntroduced,
     69     AR_Deprecated,
     70     AR_Unavailable
     71   };
     72 
     73 /// Decl - This represents one declaration (or definition), e.g. a variable,
     74 /// typedef, function, struct, etc.
     75 ///
     76 /// Note: There are objects tacked on before the *beginning* of Decl
     77 /// (and its subclasses) in its Decl::operator new(). Proper alignment
     78 /// of all subclasses (not requiring more than the alignment of Decl) is
     79 /// asserted in DeclBase.cpp.
     80 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) Decl {
     81 public:
     82   /// \brief Lists the kind of concrete classes of Decl.
     83   enum Kind {
     84 #define DECL(DERIVED, BASE) DERIVED,
     85 #define ABSTRACT_DECL(DECL)
     86 #define DECL_RANGE(BASE, START, END) \
     87         first##BASE = START, last##BASE = END,
     88 #define LAST_DECL_RANGE(BASE, START, END) \
     89         first##BASE = START, last##BASE = END
     90 #include "clang/AST/DeclNodes.inc"
     91   };
     92 
     93   /// \brief A placeholder type used to construct an empty shell of a
     94   /// decl-derived type that will be filled in later (e.g., by some
     95   /// deserialization method).
     96   struct EmptyShell { };
     97 
     98   /// IdentifierNamespace - The different namespaces in which
     99   /// declarations may appear.  According to C99 6.2.3, there are
    100   /// four namespaces, labels, tags, members and ordinary
    101   /// identifiers.  C++ describes lookup completely differently:
    102   /// certain lookups merely "ignore" certain kinds of declarations,
    103   /// usually based on whether the declaration is of a type, etc.
    104   ///
    105   /// These are meant as bitmasks, so that searches in
    106   /// C++ can look into the "tag" namespace during ordinary lookup.
    107   ///
    108   /// Decl currently provides 15 bits of IDNS bits.
    109   enum IdentifierNamespace {
    110     /// Labels, declared with 'x:' and referenced with 'goto x'.
    111     IDNS_Label               = 0x0001,
    112 
    113     /// Tags, declared with 'struct foo;' and referenced with
    114     /// 'struct foo'.  All tags are also types.  This is what
    115     /// elaborated-type-specifiers look for in C.
    116     /// This also contains names that conflict with tags in the
    117     /// same scope but that are otherwise ordinary names (non-type
    118     /// template parameters and indirect field declarations).
    119     IDNS_Tag                 = 0x0002,
    120 
    121     /// Types, declared with 'struct foo', typedefs, etc.
    122     /// This is what elaborated-type-specifiers look for in C++,
    123     /// but note that it's ill-formed to find a non-tag.
    124     IDNS_Type                = 0x0004,
    125 
    126     /// Members, declared with object declarations within tag
    127     /// definitions.  In C, these can only be found by "qualified"
    128     /// lookup in member expressions.  In C++, they're found by
    129     /// normal lookup.
    130     IDNS_Member              = 0x0008,
    131 
    132     /// Namespaces, declared with 'namespace foo {}'.
    133     /// Lookup for nested-name-specifiers find these.
    134     IDNS_Namespace           = 0x0010,
    135 
    136     /// Ordinary names.  In C, everything that's not a label, tag,
    137     /// member, or function-local extern ends up here.
    138     IDNS_Ordinary            = 0x0020,
    139 
    140     /// Objective C \@protocol.
    141     IDNS_ObjCProtocol        = 0x0040,
    142 
    143     /// This declaration is a friend function.  A friend function
    144     /// declaration is always in this namespace but may also be in
    145     /// IDNS_Ordinary if it was previously declared.
    146     IDNS_OrdinaryFriend      = 0x0080,
    147 
    148     /// This declaration is a friend class.  A friend class
    149     /// declaration is always in this namespace but may also be in
    150     /// IDNS_Tag|IDNS_Type if it was previously declared.
    151     IDNS_TagFriend           = 0x0100,
    152 
    153     /// This declaration is a using declaration.  A using declaration
    154     /// *introduces* a number of other declarations into the current
    155     /// scope, and those declarations use the IDNS of their targets,
    156     /// but the actual using declarations go in this namespace.
    157     IDNS_Using               = 0x0200,
    158 
    159     /// This declaration is a C++ operator declared in a non-class
    160     /// context.  All such operators are also in IDNS_Ordinary.
    161     /// C++ lexical operator lookup looks for these.
    162     IDNS_NonMemberOperator   = 0x0400,
    163 
    164     /// This declaration is a function-local extern declaration of a
    165     /// variable or function. This may also be IDNS_Ordinary if it
    166     /// has been declared outside any function. These act mostly like
    167     /// invisible friend declarations, but are also visible to unqualified
    168     /// lookup within the scope of the declaring function.
    169     IDNS_LocalExtern         = 0x0800,
    170 
    171     /// This declaration is an OpenMP user defined reduction construction.
    172     IDNS_OMPReduction        = 0x1000
    173   };
    174 
    175   /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
    176   /// parameter types in method declarations.  Other than remembering
    177   /// them and mangling them into the method's signature string, these
    178   /// are ignored by the compiler; they are consumed by certain
    179   /// remote-messaging frameworks.
    180   ///
    181   /// in, inout, and out are mutually exclusive and apply only to
    182   /// method parameters.  bycopy and byref are mutually exclusive and
    183   /// apply only to method parameters (?).  oneway applies only to
    184   /// results.  All of these expect their corresponding parameter to
    185   /// have a particular type.  None of this is currently enforced by
    186   /// clang.
    187   ///
    188   /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
    189   enum ObjCDeclQualifier {
    190     OBJC_TQ_None = 0x0,
    191     OBJC_TQ_In = 0x1,
    192     OBJC_TQ_Inout = 0x2,
    193     OBJC_TQ_Out = 0x4,
    194     OBJC_TQ_Bycopy = 0x8,
    195     OBJC_TQ_Byref = 0x10,
    196     OBJC_TQ_Oneway = 0x20,
    197 
    198     /// The nullability qualifier is set when the nullability of the
    199     /// result or parameter was expressed via a context-sensitive
    200     /// keyword.
    201     OBJC_TQ_CSNullability = 0x40
    202   };
    203 
    204 protected:
    205   // Enumeration values used in the bits stored in NextInContextAndBits.
    206   enum {
    207     /// \brief Whether this declaration is a top-level declaration (function,
    208     /// global variable, etc.) that is lexically inside an objc container
    209     /// definition.
    210     TopLevelDeclInObjCContainerFlag = 0x01,
    211 
    212     /// \brief Whether this declaration is private to the module in which it was
    213     /// defined.
    214     ModulePrivateFlag = 0x02
    215   };
    216 
    217   /// \brief The next declaration within the same lexical
    218   /// DeclContext. These pointers form the linked list that is
    219   /// traversed via DeclContext's decls_begin()/decls_end().
    220   ///
    221   /// The extra two bits are used for the TopLevelDeclInObjCContainer and
    222   /// ModulePrivate bits.
    223   llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
    224 
    225 private:
    226   friend class DeclContext;
    227 
    228   struct MultipleDC {
    229     DeclContext *SemanticDC;
    230     DeclContext *LexicalDC;
    231   };
    232 
    233 
    234   /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
    235   /// For declarations that don't contain C++ scope specifiers, it contains
    236   /// the DeclContext where the Decl was declared.
    237   /// For declarations with C++ scope specifiers, it contains a MultipleDC*
    238   /// with the context where it semantically belongs (SemanticDC) and the
    239   /// context where it was lexically declared (LexicalDC).
    240   /// e.g.:
    241   ///
    242   ///   namespace A {
    243   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
    244   ///   }
    245   ///   void A::f(); // SemanticDC == namespace 'A'
    246   ///                // LexicalDC == global namespace
    247   llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
    248 
    249   inline bool isInSemaDC() const    { return DeclCtx.is<DeclContext*>(); }
    250   inline bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
    251   inline MultipleDC *getMultipleDC() const {
    252     return DeclCtx.get<MultipleDC*>();
    253   }
    254   inline DeclContext *getSemanticDC() const {
    255     return DeclCtx.get<DeclContext*>();
    256   }
    257 
    258   /// Loc - The location of this decl.
    259   SourceLocation Loc;
    260 
    261   /// DeclKind - This indicates which class this is.
    262   unsigned DeclKind : 7;
    263 
    264   /// InvalidDecl - This indicates a semantic error occurred.
    265   unsigned InvalidDecl :  1;
    266 
    267   /// HasAttrs - This indicates whether the decl has attributes or not.
    268   unsigned HasAttrs : 1;
    269 
    270   /// Implicit - Whether this declaration was implicitly generated by
    271   /// the implementation rather than explicitly written by the user.
    272   unsigned Implicit : 1;
    273 
    274   /// \brief Whether this declaration was "used", meaning that a definition is
    275   /// required.
    276   unsigned Used : 1;
    277 
    278   /// \brief Whether this declaration was "referenced".
    279   /// The difference with 'Used' is whether the reference appears in a
    280   /// evaluated context or not, e.g. functions used in uninstantiated templates
    281   /// are regarded as "referenced" but not "used".
    282   unsigned Referenced : 1;
    283 
    284   /// \brief Whether statistic collection is enabled.
    285   static bool StatisticsEnabled;
    286 
    287 protected:
    288   /// Access - Used by C++ decls for the access specifier.
    289   // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
    290   unsigned Access : 2;
    291   friend class CXXClassMemberWrapper;
    292 
    293   /// \brief Whether this declaration was loaded from an AST file.
    294   unsigned FromASTFile : 1;
    295 
    296   /// \brief Whether this declaration is hidden from normal name lookup, e.g.,
    297   /// because it is was loaded from an AST file is either module-private or
    298   /// because its submodule has not been made visible.
    299   unsigned Hidden : 1;
    300 
    301   /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
    302   unsigned IdentifierNamespace : 13;
    303 
    304   /// \brief If 0, we have not computed the linkage of this declaration.
    305   /// Otherwise, it is the linkage + 1.
    306   mutable unsigned CacheValidAndLinkage : 3;
    307 
    308   friend class ASTDeclWriter;
    309   friend class ASTDeclReader;
    310   friend class ASTReader;
    311   friend class LinkageComputer;
    312 
    313   template<typename decl_type> friend class Redeclarable;
    314 
    315   /// \brief Allocate memory for a deserialized declaration.
    316   ///
    317   /// This routine must be used to allocate memory for any declaration that is
    318   /// deserialized from a module file.
    319   ///
    320   /// \param Size The size of the allocated object.
    321   /// \param Ctx The context in which we will allocate memory.
    322   /// \param ID The global ID of the deserialized declaration.
    323   /// \param Extra The amount of extra space to allocate after the object.
    324   void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
    325                      std::size_t Extra = 0);
    326 
    327   /// \brief Allocate memory for a non-deserialized declaration.
    328   void *operator new(std::size_t Size, const ASTContext &Ctx,
    329                      DeclContext *Parent, std::size_t Extra = 0);
    330 
    331 private:
    332   bool AccessDeclContextSanity() const;
    333 
    334 protected:
    335 
    336   Decl(Kind DK, DeclContext *DC, SourceLocation L)
    337     : NextInContextAndBits(), DeclCtx(DC),
    338       Loc(L), DeclKind(DK), InvalidDecl(0),
    339       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
    340       Access(AS_none), FromASTFile(0), Hidden(DC && cast<Decl>(DC)->Hidden),
    341       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
    342       CacheValidAndLinkage(0)
    343   {
    344     if (StatisticsEnabled) add(DK);
    345   }
    346 
    347   Decl(Kind DK, EmptyShell Empty)
    348     : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
    349       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
    350       Access(AS_none), FromASTFile(0), Hidden(0),
    351       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
    352       CacheValidAndLinkage(0)
    353   {
    354     if (StatisticsEnabled) add(DK);
    355   }
    356 
    357   virtual ~Decl();
    358 
    359   /// \brief Update a potentially out-of-date declaration.
    360   void updateOutOfDate(IdentifierInfo &II) const;
    361 
    362   Linkage getCachedLinkage() const {
    363     return Linkage(CacheValidAndLinkage - 1);
    364   }
    365 
    366   void setCachedLinkage(Linkage L) const {
    367     CacheValidAndLinkage = L + 1;
    368   }
    369 
    370   bool hasCachedLinkage() const {
    371     return CacheValidAndLinkage;
    372   }
    373 
    374 public:
    375 
    376   /// \brief Source range that this declaration covers.
    377   virtual SourceRange getSourceRange() const LLVM_READONLY {
    378     return SourceRange(getLocation(), getLocation());
    379   }
    380   SourceLocation getLocStart() const LLVM_READONLY {
    381     return getSourceRange().getBegin();
    382   }
    383   SourceLocation getLocEnd() const LLVM_READONLY {
    384     return getSourceRange().getEnd();
    385   }
    386 
    387   SourceLocation getLocation() const { return Loc; }
    388   void setLocation(SourceLocation L) { Loc = L; }
    389 
    390   Kind getKind() const { return static_cast<Kind>(DeclKind); }
    391   const char *getDeclKindName() const;
    392 
    393   Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
    394   const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
    395 
    396   DeclContext *getDeclContext() {
    397     if (isInSemaDC())
    398       return getSemanticDC();
    399     return getMultipleDC()->SemanticDC;
    400   }
    401   const DeclContext *getDeclContext() const {
    402     return const_cast<Decl*>(this)->getDeclContext();
    403   }
    404 
    405   /// Find the innermost non-closure ancestor of this declaration,
    406   /// walking up through blocks, lambdas, etc.  If that ancestor is
    407   /// not a code context (!isFunctionOrMethod()), returns null.
    408   ///
    409   /// A declaration may be its own non-closure context.
    410   Decl *getNonClosureContext();
    411   const Decl *getNonClosureContext() const {
    412     return const_cast<Decl*>(this)->getNonClosureContext();
    413   }
    414 
    415   TranslationUnitDecl *getTranslationUnitDecl();
    416   const TranslationUnitDecl *getTranslationUnitDecl() const {
    417     return const_cast<Decl*>(this)->getTranslationUnitDecl();
    418   }
    419 
    420   bool isInAnonymousNamespace() const;
    421 
    422   bool isInStdNamespace() const;
    423 
    424   ASTContext &getASTContext() const LLVM_READONLY;
    425 
    426   void setAccess(AccessSpecifier AS) {
    427     Access = AS;
    428     assert(AccessDeclContextSanity());
    429   }
    430 
    431   AccessSpecifier getAccess() const {
    432     assert(AccessDeclContextSanity());
    433     return AccessSpecifier(Access);
    434   }
    435 
    436   /// \brief Retrieve the access specifier for this declaration, even though
    437   /// it may not yet have been properly set.
    438   AccessSpecifier getAccessUnsafe() const {
    439     return AccessSpecifier(Access);
    440   }
    441 
    442   bool hasAttrs() const { return HasAttrs; }
    443   void setAttrs(const AttrVec& Attrs) {
    444     return setAttrsImpl(Attrs, getASTContext());
    445   }
    446   AttrVec &getAttrs() {
    447     return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
    448   }
    449   const AttrVec &getAttrs() const;
    450   void dropAttrs();
    451 
    452   void addAttr(Attr *A) {
    453     if (hasAttrs())
    454       getAttrs().push_back(A);
    455     else
    456       setAttrs(AttrVec(1, A));
    457   }
    458 
    459   typedef AttrVec::const_iterator attr_iterator;
    460   typedef llvm::iterator_range<attr_iterator> attr_range;
    461 
    462   attr_range attrs() const {
    463     return attr_range(attr_begin(), attr_end());
    464   }
    465 
    466   attr_iterator attr_begin() const {
    467     return hasAttrs() ? getAttrs().begin() : nullptr;
    468   }
    469   attr_iterator attr_end() const {
    470     return hasAttrs() ? getAttrs().end() : nullptr;
    471   }
    472 
    473   template <typename T>
    474   void dropAttr() {
    475     if (!HasAttrs) return;
    476 
    477     AttrVec &Vec = getAttrs();
    478     Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
    479 
    480     if (Vec.empty())
    481       HasAttrs = false;
    482   }
    483 
    484   template <typename T>
    485   llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
    486     return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
    487   }
    488 
    489   template <typename T>
    490   specific_attr_iterator<T> specific_attr_begin() const {
    491     return specific_attr_iterator<T>(attr_begin());
    492   }
    493   template <typename T>
    494   specific_attr_iterator<T> specific_attr_end() const {
    495     return specific_attr_iterator<T>(attr_end());
    496   }
    497 
    498   template<typename T> T *getAttr() const {
    499     return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
    500   }
    501   template<typename T> bool hasAttr() const {
    502     return hasAttrs() && hasSpecificAttr<T>(getAttrs());
    503   }
    504 
    505   /// getMaxAlignment - return the maximum alignment specified by attributes
    506   /// on this decl, 0 if there are none.
    507   unsigned getMaxAlignment() const;
    508 
    509   /// setInvalidDecl - Indicates the Decl had a semantic error. This
    510   /// allows for graceful error recovery.
    511   void setInvalidDecl(bool Invalid = true);
    512   bool isInvalidDecl() const { return (bool) InvalidDecl; }
    513 
    514   /// isImplicit - Indicates whether the declaration was implicitly
    515   /// generated by the implementation. If false, this declaration
    516   /// was written explicitly in the source code.
    517   bool isImplicit() const { return Implicit; }
    518   void setImplicit(bool I = true) { Implicit = I; }
    519 
    520   /// \brief Whether *any* (re-)declaration of the entity was used, meaning that
    521   /// a definition is required.
    522   ///
    523   /// \param CheckUsedAttr When true, also consider the "used" attribute
    524   /// (in addition to the "used" bit set by \c setUsed()) when determining
    525   /// whether the function is used.
    526   bool isUsed(bool CheckUsedAttr = true) const;
    527 
    528   /// \brief Set whether the declaration is used, in the sense of odr-use.
    529   ///
    530   /// This should only be used immediately after creating a declaration.
    531   /// It intentionally doesn't notify any listeners.
    532   void setIsUsed() { getCanonicalDecl()->Used = true; }
    533 
    534   /// \brief Mark the declaration used, in the sense of odr-use.
    535   ///
    536   /// This notifies any mutation listeners in addition to setting a bit
    537   /// indicating the declaration is used.
    538   void markUsed(ASTContext &C);
    539 
    540   /// \brief Whether any declaration of this entity was referenced.
    541   bool isReferenced() const;
    542 
    543   /// \brief Whether this declaration was referenced. This should not be relied
    544   /// upon for anything other than debugging.
    545   bool isThisDeclarationReferenced() const { return Referenced; }
    546 
    547   void setReferenced(bool R = true) { Referenced = R; }
    548 
    549   /// \brief Whether this declaration is a top-level declaration (function,
    550   /// global variable, etc.) that is lexically inside an objc container
    551   /// definition.
    552   bool isTopLevelDeclInObjCContainer() const {
    553     return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
    554   }
    555 
    556   void setTopLevelDeclInObjCContainer(bool V = true) {
    557     unsigned Bits = NextInContextAndBits.getInt();
    558     if (V)
    559       Bits |= TopLevelDeclInObjCContainerFlag;
    560     else
    561       Bits &= ~TopLevelDeclInObjCContainerFlag;
    562     NextInContextAndBits.setInt(Bits);
    563   }
    564 
    565   /// \brief Whether this declaration was marked as being private to the
    566   /// module in which it was defined.
    567   bool isModulePrivate() const {
    568     return NextInContextAndBits.getInt() & ModulePrivateFlag;
    569   }
    570 
    571   /// \brief Whether this declaration is exported (by virtue of being lexically
    572   /// within an ExportDecl or by being a NamespaceDecl).
    573   bool isExported() const;
    574 
    575   /// Return true if this declaration has an attribute which acts as
    576   /// definition of the entity, such as 'alias' or 'ifunc'.
    577   bool hasDefiningAttr() const;
    578 
    579   /// Return this declaration's defining attribute if it has one.
    580   const Attr *getDefiningAttr() const;
    581 
    582 protected:
    583   /// \brief Specify whether this declaration was marked as being private
    584   /// to the module in which it was defined.
    585   void setModulePrivate(bool MP = true) {
    586     unsigned Bits = NextInContextAndBits.getInt();
    587     if (MP)
    588       Bits |= ModulePrivateFlag;
    589     else
    590       Bits &= ~ModulePrivateFlag;
    591     NextInContextAndBits.setInt(Bits);
    592   }
    593 
    594   /// \brief Set the owning module ID.
    595   void setOwningModuleID(unsigned ID) {
    596     assert(isFromASTFile() && "Only works on a deserialized declaration");
    597     *((unsigned*)this - 2) = ID;
    598   }
    599 
    600 public:
    601 
    602   /// \brief Determine the availability of the given declaration.
    603   ///
    604   /// This routine will determine the most restrictive availability of
    605   /// the given declaration (e.g., preferring 'unavailable' to
    606   /// 'deprecated').
    607   ///
    608   /// \param Message If non-NULL and the result is not \c
    609   /// AR_Available, will be set to a (possibly empty) message
    610   /// describing why the declaration has not been introduced, is
    611   /// deprecated, or is unavailable.
    612   ///
    613   /// \param EnclosingVersion The version to compare with. If empty, assume the
    614   /// deployment target version.
    615   AvailabilityResult
    616   getAvailability(std::string *Message = nullptr,
    617                   VersionTuple EnclosingVersion = VersionTuple()) const;
    618 
    619   /// \brief Determine whether this declaration is marked 'deprecated'.
    620   ///
    621   /// \param Message If non-NULL and the declaration is deprecated,
    622   /// this will be set to the message describing why the declaration
    623   /// was deprecated (which may be empty).
    624   bool isDeprecated(std::string *Message = nullptr) const {
    625     return getAvailability(Message) == AR_Deprecated;
    626   }
    627 
    628   /// \brief Determine whether this declaration is marked 'unavailable'.
    629   ///
    630   /// \param Message If non-NULL and the declaration is unavailable,
    631   /// this will be set to the message describing why the declaration
    632   /// was made unavailable (which may be empty).
    633   bool isUnavailable(std::string *Message = nullptr) const {
    634     return getAvailability(Message) == AR_Unavailable;
    635   }
    636 
    637   /// \brief Determine whether this is a weak-imported symbol.
    638   ///
    639   /// Weak-imported symbols are typically marked with the
    640   /// 'weak_import' attribute, but may also be marked with an
    641   /// 'availability' attribute where we're targing a platform prior to
    642   /// the introduction of this feature.
    643   bool isWeakImported() const;
    644 
    645   /// \brief Determines whether this symbol can be weak-imported,
    646   /// e.g., whether it would be well-formed to add the weak_import
    647   /// attribute.
    648   ///
    649   /// \param IsDefinition Set to \c true to indicate that this
    650   /// declaration cannot be weak-imported because it has a definition.
    651   bool canBeWeakImported(bool &IsDefinition) const;
    652 
    653   /// \brief Determine whether this declaration came from an AST file (such as
    654   /// a precompiled header or module) rather than having been parsed.
    655   bool isFromASTFile() const { return FromASTFile; }
    656 
    657   /// \brief Retrieve the global declaration ID associated with this
    658   /// declaration, which specifies where this Decl was loaded from.
    659   unsigned getGlobalID() const {
    660     if (isFromASTFile())
    661       return *((const unsigned*)this - 1);
    662     return 0;
    663   }
    664 
    665   /// \brief Retrieve the global ID of the module that owns this particular
    666   /// declaration.
    667   unsigned getOwningModuleID() const {
    668     if (isFromASTFile())
    669       return *((const unsigned*)this - 2);
    670     return 0;
    671   }
    672 
    673 private:
    674   Module *getOwningModuleSlow() const;
    675 protected:
    676   bool hasLocalOwningModuleStorage() const;
    677 
    678 public:
    679   /// \brief Get the imported owning module, if this decl is from an imported
    680   /// (non-local) module.
    681   Module *getImportedOwningModule() const {
    682     if (!isFromASTFile())
    683       return nullptr;
    684 
    685     return getOwningModuleSlow();
    686   }
    687 
    688   /// \brief Get the local owning module, if known. Returns nullptr if owner is
    689   /// not yet known or declaration is not from a module.
    690   Module *getLocalOwningModule() const {
    691     if (isFromASTFile() || !Hidden)
    692       return nullptr;
    693     return reinterpret_cast<Module *const *>(this)[-1];
    694   }
    695   void setLocalOwningModule(Module *M) {
    696     assert(!isFromASTFile() && Hidden && hasLocalOwningModuleStorage() &&
    697            "should not have a cached owning module");
    698     reinterpret_cast<Module **>(this)[-1] = M;
    699   }
    700 
    701   unsigned getIdentifierNamespace() const {
    702     return IdentifierNamespace;
    703   }
    704   bool isInIdentifierNamespace(unsigned NS) const {
    705     return getIdentifierNamespace() & NS;
    706   }
    707   static unsigned getIdentifierNamespaceForKind(Kind DK);
    708 
    709   bool hasTagIdentifierNamespace() const {
    710     return isTagIdentifierNamespace(getIdentifierNamespace());
    711   }
    712   static bool isTagIdentifierNamespace(unsigned NS) {
    713     // TagDecls have Tag and Type set and may also have TagFriend.
    714     return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
    715   }
    716 
    717   /// getLexicalDeclContext - The declaration context where this Decl was
    718   /// lexically declared (LexicalDC). May be different from
    719   /// getDeclContext() (SemanticDC).
    720   /// e.g.:
    721   ///
    722   ///   namespace A {
    723   ///      void f(); // SemanticDC == LexicalDC == 'namespace A'
    724   ///   }
    725   ///   void A::f(); // SemanticDC == namespace 'A'
    726   ///                // LexicalDC == global namespace
    727   DeclContext *getLexicalDeclContext() {
    728     if (isInSemaDC())
    729       return getSemanticDC();
    730     return getMultipleDC()->LexicalDC;
    731   }
    732   const DeclContext *getLexicalDeclContext() const {
    733     return const_cast<Decl*>(this)->getLexicalDeclContext();
    734   }
    735 
    736   /// Determine whether this declaration is declared out of line (outside its
    737   /// semantic context).
    738   virtual bool isOutOfLine() const;
    739 
    740   /// setDeclContext - Set both the semantic and lexical DeclContext
    741   /// to DC.
    742   void setDeclContext(DeclContext *DC);
    743 
    744   void setLexicalDeclContext(DeclContext *DC);
    745 
    746   /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
    747   /// scoped decl is defined outside the current function or method.  This is
    748   /// roughly global variables and functions, but also handles enums (which
    749   /// could be defined inside or outside a function etc).
    750   bool isDefinedOutsideFunctionOrMethod() const {
    751     return getParentFunctionOrMethod() == nullptr;
    752   }
    753 
    754   /// \brief Returns true if this declaration lexically is inside a function.
    755   /// It recognizes non-defining declarations as well as members of local
    756   /// classes:
    757   /// \code
    758   ///     void foo() { void bar(); }
    759   ///     void foo2() { class ABC { void bar(); }; }
    760   /// \endcode
    761   bool isLexicallyWithinFunctionOrMethod() const;
    762 
    763   /// \brief If this decl is defined inside a function/method/block it returns
    764   /// the corresponding DeclContext, otherwise it returns null.
    765   const DeclContext *getParentFunctionOrMethod() const;
    766   DeclContext *getParentFunctionOrMethod() {
    767     return const_cast<DeclContext*>(
    768                     const_cast<const Decl*>(this)->getParentFunctionOrMethod());
    769   }
    770 
    771   /// \brief Retrieves the "canonical" declaration of the given declaration.
    772   virtual Decl *getCanonicalDecl() { return this; }
    773   const Decl *getCanonicalDecl() const {
    774     return const_cast<Decl*>(this)->getCanonicalDecl();
    775   }
    776 
    777   /// \brief Whether this particular Decl is a canonical one.
    778   bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
    779 
    780 protected:
    781   /// \brief Returns the next redeclaration or itself if this is the only decl.
    782   ///
    783   /// Decl subclasses that can be redeclared should override this method so that
    784   /// Decl::redecl_iterator can iterate over them.
    785   virtual Decl *getNextRedeclarationImpl() { return this; }
    786 
    787   /// \brief Implementation of getPreviousDecl(), to be overridden by any
    788   /// subclass that has a redeclaration chain.
    789   virtual Decl *getPreviousDeclImpl() { return nullptr; }
    790 
    791   /// \brief Implementation of getMostRecentDecl(), to be overridden by any
    792   /// subclass that has a redeclaration chain.
    793   virtual Decl *getMostRecentDeclImpl() { return this; }
    794 
    795 public:
    796   /// \brief Iterates through all the redeclarations of the same decl.
    797   class redecl_iterator {
    798     /// Current - The current declaration.
    799     Decl *Current;
    800     Decl *Starter;
    801 
    802   public:
    803     typedef Decl *value_type;
    804     typedef const value_type &reference;
    805     typedef const value_type *pointer;
    806     typedef std::forward_iterator_tag iterator_category;
    807     typedef std::ptrdiff_t difference_type;
    808 
    809     redecl_iterator() : Current(nullptr) { }
    810     explicit redecl_iterator(Decl *C) : Current(C), Starter(C) { }
    811 
    812     reference operator*() const { return Current; }
    813     value_type operator->() const { return Current; }
    814 
    815     redecl_iterator& operator++() {
    816       assert(Current && "Advancing while iterator has reached end");
    817       // Get either previous decl or latest decl.
    818       Decl *Next = Current->getNextRedeclarationImpl();
    819       assert(Next && "Should return next redeclaration or itself, never null!");
    820       Current = (Next != Starter) ? Next : nullptr;
    821       return *this;
    822     }
    823 
    824     redecl_iterator operator++(int) {
    825       redecl_iterator tmp(*this);
    826       ++(*this);
    827       return tmp;
    828     }
    829 
    830     friend bool operator==(redecl_iterator x, redecl_iterator y) {
    831       return x.Current == y.Current;
    832     }
    833     friend bool operator!=(redecl_iterator x, redecl_iterator y) {
    834       return x.Current != y.Current;
    835     }
    836   };
    837 
    838   typedef llvm::iterator_range<redecl_iterator> redecl_range;
    839 
    840   /// \brief Returns an iterator range for all the redeclarations of the same
    841   /// decl. It will iterate at least once (when this decl is the only one).
    842   redecl_range redecls() const {
    843     return redecl_range(redecls_begin(), redecls_end());
    844   }
    845 
    846   redecl_iterator redecls_begin() const {
    847     return redecl_iterator(const_cast<Decl *>(this));
    848   }
    849   redecl_iterator redecls_end() const { return redecl_iterator(); }
    850 
    851   /// \brief Retrieve the previous declaration that declares the same entity
    852   /// as this declaration, or NULL if there is no previous declaration.
    853   Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
    854 
    855   /// \brief Retrieve the most recent declaration that declares the same entity
    856   /// as this declaration, or NULL if there is no previous declaration.
    857   const Decl *getPreviousDecl() const {
    858     return const_cast<Decl *>(this)->getPreviousDeclImpl();
    859   }
    860 
    861   /// \brief True if this is the first declaration in its redeclaration chain.
    862   bool isFirstDecl() const {
    863     return getPreviousDecl() == nullptr;
    864   }
    865 
    866   /// \brief Retrieve the most recent declaration that declares the same entity
    867   /// as this declaration (which may be this declaration).
    868   Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
    869 
    870   /// \brief Retrieve the most recent declaration that declares the same entity
    871   /// as this declaration (which may be this declaration).
    872   const Decl *getMostRecentDecl() const {
    873     return const_cast<Decl *>(this)->getMostRecentDeclImpl();
    874   }
    875 
    876   /// getBody - If this Decl represents a declaration for a body of code,
    877   ///  such as a function or method definition, this method returns the
    878   ///  top-level Stmt* of that body.  Otherwise this method returns null.
    879   virtual Stmt* getBody() const { return nullptr; }
    880 
    881   /// \brief Returns true if this \c Decl represents a declaration for a body of
    882   /// code, such as a function or method definition.
    883   /// Note that \c hasBody can also return true if any redeclaration of this
    884   /// \c Decl represents a declaration for a body of code.
    885   virtual bool hasBody() const { return getBody() != nullptr; }
    886 
    887   /// getBodyRBrace - Gets the right brace of the body, if a body exists.
    888   /// This works whether the body is a CompoundStmt or a CXXTryStmt.
    889   SourceLocation getBodyRBrace() const;
    890 
    891   // global temp stats (until we have a per-module visitor)
    892   static void add(Kind k);
    893   static void EnableStatistics();
    894   static void PrintStats();
    895 
    896   /// isTemplateParameter - Determines whether this declaration is a
    897   /// template parameter.
    898   bool isTemplateParameter() const;
    899 
    900   /// isTemplateParameter - Determines whether this declaration is a
    901   /// template parameter pack.
    902   bool isTemplateParameterPack() const;
    903 
    904   /// \brief Whether this declaration is a parameter pack.
    905   bool isParameterPack() const;
    906 
    907   /// \brief returns true if this declaration is a template
    908   bool isTemplateDecl() const;
    909 
    910   /// \brief Whether this declaration is a function or function template.
    911   bool isFunctionOrFunctionTemplate() const {
    912     return (DeclKind >= Decl::firstFunction &&
    913             DeclKind <= Decl::lastFunction) ||
    914            DeclKind == FunctionTemplate;
    915   }
    916 
    917   /// \brief If this is a declaration that describes some template, this
    918   /// method returns that template declaration.
    919   TemplateDecl *getDescribedTemplate() const;
    920 
    921   /// \brief Returns the function itself, or the templated function if this is a
    922   /// function template.
    923   FunctionDecl *getAsFunction() LLVM_READONLY;
    924 
    925   const FunctionDecl *getAsFunction() const {
    926     return const_cast<Decl *>(this)->getAsFunction();
    927   }
    928 
    929   /// \brief Changes the namespace of this declaration to reflect that it's
    930   /// a function-local extern declaration.
    931   ///
    932   /// These declarations appear in the lexical context of the extern
    933   /// declaration, but in the semantic context of the enclosing namespace
    934   /// scope.
    935   void setLocalExternDecl() {
    936     assert((IdentifierNamespace == IDNS_Ordinary ||
    937             IdentifierNamespace == IDNS_OrdinaryFriend) &&
    938            "namespace is not ordinary");
    939 
    940     Decl *Prev = getPreviousDecl();
    941     IdentifierNamespace &= ~IDNS_Ordinary;
    942 
    943     IdentifierNamespace |= IDNS_LocalExtern;
    944     if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
    945       IdentifierNamespace |= IDNS_Ordinary;
    946   }
    947 
    948   /// \brief Determine whether this is a block-scope declaration with linkage.
    949   /// This will either be a local variable declaration declared 'extern', or a
    950   /// local function declaration.
    951   bool isLocalExternDecl() {
    952     return IdentifierNamespace & IDNS_LocalExtern;
    953   }
    954 
    955   /// \brief Changes the namespace of this declaration to reflect that it's
    956   /// the object of a friend declaration.
    957   ///
    958   /// These declarations appear in the lexical context of the friending
    959   /// class, but in the semantic context of the actual entity.  This property
    960   /// applies only to a specific decl object;  other redeclarations of the
    961   /// same entity may not (and probably don't) share this property.
    962   void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
    963     unsigned OldNS = IdentifierNamespace;
    964     assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
    965                      IDNS_TagFriend | IDNS_OrdinaryFriend |
    966                      IDNS_LocalExtern)) &&
    967            "namespace includes neither ordinary nor tag");
    968     assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
    969                        IDNS_TagFriend | IDNS_OrdinaryFriend |
    970                        IDNS_LocalExtern)) &&
    971            "namespace includes other than ordinary or tag");
    972 
    973     Decl *Prev = getPreviousDecl();
    974     IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
    975 
    976     if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
    977       IdentifierNamespace |= IDNS_TagFriend;
    978       if (PerformFriendInjection ||
    979           (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
    980         IdentifierNamespace |= IDNS_Tag | IDNS_Type;
    981     }
    982 
    983     if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
    984       IdentifierNamespace |= IDNS_OrdinaryFriend;
    985       if (PerformFriendInjection ||
    986           (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
    987         IdentifierNamespace |= IDNS_Ordinary;
    988     }
    989   }
    990 
    991   enum FriendObjectKind {
    992     FOK_None,      ///< Not a friend object.
    993     FOK_Declared,  ///< A friend of a previously-declared entity.
    994     FOK_Undeclared ///< A friend of a previously-undeclared entity.
    995   };
    996 
    997   /// \brief Determines whether this declaration is the object of a
    998   /// friend declaration and, if so, what kind.
    999   ///
   1000   /// There is currently no direct way to find the associated FriendDecl.
   1001   FriendObjectKind getFriendObjectKind() const {
   1002     unsigned mask =
   1003         (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
   1004     if (!mask) return FOK_None;
   1005     return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
   1006                                                              : FOK_Undeclared);
   1007   }
   1008 
   1009   /// Specifies that this declaration is a C++ overloaded non-member.
   1010   void setNonMemberOperator() {
   1011     assert(getKind() == Function || getKind() == FunctionTemplate);
   1012     assert((IdentifierNamespace & IDNS_Ordinary) &&
   1013            "visible non-member operators should be in ordinary namespace");
   1014     IdentifierNamespace |= IDNS_NonMemberOperator;
   1015   }
   1016 
   1017   static bool classofKind(Kind K) { return true; }
   1018   static DeclContext *castToDeclContext(const Decl *);
   1019   static Decl *castFromDeclContext(const DeclContext *);
   1020 
   1021   void print(raw_ostream &Out, unsigned Indentation = 0,
   1022              bool PrintInstantiation = false) const;
   1023   void print(raw_ostream &Out, const PrintingPolicy &Policy,
   1024              unsigned Indentation = 0, bool PrintInstantiation = false) const;
   1025   static void printGroup(Decl** Begin, unsigned NumDecls,
   1026                          raw_ostream &Out, const PrintingPolicy &Policy,
   1027                          unsigned Indentation = 0);
   1028   // Debuggers don't usually respect default arguments.
   1029   void dump() const;
   1030   // Same as dump(), but forces color printing.
   1031   void dumpColor() const;
   1032   void dump(raw_ostream &Out, bool Deserialize = false) const;
   1033 
   1034   /// \brief Looks through the Decl's underlying type to extract a FunctionType
   1035   /// when possible. Will return null if the type underlying the Decl does not
   1036   /// have a FunctionType.
   1037   const FunctionType *getFunctionType(bool BlocksToo = true) const;
   1038 
   1039 private:
   1040   void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
   1041   void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
   1042                            ASTContext &Ctx);
   1043 
   1044 protected:
   1045   ASTMutationListener *getASTMutationListener() const;
   1046 };
   1047 
   1048 /// \brief Determine whether two declarations declare the same entity.
   1049 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
   1050   if (!D1 || !D2)
   1051     return false;
   1052 
   1053   if (D1 == D2)
   1054     return true;
   1055 
   1056   return D1->getCanonicalDecl() == D2->getCanonicalDecl();
   1057 }
   1058 
   1059 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
   1060 /// doing something to a specific decl.
   1061 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
   1062   const Decl *TheDecl;
   1063   SourceLocation Loc;
   1064   SourceManager &SM;
   1065   const char *Message;
   1066 public:
   1067   PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
   1068                        SourceManager &sm, const char *Msg)
   1069   : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
   1070 
   1071   void print(raw_ostream &OS) const override;
   1072 };
   1073 
   1074 /// \brief The results of name lookup within a DeclContext. This is either a
   1075 /// single result (with no stable storage) or a collection of results (with
   1076 /// stable storage provided by the lookup table).
   1077 class DeclContextLookupResult {
   1078   typedef ArrayRef<NamedDecl *> ResultTy;
   1079   ResultTy Result;
   1080   // If there is only one lookup result, it would be invalidated by
   1081   // reallocations of the name table, so store it separately.
   1082   NamedDecl *Single;
   1083 
   1084   static NamedDecl *const SingleElementDummyList;
   1085 
   1086 public:
   1087   DeclContextLookupResult() : Result(), Single() {}
   1088   DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
   1089       : Result(Result), Single() {}
   1090   DeclContextLookupResult(NamedDecl *Single)
   1091       : Result(SingleElementDummyList), Single(Single) {}
   1092 
   1093   class iterator;
   1094   typedef llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
   1095                                       std::random_access_iterator_tag,
   1096                                       NamedDecl *const> IteratorBase;
   1097   class iterator : public IteratorBase {
   1098     value_type SingleElement;
   1099 
   1100   public:
   1101     iterator() : IteratorBase(), SingleElement() {}
   1102     explicit iterator(pointer Pos, value_type Single = nullptr)
   1103         : IteratorBase(Pos), SingleElement(Single) {}
   1104 
   1105     reference operator*() const {
   1106       return SingleElement ? SingleElement : IteratorBase::operator*();
   1107     }
   1108   };
   1109   typedef iterator const_iterator;
   1110   typedef iterator::pointer pointer;
   1111   typedef iterator::reference reference;
   1112 
   1113   iterator begin() const { return iterator(Result.begin(), Single); }
   1114   iterator end() const { return iterator(Result.end(), Single); }
   1115 
   1116   bool empty() const { return Result.empty(); }
   1117   pointer data() const { return Single ? &Single : Result.data(); }
   1118   size_t size() const { return Single ? 1 : Result.size(); }
   1119   reference front() const { return Single ? Single : Result.front(); }
   1120   reference back() const { return Single ? Single : Result.back(); }
   1121   reference operator[](size_t N) const { return Single ? Single : Result[N]; }
   1122 
   1123   // FIXME: Remove this from the interface
   1124   DeclContextLookupResult slice(size_t N) const {
   1125     DeclContextLookupResult Sliced = Result.slice(N);
   1126     Sliced.Single = Single;
   1127     return Sliced;
   1128   }
   1129 };
   1130 
   1131 /// DeclContext - This is used only as base class of specific decl types that
   1132 /// can act as declaration contexts. These decls are (only the top classes
   1133 /// that directly derive from DeclContext are mentioned, not their subclasses):
   1134 ///
   1135 ///   TranslationUnitDecl
   1136 ///   NamespaceDecl
   1137 ///   FunctionDecl
   1138 ///   TagDecl
   1139 ///   ObjCMethodDecl
   1140 ///   ObjCContainerDecl
   1141 ///   LinkageSpecDecl
   1142 ///   ExportDecl
   1143 ///   BlockDecl
   1144 ///   OMPDeclareReductionDecl
   1145 ///
   1146 class DeclContext {
   1147   /// DeclKind - This indicates which class this is.
   1148   unsigned DeclKind : 8;
   1149 
   1150   /// \brief Whether this declaration context also has some external
   1151   /// storage that contains additional declarations that are lexically
   1152   /// part of this context.
   1153   mutable bool ExternalLexicalStorage : 1;
   1154 
   1155   /// \brief Whether this declaration context also has some external
   1156   /// storage that contains additional declarations that are visible
   1157   /// in this context.
   1158   mutable bool ExternalVisibleStorage : 1;
   1159 
   1160   /// \brief Whether this declaration context has had external visible
   1161   /// storage added since the last lookup. In this case, \c LookupPtr's
   1162   /// invariant may not hold and needs to be fixed before we perform
   1163   /// another lookup.
   1164   mutable bool NeedToReconcileExternalVisibleStorage : 1;
   1165 
   1166   /// \brief If \c true, this context may have local lexical declarations
   1167   /// that are missing from the lookup table.
   1168   mutable bool HasLazyLocalLexicalLookups : 1;
   1169 
   1170   /// \brief If \c true, the external source may have lexical declarations
   1171   /// that are missing from the lookup table.
   1172   mutable bool HasLazyExternalLexicalLookups : 1;
   1173 
   1174   /// \brief If \c true, lookups should only return identifier from
   1175   /// DeclContext scope (for example TranslationUnit). Used in
   1176   /// LookupQualifiedName()
   1177   mutable bool UseQualifiedLookup : 1;
   1178 
   1179   /// \brief Pointer to the data structure used to lookup declarations
   1180   /// within this context (or a DependentStoredDeclsMap if this is a
   1181   /// dependent context). We maintain the invariant that, if the map
   1182   /// contains an entry for a DeclarationName (and we haven't lazily
   1183   /// omitted anything), then it contains all relevant entries for that
   1184   /// name (modulo the hasExternalDecls() flag).
   1185   mutable StoredDeclsMap *LookupPtr;
   1186 
   1187 protected:
   1188   /// FirstDecl - The first declaration stored within this declaration
   1189   /// context.
   1190   mutable Decl *FirstDecl;
   1191 
   1192   /// LastDecl - The last declaration stored within this declaration
   1193   /// context. FIXME: We could probably cache this value somewhere
   1194   /// outside of the DeclContext, to reduce the size of DeclContext by
   1195   /// another pointer.
   1196   mutable Decl *LastDecl;
   1197 
   1198   friend class ExternalASTSource;
   1199   friend class ASTDeclReader;
   1200   friend class ASTWriter;
   1201 
   1202   /// \brief Build up a chain of declarations.
   1203   ///
   1204   /// \returns the first/last pair of declarations.
   1205   static std::pair<Decl *, Decl *>
   1206   BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
   1207 
   1208   DeclContext(Decl::Kind K)
   1209       : DeclKind(K), ExternalLexicalStorage(false),
   1210         ExternalVisibleStorage(false),
   1211         NeedToReconcileExternalVisibleStorage(false),
   1212         HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
   1213         UseQualifiedLookup(false),
   1214         LookupPtr(nullptr), FirstDecl(nullptr), LastDecl(nullptr) {}
   1215 
   1216 public:
   1217   ~DeclContext();
   1218 
   1219   Decl::Kind getDeclKind() const {
   1220     return static_cast<Decl::Kind>(DeclKind);
   1221   }
   1222   const char *getDeclKindName() const;
   1223 
   1224   /// getParent - Returns the containing DeclContext.
   1225   DeclContext *getParent() {
   1226     return cast<Decl>(this)->getDeclContext();
   1227   }
   1228   const DeclContext *getParent() const {
   1229     return const_cast<DeclContext*>(this)->getParent();
   1230   }
   1231 
   1232   /// getLexicalParent - Returns the containing lexical DeclContext. May be
   1233   /// different from getParent, e.g.:
   1234   ///
   1235   ///   namespace A {
   1236   ///      struct S;
   1237   ///   }
   1238   ///   struct A::S {}; // getParent() == namespace 'A'
   1239   ///                   // getLexicalParent() == translation unit
   1240   ///
   1241   DeclContext *getLexicalParent() {
   1242     return cast<Decl>(this)->getLexicalDeclContext();
   1243   }
   1244   const DeclContext *getLexicalParent() const {
   1245     return const_cast<DeclContext*>(this)->getLexicalParent();
   1246   }
   1247 
   1248   DeclContext *getLookupParent();
   1249 
   1250   const DeclContext *getLookupParent() const {
   1251     return const_cast<DeclContext*>(this)->getLookupParent();
   1252   }
   1253 
   1254   ASTContext &getParentASTContext() const {
   1255     return cast<Decl>(this)->getASTContext();
   1256   }
   1257 
   1258   bool isClosure() const {
   1259     return DeclKind == Decl::Block;
   1260   }
   1261 
   1262   bool isObjCContainer() const {
   1263     switch (DeclKind) {
   1264         case Decl::ObjCCategory:
   1265         case Decl::ObjCCategoryImpl:
   1266         case Decl::ObjCImplementation:
   1267         case Decl::ObjCInterface:
   1268         case Decl::ObjCProtocol:
   1269             return true;
   1270     }
   1271     return false;
   1272   }
   1273 
   1274   bool isFunctionOrMethod() const {
   1275     switch (DeclKind) {
   1276     case Decl::Block:
   1277     case Decl::Captured:
   1278     case Decl::ObjCMethod:
   1279       return true;
   1280     default:
   1281       return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
   1282     }
   1283   }
   1284 
   1285   /// \brief Test whether the context supports looking up names.
   1286   bool isLookupContext() const {
   1287     return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
   1288            DeclKind != Decl::Export;
   1289   }
   1290 
   1291   bool isFileContext() const {
   1292     return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
   1293   }
   1294 
   1295   bool isTranslationUnit() const {
   1296     return DeclKind == Decl::TranslationUnit;
   1297   }
   1298 
   1299   bool isRecord() const {
   1300     return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
   1301   }
   1302 
   1303   bool isNamespace() const {
   1304     return DeclKind == Decl::Namespace;
   1305   }
   1306 
   1307   bool isStdNamespace() const;
   1308 
   1309   bool isInlineNamespace() const;
   1310 
   1311   /// \brief Determines whether this context is dependent on a
   1312   /// template parameter.
   1313   bool isDependentContext() const;
   1314 
   1315   /// isTransparentContext - Determines whether this context is a
   1316   /// "transparent" context, meaning that the members declared in this
   1317   /// context are semantically declared in the nearest enclosing
   1318   /// non-transparent (opaque) context but are lexically declared in
   1319   /// this context. For example, consider the enumerators of an
   1320   /// enumeration type:
   1321   /// @code
   1322   /// enum E {
   1323   ///   Val1
   1324   /// };
   1325   /// @endcode
   1326   /// Here, E is a transparent context, so its enumerator (Val1) will
   1327   /// appear (semantically) that it is in the same context of E.
   1328   /// Examples of transparent contexts include: enumerations (except for
   1329   /// C++0x scoped enums), and C++ linkage specifications.
   1330   bool isTransparentContext() const;
   1331 
   1332   /// \brief Determines whether this context or some of its ancestors is a
   1333   /// linkage specification context that specifies C linkage.
   1334   bool isExternCContext() const;
   1335 
   1336   /// \brief Retrieve the nearest enclosing C linkage specification context.
   1337   const LinkageSpecDecl *getExternCContext() const;
   1338 
   1339   /// \brief Determines whether this context or some of its ancestors is a
   1340   /// linkage specification context that specifies C++ linkage.
   1341   bool isExternCXXContext() const;
   1342 
   1343   /// \brief Determine whether this declaration context is equivalent
   1344   /// to the declaration context DC.
   1345   bool Equals(const DeclContext *DC) const {
   1346     return DC && this->getPrimaryContext() == DC->getPrimaryContext();
   1347   }
   1348 
   1349   /// \brief Determine whether this declaration context encloses the
   1350   /// declaration context DC.
   1351   bool Encloses(const DeclContext *DC) const;
   1352 
   1353   /// \brief Find the nearest non-closure ancestor of this context,
   1354   /// i.e. the innermost semantic parent of this context which is not
   1355   /// a closure.  A context may be its own non-closure ancestor.
   1356   Decl *getNonClosureAncestor();
   1357   const Decl *getNonClosureAncestor() const {
   1358     return const_cast<DeclContext*>(this)->getNonClosureAncestor();
   1359   }
   1360 
   1361   /// getPrimaryContext - There may be many different
   1362   /// declarations of the same entity (including forward declarations
   1363   /// of classes, multiple definitions of namespaces, etc.), each with
   1364   /// a different set of declarations. This routine returns the
   1365   /// "primary" DeclContext structure, which will contain the
   1366   /// information needed to perform name lookup into this context.
   1367   DeclContext *getPrimaryContext();
   1368   const DeclContext *getPrimaryContext() const {
   1369     return const_cast<DeclContext*>(this)->getPrimaryContext();
   1370   }
   1371 
   1372   /// getRedeclContext - Retrieve the context in which an entity conflicts with
   1373   /// other entities of the same name, or where it is a redeclaration if the
   1374   /// two entities are compatible. This skips through transparent contexts.
   1375   DeclContext *getRedeclContext();
   1376   const DeclContext *getRedeclContext() const {
   1377     return const_cast<DeclContext *>(this)->getRedeclContext();
   1378   }
   1379 
   1380   /// \brief Retrieve the nearest enclosing namespace context.
   1381   DeclContext *getEnclosingNamespaceContext();
   1382   const DeclContext *getEnclosingNamespaceContext() const {
   1383     return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
   1384   }
   1385 
   1386   /// \brief Retrieve the outermost lexically enclosing record context.
   1387   RecordDecl *getOuterLexicalRecordContext();
   1388   const RecordDecl *getOuterLexicalRecordContext() const {
   1389     return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
   1390   }
   1391 
   1392   /// \brief Test if this context is part of the enclosing namespace set of
   1393   /// the context NS, as defined in C++0x [namespace.def]p9. If either context
   1394   /// isn't a namespace, this is equivalent to Equals().
   1395   ///
   1396   /// The enclosing namespace set of a namespace is the namespace and, if it is
   1397   /// inline, its enclosing namespace, recursively.
   1398   bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
   1399 
   1400   /// \brief Collects all of the declaration contexts that are semantically
   1401   /// connected to this declaration context.
   1402   ///
   1403   /// For declaration contexts that have multiple semantically connected but
   1404   /// syntactically distinct contexts, such as C++ namespaces, this routine
   1405   /// retrieves the complete set of such declaration contexts in source order.
   1406   /// For example, given:
   1407   ///
   1408   /// \code
   1409   /// namespace N {
   1410   ///   int x;
   1411   /// }
   1412   /// namespace N {
   1413   ///   int y;
   1414   /// }
   1415   /// \endcode
   1416   ///
   1417   /// The \c Contexts parameter will contain both definitions of N.
   1418   ///
   1419   /// \param Contexts Will be cleared and set to the set of declaration
   1420   /// contexts that are semanticaly connected to this declaration context,
   1421   /// in source order, including this context (which may be the only result,
   1422   /// for non-namespace contexts).
   1423   void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
   1424 
   1425   /// decl_iterator - Iterates through the declarations stored
   1426   /// within this context.
   1427   class decl_iterator {
   1428     /// Current - The current declaration.
   1429     Decl *Current;
   1430 
   1431   public:
   1432     typedef Decl *value_type;
   1433     typedef const value_type &reference;
   1434     typedef const value_type *pointer;
   1435     typedef std::forward_iterator_tag iterator_category;
   1436     typedef std::ptrdiff_t            difference_type;
   1437 
   1438     decl_iterator() : Current(nullptr) { }
   1439     explicit decl_iterator(Decl *C) : Current(C) { }
   1440 
   1441     reference operator*() const { return Current; }
   1442     // This doesn't meet the iterator requirements, but it's convenient
   1443     value_type operator->() const { return Current; }
   1444 
   1445     decl_iterator& operator++() {
   1446       Current = Current->getNextDeclInContext();
   1447       return *this;
   1448     }
   1449 
   1450     decl_iterator operator++(int) {
   1451       decl_iterator tmp(*this);
   1452       ++(*this);
   1453       return tmp;
   1454     }
   1455 
   1456     friend bool operator==(decl_iterator x, decl_iterator y) {
   1457       return x.Current == y.Current;
   1458     }
   1459     friend bool operator!=(decl_iterator x, decl_iterator y) {
   1460       return x.Current != y.Current;
   1461     }
   1462   };
   1463 
   1464   typedef llvm::iterator_range<decl_iterator> decl_range;
   1465 
   1466   /// decls_begin/decls_end - Iterate over the declarations stored in
   1467   /// this context.
   1468   decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
   1469   decl_iterator decls_begin() const;
   1470   decl_iterator decls_end() const { return decl_iterator(); }
   1471   bool decls_empty() const;
   1472 
   1473   /// noload_decls_begin/end - Iterate over the declarations stored in this
   1474   /// context that are currently loaded; don't attempt to retrieve anything
   1475   /// from an external source.
   1476   decl_range noload_decls() const {
   1477     return decl_range(noload_decls_begin(), noload_decls_end());
   1478   }
   1479   decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
   1480   decl_iterator noload_decls_end() const { return decl_iterator(); }
   1481 
   1482   /// specific_decl_iterator - Iterates over a subrange of
   1483   /// declarations stored in a DeclContext, providing only those that
   1484   /// are of type SpecificDecl (or a class derived from it). This
   1485   /// iterator is used, for example, to provide iteration over just
   1486   /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
   1487   template<typename SpecificDecl>
   1488   class specific_decl_iterator {
   1489     /// Current - The current, underlying declaration iterator, which
   1490     /// will either be NULL or will point to a declaration of
   1491     /// type SpecificDecl.
   1492     DeclContext::decl_iterator Current;
   1493 
   1494     /// SkipToNextDecl - Advances the current position up to the next
   1495     /// declaration of type SpecificDecl that also meets the criteria
   1496     /// required by Acceptable.
   1497     void SkipToNextDecl() {
   1498       while (*Current && !isa<SpecificDecl>(*Current))
   1499         ++Current;
   1500     }
   1501 
   1502   public:
   1503     typedef SpecificDecl *value_type;
   1504     // TODO: Add reference and pointer typedefs (with some appropriate proxy
   1505     // type) if we ever have a need for them.
   1506     typedef void reference;
   1507     typedef void pointer;
   1508     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
   1509       difference_type;
   1510     typedef std::forward_iterator_tag iterator_category;
   1511 
   1512     specific_decl_iterator() : Current() { }
   1513 
   1514     /// specific_decl_iterator - Construct a new iterator over a
   1515     /// subset of the declarations the range [C,
   1516     /// end-of-declarations). If A is non-NULL, it is a pointer to a
   1517     /// member function of SpecificDecl that should return true for
   1518     /// all of the SpecificDecl instances that will be in the subset
   1519     /// of iterators. For example, if you want Objective-C instance
   1520     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
   1521     /// &ObjCMethodDecl::isInstanceMethod.
   1522     explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
   1523       SkipToNextDecl();
   1524     }
   1525 
   1526     value_type operator*() const { return cast<SpecificDecl>(*Current); }
   1527     // This doesn't meet the iterator requirements, but it's convenient
   1528     value_type operator->() const { return **this; }
   1529 
   1530     specific_decl_iterator& operator++() {
   1531       ++Current;
   1532       SkipToNextDecl();
   1533       return *this;
   1534     }
   1535 
   1536     specific_decl_iterator operator++(int) {
   1537       specific_decl_iterator tmp(*this);
   1538       ++(*this);
   1539       return tmp;
   1540     }
   1541 
   1542     friend bool operator==(const specific_decl_iterator& x,
   1543                            const specific_decl_iterator& y) {
   1544       return x.Current == y.Current;
   1545     }
   1546 
   1547     friend bool operator!=(const specific_decl_iterator& x,
   1548                            const specific_decl_iterator& y) {
   1549       return x.Current != y.Current;
   1550     }
   1551   };
   1552 
   1553   /// \brief Iterates over a filtered subrange of declarations stored
   1554   /// in a DeclContext.
   1555   ///
   1556   /// This iterator visits only those declarations that are of type
   1557   /// SpecificDecl (or a class derived from it) and that meet some
   1558   /// additional run-time criteria. This iterator is used, for
   1559   /// example, to provide access to the instance methods within an
   1560   /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
   1561   /// Acceptable = ObjCMethodDecl::isInstanceMethod).
   1562   template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
   1563   class filtered_decl_iterator {
   1564     /// Current - The current, underlying declaration iterator, which
   1565     /// will either be NULL or will point to a declaration of
   1566     /// type SpecificDecl.
   1567     DeclContext::decl_iterator Current;
   1568 
   1569     /// SkipToNextDecl - Advances the current position up to the next
   1570     /// declaration of type SpecificDecl that also meets the criteria
   1571     /// required by Acceptable.
   1572     void SkipToNextDecl() {
   1573       while (*Current &&
   1574              (!isa<SpecificDecl>(*Current) ||
   1575               (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
   1576         ++Current;
   1577     }
   1578 
   1579   public:
   1580     typedef SpecificDecl *value_type;
   1581     // TODO: Add reference and pointer typedefs (with some appropriate proxy
   1582     // type) if we ever have a need for them.
   1583     typedef void reference;
   1584     typedef void pointer;
   1585     typedef std::iterator_traits<DeclContext::decl_iterator>::difference_type
   1586       difference_type;
   1587     typedef std::forward_iterator_tag iterator_category;
   1588 
   1589     filtered_decl_iterator() : Current() { }
   1590 
   1591     /// filtered_decl_iterator - Construct a new iterator over a
   1592     /// subset of the declarations the range [C,
   1593     /// end-of-declarations). If A is non-NULL, it is a pointer to a
   1594     /// member function of SpecificDecl that should return true for
   1595     /// all of the SpecificDecl instances that will be in the subset
   1596     /// of iterators. For example, if you want Objective-C instance
   1597     /// methods, SpecificDecl will be ObjCMethodDecl and A will be
   1598     /// &ObjCMethodDecl::isInstanceMethod.
   1599     explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
   1600       SkipToNextDecl();
   1601     }
   1602 
   1603     value_type operator*() const { return cast<SpecificDecl>(*Current); }
   1604     value_type operator->() const { return cast<SpecificDecl>(*Current); }
   1605 
   1606     filtered_decl_iterator& operator++() {
   1607       ++Current;
   1608       SkipToNextDecl();
   1609       return *this;
   1610     }
   1611 
   1612     filtered_decl_iterator operator++(int) {
   1613       filtered_decl_iterator tmp(*this);
   1614       ++(*this);
   1615       return tmp;
   1616     }
   1617 
   1618     friend bool operator==(const filtered_decl_iterator& x,
   1619                            const filtered_decl_iterator& y) {
   1620       return x.Current == y.Current;
   1621     }
   1622 
   1623     friend bool operator!=(const filtered_decl_iterator& x,
   1624                            const filtered_decl_iterator& y) {
   1625       return x.Current != y.Current;
   1626     }
   1627   };
   1628 
   1629   /// @brief Add the declaration D into this context.
   1630   ///
   1631   /// This routine should be invoked when the declaration D has first
   1632   /// been declared, to place D into the context where it was
   1633   /// (lexically) defined. Every declaration must be added to one
   1634   /// (and only one!) context, where it can be visited via
   1635   /// [decls_begin(), decls_end()). Once a declaration has been added
   1636   /// to its lexical context, the corresponding DeclContext owns the
   1637   /// declaration.
   1638   ///
   1639   /// If D is also a NamedDecl, it will be made visible within its
   1640   /// semantic context via makeDeclVisibleInContext.
   1641   void addDecl(Decl *D);
   1642 
   1643   /// @brief Add the declaration D into this context, but suppress
   1644   /// searches for external declarations with the same name.
   1645   ///
   1646   /// Although analogous in function to addDecl, this removes an
   1647   /// important check.  This is only useful if the Decl is being
   1648   /// added in response to an external search; in all other cases,
   1649   /// addDecl() is the right function to use.
   1650   /// See the ASTImporter for use cases.
   1651   void addDeclInternal(Decl *D);
   1652 
   1653   /// @brief Add the declaration D to this context without modifying
   1654   /// any lookup tables.
   1655   ///
   1656   /// This is useful for some operations in dependent contexts where
   1657   /// the semantic context might not be dependent;  this basically
   1658   /// only happens with friends.
   1659   void addHiddenDecl(Decl *D);
   1660 
   1661   /// @brief Removes a declaration from this context.
   1662   void removeDecl(Decl *D);
   1663 
   1664   /// @brief Checks whether a declaration is in this context.
   1665   bool containsDecl(Decl *D) const;
   1666 
   1667   typedef DeclContextLookupResult lookup_result;
   1668   typedef lookup_result::iterator lookup_iterator;
   1669 
   1670   /// lookup - Find the declarations (if any) with the given Name in
   1671   /// this context. Returns a range of iterators that contains all of
   1672   /// the declarations with this name, with object, function, member,
   1673   /// and enumerator names preceding any tag name. Note that this
   1674   /// routine will not look into parent contexts.
   1675   lookup_result lookup(DeclarationName Name) const;
   1676 
   1677   /// \brief Find the declarations with the given name that are visible
   1678   /// within this context; don't attempt to retrieve anything from an
   1679   /// external source.
   1680   lookup_result noload_lookup(DeclarationName Name);
   1681 
   1682   /// \brief A simplistic name lookup mechanism that performs name lookup
   1683   /// into this declaration context without consulting the external source.
   1684   ///
   1685   /// This function should almost never be used, because it subverts the
   1686   /// usual relationship between a DeclContext and the external source.
   1687   /// See the ASTImporter for the (few, but important) use cases.
   1688   ///
   1689   /// FIXME: This is very inefficient; replace uses of it with uses of
   1690   /// noload_lookup.
   1691   void localUncachedLookup(DeclarationName Name,
   1692                            SmallVectorImpl<NamedDecl *> &Results);
   1693 
   1694   /// @brief Makes a declaration visible within this context.
   1695   ///
   1696   /// This routine makes the declaration D visible to name lookup
   1697   /// within this context and, if this is a transparent context,
   1698   /// within its parent contexts up to the first enclosing
   1699   /// non-transparent context. Making a declaration visible within a
   1700   /// context does not transfer ownership of a declaration, and a
   1701   /// declaration can be visible in many contexts that aren't its
   1702   /// lexical context.
   1703   ///
   1704   /// If D is a redeclaration of an existing declaration that is
   1705   /// visible from this context, as determined by
   1706   /// NamedDecl::declarationReplaces, the previous declaration will be
   1707   /// replaced with D.
   1708   void makeDeclVisibleInContext(NamedDecl *D);
   1709 
   1710   /// all_lookups_iterator - An iterator that provides a view over the results
   1711   /// of looking up every possible name.
   1712   class all_lookups_iterator;
   1713 
   1714   typedef llvm::iterator_range<all_lookups_iterator> lookups_range;
   1715 
   1716   lookups_range lookups() const;
   1717   lookups_range noload_lookups() const;
   1718 
   1719   /// \brief Iterators over all possible lookups within this context.
   1720   all_lookups_iterator lookups_begin() const;
   1721   all_lookups_iterator lookups_end() const;
   1722 
   1723   /// \brief Iterators over all possible lookups within this context that are
   1724   /// currently loaded; don't attempt to retrieve anything from an external
   1725   /// source.
   1726   all_lookups_iterator noload_lookups_begin() const;
   1727   all_lookups_iterator noload_lookups_end() const;
   1728 
   1729   struct udir_iterator;
   1730   typedef llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
   1731                                       std::random_access_iterator_tag,
   1732                                       UsingDirectiveDecl *> udir_iterator_base;
   1733   struct udir_iterator : udir_iterator_base {
   1734     udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
   1735     UsingDirectiveDecl *operator*() const;
   1736   };
   1737 
   1738   typedef llvm::iterator_range<udir_iterator> udir_range;
   1739 
   1740   udir_range using_directives() const;
   1741 
   1742   // These are all defined in DependentDiagnostic.h.
   1743   class ddiag_iterator;
   1744   typedef llvm::iterator_range<DeclContext::ddiag_iterator> ddiag_range;
   1745 
   1746   inline ddiag_range ddiags() const;
   1747 
   1748   // Low-level accessors
   1749 
   1750   /// \brief Mark that there are external lexical declarations that we need
   1751   /// to include in our lookup table (and that are not available as external
   1752   /// visible lookups). These extra lookup results will be found by walking
   1753   /// the lexical declarations of this context. This should be used only if
   1754   /// setHasExternalLexicalStorage() has been called on any decl context for
   1755   /// which this is the primary context.
   1756   void setMustBuildLookupTable() {
   1757     assert(this == getPrimaryContext() &&
   1758            "should only be called on primary context");
   1759     HasLazyExternalLexicalLookups = true;
   1760   }
   1761 
   1762   /// \brief Retrieve the internal representation of the lookup structure.
   1763   /// This may omit some names if we are lazily building the structure.
   1764   StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
   1765 
   1766   /// \brief Ensure the lookup structure is fully-built and return it.
   1767   StoredDeclsMap *buildLookup();
   1768 
   1769   /// \brief Whether this DeclContext has external storage containing
   1770   /// additional declarations that are lexically in this context.
   1771   bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
   1772 
   1773   /// \brief State whether this DeclContext has external storage for
   1774   /// declarations lexically in this context.
   1775   void setHasExternalLexicalStorage(bool ES = true) {
   1776     ExternalLexicalStorage = ES;
   1777   }
   1778 
   1779   /// \brief Whether this DeclContext has external storage containing
   1780   /// additional declarations that are visible in this context.
   1781   bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
   1782 
   1783   /// \brief State whether this DeclContext has external storage for
   1784   /// declarations visible in this context.
   1785   void setHasExternalVisibleStorage(bool ES = true) {
   1786     ExternalVisibleStorage = ES;
   1787     if (ES && LookupPtr)
   1788       NeedToReconcileExternalVisibleStorage = true;
   1789   }
   1790 
   1791   /// \brief Determine whether the given declaration is stored in the list of
   1792   /// declarations lexically within this context.
   1793   bool isDeclInLexicalTraversal(const Decl *D) const {
   1794     return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
   1795                  D == LastDecl);
   1796   }
   1797 
   1798   bool setUseQualifiedLookup(bool use = true) {
   1799     bool old_value = UseQualifiedLookup;
   1800     UseQualifiedLookup = use;
   1801     return old_value;
   1802   }
   1803 
   1804   bool shouldUseQualifiedLookup() const {
   1805     return UseQualifiedLookup;
   1806   }
   1807 
   1808   static bool classof(const Decl *D);
   1809   static bool classof(const DeclContext *D) { return true; }
   1810 
   1811   void dumpDeclContext() const;
   1812   void dumpLookups() const;
   1813   void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
   1814                    bool Deserialize = false) const;
   1815 
   1816 private:
   1817   void reconcileExternalVisibleStorage() const;
   1818   bool LoadLexicalDeclsFromExternalStorage() const;
   1819 
   1820   /// @brief Makes a declaration visible within this context, but
   1821   /// suppresses searches for external declarations with the same
   1822   /// name.
   1823   ///
   1824   /// Analogous to makeDeclVisibleInContext, but for the exclusive
   1825   /// use of addDeclInternal().
   1826   void makeDeclVisibleInContextInternal(NamedDecl *D);
   1827 
   1828   friend class DependentDiagnostic;
   1829   StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
   1830 
   1831   void buildLookupImpl(DeclContext *DCtx, bool Internal);
   1832   void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
   1833                                          bool Rediscoverable);
   1834   void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
   1835 };
   1836 
   1837 inline bool Decl::isTemplateParameter() const {
   1838   return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
   1839          getKind() == TemplateTemplateParm;
   1840 }
   1841 
   1842 // Specialization selected when ToTy is not a known subclass of DeclContext.
   1843 template <class ToTy,
   1844           bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
   1845 struct cast_convert_decl_context {
   1846   static const ToTy *doit(const DeclContext *Val) {
   1847     return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
   1848   }
   1849 
   1850   static ToTy *doit(DeclContext *Val) {
   1851     return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
   1852   }
   1853 };
   1854 
   1855 // Specialization selected when ToTy is a known subclass of DeclContext.
   1856 template <class ToTy>
   1857 struct cast_convert_decl_context<ToTy, true> {
   1858   static const ToTy *doit(const DeclContext *Val) {
   1859     return static_cast<const ToTy*>(Val);
   1860   }
   1861 
   1862   static ToTy *doit(DeclContext *Val) {
   1863     return static_cast<ToTy*>(Val);
   1864   }
   1865 };
   1866 
   1867 
   1868 } // end clang.
   1869 
   1870 namespace llvm {
   1871 
   1872 /// isa<T>(DeclContext*)
   1873 template <typename To>
   1874 struct isa_impl<To, ::clang::DeclContext> {
   1875   static bool doit(const ::clang::DeclContext &Val) {
   1876     return To::classofKind(Val.getDeclKind());
   1877   }
   1878 };
   1879 
   1880 /// cast<T>(DeclContext*)
   1881 template<class ToTy>
   1882 struct cast_convert_val<ToTy,
   1883                         const ::clang::DeclContext,const ::clang::DeclContext> {
   1884   static const ToTy &doit(const ::clang::DeclContext &Val) {
   1885     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
   1886   }
   1887 };
   1888 template<class ToTy>
   1889 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
   1890   static ToTy &doit(::clang::DeclContext &Val) {
   1891     return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
   1892   }
   1893 };
   1894 template<class ToTy>
   1895 struct cast_convert_val<ToTy,
   1896                      const ::clang::DeclContext*, const ::clang::DeclContext*> {
   1897   static const ToTy *doit(const ::clang::DeclContext *Val) {
   1898     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
   1899   }
   1900 };
   1901 template<class ToTy>
   1902 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
   1903   static ToTy *doit(::clang::DeclContext *Val) {
   1904     return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
   1905   }
   1906 };
   1907 
   1908 /// Implement cast_convert_val for Decl -> DeclContext conversions.
   1909 template<class FromTy>
   1910 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
   1911   static ::clang::DeclContext &doit(const FromTy &Val) {
   1912     return *FromTy::castToDeclContext(&Val);
   1913   }
   1914 };
   1915 
   1916 template<class FromTy>
   1917 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
   1918   static ::clang::DeclContext *doit(const FromTy *Val) {
   1919     return FromTy::castToDeclContext(Val);
   1920   }
   1921 };
   1922 
   1923 template<class FromTy>
   1924 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
   1925   static const ::clang::DeclContext &doit(const FromTy &Val) {
   1926     return *FromTy::castToDeclContext(&Val);
   1927   }
   1928 };
   1929 
   1930 template<class FromTy>
   1931 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
   1932   static const ::clang::DeclContext *doit(const FromTy *Val) {
   1933     return FromTy::castToDeclContext(Val);
   1934   }
   1935 };
   1936 
   1937 } // end namespace llvm
   1938 
   1939 #endif
   1940