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