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