]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - include/clang/AST/Decl.h
Vendor import of clang trunk r126079:
[FreeBSD/FreeBSD.git] / include / clang / AST / Decl.h
1 //===--- Decl.h - 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 subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_AST_DECL_H
15 #define LLVM_CLANG_AST_DECL_H
16
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/Redeclarable.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/ExternalASTSource.h"
22 #include "clang/Basic/Linkage.h"
23
24 namespace clang {
25 class CXXTemporary;
26 class Expr;
27 class FunctionTemplateDecl;
28 class Stmt;
29 class CompoundStmt;
30 class StringLiteral;
31 class NestedNameSpecifier;
32 class TemplateParameterList;
33 class TemplateArgumentList;
34 class MemberSpecializationInfo;
35 class FunctionTemplateSpecializationInfo;
36 class DependentFunctionTemplateSpecializationInfo;
37 class TypeLoc;
38 class UnresolvedSetImpl;
39 class LabelStmt;
40
41 /// \brief A container of type source information.
42 ///
43 /// A client can read the relevant info using TypeLoc wrappers, e.g:
44 /// @code
45 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
46 /// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
47 ///   PL->getStarLoc().print(OS, SrcMgr);
48 /// @endcode
49 ///
50 class TypeSourceInfo {
51   QualType Ty;
52   // Contains a memory block after the class, used for type source information,
53   // allocated by ASTContext.
54   friend class ASTContext;
55   TypeSourceInfo(QualType ty) : Ty(ty) { }
56 public:
57   /// \brief Return the type wrapped by this type source info.
58   QualType getType() const { return Ty; }
59
60   /// \brief Return the TypeLoc wrapper for the type source info.
61   TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
62 };
63
64 /// TranslationUnitDecl - The top declaration context.
65 class TranslationUnitDecl : public Decl, public DeclContext {
66   ASTContext &Ctx;
67
68   /// The (most recently entered) anonymous namespace for this
69   /// translation unit, if one has been created.
70   NamespaceDecl *AnonymousNamespace;
71
72   explicit TranslationUnitDecl(ASTContext &ctx)
73     : Decl(TranslationUnit, 0, SourceLocation()),
74       DeclContext(TranslationUnit),
75       Ctx(ctx), AnonymousNamespace(0) {}
76 public:
77   ASTContext &getASTContext() const { return Ctx; }
78
79   NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
80   void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
81
82   static TranslationUnitDecl *Create(ASTContext &C);
83   // Implement isa/cast/dyncast/etc.
84   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
85   static bool classof(const TranslationUnitDecl *D) { return true; }
86   static bool classofKind(Kind K) { return K == TranslationUnit; }
87   static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
88     return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
89   }
90   static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
91     return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
92   }
93 };
94
95 /// NamedDecl - This represents a decl with a name.  Many decls have names such
96 /// as ObjCMethodDecl, but not @class, etc.
97 class NamedDecl : public Decl {
98   /// Name - The name of this declaration, which is typically a normal
99   /// identifier but may also be a special kind of name (C++
100   /// constructor, Objective-C selector, etc.)
101   DeclarationName Name;
102
103 protected:
104   NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
105     : Decl(DK, DC, L), Name(N) { }
106
107 public:
108   /// getIdentifier - Get the identifier that names this declaration,
109   /// if there is one. This will return NULL if this declaration has
110   /// no name (e.g., for an unnamed class) or if the name is a special
111   /// name (C++ constructor, Objective-C selector, etc.).
112   IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
113
114   /// getName - Get the name of identifier for this declaration as a StringRef.
115   /// This requires that the declaration have a name and that it be a simple
116   /// identifier.
117   llvm::StringRef getName() const {
118     assert(Name.isIdentifier() && "Name is not a simple identifier");
119     return getIdentifier() ? getIdentifier()->getName() : "";
120   }
121
122   /// getNameAsString - Get a human-readable name for the declaration, even if
123   /// it is one of the special kinds of names (C++ constructor, Objective-C
124   /// selector, etc).  Creating this name requires expensive string
125   /// manipulation, so it should be called only when performance doesn't matter.
126   /// For simple declarations, getNameAsCString() should suffice.
127   //
128   // FIXME: This function should be renamed to indicate that it is not just an
129   // alternate form of getName(), and clients should move as appropriate.
130   //
131   // FIXME: Deprecated, move clients to getName().
132   std::string getNameAsString() const { return Name.getAsString(); }
133
134   void printName(llvm::raw_ostream &os) const { return Name.printName(os); }
135
136   /// getDeclName - Get the actual, stored name of the declaration,
137   /// which may be a special name.
138   DeclarationName getDeclName() const { return Name; }
139
140   /// \brief Set the name of this declaration.
141   void setDeclName(DeclarationName N) { Name = N; }
142
143   /// getQualifiedNameAsString - Returns human-readable qualified name for
144   /// declaration, like A::B::i, for i being member of namespace A::B.
145   /// If declaration is not member of context which can be named (record,
146   /// namespace), it will return same result as getNameAsString().
147   /// Creating this name is expensive, so it should be called only when
148   /// performance doesn't matter.
149   std::string getQualifiedNameAsString() const;
150   std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
151
152   /// getNameForDiagnostic - Appends a human-readable name for this
153   /// declaration into the given string.
154   ///
155   /// This is the method invoked by Sema when displaying a NamedDecl
156   /// in a diagnostic.  It does not necessarily produce the same
157   /// result as getNameAsString(); for example, class template
158   /// specializations are printed with their template arguments.
159   ///
160   /// TODO: use an API that doesn't require so many temporary strings
161   virtual void getNameForDiagnostic(std::string &S,
162                                     const PrintingPolicy &Policy,
163                                     bool Qualified) const {
164     if (Qualified)
165       S += getQualifiedNameAsString(Policy);
166     else
167       S += getNameAsString();
168   }
169
170   /// declarationReplaces - Determine whether this declaration, if
171   /// known to be well-formed within its context, will replace the
172   /// declaration OldD if introduced into scope. A declaration will
173   /// replace another declaration if, for example, it is a
174   /// redeclaration of the same variable or function, but not if it is
175   /// a declaration of a different kind (function vs. class) or an
176   /// overloaded function.
177   bool declarationReplaces(NamedDecl *OldD) const;
178
179   /// \brief Determine whether this declaration has linkage.
180   bool hasLinkage() const;
181
182   /// \brief Determine whether this declaration is a C++ class member.
183   bool isCXXClassMember() const {
184     const DeclContext *DC = getDeclContext();
185
186     // C++0x [class.mem]p1:
187     //   The enumerators of an unscoped enumeration defined in
188     //   the class are members of the class.
189     // FIXME: support C++0x scoped enumerations.
190     if (isa<EnumDecl>(DC))
191       DC = DC->getParent();
192
193     return DC->isRecord();
194   }
195
196   /// \brief Given that this declaration is a C++ class member,
197   /// determine whether it's an instance member of its class.
198   bool isCXXInstanceMember() const;
199
200   class LinkageInfo {
201     Linkage linkage_;
202     Visibility visibility_;
203     bool explicit_;
204
205   public:
206     LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility),
207                     explicit_(false) {}
208     LinkageInfo(Linkage L, Visibility V, bool E)
209       : linkage_(L), visibility_(V), explicit_(E) {}
210
211     static LinkageInfo external() {
212       return LinkageInfo();
213     }
214     static LinkageInfo internal() {
215       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
216     }
217     static LinkageInfo uniqueExternal() {
218       return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false);
219     }
220     static LinkageInfo none() {
221       return LinkageInfo(NoLinkage, DefaultVisibility, false);
222     }
223
224     Linkage linkage() const { return linkage_; }
225     Visibility visibility() const { return visibility_; }
226     bool visibilityExplicit() const { return explicit_; }
227
228     void setLinkage(Linkage L) { linkage_ = L; }
229     void setVisibility(Visibility V) { visibility_ = V; }
230     void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; }
231     void setVisibility(LinkageInfo Other) {
232       setVisibility(Other.visibility(), Other.visibilityExplicit());
233     }
234
235     void mergeLinkage(Linkage L) {
236       setLinkage(minLinkage(linkage(), L));
237     }
238     void mergeLinkage(LinkageInfo Other) {
239       setLinkage(minLinkage(linkage(), Other.linkage()));
240     }
241
242     void mergeVisibility(Visibility V) {
243       setVisibility(minVisibility(visibility(), V));
244     }
245     void mergeVisibility(Visibility V, bool E) {
246       setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E);
247     }
248     void mergeVisibility(LinkageInfo Other) {
249       mergeVisibility(Other.visibility(), Other.visibilityExplicit());
250     }
251
252     void merge(LinkageInfo Other) {
253       mergeLinkage(Other);
254       mergeVisibility(Other);
255     }
256     void merge(std::pair<Linkage,Visibility> LV) {
257       mergeLinkage(LV.first);
258       mergeVisibility(LV.second);
259     }
260
261     friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
262       L.merge(R);
263       return L;
264     }
265   };
266
267   /// \brief Determine what kind of linkage this entity has.
268   Linkage getLinkage() const;
269
270   /// \brief Determines the visibility of this entity.
271   Visibility getVisibility() const { return getLinkageAndVisibility().visibility(); }
272
273   /// \brief Determines the linkage and visibility of this entity.
274   LinkageInfo getLinkageAndVisibility() const;
275
276   /// \brief Clear the linkage cache in response to a change
277   /// to the declaration. 
278   void ClearLinkageCache();
279
280   /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
281   /// the underlying named decl.
282   NamedDecl *getUnderlyingDecl();
283   const NamedDecl *getUnderlyingDecl() const {
284     return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
285   }
286
287   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
288   static bool classof(const NamedDecl *D) { return true; }
289   static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
290 };
291
292 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
293                                      const NamedDecl *ND) {
294   ND->getDeclName().printName(OS);
295   return OS;
296 }
297
298 /// LabelDecl - Represents the declaration of a label.  Labels also have a
299 /// corresponding LabelStmt, which indicates the position that the label was
300 /// defined at.  For normal labels, the location of the decl is the same as the
301 /// location of the statement.  For GNU local labels (__label__), the decl
302 /// location is where the __label__ is.
303 class LabelDecl : public NamedDecl {
304   LabelStmt *TheStmt;
305   LabelDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *II, LabelStmt *S)
306     : NamedDecl(Label, DC, L, II), TheStmt(S) {}
307   
308 public:
309   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
310                            SourceLocation L, IdentifierInfo *II);
311
312   LabelStmt *getStmt() const { return TheStmt; }
313   void setStmt(LabelStmt *T) { TheStmt = T; }
314   
315   // Implement isa/cast/dyncast/etc.
316   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
317   static bool classof(const LabelDecl *D) { return true; }
318   static bool classofKind(Kind K) { return K == Label; }
319 };
320   
321 /// NamespaceDecl - Represent a C++ namespace.
322 class NamespaceDecl : public NamedDecl, public DeclContext {
323   bool IsInline : 1;
324
325   SourceLocation LBracLoc, RBracLoc;
326
327   // For extended namespace definitions:
328   //
329   // namespace A { int x; }
330   // namespace A { int y; }
331   //
332   // there will be one NamespaceDecl for each declaration.
333   // NextNamespace points to the next extended declaration.
334   // OrigNamespace points to the original namespace declaration.
335   // OrigNamespace of the first namespace decl points to its anonymous namespace
336   LazyDeclPtr NextNamespace;
337
338   /// \brief A pointer to either the original namespace definition for
339   /// this namespace (if the boolean value is false) or the anonymous
340   /// namespace that lives just inside this namespace (if the boolean
341   /// value is true).
342   ///
343   /// We can combine these two notions because the anonymous namespace
344   /// must only be stored in one of the namespace declarations (so all
345   /// of the namespace declarations can find it). We therefore choose
346   /// the original namespace declaration, since all of the namespace
347   /// declarations have a link directly to it; the original namespace
348   /// declaration itself only needs to know that it is the original
349   /// namespace declaration (which the boolean indicates).
350   llvm::PointerIntPair<NamespaceDecl *, 1, bool> OrigOrAnonNamespace;
351
352   NamespaceDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id)
353     : NamedDecl(Namespace, DC, L, Id), DeclContext(Namespace),
354       IsInline(false), NextNamespace(), OrigOrAnonNamespace(0, true) { }
355
356 public:
357   static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
358                                SourceLocation L, IdentifierInfo *Id);
359
360   /// \brief Returns true if this is an anonymous namespace declaration.
361   ///
362   /// For example:
363   /// \code
364   ///   namespace {
365   ///     ...
366   ///   };
367   /// \endcode
368   /// q.v. C++ [namespace.unnamed]
369   bool isAnonymousNamespace() const {
370     return !getIdentifier();
371   }
372
373   /// \brief Returns true if this is an inline namespace declaration.
374   bool isInline() const {
375     return IsInline;
376   }
377
378   /// \brief Set whether this is an inline namespace declaration.
379   void setInline(bool Inline) {
380     IsInline = Inline;
381   }
382
383   /// \brief Return the next extended namespace declaration or null if there
384   /// is none.
385   NamespaceDecl *getNextNamespace();
386   const NamespaceDecl *getNextNamespace() const { 
387     return const_cast<NamespaceDecl *>(this)->getNextNamespace();
388   }
389
390   /// \brief Set the next extended namespace declaration.
391   void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; }
392
393   /// \brief Get the original (first) namespace declaration.
394   NamespaceDecl *getOriginalNamespace() const {
395     if (OrigOrAnonNamespace.getInt())
396       return const_cast<NamespaceDecl *>(this);
397
398     return OrigOrAnonNamespace.getPointer();
399   }
400
401   /// \brief Return true if this declaration is an original (first) declaration
402   /// of the namespace. This is false for non-original (subsequent) namespace
403   /// declarations and anonymous namespaces.
404   bool isOriginalNamespace() const {
405     return getOriginalNamespace() == this;
406   }
407
408   /// \brief Set the original (first) namespace declaration.
409   void setOriginalNamespace(NamespaceDecl *ND) { 
410     if (ND != this) {
411       OrigOrAnonNamespace.setPointer(ND);
412       OrigOrAnonNamespace.setInt(false);
413     }
414   }
415
416   NamespaceDecl *getAnonymousNamespace() const {
417     return getOriginalNamespace()->OrigOrAnonNamespace.getPointer();
418   }
419
420   void setAnonymousNamespace(NamespaceDecl *D) {
421     assert(!D || D->isAnonymousNamespace());
422     assert(!D || D->getParent() == this);
423     getOriginalNamespace()->OrigOrAnonNamespace.setPointer(D);
424   }
425
426   virtual NamespaceDecl *getCanonicalDecl() { return getOriginalNamespace(); }
427   const NamespaceDecl *getCanonicalDecl() const { 
428     return getOriginalNamespace(); 
429   }
430
431   virtual SourceRange getSourceRange() const {
432     return SourceRange(getLocation(), RBracLoc);
433   }
434
435   SourceLocation getLBracLoc() const { return LBracLoc; }
436   SourceLocation getRBracLoc() const { return RBracLoc; }
437   void setLBracLoc(SourceLocation L) { LBracLoc = L; }
438   void setRBracLoc(SourceLocation R) { RBracLoc = R; }
439   
440   // Implement isa/cast/dyncast/etc.
441   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
442   static bool classof(const NamespaceDecl *D) { return true; }
443   static bool classofKind(Kind K) { return K == Namespace; }
444   static DeclContext *castToDeclContext(const NamespaceDecl *D) {
445     return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
446   }
447   static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
448     return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
449   }
450   
451   friend class ASTDeclReader;
452   friend class ASTDeclWriter;
453 };
454
455 /// ValueDecl - Represent the declaration of a variable (in which case it is
456 /// an lvalue) a function (in which case it is a function designator) or
457 /// an enum constant.
458 class ValueDecl : public NamedDecl {
459   QualType DeclType;
460
461 protected:
462   ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
463             DeclarationName N, QualType T)
464     : NamedDecl(DK, DC, L, N), DeclType(T) {}
465 public:
466   QualType getType() const { return DeclType; }
467   void setType(QualType newType) { DeclType = newType; }
468
469   // Implement isa/cast/dyncast/etc.
470   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
471   static bool classof(const ValueDecl *D) { return true; }
472   static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
473 };
474
475 /// QualifierInfo - A struct with extended info about a syntactic
476 /// name qualifier, to be used for the case of out-of-line declarations.
477 struct QualifierInfo {
478   /// NNS - The syntactic name qualifier.
479   NestedNameSpecifier *NNS;
480   /// NNSRange - The source range for the qualifier.
481   SourceRange NNSRange;
482   /// NumTemplParamLists - The number of template parameter lists
483   /// that were matched against the template-ids occurring into the NNS.
484   unsigned NumTemplParamLists;
485   /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
486   /// containing pointers to the matched template parameter lists.
487   TemplateParameterList** TemplParamLists;
488
489   /// Default constructor.
490   QualifierInfo()
491     : NNS(0), NNSRange(), NumTemplParamLists(0), TemplParamLists(0) {}
492   /// setTemplateParameterListsInfo - Sets info about matched template
493   /// parameter lists.
494   void setTemplateParameterListsInfo(ASTContext &Context,
495                                      unsigned NumTPLists,
496                                      TemplateParameterList **TPLists);
497   
498 private:
499   // Copy constructor and copy assignment are disabled.
500   QualifierInfo(const QualifierInfo&);
501   QualifierInfo& operator=(const QualifierInfo&);
502 };
503
504 /// \brief Represents a ValueDecl that came out of a declarator.
505 /// Contains type source information through TypeSourceInfo.
506 class DeclaratorDecl : public ValueDecl {
507   // A struct representing both a TInfo and a syntactic qualifier,
508   // to be used for the (uncommon) case of out-of-line declarations.
509   struct ExtInfo : public QualifierInfo {
510     TypeSourceInfo *TInfo;
511   };
512
513   llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
514
515   bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
516   ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
517   const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
518
519 protected:
520   DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
521                  DeclarationName N, QualType T, TypeSourceInfo *TInfo)
522     : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo) {}
523
524 public:
525   TypeSourceInfo *getTypeSourceInfo() const {
526     return hasExtInfo()
527       ? getExtInfo()->TInfo
528       : DeclInfo.get<TypeSourceInfo*>();
529   }
530   void setTypeSourceInfo(TypeSourceInfo *TI) {
531     if (hasExtInfo())
532       getExtInfo()->TInfo = TI;
533     else
534       DeclInfo = TI;
535   }
536
537   /// getInnerLocStart - Return SourceLocation representing start of source
538   /// range ignoring outer template declarations.
539   virtual SourceLocation getInnerLocStart() const { return getLocation(); }
540
541   /// getOuterLocStart - Return SourceLocation representing start of source
542   /// range taking into account any outer template declarations.
543   SourceLocation getOuterLocStart() const;
544   SourceRange getSourceRange() const {
545     return SourceRange(getOuterLocStart(), getLocation());
546   }
547
548   NestedNameSpecifier *getQualifier() const {
549     return hasExtInfo() ? getExtInfo()->NNS : 0;
550   }
551   SourceRange getQualifierRange() const {
552     return hasExtInfo() ? getExtInfo()->NNSRange : SourceRange();
553   }
554   void setQualifierInfo(NestedNameSpecifier *Qualifier,
555                         SourceRange QualifierRange);
556
557   unsigned getNumTemplateParameterLists() const {
558     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
559   }
560   TemplateParameterList *getTemplateParameterList(unsigned index) const {
561     assert(index < getNumTemplateParameterLists());
562     return getExtInfo()->TemplParamLists[index];
563   }
564   void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
565                                      TemplateParameterList **TPLists) {
566     getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
567   }
568
569   SourceLocation getTypeSpecStartLoc() const;
570
571   // Implement isa/cast/dyncast/etc.
572   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
573   static bool classof(const DeclaratorDecl *D) { return true; }
574   static bool classofKind(Kind K) {
575     return K >= firstDeclarator && K <= lastDeclarator;
576   }
577
578   friend class ASTDeclReader;
579   friend class ASTDeclWriter;
580 };
581
582 /// \brief Structure used to store a statement, the constant value to
583 /// which it was evaluated (if any), and whether or not the statement
584 /// is an integral constant expression (if known).
585 struct EvaluatedStmt {
586   EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
587                     CheckingICE(false), IsICE(false) { }
588
589   /// \brief Whether this statement was already evaluated.
590   bool WasEvaluated : 1;
591
592   /// \brief Whether this statement is being evaluated.
593   bool IsEvaluating : 1;
594
595   /// \brief Whether we already checked whether this statement was an
596   /// integral constant expression.
597   bool CheckedICE : 1;
598
599   /// \brief Whether we are checking whether this statement is an
600   /// integral constant expression.
601   bool CheckingICE : 1;
602
603   /// \brief Whether this statement is an integral constant
604   /// expression. Only valid if CheckedICE is true.
605   bool IsICE : 1;
606
607   Stmt *Value;
608   APValue Evaluated;
609 };
610
611 /// VarDecl - An instance of this class is created to represent a variable
612 /// declaration or definition.
613 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
614 public:
615   typedef clang::StorageClass StorageClass;
616
617   /// getStorageClassSpecifierString - Return the string used to
618   /// specify the storage class \arg SC.
619   ///
620   /// It is illegal to call this function with SC == None.
621   static const char *getStorageClassSpecifierString(StorageClass SC);
622
623 protected:
624   /// \brief Placeholder type used in Init to denote an unparsed C++ default
625   /// argument.
626   struct UnparsedDefaultArgument;
627
628   /// \brief Placeholder type used in Init to denote an uninstantiated C++
629   /// default argument.
630   struct UninstantiatedDefaultArgument;
631
632   typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
633                               UnparsedDefaultArgument *,
634                               UninstantiatedDefaultArgument *> InitType;
635
636   /// \brief The initializer for this variable or, for a ParmVarDecl, the
637   /// C++ default argument.
638   mutable InitType Init;
639
640 private:
641   // FIXME: This can be packed into the bitfields in Decl.
642   unsigned SClass : 3;
643   unsigned SClassAsWritten : 3;
644   bool ThreadSpecified : 1;
645   bool HasCXXDirectInit : 1;
646
647   /// \brief Whether this variable is the exception variable in a C++ catch
648   /// or an Objective-C @catch statement.
649   bool ExceptionVar : 1;
650   
651   /// \brief Whether this local variable could be allocated in the return
652   /// slot of its function, enabling the named return value optimization (NRVO).
653   bool NRVOVariable : 1;
654
655   /// \brief Whether this variable has a deduced C++0x auto type for which we're
656   /// currently parsing the initializer.
657   bool ParsingAutoInit : 1;
658   
659   friend class StmtIteratorBase;
660   friend class ASTDeclReader;
661   
662 protected:
663   VarDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
664           QualType T, TypeSourceInfo *TInfo, StorageClass SC,
665           StorageClass SCAsWritten)
666     : DeclaratorDecl(DK, DC, L, Id, T, TInfo), Init(),
667       ThreadSpecified(false), HasCXXDirectInit(false),
668       ExceptionVar(false), NRVOVariable(false), ParsingAutoInit(false) {
669     SClass = SC;
670     SClassAsWritten = SCAsWritten;
671   }
672
673   typedef Redeclarable<VarDecl> redeclarable_base;
674   virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
675
676 public:
677   typedef redeclarable_base::redecl_iterator redecl_iterator;
678   redecl_iterator redecls_begin() const {
679     return redeclarable_base::redecls_begin();
680   }
681   redecl_iterator redecls_end() const {
682     return redeclarable_base::redecls_end();
683   }
684
685   static VarDecl *Create(ASTContext &C, DeclContext *DC,
686                          SourceLocation L, IdentifierInfo *Id,
687                          QualType T, TypeSourceInfo *TInfo, StorageClass S,
688                          StorageClass SCAsWritten);
689
690   virtual SourceLocation getInnerLocStart() const;
691   virtual SourceRange getSourceRange() const;
692
693   StorageClass getStorageClass() const { return (StorageClass)SClass; }
694   StorageClass getStorageClassAsWritten() const {
695     return (StorageClass) SClassAsWritten;
696   }
697   void setStorageClass(StorageClass SC);
698   void setStorageClassAsWritten(StorageClass SC) {
699     assert(isLegalForVariable(SC));
700     SClassAsWritten = SC;
701   }
702
703   void setThreadSpecified(bool T) { ThreadSpecified = T; }
704   bool isThreadSpecified() const {
705     return ThreadSpecified;
706   }
707
708   /// hasLocalStorage - Returns true if a variable with function scope
709   ///  is a non-static local variable.
710   bool hasLocalStorage() const {
711     if (getStorageClass() == SC_None)
712       return !isFileVarDecl();
713
714     // Return true for:  Auto, Register.
715     // Return false for: Extern, Static, PrivateExtern.
716
717     return getStorageClass() >= SC_Auto;
718   }
719
720   /// isStaticLocal - Returns true if a variable with function scope is a 
721   /// static local variable.
722   bool isStaticLocal() const {
723     return getStorageClass() == SC_Static && !isFileVarDecl();
724   }
725   
726   /// hasExternStorage - Returns true if a variable has extern or
727   /// __private_extern__ storage.
728   bool hasExternalStorage() const {
729     return getStorageClass() == SC_Extern ||
730            getStorageClass() == SC_PrivateExtern;
731   }
732
733   /// hasGlobalStorage - Returns true for all variables that do not
734   ///  have local storage.  This includs all global variables as well
735   ///  as static variables declared within a function.
736   bool hasGlobalStorage() const { return !hasLocalStorage(); }
737
738   /// \brief Determines whether this variable is a variable with
739   /// external, C linkage.
740   bool isExternC() const;
741
742   /// isLocalVarDecl - Returns true for local variable declarations
743   /// other than parameters.  Note that this includes static variables
744   /// inside of functions. It also includes variables inside blocks.
745   ///
746   ///   void foo() { int x; static int y; extern int z; }
747   ///
748   bool isLocalVarDecl() const {
749     if (getKind() != Decl::Var)
750       return false;
751     if (const DeclContext *DC = getDeclContext())
752       return DC->getRedeclContext()->isFunctionOrMethod();
753     return false;
754   }
755
756   /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
757   /// excludes variables declared in blocks.
758   bool isFunctionOrMethodVarDecl() const {
759     if (getKind() != Decl::Var)
760       return false;
761     const DeclContext *DC = getDeclContext()->getRedeclContext();
762     return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
763   }
764
765   /// \brief Determines whether this is a static data member.
766   ///
767   /// This will only be true in C++, and applies to, e.g., the
768   /// variable 'x' in:
769   /// \code
770   /// struct S {
771   ///   static int x;
772   /// };
773   /// \endcode
774   bool isStaticDataMember() const {
775     // If it wasn't static, it would be a FieldDecl.
776     return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
777   }
778
779   virtual VarDecl *getCanonicalDecl();
780   const VarDecl *getCanonicalDecl() const {
781     return const_cast<VarDecl*>(this)->getCanonicalDecl();
782   }
783
784   enum DefinitionKind {
785     DeclarationOnly,      ///< This declaration is only a declaration.
786     TentativeDefinition,  ///< This declaration is a tentative definition.
787     Definition            ///< This declaration is definitely a definition.
788   };
789
790   /// \brief Check whether this declaration is a definition. If this could be
791   /// a tentative definition (in C), don't check whether there's an overriding
792   /// definition.
793   DefinitionKind isThisDeclarationADefinition() const;
794
795   /// \brief Check whether this variable is defined in this
796   /// translation unit.
797   DefinitionKind hasDefinition() const;
798
799   /// \brief Get the tentative definition that acts as the real definition in
800   /// a TU. Returns null if there is a proper definition available.
801   VarDecl *getActingDefinition();
802   const VarDecl *getActingDefinition() const {
803     return const_cast<VarDecl*>(this)->getActingDefinition();
804   }
805
806   /// \brief Determine whether this is a tentative definition of a
807   /// variable in C.
808   bool isTentativeDefinitionNow() const;
809
810   /// \brief Get the real (not just tentative) definition for this declaration.
811   VarDecl *getDefinition();
812   const VarDecl *getDefinition() const {
813     return const_cast<VarDecl*>(this)->getDefinition();
814   }
815
816   /// \brief Determine whether this is or was instantiated from an out-of-line 
817   /// definition of a static data member.
818   virtual bool isOutOfLine() const;
819
820   /// \brief If this is a static data member, find its out-of-line definition.
821   VarDecl *getOutOfLineDefinition();
822   
823   /// isFileVarDecl - Returns true for file scoped variable declaration.
824   bool isFileVarDecl() const {
825     if (getKind() != Decl::Var)
826       return false;
827     
828     if (getDeclContext()->getRedeclContext()->isFileContext())
829       return true;
830     
831     if (isStaticDataMember())
832       return true;
833
834     return false;
835   }
836
837   /// getAnyInitializer - Get the initializer for this variable, no matter which
838   /// declaration it is attached to.
839   const Expr *getAnyInitializer() const {
840     const VarDecl *D;
841     return getAnyInitializer(D);
842   }
843
844   /// getAnyInitializer - Get the initializer for this variable, no matter which
845   /// declaration it is attached to. Also get that declaration.
846   const Expr *getAnyInitializer(const VarDecl *&D) const;
847
848   bool hasInit() const {
849     return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
850   }
851   const Expr *getInit() const {
852     if (Init.isNull())
853       return 0;
854
855     const Stmt *S = Init.dyn_cast<Stmt *>();
856     if (!S) {
857       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
858         S = ES->Value;
859     }
860     return (const Expr*) S;
861   }
862   Expr *getInit() {
863     if (Init.isNull())
864       return 0;
865
866     Stmt *S = Init.dyn_cast<Stmt *>();
867     if (!S) {
868       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
869         S = ES->Value;
870     }
871
872     return (Expr*) S;
873   }
874
875   /// \brief Retrieve the address of the initializer expression.
876   Stmt **getInitAddress() {
877     if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
878       return &ES->Value;
879
880     // This union hack tip-toes around strict-aliasing rules.
881     union {
882       InitType *InitPtr;
883       Stmt **StmtPtr;
884     };
885
886     InitPtr = &Init;
887     return StmtPtr;
888   }
889
890   void setInit(Expr *I);
891
892   /// \brief Check whether we are in the process of parsing an initializer
893   /// needed to deduce the type of this variable.
894   bool isParsingAutoInit() const {
895     return ParsingAutoInit;
896   }
897
898   /// \brief Note whether we are currently parsing an initializer needed to
899   /// deduce the type of this variable.
900   void setParsingAutoInit(bool P) {
901     ParsingAutoInit = P;
902   }
903
904   EvaluatedStmt *EnsureEvaluatedStmt() const {
905     EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
906     if (!Eval) {
907       Stmt *S = Init.get<Stmt *>();
908       Eval = new (getASTContext()) EvaluatedStmt;
909       Eval->Value = S;
910       Init = Eval;
911     }
912     return Eval;
913   }
914
915   /// \brief Check whether we are in the process of checking whether the
916   /// initializer can be evaluated.
917   bool isEvaluatingValue() const {
918     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
919       return Eval->IsEvaluating;
920
921     return false;
922   }
923
924   /// \brief Note that we now are checking whether the initializer can be
925   /// evaluated.
926   void setEvaluatingValue() const {
927     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
928     Eval->IsEvaluating = true;
929   }
930
931   /// \brief Note that constant evaluation has computed the given
932   /// value for this variable's initializer.
933   void setEvaluatedValue(const APValue &Value) const {
934     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
935     Eval->IsEvaluating = false;
936     Eval->WasEvaluated = true;
937     Eval->Evaluated = Value;
938   }
939
940   /// \brief Return the already-evaluated value of this variable's
941   /// initializer, or NULL if the value is not yet known. Returns pointer
942   /// to untyped APValue if the value could not be evaluated.
943   APValue *getEvaluatedValue() const {
944     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
945       if (Eval->WasEvaluated)
946         return &Eval->Evaluated;
947
948     return 0;
949   }
950
951   /// \brief Determines whether it is already known whether the
952   /// initializer is an integral constant expression or not.
953   bool isInitKnownICE() const {
954     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
955       return Eval->CheckedICE;
956
957     return false;
958   }
959
960   /// \brief Determines whether the initializer is an integral
961   /// constant expression.
962   ///
963   /// \pre isInitKnownICE()
964   bool isInitICE() const {
965     assert(isInitKnownICE() &&
966            "Check whether we already know that the initializer is an ICE");
967     return Init.get<EvaluatedStmt *>()->IsICE;
968   }
969
970   /// \brief Check whether we are in the process of checking the initializer
971   /// is an integral constant expression.
972   bool isCheckingICE() const {
973     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
974       return Eval->CheckingICE;
975
976     return false;
977   }
978
979   /// \brief Note that we now are checking whether the initializer is an
980   /// integral constant expression.
981   void setCheckingICE() const {
982     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
983     Eval->CheckingICE = true;
984   }
985
986   /// \brief Note that we now know whether the initializer is an
987   /// integral constant expression.
988   void setInitKnownICE(bool IsICE) const {
989     EvaluatedStmt *Eval = EnsureEvaluatedStmt();
990     Eval->CheckingICE = false;
991     Eval->CheckedICE = true;
992     Eval->IsICE = IsICE;
993   }
994
995   void setCXXDirectInitializer(bool T) { HasCXXDirectInit = T; }
996
997   /// hasCXXDirectInitializer - If true, the initializer was a direct
998   /// initializer, e.g: "int x(1);". The Init expression will be the expression
999   /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
1000   /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
1001   /// by checking hasCXXDirectInitializer.
1002   ///
1003   bool hasCXXDirectInitializer() const {
1004     return HasCXXDirectInit;
1005   }
1006
1007   /// \brief Determine whether this variable is the exception variable in a
1008   /// C++ catch statememt or an Objective-C @catch statement.
1009   bool isExceptionVariable() const {
1010     return ExceptionVar;
1011   }
1012   void setExceptionVariable(bool EV) { ExceptionVar = EV; }
1013   
1014   /// \brief Determine whether this local variable can be used with the named
1015   /// return value optimization (NRVO).
1016   ///
1017   /// The named return value optimization (NRVO) works by marking certain
1018   /// non-volatile local variables of class type as NRVO objects. These
1019   /// locals can be allocated within the return slot of their containing
1020   /// function, in which case there is no need to copy the object to the
1021   /// return slot when returning from the function. Within the function body,
1022   /// each return that returns the NRVO object will have this variable as its
1023   /// NRVO candidate.
1024   bool isNRVOVariable() const { return NRVOVariable; }
1025   void setNRVOVariable(bool NRVO) { NRVOVariable = NRVO; }
1026   
1027   /// \brief If this variable is an instantiated static data member of a
1028   /// class template specialization, returns the templated static data member
1029   /// from which it was instantiated.
1030   VarDecl *getInstantiatedFromStaticDataMember() const;
1031
1032   /// \brief If this variable is a static data member, determine what kind of 
1033   /// template specialization or instantiation this is.
1034   TemplateSpecializationKind getTemplateSpecializationKind() const;
1035   
1036   /// \brief If this variable is an instantiation of a static data member of a
1037   /// class template specialization, retrieves the member specialization
1038   /// information.
1039   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1040   
1041   /// \brief For a static data member that was instantiated from a static
1042   /// data member of a class template, set the template specialiation kind.
1043   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1044                         SourceLocation PointOfInstantiation = SourceLocation());
1045
1046   // Implement isa/cast/dyncast/etc.
1047   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1048   static bool classof(const VarDecl *D) { return true; }
1049   static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1050 };
1051
1052 class ImplicitParamDecl : public VarDecl {
1053 protected:
1054   ImplicitParamDecl(Kind DK, DeclContext *DC, SourceLocation L,
1055                     IdentifierInfo *Id, QualType Tw)
1056     : VarDecl(DK, DC, L, Id, Tw, /*TInfo=*/0, SC_None, SC_None) {
1057     setImplicit();
1058   }
1059 public:
1060   static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1061                                    SourceLocation L, IdentifierInfo *Id,
1062                                    QualType T);
1063   // Implement isa/cast/dyncast/etc.
1064   static bool classof(const ImplicitParamDecl *D) { return true; }
1065   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1066   static bool classofKind(Kind K) { return K == ImplicitParam; }
1067 };
1068
1069 /// ParmVarDecl - Represent a parameter to a function.
1070 class ParmVarDecl : public VarDecl {
1071   // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
1072   /// FIXME: Also can be paced into the bitfields in Decl.
1073   /// in, inout, etc.
1074   unsigned objcDeclQualifier : 6;
1075   bool HasInheritedDefaultArg : 1;
1076
1077 protected:
1078   ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation L,
1079               IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1080               StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
1081     : VarDecl(DK, DC, L, Id, T, TInfo, S, SCAsWritten),
1082       objcDeclQualifier(OBJC_TQ_None), HasInheritedDefaultArg(false) {
1083     setDefaultArg(DefArg);
1084   }
1085
1086 public:
1087   static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1088                              SourceLocation L,IdentifierInfo *Id,
1089                              QualType T, TypeSourceInfo *TInfo,
1090                              StorageClass S, StorageClass SCAsWritten,
1091                              Expr *DefArg);
1092
1093   ObjCDeclQualifier getObjCDeclQualifier() const {
1094     return ObjCDeclQualifier(objcDeclQualifier);
1095   }
1096   void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1097     objcDeclQualifier = QTVal;
1098   }
1099
1100   Expr *getDefaultArg();
1101   const Expr *getDefaultArg() const {
1102     return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1103   }
1104   
1105   void setDefaultArg(Expr *defarg) {
1106     Init = reinterpret_cast<Stmt *>(defarg);
1107   }
1108
1109   unsigned getNumDefaultArgTemporaries() const;
1110   CXXTemporary *getDefaultArgTemporary(unsigned i);
1111   const CXXTemporary *getDefaultArgTemporary(unsigned i) const {
1112     return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i);
1113   }
1114   
1115   /// \brief Retrieve the source range that covers the entire default
1116   /// argument.
1117   SourceRange getDefaultArgRange() const;  
1118   void setUninstantiatedDefaultArg(Expr *arg) {
1119     Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1120   }
1121   Expr *getUninstantiatedDefaultArg() {
1122     return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1123   }
1124   const Expr *getUninstantiatedDefaultArg() const {
1125     return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1126   }
1127
1128   /// hasDefaultArg - Determines whether this parameter has a default argument,
1129   /// either parsed or not.
1130   bool hasDefaultArg() const {
1131     return getInit() || hasUnparsedDefaultArg() ||
1132       hasUninstantiatedDefaultArg();
1133   }
1134
1135   /// hasUnparsedDefaultArg - Determines whether this parameter has a
1136   /// default argument that has not yet been parsed. This will occur
1137   /// during the processing of a C++ class whose member functions have
1138   /// default arguments, e.g.,
1139   /// @code
1140   ///   class X {
1141   ///   public:
1142   ///     void f(int x = 17); // x has an unparsed default argument now
1143   ///   }; // x has a regular default argument now
1144   /// @endcode
1145   bool hasUnparsedDefaultArg() const {
1146     return Init.is<UnparsedDefaultArgument*>();
1147   }
1148
1149   bool hasUninstantiatedDefaultArg() const {
1150     return Init.is<UninstantiatedDefaultArgument*>();
1151   }
1152
1153   /// setUnparsedDefaultArg - Specify that this parameter has an
1154   /// unparsed default argument. The argument will be replaced with a
1155   /// real default argument via setDefaultArg when the class
1156   /// definition enclosing the function declaration that owns this
1157   /// default argument is completed.
1158   void setUnparsedDefaultArg() {
1159     Init = (UnparsedDefaultArgument *)0;
1160   }
1161
1162   bool hasInheritedDefaultArg() const {
1163     return HasInheritedDefaultArg;
1164   }
1165
1166   void setHasInheritedDefaultArg(bool I = true) {
1167     HasInheritedDefaultArg = I;
1168   }
1169
1170   QualType getOriginalType() const {
1171     if (getTypeSourceInfo())
1172       return getTypeSourceInfo()->getType();
1173     return getType();
1174   }
1175
1176   /// \brief Determine whether this parameter is actually a function
1177   /// parameter pack.
1178   bool isParameterPack() const;
1179   
1180   /// setOwningFunction - Sets the function declaration that owns this
1181   /// ParmVarDecl. Since ParmVarDecls are often created before the
1182   /// FunctionDecls that own them, this routine is required to update
1183   /// the DeclContext appropriately.
1184   void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1185
1186   // Implement isa/cast/dyncast/etc.
1187   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1188   static bool classof(const ParmVarDecl *D) { return true; }
1189   static bool classofKind(Kind K) { return K == ParmVar; }
1190 };
1191
1192 /// FunctionDecl - An instance of this class is created to represent a
1193 /// function declaration or definition.
1194 ///
1195 /// Since a given function can be declared several times in a program,
1196 /// there may be several FunctionDecls that correspond to that
1197 /// function. Only one of those FunctionDecls will be found when
1198 /// traversing the list of declarations in the context of the
1199 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1200 /// contains all of the information known about the function. Other,
1201 /// previous declarations of the function are available via the
1202 /// getPreviousDeclaration() chain.
1203 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1204                      public Redeclarable<FunctionDecl> {
1205 public:
1206   typedef clang::StorageClass StorageClass;
1207
1208   /// \brief The kind of templated function a FunctionDecl can be.
1209   enum TemplatedKind {
1210     TK_NonTemplate,
1211     TK_FunctionTemplate,
1212     TK_MemberSpecialization,
1213     TK_FunctionTemplateSpecialization,
1214     TK_DependentFunctionTemplateSpecialization
1215   };
1216
1217 private:
1218   /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1219   /// parameters of this function.  This is null if a prototype or if there are
1220   /// no formals.
1221   ParmVarDecl **ParamInfo;
1222
1223   LazyDeclStmtPtr Body;
1224
1225   // FIXME: This can be packed into the bitfields in Decl.
1226   // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1227   unsigned SClass : 2;
1228   unsigned SClassAsWritten : 2;
1229   bool IsInline : 1;
1230   bool IsInlineSpecified : 1;
1231   bool IsVirtualAsWritten : 1;
1232   bool IsPure : 1;
1233   bool HasInheritedPrototype : 1;
1234   bool HasWrittenPrototype : 1;
1235   bool IsDeleted : 1;
1236   bool IsTrivial : 1; // sunk from CXXMethodDecl
1237   bool HasImplicitReturnZero : 1;
1238
1239   /// \brief End part of this FunctionDecl's source range.
1240   ///
1241   /// We could compute the full range in getSourceRange(). However, when we're
1242   /// dealing with a function definition deserialized from a PCH/AST file,
1243   /// we can only compute the full range once the function body has been
1244   /// de-serialized, so it's far better to have the (sometimes-redundant)
1245   /// EndRangeLoc.
1246   SourceLocation EndRangeLoc;
1247
1248   /// \brief The template or declaration that this declaration
1249   /// describes or was instantiated from, respectively.
1250   ///
1251   /// For non-templates, this value will be NULL. For function
1252   /// declarations that describe a function template, this will be a
1253   /// pointer to a FunctionTemplateDecl. For member functions
1254   /// of class template specializations, this will be a MemberSpecializationInfo
1255   /// pointer containing information about the specialization.
1256   /// For function template specializations, this will be a
1257   /// FunctionTemplateSpecializationInfo, which contains information about
1258   /// the template being specialized and the template arguments involved in
1259   /// that specialization.
1260   llvm::PointerUnion4<FunctionTemplateDecl *, 
1261                       MemberSpecializationInfo *,
1262                       FunctionTemplateSpecializationInfo *,
1263                       DependentFunctionTemplateSpecializationInfo *>
1264     TemplateOrSpecialization;
1265
1266   /// DNLoc - Provides source/type location info for the
1267   /// declaration name embedded in the DeclaratorDecl base class.
1268   DeclarationNameLoc DNLoc;
1269
1270   /// \brief Specify that this function declaration is actually a function
1271   /// template specialization.
1272   ///
1273   /// \param C the ASTContext.
1274   ///
1275   /// \param Template the function template that this function template
1276   /// specialization specializes.
1277   ///
1278   /// \param TemplateArgs the template arguments that produced this
1279   /// function template specialization from the template.
1280   ///
1281   /// \param InsertPos If non-NULL, the position in the function template
1282   /// specialization set where the function template specialization data will
1283   /// be inserted.
1284   ///
1285   /// \param TSK the kind of template specialization this is.
1286   ///
1287   /// \param TemplateArgsAsWritten location info of template arguments.
1288   ///
1289   /// \param PointOfInstantiation point at which the function template
1290   /// specialization was first instantiated. 
1291   void setFunctionTemplateSpecialization(ASTContext &C,
1292                                          FunctionTemplateDecl *Template,
1293                                        const TemplateArgumentList *TemplateArgs,
1294                                          void *InsertPos,
1295                                          TemplateSpecializationKind TSK,
1296                           const TemplateArgumentListInfo *TemplateArgsAsWritten,
1297                                          SourceLocation PointOfInstantiation);
1298
1299   /// \brief Specify that this record is an instantiation of the
1300   /// member function FD.
1301   void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1302                                         TemplateSpecializationKind TSK);
1303
1304   void setParams(ASTContext &C, ParmVarDecl **NewParamInfo, unsigned NumParams);
1305
1306 protected:
1307   FunctionDecl(Kind DK, DeclContext *DC, const DeclarationNameInfo &NameInfo,
1308                QualType T, TypeSourceInfo *TInfo,
1309                StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified)
1310     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo),
1311       DeclContext(DK),
1312       ParamInfo(0), Body(),
1313       SClass(S), SClassAsWritten(SCAsWritten), 
1314       IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1315       IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1316       HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1317       HasImplicitReturnZero(false), EndRangeLoc(NameInfo.getEndLoc()),
1318       TemplateOrSpecialization(),
1319       DNLoc(NameInfo.getInfo()) {}
1320
1321   typedef Redeclarable<FunctionDecl> redeclarable_base;
1322   virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1323
1324 public:
1325   typedef redeclarable_base::redecl_iterator redecl_iterator;
1326   redecl_iterator redecls_begin() const {
1327     return redeclarable_base::redecls_begin();
1328   }
1329   redecl_iterator redecls_end() const {
1330     return redeclarable_base::redecls_end();
1331   }
1332
1333   static FunctionDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1334                               DeclarationName N, QualType T,
1335                               TypeSourceInfo *TInfo,
1336                               StorageClass S = SC_None,
1337                               StorageClass SCAsWritten = SC_None,
1338                               bool isInlineSpecified = false,
1339                               bool hasWrittenPrototype = true) {
1340     DeclarationNameInfo NameInfo(N, L);
1341     return FunctionDecl::Create(C, DC, NameInfo, T, TInfo, S, SCAsWritten,
1342                                 isInlineSpecified, hasWrittenPrototype);
1343   }
1344
1345   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1346                               const DeclarationNameInfo &NameInfo,
1347                               QualType T, TypeSourceInfo *TInfo,
1348                               StorageClass S = SC_None,
1349                               StorageClass SCAsWritten = SC_None,
1350                               bool isInlineSpecified = false,
1351                               bool hasWrittenPrototype = true);
1352
1353   DeclarationNameInfo getNameInfo() const {
1354     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1355   }
1356
1357   virtual void getNameForDiagnostic(std::string &S,
1358                                     const PrintingPolicy &Policy,
1359                                     bool Qualified) const;
1360
1361   virtual SourceRange getSourceRange() const {
1362     return SourceRange(getOuterLocStart(), EndRangeLoc);
1363   }
1364   void setLocEnd(SourceLocation E) {
1365     EndRangeLoc = E;
1366   }
1367
1368   /// \brief Returns true if the function has a body (definition). The
1369   /// function body might be in any of the (re-)declarations of this
1370   /// function. The variant that accepts a FunctionDecl pointer will
1371   /// set that function declaration to the actual declaration
1372   /// containing the body (if there is one).
1373   bool hasBody(const FunctionDecl *&Definition) const;
1374
1375   virtual bool hasBody() const {
1376     const FunctionDecl* Definition;
1377     return hasBody(Definition);
1378   }
1379
1380   /// getBody - Retrieve the body (definition) of the function. The
1381   /// function body might be in any of the (re-)declarations of this
1382   /// function. The variant that accepts a FunctionDecl pointer will
1383   /// set that function declaration to the actual declaration
1384   /// containing the body (if there is one).
1385   /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1386   /// unnecessary AST de-serialization of the body.
1387   Stmt *getBody(const FunctionDecl *&Definition) const;
1388
1389   virtual Stmt *getBody() const {
1390     const FunctionDecl* Definition;
1391     return getBody(Definition);
1392   }
1393
1394   /// isThisDeclarationADefinition - Returns whether this specific
1395   /// declaration of the function is also a definition. This does not
1396   /// determine whether the function has been defined (e.g., in a
1397   /// previous definition); for that information, use getBody.
1398   /// FIXME: Should return true if function is deleted or defaulted. However,
1399   /// CodeGenModule.cpp uses it, and I don't know if this would break it.
1400   bool isThisDeclarationADefinition() const { return Body; }
1401
1402   void setBody(Stmt *B);
1403   void setLazyBody(uint64_t Offset) { Body = Offset; }
1404
1405   /// Whether this function is variadic.
1406   bool isVariadic() const;
1407
1408   /// Whether this function is marked as virtual explicitly.
1409   bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1410   void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1411
1412   /// Whether this virtual function is pure, i.e. makes the containing class
1413   /// abstract.
1414   bool isPure() const { return IsPure; }
1415   void setPure(bool P = true);
1416
1417   /// Whether this function is "trivial" in some specialized C++ senses.
1418   /// Can only be true for default constructors, copy constructors,
1419   /// copy assignment operators, and destructors.  Not meaningful until
1420   /// the class has been fully built by Sema.
1421   bool isTrivial() const { return IsTrivial; }
1422   void setTrivial(bool IT) { IsTrivial = IT; }
1423
1424   /// Whether falling off this function implicitly returns null/zero.
1425   /// If a more specific implicit return value is required, front-ends
1426   /// should synthesize the appropriate return statements.
1427   bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1428   void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1429
1430   /// \brief Whether this function has a prototype, either because one
1431   /// was explicitly written or because it was "inherited" by merging
1432   /// a declaration without a prototype with a declaration that has a
1433   /// prototype.
1434   bool hasPrototype() const {
1435     return HasWrittenPrototype || HasInheritedPrototype;
1436   }
1437
1438   bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1439
1440   /// \brief Whether this function inherited its prototype from a
1441   /// previous declaration.
1442   bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1443   void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1444
1445   /// \brief Whether this function has been deleted.
1446   ///
1447   /// A function that is "deleted" (via the C++0x "= delete" syntax)
1448   /// acts like a normal function, except that it cannot actually be
1449   /// called or have its address taken. Deleted functions are
1450   /// typically used in C++ overload resolution to attract arguments
1451   /// whose type or lvalue/rvalue-ness would permit the use of a
1452   /// different overload that would behave incorrectly. For example,
1453   /// one might use deleted functions to ban implicit conversion from
1454   /// a floating-point number to an Integer type:
1455   ///
1456   /// @code
1457   /// struct Integer {
1458   ///   Integer(long); // construct from a long
1459   ///   Integer(double) = delete; // no construction from float or double
1460   ///   Integer(long double) = delete; // no construction from long double
1461   /// };
1462   /// @endcode
1463   bool isDeleted() const { return IsDeleted; }
1464   void setDeleted(bool D = true) { IsDeleted = D; }
1465
1466   /// \brief Determines whether this is a function "main", which is
1467   /// the entry point into an executable program.
1468   bool isMain() const;
1469
1470   /// \brief Determines whether this function is a function with
1471   /// external, C linkage.
1472   bool isExternC() const;
1473
1474   /// \brief Determines whether this is a global function.
1475   bool isGlobal() const;
1476
1477   void setPreviousDeclaration(FunctionDecl * PrevDecl);
1478
1479   virtual const FunctionDecl *getCanonicalDecl() const;
1480   virtual FunctionDecl *getCanonicalDecl();
1481
1482   unsigned getBuiltinID() const;
1483
1484   // Iterator access to formal parameters.
1485   unsigned param_size() const { return getNumParams(); }
1486   typedef ParmVarDecl **param_iterator;
1487   typedef ParmVarDecl * const *param_const_iterator;
1488
1489   param_iterator param_begin() { return ParamInfo; }
1490   param_iterator param_end()   { return ParamInfo+param_size(); }
1491
1492   param_const_iterator param_begin() const { return ParamInfo; }
1493   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1494
1495   /// getNumParams - Return the number of parameters this function must have
1496   /// based on its FunctionType.  This is the length of the ParamInfo array
1497   /// after it has been created.
1498   unsigned getNumParams() const;
1499
1500   const ParmVarDecl *getParamDecl(unsigned i) const {
1501     assert(i < getNumParams() && "Illegal param #");
1502     return ParamInfo[i];
1503   }
1504   ParmVarDecl *getParamDecl(unsigned i) {
1505     assert(i < getNumParams() && "Illegal param #");
1506     return ParamInfo[i];
1507   }
1508   void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams) {
1509     setParams(getASTContext(), NewParamInfo, NumParams);
1510   }
1511
1512   /// getMinRequiredArguments - Returns the minimum number of arguments
1513   /// needed to call this function. This may be fewer than the number of
1514   /// function parameters, if some of the parameters have default
1515   /// arguments (in C++).
1516   unsigned getMinRequiredArguments() const;
1517
1518   QualType getResultType() const {
1519     return getType()->getAs<FunctionType>()->getResultType();
1520   }
1521   
1522   /// \brief Determine the type of an expression that calls this function.
1523   QualType getCallResultType() const {
1524     return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1525   }
1526                        
1527   StorageClass getStorageClass() const { return StorageClass(SClass); }
1528   void setStorageClass(StorageClass SC);
1529
1530   StorageClass getStorageClassAsWritten() const {
1531     return StorageClass(SClassAsWritten);
1532   }
1533
1534   /// \brief Determine whether the "inline" keyword was specified for this
1535   /// function.
1536   bool isInlineSpecified() const { return IsInlineSpecified; }
1537                        
1538   /// Set whether the "inline" keyword was specified for this function.
1539   void setInlineSpecified(bool I) { 
1540     IsInlineSpecified = I; 
1541     IsInline = I;
1542   }
1543
1544   /// Flag that this function is implicitly inline.
1545   void setImplicitlyInline() {
1546     IsInline = true;
1547   }
1548
1549   /// \brief Determine whether this function should be inlined, because it is
1550   /// either marked "inline" or is a member function of a C++ class that
1551   /// was defined in the class body.
1552   bool isInlined() const;
1553
1554   bool isInlineDefinitionExternallyVisible() const;
1555                        
1556   /// isOverloadedOperator - Whether this function declaration
1557   /// represents an C++ overloaded operator, e.g., "operator+".
1558   bool isOverloadedOperator() const {
1559     return getOverloadedOperator() != OO_None;
1560   }
1561
1562   OverloadedOperatorKind getOverloadedOperator() const;
1563
1564   const IdentifierInfo *getLiteralIdentifier() const;
1565
1566   /// \brief If this function is an instantiation of a member function
1567   /// of a class template specialization, retrieves the function from
1568   /// which it was instantiated.
1569   ///
1570   /// This routine will return non-NULL for (non-templated) member
1571   /// functions of class templates and for instantiations of function
1572   /// templates. For example, given:
1573   ///
1574   /// \code
1575   /// template<typename T>
1576   /// struct X {
1577   ///   void f(T);
1578   /// };
1579   /// \endcode
1580   ///
1581   /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1582   /// whose parent is the class template specialization X<int>. For
1583   /// this declaration, getInstantiatedFromFunction() will return
1584   /// the FunctionDecl X<T>::A. When a complete definition of
1585   /// X<int>::A is required, it will be instantiated from the
1586   /// declaration returned by getInstantiatedFromMemberFunction().
1587   FunctionDecl *getInstantiatedFromMemberFunction() const;
1588   
1589   /// \brief What kind of templated function this is.
1590   TemplatedKind getTemplatedKind() const;
1591
1592   /// \brief If this function is an instantiation of a member function of a
1593   /// class template specialization, retrieves the member specialization
1594   /// information.
1595   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1596                        
1597   /// \brief Specify that this record is an instantiation of the
1598   /// member function FD.
1599   void setInstantiationOfMemberFunction(FunctionDecl *FD,
1600                                         TemplateSpecializationKind TSK) {
1601     setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1602   }
1603
1604   /// \brief Retrieves the function template that is described by this
1605   /// function declaration.
1606   ///
1607   /// Every function template is represented as a FunctionTemplateDecl
1608   /// and a FunctionDecl (or something derived from FunctionDecl). The
1609   /// former contains template properties (such as the template
1610   /// parameter lists) while the latter contains the actual
1611   /// description of the template's
1612   /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1613   /// FunctionDecl that describes the function template,
1614   /// getDescribedFunctionTemplate() retrieves the
1615   /// FunctionTemplateDecl from a FunctionDecl.
1616   FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1617     return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1618   }
1619
1620   void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1621     TemplateOrSpecialization = Template;
1622   }
1623
1624   /// \brief Determine whether this function is a function template 
1625   /// specialization.
1626   bool isFunctionTemplateSpecialization() const {
1627     return getPrimaryTemplate() != 0;
1628   }
1629        
1630   /// \brief If this function is actually a function template specialization,
1631   /// retrieve information about this function template specialization. 
1632   /// Otherwise, returns NULL.
1633   FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1634     return TemplateOrSpecialization.
1635              dyn_cast<FunctionTemplateSpecializationInfo*>();
1636   }
1637
1638   /// \brief Determines whether this function is a function template
1639   /// specialization or a member of a class template specialization that can
1640   /// be implicitly instantiated.
1641   bool isImplicitlyInstantiable() const;
1642               
1643   /// \brief Retrieve the function declaration from which this function could
1644   /// be instantiated, if it is an instantiation (rather than a non-template
1645   /// or a specialization, for example).
1646   FunctionDecl *getTemplateInstantiationPattern() const;
1647
1648   /// \brief Retrieve the primary template that this function template
1649   /// specialization either specializes or was instantiated from.
1650   ///
1651   /// If this function declaration is not a function template specialization,
1652   /// returns NULL.
1653   FunctionTemplateDecl *getPrimaryTemplate() const;
1654
1655   /// \brief Retrieve the template arguments used to produce this function
1656   /// template specialization from the primary template.
1657   ///
1658   /// If this function declaration is not a function template specialization,
1659   /// returns NULL.
1660   const TemplateArgumentList *getTemplateSpecializationArgs() const;
1661
1662   /// \brief Retrieve the template argument list as written in the sources,
1663   /// if any.
1664   ///
1665   /// If this function declaration is not a function template specialization
1666   /// or if it had no explicit template argument list, returns NULL.
1667   /// Note that it an explicit template argument list may be written empty,
1668   /// e.g., template<> void foo<>(char* s);
1669   const TemplateArgumentListInfo*
1670   getTemplateSpecializationArgsAsWritten() const;
1671
1672   /// \brief Specify that this function declaration is actually a function
1673   /// template specialization.
1674   ///
1675   /// \param Template the function template that this function template
1676   /// specialization specializes.
1677   ///
1678   /// \param TemplateArgs the template arguments that produced this
1679   /// function template specialization from the template.
1680   ///
1681   /// \param InsertPos If non-NULL, the position in the function template
1682   /// specialization set where the function template specialization data will
1683   /// be inserted.
1684   ///
1685   /// \param TSK the kind of template specialization this is.
1686   ///
1687   /// \param TemplateArgsAsWritten location info of template arguments.
1688   ///
1689   /// \param PointOfInstantiation point at which the function template
1690   /// specialization was first instantiated. 
1691   void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1692                                       const TemplateArgumentList *TemplateArgs,
1693                                          void *InsertPos,
1694                     TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
1695                     const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
1696                     SourceLocation PointOfInstantiation = SourceLocation()) {
1697     setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
1698                                       InsertPos, TSK, TemplateArgsAsWritten,
1699                                       PointOfInstantiation);
1700   }
1701
1702   /// \brief Specifies that this function declaration is actually a
1703   /// dependent function template specialization.
1704   void setDependentTemplateSpecialization(ASTContext &Context,
1705                              const UnresolvedSetImpl &Templates,
1706                       const TemplateArgumentListInfo &TemplateArgs);
1707
1708   DependentFunctionTemplateSpecializationInfo *
1709   getDependentSpecializationInfo() const {
1710     return TemplateOrSpecialization.
1711              dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
1712   }
1713
1714   /// \brief Determine what kind of template instantiation this function
1715   /// represents.
1716   TemplateSpecializationKind getTemplateSpecializationKind() const;
1717
1718   /// \brief Determine what kind of template instantiation this function
1719   /// represents.
1720   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1721                         SourceLocation PointOfInstantiation = SourceLocation());
1722
1723   /// \brief Retrieve the (first) point of instantiation of a function template
1724   /// specialization or a member of a class template specialization.
1725   ///
1726   /// \returns the first point of instantiation, if this function was 
1727   /// instantiated from a template; otherwie, returns an invalid source 
1728   /// location.
1729   SourceLocation getPointOfInstantiation() const;
1730                        
1731   /// \brief Determine whether this is or was instantiated from an out-of-line 
1732   /// definition of a member function.
1733   virtual bool isOutOfLine() const;
1734                        
1735   // Implement isa/cast/dyncast/etc.
1736   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1737   static bool classof(const FunctionDecl *D) { return true; }
1738   static bool classofKind(Kind K) {
1739     return K >= firstFunction && K <= lastFunction;
1740   }
1741   static DeclContext *castToDeclContext(const FunctionDecl *D) {
1742     return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
1743   }
1744   static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
1745     return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
1746   }
1747
1748   friend class ASTDeclReader;
1749   friend class ASTDeclWriter;
1750 };
1751
1752
1753 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
1754 /// represent a member of a struct/union/class.
1755 class FieldDecl : public DeclaratorDecl {
1756   // FIXME: This can be packed into the bitfields in Decl.
1757   bool Mutable : 1;
1758   mutable unsigned CachedFieldIndex : 31;
1759
1760   Expr *BitWidth;
1761 protected:
1762   FieldDecl(Kind DK, DeclContext *DC, SourceLocation L,
1763             IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1764             Expr *BW, bool Mutable)
1765     : DeclaratorDecl(DK, DC, L, Id, T, TInfo),
1766       Mutable(Mutable), CachedFieldIndex(0), BitWidth(BW) {
1767   }
1768
1769 public:
1770   static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
1771                            SourceLocation L, IdentifierInfo *Id, QualType T,
1772                            TypeSourceInfo *TInfo, Expr *BW, bool Mutable);
1773
1774   /// getFieldIndex - Returns the index of this field within its record,
1775   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
1776   unsigned getFieldIndex() const;
1777
1778   /// isMutable - Determines whether this field is mutable (C++ only).
1779   bool isMutable() const { return Mutable; }
1780
1781   /// \brief Set whether this field is mutable (C++ only).
1782   void setMutable(bool M) { Mutable = M; }
1783
1784   /// isBitfield - Determines whether this field is a bitfield.
1785   bool isBitField() const { return BitWidth != NULL; }
1786
1787   /// @brief Determines whether this is an unnamed bitfield.
1788   bool isUnnamedBitfield() const { return BitWidth != NULL && !getDeclName(); }
1789
1790   /// isAnonymousStructOrUnion - Determines whether this field is a
1791   /// representative for an anonymous struct or union. Such fields are
1792   /// unnamed and are implicitly generated by the implementation to
1793   /// store the data for the anonymous union or struct.
1794   bool isAnonymousStructOrUnion() const;
1795
1796   Expr *getBitWidth() const { return BitWidth; }
1797   void setBitWidth(Expr *BW) { BitWidth = BW; }
1798
1799   /// getParent - Returns the parent of this field declaration, which
1800   /// is the struct in which this method is defined.
1801   const RecordDecl *getParent() const {
1802     return cast<RecordDecl>(getDeclContext());
1803   }
1804
1805   RecordDecl *getParent() {
1806     return cast<RecordDecl>(getDeclContext());
1807   }
1808   
1809   // Implement isa/cast/dyncast/etc.
1810   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1811   static bool classof(const FieldDecl *D) { return true; }
1812   static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
1813 };
1814
1815 /// EnumConstantDecl - An instance of this object exists for each enum constant
1816 /// that is defined.  For example, in "enum X {a,b}", each of a/b are
1817 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
1818 /// TagType for the X EnumDecl.
1819 class EnumConstantDecl : public ValueDecl {
1820   Stmt *Init; // an integer constant expression
1821   llvm::APSInt Val; // The value.
1822 protected:
1823   EnumConstantDecl(DeclContext *DC, SourceLocation L,
1824                    IdentifierInfo *Id, QualType T, Expr *E,
1825                    const llvm::APSInt &V)
1826     : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
1827
1828 public:
1829
1830   static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
1831                                   SourceLocation L, IdentifierInfo *Id,
1832                                   QualType T, Expr *E,
1833                                   const llvm::APSInt &V);
1834
1835   const Expr *getInitExpr() const { return (const Expr*) Init; }
1836   Expr *getInitExpr() { return (Expr*) Init; }
1837   const llvm::APSInt &getInitVal() const { return Val; }
1838
1839   void setInitExpr(Expr *E) { Init = (Stmt*) E; }
1840   void setInitVal(const llvm::APSInt &V) { Val = V; }
1841
1842   SourceRange getSourceRange() const;
1843   
1844   // Implement isa/cast/dyncast/etc.
1845   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1846   static bool classof(const EnumConstantDecl *D) { return true; }
1847   static bool classofKind(Kind K) { return K == EnumConstant; }
1848
1849   friend class StmtIteratorBase;
1850 };
1851
1852 /// IndirectFieldDecl - An instance of this class is created to represent a
1853 /// field injected from an anonymous union/struct into the parent scope.
1854 /// IndirectFieldDecl are always implicit.
1855 class IndirectFieldDecl : public ValueDecl {
1856   NamedDecl **Chaining;
1857   unsigned ChainingSize;
1858
1859   IndirectFieldDecl(DeclContext *DC, SourceLocation L,
1860                     DeclarationName N, QualType T,
1861                     NamedDecl **CH, unsigned CHS)
1862     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
1863
1864 public:
1865   static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
1866                                    SourceLocation L, IdentifierInfo *Id,
1867                                    QualType T, NamedDecl **CH, unsigned CHS);
1868   
1869   typedef NamedDecl * const *chain_iterator;
1870   chain_iterator chain_begin() const { return Chaining; }
1871   chain_iterator chain_end() const  { return Chaining+ChainingSize; }
1872
1873   unsigned getChainingSize() const { return ChainingSize; }
1874
1875   FieldDecl *getAnonField() const {
1876     assert(ChainingSize >= 2);
1877     return cast<FieldDecl>(Chaining[ChainingSize - 1]);
1878   }
1879
1880   VarDecl *getVarDecl() const {
1881     assert(ChainingSize >= 2);
1882     return dyn_cast<VarDecl>(*chain_begin());
1883   }
1884
1885   // Implement isa/cast/dyncast/etc.
1886   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1887   static bool classof(const IndirectFieldDecl *D) { return true; }
1888   static bool classofKind(Kind K) { return K == IndirectField; }
1889   friend class ASTDeclReader;
1890 };
1891
1892 /// TypeDecl - Represents a declaration of a type.
1893 ///
1894 class TypeDecl : public NamedDecl {
1895   /// TypeForDecl - This indicates the Type object that represents
1896   /// this TypeDecl.  It is a cache maintained by
1897   /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
1898   /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
1899   mutable const Type *TypeForDecl;
1900   friend class ASTContext;
1901   friend class DeclContext;
1902   friend class TagDecl;
1903   friend class TemplateTypeParmDecl;
1904   friend class TagType;
1905
1906 protected:
1907   TypeDecl(Kind DK, DeclContext *DC, SourceLocation L,
1908            IdentifierInfo *Id)
1909     : NamedDecl(DK, DC, L, Id), TypeForDecl(0) {}
1910
1911 public:
1912   // Low-level accessor
1913   const Type *getTypeForDecl() const { return TypeForDecl; }
1914   void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
1915
1916   // Implement isa/cast/dyncast/etc.
1917   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1918   static bool classof(const TypeDecl *D) { return true; }
1919   static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
1920 };
1921
1922
1923 class TypedefDecl : public TypeDecl, public Redeclarable<TypedefDecl> {
1924   /// UnderlyingType - This is the type the typedef is set to.
1925   TypeSourceInfo *TInfo;
1926
1927   TypedefDecl(DeclContext *DC, SourceLocation L,
1928               IdentifierInfo *Id, TypeSourceInfo *TInfo)
1929     : TypeDecl(Typedef, DC, L, Id), TInfo(TInfo) {}
1930
1931 protected:
1932   typedef Redeclarable<TypedefDecl> redeclarable_base;
1933   virtual TypedefDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1934
1935 public:
1936   typedef redeclarable_base::redecl_iterator redecl_iterator;
1937   redecl_iterator redecls_begin() const {
1938     return redeclarable_base::redecls_begin();
1939   }
1940   redecl_iterator redecls_end() const {
1941     return redeclarable_base::redecls_end();
1942   }
1943
1944   static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
1945                              SourceLocation L, IdentifierInfo *Id,
1946                              TypeSourceInfo *TInfo);
1947
1948   TypeSourceInfo *getTypeSourceInfo() const {
1949     return TInfo;
1950   }
1951
1952   /// Retrieves the canonical declaration of this typedef.
1953   TypedefDecl *getCanonicalDecl() {
1954     return getFirstDeclaration();
1955   }
1956   const TypedefDecl *getCanonicalDecl() const {
1957     return getFirstDeclaration();
1958   }
1959
1960   QualType getUnderlyingType() const {
1961     return TInfo->getType();
1962   }
1963   void setTypeSourceInfo(TypeSourceInfo *newType) {
1964     TInfo = newType;
1965   }
1966
1967   // Implement isa/cast/dyncast/etc.
1968   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1969   static bool classof(const TypedefDecl *D) { return true; }
1970   static bool classofKind(Kind K) { return K == Typedef; }
1971 };
1972
1973 class TypedefDecl;
1974
1975 /// TagDecl - Represents the declaration of a struct/union/class/enum.
1976 class TagDecl
1977   : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
1978 public:
1979   // This is really ugly.
1980   typedef TagTypeKind TagKind;
1981
1982 private:
1983   // FIXME: This can be packed into the bitfields in Decl.
1984   /// TagDeclKind - The TagKind enum.
1985   unsigned TagDeclKind : 2;
1986
1987   /// IsDefinition - True if this is a definition ("struct foo {};"), false if
1988   /// it is a declaration ("struct foo;").
1989   bool IsDefinition : 1;
1990
1991   /// IsBeingDefined - True if this is currently being defined.
1992   bool IsBeingDefined : 1;
1993
1994   /// IsEmbeddedInDeclarator - True if this tag declaration is
1995   /// "embedded" (i.e., defined or declared for the very first time)
1996   /// in the syntax of a declarator.
1997   bool IsEmbeddedInDeclarator : 1;
1998
1999 protected:
2000   // These are used by (and only defined for) EnumDecl.
2001   unsigned NumPositiveBits : 8;
2002   unsigned NumNegativeBits : 8;
2003
2004   /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2005   /// possible in C++0x mode.
2006   bool IsScoped : 1;
2007   /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2008   /// then this is true if the scoped enum was declared using the class
2009   /// tag, false if it was declared with the struct tag. No meaning is
2010   /// associated if this tag declaration is not a scoped enum.
2011   bool IsScopedUsingClassTag : 1;
2012
2013   /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2014   /// possible in C++0x mode.
2015   bool IsFixed : 1;
2016
2017 private:
2018   SourceLocation TagKeywordLoc;
2019   SourceLocation RBraceLoc;
2020
2021   // A struct representing syntactic qualifier info,
2022   // to be used for the (uncommon) case of out-of-line declarations.
2023   typedef QualifierInfo ExtInfo;
2024
2025   /// TypedefDeclOrQualifier - If the (out-of-line) tag declaration name
2026   /// is qualified, it points to the qualifier info (nns and range);
2027   /// otherwise, if the tag declaration is anonymous and it is part of
2028   /// a typedef, it points to the TypedefDecl (used for mangling);
2029   /// otherwise, it is a null (TypedefDecl) pointer.
2030   llvm::PointerUnion<TypedefDecl*, ExtInfo*> TypedefDeclOrQualifier;
2031
2032   bool hasExtInfo() const { return TypedefDeclOrQualifier.is<ExtInfo*>(); }
2033   ExtInfo *getExtInfo() { return TypedefDeclOrQualifier.get<ExtInfo*>(); }
2034   const ExtInfo *getExtInfo() const {
2035     return TypedefDeclOrQualifier.get<ExtInfo*>();
2036   }
2037
2038 protected:
2039   TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2040           SourceLocation L, IdentifierInfo *Id,
2041           TagDecl *PrevDecl, SourceLocation TKL = SourceLocation())
2042     : TypeDecl(DK, DC, L, Id), DeclContext(DK), TagKeywordLoc(TKL),
2043       TypedefDeclOrQualifier((TypedefDecl*) 0) {
2044     assert((DK != Enum || TK == TTK_Enum) &&
2045            "EnumDecl not matched with TTK_Enum");
2046     TagDeclKind = TK;
2047     IsDefinition = false;
2048     IsBeingDefined = false;
2049     IsEmbeddedInDeclarator = false;
2050     setPreviousDeclaration(PrevDecl);
2051   }
2052
2053   typedef Redeclarable<TagDecl> redeclarable_base;
2054   virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2055
2056   /// @brief Completes the definition of this tag declaration.
2057   ///
2058   /// This is a helper function for derived classes.
2059   void completeDefinition();    
2060     
2061 public:
2062   typedef redeclarable_base::redecl_iterator redecl_iterator;
2063   redecl_iterator redecls_begin() const {
2064     return redeclarable_base::redecls_begin();
2065   }
2066   redecl_iterator redecls_end() const {
2067     return redeclarable_base::redecls_end();
2068   }
2069
2070   SourceLocation getRBraceLoc() const { return RBraceLoc; }
2071   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2072
2073   SourceLocation getTagKeywordLoc() const { return TagKeywordLoc; }
2074   void setTagKeywordLoc(SourceLocation TKL) { TagKeywordLoc = TKL; }
2075
2076   /// getInnerLocStart - Return SourceLocation representing start of source
2077   /// range ignoring outer template declarations.
2078   virtual SourceLocation getInnerLocStart() const { return TagKeywordLoc; }
2079
2080   /// getOuterLocStart - Return SourceLocation representing start of source
2081   /// range taking into account any outer template declarations.
2082   SourceLocation getOuterLocStart() const;
2083   virtual SourceRange getSourceRange() const;
2084
2085   virtual TagDecl* getCanonicalDecl();
2086   const TagDecl* getCanonicalDecl() const {
2087     return const_cast<TagDecl*>(this)->getCanonicalDecl();
2088   }
2089
2090   /// isThisDeclarationADefinition() - Return true if this declaration
2091   /// defines the type.  Provided for consistency.
2092   bool isThisDeclarationADefinition() const {
2093     return isDefinition();
2094   }
2095
2096   /// isDefinition - Return true if this decl has its body specified.
2097   bool isDefinition() const {
2098     return IsDefinition;
2099   }
2100
2101   /// isBeingDefined - Return true if this decl is currently being defined.
2102   bool isBeingDefined() const {
2103     return IsBeingDefined;
2104   }
2105
2106   bool isEmbeddedInDeclarator() const {
2107     return IsEmbeddedInDeclarator;
2108   }
2109   void setEmbeddedInDeclarator(bool isInDeclarator) {
2110     IsEmbeddedInDeclarator = isInDeclarator;
2111   }
2112
2113   /// \brief Whether this declaration declares a type that is
2114   /// dependent, i.e., a type that somehow depends on template
2115   /// parameters.
2116   bool isDependentType() const { return isDependentContext(); }
2117
2118   /// @brief Starts the definition of this tag declaration.
2119   ///
2120   /// This method should be invoked at the beginning of the definition
2121   /// of this tag declaration. It will set the tag type into a state
2122   /// where it is in the process of being defined.
2123   void startDefinition();
2124
2125   /// getDefinition - Returns the TagDecl that actually defines this
2126   ///  struct/union/class/enum.  When determining whether or not a
2127   ///  struct/union/class/enum is completely defined, one should use this method
2128   ///  as opposed to 'isDefinition'.  'isDefinition' indicates whether or not a
2129   ///  specific TagDecl is defining declaration, not whether or not the
2130   ///  struct/union/class/enum type is defined.  This method returns NULL if
2131   ///  there is no TagDecl that defines the struct/union/class/enum.
2132   TagDecl* getDefinition() const;
2133
2134   void setDefinition(bool V) { IsDefinition = V; }
2135
2136   const char *getKindName() const {
2137     return TypeWithKeyword::getTagTypeKindName(getTagKind());
2138   }
2139
2140   TagKind getTagKind() const {
2141     return TagKind(TagDeclKind);
2142   }
2143
2144   void setTagKind(TagKind TK) { TagDeclKind = TK; }
2145
2146   bool isStruct() const { return getTagKind() == TTK_Struct; }
2147   bool isClass()  const { return getTagKind() == TTK_Class; }
2148   bool isUnion()  const { return getTagKind() == TTK_Union; }
2149   bool isEnum()   const { return getTagKind() == TTK_Enum; }
2150
2151   TypedefDecl *getTypedefForAnonDecl() const {
2152     return hasExtInfo() ? 0 : TypedefDeclOrQualifier.get<TypedefDecl*>();
2153   }
2154
2155   void setTypedefForAnonDecl(TypedefDecl *TDD);
2156
2157   NestedNameSpecifier *getQualifier() const {
2158     return hasExtInfo() ? getExtInfo()->NNS : 0;
2159   }
2160   SourceRange getQualifierRange() const {
2161     return hasExtInfo() ? getExtInfo()->NNSRange : SourceRange();
2162   }
2163   void setQualifierInfo(NestedNameSpecifier *Qualifier,
2164                         SourceRange QualifierRange);
2165
2166   unsigned getNumTemplateParameterLists() const {
2167     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2168   }
2169   TemplateParameterList *getTemplateParameterList(unsigned i) const {
2170     assert(i < getNumTemplateParameterLists());
2171     return getExtInfo()->TemplParamLists[i];
2172   }
2173   void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2174                                      TemplateParameterList **TPLists) {
2175     getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2176   }
2177
2178   // Implement isa/cast/dyncast/etc.
2179   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2180   static bool classof(const TagDecl *D) { return true; }
2181   static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2182
2183   static DeclContext *castToDeclContext(const TagDecl *D) {
2184     return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2185   }
2186   static TagDecl *castFromDeclContext(const DeclContext *DC) {
2187     return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2188   }
2189
2190   friend class ASTDeclReader;
2191   friend class ASTDeclWriter;
2192 };
2193
2194 /// EnumDecl - Represents an enum.  As an extension, we allow forward-declared
2195 /// enums.
2196 class EnumDecl : public TagDecl {
2197   /// IntegerType - This represent the integer type that the enum corresponds
2198   /// to for code generation purposes.  Note that the enumerator constants may
2199   /// have a different type than this does.
2200   ///
2201   /// If the underlying integer type was explicitly stated in the source
2202   /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2203   /// was automatically deduced somehow, and this is a Type*.
2204   ///
2205   /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2206   /// some cases it won't.
2207   ///
2208   /// The underlying type of an enumeration never has any qualifiers, so
2209   /// we can get away with just storing a raw Type*, and thus save an
2210   /// extra pointer when TypeSourceInfo is needed.
2211
2212   llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2213
2214   /// PromotionType - The integer type that values of this type should
2215   /// promote to.  In C, enumerators are generally of an integer type
2216   /// directly, but gcc-style large enumerators (and all enumerators
2217   /// in C++) are of the enum type instead.
2218   QualType PromotionType;
2219
2220   /// \brief If the enumeration was instantiated from an enumeration
2221   /// within a class or function template, this pointer refers to the
2222   /// enumeration declared within the template.
2223   EnumDecl *InstantiatedFrom;
2224
2225   // The number of positive and negative bits required by the
2226   // enumerators are stored in the SubclassBits field.
2227   enum {
2228     NumBitsWidth = 8,
2229     NumBitsMask = (1 << NumBitsWidth) - 1
2230   };
2231
2232   EnumDecl(DeclContext *DC, SourceLocation L,
2233            IdentifierInfo *Id, EnumDecl *PrevDecl, SourceLocation TKL,
2234            bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2235     : TagDecl(Enum, TTK_Enum, DC, L, Id, PrevDecl, TKL), InstantiatedFrom(0) {
2236       assert(Scoped || !ScopedUsingClassTag);
2237       IntegerType = (const Type*)0;
2238       NumNegativeBits = 0;
2239       NumPositiveBits = 0;
2240       IsScoped = Scoped;
2241       IsScopedUsingClassTag = ScopedUsingClassTag;
2242       IsFixed = Fixed;
2243     }
2244 public:
2245   EnumDecl *getCanonicalDecl() {
2246     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2247   }
2248   const EnumDecl *getCanonicalDecl() const {
2249     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2250   }
2251
2252   const EnumDecl *getPreviousDeclaration() const {
2253     return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
2254   }
2255   EnumDecl *getPreviousDeclaration() {
2256     return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
2257   }
2258
2259   static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2260                           SourceLocation L, IdentifierInfo *Id,
2261                           SourceLocation TKL, EnumDecl *PrevDecl,
2262                           bool IsScoped, bool IsScopedUsingClassTag,
2263                           bool IsFixed);
2264   static EnumDecl *Create(ASTContext &C, EmptyShell Empty);
2265
2266   /// completeDefinition - When created, the EnumDecl corresponds to a
2267   /// forward-declared enum. This method is used to mark the
2268   /// declaration as being defined; it's enumerators have already been
2269   /// added (via DeclContext::addDecl). NewType is the new underlying
2270   /// type of the enumeration type.
2271   void completeDefinition(QualType NewType,
2272                           QualType PromotionType,
2273                           unsigned NumPositiveBits,
2274                           unsigned NumNegativeBits);
2275
2276   // enumerator_iterator - Iterates through the enumerators of this
2277   // enumeration.
2278   typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2279
2280   enumerator_iterator enumerator_begin() const {
2281     const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
2282     if (!E)
2283       E = this;
2284     return enumerator_iterator(E->decls_begin());
2285   }
2286
2287   enumerator_iterator enumerator_end() const {
2288     const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
2289     if (!E)
2290       E = this;
2291     return enumerator_iterator(E->decls_end());
2292   }
2293
2294   /// getPromotionType - Return the integer type that enumerators
2295   /// should promote to.
2296   QualType getPromotionType() const { return PromotionType; }
2297
2298   /// \brief Set the promotion type.
2299   void setPromotionType(QualType T) { PromotionType = T; }
2300
2301   /// getIntegerType - Return the integer type this enum decl corresponds to.
2302   /// This returns a null qualtype for an enum forward definition.
2303   QualType getIntegerType() const {
2304     if (!IntegerType)
2305       return QualType();
2306     if (const Type* T = IntegerType.dyn_cast<const Type*>())
2307       return QualType(T, 0);
2308     return IntegerType.get<TypeSourceInfo*>()->getType();
2309   }
2310
2311   /// \brief Set the underlying integer type.
2312   void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2313
2314   /// \brief Set the underlying integer type source info.
2315   void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2316
2317   /// \brief Return the type source info for the underlying integer type,
2318   /// if no type source info exists, return 0.
2319   TypeSourceInfo* getIntegerTypeSourceInfo() const {
2320     return IntegerType.dyn_cast<TypeSourceInfo*>();
2321   }
2322
2323   /// \brief Returns the width in bits requred to store all the
2324   /// non-negative enumerators of this enum.
2325   unsigned getNumPositiveBits() const {
2326     return NumPositiveBits;
2327   }
2328   void setNumPositiveBits(unsigned Num) {
2329     NumPositiveBits = Num;
2330     assert(NumPositiveBits == Num && "can't store this bitcount");
2331   }
2332
2333   /// \brief Returns the width in bits requred to store all the
2334   /// negative enumerators of this enum.  These widths include
2335   /// the rightmost leading 1;  that is:
2336   /// 
2337   /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
2338   /// ------------------------     -------     -----------------
2339   ///                       -1     1111111                     1
2340   ///                      -10     1110110                     5
2341   ///                     -101     1001011                     8
2342   unsigned getNumNegativeBits() const {
2343     return NumNegativeBits;
2344   }
2345   void setNumNegativeBits(unsigned Num) {
2346     NumNegativeBits = Num;
2347   }
2348
2349   /// \brief Returns true if this is a C++0x scoped enumeration.
2350   bool isScoped() const {
2351     return IsScoped;
2352   }
2353
2354   /// \brief Returns true if this is a C++0x scoped enumeration.
2355   bool isScopedUsingClassTag() const {
2356     return IsScopedUsingClassTag;
2357   }
2358
2359   /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2360   /// type.
2361   bool isFixed() const {
2362     return IsFixed;
2363   }
2364
2365   /// \brief Returns true if this can be considered a complete type.
2366   bool isComplete() const {
2367     return isDefinition() || isFixed();
2368   }
2369
2370   /// \brief Returns the enumeration (declared within the template)
2371   /// from which this enumeration type was instantiated, or NULL if
2372   /// this enumeration was not instantiated from any template.
2373   EnumDecl *getInstantiatedFromMemberEnum() const {
2374     return InstantiatedFrom;
2375   }
2376
2377   void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; }
2378
2379   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2380   static bool classof(const EnumDecl *D) { return true; }
2381   static bool classofKind(Kind K) { return K == Enum; }
2382
2383   friend class ASTDeclReader;
2384 };
2385
2386
2387 /// RecordDecl - Represents a struct/union/class.  For example:
2388 ///   struct X;                  // Forward declaration, no "body".
2389 ///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
2390 /// This decl will be marked invalid if *any* members are invalid.
2391 ///
2392 class RecordDecl : public TagDecl {
2393   // FIXME: This can be packed into the bitfields in Decl.
2394   /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2395   /// array member (e.g. int X[]) or if this union contains a struct that does.
2396   /// If so, this cannot be contained in arrays or other structs as a member.
2397   bool HasFlexibleArrayMember : 1;
2398
2399   /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2400   /// or union.
2401   bool AnonymousStructOrUnion : 1;
2402
2403   /// HasObjectMember - This is true if this struct has at least one member
2404   /// containing an object.
2405   bool HasObjectMember : 1;
2406
2407   /// \brief Whether the field declarations of this record have been loaded
2408   /// from external storage. To avoid unnecessary deserialization of
2409   /// methods/nested types we allow deserialization of just the fields
2410   /// when needed.
2411   mutable bool LoadedFieldsFromExternalStorage : 1;
2412   friend class DeclContext;
2413
2414 protected:
2415   RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2416              SourceLocation L, IdentifierInfo *Id,
2417              RecordDecl *PrevDecl, SourceLocation TKL);
2418
2419 public:
2420   static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2421                             SourceLocation L, IdentifierInfo *Id,
2422                             SourceLocation TKL = SourceLocation(),
2423                             RecordDecl* PrevDecl = 0);
2424   static RecordDecl *Create(const ASTContext &C, EmptyShell Empty);
2425
2426   const RecordDecl *getPreviousDeclaration() const {
2427     return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
2428   }
2429   RecordDecl *getPreviousDeclaration() {
2430     return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
2431   }
2432
2433   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
2434   void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2435
2436   /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2437   /// or union. To be an anonymous struct or union, it must have been
2438   /// declared without a name and there must be no objects of this
2439   /// type declared, e.g.,
2440   /// @code
2441   ///   union { int i; float f; };
2442   /// @endcode
2443   /// is an anonymous union but neither of the following are:
2444   /// @code
2445   ///  union X { int i; float f; };
2446   ///  union { int i; float f; } obj;
2447   /// @endcode
2448   bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
2449   void setAnonymousStructOrUnion(bool Anon) {
2450     AnonymousStructOrUnion = Anon;
2451   }
2452
2453   bool hasObjectMember() const { return HasObjectMember; }
2454   void setHasObjectMember (bool val) { HasObjectMember = val; }
2455
2456   /// \brief Determines whether this declaration represents the
2457   /// injected class name.
2458   ///
2459   /// The injected class name in C++ is the name of the class that
2460   /// appears inside the class itself. For example:
2461   ///
2462   /// \code
2463   /// struct C {
2464   ///   // C is implicitly declared here as a synonym for the class name.
2465   /// };
2466   ///
2467   /// C::C c; // same as "C c;"
2468   /// \endcode
2469   bool isInjectedClassName() const;
2470
2471   /// getDefinition - Returns the RecordDecl that actually defines this
2472   ///  struct/union/class.  When determining whether or not a struct/union/class
2473   ///  is completely defined, one should use this method as opposed to
2474   ///  'isDefinition'.  'isDefinition' indicates whether or not a specific
2475   ///  RecordDecl is defining declaration, not whether or not the record
2476   ///  type is defined.  This method returns NULL if there is no RecordDecl
2477   ///  that defines the struct/union/tag.
2478   RecordDecl* getDefinition() const {
2479     return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2480   }
2481
2482   // Iterator access to field members. The field iterator only visits
2483   // the non-static data members of this class, ignoring any static
2484   // data members, functions, constructors, destructors, etc.
2485   typedef specific_decl_iterator<FieldDecl> field_iterator;
2486
2487   field_iterator field_begin() const;
2488
2489   field_iterator field_end() const {
2490     return field_iterator(decl_iterator());
2491   }
2492
2493   // field_empty - Whether there are any fields (non-static data
2494   // members) in this record.
2495   bool field_empty() const {
2496     return field_begin() == field_end();
2497   }
2498
2499   /// completeDefinition - Notes that the definition of this type is
2500   /// now complete.
2501   virtual void completeDefinition();
2502
2503   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2504   static bool classof(const RecordDecl *D) { return true; }
2505   static bool classofKind(Kind K) {
2506     return K >= firstRecord && K <= lastRecord;
2507   }
2508
2509 private:
2510   /// \brief Deserialize just the fields.
2511   void LoadFieldsFromExternalStorage() const;
2512 };
2513
2514 class FileScopeAsmDecl : public Decl {
2515   StringLiteral *AsmString;
2516   FileScopeAsmDecl(DeclContext *DC, SourceLocation L, StringLiteral *asmstring)
2517     : Decl(FileScopeAsm, DC, L), AsmString(asmstring) {}
2518 public:
2519   static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
2520                                   SourceLocation L, StringLiteral *Str);
2521
2522   const StringLiteral *getAsmString() const { return AsmString; }
2523   StringLiteral *getAsmString() { return AsmString; }
2524   void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
2525
2526   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2527   static bool classof(const FileScopeAsmDecl *D) { return true; }
2528   static bool classofKind(Kind K) { return K == FileScopeAsm; }
2529 };
2530
2531 /// BlockDecl - This represents a block literal declaration, which is like an
2532 /// unnamed FunctionDecl.  For example:
2533 /// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
2534 ///
2535 class BlockDecl : public Decl, public DeclContext {
2536 public:
2537   /// A class which contains all the information about a particular
2538   /// captured value.
2539   class Capture {
2540     enum {
2541       flag_isByRef = 0x1,
2542       flag_isNested = 0x2
2543     };
2544
2545     /// The variable being captured.
2546     llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
2547
2548     /// The copy expression, expressed in terms of a DeclRef (or
2549     /// BlockDeclRef) to the captured variable.  Only required if the
2550     /// variable has a C++ class type.
2551     Expr *CopyExpr;
2552
2553   public:
2554     Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
2555       : VariableAndFlags(variable,
2556                   (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
2557         CopyExpr(copy) {}
2558
2559     /// The variable being captured.
2560     VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
2561
2562     /// Whether this is a "by ref" capture, i.e. a capture of a __block
2563     /// variable.
2564     bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
2565
2566     /// Whether this is a nested capture, i.e. the variable captured
2567     /// is not from outside the immediately enclosing function/block.
2568     bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
2569
2570     bool hasCopyExpr() const { return CopyExpr != 0; }
2571     Expr *getCopyExpr() const { return CopyExpr; }
2572     void setCopyExpr(Expr *e) { CopyExpr = e; }
2573   };
2574
2575 private:
2576   // FIXME: This can be packed into the bitfields in Decl.
2577   bool IsVariadic : 1;
2578   bool CapturesCXXThis : 1;
2579   /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
2580   /// parameters of this function.  This is null if a prototype or if there are
2581   /// no formals.
2582   ParmVarDecl **ParamInfo;
2583   unsigned NumParams;
2584
2585   Stmt *Body;
2586   TypeSourceInfo *SignatureAsWritten;
2587
2588   Capture *Captures;
2589   unsigned NumCaptures;
2590
2591 protected:
2592   BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
2593     : Decl(Block, DC, CaretLoc), DeclContext(Block),
2594       IsVariadic(false), CapturesCXXThis(false),
2595       ParamInfo(0), NumParams(0), Body(0),
2596       SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
2597
2598 public:
2599   static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
2600
2601   SourceLocation getCaretLocation() const { return getLocation(); }
2602
2603   bool isVariadic() const { return IsVariadic; }
2604   void setIsVariadic(bool value) { IsVariadic = value; }
2605
2606   CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
2607   Stmt *getBody() const { return (Stmt*) Body; }
2608   void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
2609
2610   void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
2611   TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
2612
2613   // Iterator access to formal parameters.
2614   unsigned param_size() const { return getNumParams(); }
2615   typedef ParmVarDecl **param_iterator;
2616   typedef ParmVarDecl * const *param_const_iterator;
2617
2618   bool param_empty() const { return NumParams == 0; }
2619   param_iterator param_begin()  { return ParamInfo; }
2620   param_iterator param_end()   { return ParamInfo+param_size(); }
2621
2622   param_const_iterator param_begin() const { return ParamInfo; }
2623   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
2624
2625   unsigned getNumParams() const { return NumParams; }
2626   const ParmVarDecl *getParamDecl(unsigned i) const {
2627     assert(i < getNumParams() && "Illegal param #");
2628     return ParamInfo[i];
2629   }
2630   ParmVarDecl *getParamDecl(unsigned i) {
2631     assert(i < getNumParams() && "Illegal param #");
2632     return ParamInfo[i];
2633   }
2634   void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams);
2635
2636   /// hasCaptures - True if this block (or its nested blocks) captures
2637   /// anything of local storage from its enclosing scopes.
2638   bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
2639
2640   /// getNumCaptures - Returns the number of captured variables.
2641   /// Does not include an entry for 'this'.
2642   unsigned getNumCaptures() const { return NumCaptures; }
2643
2644   typedef const Capture *capture_iterator;
2645   typedef const Capture *capture_const_iterator;
2646   capture_iterator capture_begin() { return Captures; }
2647   capture_iterator capture_end() { return Captures + NumCaptures; }
2648   capture_const_iterator capture_begin() const { return Captures; }
2649   capture_const_iterator capture_end() const { return Captures + NumCaptures; }
2650
2651   bool capturesCXXThis() const { return CapturesCXXThis; }
2652
2653   void setCaptures(ASTContext &Context,
2654                    const Capture *begin,
2655                    const Capture *end,
2656                    bool capturesCXXThis);
2657
2658   virtual SourceRange getSourceRange() const;
2659   
2660   // Implement isa/cast/dyncast/etc.
2661   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2662   static bool classof(const BlockDecl *D) { return true; }
2663   static bool classofKind(Kind K) { return K == Block; }
2664   static DeclContext *castToDeclContext(const BlockDecl *D) {
2665     return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
2666   }
2667   static BlockDecl *castFromDeclContext(const DeclContext *DC) {
2668     return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
2669   }
2670 };
2671
2672 /// Insertion operator for diagnostics.  This allows sending NamedDecl's
2673 /// into a diagnostic with <<.
2674 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
2675                                            NamedDecl* ND) {
2676   DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), Diagnostic::ak_nameddecl);
2677   return DB;
2678 }
2679
2680 template<typename decl_type>
2681 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
2682   // Note: This routine is implemented here because we need both NamedDecl
2683   // and Redeclarable to be defined.
2684
2685   decl_type *First;
2686   
2687   if (PrevDecl) {
2688     // Point to previous. Make sure that this is actually the most recent
2689     // redeclaration, or we can build invalid chains. If the most recent
2690     // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
2691     RedeclLink = PreviousDeclLink(llvm::cast<decl_type>(
2692                                                         PrevDecl->getMostRecentDeclaration()));
2693     First = PrevDecl->getFirstDeclaration();
2694     assert(First->RedeclLink.NextIsLatest() && "Expected first");
2695   } else {
2696     // Make this first.
2697     First = static_cast<decl_type*>(this);
2698   }
2699   
2700   // First one will point to this one as latest.
2701   First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
2702   if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
2703     ND->ClearLinkageCache();
2704 }
2705
2706 }  // end namespace clang
2707
2708 #endif