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