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