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