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