Decl.h revision 9f8bd33a1c125fdf825681c61f8170c4424f6616
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/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/Redeclarable.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/Linkage.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/Optional.h"
26#include "llvm/Support/Compiler.h"
27
28namespace clang {
29struct ASTTemplateArgumentListInfo;
30class CXXTemporary;
31class CompoundStmt;
32class DependentFunctionTemplateSpecializationInfo;
33class Expr;
34class FunctionTemplateDecl;
35class FunctionTemplateSpecializationInfo;
36class LabelStmt;
37class MemberSpecializationInfo;
38class Module;
39class NestedNameSpecifier;
40class Stmt;
41class StringLiteral;
42class TemplateArgumentList;
43class TemplateParameterList;
44class TypeLoc;
45class UnresolvedSetImpl;
46
47/// \brief A container of type source information.
48///
49/// A client can read the relevant info using TypeLoc wrappers, e.g:
50/// @code
51/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
52/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
53///   PL->getStarLoc().print(OS, SrcMgr);
54/// @endcode
55///
56class TypeSourceInfo {
57  QualType Ty;
58  // Contains a memory block after the class, used for type source information,
59  // allocated by ASTContext.
60  friend class ASTContext;
61  TypeSourceInfo(QualType ty) : Ty(ty) { }
62public:
63  /// \brief Return the type wrapped by this type source info.
64  QualType getType() const { return Ty; }
65
66  /// \brief Return the TypeLoc wrapper for the type source info.
67  TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
68};
69
70/// TranslationUnitDecl - The top declaration context.
71class TranslationUnitDecl : public Decl, public DeclContext {
72  virtual void anchor();
73  ASTContext &Ctx;
74
75  /// The (most recently entered) anonymous namespace for this
76  /// translation unit, if one has been created.
77  NamespaceDecl *AnonymousNamespace;
78
79  explicit TranslationUnitDecl(ASTContext &ctx)
80    : Decl(TranslationUnit, 0, SourceLocation()),
81      DeclContext(TranslationUnit),
82      Ctx(ctx), AnonymousNamespace(0) {}
83public:
84  ASTContext &getASTContext() const { return Ctx; }
85
86  NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
87  void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
88
89  static TranslationUnitDecl *Create(ASTContext &C);
90  // Implement isa/cast/dyncast/etc.
91  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
92  static bool classofKind(Kind K) { return K == TranslationUnit; }
93  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
94    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
95  }
96  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
97    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
98  }
99};
100
101/// NamedDecl - This represents a decl with a name.  Many decls have names such
102/// as ObjCMethodDecl, but not \@class, etc.
103class NamedDecl : public Decl {
104  virtual void anchor();
105  /// Name - The name of this declaration, which is typically a normal
106  /// identifier but may also be a special kind of name (C++
107  /// constructor, Objective-C selector, etc.)
108  DeclarationName Name;
109
110private:
111  NamedDecl *getUnderlyingDeclImpl();
112  void verifyLinkage() const;
113
114protected:
115  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
116    : Decl(DK, DC, L), Name(N) { }
117
118public:
119  /// getIdentifier - Get the identifier that names this declaration,
120  /// if there is one. This will return NULL if this declaration has
121  /// no name (e.g., for an unnamed class) or if the name is a special
122  /// name (C++ constructor, Objective-C selector, etc.).
123  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
124
125  /// getName - Get the name of identifier for this declaration as a StringRef.
126  /// This requires that the declaration have a name and that it be a simple
127  /// identifier.
128  StringRef getName() const {
129    assert(Name.isIdentifier() && "Name is not a simple identifier");
130    return getIdentifier() ? getIdentifier()->getName() : "";
131  }
132
133  /// getNameAsString - Get a human-readable name for the declaration, even if
134  /// it is one of the special kinds of names (C++ constructor, Objective-C
135  /// selector, etc).  Creating this name requires expensive string
136  /// manipulation, so it should be called only when performance doesn't matter.
137  /// For simple declarations, getNameAsCString() should suffice.
138  //
139  // FIXME: This function should be renamed to indicate that it is not just an
140  // alternate form of getName(), and clients should move as appropriate.
141  //
142  // FIXME: Deprecated, move clients to getName().
143  std::string getNameAsString() const { return Name.getAsString(); }
144
145  void printName(raw_ostream &os) const { return Name.printName(os); }
146
147  /// getDeclName - Get the actual, stored name of the declaration,
148  /// which may be a special name.
149  DeclarationName getDeclName() const { return Name; }
150
151  /// \brief Set the name of this declaration.
152  void setDeclName(DeclarationName N) { Name = N; }
153
154  /// printQualifiedName - Returns human-readable qualified name for
155  /// declaration, like A::B::i, for i being member of namespace A::B.
156  /// If declaration is not member of context which can be named (record,
157  /// namespace), it will return same result as printName().
158  /// Creating this name is expensive, so it should be called only when
159  /// performance doesn't matter.
160  void printQualifiedName(raw_ostream &OS) const;
161  void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
162
163  // FIXME: Remove string versions.
164  std::string getQualifiedNameAsString() const;
165  std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
166
167  /// getNameForDiagnostic - Appends a human-readable name for this
168  /// declaration into the given stream.
169  ///
170  /// This is the method invoked by Sema when displaying a NamedDecl
171  /// in a diagnostic.  It does not necessarily produce the same
172  /// result as printName(); for example, class template
173  /// specializations are printed with their template arguments.
174  virtual void getNameForDiagnostic(raw_ostream &OS,
175                                    const PrintingPolicy &Policy,
176                                    bool Qualified) const;
177
178  /// declarationReplaces - Determine whether this declaration, if
179  /// known to be well-formed within its context, will replace the
180  /// declaration OldD if introduced into scope. A declaration will
181  /// replace another declaration if, for example, it is a
182  /// redeclaration of the same variable or function, but not if it is
183  /// a declaration of a different kind (function vs. class) or an
184  /// overloaded function.
185  bool declarationReplaces(NamedDecl *OldD) const;
186
187  /// \brief Determine whether this declaration has linkage.
188  bool hasLinkage() const;
189
190  using Decl::isModulePrivate;
191  using Decl::setModulePrivate;
192
193  /// \brief Determine whether this declaration is hidden from name lookup.
194  bool isHidden() const { return Hidden; }
195
196  /// \brief Determine whether this declaration is a C++ class member.
197  bool isCXXClassMember() const {
198    const DeclContext *DC = getDeclContext();
199
200    // C++0x [class.mem]p1:
201    //   The enumerators of an unscoped enumeration defined in
202    //   the class are members of the class.
203    // FIXME: support C++0x scoped enumerations.
204    if (isa<EnumDecl>(DC))
205      DC = DC->getParent();
206
207    return DC->isRecord();
208  }
209
210  /// \brief Determine whether the given declaration is an instance member of
211  /// a C++ class.
212  bool isCXXInstanceMember() const;
213
214  /// \brief Determine what kind of linkage this entity has.
215  Linkage getLinkage() const;
216
217  /// \brief True if this decl has external linkage.
218  bool hasExternalLinkage() const {
219    return getLinkage() == ExternalLinkage;
220  }
221
222  /// \brief Determines the visibility of this entity.
223  Visibility getVisibility() const {
224    return getLinkageAndVisibility().getVisibility();
225  }
226
227  /// \brief Determines the linkage and visibility of this entity.
228  LinkageInfo getLinkageAndVisibility() const;
229
230  /// Kinds of explicit visibility.
231  enum ExplicitVisibilityKind {
232    VisibilityForType,
233    VisibilityForValue
234  };
235
236  /// \brief If visibility was explicitly specified for this
237  /// declaration, return that visibility.
238  Optional<Visibility>
239  getExplicitVisibility(ExplicitVisibilityKind kind) const;
240
241  /// \brief True if the computed linkage is valid. Used for consistency
242  /// checking. Should always return true.
243  bool isLinkageValid() const;
244
245  /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
246  /// the underlying named decl.
247  NamedDecl *getUnderlyingDecl() {
248    // Fast-path the common case.
249    if (this->getKind() != UsingShadow &&
250        this->getKind() != ObjCCompatibleAlias)
251      return this;
252
253    return getUnderlyingDeclImpl();
254  }
255  const NamedDecl *getUnderlyingDecl() const {
256    return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
257  }
258
259  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
260  static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
261};
262
263inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
264  ND.printName(OS);
265  return OS;
266}
267
268/// LabelDecl - Represents the declaration of a label.  Labels also have a
269/// corresponding LabelStmt, which indicates the position that the label was
270/// defined at.  For normal labels, the location of the decl is the same as the
271/// location of the statement.  For GNU local labels (__label__), the decl
272/// location is where the __label__ is.
273class LabelDecl : public NamedDecl {
274  virtual void anchor();
275  LabelStmt *TheStmt;
276  /// LocStart - For normal labels, this is the same as the main declaration
277  /// label, i.e., the location of the identifier; for GNU local labels,
278  /// this is the location of the __label__ keyword.
279  SourceLocation LocStart;
280
281  LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
282            LabelStmt *S, SourceLocation StartL)
283    : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
284
285public:
286  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
287                           SourceLocation IdentL, IdentifierInfo *II);
288  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
289                           SourceLocation IdentL, IdentifierInfo *II,
290                           SourceLocation GnuLabelL);
291  static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
292
293  LabelStmt *getStmt() const { return TheStmt; }
294  void setStmt(LabelStmt *T) { TheStmt = T; }
295
296  bool isGnuLocal() const { return LocStart != getLocation(); }
297  void setLocStart(SourceLocation L) { LocStart = L; }
298
299  SourceRange getSourceRange() const LLVM_READONLY {
300    return SourceRange(LocStart, getLocation());
301  }
302
303  // Implement isa/cast/dyncast/etc.
304  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
305  static bool classofKind(Kind K) { return K == Label; }
306};
307
308/// NamespaceDecl - Represent a C++ namespace.
309class NamespaceDecl : public NamedDecl, public DeclContext,
310                      public Redeclarable<NamespaceDecl>
311{
312  virtual void anchor();
313
314  /// LocStart - The starting location of the source range, pointing
315  /// to either the namespace or the inline keyword.
316  SourceLocation LocStart;
317  /// RBraceLoc - The ending location of the source range.
318  SourceLocation RBraceLoc;
319
320  /// \brief A pointer to either the anonymous namespace that lives just inside
321  /// this namespace or to the first namespace in the chain (the latter case
322  /// only when this is not the first in the chain), along with a
323  /// boolean value indicating whether this is an inline namespace.
324  llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
325
326  NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc,
327                SourceLocation IdLoc, IdentifierInfo *Id,
328                NamespaceDecl *PrevDecl);
329
330  typedef Redeclarable<NamespaceDecl> redeclarable_base;
331  virtual NamespaceDecl *getNextRedeclaration() {
332    return RedeclLink.getNext();
333  }
334  virtual NamespaceDecl *getPreviousDeclImpl() {
335    return getPreviousDecl();
336  }
337  virtual NamespaceDecl *getMostRecentDeclImpl() {
338    return getMostRecentDecl();
339  }
340
341public:
342  static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
343                               bool Inline, SourceLocation StartLoc,
344                               SourceLocation IdLoc, IdentifierInfo *Id,
345                               NamespaceDecl *PrevDecl);
346
347  static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
348
349  typedef redeclarable_base::redecl_iterator redecl_iterator;
350  using redeclarable_base::redecls_begin;
351  using redeclarable_base::redecls_end;
352  using redeclarable_base::getPreviousDecl;
353  using redeclarable_base::getMostRecentDecl;
354
355  /// \brief Returns true if this is an anonymous namespace declaration.
356  ///
357  /// For example:
358  /// \code
359  ///   namespace {
360  ///     ...
361  ///   };
362  /// \endcode
363  /// q.v. C++ [namespace.unnamed]
364  bool isAnonymousNamespace() const {
365    return !getIdentifier();
366  }
367
368  /// \brief Returns true if this is an inline namespace declaration.
369  bool isInline() const {
370    return AnonOrFirstNamespaceAndInline.getInt();
371  }
372
373  /// \brief Set whether this is an inline namespace declaration.
374  void setInline(bool Inline) {
375    AnonOrFirstNamespaceAndInline.setInt(Inline);
376  }
377
378  /// \brief Get the original (first) namespace declaration.
379  NamespaceDecl *getOriginalNamespace() {
380    if (isFirstDeclaration())
381      return this;
382
383    return AnonOrFirstNamespaceAndInline.getPointer();
384  }
385
386  /// \brief Get the original (first) namespace declaration.
387  const NamespaceDecl *getOriginalNamespace() const {
388    if (isFirstDeclaration())
389      return this;
390
391    return AnonOrFirstNamespaceAndInline.getPointer();
392  }
393
394  /// \brief Return true if this declaration is an original (first) declaration
395  /// of the namespace. This is false for non-original (subsequent) namespace
396  /// declarations and anonymous namespaces.
397  bool isOriginalNamespace() const {
398    return isFirstDeclaration();
399  }
400
401  /// \brief Retrieve the anonymous namespace nested inside this namespace,
402  /// if any.
403  NamespaceDecl *getAnonymousNamespace() const {
404    return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
405  }
406
407  void setAnonymousNamespace(NamespaceDecl *D) {
408    getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
409  }
410
411  /// Retrieves the canonical declaration of this namespace.
412  NamespaceDecl *getCanonicalDecl() {
413    return getOriginalNamespace();
414  }
415  const NamespaceDecl *getCanonicalDecl() const {
416    return getOriginalNamespace();
417  }
418
419  virtual SourceRange getSourceRange() const LLVM_READONLY {
420    return SourceRange(LocStart, RBraceLoc);
421  }
422
423  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
424  SourceLocation getRBraceLoc() const { return RBraceLoc; }
425  void setLocStart(SourceLocation L) { LocStart = L; }
426  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
427
428  // Implement isa/cast/dyncast/etc.
429  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
430  static bool classofKind(Kind K) { return K == Namespace; }
431  static DeclContext *castToDeclContext(const NamespaceDecl *D) {
432    return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
433  }
434  static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
435    return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
436  }
437
438  friend class ASTDeclReader;
439  friend class ASTDeclWriter;
440};
441
442/// ValueDecl - Represent the declaration of a variable (in which case it is
443/// an lvalue) a function (in which case it is a function designator) or
444/// an enum constant.
445class ValueDecl : public NamedDecl {
446  virtual void anchor();
447  QualType DeclType;
448
449protected:
450  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
451            DeclarationName N, QualType T)
452    : NamedDecl(DK, DC, L, N), DeclType(T) {}
453public:
454  QualType getType() const { return DeclType; }
455  void setType(QualType newType) { DeclType = newType; }
456
457  /// \brief Determine whether this symbol is weakly-imported,
458  ///        or declared with the weak or weak-ref attr.
459  bool isWeak() const;
460
461  // Implement isa/cast/dyncast/etc.
462  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
463  static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
464};
465
466/// QualifierInfo - A struct with extended info about a syntactic
467/// name qualifier, to be used for the case of out-of-line declarations.
468struct QualifierInfo {
469  NestedNameSpecifierLoc QualifierLoc;
470
471  /// NumTemplParamLists - The number of "outer" template parameter lists.
472  /// The count includes all of the template parameter lists that were matched
473  /// against the template-ids occurring into the NNS and possibly (in the
474  /// case of an explicit specialization) a final "template <>".
475  unsigned NumTemplParamLists;
476
477  /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
478  /// containing pointers to the "outer" template parameter lists.
479  /// It includes all of the template parameter lists that were matched
480  /// against the template-ids occurring into the NNS and possibly (in the
481  /// case of an explicit specialization) a final "template <>".
482  TemplateParameterList** TemplParamLists;
483
484  /// Default constructor.
485  QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
486
487  /// setTemplateParameterListsInfo - Sets info about "outer" template
488  /// parameter lists.
489  void setTemplateParameterListsInfo(ASTContext &Context,
490                                     unsigned NumTPLists,
491                                     TemplateParameterList **TPLists);
492
493private:
494  // Copy constructor and copy assignment are disabled.
495  QualifierInfo(const QualifierInfo&) LLVM_DELETED_FUNCTION;
496  QualifierInfo& operator=(const QualifierInfo&) LLVM_DELETED_FUNCTION;
497};
498
499/// \brief Represents a ValueDecl that came out of a declarator.
500/// Contains type source information through TypeSourceInfo.
501class DeclaratorDecl : public ValueDecl {
502  // A struct representing both a TInfo and a syntactic qualifier,
503  // to be used for the (uncommon) case of out-of-line declarations.
504  struct ExtInfo : public QualifierInfo {
505    TypeSourceInfo *TInfo;
506  };
507
508  llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
509
510  /// InnerLocStart - The start of the source range for this declaration,
511  /// ignoring outer template declarations.
512  SourceLocation InnerLocStart;
513
514  bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
515  ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
516  const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
517
518protected:
519  DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
520                 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
521                 SourceLocation StartL)
522    : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
523  }
524
525public:
526  TypeSourceInfo *getTypeSourceInfo() const {
527    return hasExtInfo()
528      ? getExtInfo()->TInfo
529      : DeclInfo.get<TypeSourceInfo*>();
530  }
531  void setTypeSourceInfo(TypeSourceInfo *TI) {
532    if (hasExtInfo())
533      getExtInfo()->TInfo = TI;
534    else
535      DeclInfo = TI;
536  }
537
538  /// getInnerLocStart - Return SourceLocation representing start of source
539  /// range ignoring outer template declarations.
540  SourceLocation getInnerLocStart() const { return InnerLocStart; }
541  void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
542
543  /// getOuterLocStart - Return SourceLocation representing start of source
544  /// range taking into account any outer template declarations.
545  SourceLocation getOuterLocStart() const;
546
547  virtual SourceRange getSourceRange() const LLVM_READONLY;
548  SourceLocation getLocStart() const LLVM_READONLY {
549    return getOuterLocStart();
550  }
551
552  /// \brief Retrieve the nested-name-specifier that qualifies the name of this
553  /// declaration, if it was present in the source.
554  NestedNameSpecifier *getQualifier() const {
555    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
556                        : 0;
557  }
558
559  /// \brief Retrieve the nested-name-specifier (with source-location
560  /// information) that qualifies the name of this declaration, if it was
561  /// present in the source.
562  NestedNameSpecifierLoc getQualifierLoc() const {
563    return hasExtInfo() ? getExtInfo()->QualifierLoc
564                        : NestedNameSpecifierLoc();
565  }
566
567  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
568
569  unsigned getNumTemplateParameterLists() const {
570    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
571  }
572  TemplateParameterList *getTemplateParameterList(unsigned index) const {
573    assert(index < getNumTemplateParameterLists());
574    return getExtInfo()->TemplParamLists[index];
575  }
576  void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
577                                     TemplateParameterList **TPLists);
578
579  SourceLocation getTypeSpecStartLoc() const;
580
581  // Implement isa/cast/dyncast/etc.
582  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
583  static bool classofKind(Kind K) {
584    return K >= firstDeclarator && K <= lastDeclarator;
585  }
586
587  friend class ASTDeclReader;
588  friend class ASTDeclWriter;
589};
590
591/// \brief Structure used to store a statement, the constant value to
592/// which it was evaluated (if any), and whether or not the statement
593/// is an integral constant expression (if known).
594struct EvaluatedStmt {
595  EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
596                    CheckingICE(false), IsICE(false) { }
597
598  /// \brief Whether this statement was already evaluated.
599  bool WasEvaluated : 1;
600
601  /// \brief Whether this statement is being evaluated.
602  bool IsEvaluating : 1;
603
604  /// \brief Whether we already checked whether this statement was an
605  /// integral constant expression.
606  bool CheckedICE : 1;
607
608  /// \brief Whether we are checking whether this statement is an
609  /// integral constant expression.
610  bool CheckingICE : 1;
611
612  /// \brief Whether this statement is an integral constant expression,
613  /// or in C++11, whether the statement is a constant expression. Only
614  /// valid if CheckedICE is true.
615  bool IsICE : 1;
616
617  Stmt *Value;
618  APValue Evaluated;
619};
620
621/// VarDecl - An instance of this class is created to represent a variable
622/// declaration or definition.
623class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
624public:
625  typedef clang::StorageClass StorageClass;
626
627  /// getStorageClassSpecifierString - Return the string used to
628  /// specify the storage class \p SC.
629  ///
630  /// It is illegal to call this function with SC == None.
631  static const char *getStorageClassSpecifierString(StorageClass SC);
632
633  /// \brief Initialization styles.
634  enum InitializationStyle {
635    CInit,    ///< C-style initialization with assignment
636    CallInit, ///< Call-style initialization (C++98)
637    ListInit  ///< Direct list-initialization (C++11)
638  };
639
640protected:
641  /// \brief Placeholder type used in Init to denote an unparsed C++ default
642  /// argument.
643  struct UnparsedDefaultArgument;
644
645  /// \brief Placeholder type used in Init to denote an uninstantiated C++
646  /// default argument.
647  struct UninstantiatedDefaultArgument;
648
649  typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
650                              UnparsedDefaultArgument *,
651                              UninstantiatedDefaultArgument *> InitType;
652
653  /// \brief The initializer for this variable or, for a ParmVarDecl, the
654  /// C++ default argument.
655  mutable InitType Init;
656
657private:
658  class VarDeclBitfields {
659    friend class VarDecl;
660    friend class ASTDeclReader;
661
662    unsigned SClass : 3;
663    unsigned SClassAsWritten : 3;
664    unsigned ThreadSpecified : 1;
665    unsigned InitStyle : 2;
666
667    /// \brief Whether this variable is the exception variable in a C++ catch
668    /// or an Objective-C @catch statement.
669    unsigned ExceptionVar : 1;
670
671    /// \brief Whether this local variable could be allocated in the return
672    /// slot of its function, enabling the named return value optimization
673    /// (NRVO).
674    unsigned NRVOVariable : 1;
675
676    /// \brief Whether this variable is the for-range-declaration in a C++0x
677    /// for-range statement.
678    unsigned CXXForRangeDecl : 1;
679
680    /// \brief Whether this variable is an ARC pseudo-__strong
681    /// variable;  see isARCPseudoStrong() for details.
682    unsigned ARCPseudoStrong : 1;
683
684    /// \brief Whether this variable is (C++0x) constexpr.
685    unsigned IsConstexpr : 1;
686  };
687  enum { NumVarDeclBits = 14 };
688
689  friend class ASTDeclReader;
690  friend class StmtIteratorBase;
691
692protected:
693  enum { NumParameterIndexBits = 8 };
694
695  class ParmVarDeclBitfields {
696    friend class ParmVarDecl;
697    friend class ASTDeclReader;
698
699    unsigned : NumVarDeclBits;
700
701    /// Whether this parameter inherits a default argument from a
702    /// prior declaration.
703    unsigned HasInheritedDefaultArg : 1;
704
705    /// Whether this parameter undergoes K&R argument promotion.
706    unsigned IsKNRPromoted : 1;
707
708    /// Whether this parameter is an ObjC method parameter or not.
709    unsigned IsObjCMethodParam : 1;
710
711    /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
712    /// Otherwise, the number of function parameter scopes enclosing
713    /// the function parameter scope in which this parameter was
714    /// declared.
715    unsigned ScopeDepthOrObjCQuals : 7;
716
717    /// The number of parameters preceding this parameter in the
718    /// function parameter scope in which it was declared.
719    unsigned ParameterIndex : NumParameterIndexBits;
720  };
721
722  union {
723    unsigned AllBits;
724    VarDeclBitfields VarDeclBits;
725    ParmVarDeclBitfields ParmVarDeclBits;
726  };
727
728  VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
729          SourceLocation IdLoc, IdentifierInfo *Id,
730          QualType T, TypeSourceInfo *TInfo, StorageClass SC,
731          StorageClass SCAsWritten)
732    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
733    assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
734    assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
735    AllBits = 0;
736    VarDeclBits.SClass = SC;
737    VarDeclBits.SClassAsWritten = SCAsWritten;
738    // Everything else is implicitly initialized to false.
739  }
740
741  typedef Redeclarable<VarDecl> redeclarable_base;
742  virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
743  virtual VarDecl *getPreviousDeclImpl() {
744    return getPreviousDecl();
745  }
746  virtual VarDecl *getMostRecentDeclImpl() {
747    return getMostRecentDecl();
748  }
749
750public:
751  typedef redeclarable_base::redecl_iterator redecl_iterator;
752  using redeclarable_base::redecls_begin;
753  using redeclarable_base::redecls_end;
754  using redeclarable_base::getPreviousDecl;
755  using redeclarable_base::getMostRecentDecl;
756
757  static VarDecl *Create(ASTContext &C, DeclContext *DC,
758                         SourceLocation StartLoc, SourceLocation IdLoc,
759                         IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
760                         StorageClass S, StorageClass SCAsWritten);
761
762  static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
763
764  virtual SourceRange getSourceRange() const LLVM_READONLY;
765
766  StorageClass getStorageClass() const {
767    return (StorageClass) VarDeclBits.SClass;
768  }
769  StorageClass getStorageClassAsWritten() const {
770    return (StorageClass) VarDeclBits.SClassAsWritten;
771  }
772  void setStorageClass(StorageClass SC);
773  void setStorageClassAsWritten(StorageClass SC) {
774    assert(isLegalForVariable(SC));
775    VarDeclBits.SClassAsWritten = SC;
776  }
777
778  void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
779  bool isThreadSpecified() const {
780    return VarDeclBits.ThreadSpecified;
781  }
782
783  /// hasLocalStorage - Returns true if a variable with function scope
784  ///  is a non-static local variable.
785  bool hasLocalStorage() const {
786    if (getStorageClass() == SC_None)
787      return !isFileVarDecl();
788
789    // Return true for:  Auto, Register.
790    // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
791
792    return getStorageClass() >= SC_Auto;
793  }
794
795  /// isStaticLocal - Returns true if a variable with function scope is a
796  /// static local variable.
797  bool isStaticLocal() const {
798    return getStorageClass() == SC_Static && !isFileVarDecl();
799  }
800
801  /// \brief Returns true if a variable has extern or __private_extern__
802  /// storage.
803  bool hasExternalStorage() const {
804    return getStorageClass() == SC_Extern ||
805           getStorageClass() == SC_PrivateExtern;
806  }
807
808  /// \brief Returns true if a variable was written with extern or
809  /// __private_extern__ storage.
810  bool hasExternalStorageAsWritten() const {
811    return getStorageClassAsWritten() == SC_Extern ||
812           getStorageClassAsWritten() == SC_PrivateExtern;
813  }
814
815  /// hasGlobalStorage - Returns true for all variables that do not
816  ///  have local storage.  This includs all global variables as well
817  ///  as static variables declared within a function.
818  bool hasGlobalStorage() const { return !hasLocalStorage(); }
819
820  /// Compute the language linkage.
821  LanguageLinkage getLanguageLinkage() const;
822
823  /// \brief Determines whether this variable is a variable with
824  /// external, C linkage.
825  bool isExternC() const;
826
827  /// isLocalVarDecl - Returns true for local variable declarations
828  /// other than parameters.  Note that this includes static variables
829  /// inside of functions. It also includes variables inside blocks.
830  ///
831  ///   void foo() { int x; static int y; extern int z; }
832  ///
833  bool isLocalVarDecl() const {
834    if (getKind() != Decl::Var)
835      return false;
836    if (const DeclContext *DC = getDeclContext())
837      return DC->getRedeclContext()->isFunctionOrMethod();
838    return false;
839  }
840
841  /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
842  /// excludes variables declared in blocks.
843  bool isFunctionOrMethodVarDecl() const {
844    if (getKind() != Decl::Var)
845      return false;
846    const DeclContext *DC = getDeclContext()->getRedeclContext();
847    return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
848  }
849
850  /// \brief Determines whether this is a static data member.
851  ///
852  /// This will only be true in C++, and applies to, e.g., the
853  /// variable 'x' in:
854  /// \code
855  /// struct S {
856  ///   static int x;
857  /// };
858  /// \endcode
859  bool isStaticDataMember() const {
860    // If it wasn't static, it would be a FieldDecl.
861    return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
862  }
863
864  virtual VarDecl *getCanonicalDecl();
865  const VarDecl *getCanonicalDecl() const {
866    return const_cast<VarDecl*>(this)->getCanonicalDecl();
867  }
868
869  enum DefinitionKind {
870    DeclarationOnly,      ///< This declaration is only a declaration.
871    TentativeDefinition,  ///< This declaration is a tentative definition.
872    Definition            ///< This declaration is definitely a definition.
873  };
874
875  /// \brief Check whether this declaration is a definition. If this could be
876  /// a tentative definition (in C), don't check whether there's an overriding
877  /// definition.
878  DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
879  DefinitionKind isThisDeclarationADefinition() const {
880    return isThisDeclarationADefinition(getASTContext());
881  }
882
883  /// \brief Check whether this variable is defined in this
884  /// translation unit.
885  DefinitionKind hasDefinition(ASTContext &) const;
886  DefinitionKind hasDefinition() const {
887    return hasDefinition(getASTContext());
888  }
889
890  /// \brief Get the tentative definition that acts as the real definition in
891  /// a TU. Returns null if there is a proper definition available.
892  VarDecl *getActingDefinition();
893  const VarDecl *getActingDefinition() const {
894    return const_cast<VarDecl*>(this)->getActingDefinition();
895  }
896
897  /// \brief Determine whether this is a tentative definition of a
898  /// variable in C.
899  bool isTentativeDefinitionNow() const;
900
901  /// \brief Get the real (not just tentative) definition for this declaration.
902  VarDecl *getDefinition(ASTContext &);
903  const VarDecl *getDefinition(ASTContext &C) const {
904    return const_cast<VarDecl*>(this)->getDefinition(C);
905  }
906  VarDecl *getDefinition() {
907    return getDefinition(getASTContext());
908  }
909  const VarDecl *getDefinition() const {
910    return const_cast<VarDecl*>(this)->getDefinition();
911  }
912
913  /// \brief Determine whether this is or was instantiated from an out-of-line
914  /// definition of a static data member.
915  virtual bool isOutOfLine() const;
916
917  /// \brief If this is a static data member, find its out-of-line definition.
918  VarDecl *getOutOfLineDefinition();
919
920  /// isFileVarDecl - Returns true for file scoped variable declaration.
921  bool isFileVarDecl() const {
922    if (getKind() != Decl::Var)
923      return false;
924
925    if (getDeclContext()->getRedeclContext()->isFileContext())
926      return true;
927
928    if (isStaticDataMember())
929      return true;
930
931    return false;
932  }
933
934  /// getAnyInitializer - Get the initializer for this variable, no matter which
935  /// declaration it is attached to.
936  const Expr *getAnyInitializer() const {
937    const VarDecl *D;
938    return getAnyInitializer(D);
939  }
940
941  /// getAnyInitializer - Get the initializer for this variable, no matter which
942  /// declaration it is attached to. Also get that declaration.
943  const Expr *getAnyInitializer(const VarDecl *&D) const;
944
945  bool hasInit() const {
946    return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
947  }
948  const Expr *getInit() const {
949    if (Init.isNull())
950      return 0;
951
952    const Stmt *S = Init.dyn_cast<Stmt *>();
953    if (!S) {
954      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
955        S = ES->Value;
956    }
957    return (const Expr*) S;
958  }
959  Expr *getInit() {
960    if (Init.isNull())
961      return 0;
962
963    Stmt *S = Init.dyn_cast<Stmt *>();
964    if (!S) {
965      if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
966        S = ES->Value;
967    }
968
969    return (Expr*) S;
970  }
971
972  /// \brief Retrieve the address of the initializer expression.
973  Stmt **getInitAddress() {
974    if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
975      return &ES->Value;
976
977    // This union hack tip-toes around strict-aliasing rules.
978    union {
979      InitType *InitPtr;
980      Stmt **StmtPtr;
981    };
982
983    InitPtr = &Init;
984    return StmtPtr;
985  }
986
987  void setInit(Expr *I);
988
989  /// \brief Determine whether this variable is a reference that
990  /// extends the lifetime of its temporary initializer.
991  ///
992  /// A reference extends the lifetime of its temporary initializer if
993  /// it's initializer is an rvalue that would normally go out of scope
994  /// at the end of the initializer (a full expression). In such cases,
995  /// the reference itself takes ownership of the temporary, which will
996  /// be destroyed when the reference goes out of scope. For example:
997  ///
998  /// \code
999  /// const int &r = 1.0; // creates a temporary of type 'int'
1000  /// \endcode
1001  bool extendsLifetimeOfTemporary() const;
1002
1003  /// \brief Determine whether this variable's value can be used in a
1004  /// constant expression, according to the relevant language standard.
1005  /// This only checks properties of the declaration, and does not check
1006  /// whether the initializer is in fact a constant expression.
1007  bool isUsableInConstantExpressions(ASTContext &C) const;
1008
1009  EvaluatedStmt *ensureEvaluatedStmt() const;
1010
1011  /// \brief Attempt to evaluate the value of the initializer attached to this
1012  /// declaration, and produce notes explaining why it cannot be evaluated or is
1013  /// not a constant expression. Returns a pointer to the value if evaluation
1014  /// succeeded, 0 otherwise.
1015  APValue *evaluateValue() const;
1016  APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1017
1018  /// \brief Return the already-evaluated value of this variable's
1019  /// initializer, or NULL if the value is not yet known. Returns pointer
1020  /// to untyped APValue if the value could not be evaluated.
1021  APValue *getEvaluatedValue() const {
1022    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1023      if (Eval->WasEvaluated)
1024        return &Eval->Evaluated;
1025
1026    return 0;
1027  }
1028
1029  /// \brief Determines whether it is already known whether the
1030  /// initializer is an integral constant expression or not.
1031  bool isInitKnownICE() const {
1032    if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1033      return Eval->CheckedICE;
1034
1035    return false;
1036  }
1037
1038  /// \brief Determines whether the initializer is an integral constant
1039  /// expression, or in C++11, whether the initializer is a constant
1040  /// expression.
1041  ///
1042  /// \pre isInitKnownICE()
1043  bool isInitICE() const {
1044    assert(isInitKnownICE() &&
1045           "Check whether we already know that the initializer is an ICE");
1046    return Init.get<EvaluatedStmt *>()->IsICE;
1047  }
1048
1049  /// \brief Determine whether the value of the initializer attached to this
1050  /// declaration is an integral constant expression.
1051  bool checkInitIsICE() const;
1052
1053  void setInitStyle(InitializationStyle Style) {
1054    VarDeclBits.InitStyle = Style;
1055  }
1056
1057  /// \brief The style of initialization for this declaration.
1058  ///
1059  /// C-style initialization is "int x = 1;". Call-style initialization is
1060  /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1061  /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1062  /// expression for class types. List-style initialization is C++11 syntax,
1063  /// e.g. "int x{1};". Clients can distinguish between different forms of
1064  /// initialization by checking this value. In particular, "int x = {1};" is
1065  /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1066  /// Init expression in all three cases is an InitListExpr.
1067  InitializationStyle getInitStyle() const {
1068    return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1069  }
1070
1071  /// \brief Whether the initializer is a direct-initializer (list or call).
1072  bool isDirectInit() const {
1073    return getInitStyle() != CInit;
1074  }
1075
1076  /// \brief Determine whether this variable is the exception variable in a
1077  /// C++ catch statememt or an Objective-C \@catch statement.
1078  bool isExceptionVariable() const {
1079    return VarDeclBits.ExceptionVar;
1080  }
1081  void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1082
1083  /// \brief Determine whether this local variable can be used with the named
1084  /// return value optimization (NRVO).
1085  ///
1086  /// The named return value optimization (NRVO) works by marking certain
1087  /// non-volatile local variables of class type as NRVO objects. These
1088  /// locals can be allocated within the return slot of their containing
1089  /// function, in which case there is no need to copy the object to the
1090  /// return slot when returning from the function. Within the function body,
1091  /// each return that returns the NRVO object will have this variable as its
1092  /// NRVO candidate.
1093  bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1094  void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1095
1096  /// \brief Determine whether this variable is the for-range-declaration in
1097  /// a C++0x for-range statement.
1098  bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1099  void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1100
1101  /// \brief Determine whether this variable is an ARC pseudo-__strong
1102  /// variable.  A pseudo-__strong variable has a __strong-qualified
1103  /// type but does not actually retain the object written into it.
1104  /// Generally such variables are also 'const' for safety.
1105  bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1106  void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1107
1108  /// Whether this variable is (C++11) constexpr.
1109  bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
1110  void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1111
1112  /// \brief If this variable is an instantiated static data member of a
1113  /// class template specialization, returns the templated static data member
1114  /// from which it was instantiated.
1115  VarDecl *getInstantiatedFromStaticDataMember() const;
1116
1117  /// \brief If this variable is a static data member, determine what kind of
1118  /// template specialization or instantiation this is.
1119  TemplateSpecializationKind getTemplateSpecializationKind() const;
1120
1121  /// \brief If this variable is an instantiation of a static data member of a
1122  /// class template specialization, retrieves the member specialization
1123  /// information.
1124  MemberSpecializationInfo *getMemberSpecializationInfo() const;
1125
1126  /// \brief For a static data member that was instantiated from a static
1127  /// data member of a class template, set the template specialiation kind.
1128  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1129                        SourceLocation PointOfInstantiation = SourceLocation());
1130
1131  // Implement isa/cast/dyncast/etc.
1132  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1133  static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1134};
1135
1136class ImplicitParamDecl : public VarDecl {
1137  virtual void anchor();
1138public:
1139  static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1140                                   SourceLocation IdLoc, IdentifierInfo *Id,
1141                                   QualType T);
1142
1143  static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1144
1145  ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1146                    IdentifierInfo *Id, QualType Type)
1147    : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1148              /*tinfo*/ 0, SC_None, SC_None) {
1149    setImplicit();
1150  }
1151
1152  // Implement isa/cast/dyncast/etc.
1153  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1154  static bool classofKind(Kind K) { return K == ImplicitParam; }
1155};
1156
1157/// ParmVarDecl - Represents a parameter to a function.
1158class ParmVarDecl : public VarDecl {
1159public:
1160  enum { MaxFunctionScopeDepth = 255 };
1161  enum { MaxFunctionScopeIndex = 255 };
1162
1163protected:
1164  ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1165              SourceLocation IdLoc, IdentifierInfo *Id,
1166              QualType T, TypeSourceInfo *TInfo,
1167              StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
1168    : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) {
1169    assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1170    assert(ParmVarDeclBits.IsKNRPromoted == false);
1171    assert(ParmVarDeclBits.IsObjCMethodParam == false);
1172    setDefaultArg(DefArg);
1173  }
1174
1175public:
1176  static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1177                             SourceLocation StartLoc,
1178                             SourceLocation IdLoc, IdentifierInfo *Id,
1179                             QualType T, TypeSourceInfo *TInfo,
1180                             StorageClass S, StorageClass SCAsWritten,
1181                             Expr *DefArg);
1182
1183  static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1184
1185  virtual SourceRange getSourceRange() const LLVM_READONLY;
1186
1187  void setObjCMethodScopeInfo(unsigned parameterIndex) {
1188    ParmVarDeclBits.IsObjCMethodParam = true;
1189    setParameterIndex(parameterIndex);
1190  }
1191
1192  void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1193    assert(!ParmVarDeclBits.IsObjCMethodParam);
1194
1195    ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1196    assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1197           && "truncation!");
1198
1199    setParameterIndex(parameterIndex);
1200  }
1201
1202  bool isObjCMethodParameter() const {
1203    return ParmVarDeclBits.IsObjCMethodParam;
1204  }
1205
1206  unsigned getFunctionScopeDepth() const {
1207    if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1208    return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1209  }
1210
1211  /// Returns the index of this parameter in its prototype or method scope.
1212  unsigned getFunctionScopeIndex() const {
1213    return getParameterIndex();
1214  }
1215
1216  ObjCDeclQualifier getObjCDeclQualifier() const {
1217    if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1218    return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1219  }
1220  void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1221    assert(ParmVarDeclBits.IsObjCMethodParam);
1222    ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1223  }
1224
1225  /// True if the value passed to this parameter must undergo
1226  /// K&R-style default argument promotion:
1227  ///
1228  /// C99 6.5.2.2.
1229  ///   If the expression that denotes the called function has a type
1230  ///   that does not include a prototype, the integer promotions are
1231  ///   performed on each argument, and arguments that have type float
1232  ///   are promoted to double.
1233  bool isKNRPromoted() const {
1234    return ParmVarDeclBits.IsKNRPromoted;
1235  }
1236  void setKNRPromoted(bool promoted) {
1237    ParmVarDeclBits.IsKNRPromoted = promoted;
1238  }
1239
1240  Expr *getDefaultArg();
1241  const Expr *getDefaultArg() const {
1242    return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1243  }
1244
1245  void setDefaultArg(Expr *defarg) {
1246    Init = reinterpret_cast<Stmt *>(defarg);
1247  }
1248
1249  /// \brief Retrieve the source range that covers the entire default
1250  /// argument.
1251  SourceRange getDefaultArgRange() const;
1252  void setUninstantiatedDefaultArg(Expr *arg) {
1253    Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1254  }
1255  Expr *getUninstantiatedDefaultArg() {
1256    return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1257  }
1258  const Expr *getUninstantiatedDefaultArg() const {
1259    return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1260  }
1261
1262  /// hasDefaultArg - Determines whether this parameter has a default argument,
1263  /// either parsed or not.
1264  bool hasDefaultArg() const {
1265    return getInit() || hasUnparsedDefaultArg() ||
1266      hasUninstantiatedDefaultArg();
1267  }
1268
1269  /// hasUnparsedDefaultArg - Determines whether this parameter has a
1270  /// default argument that has not yet been parsed. This will occur
1271  /// during the processing of a C++ class whose member functions have
1272  /// default arguments, e.g.,
1273  /// @code
1274  ///   class X {
1275  ///   public:
1276  ///     void f(int x = 17); // x has an unparsed default argument now
1277  ///   }; // x has a regular default argument now
1278  /// @endcode
1279  bool hasUnparsedDefaultArg() const {
1280    return Init.is<UnparsedDefaultArgument*>();
1281  }
1282
1283  bool hasUninstantiatedDefaultArg() const {
1284    return Init.is<UninstantiatedDefaultArgument*>();
1285  }
1286
1287  /// setUnparsedDefaultArg - Specify that this parameter has an
1288  /// unparsed default argument. The argument will be replaced with a
1289  /// real default argument via setDefaultArg when the class
1290  /// definition enclosing the function declaration that owns this
1291  /// default argument is completed.
1292  void setUnparsedDefaultArg() {
1293    Init = (UnparsedDefaultArgument *)0;
1294  }
1295
1296  bool hasInheritedDefaultArg() const {
1297    return ParmVarDeclBits.HasInheritedDefaultArg;
1298  }
1299
1300  void setHasInheritedDefaultArg(bool I = true) {
1301    ParmVarDeclBits.HasInheritedDefaultArg = I;
1302  }
1303
1304  QualType getOriginalType() const {
1305    if (getTypeSourceInfo())
1306      return getTypeSourceInfo()->getType();
1307    return getType();
1308  }
1309
1310  /// \brief Determine whether this parameter is actually a function
1311  /// parameter pack.
1312  bool isParameterPack() const;
1313
1314  /// setOwningFunction - Sets the function declaration that owns this
1315  /// ParmVarDecl. Since ParmVarDecls are often created before the
1316  /// FunctionDecls that own them, this routine is required to update
1317  /// the DeclContext appropriately.
1318  void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1319
1320  // Implement isa/cast/dyncast/etc.
1321  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1322  static bool classofKind(Kind K) { return K == ParmVar; }
1323
1324private:
1325  enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1326
1327  void setParameterIndex(unsigned parameterIndex) {
1328    if (parameterIndex >= ParameterIndexSentinel) {
1329      setParameterIndexLarge(parameterIndex);
1330      return;
1331    }
1332
1333    ParmVarDeclBits.ParameterIndex = parameterIndex;
1334    assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1335  }
1336  unsigned getParameterIndex() const {
1337    unsigned d = ParmVarDeclBits.ParameterIndex;
1338    return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1339  }
1340
1341  void setParameterIndexLarge(unsigned parameterIndex);
1342  unsigned getParameterIndexLarge() const;
1343};
1344
1345/// FunctionDecl - An instance of this class is created to represent a
1346/// function declaration or definition.
1347///
1348/// Since a given function can be declared several times in a program,
1349/// there may be several FunctionDecls that correspond to that
1350/// function. Only one of those FunctionDecls will be found when
1351/// traversing the list of declarations in the context of the
1352/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1353/// contains all of the information known about the function. Other,
1354/// previous declarations of the function are available via the
1355/// getPreviousDecl() chain.
1356class FunctionDecl : public DeclaratorDecl, public DeclContext,
1357                     public Redeclarable<FunctionDecl> {
1358public:
1359  typedef clang::StorageClass StorageClass;
1360
1361  /// \brief The kind of templated function a FunctionDecl can be.
1362  enum TemplatedKind {
1363    TK_NonTemplate,
1364    TK_FunctionTemplate,
1365    TK_MemberSpecialization,
1366    TK_FunctionTemplateSpecialization,
1367    TK_DependentFunctionTemplateSpecialization
1368  };
1369
1370private:
1371  /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1372  /// parameters of this function.  This is null if a prototype or if there are
1373  /// no formals.
1374  ParmVarDecl **ParamInfo;
1375
1376  /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
1377  /// decls defined in the function prototype that are not parameters. E.g.
1378  /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
1379  ArrayRef<NamedDecl *> DeclsInPrototypeScope;
1380
1381  LazyDeclStmtPtr Body;
1382
1383  // FIXME: This can be packed into the bitfields in Decl.
1384  // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1385  unsigned SClass : 2;
1386  unsigned SClassAsWritten : 2;
1387  bool IsInline : 1;
1388  bool IsInlineSpecified : 1;
1389  bool IsVirtualAsWritten : 1;
1390  bool IsPure : 1;
1391  bool HasInheritedPrototype : 1;
1392  bool HasWrittenPrototype : 1;
1393  bool IsDeleted : 1;
1394  bool IsTrivial : 1; // sunk from CXXMethodDecl
1395  bool IsDefaulted : 1; // sunk from CXXMethoDecl
1396  bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1397  bool HasImplicitReturnZero : 1;
1398  bool IsLateTemplateParsed : 1;
1399  bool IsConstexpr : 1;
1400
1401  /// \brief Indicates if the function was a definition but its body was
1402  /// skipped.
1403  unsigned HasSkippedBody : 1;
1404
1405  /// \brief End part of this FunctionDecl's source range.
1406  ///
1407  /// We could compute the full range in getSourceRange(). However, when we're
1408  /// dealing with a function definition deserialized from a PCH/AST file,
1409  /// we can only compute the full range once the function body has been
1410  /// de-serialized, so it's far better to have the (sometimes-redundant)
1411  /// EndRangeLoc.
1412  SourceLocation EndRangeLoc;
1413
1414  /// \brief The template or declaration that this declaration
1415  /// describes or was instantiated from, respectively.
1416  ///
1417  /// For non-templates, this value will be NULL. For function
1418  /// declarations that describe a function template, this will be a
1419  /// pointer to a FunctionTemplateDecl. For member functions
1420  /// of class template specializations, this will be a MemberSpecializationInfo
1421  /// pointer containing information about the specialization.
1422  /// For function template specializations, this will be a
1423  /// FunctionTemplateSpecializationInfo, which contains information about
1424  /// the template being specialized and the template arguments involved in
1425  /// that specialization.
1426  llvm::PointerUnion4<FunctionTemplateDecl *,
1427                      MemberSpecializationInfo *,
1428                      FunctionTemplateSpecializationInfo *,
1429                      DependentFunctionTemplateSpecializationInfo *>
1430    TemplateOrSpecialization;
1431
1432  /// DNLoc - Provides source/type location info for the
1433  /// declaration name embedded in the DeclaratorDecl base class.
1434  DeclarationNameLoc DNLoc;
1435
1436  /// \brief Specify that this function declaration is actually a function
1437  /// template specialization.
1438  ///
1439  /// \param C the ASTContext.
1440  ///
1441  /// \param Template the function template that this function template
1442  /// specialization specializes.
1443  ///
1444  /// \param TemplateArgs the template arguments that produced this
1445  /// function template specialization from the template.
1446  ///
1447  /// \param InsertPos If non-NULL, the position in the function template
1448  /// specialization set where the function template specialization data will
1449  /// be inserted.
1450  ///
1451  /// \param TSK the kind of template specialization this is.
1452  ///
1453  /// \param TemplateArgsAsWritten location info of template arguments.
1454  ///
1455  /// \param PointOfInstantiation point at which the function template
1456  /// specialization was first instantiated.
1457  void setFunctionTemplateSpecialization(ASTContext &C,
1458                                         FunctionTemplateDecl *Template,
1459                                       const TemplateArgumentList *TemplateArgs,
1460                                         void *InsertPos,
1461                                         TemplateSpecializationKind TSK,
1462                          const TemplateArgumentListInfo *TemplateArgsAsWritten,
1463                                         SourceLocation PointOfInstantiation);
1464
1465  /// \brief Specify that this record is an instantiation of the
1466  /// member function FD.
1467  void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1468                                        TemplateSpecializationKind TSK);
1469
1470  void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1471
1472protected:
1473  FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1474               const DeclarationNameInfo &NameInfo,
1475               QualType T, TypeSourceInfo *TInfo,
1476               StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified,
1477               bool isConstexprSpecified)
1478    : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1479                     StartLoc),
1480      DeclContext(DK),
1481      ParamInfo(0), Body(),
1482      SClass(S), SClassAsWritten(SCAsWritten),
1483      IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1484      IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1485      HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1486      IsDefaulted(false), IsExplicitlyDefaulted(false),
1487      HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1488      IsConstexpr(isConstexprSpecified), HasSkippedBody(false),
1489      EndRangeLoc(NameInfo.getEndLoc()),
1490      TemplateOrSpecialization(),
1491      DNLoc(NameInfo.getInfo()) {}
1492
1493  typedef Redeclarable<FunctionDecl> redeclarable_base;
1494  virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1495  virtual FunctionDecl *getPreviousDeclImpl() {
1496    return getPreviousDecl();
1497  }
1498  virtual FunctionDecl *getMostRecentDeclImpl() {
1499    return getMostRecentDecl();
1500  }
1501
1502public:
1503  typedef redeclarable_base::redecl_iterator redecl_iterator;
1504  using redeclarable_base::redecls_begin;
1505  using redeclarable_base::redecls_end;
1506  using redeclarable_base::getPreviousDecl;
1507  using redeclarable_base::getMostRecentDecl;
1508
1509  static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1510                              SourceLocation StartLoc, SourceLocation NLoc,
1511                              DeclarationName N, QualType T,
1512                              TypeSourceInfo *TInfo,
1513                              StorageClass SC,
1514                              StorageClass SCAsWritten,
1515                              bool isInlineSpecified = false,
1516                              bool hasWrittenPrototype = true,
1517                              bool isConstexprSpecified = false) {
1518    DeclarationNameInfo NameInfo(N, NLoc);
1519    return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1520                                SC, SCAsWritten,
1521                                isInlineSpecified, hasWrittenPrototype,
1522                                isConstexprSpecified);
1523  }
1524
1525  static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1526                              SourceLocation StartLoc,
1527                              const DeclarationNameInfo &NameInfo,
1528                              QualType T, TypeSourceInfo *TInfo,
1529                              StorageClass SC,
1530                              StorageClass SCAsWritten,
1531                              bool isInlineSpecified,
1532                              bool hasWrittenPrototype,
1533                              bool isConstexprSpecified = false);
1534
1535  static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1536
1537  DeclarationNameInfo getNameInfo() const {
1538    return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1539  }
1540
1541  virtual void getNameForDiagnostic(raw_ostream &OS,
1542                                    const PrintingPolicy &Policy,
1543                                    bool Qualified) const;
1544
1545  void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1546
1547  virtual SourceRange getSourceRange() const LLVM_READONLY;
1548
1549  /// \brief Returns true if the function has a body (definition). The
1550  /// function body might be in any of the (re-)declarations of this
1551  /// function. The variant that accepts a FunctionDecl pointer will
1552  /// set that function declaration to the actual declaration
1553  /// containing the body (if there is one).
1554  bool hasBody(const FunctionDecl *&Definition) const;
1555
1556  virtual bool hasBody() const {
1557    const FunctionDecl* Definition;
1558    return hasBody(Definition);
1559  }
1560
1561  /// hasTrivialBody - Returns whether the function has a trivial body that does
1562  /// not require any specific codegen.
1563  bool hasTrivialBody() const;
1564
1565  /// isDefined - Returns true if the function is defined at all, including
1566  /// a deleted definition. Except for the behavior when the function is
1567  /// deleted, behaves like hasBody.
1568  bool isDefined(const FunctionDecl *&Definition) const;
1569
1570  virtual bool isDefined() const {
1571    const FunctionDecl* Definition;
1572    return isDefined(Definition);
1573  }
1574
1575  /// getBody - Retrieve the body (definition) of the function. The
1576  /// function body might be in any of the (re-)declarations of this
1577  /// function. The variant that accepts a FunctionDecl pointer will
1578  /// set that function declaration to the actual declaration
1579  /// containing the body (if there is one).
1580  /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1581  /// unnecessary AST de-serialization of the body.
1582  Stmt *getBody(const FunctionDecl *&Definition) const;
1583
1584  virtual Stmt *getBody() const {
1585    const FunctionDecl* Definition;
1586    return getBody(Definition);
1587  }
1588
1589  /// isThisDeclarationADefinition - Returns whether this specific
1590  /// declaration of the function is also a definition. This does not
1591  /// determine whether the function has been defined (e.g., in a
1592  /// previous definition); for that information, use isDefined. Note
1593  /// that this returns false for a defaulted function unless that function
1594  /// has been implicitly defined (possibly as deleted).
1595  bool isThisDeclarationADefinition() const {
1596    return IsDeleted || Body || IsLateTemplateParsed;
1597  }
1598
1599  /// doesThisDeclarationHaveABody - Returns whether this specific
1600  /// declaration of the function has a body - that is, if it is a non-
1601  /// deleted definition.
1602  bool doesThisDeclarationHaveABody() const {
1603    return Body || IsLateTemplateParsed;
1604  }
1605
1606  void setBody(Stmt *B);
1607  void setLazyBody(uint64_t Offset) { Body = Offset; }
1608
1609  /// Whether this function is variadic.
1610  bool isVariadic() const;
1611
1612  /// Whether this function is marked as virtual explicitly.
1613  bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1614  void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1615
1616  /// Whether this virtual function is pure, i.e. makes the containing class
1617  /// abstract.
1618  bool isPure() const { return IsPure; }
1619  void setPure(bool P = true);
1620
1621  /// Whether this templated function will be late parsed.
1622  bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1623  void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1624
1625  /// Whether this function is "trivial" in some specialized C++ senses.
1626  /// Can only be true for default constructors, copy constructors,
1627  /// copy assignment operators, and destructors.  Not meaningful until
1628  /// the class has been fully built by Sema.
1629  bool isTrivial() const { return IsTrivial; }
1630  void setTrivial(bool IT) { IsTrivial = IT; }
1631
1632  /// Whether this function is defaulted per C++0x. Only valid for
1633  /// special member functions.
1634  bool isDefaulted() const { return IsDefaulted; }
1635  void setDefaulted(bool D = true) { IsDefaulted = D; }
1636
1637  /// Whether this function is explicitly defaulted per C++0x. Only valid
1638  /// for special member functions.
1639  bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1640  void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1641
1642  /// Whether falling off this function implicitly returns null/zero.
1643  /// If a more specific implicit return value is required, front-ends
1644  /// should synthesize the appropriate return statements.
1645  bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1646  void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1647
1648  /// \brief Whether this function has a prototype, either because one
1649  /// was explicitly written or because it was "inherited" by merging
1650  /// a declaration without a prototype with a declaration that has a
1651  /// prototype.
1652  bool hasPrototype() const {
1653    return HasWrittenPrototype || HasInheritedPrototype;
1654  }
1655
1656  bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1657
1658  /// \brief Whether this function inherited its prototype from a
1659  /// previous declaration.
1660  bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1661  void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1662
1663  /// Whether this is a (C++11) constexpr function or constexpr constructor.
1664  bool isConstexpr() const { return IsConstexpr; }
1665  void setConstexpr(bool IC) { IsConstexpr = IC; }
1666
1667  /// \brief Whether this function has been deleted.
1668  ///
1669  /// A function that is "deleted" (via the C++0x "= delete" syntax)
1670  /// acts like a normal function, except that it cannot actually be
1671  /// called or have its address taken. Deleted functions are
1672  /// typically used in C++ overload resolution to attract arguments
1673  /// whose type or lvalue/rvalue-ness would permit the use of a
1674  /// different overload that would behave incorrectly. For example,
1675  /// one might use deleted functions to ban implicit conversion from
1676  /// a floating-point number to an Integer type:
1677  ///
1678  /// @code
1679  /// struct Integer {
1680  ///   Integer(long); // construct from a long
1681  ///   Integer(double) = delete; // no construction from float or double
1682  ///   Integer(long double) = delete; // no construction from long double
1683  /// };
1684  /// @endcode
1685  // If a function is deleted, its first declaration must be.
1686  bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1687  bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1688  void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1689
1690  /// \brief Determines whether this function is "main", which is the
1691  /// entry point into an executable program.
1692  bool isMain() const;
1693
1694  /// \brief Determines whether this operator new or delete is one
1695  /// of the reserved global placement operators:
1696  ///    void *operator new(size_t, void *);
1697  ///    void *operator new[](size_t, void *);
1698  ///    void operator delete(void *, void *);
1699  ///    void operator delete[](void *, void *);
1700  /// These functions have special behavior under [new.delete.placement]:
1701  ///    These functions are reserved, a C++ program may not define
1702  ///    functions that displace the versions in the Standard C++ library.
1703  ///    The provisions of [basic.stc.dynamic] do not apply to these
1704  ///    reserved placement forms of operator new and operator delete.
1705  ///
1706  /// This function must be an allocation or deallocation function.
1707  bool isReservedGlobalPlacementOperator() const;
1708
1709  /// Compute the language linkage.
1710  LanguageLinkage getLanguageLinkage() const;
1711
1712  /// \brief Determines whether this function is a function with
1713  /// external, C linkage.
1714  bool isExternC() const;
1715
1716  /// \brief Determines whether this is a global function.
1717  bool isGlobal() const;
1718
1719  /// \brief Determines whether this function is known to be 'noreturn', through
1720  /// an attribute on its declaration or its type.
1721  bool isNoReturn() const;
1722
1723  /// \brief True if the function was a definition but its body was skipped.
1724  bool hasSkippedBody() const { return HasSkippedBody; }
1725  void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
1726
1727  void setPreviousDeclaration(FunctionDecl * PrevDecl);
1728
1729  virtual const FunctionDecl *getCanonicalDecl() const;
1730  virtual FunctionDecl *getCanonicalDecl();
1731
1732  unsigned getBuiltinID() const;
1733
1734  // Iterator access to formal parameters.
1735  unsigned param_size() const { return getNumParams(); }
1736  typedef ParmVarDecl **param_iterator;
1737  typedef ParmVarDecl * const *param_const_iterator;
1738
1739  param_iterator param_begin() { return ParamInfo; }
1740  param_iterator param_end()   { return ParamInfo+param_size(); }
1741
1742  param_const_iterator param_begin() const { return ParamInfo; }
1743  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1744
1745  /// getNumParams - Return the number of parameters this function must have
1746  /// based on its FunctionType.  This is the length of the ParamInfo array
1747  /// after it has been created.
1748  unsigned getNumParams() const;
1749
1750  const ParmVarDecl *getParamDecl(unsigned i) const {
1751    assert(i < getNumParams() && "Illegal param #");
1752    return ParamInfo[i];
1753  }
1754  ParmVarDecl *getParamDecl(unsigned i) {
1755    assert(i < getNumParams() && "Illegal param #");
1756    return ParamInfo[i];
1757  }
1758  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
1759    setParams(getASTContext(), NewParamInfo);
1760  }
1761
1762  const ArrayRef<NamedDecl *> &getDeclsInPrototypeScope() const {
1763    return DeclsInPrototypeScope;
1764  }
1765  void setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls);
1766
1767  /// getMinRequiredArguments - Returns the minimum number of arguments
1768  /// needed to call this function. This may be fewer than the number of
1769  /// function parameters, if some of the parameters have default
1770  /// arguments (in C++).
1771  unsigned getMinRequiredArguments() const;
1772
1773  QualType getResultType() const {
1774    return getType()->getAs<FunctionType>()->getResultType();
1775  }
1776
1777  /// \brief Determine the type of an expression that calls this function.
1778  QualType getCallResultType() const {
1779    return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1780  }
1781
1782  StorageClass getStorageClass() const { return StorageClass(SClass); }
1783  void setStorageClass(StorageClass SC);
1784
1785  StorageClass getStorageClassAsWritten() const {
1786    return StorageClass(SClassAsWritten);
1787  }
1788
1789  /// \brief Determine whether the "inline" keyword was specified for this
1790  /// function.
1791  bool isInlineSpecified() const { return IsInlineSpecified; }
1792
1793  /// Set whether the "inline" keyword was specified for this function.
1794  void setInlineSpecified(bool I) {
1795    IsInlineSpecified = I;
1796    IsInline = I;
1797  }
1798
1799  /// Flag that this function is implicitly inline.
1800  void setImplicitlyInline() {
1801    IsInline = true;
1802  }
1803
1804  /// \brief Determine whether this function should be inlined, because it is
1805  /// either marked "inline" or "constexpr" or is a member function of a class
1806  /// that was defined in the class body.
1807  bool isInlined() const { return IsInline; }
1808
1809  bool isInlineDefinitionExternallyVisible() const;
1810
1811  bool doesDeclarationForceExternallyVisibleDefinition() const;
1812
1813  /// isOverloadedOperator - Whether this function declaration
1814  /// represents an C++ overloaded operator, e.g., "operator+".
1815  bool isOverloadedOperator() const {
1816    return getOverloadedOperator() != OO_None;
1817  }
1818
1819  OverloadedOperatorKind getOverloadedOperator() const;
1820
1821  const IdentifierInfo *getLiteralIdentifier() const;
1822
1823  /// \brief If this function is an instantiation of a member function
1824  /// of a class template specialization, retrieves the function from
1825  /// which it was instantiated.
1826  ///
1827  /// This routine will return non-NULL for (non-templated) member
1828  /// functions of class templates and for instantiations of function
1829  /// templates. For example, given:
1830  ///
1831  /// \code
1832  /// template<typename T>
1833  /// struct X {
1834  ///   void f(T);
1835  /// };
1836  /// \endcode
1837  ///
1838  /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1839  /// whose parent is the class template specialization X<int>. For
1840  /// this declaration, getInstantiatedFromFunction() will return
1841  /// the FunctionDecl X<T>::A. When a complete definition of
1842  /// X<int>::A is required, it will be instantiated from the
1843  /// declaration returned by getInstantiatedFromMemberFunction().
1844  FunctionDecl *getInstantiatedFromMemberFunction() const;
1845
1846  /// \brief What kind of templated function this is.
1847  TemplatedKind getTemplatedKind() const;
1848
1849  /// \brief If this function is an instantiation of a member function of a
1850  /// class template specialization, retrieves the member specialization
1851  /// information.
1852  MemberSpecializationInfo *getMemberSpecializationInfo() const {
1853    return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1854  }
1855
1856  /// \brief Specify that this record is an instantiation of the
1857  /// member function FD.
1858  void setInstantiationOfMemberFunction(FunctionDecl *FD,
1859                                        TemplateSpecializationKind TSK) {
1860    setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1861  }
1862
1863  /// \brief Retrieves the function template that is described by this
1864  /// function declaration.
1865  ///
1866  /// Every function template is represented as a FunctionTemplateDecl
1867  /// and a FunctionDecl (or something derived from FunctionDecl). The
1868  /// former contains template properties (such as the template
1869  /// parameter lists) while the latter contains the actual
1870  /// description of the template's
1871  /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1872  /// FunctionDecl that describes the function template,
1873  /// getDescribedFunctionTemplate() retrieves the
1874  /// FunctionTemplateDecl from a FunctionDecl.
1875  FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1876    return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1877  }
1878
1879  void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1880    TemplateOrSpecialization = Template;
1881  }
1882
1883  /// \brief Determine whether this function is a function template
1884  /// specialization.
1885  bool isFunctionTemplateSpecialization() const {
1886    return getPrimaryTemplate() != 0;
1887  }
1888
1889  /// \brief Retrieve the class scope template pattern that this function
1890  ///  template specialization is instantiated from.
1891  FunctionDecl *getClassScopeSpecializationPattern() const;
1892
1893  /// \brief If this function is actually a function template specialization,
1894  /// retrieve information about this function template specialization.
1895  /// Otherwise, returns NULL.
1896  FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1897    return TemplateOrSpecialization.
1898             dyn_cast<FunctionTemplateSpecializationInfo*>();
1899  }
1900
1901  /// \brief Determines whether this function is a function template
1902  /// specialization or a member of a class template specialization that can
1903  /// be implicitly instantiated.
1904  bool isImplicitlyInstantiable() const;
1905
1906  /// \brief Determines if the given function was instantiated from a
1907  /// function template.
1908  bool isTemplateInstantiation() const;
1909
1910  /// \brief Retrieve the function declaration from which this function could
1911  /// be instantiated, if it is an instantiation (rather than a non-template
1912  /// or a specialization, for example).
1913  FunctionDecl *getTemplateInstantiationPattern() const;
1914
1915  /// \brief Retrieve the primary template that this function template
1916  /// specialization either specializes or was instantiated from.
1917  ///
1918  /// If this function declaration is not a function template specialization,
1919  /// returns NULL.
1920  FunctionTemplateDecl *getPrimaryTemplate() const;
1921
1922  /// \brief Retrieve the template arguments used to produce this function
1923  /// template specialization from the primary template.
1924  ///
1925  /// If this function declaration is not a function template specialization,
1926  /// returns NULL.
1927  const TemplateArgumentList *getTemplateSpecializationArgs() const;
1928
1929  /// \brief Retrieve the template argument list as written in the sources,
1930  /// if any.
1931  ///
1932  /// If this function declaration is not a function template specialization
1933  /// or if it had no explicit template argument list, returns NULL.
1934  /// Note that it an explicit template argument list may be written empty,
1935  /// e.g., template<> void foo<>(char* s);
1936  const ASTTemplateArgumentListInfo*
1937  getTemplateSpecializationArgsAsWritten() const;
1938
1939  /// \brief Specify that this function declaration is actually a function
1940  /// template specialization.
1941  ///
1942  /// \param Template the function template that this function template
1943  /// specialization specializes.
1944  ///
1945  /// \param TemplateArgs the template arguments that produced this
1946  /// function template specialization from the template.
1947  ///
1948  /// \param InsertPos If non-NULL, the position in the function template
1949  /// specialization set where the function template specialization data will
1950  /// be inserted.
1951  ///
1952  /// \param TSK the kind of template specialization this is.
1953  ///
1954  /// \param TemplateArgsAsWritten location info of template arguments.
1955  ///
1956  /// \param PointOfInstantiation point at which the function template
1957  /// specialization was first instantiated.
1958  void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1959                                      const TemplateArgumentList *TemplateArgs,
1960                                         void *InsertPos,
1961                    TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
1962                    const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
1963                    SourceLocation PointOfInstantiation = SourceLocation()) {
1964    setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
1965                                      InsertPos, TSK, TemplateArgsAsWritten,
1966                                      PointOfInstantiation);
1967  }
1968
1969  /// \brief Specifies that this function declaration is actually a
1970  /// dependent function template specialization.
1971  void setDependentTemplateSpecialization(ASTContext &Context,
1972                             const UnresolvedSetImpl &Templates,
1973                      const TemplateArgumentListInfo &TemplateArgs);
1974
1975  DependentFunctionTemplateSpecializationInfo *
1976  getDependentSpecializationInfo() const {
1977    return TemplateOrSpecialization.
1978             dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
1979  }
1980
1981  /// \brief Determine what kind of template instantiation this function
1982  /// represents.
1983  TemplateSpecializationKind getTemplateSpecializationKind() const;
1984
1985  /// \brief Determine what kind of template instantiation this function
1986  /// represents.
1987  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1988                        SourceLocation PointOfInstantiation = SourceLocation());
1989
1990  /// \brief Retrieve the (first) point of instantiation of a function template
1991  /// specialization or a member of a class template specialization.
1992  ///
1993  /// \returns the first point of instantiation, if this function was
1994  /// instantiated from a template; otherwise, returns an invalid source
1995  /// location.
1996  SourceLocation getPointOfInstantiation() const;
1997
1998  /// \brief Determine whether this is or was instantiated from an out-of-line
1999  /// definition of a member function.
2000  virtual bool isOutOfLine() const;
2001
2002  /// \brief Identify a memory copying or setting function.
2003  /// If the given function is a memory copy or setting function, returns
2004  /// the corresponding Builtin ID. If the function is not a memory function,
2005  /// returns 0.
2006  unsigned getMemoryFunctionKind() const;
2007
2008  // Implement isa/cast/dyncast/etc.
2009  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2010  static bool classofKind(Kind K) {
2011    return K >= firstFunction && K <= lastFunction;
2012  }
2013  static DeclContext *castToDeclContext(const FunctionDecl *D) {
2014    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2015  }
2016  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2017    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2018  }
2019
2020  friend class ASTDeclReader;
2021  friend class ASTDeclWriter;
2022};
2023
2024
2025/// FieldDecl - An instance of this class is created by Sema::ActOnField to
2026/// represent a member of a struct/union/class.
2027class FieldDecl : public DeclaratorDecl {
2028  // FIXME: This can be packed into the bitfields in Decl.
2029  bool Mutable : 1;
2030  mutable unsigned CachedFieldIndex : 31;
2031
2032  /// \brief An InClassInitStyle value, and either a bit width expression (if
2033  /// the InClassInitStyle value is ICIS_NoInit), or a pointer to the in-class
2034  /// initializer for this field (otherwise).
2035  ///
2036  /// We can safely combine these two because in-class initializers are not
2037  /// permitted for bit-fields.
2038  ///
2039  /// If the InClassInitStyle is not ICIS_NoInit and the initializer is null,
2040  /// then this field has an in-class initializer which has not yet been parsed
2041  /// and attached.
2042  llvm::PointerIntPair<Expr *, 2, unsigned> InitializerOrBitWidth;
2043protected:
2044  FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2045            SourceLocation IdLoc, IdentifierInfo *Id,
2046            QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2047            InClassInitStyle InitStyle)
2048    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2049      Mutable(Mutable), CachedFieldIndex(0),
2050      InitializerOrBitWidth(BW, InitStyle) {
2051    assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2052  }
2053
2054public:
2055  static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2056                           SourceLocation StartLoc, SourceLocation IdLoc,
2057                           IdentifierInfo *Id, QualType T,
2058                           TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2059                           InClassInitStyle InitStyle);
2060
2061  static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2062
2063  /// getFieldIndex - Returns the index of this field within its record,
2064  /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2065  unsigned getFieldIndex() const;
2066
2067  /// isMutable - Determines whether this field is mutable (C++ only).
2068  bool isMutable() const { return Mutable; }
2069
2070  /// isBitfield - Determines whether this field is a bitfield.
2071  bool isBitField() const {
2072    return getInClassInitStyle() == ICIS_NoInit &&
2073           InitializerOrBitWidth.getPointer();
2074  }
2075
2076  /// @brief Determines whether this is an unnamed bitfield.
2077  bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2078
2079  /// isAnonymousStructOrUnion - Determines whether this field is a
2080  /// representative for an anonymous struct or union. Such fields are
2081  /// unnamed and are implicitly generated by the implementation to
2082  /// store the data for the anonymous union or struct.
2083  bool isAnonymousStructOrUnion() const;
2084
2085  Expr *getBitWidth() const {
2086    return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2087  }
2088  unsigned getBitWidthValue(const ASTContext &Ctx) const;
2089
2090  /// setBitWidth - Set the bit-field width for this member.
2091  // Note: used by some clients (i.e., do not remove it).
2092  void setBitWidth(Expr *Width);
2093  /// removeBitWidth - Remove the bit-field width from this member.
2094  // Note: used by some clients (i.e., do not remove it).
2095  void removeBitWidth() {
2096    assert(isBitField() && "no bitfield width to remove");
2097    InitializerOrBitWidth.setPointer(0);
2098  }
2099
2100  /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2101  /// this field has.
2102  InClassInitStyle getInClassInitStyle() const {
2103    return static_cast<InClassInitStyle>(InitializerOrBitWidth.getInt());
2104  }
2105
2106  /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2107  /// initializer.
2108  bool hasInClassInitializer() const {
2109    return getInClassInitStyle() != ICIS_NoInit;
2110  }
2111  /// getInClassInitializer - Get the C++11 in-class initializer for this
2112  /// member, or null if one has not been set. If a valid declaration has an
2113  /// in-class initializer, but this returns null, then we have not parsed and
2114  /// attached it yet.
2115  Expr *getInClassInitializer() const {
2116    return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2117  }
2118  /// setInClassInitializer - Set the C++11 in-class initializer for this
2119  /// member.
2120  void setInClassInitializer(Expr *Init);
2121  /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2122  /// member.
2123  void removeInClassInitializer() {
2124    assert(hasInClassInitializer() && "no initializer to remove");
2125    InitializerOrBitWidth.setPointer(0);
2126    InitializerOrBitWidth.setInt(ICIS_NoInit);
2127  }
2128
2129  /// getParent - Returns the parent of this field declaration, which
2130  /// is the struct in which this method is defined.
2131  const RecordDecl *getParent() const {
2132    return cast<RecordDecl>(getDeclContext());
2133  }
2134
2135  RecordDecl *getParent() {
2136    return cast<RecordDecl>(getDeclContext());
2137  }
2138
2139  SourceRange getSourceRange() const LLVM_READONLY;
2140
2141  // Implement isa/cast/dyncast/etc.
2142  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2143  static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2144
2145  friend class ASTDeclReader;
2146  friend class ASTDeclWriter;
2147};
2148
2149/// EnumConstantDecl - An instance of this object exists for each enum constant
2150/// that is defined.  For example, in "enum X {a,b}", each of a/b are
2151/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2152/// TagType for the X EnumDecl.
2153class EnumConstantDecl : public ValueDecl {
2154  Stmt *Init; // an integer constant expression
2155  llvm::APSInt Val; // The value.
2156protected:
2157  EnumConstantDecl(DeclContext *DC, SourceLocation L,
2158                   IdentifierInfo *Id, QualType T, Expr *E,
2159                   const llvm::APSInt &V)
2160    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2161
2162public:
2163
2164  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2165                                  SourceLocation L, IdentifierInfo *Id,
2166                                  QualType T, Expr *E,
2167                                  const llvm::APSInt &V);
2168  static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2169
2170  const Expr *getInitExpr() const { return (const Expr*) Init; }
2171  Expr *getInitExpr() { return (Expr*) Init; }
2172  const llvm::APSInt &getInitVal() const { return Val; }
2173
2174  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2175  void setInitVal(const llvm::APSInt &V) { Val = V; }
2176
2177  SourceRange getSourceRange() const LLVM_READONLY;
2178
2179  // Implement isa/cast/dyncast/etc.
2180  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2181  static bool classofKind(Kind K) { return K == EnumConstant; }
2182
2183  friend class StmtIteratorBase;
2184};
2185
2186/// IndirectFieldDecl - An instance of this class is created to represent a
2187/// field injected from an anonymous union/struct into the parent scope.
2188/// IndirectFieldDecl are always implicit.
2189class IndirectFieldDecl : public ValueDecl {
2190  virtual void anchor();
2191  NamedDecl **Chaining;
2192  unsigned ChainingSize;
2193
2194  IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2195                    DeclarationName N, QualType T,
2196                    NamedDecl **CH, unsigned CHS)
2197    : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2198
2199public:
2200  static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2201                                   SourceLocation L, IdentifierInfo *Id,
2202                                   QualType T, NamedDecl **CH, unsigned CHS);
2203
2204  static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2205
2206  typedef NamedDecl * const *chain_iterator;
2207  chain_iterator chain_begin() const { return Chaining; }
2208  chain_iterator chain_end() const  { return Chaining+ChainingSize; }
2209
2210  unsigned getChainingSize() const { return ChainingSize; }
2211
2212  FieldDecl *getAnonField() const {
2213    assert(ChainingSize >= 2);
2214    return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2215  }
2216
2217  VarDecl *getVarDecl() const {
2218    assert(ChainingSize >= 2);
2219    return dyn_cast<VarDecl>(*chain_begin());
2220  }
2221
2222  // Implement isa/cast/dyncast/etc.
2223  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2224  static bool classofKind(Kind K) { return K == IndirectField; }
2225  friend class ASTDeclReader;
2226};
2227
2228/// TypeDecl - Represents a declaration of a type.
2229///
2230class TypeDecl : public NamedDecl {
2231  virtual void anchor();
2232  /// TypeForDecl - This indicates the Type object that represents
2233  /// this TypeDecl.  It is a cache maintained by
2234  /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2235  /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2236  mutable const Type *TypeForDecl;
2237  /// LocStart - The start of the source range for this declaration.
2238  SourceLocation LocStart;
2239  friend class ASTContext;
2240  friend class DeclContext;
2241  friend class TagDecl;
2242  friend class TemplateTypeParmDecl;
2243  friend class TagType;
2244  friend class ASTReader;
2245
2246protected:
2247  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2248           SourceLocation StartL = SourceLocation())
2249    : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2250
2251public:
2252  // Low-level accessor. If you just want the type defined by this node,
2253  // check out ASTContext::getTypeDeclType or one of
2254  // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2255  // already know the specific kind of node this is.
2256  const Type *getTypeForDecl() const { return TypeForDecl; }
2257  void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2258
2259  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2260  void setLocStart(SourceLocation L) { LocStart = L; }
2261  virtual SourceRange getSourceRange() const LLVM_READONLY {
2262    if (LocStart.isValid())
2263      return SourceRange(LocStart, getLocation());
2264    else
2265      return SourceRange(getLocation());
2266  }
2267
2268  // Implement isa/cast/dyncast/etc.
2269  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2270  static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2271};
2272
2273
2274/// Base class for declarations which introduce a typedef-name.
2275class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2276  virtual void anchor();
2277  /// UnderlyingType - This is the type the typedef is set to.
2278  TypeSourceInfo *TInfo;
2279
2280protected:
2281  TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2282                  SourceLocation IdLoc, IdentifierInfo *Id,
2283                  TypeSourceInfo *TInfo)
2284    : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
2285
2286  typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2287  virtual TypedefNameDecl *getNextRedeclaration() {
2288    return RedeclLink.getNext();
2289  }
2290  virtual TypedefNameDecl *getPreviousDeclImpl() {
2291    return getPreviousDecl();
2292  }
2293  virtual TypedefNameDecl *getMostRecentDeclImpl() {
2294    return getMostRecentDecl();
2295  }
2296
2297public:
2298  typedef redeclarable_base::redecl_iterator redecl_iterator;
2299  using redeclarable_base::redecls_begin;
2300  using redeclarable_base::redecls_end;
2301  using redeclarable_base::getPreviousDecl;
2302  using redeclarable_base::getMostRecentDecl;
2303
2304  TypeSourceInfo *getTypeSourceInfo() const {
2305    return TInfo;
2306  }
2307
2308  /// Retrieves the canonical declaration of this typedef-name.
2309  TypedefNameDecl *getCanonicalDecl() {
2310    return getFirstDeclaration();
2311  }
2312  const TypedefNameDecl *getCanonicalDecl() const {
2313    return getFirstDeclaration();
2314  }
2315
2316  QualType getUnderlyingType() const {
2317    return TInfo->getType();
2318  }
2319  void setTypeSourceInfo(TypeSourceInfo *newType) {
2320    TInfo = newType;
2321  }
2322
2323  // Implement isa/cast/dyncast/etc.
2324  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2325  static bool classofKind(Kind K) {
2326    return K >= firstTypedefName && K <= lastTypedefName;
2327  }
2328};
2329
2330/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2331/// type specifier.
2332class TypedefDecl : public TypedefNameDecl {
2333  TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2334              IdentifierInfo *Id, TypeSourceInfo *TInfo)
2335    : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2336
2337public:
2338  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2339                             SourceLocation StartLoc, SourceLocation IdLoc,
2340                             IdentifierInfo *Id, TypeSourceInfo *TInfo);
2341  static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2342
2343  SourceRange getSourceRange() const LLVM_READONLY;
2344
2345  // Implement isa/cast/dyncast/etc.
2346  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2347  static bool classofKind(Kind K) { return K == Typedef; }
2348};
2349
2350/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2351/// alias-declaration.
2352class TypeAliasDecl : public TypedefNameDecl {
2353  TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2354                IdentifierInfo *Id, TypeSourceInfo *TInfo)
2355    : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2356
2357public:
2358  static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2359                               SourceLocation StartLoc, SourceLocation IdLoc,
2360                               IdentifierInfo *Id, TypeSourceInfo *TInfo);
2361  static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2362
2363  SourceRange getSourceRange() const LLVM_READONLY;
2364
2365  // Implement isa/cast/dyncast/etc.
2366  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2367  static bool classofKind(Kind K) { return K == TypeAlias; }
2368};
2369
2370/// TagDecl - Represents the declaration of a struct/union/class/enum.
2371class TagDecl
2372  : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2373public:
2374  // This is really ugly.
2375  typedef TagTypeKind TagKind;
2376
2377private:
2378  // FIXME: This can be packed into the bitfields in Decl.
2379  /// TagDeclKind - The TagKind enum.
2380  unsigned TagDeclKind : 3;
2381
2382  /// IsCompleteDefinition - True if this is a definition ("struct foo
2383  /// {};"), false if it is a declaration ("struct foo;").  It is not
2384  /// a definition until the definition has been fully processed.
2385  bool IsCompleteDefinition : 1;
2386
2387protected:
2388  /// IsBeingDefined - True if this is currently being defined.
2389  bool IsBeingDefined : 1;
2390
2391private:
2392  /// IsEmbeddedInDeclarator - True if this tag declaration is
2393  /// "embedded" (i.e., defined or declared for the very first time)
2394  /// in the syntax of a declarator.
2395  bool IsEmbeddedInDeclarator : 1;
2396
2397  /// \brief True if this tag is free standing, e.g. "struct foo;".
2398  bool IsFreeStanding : 1;
2399
2400protected:
2401  // These are used by (and only defined for) EnumDecl.
2402  unsigned NumPositiveBits : 8;
2403  unsigned NumNegativeBits : 8;
2404
2405  /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2406  /// possible in C++11 mode.
2407  bool IsScoped : 1;
2408  /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2409  /// then this is true if the scoped enum was declared using the class
2410  /// tag, false if it was declared with the struct tag. No meaning is
2411  /// associated if this tag declaration is not a scoped enum.
2412  bool IsScopedUsingClassTag : 1;
2413
2414  /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2415  /// possible in C++11 or Microsoft extensions mode.
2416  bool IsFixed : 1;
2417
2418  /// \brief Indicates whether it is possible for declarations of this kind
2419  /// to have an out-of-date definition.
2420  ///
2421  /// This option is only enabled when modules are enabled.
2422  bool MayHaveOutOfDateDef : 1;
2423
2424private:
2425  SourceLocation RBraceLoc;
2426
2427  // A struct representing syntactic qualifier info,
2428  // to be used for the (uncommon) case of out-of-line declarations.
2429  typedef QualifierInfo ExtInfo;
2430
2431  /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
2432  /// is qualified, it points to the qualifier info (nns and range);
2433  /// otherwise, if the tag declaration is anonymous and it is part of
2434  /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2435  /// otherwise, it is a null (TypedefNameDecl) pointer.
2436  llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
2437
2438  bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
2439  ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
2440  const ExtInfo *getExtInfo() const {
2441    return TypedefNameDeclOrQualifier.get<ExtInfo*>();
2442  }
2443
2444protected:
2445  TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2446          SourceLocation L, IdentifierInfo *Id,
2447          TagDecl *PrevDecl, SourceLocation StartL)
2448    : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
2449      TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
2450    assert((DK != Enum || TK == TTK_Enum) &&
2451           "EnumDecl not matched with TTK_Enum");
2452    TagDeclKind = TK;
2453    IsCompleteDefinition = false;
2454    IsBeingDefined = false;
2455    IsEmbeddedInDeclarator = false;
2456    IsFreeStanding = false;
2457    setPreviousDeclaration(PrevDecl);
2458  }
2459
2460  typedef Redeclarable<TagDecl> redeclarable_base;
2461  virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2462  virtual TagDecl *getPreviousDeclImpl() {
2463    return getPreviousDecl();
2464  }
2465  virtual TagDecl *getMostRecentDeclImpl() {
2466    return getMostRecentDecl();
2467  }
2468
2469  /// @brief Completes the definition of this tag declaration.
2470  ///
2471  /// This is a helper function for derived classes.
2472  void completeDefinition();
2473
2474public:
2475  typedef redeclarable_base::redecl_iterator redecl_iterator;
2476  using redeclarable_base::redecls_begin;
2477  using redeclarable_base::redecls_end;
2478  using redeclarable_base::getPreviousDecl;
2479  using redeclarable_base::getMostRecentDecl;
2480
2481  SourceLocation getRBraceLoc() const { return RBraceLoc; }
2482  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2483
2484  /// getInnerLocStart - Return SourceLocation representing start of source
2485  /// range ignoring outer template declarations.
2486  SourceLocation getInnerLocStart() const { return getLocStart(); }
2487
2488  /// getOuterLocStart - Return SourceLocation representing start of source
2489  /// range taking into account any outer template declarations.
2490  SourceLocation getOuterLocStart() const;
2491  virtual SourceRange getSourceRange() const LLVM_READONLY;
2492
2493  virtual TagDecl* getCanonicalDecl();
2494  const TagDecl* getCanonicalDecl() const {
2495    return const_cast<TagDecl*>(this)->getCanonicalDecl();
2496  }
2497
2498  /// isThisDeclarationADefinition() - Return true if this declaration
2499  /// is a completion definintion of the type.  Provided for consistency.
2500  bool isThisDeclarationADefinition() const {
2501    return isCompleteDefinition();
2502  }
2503
2504  /// isCompleteDefinition - Return true if this decl has its body
2505  /// fully specified.
2506  bool isCompleteDefinition() const {
2507    return IsCompleteDefinition;
2508  }
2509
2510  /// isBeingDefined - Return true if this decl is currently being defined.
2511  bool isBeingDefined() const {
2512    return IsBeingDefined;
2513  }
2514
2515  bool isEmbeddedInDeclarator() const {
2516    return IsEmbeddedInDeclarator;
2517  }
2518  void setEmbeddedInDeclarator(bool isInDeclarator) {
2519    IsEmbeddedInDeclarator = isInDeclarator;
2520  }
2521
2522  bool isFreeStanding() const { return IsFreeStanding; }
2523  void setFreeStanding(bool isFreeStanding = true) {
2524    IsFreeStanding = isFreeStanding;
2525  }
2526
2527  /// \brief Whether this declaration declares a type that is
2528  /// dependent, i.e., a type that somehow depends on template
2529  /// parameters.
2530  bool isDependentType() const { return isDependentContext(); }
2531
2532  /// @brief Starts the definition of this tag declaration.
2533  ///
2534  /// This method should be invoked at the beginning of the definition
2535  /// of this tag declaration. It will set the tag type into a state
2536  /// where it is in the process of being defined.
2537  void startDefinition();
2538
2539  /// getDefinition - Returns the TagDecl that actually defines this
2540  ///  struct/union/class/enum.  When determining whether or not a
2541  ///  struct/union/class/enum has a definition, one should use this
2542  ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
2543  ///  whether or not a specific TagDecl is defining declaration, not
2544  ///  whether or not the struct/union/class/enum type is defined.
2545  ///  This method returns NULL if there is no TagDecl that defines
2546  ///  the struct/union/class/enum.
2547  TagDecl *getDefinition() const;
2548
2549  void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2550
2551  // FIXME: Return StringRef;
2552  const char *getKindName() const {
2553    return TypeWithKeyword::getTagTypeKindName(getTagKind());
2554  }
2555
2556  TagKind getTagKind() const {
2557    return TagKind(TagDeclKind);
2558  }
2559
2560  void setTagKind(TagKind TK) { TagDeclKind = TK; }
2561
2562  bool isStruct() const { return getTagKind() == TTK_Struct; }
2563  bool isInterface() const { return getTagKind() == TTK_Interface; }
2564  bool isClass()  const { return getTagKind() == TTK_Class; }
2565  bool isUnion()  const { return getTagKind() == TTK_Union; }
2566  bool isEnum()   const { return getTagKind() == TTK_Enum; }
2567
2568  /// Is this tag type named, either directly or via being defined in
2569  /// a typedef of this type?
2570  ///
2571  /// C++11 [basic.link]p8:
2572  ///   A type is said to have linkage if and only if:
2573  ///     - it is a class or enumeration type that is named (or has a
2574  ///       name for linkage purposes) and the name has linkage; ...
2575  /// C++11 [dcl.typedef]p9:
2576  ///   If the typedef declaration defines an unnamed class (or enum),
2577  ///   the first typedef-name declared by the declaration to be that
2578  ///   class type (or enum type) is used to denote the class type (or
2579  ///   enum type) for linkage purposes only.
2580  ///
2581  /// C does not have an analogous rule, but the same concept is
2582  /// nonetheless useful in some places.
2583  bool hasNameForLinkage() const {
2584    return (getDeclName() || getTypedefNameForAnonDecl());
2585  }
2586
2587  TypedefNameDecl *getTypedefNameForAnonDecl() const {
2588    return hasExtInfo() ? 0 :
2589           TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
2590  }
2591
2592  void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2593
2594  /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2595  /// declaration, if it was present in the source.
2596  NestedNameSpecifier *getQualifier() const {
2597    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2598                        : 0;
2599  }
2600
2601  /// \brief Retrieve the nested-name-specifier (with source-location
2602  /// information) that qualifies the name of this declaration, if it was
2603  /// present in the source.
2604  NestedNameSpecifierLoc getQualifierLoc() const {
2605    return hasExtInfo() ? getExtInfo()->QualifierLoc
2606                        : NestedNameSpecifierLoc();
2607  }
2608
2609  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2610
2611  unsigned getNumTemplateParameterLists() const {
2612    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2613  }
2614  TemplateParameterList *getTemplateParameterList(unsigned i) const {
2615    assert(i < getNumTemplateParameterLists());
2616    return getExtInfo()->TemplParamLists[i];
2617  }
2618  void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2619                                     TemplateParameterList **TPLists);
2620
2621  // Implement isa/cast/dyncast/etc.
2622  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2623  static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2624
2625  static DeclContext *castToDeclContext(const TagDecl *D) {
2626    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2627  }
2628  static TagDecl *castFromDeclContext(const DeclContext *DC) {
2629    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2630  }
2631
2632  friend class ASTDeclReader;
2633  friend class ASTDeclWriter;
2634};
2635
2636/// EnumDecl - Represents an enum.  In C++11, enums can be forward-declared
2637/// with a fixed underlying type, and in C we allow them to be forward-declared
2638/// with no underlying type as an extension.
2639class EnumDecl : public TagDecl {
2640  virtual void anchor();
2641  /// IntegerType - This represent the integer type that the enum corresponds
2642  /// to for code generation purposes.  Note that the enumerator constants may
2643  /// have a different type than this does.
2644  ///
2645  /// If the underlying integer type was explicitly stated in the source
2646  /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2647  /// was automatically deduced somehow, and this is a Type*.
2648  ///
2649  /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2650  /// some cases it won't.
2651  ///
2652  /// The underlying type of an enumeration never has any qualifiers, so
2653  /// we can get away with just storing a raw Type*, and thus save an
2654  /// extra pointer when TypeSourceInfo is needed.
2655
2656  llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2657
2658  /// PromotionType - The integer type that values of this type should
2659  /// promote to.  In C, enumerators are generally of an integer type
2660  /// directly, but gcc-style large enumerators (and all enumerators
2661  /// in C++) are of the enum type instead.
2662  QualType PromotionType;
2663
2664  /// \brief If this enumeration is an instantiation of a member enumeration
2665  /// of a class template specialization, this is the member specialization
2666  /// information.
2667  MemberSpecializationInfo *SpecializationInfo;
2668
2669  EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2670           IdentifierInfo *Id, EnumDecl *PrevDecl,
2671           bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2672    : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2673      SpecializationInfo(0) {
2674    assert(Scoped || !ScopedUsingClassTag);
2675    IntegerType = (const Type*)0;
2676    NumNegativeBits = 0;
2677    NumPositiveBits = 0;
2678    IsScoped = Scoped;
2679    IsScopedUsingClassTag = ScopedUsingClassTag;
2680    IsFixed = Fixed;
2681  }
2682
2683  void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2684                                    TemplateSpecializationKind TSK);
2685public:
2686  EnumDecl *getCanonicalDecl() {
2687    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2688  }
2689  const EnumDecl *getCanonicalDecl() const {
2690    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2691  }
2692
2693  const EnumDecl *getPreviousDecl() const {
2694    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2695  }
2696  EnumDecl *getPreviousDecl() {
2697    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2698  }
2699
2700  const EnumDecl *getMostRecentDecl() const {
2701    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2702  }
2703  EnumDecl *getMostRecentDecl() {
2704    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2705  }
2706
2707  EnumDecl *getDefinition() const {
2708    return cast_or_null<EnumDecl>(TagDecl::getDefinition());
2709  }
2710
2711  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2712                          SourceLocation StartLoc, SourceLocation IdLoc,
2713                          IdentifierInfo *Id, EnumDecl *PrevDecl,
2714                          bool IsScoped, bool IsScopedUsingClassTag,
2715                          bool IsFixed);
2716  static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2717
2718  /// completeDefinition - When created, the EnumDecl corresponds to a
2719  /// forward-declared enum. This method is used to mark the
2720  /// declaration as being defined; it's enumerators have already been
2721  /// added (via DeclContext::addDecl). NewType is the new underlying
2722  /// type of the enumeration type.
2723  void completeDefinition(QualType NewType,
2724                          QualType PromotionType,
2725                          unsigned NumPositiveBits,
2726                          unsigned NumNegativeBits);
2727
2728  // enumerator_iterator - Iterates through the enumerators of this
2729  // enumeration.
2730  typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2731
2732  enumerator_iterator enumerator_begin() const {
2733    const EnumDecl *E = getDefinition();
2734    if (!E)
2735      E = this;
2736    return enumerator_iterator(E->decls_begin());
2737  }
2738
2739  enumerator_iterator enumerator_end() const {
2740    const EnumDecl *E = getDefinition();
2741    if (!E)
2742      E = this;
2743    return enumerator_iterator(E->decls_end());
2744  }
2745
2746  /// getPromotionType - Return the integer type that enumerators
2747  /// should promote to.
2748  QualType getPromotionType() const { return PromotionType; }
2749
2750  /// \brief Set the promotion type.
2751  void setPromotionType(QualType T) { PromotionType = T; }
2752
2753  /// getIntegerType - Return the integer type this enum decl corresponds to.
2754  /// This returns a null qualtype for an enum forward definition.
2755  QualType getIntegerType() const {
2756    if (!IntegerType)
2757      return QualType();
2758    if (const Type* T = IntegerType.dyn_cast<const Type*>())
2759      return QualType(T, 0);
2760    return IntegerType.get<TypeSourceInfo*>()->getType();
2761  }
2762
2763  /// \brief Set the underlying integer type.
2764  void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2765
2766  /// \brief Set the underlying integer type source info.
2767  void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2768
2769  /// \brief Return the type source info for the underlying integer type,
2770  /// if no type source info exists, return 0.
2771  TypeSourceInfo* getIntegerTypeSourceInfo() const {
2772    return IntegerType.dyn_cast<TypeSourceInfo*>();
2773  }
2774
2775  /// \brief Returns the width in bits required to store all the
2776  /// non-negative enumerators of this enum.
2777  unsigned getNumPositiveBits() const {
2778    return NumPositiveBits;
2779  }
2780  void setNumPositiveBits(unsigned Num) {
2781    NumPositiveBits = Num;
2782    assert(NumPositiveBits == Num && "can't store this bitcount");
2783  }
2784
2785  /// \brief Returns the width in bits required to store all the
2786  /// negative enumerators of this enum.  These widths include
2787  /// the rightmost leading 1;  that is:
2788  ///
2789  /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
2790  /// ------------------------     -------     -----------------
2791  ///                       -1     1111111                     1
2792  ///                      -10     1110110                     5
2793  ///                     -101     1001011                     8
2794  unsigned getNumNegativeBits() const {
2795    return NumNegativeBits;
2796  }
2797  void setNumNegativeBits(unsigned Num) {
2798    NumNegativeBits = Num;
2799  }
2800
2801  /// \brief Returns true if this is a C++0x scoped enumeration.
2802  bool isScoped() const {
2803    return IsScoped;
2804  }
2805
2806  /// \brief Returns true if this is a C++0x scoped enumeration.
2807  bool isScopedUsingClassTag() const {
2808    return IsScopedUsingClassTag;
2809  }
2810
2811  /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2812  /// type.
2813  bool isFixed() const {
2814    return IsFixed;
2815  }
2816
2817  /// \brief Returns true if this can be considered a complete type.
2818  bool isComplete() const {
2819    return isCompleteDefinition() || isFixed();
2820  }
2821
2822  /// \brief Returns the enumeration (declared within the template)
2823  /// from which this enumeration type was instantiated, or NULL if
2824  /// this enumeration was not instantiated from any template.
2825  EnumDecl *getInstantiatedFromMemberEnum() const;
2826
2827  /// \brief If this enumeration is a member of a specialization of a
2828  /// templated class, determine what kind of template specialization
2829  /// or instantiation this is.
2830  TemplateSpecializationKind getTemplateSpecializationKind() const;
2831
2832  /// \brief For an enumeration member that was instantiated from a member
2833  /// enumeration of a templated class, set the template specialiation kind.
2834  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2835                        SourceLocation PointOfInstantiation = SourceLocation());
2836
2837  /// \brief If this enumeration is an instantiation of a member enumeration of
2838  /// a class template specialization, retrieves the member specialization
2839  /// information.
2840  MemberSpecializationInfo *getMemberSpecializationInfo() const {
2841    return SpecializationInfo;
2842  }
2843
2844  /// \brief Specify that this enumeration is an instantiation of the
2845  /// member enumeration ED.
2846  void setInstantiationOfMemberEnum(EnumDecl *ED,
2847                                    TemplateSpecializationKind TSK) {
2848    setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
2849  }
2850
2851  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2852  static bool classofKind(Kind K) { return K == Enum; }
2853
2854  friend class ASTDeclReader;
2855};
2856
2857
2858/// RecordDecl - Represents a struct/union/class.  For example:
2859///   struct X;                  // Forward declaration, no "body".
2860///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
2861/// This decl will be marked invalid if *any* members are invalid.
2862///
2863class RecordDecl : public TagDecl {
2864  // FIXME: This can be packed into the bitfields in Decl.
2865  /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2866  /// array member (e.g. int X[]) or if this union contains a struct that does.
2867  /// If so, this cannot be contained in arrays or other structs as a member.
2868  bool HasFlexibleArrayMember : 1;
2869
2870  /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2871  /// or union.
2872  bool AnonymousStructOrUnion : 1;
2873
2874  /// HasObjectMember - This is true if this struct has at least one member
2875  /// containing an Objective-C object pointer type.
2876  bool HasObjectMember : 1;
2877
2878  /// HasVolatileMember - This is true if struct has at least one member of
2879  /// 'volatile' type.
2880  bool HasVolatileMember : 1;
2881
2882  /// \brief Whether the field declarations of this record have been loaded
2883  /// from external storage. To avoid unnecessary deserialization of
2884  /// methods/nested types we allow deserialization of just the fields
2885  /// when needed.
2886  mutable bool LoadedFieldsFromExternalStorage : 1;
2887  friend class DeclContext;
2888
2889protected:
2890  RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2891             SourceLocation StartLoc, SourceLocation IdLoc,
2892             IdentifierInfo *Id, RecordDecl *PrevDecl);
2893
2894public:
2895  static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2896                            SourceLocation StartLoc, SourceLocation IdLoc,
2897                            IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
2898  static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
2899
2900  const RecordDecl *getPreviousDecl() const {
2901    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2902  }
2903  RecordDecl *getPreviousDecl() {
2904    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2905  }
2906
2907  const RecordDecl *getMostRecentDecl() const {
2908    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2909  }
2910  RecordDecl *getMostRecentDecl() {
2911    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2912  }
2913
2914  bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
2915  void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2916
2917  /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2918  /// or union. To be an anonymous struct or union, it must have been
2919  /// declared without a name and there must be no objects of this
2920  /// type declared, e.g.,
2921  /// @code
2922  ///   union { int i; float f; };
2923  /// @endcode
2924  /// is an anonymous union but neither of the following are:
2925  /// @code
2926  ///  union X { int i; float f; };
2927  ///  union { int i; float f; } obj;
2928  /// @endcode
2929  bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
2930  void setAnonymousStructOrUnion(bool Anon) {
2931    AnonymousStructOrUnion = Anon;
2932  }
2933
2934  bool hasObjectMember() const { return HasObjectMember; }
2935  void setHasObjectMember (bool val) { HasObjectMember = val; }
2936
2937  bool hasVolatileMember() const { return HasVolatileMember; }
2938  void setHasVolatileMember (bool val) { HasVolatileMember = val; }
2939
2940  /// \brief Determines whether this declaration represents the
2941  /// injected class name.
2942  ///
2943  /// The injected class name in C++ is the name of the class that
2944  /// appears inside the class itself. For example:
2945  ///
2946  /// \code
2947  /// struct C {
2948  ///   // C is implicitly declared here as a synonym for the class name.
2949  /// };
2950  ///
2951  /// C::C c; // same as "C c;"
2952  /// \endcode
2953  bool isInjectedClassName() const;
2954
2955  /// getDefinition - Returns the RecordDecl that actually defines
2956  ///  this struct/union/class.  When determining whether or not a
2957  ///  struct/union/class is completely defined, one should use this
2958  ///  method as opposed to 'isCompleteDefinition'.
2959  ///  'isCompleteDefinition' indicates whether or not a specific
2960  ///  RecordDecl is a completed definition, not whether or not the
2961  ///  record type is defined.  This method returns NULL if there is
2962  ///  no RecordDecl that defines the struct/union/tag.
2963  RecordDecl *getDefinition() const {
2964    return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2965  }
2966
2967  // Iterator access to field members. The field iterator only visits
2968  // the non-static data members of this class, ignoring any static
2969  // data members, functions, constructors, destructors, etc.
2970  typedef specific_decl_iterator<FieldDecl> field_iterator;
2971
2972  field_iterator field_begin() const;
2973
2974  field_iterator field_end() const {
2975    return field_iterator(decl_iterator());
2976  }
2977
2978  // field_empty - Whether there are any fields (non-static data
2979  // members) in this record.
2980  bool field_empty() const {
2981    return field_begin() == field_end();
2982  }
2983
2984  /// completeDefinition - Notes that the definition of this type is
2985  /// now complete.
2986  virtual void completeDefinition();
2987
2988  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2989  static bool classofKind(Kind K) {
2990    return K >= firstRecord && K <= lastRecord;
2991  }
2992
2993  /// isMsStrust - Get whether or not this is an ms_struct which can
2994  /// be turned on with an attribute, pragma, or -mms-bitfields
2995  /// commandline option.
2996  bool isMsStruct(const ASTContext &C) const;
2997
2998private:
2999  /// \brief Deserialize just the fields.
3000  void LoadFieldsFromExternalStorage() const;
3001};
3002
3003class FileScopeAsmDecl : public Decl {
3004  virtual void anchor();
3005  StringLiteral *AsmString;
3006  SourceLocation RParenLoc;
3007  FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3008                   SourceLocation StartL, SourceLocation EndL)
3009    : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3010public:
3011  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3012                                  StringLiteral *Str, SourceLocation AsmLoc,
3013                                  SourceLocation RParenLoc);
3014
3015  static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3016
3017  SourceLocation getAsmLoc() const { return getLocation(); }
3018  SourceLocation getRParenLoc() const { return RParenLoc; }
3019  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3020  SourceRange getSourceRange() const LLVM_READONLY {
3021    return SourceRange(getAsmLoc(), getRParenLoc());
3022  }
3023
3024  const StringLiteral *getAsmString() const { return AsmString; }
3025  StringLiteral *getAsmString() { return AsmString; }
3026  void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3027
3028  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3029  static bool classofKind(Kind K) { return K == FileScopeAsm; }
3030};
3031
3032/// BlockDecl - This represents a block literal declaration, which is like an
3033/// unnamed FunctionDecl.  For example:
3034/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3035///
3036class BlockDecl : public Decl, public DeclContext {
3037public:
3038  /// A class which contains all the information about a particular
3039  /// captured value.
3040  class Capture {
3041    enum {
3042      flag_isByRef = 0x1,
3043      flag_isNested = 0x2
3044    };
3045
3046    /// The variable being captured.
3047    llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3048
3049    /// The copy expression, expressed in terms of a DeclRef (or
3050    /// BlockDeclRef) to the captured variable.  Only required if the
3051    /// variable has a C++ class type.
3052    Expr *CopyExpr;
3053
3054  public:
3055    Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3056      : VariableAndFlags(variable,
3057                  (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3058        CopyExpr(copy) {}
3059
3060    /// The variable being captured.
3061    VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3062
3063    /// Whether this is a "by ref" capture, i.e. a capture of a __block
3064    /// variable.
3065    bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3066
3067    /// Whether this is a nested capture, i.e. the variable captured
3068    /// is not from outside the immediately enclosing function/block.
3069    bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3070
3071    bool hasCopyExpr() const { return CopyExpr != 0; }
3072    Expr *getCopyExpr() const { return CopyExpr; }
3073    void setCopyExpr(Expr *e) { CopyExpr = e; }
3074  };
3075
3076private:
3077  // FIXME: This can be packed into the bitfields in Decl.
3078  bool IsVariadic : 1;
3079  bool CapturesCXXThis : 1;
3080  bool BlockMissingReturnType : 1;
3081  bool IsConversionFromLambda : 1;
3082  /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3083  /// parameters of this function.  This is null if a prototype or if there are
3084  /// no formals.
3085  ParmVarDecl **ParamInfo;
3086  unsigned NumParams;
3087
3088  Stmt *Body;
3089  TypeSourceInfo *SignatureAsWritten;
3090
3091  Capture *Captures;
3092  unsigned NumCaptures;
3093
3094protected:
3095  BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3096    : Decl(Block, DC, CaretLoc), DeclContext(Block),
3097      IsVariadic(false), CapturesCXXThis(false),
3098      BlockMissingReturnType(true), IsConversionFromLambda(false),
3099      ParamInfo(0), NumParams(0), Body(0),
3100      SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
3101
3102public:
3103  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3104  static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3105
3106  SourceLocation getCaretLocation() const { return getLocation(); }
3107
3108  bool isVariadic() const { return IsVariadic; }
3109  void setIsVariadic(bool value) { IsVariadic = value; }
3110
3111  CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3112  Stmt *getBody() const { return (Stmt*) Body; }
3113  void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3114
3115  void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3116  TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3117
3118  // Iterator access to formal parameters.
3119  unsigned param_size() const { return getNumParams(); }
3120  typedef ParmVarDecl **param_iterator;
3121  typedef ParmVarDecl * const *param_const_iterator;
3122
3123  bool param_empty() const { return NumParams == 0; }
3124  param_iterator param_begin()  { return ParamInfo; }
3125  param_iterator param_end()   { return ParamInfo+param_size(); }
3126
3127  param_const_iterator param_begin() const { return ParamInfo; }
3128  param_const_iterator param_end() const   { return ParamInfo+param_size(); }
3129
3130  unsigned getNumParams() const { return NumParams; }
3131  const ParmVarDecl *getParamDecl(unsigned i) const {
3132    assert(i < getNumParams() && "Illegal param #");
3133    return ParamInfo[i];
3134  }
3135  ParmVarDecl *getParamDecl(unsigned i) {
3136    assert(i < getNumParams() && "Illegal param #");
3137    return ParamInfo[i];
3138  }
3139  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3140
3141  /// hasCaptures - True if this block (or its nested blocks) captures
3142  /// anything of local storage from its enclosing scopes.
3143  bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3144
3145  /// getNumCaptures - Returns the number of captured variables.
3146  /// Does not include an entry for 'this'.
3147  unsigned getNumCaptures() const { return NumCaptures; }
3148
3149  typedef const Capture *capture_iterator;
3150  typedef const Capture *capture_const_iterator;
3151  capture_iterator capture_begin() { return Captures; }
3152  capture_iterator capture_end() { return Captures + NumCaptures; }
3153  capture_const_iterator capture_begin() const { return Captures; }
3154  capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3155
3156  bool capturesCXXThis() const { return CapturesCXXThis; }
3157  bool blockMissingReturnType() const { return BlockMissingReturnType; }
3158  void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3159
3160  bool isConversionFromLambda() const { return IsConversionFromLambda; }
3161  void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3162
3163  bool capturesVariable(const VarDecl *var) const;
3164
3165  void setCaptures(ASTContext &Context,
3166                   const Capture *begin,
3167                   const Capture *end,
3168                   bool capturesCXXThis);
3169
3170  virtual SourceRange getSourceRange() const LLVM_READONLY;
3171
3172  // Implement isa/cast/dyncast/etc.
3173  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3174  static bool classofKind(Kind K) { return K == Block; }
3175  static DeclContext *castToDeclContext(const BlockDecl *D) {
3176    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3177  }
3178  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3179    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3180  }
3181};
3182
3183/// \brief Describes a module import declaration, which makes the contents
3184/// of the named module visible in the current translation unit.
3185///
3186/// An import declaration imports the named module (or submodule). For example:
3187/// \code
3188///   @import std.vector;
3189/// \endcode
3190///
3191/// Import declarations can also be implicitly generated from
3192/// \#include/\#import directives.
3193class ImportDecl : public Decl {
3194  /// \brief The imported module, along with a bit that indicates whether
3195  /// we have source-location information for each identifier in the module
3196  /// name.
3197  ///
3198  /// When the bit is false, we only have a single source location for the
3199  /// end of the import declaration.
3200  llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3201
3202  /// \brief The next import in the list of imports local to the translation
3203  /// unit being parsed (not loaded from an AST file).
3204  ImportDecl *NextLocalImport;
3205
3206  friend class ASTReader;
3207  friend class ASTDeclReader;
3208  friend class ASTContext;
3209
3210  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3211             ArrayRef<SourceLocation> IdentifierLocs);
3212
3213  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3214             SourceLocation EndLoc);
3215
3216  ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3217
3218public:
3219  /// \brief Create a new module import declaration.
3220  static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3221                            SourceLocation StartLoc, Module *Imported,
3222                            ArrayRef<SourceLocation> IdentifierLocs);
3223
3224  /// \brief Create a new module import declaration for an implicitly-generated
3225  /// import.
3226  static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3227                                    SourceLocation StartLoc, Module *Imported,
3228                                    SourceLocation EndLoc);
3229
3230  /// \brief Create a new, deserialized module import declaration.
3231  static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3232                                        unsigned NumLocations);
3233
3234  /// \brief Retrieve the module that was imported by the import declaration.
3235  Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3236
3237  /// \brief Retrieves the locations of each of the identifiers that make up
3238  /// the complete module name in the import declaration.
3239  ///
3240  /// This will return an empty array if the locations of the individual
3241  /// identifiers aren't available.
3242  ArrayRef<SourceLocation> getIdentifierLocs() const;
3243
3244  virtual SourceRange getSourceRange() const LLVM_READONLY;
3245
3246  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3247  static bool classofKind(Kind K) { return K == Import; }
3248};
3249
3250/// \brief Represents an empty-declaration.
3251class EmptyDecl : public Decl {
3252  virtual void anchor();
3253  EmptyDecl(DeclContext *DC, SourceLocation L)
3254    : Decl(Empty, DC, L) { }
3255
3256public:
3257  static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3258                           SourceLocation L);
3259  static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3260
3261  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3262  static bool classofKind(Kind K) { return K == Empty; }
3263};
3264
3265/// Insertion operator for diagnostics.  This allows sending NamedDecl's
3266/// into a diagnostic with <<.
3267inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3268                                           const NamedDecl* ND) {
3269  DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3270                  DiagnosticsEngine::ak_nameddecl);
3271  return DB;
3272}
3273inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3274                                           const NamedDecl* ND) {
3275  PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3276                  DiagnosticsEngine::ak_nameddecl);
3277  return PD;
3278}
3279
3280template<typename decl_type>
3281void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3282  // Note: This routine is implemented here because we need both NamedDecl
3283  // and Redeclarable to be defined.
3284
3285  decl_type *First;
3286
3287  if (PrevDecl) {
3288    // Point to previous. Make sure that this is actually the most recent
3289    // redeclaration, or we can build invalid chains. If the most recent
3290    // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3291    First = PrevDecl->getFirstDeclaration();
3292    assert(First->RedeclLink.NextIsLatest() && "Expected first");
3293    decl_type *MostRecent = First->RedeclLink.getNext();
3294    RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3295  } else {
3296    // Make this first.
3297    First = static_cast<decl_type*>(this);
3298  }
3299
3300  // First one will point to this one as latest.
3301  First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3302  assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3303         cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3304}
3305
3306// Inline function definitions.
3307
3308/// \brief Check if the given decl is complete.
3309///
3310/// We use this function to break a cycle between the inline definitions in
3311/// Type.h and Decl.h.
3312inline bool IsEnumDeclComplete(EnumDecl *ED) {
3313  return ED->isComplete();
3314}
3315
3316/// \brief Check if the given decl is scoped.
3317///
3318/// We use this function to break a cycle between the inline definitions in
3319/// Type.h and Decl.h.
3320inline bool IsEnumDeclScoped(EnumDecl *ED) {
3321  return ED->isScoped();
3322}
3323
3324}  // end namespace clang
3325
3326#endif
3327