Decl.h revision 0cef483f3b9d6a7f9fdbc5910d0a3ed64130e8e1
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
24namespace clang {
25class CXXTemporary;
26class Expr;
27class FunctionTemplateDecl;
28class Stmt;
29class CompoundStmt;
30class StringLiteral;
31class TemplateArgumentList;
32class MemberSpecializationInfo;
33class FunctionTemplateSpecializationInfo;
34class TypeLoc;
35
36/// \brief A container of type source information.
37///
38/// A client can read the relevant info using TypeLoc wrappers, e.g:
39/// @code
40/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
41/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
42///   PL->getStarLoc().print(OS, SrcMgr);
43/// @endcode
44///
45class TypeSourceInfo {
46  QualType Ty;
47  // Contains a memory block after the class, used for type source information,
48  // allocated by ASTContext.
49  friend class ASTContext;
50  TypeSourceInfo(QualType ty) : Ty(ty) { }
51public:
52  /// \brief Return the type wrapped by this type source info.
53  QualType getType() const { return Ty; }
54
55  /// \brief Return the TypeLoc wrapper for the type source info.
56  TypeLoc getTypeLoc() const;
57};
58
59/// TranslationUnitDecl - The top declaration context.
60class TranslationUnitDecl : public Decl, public DeclContext {
61  ASTContext &Ctx;
62
63  /// The (most recently entered) anonymous namespace for this
64  /// translation unit, if one has been created.
65  NamespaceDecl *AnonymousNamespace;
66
67  explicit TranslationUnitDecl(ASTContext &ctx)
68    : Decl(TranslationUnit, 0, SourceLocation()),
69      DeclContext(TranslationUnit),
70      Ctx(ctx), AnonymousNamespace(0) {}
71public:
72  ASTContext &getASTContext() const { return Ctx; }
73
74  NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
75  void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
76
77  static TranslationUnitDecl *Create(ASTContext &C);
78  // Implement isa/cast/dyncast/etc.
79  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
80  static bool classof(const TranslationUnitDecl *D) { return true; }
81  static bool classofKind(Kind K) { return K == TranslationUnit; }
82  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
83    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
84  }
85  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
86    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
87  }
88};
89
90/// NamedDecl - This represents a decl with a name.  Many decls have names such
91/// as ObjCMethodDecl, but not @class, etc.
92class NamedDecl : public Decl {
93  /// Name - The name of this declaration, which is typically a normal
94  /// identifier but may also be a special kind of name (C++
95  /// constructor, Objective-C selector, etc.)
96  DeclarationName Name;
97
98protected:
99  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
100    : Decl(DK, DC, L), Name(N) { }
101
102public:
103  /// getIdentifier - Get the identifier that names this declaration,
104  /// if there is one. This will return NULL if this declaration has
105  /// no name (e.g., for an unnamed class) or if the name is a special
106  /// name (C++ constructor, Objective-C selector, etc.).
107  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
108
109  /// getName - Get the name of identifier for this declaration as a StringRef.
110  /// This requires that the declaration have a name and that it be a simple
111  /// identifier.
112  llvm::StringRef getName() const {
113    assert(Name.isIdentifier() && "Name is not a simple identifier");
114    return getIdentifier() ? getIdentifier()->getName() : "";
115  }
116
117  /// getNameAsCString - Get the name of identifier for this declaration as a
118  /// C string (const char*).  This requires that the declaration have a name
119  /// and that it be a simple identifier.
120  //
121  // FIXME: Deprecated, move clients to getName().
122  const char *getNameAsCString() const {
123    assert(Name.isIdentifier() && "Name is not a simple identifier");
124    return getIdentifier() ? getIdentifier()->getNameStart() : "";
125  }
126
127  /// getNameAsString - Get a human-readable name for the declaration, even if
128  /// it is one of the special kinds of names (C++ constructor, Objective-C
129  /// selector, etc).  Creating this name requires expensive string
130  /// manipulation, so it should be called only when performance doesn't matter.
131  /// For simple declarations, getNameAsCString() should suffice.
132  //
133  // FIXME: This function should be renamed to indicate that it is not just an
134  // alternate form of getName(), and clients should move as appropriate.
135  //
136  // FIXME: Deprecated, move clients to getName().
137  std::string getNameAsString() const { return Name.getAsString(); }
138
139  /// getDeclName - Get the actual, stored name of the declaration,
140  /// which may be a special name.
141  DeclarationName getDeclName() const { return Name; }
142
143  /// \brief Set the name of this declaration.
144  void setDeclName(DeclarationName N) { Name = N; }
145
146  /// getQualifiedNameAsString - Returns human-readable qualified name for
147  /// declaration, like A::B::i, for i being member of namespace A::B.
148  /// If declaration is not member of context which can be named (record,
149  /// namespace), it will return same result as getNameAsString().
150  /// Creating this name is expensive, so it should be called only when
151  /// performance doesn't matter.
152  std::string getQualifiedNameAsString() const;
153  std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
154
155  /// getNameForDiagnostic - Appends a human-readable name for this
156  /// declaration into the given string.
157  ///
158  /// This is the method invoked by Sema when displaying a NamedDecl
159  /// in a diagnostic.  It does not necessarily produce the same
160  /// result as getNameAsString(); for example, class template
161  /// specializations are printed with their template arguments.
162  ///
163  /// TODO: use an API that doesn't require so many temporary strings
164  virtual void getNameForDiagnostic(std::string &S,
165                                    const PrintingPolicy &Policy,
166                                    bool Qualified) const {
167    if (Qualified)
168      S += getQualifiedNameAsString(Policy);
169    else
170      S += getNameAsString();
171  }
172
173  /// declarationReplaces - Determine whether this declaration, if
174  /// known to be well-formed within its context, will replace the
175  /// declaration OldD if introduced into scope. A declaration will
176  /// replace another declaration if, for example, it is a
177  /// redeclaration of the same variable or function, but not if it is
178  /// a declaration of a different kind (function vs. class) or an
179  /// overloaded function.
180  bool declarationReplaces(NamedDecl *OldD) const;
181
182  /// \brief Determine whether this declaration has linkage.
183  bool hasLinkage() const;
184
185  /// \brief Determine whether this declaration is a C++ class member.
186  bool isCXXClassMember() const {
187    const DeclContext *DC = getDeclContext();
188
189    // C++0x [class.mem]p1:
190    //   The enumerators of an unscoped enumeration defined in
191    //   the class are members of the class.
192    // FIXME: support C++0x scoped enumerations.
193    if (isa<EnumDecl>(DC))
194      DC = DC->getParent();
195
196    return DC->isRecord();
197  }
198
199  /// \brief Determine what kind of linkage this entity has.
200  Linkage getLinkage() const;
201
202  /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
203  /// the underlying named decl.
204  NamedDecl *getUnderlyingDecl();
205  const NamedDecl *getUnderlyingDecl() const {
206    return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
207  }
208
209  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
210  static bool classof(const NamedDecl *D) { return true; }
211  static bool classofKind(Kind K) { return K >= NamedFirst && K <= NamedLast; }
212};
213
214/// NamespaceDecl - Represent a C++ namespace.
215class NamespaceDecl : public NamedDecl, public DeclContext {
216  SourceLocation LBracLoc, RBracLoc;
217
218  // For extended namespace definitions:
219  //
220  // namespace A { int x; }
221  // namespace A { int y; }
222  //
223  // there will be one NamespaceDecl for each declaration.
224  // NextNamespace points to the next extended declaration.
225  // OrigNamespace points to the original namespace declaration.
226  // OrigNamespace of the first namespace decl points to itself.
227  NamespaceDecl *OrigNamespace, *NextNamespace;
228
229  // The (most recently entered) anonymous namespace inside this
230  // namespace.
231  NamespaceDecl *AnonymousNamespace;
232
233  NamespaceDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id)
234    : NamedDecl(Namespace, DC, L, Id), DeclContext(Namespace) {
235    OrigNamespace = this;
236    NextNamespace = 0;
237    AnonymousNamespace = 0;
238  }
239public:
240  static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
241                               SourceLocation L, IdentifierInfo *Id);
242
243  virtual void Destroy(ASTContext& C);
244
245  // \brief Returns true if this is an anonymous namespace declaration.
246  //
247  // For example:
248  //   namespace {
249  //     ...
250  //   };
251  // q.v. C++ [namespace.unnamed]
252  bool isAnonymousNamespace() const {
253    return !getIdentifier();
254  }
255
256  NamespaceDecl *getNextNamespace() { return NextNamespace; }
257  const NamespaceDecl *getNextNamespace() const { return NextNamespace; }
258  void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; }
259
260  NamespaceDecl *getOriginalNamespace() const {
261    return OrigNamespace;
262  }
263  void setOriginalNamespace(NamespaceDecl *ND) { OrigNamespace = ND; }
264
265  NamespaceDecl *getAnonymousNamespace() const {
266    return AnonymousNamespace;
267  }
268
269  void setAnonymousNamespace(NamespaceDecl *D) {
270    assert(!D || D->isAnonymousNamespace());
271    assert(!D || D->getParent() == this);
272    AnonymousNamespace = D;
273  }
274
275  virtual NamespaceDecl *getCanonicalDecl() { return OrigNamespace; }
276  const NamespaceDecl *getCanonicalDecl() const { return OrigNamespace; }
277
278  virtual SourceRange getSourceRange() const {
279    return SourceRange(getLocation(), RBracLoc);
280  }
281
282  SourceLocation getLBracLoc() const { return LBracLoc; }
283  SourceLocation getRBracLoc() const { return RBracLoc; }
284  void setLBracLoc(SourceLocation LBrace) { LBracLoc = LBrace; }
285  void setRBracLoc(SourceLocation RBrace) { RBracLoc = RBrace; }
286
287  // Implement isa/cast/dyncast/etc.
288  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
289  static bool classof(const NamespaceDecl *D) { return true; }
290  static bool classofKind(Kind K) { return K == Namespace; }
291  static DeclContext *castToDeclContext(const NamespaceDecl *D) {
292    return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
293  }
294  static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
295    return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
296  }
297};
298
299/// ValueDecl - Represent the declaration of a variable (in which case it is
300/// an lvalue) a function (in which case it is a function designator) or
301/// an enum constant.
302class ValueDecl : public NamedDecl {
303  QualType DeclType;
304
305protected:
306  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
307            DeclarationName N, QualType T)
308    : NamedDecl(DK, DC, L, N), DeclType(T) {}
309public:
310  QualType getType() const { return DeclType; }
311  void setType(QualType newType) { DeclType = newType; }
312
313  // Implement isa/cast/dyncast/etc.
314  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
315  static bool classof(const ValueDecl *D) { return true; }
316  static bool classofKind(Kind K) { return K >= ValueFirst && K <= ValueLast; }
317};
318
319/// \brief Represents a ValueDecl that came out of a declarator.
320/// Contains type source information through TypeSourceInfo.
321class DeclaratorDecl : public ValueDecl {
322  TypeSourceInfo *DeclInfo;
323
324protected:
325  DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
326                 DeclarationName N, QualType T, TypeSourceInfo *TInfo)
327    : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo) {}
328
329public:
330  TypeSourceInfo *getTypeSourceInfo() const { return DeclInfo; }
331  void setTypeSourceInfo(TypeSourceInfo *TInfo) { DeclInfo = TInfo; }
332
333  SourceLocation getTypeSpecStartLoc() const;
334
335  // Implement isa/cast/dyncast/etc.
336  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
337  static bool classof(const DeclaratorDecl *D) { return true; }
338  static bool classofKind(Kind K) {
339    return K >= DeclaratorFirst && K <= DeclaratorLast;
340  }
341};
342
343/// \brief Structure used to store a statement, the constant value to
344/// which it was evaluated (if any), and whether or not the statement
345/// is an integral constant expression (if known).
346struct EvaluatedStmt {
347  EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
348                    CheckingICE(false), IsICE(false) { }
349
350  /// \brief Whether this statement was already evaluated.
351  bool WasEvaluated : 1;
352
353  /// \brief Whether this statement is being evaluated.
354  bool IsEvaluating : 1;
355
356  /// \brief Whether we already checked whether this statement was an
357  /// integral constant expression.
358  bool CheckedICE : 1;
359
360  /// \brief Whether we are checking whether this statement is an
361  /// integral constant expression.
362  bool CheckingICE : 1;
363
364  /// \brief Whether this statement is an integral constant
365  /// expression. Only valid if CheckedICE is true.
366  bool IsICE : 1;
367
368  Stmt *Value;
369  APValue Evaluated;
370};
371
372// \brief Describes the kind of template specialization that a
373// particular template specialization declaration represents.
374enum TemplateSpecializationKind {
375  /// This template specialization was formed from a template-id but
376  /// has not yet been declared, defined, or instantiated.
377  TSK_Undeclared = 0,
378  /// This template specialization was implicitly instantiated from a
379  /// template. (C++ [temp.inst]).
380  TSK_ImplicitInstantiation,
381  /// This template specialization was declared or defined by an
382  /// explicit specialization (C++ [temp.expl.spec]) or partial
383  /// specialization (C++ [temp.class.spec]).
384  TSK_ExplicitSpecialization,
385  /// This template specialization was instantiated from a template
386  /// due to an explicit instantiation declaration request
387  /// (C++0x [temp.explicit]).
388  TSK_ExplicitInstantiationDeclaration,
389  /// This template specialization was instantiated from a template
390  /// due to an explicit instantiation definition request
391  /// (C++ [temp.explicit]).
392  TSK_ExplicitInstantiationDefinition
393};
394
395/// VarDecl - An instance of this class is created to represent a variable
396/// declaration or definition.
397class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
398public:
399  enum StorageClass {
400    None, Auto, Register, Extern, Static, PrivateExtern
401  };
402
403  /// getStorageClassSpecifierString - Return the string used to
404  /// specify the storage class \arg SC.
405  ///
406  /// It is illegal to call this function with SC == None.
407  static const char *getStorageClassSpecifierString(StorageClass SC);
408
409protected:
410  /// \brief Placeholder type used in Init to denote an unparsed C++ default
411  /// argument.
412  struct UnparsedDefaultArgument;
413
414  /// \brief Placeholder type used in Init to denote an uninstantiated C++
415  /// default argument.
416  struct UninstantiatedDefaultArgument;
417
418  typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
419                              UnparsedDefaultArgument *,
420                              UninstantiatedDefaultArgument *> InitType;
421
422  /// \brief The initializer for this variable or, for a ParmVarDecl, the
423  /// C++ default argument.
424  mutable InitType Init;
425
426private:
427  // FIXME: This can be packed into the bitfields in Decl.
428  unsigned SClass : 3;
429  bool ThreadSpecified : 1;
430  bool HasCXXDirectInit : 1;
431
432  /// DeclaredInCondition - Whether this variable was declared in a
433  /// condition, e.g., if (int x = foo()) { ... }.
434  bool DeclaredInCondition : 1;
435
436  friend class StmtIteratorBase;
437protected:
438  VarDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
439          QualType T, TypeSourceInfo *TInfo, StorageClass SC)
440    : DeclaratorDecl(DK, DC, L, Id, T, TInfo), Init(),
441      ThreadSpecified(false), HasCXXDirectInit(false),
442      DeclaredInCondition(false) {
443    SClass = SC;
444  }
445
446  typedef Redeclarable<VarDecl> redeclarable_base;
447  virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
448
449public:
450  typedef redeclarable_base::redecl_iterator redecl_iterator;
451  redecl_iterator redecls_begin() const {
452    return redeclarable_base::redecls_begin();
453  }
454  redecl_iterator redecls_end() const {
455    return redeclarable_base::redecls_end();
456  }
457
458  static VarDecl *Create(ASTContext &C, DeclContext *DC,
459                         SourceLocation L, IdentifierInfo *Id,
460                         QualType T, TypeSourceInfo *TInfo, StorageClass S);
461
462  virtual void Destroy(ASTContext& C);
463  virtual ~VarDecl();
464
465  virtual SourceRange getSourceRange() const;
466
467  StorageClass getStorageClass() const { return (StorageClass)SClass; }
468  void setStorageClass(StorageClass SC) { SClass = SC; }
469
470  void setThreadSpecified(bool T) { ThreadSpecified = T; }
471  bool isThreadSpecified() const {
472    return ThreadSpecified;
473  }
474
475  /// hasLocalStorage - Returns true if a variable with function scope
476  ///  is a non-static local variable.
477  bool hasLocalStorage() const {
478    if (getStorageClass() == None)
479      return !isFileVarDecl();
480
481    // Return true for:  Auto, Register.
482    // Return false for: Extern, Static, PrivateExtern.
483
484    return getStorageClass() <= Register;
485  }
486
487  /// hasExternStorage - Returns true if a variable has extern or
488  /// __private_extern__ storage.
489  bool hasExternalStorage() const {
490    return getStorageClass() == Extern || getStorageClass() == PrivateExtern;
491  }
492
493  /// hasGlobalStorage - Returns true for all variables that do not
494  ///  have local storage.  This includs all global variables as well
495  ///  as static variables declared within a function.
496  bool hasGlobalStorage() const { return !hasLocalStorage(); }
497
498  /// \brief Determines whether this variable is a variable with
499  /// external, C linkage.
500  bool isExternC() const;
501
502  /// isBlockVarDecl - Returns true for local variable declarations.  Note that
503  /// this includes static variables inside of functions.
504  ///
505  ///   void foo() { int x; static int y; extern int z; }
506  ///
507  bool isBlockVarDecl() const {
508    if (getKind() != Decl::Var)
509      return false;
510    if (const DeclContext *DC = getDeclContext())
511      return DC->getLookupContext()->isFunctionOrMethod();
512    return false;
513  }
514
515  /// \brief Determines whether this is a static data member.
516  ///
517  /// This will only be true in C++, and applies to, e.g., the
518  /// variable 'x' in:
519  /// \code
520  /// struct S {
521  ///   static int x;
522  /// };
523  /// \endcode
524  bool isStaticDataMember() const {
525    // If it wasn't static, it would be a FieldDecl.
526    return getDeclContext()->isRecord();
527  }
528
529  virtual VarDecl *getCanonicalDecl();
530  const VarDecl *getCanonicalDecl() const {
531    return const_cast<VarDecl*>(this)->getCanonicalDecl();
532  }
533
534  enum DefinitionKind {
535    DeclarationOnly,      ///< This declaration is only a declaration.
536    TentativeDefinition,  ///< This declaration is a tentative definition.
537    Definition            ///< This declaration is definitely a definition.
538  };
539
540  /// \brief Check whether this declaration is a definition. If this could be
541  /// a tentative definition (in C), don't check whether there's an overriding
542  /// definition.
543  DefinitionKind isThisDeclarationADefinition() const;
544
545  /// \brief Get the tentative definition that acts as the real definition in
546  /// a TU. Returns null if there is a proper definition available.
547  VarDecl *getActingDefinition();
548  const VarDecl *getActingDefinition() const {
549    return const_cast<VarDecl*>(this)->getActingDefinition();
550  }
551
552  /// \brief Determine whether this is a tentative definition of a
553  /// variable in C.
554  bool isTentativeDefinitionNow() const;
555
556  /// \brief Get the real (not just tentative) definition for this declaration.
557  VarDecl *getDefinition();
558  const VarDecl *getDefinition() const {
559    return const_cast<VarDecl*>(this)->getDefinition();
560  }
561
562  /// \brief Determine whether this is or was instantiated from an out-of-line
563  /// definition of a static data member.
564  virtual bool isOutOfLine() const;
565
566  /// \brief If this is a static data member, find its out-of-line definition.
567  VarDecl *getOutOfLineDefinition();
568
569  /// isFileVarDecl - Returns true for file scoped variable declaration.
570  bool isFileVarDecl() const {
571    if (getKind() != Decl::Var)
572      return false;
573    if (const DeclContext *Ctx = getDeclContext()) {
574      Ctx = Ctx->getLookupContext();
575      if (isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx) )
576        return true;
577    }
578    if (isStaticDataMember())
579      return true;
580
581    return false;
582  }
583
584  /// getAnyInitializer - Get the initializer for this variable, no matter which
585  /// declaration it is attached to.
586  const Expr *getAnyInitializer() const {
587    const VarDecl *D;
588    return getAnyInitializer(D);
589  }
590
591  /// getAnyInitializer - Get the initializer for this variable, no matter which
592  /// declaration it is attached to. Also get that declaration.
593  const Expr *getAnyInitializer(const VarDecl *&D) const;
594
595  bool hasInit() const {
596    return !Init.isNull();
597  }
598  const Expr *getInit() const {
599    if (Init.isNull())
600      return 0;
601
602    const Stmt *S = Init.dyn_cast<Stmt *>();
603    if (!S) {
604      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
605        S = ES->Value;
606    }
607    return (const Expr*) S;
608  }
609  Expr *getInit() {
610    if (Init.isNull())
611      return 0;
612
613    Stmt *S = Init.dyn_cast<Stmt *>();
614    if (!S) {
615      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
616        S = ES->Value;
617    }
618
619    return (Expr*) S;
620  }
621
622  /// \brief Retrieve the address of the initializer expression.
623  Stmt **getInitAddress() {
624    if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
625      return &ES->Value;
626
627    // This union hack tip-toes around strict-aliasing rules.
628    union {
629      InitType *InitPtr;
630      Stmt **StmtPtr;
631    };
632
633    InitPtr = &Init;
634    return StmtPtr;
635  }
636
637  void setInit(Expr *I);
638
639  EvaluatedStmt *EnsureEvaluatedStmt() const {
640    EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
641    if (!Eval) {
642      Stmt *S = Init.get<Stmt *>();
643      Eval = new (getASTContext()) EvaluatedStmt;
644      Eval->Value = S;
645      Init = Eval;
646    }
647    return Eval;
648  }
649
650  /// \brief Check whether we are in the process of checking whether the
651  /// initializer can be evaluated.
652  bool isEvaluatingValue() const {
653    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
654      return Eval->IsEvaluating;
655
656    return false;
657  }
658
659  /// \brief Note that we now are checking whether the initializer can be
660  /// evaluated.
661  void setEvaluatingValue() const {
662    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
663    Eval->IsEvaluating = true;
664  }
665
666  /// \brief Note that constant evaluation has computed the given
667  /// value for this variable's initializer.
668  void setEvaluatedValue(const APValue &Value) const {
669    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
670    Eval->IsEvaluating = false;
671    Eval->WasEvaluated = true;
672    Eval->Evaluated = Value;
673  }
674
675  /// \brief Return the already-evaluated value of this variable's
676  /// initializer, or NULL if the value is not yet known. Returns pointer
677  /// to untyped APValue if the value could not be evaluated.
678  APValue *getEvaluatedValue() const {
679    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
680      if (Eval->WasEvaluated)
681        return &Eval->Evaluated;
682
683    return 0;
684  }
685
686  /// \brief Determines whether it is already known whether the
687  /// initializer is an integral constant expression or not.
688  bool isInitKnownICE() const {
689    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
690      return Eval->CheckedICE;
691
692    return false;
693  }
694
695  /// \brief Determines whether the initializer is an integral
696  /// constant expression.
697  ///
698  /// \pre isInitKnownICE()
699  bool isInitICE() const {
700    assert(isInitKnownICE() &&
701           "Check whether we already know that the initializer is an ICE");
702    return Init.get<EvaluatedStmt *>()->IsICE;
703  }
704
705  /// \brief Check whether we are in the process of checking the initializer
706  /// is an integral constant expression.
707  bool isCheckingICE() const {
708    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
709      return Eval->CheckingICE;
710
711    return false;
712  }
713
714  /// \brief Note that we now are checking whether the initializer is an
715  /// integral constant expression.
716  void setCheckingICE() const {
717    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
718    Eval->CheckingICE = true;
719  }
720
721  /// \brief Note that we now know whether the initializer is an
722  /// integral constant expression.
723  void setInitKnownICE(bool IsICE) const {
724    EvaluatedStmt *Eval = EnsureEvaluatedStmt();
725    Eval->CheckingICE = false;
726    Eval->CheckedICE = true;
727    Eval->IsICE = IsICE;
728  }
729
730  void setCXXDirectInitializer(bool T) { HasCXXDirectInit = T; }
731
732  /// hasCXXDirectInitializer - If true, the initializer was a direct
733  /// initializer, e.g: "int x(1);". The Init expression will be the expression
734  /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
735  /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
736  /// by checking hasCXXDirectInitializer.
737  ///
738  bool hasCXXDirectInitializer() const {
739    return HasCXXDirectInit;
740  }
741
742  /// isDeclaredInCondition - Whether this variable was declared as
743  /// part of a condition in an if/switch/while statement, e.g.,
744  /// @code
745  /// if (int x = foo()) { ... }
746  /// @endcode
747  bool isDeclaredInCondition() const {
748    return DeclaredInCondition;
749  }
750  void setDeclaredInCondition(bool InCondition) {
751    DeclaredInCondition = InCondition;
752  }
753
754  /// \brief If this variable is an instantiated static data member of a
755  /// class template specialization, returns the templated static data member
756  /// from which it was instantiated.
757  VarDecl *getInstantiatedFromStaticDataMember() const;
758
759  /// \brief If this variable is a static data member, determine what kind of
760  /// template specialization or instantiation this is.
761  TemplateSpecializationKind getTemplateSpecializationKind() const;
762
763  /// \brief If this variable is an instantiation of a static data member of a
764  /// class template specialization, retrieves the member specialization
765  /// information.
766  MemberSpecializationInfo *getMemberSpecializationInfo() const;
767
768  /// \brief For a static data member that was instantiated from a static
769  /// data member of a class template, set the template specialiation kind.
770  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
771                        SourceLocation PointOfInstantiation = SourceLocation());
772
773  // Implement isa/cast/dyncast/etc.
774  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
775  static bool classof(const VarDecl *D) { return true; }
776  static bool classofKind(Kind K) { return K >= VarFirst && K <= VarLast; }
777};
778
779class ImplicitParamDecl : public VarDecl {
780protected:
781  ImplicitParamDecl(Kind DK, DeclContext *DC, SourceLocation L,
782                    IdentifierInfo *Id, QualType Tw)
783    : VarDecl(DK, DC, L, Id, Tw, /*TInfo=*/0, VarDecl::None) {}
784public:
785  static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
786                                   SourceLocation L, IdentifierInfo *Id,
787                                   QualType T);
788  // Implement isa/cast/dyncast/etc.
789  static bool classof(const ImplicitParamDecl *D) { return true; }
790  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
791  static bool classofKind(Kind K) { return K == ImplicitParam; }
792};
793
794/// ParmVarDecl - Represent a parameter to a function.
795class ParmVarDecl : public VarDecl {
796  // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
797  /// FIXME: Also can be paced into the bitfields in Decl.
798  /// in, inout, etc.
799  unsigned objcDeclQualifier : 6;
800
801protected:
802  ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation L,
803              IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
804              StorageClass S, Expr *DefArg)
805  : VarDecl(DK, DC, L, Id, T, TInfo, S), objcDeclQualifier(OBJC_TQ_None) {
806    setDefaultArg(DefArg);
807  }
808
809public:
810  static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
811                             SourceLocation L,IdentifierInfo *Id,
812                             QualType T, TypeSourceInfo *TInfo,
813                             StorageClass S, Expr *DefArg);
814
815  ObjCDeclQualifier getObjCDeclQualifier() const {
816    return ObjCDeclQualifier(objcDeclQualifier);
817  }
818  void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
819    objcDeclQualifier = QTVal;
820  }
821
822  Expr *getDefaultArg();
823  const Expr *getDefaultArg() const {
824    return const_cast<ParmVarDecl *>(this)->getDefaultArg();
825  }
826
827  void setDefaultArg(Expr *defarg) {
828    Init = reinterpret_cast<Stmt *>(defarg);
829  }
830
831  unsigned getNumDefaultArgTemporaries() const;
832  CXXTemporary *getDefaultArgTemporary(unsigned i);
833  const CXXTemporary *getDefaultArgTemporary(unsigned i) const {
834    return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i);
835  }
836
837  /// \brief Retrieve the source range that covers the entire default
838  /// argument.
839  SourceRange getDefaultArgRange() const;
840  void setUninstantiatedDefaultArg(Expr *arg) {
841    Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
842  }
843  Expr *getUninstantiatedDefaultArg() {
844    return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
845  }
846  const Expr *getUninstantiatedDefaultArg() const {
847    return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
848  }
849
850  /// hasDefaultArg - Determines whether this parameter has a default argument,
851  /// either parsed or not.
852  bool hasDefaultArg() const {
853    return getInit() || hasUnparsedDefaultArg() ||
854      hasUninstantiatedDefaultArg();
855  }
856
857  /// hasUnparsedDefaultArg - Determines whether this parameter has a
858  /// default argument that has not yet been parsed. This will occur
859  /// during the processing of a C++ class whose member functions have
860  /// default arguments, e.g.,
861  /// @code
862  ///   class X {
863  ///   public:
864  ///     void f(int x = 17); // x has an unparsed default argument now
865  ///   }; // x has a regular default argument now
866  /// @endcode
867  bool hasUnparsedDefaultArg() const {
868    return Init.is<UnparsedDefaultArgument*>();
869  }
870
871  bool hasUninstantiatedDefaultArg() const {
872    return Init.is<UninstantiatedDefaultArgument*>();
873  }
874
875  /// setUnparsedDefaultArg - Specify that this parameter has an
876  /// unparsed default argument. The argument will be replaced with a
877  /// real default argument via setDefaultArg when the class
878  /// definition enclosing the function declaration that owns this
879  /// default argument is completed.
880  void setUnparsedDefaultArg() {
881    Init = (UnparsedDefaultArgument *)0;
882  }
883
884  QualType getOriginalType() const {
885    if (getTypeSourceInfo())
886      return getTypeSourceInfo()->getType();
887    return getType();
888  }
889
890  /// setOwningFunction - Sets the function declaration that owns this
891  /// ParmVarDecl. Since ParmVarDecls are often created before the
892  /// FunctionDecls that own them, this routine is required to update
893  /// the DeclContext appropriately.
894  void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
895
896  // Implement isa/cast/dyncast/etc.
897  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
898  static bool classof(const ParmVarDecl *D) { return true; }
899  static bool classofKind(Kind K) { return K == ParmVar; }
900};
901
902/// FunctionDecl - An instance of this class is created to represent a
903/// function declaration or definition.
904///
905/// Since a given function can be declared several times in a program,
906/// there may be several FunctionDecls that correspond to that
907/// function. Only one of those FunctionDecls will be found when
908/// traversing the list of declarations in the context of the
909/// FunctionDecl (e.g., the translation unit); this FunctionDecl
910/// contains all of the information known about the function. Other,
911/// previous declarations of the function are available via the
912/// getPreviousDeclaration() chain.
913class FunctionDecl : public DeclaratorDecl, public DeclContext,
914                     public Redeclarable<FunctionDecl> {
915public:
916  enum StorageClass {
917    None, Extern, Static, PrivateExtern
918  };
919
920private:
921  /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
922  /// parameters of this function.  This is null if a prototype or if there are
923  /// no formals.
924  ParmVarDecl **ParamInfo;
925
926  LazyDeclStmtPtr Body;
927
928  // FIXME: This can be packed into the bitfields in Decl.
929  // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
930  unsigned SClass : 2;
931  bool IsInline : 1;
932  bool IsVirtualAsWritten : 1;
933  bool IsPure : 1;
934  bool HasInheritedPrototype : 1;
935  bool HasWrittenPrototype : 1;
936  bool IsDeleted : 1;
937  bool IsTrivial : 1; // sunk from CXXMethodDecl
938  bool IsCopyAssignment : 1;  // sunk from CXXMethodDecl
939  bool HasImplicitReturnZero : 1;
940
941  /// \brief End part of this FunctionDecl's source range.
942  ///
943  /// We could compute the full range in getSourceRange(). However, when we're
944  /// dealing with a function definition deserialized from a PCH/AST file,
945  /// we can only compute the full range once the function body has been
946  /// de-serialized, so it's far better to have the (sometimes-redundant)
947  /// EndRangeLoc.
948  SourceLocation EndRangeLoc;
949
950  /// \brief The template or declaration that this declaration
951  /// describes or was instantiated from, respectively.
952  ///
953  /// For non-templates, this value will be NULL. For function
954  /// declarations that describe a function template, this will be a
955  /// pointer to a FunctionTemplateDecl. For member functions
956  /// of class template specializations, this will be a MemberSpecializationInfo
957  /// pointer containing information about the specialization.
958  /// For function template specializations, this will be a
959  /// FunctionTemplateSpecializationInfo, which contains information about
960  /// the template being specialized and the template arguments involved in
961  /// that specialization.
962  llvm::PointerUnion3<FunctionTemplateDecl *,
963                      MemberSpecializationInfo *,
964                      FunctionTemplateSpecializationInfo *>
965    TemplateOrSpecialization;
966
967protected:
968  FunctionDecl(Kind DK, DeclContext *DC, SourceLocation L,
969               DeclarationName N, QualType T, TypeSourceInfo *TInfo,
970               StorageClass S, bool isInline)
971    : DeclaratorDecl(DK, DC, L, N, T, TInfo),
972      DeclContext(DK),
973      ParamInfo(0), Body(),
974      SClass(S), IsInline(isInline),
975      IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
976      HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
977      IsCopyAssignment(false),
978      HasImplicitReturnZero(false),
979      EndRangeLoc(L), TemplateOrSpecialization() {}
980
981  virtual ~FunctionDecl() {}
982  virtual void Destroy(ASTContext& C);
983
984  typedef Redeclarable<FunctionDecl> redeclarable_base;
985  virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
986
987public:
988  typedef redeclarable_base::redecl_iterator redecl_iterator;
989  redecl_iterator redecls_begin() const {
990    return redeclarable_base::redecls_begin();
991  }
992  redecl_iterator redecls_end() const {
993    return redeclarable_base::redecls_end();
994  }
995
996  static FunctionDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
997                              DeclarationName N, QualType T,
998                              TypeSourceInfo *TInfo,
999                              StorageClass S = None, bool isInline = false,
1000                              bool hasWrittenPrototype = true);
1001
1002  virtual void getNameForDiagnostic(std::string &S,
1003                                    const PrintingPolicy &Policy,
1004                                    bool Qualified) const;
1005
1006  virtual SourceRange getSourceRange() const {
1007    return SourceRange(getLocation(), EndRangeLoc);
1008  }
1009  void setLocEnd(SourceLocation E) {
1010    EndRangeLoc = E;
1011  }
1012
1013  /// getBody - Retrieve the body (definition) of the function. The
1014  /// function body might be in any of the (re-)declarations of this
1015  /// function. The variant that accepts a FunctionDecl pointer will
1016  /// set that function declaration to the actual declaration
1017  /// containing the body (if there is one).
1018  Stmt *getBody(const FunctionDecl *&Definition) const;
1019
1020  virtual Stmt *getBody() const {
1021    const FunctionDecl* Definition;
1022    return getBody(Definition);
1023  }
1024
1025  /// isThisDeclarationADefinition - Returns whether this specific
1026  /// declaration of the function is also a definition. This does not
1027  /// determine whether the function has been defined (e.g., in a
1028  /// previous definition); for that information, use getBody.
1029  /// FIXME: Should return true if function is deleted or defaulted. However,
1030  /// CodeGenModule.cpp uses it, and I don't know if this would break it.
1031  bool isThisDeclarationADefinition() const { return Body; }
1032
1033  void setBody(Stmt *B);
1034  void setLazyBody(uint64_t Offset) { Body = Offset; }
1035
1036  /// Whether this function is marked as virtual explicitly.
1037  bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1038  void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1039
1040  /// Whether this virtual function is pure, i.e. makes the containing class
1041  /// abstract.
1042  bool isPure() const { return IsPure; }
1043  void setPure(bool P = true) { IsPure = P; }
1044
1045  /// Whether this function is "trivial" in some specialized C++ senses.
1046  /// Can only be true for default constructors, copy constructors,
1047  /// copy assignment operators, and destructors.  Not meaningful until
1048  /// the class has been fully built by Sema.
1049  bool isTrivial() const { return IsTrivial; }
1050  void setTrivial(bool IT) { IsTrivial = IT; }
1051
1052  bool isCopyAssignment() const { return IsCopyAssignment; }
1053  void setCopyAssignment(bool CA) { IsCopyAssignment = CA; }
1054
1055  /// Whether falling off this function implicitly returns null/zero.
1056  /// If a more specific implicit return value is required, front-ends
1057  /// should synthesize the appropriate return statements.
1058  bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1059  void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1060
1061  /// \brief Whether this function has a prototype, either because one
1062  /// was explicitly written or because it was "inherited" by merging
1063  /// a declaration without a prototype with a declaration that has a
1064  /// prototype.
1065  bool hasPrototype() const {
1066    return HasWrittenPrototype || HasInheritedPrototype;
1067  }
1068
1069  bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1070  void setHasWrittenPrototype(bool P) { HasWrittenPrototype = P; }
1071
1072  /// \brief Whether this function inherited its prototype from a
1073  /// previous declaration.
1074  bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1075  void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1076
1077  /// \brief Whether this function has been deleted.
1078  ///
1079  /// A function that is "deleted" (via the C++0x "= delete" syntax)
1080  /// acts like a normal function, except that it cannot actually be
1081  /// called or have its address taken. Deleted functions are
1082  /// typically used in C++ overload resolution to attract arguments
1083  /// whose type or lvalue/rvalue-ness would permit the use of a
1084  /// different overload that would behave incorrectly. For example,
1085  /// one might use deleted functions to ban implicit conversion from
1086  /// a floating-point number to an Integer type:
1087  ///
1088  /// @code
1089  /// struct Integer {
1090  ///   Integer(long); // construct from a long
1091  ///   Integer(double) = delete; // no construction from float or double
1092  ///   Integer(long double) = delete; // no construction from long double
1093  /// };
1094  /// @endcode
1095  bool isDeleted() const { return IsDeleted; }
1096  void setDeleted(bool D = true) { IsDeleted = D; }
1097
1098  /// \brief Determines whether this is a function "main", which is
1099  /// the entry point into an executable program.
1100  bool isMain() const;
1101
1102  /// \brief Determines whether this function is a function with
1103  /// external, C linkage.
1104  bool isExternC() const;
1105
1106  /// \brief Determines whether this is a global function.
1107  bool isGlobal() const;
1108
1109  void setPreviousDeclaration(FunctionDecl * PrevDecl);
1110
1111  virtual const FunctionDecl *getCanonicalDecl() const;
1112  virtual FunctionDecl *getCanonicalDecl();
1113
1114  unsigned getBuiltinID() const;
1115
1116  // Iterator access to formal parameters.
1117  unsigned param_size() const { return getNumParams(); }
1118  typedef ParmVarDecl **param_iterator;
1119  typedef ParmVarDecl * const *param_const_iterator;
1120
1121  param_iterator param_begin() { return ParamInfo; }
1122  param_iterator param_end()   { return ParamInfo+param_size(); }
1123
1124  param_const_iterator param_begin() const { return ParamInfo; }
1125  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1126
1127  /// getNumParams - Return the number of parameters this function must have
1128  /// based on its FunctionType.  This is the length of the ParamInfo array
1129  /// after it has been created.
1130  unsigned getNumParams() const;
1131
1132  const ParmVarDecl *getParamDecl(unsigned i) const {
1133    assert(i < getNumParams() && "Illegal param #");
1134    return ParamInfo[i];
1135  }
1136  ParmVarDecl *getParamDecl(unsigned i) {
1137    assert(i < getNumParams() && "Illegal param #");
1138    return ParamInfo[i];
1139  }
1140  void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams);
1141
1142  /// getMinRequiredArguments - Returns the minimum number of arguments
1143  /// needed to call this function. This may be fewer than the number of
1144  /// function parameters, if some of the parameters have default
1145  /// arguments (in C++).
1146  unsigned getMinRequiredArguments() const;
1147
1148  QualType getResultType() const {
1149    return getType()->getAs<FunctionType>()->getResultType();
1150  }
1151  StorageClass getStorageClass() const { return StorageClass(SClass); }
1152  void setStorageClass(StorageClass SC) { SClass = SC; }
1153
1154  /// \brief Determine whether the "inline" keyword was specified for this
1155  /// function.
1156  bool isInlineSpecified() const { return IsInline; }
1157
1158  /// Set whether the "inline" keyword was specified for this function.
1159  void setInlineSpecified(bool I) { IsInline = I; }
1160
1161  /// \brief Determine whether this function should be inlined, because it is
1162  /// either marked "inline" or is a member function of a C++ class that
1163  /// was defined in the class body.
1164  bool isInlined() const;
1165
1166  bool isInlineDefinitionExternallyVisible() const;
1167
1168  /// isOverloadedOperator - Whether this function declaration
1169  /// represents an C++ overloaded operator, e.g., "operator+".
1170  bool isOverloadedOperator() const {
1171    return getOverloadedOperator() != OO_None;
1172  }
1173
1174  OverloadedOperatorKind getOverloadedOperator() const;
1175
1176  const IdentifierInfo *getLiteralIdentifier() const;
1177
1178  /// \brief If this function is an instantiation of a member function
1179  /// of a class template specialization, retrieves the function from
1180  /// which it was instantiated.
1181  ///
1182  /// This routine will return non-NULL for (non-templated) member
1183  /// functions of class templates and for instantiations of function
1184  /// templates. For example, given:
1185  ///
1186  /// \code
1187  /// template<typename T>
1188  /// struct X {
1189  ///   void f(T);
1190  /// };
1191  /// \endcode
1192  ///
1193  /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1194  /// whose parent is the class template specialization X<int>. For
1195  /// this declaration, getInstantiatedFromFunction() will return
1196  /// the FunctionDecl X<T>::A. When a complete definition of
1197  /// X<int>::A is required, it will be instantiated from the
1198  /// declaration returned by getInstantiatedFromMemberFunction().
1199  FunctionDecl *getInstantiatedFromMemberFunction() const;
1200
1201  /// \brief If this function is an instantiation of a member function of a
1202  /// class template specialization, retrieves the member specialization
1203  /// information.
1204  MemberSpecializationInfo *getMemberSpecializationInfo() const;
1205
1206  /// \brief Specify that this record is an instantiation of the
1207  /// member function FD.
1208  void setInstantiationOfMemberFunction(FunctionDecl *FD,
1209                                        TemplateSpecializationKind TSK);
1210
1211  /// \brief Retrieves the function template that is described by this
1212  /// function declaration.
1213  ///
1214  /// Every function template is represented as a FunctionTemplateDecl
1215  /// and a FunctionDecl (or something derived from FunctionDecl). The
1216  /// former contains template properties (such as the template
1217  /// parameter lists) while the latter contains the actual
1218  /// description of the template's
1219  /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1220  /// FunctionDecl that describes the function template,
1221  /// getDescribedFunctionTemplate() retrieves the
1222  /// FunctionTemplateDecl from a FunctionDecl.
1223  FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1224    return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1225  }
1226
1227  void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1228    TemplateOrSpecialization = Template;
1229  }
1230
1231  /// \brief Determine whether this function is a function template
1232  /// specialization.
1233  bool isFunctionTemplateSpecialization() const {
1234    return getPrimaryTemplate() != 0;
1235  }
1236
1237  /// \brief If this function is actually a function template specialization,
1238  /// retrieve information about this function template specialization.
1239  /// Otherwise, returns NULL.
1240  FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1241    return TemplateOrSpecialization.
1242             dyn_cast<FunctionTemplateSpecializationInfo*>();
1243  }
1244
1245  /// \brief Determines whether this function is a function template
1246  /// specialization or a member of a class template specialization that can
1247  /// be implicitly instantiated.
1248  bool isImplicitlyInstantiable() const;
1249
1250  /// \brief Retrieve the function declaration from which this function could
1251  /// be instantiated, if it is an instantiation (rather than a non-template
1252  /// or a specialization, for example).
1253  FunctionDecl *getTemplateInstantiationPattern() const;
1254
1255  /// \brief Retrieve the primary template that this function template
1256  /// specialization either specializes or was instantiated from.
1257  ///
1258  /// If this function declaration is not a function template specialization,
1259  /// returns NULL.
1260  FunctionTemplateDecl *getPrimaryTemplate() const;
1261
1262  /// \brief Retrieve the template arguments used to produce this function
1263  /// template specialization from the primary template.
1264  ///
1265  /// If this function declaration is not a function template specialization,
1266  /// returns NULL.
1267  const TemplateArgumentList *getTemplateSpecializationArgs() const;
1268
1269  /// \brief Specify that this function declaration is actually a function
1270  /// template specialization.
1271  ///
1272  /// \param Context the AST context in which this function resides.
1273  ///
1274  /// \param Template the function template that this function template
1275  /// specialization specializes.
1276  ///
1277  /// \param TemplateArgs the template arguments that produced this
1278  /// function template specialization from the template.
1279  ///
1280  /// \param InsertPos If non-NULL, the position in the function template
1281  /// specialization set where the function template specialization data will
1282  /// be inserted.
1283  ///
1284  /// \param TSK the kind of template specialization this is.
1285  void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1286                                      const TemplateArgumentList *TemplateArgs,
1287                                         void *InsertPos,
1288                    TemplateSpecializationKind TSK = TSK_ImplicitInstantiation);
1289
1290  /// \brief Determine what kind of template instantiation this function
1291  /// represents.
1292  TemplateSpecializationKind getTemplateSpecializationKind() const;
1293
1294  /// \brief Determine what kind of template instantiation this function
1295  /// represents.
1296  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1297                        SourceLocation PointOfInstantiation = SourceLocation());
1298
1299  /// \brief Retrieve the (first) point of instantiation of a function template
1300  /// specialization or a member of a class template specialization.
1301  ///
1302  /// \returns the first point of instantiation, if this function was
1303  /// instantiated from a template; otherwie, returns an invalid source
1304  /// location.
1305  SourceLocation getPointOfInstantiation() const;
1306
1307  /// \brief Determine whether this is or was instantiated from an out-of-line
1308  /// definition of a member function.
1309  virtual bool isOutOfLine() const;
1310
1311  // Implement isa/cast/dyncast/etc.
1312  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1313  static bool classof(const FunctionDecl *D) { return true; }
1314  static bool classofKind(Kind K) {
1315    return K >= FunctionFirst && K <= FunctionLast;
1316  }
1317  static DeclContext *castToDeclContext(const FunctionDecl *D) {
1318    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
1319  }
1320  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
1321    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
1322  }
1323};
1324
1325
1326/// FieldDecl - An instance of this class is created by Sema::ActOnField to
1327/// represent a member of a struct/union/class.
1328class FieldDecl : public DeclaratorDecl {
1329  // FIXME: This can be packed into the bitfields in Decl.
1330  bool Mutable : 1;
1331  Expr *BitWidth;
1332protected:
1333  FieldDecl(Kind DK, DeclContext *DC, SourceLocation L,
1334            IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1335            Expr *BW, bool Mutable)
1336    : DeclaratorDecl(DK, DC, L, Id, T, TInfo), Mutable(Mutable), BitWidth(BW) {
1337  }
1338
1339public:
1340  static FieldDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1341                           IdentifierInfo *Id, QualType T,
1342                           TypeSourceInfo *TInfo, Expr *BW, bool Mutable);
1343
1344  /// isMutable - Determines whether this field is mutable (C++ only).
1345  bool isMutable() const { return Mutable; }
1346
1347  /// \brief Set whether this field is mutable (C++ only).
1348  void setMutable(bool M) { Mutable = M; }
1349
1350  /// isBitfield - Determines whether this field is a bitfield.
1351  bool isBitField() const { return BitWidth != NULL; }
1352
1353  /// @brief Determines whether this is an unnamed bitfield.
1354  bool isUnnamedBitfield() const { return BitWidth != NULL && !getDeclName(); }
1355
1356  /// isAnonymousStructOrUnion - Determines whether this field is a
1357  /// representative for an anonymous struct or union. Such fields are
1358  /// unnamed and are implicitly generated by the implementation to
1359  /// store the data for the anonymous union or struct.
1360  bool isAnonymousStructOrUnion() const;
1361
1362  Expr *getBitWidth() const { return BitWidth; }
1363  void setBitWidth(Expr *BW) { BitWidth = BW; }
1364
1365  /// getParent - Returns the parent of this field declaration, which
1366  /// is the struct in which this method is defined.
1367  const RecordDecl *getParent() const {
1368    return cast<RecordDecl>(getDeclContext());
1369  }
1370
1371  RecordDecl *getParent() {
1372    return cast<RecordDecl>(getDeclContext());
1373  }
1374
1375  // Implement isa/cast/dyncast/etc.
1376  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1377  static bool classof(const FieldDecl *D) { return true; }
1378  static bool classofKind(Kind K) { return K >= FieldFirst && K <= FieldLast; }
1379};
1380
1381/// EnumConstantDecl - An instance of this object exists for each enum constant
1382/// that is defined.  For example, in "enum X {a,b}", each of a/b are
1383/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
1384/// TagType for the X EnumDecl.
1385class EnumConstantDecl : public ValueDecl {
1386  Stmt *Init; // an integer constant expression
1387  llvm::APSInt Val; // The value.
1388protected:
1389  EnumConstantDecl(DeclContext *DC, SourceLocation L,
1390                   IdentifierInfo *Id, QualType T, Expr *E,
1391                   const llvm::APSInt &V)
1392    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
1393
1394  virtual ~EnumConstantDecl() {}
1395public:
1396
1397  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
1398                                  SourceLocation L, IdentifierInfo *Id,
1399                                  QualType T, Expr *E,
1400                                  const llvm::APSInt &V);
1401
1402  virtual void Destroy(ASTContext& C);
1403
1404  const Expr *getInitExpr() const { return (const Expr*) Init; }
1405  Expr *getInitExpr() { return (Expr*) Init; }
1406  const llvm::APSInt &getInitVal() const { return Val; }
1407
1408  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
1409  void setInitVal(const llvm::APSInt &V) { Val = V; }
1410
1411  // Implement isa/cast/dyncast/etc.
1412  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1413  static bool classof(const EnumConstantDecl *D) { return true; }
1414  static bool classofKind(Kind K) { return K == EnumConstant; }
1415
1416  friend class StmtIteratorBase;
1417};
1418
1419
1420/// TypeDecl - Represents a declaration of a type.
1421///
1422class TypeDecl : public NamedDecl {
1423  /// TypeForDecl - This indicates the Type object that represents
1424  /// this TypeDecl.  It is a cache maintained by
1425  /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
1426  /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
1427  mutable Type *TypeForDecl;
1428  friend class ASTContext;
1429  friend class DeclContext;
1430  friend class TagDecl;
1431  friend class TemplateTypeParmDecl;
1432  friend class ClassTemplateSpecializationDecl;
1433  friend class TagType;
1434
1435protected:
1436  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L,
1437           IdentifierInfo *Id)
1438    : NamedDecl(DK, DC, L, Id), TypeForDecl(0) {}
1439
1440public:
1441  // Low-level accessor
1442  Type *getTypeForDecl() const { return TypeForDecl; }
1443  void setTypeForDecl(Type *TD) { TypeForDecl = TD; }
1444
1445  // Implement isa/cast/dyncast/etc.
1446  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1447  static bool classof(const TypeDecl *D) { return true; }
1448  static bool classofKind(Kind K) { return K >= TypeFirst && K <= TypeLast; }
1449};
1450
1451
1452class TypedefDecl : public TypeDecl, public Redeclarable<TypedefDecl> {
1453  /// UnderlyingType - This is the type the typedef is set to.
1454  TypeSourceInfo *TInfo;
1455
1456  TypedefDecl(DeclContext *DC, SourceLocation L,
1457              IdentifierInfo *Id, TypeSourceInfo *TInfo)
1458    : TypeDecl(Typedef, DC, L, Id), TInfo(TInfo) {}
1459
1460  virtual ~TypedefDecl();
1461public:
1462
1463  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
1464                             SourceLocation L, IdentifierInfo *Id,
1465                             TypeSourceInfo *TInfo);
1466
1467  TypeSourceInfo *getTypeSourceInfo() const {
1468    return TInfo;
1469  }
1470
1471  /// Retrieves the canonical declaration of this typedef.
1472  TypedefDecl *getCanonicalDecl() {
1473    return getFirstDeclaration();
1474  }
1475  const TypedefDecl *getCanonicalDecl() const {
1476    return getFirstDeclaration();
1477  }
1478
1479  QualType getUnderlyingType() const {
1480    return TInfo->getType();
1481  }
1482  void setTypeSourceInfo(TypeSourceInfo *newType) {
1483    TInfo = newType;
1484  }
1485
1486  // Implement isa/cast/dyncast/etc.
1487  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1488  static bool classof(const TypedefDecl *D) { return true; }
1489  static bool classofKind(Kind K) { return K == Typedef; }
1490};
1491
1492class TypedefDecl;
1493
1494/// TagDecl - Represents the declaration of a struct/union/class/enum.
1495class TagDecl
1496  : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
1497public:
1498  // This is really ugly.
1499  typedef ElaboratedType::TagKind TagKind;
1500  static const TagKind TK_struct = ElaboratedType::TK_struct;
1501  static const TagKind TK_union = ElaboratedType::TK_union;
1502  static const TagKind TK_class = ElaboratedType::TK_class;
1503  static const TagKind TK_enum = ElaboratedType::TK_enum;
1504
1505private:
1506  // FIXME: This can be packed into the bitfields in Decl.
1507  /// TagDeclKind - The TagKind enum.
1508  unsigned TagDeclKind : 2;
1509
1510  /// IsDefinition - True if this is a definition ("struct foo {};"), false if
1511  /// it is a declaration ("struct foo;").
1512  bool IsDefinition : 1;
1513
1514  /// IsEmbeddedInDeclarator - True if this tag declaration is
1515  /// "embedded" (i.e., defined or declared for the very first time)
1516  /// in the syntax of a declarator,
1517  bool IsEmbeddedInDeclarator : 1;
1518
1519  /// TypedefForAnonDecl - If a TagDecl is anonymous and part of a typedef,
1520  /// this points to the TypedefDecl. Used for mangling.
1521  TypedefDecl *TypedefForAnonDecl;
1522
1523  SourceLocation TagKeywordLoc;
1524  SourceLocation RBraceLoc;
1525
1526protected:
1527  TagDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
1528          IdentifierInfo *Id, TagDecl *PrevDecl,
1529          SourceLocation TKL = SourceLocation())
1530    : TypeDecl(DK, DC, L, Id), DeclContext(DK), TypedefForAnonDecl(0),
1531      TagKeywordLoc(TKL) {
1532    assert((DK != Enum || TK == TK_enum) &&"EnumDecl not matched with TK_enum");
1533    TagDeclKind = TK;
1534    IsDefinition = false;
1535    IsEmbeddedInDeclarator = false;
1536    setPreviousDeclaration(PrevDecl);
1537  }
1538
1539  typedef Redeclarable<TagDecl> redeclarable_base;
1540  virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1541
1542public:
1543  typedef redeclarable_base::redecl_iterator redecl_iterator;
1544  redecl_iterator redecls_begin() const {
1545    return redeclarable_base::redecls_begin();
1546  }
1547  redecl_iterator redecls_end() const {
1548    return redeclarable_base::redecls_end();
1549  }
1550
1551  SourceLocation getRBraceLoc() const { return RBraceLoc; }
1552  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
1553
1554  SourceLocation getTagKeywordLoc() const { return TagKeywordLoc; }
1555  void setTagKeywordLoc(SourceLocation TKL) { TagKeywordLoc = TKL; }
1556
1557  virtual SourceRange getSourceRange() const;
1558
1559  virtual TagDecl* getCanonicalDecl();
1560  const TagDecl* getCanonicalDecl() const {
1561    return const_cast<TagDecl*>(this)->getCanonicalDecl();
1562  }
1563
1564  /// isDefinition - Return true if this decl has its body specified.
1565  bool isDefinition() const {
1566    return IsDefinition;
1567  }
1568
1569  bool isEmbeddedInDeclarator() const {
1570    return IsEmbeddedInDeclarator;
1571  }
1572  void setEmbeddedInDeclarator(bool isInDeclarator) {
1573    IsEmbeddedInDeclarator = isInDeclarator;
1574  }
1575
1576  /// \brief Whether this declaration declares a type that is
1577  /// dependent, i.e., a type that somehow depends on template
1578  /// parameters.
1579  bool isDependentType() const { return isDependentContext(); }
1580
1581  /// @brief Starts the definition of this tag declaration.
1582  ///
1583  /// This method should be invoked at the beginning of the definition
1584  /// of this tag declaration. It will set the tag type into a state
1585  /// where it is in the process of being defined.
1586  void startDefinition();
1587
1588  /// @brief Completes the definition of this tag declaration.
1589  void completeDefinition();
1590
1591  /// getDefinition - Returns the TagDecl that actually defines this
1592  ///  struct/union/class/enum.  When determining whether or not a
1593  ///  struct/union/class/enum is completely defined, one should use this method
1594  ///  as opposed to 'isDefinition'.  'isDefinition' indicates whether or not a
1595  ///  specific TagDecl is defining declaration, not whether or not the
1596  ///  struct/union/class/enum type is defined.  This method returns NULL if
1597  ///  there is no TagDecl that defines the struct/union/class/enum.
1598  TagDecl* getDefinition() const;
1599
1600  void setDefinition(bool V) { IsDefinition = V; }
1601
1602  const char *getKindName() const {
1603    return ElaboratedType::getNameForTagKind(getTagKind());
1604  }
1605
1606  /// getTagKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
1607  /// into a tag kind.  It is an error to provide a type specifier
1608  /// which *isn't* a tag kind here.
1609  static TagKind getTagKindForTypeSpec(unsigned TypeSpec);
1610
1611  TagKind getTagKind() const {
1612    return TagKind(TagDeclKind);
1613  }
1614
1615  void setTagKind(TagKind TK) { TagDeclKind = TK; }
1616
1617  bool isStruct() const { return getTagKind() == TK_struct; }
1618  bool isClass()  const { return getTagKind() == TK_class; }
1619  bool isUnion()  const { return getTagKind() == TK_union; }
1620  bool isEnum()   const { return getTagKind() == TK_enum; }
1621
1622  TypedefDecl *getTypedefForAnonDecl() const { return TypedefForAnonDecl; }
1623  void setTypedefForAnonDecl(TypedefDecl *TDD) { TypedefForAnonDecl = TDD; }
1624
1625  // Implement isa/cast/dyncast/etc.
1626  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1627  static bool classof(const TagDecl *D) { return true; }
1628  static bool classofKind(Kind K) { return K >= TagFirst && K <= TagLast; }
1629
1630  static DeclContext *castToDeclContext(const TagDecl *D) {
1631    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
1632  }
1633  static TagDecl *castFromDeclContext(const DeclContext *DC) {
1634    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
1635  }
1636};
1637
1638/// EnumDecl - Represents an enum.  As an extension, we allow forward-declared
1639/// enums.
1640class EnumDecl : public TagDecl {
1641  /// IntegerType - This represent the integer type that the enum corresponds
1642  /// to for code generation purposes.  Note that the enumerator constants may
1643  /// have a different type than this does.
1644  QualType IntegerType;
1645
1646  /// PromotionType - The integer type that values of this type should
1647  /// promote to.  In C, enumerators are generally of an integer type
1648  /// directly, but gcc-style large enumerators (and all enumerators
1649  /// in C++) are of the enum type instead.
1650  QualType PromotionType;
1651
1652  /// \brief If the enumeration was instantiated from an enumeration
1653  /// within a class or function template, this pointer refers to the
1654  /// enumeration declared within the template.
1655  EnumDecl *InstantiatedFrom;
1656
1657  EnumDecl(DeclContext *DC, SourceLocation L,
1658           IdentifierInfo *Id, EnumDecl *PrevDecl, SourceLocation TKL)
1659    : TagDecl(Enum, TK_enum, DC, L, Id, PrevDecl, TKL), InstantiatedFrom(0) {
1660      IntegerType = QualType();
1661    }
1662public:
1663  EnumDecl *getCanonicalDecl() {
1664    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
1665  }
1666  const EnumDecl *getCanonicalDecl() const {
1667    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
1668  }
1669
1670  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
1671                          SourceLocation L, IdentifierInfo *Id,
1672                          SourceLocation TKL, EnumDecl *PrevDecl);
1673
1674  virtual void Destroy(ASTContext& C);
1675
1676  /// completeDefinition - When created, the EnumDecl corresponds to a
1677  /// forward-declared enum. This method is used to mark the
1678  /// declaration as being defined; it's enumerators have already been
1679  /// added (via DeclContext::addDecl). NewType is the new underlying
1680  /// type of the enumeration type.
1681  void completeDefinition(QualType NewType,
1682                          QualType PromotionType);
1683
1684  // enumerator_iterator - Iterates through the enumerators of this
1685  // enumeration.
1686  typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
1687
1688  enumerator_iterator enumerator_begin() const {
1689    return enumerator_iterator(this->decls_begin());
1690  }
1691
1692  enumerator_iterator enumerator_end() const {
1693    return enumerator_iterator(this->decls_end());
1694  }
1695
1696  /// getPromotionType - Return the integer type that enumerators
1697  /// should promote to.
1698  QualType getPromotionType() const { return PromotionType; }
1699
1700  /// \brief Set the promotion type.
1701  void setPromotionType(QualType T) { PromotionType = T; }
1702
1703  /// getIntegerType - Return the integer type this enum decl corresponds to.
1704  /// This returns a null qualtype for an enum forward definition.
1705  QualType getIntegerType() const { return IntegerType; }
1706
1707  /// \brief Set the underlying integer type.
1708  void setIntegerType(QualType T) { IntegerType = T; }
1709
1710  /// \brief Returns the enumeration (declared within the template)
1711  /// from which this enumeration type was instantiated, or NULL if
1712  /// this enumeration was not instantiated from any template.
1713  EnumDecl *getInstantiatedFromMemberEnum() const {
1714    return InstantiatedFrom;
1715  }
1716
1717  void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; }
1718
1719  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1720  static bool classof(const EnumDecl *D) { return true; }
1721  static bool classofKind(Kind K) { return K == Enum; }
1722};
1723
1724
1725/// RecordDecl - Represents a struct/union/class.  For example:
1726///   struct X;                  // Forward declaration, no "body".
1727///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
1728/// This decl will be marked invalid if *any* members are invalid.
1729///
1730class RecordDecl : public TagDecl {
1731  // FIXME: This can be packed into the bitfields in Decl.
1732  /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
1733  /// array member (e.g. int X[]) or if this union contains a struct that does.
1734  /// If so, this cannot be contained in arrays or other structs as a member.
1735  bool HasFlexibleArrayMember : 1;
1736
1737  /// AnonymousStructOrUnion - Whether this is the type of an
1738  /// anonymous struct or union.
1739  bool AnonymousStructOrUnion : 1;
1740
1741  /// HasObjectMember - This is true if this struct has at least one
1742  /// member containing an object
1743  bool HasObjectMember : 1;
1744
1745protected:
1746  RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
1747             SourceLocation L, IdentifierInfo *Id,
1748             RecordDecl *PrevDecl, SourceLocation TKL);
1749  virtual ~RecordDecl();
1750
1751public:
1752  static RecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC,
1753                            SourceLocation L, IdentifierInfo *Id,
1754                            SourceLocation TKL = SourceLocation(),
1755                            RecordDecl* PrevDecl = 0);
1756
1757  virtual void Destroy(ASTContext& C);
1758
1759  bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
1760  void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
1761
1762  /// isAnonymousStructOrUnion - Whether this is an anonymous struct
1763  /// or union. To be an anonymous struct or union, it must have been
1764  /// declared without a name and there must be no objects of this
1765  /// type declared, e.g.,
1766  /// @code
1767  ///   union { int i; float f; };
1768  /// @endcode
1769  /// is an anonymous union but neither of the following are:
1770  /// @code
1771  ///  union X { int i; float f; };
1772  ///  union { int i; float f; } obj;
1773  /// @endcode
1774  bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
1775  void setAnonymousStructOrUnion(bool Anon) {
1776    AnonymousStructOrUnion = Anon;
1777  }
1778
1779  bool hasObjectMember() const { return HasObjectMember; }
1780  void setHasObjectMember (bool val) { HasObjectMember = val; }
1781
1782  /// \brief Determines whether this declaration represents the
1783  /// injected class name.
1784  ///
1785  /// The injected class name in C++ is the name of the class that
1786  /// appears inside the class itself. For example:
1787  ///
1788  /// \code
1789  /// struct C {
1790  ///   // C is implicitly declared here as a synonym for the class name.
1791  /// };
1792  ///
1793  /// C::C c; // same as "C c;"
1794  /// \endcode
1795  bool isInjectedClassName() const;
1796
1797  /// getDefinition - Returns the RecordDecl that actually defines this
1798  ///  struct/union/class.  When determining whether or not a struct/union/class
1799  ///  is completely defined, one should use this method as opposed to
1800  ///  'isDefinition'.  'isDefinition' indicates whether or not a specific
1801  ///  RecordDecl is defining declaration, not whether or not the record
1802  ///  type is defined.  This method returns NULL if there is no RecordDecl
1803  ///  that defines the struct/union/tag.
1804  RecordDecl* getDefinition() const {
1805    return cast_or_null<RecordDecl>(TagDecl::getDefinition());
1806  }
1807
1808  // Iterator access to field members. The field iterator only visits
1809  // the non-static data members of this class, ignoring any static
1810  // data members, functions, constructors, destructors, etc.
1811  typedef specific_decl_iterator<FieldDecl> field_iterator;
1812
1813  field_iterator field_begin() const {
1814    return field_iterator(decls_begin());
1815  }
1816  field_iterator field_end() const {
1817    return field_iterator(decls_end());
1818  }
1819
1820  // field_empty - Whether there are any fields (non-static data
1821  // members) in this record.
1822  bool field_empty() const {
1823    return field_begin() == field_end();
1824  }
1825
1826  /// completeDefinition - Notes that the definition of this type is
1827  /// now complete.
1828  void completeDefinition();
1829
1830  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1831  static bool classof(const RecordDecl *D) { return true; }
1832  static bool classofKind(Kind K) {
1833    return K >= RecordFirst && K <= RecordLast;
1834  }
1835};
1836
1837class FileScopeAsmDecl : public Decl {
1838  StringLiteral *AsmString;
1839  FileScopeAsmDecl(DeclContext *DC, SourceLocation L, StringLiteral *asmstring)
1840    : Decl(FileScopeAsm, DC, L), AsmString(asmstring) {}
1841public:
1842  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
1843                                  SourceLocation L, StringLiteral *Str);
1844
1845  const StringLiteral *getAsmString() const { return AsmString; }
1846  StringLiteral *getAsmString() { return AsmString; }
1847  void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
1848
1849  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1850  static bool classof(const FileScopeAsmDecl *D) { return true; }
1851  static bool classofKind(Kind K) { return K == FileScopeAsm; }
1852};
1853
1854/// BlockDecl - This represents a block literal declaration, which is like an
1855/// unnamed FunctionDecl.  For example:
1856/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
1857///
1858class BlockDecl : public Decl, public DeclContext {
1859  // FIXME: This can be packed into the bitfields in Decl.
1860  bool isVariadic : 1;
1861  /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
1862  /// parameters of this function.  This is null if a prototype or if there are
1863  /// no formals.
1864  ParmVarDecl **ParamInfo;
1865  unsigned NumParams;
1866
1867  Stmt *Body;
1868
1869protected:
1870  BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
1871    : Decl(Block, DC, CaretLoc), DeclContext(Block),
1872      isVariadic(false), ParamInfo(0), NumParams(0), Body(0) {}
1873
1874  virtual ~BlockDecl();
1875  virtual void Destroy(ASTContext& C);
1876
1877public:
1878  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
1879
1880  SourceLocation getCaretLocation() const { return getLocation(); }
1881
1882  bool IsVariadic() const { return isVariadic; }
1883  void setIsVariadic(bool value) { isVariadic = value; }
1884
1885  CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
1886  Stmt *getBody() const { return (Stmt*) Body; }
1887  void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
1888
1889  // Iterator access to formal parameters.
1890  unsigned param_size() const { return getNumParams(); }
1891  typedef ParmVarDecl **param_iterator;
1892  typedef ParmVarDecl * const *param_const_iterator;
1893
1894  bool param_empty() const { return NumParams == 0; }
1895  param_iterator param_begin()  { return ParamInfo; }
1896  param_iterator param_end()   { return ParamInfo+param_size(); }
1897
1898  param_const_iterator param_begin() const { return ParamInfo; }
1899  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1900
1901  unsigned getNumParams() const;
1902  const ParmVarDecl *getParamDecl(unsigned i) const {
1903    assert(i < getNumParams() && "Illegal param #");
1904    return ParamInfo[i];
1905  }
1906  ParmVarDecl *getParamDecl(unsigned i) {
1907    assert(i < getNumParams() && "Illegal param #");
1908    return ParamInfo[i];
1909  }
1910  void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams);
1911
1912  // Implement isa/cast/dyncast/etc.
1913  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1914  static bool classof(const BlockDecl *D) { return true; }
1915  static bool classofKind(Kind K) { return K == Block; }
1916  static DeclContext *castToDeclContext(const BlockDecl *D) {
1917    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
1918  }
1919  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
1920    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
1921  }
1922};
1923
1924/// Insertion operator for diagnostics.  This allows sending NamedDecl's
1925/// into a diagnostic with <<.
1926inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1927                                           NamedDecl* ND) {
1928  DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), Diagnostic::ak_nameddecl);
1929  return DB;
1930}
1931
1932}  // end namespace clang
1933
1934#endif
1935