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