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