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