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