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