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