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  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. Valid for e.g.
2129  /// special member functions, defaulted comparisions (not methods!).
2130  bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2131  void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2132
2133  /// Whether this function is explicitly defaulted.
2134  bool isExplicitlyDefaulted() const {
2135    return FunctionDeclBits.IsExplicitlyDefaulted;
2136  }
2137
2138  /// State that this function is explicitly defaulted.
2139  void setExplicitlyDefaulted(bool ED = true) {
2140    FunctionDeclBits.IsExplicitlyDefaulted = ED;
2141  }
2142
2143  /// True if this method is user-declared and was not
2144  /// deleted or defaulted on its first declaration.
2145  bool isUserProvided() const {
2146    auto *DeclAsWritten = this;
2147    if (FunctionDecl *Pattern = getTemplateInstantiationPattern())
2148      DeclAsWritten = Pattern;
2149    return !(DeclAsWritten->isDeleted() ||
2150             DeclAsWritten->getCanonicalDecl()->isDefaulted());
2151  }
2152
2153  /// Whether falling off this function implicitly returns null/zero.
2154  /// If a more specific implicit return value is required, front-ends
2155  /// should synthesize the appropriate return statements.
2156  bool hasImplicitReturnZero() const {
2157    return FunctionDeclBits.HasImplicitReturnZero;
2158  }
2159
2160  /// State that falling off this function implicitly returns null/zero.
2161  /// If a more specific implicit return value is required, front-ends
2162  /// should synthesize the appropriate return statements.
2163  void setHasImplicitReturnZero(bool IRZ) {
2164    FunctionDeclBits.HasImplicitReturnZero = IRZ;
2165  }
2166
2167  /// Whether this function has a prototype, either because one
2168  /// was explicitly written or because it was "inherited" by merging
2169  /// a declaration without a prototype with a declaration that has a
2170  /// prototype.
2171  bool hasPrototype() const {
2172    return hasWrittenPrototype() || hasInheritedPrototype();
2173  }
2174
2175  /// Whether this function has a written prototype.
2176  bool hasWrittenPrototype() const {
2177    return FunctionDeclBits.HasWrittenPrototype;
2178  }
2179
2180  /// State that this function has a written prototype.
2181  void setHasWrittenPrototype(bool P = true) {
2182    FunctionDeclBits.HasWrittenPrototype = P;
2183  }
2184
2185  /// Whether this function inherited its prototype from a
2186  /// previous declaration.
2187  bool hasInheritedPrototype() const {
2188    return FunctionDeclBits.HasInheritedPrototype;
2189  }
2190
2191  /// State that this function inherited its prototype from a
2192  /// previous declaration.
2193  void setHasInheritedPrototype(bool P = true) {
2194    FunctionDeclBits.HasInheritedPrototype = P;
2195  }
2196
2197  /// Whether this is a (C++11) constexpr function or constexpr constructor.
2198  bool isConstexpr() const {
2199    return FunctionDeclBits.ConstexprKind != CSK_unspecified;
2200  }
2201  void setConstexprKind(ConstexprSpecKind CSK) {
2202    FunctionDeclBits.ConstexprKind = CSK;
2203  }
2204  ConstexprSpecKind getConstexprKind() const {
2205    return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2206  }
2207  bool isConstexprSpecified() const {
2208    return FunctionDeclBits.ConstexprKind == CSK_constexpr;
2209  }
2210  bool isConsteval() const {
2211    return FunctionDeclBits.ConstexprKind == CSK_consteval;
2212  }
2213
2214  /// Whether the instantiation of this function is pending.
2215  /// This bit is set when the decision to instantiate this function is made
2216  /// and unset if and when the function body is created. That leaves out
2217  /// cases where instantiation did not happen because the template definition
2218  /// was not seen in this TU. This bit remains set in those cases, under the
2219  /// assumption that the instantiation will happen in some other TU.
2220  bool instantiationIsPending() const {
2221    return FunctionDeclBits.InstantiationIsPending;
2222  }
2223
2224  /// State that the instantiation of this function is pending.
2225  /// (see instantiationIsPending)
2226  void setInstantiationIsPending(bool IC) {
2227    FunctionDeclBits.InstantiationIsPending = IC;
2228  }
2229
2230  /// Indicates the function uses __try.
2231  bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2232  void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2233
2234  /// Indicates the function uses Floating Point constrained intrinsics
2235  bool usesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }
2236  void setUsesFPIntrin(bool Val) { FunctionDeclBits.UsesFPIntrin = Val; }
2237
2238  /// Whether this function has been deleted.
2239  ///
2240  /// A function that is "deleted" (via the C++0x "= delete" syntax)
2241  /// acts like a normal function, except that it cannot actually be
2242  /// called or have its address taken. Deleted functions are
2243  /// typically used in C++ overload resolution to attract arguments
2244  /// whose type or lvalue/rvalue-ness would permit the use of a
2245  /// different overload that would behave incorrectly. For example,
2246  /// one might use deleted functions to ban implicit conversion from
2247  /// a floating-point number to an Integer type:
2248  ///
2249  /// @code
2250  /// struct Integer {
2251  ///   Integer(long); // construct from a long
2252  ///   Integer(double) = delete; // no construction from float or double
2253  ///   Integer(long double) = delete; // no construction from long double
2254  /// };
2255  /// @endcode
2256  // If a function is deleted, its first declaration must be.
2257  bool isDeleted() const {
2258    return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2259  }
2260
2261  bool isDeletedAsWritten() const {
2262    return FunctionDeclBits.IsDeleted && !isDefaulted();
2263  }
2264
2265  void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2266
2267  /// Determines whether this function is "main", which is the
2268  /// entry point into an executable program.
2269  bool isMain() const;
2270
2271  /// Determines whether this function is a MSVCRT user defined entry
2272  /// point.
2273  bool isMSVCRTEntryPoint() const;
2274
2275  /// Determines whether this operator new or delete is one
2276  /// of the reserved global placement operators:
2277  ///    void *operator new(size_t, void *);
2278  ///    void *operator new[](size_t, void *);
2279  ///    void operator delete(void *, void *);
2280  ///    void operator delete[](void *, void *);
2281  /// These functions have special behavior under [new.delete.placement]:
2282  ///    These functions are reserved, a C++ program may not define
2283  ///    functions that displace the versions in the Standard C++ library.
2284  ///    The provisions of [basic.stc.dynamic] do not apply to these
2285  ///    reserved placement forms of operator new and operator delete.
2286  ///
2287  /// This function must be an allocation or deallocation function.
2288  bool isReservedGlobalPlacementOperator() const;
2289
2290  /// Determines whether this function is one of the replaceable
2291  /// global allocation functions:
2292  ///    void *operator new(size_t);
2293  ///    void *operator new(size_t, const std::nothrow_t &) noexcept;
2294  ///    void *operator new[](size_t);
2295  ///    void *operator new[](size_t, const std::nothrow_t &) noexcept;
2296  ///    void operator delete(void *) noexcept;
2297  ///    void operator delete(void *, std::size_t) noexcept;      [C++1y]
2298  ///    void operator delete(void *, const std::nothrow_t &) noexcept;
2299  ///    void operator delete[](void *) noexcept;
2300  ///    void operator delete[](void *, std::size_t) noexcept;    [C++1y]
2301  ///    void operator delete[](void *, const std::nothrow_t &) noexcept;
2302  /// These functions have special behavior under C++1y [expr.new]:
2303  ///    An implementation is allowed to omit a call to a replaceable global
2304  ///    allocation function. [...]
2305  ///
2306  /// If this function is an aligned allocation/deallocation function, return
2307  /// the parameter number of the requested alignment through AlignmentParam.
2308  ///
2309  /// If this function is an allocation/deallocation function that takes
2310  /// the `std::nothrow_t` tag, return true through IsNothrow,
2311  bool isReplaceableGlobalAllocationFunction(
2312      Optional<unsigned> *AlignmentParam = nullptr,
2313      bool *IsNothrow = nullptr) const;
2314
2315  /// Determine if this function provides an inline implementation of a builtin.
2316  bool isInlineBuiltinDeclaration() const;
2317
2318  /// Determine whether this is a destroying operator delete.
2319  bool isDestroyingOperatorDelete() const;
2320
2321  /// Compute the language linkage.
2322  LanguageLinkage getLanguageLinkage() const;
2323
2324  /// Determines whether this function is a function with
2325  /// external, C linkage.
2326  bool isExternC() const;
2327
2328  /// Determines whether this function's context is, or is nested within,
2329  /// a C++ extern "C" linkage spec.
2330  bool isInExternCContext() const;
2331
2332  /// Determines whether this function's context is, or is nested within,
2333  /// a C++ extern "C++" linkage spec.
2334  bool isInExternCXXContext() const;
2335
2336  /// Determines whether this is a global function.
2337  bool isGlobal() const;
2338
2339  /// Determines whether this function is known to be 'noreturn', through
2340  /// an attribute on its declaration or its type.
2341  bool isNoReturn() const;
2342
2343  /// True if the function was a definition but its body was skipped.
2344  bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2345  void setHasSkippedBody(bool Skipped = true) {
2346    FunctionDeclBits.HasSkippedBody = Skipped;
2347  }
2348
2349  /// True if this function will eventually have a body, once it's fully parsed.
2350  bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2351  void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2352
2353  /// True if this function is considered a multiversioned function.
2354  bool isMultiVersion() const {
2355    return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2356  }
2357
2358  /// Sets the multiversion state for this declaration and all of its
2359  /// redeclarations.
2360  void setIsMultiVersion(bool V = true) {
2361    getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2362  }
2363
2364  /// Gets the kind of multiversioning attribute this declaration has. Note that
2365  /// this can return a value even if the function is not multiversion, such as
2366  /// the case of 'target'.
2367  MultiVersionKind getMultiVersionKind() const;
2368
2369
2370  /// True if this function is a multiversioned dispatch function as a part of
2371  /// the cpu_specific/cpu_dispatch functionality.
2372  bool isCPUDispatchMultiVersion() const;
2373  /// True if this function is a multiversioned processor specific function as a
2374  /// part of the cpu_specific/cpu_dispatch functionality.
2375  bool isCPUSpecificMultiVersion() const;
2376
2377  /// True if this function is a multiversioned dispatch function as a part of
2378  /// the target functionality.
2379  bool isTargetMultiVersion() const;
2380
2381  /// \brief Get the associated-constraints of this function declaration.
2382  /// Currently, this will either be a vector of size 1 containing the
2383  /// trailing-requires-clause or an empty vector.
2384  ///
2385  /// Use this instead of getTrailingRequiresClause for concepts APIs that
2386  /// accept an ArrayRef of constraint expressions.
2387  void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const {
2388    if (auto *TRC = getTrailingRequiresClause())
2389      AC.push_back(TRC);
2390  }
2391
2392  void setPreviousDeclaration(FunctionDecl * PrevDecl);
2393
2394  FunctionDecl *getCanonicalDecl() override;
2395  const FunctionDecl *getCanonicalDecl() const {
2396    return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2397  }
2398
2399  unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2400
2401  // ArrayRef interface to parameters.
2402  ArrayRef<ParmVarDecl *> parameters() const {
2403    return {ParamInfo, getNumParams()};
2404  }
2405  MutableArrayRef<ParmVarDecl *> parameters() {
2406    return {ParamInfo, getNumParams()};
2407  }
2408
2409  // Iterator access to formal parameters.
2410  using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2411  using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2412
2413  bool param_empty() const { return parameters().empty(); }
2414  param_iterator param_begin() { return parameters().begin(); }
2415  param_iterator param_end() { return parameters().end(); }
2416  param_const_iterator param_begin() const { return parameters().begin(); }
2417  param_const_iterator param_end() const { return parameters().end(); }
2418  size_t param_size() const { return parameters().size(); }
2419
2420  /// Return the number of parameters this function must have based on its
2421  /// FunctionType.  This is the length of the ParamInfo array after it has been
2422  /// created.
2423  unsigned getNumParams() const;
2424
2425  const ParmVarDecl *getParamDecl(unsigned i) const {
2426    assert(i < getNumParams() && "Illegal param #");
2427    return ParamInfo[i];
2428  }
2429  ParmVarDecl *getParamDecl(unsigned i) {
2430    assert(i < getNumParams() && "Illegal param #");
2431    return ParamInfo[i];
2432  }
2433  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2434    setParams(getASTContext(), NewParamInfo);
2435  }
2436
2437  /// Returns the minimum number of arguments needed to call this function. This
2438  /// may be fewer than the number of function parameters, if some of the
2439  /// parameters have default arguments (in C++).
2440  unsigned getMinRequiredArguments() const;
2441
2442  /// Determine whether this function has a single parameter, or multiple
2443  /// parameters where all but the first have default arguments.
2444  ///
2445  /// This notion is used in the definition of copy/move constructors and
2446  /// initializer list constructors. Note that, unlike getMinRequiredArguments,
2447  /// parameter packs are not treated specially here.
2448  bool hasOneParamOrDefaultArgs() const;
2449
2450  /// Find the source location information for how the type of this function
2451  /// was written. May be absent (for example if the function was declared via
2452  /// a typedef) and may contain a different type from that of the function
2453  /// (for example if the function type was adjusted by an attribute).
2454  FunctionTypeLoc getFunctionTypeLoc() const;
2455
2456  QualType getReturnType() const {
2457    return getType()->castAs<FunctionType>()->getReturnType();
2458  }
2459
2460  /// Attempt to compute an informative source range covering the
2461  /// function return type. This may omit qualifiers and other information with
2462  /// limited representation in the AST.
2463  SourceRange getReturnTypeSourceRange() const;
2464
2465  /// Attempt to compute an informative source range covering the
2466  /// function parameters, including the ellipsis of a variadic function.
2467  /// The source range excludes the parentheses, and is invalid if there are
2468  /// no parameters and no ellipsis.
2469  SourceRange getParametersSourceRange() const;
2470
2471  /// Get the declared return type, which may differ from the actual return
2472  /// type if the return type is deduced.
2473  QualType getDeclaredReturnType() const {
2474    auto *TSI = getTypeSourceInfo();
2475    QualType T = TSI ? TSI->getType() : getType();
2476    return T->castAs<FunctionType>()->getReturnType();
2477  }
2478
2479  /// Gets the ExceptionSpecificationType as declared.
2480  ExceptionSpecificationType getExceptionSpecType() const {
2481    auto *TSI = getTypeSourceInfo();
2482    QualType T = TSI ? TSI->getType() : getType();
2483    const auto *FPT = T->getAs<FunctionProtoType>();
2484    return FPT ? FPT->getExceptionSpecType() : EST_None;
2485  }
2486
2487  /// Attempt to compute an informative source range covering the
2488  /// function exception specification, if any.
2489  SourceRange getExceptionSpecSourceRange() const;
2490
2491  /// Determine the type of an expression that calls this function.
2492  QualType getCallResultType() const {
2493    return getType()->castAs<FunctionType>()->getCallResultType(
2494        getASTContext());
2495  }
2496
2497  /// Returns the storage class as written in the source. For the
2498  /// computed linkage of symbol, see getLinkage.
2499  StorageClass getStorageClass() const {
2500    return static_cast<StorageClass>(FunctionDeclBits.SClass);
2501  }
2502
2503  /// Sets the storage class as written in the source.
2504  void setStorageClass(StorageClass SClass) {
2505    FunctionDeclBits.SClass = SClass;
2506  }
2507
2508  /// Determine whether the "inline" keyword was specified for this
2509  /// function.
2510  bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2511
2512  /// Set whether the "inline" keyword was specified for this function.
2513  void setInlineSpecified(bool I) {
2514    FunctionDeclBits.IsInlineSpecified = I;
2515    FunctionDeclBits.IsInline = I;
2516  }
2517
2518  /// Flag that this function is implicitly inline.
2519  void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2520
2521  /// Determine whether this function should be inlined, because it is
2522  /// either marked "inline" or "constexpr" or is a member function of a class
2523  /// that was defined in the class body.
2524  bool isInlined() const { return FunctionDeclBits.IsInline; }
2525
2526  bool isInlineDefinitionExternallyVisible() const;
2527
2528  bool isMSExternInline() const;
2529
2530  bool doesDeclarationForceExternallyVisibleDefinition() const;
2531
2532  bool isStatic() const { return getStorageClass() == SC_Static; }
2533
2534  /// Whether this function declaration represents an C++ overloaded
2535  /// operator, e.g., "operator+".
2536  bool isOverloadedOperator() const {
2537    return getOverloadedOperator() != OO_None;
2538  }
2539
2540  OverloadedOperatorKind getOverloadedOperator() const;
2541
2542  const IdentifierInfo *getLiteralIdentifier() const;
2543
2544  /// If this function is an instantiation of a member function
2545  /// of a class template specialization, retrieves the function from
2546  /// which it was instantiated.
2547  ///
2548  /// This routine will return non-NULL for (non-templated) member
2549  /// functions of class templates and for instantiations of function
2550  /// templates. For example, given:
2551  ///
2552  /// \code
2553  /// template<typename T>
2554  /// struct X {
2555  ///   void f(T);
2556  /// };
2557  /// \endcode
2558  ///
2559  /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2560  /// whose parent is the class template specialization X<int>. For
2561  /// this declaration, getInstantiatedFromFunction() will return
2562  /// the FunctionDecl X<T>::A. When a complete definition of
2563  /// X<int>::A is required, it will be instantiated from the
2564  /// declaration returned by getInstantiatedFromMemberFunction().
2565  FunctionDecl *getInstantiatedFromMemberFunction() const;
2566
2567  /// What kind of templated function this is.
2568  TemplatedKind getTemplatedKind() const;
2569
2570  /// If this function is an instantiation of a member function of a
2571  /// class template specialization, retrieves the member specialization
2572  /// information.
2573  MemberSpecializationInfo *getMemberSpecializationInfo() const;
2574
2575  /// Specify that this record is an instantiation of the
2576  /// member function FD.
2577  void setInstantiationOfMemberFunction(FunctionDecl *FD,
2578                                        TemplateSpecializationKind TSK) {
2579    setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2580  }
2581
2582  /// Retrieves the function template that is described by this
2583  /// function declaration.
2584  ///
2585  /// Every function template is represented as a FunctionTemplateDecl
2586  /// and a FunctionDecl (or something derived from FunctionDecl). The
2587  /// former contains template properties (such as the template
2588  /// parameter lists) while the latter contains the actual
2589  /// description of the template's
2590  /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2591  /// FunctionDecl that describes the function template,
2592  /// getDescribedFunctionTemplate() retrieves the
2593  /// FunctionTemplateDecl from a FunctionDecl.
2594  FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2595
2596  void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2597
2598  /// Determine whether this function is a function template
2599  /// specialization.
2600  bool isFunctionTemplateSpecialization() const {
2601    return getPrimaryTemplate() != nullptr;
2602  }
2603
2604  /// If this function is actually a function template specialization,
2605  /// retrieve information about this function template specialization.
2606  /// Otherwise, returns NULL.
2607  FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2608
2609  /// Determines whether this function is a function template
2610  /// specialization or a member of a class template specialization that can
2611  /// be implicitly instantiated.
2612  bool isImplicitlyInstantiable() const;
2613
2614  /// Determines if the given function was instantiated from a
2615  /// function template.
2616  bool isTemplateInstantiation() const;
2617
2618  /// Retrieve the function declaration from which this function could
2619  /// be instantiated, if it is an instantiation (rather than a non-template
2620  /// or a specialization, for example).
2621  ///
2622  /// If \p ForDefinition is \c false, explicit specializations will be treated
2623  /// as if they were implicit instantiations. This will then find the pattern
2624  /// corresponding to non-definition portions of the declaration, such as
2625  /// default arguments and the exception specification.
2626  FunctionDecl *
2627  getTemplateInstantiationPattern(bool ForDefinition = true) const;
2628
2629  /// Retrieve the primary template that this function template
2630  /// specialization either specializes or was instantiated from.
2631  ///
2632  /// If this function declaration is not a function template specialization,
2633  /// returns NULL.
2634  FunctionTemplateDecl *getPrimaryTemplate() const;
2635
2636  /// Retrieve the template arguments used to produce this function
2637  /// template specialization from the primary template.
2638  ///
2639  /// If this function declaration is not a function template specialization,
2640  /// returns NULL.
2641  const TemplateArgumentList *getTemplateSpecializationArgs() const;
2642
2643  /// Retrieve the template argument list as written in the sources,
2644  /// if any.
2645  ///
2646  /// If this function declaration is not a function template specialization
2647  /// or if it had no explicit template argument list, returns NULL.
2648  /// Note that it an explicit template argument list may be written empty,
2649  /// e.g., template<> void foo<>(char* s);
2650  const ASTTemplateArgumentListInfo*
2651  getTemplateSpecializationArgsAsWritten() const;
2652
2653  /// Specify that this function declaration is actually a function
2654  /// template specialization.
2655  ///
2656  /// \param Template the function template that this function template
2657  /// specialization specializes.
2658  ///
2659  /// \param TemplateArgs the template arguments that produced this
2660  /// function template specialization from the template.
2661  ///
2662  /// \param InsertPos If non-NULL, the position in the function template
2663  /// specialization set where the function template specialization data will
2664  /// be inserted.
2665  ///
2666  /// \param TSK the kind of template specialization this is.
2667  ///
2668  /// \param TemplateArgsAsWritten location info of template arguments.
2669  ///
2670  /// \param PointOfInstantiation point at which the function template
2671  /// specialization was first instantiated.
2672  void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2673                const TemplateArgumentList *TemplateArgs,
2674                void *InsertPos,
2675                TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2676                const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2677                SourceLocation PointOfInstantiation = SourceLocation()) {
2678    setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2679                                      InsertPos, TSK, TemplateArgsAsWritten,
2680                                      PointOfInstantiation);
2681  }
2682
2683  /// Specifies that this function declaration is actually a
2684  /// dependent function template specialization.
2685  void setDependentTemplateSpecialization(ASTContext &Context,
2686                             const UnresolvedSetImpl &Templates,
2687                      const TemplateArgumentListInfo &TemplateArgs);
2688
2689  DependentFunctionTemplateSpecializationInfo *
2690  getDependentSpecializationInfo() const;
2691
2692  /// Determine what kind of template instantiation this function
2693  /// represents.
2694  TemplateSpecializationKind getTemplateSpecializationKind() const;
2695
2696  /// Determine the kind of template specialization this function represents
2697  /// for the purpose of template instantiation.
2698  TemplateSpecializationKind
2699  getTemplateSpecializationKindForInstantiation() const;
2700
2701  /// Determine what kind of template instantiation this function
2702  /// represents.
2703  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2704                        SourceLocation PointOfInstantiation = SourceLocation());
2705
2706  /// Retrieve the (first) point of instantiation of a function template
2707  /// specialization or a member of a class template specialization.
2708  ///
2709  /// \returns the first point of instantiation, if this function was
2710  /// instantiated from a template; otherwise, returns an invalid source
2711  /// location.
2712  SourceLocation getPointOfInstantiation() const;
2713
2714  /// Determine whether this is or was instantiated from an out-of-line
2715  /// definition of a member function.
2716  bool isOutOfLine() const override;
2717
2718  /// Identify a memory copying or setting function.
2719  /// If the given function is a memory copy or setting function, returns
2720  /// the corresponding Builtin ID. If the function is not a memory function,
2721  /// returns 0.
2722  unsigned getMemoryFunctionKind() const;
2723
2724  /// Returns ODRHash of the function.  This value is calculated and
2725  /// stored on first call, then the stored value returned on the other calls.
2726  unsigned getODRHash();
2727
2728  /// Returns cached ODRHash of the function.  This must have been previously
2729  /// computed and stored.
2730  unsigned getODRHash() const;
2731
2732  // Implement isa/cast/dyncast/etc.
2733  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2734  static bool classofKind(Kind K) {
2735    return K >= firstFunction && K <= lastFunction;
2736  }
2737  static DeclContext *castToDeclContext(const FunctionDecl *D) {
2738    return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2739  }
2740  static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2741    return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2742  }
2743};
2744
2745/// Represents a member of a struct/union/class.
2746class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2747  unsigned BitField : 1;
2748  unsigned Mutable : 1;
2749  mutable unsigned CachedFieldIndex : 30;
2750
2751  /// The kinds of value we can store in InitializerOrBitWidth.
2752  ///
2753  /// Note that this is compatible with InClassInitStyle except for
2754  /// ISK_CapturedVLAType.
2755  enum InitStorageKind {
2756    /// If the pointer is null, there's nothing special.  Otherwise,
2757    /// this is a bitfield and the pointer is the Expr* storing the
2758    /// bit-width.
2759    ISK_NoInit = (unsigned) ICIS_NoInit,
2760
2761    /// The pointer is an (optional due to delayed parsing) Expr*
2762    /// holding the copy-initializer.
2763    ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2764
2765    /// The pointer is an (optional due to delayed parsing) Expr*
2766    /// holding the list-initializer.
2767    ISK_InClassListInit = (unsigned) ICIS_ListInit,
2768
2769    /// The pointer is a VariableArrayType* that's been captured;
2770    /// the enclosing context is a lambda or captured statement.
2771    ISK_CapturedVLAType,
2772  };
2773
2774  /// If this is a bitfield with a default member initializer, this
2775  /// structure is used to represent the two expressions.
2776  struct InitAndBitWidth {
2777    Expr *Init;
2778    Expr *BitWidth;
2779  };
2780
2781  /// Storage for either the bit-width, the in-class initializer, or
2782  /// both (via InitAndBitWidth), or the captured variable length array bound.
2783  ///
2784  /// If the storage kind is ISK_InClassCopyInit or
2785  /// ISK_InClassListInit, but the initializer is null, then this
2786  /// field has an in-class initializer that has not yet been parsed
2787  /// and attached.
2788  // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2789  // overwhelmingly common case that we have none of these things.
2790  llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2791
2792protected:
2793  FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2794            SourceLocation IdLoc, IdentifierInfo *Id,
2795            QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2796            InClassInitStyle InitStyle)
2797    : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2798      BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2799      InitStorage(nullptr, (InitStorageKind) InitStyle) {
2800    if (BW)
2801      setBitWidth(BW);
2802  }
2803
2804public:
2805  friend class ASTDeclReader;
2806  friend class ASTDeclWriter;
2807
2808  static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2809                           SourceLocation StartLoc, SourceLocation IdLoc,
2810                           IdentifierInfo *Id, QualType T,
2811                           TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2812                           InClassInitStyle InitStyle);
2813
2814  static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2815
2816  /// Returns the index of this field within its record,
2817  /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2818  unsigned getFieldIndex() const;
2819
2820  /// Determines whether this field is mutable (C++ only).
2821  bool isMutable() const { return Mutable; }
2822
2823  /// Determines whether this field is a bitfield.
2824  bool isBitField() const { return BitField; }
2825
2826  /// Determines whether this is an unnamed bitfield.
2827  bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2828
2829  /// Determines whether this field is a
2830  /// representative for an anonymous struct or union. Such fields are
2831  /// unnamed and are implicitly generated by the implementation to
2832  /// store the data for the anonymous union or struct.
2833  bool isAnonymousStructOrUnion() const;
2834
2835  Expr *getBitWidth() const {
2836    if (!BitField)
2837      return nullptr;
2838    void *Ptr = InitStorage.getPointer();
2839    if (getInClassInitStyle())
2840      return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2841    return static_cast<Expr*>(Ptr);
2842  }
2843
2844  unsigned getBitWidthValue(const ASTContext &Ctx) const;
2845
2846  /// Set the bit-field width for this member.
2847  // Note: used by some clients (i.e., do not remove it).
2848  void setBitWidth(Expr *Width) {
2849    assert(!hasCapturedVLAType() && !BitField &&
2850           "bit width or captured type already set");
2851    assert(Width && "no bit width specified");
2852    InitStorage.setPointer(
2853        InitStorage.getInt()
2854            ? new (getASTContext())
2855                  InitAndBitWidth{getInClassInitializer(), Width}
2856            : static_cast<void*>(Width));
2857    BitField = true;
2858  }
2859
2860  /// Remove the bit-field width from this member.
2861  // Note: used by some clients (i.e., do not remove it).
2862  void removeBitWidth() {
2863    assert(isBitField() && "no bitfield width to remove");
2864    InitStorage.setPointer(getInClassInitializer());
2865    BitField = false;
2866  }
2867
2868  /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2869  /// at all and instead act as a separator between contiguous runs of other
2870  /// bit-fields.
2871  bool isZeroLengthBitField(const ASTContext &Ctx) const;
2872
2873  /// Determine if this field is a subobject of zero size, that is, either a
2874  /// zero-length bit-field or a field of empty class type with the
2875  /// [[no_unique_address]] attribute.
2876  bool isZeroSize(const ASTContext &Ctx) const;
2877
2878  /// Get the kind of (C++11) default member initializer that this field has.
2879  InClassInitStyle getInClassInitStyle() const {
2880    InitStorageKind storageKind = InitStorage.getInt();
2881    return (storageKind == ISK_CapturedVLAType
2882              ? ICIS_NoInit : (InClassInitStyle) storageKind);
2883  }
2884
2885  /// Determine whether this member has a C++11 default member initializer.
2886  bool hasInClassInitializer() const {
2887    return getInClassInitStyle() != ICIS_NoInit;
2888  }
2889
2890  /// Get the C++11 default member initializer for this member, or null if one
2891  /// has not been set. If a valid declaration has a default member initializer,
2892  /// but this returns null, then we have not parsed and attached it yet.
2893  Expr *getInClassInitializer() const {
2894    if (!hasInClassInitializer())
2895      return nullptr;
2896    void *Ptr = InitStorage.getPointer();
2897    if (BitField)
2898      return static_cast<InitAndBitWidth*>(Ptr)->Init;
2899    return static_cast<Expr*>(Ptr);
2900  }
2901
2902  /// Set the C++11 in-class initializer for this member.
2903  void setInClassInitializer(Expr *Init) {
2904    assert(hasInClassInitializer() && !getInClassInitializer());
2905    if (BitField)
2906      static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2907    else
2908      InitStorage.setPointer(Init);
2909  }
2910
2911  /// Remove the C++11 in-class initializer from this member.
2912  void removeInClassInitializer() {
2913    assert(hasInClassInitializer() && "no initializer to remove");
2914    InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2915  }
2916
2917  /// Determine whether this member captures the variable length array
2918  /// type.
2919  bool hasCapturedVLAType() const {
2920    return InitStorage.getInt() == ISK_CapturedVLAType;
2921  }
2922
2923  /// Get the captured variable length array type.
2924  const VariableArrayType *getCapturedVLAType() const {
2925    return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2926                                      InitStorage.getPointer())
2927                                : nullptr;
2928  }
2929
2930  /// Set the captured variable length array type for this field.
2931  void setCapturedVLAType(const VariableArrayType *VLAType);
2932
2933  /// Returns the parent of this field declaration, which
2934  /// is the struct in which this field is defined.
2935  ///
2936  /// Returns null if this is not a normal class/struct field declaration, e.g.
2937  /// ObjCAtDefsFieldDecl, ObjCIvarDecl.
2938  const RecordDecl *getParent() const {
2939    return dyn_cast<RecordDecl>(getDeclContext());
2940  }
2941
2942  RecordDecl *getParent() {
2943    return dyn_cast<RecordDecl>(getDeclContext());
2944  }
2945
2946  SourceRange getSourceRange() const override LLVM_READONLY;
2947
2948  /// Retrieves the canonical declaration of this field.
2949  FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2950  const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2951
2952  // Implement isa/cast/dyncast/etc.
2953  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2954  static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2955};
2956
2957/// An instance of this object exists for each enum constant
2958/// that is defined.  For example, in "enum X {a,b}", each of a/b are
2959/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2960/// TagType for the X EnumDecl.
2961class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2962  Stmt *Init; // an integer constant expression
2963  llvm::APSInt Val; // The value.
2964
2965protected:
2966  EnumConstantDecl(DeclContext *DC, SourceLocation L,
2967                   IdentifierInfo *Id, QualType T, Expr *E,
2968                   const llvm::APSInt &V)
2969    : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2970
2971public:
2972  friend class StmtIteratorBase;
2973
2974  static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2975                                  SourceLocation L, IdentifierInfo *Id,
2976                                  QualType T, Expr *E,
2977                                  const llvm::APSInt &V);
2978  static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2979
2980  const Expr *getInitExpr() const { return (const Expr*) Init; }
2981  Expr *getInitExpr() { return (Expr*) Init; }
2982  const llvm::APSInt &getInitVal() const { return Val; }
2983
2984  void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2985  void setInitVal(const llvm::APSInt &V) { Val = V; }
2986
2987  SourceRange getSourceRange() const override LLVM_READONLY;
2988
2989  /// Retrieves the canonical declaration of this enumerator.
2990  EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2991  const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2992
2993  // Implement isa/cast/dyncast/etc.
2994  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2995  static bool classofKind(Kind K) { return K == EnumConstant; }
2996};
2997
2998/// Represents a field injected from an anonymous union/struct into the parent
2999/// scope. These are always implicit.
3000class IndirectFieldDecl : public ValueDecl,
3001                          public Mergeable<IndirectFieldDecl> {
3002  NamedDecl **Chaining;
3003  unsigned ChainingSize;
3004
3005  IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
3006                    DeclarationName N, QualType T,
3007                    MutableArrayRef<NamedDecl *> CH);
3008
3009  void anchor() override;
3010
3011public:
3012  friend class ASTDeclReader;
3013
3014  static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
3015                                   SourceLocation L, IdentifierInfo *Id,
3016                                   QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
3017
3018  static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3019
3020  using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
3021
3022  ArrayRef<NamedDecl *> chain() const {
3023    return llvm::makeArrayRef(Chaining, ChainingSize);
3024  }
3025  chain_iterator chain_begin() const { return chain().begin(); }
3026  chain_iterator chain_end() const { return chain().end(); }
3027
3028  unsigned getChainingSize() const { return ChainingSize; }
3029
3030  FieldDecl *getAnonField() const {
3031    assert(chain().size() >= 2);
3032    return cast<FieldDecl>(chain().back());
3033  }
3034
3035  VarDecl *getVarDecl() const {
3036    assert(chain().size() >= 2);
3037    return dyn_cast<VarDecl>(chain().front());
3038  }
3039
3040  IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
3041  const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
3042
3043  // Implement isa/cast/dyncast/etc.
3044  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3045  static bool classofKind(Kind K) { return K == IndirectField; }
3046};
3047
3048/// Represents a declaration of a type.
3049class TypeDecl : public NamedDecl {
3050  friend class ASTContext;
3051
3052  /// This indicates the Type object that represents
3053  /// this TypeDecl.  It is a cache maintained by
3054  /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
3055  /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
3056  mutable const Type *TypeForDecl = nullptr;
3057
3058  /// The start of the source range for this declaration.
3059  SourceLocation LocStart;
3060
3061  void anchor() override;
3062
3063protected:
3064  TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
3065           SourceLocation StartL = SourceLocation())
3066    : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
3067
3068public:
3069  // Low-level accessor. If you just want the type defined by this node,
3070  // check out ASTContext::getTypeDeclType or one of
3071  // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
3072  // already know the specific kind of node this is.
3073  const Type *getTypeForDecl() const { return TypeForDecl; }
3074  void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
3075
3076  SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
3077  void setLocStart(SourceLocation L) { LocStart = L; }
3078  SourceRange getSourceRange() const override LLVM_READONLY {
3079    if (LocStart.isValid())
3080      return SourceRange(LocStart, getLocation());
3081    else
3082      return SourceRange(getLocation());
3083  }
3084
3085  // Implement isa/cast/dyncast/etc.
3086  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3087  static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
3088};
3089
3090/// Base class for declarations which introduce a typedef-name.
3091class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
3092  struct alignas(8) ModedTInfo {
3093    TypeSourceInfo *first;
3094    QualType second;
3095  };
3096
3097  /// If int part is 0, we have not computed IsTransparentTag.
3098  /// Otherwise, IsTransparentTag is (getInt() >> 1).
3099  mutable llvm::PointerIntPair<
3100      llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
3101      MaybeModedTInfo;
3102
3103  void anchor() override;
3104
3105protected:
3106  TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
3107                  SourceLocation StartLoc, SourceLocation IdLoc,
3108                  IdentifierInfo *Id, TypeSourceInfo *TInfo)
3109      : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3110        MaybeModedTInfo(TInfo, 0) {}
3111
3112  using redeclarable_base = Redeclarable<TypedefNameDecl>;
3113
3114  TypedefNameDecl *getNextRedeclarationImpl() override {
3115    return getNextRedeclaration();
3116  }
3117
3118  TypedefNameDecl *getPreviousDeclImpl() override {
3119    return getPreviousDecl();
3120  }
3121
3122  TypedefNameDecl *getMostRecentDeclImpl() override {
3123    return getMostRecentDecl();
3124  }
3125
3126public:
3127  using redecl_range = redeclarable_base::redecl_range;
3128  using redecl_iterator = redeclarable_base::redecl_iterator;
3129
3130  using redeclarable_base::redecls_begin;
3131  using redeclarable_base::redecls_end;
3132  using redeclarable_base::redecls;
3133  using redeclarable_base::getPreviousDecl;
3134  using redeclarable_base::getMostRecentDecl;
3135  using redeclarable_base::isFirstDecl;
3136
3137  bool isModed() const {
3138    return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3139  }
3140
3141  TypeSourceInfo *getTypeSourceInfo() const {
3142    return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3143                     : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3144  }
3145
3146  QualType getUnderlyingType() const {
3147    return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3148                     : MaybeModedTInfo.getPointer()
3149                           .get<TypeSourceInfo *>()
3150                           ->getType();
3151  }
3152
3153  void setTypeSourceInfo(TypeSourceInfo *newType) {
3154    MaybeModedTInfo.setPointer(newType);
3155  }
3156
3157  void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
3158    MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3159                                   ModedTInfo({unmodedTSI, modedTy}));
3160  }
3161
3162  /// Retrieves the canonical declaration of this typedef-name.
3163  TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
3164  const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3165
3166  /// Retrieves the tag declaration for which this is the typedef name for
3167  /// linkage purposes, if any.
3168  ///
3169  /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3170  /// this typedef declaration.
3171  TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3172
3173  /// Determines if this typedef shares a name and spelling location with its
3174  /// underlying tag type, as is the case with the NS_ENUM macro.
3175  bool isTransparentTag() const {
3176    if (MaybeModedTInfo.getInt())
3177      return MaybeModedTInfo.getInt() & 0x2;
3178    return isTransparentTagSlow();
3179  }
3180
3181  // Implement isa/cast/dyncast/etc.
3182  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3183  static bool classofKind(Kind K) {
3184    return K >= firstTypedefName && K <= lastTypedefName;
3185  }
3186
3187private:
3188  bool isTransparentTagSlow() const;
3189};
3190
3191/// Represents the declaration of a typedef-name via the 'typedef'
3192/// type specifier.
3193class TypedefDecl : public TypedefNameDecl {
3194  TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3195              SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3196      : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3197
3198public:
3199  static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3200                             SourceLocation StartLoc, SourceLocation IdLoc,
3201                             IdentifierInfo *Id, TypeSourceInfo *TInfo);
3202  static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3203
3204  SourceRange getSourceRange() const override LLVM_READONLY;
3205
3206  // Implement isa/cast/dyncast/etc.
3207  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3208  static bool classofKind(Kind K) { return K == Typedef; }
3209};
3210
3211/// Represents the declaration of a typedef-name via a C++11
3212/// alias-declaration.
3213class TypeAliasDecl : public TypedefNameDecl {
3214  /// The template for which this is the pattern, if any.
3215  TypeAliasTemplateDecl *Template;
3216
3217  TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3218                SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3219      : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3220        Template(nullptr) {}
3221
3222public:
3223  static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3224                               SourceLocation StartLoc, SourceLocation IdLoc,
3225                               IdentifierInfo *Id, TypeSourceInfo *TInfo);
3226  static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3227
3228  SourceRange getSourceRange() const override LLVM_READONLY;
3229
3230  TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3231  void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3232
3233  // Implement isa/cast/dyncast/etc.
3234  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3235  static bool classofKind(Kind K) { return K == TypeAlias; }
3236};
3237
3238/// Represents the declaration of a struct/union/class/enum.
3239class TagDecl : public TypeDecl,
3240                public DeclContext,
3241                public Redeclarable<TagDecl> {
3242  // This class stores some data in DeclContext::TagDeclBits
3243  // to save some space. Use the provided accessors to access it.
3244public:
3245  // This is really ugly.
3246  using TagKind = TagTypeKind;
3247
3248private:
3249  SourceRange BraceRange;
3250
3251  // A struct representing syntactic qualifier info,
3252  // to be used for the (uncommon) case of out-of-line declarations.
3253  using ExtInfo = QualifierInfo;
3254
3255  /// If the (out-of-line) tag declaration name
3256  /// is qualified, it points to the qualifier info (nns and range);
3257  /// otherwise, if the tag declaration is anonymous and it is part of
3258  /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3259  /// otherwise, if the tag declaration is anonymous and it is used as a
3260  /// declaration specifier for variables, it points to the first VarDecl (used
3261  /// for mangling);
3262  /// otherwise, it is a null (TypedefNameDecl) pointer.
3263  llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3264
3265  bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3266  ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3267  const ExtInfo *getExtInfo() const {
3268    return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3269  }
3270
3271protected:
3272  TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3273          SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3274          SourceLocation StartL);
3275
3276  using redeclarable_base = Redeclarable<TagDecl>;
3277
3278  TagDecl *getNextRedeclarationImpl() override {
3279    return getNextRedeclaration();
3280  }
3281
3282  TagDecl *getPreviousDeclImpl() override {
3283    return getPreviousDecl();
3284  }
3285
3286  TagDecl *getMostRecentDeclImpl() override {
3287    return getMostRecentDecl();
3288  }
3289
3290  /// Completes the definition of this tag declaration.
3291  ///
3292  /// This is a helper function for derived classes.
3293  void completeDefinition();
3294
3295  /// True if this decl is currently being defined.
3296  void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3297
3298  /// Indicates whether it is possible for declarations of this kind
3299  /// to have an out-of-date definition.
3300  ///
3301  /// This option is only enabled when modules are enabled.
3302  void setMayHaveOutOfDateDef(bool V = true) {
3303    TagDeclBits.MayHaveOutOfDateDef = V;
3304  }
3305
3306public:
3307  friend class ASTDeclReader;
3308  friend class ASTDeclWriter;
3309
3310  using redecl_range = redeclarable_base::redecl_range;
3311  using redecl_iterator = redeclarable_base::redecl_iterator;
3312
3313  using redeclarable_base::redecls_begin;
3314  using redeclarable_base::redecls_end;
3315  using redeclarable_base::redecls;
3316  using redeclarable_base::getPreviousDecl;
3317  using redeclarable_base::getMostRecentDecl;
3318  using redeclarable_base::isFirstDecl;
3319
3320  SourceRange getBraceRange() const { return BraceRange; }
3321  void setBraceRange(SourceRange R) { BraceRange = R; }
3322
3323  /// Return SourceLocation representing start of source
3324  /// range ignoring outer template declarations.
3325  SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3326
3327  /// Return SourceLocation representing start of source
3328  /// range taking into account any outer template declarations.
3329  SourceLocation getOuterLocStart() const;
3330  SourceRange getSourceRange() const override LLVM_READONLY;
3331
3332  TagDecl *getCanonicalDecl() override;
3333  const TagDecl *getCanonicalDecl() const {
3334    return const_cast<TagDecl*>(this)->getCanonicalDecl();
3335  }
3336
3337  /// Return true if this declaration is a completion definition of the type.
3338  /// Provided for consistency.
3339  bool isThisDeclarationADefinition() const {
3340    return isCompleteDefinition();
3341  }
3342
3343  /// Return true if this decl has its body fully specified.
3344  bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3345
3346  /// True if this decl has its body fully specified.
3347  void setCompleteDefinition(bool V = true) {
3348    TagDeclBits.IsCompleteDefinition = V;
3349  }
3350
3351  /// Return true if this complete decl is
3352  /// required to be complete for some existing use.
3353  bool isCompleteDefinitionRequired() const {
3354    return TagDeclBits.IsCompleteDefinitionRequired;
3355  }
3356
3357  /// True if this complete decl is
3358  /// required to be complete for some existing use.
3359  void setCompleteDefinitionRequired(bool V = true) {
3360    TagDeclBits.IsCompleteDefinitionRequired = V;
3361  }
3362
3363  /// Return true if this decl is currently being defined.
3364  bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3365
3366  /// True if this tag declaration is "embedded" (i.e., defined or declared
3367  /// for the very first time) in the syntax of a declarator.
3368  bool isEmbeddedInDeclarator() const {
3369    return TagDeclBits.IsEmbeddedInDeclarator;
3370  }
3371
3372  /// True if this tag declaration is "embedded" (i.e., defined or declared
3373  /// for the very first time) in the syntax of a declarator.
3374  void setEmbeddedInDeclarator(bool isInDeclarator) {
3375    TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3376  }
3377
3378  /// True if this tag is free standing, e.g. "struct foo;".
3379  bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3380
3381  /// True if this tag is free standing, e.g. "struct foo;".
3382  void setFreeStanding(bool isFreeStanding = true) {
3383    TagDeclBits.IsFreeStanding = isFreeStanding;
3384  }
3385
3386  /// Indicates whether it is possible for declarations of this kind
3387  /// to have an out-of-date definition.
3388  ///
3389  /// This option is only enabled when modules are enabled.
3390  bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3391
3392  /// Whether this declaration declares a type that is
3393  /// dependent, i.e., a type that somehow depends on template
3394  /// parameters.
3395  bool isDependentType() const { return isDependentContext(); }
3396
3397  /// Starts the definition of this tag declaration.
3398  ///
3399  /// This method should be invoked at the beginning of the definition
3400  /// of this tag declaration. It will set the tag type into a state
3401  /// where it is in the process of being defined.
3402  void startDefinition();
3403
3404  /// Returns the TagDecl that actually defines this
3405  ///  struct/union/class/enum.  When determining whether or not a
3406  ///  struct/union/class/enum has a definition, one should use this
3407  ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
3408  ///  whether or not a specific TagDecl is defining declaration, not
3409  ///  whether or not the struct/union/class/enum type is defined.
3410  ///  This method returns NULL if there is no TagDecl that defines
3411  ///  the struct/union/class/enum.
3412  TagDecl *getDefinition() const;
3413
3414  StringRef getKindName() const {
3415    return TypeWithKeyword::getTagTypeKindName(getTagKind());
3416  }
3417
3418  TagKind getTagKind() const {
3419    return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3420  }
3421
3422  void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3423
3424  bool isStruct() const { return getTagKind() == TTK_Struct; }
3425  bool isInterface() const { return getTagKind() == TTK_Interface; }
3426  bool isClass()  const { return getTagKind() == TTK_Class; }
3427  bool isUnion()  const { return getTagKind() == TTK_Union; }
3428  bool isEnum()   const { return getTagKind() == TTK_Enum; }
3429
3430  /// Is this tag type named, either directly or via being defined in
3431  /// a typedef of this type?
3432  ///
3433  /// C++11 [basic.link]p8:
3434  ///   A type is said to have linkage if and only if:
3435  ///     - it is a class or enumeration type that is named (or has a
3436  ///       name for linkage purposes) and the name has linkage; ...
3437  /// C++11 [dcl.typedef]p9:
3438  ///   If the typedef declaration defines an unnamed class (or enum),
3439  ///   the first typedef-name declared by the declaration to be that
3440  ///   class type (or enum type) is used to denote the class type (or
3441  ///   enum type) for linkage purposes only.
3442  ///
3443  /// C does not have an analogous rule, but the same concept is
3444  /// nonetheless useful in some places.
3445  bool hasNameForLinkage() const {
3446    return (getDeclName() || getTypedefNameForAnonDecl());
3447  }
3448
3449  TypedefNameDecl *getTypedefNameForAnonDecl() const {
3450    return hasExtInfo() ? nullptr
3451                        : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3452  }
3453
3454  void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3455
3456  /// Retrieve the nested-name-specifier that qualifies the name of this
3457  /// declaration, if it was present in the source.
3458  NestedNameSpecifier *getQualifier() const {
3459    return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3460                        : nullptr;
3461  }
3462
3463  /// Retrieve the nested-name-specifier (with source-location
3464  /// information) that qualifies the name of this declaration, if it was
3465  /// present in the source.
3466  NestedNameSpecifierLoc getQualifierLoc() const {
3467    return hasExtInfo() ? getExtInfo()->QualifierLoc
3468                        : NestedNameSpecifierLoc();
3469  }
3470
3471  void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3472
3473  unsigned getNumTemplateParameterLists() const {
3474    return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3475  }
3476
3477  TemplateParameterList *getTemplateParameterList(unsigned i) const {
3478    assert(i < getNumTemplateParameterLists());
3479    return getExtInfo()->TemplParamLists[i];
3480  }
3481
3482  void setTemplateParameterListsInfo(ASTContext &Context,
3483                                     ArrayRef<TemplateParameterList *> TPLists);
3484
3485  // Implement isa/cast/dyncast/etc.
3486  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3487  static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3488
3489  static DeclContext *castToDeclContext(const TagDecl *D) {
3490    return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3491  }
3492
3493  static TagDecl *castFromDeclContext(const DeclContext *DC) {
3494    return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3495  }
3496};
3497
3498/// Represents an enum.  In C++11, enums can be forward-declared
3499/// with a fixed underlying type, and in C we allow them to be forward-declared
3500/// with no underlying type as an extension.
3501class EnumDecl : public TagDecl {
3502  // This class stores some data in DeclContext::EnumDeclBits
3503  // to save some space. Use the provided accessors to access it.
3504
3505  /// This represent the integer type that the enum corresponds
3506  /// to for code generation purposes.  Note that the enumerator constants may
3507  /// have a different type than this does.
3508  ///
3509  /// If the underlying integer type was explicitly stated in the source
3510  /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3511  /// was automatically deduced somehow, and this is a Type*.
3512  ///
3513  /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3514  /// some cases it won't.
3515  ///
3516  /// The underlying type of an enumeration never has any qualifiers, so
3517  /// we can get away with just storing a raw Type*, and thus save an
3518  /// extra pointer when TypeSourceInfo is needed.
3519  llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3520
3521  /// The integer type that values of this type should
3522  /// promote to.  In C, enumerators are generally of an integer type
3523  /// directly, but gcc-style large enumerators (and all enumerators
3524  /// in C++) are of the enum type instead.
3525  QualType PromotionType;
3526
3527  /// If this enumeration is an instantiation of a member enumeration
3528  /// of a class template specialization, this is the member specialization
3529  /// information.
3530  MemberSpecializationInfo *SpecializationInfo = nullptr;
3531
3532  /// Store the ODRHash after first calculation.
3533  /// The corresponding flag HasODRHash is in EnumDeclBits
3534  /// and can be accessed with the provided accessors.
3535  unsigned ODRHash;
3536
3537  EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3538           SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3539           bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3540
3541  void anchor() override;
3542
3543  void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3544                                    TemplateSpecializationKind TSK);
3545
3546  /// Sets the width in bits required to store all the
3547  /// non-negative enumerators of this enum.
3548  void setNumPositiveBits(unsigned Num) {
3549    EnumDeclBits.NumPositiveBits = Num;
3550    assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount");
3551  }
3552
3553  /// Returns the width in bits required to store all the
3554  /// negative enumerators of this enum. (see getNumNegativeBits)
3555  void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3556
3557public:
3558  /// True if this tag declaration is a scoped enumeration. Only
3559  /// possible in C++11 mode.
3560  void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3561
3562  /// If this tag declaration is a scoped enum,
3563  /// then this is true if the scoped enum was declared using the class
3564  /// tag, false if it was declared with the struct tag. No meaning is
3565  /// associated if this tag declaration is not a scoped enum.
3566  void setScopedUsingClassTag(bool ScopedUCT = true) {
3567    EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3568  }
3569
3570  /// True if this is an Objective-C, C++11, or
3571  /// Microsoft-style enumeration with a fixed underlying type.
3572  void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3573
3574private:
3575  /// True if a valid hash is stored in ODRHash.
3576  bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3577  void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3578
3579public:
3580  friend class ASTDeclReader;
3581
3582  EnumDecl *getCanonicalDecl() override {
3583    return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3584  }
3585  const EnumDecl *getCanonicalDecl() const {
3586    return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3587  }
3588
3589  EnumDecl *getPreviousDecl() {
3590    return cast_or_null<EnumDecl>(
3591            static_cast<TagDecl *>(this)->getPreviousDecl());
3592  }
3593  const EnumDecl *getPreviousDecl() const {
3594    return const_cast<EnumDecl*>(this)->getPreviousDecl();
3595  }
3596
3597  EnumDecl *getMostRecentDecl() {
3598    return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3599  }
3600  const EnumDecl *getMostRecentDecl() const {
3601    return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3602  }
3603
3604  EnumDecl *getDefinition() const {
3605    return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3606  }
3607
3608  static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3609                          SourceLocation StartLoc, SourceLocation IdLoc,
3610                          IdentifierInfo *Id, EnumDecl *PrevDecl,
3611                          bool IsScoped, bool IsScopedUsingClassTag,
3612                          bool IsFixed);
3613  static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3614
3615  /// When created, the EnumDecl corresponds to a
3616  /// forward-declared enum. This method is used to mark the
3617  /// declaration as being defined; its enumerators have already been
3618  /// added (via DeclContext::addDecl). NewType is the new underlying
3619  /// type of the enumeration type.
3620  void completeDefinition(QualType NewType,
3621                          QualType PromotionType,
3622                          unsigned NumPositiveBits,
3623                          unsigned NumNegativeBits);
3624
3625  // Iterates through the enumerators of this enumeration.
3626  using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3627  using enumerator_range =
3628      llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3629
3630  enumerator_range enumerators() const {
3631    return enumerator_range(enumerator_begin(), enumerator_end());
3632  }
3633
3634  enumerator_iterator enumerator_begin() const {
3635    const EnumDecl *E = getDefinition();
3636    if (!E)
3637      E = this;
3638    return enumerator_iterator(E->decls_begin());
3639  }
3640
3641  enumerator_iterator enumerator_end() const {
3642    const EnumDecl *E = getDefinition();
3643    if (!E)
3644      E = this;
3645    return enumerator_iterator(E->decls_end());
3646  }
3647
3648  /// Return the integer type that enumerators should promote to.
3649  QualType getPromotionType() const { return PromotionType; }
3650
3651  /// Set the promotion type.
3652  void setPromotionType(QualType T) { PromotionType = T; }
3653
3654  /// Return the integer type this enum decl corresponds to.
3655  /// This returns a null QualType for an enum forward definition with no fixed
3656  /// underlying type.
3657  QualType getIntegerType() const {
3658    if (!IntegerType)
3659      return QualType();
3660    if (const Type *T = IntegerType.dyn_cast<const Type*>())
3661      return QualType(T, 0);
3662    return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3663  }
3664
3665  /// Set the underlying integer type.
3666  void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3667
3668  /// Set the underlying integer type source info.
3669  void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3670
3671  /// Return the type source info for the underlying integer type,
3672  /// if no type source info exists, return 0.
3673  TypeSourceInfo *getIntegerTypeSourceInfo() const {
3674    return IntegerType.dyn_cast<TypeSourceInfo*>();
3675  }
3676
3677  /// Retrieve the source range that covers the underlying type if
3678  /// specified.
3679  SourceRange getIntegerTypeRange() const LLVM_READONLY;
3680
3681  /// Returns the width in bits required to store all the
3682  /// non-negative enumerators of this enum.
3683  unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3684
3685  /// Returns the width in bits required to store all the
3686  /// negative enumerators of this enum.  These widths include
3687  /// the rightmost leading 1;  that is:
3688  ///
3689  /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
3690  /// ------------------------     -------     -----------------
3691  ///                       -1     1111111                     1
3692  ///                      -10     1110110                     5
3693  ///                     -101     1001011                     8
3694  unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3695
3696  /// Returns true if this is a C++11 scoped enumeration.
3697  bool isScoped() const { return EnumDeclBits.IsScoped; }
3698
3699  /// Returns true if this is a C++11 scoped enumeration.
3700  bool isScopedUsingClassTag() const {
3701    return EnumDeclBits.IsScopedUsingClassTag;
3702  }
3703
3704  /// Returns true if this is an Objective-C, C++11, or
3705  /// Microsoft-style enumeration with a fixed underlying type.
3706  bool isFixed() const { return EnumDeclBits.IsFixed; }
3707
3708  unsigned getODRHash();
3709
3710  /// Returns true if this can be considered a complete type.
3711  bool isComplete() const {
3712    // IntegerType is set for fixed type enums and non-fixed but implicitly
3713    // int-sized Microsoft enums.
3714    return isCompleteDefinition() || IntegerType;
3715  }
3716
3717  /// Returns true if this enum is either annotated with
3718  /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3719  bool isClosed() const;
3720
3721  /// Returns true if this enum is annotated with flag_enum and isn't annotated
3722  /// with enum_extensibility(open).
3723  bool isClosedFlag() const;
3724
3725  /// Returns true if this enum is annotated with neither flag_enum nor
3726  /// enum_extensibility(open).
3727  bool isClosedNonFlag() const;
3728
3729  /// Retrieve the enum definition from which this enumeration could
3730  /// be instantiated, if it is an instantiation (rather than a non-template).
3731  EnumDecl *getTemplateInstantiationPattern() const;
3732
3733  /// Returns the enumeration (declared within the template)
3734  /// from which this enumeration type was instantiated, or NULL if
3735  /// this enumeration was not instantiated from any template.
3736  EnumDecl *getInstantiatedFromMemberEnum() const;
3737
3738  /// If this enumeration is a member of a specialization of a
3739  /// templated class, determine what kind of template specialization
3740  /// or instantiation this is.
3741  TemplateSpecializationKind getTemplateSpecializationKind() const;
3742
3743  /// For an enumeration member that was instantiated from a member
3744  /// enumeration of a templated class, set the template specialiation kind.
3745  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3746                        SourceLocation PointOfInstantiation = SourceLocation());
3747
3748  /// If this enumeration is an instantiation of a member enumeration of
3749  /// a class template specialization, retrieves the member specialization
3750  /// information.
3751  MemberSpecializationInfo *getMemberSpecializationInfo() const {
3752    return SpecializationInfo;
3753  }
3754
3755  /// Specify that this enumeration is an instantiation of the
3756  /// member enumeration ED.
3757  void setInstantiationOfMemberEnum(EnumDecl *ED,
3758                                    TemplateSpecializationKind TSK) {
3759    setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3760  }
3761
3762  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3763  static bool classofKind(Kind K) { return K == Enum; }
3764};
3765
3766/// Represents a struct/union/class.  For example:
3767///   struct X;                  // Forward declaration, no "body".
3768///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
3769/// This decl will be marked invalid if *any* members are invalid.
3770class RecordDecl : public TagDecl {
3771  // This class stores some data in DeclContext::RecordDeclBits
3772  // to save some space. Use the provided accessors to access it.
3773public:
3774  friend class DeclContext;
3775  /// Enum that represents the different ways arguments are passed to and
3776  /// returned from function calls. This takes into account the target-specific
3777  /// and version-specific rules along with the rules determined by the
3778  /// language.
3779  enum ArgPassingKind : unsigned {
3780    /// The argument of this type can be passed directly in registers.
3781    APK_CanPassInRegs,
3782
3783    /// The argument of this type cannot be passed directly in registers.
3784    /// Records containing this type as a subobject are not forced to be passed
3785    /// indirectly. This value is used only in C++. This value is required by
3786    /// C++ because, in uncommon situations, it is possible for a class to have
3787    /// only trivial copy/move constructors even when one of its subobjects has
3788    /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3789    /// constructor in the derived class is deleted).
3790    APK_CannotPassInRegs,
3791
3792    /// The argument of this type cannot be passed directly in registers.
3793    /// Records containing this type as a subobject are forced to be passed
3794    /// indirectly.
3795    APK_CanNeverPassInRegs
3796  };
3797
3798protected:
3799  RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3800             SourceLocation StartLoc, SourceLocation IdLoc,
3801             IdentifierInfo *Id, RecordDecl *PrevDecl);
3802
3803public:
3804  static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3805                            SourceLocation StartLoc, SourceLocation IdLoc,
3806                            IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3807  static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3808
3809  RecordDecl *getPreviousDecl() {
3810    return cast_or_null<RecordDecl>(
3811            static_cast<TagDecl *>(this)->getPreviousDecl());
3812  }
3813  const RecordDecl *getPreviousDecl() const {
3814    return const_cast<RecordDecl*>(this)->getPreviousDecl();
3815  }
3816
3817  RecordDecl *getMostRecentDecl() {
3818    return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3819  }
3820  const RecordDecl *getMostRecentDecl() const {
3821    return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3822  }
3823
3824  bool hasFlexibleArrayMember() const {
3825    return RecordDeclBits.HasFlexibleArrayMember;
3826  }
3827
3828  void setHasFlexibleArrayMember(bool V) {
3829    RecordDeclBits.HasFlexibleArrayMember = V;
3830  }
3831
3832  /// Whether this is an anonymous struct or union. To be an anonymous
3833  /// struct or union, it must have been declared without a name and
3834  /// there must be no objects of this type declared, e.g.,
3835  /// @code
3836  ///   union { int i; float f; };
3837  /// @endcode
3838  /// is an anonymous union but neither of the following are:
3839  /// @code
3840  ///  union X { int i; float f; };
3841  ///  union { int i; float f; } obj;
3842  /// @endcode
3843  bool isAnonymousStructOrUnion() const {
3844    return RecordDeclBits.AnonymousStructOrUnion;
3845  }
3846
3847  void setAnonymousStructOrUnion(bool Anon) {
3848    RecordDeclBits.AnonymousStructOrUnion = Anon;
3849  }
3850
3851  bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3852  void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3853
3854  bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3855
3856  void setHasVolatileMember(bool val) {
3857    RecordDeclBits.HasVolatileMember = val;
3858  }
3859
3860  bool hasLoadedFieldsFromExternalStorage() const {
3861    return RecordDeclBits.LoadedFieldsFromExternalStorage;
3862  }
3863
3864  void setHasLoadedFieldsFromExternalStorage(bool val) const {
3865    RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3866  }
3867
3868  /// Functions to query basic properties of non-trivial C structs.
3869  bool isNonTrivialToPrimitiveDefaultInitialize() const {
3870    return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3871  }
3872
3873  void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3874    RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3875  }
3876
3877  bool isNonTrivialToPrimitiveCopy() const {
3878    return RecordDeclBits.NonTrivialToPrimitiveCopy;
3879  }
3880
3881  void setNonTrivialToPrimitiveCopy(bool V) {
3882    RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3883  }
3884
3885  bool isNonTrivialToPrimitiveDestroy() const {
3886    return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3887  }
3888
3889  void setNonTrivialToPrimitiveDestroy(bool V) {
3890    RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3891  }
3892
3893  bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
3894    return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
3895  }
3896
3897  void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
3898    RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
3899  }
3900
3901  bool hasNonTrivialToPrimitiveDestructCUnion() const {
3902    return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
3903  }
3904
3905  void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
3906    RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
3907  }
3908
3909  bool hasNonTrivialToPrimitiveCopyCUnion() const {
3910    return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
3911  }
3912
3913  void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
3914    RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
3915  }
3916
3917  /// Determine whether this class can be passed in registers. In C++ mode,
3918  /// it must have at least one trivial, non-deleted copy or move constructor.
3919  /// FIXME: This should be set as part of completeDefinition.
3920  bool canPassInRegisters() const {
3921    return getArgPassingRestrictions() == APK_CanPassInRegs;
3922  }
3923
3924  ArgPassingKind getArgPassingRestrictions() const {
3925    return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3926  }
3927
3928  void setArgPassingRestrictions(ArgPassingKind Kind) {
3929    RecordDeclBits.ArgPassingRestrictions = Kind;
3930  }
3931
3932  bool isParamDestroyedInCallee() const {
3933    return RecordDeclBits.ParamDestroyedInCallee;
3934  }
3935
3936  void setParamDestroyedInCallee(bool V) {
3937    RecordDeclBits.ParamDestroyedInCallee = V;
3938  }
3939
3940  /// Determines whether this declaration represents the
3941  /// injected class name.
3942  ///
3943  /// The injected class name in C++ is the name of the class that
3944  /// appears inside the class itself. For example:
3945  ///
3946  /// \code
3947  /// struct C {
3948  ///   // C is implicitly declared here as a synonym for the class name.
3949  /// };
3950  ///
3951  /// C::C c; // same as "C c;"
3952  /// \endcode
3953  bool isInjectedClassName() const;
3954
3955  /// Determine whether this record is a class describing a lambda
3956  /// function object.
3957  bool isLambda() const;
3958
3959  /// Determine whether this record is a record for captured variables in
3960  /// CapturedStmt construct.
3961  bool isCapturedRecord() const;
3962
3963  /// Mark the record as a record for captured variables in CapturedStmt
3964  /// construct.
3965  void setCapturedRecord();
3966
3967  /// Returns the RecordDecl that actually defines
3968  ///  this struct/union/class.  When determining whether or not a
3969  ///  struct/union/class is completely defined, one should use this
3970  ///  method as opposed to 'isCompleteDefinition'.
3971  ///  'isCompleteDefinition' indicates whether or not a specific
3972  ///  RecordDecl is a completed definition, not whether or not the
3973  ///  record type is defined.  This method returns NULL if there is
3974  ///  no RecordDecl that defines the struct/union/tag.
3975  RecordDecl *getDefinition() const {
3976    return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3977  }
3978
3979  /// Returns whether this record is a union, or contains (at any nesting level)
3980  /// a union member. This is used by CMSE to warn about possible information
3981  /// leaks.
3982  bool isOrContainsUnion() const;
3983
3984  // Iterator access to field members. The field iterator only visits
3985  // the non-static data members of this class, ignoring any static
3986  // data members, functions, constructors, destructors, etc.
3987  using field_iterator = specific_decl_iterator<FieldDecl>;
3988  using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3989
3990  field_range fields() const { return field_range(field_begin(), field_end()); }
3991  field_iterator field_begin() const;
3992
3993  field_iterator field_end() const {
3994    return field_iterator(decl_iterator());
3995  }
3996
3997  // Whether there are any fields (non-static data members) in this record.
3998  bool field_empty() const {
3999    return field_begin() == field_end();
4000  }
4001
4002  /// Note that the definition of this type is now complete.
4003  virtual void completeDefinition();
4004
4005  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4006  static bool classofKind(Kind K) {
4007    return K >= firstRecord && K <= lastRecord;
4008  }
4009
4010  /// Get whether or not this is an ms_struct which can
4011  /// be turned on with an attribute, pragma, or -mms-bitfields
4012  /// commandline option.
4013  bool isMsStruct(const ASTContext &C) const;
4014
4015  /// Whether we are allowed to insert extra padding between fields.
4016  /// These padding are added to help AddressSanitizer detect
4017  /// intra-object-overflow bugs.
4018  bool mayInsertExtraPadding(bool EmitRemark = false) const;
4019
4020  /// Finds the first data member which has a name.
4021  /// nullptr is returned if no named data member exists.
4022  const FieldDecl *findFirstNamedDataMember() const;
4023
4024private:
4025  /// Deserialize just the fields.
4026  void LoadFieldsFromExternalStorage() const;
4027};
4028
4029class FileScopeAsmDecl : public Decl {
4030  StringLiteral *AsmString;
4031  SourceLocation RParenLoc;
4032
4033  FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
4034                   SourceLocation StartL, SourceLocation EndL)
4035    : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
4036
4037  virtual void anchor();
4038
4039public:
4040  static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
4041                                  StringLiteral *Str, SourceLocation AsmLoc,
4042                                  SourceLocation RParenLoc);
4043
4044  static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4045
4046  SourceLocation getAsmLoc() const { return getLocation(); }
4047  SourceLocation getRParenLoc() const { return RParenLoc; }
4048  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4049  SourceRange getSourceRange() const override LLVM_READONLY {
4050    return SourceRange(getAsmLoc(), getRParenLoc());
4051  }
4052
4053  const StringLiteral *getAsmString() const { return AsmString; }
4054  StringLiteral *getAsmString() { return AsmString; }
4055  void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
4056
4057  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4058  static bool classofKind(Kind K) { return K == FileScopeAsm; }
4059};
4060
4061/// Represents a block literal declaration, which is like an
4062/// unnamed FunctionDecl.  For example:
4063/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
4064class BlockDecl : public Decl, public DeclContext {
4065  // This class stores some data in DeclContext::BlockDeclBits
4066  // to save some space. Use the provided accessors to access it.
4067public:
4068  /// A class which contains all the information about a particular
4069  /// captured value.
4070  class Capture {
4071    enum {
4072      flag_isByRef = 0x1,
4073      flag_isNested = 0x2
4074    };
4075
4076    /// The variable being captured.
4077    llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
4078
4079    /// The copy expression, expressed in terms of a DeclRef (or
4080    /// BlockDeclRef) to the captured variable.  Only required if the
4081    /// variable has a C++ class type.
4082    Expr *CopyExpr;
4083
4084  public:
4085    Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
4086      : VariableAndFlags(variable,
4087                  (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
4088        CopyExpr(copy) {}
4089
4090    /// The variable being captured.
4091    VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
4092
4093    /// Whether this is a "by ref" capture, i.e. a capture of a __block
4094    /// variable.
4095    bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
4096
4097    bool isEscapingByref() const {
4098      return getVariable()->isEscapingByref();
4099    }
4100
4101    bool isNonEscapingByref() const {
4102      return getVariable()->isNonEscapingByref();
4103    }
4104
4105    /// Whether this is a nested capture, i.e. the variable captured
4106    /// is not from outside the immediately enclosing function/block.
4107    bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
4108
4109    bool hasCopyExpr() const { return CopyExpr != nullptr; }
4110    Expr *getCopyExpr() const { return CopyExpr; }
4111    void setCopyExpr(Expr *e) { CopyExpr = e; }
4112  };
4113
4114private:
4115  /// A new[]'d array of pointers to ParmVarDecls for the formal
4116  /// parameters of this function.  This is null if a prototype or if there are
4117  /// no formals.
4118  ParmVarDecl **ParamInfo = nullptr;
4119  unsigned NumParams = 0;
4120
4121  Stmt *Body = nullptr;
4122  TypeSourceInfo *SignatureAsWritten = nullptr;
4123
4124  const Capture *Captures = nullptr;
4125  unsigned NumCaptures = 0;
4126
4127  unsigned ManglingNumber = 0;
4128  Decl *ManglingContextDecl = nullptr;
4129
4130protected:
4131  BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
4132
4133public:
4134  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
4135  static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4136
4137  SourceLocation getCaretLocation() const { return getLocation(); }
4138
4139  bool isVariadic() const { return BlockDeclBits.IsVariadic; }
4140  void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
4141
4142  CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
4143  Stmt *getBody() const override { return (Stmt*) Body; }
4144  void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
4145
4146  void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
4147  TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
4148
4149  // ArrayRef access to formal parameters.
4150  ArrayRef<ParmVarDecl *> parameters() const {
4151    return {ParamInfo, getNumParams()};
4152  }
4153  MutableArrayRef<ParmVarDecl *> parameters() {
4154    return {ParamInfo, getNumParams()};
4155  }
4156
4157  // Iterator access to formal parameters.
4158  using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
4159  using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
4160
4161  bool param_empty() const { return parameters().empty(); }
4162  param_iterator param_begin() { return parameters().begin(); }
4163  param_iterator param_end() { return parameters().end(); }
4164  param_const_iterator param_begin() const { return parameters().begin(); }
4165  param_const_iterator param_end() const { return parameters().end(); }
4166  size_t param_size() const { return parameters().size(); }
4167
4168  unsigned getNumParams() const { return NumParams; }
4169
4170  const ParmVarDecl *getParamDecl(unsigned i) const {
4171    assert(i < getNumParams() && "Illegal param #");
4172    return ParamInfo[i];
4173  }
4174  ParmVarDecl *getParamDecl(unsigned i) {
4175    assert(i < getNumParams() && "Illegal param #");
4176    return ParamInfo[i];
4177  }
4178
4179  void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
4180
4181  /// True if this block (or its nested blocks) captures
4182  /// anything of local storage from its enclosing scopes.
4183  bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
4184
4185  /// Returns the number of captured variables.
4186  /// Does not include an entry for 'this'.
4187  unsigned getNumCaptures() const { return NumCaptures; }
4188
4189  using capture_const_iterator = ArrayRef<Capture>::const_iterator;
4190
4191  ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
4192
4193  capture_const_iterator capture_begin() const { return captures().begin(); }
4194  capture_const_iterator capture_end() const { return captures().end(); }
4195
4196  bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4197  void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4198
4199  bool blockMissingReturnType() const {
4200    return BlockDeclBits.BlockMissingReturnType;
4201  }
4202
4203  void setBlockMissingReturnType(bool val = true) {
4204    BlockDeclBits.BlockMissingReturnType = val;
4205  }
4206
4207  bool isConversionFromLambda() const {
4208    return BlockDeclBits.IsConversionFromLambda;
4209  }
4210
4211  void setIsConversionFromLambda(bool val = true) {
4212    BlockDeclBits.IsConversionFromLambda = val;
4213  }
4214
4215  bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4216  void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4217
4218  bool canAvoidCopyToHeap() const {
4219    return BlockDeclBits.CanAvoidCopyToHeap;
4220  }
4221  void setCanAvoidCopyToHeap(bool B = true) {
4222    BlockDeclBits.CanAvoidCopyToHeap = B;
4223  }
4224
4225  bool capturesVariable(const VarDecl *var) const;
4226
4227  void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4228                   bool CapturesCXXThis);
4229
4230  unsigned getBlockManglingNumber() const { return ManglingNumber; }
4231
4232  Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
4233
4234  void setBlockMangling(unsigned Number, Decl *Ctx) {
4235    ManglingNumber = Number;
4236    ManglingContextDecl = Ctx;
4237  }
4238
4239  SourceRange getSourceRange() const override LLVM_READONLY;
4240
4241  // Implement isa/cast/dyncast/etc.
4242  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4243  static bool classofKind(Kind K) { return K == Block; }
4244  static DeclContext *castToDeclContext(const BlockDecl *D) {
4245    return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4246  }
4247  static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4248    return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4249  }
4250};
4251
4252/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4253class CapturedDecl final
4254    : public Decl,
4255      public DeclContext,
4256      private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4257protected:
4258  size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4259    return NumParams;
4260  }
4261
4262private:
4263  /// The number of parameters to the outlined function.
4264  unsigned NumParams;
4265
4266  /// The position of context parameter in list of parameters.
4267  unsigned ContextParam;
4268
4269  /// The body of the outlined function.
4270  llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4271
4272  explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4273
4274  ImplicitParamDecl *const *getParams() const {
4275    return getTrailingObjects<ImplicitParamDecl *>();
4276  }
4277
4278  ImplicitParamDecl **getParams() {
4279    return getTrailingObjects<ImplicitParamDecl *>();
4280  }
4281
4282public:
4283  friend class ASTDeclReader;
4284  friend class ASTDeclWriter;
4285  friend TrailingObjects;
4286
4287  static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4288                              unsigned NumParams);
4289  static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4290                                          unsigned NumParams);
4291
4292  Stmt *getBody() const override;
4293  void setBody(Stmt *B);
4294
4295  bool isNothrow() const;
4296  void setNothrow(bool Nothrow = true);
4297
4298  unsigned getNumParams() const { return NumParams; }
4299
4300  ImplicitParamDecl *getParam(unsigned i) const {
4301    assert(i < NumParams);
4302    return getParams()[i];
4303  }
4304  void setParam(unsigned i, ImplicitParamDecl *P) {
4305    assert(i < NumParams);
4306    getParams()[i] = P;
4307  }
4308
4309  // ArrayRef interface to parameters.
4310  ArrayRef<ImplicitParamDecl *> parameters() const {
4311    return {getParams(), getNumParams()};
4312  }
4313  MutableArrayRef<ImplicitParamDecl *> parameters() {
4314    return {getParams(), getNumParams()};
4315  }
4316
4317  /// Retrieve the parameter containing captured variables.
4318  ImplicitParamDecl *getContextParam() const {
4319    assert(ContextParam < NumParams);
4320    return getParam(ContextParam);
4321  }
4322  void setContextParam(unsigned i, ImplicitParamDecl *P) {
4323    assert(i < NumParams);
4324    ContextParam = i;
4325    setParam(i, P);
4326  }
4327  unsigned getContextParamPosition() const { return ContextParam; }
4328
4329  using param_iterator = ImplicitParamDecl *const *;
4330  using param_range = llvm::iterator_range<param_iterator>;
4331
4332  /// Retrieve an iterator pointing to the first parameter decl.
4333  param_iterator param_begin() const { return getParams(); }
4334  /// Retrieve an iterator one past the last parameter decl.
4335  param_iterator param_end() const { return getParams() + NumParams; }
4336
4337  // Implement isa/cast/dyncast/etc.
4338  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4339  static bool classofKind(Kind K) { return K == Captured; }
4340  static DeclContext *castToDeclContext(const CapturedDecl *D) {
4341    return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4342  }
4343  static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4344    return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4345  }
4346};
4347
4348/// Describes a module import declaration, which makes the contents
4349/// of the named module visible in the current translation unit.
4350///
4351/// An import declaration imports the named module (or submodule). For example:
4352/// \code
4353///   @import std.vector;
4354/// \endcode
4355///
4356/// Import declarations can also be implicitly generated from
4357/// \#include/\#import directives.
4358class ImportDecl final : public Decl,
4359                         llvm::TrailingObjects<ImportDecl, SourceLocation> {
4360  friend class ASTContext;
4361  friend class ASTDeclReader;
4362  friend class ASTReader;
4363  friend TrailingObjects;
4364
4365  /// The imported module.
4366  Module *ImportedModule = nullptr;
4367
4368  /// The next import in the list of imports local to the translation
4369  /// unit being parsed (not loaded from an AST file).
4370  ///
4371  /// Includes a bit that indicates whether we have source-location information
4372  /// for each identifier in the module name.
4373  ///
4374  /// When the bit is false, we only have a single source location for the
4375  /// end of the import declaration.
4376  llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete;
4377
4378  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4379             ArrayRef<SourceLocation> IdentifierLocs);
4380
4381  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4382             SourceLocation EndLoc);
4383
4384  ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4385
4386  bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); }
4387
4388  void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); }
4389
4390  /// The next import in the list of imports local to the translation
4391  /// unit being parsed (not loaded from an AST file).
4392  ImportDecl *getNextLocalImport() const {
4393    return NextLocalImportAndComplete.getPointer();
4394  }
4395
4396  void setNextLocalImport(ImportDecl *Import) {
4397    NextLocalImportAndComplete.setPointer(Import);
4398  }
4399
4400public:
4401  /// Create a new module import declaration.
4402  static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4403                            SourceLocation StartLoc, Module *Imported,
4404                            ArrayRef<SourceLocation> IdentifierLocs);
4405
4406  /// Create a new module import declaration for an implicitly-generated
4407  /// import.
4408  static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4409                                    SourceLocation StartLoc, Module *Imported,
4410                                    SourceLocation EndLoc);
4411
4412  /// Create a new, deserialized module import declaration.
4413  static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4414                                        unsigned NumLocations);
4415
4416  /// Retrieve the module that was imported by the import declaration.
4417  Module *getImportedModule() const { return ImportedModule; }
4418
4419  /// Retrieves the locations of each of the identifiers that make up
4420  /// the complete module name in the import declaration.
4421  ///
4422  /// This will return an empty array if the locations of the individual
4423  /// identifiers aren't available.
4424  ArrayRef<SourceLocation> getIdentifierLocs() const;
4425
4426  SourceRange getSourceRange() const override LLVM_READONLY;
4427
4428  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4429  static bool classofKind(Kind K) { return K == Import; }
4430};
4431
4432/// Represents a C++ Modules TS module export declaration.
4433///
4434/// For example:
4435/// \code
4436///   export void foo();
4437/// \endcode
4438class ExportDecl final : public Decl, public DeclContext {
4439  virtual void anchor();
4440
4441private:
4442  friend class ASTDeclReader;
4443
4444  /// The source location for the right brace (if valid).
4445  SourceLocation RBraceLoc;
4446
4447  ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4448      : Decl(Export, DC, ExportLoc), DeclContext(Export),
4449        RBraceLoc(SourceLocation()) {}
4450
4451public:
4452  static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4453                            SourceLocation ExportLoc);
4454  static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4455
4456  SourceLocation getExportLoc() const { return getLocation(); }
4457  SourceLocation getRBraceLoc() const { return RBraceLoc; }
4458  void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4459
4460  bool hasBraces() const { return RBraceLoc.isValid(); }
4461
4462  SourceLocation getEndLoc() const LLVM_READONLY {
4463    if (hasBraces())
4464      return RBraceLoc;
4465    // No braces: get the end location of the (only) declaration in context
4466    // (if present).
4467    return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4468  }
4469
4470  SourceRange getSourceRange() const override LLVM_READONLY {
4471    return SourceRange(getLocation(), getEndLoc());
4472  }
4473
4474  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4475  static bool classofKind(Kind K) { return K == Export; }
4476  static DeclContext *castToDeclContext(const ExportDecl *D) {
4477    return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4478  }
4479  static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4480    return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4481  }
4482};
4483
4484/// Represents an empty-declaration.
4485class EmptyDecl : public Decl {
4486  EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4487
4488  virtual void anchor();
4489
4490public:
4491  static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4492                           SourceLocation L);
4493  static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4494
4495  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4496  static bool classofKind(Kind K) { return K == Empty; }
4497};
4498
4499/// Insertion operator for diagnostics.  This allows sending NamedDecl's
4500/// into a diagnostic with <<.
4501inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4502                                           const NamedDecl* ND) {
4503  DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4504                  DiagnosticsEngine::ak_nameddecl);
4505  return DB;
4506}
4507inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4508                                           const NamedDecl* ND) {
4509  PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4510                  DiagnosticsEngine::ak_nameddecl);
4511  return PD;
4512}
4513
4514template<typename decl_type>
4515void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4516  // Note: This routine is implemented here because we need both NamedDecl
4517  // and Redeclarable to be defined.
4518  assert(RedeclLink.isFirst() &&
4519         "setPreviousDecl on a decl already in a redeclaration chain");
4520
4521  if (PrevDecl) {
4522    // Point to previous. Make sure that this is actually the most recent
4523    // redeclaration, or we can build invalid chains. If the most recent
4524    // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4525    First = PrevDecl->getFirstDecl();
4526    assert(First->RedeclLink.isFirst() && "Expected first");
4527    decl_type *MostRecent = First->getNextRedeclaration();
4528    RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4529
4530    // If the declaration was previously visible, a redeclaration of it remains
4531    // visible even if it wouldn't be visible by itself.
4532    static_cast<decl_type*>(this)->IdentifierNamespace |=
4533      MostRecent->getIdentifierNamespace() &
4534      (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4535  } else {
4536    // Make this first.
4537    First = static_cast<decl_type*>(this);
4538  }
4539
4540  // First one will point to this one as latest.
4541  First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4542
4543  assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
4544         cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
4545}
4546
4547// Inline function definitions.
4548
4549/// Check if the given decl is complete.
4550///
4551/// We use this function to break a cycle between the inline definitions in
4552/// Type.h and Decl.h.
4553inline bool IsEnumDeclComplete(EnumDecl *ED) {
4554  return ED->isComplete();
4555}
4556
4557/// Check if the given decl is scoped.
4558///
4559/// We use this function to break a cycle between the inline definitions in
4560/// Type.h and Decl.h.
4561inline bool IsEnumDeclScoped(EnumDecl *ED) {
4562  return ED->isScoped();
4563}
4564
4565/// OpenMP variants are mangled early based on their OpenMP context selector.
4566/// The new name looks likes this:
4567///  <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context>
4568static constexpr StringRef getOpenMPVariantManglingSeparatorStr() {
4569  return "$ompvariant";
4570}
4571
4572} // namespace clang
4573
4574#endif // LLVM_CLANG_AST_DECL_H
4575