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