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