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