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