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