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