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