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