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