1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9//  This file defines the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECL_H
14#define LLVM_CLANG_AST_DECL_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContextAllocate.h"
18#include "clang/AST/DeclAccessPair.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/ExternalASTSource.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Redeclarable.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/AddressSpaces.h"
26#include "clang/Basic/Diagnostic.h"
27#include "clang/Basic/IdentifierTable.h"
28#include "clang/Basic/LLVM.h"
29#include "clang/Basic/Linkage.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/PragmaKinds.h"
33#include "clang/Basic/SourceLocation.h"
34#include "clang/Basic/Specifiers.h"
35#include "clang/Basic/Visibility.h"
36#include "llvm/ADT/APSInt.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/TrailingObjects.h"
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <string>
50#include <utility>
51
52namespace clang {
53
54class ASTContext;
55struct ASTTemplateArgumentListInfo;
56class Attr;
57class CompoundStmt;
58class DependentFunctionTemplateSpecializationInfo;
59class EnumDecl;
60class Expr;
61class FunctionTemplateDecl;
62class FunctionTemplateSpecializationInfo;
63class FunctionTypeLoc;
64class LabelStmt;
65class MemberSpecializationInfo;
66class Module;
67class NamespaceDecl;
68class ParmVarDecl;
69class RecordDecl;
70class Stmt;
71class StringLiteral;
72class TagDecl;
73class TemplateArgumentList;
74class TemplateArgumentListInfo;
75class TemplateParameterList;
76class TypeAliasTemplateDecl;
77class TypeLoc;
78class UnresolvedSetImpl;
79class VarTemplateDecl;
80
81/// The top declaration context.
82class TranslationUnitDecl : public Decl, public DeclContext {
83  ASTContext &Ctx;
84
85  /// The (most recently entered) anonymous namespace for this
86  /// translation unit, if one has been created.
87  NamespaceDecl *AnonymousNamespace = nullptr;
88
89  explicit TranslationUnitDecl(ASTContext &ctx);
90
91  virtual void anchor();
92
93public:
94  ASTContext &getASTContext() const { return Ctx; }
95
96  NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
97  void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
98
99  static TranslationUnitDecl *Create(ASTContext &C);
100
101  // Implement isa/cast/dyncast/etc.
102  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
103  static bool classofKind(Kind K) { return K == TranslationUnit; }
104  static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
105    return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
106  }
107  static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
108    return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
109  }
110};
111
112/// Represents a `#pragma comment` line. Always a child of
113/// TranslationUnitDecl.
114class PragmaCommentDecl final
115    : public Decl,
116      private llvm::TrailingObjects<PragmaCommentDecl, char> {
117  friend class ASTDeclReader;
118  friend class ASTDeclWriter;
119  friend TrailingObjects;
120
121  PragmaMSCommentKind CommentKind;
122
123  PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
124                    PragmaMSCommentKind CommentKind)
125      : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
126
127  virtual void anchor();
128
129public:
130  static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
131                                   SourceLocation CommentLoc,
132                                   PragmaMSCommentKind CommentKind,
133                                   StringRef Arg);
134  static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
135                                               unsigned ArgSize);
136
137  PragmaMSCommentKind getCommentKind() const { return CommentKind; }
138
139  StringRef getArg() const { return getTrailingObjects<char>(); }
140
141  // Implement isa/cast/dyncast/etc.
142  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
143  static bool classofKind(Kind K) { return K == PragmaComment; }
144};
145
146/// Represents a `#pragma detect_mismatch` line. Always a child of
147/// TranslationUnitDecl.
148class PragmaDetectMismatchDecl final
149    : public Decl,
150      private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
151  friend class ASTDeclReader;
152  friend class ASTDeclWriter;
153  friend TrailingObjects;
154
155  size_t ValueStart;
156
157  PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
158                           size_t ValueStart)
159      : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
160
161  virtual void anchor();
162
163public:
164  static PragmaDetectMismatchDecl *Create(const ASTContext &C,
165                                          TranslationUnitDecl *DC,
166                                          SourceLocation Loc, StringRef Name,
167                                          StringRef Value);
168  static PragmaDetectMismatchDecl *
169  CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
170
171  StringRef getName() const { return getTrailingObjects<char>(); }
172  StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
173
174  // Implement isa/cast/dyncast/etc.
175  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
176  static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
177};
178
179/// Declaration context for names declared as extern "C" in C++. This
180/// is neither the semantic nor lexical context for such declarations, but is
181/// used to check for conflicts with other extern "C" declarations. Example:
182///
183/// \code
184///   namespace N { extern "C" void f(); } // #1
185///   void N::f() {}                       // #2
186///   namespace M { extern "C" void f(); } // #3
187/// \endcode
188///
189/// The semantic context of #1 is namespace N and its lexical context is the
190/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
191/// context is the TU. However, both declarations are also visible in the
192/// extern "C" context.
193///
194/// The declaration at #3 finds it is a redeclaration of \c N::f through
195/// lookup in the extern "C" context.
196class ExternCContextDecl : public Decl, public DeclContext {
197  explicit ExternCContextDecl(TranslationUnitDecl *TU)
198    : Decl(ExternCContext, TU, SourceLocation()),
199      DeclContext(ExternCContext) {}
200
201  virtual void anchor();
202
203public:
204  static ExternCContextDecl *Create(const ASTContext &C,
205                                    TranslationUnitDecl *TU);
206
207  // Implement isa/cast/dyncast/etc.
208  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
209  static bool classofKind(Kind K) { return K == ExternCContext; }
210  static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
211    return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
212  }
213  static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
214    return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
215  }
216};
217
218/// This represents a decl that may have a name.  Many decls have names such
219/// as ObjCMethodDecl, but not \@class, etc.
220///
221/// Note that not every NamedDecl is actually named (e.g., a struct might
222/// be anonymous), and not every name is an identifier.
223class NamedDecl : public Decl {
224  /// The name of this declaration, which is typically a normal
225  /// identifier but may also be a special kind of name (C++
226  /// constructor, Objective-C selector, etc.)
227  DeclarationName Name;
228
229  virtual void anchor();
230
231private:
232  NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
233
234protected:
235  NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
236      : Decl(DK, DC, L), Name(N) {}
237
238public:
239  /// Get the identifier that names this declaration, if there is one.
240  ///
241  /// This will return NULL if this declaration has no name (e.g., for
242  /// an unnamed class) or if the name is a special name (C++ constructor,
243  /// Objective-C selector, etc.).
244  IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
245
246  /// Get the name of identifier for this declaration as a StringRef.
247  ///
248  /// This requires that the declaration have a name and that it be a simple
249  /// identifier.
250  StringRef getName() const {
251    assert(Name.isIdentifier() && "Name is not a simple identifier");
252    return getIdentifier() ? getIdentifier()->getName() : "";
253  }
254
255  /// Get a human-readable name for the declaration, even if it is one of the
256  /// special kinds of names (C++ constructor, Objective-C selector, etc).
257  ///
258  /// Creating this name requires expensive string manipulation, so it should
259  /// be called only when performance doesn't matter. For simple declarations,
260  /// getNameAsCString() should suffice.
261  //
262  // FIXME: This function should be renamed to indicate that it is not just an
263  // alternate form of getName(), and clients should move as appropriate.
264  //
265  // FIXME: Deprecated, move clients to getName().
266  std::string getNameAsString() const { return Name.getAsString(); }
267
268  virtual void printName(raw_ostream &os) const;
269
270  /// Get the actual, stored name of the declaration, which may be a special
271  /// name.
272  DeclarationName getDeclName() const { return Name; }
273
274  /// Set the name of this declaration.
275  void setDeclName(DeclarationName N) { Name = N; }
276
277  /// Returns a human-readable qualified name for this declaration, like
278  /// A::B::i, for i being member of namespace A::B.
279  ///
280  /// If the declaration is not a member of context which can be named (record,
281  /// namespace), it will return the same result as printName().
282  ///
283  /// Creating this name is expensive, so it should be called only when
284  /// performance doesn't matter.
285  void printQualifiedName(raw_ostream &OS) const;
286  void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
287
288  /// Print only the nested name specifier part of a fully-qualified name,
289  /// including the '::' at the end. E.g.
290  ///    when `printQualifiedName(D)` prints "A::B::i",
291  ///    this function prints "A::B::".
292  void printNestedNameSpecifier(raw_ostream &OS) const;
293  void printNestedNameSpecifier(raw_ostream &OS,
294                                const PrintingPolicy &Policy) const;
295
296  // FIXME: Remove string version.
297  std::string getQualifiedNameAsString() const;
298
299  /// Appends a human-readable name for this declaration into the given stream.
300  ///
301  /// This is the method invoked by Sema when displaying a NamedDecl
302  /// in a diagnostic.  It does not necessarily produce the same
303  /// result as printName(); for example, class template
304  /// specializations are printed with their template arguments.
305  virtual void getNameForDiagnostic(raw_ostream &OS,
306                                    const PrintingPolicy &Policy,
307                                    bool Qualified) const;
308
309  /// Determine whether this declaration, if known to be well-formed within
310  /// its context, will replace the declaration OldD if introduced into scope.
311  ///
312  /// A declaration will replace another declaration if, for example, it is
313  /// a redeclaration of the same variable or function, but not if it is a
314  /// declaration of a different kind (function vs. class) or an overloaded
315  /// function.
316  ///
317  /// \param IsKnownNewer \c true if this declaration is known to be newer
318  /// than \p OldD (for instance, if this declaration is newly-created).
319  bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
320
321  /// Determine whether this declaration has linkage.
322  bool hasLinkage() const;
323
324  using Decl::isModulePrivate;
325  using Decl::setModulePrivate;
326
327  /// Determine whether this declaration is a C++ class member.
328  bool isCXXClassMember() const {
329    const DeclContext *DC = getDeclContext();
330
331    // C++0x [class.mem]p1:
332    //   The enumerators of an unscoped enumeration defined in
333    //   the class are members of the class.
334    if (isa<EnumDecl>(DC))
335      DC = DC->getRedeclContext();
336
337    return DC->isRecord();
338  }
339
340  /// Determine whether the given declaration is an instance member of
341  /// a C++ class.
342  bool isCXXInstanceMember() const;
343
344  /// Determine what kind of linkage this entity has.
345  ///
346  /// This is not the linkage as defined by the standard or the codegen notion
347  /// of linkage. It is just an implementation detail that is used to compute
348  /// those.
349  Linkage getLinkageInternal() const;
350
351  /// Get the linkage from a semantic point of view. Entities in
352  /// anonymous namespaces are external (in c++98).
353  Linkage getFormalLinkage() const {
354    return clang::getFormalLinkage(getLinkageInternal());
355  }
356
357  /// True if this decl has external linkage.
358  bool hasExternalFormalLinkage() const {
359    return isExternalFormalLinkage(getLinkageInternal());
360  }
361
362  bool isExternallyVisible() const {
363    return clang::isExternallyVisible(getLinkageInternal());
364  }
365
366  /// Determine whether this declaration can be redeclared in a
367  /// different translation unit.
368  bool isExternallyDeclarable() const {
369    return isExternallyVisible() && !getOwningModuleForLinkage();
370  }
371
372  /// Determines the visibility of this entity.
373  Visibility getVisibility() const {
374    return getLinkageAndVisibility().getVisibility();
375  }
376
377  /// Determines the linkage and visibility of this entity.
378  LinkageInfo getLinkageAndVisibility() const;
379
380  /// Kinds of explicit visibility.
381  enum ExplicitVisibilityKind {
382    /// Do an LV computation for, ultimately, a type.
383    /// Visibility may be restricted by type visibility settings and
384    /// the visibility of template arguments.
385    VisibilityForType,
386
387    /// Do an LV computation for, ultimately, a non-type declaration.
388    /// Visibility may be restricted by value visibility settings and
389    /// the visibility of template arguments.
390    VisibilityForValue
391  };
392
393  /// If visibility was explicitly specified for this
394  /// declaration, return that visibility.
395  Optional<Visibility>
396  getExplicitVisibility(ExplicitVisibilityKind kind) const;
397
398  /// True if the computed linkage is valid. Used for consistency
399  /// checking. Should always return true.
400  bool isLinkageValid() const;
401
402  /// True if something has required us to compute the linkage
403  /// of this declaration.
404  ///
405  /// Language features which can retroactively change linkage (like a
406  /// typedef name for linkage purposes) may need to consider this,
407  /// but hopefully only in transitory ways during parsing.
408  bool hasLinkageBeenComputed() const {
409    return hasCachedLinkage();
410  }
411
412  /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
413  /// the underlying named decl.
414  NamedDecl *getUnderlyingDecl() {
415    // Fast-path the common case.
416    if (this->getKind() != UsingShadow &&
417        this->getKind() != ConstructorUsingShadow &&
418        this->getKind() != ObjCCompatibleAlias &&
419        this->getKind() != NamespaceAlias)
420      return this;
421
422    return getUnderlyingDeclImpl();
423  }
424  const NamedDecl *getUnderlyingDecl() const {
425    return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
426  }
427
428  NamedDecl *getMostRecentDecl() {
429    return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
430  }
431  const NamedDecl *getMostRecentDecl() const {
432    return const_cast<NamedDecl*>(this)->getMostRecentDecl();
433  }
434
435  ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
436
437  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
438  static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
439};
440
441inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
442  ND.printName(OS);
443  return OS;
444}
445
446/// Represents the declaration of a label.  Labels also have a
447/// corresponding LabelStmt, which indicates the position that the label was
448/// defined at.  For normal labels, the location of the decl is the same as the
449/// location of the statement.  For GNU local labels (__label__), the decl
450/// location is where the __label__ is.
451class LabelDecl : public NamedDecl {
452  LabelStmt *TheStmt;
453  StringRef MSAsmName;
454  bool MSAsmNameResolved = false;
455
456  /// For normal labels, this is the same as the main declaration
457  /// label, i.e., the location of the identifier; for GNU local labels,
458  /// this is the location of the __label__ keyword.
459  SourceLocation LocStart;
460
461  LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
462            LabelStmt *S, SourceLocation StartL)
463      : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
464
465  void anchor() override;
466
467public:
468  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
469                           SourceLocation IdentL, IdentifierInfo *II);
470  static LabelDecl *Create(ASTContext &C, DeclContext *DC,
471                           SourceLocation IdentL, IdentifierInfo *II,
472                           SourceLocation GnuLabelL);
473  static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
474
475  LabelStmt *getStmt() const { return TheStmt; }
476  void setStmt(LabelStmt *T) { TheStmt = T; }
477
478  bool isGnuLocal() const { return LocStart != getLocation(); }
479  void setLocStart(SourceLocation L) { LocStart = L; }
480
481  SourceRange getSourceRange() const override LLVM_READONLY {
482    return SourceRange(LocStart, getLocation());
483  }
484
485  bool isMSAsmLabel() const { return !MSAsmName.empty(); }
486  bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
487  void setMSAsmLabel(StringRef Name);
488  StringRef getMSAsmLabel() const { return MSAsmName; }
489  void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
490
491  // Implement isa/cast/dyncast/etc.
492  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
493  static bool classofKind(Kind K) { return K == Label; }
494};
495
496/// Represent a C++ namespace.
497class NamespaceDecl : public NamedDecl, public DeclContext,
498                      public Redeclarable<NamespaceDecl>
499{
500  /// The starting location of the source range, pointing
501  /// to either the namespace or the inline keyword.
502  SourceLocation LocStart;
503
504  /// The ending location of the source range.
505  SourceLocation RBraceLoc;
506
507  /// A pointer to either the anonymous namespace that lives just inside
508  /// this namespace or to the first namespace in the chain (the latter case
509  /// only when this is not the first in the chain), along with a
510  /// boolean value indicating whether this is an inline namespace.
511  llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
512
513  NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
514                SourceLocation StartLoc, SourceLocation IdLoc,
515                IdentifierInfo *Id, NamespaceDecl *PrevDecl);
516
517  using redeclarable_base = Redeclarable<NamespaceDecl>;
518
519  NamespaceDecl *getNextRedeclarationImpl() override;
520  NamespaceDecl *getPreviousDeclImpl() override;
521  NamespaceDecl *getMostRecentDeclImpl() override;
522
523public:
524  friend class ASTDeclReader;
525  friend class ASTDeclWriter;
526
527  static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
528                               bool Inline, SourceLocation StartLoc,
529                               SourceLocation IdLoc, IdentifierInfo *Id,
530                               NamespaceDecl *PrevDecl);
531
532  static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
533
534  using redecl_range = redeclarable_base::redecl_range;
535  using redecl_iterator = redeclarable_base::redecl_iterator;
536
537  using redeclarable_base::redecls_begin;
538  using redeclarable_base::redecls_end;
539  using redeclarable_base::redecls;
540  using redeclarable_base::getPreviousDecl;
541  using redeclarable_base::getMostRecentDecl;
542  using redeclarable_base::isFirstDecl;
543
544  /// Returns true if this is an anonymous namespace declaration.
545  ///
546  /// For example:
547  /// \code
548  ///   namespace {
549  ///     ...
550  ///   };
551  /// \endcode
552  /// q.v. C++ [namespace.unnamed]
553  bool isAnonymousNamespace() const {
554    return !getIdentifier();
555  }
556
557  /// Returns true if this is an inline namespace declaration.
558  bool isInline() const {
559    return AnonOrFirstNamespaceAndInline.getInt();
560  }
561
562  /// Set whether this is an inline namespace declaration.
563  void setInline(bool Inline) {
564    AnonOrFirstNamespaceAndInline.setInt(Inline);
565  }
566
567  /// Get the original (first) namespace declaration.
568  NamespaceDecl *getOriginalNamespace();
569
570  /// Get the original (first) namespace declaration.
571  const NamespaceDecl *getOriginalNamespace() const;
572
573  /// Return true if this declaration is an original (first) declaration
574  /// of the namespace. This is false for non-original (subsequent) namespace
575  /// declarations and anonymous namespaces.
576  bool isOriginalNamespace() const;
577
578  /// Retrieve the anonymous namespace nested inside this namespace,
579  /// if any.
580  NamespaceDecl *getAnonymousNamespace() const {
581    return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
582  }
583
584  void setAnonymousNamespace(NamespaceDecl *D) {
585    getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
586  }
587
588  /// Retrieves the canonical declaration of this namespace.
589  NamespaceDecl *getCanonicalDecl() override {
590    return getOriginalNamespace();
591  }
592  const NamespaceDecl *getCanonicalDecl() const {
593    return getOriginalNamespace();
594  }
595
596  SourceRange getSourceRange() const override LLVM_READONLY {
597    return SourceRange(LocStart, RBraceLoc);
598  }
599
600  SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
601  SourceLocation getRBraceLoc() const { return RBraceLoc; }
602  void setLocStart(SourceLocation L) { LocStart = L; }
603  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
604
605  // Implement isa/cast/dyncast/etc.
606  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
607  static bool classofKind(Kind K) { return K == Namespace; }
608  static DeclContext *castToDeclContext(const NamespaceDecl *D) {
609    return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
610  }
611  static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
612    return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
613  }
614};
615
616/// Represent the declaration of a variable (in which case it is
617/// an lvalue) a function (in which case it is a function designator) or
618/// an enum constant.
619class ValueDecl : public NamedDecl {
620  QualType DeclType;
621
622  void anchor() override;
623
624protected:
625  ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
626            DeclarationName N, QualType T)
627    : NamedDecl(DK, DC, L, N), DeclType(T) {}
628
629public:
630  QualType getType() const { return DeclType; }
631  void setType(QualType newType) { DeclType = newType; }
632
633  /// Determine whether this symbol is weakly-imported,
634  ///        or declared with the weak or weak-ref attr.
635  bool isWeak() const;
636
637  // Implement isa/cast/dyncast/etc.
638  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
639  static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
640};
641
642/// A struct with extended info about a syntactic
643/// name qualifier, to be used for the case of out-of-line declarations.
644struct QualifierInfo {
645  NestedNameSpecifierLoc QualifierLoc;
646
647  /// The number of "outer" template parameter lists.
648  /// The count includes all of the template parameter lists that were matched
649  /// against the template-ids occurring into the NNS and possibly (in the
650  /// case of an explicit specialization) a final "template <>".
651  unsigned NumTemplParamLists = 0;
652
653  /// A new-allocated array of size NumTemplParamLists,
654  /// containing pointers to the "outer" template parameter lists.
655  /// It includes all of the template parameter lists that were matched
656  /// against the template-ids occurring into the NNS and possibly (in the
657  /// case of an explicit specialization) a final "template <>".
658  TemplateParameterList** TemplParamLists = nullptr;
659
660  QualifierInfo() = default;
661  QualifierInfo(const QualifierInfo &) = delete;
662  QualifierInfo& operator=(const QualifierInfo &) = delete;
663
664  /// Sets info about "outer" template parameter lists.
665  void setTemplateParameterListsInfo(ASTContext &Context,
666                                     ArrayRef<TemplateParameterList *> TPLists);
667};
668
669/// Represents a ValueDecl that came out of a declarator.
670/// Contains type source information through TypeSourceInfo.
671class DeclaratorDecl : public ValueDecl {
672  // A struct representing a TInfo, a trailing requires-clause and a syntactic
673  // qualifier, to be used for the (uncommon) case of out-of-line declarations
674  // and constrained function decls.
675  struct ExtInfo : public QualifierInfo {
676    TypeSourceInfo *TInfo;
677    Expr *TrailingRequiresClause = nullptr;
678  };
679
680  llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
681
682  /// The start of the source range for this declaration,
683  /// ignoring outer template declarations.
684  SourceLocation InnerLocStart;
685
686  bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
687  ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
688  const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
689
690protected:
691  DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
692                 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
693                 SourceLocation StartL)
694      : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
695
696public:
697  friend class ASTDeclReader;
698  friend class ASTDeclWriter;
699
700  TypeSourceInfo *getTypeSourceInfo() const {
701    return hasExtInfo()
702      ? getExtInfo()->TInfo
703      : DeclInfo.get<TypeSourceInfo*>();
704  }
705
706  void setTypeSourceInfo(TypeSourceInfo *TI) {
707    if (hasExtInfo())
708      getExtInfo()->TInfo = TI;
709    else
710      DeclInfo = TI;
711  }
712
713  /// Return start of source range ignoring outer template declarations.
714  SourceLocation getInnerLocStart() const { return InnerLocStart; }
715  void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
716
717  /// Return start of source range taking into account any outer template
718  /// declarations.
719  SourceLocation getOuterLocStart() const;
720
721  SourceRange getSourceRange() const override LLVM_READONLY;
722
723  SourceLocation getBeginLoc() const LLVM_READONLY {
724    return getOuterLocStart();
725  }
726
727  /// Retrieve the nested-name-specifier that qualifies the name of this
728  /// declaration, if it was present in the source.
729  NestedNameSpecifier *getQualifier() const {
730    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
731                        : nullptr;
732  }
733
734  /// Retrieve the nested-name-specifier (with source-location
735  /// information) that qualifies the name of this declaration, if it was
736  /// present in the source.
737  NestedNameSpecifierLoc getQualifierLoc() const {
738    return hasExtInfo() ? getExtInfo()->QualifierLoc
739                        : NestedNameSpecifierLoc();
740  }
741
742  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
743
744  /// \brief Get the constraint-expression introduced by the trailing
745  /// requires-clause in the function/member declaration, or null if no
746  /// requires-clause was provided.
747  Expr *getTrailingRequiresClause() {
748    return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
749                        : nullptr;
750  }
751
752  const Expr *getTrailingRequiresClause() const {
753    return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
754                        : nullptr;
755  }
756
757  void setTrailingRequiresClause(Expr *TrailingRequiresClause);
758
759  unsigned getNumTemplateParameterLists() const {
760    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
761  }
762
763  TemplateParameterList *getTemplateParameterList(unsigned index) const {
764    assert(index < getNumTemplateParameterLists());
765    return getExtInfo()->TemplParamLists[index];
766  }
767
768  void setTemplateParameterListsInfo(ASTContext &Context,
769                                     ArrayRef<TemplateParameterList *> TPLists);
770
771  SourceLocation getTypeSpecStartLoc() const;
772  SourceLocation getTypeSpecEndLoc() const;
773
774  // Implement isa/cast/dyncast/etc.
775  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
776  static bool classofKind(Kind K) {
777    return K >= firstDeclarator && K <= lastDeclarator;
778  }
779};
780
781/// Structure used to store a statement, the constant value to
782/// which it was evaluated (if any), and whether or not the statement
783/// is an integral constant expression (if known).
784struct EvaluatedStmt {
785  /// Whether this statement was already evaluated.
786  bool WasEvaluated : 1;
787
788  /// Whether this statement is being evaluated.
789  bool IsEvaluating : 1;
790
791  /// Whether we already checked whether this statement was an
792  /// integral constant expression.
793  bool CheckedICE : 1;
794
795  /// Whether we are checking whether this statement is an
796  /// integral constant expression.
797  bool CheckingICE : 1;
798
799  /// Whether this statement is an integral constant expression,
800  /// or in C++11, whether the statement is a constant expression. Only
801  /// valid if CheckedICE is true.
802  bool IsICE : 1;
803
804  /// Whether this variable is known to have constant destruction. That is,
805  /// whether running the destructor on the initial value is a side-effect
806  /// (and doesn't inspect any state that might have changed during program
807  /// execution). This is currently only computed if the destructor is
808  /// non-trivial.
809  bool HasConstantDestruction : 1;
810
811  Stmt *Value;
812  APValue Evaluated;
813
814  EvaluatedStmt()
815      : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
816        CheckingICE(false), IsICE(false), HasConstantDestruction(false) {}
817};
818
819/// Represents a variable declaration or definition.
820class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
821public:
822  /// Initialization styles.
823  enum InitializationStyle {
824    /// C-style initialization with assignment
825    CInit,
826
827    /// Call-style initialization (C++98)
828    CallInit,
829
830    /// Direct list-initialization (C++11)
831    ListInit
832  };
833
834  /// Kinds of thread-local storage.
835  enum TLSKind {
836    /// Not a TLS variable.
837    TLS_None,
838
839    /// TLS with a known-constant initializer.
840    TLS_Static,
841
842    /// TLS with a dynamic initializer.
843    TLS_Dynamic
844  };
845
846  /// Return the string used to specify the storage class \p SC.
847  ///
848  /// It is illegal to call this function with SC == None.
849  static const char *getStorageClassSpecifierString(StorageClass SC);
850
851protected:
852  // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
853  // have allocated the auxiliary struct of information there.
854  //
855  // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
856  // this as *many* VarDecls are ParmVarDecls that don't have default
857  // arguments. We could save some space by moving this pointer union to be
858  // allocated in trailing space when necessary.
859  using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
860
861  /// The initializer for this variable or, for a ParmVarDecl, the
862  /// C++ default argument.
863  mutable InitType Init;
864
865private:
866  friend class ASTDeclReader;
867  friend class ASTNodeImporter;
868  friend class StmtIteratorBase;
869
870  class VarDeclBitfields {
871    friend class ASTDeclReader;
872    friend class VarDecl;
873
874    unsigned SClass : 3;
875    unsigned TSCSpec : 2;
876    unsigned InitStyle : 2;
877
878    /// Whether this variable is an ARC pseudo-__strong variable; see
879    /// isARCPseudoStrong() for details.
880    unsigned ARCPseudoStrong : 1;
881  };
882  enum { NumVarDeclBits = 8 };
883
884protected:
885  enum { NumParameterIndexBits = 8 };
886
887  enum DefaultArgKind {
888    DAK_None,
889    DAK_Unparsed,
890    DAK_Uninstantiated,
891    DAK_Normal
892  };
893
894  enum { NumScopeDepthOrObjCQualsBits = 7 };
895
896  class ParmVarDeclBitfields {
897    friend class ASTDeclReader;
898    friend class ParmVarDecl;
899
900    unsigned : NumVarDeclBits;
901
902    /// Whether this parameter inherits a default argument from a
903    /// prior declaration.
904    unsigned HasInheritedDefaultArg : 1;
905
906    /// Describes the kind of default argument for this parameter. By default
907    /// this is none. If this is normal, then the default argument is stored in
908    /// the \c VarDecl initializer expression unless we were unable to parse
909    /// (even an invalid) expression for the default argument.
910    unsigned DefaultArgKind : 2;
911
912    /// Whether this parameter undergoes K&R argument promotion.
913    unsigned IsKNRPromoted : 1;
914
915    /// Whether this parameter is an ObjC method parameter or not.
916    unsigned IsObjCMethodParam : 1;
917
918    /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
919    /// Otherwise, the number of function parameter scopes enclosing
920    /// the function parameter scope in which this parameter was
921    /// declared.
922    unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
923
924    /// The number of parameters preceding this parameter in the
925    /// function parameter scope in which it was declared.
926    unsigned ParameterIndex : NumParameterIndexBits;
927  };
928
929  class NonParmVarDeclBitfields {
930    friend class ASTDeclReader;
931    friend class ImplicitParamDecl;
932    friend class VarDecl;
933
934    unsigned : NumVarDeclBits;
935
936    // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
937    /// Whether this variable is a definition which was demoted due to
938    /// module merge.
939    unsigned IsThisDeclarationADemotedDefinition : 1;
940
941    /// Whether this variable is the exception variable in a C++ catch
942    /// or an Objective-C @catch statement.
943    unsigned ExceptionVar : 1;
944
945    /// Whether this local variable could be allocated in the return
946    /// slot of its function, enabling the named return value optimization
947    /// (NRVO).
948    unsigned NRVOVariable : 1;
949
950    /// Whether this variable is the for-range-declaration in a C++0x
951    /// for-range statement.
952    unsigned CXXForRangeDecl : 1;
953
954    /// Whether this variable is the for-in loop declaration in Objective-C.
955    unsigned ObjCForDecl : 1;
956
957    /// Whether this variable is (C++1z) inline.
958    unsigned IsInline : 1;
959
960    /// Whether this variable has (C++1z) inline explicitly specified.
961    unsigned IsInlineSpecified : 1;
962
963    /// Whether this variable is (C++0x) constexpr.
964    unsigned IsConstexpr : 1;
965
966    /// Whether this variable is the implicit variable for a lambda
967    /// init-capture.
968    unsigned IsInitCapture : 1;
969
970    /// Whether this local extern variable's previous declaration was
971    /// declared in the same block scope. This controls whether we should merge
972    /// the type of this declaration with its previous declaration.
973    unsigned PreviousDeclInSameBlockScope : 1;
974
975    /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
976    /// something else.
977    unsigned ImplicitParamKind : 3;
978
979    unsigned EscapingByref : 1;
980  };
981
982  union {
983    unsigned AllBits;
984    VarDeclBitfields VarDeclBits;
985    ParmVarDeclBitfields ParmVarDeclBits;
986    NonParmVarDeclBitfields NonParmVarDeclBits;
987  };
988
989  VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
990          SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
991          TypeSourceInfo *TInfo, StorageClass SC);
992
993  using redeclarable_base = Redeclarable<VarDecl>;
994
995  VarDecl *getNextRedeclarationImpl() override {
996    return getNextRedeclaration();
997  }
998
999  VarDecl *getPreviousDeclImpl() override {
1000    return getPreviousDecl();
1001  }
1002
1003  VarDecl *getMostRecentDeclImpl() override {
1004    return getMostRecentDecl();
1005  }
1006
1007public:
1008  using redecl_range = redeclarable_base::redecl_range;
1009  using redecl_iterator = redeclarable_base::redecl_iterator;
1010
1011  using redeclarable_base::redecls_begin;
1012  using redeclarable_base::redecls_end;
1013  using redeclarable_base::redecls;
1014  using redeclarable_base::getPreviousDecl;
1015  using redeclarable_base::getMostRecentDecl;
1016  using redeclarable_base::isFirstDecl;
1017
1018  static VarDecl *Create(ASTContext &C, DeclContext *DC,
1019                         SourceLocation StartLoc, SourceLocation IdLoc,
1020                         IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1021                         StorageClass S);
1022
1023  static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1024
1025  SourceRange getSourceRange() const override LLVM_READONLY;
1026
1027  /// Returns the storage class as written in the source. For the
1028  /// computed linkage of symbol, see getLinkage.
1029  StorageClass getStorageClass() const {
1030    return (StorageClass) VarDeclBits.SClass;
1031  }
1032  void setStorageClass(StorageClass SC);
1033
1034  void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1035    VarDeclBits.TSCSpec = TSC;
1036    assert(VarDeclBits.TSCSpec == TSC && "truncation");
1037  }
1038  ThreadStorageClassSpecifier getTSCSpec() const {
1039    return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1040  }
1041  TLSKind getTLSKind() const;
1042
1043  /// Returns true if a variable with function scope is a non-static local
1044  /// variable.
1045  bool hasLocalStorage() const {
1046    if (getStorageClass() == SC_None) {
1047      // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1048      // used to describe variables allocated in global memory and which are
1049      // accessed inside a kernel(s) as read-only variables. As such, variables
1050      // in constant address space cannot have local storage.
1051      if (getType().getAddressSpace() == LangAS::opencl_constant)
1052        return false;
1053      // Second check is for C++11 [dcl.stc]p4.
1054      return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1055    }
1056
1057    // Global Named Register (GNU extension)
1058    if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1059      return false;
1060
1061    // Return true for:  Auto, Register.
1062    // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1063
1064    return getStorageClass() >= SC_Auto;
1065  }
1066
1067  /// Returns true if a variable with function scope is a static local
1068  /// variable.
1069  bool isStaticLocal() const {
1070    return (getStorageClass() == SC_Static ||
1071            // C++11 [dcl.stc]p4
1072            (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1073      && !isFileVarDecl();
1074  }
1075
1076  /// Returns true if a variable has extern or __private_extern__
1077  /// storage.
1078  bool hasExternalStorage() const {
1079    return getStorageClass() == SC_Extern ||
1080           getStorageClass() == SC_PrivateExtern;
1081  }
1082
1083  /// Returns true for all variables that do not have local storage.
1084  ///
1085  /// This includes all global variables as well as static variables declared
1086  /// within a function.
1087  bool hasGlobalStorage() const { return !hasLocalStorage(); }
1088
1089  /// Get the storage duration of this variable, per C++ [basic.stc].
1090  StorageDuration getStorageDuration() const {
1091    return hasLocalStorage() ? SD_Automatic :
1092           getTSCSpec() ? SD_Thread : SD_Static;
1093  }
1094
1095  /// Compute the language linkage.
1096  LanguageLinkage getLanguageLinkage() const;
1097
1098  /// Determines whether this variable is a variable with external, C linkage.
1099  bool isExternC() const;
1100
1101  /// Determines whether this variable's context is, or is nested within,
1102  /// a C++ extern "C" linkage spec.
1103  bool isInExternCContext() const;
1104
1105  /// Determines whether this variable's context is, or is nested within,
1106  /// a C++ extern "C++" linkage spec.
1107  bool isInExternCXXContext() const;
1108
1109  /// Returns true for local variable declarations other than parameters.
1110  /// Note that this includes static variables inside of functions. It also
1111  /// includes variables inside blocks.
1112  ///
1113  ///   void foo() { int x; static int y; extern int z; }
1114  bool isLocalVarDecl() const {
1115    if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1116      return false;
1117    if (const DeclContext *DC = getLexicalDeclContext())
1118      return DC->getRedeclContext()->isFunctionOrMethod();
1119    return false;
1120  }
1121
1122  /// Similar to isLocalVarDecl but also includes parameters.
1123  bool isLocalVarDeclOrParm() const {
1124    return isLocalVarDecl() || getKind() == Decl::ParmVar;
1125  }
1126
1127  /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1128  bool isFunctionOrMethodVarDecl() const {
1129    if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1130      return false;
1131    const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1132    return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1133  }
1134
1135  /// Determines whether this is a static data member.
1136  ///
1137  /// This will only be true in C++, and applies to, e.g., the
1138  /// variable 'x' in:
1139  /// \code
1140  /// struct S {
1141  ///   static int x;
1142  /// };
1143  /// \endcode
1144  bool isStaticDataMember() const {
1145    // If it wasn't static, it would be a FieldDecl.
1146    return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1147  }
1148
1149  VarDecl *getCanonicalDecl() override;
1150  const VarDecl *getCanonicalDecl() const {
1151    return const_cast<VarDecl*>(this)->getCanonicalDecl();
1152  }
1153
1154  enum DefinitionKind {
1155    /// This declaration is only a declaration.
1156    DeclarationOnly,
1157
1158    /// This declaration is a tentative definition.
1159    TentativeDefinition,
1160
1161    /// This declaration is definitely a definition.
1162    Definition
1163  };
1164
1165  /// Check whether this declaration is a definition. If this could be
1166  /// a tentative definition (in C), don't check whether there's an overriding
1167  /// definition.
1168  DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1169  DefinitionKind isThisDeclarationADefinition() const {
1170    return isThisDeclarationADefinition(getASTContext());
1171  }
1172
1173  /// Check whether this variable is defined in this translation unit.
1174  DefinitionKind hasDefinition(ASTContext &) const;
1175  DefinitionKind hasDefinition() const {
1176    return hasDefinition(getASTContext());
1177  }
1178
1179  /// Get the tentative definition that acts as the real definition in a TU.
1180  /// Returns null if there is a proper definition available.
1181  VarDecl *getActingDefinition();
1182  const VarDecl *getActingDefinition() const {
1183    return const_cast<VarDecl*>(this)->getActingDefinition();
1184  }
1185
1186  /// Get the real (not just tentative) definition for this declaration.
1187  VarDecl *getDefinition(ASTContext &);
1188  const VarDecl *getDefinition(ASTContext &C) const {
1189    return const_cast<VarDecl*>(this)->getDefinition(C);
1190  }
1191  VarDecl *getDefinition() {
1192    return getDefinition(getASTContext());
1193  }
1194  const VarDecl *getDefinition() const {
1195    return const_cast<VarDecl*>(this)->getDefinition();
1196  }
1197
1198  /// Determine whether this is or was instantiated from an out-of-line
1199  /// definition of a static data member.
1200  bool isOutOfLine() const override;
1201
1202  /// Returns true for file scoped variable declaration.
1203  bool isFileVarDecl() const {
1204    Kind K = getKind();
1205    if (K == ParmVar || K == ImplicitParam)
1206      return false;
1207
1208    if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1209      return true;
1210
1211    if (isStaticDataMember())
1212      return true;
1213
1214    return false;
1215  }
1216
1217  /// Get the initializer for this variable, no matter which
1218  /// declaration it is attached to.
1219  const Expr *getAnyInitializer() const {
1220    const VarDecl *D;
1221    return getAnyInitializer(D);
1222  }
1223
1224  /// Get the initializer for this variable, no matter which
1225  /// declaration it is attached to. Also get that declaration.
1226  const Expr *getAnyInitializer(const VarDecl *&D) const;
1227
1228  bool hasInit() const;
1229  const Expr *getInit() const {
1230    return const_cast<VarDecl *>(this)->getInit();
1231  }
1232  Expr *getInit();
1233
1234  /// Retrieve the address of the initializer expression.
1235  Stmt **getInitAddress();
1236
1237  void setInit(Expr *I);
1238
1239  /// Get the initializing declaration of this variable, if any. This is
1240  /// usually the definition, except that for a static data member it can be
1241  /// the in-class declaration.
1242  VarDecl *getInitializingDeclaration();
1243  const VarDecl *getInitializingDeclaration() const {
1244    return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1245  }
1246
1247  /// Determine whether this variable's value might be usable in a
1248  /// constant expression, according to the relevant language standard.
1249  /// This only checks properties of the declaration, and does not check
1250  /// whether the initializer is in fact a constant expression.
1251  bool mightBeUsableInConstantExpressions(ASTContext &C) const;
1252
1253  /// Determine whether this variable's value can be used in a
1254  /// constant expression, according to the relevant language standard,
1255  /// including checking whether it was initialized by a constant expression.
1256  bool isUsableInConstantExpressions(ASTContext &C) const;
1257
1258  EvaluatedStmt *ensureEvaluatedStmt() const;
1259
1260  /// Attempt to evaluate the value of the initializer attached to this
1261  /// declaration, and produce notes explaining why it cannot be evaluated or is
1262  /// not a constant expression. Returns a pointer to the value if evaluation
1263  /// succeeded, 0 otherwise.
1264  APValue *evaluateValue() const;
1265  APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1266
1267  /// Return the already-evaluated value of this variable's
1268  /// initializer, or NULL if the value is not yet known. Returns pointer
1269  /// to untyped APValue if the value could not be evaluated.
1270  APValue *getEvaluatedValue() const;
1271
1272  /// Evaluate the destruction of this variable to determine if it constitutes
1273  /// constant destruction.
1274  ///
1275  /// \pre isInitICE()
1276  /// \return \c true if this variable has constant destruction, \c false if
1277  ///         not.
1278  bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1279
1280  /// Determines whether it is already known whether the
1281  /// initializer is an integral constant expression or not.
1282  bool isInitKnownICE() const;
1283
1284  /// Determines whether the initializer is an integral constant
1285  /// expression, or in C++11, whether the initializer is a constant
1286  /// expression.
1287  ///
1288  /// \pre isInitKnownICE()
1289  bool isInitICE() const;
1290
1291  /// Determine whether the value of the initializer attached to this
1292  /// declaration is an integral constant expression.
1293  bool checkInitIsICE() const;
1294
1295  void setInitStyle(InitializationStyle Style) {
1296    VarDeclBits.InitStyle = Style;
1297  }
1298
1299  /// The style of initialization for this declaration.
1300  ///
1301  /// C-style initialization is "int x = 1;". Call-style initialization is
1302  /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1303  /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1304  /// expression for class types. List-style initialization is C++11 syntax,
1305  /// e.g. "int x{1};". Clients can distinguish between different forms of
1306  /// initialization by checking this value. In particular, "int x = {1};" is
1307  /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1308  /// Init expression in all three cases is an InitListExpr.
1309  InitializationStyle getInitStyle() const {
1310    return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1311  }
1312
1313  /// Whether the initializer is a direct-initializer (list or call).
1314  bool isDirectInit() const {
1315    return getInitStyle() != CInit;
1316  }
1317
1318  /// If this definition should pretend to be a declaration.
1319  bool isThisDeclarationADemotedDefinition() const {
1320    return isa<ParmVarDecl>(this) ? false :
1321      NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1322  }
1323
1324  /// This is a definition which should be demoted to a declaration.
1325  ///
1326  /// In some cases (mostly module merging) we can end up with two visible
1327  /// definitions one of which needs to be demoted to a declaration to keep
1328  /// the AST invariants.
1329  void demoteThisDefinitionToDeclaration() {
1330    assert(isThisDeclarationADefinition() && "Not a definition!");
1331    assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1332    NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1333  }
1334
1335  /// Determine whether this variable is the exception variable in a
1336  /// C++ catch statememt or an Objective-C \@catch statement.
1337  bool isExceptionVariable() const {
1338    return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1339  }
1340  void setExceptionVariable(bool EV) {
1341    assert(!isa<ParmVarDecl>(this));
1342    NonParmVarDeclBits.ExceptionVar = EV;
1343  }
1344
1345  /// Determine whether this local variable can be used with the named
1346  /// return value optimization (NRVO).
1347  ///
1348  /// The named return value optimization (NRVO) works by marking certain
1349  /// non-volatile local variables of class type as NRVO objects. These
1350  /// locals can be allocated within the return slot of their containing
1351  /// function, in which case there is no need to copy the object to the
1352  /// return slot when returning from the function. Within the function body,
1353  /// each return that returns the NRVO object will have this variable as its
1354  /// NRVO candidate.
1355  bool isNRVOVariable() const {
1356    return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1357  }
1358  void setNRVOVariable(bool NRVO) {
1359    assert(!isa<ParmVarDecl>(this));
1360    NonParmVarDeclBits.NRVOVariable = NRVO;
1361  }
1362
1363  /// Determine whether this variable is the for-range-declaration in
1364  /// a C++0x for-range statement.
1365  bool isCXXForRangeDecl() const {
1366    return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1367  }
1368  void setCXXForRangeDecl(bool FRD) {
1369    assert(!isa<ParmVarDecl>(this));
1370    NonParmVarDeclBits.CXXForRangeDecl = FRD;
1371  }
1372
1373  /// Determine whether this variable is a for-loop declaration for a
1374  /// for-in statement in Objective-C.
1375  bool isObjCForDecl() const {
1376    return NonParmVarDeclBits.ObjCForDecl;
1377  }
1378
1379  void setObjCForDecl(bool FRD) {
1380    NonParmVarDeclBits.ObjCForDecl = FRD;
1381  }
1382
1383  /// Determine whether this variable is an ARC pseudo-__strong variable. A
1384  /// pseudo-__strong variable has a __strong-qualified type but does not
1385  /// actually retain the object written into it. Generally such variables are
1386  /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1387  /// the variable is annotated with the objc_externally_retained attribute, 2)
1388  /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1389  /// loop.
1390  bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1391  void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1392
1393  /// Whether this variable is (C++1z) inline.
1394  bool isInline() const {
1395    return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1396  }
1397  bool isInlineSpecified() const {
1398    return isa<ParmVarDecl>(this) ? false
1399                                  : NonParmVarDeclBits.IsInlineSpecified;
1400  }
1401  void setInlineSpecified() {
1402    assert(!isa<ParmVarDecl>(this));
1403    NonParmVarDeclBits.IsInline = true;
1404    NonParmVarDeclBits.IsInlineSpecified = true;
1405  }
1406  void setImplicitlyInline() {
1407    assert(!isa<ParmVarDecl>(this));
1408    NonParmVarDeclBits.IsInline = true;
1409  }
1410
1411  /// Whether this variable is (C++11) constexpr.
1412  bool isConstexpr() const {
1413    return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1414  }
1415  void setConstexpr(bool IC) {
1416    assert(!isa<ParmVarDecl>(this));
1417    NonParmVarDeclBits.IsConstexpr = IC;
1418  }
1419
1420  /// Whether this variable is the implicit variable for a lambda init-capture.
1421  bool isInitCapture() const {
1422    return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1423  }
1424  void setInitCapture(bool IC) {
1425    assert(!isa<ParmVarDecl>(this));
1426    NonParmVarDeclBits.IsInitCapture = IC;
1427  }
1428
1429  /// Determine whether this variable is actually a function parameter pack or
1430  /// init-capture pack.
1431  bool isParameterPack() const;
1432
1433  /// Whether this local extern variable declaration's previous declaration
1434  /// was declared in the same block scope. Only correct in C++.
1435  bool isPreviousDeclInSameBlockScope() const {
1436    return isa<ParmVarDecl>(this)
1437               ? false
1438               : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1439  }
1440  void setPreviousDeclInSameBlockScope(bool Same) {
1441    assert(!isa<ParmVarDecl>(this));
1442    NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1443  }
1444
1445  /// Indicates the capture is a __block variable that is captured by a block
1446  /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1447  /// returns false).
1448  bool isEscapingByref() const;
1449
1450  /// Indicates the capture is a __block variable that is never captured by an
1451  /// escaping block.
1452  bool isNonEscapingByref() const;
1453
1454  void setEscapingByref() {
1455    NonParmVarDeclBits.EscapingByref = true;
1456  }
1457
1458  /// Retrieve the variable declaration from which this variable could
1459  /// be instantiated, if it is an instantiation (rather than a non-template).
1460  VarDecl *getTemplateInstantiationPattern() const;
1461
1462  /// If this variable is an instantiated static data member of a
1463  /// class template specialization, returns the templated static data member
1464  /// from which it was instantiated.
1465  VarDecl *getInstantiatedFromStaticDataMember() const;
1466
1467  /// If this variable is an instantiation of a variable template or a
1468  /// static data member of a class template, determine what kind of
1469  /// template specialization or instantiation this is.
1470  TemplateSpecializationKind getTemplateSpecializationKind() const;
1471
1472  /// Get the template specialization kind of this variable for the purposes of
1473  /// template instantiation. This differs from getTemplateSpecializationKind()
1474  /// for an instantiation of a class-scope explicit specialization.
1475  TemplateSpecializationKind
1476  getTemplateSpecializationKindForInstantiation() const;
1477
1478  /// If this variable is an instantiation of a variable template or a
1479  /// static data member of a class template, determine its point of
1480  /// instantiation.
1481  SourceLocation getPointOfInstantiation() const;
1482
1483  /// If this variable is an instantiation of a static data member of a
1484  /// class template specialization, retrieves the member specialization
1485  /// information.
1486  MemberSpecializationInfo *getMemberSpecializationInfo() const;
1487
1488  /// For a static data member that was instantiated from a static
1489  /// data member of a class template, set the template specialiation kind.
1490  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1491                        SourceLocation PointOfInstantiation = SourceLocation());
1492
1493  /// Specify that this variable is an instantiation of the
1494  /// static data member VD.
1495  void setInstantiationOfStaticDataMember(VarDecl *VD,
1496                                          TemplateSpecializationKind TSK);
1497
1498  /// Retrieves the variable template that is described by this
1499  /// variable declaration.
1500  ///
1501  /// Every variable template is represented as a VarTemplateDecl and a
1502  /// VarDecl. The former contains template properties (such as
1503  /// the template parameter lists) while the latter contains the
1504  /// actual description of the template's
1505  /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1506  /// VarDecl that from a VarTemplateDecl, while
1507  /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1508  /// a VarDecl.
1509  VarTemplateDecl *getDescribedVarTemplate() const;
1510
1511  void setDescribedVarTemplate(VarTemplateDecl *Template);
1512
1513  // Is this variable known to have a definition somewhere in the complete
1514  // program? This may be true even if the declaration has internal linkage and
1515  // has no definition within this source file.
1516  bool isKnownToBeDefined() const;
1517
1518  /// Is destruction of this variable entirely suppressed? If so, the variable
1519  /// need not have a usable destructor at all.
1520  bool isNoDestroy(const ASTContext &) const;
1521
1522  /// Would the destruction of this variable have any effect, and if so, what
1523  /// kind?
1524  QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1525
1526  // Implement isa/cast/dyncast/etc.
1527  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1528  static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1529};
1530
1531class ImplicitParamDecl : public VarDecl {
1532  void anchor() override;
1533
1534public:
1535  /// Defines the kind of the implicit parameter: is this an implicit parameter
1536  /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1537  /// context or something else.
1538  enum ImplicitParamKind : unsigned {
1539    /// Parameter for Objective-C 'self' argument
1540    ObjCSelf,
1541
1542    /// Parameter for Objective-C '_cmd' argument
1543    ObjCCmd,
1544
1545    /// Parameter for C++ 'this' argument
1546    CXXThis,
1547
1548    /// Parameter for C++ virtual table pointers
1549    CXXVTT,
1550
1551    /// Parameter for captured context
1552    CapturedContext,
1553
1554    /// Other implicit parameter
1555    Other,
1556  };
1557
1558  /// Create implicit parameter.
1559  static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1560                                   SourceLocation IdLoc, IdentifierInfo *Id,
1561                                   QualType T, ImplicitParamKind ParamKind);
1562  static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1563                                   ImplicitParamKind ParamKind);
1564
1565  static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1566
1567  ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1568                    IdentifierInfo *Id, QualType Type,
1569                    ImplicitParamKind ParamKind)
1570      : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1571                /*TInfo=*/nullptr, SC_None) {
1572    NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1573    setImplicit();
1574  }
1575
1576  ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1577      : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1578                SourceLocation(), /*Id=*/nullptr, Type,
1579                /*TInfo=*/nullptr, SC_None) {
1580    NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1581    setImplicit();
1582  }
1583
1584  /// Returns the implicit parameter kind.
1585  ImplicitParamKind getParameterKind() const {
1586    return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1587  }
1588
1589  // Implement isa/cast/dyncast/etc.
1590  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1591  static bool classofKind(Kind K) { return K == ImplicitParam; }
1592};
1593
1594/// Represents a parameter to a function.
1595class ParmVarDecl : public VarDecl {
1596public:
1597  enum { MaxFunctionScopeDepth = 255 };
1598  enum { MaxFunctionScopeIndex = 255 };
1599
1600protected:
1601  ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1602              SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1603              TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1604      : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1605    assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1606    assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1607    assert(ParmVarDeclBits.IsKNRPromoted == false);
1608    assert(ParmVarDeclBits.IsObjCMethodParam == false);
1609    setDefaultArg(DefArg);
1610  }
1611
1612public:
1613  static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1614                             SourceLocation StartLoc,
1615                             SourceLocation IdLoc, IdentifierInfo *Id,
1616                             QualType T, TypeSourceInfo *TInfo,
1617                             StorageClass S, Expr *DefArg);
1618
1619  static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1620
1621  SourceRange getSourceRange() const override LLVM_READONLY;
1622
1623  void setObjCMethodScopeInfo(unsigned parameterIndex) {
1624    ParmVarDeclBits.IsObjCMethodParam = true;
1625    setParameterIndex(parameterIndex);
1626  }
1627
1628  void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1629    assert(!ParmVarDeclBits.IsObjCMethodParam);
1630
1631    ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1632    assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1633           && "truncation!");
1634
1635    setParameterIndex(parameterIndex);
1636  }
1637
1638  bool isObjCMethodParameter() const {
1639    return ParmVarDeclBits.IsObjCMethodParam;
1640  }
1641
1642  unsigned getFunctionScopeDepth() const {
1643    if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1644    return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1645  }
1646
1647  static constexpr unsigned getMaxFunctionScopeDepth() {
1648    return (1u << NumScopeDepthOrObjCQualsBits) - 1;
1649  }
1650
1651  /// Returns the index of this parameter in its prototype or method scope.
1652  unsigned getFunctionScopeIndex() const {
1653    return getParameterIndex();
1654  }
1655
1656  ObjCDeclQualifier getObjCDeclQualifier() const {
1657    if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1658    return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1659  }
1660  void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1661    assert(ParmVarDeclBits.IsObjCMethodParam);
1662    ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1663  }
1664
1665  /// True if the value passed to this parameter must undergo
1666  /// K&R-style default argument promotion:
1667  ///
1668  /// C99 6.5.2.2.
1669  ///   If the expression that denotes the called function has a type
1670  ///   that does not include a prototype, the integer promotions are
1671  ///   performed on each argument, and arguments that have type float
1672  ///   are promoted to double.
1673  bool isKNRPromoted() const {
1674    return ParmVarDeclBits.IsKNRPromoted;
1675  }
1676  void setKNRPromoted(bool promoted) {
1677    ParmVarDeclBits.IsKNRPromoted = promoted;
1678  }
1679
1680  Expr *getDefaultArg();
1681  const Expr *getDefaultArg() const {
1682    return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1683  }
1684
1685  void setDefaultArg(Expr *defarg);
1686
1687  /// Retrieve the source range that covers the entire default
1688  /// argument.
1689  SourceRange getDefaultArgRange() const;
1690  void setUninstantiatedDefaultArg(Expr *arg);
1691  Expr *getUninstantiatedDefaultArg();
1692  const Expr *getUninstantiatedDefaultArg() const {
1693    return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1694  }
1695
1696  /// Determines whether this parameter has a default argument,
1697  /// either parsed or not.
1698  bool hasDefaultArg() const;
1699
1700  /// Determines whether this parameter has a default argument that has not
1701  /// yet been parsed. This will occur during the processing of a C++ class
1702  /// whose member functions have default arguments, e.g.,
1703  /// @code
1704  ///   class X {
1705  ///   public:
1706  ///     void f(int x = 17); // x has an unparsed default argument now
1707  ///   }; // x has a regular default argument now
1708  /// @endcode
1709  bool hasUnparsedDefaultArg() const {
1710    return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1711  }
1712
1713  bool hasUninstantiatedDefaultArg() const {
1714    return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1715  }
1716
1717  /// Specify that this parameter has an unparsed default argument.
1718  /// The argument will be replaced with a real default argument via
1719  /// setDefaultArg when the class definition enclosing the function
1720  /// declaration that owns this default argument is completed.
1721  void setUnparsedDefaultArg() {
1722    ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1723  }
1724
1725  bool hasInheritedDefaultArg() const {
1726    return ParmVarDeclBits.HasInheritedDefaultArg;
1727  }
1728
1729  void setHasInheritedDefaultArg(bool I = true) {
1730    ParmVarDeclBits.HasInheritedDefaultArg = I;
1731  }
1732
1733  QualType getOriginalType() const;
1734
1735  /// Sets the function declaration that owns this
1736  /// ParmVarDecl. Since ParmVarDecls are often created before the
1737  /// FunctionDecls that own them, this routine is required to update
1738  /// the DeclContext appropriately.
1739  void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1740
1741  // Implement isa/cast/dyncast/etc.
1742  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1743  static bool classofKind(Kind K) { return K == ParmVar; }
1744
1745private:
1746  enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1747
1748  void setParameterIndex(unsigned parameterIndex) {
1749    if (parameterIndex >= ParameterIndexSentinel) {
1750      setParameterIndexLarge(parameterIndex);
1751      return;
1752    }
1753
1754    ParmVarDeclBits.ParameterIndex = parameterIndex;
1755    assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1756  }
1757  unsigned getParameterIndex() const {
1758    unsigned d = ParmVarDeclBits.ParameterIndex;
1759    return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1760  }
1761
1762  void setParameterIndexLarge(unsigned parameterIndex);
1763  unsigned getParameterIndexLarge() const;
1764};
1765
1766enum class MultiVersionKind {
1767  None,
1768  Target,
1769  CPUSpecific,
1770  CPUDispatch
1771};
1772
1773/// Represents a function declaration or definition.
1774///
1775/// Since a given function can be declared several times in a program,
1776/// there may be several FunctionDecls that correspond to that
1777/// function. Only one of those FunctionDecls will be found when
1778/// traversing the list of declarations in the context of the
1779/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1780/// contains all of the information known about the function. Other,
1781/// previous declarations of the function are available via the
1782/// getPreviousDecl() chain.
1783class FunctionDecl : public DeclaratorDecl,
1784                     public DeclContext,
1785                     public Redeclarable<FunctionDecl> {
1786  // This class stores some data in DeclContext::FunctionDeclBits
1787  // to save some space. Use the provided accessors to access it.
1788public:
1789  /// The kind of templated function a FunctionDecl can be.
1790  enum TemplatedKind {
1791    // Not templated.
1792    TK_NonTemplate,
1793    // The pattern in a function template declaration.
1794    TK_FunctionTemplate,
1795    // A non-template function that is an instantiation or explicit
1796    // specialization of a member of a templated class.
1797    TK_MemberSpecialization,
1798    // An instantiation or explicit specialization of a function template.
1799    // Note: this might have been instantiated from a templated class if it
1800    // is a class-scope explicit specialization.
1801    TK_FunctionTemplateSpecialization,
1802    // A function template specialization that hasn't yet been resolved to a
1803    // particular specialized function template.
1804    TK_DependentFunctionTemplateSpecialization
1805  };
1806
1807  /// Stashed information about a defaulted function definition whose body has
1808  /// not yet been lazily generated.
1809  class DefaultedFunctionInfo final
1810      : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> {
1811    friend TrailingObjects;
1812    unsigned NumLookups;
1813
1814  public:
1815    static DefaultedFunctionInfo *Create(ASTContext &Context,
1816                                         ArrayRef<DeclAccessPair> Lookups);
1817    /// Get the unqualified lookup results that should be used in this
1818    /// defaulted function definition.
1819    ArrayRef<DeclAccessPair> getUnqualifiedLookups() const {
1820      return {getTrailingObjects<DeclAccessPair>(), NumLookups};
1821    }
1822  };
1823
1824private:
1825  /// A new[]'d array of pointers to VarDecls for the formal
1826  /// parameters of this function.  This is null if a prototype or if there are
1827  /// no formals.
1828  ParmVarDecl **ParamInfo = nullptr;
1829
1830  /// The active member of this union is determined by
1831  /// FunctionDeclBits.HasDefaultedFunctionInfo.
1832  union {
1833    /// The body of the function.
1834    LazyDeclStmtPtr Body;
1835    /// Information about a future defaulted function definition.
1836    DefaultedFunctionInfo *DefaultedInfo;
1837  };
1838
1839  unsigned ODRHash;
1840
1841  /// End part of this FunctionDecl's source range.
1842  ///
1843  /// We could compute the full range in getSourceRange(). However, when we're
1844  /// dealing with a function definition deserialized from a PCH/AST file,
1845  /// we can only compute the full range once the function body has been
1846  /// de-serialized, so it's far better to have the (sometimes-redundant)
1847  /// EndRangeLoc.
1848  SourceLocation EndRangeLoc;
1849
1850  /// The template or declaration that this declaration
1851  /// describes or was instantiated from, respectively.
1852  ///
1853  /// For non-templates, this value will be NULL. For function
1854  /// declarations that describe a function template, this will be a
1855  /// pointer to a FunctionTemplateDecl. For member functions
1856  /// of class template specializations, this will be a MemberSpecializationInfo
1857  /// pointer containing information about the specialization.
1858  /// For function template specializations, this will be a
1859  /// FunctionTemplateSpecializationInfo, which contains information about
1860  /// the template being specialized and the template arguments involved in
1861  /// that specialization.
1862  llvm::PointerUnion<FunctionTemplateDecl *,
1863                     MemberSpecializationInfo *,
1864                     FunctionTemplateSpecializationInfo *,
1865                     DependentFunctionTemplateSpecializationInfo *>
1866    TemplateOrSpecialization;
1867
1868  /// Provides source/type location info for the declaration name embedded in
1869  /// the DeclaratorDecl base class.
1870  DeclarationNameLoc DNLoc;
1871
1872  /// Specify that this function declaration is actually a function
1873  /// template specialization.
1874  ///
1875  /// \param C the ASTContext.
1876  ///
1877  /// \param Template the function template that this function template
1878  /// specialization specializes.
1879  ///
1880  /// \param TemplateArgs the template arguments that produced this
1881  /// function template specialization from the template.
1882  ///
1883  /// \param InsertPos If non-NULL, the position in the function template
1884  /// specialization set where the function template specialization data will
1885  /// be inserted.
1886  ///
1887  /// \param TSK the kind of template specialization this is.
1888  ///
1889  /// \param TemplateArgsAsWritten location info of template arguments.
1890  ///
1891  /// \param PointOfInstantiation point at which the function template
1892  /// specialization was first instantiated.
1893  void setFunctionTemplateSpecialization(ASTContext &C,
1894                                         FunctionTemplateDecl *Template,
1895                                       const TemplateArgumentList *TemplateArgs,
1896                                         void *InsertPos,
1897                                         TemplateSpecializationKind TSK,
1898                          const TemplateArgumentListInfo *TemplateArgsAsWritten,
1899                                         SourceLocation PointOfInstantiation);
1900
1901  /// Specify that this record is an instantiation of the
1902  /// member function FD.
1903  void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1904                                        TemplateSpecializationKind TSK);
1905
1906  void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1907
1908  // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1909  // need to access this bit but we want to avoid making ASTDeclWriter
1910  // a friend of FunctionDeclBitfields just for this.
1911  bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1912
1913  /// Whether an ODRHash has been stored.
1914  bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1915
1916  /// State that an ODRHash has been stored.
1917  void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1918
1919protected:
1920  FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1921               const DeclarationNameInfo &NameInfo, QualType T,
1922               TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1923               ConstexprSpecKind ConstexprKind,
1924               Expr *TrailingRequiresClause = nullptr);
1925
1926  using redeclarable_base = Redeclarable<FunctionDecl>;
1927
1928  FunctionDecl *getNextRedeclarationImpl() override {
1929    return getNextRedeclaration();
1930  }
1931
1932  FunctionDecl *getPreviousDeclImpl() override {
1933    return getPreviousDecl();
1934  }
1935
1936  FunctionDecl *getMostRecentDeclImpl() override {
1937    return getMostRecentDecl();
1938  }
1939
1940public:
1941  friend class ASTDeclReader;
1942  friend class ASTDeclWriter;
1943
1944  using redecl_range = redeclarable_base::redecl_range;
1945  using redecl_iterator = redeclarable_base::redecl_iterator;
1946
1947  using redeclarable_base::redecls_begin;
1948  using redeclarable_base::redecls_end;
1949  using redeclarable_base::redecls;
1950  using redeclarable_base::getPreviousDecl;
1951  using redeclarable_base::getMostRecentDecl;
1952  using redeclarable_base::isFirstDecl;
1953
1954  static FunctionDecl *
1955  Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1956         SourceLocation NLoc, DeclarationName N, QualType T,
1957         TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false,
1958         bool hasWrittenPrototype = true,
1959         ConstexprSpecKind ConstexprKind = CSK_unspecified,
1960         Expr *TrailingRequiresClause = nullptr) {
1961    DeclarationNameInfo NameInfo(N, NLoc);
1962    return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
1963                                isInlineSpecified, hasWrittenPrototype,
1964                                ConstexprKind, TrailingRequiresClause);
1965  }
1966
1967  static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1968                              SourceLocation StartLoc,
1969                              const DeclarationNameInfo &NameInfo, QualType T,
1970                              TypeSourceInfo *TInfo, StorageClass SC,
1971                              bool isInlineSpecified, bool hasWrittenPrototype,
1972                              ConstexprSpecKind ConstexprKind,
1973                              Expr *TrailingRequiresClause);
1974
1975  static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1976
1977  DeclarationNameInfo getNameInfo() const {
1978    return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1979  }
1980
1981  void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1982                            bool Qualified) const override;
1983
1984  void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1985
1986  /// Returns the location of the ellipsis of a variadic function.
1987  SourceLocation getEllipsisLoc() const {
1988    const auto *FPT = getType()->getAs<FunctionProtoType>();
1989    if (FPT && FPT->isVariadic())
1990      return FPT->getEllipsisLoc();
1991    return SourceLocation();
1992  }
1993
1994  SourceRange getSourceRange() const override LLVM_READONLY;
1995
1996  // Function definitions.
1997  //
1998  // A function declaration may be:
1999  // - a non defining declaration,
2000  // - a definition. A function may be defined because:
2001  //   - it has a body, or will have it in the case of late parsing.
2002  //   - it has an uninstantiated body. The body does not exist because the
2003  //     function is not used yet, but the declaration is considered a
2004  //     definition and does not allow other definition of this function.
2005  //   - it does not have a user specified body, but it does not allow
2006  //     redefinition, because it is deleted/defaulted or is defined through
2007  //     some other mechanism (alias, ifunc).
2008
2009  /// Returns true if the function has a body.
2010  ///
2011  /// The function body might be in any of the (re-)declarations of this
2012  /// function. The variant that accepts a FunctionDecl pointer will set that
2013  /// function declaration to the actual declaration containing the body (if
2014  /// there is one).
2015  bool hasBody(const FunctionDecl *&Definition) const;
2016
2017  bool hasBody() const override {
2018    const FunctionDecl* Definition;
2019    return hasBody(Definition);
2020  }
2021
2022  /// Returns whether the function has a trivial body that does not require any
2023  /// specific codegen.
2024  bool hasTrivialBody() const;
2025
2026  /// Returns true if the function has a definition that does not need to be
2027  /// instantiated.
2028  ///
2029  /// The variant that accepts a FunctionDecl pointer will set that function
2030  /// declaration to the declaration that is a definition (if there is one).
2031  bool isDefined(const FunctionDecl *&Definition) const;
2032
2033  virtual bool isDefined() const {
2034    const FunctionDecl* Definition;
2035    return isDefined(Definition);
2036  }
2037
2038  /// Get the definition for this declaration.
2039  FunctionDecl *getDefinition() {
2040    const FunctionDecl *Definition;
2041    if (isDefined(Definition))
2042      return const_cast<FunctionDecl *>(Definition);
2043    return nullptr;
2044  }
2045  const FunctionDecl *getDefinition() const {
2046    return const_cast<FunctionDecl *>(this)->getDefinition();
2047  }
2048
2049  /// Retrieve the body (definition) of the function. The function body might be
2050  /// in any of the (re-)declarations of this function. The variant that accepts
2051  /// a FunctionDecl pointer will set that function declaration to the actual
2052  /// declaration containing the body (if there is one).
2053  /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2054  /// unnecessary AST de-serialization of the body.
2055  Stmt *getBody(const FunctionDecl *&Definition) const;
2056
2057  Stmt *getBody() const override {
2058    const FunctionDecl* Definition;
2059    return getBody(Definition);
2060  }
2061
2062  /// Returns whether this specific declaration of the function is also a
2063  /// definition that does not contain uninstantiated body.
2064  ///
2065  /// This does not determine whether the function has been defined (e.g., in a
2066  /// previous definition); for that information, use isDefined.
2067  ///
2068  /// Note: the function declaration does not become a definition until the
2069  /// parser reaches the definition, if called before, this function will return
2070  /// `false`.
2071  bool isThisDeclarationADefinition() const {
2072    return isDeletedAsWritten() || isDefaulted() ||
2073           doesThisDeclarationHaveABody() || hasSkippedBody() ||
2074           willHaveBody() || hasDefiningAttr();
2075  }
2076
2077  /// Returns whether this specific declaration of the function has a body.
2078  bool doesThisDeclarationHaveABody() const {
2079    return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) ||
2080           isLateTemplateParsed();
2081  }
2082
2083  void setBody(Stmt *B);
2084  void setLazyBody(uint64_t Offset) {
2085    FunctionDeclBits.HasDefaultedFunctionInfo = false;
2086    Body = LazyDeclStmtPtr(Offset);
2087  }
2088
2089  void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info);
2090  DefaultedFunctionInfo *getDefaultedFunctionInfo() const;
2091
2092  /// Whether this function is variadic.
2093  bool isVariadic() const;
2094
2095  /// Whether this function is marked as virtual explicitly.
2096  bool isVirtualAsWritten() const {
2097    return FunctionDeclBits.IsVirtualAsWritten;
2098  }
2099
2100  /// State that this function is marked as virtual explicitly.
2101  void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2102
2103  /// Whether this virtual function is pure, i.e. makes the containing class
2104  /// abstract.
2105  bool isPure() const { return FunctionDeclBits.IsPure; }
2106  void setPure(bool P = true);
2107
2108  /// Whether this templated function will be late parsed.
2109  bool isLateTemplateParsed() const {
2110    return FunctionDeclBits.IsLateTemplateParsed;
2111  }
2112
2113  /// State that this templated function will be late parsed.
2114  void setLateTemplateParsed(bool ILT = true) {
2115    FunctionDeclBits.IsLateTemplateParsed = ILT;
2116  }
2117
2118  /// Whether this function is "trivial" in some specialized C++ senses.
2119  /// Can only be true for default constructors, copy constructors,
2120  /// copy assignment operators, and destructors.  Not meaningful until
2121  /// the class has been fully built by Sema.
2122  bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2123  void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2124
2125  bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2126  void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2127
2128  /// Whether this function is defaulted per C++0x. Only valid for
2129  /// special member functions.
2130  bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2131  void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2132
2133  /// Whether this function is explicitly defaulted per C++0x. Only valid
2134  /// for special member functions.
2135  bool isExplicitlyDefaulted() const {
2136    return FunctionDeclBits.IsExplicitlyDefaulted;
2137  }
2138
2139  /// State that this function is explicitly defaulted per C++0x. Only valid
2140  /// for special member functions.
2141  void setExplicitlyDefaulted(bool ED = true) {
2142    FunctionDeclBits.IsExplicitlyDefaulted = ED;
2143  }
2144
2145  /// True if this method is user-declared and was not
2146  /// deleted or defaulted on its first declaration.
2147  bool isUserProvided() const {
2148    auto *DeclAsWritten = this;
2149    if (FunctionDecl *Pattern = getTemplateInstantiationPattern())
2150      DeclAsWritten = Pattern;
2151    return !(DeclAsWritten->isDeleted() ||
2152             DeclAsWritten->getCanonicalDecl()->isDefaulted());
2153  }
2154
2155  /// Whether falling off this function implicitly returns null/zero.
2156  /// If a more specific implicit return value is required, front-ends
2157  /// should synthesize the appropriate return statements.
2158  bool hasImplicitReturnZero() const {
2159    return FunctionDeclBits.HasImplicitReturnZero;
2160  }
2161
2162  /// State that falling off this function implicitly returns null/zero.
2163  /// If a more specific implicit return value is required, front-ends
2164  /// should synthesize the appropriate return statements.
2165  void setHasImplicitReturnZero(bool IRZ) {
2166    FunctionDeclBits.HasImplicitReturnZero = IRZ;
2167  }
2168
2169  /// Whether this function has a prototype, either because one
2170  /// was explicitly written or because it was "inherited" by merging
2171  /// a declaration without a prototype with a declaration that has a
2172  /// prototype.
2173  bool hasPrototype() const {
2174    return hasWrittenPrototype() || hasInheritedPrototype();
2175  }
2176
2177  /// Whether this function has a written prototype.
2178  bool hasWrittenPrototype() const {
2179    return FunctionDeclBits.HasWrittenPrototype;
2180  }
2181
2182  /// State that this function has a written prototype.
2183  void setHasWrittenPrototype(bool P = true) {
2184    FunctionDeclBits.HasWrittenPrototype = P;
2185  }
2186
2187  /// Whether this function inherited its prototype from a
2188  /// previous declaration.
2189  bool hasInheritedPrototype() const {
2190    return FunctionDeclBits.HasInheritedPrototype;
2191  }
2192
2193  /// State that this function inherited its prototype from a
2194  /// previous declaration.
2195  void setHasInheritedPrototype(bool P = true) {
2196    FunctionDeclBits.HasInheritedPrototype = P;
2197  }
2198
2199  /// Whether this is a (C++11) constexpr function or constexpr constructor.
2200  bool isConstexpr() const {
2201    return FunctionDeclBits.ConstexprKind != CSK_unspecified;
2202  }
2203  void setConstexprKind(ConstexprSpecKind CSK) {
2204    FunctionDeclBits.ConstexprKind = CSK;
2205  }
2206  ConstexprSpecKind getConstexprKind() const {
2207    return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2208  }
2209  bool isConstexprSpecified() const {
2210    return FunctionDeclBits.ConstexprKind == CSK_constexpr;
2211  }
2212  bool isConsteval() const {
2213    return FunctionDeclBits.ConstexprKind == CSK_consteval;
2214  }
2215
2216  /// Whether the instantiation of this function is pending.
2217  /// This bit is set when the decision to instantiate this function is made
2218  /// and unset if and when the function body is created. That leaves out
2219  /// cases where instantiation did not happen because the template definition
2220  /// was not seen in this TU. This bit remains set in those cases, under the
2221  /// assumption that the instantiation will happen in some other TU.
2222  bool instantiationIsPending() const {
2223    return FunctionDeclBits.InstantiationIsPending;
2224  }
2225
2226  /// State that the instantiation of this function is pending.
2227  /// (see instantiationIsPending)
2228  void setInstantiationIsPending(bool IC) {
2229    FunctionDeclBits.InstantiationIsPending = IC;
2230  }
2231
2232  /// Indicates the function uses __try.
2233  bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2234  void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2235
2236  /// Indicates the function uses Floating Point constrained intrinsics
2237  bool usesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }
2238  void setUsesFPIntrin(bool Val) { FunctionDeclBits.UsesFPIntrin = Val; }
2239
2240  /// Whether this function has been deleted.
2241  ///
2242  /// A function that is "deleted" (via the C++0x "= delete" syntax)
2243  /// acts like a normal function, except that it cannot actually be
2244  /// called or have its address taken. Deleted functions are
2245  /// typically used in C++ overload resolution to attract arguments
2246  /// whose type or lvalue/rvalue-ness would permit the use of a
2247  /// different overload that would behave incorrectly. For example,
2248  /// one might use deleted functions to ban implicit conversion from
2249  /// a floating-point number to an Integer type:
2250  ///
2251  /// @code
2252  /// struct Integer {
2253  ///   Integer(long); // construct from a long
2254  ///   Integer(double) = delete; // no construction from float or double
2255  ///   Integer(long double) = delete; // no construction from long double
2256  /// };
2257  /// @endcode
2258  // If a function is deleted, its first declaration must be.
2259  bool isDeleted() const {
2260    return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2261  }
2262
2263  bool isDeletedAsWritten() const {
2264    return FunctionDeclBits.IsDeleted && !isDefaulted();
2265  }
2266
2267  void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2268
2269  /// Determines whether this function is "main", which is the
2270  /// entry point into an executable program.
2271  bool isMain() const;
2272
2273  /// Determines whether this function is a MSVCRT user defined entry
2274  /// point.
2275  bool isMSVCRTEntryPoint() const;
2276
2277  /// Determines whether this operator new or delete is one
2278  /// of the reserved global placement operators:
2279  ///    void *operator new(size_t, void *);
2280  ///    void *operator new[](size_t, void *);
2281  ///    void operator delete(void *, void *);
2282  ///    void operator delete[](void *, void *);
2283  /// These functions have special behavior under [new.delete.placement]:
2284  ///    These functions are reserved, a C++ program may not define
2285  ///    functions that displace the versions in the Standard C++ library.
2286  ///    The provisions of [basic.stc.dynamic] do not apply to these
2287  ///    reserved placement forms of operator new and operator delete.
2288  ///
2289  /// This function must be an allocation or deallocation function.
2290  bool isReservedGlobalPlacementOperator() const;
2291
2292  /// Determines whether this function is one of the replaceable
2293  /// global allocation functions:
2294  ///    void *operator new(size_t);
2295  ///    void *operator new(size_t, const std::nothrow_t &) noexcept;
2296  ///    void *operator new[](size_t);
2297  ///    void *operator new[](size_t, const std::nothrow_t &) noexcept;
2298  ///    void operator delete(void *) noexcept;
2299  ///    void operator delete(void *, std::size_t) noexcept;      [C++1y]
2300  ///    void operator delete(void *, const std::nothrow_t &) noexcept;
2301  ///    void operator delete[](void *) noexcept;
2302  ///    void operator delete[](void *, std::size_t) noexcept;    [C++1y]
2303  ///    void operator delete[](void *, const std::nothrow_t &) noexcept;
2304  /// These functions have special behavior under C++1y [expr.new]:
2305  ///    An implementation is allowed to omit a call to a replaceable global
2306  ///    allocation function. [...]
2307  ///
2308  /// If this function is an aligned allocation/deallocation function, return
2309  /// true through IsAligned.
2310  bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2311
2312  /// Determine if this function provides an inline implementation of a builtin.
2313  bool isInlineBuiltinDeclaration() const;
2314
2315  /// Determine whether this is a destroying operator delete.
2316  bool isDestroyingOperatorDelete() const;
2317
2318  /// Compute the language linkage.
2319  LanguageLinkage getLanguageLinkage() const;
2320
2321  /// Determines whether this function is a function with
2322  /// external, C linkage.
2323  bool isExternC() const;
2324
2325  /// Determines whether this function's context is, or is nested within,
2326  /// a C++ extern "C" linkage spec.
2327  bool isInExternCContext() const;
2328
2329  /// Determines whether this function's context is, or is nested within,
2330  /// a C++ extern "C++" linkage spec.
2331  bool isInExternCXXContext() const;
2332
2333  /// Determines whether this is a global function.
2334  bool isGlobal() const;
2335
2336  /// Determines whether this function is known to be 'noreturn', through
2337  /// an attribute on its declaration or its type.
2338  bool isNoReturn() const;
2339
2340  /// True if the function was a definition but its body was skipped.
2341  bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2342  void setHasSkippedBody(bool Skipped = true) {
2343    FunctionDeclBits.HasSkippedBody = Skipped;
2344  }
2345
2346  /// True if this function will eventually have a body, once it's fully parsed.
2347  bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2348  void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2349
2350  /// True if this function is considered a multiversioned function.
2351  bool isMultiVersion() const {
2352    return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2353  }
2354
2355  /// Sets the multiversion state for this declaration and all of its
2356  /// redeclarations.
2357  void setIsMultiVersion(bool V = true) {
2358    getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2359  }
2360
2361  /// Gets the kind of multiversioning attribute this declaration has. Note that
2362  /// this can return a value even if the function is not multiversion, such as
2363  /// the case of 'target'.
2364  MultiVersionKind getMultiVersionKind() const;
2365
2366
2367  /// True if this function is a multiversioned dispatch function as a part of
2368  /// the cpu_specific/cpu_dispatch functionality.
2369  bool isCPUDispatchMultiVersion() const;
2370  /// True if this function is a multiversioned processor specific function as a
2371  /// part of the cpu_specific/cpu_dispatch functionality.
2372  bool isCPUSpecificMultiVersion() const;
2373
2374  /// True if this function is a multiversioned dispatch function as a part of
2375  /// the target functionality.
2376  bool isTargetMultiVersion() const;
2377
2378  /// \brief Get the associated-constraints of this function declaration.
2379  /// Currently, this will either be a vector of size 1 containing the
2380  /// trailing-requires-clause or an empty vector.
2381  ///
2382  /// Use this instead of getTrailingRequiresClause for concepts APIs that
2383  /// accept an ArrayRef of constraint expressions.
2384  void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const {
2385    if (auto *TRC = getTrailingRequiresClause())
2386      AC.push_back(TRC);
2387  }
2388
2389  void setPreviousDeclaration(FunctionDecl * PrevDecl);
2390
2391  FunctionDecl *getCanonicalDecl() override;
2392  const FunctionDecl *getCanonicalDecl() const {
2393    return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2394  }
2395
2396  unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2397
2398  // ArrayRef interface to parameters.
2399  ArrayRef<ParmVarDecl *> parameters() const {
2400    return {ParamInfo, getNumParams()};
2401  }
2402  MutableArrayRef<ParmVarDecl *> parameters() {
2403    return {ParamInfo, getNumParams()};
2404  }
2405
2406  // Iterator access to formal parameters.
2407  using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2408  using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2409
2410  bool param_empty() const { return parameters().empty(); }
2411  param_iterator param_begin() { return parameters().begin(); }
2412  param_iterator param_end() { return parameters().end(); }
2413  param_const_iterator param_begin() const { return parameters().begin(); }
2414  param_const_iterator param_end() const { return parameters().end(); }
2415  size_t param_size() const { return parameters().size(); }
2416
2417  /// Return the number of parameters this function must have based on its
2418  /// FunctionType.  This is the length of the ParamInfo array after it has been
2419  /// created.
2420  unsigned getNumParams() const;
2421
2422  const ParmVarDecl *getParamDecl(unsigned i) const {
2423    assert(i < getNumParams() && "Illegal param #");
2424    return ParamInfo[i];
2425  }
2426  ParmVarDecl *getParamDecl(unsigned i) {
2427    assert(i < getNumParams() && "Illegal param #");
2428    return ParamInfo[i];
2429  }
2430  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2431    setParams(getASTContext(), NewParamInfo);
2432  }
2433
2434  /// Returns the minimum number of arguments needed to call this function. This
2435  /// may be fewer than the number of function parameters, if some of the
2436  /// parameters have default arguments (in C++).
2437  unsigned getMinRequiredArguments() const;
2438
2439  /// Find the source location information for how the type of this function
2440  /// was written. May be absent (for example if the function was declared via
2441  /// a typedef) and may contain a different type from that of the function
2442  /// (for example if the function type was adjusted by an attribute).
2443  FunctionTypeLoc getFunctionTypeLoc() const;
2444
2445  QualType getReturnType() const {
2446    return getType()->castAs<FunctionType>()->getReturnType();
2447  }
2448
2449  /// Attempt to compute an informative source range covering the
2450  /// function return type. This may omit qualifiers and other information with
2451  /// limited representation in the AST.
2452  SourceRange getReturnTypeSourceRange() const;
2453
2454  /// Attempt to compute an informative source range covering the
2455  /// function parameters, including the ellipsis of a variadic function.
2456  /// The source range excludes the parentheses, and is invalid if there are
2457  /// no parameters and no ellipsis.
2458  SourceRange getParametersSourceRange() const;
2459
2460  /// Get the declared return type, which may differ from the actual return
2461  /// type if the return type is deduced.
2462  QualType getDeclaredReturnType() const {
2463    auto *TSI = getTypeSourceInfo();
2464    QualType T = TSI ? TSI->getType() : getType();
2465    return T->castAs<FunctionType>()->getReturnType();
2466  }
2467
2468  /// Gets the ExceptionSpecificationType as declared.
2469  ExceptionSpecificationType getExceptionSpecType() const {
2470    auto *TSI = getTypeSourceInfo();
2471    QualType T = TSI ? TSI->getType() : getType();
2472    const auto *FPT = T->getAs<FunctionProtoType>();
2473    return FPT ? FPT->getExceptionSpecType() : EST_None;
2474  }
2475
2476  /// Attempt to compute an informative source range covering the
2477  /// function exception specification, if any.
2478  SourceRange getExceptionSpecSourceRange() const;
2479
2480  /// Determine the type of an expression that calls this function.
2481  QualType getCallResultType() const {
2482    return getType()->castAs<FunctionType>()->getCallResultType(
2483        getASTContext());
2484  }
2485
2486  /// Returns the storage class as written in the source. For the
2487  /// computed linkage of symbol, see getLinkage.
2488  StorageClass getStorageClass() const {
2489    return static_cast<StorageClass>(FunctionDeclBits.SClass);
2490  }
2491
2492  /// Sets the storage class as written in the source.
2493  void setStorageClass(StorageClass SClass) {
2494    FunctionDeclBits.SClass = SClass;
2495  }
2496
2497  /// Determine whether the "inline" keyword was specified for this
2498  /// function.
2499  bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2500
2501  /// Set whether the "inline" keyword was specified for this function.
2502  void setInlineSpecified(bool I) {
2503    FunctionDeclBits.IsInlineSpecified = I;
2504    FunctionDeclBits.IsInline = I;
2505  }
2506
2507  /// Flag that this function is implicitly inline.
2508  void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2509
2510  /// Determine whether this function should be inlined, because it is
2511  /// either marked "inline" or "constexpr" or is a member function of a class
2512  /// that was defined in the class body.
2513  bool isInlined() const { return FunctionDeclBits.IsInline; }
2514
2515  bool isInlineDefinitionExternallyVisible() const;
2516
2517  bool isMSExternInline() const;
2518
2519  bool doesDeclarationForceExternallyVisibleDefinition() const;
2520
2521  bool isStatic() const { return getStorageClass() == SC_Static; }
2522
2523  /// Whether this function declaration represents an C++ overloaded
2524  /// operator, e.g., "operator+".
2525  bool isOverloadedOperator() const {
2526    return getOverloadedOperator() != OO_None;
2527  }
2528
2529  OverloadedOperatorKind getOverloadedOperator() const;
2530
2531  const IdentifierInfo *getLiteralIdentifier() const;
2532
2533  /// If this function is an instantiation of a member function
2534  /// of a class template specialization, retrieves the function from
2535  /// which it was instantiated.
2536  ///
2537  /// This routine will return non-NULL for (non-templated) member
2538  /// functions of class templates and for instantiations of function
2539  /// templates. For example, given:
2540  ///
2541  /// \code
2542  /// template<typename T>
2543  /// struct X {
2544  ///   void f(T);
2545  /// };
2546  /// \endcode
2547  ///
2548  /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2549  /// whose parent is the class template specialization X<int>. For
2550  /// this declaration, getInstantiatedFromFunction() will return
2551  /// the FunctionDecl X<T>::A. When a complete definition of
2552  /// X<int>::A is required, it will be instantiated from the
2553  /// declaration returned by getInstantiatedFromMemberFunction().
2554  FunctionDecl *getInstantiatedFromMemberFunction() const;
2555
2556  /// What kind of templated function this is.
2557  TemplatedKind getTemplatedKind() const;
2558
2559  /// If this function is an instantiation of a member function of a
2560  /// class template specialization, retrieves the member specialization
2561  /// information.
2562  MemberSpecializationInfo *getMemberSpecializationInfo() const;
2563
2564  /// Specify that this record is an instantiation of the
2565  /// member function FD.
2566  void setInstantiationOfMemberFunction(FunctionDecl *FD,
2567                                        TemplateSpecializationKind TSK) {
2568    setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2569  }
2570
2571  /// Retrieves the function template that is described by this
2572  /// function declaration.
2573  ///
2574  /// Every function template is represented as a FunctionTemplateDecl
2575  /// and a FunctionDecl (or something derived from FunctionDecl). The
2576  /// former contains template properties (such as the template
2577  /// parameter lists) while the latter contains the actual
2578  /// description of the template's
2579  /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2580  /// FunctionDecl that describes the function template,
2581  /// getDescribedFunctionTemplate() retrieves the
2582  /// FunctionTemplateDecl from a FunctionDecl.
2583  FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2584
2585  void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2586
2587  /// Determine whether this function is a function template
2588  /// specialization.
2589  bool isFunctionTemplateSpecialization() const {
2590    return getPrimaryTemplate() != nullptr;
2591  }
2592
2593  /// If this function is actually a function template specialization,
2594  /// retrieve information about this function template specialization.
2595  /// Otherwise, returns NULL.
2596  FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2597
2598  /// Determines whether this function is a function template
2599  /// specialization or a member of a class template specialization that can
2600  /// be implicitly instantiated.
2601  bool isImplicitlyInstantiable() const;
2602
2603  /// Determines if the given function was instantiated from a
2604  /// function template.
2605  bool isTemplateInstantiation() const;
2606
2607  /// Retrieve the function declaration from which this function could
2608  /// be instantiated, if it is an instantiation (rather than a non-template
2609  /// or a specialization, for example).
2610  FunctionDecl *getTemplateInstantiationPattern() const;
2611
2612  /// Retrieve the primary template that this function template
2613  /// specialization either specializes or was instantiated from.
2614  ///
2615  /// If this function declaration is not a function template specialization,
2616  /// returns NULL.
2617  FunctionTemplateDecl *getPrimaryTemplate() const;
2618
2619  /// Retrieve the template arguments used to produce this function
2620  /// template specialization from the primary template.
2621  ///
2622  /// If this function declaration is not a function template specialization,
2623  /// returns NULL.
2624  const TemplateArgumentList *getTemplateSpecializationArgs() const;
2625
2626  /// Retrieve the template argument list as written in the sources,
2627  /// if any.
2628  ///
2629  /// If this function declaration is not a function template specialization
2630  /// or if it had no explicit template argument list, returns NULL.
2631  /// Note that it an explicit template argument list may be written empty,
2632  /// e.g., template<> void foo<>(char* s);
2633  const ASTTemplateArgumentListInfo*
2634  getTemplateSpecializationArgsAsWritten() const;
2635
2636  /// Specify that this function declaration is actually a function
2637  /// template specialization.
2638  ///
2639  /// \param Template the function template that this function template
2640  /// specialization specializes.
2641  ///
2642  /// \param TemplateArgs the template arguments that produced this
2643  /// function template specialization from the template.
2644  ///
2645  /// \param InsertPos If non-NULL, the position in the function template
2646  /// specialization set where the function template specialization data will
2647  /// be inserted.
2648  ///
2649  /// \param TSK the kind of template specialization this is.
2650  ///
2651  /// \param TemplateArgsAsWritten location info of template arguments.
2652  ///
2653  /// \param PointOfInstantiation point at which the function template
2654  /// specialization was first instantiated.
2655  void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2656                const TemplateArgumentList *TemplateArgs,
2657                void *InsertPos,
2658                TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2659                const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2660                SourceLocation PointOfInstantiation = SourceLocation()) {
2661    setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2662                                      InsertPos, TSK, TemplateArgsAsWritten,
2663                                      PointOfInstantiation);
2664  }
2665
2666  /// Specifies that this function declaration is actually a
2667  /// dependent function template specialization.
2668  void setDependentTemplateSpecialization(ASTContext &Context,
2669                             const UnresolvedSetImpl &Templates,
2670                      const TemplateArgumentListInfo &TemplateArgs);
2671
2672  DependentFunctionTemplateSpecializationInfo *
2673  getDependentSpecializationInfo() const;
2674
2675  /// Determine what kind of template instantiation this function
2676  /// represents.
2677  TemplateSpecializationKind getTemplateSpecializationKind() const;
2678
2679  /// Determine the kind of template specialization this function represents
2680  /// for the purpose of template instantiation.
2681  TemplateSpecializationKind
2682  getTemplateSpecializationKindForInstantiation() const;
2683
2684  /// Determine what kind of template instantiation this function
2685  /// represents.
2686  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2687                        SourceLocation PointOfInstantiation = SourceLocation());
2688
2689  /// Retrieve the (first) point of instantiation of a function template
2690  /// specialization or a member of a class template specialization.
2691  ///
2692  /// \returns the first point of instantiation, if this function was
2693  /// instantiated from a template; otherwise, returns an invalid source
2694  /// location.
2695  SourceLocation getPointOfInstantiation() const;
2696
2697  /// Determine whether this is or was instantiated from an out-of-line
2698  /// definition of a member function.
2699  bool isOutOfLine() const override;
2700
2701  /// Identify a memory copying or setting function.
2702  /// If the given function is a memory copy or setting function, returns
2703  /// the corresponding Builtin ID. If the function is not a memory function,
2704  /// returns 0.
2705  unsigned getMemoryFunctionKind() const;
2706
2707  /// Returns ODRHash of the function.  This value is calculated and
2708  /// stored on first call, then the stored value returned on the other calls.
2709  unsigned getODRHash();
2710
2711  /// Returns cached ODRHash of the function.  This must have been previously
2712  /// computed and stored.
2713  unsigned getODRHash() const;
2714
2715  // Implement isa/cast/dyncast/etc.
2716  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2717  static bool classofKind(Kind K) {
2718    return K >= firstFunction && K <= lastFunction;
2719  }
2720  static DeclContext *castToDeclContext(const FunctionDecl *D) {
2721    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2722  }
2723  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2724    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2725  }
2726};
2727
2728/// Represents a member of a struct/union/class.
2729class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2730  unsigned BitField : 1;
2731  unsigned Mutable : 1;
2732  mutable unsigned CachedFieldIndex : 30;
2733
2734  /// The kinds of value we can store in InitializerOrBitWidth.
2735  ///
2736  /// Note that this is compatible with InClassInitStyle except for
2737  /// ISK_CapturedVLAType.
2738  enum InitStorageKind {
2739    /// If the pointer is null, there's nothing special.  Otherwise,
2740    /// this is a bitfield and the pointer is the Expr* storing the
2741    /// bit-width.
2742    ISK_NoInit = (unsigned) ICIS_NoInit,
2743
2744    /// The pointer is an (optional due to delayed parsing) Expr*
2745    /// holding the copy-initializer.
2746    ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2747
2748    /// The pointer is an (optional due to delayed parsing) Expr*
2749    /// holding the list-initializer.
2750    ISK_InClassListInit = (unsigned) ICIS_ListInit,
2751
2752    /// The pointer is a VariableArrayType* that's been captured;
2753    /// the enclosing context is a lambda or captured statement.
2754    ISK_CapturedVLAType,
2755  };
2756
2757  /// If this is a bitfield with a default member initializer, this
2758  /// structure is used to represent the two expressions.
2759  struct InitAndBitWidth {
2760    Expr *Init;
2761    Expr *BitWidth;
2762  };
2763
2764  /// Storage for either the bit-width, the in-class initializer, or
2765  /// both (via InitAndBitWidth), or the captured variable length array bound.
2766  ///
2767  /// If the storage kind is ISK_InClassCopyInit or
2768  /// ISK_InClassListInit, but the initializer is null, then this
2769  /// field has an in-class initializer that has not yet been parsed
2770  /// and attached.
2771  // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2772  // overwhelmingly common case that we have none of these things.
2773  llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2774
2775protected:
2776  FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2777            SourceLocation IdLoc, IdentifierInfo *Id,
2778            QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2779            InClassInitStyle InitStyle)
2780    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2781      BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2782      InitStorage(nullptr, (InitStorageKind) InitStyle) {
2783    if (BW)
2784      setBitWidth(BW);
2785  }
2786
2787public:
2788  friend class ASTDeclReader;
2789  friend class ASTDeclWriter;
2790
2791  static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2792                           SourceLocation StartLoc, SourceLocation IdLoc,
2793                           IdentifierInfo *Id, QualType T,
2794                           TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2795                           InClassInitStyle InitStyle);
2796
2797  static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2798
2799  /// Returns the index of this field within its record,
2800  /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2801  unsigned getFieldIndex() const;
2802
2803  /// Determines whether this field is mutable (C++ only).
2804  bool isMutable() const { return Mutable; }
2805
2806  /// Determines whether this field is a bitfield.
2807  bool isBitField() const { return BitField; }
2808
2809  /// Determines whether this is an unnamed bitfield.
2810  bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2811
2812  /// Determines whether this field is a
2813  /// representative for an anonymous struct or union. Such fields are
2814  /// unnamed and are implicitly generated by the implementation to
2815  /// store the data for the anonymous union or struct.
2816  bool isAnonymousStructOrUnion() const;
2817
2818  Expr *getBitWidth() const {
2819    if (!BitField)
2820      return nullptr;
2821    void *Ptr = InitStorage.getPointer();
2822    if (getInClassInitStyle())
2823      return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2824    return static_cast<Expr*>(Ptr);
2825  }
2826
2827  unsigned getBitWidthValue(const ASTContext &Ctx) const;
2828
2829  /// Set the bit-field width for this member.
2830  // Note: used by some clients (i.e., do not remove it).
2831  void setBitWidth(Expr *Width) {
2832    assert(!hasCapturedVLAType() && !BitField &&
2833           "bit width or captured type already set");
2834    assert(Width && "no bit width specified");
2835    InitStorage.setPointer(
2836        InitStorage.getInt()
2837            ? new (getASTContext())
2838                  InitAndBitWidth{getInClassInitializer(), Width}
2839            : static_cast<void*>(Width));
2840    BitField = true;
2841  }
2842
2843  /// Remove the bit-field width from this member.
2844  // Note: used by some clients (i.e., do not remove it).
2845  void removeBitWidth() {
2846    assert(isBitField() && "no bitfield width to remove");
2847    InitStorage.setPointer(getInClassInitializer());
2848    BitField = false;
2849  }
2850
2851  /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2852  /// at all and instead act as a separator between contiguous runs of other
2853  /// bit-fields.
2854  bool isZeroLengthBitField(const ASTContext &Ctx) const;
2855
2856  /// Determine if this field is a subobject of zero size, that is, either a
2857  /// zero-length bit-field or a field of empty class type with the
2858  /// [[no_unique_address]] attribute.
2859  bool isZeroSize(const ASTContext &Ctx) const;
2860
2861  /// Get the kind of (C++11) default member initializer that this field has.
2862  InClassInitStyle getInClassInitStyle() const {
2863    InitStorageKind storageKind = InitStorage.getInt();
2864    return (storageKind == ISK_CapturedVLAType
2865              ? ICIS_NoInit : (InClassInitStyle) storageKind);
2866  }
2867
2868  /// Determine whether this member has a C++11 default member initializer.
2869  bool hasInClassInitializer() const {
2870    return getInClassInitStyle() != ICIS_NoInit;
2871  }
2872
2873  /// Get the C++11 default member initializer for this member, or null if one
2874  /// has not been set. If a valid declaration has a default member initializer,
2875  /// but this returns null, then we have not parsed and attached it yet.
2876  Expr *getInClassInitializer() const {
2877    if (!hasInClassInitializer())
2878      return nullptr;
2879    void *Ptr = InitStorage.getPointer();
2880    if (BitField)
2881      return static_cast<InitAndBitWidth*>(Ptr)->Init;
2882    return static_cast<Expr*>(Ptr);
2883  }
2884
2885  /// Set the C++11 in-class initializer for this member.
2886  void setInClassInitializer(Expr *Init) {
2887    assert(hasInClassInitializer() && !getInClassInitializer());
2888    if (BitField)
2889      static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2890    else
2891      InitStorage.setPointer(Init);
2892  }
2893
2894  /// Remove the C++11 in-class initializer from this member.
2895  void removeInClassInitializer() {
2896    assert(hasInClassInitializer() && "no initializer to remove");
2897    InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2898  }
2899
2900  /// Determine whether this member captures the variable length array
2901  /// type.
2902  bool hasCapturedVLAType() const {
2903    return InitStorage.getInt() == ISK_CapturedVLAType;
2904  }
2905
2906  /// Get the captured variable length array type.
2907  const VariableArrayType *getCapturedVLAType() const {
2908    return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2909                                      InitStorage.getPointer())
2910                                : nullptr;
2911  }
2912
2913  /// Set the captured variable length array type for this field.
2914  void setCapturedVLAType(const VariableArrayType *VLAType);
2915
2916  /// Returns the parent of this field declaration, which
2917  /// is the struct in which this field is defined.
2918  const RecordDecl *getParent() const {
2919    return cast<RecordDecl>(getDeclContext());
2920  }
2921
2922  RecordDecl *getParent() {
2923    return cast<RecordDecl>(getDeclContext());
2924  }
2925
2926  SourceRange getSourceRange() const override LLVM_READONLY;
2927
2928  /// Retrieves the canonical declaration of this field.
2929  FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2930  const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2931
2932  // Implement isa/cast/dyncast/etc.
2933  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2934  static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2935};
2936
2937/// An instance of this object exists for each enum constant
2938/// that is defined.  For example, in "enum X {a,b}", each of a/b are
2939/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2940/// TagType for the X EnumDecl.
2941class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2942  Stmt *Init; // an integer constant expression
2943  llvm::APSInt Val; // The value.
2944
2945protected:
2946  EnumConstantDecl(DeclContext *DC, SourceLocation L,
2947                   IdentifierInfo *Id, QualType T, Expr *E,
2948                   const llvm::APSInt &V)
2949    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2950
2951public:
2952  friend class StmtIteratorBase;
2953
2954  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2955                                  SourceLocation L, IdentifierInfo *Id,
2956                                  QualType T, Expr *E,
2957                                  const llvm::APSInt &V);
2958  static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2959
2960  const Expr *getInitExpr() const { return (const Expr*) Init; }
2961  Expr *getInitExpr() { return (Expr*) Init; }
2962  const llvm::APSInt &getInitVal() const { return Val; }
2963
2964  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2965  void setInitVal(const llvm::APSInt &V) { Val = V; }
2966
2967  SourceRange getSourceRange() const override LLVM_READONLY;
2968
2969  /// Retrieves the canonical declaration of this enumerator.
2970  EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2971  const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2972
2973  // Implement isa/cast/dyncast/etc.
2974  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2975  static bool classofKind(Kind K) { return K == EnumConstant; }
2976};
2977
2978/// Represents a field injected from an anonymous union/struct into the parent
2979/// scope. These are always implicit.
2980class IndirectFieldDecl : public ValueDecl,
2981                          public Mergeable<IndirectFieldDecl> {
2982  NamedDecl **Chaining;
2983  unsigned ChainingSize;
2984
2985  IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2986                    DeclarationName N, QualType T,
2987                    MutableArrayRef<NamedDecl *> CH);
2988
2989  void anchor() override;
2990
2991public:
2992  friend class ASTDeclReader;
2993
2994  static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2995                                   SourceLocation L, IdentifierInfo *Id,
2996                                   QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2997
2998  static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2999
3000  using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
3001
3002  ArrayRef<NamedDecl *> chain() const {
3003    return llvm::makeArrayRef(Chaining, ChainingSize);
3004  }
3005  chain_iterator chain_begin() const { return chain().begin(); }
3006  chain_iterator chain_end() const { return chain().end(); }
3007
3008  unsigned getChainingSize() const { return ChainingSize; }
3009
3010  FieldDecl *getAnonField() const {
3011    assert(chain().size() >= 2);
3012    return cast<FieldDecl>(chain().back());
3013  }
3014
3015  VarDecl *getVarDecl() const {
3016    assert(chain().size() >= 2);
3017    return dyn_cast<VarDecl>(chain().front());
3018  }
3019
3020  IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
3021  const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
3022
3023  // Implement isa/cast/dyncast/etc.
3024  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3025  static bool classofKind(Kind K) { return K == IndirectField; }
3026};
3027
3028/// Represents a declaration of a type.
3029class TypeDecl : public NamedDecl {
3030  friend class ASTContext;
3031
3032  /// This indicates the Type object that represents
3033  /// this TypeDecl.  It is a cache maintained by
3034  /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
3035  /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
3036  mutable const Type *TypeForDecl = nullptr;
3037
3038  /// The start of the source range for this declaration.
3039  SourceLocation LocStart;
3040
3041  void anchor() override;
3042
3043protected:
3044  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
3045           SourceLocation StartL = SourceLocation())
3046    : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
3047
3048public:
3049  // Low-level accessor. If you just want the type defined by this node,
3050  // check out ASTContext::getTypeDeclType or one of
3051  // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
3052  // already know the specific kind of node this is.
3053  const Type *getTypeForDecl() const { return TypeForDecl; }
3054  void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
3055
3056  SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
3057  void setLocStart(SourceLocation L) { LocStart = L; }
3058  SourceRange getSourceRange() const override LLVM_READONLY {
3059    if (LocStart.isValid())
3060      return SourceRange(LocStart, getLocation());
3061    else
3062      return SourceRange(getLocation());
3063  }
3064
3065  // Implement isa/cast/dyncast/etc.
3066  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3067  static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
3068};
3069
3070/// Base class for declarations which introduce a typedef-name.
3071class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
3072  struct alignas(8) ModedTInfo {
3073    TypeSourceInfo *first;
3074    QualType second;
3075  };
3076
3077  /// If int part is 0, we have not computed IsTransparentTag.
3078  /// Otherwise, IsTransparentTag is (getInt() >> 1).
3079  mutable llvm::PointerIntPair<
3080      llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
3081      MaybeModedTInfo;
3082
3083  void anchor() override;
3084
3085protected:
3086  TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
3087                  SourceLocation StartLoc, SourceLocation IdLoc,
3088                  IdentifierInfo *Id, TypeSourceInfo *TInfo)
3089      : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3090        MaybeModedTInfo(TInfo, 0) {}
3091
3092  using redeclarable_base = Redeclarable<TypedefNameDecl>;
3093
3094  TypedefNameDecl *getNextRedeclarationImpl() override {
3095    return getNextRedeclaration();
3096  }
3097
3098  TypedefNameDecl *getPreviousDeclImpl() override {
3099    return getPreviousDecl();
3100  }
3101
3102  TypedefNameDecl *getMostRecentDeclImpl() override {
3103    return getMostRecentDecl();
3104  }
3105
3106public:
3107  using redecl_range = redeclarable_base::redecl_range;
3108  using redecl_iterator = redeclarable_base::redecl_iterator;
3109
3110  using redeclarable_base::redecls_begin;
3111  using redeclarable_base::redecls_end;
3112  using redeclarable_base::redecls;
3113  using redeclarable_base::getPreviousDecl;
3114  using redeclarable_base::getMostRecentDecl;
3115  using redeclarable_base::isFirstDecl;
3116
3117  bool isModed() const {
3118    return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3119  }
3120
3121  TypeSourceInfo *getTypeSourceInfo() const {
3122    return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3123                     : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3124  }
3125
3126  QualType getUnderlyingType() const {
3127    return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3128                     : MaybeModedTInfo.getPointer()
3129                           .get<TypeSourceInfo *>()
3130                           ->getType();
3131  }
3132
3133  void setTypeSourceInfo(TypeSourceInfo *newType) {
3134    MaybeModedTInfo.setPointer(newType);
3135  }
3136
3137  void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
3138    MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3139                                   ModedTInfo({unmodedTSI, modedTy}));
3140  }
3141
3142  /// Retrieves the canonical declaration of this typedef-name.
3143  TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
3144  const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3145
3146  /// Retrieves the tag declaration for which this is the typedef name for
3147  /// linkage purposes, if any.
3148  ///
3149  /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3150  /// this typedef declaration.
3151  TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3152
3153  /// Determines if this typedef shares a name and spelling location with its
3154  /// underlying tag type, as is the case with the NS_ENUM macro.
3155  bool isTransparentTag() const {
3156    if (MaybeModedTInfo.getInt())
3157      return MaybeModedTInfo.getInt() & 0x2;
3158    return isTransparentTagSlow();
3159  }
3160
3161  // Implement isa/cast/dyncast/etc.
3162  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3163  static bool classofKind(Kind K) {
3164    return K >= firstTypedefName && K <= lastTypedefName;
3165  }
3166
3167private:
3168  bool isTransparentTagSlow() const;
3169};
3170
3171/// Represents the declaration of a typedef-name via the 'typedef'
3172/// type specifier.
3173class TypedefDecl : public TypedefNameDecl {
3174  TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3175              SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3176      : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3177
3178public:
3179  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3180                             SourceLocation StartLoc, SourceLocation IdLoc,
3181                             IdentifierInfo *Id, TypeSourceInfo *TInfo);
3182  static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3183
3184  SourceRange getSourceRange() const override LLVM_READONLY;
3185
3186  // Implement isa/cast/dyncast/etc.
3187  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3188  static bool classofKind(Kind K) { return K == Typedef; }
3189};
3190
3191/// Represents the declaration of a typedef-name via a C++11
3192/// alias-declaration.
3193class TypeAliasDecl : public TypedefNameDecl {
3194  /// The template for which this is the pattern, if any.
3195  TypeAliasTemplateDecl *Template;
3196
3197  TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3198                SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3199      : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3200        Template(nullptr) {}
3201
3202public:
3203  static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3204                               SourceLocation StartLoc, SourceLocation IdLoc,
3205                               IdentifierInfo *Id, TypeSourceInfo *TInfo);
3206  static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3207
3208  SourceRange getSourceRange() const override LLVM_READONLY;
3209
3210  TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3211  void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3212
3213  // Implement isa/cast/dyncast/etc.
3214  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3215  static bool classofKind(Kind K) { return K == TypeAlias; }
3216};
3217
3218/// Represents the declaration of a struct/union/class/enum.
3219class TagDecl : public TypeDecl,
3220                public DeclContext,
3221                public Redeclarable<TagDecl> {
3222  // This class stores some data in DeclContext::TagDeclBits
3223  // to save some space. Use the provided accessors to access it.
3224public:
3225  // This is really ugly.
3226  using TagKind = TagTypeKind;
3227
3228private:
3229  SourceRange BraceRange;
3230
3231  // A struct representing syntactic qualifier info,
3232  // to be used for the (uncommon) case of out-of-line declarations.
3233  using ExtInfo = QualifierInfo;
3234
3235  /// If the (out-of-line) tag declaration name
3236  /// is qualified, it points to the qualifier info (nns and range);
3237  /// otherwise, if the tag declaration is anonymous and it is part of
3238  /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3239  /// otherwise, if the tag declaration is anonymous and it is used as a
3240  /// declaration specifier for variables, it points to the first VarDecl (used
3241  /// for mangling);
3242  /// otherwise, it is a null (TypedefNameDecl) pointer.
3243  llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3244
3245  bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3246  ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3247  const ExtInfo *getExtInfo() const {
3248    return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3249  }
3250
3251protected:
3252  TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3253          SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3254          SourceLocation StartL);
3255
3256  using redeclarable_base = Redeclarable<TagDecl>;
3257
3258  TagDecl *getNextRedeclarationImpl() override {
3259    return getNextRedeclaration();
3260  }
3261
3262  TagDecl *getPreviousDeclImpl() override {
3263    return getPreviousDecl();
3264  }
3265
3266  TagDecl *getMostRecentDeclImpl() override {
3267    return getMostRecentDecl();
3268  }
3269
3270  /// Completes the definition of this tag declaration.
3271  ///
3272  /// This is a helper function for derived classes.
3273  void completeDefinition();
3274
3275  /// True if this decl is currently being defined.
3276  void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3277
3278  /// Indicates whether it is possible for declarations of this kind
3279  /// to have an out-of-date definition.
3280  ///
3281  /// This option is only enabled when modules are enabled.
3282  void setMayHaveOutOfDateDef(bool V = true) {
3283    TagDeclBits.MayHaveOutOfDateDef = V;
3284  }
3285
3286public:
3287  friend class ASTDeclReader;
3288  friend class ASTDeclWriter;
3289
3290  using redecl_range = redeclarable_base::redecl_range;
3291  using redecl_iterator = redeclarable_base::redecl_iterator;
3292
3293  using redeclarable_base::redecls_begin;
3294  using redeclarable_base::redecls_end;
3295  using redeclarable_base::redecls;
3296  using redeclarable_base::getPreviousDecl;
3297  using redeclarable_base::getMostRecentDecl;
3298  using redeclarable_base::isFirstDecl;
3299
3300  SourceRange getBraceRange() const { return BraceRange; }
3301  void setBraceRange(SourceRange R) { BraceRange = R; }
3302
3303  /// Return SourceLocation representing start of source
3304  /// range ignoring outer template declarations.
3305  SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3306
3307  /// Return SourceLocation representing start of source
3308  /// range taking into account any outer template declarations.
3309  SourceLocation getOuterLocStart() const;
3310  SourceRange getSourceRange() const override LLVM_READONLY;
3311
3312  TagDecl *getCanonicalDecl() override;
3313  const TagDecl *getCanonicalDecl() const {
3314    return const_cast<TagDecl*>(this)->getCanonicalDecl();
3315  }
3316
3317  /// Return true if this declaration is a completion definition of the type.
3318  /// Provided for consistency.
3319  bool isThisDeclarationADefinition() const {
3320    return isCompleteDefinition();
3321  }
3322
3323  /// Return true if this decl has its body fully specified.
3324  bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3325
3326  /// True if this decl has its body fully specified.
3327  void setCompleteDefinition(bool V = true) {
3328    TagDeclBits.IsCompleteDefinition = V;
3329  }
3330
3331  /// Return true if this complete decl is
3332  /// required to be complete for some existing use.
3333  bool isCompleteDefinitionRequired() const {
3334    return TagDeclBits.IsCompleteDefinitionRequired;
3335  }
3336
3337  /// True if this complete decl is
3338  /// required to be complete for some existing use.
3339  void setCompleteDefinitionRequired(bool V = true) {
3340    TagDeclBits.IsCompleteDefinitionRequired = V;
3341  }
3342
3343  /// Return true if this decl is currently being defined.
3344  bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3345
3346  /// True if this tag declaration is "embedded" (i.e., defined or declared
3347  /// for the very first time) in the syntax of a declarator.
3348  bool isEmbeddedInDeclarator() const {
3349    return TagDeclBits.IsEmbeddedInDeclarator;
3350  }
3351
3352  /// True if this tag declaration is "embedded" (i.e., defined or declared
3353  /// for the very first time) in the syntax of a declarator.
3354  void setEmbeddedInDeclarator(bool isInDeclarator) {
3355    TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3356  }
3357
3358  /// True if this tag is free standing, e.g. "struct foo;".
3359  bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3360
3361  /// True if this tag is free standing, e.g. "struct foo;".
3362  void setFreeStanding(bool isFreeStanding = true) {
3363    TagDeclBits.IsFreeStanding = isFreeStanding;
3364  }
3365
3366  /// Indicates whether it is possible for declarations of this kind
3367  /// to have an out-of-date definition.
3368  ///
3369  /// This option is only enabled when modules are enabled.
3370  bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3371
3372  /// Whether this declaration declares a type that is
3373  /// dependent, i.e., a type that somehow depends on template
3374  /// parameters.
3375  bool isDependentType() const { return isDependentContext(); }
3376
3377  /// Starts the definition of this tag declaration.
3378  ///
3379  /// This method should be invoked at the beginning of the definition
3380  /// of this tag declaration. It will set the tag type into a state
3381  /// where it is in the process of being defined.
3382  void startDefinition();
3383
3384  /// Returns the TagDecl that actually defines this
3385  ///  struct/union/class/enum.  When determining whether or not a
3386  ///  struct/union/class/enum has a definition, one should use this
3387  ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
3388  ///  whether or not a specific TagDecl is defining declaration, not
3389  ///  whether or not the struct/union/class/enum type is defined.
3390  ///  This method returns NULL if there is no TagDecl that defines
3391  ///  the struct/union/class/enum.
3392  TagDecl *getDefinition() const;
3393
3394  StringRef getKindName() const {
3395    return TypeWithKeyword::getTagTypeKindName(getTagKind());
3396  }
3397
3398  TagKind getTagKind() const {
3399    return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3400  }
3401
3402  void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3403
3404  bool isStruct() const { return getTagKind() == TTK_Struct; }
3405  bool isInterface() const { return getTagKind() == TTK_Interface; }
3406  bool isClass()  const { return getTagKind() == TTK_Class; }
3407  bool isUnion()  const { return getTagKind() == TTK_Union; }
3408  bool isEnum()   const { return getTagKind() == TTK_Enum; }
3409
3410  /// Is this tag type named, either directly or via being defined in
3411  /// a typedef of this type?
3412  ///
3413  /// C++11 [basic.link]p8:
3414  ///   A type is said to have linkage if and only if:
3415  ///     - it is a class or enumeration type that is named (or has a
3416  ///       name for linkage purposes) and the name has linkage; ...
3417  /// C++11 [dcl.typedef]p9:
3418  ///   If the typedef declaration defines an unnamed class (or enum),
3419  ///   the first typedef-name declared by the declaration to be that
3420  ///   class type (or enum type) is used to denote the class type (or
3421  ///   enum type) for linkage purposes only.
3422  ///
3423  /// C does not have an analogous rule, but the same concept is
3424  /// nonetheless useful in some places.
3425  bool hasNameForLinkage() const {
3426    return (getDeclName() || getTypedefNameForAnonDecl());
3427  }
3428
3429  TypedefNameDecl *getTypedefNameForAnonDecl() const {
3430    return hasExtInfo() ? nullptr
3431                        : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3432  }
3433
3434  void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3435
3436  /// Retrieve the nested-name-specifier that qualifies the name of this
3437  /// declaration, if it was present in the source.
3438  NestedNameSpecifier *getQualifier() const {
3439    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3440                        : nullptr;
3441  }
3442
3443  /// Retrieve the nested-name-specifier (with source-location
3444  /// information) that qualifies the name of this declaration, if it was
3445  /// present in the source.
3446  NestedNameSpecifierLoc getQualifierLoc() const {
3447    return hasExtInfo() ? getExtInfo()->QualifierLoc
3448                        : NestedNameSpecifierLoc();
3449  }
3450
3451  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3452
3453  unsigned getNumTemplateParameterLists() const {
3454    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3455  }
3456
3457  TemplateParameterList *getTemplateParameterList(unsigned i) const {
3458    assert(i < getNumTemplateParameterLists());
3459    return getExtInfo()->TemplParamLists[i];
3460  }
3461
3462  void setTemplateParameterListsInfo(ASTContext &Context,
3463                                     ArrayRef<TemplateParameterList *> TPLists);
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 >= firstTag && K <= lastTag; }
3468
3469  static DeclContext *castToDeclContext(const TagDecl *D) {
3470    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3471  }
3472
3473  static TagDecl *castFromDeclContext(const DeclContext *DC) {
3474    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3475  }
3476};
3477
3478/// Represents an enum.  In C++11, enums can be forward-declared
3479/// with a fixed underlying type, and in C we allow them to be forward-declared
3480/// with no underlying type as an extension.
3481class EnumDecl : public TagDecl {
3482  // This class stores some data in DeclContext::EnumDeclBits
3483  // to save some space. Use the provided accessors to access it.
3484
3485  /// This represent the integer type that the enum corresponds
3486  /// to for code generation purposes.  Note that the enumerator constants may
3487  /// have a different type than this does.
3488  ///
3489  /// If the underlying integer type was explicitly stated in the source
3490  /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3491  /// was automatically deduced somehow, and this is a Type*.
3492  ///
3493  /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3494  /// some cases it won't.
3495  ///
3496  /// The underlying type of an enumeration never has any qualifiers, so
3497  /// we can get away with just storing a raw Type*, and thus save an
3498  /// extra pointer when TypeSourceInfo is needed.
3499  llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3500
3501  /// The integer type that values of this type should
3502  /// promote to.  In C, enumerators are generally of an integer type
3503  /// directly, but gcc-style large enumerators (and all enumerators
3504  /// in C++) are of the enum type instead.
3505  QualType PromotionType;
3506
3507  /// If this enumeration is an instantiation of a member enumeration
3508  /// of a class template specialization, this is the member specialization
3509  /// information.
3510  MemberSpecializationInfo *SpecializationInfo = nullptr;
3511
3512  /// Store the ODRHash after first calculation.
3513  /// The corresponding flag HasODRHash is in EnumDeclBits
3514  /// and can be accessed with the provided accessors.
3515  unsigned ODRHash;
3516
3517  EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3518           SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3519           bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3520
3521  void anchor() override;
3522
3523  void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3524                                    TemplateSpecializationKind TSK);
3525
3526  /// Sets the width in bits required to store all the
3527  /// non-negative enumerators of this enum.
3528  void setNumPositiveBits(unsigned Num) {
3529    EnumDeclBits.NumPositiveBits = Num;
3530    assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount");
3531  }
3532
3533  /// Returns the width in bits required to store all the
3534  /// negative enumerators of this enum. (see getNumNegativeBits)
3535  void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3536
3537  /// True if this tag declaration is a scoped enumeration. Only
3538  /// possible in C++11 mode.
3539  void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3540
3541  /// If this tag declaration is a scoped enum,
3542  /// then this is true if the scoped enum was declared using the class
3543  /// tag, false if it was declared with the struct tag. No meaning is
3544  /// associated if this tag declaration is not a scoped enum.
3545  void setScopedUsingClassTag(bool ScopedUCT = true) {
3546    EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3547  }
3548
3549  /// True if this is an Objective-C, C++11, or
3550  /// Microsoft-style enumeration with a fixed underlying type.
3551  void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3552
3553  /// True if a valid hash is stored in ODRHash.
3554  bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3555  void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3556
3557public:
3558  friend class ASTDeclReader;
3559
3560  EnumDecl *getCanonicalDecl() override {
3561    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3562  }
3563  const EnumDecl *getCanonicalDecl() const {
3564    return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3565  }
3566
3567  EnumDecl *getPreviousDecl() {
3568    return cast_or_null<EnumDecl>(
3569            static_cast<TagDecl *>(this)->getPreviousDecl());
3570  }
3571  const EnumDecl *getPreviousDecl() const {
3572    return const_cast<EnumDecl*>(this)->getPreviousDecl();
3573  }
3574
3575  EnumDecl *getMostRecentDecl() {
3576    return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3577  }
3578  const EnumDecl *getMostRecentDecl() const {
3579    return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3580  }
3581
3582  EnumDecl *getDefinition() const {
3583    return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3584  }
3585
3586  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3587                          SourceLocation StartLoc, SourceLocation IdLoc,
3588                          IdentifierInfo *Id, EnumDecl *PrevDecl,
3589                          bool IsScoped, bool IsScopedUsingClassTag,
3590                          bool IsFixed);
3591  static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3592
3593  /// When created, the EnumDecl corresponds to a
3594  /// forward-declared enum. This method is used to mark the
3595  /// declaration as being defined; its enumerators have already been
3596  /// added (via DeclContext::addDecl). NewType is the new underlying
3597  /// type of the enumeration type.
3598  void completeDefinition(QualType NewType,
3599                          QualType PromotionType,
3600                          unsigned NumPositiveBits,
3601                          unsigned NumNegativeBits);
3602
3603  // Iterates through the enumerators of this enumeration.
3604  using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3605  using enumerator_range =
3606      llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3607
3608  enumerator_range enumerators() const {
3609    return enumerator_range(enumerator_begin(), enumerator_end());
3610  }
3611
3612  enumerator_iterator enumerator_begin() const {
3613    const EnumDecl *E = getDefinition();
3614    if (!E)
3615      E = this;
3616    return enumerator_iterator(E->decls_begin());
3617  }
3618
3619  enumerator_iterator enumerator_end() const {
3620    const EnumDecl *E = getDefinition();
3621    if (!E)
3622      E = this;
3623    return enumerator_iterator(E->decls_end());
3624  }
3625
3626  /// Return the integer type that enumerators should promote to.
3627  QualType getPromotionType() const { return PromotionType; }
3628
3629  /// Set the promotion type.
3630  void setPromotionType(QualType T) { PromotionType = T; }
3631
3632  /// Return the integer type this enum decl corresponds to.
3633  /// This returns a null QualType for an enum forward definition with no fixed
3634  /// underlying type.
3635  QualType getIntegerType() const {
3636    if (!IntegerType)
3637      return QualType();
3638    if (const Type *T = IntegerType.dyn_cast<const Type*>())
3639      return QualType(T, 0);
3640    return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3641  }
3642
3643  /// Set the underlying integer type.
3644  void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3645
3646  /// Set the underlying integer type source info.
3647  void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3648
3649  /// Return the type source info for the underlying integer type,
3650  /// if no type source info exists, return 0.
3651  TypeSourceInfo *getIntegerTypeSourceInfo() const {
3652    return IntegerType.dyn_cast<TypeSourceInfo*>();
3653  }
3654
3655  /// Retrieve the source range that covers the underlying type if
3656  /// specified.
3657  SourceRange getIntegerTypeRange() const LLVM_READONLY;
3658
3659  /// Returns the width in bits required to store all the
3660  /// non-negative enumerators of this enum.
3661  unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3662
3663  /// Returns the width in bits required to store all the
3664  /// negative enumerators of this enum.  These widths include
3665  /// the rightmost leading 1;  that is:
3666  ///
3667  /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
3668  /// ------------------------     -------     -----------------
3669  ///                       -1     1111111                     1
3670  ///                      -10     1110110                     5
3671  ///                     -101     1001011                     8
3672  unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3673
3674  /// Returns true if this is a C++11 scoped enumeration.
3675  bool isScoped() const { return EnumDeclBits.IsScoped; }
3676
3677  /// Returns true if this is a C++11 scoped enumeration.
3678  bool isScopedUsingClassTag() const {
3679    return EnumDeclBits.IsScopedUsingClassTag;
3680  }
3681
3682  /// Returns true if this is an Objective-C, C++11, or
3683  /// Microsoft-style enumeration with a fixed underlying type.
3684  bool isFixed() const { return EnumDeclBits.IsFixed; }
3685
3686  unsigned getODRHash();
3687
3688  /// Returns true if this can be considered a complete type.
3689  bool isComplete() const {
3690    // IntegerType is set for fixed type enums and non-fixed but implicitly
3691    // int-sized Microsoft enums.
3692    return isCompleteDefinition() || IntegerType;
3693  }
3694
3695  /// Returns true if this enum is either annotated with
3696  /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3697  bool isClosed() const;
3698
3699  /// Returns true if this enum is annotated with flag_enum and isn't annotated
3700  /// with enum_extensibility(open).
3701  bool isClosedFlag() const;
3702
3703  /// Returns true if this enum is annotated with neither flag_enum nor
3704  /// enum_extensibility(open).
3705  bool isClosedNonFlag() const;
3706
3707  /// Retrieve the enum definition from which this enumeration could
3708  /// be instantiated, if it is an instantiation (rather than a non-template).
3709  EnumDecl *getTemplateInstantiationPattern() const;
3710
3711  /// Returns the enumeration (declared within the template)
3712  /// from which this enumeration type was instantiated, or NULL if
3713  /// this enumeration was not instantiated from any template.
3714  EnumDecl *getInstantiatedFromMemberEnum() const;
3715
3716  /// If this enumeration is a member of a specialization of a
3717  /// templated class, determine what kind of template specialization
3718  /// or instantiation this is.
3719  TemplateSpecializationKind getTemplateSpecializationKind() const;
3720
3721  /// For an enumeration member that was instantiated from a member
3722  /// enumeration of a templated class, set the template specialiation kind.
3723  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3724                        SourceLocation PointOfInstantiation = SourceLocation());
3725
3726  /// If this enumeration is an instantiation of a member enumeration of
3727  /// a class template specialization, retrieves the member specialization
3728  /// information.
3729  MemberSpecializationInfo *getMemberSpecializationInfo() const {
3730    return SpecializationInfo;
3731  }
3732
3733  /// Specify that this enumeration is an instantiation of the
3734  /// member enumeration ED.
3735  void setInstantiationOfMemberEnum(EnumDecl *ED,
3736                                    TemplateSpecializationKind TSK) {
3737    setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3738  }
3739
3740  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3741  static bool classofKind(Kind K) { return K == Enum; }
3742};
3743
3744/// Represents a struct/union/class.  For example:
3745///   struct X;                  // Forward declaration, no "body".
3746///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
3747/// This decl will be marked invalid if *any* members are invalid.
3748class RecordDecl : public TagDecl {
3749  // This class stores some data in DeclContext::RecordDeclBits
3750  // to save some space. Use the provided accessors to access it.
3751public:
3752  friend class DeclContext;
3753  /// Enum that represents the different ways arguments are passed to and
3754  /// returned from function calls. This takes into account the target-specific
3755  /// and version-specific rules along with the rules determined by the
3756  /// language.
3757  enum ArgPassingKind : unsigned {
3758    /// The argument of this type can be passed directly in registers.
3759    APK_CanPassInRegs,
3760
3761    /// The argument of this type cannot be passed directly in registers.
3762    /// Records containing this type as a subobject are not forced to be passed
3763    /// indirectly. This value is used only in C++. This value is required by
3764    /// C++ because, in uncommon situations, it is possible for a class to have
3765    /// only trivial copy/move constructors even when one of its subobjects has
3766    /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3767    /// constructor in the derived class is deleted).
3768    APK_CannotPassInRegs,
3769
3770    /// The argument of this type cannot be passed directly in registers.
3771    /// Records containing this type as a subobject are forced to be passed
3772    /// indirectly.
3773    APK_CanNeverPassInRegs
3774  };
3775
3776protected:
3777  RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3778             SourceLocation StartLoc, SourceLocation IdLoc,
3779             IdentifierInfo *Id, RecordDecl *PrevDecl);
3780
3781public:
3782  static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3783                            SourceLocation StartLoc, SourceLocation IdLoc,
3784                            IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3785  static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3786
3787  RecordDecl *getPreviousDecl() {
3788    return cast_or_null<RecordDecl>(
3789            static_cast<TagDecl *>(this)->getPreviousDecl());
3790  }
3791  const RecordDecl *getPreviousDecl() const {
3792    return const_cast<RecordDecl*>(this)->getPreviousDecl();
3793  }
3794
3795  RecordDecl *getMostRecentDecl() {
3796    return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3797  }
3798  const RecordDecl *getMostRecentDecl() const {
3799    return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3800  }
3801
3802  bool hasFlexibleArrayMember() const {
3803    return RecordDeclBits.HasFlexibleArrayMember;
3804  }
3805
3806  void setHasFlexibleArrayMember(bool V) {
3807    RecordDeclBits.HasFlexibleArrayMember = V;
3808  }
3809
3810  /// Whether this is an anonymous struct or union. To be an anonymous
3811  /// struct or union, it must have been declared without a name and
3812  /// there must be no objects of this type declared, e.g.,
3813  /// @code
3814  ///   union { int i; float f; };
3815  /// @endcode
3816  /// is an anonymous union but neither of the following are:
3817  /// @code
3818  ///  union X { int i; float f; };
3819  ///  union { int i; float f; } obj;
3820  /// @endcode
3821  bool isAnonymousStructOrUnion() const {
3822    return RecordDeclBits.AnonymousStructOrUnion;
3823  }
3824
3825  void setAnonymousStructOrUnion(bool Anon) {
3826    RecordDeclBits.AnonymousStructOrUnion = Anon;
3827  }
3828
3829  bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3830  void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3831
3832  bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3833
3834  void setHasVolatileMember(bool val) {
3835    RecordDeclBits.HasVolatileMember = val;
3836  }
3837
3838  bool hasLoadedFieldsFromExternalStorage() const {
3839    return RecordDeclBits.LoadedFieldsFromExternalStorage;
3840  }
3841
3842  void setHasLoadedFieldsFromExternalStorage(bool val) const {
3843    RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3844  }
3845
3846  /// Functions to query basic properties of non-trivial C structs.
3847  bool isNonTrivialToPrimitiveDefaultInitialize() const {
3848    return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3849  }
3850
3851  void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3852    RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3853  }
3854
3855  bool isNonTrivialToPrimitiveCopy() const {
3856    return RecordDeclBits.NonTrivialToPrimitiveCopy;
3857  }
3858
3859  void setNonTrivialToPrimitiveCopy(bool V) {
3860    RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3861  }
3862
3863  bool isNonTrivialToPrimitiveDestroy() const {
3864    return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3865  }
3866
3867  void setNonTrivialToPrimitiveDestroy(bool V) {
3868    RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3869  }
3870
3871  bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
3872    return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
3873  }
3874
3875  void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
3876    RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
3877  }
3878
3879  bool hasNonTrivialToPrimitiveDestructCUnion() const {
3880    return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
3881  }
3882
3883  void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
3884    RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
3885  }
3886
3887  bool hasNonTrivialToPrimitiveCopyCUnion() const {
3888    return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
3889  }
3890
3891  void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
3892    RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
3893  }
3894
3895  /// Determine whether this class can be passed in registers. In C++ mode,
3896  /// it must have at least one trivial, non-deleted copy or move constructor.
3897  /// FIXME: This should be set as part of completeDefinition.
3898  bool canPassInRegisters() const {
3899    return getArgPassingRestrictions() == APK_CanPassInRegs;
3900  }
3901
3902  ArgPassingKind getArgPassingRestrictions() const {
3903    return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3904  }
3905
3906  void setArgPassingRestrictions(ArgPassingKind Kind) {
3907    RecordDeclBits.ArgPassingRestrictions = Kind;
3908  }
3909
3910  bool isParamDestroyedInCallee() const {
3911    return RecordDeclBits.ParamDestroyedInCallee;
3912  }
3913
3914  void setParamDestroyedInCallee(bool V) {
3915    RecordDeclBits.ParamDestroyedInCallee = V;
3916  }
3917
3918  /// Determines whether this declaration represents the
3919  /// injected class name.
3920  ///
3921  /// The injected class name in C++ is the name of the class that
3922  /// appears inside the class itself. For example:
3923  ///
3924  /// \code
3925  /// struct C {
3926  ///   // C is implicitly declared here as a synonym for the class name.
3927  /// };
3928  ///
3929  /// C::C c; // same as "C c;"
3930  /// \endcode
3931  bool isInjectedClassName() const;
3932
3933  /// Determine whether this record is a class describing a lambda
3934  /// function object.
3935  bool isLambda() const;
3936
3937  /// Determine whether this record is a record for captured variables in
3938  /// CapturedStmt construct.
3939  bool isCapturedRecord() const;
3940
3941  /// Mark the record as a record for captured variables in CapturedStmt
3942  /// construct.
3943  void setCapturedRecord();
3944
3945  /// Returns the RecordDecl that actually defines
3946  ///  this struct/union/class.  When determining whether or not a
3947  ///  struct/union/class is completely defined, one should use this
3948  ///  method as opposed to 'isCompleteDefinition'.
3949  ///  'isCompleteDefinition' indicates whether or not a specific
3950  ///  RecordDecl is a completed definition, not whether or not the
3951  ///  record type is defined.  This method returns NULL if there is
3952  ///  no RecordDecl that defines the struct/union/tag.
3953  RecordDecl *getDefinition() const {
3954    return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3955  }
3956
3957  // Iterator access to field members. The field iterator only visits
3958  // the non-static data members of this class, ignoring any static
3959  // data members, functions, constructors, destructors, etc.
3960  using field_iterator = specific_decl_iterator<FieldDecl>;
3961  using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3962
3963  field_range fields() const { return field_range(field_begin(), field_end()); }
3964  field_iterator field_begin() const;
3965
3966  field_iterator field_end() const {
3967    return field_iterator(decl_iterator());
3968  }
3969
3970  // Whether there are any fields (non-static data members) in this record.
3971  bool field_empty() const {
3972    return field_begin() == field_end();
3973  }
3974
3975  /// Note that the definition of this type is now complete.
3976  virtual void completeDefinition();
3977
3978  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3979  static bool classofKind(Kind K) {
3980    return K >= firstRecord && K <= lastRecord;
3981  }
3982
3983  /// Get whether or not this is an ms_struct which can
3984  /// be turned on with an attribute, pragma, or -mms-bitfields
3985  /// commandline option.
3986  bool isMsStruct(const ASTContext &C) const;
3987
3988  /// Whether we are allowed to insert extra padding between fields.
3989  /// These padding are added to help AddressSanitizer detect
3990  /// intra-object-overflow bugs.
3991  bool mayInsertExtraPadding(bool EmitRemark = false) const;
3992
3993  /// Finds the first data member which has a name.
3994  /// nullptr is returned if no named data member exists.
3995  const FieldDecl *findFirstNamedDataMember() const;
3996
3997private:
3998  /// Deserialize just the fields.
3999  void LoadFieldsFromExternalStorage() const;
4000};
4001
4002class FileScopeAsmDecl : public Decl {
4003  StringLiteral *AsmString;
4004  SourceLocation RParenLoc;
4005
4006  FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
4007                   SourceLocation StartL, SourceLocation EndL)
4008    : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
4009
4010  virtual void anchor();
4011
4012public:
4013  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
4014                                  StringLiteral *Str, SourceLocation AsmLoc,
4015                                  SourceLocation RParenLoc);
4016
4017  static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4018
4019  SourceLocation getAsmLoc() const { return getLocation(); }
4020  SourceLocation getRParenLoc() const { return RParenLoc; }
4021  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4022  SourceRange getSourceRange() const override LLVM_READONLY {
4023    return SourceRange(getAsmLoc(), getRParenLoc());
4024  }
4025
4026  const StringLiteral *getAsmString() const { return AsmString; }
4027  StringLiteral *getAsmString() { return AsmString; }
4028  void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
4029
4030  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4031  static bool classofKind(Kind K) { return K == FileScopeAsm; }
4032};
4033
4034/// Represents a block literal declaration, which is like an
4035/// unnamed FunctionDecl.  For example:
4036/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
4037class BlockDecl : public Decl, public DeclContext {
4038  // This class stores some data in DeclContext::BlockDeclBits
4039  // to save some space. Use the provided accessors to access it.
4040public:
4041  /// A class which contains all the information about a particular
4042  /// captured value.
4043  class Capture {
4044    enum {
4045      flag_isByRef = 0x1,
4046      flag_isNested = 0x2
4047    };
4048
4049    /// The variable being captured.
4050    llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
4051
4052    /// The copy expression, expressed in terms of a DeclRef (or
4053    /// BlockDeclRef) to the captured variable.  Only required if the
4054    /// variable has a C++ class type.
4055    Expr *CopyExpr;
4056
4057  public:
4058    Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
4059      : VariableAndFlags(variable,
4060                  (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
4061        CopyExpr(copy) {}
4062
4063    /// The variable being captured.
4064    VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
4065
4066    /// Whether this is a "by ref" capture, i.e. a capture of a __block
4067    /// variable.
4068    bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
4069
4070    bool isEscapingByref() const {
4071      return getVariable()->isEscapingByref();
4072    }
4073
4074    bool isNonEscapingByref() const {
4075      return getVariable()->isNonEscapingByref();
4076    }
4077
4078    /// Whether this is a nested capture, i.e. the variable captured
4079    /// is not from outside the immediately enclosing function/block.
4080    bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
4081
4082    bool hasCopyExpr() const { return CopyExpr != nullptr; }
4083    Expr *getCopyExpr() const { return CopyExpr; }
4084    void setCopyExpr(Expr *e) { CopyExpr = e; }
4085  };
4086
4087private:
4088  /// A new[]'d array of pointers to ParmVarDecls for the formal
4089  /// parameters of this function.  This is null if a prototype or if there are
4090  /// no formals.
4091  ParmVarDecl **ParamInfo = nullptr;
4092  unsigned NumParams = 0;
4093
4094  Stmt *Body = nullptr;
4095  TypeSourceInfo *SignatureAsWritten = nullptr;
4096
4097  const Capture *Captures = nullptr;
4098  unsigned NumCaptures = 0;
4099
4100  unsigned ManglingNumber = 0;
4101  Decl *ManglingContextDecl = nullptr;
4102
4103protected:
4104  BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
4105
4106public:
4107  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
4108  static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4109
4110  SourceLocation getCaretLocation() const { return getLocation(); }
4111
4112  bool isVariadic() const { return BlockDeclBits.IsVariadic; }
4113  void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
4114
4115  CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
4116  Stmt *getBody() const override { return (Stmt*) Body; }
4117  void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
4118
4119  void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
4120  TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
4121
4122  // ArrayRef access to formal parameters.
4123  ArrayRef<ParmVarDecl *> parameters() const {
4124    return {ParamInfo, getNumParams()};
4125  }
4126  MutableArrayRef<ParmVarDecl *> parameters() {
4127    return {ParamInfo, getNumParams()};
4128  }
4129
4130  // Iterator access to formal parameters.
4131  using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
4132  using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
4133
4134  bool param_empty() const { return parameters().empty(); }
4135  param_iterator param_begin() { return parameters().begin(); }
4136  param_iterator param_end() { return parameters().end(); }
4137  param_const_iterator param_begin() const { return parameters().begin(); }
4138  param_const_iterator param_end() const { return parameters().end(); }
4139  size_t param_size() const { return parameters().size(); }
4140
4141  unsigned getNumParams() const { return NumParams; }
4142
4143  const ParmVarDecl *getParamDecl(unsigned i) const {
4144    assert(i < getNumParams() && "Illegal param #");
4145    return ParamInfo[i];
4146  }
4147  ParmVarDecl *getParamDecl(unsigned i) {
4148    assert(i < getNumParams() && "Illegal param #");
4149    return ParamInfo[i];
4150  }
4151
4152  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
4153
4154  /// True if this block (or its nested blocks) captures
4155  /// anything of local storage from its enclosing scopes.
4156  bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
4157
4158  /// Returns the number of captured variables.
4159  /// Does not include an entry for 'this'.
4160  unsigned getNumCaptures() const { return NumCaptures; }
4161
4162  using capture_const_iterator = ArrayRef<Capture>::const_iterator;
4163
4164  ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
4165
4166  capture_const_iterator capture_begin() const { return captures().begin(); }
4167  capture_const_iterator capture_end() const { return captures().end(); }
4168
4169  bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4170  void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4171
4172  bool blockMissingReturnType() const {
4173    return BlockDeclBits.BlockMissingReturnType;
4174  }
4175
4176  void setBlockMissingReturnType(bool val = true) {
4177    BlockDeclBits.BlockMissingReturnType = val;
4178  }
4179
4180  bool isConversionFromLambda() const {
4181    return BlockDeclBits.IsConversionFromLambda;
4182  }
4183
4184  void setIsConversionFromLambda(bool val = true) {
4185    BlockDeclBits.IsConversionFromLambda = val;
4186  }
4187
4188  bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4189  void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4190
4191  bool canAvoidCopyToHeap() const {
4192    return BlockDeclBits.CanAvoidCopyToHeap;
4193  }
4194  void setCanAvoidCopyToHeap(bool B = true) {
4195    BlockDeclBits.CanAvoidCopyToHeap = B;
4196  }
4197
4198  bool capturesVariable(const VarDecl *var) const;
4199
4200  void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4201                   bool CapturesCXXThis);
4202
4203  unsigned getBlockManglingNumber() const { return ManglingNumber; }
4204
4205  Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
4206
4207  void setBlockMangling(unsigned Number, Decl *Ctx) {
4208    ManglingNumber = Number;
4209    ManglingContextDecl = Ctx;
4210  }
4211
4212  SourceRange getSourceRange() const override LLVM_READONLY;
4213
4214  // Implement isa/cast/dyncast/etc.
4215  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4216  static bool classofKind(Kind K) { return K == Block; }
4217  static DeclContext *castToDeclContext(const BlockDecl *D) {
4218    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4219  }
4220  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4221    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4222  }
4223};
4224
4225/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4226class CapturedDecl final
4227    : public Decl,
4228      public DeclContext,
4229      private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4230protected:
4231  size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4232    return NumParams;
4233  }
4234
4235private:
4236  /// The number of parameters to the outlined function.
4237  unsigned NumParams;
4238
4239  /// The position of context parameter in list of parameters.
4240  unsigned ContextParam;
4241
4242  /// The body of the outlined function.
4243  llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4244
4245  explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4246
4247  ImplicitParamDecl *const *getParams() const {
4248    return getTrailingObjects<ImplicitParamDecl *>();
4249  }
4250
4251  ImplicitParamDecl **getParams() {
4252    return getTrailingObjects<ImplicitParamDecl *>();
4253  }
4254
4255public:
4256  friend class ASTDeclReader;
4257  friend class ASTDeclWriter;
4258  friend TrailingObjects;
4259
4260  static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4261                              unsigned NumParams);
4262  static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4263                                          unsigned NumParams);
4264
4265  Stmt *getBody() const override;
4266  void setBody(Stmt *B);
4267
4268  bool isNothrow() const;
4269  void setNothrow(bool Nothrow = true);
4270
4271  unsigned getNumParams() const { return NumParams; }
4272
4273  ImplicitParamDecl *getParam(unsigned i) const {
4274    assert(i < NumParams);
4275    return getParams()[i];
4276  }
4277  void setParam(unsigned i, ImplicitParamDecl *P) {
4278    assert(i < NumParams);
4279    getParams()[i] = P;
4280  }
4281
4282  // ArrayRef interface to parameters.
4283  ArrayRef<ImplicitParamDecl *> parameters() const {
4284    return {getParams(), getNumParams()};
4285  }
4286  MutableArrayRef<ImplicitParamDecl *> parameters() {
4287    return {getParams(), getNumParams()};
4288  }
4289
4290  /// Retrieve the parameter containing captured variables.
4291  ImplicitParamDecl *getContextParam() const {
4292    assert(ContextParam < NumParams);
4293    return getParam(ContextParam);
4294  }
4295  void setContextParam(unsigned i, ImplicitParamDecl *P) {
4296    assert(i < NumParams);
4297    ContextParam = i;
4298    setParam(i, P);
4299  }
4300  unsigned getContextParamPosition() const { return ContextParam; }
4301
4302  using param_iterator = ImplicitParamDecl *const *;
4303  using param_range = llvm::iterator_range<param_iterator>;
4304
4305  /// Retrieve an iterator pointing to the first parameter decl.
4306  param_iterator param_begin() const { return getParams(); }
4307  /// Retrieve an iterator one past the last parameter decl.
4308  param_iterator param_end() const { return getParams() + NumParams; }
4309
4310  // Implement isa/cast/dyncast/etc.
4311  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4312  static bool classofKind(Kind K) { return K == Captured; }
4313  static DeclContext *castToDeclContext(const CapturedDecl *D) {
4314    return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4315  }
4316  static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4317    return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4318  }
4319};
4320
4321/// Describes a module import declaration, which makes the contents
4322/// of the named module visible in the current translation unit.
4323///
4324/// An import declaration imports the named module (or submodule). For example:
4325/// \code
4326///   @import std.vector;
4327/// \endcode
4328///
4329/// Import declarations can also be implicitly generated from
4330/// \#include/\#import directives.
4331class ImportDecl final : public Decl,
4332                         llvm::TrailingObjects<ImportDecl, SourceLocation> {
4333  friend class ASTContext;
4334  friend class ASTDeclReader;
4335  friend class ASTReader;
4336  friend TrailingObjects;
4337
4338  /// The imported module, along with a bit that indicates whether
4339  /// we have source-location information for each identifier in the module
4340  /// name.
4341  ///
4342  /// When the bit is false, we only have a single source location for the
4343  /// end of the import declaration.
4344  llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4345
4346  /// The next import in the list of imports local to the translation
4347  /// unit being parsed (not loaded from an AST file).
4348  ImportDecl *NextLocalImport = nullptr;
4349
4350  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4351             ArrayRef<SourceLocation> IdentifierLocs);
4352
4353  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4354             SourceLocation EndLoc);
4355
4356  ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4357
4358public:
4359  /// Create a new module import declaration.
4360  static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4361                            SourceLocation StartLoc, Module *Imported,
4362                            ArrayRef<SourceLocation> IdentifierLocs);
4363
4364  /// Create a new module import declaration for an implicitly-generated
4365  /// import.
4366  static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4367                                    SourceLocation StartLoc, Module *Imported,
4368                                    SourceLocation EndLoc);
4369
4370  /// Create a new, deserialized module import declaration.
4371  static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4372                                        unsigned NumLocations);
4373
4374  /// Retrieve the module that was imported by the import declaration.
4375  Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4376
4377  /// Retrieves the locations of each of the identifiers that make up
4378  /// the complete module name in the import declaration.
4379  ///
4380  /// This will return an empty array if the locations of the individual
4381  /// identifiers aren't available.
4382  ArrayRef<SourceLocation> getIdentifierLocs() const;
4383
4384  SourceRange getSourceRange() const override LLVM_READONLY;
4385
4386  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4387  static bool classofKind(Kind K) { return K == Import; }
4388};
4389
4390/// Represents a C++ Modules TS module export declaration.
4391///
4392/// For example:
4393/// \code
4394///   export void foo();
4395/// \endcode
4396class ExportDecl final : public Decl, public DeclContext {
4397  virtual void anchor();
4398
4399private:
4400  friend class ASTDeclReader;
4401
4402  /// The source location for the right brace (if valid).
4403  SourceLocation RBraceLoc;
4404
4405  ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4406      : Decl(Export, DC, ExportLoc), DeclContext(Export),
4407        RBraceLoc(SourceLocation()) {}
4408
4409public:
4410  static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4411                            SourceLocation ExportLoc);
4412  static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4413
4414  SourceLocation getExportLoc() const { return getLocation(); }
4415  SourceLocation getRBraceLoc() const { return RBraceLoc; }
4416  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4417
4418  bool hasBraces() const { return RBraceLoc.isValid(); }
4419
4420  SourceLocation getEndLoc() const LLVM_READONLY {
4421    if (hasBraces())
4422      return RBraceLoc;
4423    // No braces: get the end location of the (only) declaration in context
4424    // (if present).
4425    return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4426  }
4427
4428  SourceRange getSourceRange() const override LLVM_READONLY {
4429    return SourceRange(getLocation(), getEndLoc());
4430  }
4431
4432  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4433  static bool classofKind(Kind K) { return K == Export; }
4434  static DeclContext *castToDeclContext(const ExportDecl *D) {
4435    return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4436  }
4437  static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4438    return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4439  }
4440};
4441
4442/// Represents an empty-declaration.
4443class EmptyDecl : public Decl {
4444  EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4445
4446  virtual void anchor();
4447
4448public:
4449  static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4450                           SourceLocation L);
4451  static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4452
4453  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4454  static bool classofKind(Kind K) { return K == Empty; }
4455};
4456
4457/// Insertion operator for diagnostics.  This allows sending NamedDecl's
4458/// into a diagnostic with <<.
4459inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4460                                           const NamedDecl* ND) {
4461  DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4462                  DiagnosticsEngine::ak_nameddecl);
4463  return DB;
4464}
4465inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4466                                           const NamedDecl* ND) {
4467  PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4468                  DiagnosticsEngine::ak_nameddecl);
4469  return PD;
4470}
4471
4472template<typename decl_type>
4473void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4474  // Note: This routine is implemented here because we need both NamedDecl
4475  // and Redeclarable to be defined.
4476  assert(RedeclLink.isFirst() &&
4477         "setPreviousDecl on a decl already in a redeclaration chain");
4478
4479  if (PrevDecl) {
4480    // Point to previous. Make sure that this is actually the most recent
4481    // redeclaration, or we can build invalid chains. If the most recent
4482    // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4483    First = PrevDecl->getFirstDecl();
4484    assert(First->RedeclLink.isFirst() && "Expected first");
4485    decl_type *MostRecent = First->getNextRedeclaration();
4486    RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4487
4488    // If the declaration was previously visible, a redeclaration of it remains
4489    // visible even if it wouldn't be visible by itself.
4490    static_cast<decl_type*>(this)->IdentifierNamespace |=
4491      MostRecent->getIdentifierNamespace() &
4492      (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4493  } else {
4494    // Make this first.
4495    First = static_cast<decl_type*>(this);
4496  }
4497
4498  // First one will point to this one as latest.
4499  First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4500
4501  assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
4502         cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
4503}
4504
4505// Inline function definitions.
4506
4507/// Check if the given decl is complete.
4508///
4509/// We use this function to break a cycle between the inline definitions in
4510/// Type.h and Decl.h.
4511inline bool IsEnumDeclComplete(EnumDecl *ED) {
4512  return ED->isComplete();
4513}
4514
4515/// Check if the given decl is scoped.
4516///
4517/// We use this function to break a cycle between the inline definitions in
4518/// Type.h and Decl.h.
4519inline bool IsEnumDeclScoped(EnumDecl *ED) {
4520  return ED->isScoped();
4521}
4522
4523} // namespace clang
4524
4525#endif // LLVM_CLANG_AST_DECL_H
4526