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