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