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