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