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