1 //===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the Decl subclasses.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_AST_DECL_H
14 #define LLVM_CLANG_AST_DECL_H
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTContextAllocate.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/ExternalASTSource.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/Redeclarable.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/AddressSpaces.h"
25 #include "clang/Basic/Diagnostic.h"
26 #include "clang/Basic/IdentifierTable.h"
27 #include "clang/Basic/LLVM.h"
28 #include "clang/Basic/Linkage.h"
29 #include "clang/Basic/OperatorKinds.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/PragmaKinds.h"
32 #include "clang/Basic/SourceLocation.h"
33 #include "clang/Basic/Specifiers.h"
34 #include "clang/Basic/Visibility.h"
35 #include "llvm/ADT/APSInt.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/PointerUnion.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/ADT/iterator_range.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/TrailingObjects.h"
54 struct ASTTemplateArgumentListInfo;
57 class DependentFunctionTemplateSpecializationInfo;
60 class FunctionTemplateDecl;
61 class FunctionTemplateSpecializationInfo;
63 class MemberSpecializationInfo;
71 class TemplateArgumentList;
72 class TemplateArgumentListInfo;
73 class TemplateParameterList;
74 class TypeAliasTemplateDecl;
76 class UnresolvedSetImpl;
77 class VarTemplateDecl;
79 /// A container of type source information.
81 /// A client can read the relevant info using TypeLoc wrappers, e.g:
83 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84 /// TL.getBeginLoc().print(OS, SrcMgr);
86 class alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
106 /// The top declaration context.
107 class TranslationUnitDecl : public Decl, public DeclContext {
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
114 explicit TranslationUnitDecl(ASTContext &ctx);
116 virtual void anchor();
119 ASTContext &getASTContext() const { return Ctx; }
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
124 static TranslationUnitDecl *Create(ASTContext &C);
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
137 /// Represents a `#pragma comment` line. Always a child of
138 /// TranslationUnitDecl.
139 class PragmaCommentDecl final
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
146 PragmaMSCommentKind CommentKind;
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
152 virtual void anchor();
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
164 StringRef getArg() const { return getTrailingObjects<char>(); }
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
171 /// Represents a `#pragma detect_mismatch` line. Always a child of
172 /// TranslationUnitDecl.
173 class PragmaDetectMismatchDecl final
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
186 virtual void anchor();
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
204 /// Declaration context for names declared as extern "C" in C++. This
205 /// is neither the semantic nor lexical context for such declarations, but is
206 /// used to check for conflicts with other extern "C" declarations. Example:
209 /// namespace N { extern "C" void f(); } // #1
210 /// void N::f() {} // #2
211 /// namespace M { extern "C" void f(); } // #3
214 /// The semantic context of #1 is namespace N and its lexical context is the
215 /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216 /// context is the TU. However, both declarations are also visible in the
217 /// extern "C" context.
219 /// The declaration at #3 finds it is a redeclaration of \c N::f through
220 /// lookup in the extern "C" context.
221 class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
226 virtual void anchor();
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
243 /// This represents a decl that may have a name. Many decls have names such
244 /// as ObjCMethodDecl, but not \@class, etc.
246 /// Note that not every NamedDecl is actually named (e.g., a struct might
247 /// be anonymous), and not every name is an identifier.
248 class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
254 virtual void anchor();
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
264 /// Get the identifier that names this declaration, if there is one.
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
271 /// Get the name of identifier for this declaration as a StringRef.
273 /// This requires that the declaration have a name and that it be a simple
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier");
277 return getIdentifier() ? getIdentifier()->getName() : "";
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
293 virtual void printName(raw_ostream &os) const;
295 /// Get the actual, stored name of the declaration, which may be a special
297 DeclarationName getDeclName() const { return Name; }
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
313 /// Print only the nested name specifier part of a fully-qualified name,
314 /// including the '::' at the end. E.g.
315 /// when `printQualifiedName(D)` prints "A::B::i",
316 /// this function prints "A::B::".
317 void printNestedNameSpecifier(raw_ostream &OS) const;
318 void printNestedNameSpecifier(raw_ostream &OS,
319 const PrintingPolicy &Policy) const;
321 // FIXME: Remove string version.
322 std::string getQualifiedNameAsString() const;
324 /// Appends a human-readable name for this declaration into the given stream.
326 /// This is the method invoked by Sema when displaying a NamedDecl
327 /// in a diagnostic. It does not necessarily produce the same
328 /// result as printName(); for example, class template
329 /// specializations are printed with their template arguments.
330 virtual void getNameForDiagnostic(raw_ostream &OS,
331 const PrintingPolicy &Policy,
332 bool Qualified) const;
334 /// Determine whether this declaration, if known to be well-formed within
335 /// its context, will replace the declaration OldD if introduced into scope.
337 /// A declaration will replace another declaration if, for example, it is
338 /// a redeclaration of the same variable or function, but not if it is a
339 /// declaration of a different kind (function vs. class) or an overloaded
342 /// \param IsKnownNewer \c true if this declaration is known to be newer
343 /// than \p OldD (for instance, if this declaration is newly-created).
344 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
346 /// Determine whether this declaration has linkage.
347 bool hasLinkage() const;
349 using Decl::isModulePrivate;
350 using Decl::setModulePrivate;
352 /// Determine whether this declaration is a C++ class member.
353 bool isCXXClassMember() const {
354 const DeclContext *DC = getDeclContext();
356 // C++0x [class.mem]p1:
357 // The enumerators of an unscoped enumeration defined in
358 // the class are members of the class.
359 if (isa<EnumDecl>(DC))
360 DC = DC->getRedeclContext();
362 return DC->isRecord();
365 /// Determine whether the given declaration is an instance member of
367 bool isCXXInstanceMember() const;
369 /// Determine what kind of linkage this entity has.
371 /// This is not the linkage as defined by the standard or the codegen notion
372 /// of linkage. It is just an implementation detail that is used to compute
374 Linkage getLinkageInternal() const;
376 /// Get the linkage from a semantic point of view. Entities in
377 /// anonymous namespaces are external (in c++98).
378 Linkage getFormalLinkage() const {
379 return clang::getFormalLinkage(getLinkageInternal());
382 /// True if this decl has external linkage.
383 bool hasExternalFormalLinkage() const {
384 return isExternalFormalLinkage(getLinkageInternal());
387 bool isExternallyVisible() const {
388 return clang::isExternallyVisible(getLinkageInternal());
391 /// Determine whether this declaration can be redeclared in a
392 /// different translation unit.
393 bool isExternallyDeclarable() const {
394 return isExternallyVisible() && !getOwningModuleForLinkage();
397 /// Determines the visibility of this entity.
398 Visibility getVisibility() const {
399 return getLinkageAndVisibility().getVisibility();
402 /// Determines the linkage and visibility of this entity.
403 LinkageInfo getLinkageAndVisibility() const;
405 /// Kinds of explicit visibility.
406 enum ExplicitVisibilityKind {
407 /// Do an LV computation for, ultimately, a type.
408 /// Visibility may be restricted by type visibility settings and
409 /// the visibility of template arguments.
412 /// Do an LV computation for, ultimately, a non-type declaration.
413 /// Visibility may be restricted by value visibility settings and
414 /// the visibility of template arguments.
418 /// If visibility was explicitly specified for this
419 /// declaration, return that visibility.
421 getExplicitVisibility(ExplicitVisibilityKind kind) const;
423 /// True if the computed linkage is valid. Used for consistency
424 /// checking. Should always return true.
425 bool isLinkageValid() const;
427 /// True if something has required us to compute the linkage
428 /// of this declaration.
430 /// Language features which can retroactively change linkage (like a
431 /// typedef name for linkage purposes) may need to consider this,
432 /// but hopefully only in transitory ways during parsing.
433 bool hasLinkageBeenComputed() const {
434 return hasCachedLinkage();
437 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
438 /// the underlying named decl.
439 NamedDecl *getUnderlyingDecl() {
440 // Fast-path the common case.
441 if (this->getKind() != UsingShadow &&
442 this->getKind() != ConstructorUsingShadow &&
443 this->getKind() != ObjCCompatibleAlias &&
444 this->getKind() != NamespaceAlias)
447 return getUnderlyingDeclImpl();
449 const NamedDecl *getUnderlyingDecl() const {
450 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
453 NamedDecl *getMostRecentDecl() {
454 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
456 const NamedDecl *getMostRecentDecl() const {
457 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
460 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
462 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
463 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
466 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
471 /// Represents the declaration of a label. Labels also have a
472 /// corresponding LabelStmt, which indicates the position that the label was
473 /// defined at. For normal labels, the location of the decl is the same as the
474 /// location of the statement. For GNU local labels (__label__), the decl
475 /// location is where the __label__ is.
476 class LabelDecl : public NamedDecl {
479 bool MSAsmNameResolved = false;
481 /// For normal labels, this is the same as the main declaration
482 /// label, i.e., the location of the identifier; for GNU local labels,
483 /// this is the location of the __label__ keyword.
484 SourceLocation LocStart;
486 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
487 LabelStmt *S, SourceLocation StartL)
488 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
490 void anchor() override;
493 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
494 SourceLocation IdentL, IdentifierInfo *II);
495 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
496 SourceLocation IdentL, IdentifierInfo *II,
497 SourceLocation GnuLabelL);
498 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
500 LabelStmt *getStmt() const { return TheStmt; }
501 void setStmt(LabelStmt *T) { TheStmt = T; }
503 bool isGnuLocal() const { return LocStart != getLocation(); }
504 void setLocStart(SourceLocation L) { LocStart = L; }
506 SourceRange getSourceRange() const override LLVM_READONLY {
507 return SourceRange(LocStart, getLocation());
510 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
511 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
512 void setMSAsmLabel(StringRef Name);
513 StringRef getMSAsmLabel() const { return MSAsmName; }
514 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
516 // Implement isa/cast/dyncast/etc.
517 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
518 static bool classofKind(Kind K) { return K == Label; }
521 /// Represent a C++ namespace.
522 class NamespaceDecl : public NamedDecl, public DeclContext,
523 public Redeclarable<NamespaceDecl>
525 /// The starting location of the source range, pointing
526 /// to either the namespace or the inline keyword.
527 SourceLocation LocStart;
529 /// The ending location of the source range.
530 SourceLocation RBraceLoc;
532 /// A pointer to either the anonymous namespace that lives just inside
533 /// this namespace or to the first namespace in the chain (the latter case
534 /// only when this is not the first in the chain), along with a
535 /// boolean value indicating whether this is an inline namespace.
536 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
538 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
539 SourceLocation StartLoc, SourceLocation IdLoc,
540 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
542 using redeclarable_base = Redeclarable<NamespaceDecl>;
544 NamespaceDecl *getNextRedeclarationImpl() override;
545 NamespaceDecl *getPreviousDeclImpl() override;
546 NamespaceDecl *getMostRecentDeclImpl() override;
549 friend class ASTDeclReader;
550 friend class ASTDeclWriter;
552 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
553 bool Inline, SourceLocation StartLoc,
554 SourceLocation IdLoc, IdentifierInfo *Id,
555 NamespaceDecl *PrevDecl);
557 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
559 using redecl_range = redeclarable_base::redecl_range;
560 using redecl_iterator = redeclarable_base::redecl_iterator;
562 using redeclarable_base::redecls_begin;
563 using redeclarable_base::redecls_end;
564 using redeclarable_base::redecls;
565 using redeclarable_base::getPreviousDecl;
566 using redeclarable_base::getMostRecentDecl;
567 using redeclarable_base::isFirstDecl;
569 /// Returns true if this is an anonymous namespace declaration.
577 /// q.v. C++ [namespace.unnamed]
578 bool isAnonymousNamespace() const {
579 return !getIdentifier();
582 /// Returns true if this is an inline namespace declaration.
583 bool isInline() const {
584 return AnonOrFirstNamespaceAndInline.getInt();
587 /// Set whether this is an inline namespace declaration.
588 void setInline(bool Inline) {
589 AnonOrFirstNamespaceAndInline.setInt(Inline);
592 /// Get the original (first) namespace declaration.
593 NamespaceDecl *getOriginalNamespace();
595 /// Get the original (first) namespace declaration.
596 const NamespaceDecl *getOriginalNamespace() const;
598 /// Return true if this declaration is an original (first) declaration
599 /// of the namespace. This is false for non-original (subsequent) namespace
600 /// declarations and anonymous namespaces.
601 bool isOriginalNamespace() const;
603 /// Retrieve the anonymous namespace nested inside this namespace,
605 NamespaceDecl *getAnonymousNamespace() const {
606 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
609 void setAnonymousNamespace(NamespaceDecl *D) {
610 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
613 /// Retrieves the canonical declaration of this namespace.
614 NamespaceDecl *getCanonicalDecl() override {
615 return getOriginalNamespace();
617 const NamespaceDecl *getCanonicalDecl() const {
618 return getOriginalNamespace();
621 SourceRange getSourceRange() const override LLVM_READONLY {
622 return SourceRange(LocStart, RBraceLoc);
625 SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
626 SourceLocation getRBraceLoc() const { return RBraceLoc; }
627 void setLocStart(SourceLocation L) { LocStart = L; }
628 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
630 // Implement isa/cast/dyncast/etc.
631 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
632 static bool classofKind(Kind K) { return K == Namespace; }
633 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
634 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
636 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
637 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
641 /// Represent the declaration of a variable (in which case it is
642 /// an lvalue) a function (in which case it is a function designator) or
643 /// an enum constant.
644 class ValueDecl : public NamedDecl {
647 void anchor() override;
650 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
651 DeclarationName N, QualType T)
652 : NamedDecl(DK, DC, L, N), DeclType(T) {}
655 QualType getType() const { return DeclType; }
656 void setType(QualType newType) { DeclType = newType; }
658 /// Determine whether this symbol is weakly-imported,
659 /// or declared with the weak or weak-ref attr.
662 // Implement isa/cast/dyncast/etc.
663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
664 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
667 /// A struct with extended info about a syntactic
668 /// name qualifier, to be used for the case of out-of-line declarations.
669 struct QualifierInfo {
670 NestedNameSpecifierLoc QualifierLoc;
672 /// The number of "outer" template parameter lists.
673 /// The count includes all of the template parameter lists that were matched
674 /// against the template-ids occurring into the NNS and possibly (in the
675 /// case of an explicit specialization) a final "template <>".
676 unsigned NumTemplParamLists = 0;
678 /// A new-allocated array of size NumTemplParamLists,
679 /// containing pointers to the "outer" template parameter lists.
680 /// It includes all of the template parameter lists that were matched
681 /// against the template-ids occurring into the NNS and possibly (in the
682 /// case of an explicit specialization) a final "template <>".
683 TemplateParameterList** TemplParamLists = nullptr;
685 QualifierInfo() = default;
686 QualifierInfo(const QualifierInfo &) = delete;
687 QualifierInfo& operator=(const QualifierInfo &) = delete;
689 /// Sets info about "outer" template parameter lists.
690 void setTemplateParameterListsInfo(ASTContext &Context,
691 ArrayRef<TemplateParameterList *> TPLists);
694 /// Represents a ValueDecl that came out of a declarator.
695 /// Contains type source information through TypeSourceInfo.
696 class DeclaratorDecl : public ValueDecl {
697 // A struct representing both a TInfo and a syntactic qualifier,
698 // to be used for the (uncommon) case of out-of-line declarations.
699 struct ExtInfo : public QualifierInfo {
700 TypeSourceInfo *TInfo;
703 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
705 /// The start of the source range for this declaration,
706 /// ignoring outer template declarations.
707 SourceLocation InnerLocStart;
709 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
710 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
711 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
714 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
715 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
716 SourceLocation StartL)
717 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
720 friend class ASTDeclReader;
721 friend class ASTDeclWriter;
723 TypeSourceInfo *getTypeSourceInfo() const {
725 ? getExtInfo()->TInfo
726 : DeclInfo.get<TypeSourceInfo*>();
729 void setTypeSourceInfo(TypeSourceInfo *TI) {
731 getExtInfo()->TInfo = TI;
736 /// Return start of source range ignoring outer template declarations.
737 SourceLocation getInnerLocStart() const { return InnerLocStart; }
738 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
740 /// Return start of source range taking into account any outer template
742 SourceLocation getOuterLocStart() const;
744 SourceRange getSourceRange() const override LLVM_READONLY;
746 SourceLocation getBeginLoc() const LLVM_READONLY {
747 return getOuterLocStart();
750 /// Retrieve the nested-name-specifier that qualifies the name of this
751 /// declaration, if it was present in the source.
752 NestedNameSpecifier *getQualifier() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
757 /// Retrieve the nested-name-specifier (with source-location
758 /// information) that qualifies the name of this declaration, if it was
759 /// present in the source.
760 NestedNameSpecifierLoc getQualifierLoc() const {
761 return hasExtInfo() ? getExtInfo()->QualifierLoc
762 : NestedNameSpecifierLoc();
765 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
767 unsigned getNumTemplateParameterLists() const {
768 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
771 TemplateParameterList *getTemplateParameterList(unsigned index) const {
772 assert(index < getNumTemplateParameterLists());
773 return getExtInfo()->TemplParamLists[index];
776 void setTemplateParameterListsInfo(ASTContext &Context,
777 ArrayRef<TemplateParameterList *> TPLists);
779 SourceLocation getTypeSpecStartLoc() const;
781 // Implement isa/cast/dyncast/etc.
782 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
783 static bool classofKind(Kind K) {
784 return K >= firstDeclarator && K <= lastDeclarator;
788 /// Structure used to store a statement, the constant value to
789 /// which it was evaluated (if any), and whether or not the statement
790 /// is an integral constant expression (if known).
791 struct EvaluatedStmt {
792 /// Whether this statement was already evaluated.
793 bool WasEvaluated : 1;
795 /// Whether this statement is being evaluated.
796 bool IsEvaluating : 1;
798 /// Whether we already checked whether this statement was an
799 /// integral constant expression.
802 /// Whether we are checking whether this statement is an
803 /// integral constant expression.
804 bool CheckingICE : 1;
806 /// Whether this statement is an integral constant expression,
807 /// or in C++11, whether the statement is a constant expression. Only
808 /// valid if CheckedICE is true.
811 /// Whether this variable is known to have constant destruction. That is,
812 /// whether running the destructor on the initial value is a side-effect
813 /// (and doesn't inspect any state that might have changed during program
814 /// execution). This is currently only computed if the destructor is
816 bool HasConstantDestruction : 1;
822 : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
823 CheckingICE(false), IsICE(false), HasConstantDestruction(false) {}
826 /// Represents a variable declaration or definition.
827 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
829 /// Initialization styles.
830 enum InitializationStyle {
831 /// C-style initialization with assignment
834 /// Call-style initialization (C++98)
837 /// Direct list-initialization (C++11)
841 /// Kinds of thread-local storage.
843 /// Not a TLS variable.
846 /// TLS with a known-constant initializer.
849 /// TLS with a dynamic initializer.
853 /// Return the string used to specify the storage class \p SC.
855 /// It is illegal to call this function with SC == None.
856 static const char *getStorageClassSpecifierString(StorageClass SC);
859 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
860 // have allocated the auxiliary struct of information there.
862 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
863 // this as *many* VarDecls are ParmVarDecls that don't have default
864 // arguments. We could save some space by moving this pointer union to be
865 // allocated in trailing space when necessary.
866 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
868 /// The initializer for this variable or, for a ParmVarDecl, the
869 /// C++ default argument.
870 mutable InitType Init;
873 friend class ASTDeclReader;
874 friend class ASTNodeImporter;
875 friend class StmtIteratorBase;
877 class VarDeclBitfields {
878 friend class ASTDeclReader;
879 friend class VarDecl;
882 unsigned TSCSpec : 2;
883 unsigned InitStyle : 2;
885 /// Whether this variable is an ARC pseudo-__strong variable; see
886 /// isARCPseudoStrong() for details.
887 unsigned ARCPseudoStrong : 1;
889 enum { NumVarDeclBits = 8 };
892 enum { NumParameterIndexBits = 8 };
894 enum DefaultArgKind {
901 class ParmVarDeclBitfields {
902 friend class ASTDeclReader;
903 friend class ParmVarDecl;
905 unsigned : NumVarDeclBits;
907 /// Whether this parameter inherits a default argument from a
908 /// prior declaration.
909 unsigned HasInheritedDefaultArg : 1;
911 /// Describes the kind of default argument for this parameter. By default
912 /// this is none. If this is normal, then the default argument is stored in
913 /// the \c VarDecl initializer expression unless we were unable to parse
914 /// (even an invalid) expression for the default argument.
915 unsigned DefaultArgKind : 2;
917 /// Whether this parameter undergoes K&R argument promotion.
918 unsigned IsKNRPromoted : 1;
920 /// Whether this parameter is an ObjC method parameter or not.
921 unsigned IsObjCMethodParam : 1;
923 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
924 /// Otherwise, the number of function parameter scopes enclosing
925 /// the function parameter scope in which this parameter was
927 unsigned ScopeDepthOrObjCQuals : 7;
929 /// The number of parameters preceding this parameter in the
930 /// function parameter scope in which it was declared.
931 unsigned ParameterIndex : NumParameterIndexBits;
934 class NonParmVarDeclBitfields {
935 friend class ASTDeclReader;
936 friend class ImplicitParamDecl;
937 friend class VarDecl;
939 unsigned : NumVarDeclBits;
941 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
942 /// Whether this variable is a definition which was demoted due to
944 unsigned IsThisDeclarationADemotedDefinition : 1;
946 /// Whether this variable is the exception variable in a C++ catch
947 /// or an Objective-C @catch statement.
948 unsigned ExceptionVar : 1;
950 /// Whether this local variable could be allocated in the return
951 /// slot of its function, enabling the named return value optimization
953 unsigned NRVOVariable : 1;
955 /// Whether this variable is the for-range-declaration in a C++0x
956 /// for-range statement.
957 unsigned CXXForRangeDecl : 1;
959 /// Whether this variable is the for-in loop declaration in Objective-C.
960 unsigned ObjCForDecl : 1;
962 /// Whether this variable is (C++1z) inline.
963 unsigned IsInline : 1;
965 /// Whether this variable has (C++1z) inline explicitly specified.
966 unsigned IsInlineSpecified : 1;
968 /// Whether this variable is (C++0x) constexpr.
969 unsigned IsConstexpr : 1;
971 /// Whether this variable is the implicit variable for a lambda
973 unsigned IsInitCapture : 1;
975 /// Whether this local extern variable's previous declaration was
976 /// declared in the same block scope. This controls whether we should merge
977 /// the type of this declaration with its previous declaration.
978 unsigned PreviousDeclInSameBlockScope : 1;
980 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
982 unsigned ImplicitParamKind : 3;
984 unsigned EscapingByref : 1;
989 VarDeclBitfields VarDeclBits;
990 ParmVarDeclBitfields ParmVarDeclBits;
991 NonParmVarDeclBitfields NonParmVarDeclBits;
994 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
995 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
996 TypeSourceInfo *TInfo, StorageClass SC);
998 using redeclarable_base = Redeclarable<VarDecl>;
1000 VarDecl *getNextRedeclarationImpl() override {
1001 return getNextRedeclaration();
1004 VarDecl *getPreviousDeclImpl() override {
1005 return getPreviousDecl();
1008 VarDecl *getMostRecentDeclImpl() override {
1009 return getMostRecentDecl();
1013 using redecl_range = redeclarable_base::redecl_range;
1014 using redecl_iterator = redeclarable_base::redecl_iterator;
1016 using redeclarable_base::redecls_begin;
1017 using redeclarable_base::redecls_end;
1018 using redeclarable_base::redecls;
1019 using redeclarable_base::getPreviousDecl;
1020 using redeclarable_base::getMostRecentDecl;
1021 using redeclarable_base::isFirstDecl;
1023 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1024 SourceLocation StartLoc, SourceLocation IdLoc,
1025 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1028 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1030 SourceRange getSourceRange() const override LLVM_READONLY;
1032 /// Returns the storage class as written in the source. For the
1033 /// computed linkage of symbol, see getLinkage.
1034 StorageClass getStorageClass() const {
1035 return (StorageClass) VarDeclBits.SClass;
1037 void setStorageClass(StorageClass SC);
1039 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1040 VarDeclBits.TSCSpec = TSC;
1041 assert(VarDeclBits.TSCSpec == TSC && "truncation");
1043 ThreadStorageClassSpecifier getTSCSpec() const {
1044 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1046 TLSKind getTLSKind() const;
1048 /// Returns true if a variable with function scope is a non-static local
1050 bool hasLocalStorage() const {
1051 if (getStorageClass() == SC_None) {
1052 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1053 // used to describe variables allocated in global memory and which are
1054 // accessed inside a kernel(s) as read-only variables. As such, variables
1055 // in constant address space cannot have local storage.
1056 if (getType().getAddressSpace() == LangAS::opencl_constant)
1058 // Second check is for C++11 [dcl.stc]p4.
1059 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1062 // Global Named Register (GNU extension)
1063 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1066 // Return true for: Auto, Register.
1067 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1069 return getStorageClass() >= SC_Auto;
1072 /// Returns true if a variable with function scope is a static local
1074 bool isStaticLocal() const {
1075 return (getStorageClass() == SC_Static ||
1076 // C++11 [dcl.stc]p4
1077 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1078 && !isFileVarDecl();
1081 /// Returns true if a variable has extern or __private_extern__
1083 bool hasExternalStorage() const {
1084 return getStorageClass() == SC_Extern ||
1085 getStorageClass() == SC_PrivateExtern;
1088 /// Returns true for all variables that do not have local storage.
1090 /// This includes all global variables as well as static variables declared
1091 /// within a function.
1092 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1094 /// Get the storage duration of this variable, per C++ [basic.stc].
1095 StorageDuration getStorageDuration() const {
1096 return hasLocalStorage() ? SD_Automatic :
1097 getTSCSpec() ? SD_Thread : SD_Static;
1100 /// Compute the language linkage.
1101 LanguageLinkage getLanguageLinkage() const;
1103 /// Determines whether this variable is a variable with external, C linkage.
1104 bool isExternC() const;
1106 /// Determines whether this variable's context is, or is nested within,
1107 /// a C++ extern "C" linkage spec.
1108 bool isInExternCContext() const;
1110 /// Determines whether this variable's context is, or is nested within,
1111 /// a C++ extern "C++" linkage spec.
1112 bool isInExternCXXContext() const;
1114 /// Returns true for local variable declarations other than parameters.
1115 /// Note that this includes static variables inside of functions. It also
1116 /// includes variables inside blocks.
1118 /// void foo() { int x; static int y; extern int z; }
1119 bool isLocalVarDecl() const {
1120 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1122 if (const DeclContext *DC = getLexicalDeclContext())
1123 return DC->getRedeclContext()->isFunctionOrMethod();
1127 /// Similar to isLocalVarDecl but also includes parameters.
1128 bool isLocalVarDeclOrParm() const {
1129 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1132 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1133 bool isFunctionOrMethodVarDecl() const {
1134 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1136 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1137 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1140 /// Determines whether this is a static data member.
1142 /// This will only be true in C++, and applies to, e.g., the
1143 /// variable 'x' in:
1149 bool isStaticDataMember() const {
1150 // If it wasn't static, it would be a FieldDecl.
1151 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1154 VarDecl *getCanonicalDecl() override;
1155 const VarDecl *getCanonicalDecl() const {
1156 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1159 enum DefinitionKind {
1160 /// This declaration is only a declaration.
1163 /// This declaration is a tentative definition.
1164 TentativeDefinition,
1166 /// This declaration is definitely a definition.
1170 /// Check whether this declaration is a definition. If this could be
1171 /// a tentative definition (in C), don't check whether there's an overriding
1173 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1174 DefinitionKind isThisDeclarationADefinition() const {
1175 return isThisDeclarationADefinition(getASTContext());
1178 /// Check whether this variable is defined in this translation unit.
1179 DefinitionKind hasDefinition(ASTContext &) const;
1180 DefinitionKind hasDefinition() const {
1181 return hasDefinition(getASTContext());
1184 /// Get the tentative definition that acts as the real definition in a TU.
1185 /// Returns null if there is a proper definition available.
1186 VarDecl *getActingDefinition();
1187 const VarDecl *getActingDefinition() const {
1188 return const_cast<VarDecl*>(this)->getActingDefinition();
1191 /// Get the real (not just tentative) definition for this declaration.
1192 VarDecl *getDefinition(ASTContext &);
1193 const VarDecl *getDefinition(ASTContext &C) const {
1194 return const_cast<VarDecl*>(this)->getDefinition(C);
1196 VarDecl *getDefinition() {
1197 return getDefinition(getASTContext());
1199 const VarDecl *getDefinition() const {
1200 return const_cast<VarDecl*>(this)->getDefinition();
1203 /// Determine whether this is or was instantiated from an out-of-line
1204 /// definition of a static data member.
1205 bool isOutOfLine() const override;
1207 /// Returns true for file scoped variable declaration.
1208 bool isFileVarDecl() const {
1210 if (K == ParmVar || K == ImplicitParam)
1213 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1216 if (isStaticDataMember())
1222 /// Get the initializer for this variable, no matter which
1223 /// declaration it is attached to.
1224 const Expr *getAnyInitializer() const {
1226 return getAnyInitializer(D);
1229 /// Get the initializer for this variable, no matter which
1230 /// declaration it is attached to. Also get that declaration.
1231 const Expr *getAnyInitializer(const VarDecl *&D) const;
1233 bool hasInit() const;
1234 const Expr *getInit() const {
1235 return const_cast<VarDecl *>(this)->getInit();
1239 /// Retrieve the address of the initializer expression.
1240 Stmt **getInitAddress();
1242 void setInit(Expr *I);
1244 /// Get the initializing declaration of this variable, if any. This is
1245 /// usually the definition, except that for a static data member it can be
1246 /// the in-class declaration.
1247 VarDecl *getInitializingDeclaration();
1248 const VarDecl *getInitializingDeclaration() const {
1249 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1252 /// Determine whether this variable's value might be usable in a
1253 /// constant expression, according to the relevant language standard.
1254 /// This only checks properties of the declaration, and does not check
1255 /// whether the initializer is in fact a constant expression.
1256 bool mightBeUsableInConstantExpressions(ASTContext &C) const;
1258 /// Determine whether this variable's value can be used in a
1259 /// constant expression, according to the relevant language standard,
1260 /// including checking whether it was initialized by a constant expression.
1261 bool isUsableInConstantExpressions(ASTContext &C) const;
1263 EvaluatedStmt *ensureEvaluatedStmt() const;
1265 /// Attempt to evaluate the value of the initializer attached to this
1266 /// declaration, and produce notes explaining why it cannot be evaluated or is
1267 /// not a constant expression. Returns a pointer to the value if evaluation
1268 /// succeeded, 0 otherwise.
1269 APValue *evaluateValue() const;
1270 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1272 /// Return the already-evaluated value of this variable's
1273 /// initializer, or NULL if the value is not yet known. Returns pointer
1274 /// to untyped APValue if the value could not be evaluated.
1275 APValue *getEvaluatedValue() const;
1277 /// Evaluate the destruction of this variable to determine if it constitutes
1278 /// constant destruction.
1280 /// \pre isInitICE()
1281 /// \return \c true if this variable has constant destruction, \c false if
1283 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1285 /// Determines whether it is already known whether the
1286 /// initializer is an integral constant expression or not.
1287 bool isInitKnownICE() const;
1289 /// Determines whether the initializer is an integral constant
1290 /// expression, or in C++11, whether the initializer is a constant
1293 /// \pre isInitKnownICE()
1294 bool isInitICE() const;
1296 /// Determine whether the value of the initializer attached to this
1297 /// declaration is an integral constant expression.
1298 bool checkInitIsICE() const;
1300 void setInitStyle(InitializationStyle Style) {
1301 VarDeclBits.InitStyle = Style;
1304 /// The style of initialization for this declaration.
1306 /// C-style initialization is "int x = 1;". Call-style initialization is
1307 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1308 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1309 /// expression for class types. List-style initialization is C++11 syntax,
1310 /// e.g. "int x{1};". Clients can distinguish between different forms of
1311 /// initialization by checking this value. In particular, "int x = {1};" is
1312 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1313 /// Init expression in all three cases is an InitListExpr.
1314 InitializationStyle getInitStyle() const {
1315 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1318 /// Whether the initializer is a direct-initializer (list or call).
1319 bool isDirectInit() const {
1320 return getInitStyle() != CInit;
1323 /// If this definition should pretend to be a declaration.
1324 bool isThisDeclarationADemotedDefinition() const {
1325 return isa<ParmVarDecl>(this) ? false :
1326 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1329 /// This is a definition which should be demoted to a declaration.
1331 /// In some cases (mostly module merging) we can end up with two visible
1332 /// definitions one of which needs to be demoted to a declaration to keep
1333 /// the AST invariants.
1334 void demoteThisDefinitionToDeclaration() {
1335 assert(isThisDeclarationADefinition() && "Not a definition!");
1336 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1337 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1340 /// Determine whether this variable is the exception variable in a
1341 /// C++ catch statememt or an Objective-C \@catch statement.
1342 bool isExceptionVariable() const {
1343 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1345 void setExceptionVariable(bool EV) {
1346 assert(!isa<ParmVarDecl>(this));
1347 NonParmVarDeclBits.ExceptionVar = EV;
1350 /// Determine whether this local variable can be used with the named
1351 /// return value optimization (NRVO).
1353 /// The named return value optimization (NRVO) works by marking certain
1354 /// non-volatile local variables of class type as NRVO objects. These
1355 /// locals can be allocated within the return slot of their containing
1356 /// function, in which case there is no need to copy the object to the
1357 /// return slot when returning from the function. Within the function body,
1358 /// each return that returns the NRVO object will have this variable as its
1360 bool isNRVOVariable() const {
1361 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1363 void setNRVOVariable(bool NRVO) {
1364 assert(!isa<ParmVarDecl>(this));
1365 NonParmVarDeclBits.NRVOVariable = NRVO;
1368 /// Determine whether this variable is the for-range-declaration in
1369 /// a C++0x for-range statement.
1370 bool isCXXForRangeDecl() const {
1371 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1373 void setCXXForRangeDecl(bool FRD) {
1374 assert(!isa<ParmVarDecl>(this));
1375 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1378 /// Determine whether this variable is a for-loop declaration for a
1379 /// for-in statement in Objective-C.
1380 bool isObjCForDecl() const {
1381 return NonParmVarDeclBits.ObjCForDecl;
1384 void setObjCForDecl(bool FRD) {
1385 NonParmVarDeclBits.ObjCForDecl = FRD;
1388 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1389 /// pseudo-__strong variable has a __strong-qualified type but does not
1390 /// actually retain the object written into it. Generally such variables are
1391 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1392 /// the variable is annotated with the objc_externally_retained attribute, 2)
1393 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1395 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1396 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1398 /// Whether this variable is (C++1z) inline.
1399 bool isInline() const {
1400 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1402 bool isInlineSpecified() const {
1403 return isa<ParmVarDecl>(this) ? false
1404 : NonParmVarDeclBits.IsInlineSpecified;
1406 void setInlineSpecified() {
1407 assert(!isa<ParmVarDecl>(this));
1408 NonParmVarDeclBits.IsInline = true;
1409 NonParmVarDeclBits.IsInlineSpecified = true;
1411 void setImplicitlyInline() {
1412 assert(!isa<ParmVarDecl>(this));
1413 NonParmVarDeclBits.IsInline = true;
1416 /// Whether this variable is (C++11) constexpr.
1417 bool isConstexpr() const {
1418 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1420 void setConstexpr(bool IC) {
1421 assert(!isa<ParmVarDecl>(this));
1422 NonParmVarDeclBits.IsConstexpr = IC;
1425 /// Whether this variable is the implicit variable for a lambda init-capture.
1426 bool isInitCapture() const {
1427 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1429 void setInitCapture(bool IC) {
1430 assert(!isa<ParmVarDecl>(this));
1431 NonParmVarDeclBits.IsInitCapture = IC;
1434 /// Determine whether this variable is actually a function parameter pack or
1435 /// init-capture pack.
1436 bool isParameterPack() const;
1438 /// Whether this local extern variable declaration's previous declaration
1439 /// was declared in the same block scope. Only correct in C++.
1440 bool isPreviousDeclInSameBlockScope() const {
1441 return isa<ParmVarDecl>(this)
1443 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1445 void setPreviousDeclInSameBlockScope(bool Same) {
1446 assert(!isa<ParmVarDecl>(this));
1447 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1450 /// Indicates the capture is a __block variable that is captured by a block
1451 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1453 bool isEscapingByref() const;
1455 /// Indicates the capture is a __block variable that is never captured by an
1457 bool isNonEscapingByref() const;
1459 void setEscapingByref() {
1460 NonParmVarDeclBits.EscapingByref = true;
1463 /// Retrieve the variable declaration from which this variable could
1464 /// be instantiated, if it is an instantiation (rather than a non-template).
1465 VarDecl *getTemplateInstantiationPattern() const;
1467 /// If this variable is an instantiated static data member of a
1468 /// class template specialization, returns the templated static data member
1469 /// from which it was instantiated.
1470 VarDecl *getInstantiatedFromStaticDataMember() const;
1472 /// If this variable is an instantiation of a variable template or a
1473 /// static data member of a class template, determine what kind of
1474 /// template specialization or instantiation this is.
1475 TemplateSpecializationKind getTemplateSpecializationKind() const;
1477 /// Get the template specialization kind of this variable for the purposes of
1478 /// template instantiation. This differs from getTemplateSpecializationKind()
1479 /// for an instantiation of a class-scope explicit specialization.
1480 TemplateSpecializationKind
1481 getTemplateSpecializationKindForInstantiation() const;
1483 /// If this variable is an instantiation of a variable template or a
1484 /// static data member of a class template, determine its point of
1486 SourceLocation getPointOfInstantiation() const;
1488 /// If this variable is an instantiation of a static data member of a
1489 /// class template specialization, retrieves the member specialization
1491 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1493 /// For a static data member that was instantiated from a static
1494 /// data member of a class template, set the template specialiation kind.
1495 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1496 SourceLocation PointOfInstantiation = SourceLocation());
1498 /// Specify that this variable is an instantiation of the
1499 /// static data member VD.
1500 void setInstantiationOfStaticDataMember(VarDecl *VD,
1501 TemplateSpecializationKind TSK);
1503 /// Retrieves the variable template that is described by this
1504 /// variable declaration.
1506 /// Every variable template is represented as a VarTemplateDecl and a
1507 /// VarDecl. The former contains template properties (such as
1508 /// the template parameter lists) while the latter contains the
1509 /// actual description of the template's
1510 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1511 /// VarDecl that from a VarTemplateDecl, while
1512 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1514 VarTemplateDecl *getDescribedVarTemplate() const;
1516 void setDescribedVarTemplate(VarTemplateDecl *Template);
1518 // Is this variable known to have a definition somewhere in the complete
1519 // program? This may be true even if the declaration has internal linkage and
1520 // has no definition within this source file.
1521 bool isKnownToBeDefined() const;
1523 /// Is destruction of this variable entirely suppressed? If so, the variable
1524 /// need not have a usable destructor at all.
1525 bool isNoDestroy(const ASTContext &) const;
1527 /// Do we need to emit an exit-time destructor for this variable, and if so,
1529 QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1531 // Implement isa/cast/dyncast/etc.
1532 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1533 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1536 class ImplicitParamDecl : public VarDecl {
1537 void anchor() override;
1540 /// Defines the kind of the implicit parameter: is this an implicit parameter
1541 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1542 /// context or something else.
1543 enum ImplicitParamKind : unsigned {
1544 /// Parameter for Objective-C 'self' argument
1547 /// Parameter for Objective-C '_cmd' argument
1550 /// Parameter for C++ 'this' argument
1553 /// Parameter for C++ virtual table pointers
1556 /// Parameter for captured context
1559 /// Other implicit parameter
1563 /// Create implicit parameter.
1564 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1565 SourceLocation IdLoc, IdentifierInfo *Id,
1566 QualType T, ImplicitParamKind ParamKind);
1567 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1568 ImplicitParamKind ParamKind);
1570 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1572 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1573 IdentifierInfo *Id, QualType Type,
1574 ImplicitParamKind ParamKind)
1575 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1576 /*TInfo=*/nullptr, SC_None) {
1577 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1581 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1582 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1583 SourceLocation(), /*Id=*/nullptr, Type,
1584 /*TInfo=*/nullptr, SC_None) {
1585 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1589 /// Returns the implicit parameter kind.
1590 ImplicitParamKind getParameterKind() const {
1591 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1594 // Implement isa/cast/dyncast/etc.
1595 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1596 static bool classofKind(Kind K) { return K == ImplicitParam; }
1599 /// Represents a parameter to a function.
1600 class ParmVarDecl : public VarDecl {
1602 enum { MaxFunctionScopeDepth = 255 };
1603 enum { MaxFunctionScopeIndex = 255 };
1606 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1607 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1608 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1609 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1610 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1611 assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1612 assert(ParmVarDeclBits.IsKNRPromoted == false);
1613 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1614 setDefaultArg(DefArg);
1618 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1619 SourceLocation StartLoc,
1620 SourceLocation IdLoc, IdentifierInfo *Id,
1621 QualType T, TypeSourceInfo *TInfo,
1622 StorageClass S, Expr *DefArg);
1624 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1626 SourceRange getSourceRange() const override LLVM_READONLY;
1628 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1629 ParmVarDeclBits.IsObjCMethodParam = true;
1630 setParameterIndex(parameterIndex);
1633 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1634 assert(!ParmVarDeclBits.IsObjCMethodParam);
1636 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1637 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1640 setParameterIndex(parameterIndex);
1643 bool isObjCMethodParameter() const {
1644 return ParmVarDeclBits.IsObjCMethodParam;
1647 unsigned getFunctionScopeDepth() const {
1648 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1649 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1652 /// Returns the index of this parameter in its prototype or method scope.
1653 unsigned getFunctionScopeIndex() const {
1654 return getParameterIndex();
1657 ObjCDeclQualifier getObjCDeclQualifier() const {
1658 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1659 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1661 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1662 assert(ParmVarDeclBits.IsObjCMethodParam);
1663 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1666 /// True if the value passed to this parameter must undergo
1667 /// K&R-style default argument promotion:
1670 /// If the expression that denotes the called function has a type
1671 /// that does not include a prototype, the integer promotions are
1672 /// performed on each argument, and arguments that have type float
1673 /// are promoted to double.
1674 bool isKNRPromoted() const {
1675 return ParmVarDeclBits.IsKNRPromoted;
1677 void setKNRPromoted(bool promoted) {
1678 ParmVarDeclBits.IsKNRPromoted = promoted;
1681 Expr *getDefaultArg();
1682 const Expr *getDefaultArg() const {
1683 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1686 void setDefaultArg(Expr *defarg);
1688 /// Retrieve the source range that covers the entire default
1690 SourceRange getDefaultArgRange() const;
1691 void setUninstantiatedDefaultArg(Expr *arg);
1692 Expr *getUninstantiatedDefaultArg();
1693 const Expr *getUninstantiatedDefaultArg() const {
1694 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1697 /// Determines whether this parameter has a default argument,
1698 /// either parsed or not.
1699 bool hasDefaultArg() const;
1701 /// Determines whether this parameter has a default argument that has not
1702 /// yet been parsed. This will occur during the processing of a C++ class
1703 /// whose member functions have default arguments, e.g.,
1707 /// void f(int x = 17); // x has an unparsed default argument now
1708 /// }; // x has a regular default argument now
1710 bool hasUnparsedDefaultArg() const {
1711 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1714 bool hasUninstantiatedDefaultArg() const {
1715 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1718 /// Specify that this parameter has an unparsed default argument.
1719 /// The argument will be replaced with a real default argument via
1720 /// setDefaultArg when the class definition enclosing the function
1721 /// declaration that owns this default argument is completed.
1722 void setUnparsedDefaultArg() {
1723 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1726 bool hasInheritedDefaultArg() const {
1727 return ParmVarDeclBits.HasInheritedDefaultArg;
1730 void setHasInheritedDefaultArg(bool I = true) {
1731 ParmVarDeclBits.HasInheritedDefaultArg = I;
1734 QualType getOriginalType() const;
1736 /// Sets the function declaration that owns this
1737 /// ParmVarDecl. Since ParmVarDecls are often created before the
1738 /// FunctionDecls that own them, this routine is required to update
1739 /// the DeclContext appropriately.
1740 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1742 // Implement isa/cast/dyncast/etc.
1743 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1744 static bool classofKind(Kind K) { return K == ParmVar; }
1747 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1749 void setParameterIndex(unsigned parameterIndex) {
1750 if (parameterIndex >= ParameterIndexSentinel) {
1751 setParameterIndexLarge(parameterIndex);
1755 ParmVarDeclBits.ParameterIndex = parameterIndex;
1756 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1758 unsigned getParameterIndex() const {
1759 unsigned d = ParmVarDeclBits.ParameterIndex;
1760 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1763 void setParameterIndexLarge(unsigned parameterIndex);
1764 unsigned getParameterIndexLarge() const;
1767 enum class MultiVersionKind {
1774 /// Represents a function declaration or definition.
1776 /// Since a given function can be declared several times in a program,
1777 /// there may be several FunctionDecls that correspond to that
1778 /// function. Only one of those FunctionDecls will be found when
1779 /// traversing the list of declarations in the context of the
1780 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1781 /// contains all of the information known about the function. Other,
1782 /// previous declarations of the function are available via the
1783 /// getPreviousDecl() chain.
1784 class FunctionDecl : public DeclaratorDecl,
1786 public Redeclarable<FunctionDecl> {
1787 // This class stores some data in DeclContext::FunctionDeclBits
1788 // to save some space. Use the provided accessors to access it.
1790 /// The kind of templated function a FunctionDecl can be.
1791 enum TemplatedKind {
1794 // The pattern in a function template declaration.
1795 TK_FunctionTemplate,
1796 // A non-template function that is an instantiation or explicit
1797 // specialization of a member of a templated class.
1798 TK_MemberSpecialization,
1799 // An instantiation or explicit specialization of a function template.
1800 // Note: this might have been instantiated from a templated class if it
1801 // is a class-scope explicit specialization.
1802 TK_FunctionTemplateSpecialization,
1803 // A function template specialization that hasn't yet been resolved to a
1804 // particular specialized function template.
1805 TK_DependentFunctionTemplateSpecialization
1809 /// A new[]'d array of pointers to VarDecls for the formal
1810 /// parameters of this function. This is null if a prototype or if there are
1812 ParmVarDecl **ParamInfo = nullptr;
1814 LazyDeclStmtPtr Body;
1818 /// End part of this FunctionDecl's source range.
1820 /// We could compute the full range in getSourceRange(). However, when we're
1821 /// dealing with a function definition deserialized from a PCH/AST file,
1822 /// we can only compute the full range once the function body has been
1823 /// de-serialized, so it's far better to have the (sometimes-redundant)
1825 SourceLocation EndRangeLoc;
1827 /// The template or declaration that this declaration
1828 /// describes or was instantiated from, respectively.
1830 /// For non-templates, this value will be NULL. For function
1831 /// declarations that describe a function template, this will be a
1832 /// pointer to a FunctionTemplateDecl. For member functions
1833 /// of class template specializations, this will be a MemberSpecializationInfo
1834 /// pointer containing information about the specialization.
1835 /// For function template specializations, this will be a
1836 /// FunctionTemplateSpecializationInfo, which contains information about
1837 /// the template being specialized and the template arguments involved in
1838 /// that specialization.
1839 llvm::PointerUnion4<FunctionTemplateDecl *,
1840 MemberSpecializationInfo *,
1841 FunctionTemplateSpecializationInfo *,
1842 DependentFunctionTemplateSpecializationInfo *>
1843 TemplateOrSpecialization;
1845 /// Provides source/type location info for the declaration name embedded in
1846 /// the DeclaratorDecl base class.
1847 DeclarationNameLoc DNLoc;
1849 /// Specify that this function declaration is actually a function
1850 /// template specialization.
1852 /// \param C the ASTContext.
1854 /// \param Template the function template that this function template
1855 /// specialization specializes.
1857 /// \param TemplateArgs the template arguments that produced this
1858 /// function template specialization from the template.
1860 /// \param InsertPos If non-NULL, the position in the function template
1861 /// specialization set where the function template specialization data will
1864 /// \param TSK the kind of template specialization this is.
1866 /// \param TemplateArgsAsWritten location info of template arguments.
1868 /// \param PointOfInstantiation point at which the function template
1869 /// specialization was first instantiated.
1870 void setFunctionTemplateSpecialization(ASTContext &C,
1871 FunctionTemplateDecl *Template,
1872 const TemplateArgumentList *TemplateArgs,
1874 TemplateSpecializationKind TSK,
1875 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1876 SourceLocation PointOfInstantiation);
1878 /// Specify that this record is an instantiation of the
1879 /// member function FD.
1880 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1881 TemplateSpecializationKind TSK);
1883 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1885 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1886 // need to access this bit but we want to avoid making ASTDeclWriter
1887 // a friend of FunctionDeclBitfields just for this.
1888 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1890 /// Whether an ODRHash has been stored.
1891 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1893 /// State that an ODRHash has been stored.
1894 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1897 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1898 const DeclarationNameInfo &NameInfo, QualType T,
1899 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1900 ConstexprSpecKind ConstexprKind);
1902 using redeclarable_base = Redeclarable<FunctionDecl>;
1904 FunctionDecl *getNextRedeclarationImpl() override {
1905 return getNextRedeclaration();
1908 FunctionDecl *getPreviousDeclImpl() override {
1909 return getPreviousDecl();
1912 FunctionDecl *getMostRecentDeclImpl() override {
1913 return getMostRecentDecl();
1917 friend class ASTDeclReader;
1918 friend class ASTDeclWriter;
1920 using redecl_range = redeclarable_base::redecl_range;
1921 using redecl_iterator = redeclarable_base::redecl_iterator;
1923 using redeclarable_base::redecls_begin;
1924 using redeclarable_base::redecls_end;
1925 using redeclarable_base::redecls;
1926 using redeclarable_base::getPreviousDecl;
1927 using redeclarable_base::getMostRecentDecl;
1928 using redeclarable_base::isFirstDecl;
1930 static FunctionDecl *
1931 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1932 SourceLocation NLoc, DeclarationName N, QualType T,
1933 TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false,
1934 bool hasWrittenPrototype = true,
1935 ConstexprSpecKind ConstexprKind = CSK_unspecified) {
1936 DeclarationNameInfo NameInfo(N, NLoc);
1937 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
1938 isInlineSpecified, hasWrittenPrototype,
1942 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1943 SourceLocation StartLoc,
1944 const DeclarationNameInfo &NameInfo, QualType T,
1945 TypeSourceInfo *TInfo, StorageClass SC,
1946 bool isInlineSpecified, bool hasWrittenPrototype,
1947 ConstexprSpecKind ConstexprKind);
1949 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1951 DeclarationNameInfo getNameInfo() const {
1952 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1955 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1956 bool Qualified) const override;
1958 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1960 SourceRange getSourceRange() const override LLVM_READONLY;
1962 // Function definitions.
1964 // A function declaration may be:
1965 // - a non defining declaration,
1966 // - a definition. A function may be defined because:
1967 // - it has a body, or will have it in the case of late parsing.
1968 // - it has an uninstantiated body. The body does not exist because the
1969 // function is not used yet, but the declaration is considered a
1970 // definition and does not allow other definition of this function.
1971 // - it does not have a user specified body, but it does not allow
1972 // redefinition, because it is deleted/defaulted or is defined through
1973 // some other mechanism (alias, ifunc).
1975 /// Returns true if the function has a body.
1977 /// The function body might be in any of the (re-)declarations of this
1978 /// function. The variant that accepts a FunctionDecl pointer will set that
1979 /// function declaration to the actual declaration containing the body (if
1981 bool hasBody(const FunctionDecl *&Definition) const;
1983 bool hasBody() const override {
1984 const FunctionDecl* Definition;
1985 return hasBody(Definition);
1988 /// Returns whether the function has a trivial body that does not require any
1989 /// specific codegen.
1990 bool hasTrivialBody() const;
1992 /// Returns true if the function has a definition that does not need to be
1995 /// The variant that accepts a FunctionDecl pointer will set that function
1996 /// declaration to the declaration that is a definition (if there is one).
1997 bool isDefined(const FunctionDecl *&Definition) const;
1999 virtual bool isDefined() const {
2000 const FunctionDecl* Definition;
2001 return isDefined(Definition);
2004 /// Get the definition for this declaration.
2005 FunctionDecl *getDefinition() {
2006 const FunctionDecl *Definition;
2007 if (isDefined(Definition))
2008 return const_cast<FunctionDecl *>(Definition);
2011 const FunctionDecl *getDefinition() const {
2012 return const_cast<FunctionDecl *>(this)->getDefinition();
2015 /// Retrieve the body (definition) of the function. The function body might be
2016 /// in any of the (re-)declarations of this function. The variant that accepts
2017 /// a FunctionDecl pointer will set that function declaration to the actual
2018 /// declaration containing the body (if there is one).
2019 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2020 /// unnecessary AST de-serialization of the body.
2021 Stmt *getBody(const FunctionDecl *&Definition) const;
2023 Stmt *getBody() const override {
2024 const FunctionDecl* Definition;
2025 return getBody(Definition);
2028 /// Returns whether this specific declaration of the function is also a
2029 /// definition that does not contain uninstantiated body.
2031 /// This does not determine whether the function has been defined (e.g., in a
2032 /// previous definition); for that information, use isDefined.
2033 bool isThisDeclarationADefinition() const {
2034 return isDeletedAsWritten() || isDefaulted() || Body || hasSkippedBody() ||
2035 isLateTemplateParsed() || willHaveBody() || hasDefiningAttr();
2038 /// Returns whether this specific declaration of the function has a body.
2039 bool doesThisDeclarationHaveABody() const {
2040 return Body || isLateTemplateParsed();
2043 void setBody(Stmt *B);
2044 void setLazyBody(uint64_t Offset) { Body = Offset; }
2046 /// Whether this function is variadic.
2047 bool isVariadic() const;
2049 /// Whether this function is marked as virtual explicitly.
2050 bool isVirtualAsWritten() const {
2051 return FunctionDeclBits.IsVirtualAsWritten;
2054 /// State that this function is marked as virtual explicitly.
2055 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2057 /// Whether this virtual function is pure, i.e. makes the containing class
2059 bool isPure() const { return FunctionDeclBits.IsPure; }
2060 void setPure(bool P = true);
2062 /// Whether this templated function will be late parsed.
2063 bool isLateTemplateParsed() const {
2064 return FunctionDeclBits.IsLateTemplateParsed;
2067 /// State that this templated function will be late parsed.
2068 void setLateTemplateParsed(bool ILT = true) {
2069 FunctionDeclBits.IsLateTemplateParsed = ILT;
2072 /// Whether this function is "trivial" in some specialized C++ senses.
2073 /// Can only be true for default constructors, copy constructors,
2074 /// copy assignment operators, and destructors. Not meaningful until
2075 /// the class has been fully built by Sema.
2076 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2077 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2079 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2080 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2082 /// Whether this function is defaulted per C++0x. Only valid for
2083 /// special member functions.
2084 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2085 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2087 /// Whether this function is explicitly defaulted per C++0x. Only valid
2088 /// for special member functions.
2089 bool isExplicitlyDefaulted() const {
2090 return FunctionDeclBits.IsExplicitlyDefaulted;
2093 /// State that this function is explicitly defaulted per C++0x. Only valid
2094 /// for special member functions.
2095 void setExplicitlyDefaulted(bool ED = true) {
2096 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2099 /// Whether falling off this function implicitly returns null/zero.
2100 /// If a more specific implicit return value is required, front-ends
2101 /// should synthesize the appropriate return statements.
2102 bool hasImplicitReturnZero() const {
2103 return FunctionDeclBits.HasImplicitReturnZero;
2106 /// State that falling off this function implicitly returns null/zero.
2107 /// If a more specific implicit return value is required, front-ends
2108 /// should synthesize the appropriate return statements.
2109 void setHasImplicitReturnZero(bool IRZ) {
2110 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2113 /// Whether this function has a prototype, either because one
2114 /// was explicitly written or because it was "inherited" by merging
2115 /// a declaration without a prototype with a declaration that has a
2117 bool hasPrototype() const {
2118 return hasWrittenPrototype() || hasInheritedPrototype();
2121 /// Whether this function has a written prototype.
2122 bool hasWrittenPrototype() const {
2123 return FunctionDeclBits.HasWrittenPrototype;
2126 /// State that this function has a written prototype.
2127 void setHasWrittenPrototype(bool P = true) {
2128 FunctionDeclBits.HasWrittenPrototype = P;
2131 /// Whether this function inherited its prototype from a
2132 /// previous declaration.
2133 bool hasInheritedPrototype() const {
2134 return FunctionDeclBits.HasInheritedPrototype;
2137 /// State that this function inherited its prototype from a
2138 /// previous declaration.
2139 void setHasInheritedPrototype(bool P = true) {
2140 FunctionDeclBits.HasInheritedPrototype = P;
2143 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2144 bool isConstexpr() const {
2145 return FunctionDeclBits.ConstexprKind != CSK_unspecified;
2147 void setConstexprKind(ConstexprSpecKind CSK) {
2148 FunctionDeclBits.ConstexprKind = CSK;
2150 ConstexprSpecKind getConstexprKind() const {
2151 return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2153 bool isConstexprSpecified() const {
2154 return FunctionDeclBits.ConstexprKind == CSK_constexpr;
2156 bool isConsteval() const {
2157 return FunctionDeclBits.ConstexprKind == CSK_consteval;
2160 /// Whether the instantiation of this function is pending.
2161 /// This bit is set when the decision to instantiate this function is made
2162 /// and unset if and when the function body is created. That leaves out
2163 /// cases where instantiation did not happen because the template definition
2164 /// was not seen in this TU. This bit remains set in those cases, under the
2165 /// assumption that the instantiation will happen in some other TU.
2166 bool instantiationIsPending() const {
2167 return FunctionDeclBits.InstantiationIsPending;
2170 /// State that the instantiation of this function is pending.
2171 /// (see instantiationIsPending)
2172 void setInstantiationIsPending(bool IC) {
2173 FunctionDeclBits.InstantiationIsPending = IC;
2176 /// Indicates the function uses __try.
2177 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2178 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2180 /// Whether this function has been deleted.
2182 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2183 /// acts like a normal function, except that it cannot actually be
2184 /// called or have its address taken. Deleted functions are
2185 /// typically used in C++ overload resolution to attract arguments
2186 /// whose type or lvalue/rvalue-ness would permit the use of a
2187 /// different overload that would behave incorrectly. For example,
2188 /// one might use deleted functions to ban implicit conversion from
2189 /// a floating-point number to an Integer type:
2192 /// struct Integer {
2193 /// Integer(long); // construct from a long
2194 /// Integer(double) = delete; // no construction from float or double
2195 /// Integer(long double) = delete; // no construction from long double
2198 // If a function is deleted, its first declaration must be.
2199 bool isDeleted() const {
2200 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2203 bool isDeletedAsWritten() const {
2204 return FunctionDeclBits.IsDeleted && !isDefaulted();
2207 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2209 /// Determines whether this function is "main", which is the
2210 /// entry point into an executable program.
2211 bool isMain() const;
2213 /// Determines whether this function is a MSVCRT user defined entry
2215 bool isMSVCRTEntryPoint() const;
2217 /// Determines whether this operator new or delete is one
2218 /// of the reserved global placement operators:
2219 /// void *operator new(size_t, void *);
2220 /// void *operator new[](size_t, void *);
2221 /// void operator delete(void *, void *);
2222 /// void operator delete[](void *, void *);
2223 /// These functions have special behavior under [new.delete.placement]:
2224 /// These functions are reserved, a C++ program may not define
2225 /// functions that displace the versions in the Standard C++ library.
2226 /// The provisions of [basic.stc.dynamic] do not apply to these
2227 /// reserved placement forms of operator new and operator delete.
2229 /// This function must be an allocation or deallocation function.
2230 bool isReservedGlobalPlacementOperator() const;
2232 /// Determines whether this function is one of the replaceable
2233 /// global allocation functions:
2234 /// void *operator new(size_t);
2235 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2236 /// void *operator new[](size_t);
2237 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2238 /// void operator delete(void *) noexcept;
2239 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2240 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2241 /// void operator delete[](void *) noexcept;
2242 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2243 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2244 /// These functions have special behavior under C++1y [expr.new]:
2245 /// An implementation is allowed to omit a call to a replaceable global
2246 /// allocation function. [...]
2248 /// If this function is an aligned allocation/deallocation function, return
2249 /// true through IsAligned.
2250 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2252 /// Determine whether this is a destroying operator delete.
2253 bool isDestroyingOperatorDelete() const;
2255 /// Compute the language linkage.
2256 LanguageLinkage getLanguageLinkage() const;
2258 /// Determines whether this function is a function with
2259 /// external, C linkage.
2260 bool isExternC() const;
2262 /// Determines whether this function's context is, or is nested within,
2263 /// a C++ extern "C" linkage spec.
2264 bool isInExternCContext() const;
2266 /// Determines whether this function's context is, or is nested within,
2267 /// a C++ extern "C++" linkage spec.
2268 bool isInExternCXXContext() const;
2270 /// Determines whether this is a global function.
2271 bool isGlobal() const;
2273 /// Determines whether this function is known to be 'noreturn', through
2274 /// an attribute on its declaration or its type.
2275 bool isNoReturn() const;
2277 /// True if the function was a definition but its body was skipped.
2278 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2279 void setHasSkippedBody(bool Skipped = true) {
2280 FunctionDeclBits.HasSkippedBody = Skipped;
2283 /// True if this function will eventually have a body, once it's fully parsed.
2284 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2285 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2287 /// True if this function is considered a multiversioned function.
2288 bool isMultiVersion() const {
2289 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2292 /// Sets the multiversion state for this declaration and all of its
2294 void setIsMultiVersion(bool V = true) {
2295 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2298 /// Gets the kind of multiversioning attribute this declaration has. Note that
2299 /// this can return a value even if the function is not multiversion, such as
2300 /// the case of 'target'.
2301 MultiVersionKind getMultiVersionKind() const;
2304 /// True if this function is a multiversioned dispatch function as a part of
2305 /// the cpu_specific/cpu_dispatch functionality.
2306 bool isCPUDispatchMultiVersion() const;
2307 /// True if this function is a multiversioned processor specific function as a
2308 /// part of the cpu_specific/cpu_dispatch functionality.
2309 bool isCPUSpecificMultiVersion() const;
2311 /// True if this function is a multiversioned dispatch function as a part of
2312 /// the target functionality.
2313 bool isTargetMultiVersion() const;
2315 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2317 FunctionDecl *getCanonicalDecl() override;
2318 const FunctionDecl *getCanonicalDecl() const {
2319 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2322 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2324 // ArrayRef interface to parameters.
2325 ArrayRef<ParmVarDecl *> parameters() const {
2326 return {ParamInfo, getNumParams()};
2328 MutableArrayRef<ParmVarDecl *> parameters() {
2329 return {ParamInfo, getNumParams()};
2332 // Iterator access to formal parameters.
2333 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2334 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2336 bool param_empty() const { return parameters().empty(); }
2337 param_iterator param_begin() { return parameters().begin(); }
2338 param_iterator param_end() { return parameters().end(); }
2339 param_const_iterator param_begin() const { return parameters().begin(); }
2340 param_const_iterator param_end() const { return parameters().end(); }
2341 size_t param_size() const { return parameters().size(); }
2343 /// Return the number of parameters this function must have based on its
2344 /// FunctionType. This is the length of the ParamInfo array after it has been
2346 unsigned getNumParams() const;
2348 const ParmVarDecl *getParamDecl(unsigned i) const {
2349 assert(i < getNumParams() && "Illegal param #");
2350 return ParamInfo[i];
2352 ParmVarDecl *getParamDecl(unsigned i) {
2353 assert(i < getNumParams() && "Illegal param #");
2354 return ParamInfo[i];
2356 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2357 setParams(getASTContext(), NewParamInfo);
2360 /// Returns the minimum number of arguments needed to call this function. This
2361 /// may be fewer than the number of function parameters, if some of the
2362 /// parameters have default arguments (in C++).
2363 unsigned getMinRequiredArguments() const;
2365 QualType getReturnType() const {
2366 return getType()->castAs<FunctionType>()->getReturnType();
2369 /// Attempt to compute an informative source range covering the
2370 /// function return type. This may omit qualifiers and other information with
2371 /// limited representation in the AST.
2372 SourceRange getReturnTypeSourceRange() const;
2374 /// Get the declared return type, which may differ from the actual return
2375 /// type if the return type is deduced.
2376 QualType getDeclaredReturnType() const {
2377 auto *TSI = getTypeSourceInfo();
2378 QualType T = TSI ? TSI->getType() : getType();
2379 return T->castAs<FunctionType>()->getReturnType();
2382 /// Gets the ExceptionSpecificationType as declared.
2383 ExceptionSpecificationType getExceptionSpecType() const {
2384 auto *TSI = getTypeSourceInfo();
2385 QualType T = TSI ? TSI->getType() : getType();
2386 const auto *FPT = T->getAs<FunctionProtoType>();
2387 return FPT ? FPT->getExceptionSpecType() : EST_None;
2390 /// Attempt to compute an informative source range covering the
2391 /// function exception specification, if any.
2392 SourceRange getExceptionSpecSourceRange() const;
2394 /// Determine the type of an expression that calls this function.
2395 QualType getCallResultType() const {
2396 return getType()->castAs<FunctionType>()->getCallResultType(
2400 /// Returns the storage class as written in the source. For the
2401 /// computed linkage of symbol, see getLinkage.
2402 StorageClass getStorageClass() const {
2403 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2406 /// Sets the storage class as written in the source.
2407 void setStorageClass(StorageClass SClass) {
2408 FunctionDeclBits.SClass = SClass;
2411 /// Determine whether the "inline" keyword was specified for this
2413 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2415 /// Set whether the "inline" keyword was specified for this function.
2416 void setInlineSpecified(bool I) {
2417 FunctionDeclBits.IsInlineSpecified = I;
2418 FunctionDeclBits.IsInline = I;
2421 /// Flag that this function is implicitly inline.
2422 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2424 /// Determine whether this function should be inlined, because it is
2425 /// either marked "inline" or "constexpr" or is a member function of a class
2426 /// that was defined in the class body.
2427 bool isInlined() const { return FunctionDeclBits.IsInline; }
2429 bool isInlineDefinitionExternallyVisible() const;
2431 bool isMSExternInline() const;
2433 bool doesDeclarationForceExternallyVisibleDefinition() const;
2435 bool isStatic() const { return getStorageClass() == SC_Static; }
2437 /// Whether this function declaration represents an C++ overloaded
2438 /// operator, e.g., "operator+".
2439 bool isOverloadedOperator() const {
2440 return getOverloadedOperator() != OO_None;
2443 OverloadedOperatorKind getOverloadedOperator() const;
2445 const IdentifierInfo *getLiteralIdentifier() const;
2447 /// If this function is an instantiation of a member function
2448 /// of a class template specialization, retrieves the function from
2449 /// which it was instantiated.
2451 /// This routine will return non-NULL for (non-templated) member
2452 /// functions of class templates and for instantiations of function
2453 /// templates. For example, given:
2456 /// template<typename T>
2462 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2463 /// whose parent is the class template specialization X<int>. For
2464 /// this declaration, getInstantiatedFromFunction() will return
2465 /// the FunctionDecl X<T>::A. When a complete definition of
2466 /// X<int>::A is required, it will be instantiated from the
2467 /// declaration returned by getInstantiatedFromMemberFunction().
2468 FunctionDecl *getInstantiatedFromMemberFunction() const;
2470 /// What kind of templated function this is.
2471 TemplatedKind getTemplatedKind() const;
2473 /// If this function is an instantiation of a member function of a
2474 /// class template specialization, retrieves the member specialization
2476 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2478 /// Specify that this record is an instantiation of the
2479 /// member function FD.
2480 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2481 TemplateSpecializationKind TSK) {
2482 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2485 /// Retrieves the function template that is described by this
2486 /// function declaration.
2488 /// Every function template is represented as a FunctionTemplateDecl
2489 /// and a FunctionDecl (or something derived from FunctionDecl). The
2490 /// former contains template properties (such as the template
2491 /// parameter lists) while the latter contains the actual
2492 /// description of the template's
2493 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2494 /// FunctionDecl that describes the function template,
2495 /// getDescribedFunctionTemplate() retrieves the
2496 /// FunctionTemplateDecl from a FunctionDecl.
2497 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2499 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2501 /// Determine whether this function is a function template
2503 bool isFunctionTemplateSpecialization() const {
2504 return getPrimaryTemplate() != nullptr;
2507 /// If this function is actually a function template specialization,
2508 /// retrieve information about this function template specialization.
2509 /// Otherwise, returns NULL.
2510 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2512 /// Determines whether this function is a function template
2513 /// specialization or a member of a class template specialization that can
2514 /// be implicitly instantiated.
2515 bool isImplicitlyInstantiable() const;
2517 /// Determines if the given function was instantiated from a
2518 /// function template.
2519 bool isTemplateInstantiation() const;
2521 /// Retrieve the function declaration from which this function could
2522 /// be instantiated, if it is an instantiation (rather than a non-template
2523 /// or a specialization, for example).
2524 FunctionDecl *getTemplateInstantiationPattern() const;
2526 /// Retrieve the primary template that this function template
2527 /// specialization either specializes or was instantiated from.
2529 /// If this function declaration is not a function template specialization,
2531 FunctionTemplateDecl *getPrimaryTemplate() const;
2533 /// Retrieve the template arguments used to produce this function
2534 /// template specialization from the primary template.
2536 /// If this function declaration is not a function template specialization,
2538 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2540 /// Retrieve the template argument list as written in the sources,
2543 /// If this function declaration is not a function template specialization
2544 /// or if it had no explicit template argument list, returns NULL.
2545 /// Note that it an explicit template argument list may be written empty,
2546 /// e.g., template<> void foo<>(char* s);
2547 const ASTTemplateArgumentListInfo*
2548 getTemplateSpecializationArgsAsWritten() const;
2550 /// Specify that this function declaration is actually a function
2551 /// template specialization.
2553 /// \param Template the function template that this function template
2554 /// specialization specializes.
2556 /// \param TemplateArgs the template arguments that produced this
2557 /// function template specialization from the template.
2559 /// \param InsertPos If non-NULL, the position in the function template
2560 /// specialization set where the function template specialization data will
2563 /// \param TSK the kind of template specialization this is.
2565 /// \param TemplateArgsAsWritten location info of template arguments.
2567 /// \param PointOfInstantiation point at which the function template
2568 /// specialization was first instantiated.
2569 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2570 const TemplateArgumentList *TemplateArgs,
2572 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2573 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2574 SourceLocation PointOfInstantiation = SourceLocation()) {
2575 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2576 InsertPos, TSK, TemplateArgsAsWritten,
2577 PointOfInstantiation);
2580 /// Specifies that this function declaration is actually a
2581 /// dependent function template specialization.
2582 void setDependentTemplateSpecialization(ASTContext &Context,
2583 const UnresolvedSetImpl &Templates,
2584 const TemplateArgumentListInfo &TemplateArgs);
2586 DependentFunctionTemplateSpecializationInfo *
2587 getDependentSpecializationInfo() const;
2589 /// Determine what kind of template instantiation this function
2591 TemplateSpecializationKind getTemplateSpecializationKind() const;
2593 /// Determine the kind of template specialization this function represents
2594 /// for the purpose of template instantiation.
2595 TemplateSpecializationKind
2596 getTemplateSpecializationKindForInstantiation() const;
2598 /// Determine what kind of template instantiation this function
2600 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2601 SourceLocation PointOfInstantiation = SourceLocation());
2603 /// Retrieve the (first) point of instantiation of a function template
2604 /// specialization or a member of a class template specialization.
2606 /// \returns the first point of instantiation, if this function was
2607 /// instantiated from a template; otherwise, returns an invalid source
2609 SourceLocation getPointOfInstantiation() const;
2611 /// Determine whether this is or was instantiated from an out-of-line
2612 /// definition of a member function.
2613 bool isOutOfLine() const override;
2615 /// Identify a memory copying or setting function.
2616 /// If the given function is a memory copy or setting function, returns
2617 /// the corresponding Builtin ID. If the function is not a memory function,
2619 unsigned getMemoryFunctionKind() const;
2621 /// Returns ODRHash of the function. This value is calculated and
2622 /// stored on first call, then the stored value returned on the other calls.
2623 unsigned getODRHash();
2625 /// Returns cached ODRHash of the function. This must have been previously
2626 /// computed and stored.
2627 unsigned getODRHash() const;
2629 // Implement isa/cast/dyncast/etc.
2630 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2631 static bool classofKind(Kind K) {
2632 return K >= firstFunction && K <= lastFunction;
2634 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2635 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2637 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2638 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2642 /// Represents a member of a struct/union/class.
2643 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2644 unsigned BitField : 1;
2645 unsigned Mutable : 1;
2646 mutable unsigned CachedFieldIndex : 30;
2648 /// The kinds of value we can store in InitializerOrBitWidth.
2650 /// Note that this is compatible with InClassInitStyle except for
2651 /// ISK_CapturedVLAType.
2652 enum InitStorageKind {
2653 /// If the pointer is null, there's nothing special. Otherwise,
2654 /// this is a bitfield and the pointer is the Expr* storing the
2656 ISK_NoInit = (unsigned) ICIS_NoInit,
2658 /// The pointer is an (optional due to delayed parsing) Expr*
2659 /// holding the copy-initializer.
2660 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2662 /// The pointer is an (optional due to delayed parsing) Expr*
2663 /// holding the list-initializer.
2664 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2666 /// The pointer is a VariableArrayType* that's been captured;
2667 /// the enclosing context is a lambda or captured statement.
2668 ISK_CapturedVLAType,
2671 /// If this is a bitfield with a default member initializer, this
2672 /// structure is used to represent the two expressions.
2673 struct InitAndBitWidth {
2678 /// Storage for either the bit-width, the in-class initializer, or
2679 /// both (via InitAndBitWidth), or the captured variable length array bound.
2681 /// If the storage kind is ISK_InClassCopyInit or
2682 /// ISK_InClassListInit, but the initializer is null, then this
2683 /// field has an in-class initializer that has not yet been parsed
2685 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2686 // overwhelmingly common case that we have none of these things.
2687 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2690 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2691 SourceLocation IdLoc, IdentifierInfo *Id,
2692 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2693 InClassInitStyle InitStyle)
2694 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2695 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2696 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2702 friend class ASTDeclReader;
2703 friend class ASTDeclWriter;
2705 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2706 SourceLocation StartLoc, SourceLocation IdLoc,
2707 IdentifierInfo *Id, QualType T,
2708 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2709 InClassInitStyle InitStyle);
2711 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2713 /// Returns the index of this field within its record,
2714 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2715 unsigned getFieldIndex() const;
2717 /// Determines whether this field is mutable (C++ only).
2718 bool isMutable() const { return Mutable; }
2720 /// Determines whether this field is a bitfield.
2721 bool isBitField() const { return BitField; }
2723 /// Determines whether this is an unnamed bitfield.
2724 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2726 /// Determines whether this field is a
2727 /// representative for an anonymous struct or union. Such fields are
2728 /// unnamed and are implicitly generated by the implementation to
2729 /// store the data for the anonymous union or struct.
2730 bool isAnonymousStructOrUnion() const;
2732 Expr *getBitWidth() const {
2735 void *Ptr = InitStorage.getPointer();
2736 if (getInClassInitStyle())
2737 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2738 return static_cast<Expr*>(Ptr);
2741 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2743 /// Set the bit-field width for this member.
2744 // Note: used by some clients (i.e., do not remove it).
2745 void setBitWidth(Expr *Width) {
2746 assert(!hasCapturedVLAType() && !BitField &&
2747 "bit width or captured type already set");
2748 assert(Width && "no bit width specified");
2749 InitStorage.setPointer(
2750 InitStorage.getInt()
2751 ? new (getASTContext())
2752 InitAndBitWidth{getInClassInitializer(), Width}
2753 : static_cast<void*>(Width));
2757 /// Remove the bit-field width from this member.
2758 // Note: used by some clients (i.e., do not remove it).
2759 void removeBitWidth() {
2760 assert(isBitField() && "no bitfield width to remove");
2761 InitStorage.setPointer(getInClassInitializer());
2765 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2766 /// at all and instead act as a separator between contiguous runs of other
2768 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2770 /// Determine if this field is a subobject of zero size, that is, either a
2771 /// zero-length bit-field or a field of empty class type with the
2772 /// [[no_unique_address]] attribute.
2773 bool isZeroSize(const ASTContext &Ctx) const;
2775 /// Get the kind of (C++11) default member initializer that this field has.
2776 InClassInitStyle getInClassInitStyle() const {
2777 InitStorageKind storageKind = InitStorage.getInt();
2778 return (storageKind == ISK_CapturedVLAType
2779 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2782 /// Determine whether this member has a C++11 default member initializer.
2783 bool hasInClassInitializer() const {
2784 return getInClassInitStyle() != ICIS_NoInit;
2787 /// Get the C++11 default member initializer for this member, or null if one
2788 /// has not been set. If a valid declaration has a default member initializer,
2789 /// but this returns null, then we have not parsed and attached it yet.
2790 Expr *getInClassInitializer() const {
2791 if (!hasInClassInitializer())
2793 void *Ptr = InitStorage.getPointer();
2795 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2796 return static_cast<Expr*>(Ptr);
2799 /// Set the C++11 in-class initializer for this member.
2800 void setInClassInitializer(Expr *Init) {
2801 assert(hasInClassInitializer() && !getInClassInitializer());
2803 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2805 InitStorage.setPointer(Init);
2808 /// Remove the C++11 in-class initializer from this member.
2809 void removeInClassInitializer() {
2810 assert(hasInClassInitializer() && "no initializer to remove");
2811 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2814 /// Determine whether this member captures the variable length array
2816 bool hasCapturedVLAType() const {
2817 return InitStorage.getInt() == ISK_CapturedVLAType;
2820 /// Get the captured variable length array type.
2821 const VariableArrayType *getCapturedVLAType() const {
2822 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2823 InitStorage.getPointer())
2827 /// Set the captured variable length array type for this field.
2828 void setCapturedVLAType(const VariableArrayType *VLAType);
2830 /// Returns the parent of this field declaration, which
2831 /// is the struct in which this field is defined.
2832 const RecordDecl *getParent() const {
2833 return cast<RecordDecl>(getDeclContext());
2836 RecordDecl *getParent() {
2837 return cast<RecordDecl>(getDeclContext());
2840 SourceRange getSourceRange() const override LLVM_READONLY;
2842 /// Retrieves the canonical declaration of this field.
2843 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2844 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2846 // Implement isa/cast/dyncast/etc.
2847 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2848 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2851 /// An instance of this object exists for each enum constant
2852 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2853 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2854 /// TagType for the X EnumDecl.
2855 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2856 Stmt *Init; // an integer constant expression
2857 llvm::APSInt Val; // The value.
2860 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2861 IdentifierInfo *Id, QualType T, Expr *E,
2862 const llvm::APSInt &V)
2863 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2866 friend class StmtIteratorBase;
2868 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2869 SourceLocation L, IdentifierInfo *Id,
2870 QualType T, Expr *E,
2871 const llvm::APSInt &V);
2872 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2874 const Expr *getInitExpr() const { return (const Expr*) Init; }
2875 Expr *getInitExpr() { return (Expr*) Init; }
2876 const llvm::APSInt &getInitVal() const { return Val; }
2878 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2879 void setInitVal(const llvm::APSInt &V) { Val = V; }
2881 SourceRange getSourceRange() const override LLVM_READONLY;
2883 /// Retrieves the canonical declaration of this enumerator.
2884 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2885 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2887 // Implement isa/cast/dyncast/etc.
2888 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2889 static bool classofKind(Kind K) { return K == EnumConstant; }
2892 /// Represents a field injected from an anonymous union/struct into the parent
2893 /// scope. These are always implicit.
2894 class IndirectFieldDecl : public ValueDecl,
2895 public Mergeable<IndirectFieldDecl> {
2896 NamedDecl **Chaining;
2897 unsigned ChainingSize;
2899 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2900 DeclarationName N, QualType T,
2901 MutableArrayRef<NamedDecl *> CH);
2903 void anchor() override;
2906 friend class ASTDeclReader;
2908 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2909 SourceLocation L, IdentifierInfo *Id,
2910 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2912 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2914 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2916 ArrayRef<NamedDecl *> chain() const {
2917 return llvm::makeArrayRef(Chaining, ChainingSize);
2919 chain_iterator chain_begin() const { return chain().begin(); }
2920 chain_iterator chain_end() const { return chain().end(); }
2922 unsigned getChainingSize() const { return ChainingSize; }
2924 FieldDecl *getAnonField() const {
2925 assert(chain().size() >= 2);
2926 return cast<FieldDecl>(chain().back());
2929 VarDecl *getVarDecl() const {
2930 assert(chain().size() >= 2);
2931 return dyn_cast<VarDecl>(chain().front());
2934 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2935 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2937 // Implement isa/cast/dyncast/etc.
2938 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2939 static bool classofKind(Kind K) { return K == IndirectField; }
2942 /// Represents a declaration of a type.
2943 class TypeDecl : public NamedDecl {
2944 friend class ASTContext;
2946 /// This indicates the Type object that represents
2947 /// this TypeDecl. It is a cache maintained by
2948 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2949 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2950 mutable const Type *TypeForDecl = nullptr;
2952 /// The start of the source range for this declaration.
2953 SourceLocation LocStart;
2955 void anchor() override;
2958 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2959 SourceLocation StartL = SourceLocation())
2960 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2963 // Low-level accessor. If you just want the type defined by this node,
2964 // check out ASTContext::getTypeDeclType or one of
2965 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2966 // already know the specific kind of node this is.
2967 const Type *getTypeForDecl() const { return TypeForDecl; }
2968 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2970 SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
2971 void setLocStart(SourceLocation L) { LocStart = L; }
2972 SourceRange getSourceRange() const override LLVM_READONLY {
2973 if (LocStart.isValid())
2974 return SourceRange(LocStart, getLocation());
2976 return SourceRange(getLocation());
2979 // Implement isa/cast/dyncast/etc.
2980 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2981 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2984 /// Base class for declarations which introduce a typedef-name.
2985 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2986 struct alignas(8) ModedTInfo {
2987 TypeSourceInfo *first;
2991 /// If int part is 0, we have not computed IsTransparentTag.
2992 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2993 mutable llvm::PointerIntPair<
2994 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2997 void anchor() override;
3000 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
3001 SourceLocation StartLoc, SourceLocation IdLoc,
3002 IdentifierInfo *Id, TypeSourceInfo *TInfo)
3003 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3004 MaybeModedTInfo(TInfo, 0) {}
3006 using redeclarable_base = Redeclarable<TypedefNameDecl>;
3008 TypedefNameDecl *getNextRedeclarationImpl() override {
3009 return getNextRedeclaration();
3012 TypedefNameDecl *getPreviousDeclImpl() override {
3013 return getPreviousDecl();
3016 TypedefNameDecl *getMostRecentDeclImpl() override {
3017 return getMostRecentDecl();
3021 using redecl_range = redeclarable_base::redecl_range;
3022 using redecl_iterator = redeclarable_base::redecl_iterator;
3024 using redeclarable_base::redecls_begin;
3025 using redeclarable_base::redecls_end;
3026 using redeclarable_base::redecls;
3027 using redeclarable_base::getPreviousDecl;
3028 using redeclarable_base::getMostRecentDecl;
3029 using redeclarable_base::isFirstDecl;
3031 bool isModed() const {
3032 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3035 TypeSourceInfo *getTypeSourceInfo() const {
3036 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3037 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3040 QualType getUnderlyingType() const {
3041 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3042 : MaybeModedTInfo.getPointer()
3043 .get<TypeSourceInfo *>()
3047 void setTypeSourceInfo(TypeSourceInfo *newType) {
3048 MaybeModedTInfo.setPointer(newType);
3051 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
3052 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3053 ModedTInfo({unmodedTSI, modedTy}));
3056 /// Retrieves the canonical declaration of this typedef-name.
3057 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
3058 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3060 /// Retrieves the tag declaration for which this is the typedef name for
3061 /// linkage purposes, if any.
3063 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3064 /// this typedef declaration.
3065 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3067 /// Determines if this typedef shares a name and spelling location with its
3068 /// underlying tag type, as is the case with the NS_ENUM macro.
3069 bool isTransparentTag() const {
3070 if (MaybeModedTInfo.getInt())
3071 return MaybeModedTInfo.getInt() & 0x2;
3072 return isTransparentTagSlow();
3075 // Implement isa/cast/dyncast/etc.
3076 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3077 static bool classofKind(Kind K) {
3078 return K >= firstTypedefName && K <= lastTypedefName;
3082 bool isTransparentTagSlow() const;
3085 /// Represents the declaration of a typedef-name via the 'typedef'
3087 class TypedefDecl : public TypedefNameDecl {
3088 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3089 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3090 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3093 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3094 SourceLocation StartLoc, SourceLocation IdLoc,
3095 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3096 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3098 SourceRange getSourceRange() const override LLVM_READONLY;
3100 // Implement isa/cast/dyncast/etc.
3101 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3102 static bool classofKind(Kind K) { return K == Typedef; }
3105 /// Represents the declaration of a typedef-name via a C++11
3106 /// alias-declaration.
3107 class TypeAliasDecl : public TypedefNameDecl {
3108 /// The template for which this is the pattern, if any.
3109 TypeAliasTemplateDecl *Template;
3111 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3112 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3113 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3114 Template(nullptr) {}
3117 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3118 SourceLocation StartLoc, SourceLocation IdLoc,
3119 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3120 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3122 SourceRange getSourceRange() const override LLVM_READONLY;
3124 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3125 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3127 // Implement isa/cast/dyncast/etc.
3128 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3129 static bool classofKind(Kind K) { return K == TypeAlias; }
3132 /// Represents the declaration of a struct/union/class/enum.
3133 class TagDecl : public TypeDecl,
3135 public Redeclarable<TagDecl> {
3136 // This class stores some data in DeclContext::TagDeclBits
3137 // to save some space. Use the provided accessors to access it.
3139 // This is really ugly.
3140 using TagKind = TagTypeKind;
3143 SourceRange BraceRange;
3145 // A struct representing syntactic qualifier info,
3146 // to be used for the (uncommon) case of out-of-line declarations.
3147 using ExtInfo = QualifierInfo;
3149 /// If the (out-of-line) tag declaration name
3150 /// is qualified, it points to the qualifier info (nns and range);
3151 /// otherwise, if the tag declaration is anonymous and it is part of
3152 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3153 /// otherwise, if the tag declaration is anonymous and it is used as a
3154 /// declaration specifier for variables, it points to the first VarDecl (used
3156 /// otherwise, it is a null (TypedefNameDecl) pointer.
3157 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3159 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3160 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3161 const ExtInfo *getExtInfo() const {
3162 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3166 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3167 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3168 SourceLocation StartL);
3170 using redeclarable_base = Redeclarable<TagDecl>;
3172 TagDecl *getNextRedeclarationImpl() override {
3173 return getNextRedeclaration();
3176 TagDecl *getPreviousDeclImpl() override {
3177 return getPreviousDecl();
3180 TagDecl *getMostRecentDeclImpl() override {
3181 return getMostRecentDecl();
3184 /// Completes the definition of this tag declaration.
3186 /// This is a helper function for derived classes.
3187 void completeDefinition();
3189 /// True if this decl is currently being defined.
3190 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3192 /// Indicates whether it is possible for declarations of this kind
3193 /// to have an out-of-date definition.
3195 /// This option is only enabled when modules are enabled.
3196 void setMayHaveOutOfDateDef(bool V = true) {
3197 TagDeclBits.MayHaveOutOfDateDef = V;
3201 friend class ASTDeclReader;
3202 friend class ASTDeclWriter;
3204 using redecl_range = redeclarable_base::redecl_range;
3205 using redecl_iterator = redeclarable_base::redecl_iterator;
3207 using redeclarable_base::redecls_begin;
3208 using redeclarable_base::redecls_end;
3209 using redeclarable_base::redecls;
3210 using redeclarable_base::getPreviousDecl;
3211 using redeclarable_base::getMostRecentDecl;
3212 using redeclarable_base::isFirstDecl;
3214 SourceRange getBraceRange() const { return BraceRange; }
3215 void setBraceRange(SourceRange R) { BraceRange = R; }
3217 /// Return SourceLocation representing start of source
3218 /// range ignoring outer template declarations.
3219 SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3221 /// Return SourceLocation representing start of source
3222 /// range taking into account any outer template declarations.
3223 SourceLocation getOuterLocStart() const;
3224 SourceRange getSourceRange() const override LLVM_READONLY;
3226 TagDecl *getCanonicalDecl() override;
3227 const TagDecl *getCanonicalDecl() const {
3228 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3231 /// Return true if this declaration is a completion definition of the type.
3232 /// Provided for consistency.
3233 bool isThisDeclarationADefinition() const {
3234 return isCompleteDefinition();
3237 /// Return true if this decl has its body fully specified.
3238 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3240 /// True if this decl has its body fully specified.
3241 void setCompleteDefinition(bool V = true) {
3242 TagDeclBits.IsCompleteDefinition = V;
3245 /// Return true if this complete decl is
3246 /// required to be complete for some existing use.
3247 bool isCompleteDefinitionRequired() const {
3248 return TagDeclBits.IsCompleteDefinitionRequired;
3251 /// True if this complete decl is
3252 /// required to be complete for some existing use.
3253 void setCompleteDefinitionRequired(bool V = true) {
3254 TagDeclBits.IsCompleteDefinitionRequired = V;
3257 /// Return true if this decl is currently being defined.
3258 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3260 /// True if this tag declaration is "embedded" (i.e., defined or declared
3261 /// for the very first time) in the syntax of a declarator.
3262 bool isEmbeddedInDeclarator() const {
3263 return TagDeclBits.IsEmbeddedInDeclarator;
3266 /// True if this tag declaration is "embedded" (i.e., defined or declared
3267 /// for the very first time) in the syntax of a declarator.
3268 void setEmbeddedInDeclarator(bool isInDeclarator) {
3269 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3272 /// True if this tag is free standing, e.g. "struct foo;".
3273 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3275 /// True if this tag is free standing, e.g. "struct foo;".
3276 void setFreeStanding(bool isFreeStanding = true) {
3277 TagDeclBits.IsFreeStanding = isFreeStanding;
3280 /// Indicates whether it is possible for declarations of this kind
3281 /// to have an out-of-date definition.
3283 /// This option is only enabled when modules are enabled.
3284 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3286 /// Whether this declaration declares a type that is
3287 /// dependent, i.e., a type that somehow depends on template
3289 bool isDependentType() const { return isDependentContext(); }
3291 /// Starts the definition of this tag declaration.
3293 /// This method should be invoked at the beginning of the definition
3294 /// of this tag declaration. It will set the tag type into a state
3295 /// where it is in the process of being defined.
3296 void startDefinition();
3298 /// Returns the TagDecl that actually defines this
3299 /// struct/union/class/enum. When determining whether or not a
3300 /// struct/union/class/enum has a definition, one should use this
3301 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3302 /// whether or not a specific TagDecl is defining declaration, not
3303 /// whether or not the struct/union/class/enum type is defined.
3304 /// This method returns NULL if there is no TagDecl that defines
3305 /// the struct/union/class/enum.
3306 TagDecl *getDefinition() const;
3308 StringRef getKindName() const {
3309 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3312 TagKind getTagKind() const {
3313 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3316 void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3318 bool isStruct() const { return getTagKind() == TTK_Struct; }
3319 bool isInterface() const { return getTagKind() == TTK_Interface; }
3320 bool isClass() const { return getTagKind() == TTK_Class; }
3321 bool isUnion() const { return getTagKind() == TTK_Union; }
3322 bool isEnum() const { return getTagKind() == TTK_Enum; }
3324 /// Is this tag type named, either directly or via being defined in
3325 /// a typedef of this type?
3327 /// C++11 [basic.link]p8:
3328 /// A type is said to have linkage if and only if:
3329 /// - it is a class or enumeration type that is named (or has a
3330 /// name for linkage purposes) and the name has linkage; ...
3331 /// C++11 [dcl.typedef]p9:
3332 /// If the typedef declaration defines an unnamed class (or enum),
3333 /// the first typedef-name declared by the declaration to be that
3334 /// class type (or enum type) is used to denote the class type (or
3335 /// enum type) for linkage purposes only.
3337 /// C does not have an analogous rule, but the same concept is
3338 /// nonetheless useful in some places.
3339 bool hasNameForLinkage() const {
3340 return (getDeclName() || getTypedefNameForAnonDecl());
3343 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3344 return hasExtInfo() ? nullptr
3345 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3348 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3350 /// Retrieve the nested-name-specifier that qualifies the name of this
3351 /// declaration, if it was present in the source.
3352 NestedNameSpecifier *getQualifier() const {
3353 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3357 /// Retrieve the nested-name-specifier (with source-location
3358 /// information) that qualifies the name of this declaration, if it was
3359 /// present in the source.
3360 NestedNameSpecifierLoc getQualifierLoc() const {
3361 return hasExtInfo() ? getExtInfo()->QualifierLoc
3362 : NestedNameSpecifierLoc();
3365 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3367 unsigned getNumTemplateParameterLists() const {
3368 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3371 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3372 assert(i < getNumTemplateParameterLists());
3373 return getExtInfo()->TemplParamLists[i];
3376 void setTemplateParameterListsInfo(ASTContext &Context,
3377 ArrayRef<TemplateParameterList *> TPLists);
3379 // Implement isa/cast/dyncast/etc.
3380 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3381 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3383 static DeclContext *castToDeclContext(const TagDecl *D) {
3384 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3387 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3388 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3392 /// Represents an enum. In C++11, enums can be forward-declared
3393 /// with a fixed underlying type, and in C we allow them to be forward-declared
3394 /// with no underlying type as an extension.
3395 class EnumDecl : public TagDecl {
3396 // This class stores some data in DeclContext::EnumDeclBits
3397 // to save some space. Use the provided accessors to access it.
3399 /// This represent the integer type that the enum corresponds
3400 /// to for code generation purposes. Note that the enumerator constants may
3401 /// have a different type than this does.
3403 /// If the underlying integer type was explicitly stated in the source
3404 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3405 /// was automatically deduced somehow, and this is a Type*.
3407 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3408 /// some cases it won't.
3410 /// The underlying type of an enumeration never has any qualifiers, so
3411 /// we can get away with just storing a raw Type*, and thus save an
3412 /// extra pointer when TypeSourceInfo is needed.
3413 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3415 /// The integer type that values of this type should
3416 /// promote to. In C, enumerators are generally of an integer type
3417 /// directly, but gcc-style large enumerators (and all enumerators
3418 /// in C++) are of the enum type instead.
3419 QualType PromotionType;
3421 /// If this enumeration is an instantiation of a member enumeration
3422 /// of a class template specialization, this is the member specialization
3424 MemberSpecializationInfo *SpecializationInfo = nullptr;
3426 /// Store the ODRHash after first calculation.
3427 /// The corresponding flag HasODRHash is in EnumDeclBits
3428 /// and can be accessed with the provided accessors.
3431 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3432 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3433 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3435 void anchor() override;
3437 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3438 TemplateSpecializationKind TSK);
3440 /// Sets the width in bits required to store all the
3441 /// non-negative enumerators of this enum.
3442 void setNumPositiveBits(unsigned Num) {
3443 EnumDeclBits.NumPositiveBits = Num;
3444 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount");
3447 /// Returns the width in bits required to store all the
3448 /// negative enumerators of this enum. (see getNumNegativeBits)
3449 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3451 /// True if this tag declaration is a scoped enumeration. Only
3452 /// possible in C++11 mode.
3453 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3455 /// If this tag declaration is a scoped enum,
3456 /// then this is true if the scoped enum was declared using the class
3457 /// tag, false if it was declared with the struct tag. No meaning is
3458 /// associated if this tag declaration is not a scoped enum.
3459 void setScopedUsingClassTag(bool ScopedUCT = true) {
3460 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3463 /// True if this is an Objective-C, C++11, or
3464 /// Microsoft-style enumeration with a fixed underlying type.
3465 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3467 /// True if a valid hash is stored in ODRHash.
3468 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3469 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3472 friend class ASTDeclReader;
3474 EnumDecl *getCanonicalDecl() override {
3475 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3477 const EnumDecl *getCanonicalDecl() const {
3478 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3481 EnumDecl *getPreviousDecl() {
3482 return cast_or_null<EnumDecl>(
3483 static_cast<TagDecl *>(this)->getPreviousDecl());
3485 const EnumDecl *getPreviousDecl() const {
3486 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3489 EnumDecl *getMostRecentDecl() {
3490 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3492 const EnumDecl *getMostRecentDecl() const {
3493 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3496 EnumDecl *getDefinition() const {
3497 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3500 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3501 SourceLocation StartLoc, SourceLocation IdLoc,
3502 IdentifierInfo *Id, EnumDecl *PrevDecl,
3503 bool IsScoped, bool IsScopedUsingClassTag,
3505 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3507 /// When created, the EnumDecl corresponds to a
3508 /// forward-declared enum. This method is used to mark the
3509 /// declaration as being defined; its enumerators have already been
3510 /// added (via DeclContext::addDecl). NewType is the new underlying
3511 /// type of the enumeration type.
3512 void completeDefinition(QualType NewType,
3513 QualType PromotionType,
3514 unsigned NumPositiveBits,
3515 unsigned NumNegativeBits);
3517 // Iterates through the enumerators of this enumeration.
3518 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3519 using enumerator_range =
3520 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3522 enumerator_range enumerators() const {
3523 return enumerator_range(enumerator_begin(), enumerator_end());
3526 enumerator_iterator enumerator_begin() const {
3527 const EnumDecl *E = getDefinition();
3530 return enumerator_iterator(E->decls_begin());
3533 enumerator_iterator enumerator_end() const {
3534 const EnumDecl *E = getDefinition();
3537 return enumerator_iterator(E->decls_end());
3540 /// Return the integer type that enumerators should promote to.
3541 QualType getPromotionType() const { return PromotionType; }
3543 /// Set the promotion type.
3544 void setPromotionType(QualType T) { PromotionType = T; }
3546 /// Return the integer type this enum decl corresponds to.
3547 /// This returns a null QualType for an enum forward definition with no fixed
3548 /// underlying type.
3549 QualType getIntegerType() const {
3552 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3553 return QualType(T, 0);
3554 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3557 /// Set the underlying integer type.
3558 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3560 /// Set the underlying integer type source info.
3561 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3563 /// Return the type source info for the underlying integer type,
3564 /// if no type source info exists, return 0.
3565 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3566 return IntegerType.dyn_cast<TypeSourceInfo*>();
3569 /// Retrieve the source range that covers the underlying type if
3571 SourceRange getIntegerTypeRange() const LLVM_READONLY;
3573 /// Returns the width in bits required to store all the
3574 /// non-negative enumerators of this enum.
3575 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3577 /// Returns the width in bits required to store all the
3578 /// negative enumerators of this enum. These widths include
3579 /// the rightmost leading 1; that is:
3581 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3582 /// ------------------------ ------- -----------------
3586 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3588 /// Returns true if this is a C++11 scoped enumeration.
3589 bool isScoped() const { return EnumDeclBits.IsScoped; }
3591 /// Returns true if this is a C++11 scoped enumeration.
3592 bool isScopedUsingClassTag() const {
3593 return EnumDeclBits.IsScopedUsingClassTag;
3596 /// Returns true if this is an Objective-C, C++11, or
3597 /// Microsoft-style enumeration with a fixed underlying type.
3598 bool isFixed() const { return EnumDeclBits.IsFixed; }
3600 unsigned getODRHash();
3602 /// Returns true if this can be considered a complete type.
3603 bool isComplete() const {
3604 // IntegerType is set for fixed type enums and non-fixed but implicitly
3605 // int-sized Microsoft enums.
3606 return isCompleteDefinition() || IntegerType;
3609 /// Returns true if this enum is either annotated with
3610 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3611 bool isClosed() const;
3613 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3614 /// with enum_extensibility(open).
3615 bool isClosedFlag() const;
3617 /// Returns true if this enum is annotated with neither flag_enum nor
3618 /// enum_extensibility(open).
3619 bool isClosedNonFlag() const;
3621 /// Retrieve the enum definition from which this enumeration could
3622 /// be instantiated, if it is an instantiation (rather than a non-template).
3623 EnumDecl *getTemplateInstantiationPattern() const;
3625 /// Returns the enumeration (declared within the template)
3626 /// from which this enumeration type was instantiated, or NULL if
3627 /// this enumeration was not instantiated from any template.
3628 EnumDecl *getInstantiatedFromMemberEnum() const;
3630 /// If this enumeration is a member of a specialization of a
3631 /// templated class, determine what kind of template specialization
3632 /// or instantiation this is.
3633 TemplateSpecializationKind getTemplateSpecializationKind() const;
3635 /// For an enumeration member that was instantiated from a member
3636 /// enumeration of a templated class, set the template specialiation kind.
3637 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3638 SourceLocation PointOfInstantiation = SourceLocation());
3640 /// If this enumeration is an instantiation of a member enumeration of
3641 /// a class template specialization, retrieves the member specialization
3643 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3644 return SpecializationInfo;
3647 /// Specify that this enumeration is an instantiation of the
3648 /// member enumeration ED.
3649 void setInstantiationOfMemberEnum(EnumDecl *ED,
3650 TemplateSpecializationKind TSK) {
3651 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3654 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3655 static bool classofKind(Kind K) { return K == Enum; }
3658 /// Represents a struct/union/class. For example:
3659 /// struct X; // Forward declaration, no "body".
3660 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3661 /// This decl will be marked invalid if *any* members are invalid.
3662 class RecordDecl : public TagDecl {
3663 // This class stores some data in DeclContext::RecordDeclBits
3664 // to save some space. Use the provided accessors to access it.
3666 friend class DeclContext;
3667 /// Enum that represents the different ways arguments are passed to and
3668 /// returned from function calls. This takes into account the target-specific
3669 /// and version-specific rules along with the rules determined by the
3671 enum ArgPassingKind : unsigned {
3672 /// The argument of this type can be passed directly in registers.
3675 /// The argument of this type cannot be passed directly in registers.
3676 /// Records containing this type as a subobject are not forced to be passed
3677 /// indirectly. This value is used only in C++. This value is required by
3678 /// C++ because, in uncommon situations, it is possible for a class to have
3679 /// only trivial copy/move constructors even when one of its subobjects has
3680 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3681 /// constructor in the derived class is deleted).
3682 APK_CannotPassInRegs,
3684 /// The argument of this type cannot be passed directly in registers.
3685 /// Records containing this type as a subobject are forced to be passed
3687 APK_CanNeverPassInRegs
3691 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3692 SourceLocation StartLoc, SourceLocation IdLoc,
3693 IdentifierInfo *Id, RecordDecl *PrevDecl);
3696 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3697 SourceLocation StartLoc, SourceLocation IdLoc,
3698 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3699 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3701 RecordDecl *getPreviousDecl() {
3702 return cast_or_null<RecordDecl>(
3703 static_cast<TagDecl *>(this)->getPreviousDecl());
3705 const RecordDecl *getPreviousDecl() const {
3706 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3709 RecordDecl *getMostRecentDecl() {
3710 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3712 const RecordDecl *getMostRecentDecl() const {
3713 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3716 bool hasFlexibleArrayMember() const {
3717 return RecordDeclBits.HasFlexibleArrayMember;
3720 void setHasFlexibleArrayMember(bool V) {
3721 RecordDeclBits.HasFlexibleArrayMember = V;
3724 /// Whether this is an anonymous struct or union. To be an anonymous
3725 /// struct or union, it must have been declared without a name and
3726 /// there must be no objects of this type declared, e.g.,
3728 /// union { int i; float f; };
3730 /// is an anonymous union but neither of the following are:
3732 /// union X { int i; float f; };
3733 /// union { int i; float f; } obj;
3735 bool isAnonymousStructOrUnion() const {
3736 return RecordDeclBits.AnonymousStructOrUnion;
3739 void setAnonymousStructOrUnion(bool Anon) {
3740 RecordDeclBits.AnonymousStructOrUnion = Anon;
3743 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3744 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3746 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3748 void setHasVolatileMember(bool val) {
3749 RecordDeclBits.HasVolatileMember = val;
3752 bool hasLoadedFieldsFromExternalStorage() const {
3753 return RecordDeclBits.LoadedFieldsFromExternalStorage;
3756 void setHasLoadedFieldsFromExternalStorage(bool val) const {
3757 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3760 /// Functions to query basic properties of non-trivial C structs.
3761 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3762 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3765 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3766 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3769 bool isNonTrivialToPrimitiveCopy() const {
3770 return RecordDeclBits.NonTrivialToPrimitiveCopy;
3773 void setNonTrivialToPrimitiveCopy(bool V) {
3774 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3777 bool isNonTrivialToPrimitiveDestroy() const {
3778 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3781 void setNonTrivialToPrimitiveDestroy(bool V) {
3782 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3785 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
3786 return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
3789 void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
3790 RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
3793 bool hasNonTrivialToPrimitiveDestructCUnion() const {
3794 return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
3797 void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
3798 RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
3801 bool hasNonTrivialToPrimitiveCopyCUnion() const {
3802 return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
3805 void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
3806 RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
3809 /// Determine whether this class can be passed in registers. In C++ mode,
3810 /// it must have at least one trivial, non-deleted copy or move constructor.
3811 /// FIXME: This should be set as part of completeDefinition.
3812 bool canPassInRegisters() const {
3813 return getArgPassingRestrictions() == APK_CanPassInRegs;
3816 ArgPassingKind getArgPassingRestrictions() const {
3817 return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3820 void setArgPassingRestrictions(ArgPassingKind Kind) {
3821 RecordDeclBits.ArgPassingRestrictions = Kind;
3824 bool isParamDestroyedInCallee() const {
3825 return RecordDeclBits.ParamDestroyedInCallee;
3828 void setParamDestroyedInCallee(bool V) {
3829 RecordDeclBits.ParamDestroyedInCallee = V;
3832 /// Determines whether this declaration represents the
3833 /// injected class name.
3835 /// The injected class name in C++ is the name of the class that
3836 /// appears inside the class itself. For example:
3840 /// // C is implicitly declared here as a synonym for the class name.
3843 /// C::C c; // same as "C c;"
3845 bool isInjectedClassName() const;
3847 /// Determine whether this record is a class describing a lambda
3848 /// function object.
3849 bool isLambda() const;
3851 /// Determine whether this record is a record for captured variables in
3852 /// CapturedStmt construct.
3853 bool isCapturedRecord() const;
3855 /// Mark the record as a record for captured variables in CapturedStmt
3857 void setCapturedRecord();
3859 /// Returns the RecordDecl that actually defines
3860 /// this struct/union/class. When determining whether or not a
3861 /// struct/union/class is completely defined, one should use this
3862 /// method as opposed to 'isCompleteDefinition'.
3863 /// 'isCompleteDefinition' indicates whether or not a specific
3864 /// RecordDecl is a completed definition, not whether or not the
3865 /// record type is defined. This method returns NULL if there is
3866 /// no RecordDecl that defines the struct/union/tag.
3867 RecordDecl *getDefinition() const {
3868 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3871 // Iterator access to field members. The field iterator only visits
3872 // the non-static data members of this class, ignoring any static
3873 // data members, functions, constructors, destructors, etc.
3874 using field_iterator = specific_decl_iterator<FieldDecl>;
3875 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3877 field_range fields() const { return field_range(field_begin(), field_end()); }
3878 field_iterator field_begin() const;
3880 field_iterator field_end() const {
3881 return field_iterator(decl_iterator());
3884 // Whether there are any fields (non-static data members) in this record.
3885 bool field_empty() const {
3886 return field_begin() == field_end();
3889 /// Note that the definition of this type is now complete.
3890 virtual void completeDefinition();
3892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3893 static bool classofKind(Kind K) {
3894 return K >= firstRecord && K <= lastRecord;
3897 /// Get whether or not this is an ms_struct which can
3898 /// be turned on with an attribute, pragma, or -mms-bitfields
3899 /// commandline option.
3900 bool isMsStruct(const ASTContext &C) const;
3902 /// Whether we are allowed to insert extra padding between fields.
3903 /// These padding are added to help AddressSanitizer detect
3904 /// intra-object-overflow bugs.
3905 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3907 /// Finds the first data member which has a name.
3908 /// nullptr is returned if no named data member exists.
3909 const FieldDecl *findFirstNamedDataMember() const;
3912 /// Deserialize just the fields.
3913 void LoadFieldsFromExternalStorage() const;
3916 class FileScopeAsmDecl : public Decl {
3917 StringLiteral *AsmString;
3918 SourceLocation RParenLoc;
3920 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3921 SourceLocation StartL, SourceLocation EndL)
3922 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3924 virtual void anchor();
3927 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3928 StringLiteral *Str, SourceLocation AsmLoc,
3929 SourceLocation RParenLoc);
3931 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3933 SourceLocation getAsmLoc() const { return getLocation(); }
3934 SourceLocation getRParenLoc() const { return RParenLoc; }
3935 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3936 SourceRange getSourceRange() const override LLVM_READONLY {
3937 return SourceRange(getAsmLoc(), getRParenLoc());
3940 const StringLiteral *getAsmString() const { return AsmString; }
3941 StringLiteral *getAsmString() { return AsmString; }
3942 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3944 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3945 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3948 /// Represents a block literal declaration, which is like an
3949 /// unnamed FunctionDecl. For example:
3950 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3951 class BlockDecl : public Decl, public DeclContext {
3952 // This class stores some data in DeclContext::BlockDeclBits
3953 // to save some space. Use the provided accessors to access it.
3955 /// A class which contains all the information about a particular
3963 /// The variable being captured.
3964 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3966 /// The copy expression, expressed in terms of a DeclRef (or
3967 /// BlockDeclRef) to the captured variable. Only required if the
3968 /// variable has a C++ class type.
3972 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3973 : VariableAndFlags(variable,
3974 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3977 /// The variable being captured.
3978 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3980 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3982 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3984 bool isEscapingByref() const {
3985 return getVariable()->isEscapingByref();
3988 bool isNonEscapingByref() const {
3989 return getVariable()->isNonEscapingByref();
3992 /// Whether this is a nested capture, i.e. the variable captured
3993 /// is not from outside the immediately enclosing function/block.
3994 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3996 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3997 Expr *getCopyExpr() const { return CopyExpr; }
3998 void setCopyExpr(Expr *e) { CopyExpr = e; }
4002 /// A new[]'d array of pointers to ParmVarDecls for the formal
4003 /// parameters of this function. This is null if a prototype or if there are
4005 ParmVarDecl **ParamInfo = nullptr;
4006 unsigned NumParams = 0;
4008 Stmt *Body = nullptr;
4009 TypeSourceInfo *SignatureAsWritten = nullptr;
4011 const Capture *Captures = nullptr;
4012 unsigned NumCaptures = 0;
4014 unsigned ManglingNumber = 0;
4015 Decl *ManglingContextDecl = nullptr;
4018 BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
4021 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
4022 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4024 SourceLocation getCaretLocation() const { return getLocation(); }
4026 bool isVariadic() const { return BlockDeclBits.IsVariadic; }
4027 void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
4029 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
4030 Stmt *getBody() const override { return (Stmt*) Body; }
4031 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
4033 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
4034 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
4036 // ArrayRef access to formal parameters.
4037 ArrayRef<ParmVarDecl *> parameters() const {
4038 return {ParamInfo, getNumParams()};
4040 MutableArrayRef<ParmVarDecl *> parameters() {
4041 return {ParamInfo, getNumParams()};
4044 // Iterator access to formal parameters.
4045 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
4046 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
4048 bool param_empty() const { return parameters().empty(); }
4049 param_iterator param_begin() { return parameters().begin(); }
4050 param_iterator param_end() { return parameters().end(); }
4051 param_const_iterator param_begin() const { return parameters().begin(); }
4052 param_const_iterator param_end() const { return parameters().end(); }
4053 size_t param_size() const { return parameters().size(); }
4055 unsigned getNumParams() const { return NumParams; }
4057 const ParmVarDecl *getParamDecl(unsigned i) const {
4058 assert(i < getNumParams() && "Illegal param #");
4059 return ParamInfo[i];
4061 ParmVarDecl *getParamDecl(unsigned i) {
4062 assert(i < getNumParams() && "Illegal param #");
4063 return ParamInfo[i];
4066 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
4068 /// True if this block (or its nested blocks) captures
4069 /// anything of local storage from its enclosing scopes.
4070 bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
4072 /// Returns the number of captured variables.
4073 /// Does not include an entry for 'this'.
4074 unsigned getNumCaptures() const { return NumCaptures; }
4076 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
4078 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
4080 capture_const_iterator capture_begin() const { return captures().begin(); }
4081 capture_const_iterator capture_end() const { return captures().end(); }
4083 bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4084 void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4086 bool blockMissingReturnType() const {
4087 return BlockDeclBits.BlockMissingReturnType;
4090 void setBlockMissingReturnType(bool val = true) {
4091 BlockDeclBits.BlockMissingReturnType = val;
4094 bool isConversionFromLambda() const {
4095 return BlockDeclBits.IsConversionFromLambda;
4098 void setIsConversionFromLambda(bool val = true) {
4099 BlockDeclBits.IsConversionFromLambda = val;
4102 bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4103 void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4105 bool canAvoidCopyToHeap() const {
4106 return BlockDeclBits.CanAvoidCopyToHeap;
4108 void setCanAvoidCopyToHeap(bool B = true) {
4109 BlockDeclBits.CanAvoidCopyToHeap = B;
4112 bool capturesVariable(const VarDecl *var) const;
4114 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4115 bool CapturesCXXThis);
4117 unsigned getBlockManglingNumber() const { return ManglingNumber; }
4119 Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
4121 void setBlockMangling(unsigned Number, Decl *Ctx) {
4122 ManglingNumber = Number;
4123 ManglingContextDecl = Ctx;
4126 SourceRange getSourceRange() const override LLVM_READONLY;
4128 // Implement isa/cast/dyncast/etc.
4129 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4130 static bool classofKind(Kind K) { return K == Block; }
4131 static DeclContext *castToDeclContext(const BlockDecl *D) {
4132 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4134 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4135 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4139 /// Represents the body of a CapturedStmt, and serves as its DeclContext.
4140 class CapturedDecl final
4143 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4145 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4150 /// The number of parameters to the outlined function.
4153 /// The position of context parameter in list of parameters.
4154 unsigned ContextParam;
4156 /// The body of the outlined function.
4157 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4159 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4161 ImplicitParamDecl *const *getParams() const {
4162 return getTrailingObjects<ImplicitParamDecl *>();
4165 ImplicitParamDecl **getParams() {
4166 return getTrailingObjects<ImplicitParamDecl *>();
4170 friend class ASTDeclReader;
4171 friend class ASTDeclWriter;
4172 friend TrailingObjects;
4174 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4175 unsigned NumParams);
4176 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4177 unsigned NumParams);
4179 Stmt *getBody() const override;
4180 void setBody(Stmt *B);
4182 bool isNothrow() const;
4183 void setNothrow(bool Nothrow = true);
4185 unsigned getNumParams() const { return NumParams; }
4187 ImplicitParamDecl *getParam(unsigned i) const {
4188 assert(i < NumParams);
4189 return getParams()[i];
4191 void setParam(unsigned i, ImplicitParamDecl *P) {
4192 assert(i < NumParams);
4196 // ArrayRef interface to parameters.
4197 ArrayRef<ImplicitParamDecl *> parameters() const {
4198 return {getParams(), getNumParams()};
4200 MutableArrayRef<ImplicitParamDecl *> parameters() {
4201 return {getParams(), getNumParams()};
4204 /// Retrieve the parameter containing captured variables.
4205 ImplicitParamDecl *getContextParam() const {
4206 assert(ContextParam < NumParams);
4207 return getParam(ContextParam);
4209 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4210 assert(i < NumParams);
4214 unsigned getContextParamPosition() const { return ContextParam; }
4216 using param_iterator = ImplicitParamDecl *const *;
4217 using param_range = llvm::iterator_range<param_iterator>;
4219 /// Retrieve an iterator pointing to the first parameter decl.
4220 param_iterator param_begin() const { return getParams(); }
4221 /// Retrieve an iterator one past the last parameter decl.
4222 param_iterator param_end() const { return getParams() + NumParams; }
4224 // Implement isa/cast/dyncast/etc.
4225 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4226 static bool classofKind(Kind K) { return K == Captured; }
4227 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4228 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4230 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4231 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4235 /// Describes a module import declaration, which makes the contents
4236 /// of the named module visible in the current translation unit.
4238 /// An import declaration imports the named module (or submodule). For example:
4240 /// @import std.vector;
4243 /// Import declarations can also be implicitly generated from
4244 /// \#include/\#import directives.
4245 class ImportDecl final : public Decl,
4246 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4247 friend class ASTContext;
4248 friend class ASTDeclReader;
4249 friend class ASTReader;
4250 friend TrailingObjects;
4252 /// The imported module, along with a bit that indicates whether
4253 /// we have source-location information for each identifier in the module
4256 /// When the bit is false, we only have a single source location for the
4257 /// end of the import declaration.
4258 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4260 /// The next import in the list of imports local to the translation
4261 /// unit being parsed (not loaded from an AST file).
4262 ImportDecl *NextLocalImport = nullptr;
4264 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4265 ArrayRef<SourceLocation> IdentifierLocs);
4267 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4268 SourceLocation EndLoc);
4270 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4273 /// Create a new module import declaration.
4274 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4275 SourceLocation StartLoc, Module *Imported,
4276 ArrayRef<SourceLocation> IdentifierLocs);
4278 /// Create a new module import declaration for an implicitly-generated
4280 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4281 SourceLocation StartLoc, Module *Imported,
4282 SourceLocation EndLoc);
4284 /// Create a new, deserialized module import declaration.
4285 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4286 unsigned NumLocations);
4288 /// Retrieve the module that was imported by the import declaration.
4289 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4291 /// Retrieves the locations of each of the identifiers that make up
4292 /// the complete module name in the import declaration.
4294 /// This will return an empty array if the locations of the individual
4295 /// identifiers aren't available.
4296 ArrayRef<SourceLocation> getIdentifierLocs() const;
4298 SourceRange getSourceRange() const override LLVM_READONLY;
4300 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4301 static bool classofKind(Kind K) { return K == Import; }
4304 /// Represents a C++ Modules TS module export declaration.
4308 /// export void foo();
4310 class ExportDecl final : public Decl, public DeclContext {
4311 virtual void anchor();
4314 friend class ASTDeclReader;
4316 /// The source location for the right brace (if valid).
4317 SourceLocation RBraceLoc;
4319 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4320 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4321 RBraceLoc(SourceLocation()) {}
4324 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4325 SourceLocation ExportLoc);
4326 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4328 SourceLocation getExportLoc() const { return getLocation(); }
4329 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4330 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4332 bool hasBraces() const { return RBraceLoc.isValid(); }
4334 SourceLocation getEndLoc() const LLVM_READONLY {
4337 // No braces: get the end location of the (only) declaration in context
4339 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4342 SourceRange getSourceRange() const override LLVM_READONLY {
4343 return SourceRange(getLocation(), getEndLoc());
4346 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4347 static bool classofKind(Kind K) { return K == Export; }
4348 static DeclContext *castToDeclContext(const ExportDecl *D) {
4349 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4351 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4352 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4356 /// Represents an empty-declaration.
4357 class EmptyDecl : public Decl {
4358 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4360 virtual void anchor();
4363 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4365 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4367 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4368 static bool classofKind(Kind K) { return K == Empty; }
4371 /// Insertion operator for diagnostics. This allows sending NamedDecl's
4372 /// into a diagnostic with <<.
4373 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4374 const NamedDecl* ND) {
4375 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4376 DiagnosticsEngine::ak_nameddecl);
4379 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4380 const NamedDecl* ND) {
4381 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4382 DiagnosticsEngine::ak_nameddecl);
4386 template<typename decl_type>
4387 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4388 // Note: This routine is implemented here because we need both NamedDecl
4389 // and Redeclarable to be defined.
4390 assert(RedeclLink.isFirst() &&
4391 "setPreviousDecl on a decl already in a redeclaration chain");
4394 // Point to previous. Make sure that this is actually the most recent
4395 // redeclaration, or we can build invalid chains. If the most recent
4396 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4397 First = PrevDecl->getFirstDecl();
4398 assert(First->RedeclLink.isFirst() && "Expected first");
4399 decl_type *MostRecent = First->getNextRedeclaration();
4400 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4402 // If the declaration was previously visible, a redeclaration of it remains
4403 // visible even if it wouldn't be visible by itself.
4404 static_cast<decl_type*>(this)->IdentifierNamespace |=
4405 MostRecent->getIdentifierNamespace() &
4406 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4409 First = static_cast<decl_type*>(this);
4412 // First one will point to this one as latest.
4413 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4415 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
4416 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
4419 // Inline function definitions.
4421 /// Check if the given decl is complete.
4423 /// We use this function to break a cycle between the inline definitions in
4424 /// Type.h and Decl.h.
4425 inline bool IsEnumDeclComplete(EnumDecl *ED) {
4426 return ED->isComplete();
4429 /// Check if the given decl is scoped.
4431 /// We use this function to break a cycle between the inline definitions in
4432 /// Type.h and Decl.h.
4433 inline bool IsEnumDeclScoped(EnumDecl *ED) {
4434 return ED->isScoped();
4437 } // namespace clang
4439 #endif // LLVM_CLANG_AST_DECL_H