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