1 //===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Decl subclasses.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_AST_DECL_H
15 #define LLVM_CLANG_AST_DECL_H
17 #include "clang/AST/APValue.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 /// \brief 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.getStartLoc().print(OS, SrcMgr);
86 class 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 /// \brief Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
99 /// \brief Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
102 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
106 /// TranslationUnitDecl - 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 /// \brief 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 /// \brief 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 /// \brief 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 /// NamedDecl - This represents a decl with a name. Many decls have names such
244 /// as ObjCMethodDecl, but not \@class, etc.
245 class NamedDecl : public Decl {
246 /// Name - The name of this declaration, which is typically a normal
247 /// identifier but may also be a special kind of name (C++
248 /// constructor, Objective-C selector, etc.)
249 DeclarationName Name;
251 virtual void anchor();
254 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
257 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
258 : Decl(DK, DC, L), Name(N) {}
261 /// getIdentifier - Get the identifier that names this declaration,
262 /// if there is one. This will return NULL if this declaration has
263 /// no name (e.g., for an unnamed class) or if the name is a special
264 /// name (C++ constructor, Objective-C selector, etc.).
265 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
267 /// getName - Get the name of identifier for this declaration as a StringRef.
268 /// This requires that the declaration have a name and that it be a simple
270 StringRef getName() const {
271 assert(Name.isIdentifier() && "Name is not a simple identifier");
272 return getIdentifier() ? getIdentifier()->getName() : "";
275 /// getNameAsString - Get a human-readable name for the declaration, even if
276 /// it is one of the special kinds of names (C++ constructor, Objective-C
277 /// selector, etc). Creating this name requires expensive string
278 /// manipulation, so it should be called only when performance doesn't matter.
279 /// For simple declarations, getNameAsCString() should suffice.
281 // FIXME: This function should be renamed to indicate that it is not just an
282 // alternate form of getName(), and clients should move as appropriate.
284 // FIXME: Deprecated, move clients to getName().
285 std::string getNameAsString() const { return Name.getAsString(); }
287 virtual void printName(raw_ostream &os) const;
289 /// getDeclName - Get the actual, stored name of the declaration,
290 /// which may be a special name.
291 DeclarationName getDeclName() const { return Name; }
293 /// \brief Set the name of this declaration.
294 void setDeclName(DeclarationName N) { Name = N; }
296 /// printQualifiedName - Returns human-readable qualified name for
297 /// declaration, like A::B::i, for i being member of namespace A::B.
298 /// If declaration is not member of context which can be named (record,
299 /// namespace), it will return same result as printName().
300 /// Creating this name is expensive, so it should be called only when
301 /// performance doesn't matter.
302 void printQualifiedName(raw_ostream &OS) const;
303 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
305 // FIXME: Remove string version.
306 std::string getQualifiedNameAsString() const;
308 /// Appends a human-readable name for this declaration into the given stream.
310 /// This is the method invoked by Sema when displaying a NamedDecl
311 /// in a diagnostic. It does not necessarily produce the same
312 /// result as printName(); for example, class template
313 /// specializations are printed with their template arguments.
314 virtual void getNameForDiagnostic(raw_ostream &OS,
315 const PrintingPolicy &Policy,
316 bool Qualified) const;
318 /// \brief Determine whether this declaration, if
319 /// known to be well-formed within its context, will replace the
320 /// declaration OldD if introduced into scope. A declaration will
321 /// replace another declaration if, for example, it is a
322 /// redeclaration of the same variable or function, but not if it is
323 /// a declaration of a different kind (function vs. class) or an
324 /// overloaded function.
326 /// \param IsKnownNewer \c true if this declaration is known to be newer
327 /// than \p OldD (for instance, if this declaration is newly-created).
328 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
330 /// \brief Determine whether this declaration has linkage.
331 bool hasLinkage() const;
333 using Decl::isModulePrivate;
334 using Decl::setModulePrivate;
336 /// \brief Determine whether this declaration is a C++ class member.
337 bool isCXXClassMember() const {
338 const DeclContext *DC = getDeclContext();
340 // C++0x [class.mem]p1:
341 // The enumerators of an unscoped enumeration defined in
342 // the class are members of the class.
343 if (isa<EnumDecl>(DC))
344 DC = DC->getRedeclContext();
346 return DC->isRecord();
349 /// \brief Determine whether the given declaration is an instance member of
351 bool isCXXInstanceMember() const;
353 /// \brief Determine what kind of linkage this entity has.
354 /// This is not the linkage as defined by the standard or the codegen notion
355 /// of linkage. It is just an implementation detail that is used to compute
357 Linkage getLinkageInternal() const;
359 /// \brief Get the linkage from a semantic point of view. Entities in
360 /// anonymous namespaces are external (in c++98).
361 Linkage getFormalLinkage() const {
362 return clang::getFormalLinkage(getLinkageInternal());
365 /// \brief True if this decl has external linkage.
366 bool hasExternalFormalLinkage() const {
367 return isExternalFormalLinkage(getLinkageInternal());
370 bool isExternallyVisible() const {
371 return clang::isExternallyVisible(getLinkageInternal());
374 /// Determine whether this declaration can be redeclared in a
375 /// different translation unit.
376 bool isExternallyDeclarable() const {
377 return isExternallyVisible() && !getOwningModuleForLinkage();
380 /// \brief Determines the visibility of this entity.
381 Visibility getVisibility() const {
382 return getLinkageAndVisibility().getVisibility();
385 /// \brief Determines the linkage and visibility of this entity.
386 LinkageInfo getLinkageAndVisibility() const;
388 /// Kinds of explicit visibility.
389 enum ExplicitVisibilityKind {
390 /// Do an LV computation for, ultimately, a type.
391 /// Visibility may be restricted by type visibility settings and
392 /// the visibility of template arguments.
395 /// Do an LV computation for, ultimately, a non-type declaration.
396 /// Visibility may be restricted by value visibility settings and
397 /// the visibility of template arguments.
401 /// \brief If visibility was explicitly specified for this
402 /// declaration, return that visibility.
404 getExplicitVisibility(ExplicitVisibilityKind kind) const;
406 /// \brief True if the computed linkage is valid. Used for consistency
407 /// checking. Should always return true.
408 bool isLinkageValid() const;
410 /// \brief True if something has required us to compute the linkage
411 /// of this declaration.
413 /// Language features which can retroactively change linkage (like a
414 /// typedef name for linkage purposes) may need to consider this,
415 /// but hopefully only in transitory ways during parsing.
416 bool hasLinkageBeenComputed() const {
417 return hasCachedLinkage();
420 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
421 /// the underlying named decl.
422 NamedDecl *getUnderlyingDecl() {
423 // Fast-path the common case.
424 if (this->getKind() != UsingShadow &&
425 this->getKind() != ConstructorUsingShadow &&
426 this->getKind() != ObjCCompatibleAlias &&
427 this->getKind() != NamespaceAlias)
430 return getUnderlyingDeclImpl();
432 const NamedDecl *getUnderlyingDecl() const {
433 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
436 NamedDecl *getMostRecentDecl() {
437 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
439 const NamedDecl *getMostRecentDecl() const {
440 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
443 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
445 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
446 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
449 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
454 /// LabelDecl - Represents the declaration of a label. Labels also have a
455 /// corresponding LabelStmt, which indicates the position that the label was
456 /// defined at. For normal labels, the location of the decl is the same as the
457 /// location of the statement. For GNU local labels (__label__), the decl
458 /// location is where the __label__ is.
459 class LabelDecl : public NamedDecl {
462 bool MSAsmNameResolved = false;
464 /// LocStart - For normal labels, this is the same as the main declaration
465 /// label, i.e., the location of the identifier; for GNU local labels,
466 /// this is the location of the __label__ keyword.
467 SourceLocation LocStart;
469 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
470 LabelStmt *S, SourceLocation StartL)
471 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
473 void anchor() override;
476 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
477 SourceLocation IdentL, IdentifierInfo *II);
478 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
479 SourceLocation IdentL, IdentifierInfo *II,
480 SourceLocation GnuLabelL);
481 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
483 LabelStmt *getStmt() const { return TheStmt; }
484 void setStmt(LabelStmt *T) { TheStmt = T; }
486 bool isGnuLocal() const { return LocStart != getLocation(); }
487 void setLocStart(SourceLocation L) { LocStart = L; }
489 SourceRange getSourceRange() const override LLVM_READONLY {
490 return SourceRange(LocStart, getLocation());
493 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
494 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
495 void setMSAsmLabel(StringRef Name);
496 StringRef getMSAsmLabel() const { return MSAsmName; }
497 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
499 // Implement isa/cast/dyncast/etc.
500 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
501 static bool classofKind(Kind K) { return K == Label; }
504 /// NamespaceDecl - Represent a C++ namespace.
505 class NamespaceDecl : public NamedDecl, public DeclContext,
506 public Redeclarable<NamespaceDecl>
508 /// LocStart - The starting location of the source range, pointing
509 /// to either the namespace or the inline keyword.
510 SourceLocation LocStart;
512 /// RBraceLoc - The ending location of the source range.
513 SourceLocation RBraceLoc;
515 /// \brief A pointer to either the anonymous namespace that lives just inside
516 /// this namespace or to the first namespace in the chain (the latter case
517 /// only when this is not the first in the chain), along with a
518 /// boolean value indicating whether this is an inline namespace.
519 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
521 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
522 SourceLocation StartLoc, SourceLocation IdLoc,
523 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
525 using redeclarable_base = Redeclarable<NamespaceDecl>;
527 NamespaceDecl *getNextRedeclarationImpl() override;
528 NamespaceDecl *getPreviousDeclImpl() override;
529 NamespaceDecl *getMostRecentDeclImpl() override;
532 friend class ASTDeclReader;
533 friend class ASTDeclWriter;
535 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
536 bool Inline, SourceLocation StartLoc,
537 SourceLocation IdLoc, IdentifierInfo *Id,
538 NamespaceDecl *PrevDecl);
540 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
542 using redecl_range = redeclarable_base::redecl_range;
543 using redecl_iterator = redeclarable_base::redecl_iterator;
545 using redeclarable_base::redecls_begin;
546 using redeclarable_base::redecls_end;
547 using redeclarable_base::redecls;
548 using redeclarable_base::getPreviousDecl;
549 using redeclarable_base::getMostRecentDecl;
550 using redeclarable_base::isFirstDecl;
552 /// \brief Returns true if this is an anonymous namespace declaration.
560 /// q.v. C++ [namespace.unnamed]
561 bool isAnonymousNamespace() const {
562 return !getIdentifier();
565 /// \brief Returns true if this is an inline namespace declaration.
566 bool isInline() const {
567 return AnonOrFirstNamespaceAndInline.getInt();
570 /// \brief Set whether this is an inline namespace declaration.
571 void setInline(bool Inline) {
572 AnonOrFirstNamespaceAndInline.setInt(Inline);
575 /// \brief Get the original (first) namespace declaration.
576 NamespaceDecl *getOriginalNamespace();
578 /// \brief Get the original (first) namespace declaration.
579 const NamespaceDecl *getOriginalNamespace() const;
581 /// \brief Return true if this declaration is an original (first) declaration
582 /// of the namespace. This is false for non-original (subsequent) namespace
583 /// declarations and anonymous namespaces.
584 bool isOriginalNamespace() const;
586 /// \brief Retrieve the anonymous namespace nested inside this namespace,
588 NamespaceDecl *getAnonymousNamespace() const {
589 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
592 void setAnonymousNamespace(NamespaceDecl *D) {
593 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
596 /// Retrieves the canonical declaration of this namespace.
597 NamespaceDecl *getCanonicalDecl() override {
598 return getOriginalNamespace();
600 const NamespaceDecl *getCanonicalDecl() const {
601 return getOriginalNamespace();
604 SourceRange getSourceRange() const override LLVM_READONLY {
605 return SourceRange(LocStart, RBraceLoc);
608 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
609 SourceLocation getRBraceLoc() const { return RBraceLoc; }
610 void setLocStart(SourceLocation L) { LocStart = L; }
611 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
613 // Implement isa/cast/dyncast/etc.
614 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
615 static bool classofKind(Kind K) { return K == Namespace; }
616 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
617 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
619 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
620 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
624 /// ValueDecl - Represent the declaration of a variable (in which case it is
625 /// an lvalue) a function (in which case it is a function designator) or
626 /// an enum constant.
627 class ValueDecl : public NamedDecl {
630 void anchor() override;
633 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
634 DeclarationName N, QualType T)
635 : NamedDecl(DK, DC, L, N), DeclType(T) {}
638 QualType getType() const { return DeclType; }
639 void setType(QualType newType) { DeclType = newType; }
641 /// \brief Determine whether this symbol is weakly-imported,
642 /// or declared with the weak or weak-ref attr.
645 // Implement isa/cast/dyncast/etc.
646 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
647 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
650 /// QualifierInfo - A struct with extended info about a syntactic
651 /// name qualifier, to be used for the case of out-of-line declarations.
652 struct QualifierInfo {
653 NestedNameSpecifierLoc QualifierLoc;
655 /// NumTemplParamLists - The number of "outer" template parameter lists.
656 /// The count includes all of the template parameter lists that were matched
657 /// against the template-ids occurring into the NNS and possibly (in the
658 /// case of an explicit specialization) a final "template <>".
659 unsigned NumTemplParamLists = 0;
661 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
662 /// containing pointers to the "outer" template parameter lists.
663 /// It includes all of the template parameter lists that were matched
664 /// against the template-ids occurring into the NNS and possibly (in the
665 /// case of an explicit specialization) a final "template <>".
666 TemplateParameterList** TemplParamLists = nullptr;
668 QualifierInfo() = default;
669 QualifierInfo(const QualifierInfo &) = delete;
670 QualifierInfo& operator=(const QualifierInfo &) = delete;
672 /// setTemplateParameterListsInfo - Sets info about "outer" template
674 void setTemplateParameterListsInfo(ASTContext &Context,
675 ArrayRef<TemplateParameterList *> TPLists);
678 /// \brief Represents a ValueDecl that came out of a declarator.
679 /// Contains type source information through TypeSourceInfo.
680 class DeclaratorDecl : public ValueDecl {
681 // A struct representing both a TInfo and a syntactic qualifier,
682 // to be used for the (uncommon) case of out-of-line declarations.
683 struct ExtInfo : public QualifierInfo {
684 TypeSourceInfo *TInfo;
687 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
689 /// InnerLocStart - The start of the source range for this declaration,
690 /// ignoring outer template declarations.
691 SourceLocation InnerLocStart;
693 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
694 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
695 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
698 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
699 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
700 SourceLocation StartL)
701 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
704 friend class ASTDeclReader;
705 friend class ASTDeclWriter;
707 TypeSourceInfo *getTypeSourceInfo() const {
709 ? getExtInfo()->TInfo
710 : DeclInfo.get<TypeSourceInfo*>();
713 void setTypeSourceInfo(TypeSourceInfo *TI) {
715 getExtInfo()->TInfo = TI;
720 /// getInnerLocStart - Return SourceLocation representing start of source
721 /// range ignoring outer template declarations.
722 SourceLocation getInnerLocStart() const { return InnerLocStart; }
723 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
725 /// getOuterLocStart - Return SourceLocation representing start of source
726 /// range taking into account any outer template declarations.
727 SourceLocation getOuterLocStart() const;
729 SourceRange getSourceRange() const override LLVM_READONLY;
731 SourceLocation getLocStart() const LLVM_READONLY {
732 return getOuterLocStart();
735 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
736 /// declaration, if it was present in the source.
737 NestedNameSpecifier *getQualifier() const {
738 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
742 /// \brief Retrieve the nested-name-specifier (with source-location
743 /// information) that qualifies the name of this declaration, if it was
744 /// present in the source.
745 NestedNameSpecifierLoc getQualifierLoc() const {
746 return hasExtInfo() ? getExtInfo()->QualifierLoc
747 : NestedNameSpecifierLoc();
750 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
752 unsigned getNumTemplateParameterLists() const {
753 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
756 TemplateParameterList *getTemplateParameterList(unsigned index) const {
757 assert(index < getNumTemplateParameterLists());
758 return getExtInfo()->TemplParamLists[index];
761 void setTemplateParameterListsInfo(ASTContext &Context,
762 ArrayRef<TemplateParameterList *> TPLists);
764 SourceLocation getTypeSpecStartLoc() const;
766 // Implement isa/cast/dyncast/etc.
767 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
768 static bool classofKind(Kind K) {
769 return K >= firstDeclarator && K <= lastDeclarator;
773 /// \brief Structure used to store a statement, the constant value to
774 /// which it was evaluated (if any), and whether or not the statement
775 /// is an integral constant expression (if known).
776 struct EvaluatedStmt {
777 /// \brief Whether this statement was already evaluated.
778 bool WasEvaluated : 1;
780 /// \brief Whether this statement is being evaluated.
781 bool IsEvaluating : 1;
783 /// \brief Whether we already checked whether this statement was an
784 /// integral constant expression.
787 /// \brief Whether we are checking whether this statement is an
788 /// integral constant expression.
789 bool CheckingICE : 1;
791 /// \brief Whether this statement is an integral constant expression,
792 /// or in C++11, whether the statement is a constant expression. Only
793 /// valid if CheckedICE is true.
799 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
800 CheckingICE(false), IsICE(false) {}
804 /// VarDecl - An instance of this class is created to represent a variable
805 /// declaration or definition.
806 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
808 /// \brief Initialization styles.
809 enum InitializationStyle {
810 /// C-style initialization with assignment
813 /// Call-style initialization (C++98)
816 /// Direct list-initialization (C++11)
820 /// \brief Kinds of thread-local storage.
822 /// Not a TLS variable.
825 /// TLS with a known-constant initializer.
828 /// TLS with a dynamic initializer.
832 /// getStorageClassSpecifierString - Return the string used to
833 /// specify the storage class \p SC.
835 /// It is illegal to call this function with SC == None.
836 static const char *getStorageClassSpecifierString(StorageClass SC);
839 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
840 // have allocated the auxiliary struct of information there.
842 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
843 // this as *many* VarDecls are ParmVarDecls that don't have default
844 // arguments. We could save some space by moving this pointer union to be
845 // allocated in trailing space when necessary.
846 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
848 /// \brief The initializer for this variable or, for a ParmVarDecl, the
849 /// C++ default argument.
850 mutable InitType Init;
853 friend class ASTDeclReader;
854 friend class ASTNodeImporter;
855 friend class StmtIteratorBase;
857 class VarDeclBitfields {
858 friend class ASTDeclReader;
859 friend class VarDecl;
862 unsigned TSCSpec : 2;
863 unsigned InitStyle : 2;
865 enum { NumVarDeclBits = 7 };
868 enum { NumParameterIndexBits = 8 };
870 enum DefaultArgKind {
877 class ParmVarDeclBitfields {
878 friend class ASTDeclReader;
879 friend class ParmVarDecl;
881 unsigned : NumVarDeclBits;
883 /// Whether this parameter inherits a default argument from a
884 /// prior declaration.
885 unsigned HasInheritedDefaultArg : 1;
887 /// Describes the kind of default argument for this parameter. By default
888 /// this is none. If this is normal, then the default argument is stored in
889 /// the \c VarDecl initializer expression unless we were unable to parse
890 /// (even an invalid) expression for the default argument.
891 unsigned DefaultArgKind : 2;
893 /// Whether this parameter undergoes K&R argument promotion.
894 unsigned IsKNRPromoted : 1;
896 /// Whether this parameter is an ObjC method parameter or not.
897 unsigned IsObjCMethodParam : 1;
899 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
900 /// Otherwise, the number of function parameter scopes enclosing
901 /// the function parameter scope in which this parameter was
903 unsigned ScopeDepthOrObjCQuals : 7;
905 /// The number of parameters preceding this parameter in the
906 /// function parameter scope in which it was declared.
907 unsigned ParameterIndex : NumParameterIndexBits;
910 class NonParmVarDeclBitfields {
911 friend class ASTDeclReader;
912 friend class ImplicitParamDecl;
913 friend class VarDecl;
915 unsigned : NumVarDeclBits;
917 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
918 /// \brief Whether this variable is a definition which was demoted due to
920 unsigned IsThisDeclarationADemotedDefinition : 1;
922 /// \brief Whether this variable is the exception variable in a C++ catch
923 /// or an Objective-C @catch statement.
924 unsigned ExceptionVar : 1;
926 /// \brief Whether this local variable could be allocated in the return
927 /// slot of its function, enabling the named return value optimization
929 unsigned NRVOVariable : 1;
931 /// \brief Whether this variable is the for-range-declaration in a C++0x
932 /// for-range statement.
933 unsigned CXXForRangeDecl : 1;
935 /// \brief Whether this variable is an ARC pseudo-__strong
936 /// variable; see isARCPseudoStrong() for details.
937 unsigned ARCPseudoStrong : 1;
939 /// \brief Whether this variable is (C++1z) inline.
940 unsigned IsInline : 1;
942 /// \brief Whether this variable has (C++1z) inline explicitly specified.
943 unsigned IsInlineSpecified : 1;
945 /// \brief Whether this variable is (C++0x) constexpr.
946 unsigned IsConstexpr : 1;
948 /// \brief Whether this variable is the implicit variable for a lambda
950 unsigned IsInitCapture : 1;
952 /// \brief Whether this local extern variable's previous declaration was
953 /// declared in the same block scope. This controls whether we should merge
954 /// the type of this declaration with its previous declaration.
955 unsigned PreviousDeclInSameBlockScope : 1;
957 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
959 unsigned ImplicitParamKind : 3;
964 VarDeclBitfields VarDeclBits;
965 ParmVarDeclBitfields ParmVarDeclBits;
966 NonParmVarDeclBitfields NonParmVarDeclBits;
969 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
970 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
971 TypeSourceInfo *TInfo, StorageClass SC);
973 using redeclarable_base = Redeclarable<VarDecl>;
975 VarDecl *getNextRedeclarationImpl() override {
976 return getNextRedeclaration();
979 VarDecl *getPreviousDeclImpl() override {
980 return getPreviousDecl();
983 VarDecl *getMostRecentDeclImpl() override {
984 return getMostRecentDecl();
988 using redecl_range = redeclarable_base::redecl_range;
989 using redecl_iterator = redeclarable_base::redecl_iterator;
991 using redeclarable_base::redecls_begin;
992 using redeclarable_base::redecls_end;
993 using redeclarable_base::redecls;
994 using redeclarable_base::getPreviousDecl;
995 using redeclarable_base::getMostRecentDecl;
996 using redeclarable_base::isFirstDecl;
998 static VarDecl *Create(ASTContext &C, DeclContext *DC,
999 SourceLocation StartLoc, SourceLocation IdLoc,
1000 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1003 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1005 SourceRange getSourceRange() const override LLVM_READONLY;
1007 /// \brief Returns the storage class as written in the source. For the
1008 /// computed linkage of symbol, see getLinkage.
1009 StorageClass getStorageClass() const {
1010 return (StorageClass) VarDeclBits.SClass;
1012 void setStorageClass(StorageClass SC);
1014 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1015 VarDeclBits.TSCSpec = TSC;
1016 assert(VarDeclBits.TSCSpec == TSC && "truncation");
1018 ThreadStorageClassSpecifier getTSCSpec() const {
1019 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1021 TLSKind getTLSKind() const;
1023 /// hasLocalStorage - Returns true if a variable with function scope
1024 /// is a non-static local variable.
1025 bool hasLocalStorage() const {
1026 if (getStorageClass() == SC_None) {
1027 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1028 // used to describe variables allocated in global memory and which are
1029 // accessed inside a kernel(s) as read-only variables. As such, variables
1030 // in constant address space cannot have local storage.
1031 if (getType().getAddressSpace() == LangAS::opencl_constant)
1033 // Second check is for C++11 [dcl.stc]p4.
1034 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1037 // Global Named Register (GNU extension)
1038 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1041 // Return true for: Auto, Register.
1042 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1044 return getStorageClass() >= SC_Auto;
1047 /// isStaticLocal - Returns true if a variable with function scope is a
1048 /// static local variable.
1049 bool isStaticLocal() const {
1050 return (getStorageClass() == SC_Static ||
1051 // C++11 [dcl.stc]p4
1052 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1053 && !isFileVarDecl();
1056 /// \brief Returns true if a variable has extern or __private_extern__
1058 bool hasExternalStorage() const {
1059 return getStorageClass() == SC_Extern ||
1060 getStorageClass() == SC_PrivateExtern;
1063 /// \brief Returns true for all variables that do not have local storage.
1065 /// This includes all global variables as well as static variables declared
1066 /// within a function.
1067 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1069 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1070 StorageDuration getStorageDuration() const {
1071 return hasLocalStorage() ? SD_Automatic :
1072 getTSCSpec() ? SD_Thread : SD_Static;
1075 /// \brief Compute the language linkage.
1076 LanguageLinkage getLanguageLinkage() const;
1078 /// \brief Determines whether this variable is a variable with
1079 /// external, C linkage.
1080 bool isExternC() const;
1082 /// \brief Determines whether this variable's context is, or is nested within,
1083 /// a C++ extern "C" linkage spec.
1084 bool isInExternCContext() const;
1086 /// \brief Determines whether this variable's context is, or is nested within,
1087 /// a C++ extern "C++" linkage spec.
1088 bool isInExternCXXContext() const;
1090 /// isLocalVarDecl - Returns true for local variable declarations
1091 /// other than parameters. Note that this includes static variables
1092 /// inside of functions. It also includes variables inside blocks.
1094 /// void foo() { int x; static int y; extern int z; }
1095 bool isLocalVarDecl() const {
1096 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1098 if (const DeclContext *DC = getLexicalDeclContext())
1099 return DC->getRedeclContext()->isFunctionOrMethod();
1103 /// \brief Similar to isLocalVarDecl but also includes parameters.
1104 bool isLocalVarDeclOrParm() const {
1105 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1108 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1109 /// excludes variables declared in blocks.
1110 bool isFunctionOrMethodVarDecl() const {
1111 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1113 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1114 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1117 /// \brief Determines whether this is a static data member.
1119 /// This will only be true in C++, and applies to, e.g., the
1120 /// variable 'x' in:
1126 bool isStaticDataMember() const {
1127 // If it wasn't static, it would be a FieldDecl.
1128 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1131 VarDecl *getCanonicalDecl() override;
1132 const VarDecl *getCanonicalDecl() const {
1133 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1136 enum DefinitionKind {
1137 /// This declaration is only a declaration.
1140 /// This declaration is a tentative definition.
1141 TentativeDefinition,
1143 /// This declaration is definitely a definition.
1147 /// \brief Check whether this declaration is a definition. If this could be
1148 /// a tentative definition (in C), don't check whether there's an overriding
1150 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1151 DefinitionKind isThisDeclarationADefinition() const {
1152 return isThisDeclarationADefinition(getASTContext());
1155 /// \brief Check whether this variable is defined in this
1156 /// translation unit.
1157 DefinitionKind hasDefinition(ASTContext &) const;
1158 DefinitionKind hasDefinition() const {
1159 return hasDefinition(getASTContext());
1162 /// \brief Get the tentative definition that acts as the real definition in
1163 /// a TU. Returns null if there is a proper definition available.
1164 VarDecl *getActingDefinition();
1165 const VarDecl *getActingDefinition() const {
1166 return const_cast<VarDecl*>(this)->getActingDefinition();
1169 /// \brief Get the real (not just tentative) definition for this declaration.
1170 VarDecl *getDefinition(ASTContext &);
1171 const VarDecl *getDefinition(ASTContext &C) const {
1172 return const_cast<VarDecl*>(this)->getDefinition(C);
1174 VarDecl *getDefinition() {
1175 return getDefinition(getASTContext());
1177 const VarDecl *getDefinition() const {
1178 return const_cast<VarDecl*>(this)->getDefinition();
1181 /// \brief Determine whether this is or was instantiated from an out-of-line
1182 /// definition of a static data member.
1183 bool isOutOfLine() const override;
1185 /// isFileVarDecl - Returns true for file scoped variable declaration.
1186 bool isFileVarDecl() const {
1188 if (K == ParmVar || K == ImplicitParam)
1191 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1194 if (isStaticDataMember())
1200 /// getAnyInitializer - Get the initializer for this variable, no matter which
1201 /// declaration it is attached to.
1202 const Expr *getAnyInitializer() const {
1204 return getAnyInitializer(D);
1207 /// getAnyInitializer - Get the initializer for this variable, no matter which
1208 /// declaration it is attached to. Also get that declaration.
1209 const Expr *getAnyInitializer(const VarDecl *&D) const;
1211 bool hasInit() const;
1212 const Expr *getInit() const {
1213 return const_cast<VarDecl *>(this)->getInit();
1217 /// \brief Retrieve the address of the initializer expression.
1218 Stmt **getInitAddress();
1220 void setInit(Expr *I);
1222 /// \brief Determine whether this variable's value can be used in a
1223 /// constant expression, according to the relevant language standard.
1224 /// This only checks properties of the declaration, and does not check
1225 /// whether the initializer is in fact a constant expression.
1226 bool isUsableInConstantExpressions(ASTContext &C) const;
1228 EvaluatedStmt *ensureEvaluatedStmt() const;
1230 /// \brief Attempt to evaluate the value of the initializer attached to this
1231 /// declaration, and produce notes explaining why it cannot be evaluated or is
1232 /// not a constant expression. Returns a pointer to the value if evaluation
1233 /// succeeded, 0 otherwise.
1234 APValue *evaluateValue() const;
1235 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1237 /// \brief Return the already-evaluated value of this variable's
1238 /// initializer, or NULL if the value is not yet known. Returns pointer
1239 /// to untyped APValue if the value could not be evaluated.
1240 APValue *getEvaluatedValue() const;
1242 /// \brief Determines whether it is already known whether the
1243 /// initializer is an integral constant expression or not.
1244 bool isInitKnownICE() const;
1246 /// \brief Determines whether the initializer is an integral constant
1247 /// expression, or in C++11, whether the initializer is a constant
1250 /// \pre isInitKnownICE()
1251 bool isInitICE() const;
1253 /// \brief Determine whether the value of the initializer attached to this
1254 /// declaration is an integral constant expression.
1255 bool checkInitIsICE() const;
1257 void setInitStyle(InitializationStyle Style) {
1258 VarDeclBits.InitStyle = Style;
1261 /// \brief The style of initialization for this declaration.
1263 /// C-style initialization is "int x = 1;". Call-style initialization is
1264 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1265 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1266 /// expression for class types. List-style initialization is C++11 syntax,
1267 /// e.g. "int x{1};". Clients can distinguish between different forms of
1268 /// initialization by checking this value. In particular, "int x = {1};" is
1269 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1270 /// Init expression in all three cases is an InitListExpr.
1271 InitializationStyle getInitStyle() const {
1272 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1275 /// \brief Whether the initializer is a direct-initializer (list or call).
1276 bool isDirectInit() const {
1277 return getInitStyle() != CInit;
1280 /// \brief If this definition should pretend to be a declaration.
1281 bool isThisDeclarationADemotedDefinition() const {
1282 return isa<ParmVarDecl>(this) ? false :
1283 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1286 /// \brief This is a definition which should be demoted to a declaration.
1288 /// In some cases (mostly module merging) we can end up with two visible
1289 /// definitions one of which needs to be demoted to a declaration to keep
1290 /// the AST invariants.
1291 void demoteThisDefinitionToDeclaration() {
1292 assert(isThisDeclarationADefinition() && "Not a definition!");
1293 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1294 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1297 /// \brief Determine whether this variable is the exception variable in a
1298 /// C++ catch statememt or an Objective-C \@catch statement.
1299 bool isExceptionVariable() const {
1300 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1302 void setExceptionVariable(bool EV) {
1303 assert(!isa<ParmVarDecl>(this));
1304 NonParmVarDeclBits.ExceptionVar = EV;
1307 /// \brief Determine whether this local variable can be used with the named
1308 /// return value optimization (NRVO).
1310 /// The named return value optimization (NRVO) works by marking certain
1311 /// non-volatile local variables of class type as NRVO objects. These
1312 /// locals can be allocated within the return slot of their containing
1313 /// function, in which case there is no need to copy the object to the
1314 /// return slot when returning from the function. Within the function body,
1315 /// each return that returns the NRVO object will have this variable as its
1317 bool isNRVOVariable() const {
1318 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1320 void setNRVOVariable(bool NRVO) {
1321 assert(!isa<ParmVarDecl>(this));
1322 NonParmVarDeclBits.NRVOVariable = NRVO;
1325 /// \brief Determine whether this variable is the for-range-declaration in
1326 /// a C++0x for-range statement.
1327 bool isCXXForRangeDecl() const {
1328 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1330 void setCXXForRangeDecl(bool FRD) {
1331 assert(!isa<ParmVarDecl>(this));
1332 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1335 /// \brief Determine whether this variable is an ARC pseudo-__strong
1336 /// variable. A pseudo-__strong variable has a __strong-qualified
1337 /// type but does not actually retain the object written into it.
1338 /// Generally such variables are also 'const' for safety.
1339 bool isARCPseudoStrong() const {
1340 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1342 void setARCPseudoStrong(bool ps) {
1343 assert(!isa<ParmVarDecl>(this));
1344 NonParmVarDeclBits.ARCPseudoStrong = ps;
1347 /// Whether this variable is (C++1z) inline.
1348 bool isInline() const {
1349 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1351 bool isInlineSpecified() const {
1352 return isa<ParmVarDecl>(this) ? false
1353 : NonParmVarDeclBits.IsInlineSpecified;
1355 void setInlineSpecified() {
1356 assert(!isa<ParmVarDecl>(this));
1357 NonParmVarDeclBits.IsInline = true;
1358 NonParmVarDeclBits.IsInlineSpecified = true;
1360 void setImplicitlyInline() {
1361 assert(!isa<ParmVarDecl>(this));
1362 NonParmVarDeclBits.IsInline = true;
1365 /// Whether this variable is (C++11) constexpr.
1366 bool isConstexpr() const {
1367 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1369 void setConstexpr(bool IC) {
1370 assert(!isa<ParmVarDecl>(this));
1371 NonParmVarDeclBits.IsConstexpr = IC;
1374 /// Whether this variable is the implicit variable for a lambda init-capture.
1375 bool isInitCapture() const {
1376 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1378 void setInitCapture(bool IC) {
1379 assert(!isa<ParmVarDecl>(this));
1380 NonParmVarDeclBits.IsInitCapture = IC;
1383 /// Whether this local extern variable declaration's previous declaration
1384 /// was declared in the same block scope. Only correct in C++.
1385 bool isPreviousDeclInSameBlockScope() const {
1386 return isa<ParmVarDecl>(this)
1388 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1390 void setPreviousDeclInSameBlockScope(bool Same) {
1391 assert(!isa<ParmVarDecl>(this));
1392 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1395 /// \brief Retrieve the variable declaration from which this variable could
1396 /// be instantiated, if it is an instantiation (rather than a non-template).
1397 VarDecl *getTemplateInstantiationPattern() const;
1399 /// \brief If this variable is an instantiated static data member of a
1400 /// class template specialization, returns the templated static data member
1401 /// from which it was instantiated.
1402 VarDecl *getInstantiatedFromStaticDataMember() const;
1404 /// \brief If this variable is an instantiation of a variable template or a
1405 /// static data member of a class template, determine what kind of
1406 /// template specialization or instantiation this is.
1407 TemplateSpecializationKind getTemplateSpecializationKind() const;
1409 /// \brief If this variable is an instantiation of a variable template or a
1410 /// static data member of a class template, determine its point of
1412 SourceLocation getPointOfInstantiation() const;
1414 /// \brief If this variable is an instantiation of a static data member of a
1415 /// class template specialization, retrieves the member specialization
1417 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1419 /// \brief For a static data member that was instantiated from a static
1420 /// data member of a class template, set the template specialiation kind.
1421 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1422 SourceLocation PointOfInstantiation = SourceLocation());
1424 /// \brief Specify that this variable is an instantiation of the
1425 /// static data member VD.
1426 void setInstantiationOfStaticDataMember(VarDecl *VD,
1427 TemplateSpecializationKind TSK);
1429 /// \brief Retrieves the variable template that is described by this
1430 /// variable declaration.
1432 /// Every variable template is represented as a VarTemplateDecl and a
1433 /// VarDecl. The former contains template properties (such as
1434 /// the template parameter lists) while the latter contains the
1435 /// actual description of the template's
1436 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1437 /// VarDecl that from a VarTemplateDecl, while
1438 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1440 VarTemplateDecl *getDescribedVarTemplate() const;
1442 void setDescribedVarTemplate(VarTemplateDecl *Template);
1444 // Implement isa/cast/dyncast/etc.
1445 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1446 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1449 class ImplicitParamDecl : public VarDecl {
1450 void anchor() override;
1453 /// Defines the kind of the implicit parameter: is this an implicit parameter
1454 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1455 /// context or something else.
1456 enum ImplicitParamKind : unsigned {
1457 /// Parameter for Objective-C 'self' argument
1460 /// Parameter for Objective-C '_cmd' argument
1463 /// Parameter for C++ 'this' argument
1466 /// Parameter for C++ virtual table pointers
1469 /// Parameter for captured context
1472 /// Other implicit parameter
1476 /// Create implicit parameter.
1477 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1478 SourceLocation IdLoc, IdentifierInfo *Id,
1479 QualType T, ImplicitParamKind ParamKind);
1480 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1481 ImplicitParamKind ParamKind);
1483 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1485 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1486 IdentifierInfo *Id, QualType Type,
1487 ImplicitParamKind ParamKind)
1488 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1489 /*TInfo=*/nullptr, SC_None) {
1490 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1494 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1495 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1496 SourceLocation(), /*Id=*/nullptr, Type,
1497 /*TInfo=*/nullptr, SC_None) {
1498 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1502 /// Returns the implicit parameter kind.
1503 ImplicitParamKind getParameterKind() const {
1504 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1507 // Implement isa/cast/dyncast/etc.
1508 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1509 static bool classofKind(Kind K) { return K == ImplicitParam; }
1512 /// ParmVarDecl - Represents a parameter to a function.
1513 class ParmVarDecl : public VarDecl {
1515 enum { MaxFunctionScopeDepth = 255 };
1516 enum { MaxFunctionScopeIndex = 255 };
1519 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1520 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1521 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1522 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1523 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1524 assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1525 assert(ParmVarDeclBits.IsKNRPromoted == false);
1526 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1527 setDefaultArg(DefArg);
1531 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1532 SourceLocation StartLoc,
1533 SourceLocation IdLoc, IdentifierInfo *Id,
1534 QualType T, TypeSourceInfo *TInfo,
1535 StorageClass S, Expr *DefArg);
1537 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1539 SourceRange getSourceRange() const override LLVM_READONLY;
1541 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1542 ParmVarDeclBits.IsObjCMethodParam = true;
1543 setParameterIndex(parameterIndex);
1546 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1547 assert(!ParmVarDeclBits.IsObjCMethodParam);
1549 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1550 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1553 setParameterIndex(parameterIndex);
1556 bool isObjCMethodParameter() const {
1557 return ParmVarDeclBits.IsObjCMethodParam;
1560 unsigned getFunctionScopeDepth() const {
1561 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1562 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1565 /// Returns the index of this parameter in its prototype or method scope.
1566 unsigned getFunctionScopeIndex() const {
1567 return getParameterIndex();
1570 ObjCDeclQualifier getObjCDeclQualifier() const {
1571 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1572 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1574 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1575 assert(ParmVarDeclBits.IsObjCMethodParam);
1576 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1579 /// True if the value passed to this parameter must undergo
1580 /// K&R-style default argument promotion:
1583 /// If the expression that denotes the called function has a type
1584 /// that does not include a prototype, the integer promotions are
1585 /// performed on each argument, and arguments that have type float
1586 /// are promoted to double.
1587 bool isKNRPromoted() const {
1588 return ParmVarDeclBits.IsKNRPromoted;
1590 void setKNRPromoted(bool promoted) {
1591 ParmVarDeclBits.IsKNRPromoted = promoted;
1594 Expr *getDefaultArg();
1595 const Expr *getDefaultArg() const {
1596 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1599 void setDefaultArg(Expr *defarg);
1601 /// \brief Retrieve the source range that covers the entire default
1603 SourceRange getDefaultArgRange() const;
1604 void setUninstantiatedDefaultArg(Expr *arg);
1605 Expr *getUninstantiatedDefaultArg();
1606 const Expr *getUninstantiatedDefaultArg() const {
1607 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1610 /// hasDefaultArg - Determines whether this parameter has a default argument,
1611 /// either parsed or not.
1612 bool hasDefaultArg() const;
1614 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1615 /// default argument that has not yet been parsed. This will occur
1616 /// during the processing of a C++ class whose member functions have
1617 /// default arguments, e.g.,
1621 /// void f(int x = 17); // x has an unparsed default argument now
1622 /// }; // x has a regular default argument now
1624 bool hasUnparsedDefaultArg() const {
1625 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1628 bool hasUninstantiatedDefaultArg() const {
1629 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1632 /// setUnparsedDefaultArg - Specify that this parameter has an
1633 /// unparsed default argument. The argument will be replaced with a
1634 /// real default argument via setDefaultArg when the class
1635 /// definition enclosing the function declaration that owns this
1636 /// default argument is completed.
1637 void setUnparsedDefaultArg() {
1638 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1641 bool hasInheritedDefaultArg() const {
1642 return ParmVarDeclBits.HasInheritedDefaultArg;
1645 void setHasInheritedDefaultArg(bool I = true) {
1646 ParmVarDeclBits.HasInheritedDefaultArg = I;
1649 QualType getOriginalType() const;
1651 /// \brief Determine whether this parameter is actually a function
1653 bool isParameterPack() const;
1655 /// setOwningFunction - Sets the function declaration that owns this
1656 /// ParmVarDecl. Since ParmVarDecls are often created before the
1657 /// FunctionDecls that own them, this routine is required to update
1658 /// the DeclContext appropriately.
1659 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1661 // Implement isa/cast/dyncast/etc.
1662 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1663 static bool classofKind(Kind K) { return K == ParmVar; }
1666 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1668 void setParameterIndex(unsigned parameterIndex) {
1669 if (parameterIndex >= ParameterIndexSentinel) {
1670 setParameterIndexLarge(parameterIndex);
1674 ParmVarDeclBits.ParameterIndex = parameterIndex;
1675 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1677 unsigned getParameterIndex() const {
1678 unsigned d = ParmVarDeclBits.ParameterIndex;
1679 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1682 void setParameterIndexLarge(unsigned parameterIndex);
1683 unsigned getParameterIndexLarge() const;
1686 /// An instance of this class is created to represent a function declaration or
1689 /// Since a given function can be declared several times in a program,
1690 /// there may be several FunctionDecls that correspond to that
1691 /// function. Only one of those FunctionDecls will be found when
1692 /// traversing the list of declarations in the context of the
1693 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1694 /// contains all of the information known about the function. Other,
1695 /// previous declarations of the function are available via the
1696 /// getPreviousDecl() chain.
1697 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1698 public Redeclarable<FunctionDecl> {
1700 /// \brief The kind of templated function a FunctionDecl can be.
1701 enum TemplatedKind {
1703 TK_FunctionTemplate,
1704 TK_MemberSpecialization,
1705 TK_FunctionTemplateSpecialization,
1706 TK_DependentFunctionTemplateSpecialization
1710 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1711 /// parameters of this function. This is null if a prototype or if there are
1713 ParmVarDecl **ParamInfo = nullptr;
1715 LazyDeclStmtPtr Body;
1717 // FIXME: This can be packed into the bitfields in DeclContext.
1718 // NOTE: VC++ packs bitfields poorly if the types differ.
1719 unsigned SClass : 3;
1720 unsigned IsInline : 1;
1721 unsigned IsInlineSpecified : 1;
1724 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1725 // CXXDeductionGuideDecl.
1726 unsigned IsExplicitSpecified : 1;
1729 unsigned IsVirtualAsWritten : 1;
1730 unsigned IsPure : 1;
1731 unsigned HasInheritedPrototype : 1;
1732 unsigned HasWrittenPrototype : 1;
1733 unsigned IsDeleted : 1;
1734 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1735 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1736 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1737 unsigned HasImplicitReturnZero : 1;
1738 unsigned IsLateTemplateParsed : 1;
1739 unsigned IsConstexpr : 1;
1740 unsigned InstantiationIsPending : 1;
1742 /// \brief Indicates if the function uses __try.
1743 unsigned UsesSEHTry : 1;
1745 /// \brief Indicates if the function was a definition but its body was
1747 unsigned HasSkippedBody : 1;
1749 /// Indicates if the function declaration will have a body, once we're done
1751 unsigned WillHaveBody : 1;
1754 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1755 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1756 /// int as opposed to adding a single bit to FunctionDecl.
1757 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1758 /// deduction candidate' (is used during overload resolution).
1759 unsigned IsCopyDeductionCandidate : 1;
1763 /// Store the ODRHash after first calculation.
1764 unsigned HasODRHash : 1;
1767 /// \brief End part of this FunctionDecl's source range.
1769 /// We could compute the full range in getSourceRange(). However, when we're
1770 /// dealing with a function definition deserialized from a PCH/AST file,
1771 /// we can only compute the full range once the function body has been
1772 /// de-serialized, so it's far better to have the (sometimes-redundant)
1774 SourceLocation EndRangeLoc;
1776 /// \brief The template or declaration that this declaration
1777 /// describes or was instantiated from, respectively.
1779 /// For non-templates, this value will be NULL. For function
1780 /// declarations that describe a function template, this will be a
1781 /// pointer to a FunctionTemplateDecl. For member functions
1782 /// of class template specializations, this will be a MemberSpecializationInfo
1783 /// pointer containing information about the specialization.
1784 /// For function template specializations, this will be a
1785 /// FunctionTemplateSpecializationInfo, which contains information about
1786 /// the template being specialized and the template arguments involved in
1787 /// that specialization.
1788 llvm::PointerUnion4<FunctionTemplateDecl *,
1789 MemberSpecializationInfo *,
1790 FunctionTemplateSpecializationInfo *,
1791 DependentFunctionTemplateSpecializationInfo *>
1792 TemplateOrSpecialization;
1794 /// Provides source/type location info for the declaration name embedded in
1795 /// the DeclaratorDecl base class.
1796 DeclarationNameLoc DNLoc;
1798 /// \brief Specify that this function declaration is actually a function
1799 /// template specialization.
1801 /// \param C the ASTContext.
1803 /// \param Template the function template that this function template
1804 /// specialization specializes.
1806 /// \param TemplateArgs the template arguments that produced this
1807 /// function template specialization from the template.
1809 /// \param InsertPos If non-NULL, the position in the function template
1810 /// specialization set where the function template specialization data will
1813 /// \param TSK the kind of template specialization this is.
1815 /// \param TemplateArgsAsWritten location info of template arguments.
1817 /// \param PointOfInstantiation point at which the function template
1818 /// specialization was first instantiated.
1819 void setFunctionTemplateSpecialization(ASTContext &C,
1820 FunctionTemplateDecl *Template,
1821 const TemplateArgumentList *TemplateArgs,
1823 TemplateSpecializationKind TSK,
1824 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1825 SourceLocation PointOfInstantiation);
1827 /// \brief Specify that this record is an instantiation of the
1828 /// member function FD.
1829 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1830 TemplateSpecializationKind TSK);
1832 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1835 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1836 const DeclarationNameInfo &NameInfo, QualType T,
1837 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1838 bool isConstexprSpecified)
1839 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1841 DeclContext(DK), redeclarable_base(C), SClass(S),
1842 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1843 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1844 HasInheritedPrototype(false), HasWrittenPrototype(true),
1845 IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1846 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1847 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1848 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1849 WillHaveBody(false), IsCopyDeductionCandidate(false), HasODRHash(false),
1850 ODRHash(0), EndRangeLoc(NameInfo.getEndLoc()),
1851 DNLoc(NameInfo.getInfo()) {}
1853 using redeclarable_base = Redeclarable<FunctionDecl>;
1855 FunctionDecl *getNextRedeclarationImpl() override {
1856 return getNextRedeclaration();
1859 FunctionDecl *getPreviousDeclImpl() override {
1860 return getPreviousDecl();
1863 FunctionDecl *getMostRecentDeclImpl() override {
1864 return getMostRecentDecl();
1868 friend class ASTDeclReader;
1869 friend class ASTDeclWriter;
1871 using redecl_range = redeclarable_base::redecl_range;
1872 using redecl_iterator = redeclarable_base::redecl_iterator;
1874 using redeclarable_base::redecls_begin;
1875 using redeclarable_base::redecls_end;
1876 using redeclarable_base::redecls;
1877 using redeclarable_base::getPreviousDecl;
1878 using redeclarable_base::getMostRecentDecl;
1879 using redeclarable_base::isFirstDecl;
1881 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1882 SourceLocation StartLoc, SourceLocation NLoc,
1883 DeclarationName N, QualType T,
1884 TypeSourceInfo *TInfo,
1886 bool isInlineSpecified = false,
1887 bool hasWrittenPrototype = true,
1888 bool isConstexprSpecified = false) {
1889 DeclarationNameInfo NameInfo(N, NLoc);
1890 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1892 isInlineSpecified, hasWrittenPrototype,
1893 isConstexprSpecified);
1896 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1897 SourceLocation StartLoc,
1898 const DeclarationNameInfo &NameInfo,
1899 QualType T, TypeSourceInfo *TInfo,
1901 bool isInlineSpecified,
1902 bool hasWrittenPrototype,
1903 bool isConstexprSpecified = false);
1905 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1907 DeclarationNameInfo getNameInfo() const {
1908 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1911 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1912 bool Qualified) const override;
1914 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1916 SourceRange getSourceRange() const override LLVM_READONLY;
1918 /// \brief Returns true if the function has a body (definition). The
1919 /// function body might be in any of the (re-)declarations of this
1920 /// function. The variant that accepts a FunctionDecl pointer will
1921 /// set that function declaration to the actual declaration
1922 /// containing the body (if there is one).
1923 bool hasBody(const FunctionDecl *&Definition) const;
1925 bool hasBody() const override {
1926 const FunctionDecl* Definition;
1927 return hasBody(Definition);
1930 /// Returns whether the function has a trivial body that does not require any
1931 /// specific codegen.
1932 bool hasTrivialBody() const;
1934 /// Returns true if the function is defined at all, including a deleted
1935 /// definition. Except for the behavior when the function is deleted, behaves
1937 bool isDefined(const FunctionDecl *&Definition) const;
1939 virtual bool isDefined() const {
1940 const FunctionDecl* Definition;
1941 return isDefined(Definition);
1944 /// \brief Get the definition for this declaration.
1945 FunctionDecl *getDefinition() {
1946 const FunctionDecl *Definition;
1947 if (isDefined(Definition))
1948 return const_cast<FunctionDecl *>(Definition);
1951 const FunctionDecl *getDefinition() const {
1952 return const_cast<FunctionDecl *>(this)->getDefinition();
1955 /// Retrieve the body (definition) of the function. The function body might be
1956 /// in any of the (re-)declarations of this function. The variant that accepts
1957 /// a FunctionDecl pointer will set that function declaration to the actual
1958 /// declaration containing the body (if there is one).
1959 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1960 /// unnecessary AST de-serialization of the body.
1961 Stmt *getBody(const FunctionDecl *&Definition) const;
1963 Stmt *getBody() const override {
1964 const FunctionDecl* Definition;
1965 return getBody(Definition);
1968 /// Returns whether this specific declaration of the function is also a
1969 /// definition that does not contain uninstantiated body.
1971 /// This does not determine whether the function has been defined (e.g., in a
1972 /// previous definition); for that information, use isDefined.
1973 bool isThisDeclarationADefinition() const {
1974 return IsDeleted || IsDefaulted || Body || HasSkippedBody ||
1975 IsLateTemplateParsed || WillHaveBody || hasDefiningAttr();
1978 /// Returns whether this specific declaration of the function has a body -
1979 /// that is, if it is a non-deleted definition.
1980 bool doesThisDeclarationHaveABody() const {
1981 return Body || IsLateTemplateParsed;
1984 void setBody(Stmt *B);
1985 void setLazyBody(uint64_t Offset) { Body = Offset; }
1987 /// Whether this function is variadic.
1988 bool isVariadic() const;
1990 /// Whether this function is marked as virtual explicitly.
1991 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1992 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1994 /// Whether this virtual function is pure, i.e. makes the containing class
1996 bool isPure() const { return IsPure; }
1997 void setPure(bool P = true);
1999 /// Whether this templated function will be late parsed.
2000 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
2001 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
2003 /// Whether this function is "trivial" in some specialized C++ senses.
2004 /// Can only be true for default constructors, copy constructors,
2005 /// copy assignment operators, and destructors. Not meaningful until
2006 /// the class has been fully built by Sema.
2007 bool isTrivial() const { return IsTrivial; }
2008 void setTrivial(bool IT) { IsTrivial = IT; }
2010 /// Whether this function is defaulted per C++0x. Only valid for
2011 /// special member functions.
2012 bool isDefaulted() const { return IsDefaulted; }
2013 void setDefaulted(bool D = true) { IsDefaulted = D; }
2015 /// Whether this function is explicitly defaulted per C++0x. Only valid
2016 /// for special member functions.
2017 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2018 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2020 /// Whether falling off this function implicitly returns null/zero.
2021 /// If a more specific implicit return value is required, front-ends
2022 /// should synthesize the appropriate return statements.
2023 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2024 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2026 /// \brief Whether this function has a prototype, either because one
2027 /// was explicitly written or because it was "inherited" by merging
2028 /// a declaration without a prototype with a declaration that has a
2030 bool hasPrototype() const {
2031 return HasWrittenPrototype || HasInheritedPrototype;
2034 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2036 /// \brief Whether this function inherited its prototype from a
2037 /// previous declaration.
2038 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2039 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2041 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2042 bool isConstexpr() const { return IsConstexpr; }
2043 void setConstexpr(bool IC) { IsConstexpr = IC; }
2045 /// \brief Whether the instantiation of this function is pending.
2046 /// This bit is set when the decision to instantiate this function is made
2047 /// and unset if and when the function body is created. That leaves out
2048 /// cases where instantiation did not happen because the template definition
2049 /// was not seen in this TU. This bit remains set in those cases, under the
2050 /// assumption that the instantiation will happen in some other TU.
2051 bool instantiationIsPending() const { return InstantiationIsPending; }
2052 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2054 /// \brief Indicates the function uses __try.
2055 bool usesSEHTry() const { return UsesSEHTry; }
2056 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2058 /// \brief Whether this function has been deleted.
2060 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2061 /// acts like a normal function, except that it cannot actually be
2062 /// called or have its address taken. Deleted functions are
2063 /// typically used in C++ overload resolution to attract arguments
2064 /// whose type or lvalue/rvalue-ness would permit the use of a
2065 /// different overload that would behave incorrectly. For example,
2066 /// one might use deleted functions to ban implicit conversion from
2067 /// a floating-point number to an Integer type:
2070 /// struct Integer {
2071 /// Integer(long); // construct from a long
2072 /// Integer(double) = delete; // no construction from float or double
2073 /// Integer(long double) = delete; // no construction from long double
2076 // If a function is deleted, its first declaration must be.
2077 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2078 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2079 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2081 /// \brief Determines whether this function is "main", which is the
2082 /// entry point into an executable program.
2083 bool isMain() const;
2085 /// \brief Determines whether this function is a MSVCRT user defined entry
2087 bool isMSVCRTEntryPoint() const;
2089 /// \brief Determines whether this operator new or delete is one
2090 /// of the reserved global placement operators:
2091 /// void *operator new(size_t, void *);
2092 /// void *operator new[](size_t, void *);
2093 /// void operator delete(void *, void *);
2094 /// void operator delete[](void *, void *);
2095 /// These functions have special behavior under [new.delete.placement]:
2096 /// These functions are reserved, a C++ program may not define
2097 /// functions that displace the versions in the Standard C++ library.
2098 /// The provisions of [basic.stc.dynamic] do not apply to these
2099 /// reserved placement forms of operator new and operator delete.
2101 /// This function must be an allocation or deallocation function.
2102 bool isReservedGlobalPlacementOperator() const;
2104 /// \brief Determines whether this function is one of the replaceable
2105 /// global allocation functions:
2106 /// void *operator new(size_t);
2107 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2108 /// void *operator new[](size_t);
2109 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2110 /// void operator delete(void *) noexcept;
2111 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2112 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2113 /// void operator delete[](void *) noexcept;
2114 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2115 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2116 /// These functions have special behavior under C++1y [expr.new]:
2117 /// An implementation is allowed to omit a call to a replaceable global
2118 /// allocation function. [...]
2120 /// If this function is an aligned allocation/deallocation function, return
2121 /// true through IsAligned.
2122 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2124 /// \brief Determine whether this is a destroying operator delete.
2125 bool isDestroyingOperatorDelete() const;
2127 /// Compute the language linkage.
2128 LanguageLinkage getLanguageLinkage() const;
2130 /// \brief Determines whether this function is a function with
2131 /// external, C linkage.
2132 bool isExternC() const;
2134 /// \brief Determines whether this function's context is, or is nested within,
2135 /// a C++ extern "C" linkage spec.
2136 bool isInExternCContext() const;
2138 /// \brief Determines whether this function's context is, or is nested within,
2139 /// a C++ extern "C++" linkage spec.
2140 bool isInExternCXXContext() const;
2142 /// \brief Determines whether this is a global function.
2143 bool isGlobal() const;
2145 /// \brief Determines whether this function is known to be 'noreturn', through
2146 /// an attribute on its declaration or its type.
2147 bool isNoReturn() const;
2149 /// \brief True if the function was a definition but its body was skipped.
2150 bool hasSkippedBody() const { return HasSkippedBody; }
2151 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2153 /// True if this function will eventually have a body, once it's fully parsed.
2154 bool willHaveBody() const { return WillHaveBody; }
2155 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2157 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2159 FunctionDecl *getCanonicalDecl() override;
2160 const FunctionDecl *getCanonicalDecl() const {
2161 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2164 unsigned getBuiltinID() const;
2166 // ArrayRef interface to parameters.
2167 ArrayRef<ParmVarDecl *> parameters() const {
2168 return {ParamInfo, getNumParams()};
2170 MutableArrayRef<ParmVarDecl *> parameters() {
2171 return {ParamInfo, getNumParams()};
2174 // Iterator access to formal parameters.
2175 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2176 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2178 bool param_empty() const { return parameters().empty(); }
2179 param_iterator param_begin() { return parameters().begin(); }
2180 param_iterator param_end() { return parameters().end(); }
2181 param_const_iterator param_begin() const { return parameters().begin(); }
2182 param_const_iterator param_end() const { return parameters().end(); }
2183 size_t param_size() const { return parameters().size(); }
2185 /// Return the number of parameters this function must have based on its
2186 /// FunctionType. This is the length of the ParamInfo array after it has been
2188 unsigned getNumParams() const;
2190 const ParmVarDecl *getParamDecl(unsigned i) const {
2191 assert(i < getNumParams() && "Illegal param #");
2192 return ParamInfo[i];
2194 ParmVarDecl *getParamDecl(unsigned i) {
2195 assert(i < getNumParams() && "Illegal param #");
2196 return ParamInfo[i];
2198 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2199 setParams(getASTContext(), NewParamInfo);
2202 /// Returns the minimum number of arguments needed to call this function. This
2203 /// may be fewer than the number of function parameters, if some of the
2204 /// parameters have default arguments (in C++).
2205 unsigned getMinRequiredArguments() const;
2207 QualType getReturnType() const {
2208 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2209 return getType()->getAs<FunctionType>()->getReturnType();
2212 /// \brief Attempt to compute an informative source range covering the
2213 /// function return type. This may omit qualifiers and other information with
2214 /// limited representation in the AST.
2215 SourceRange getReturnTypeSourceRange() const;
2217 /// \brief Attempt to compute an informative source range covering the
2218 /// function exception specification, if any.
2219 SourceRange getExceptionSpecSourceRange() const;
2221 /// \brief Determine the type of an expression that calls this function.
2222 QualType getCallResultType() const {
2223 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2224 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2227 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2228 /// function, or its return type declaration.
2229 const Attr *getUnusedResultAttr() const;
2231 /// \brief Returns true if this function or its return type has the
2232 /// warn_unused_result attribute.
2233 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2235 /// \brief Returns the storage class as written in the source. For the
2236 /// computed linkage of symbol, see getLinkage.
2237 StorageClass getStorageClass() const { return StorageClass(SClass); }
2239 /// \brief Determine whether the "inline" keyword was specified for this
2241 bool isInlineSpecified() const { return IsInlineSpecified; }
2243 /// Set whether the "inline" keyword was specified for this function.
2244 void setInlineSpecified(bool I) {
2245 IsInlineSpecified = I;
2249 /// Flag that this function is implicitly inline.
2250 void setImplicitlyInline() {
2254 /// \brief Determine whether this function should be inlined, because it is
2255 /// either marked "inline" or "constexpr" or is a member function of a class
2256 /// that was defined in the class body.
2257 bool isInlined() const { return IsInline; }
2259 bool isInlineDefinitionExternallyVisible() const;
2261 bool isMSExternInline() const;
2263 bool doesDeclarationForceExternallyVisibleDefinition() const;
2265 /// isOverloadedOperator - Whether this function declaration
2266 /// represents an C++ overloaded operator, e.g., "operator+".
2267 bool isOverloadedOperator() const {
2268 return getOverloadedOperator() != OO_None;
2271 OverloadedOperatorKind getOverloadedOperator() const;
2273 const IdentifierInfo *getLiteralIdentifier() const;
2275 /// \brief If this function is an instantiation of a member function
2276 /// of a class template specialization, retrieves the function from
2277 /// which it was instantiated.
2279 /// This routine will return non-NULL for (non-templated) member
2280 /// functions of class templates and for instantiations of function
2281 /// templates. For example, given:
2284 /// template<typename T>
2290 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2291 /// whose parent is the class template specialization X<int>. For
2292 /// this declaration, getInstantiatedFromFunction() will return
2293 /// the FunctionDecl X<T>::A. When a complete definition of
2294 /// X<int>::A is required, it will be instantiated from the
2295 /// declaration returned by getInstantiatedFromMemberFunction().
2296 FunctionDecl *getInstantiatedFromMemberFunction() const;
2298 /// \brief What kind of templated function this is.
2299 TemplatedKind getTemplatedKind() const;
2301 /// \brief If this function is an instantiation of a member function of a
2302 /// class template specialization, retrieves the member specialization
2304 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2306 /// \brief Specify that this record is an instantiation of the
2307 /// member function FD.
2308 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2309 TemplateSpecializationKind TSK) {
2310 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2313 /// \brief Retrieves the function template that is described by this
2314 /// function declaration.
2316 /// Every function template is represented as a FunctionTemplateDecl
2317 /// and a FunctionDecl (or something derived from FunctionDecl). The
2318 /// former contains template properties (such as the template
2319 /// parameter lists) while the latter contains the actual
2320 /// description of the template's
2321 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2322 /// FunctionDecl that describes the function template,
2323 /// getDescribedFunctionTemplate() retrieves the
2324 /// FunctionTemplateDecl from a FunctionDecl.
2325 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2327 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2329 /// \brief Determine whether this function is a function template
2331 bool isFunctionTemplateSpecialization() const {
2332 return getPrimaryTemplate() != nullptr;
2335 /// \brief Retrieve the class scope template pattern that this function
2336 /// template specialization is instantiated from.
2337 FunctionDecl *getClassScopeSpecializationPattern() const;
2339 /// \brief If this function is actually a function template specialization,
2340 /// retrieve information about this function template specialization.
2341 /// Otherwise, returns NULL.
2342 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2344 /// \brief Determines whether this function is a function template
2345 /// specialization or a member of a class template specialization that can
2346 /// be implicitly instantiated.
2347 bool isImplicitlyInstantiable() const;
2349 /// \brief Determines if the given function was instantiated from a
2350 /// function template.
2351 bool isTemplateInstantiation() const;
2353 /// \brief Retrieve the function declaration from which this function could
2354 /// be instantiated, if it is an instantiation (rather than a non-template
2355 /// or a specialization, for example).
2356 FunctionDecl *getTemplateInstantiationPattern() const;
2358 /// \brief Retrieve the primary template that this function template
2359 /// specialization either specializes or was instantiated from.
2361 /// If this function declaration is not a function template specialization,
2363 FunctionTemplateDecl *getPrimaryTemplate() const;
2365 /// \brief Retrieve the template arguments used to produce this function
2366 /// template specialization from the primary template.
2368 /// If this function declaration is not a function template specialization,
2370 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2372 /// \brief Retrieve the template argument list as written in the sources,
2375 /// If this function declaration is not a function template specialization
2376 /// or if it had no explicit template argument list, returns NULL.
2377 /// Note that it an explicit template argument list may be written empty,
2378 /// e.g., template<> void foo<>(char* s);
2379 const ASTTemplateArgumentListInfo*
2380 getTemplateSpecializationArgsAsWritten() const;
2382 /// \brief Specify that this function declaration is actually a function
2383 /// template specialization.
2385 /// \param Template the function template that this function template
2386 /// specialization specializes.
2388 /// \param TemplateArgs the template arguments that produced this
2389 /// function template specialization from the template.
2391 /// \param InsertPos If non-NULL, the position in the function template
2392 /// specialization set where the function template specialization data will
2395 /// \param TSK the kind of template specialization this is.
2397 /// \param TemplateArgsAsWritten location info of template arguments.
2399 /// \param PointOfInstantiation point at which the function template
2400 /// specialization was first instantiated.
2401 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2402 const TemplateArgumentList *TemplateArgs,
2404 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2405 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2406 SourceLocation PointOfInstantiation = SourceLocation()) {
2407 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2408 InsertPos, TSK, TemplateArgsAsWritten,
2409 PointOfInstantiation);
2412 /// \brief Specifies that this function declaration is actually a
2413 /// dependent function template specialization.
2414 void setDependentTemplateSpecialization(ASTContext &Context,
2415 const UnresolvedSetImpl &Templates,
2416 const TemplateArgumentListInfo &TemplateArgs);
2418 DependentFunctionTemplateSpecializationInfo *
2419 getDependentSpecializationInfo() const;
2421 /// \brief Determine what kind of template instantiation this function
2423 TemplateSpecializationKind getTemplateSpecializationKind() const;
2425 /// \brief Determine what kind of template instantiation this function
2427 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2428 SourceLocation PointOfInstantiation = SourceLocation());
2430 /// \brief Retrieve the (first) point of instantiation of a function template
2431 /// specialization or a member of a class template specialization.
2433 /// \returns the first point of instantiation, if this function was
2434 /// instantiated from a template; otherwise, returns an invalid source
2436 SourceLocation getPointOfInstantiation() const;
2438 /// \brief Determine whether this is or was instantiated from an out-of-line
2439 /// definition of a member function.
2440 bool isOutOfLine() const override;
2442 /// \brief Identify a memory copying or setting function.
2443 /// If the given function is a memory copy or setting function, returns
2444 /// the corresponding Builtin ID. If the function is not a memory function,
2446 unsigned getMemoryFunctionKind() const;
2448 /// \brief Returns ODRHash of the function. This value is calculated and
2449 /// stored on first call, then the stored value returned on the other calls.
2450 unsigned getODRHash();
2452 // Implement isa/cast/dyncast/etc.
2453 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2454 static bool classofKind(Kind K) {
2455 return K >= firstFunction && K <= lastFunction;
2457 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2458 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2460 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2461 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2465 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2466 /// represent a member of a struct/union/class.
2467 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2468 unsigned BitField : 1;
2469 unsigned Mutable : 1;
2470 mutable unsigned CachedFieldIndex : 30;
2472 /// The kinds of value we can store in InitializerOrBitWidth.
2474 /// Note that this is compatible with InClassInitStyle except for
2475 /// ISK_CapturedVLAType.
2476 enum InitStorageKind {
2477 /// If the pointer is null, there's nothing special. Otherwise,
2478 /// this is a bitfield and the pointer is the Expr* storing the
2480 ISK_NoInit = (unsigned) ICIS_NoInit,
2482 /// The pointer is an (optional due to delayed parsing) Expr*
2483 /// holding the copy-initializer.
2484 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2486 /// The pointer is an (optional due to delayed parsing) Expr*
2487 /// holding the list-initializer.
2488 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2490 /// The pointer is a VariableArrayType* that's been captured;
2491 /// the enclosing context is a lambda or captured statement.
2492 ISK_CapturedVLAType,
2495 /// If this is a bitfield with a default member initializer, this
2496 /// structure is used to represent the two expressions.
2497 struct InitAndBitWidth {
2502 /// \brief Storage for either the bit-width, the in-class initializer, or
2503 /// both (via InitAndBitWidth), or the captured variable length array bound.
2505 /// If the storage kind is ISK_InClassCopyInit or
2506 /// ISK_InClassListInit, but the initializer is null, then this
2507 /// field has an in-class initializer that has not yet been parsed
2509 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2510 // overwhelmingly common case that we have none of these things.
2511 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2514 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2515 SourceLocation IdLoc, IdentifierInfo *Id,
2516 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2517 InClassInitStyle InitStyle)
2518 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2519 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2520 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2526 friend class ASTDeclReader;
2527 friend class ASTDeclWriter;
2529 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2530 SourceLocation StartLoc, SourceLocation IdLoc,
2531 IdentifierInfo *Id, QualType T,
2532 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2533 InClassInitStyle InitStyle);
2535 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2537 /// getFieldIndex - Returns the index of this field within its record,
2538 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2539 unsigned getFieldIndex() const;
2541 /// isMutable - Determines whether this field is mutable (C++ only).
2542 bool isMutable() const { return Mutable; }
2544 /// \brief Determines whether this field is a bitfield.
2545 bool isBitField() const { return BitField; }
2547 /// @brief Determines whether this is an unnamed bitfield.
2548 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2550 /// isAnonymousStructOrUnion - Determines whether this field is a
2551 /// representative for an anonymous struct or union. Such fields are
2552 /// unnamed and are implicitly generated by the implementation to
2553 /// store the data for the anonymous union or struct.
2554 bool isAnonymousStructOrUnion() const;
2556 Expr *getBitWidth() const {
2559 void *Ptr = InitStorage.getPointer();
2560 if (getInClassInitStyle())
2561 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2562 return static_cast<Expr*>(Ptr);
2565 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2567 /// setBitWidth - Set the bit-field width for this member.
2568 // Note: used by some clients (i.e., do not remove it).
2569 void setBitWidth(Expr *Width) {
2570 assert(!hasCapturedVLAType() && !BitField &&
2571 "bit width or captured type already set");
2572 assert(Width && "no bit width specified");
2573 InitStorage.setPointer(
2574 InitStorage.getInt()
2575 ? new (getASTContext())
2576 InitAndBitWidth{getInClassInitializer(), Width}
2577 : static_cast<void*>(Width));
2581 /// removeBitWidth - Remove the bit-field width from this member.
2582 // Note: used by some clients (i.e., do not remove it).
2583 void removeBitWidth() {
2584 assert(isBitField() && "no bitfield width to remove");
2585 InitStorage.setPointer(getInClassInitializer());
2589 /// Get the kind of (C++11) default member initializer that this field has.
2590 InClassInitStyle getInClassInitStyle() const {
2591 InitStorageKind storageKind = InitStorage.getInt();
2592 return (storageKind == ISK_CapturedVLAType
2593 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2596 /// Determine whether this member has a C++11 default member initializer.
2597 bool hasInClassInitializer() const {
2598 return getInClassInitStyle() != ICIS_NoInit;
2601 /// Get the C++11 default member initializer for this member, or null if one
2602 /// has not been set. If a valid declaration has a default member initializer,
2603 /// but this returns null, then we have not parsed and attached it yet.
2604 Expr *getInClassInitializer() const {
2605 if (!hasInClassInitializer())
2607 void *Ptr = InitStorage.getPointer();
2609 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2610 return static_cast<Expr*>(Ptr);
2613 /// setInClassInitializer - Set the C++11 in-class initializer for this
2615 void setInClassInitializer(Expr *Init) {
2616 assert(hasInClassInitializer() && !getInClassInitializer());
2618 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2620 InitStorage.setPointer(Init);
2623 /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2625 void removeInClassInitializer() {
2626 assert(hasInClassInitializer() && "no initializer to remove");
2627 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2630 /// \brief Determine whether this member captures the variable length array
2632 bool hasCapturedVLAType() const {
2633 return InitStorage.getInt() == ISK_CapturedVLAType;
2636 /// \brief Get the captured variable length array type.
2637 const VariableArrayType *getCapturedVLAType() const {
2638 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2639 InitStorage.getPointer())
2643 /// \brief Set the captured variable length array type for this field.
2644 void setCapturedVLAType(const VariableArrayType *VLAType);
2646 /// getParent - Returns the parent of this field declaration, which
2647 /// is the struct in which this field is defined.
2648 const RecordDecl *getParent() const {
2649 return cast<RecordDecl>(getDeclContext());
2652 RecordDecl *getParent() {
2653 return cast<RecordDecl>(getDeclContext());
2656 SourceRange getSourceRange() const override LLVM_READONLY;
2658 /// Retrieves the canonical declaration of this field.
2659 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2660 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2662 // Implement isa/cast/dyncast/etc.
2663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2664 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2667 /// EnumConstantDecl - An instance of this object exists for each enum constant
2668 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2669 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2670 /// TagType for the X EnumDecl.
2671 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2672 Stmt *Init; // an integer constant expression
2673 llvm::APSInt Val; // The value.
2676 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2677 IdentifierInfo *Id, QualType T, Expr *E,
2678 const llvm::APSInt &V)
2679 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2682 friend class StmtIteratorBase;
2684 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2685 SourceLocation L, IdentifierInfo *Id,
2686 QualType T, Expr *E,
2687 const llvm::APSInt &V);
2688 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2690 const Expr *getInitExpr() const { return (const Expr*) Init; }
2691 Expr *getInitExpr() { return (Expr*) Init; }
2692 const llvm::APSInt &getInitVal() const { return Val; }
2694 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2695 void setInitVal(const llvm::APSInt &V) { Val = V; }
2697 SourceRange getSourceRange() const override LLVM_READONLY;
2699 /// Retrieves the canonical declaration of this enumerator.
2700 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2701 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2703 // Implement isa/cast/dyncast/etc.
2704 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2705 static bool classofKind(Kind K) { return K == EnumConstant; }
2708 /// IndirectFieldDecl - An instance of this class is created to represent a
2709 /// field injected from an anonymous union/struct into the parent scope.
2710 /// IndirectFieldDecl are always implicit.
2711 class IndirectFieldDecl : public ValueDecl,
2712 public Mergeable<IndirectFieldDecl> {
2713 NamedDecl **Chaining;
2714 unsigned ChainingSize;
2716 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2717 DeclarationName N, QualType T,
2718 MutableArrayRef<NamedDecl *> CH);
2720 void anchor() override;
2723 friend class ASTDeclReader;
2725 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2726 SourceLocation L, IdentifierInfo *Id,
2727 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2729 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2731 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2733 ArrayRef<NamedDecl *> chain() const {
2734 return llvm::makeArrayRef(Chaining, ChainingSize);
2736 chain_iterator chain_begin() const { return chain().begin(); }
2737 chain_iterator chain_end() const { return chain().end(); }
2739 unsigned getChainingSize() const { return ChainingSize; }
2741 FieldDecl *getAnonField() const {
2742 assert(chain().size() >= 2);
2743 return cast<FieldDecl>(chain().back());
2746 VarDecl *getVarDecl() const {
2747 assert(chain().size() >= 2);
2748 return dyn_cast<VarDecl>(chain().front());
2751 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2752 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2754 // Implement isa/cast/dyncast/etc.
2755 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2756 static bool classofKind(Kind K) { return K == IndirectField; }
2759 /// TypeDecl - Represents a declaration of a type.
2760 class TypeDecl : public NamedDecl {
2761 friend class ASTContext;
2763 /// TypeForDecl - This indicates the Type object that represents
2764 /// this TypeDecl. It is a cache maintained by
2765 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2766 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2767 mutable const Type *TypeForDecl = nullptr;
2769 /// LocStart - The start of the source range for this declaration.
2770 SourceLocation LocStart;
2772 void anchor() override;
2775 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2776 SourceLocation StartL = SourceLocation())
2777 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2780 // Low-level accessor. If you just want the type defined by this node,
2781 // check out ASTContext::getTypeDeclType or one of
2782 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2783 // already know the specific kind of node this is.
2784 const Type *getTypeForDecl() const { return TypeForDecl; }
2785 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2787 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2788 void setLocStart(SourceLocation L) { LocStart = L; }
2789 SourceRange getSourceRange() const override LLVM_READONLY {
2790 if (LocStart.isValid())
2791 return SourceRange(LocStart, getLocation());
2793 return SourceRange(getLocation());
2796 // Implement isa/cast/dyncast/etc.
2797 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2798 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2801 /// Base class for declarations which introduce a typedef-name.
2802 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2803 using ModedTInfo = std::pair<TypeSourceInfo *, QualType>;
2804 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *> MaybeModedTInfo;
2806 // FIXME: This can be packed into the bitfields in Decl.
2807 /// If 0, we have not computed IsTransparentTag.
2808 /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
2809 mutable unsigned CacheIsTransparentTag : 2;
2811 void anchor() override;
2814 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2815 SourceLocation StartLoc, SourceLocation IdLoc,
2816 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2817 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2818 MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
2820 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2822 TypedefNameDecl *getNextRedeclarationImpl() override {
2823 return getNextRedeclaration();
2826 TypedefNameDecl *getPreviousDeclImpl() override {
2827 return getPreviousDecl();
2830 TypedefNameDecl *getMostRecentDeclImpl() override {
2831 return getMostRecentDecl();
2835 using redecl_range = redeclarable_base::redecl_range;
2836 using redecl_iterator = redeclarable_base::redecl_iterator;
2838 using redeclarable_base::redecls_begin;
2839 using redeclarable_base::redecls_end;
2840 using redeclarable_base::redecls;
2841 using redeclarable_base::getPreviousDecl;
2842 using redeclarable_base::getMostRecentDecl;
2843 using redeclarable_base::isFirstDecl;
2845 bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2847 TypeSourceInfo *getTypeSourceInfo() const {
2849 ? MaybeModedTInfo.get<ModedTInfo*>()->first
2850 : MaybeModedTInfo.get<TypeSourceInfo*>();
2853 QualType getUnderlyingType() const {
2855 ? MaybeModedTInfo.get<ModedTInfo*>()->second
2856 : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2859 void setTypeSourceInfo(TypeSourceInfo *newType) {
2860 MaybeModedTInfo = newType;
2863 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2864 MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2867 /// Retrieves the canonical declaration of this typedef-name.
2868 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2869 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2871 /// Retrieves the tag declaration for which this is the typedef name for
2872 /// linkage purposes, if any.
2874 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2875 /// this typedef declaration.
2876 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2878 /// Determines if this typedef shares a name and spelling location with its
2879 /// underlying tag type, as is the case with the NS_ENUM macro.
2880 bool isTransparentTag() const {
2881 if (CacheIsTransparentTag)
2882 return CacheIsTransparentTag & 0x2;
2883 return isTransparentTagSlow();
2886 // Implement isa/cast/dyncast/etc.
2887 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2888 static bool classofKind(Kind K) {
2889 return K >= firstTypedefName && K <= lastTypedefName;
2893 bool isTransparentTagSlow() const;
2896 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2898 class TypedefDecl : public TypedefNameDecl {
2899 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2900 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2901 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2904 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2905 SourceLocation StartLoc, SourceLocation IdLoc,
2906 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2907 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2909 SourceRange getSourceRange() const override LLVM_READONLY;
2911 // Implement isa/cast/dyncast/etc.
2912 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2913 static bool classofKind(Kind K) { return K == Typedef; }
2916 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2917 /// alias-declaration.
2918 class TypeAliasDecl : public TypedefNameDecl {
2919 /// The template for which this is the pattern, if any.
2920 TypeAliasTemplateDecl *Template;
2922 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2923 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2924 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2925 Template(nullptr) {}
2928 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2929 SourceLocation StartLoc, SourceLocation IdLoc,
2930 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2931 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2933 SourceRange getSourceRange() const override LLVM_READONLY;
2935 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2936 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2938 // Implement isa/cast/dyncast/etc.
2939 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2940 static bool classofKind(Kind K) { return K == TypeAlias; }
2943 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2945 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2947 // This is really ugly.
2948 using TagKind = TagTypeKind;
2951 // FIXME: This can be packed into the bitfields in Decl.
2952 /// TagDeclKind - The TagKind enum.
2953 unsigned TagDeclKind : 3;
2955 /// IsCompleteDefinition - True if this is a definition ("struct foo
2956 /// {};"), false if it is a declaration ("struct foo;"). It is not
2957 /// a definition until the definition has been fully processed.
2958 unsigned IsCompleteDefinition : 1;
2961 /// IsBeingDefined - True if this is currently being defined.
2962 unsigned IsBeingDefined : 1;
2965 /// IsEmbeddedInDeclarator - True if this tag declaration is
2966 /// "embedded" (i.e., defined or declared for the very first time)
2967 /// in the syntax of a declarator.
2968 unsigned IsEmbeddedInDeclarator : 1;
2970 /// \brief True if this tag is free standing, e.g. "struct foo;".
2971 unsigned IsFreeStanding : 1;
2974 // These are used by (and only defined for) EnumDecl.
2975 unsigned NumPositiveBits : 8;
2976 unsigned NumNegativeBits : 8;
2978 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2979 /// possible in C++11 mode.
2980 unsigned IsScoped : 1;
2982 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2983 /// then this is true if the scoped enum was declared using the class
2984 /// tag, false if it was declared with the struct tag. No meaning is
2985 /// associated if this tag declaration is not a scoped enum.
2986 unsigned IsScopedUsingClassTag : 1;
2988 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2989 /// possible in C++11, Microsoft extensions, or Objective C mode.
2990 unsigned IsFixed : 1;
2992 /// \brief Indicates whether it is possible for declarations of this kind
2993 /// to have an out-of-date definition.
2995 /// This option is only enabled when modules are enabled.
2996 unsigned MayHaveOutOfDateDef : 1;
2998 /// Has the full definition of this type been required by a use somewhere in
3000 unsigned IsCompleteDefinitionRequired : 1;
3003 SourceRange BraceRange;
3005 // A struct representing syntactic qualifier info,
3006 // to be used for the (uncommon) case of out-of-line declarations.
3007 using ExtInfo = QualifierInfo;
3009 /// \brief If the (out-of-line) tag declaration name
3010 /// is qualified, it points to the qualifier info (nns and range);
3011 /// otherwise, if the tag declaration is anonymous and it is part of
3012 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3013 /// otherwise, if the tag declaration is anonymous and it is used as a
3014 /// declaration specifier for variables, it points to the first VarDecl (used
3016 /// otherwise, it is a null (TypedefNameDecl) pointer.
3017 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3019 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3020 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3021 const ExtInfo *getExtInfo() const {
3022 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3026 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3027 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3028 SourceLocation StartL)
3029 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3030 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
3031 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
3032 IsCompleteDefinitionRequired(false),
3033 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3034 assert((DK != Enum || TK == TTK_Enum) &&
3035 "EnumDecl not matched with TTK_Enum");
3036 setPreviousDecl(PrevDecl);
3039 using redeclarable_base = Redeclarable<TagDecl>;
3041 TagDecl *getNextRedeclarationImpl() override {
3042 return getNextRedeclaration();
3045 TagDecl *getPreviousDeclImpl() override {
3046 return getPreviousDecl();
3049 TagDecl *getMostRecentDeclImpl() override {
3050 return getMostRecentDecl();
3053 /// @brief Completes the definition of this tag declaration.
3055 /// This is a helper function for derived classes.
3056 void completeDefinition();
3059 friend class ASTDeclReader;
3060 friend class ASTDeclWriter;
3062 using redecl_range = redeclarable_base::redecl_range;
3063 using redecl_iterator = redeclarable_base::redecl_iterator;
3065 using redeclarable_base::redecls_begin;
3066 using redeclarable_base::redecls_end;
3067 using redeclarable_base::redecls;
3068 using redeclarable_base::getPreviousDecl;
3069 using redeclarable_base::getMostRecentDecl;
3070 using redeclarable_base::isFirstDecl;
3072 SourceRange getBraceRange() const { return BraceRange; }
3073 void setBraceRange(SourceRange R) { BraceRange = R; }
3075 /// getInnerLocStart - Return SourceLocation representing start of source
3076 /// range ignoring outer template declarations.
3077 SourceLocation getInnerLocStart() const { return getLocStart(); }
3079 /// getOuterLocStart - Return SourceLocation representing start of source
3080 /// range taking into account any outer template declarations.
3081 SourceLocation getOuterLocStart() const;
3082 SourceRange getSourceRange() const override LLVM_READONLY;
3084 TagDecl *getCanonicalDecl() override;
3085 const TagDecl *getCanonicalDecl() const {
3086 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3089 /// isThisDeclarationADefinition() - Return true if this declaration
3090 /// is a completion definition of the type. Provided for consistency.
3091 bool isThisDeclarationADefinition() const {
3092 return isCompleteDefinition();
3095 /// isCompleteDefinition - Return true if this decl has its body
3096 /// fully specified.
3097 bool isCompleteDefinition() const {
3098 return IsCompleteDefinition;
3101 /// \brief Return true if this complete decl is
3102 /// required to be complete for some existing use.
3103 bool isCompleteDefinitionRequired() const {
3104 return IsCompleteDefinitionRequired;
3107 /// isBeingDefined - Return true if this decl is currently being defined.
3108 bool isBeingDefined() const {
3109 return IsBeingDefined;
3112 bool isEmbeddedInDeclarator() const {
3113 return IsEmbeddedInDeclarator;
3115 void setEmbeddedInDeclarator(bool isInDeclarator) {
3116 IsEmbeddedInDeclarator = isInDeclarator;
3119 bool isFreeStanding() const { return IsFreeStanding; }
3120 void setFreeStanding(bool isFreeStanding = true) {
3121 IsFreeStanding = isFreeStanding;
3124 /// \brief Whether this declaration declares a type that is
3125 /// dependent, i.e., a type that somehow depends on template
3127 bool isDependentType() const { return isDependentContext(); }
3129 /// @brief Starts the definition of this tag declaration.
3131 /// This method should be invoked at the beginning of the definition
3132 /// of this tag declaration. It will set the tag type into a state
3133 /// where it is in the process of being defined.
3134 void startDefinition();
3136 /// getDefinition - Returns the TagDecl that actually defines this
3137 /// struct/union/class/enum. When determining whether or not a
3138 /// struct/union/class/enum has a definition, one should use this
3139 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3140 /// whether or not a specific TagDecl is defining declaration, not
3141 /// whether or not the struct/union/class/enum type is defined.
3142 /// This method returns NULL if there is no TagDecl that defines
3143 /// the struct/union/class/enum.
3144 TagDecl *getDefinition() const;
3146 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
3148 void setCompleteDefinitionRequired(bool V = true) {
3149 IsCompleteDefinitionRequired = V;
3152 StringRef getKindName() const {
3153 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3156 TagKind getTagKind() const {
3157 return TagKind(TagDeclKind);
3160 void setTagKind(TagKind TK) { TagDeclKind = TK; }
3162 bool isStruct() const { return getTagKind() == TTK_Struct; }
3163 bool isInterface() const { return getTagKind() == TTK_Interface; }
3164 bool isClass() const { return getTagKind() == TTK_Class; }
3165 bool isUnion() const { return getTagKind() == TTK_Union; }
3166 bool isEnum() const { return getTagKind() == TTK_Enum; }
3168 /// Is this tag type named, either directly or via being defined in
3169 /// a typedef of this type?
3171 /// C++11 [basic.link]p8:
3172 /// A type is said to have linkage if and only if:
3173 /// - it is a class or enumeration type that is named (or has a
3174 /// name for linkage purposes) and the name has linkage; ...
3175 /// C++11 [dcl.typedef]p9:
3176 /// If the typedef declaration defines an unnamed class (or enum),
3177 /// the first typedef-name declared by the declaration to be that
3178 /// class type (or enum type) is used to denote the class type (or
3179 /// enum type) for linkage purposes only.
3181 /// C does not have an analogous rule, but the same concept is
3182 /// nonetheless useful in some places.
3183 bool hasNameForLinkage() const {
3184 return (getDeclName() || getTypedefNameForAnonDecl());
3187 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3188 return hasExtInfo() ? nullptr
3189 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3192 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3194 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3195 /// declaration, if it was present in the source.
3196 NestedNameSpecifier *getQualifier() const {
3197 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3201 /// \brief Retrieve the nested-name-specifier (with source-location
3202 /// information) that qualifies the name of this declaration, if it was
3203 /// present in the source.
3204 NestedNameSpecifierLoc getQualifierLoc() const {
3205 return hasExtInfo() ? getExtInfo()->QualifierLoc
3206 : NestedNameSpecifierLoc();
3209 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3211 unsigned getNumTemplateParameterLists() const {
3212 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3215 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3216 assert(i < getNumTemplateParameterLists());
3217 return getExtInfo()->TemplParamLists[i];
3220 void setTemplateParameterListsInfo(ASTContext &Context,
3221 ArrayRef<TemplateParameterList *> TPLists);
3223 // Implement isa/cast/dyncast/etc.
3224 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3225 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3227 static DeclContext *castToDeclContext(const TagDecl *D) {
3228 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3231 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3232 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3236 /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
3237 /// with a fixed underlying type, and in C we allow them to be forward-declared
3238 /// with no underlying type as an extension.
3239 class EnumDecl : public TagDecl {
3240 /// IntegerType - This represent the integer type that the enum corresponds
3241 /// to for code generation purposes. Note that the enumerator constants may
3242 /// have a different type than this does.
3244 /// If the underlying integer type was explicitly stated in the source
3245 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3246 /// was automatically deduced somehow, and this is a Type*.
3248 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3249 /// some cases it won't.
3251 /// The underlying type of an enumeration never has any qualifiers, so
3252 /// we can get away with just storing a raw Type*, and thus save an
3253 /// extra pointer when TypeSourceInfo is needed.
3254 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3256 /// PromotionType - The integer type that values of this type should
3257 /// promote to. In C, enumerators are generally of an integer type
3258 /// directly, but gcc-style large enumerators (and all enumerators
3259 /// in C++) are of the enum type instead.
3260 QualType PromotionType;
3262 /// \brief If this enumeration is an instantiation of a member enumeration
3263 /// of a class template specialization, this is the member specialization
3265 MemberSpecializationInfo *SpecializationInfo = nullptr;
3267 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3268 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3269 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3270 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3271 assert(Scoped || !ScopedUsingClassTag);
3272 IntegerType = (const Type *)nullptr;
3273 NumNegativeBits = 0;
3274 NumPositiveBits = 0;
3276 IsScopedUsingClassTag = ScopedUsingClassTag;
3280 void anchor() override;
3282 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3283 TemplateSpecializationKind TSK);
3285 friend class ASTDeclReader;
3287 EnumDecl *getCanonicalDecl() override {
3288 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3290 const EnumDecl *getCanonicalDecl() const {
3291 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3294 EnumDecl *getPreviousDecl() {
3295 return cast_or_null<EnumDecl>(
3296 static_cast<TagDecl *>(this)->getPreviousDecl());
3298 const EnumDecl *getPreviousDecl() const {
3299 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3302 EnumDecl *getMostRecentDecl() {
3303 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3305 const EnumDecl *getMostRecentDecl() const {
3306 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3309 EnumDecl *getDefinition() const {
3310 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3313 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3314 SourceLocation StartLoc, SourceLocation IdLoc,
3315 IdentifierInfo *Id, EnumDecl *PrevDecl,
3316 bool IsScoped, bool IsScopedUsingClassTag,
3318 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3320 /// completeDefinition - When created, the EnumDecl corresponds to a
3321 /// forward-declared enum. This method is used to mark the
3322 /// declaration as being defined; it's enumerators have already been
3323 /// added (via DeclContext::addDecl). NewType is the new underlying
3324 /// type of the enumeration type.
3325 void completeDefinition(QualType NewType,
3326 QualType PromotionType,
3327 unsigned NumPositiveBits,
3328 unsigned NumNegativeBits);
3330 // enumerator_iterator - Iterates through the enumerators of this
3332 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3333 using enumerator_range =
3334 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3336 enumerator_range enumerators() const {
3337 return enumerator_range(enumerator_begin(), enumerator_end());
3340 enumerator_iterator enumerator_begin() const {
3341 const EnumDecl *E = getDefinition();
3344 return enumerator_iterator(E->decls_begin());
3347 enumerator_iterator enumerator_end() const {
3348 const EnumDecl *E = getDefinition();
3351 return enumerator_iterator(E->decls_end());
3354 /// getPromotionType - Return the integer type that enumerators
3355 /// should promote to.
3356 QualType getPromotionType() const { return PromotionType; }
3358 /// \brief Set the promotion type.
3359 void setPromotionType(QualType T) { PromotionType = T; }
3361 /// getIntegerType - Return the integer type this enum decl corresponds to.
3362 /// This returns a null QualType for an enum forward definition with no fixed
3363 /// underlying type.
3364 QualType getIntegerType() const {
3367 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3368 return QualType(T, 0);
3369 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3372 /// \brief Set the underlying integer type.
3373 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3375 /// \brief Set the underlying integer type source info.
3376 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3378 /// \brief Return the type source info for the underlying integer type,
3379 /// if no type source info exists, return 0.
3380 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3381 return IntegerType.dyn_cast<TypeSourceInfo*>();
3384 /// \brief Retrieve the source range that covers the underlying type if
3386 SourceRange getIntegerTypeRange() const LLVM_READONLY;
3388 /// \brief Returns the width in bits required to store all the
3389 /// non-negative enumerators of this enum.
3390 unsigned getNumPositiveBits() const {
3391 return NumPositiveBits;
3393 void setNumPositiveBits(unsigned Num) {
3394 NumPositiveBits = Num;
3395 assert(NumPositiveBits == Num && "can't store this bitcount");
3398 /// \brief Returns the width in bits required to store all the
3399 /// negative enumerators of this enum. These widths include
3400 /// the rightmost leading 1; that is:
3402 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3403 /// ------------------------ ------- -----------------
3407 unsigned getNumNegativeBits() const {
3408 return NumNegativeBits;
3410 void setNumNegativeBits(unsigned Num) {
3411 NumNegativeBits = Num;
3414 /// \brief Returns true if this is a C++11 scoped enumeration.
3415 bool isScoped() const {
3419 /// \brief Returns true if this is a C++11 scoped enumeration.
3420 bool isScopedUsingClassTag() const {
3421 return IsScopedUsingClassTag;
3424 /// \brief Returns true if this is an Objective-C, C++11, or
3425 /// Microsoft-style enumeration with a fixed underlying type.
3426 bool isFixed() const {
3430 /// \brief Returns true if this can be considered a complete type.
3431 bool isComplete() const {
3432 return isCompleteDefinition() || isFixed();
3435 /// Returns true if this enum is either annotated with
3436 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3437 bool isClosed() const;
3439 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3440 /// with enum_extensibility(open).
3441 bool isClosedFlag() const;
3443 /// Returns true if this enum is annotated with neither flag_enum nor
3444 /// enum_extensibility(open).
3445 bool isClosedNonFlag() const;
3447 /// \brief Retrieve the enum definition from which this enumeration could
3448 /// be instantiated, if it is an instantiation (rather than a non-template).
3449 EnumDecl *getTemplateInstantiationPattern() const;
3451 /// \brief Returns the enumeration (declared within the template)
3452 /// from which this enumeration type was instantiated, or NULL if
3453 /// this enumeration was not instantiated from any template.
3454 EnumDecl *getInstantiatedFromMemberEnum() const;
3456 /// \brief If this enumeration is a member of a specialization of a
3457 /// templated class, determine what kind of template specialization
3458 /// or instantiation this is.
3459 TemplateSpecializationKind getTemplateSpecializationKind() const;
3461 /// \brief For an enumeration member that was instantiated from a member
3462 /// enumeration of a templated class, set the template specialiation kind.
3463 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3464 SourceLocation PointOfInstantiation = SourceLocation());
3466 /// \brief If this enumeration is an instantiation of a member enumeration of
3467 /// a class template specialization, retrieves the member specialization
3469 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3470 return SpecializationInfo;
3473 /// \brief Specify that this enumeration is an instantiation of the
3474 /// member enumeration ED.
3475 void setInstantiationOfMemberEnum(EnumDecl *ED,
3476 TemplateSpecializationKind TSK) {
3477 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3480 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3481 static bool classofKind(Kind K) { return K == Enum; }
3484 /// RecordDecl - Represents a struct/union/class. For example:
3485 /// struct X; // Forward declaration, no "body".
3486 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3487 /// This decl will be marked invalid if *any* members are invalid.
3488 class RecordDecl : public TagDecl {
3489 friend class DeclContext;
3491 // FIXME: This can be packed into the bitfields in Decl.
3492 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3493 /// array member (e.g. int X[]) or if this union contains a struct that does.
3494 /// If so, this cannot be contained in arrays or other structs as a member.
3495 bool HasFlexibleArrayMember : 1;
3497 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3499 bool AnonymousStructOrUnion : 1;
3501 /// HasObjectMember - This is true if this struct has at least one member
3502 /// containing an Objective-C object pointer type.
3503 bool HasObjectMember : 1;
3505 /// HasVolatileMember - This is true if struct has at least one member of
3506 /// 'volatile' type.
3507 bool HasVolatileMember : 1;
3509 /// \brief Whether the field declarations of this record have been loaded
3510 /// from external storage. To avoid unnecessary deserialization of
3511 /// methods/nested types we allow deserialization of just the fields
3513 mutable bool LoadedFieldsFromExternalStorage : 1;
3516 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3517 SourceLocation StartLoc, SourceLocation IdLoc,
3518 IdentifierInfo *Id, RecordDecl *PrevDecl);
3521 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3522 SourceLocation StartLoc, SourceLocation IdLoc,
3523 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3524 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3526 RecordDecl *getPreviousDecl() {
3527 return cast_or_null<RecordDecl>(
3528 static_cast<TagDecl *>(this)->getPreviousDecl());
3530 const RecordDecl *getPreviousDecl() const {
3531 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3534 RecordDecl *getMostRecentDecl() {
3535 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3537 const RecordDecl *getMostRecentDecl() const {
3538 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3541 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3542 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3544 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3545 /// or union. To be an anonymous struct or union, it must have been
3546 /// declared without a name and there must be no objects of this
3547 /// type declared, e.g.,
3549 /// union { int i; float f; };
3551 /// is an anonymous union but neither of the following are:
3553 /// union X { int i; float f; };
3554 /// union { int i; float f; } obj;
3556 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3557 void setAnonymousStructOrUnion(bool Anon) {
3558 AnonymousStructOrUnion = Anon;
3561 bool hasObjectMember() const { return HasObjectMember; }
3562 void setHasObjectMember (bool val) { HasObjectMember = val; }
3564 bool hasVolatileMember() const { return HasVolatileMember; }
3565 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3567 bool hasLoadedFieldsFromExternalStorage() const {
3568 return LoadedFieldsFromExternalStorage;
3570 void setHasLoadedFieldsFromExternalStorage(bool val) {
3571 LoadedFieldsFromExternalStorage = val;
3574 /// \brief Determines whether this declaration represents the
3575 /// injected class name.
3577 /// The injected class name in C++ is the name of the class that
3578 /// appears inside the class itself. For example:
3582 /// // C is implicitly declared here as a synonym for the class name.
3585 /// C::C c; // same as "C c;"
3587 bool isInjectedClassName() const;
3589 /// \brief Determine whether this record is a class describing a lambda
3590 /// function object.
3591 bool isLambda() const;
3593 /// \brief Determine whether this record is a record for captured variables in
3594 /// CapturedStmt construct.
3595 bool isCapturedRecord() const;
3597 /// \brief Mark the record as a record for captured variables in CapturedStmt
3599 void setCapturedRecord();
3601 /// getDefinition - Returns the RecordDecl that actually defines
3602 /// this struct/union/class. When determining whether or not a
3603 /// struct/union/class is completely defined, one should use this
3604 /// method as opposed to 'isCompleteDefinition'.
3605 /// 'isCompleteDefinition' indicates whether or not a specific
3606 /// RecordDecl is a completed definition, not whether or not the
3607 /// record type is defined. This method returns NULL if there is
3608 /// no RecordDecl that defines the struct/union/tag.
3609 RecordDecl *getDefinition() const {
3610 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3613 // Iterator access to field members. The field iterator only visits
3614 // the non-static data members of this class, ignoring any static
3615 // data members, functions, constructors, destructors, etc.
3616 using field_iterator = specific_decl_iterator<FieldDecl>;
3617 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3619 field_range fields() const { return field_range(field_begin(), field_end()); }
3620 field_iterator field_begin() const;
3622 field_iterator field_end() const {
3623 return field_iterator(decl_iterator());
3626 // field_empty - Whether there are any fields (non-static data
3627 // members) in this record.
3628 bool field_empty() const {
3629 return field_begin() == field_end();
3632 /// completeDefinition - Notes that the definition of this type is
3634 virtual void completeDefinition();
3636 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3637 static bool classofKind(Kind K) {
3638 return K >= firstRecord && K <= lastRecord;
3641 /// \brief Get whether or not this is an ms_struct which can
3642 /// be turned on with an attribute, pragma, or -mms-bitfields
3643 /// commandline option.
3644 bool isMsStruct(const ASTContext &C) const;
3646 /// \brief Whether we are allowed to insert extra padding between fields.
3647 /// These padding are added to help AddressSanitizer detect
3648 /// intra-object-overflow bugs.
3649 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3651 /// Finds the first data member which has a name.
3652 /// nullptr is returned if no named data member exists.
3653 const FieldDecl *findFirstNamedDataMember() const;
3656 /// \brief Deserialize just the fields.
3657 void LoadFieldsFromExternalStorage() const;
3660 class FileScopeAsmDecl : public Decl {
3661 StringLiteral *AsmString;
3662 SourceLocation RParenLoc;
3664 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3665 SourceLocation StartL, SourceLocation EndL)
3666 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3668 virtual void anchor();
3671 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3672 StringLiteral *Str, SourceLocation AsmLoc,
3673 SourceLocation RParenLoc);
3675 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3677 SourceLocation getAsmLoc() const { return getLocation(); }
3678 SourceLocation getRParenLoc() const { return RParenLoc; }
3679 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3680 SourceRange getSourceRange() const override LLVM_READONLY {
3681 return SourceRange(getAsmLoc(), getRParenLoc());
3684 const StringLiteral *getAsmString() const { return AsmString; }
3685 StringLiteral *getAsmString() { return AsmString; }
3686 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3688 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3689 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3692 /// BlockDecl - This represents a block literal declaration, which is like an
3693 /// unnamed FunctionDecl. For example:
3694 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3695 class BlockDecl : public Decl, public DeclContext {
3697 /// A class which contains all the information about a particular
3705 /// The variable being captured.
3706 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3708 /// The copy expression, expressed in terms of a DeclRef (or
3709 /// BlockDeclRef) to the captured variable. Only required if the
3710 /// variable has a C++ class type.
3714 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3715 : VariableAndFlags(variable,
3716 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3719 /// The variable being captured.
3720 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3722 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3724 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3726 /// Whether this is a nested capture, i.e. the variable captured
3727 /// is not from outside the immediately enclosing function/block.
3728 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3730 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3731 Expr *getCopyExpr() const { return CopyExpr; }
3732 void setCopyExpr(Expr *e) { CopyExpr = e; }
3736 // FIXME: This can be packed into the bitfields in Decl.
3737 bool IsVariadic : 1;
3738 bool CapturesCXXThis : 1;
3739 bool BlockMissingReturnType : 1;
3740 bool IsConversionFromLambda : 1;
3742 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3743 /// parameters of this function. This is null if a prototype or if there are
3745 ParmVarDecl **ParamInfo = nullptr;
3746 unsigned NumParams = 0;
3748 Stmt *Body = nullptr;
3749 TypeSourceInfo *SignatureAsWritten = nullptr;
3751 const Capture *Captures = nullptr;
3752 unsigned NumCaptures = 0;
3754 unsigned ManglingNumber = 0;
3755 Decl *ManglingContextDecl = nullptr;
3758 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3759 : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false),
3760 CapturesCXXThis(false), BlockMissingReturnType(true),
3761 IsConversionFromLambda(false) {}
3764 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3765 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3767 SourceLocation getCaretLocation() const { return getLocation(); }
3769 bool isVariadic() const { return IsVariadic; }
3770 void setIsVariadic(bool value) { IsVariadic = value; }
3772 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3773 Stmt *getBody() const override { return (Stmt*) Body; }
3774 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3776 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3777 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3779 // ArrayRef access to formal parameters.
3780 ArrayRef<ParmVarDecl *> parameters() const {
3781 return {ParamInfo, getNumParams()};
3783 MutableArrayRef<ParmVarDecl *> parameters() {
3784 return {ParamInfo, getNumParams()};
3787 // Iterator access to formal parameters.
3788 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3789 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3791 bool param_empty() const { return parameters().empty(); }
3792 param_iterator param_begin() { return parameters().begin(); }
3793 param_iterator param_end() { return parameters().end(); }
3794 param_const_iterator param_begin() const { return parameters().begin(); }
3795 param_const_iterator param_end() const { return parameters().end(); }
3796 size_t param_size() const { return parameters().size(); }
3798 unsigned getNumParams() const { return NumParams; }
3800 const ParmVarDecl *getParamDecl(unsigned i) const {
3801 assert(i < getNumParams() && "Illegal param #");
3802 return ParamInfo[i];
3804 ParmVarDecl *getParamDecl(unsigned i) {
3805 assert(i < getNumParams() && "Illegal param #");
3806 return ParamInfo[i];
3809 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3811 /// hasCaptures - True if this block (or its nested blocks) captures
3812 /// anything of local storage from its enclosing scopes.
3813 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3815 /// getNumCaptures - Returns the number of captured variables.
3816 /// Does not include an entry for 'this'.
3817 unsigned getNumCaptures() const { return NumCaptures; }
3819 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3821 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3823 capture_const_iterator capture_begin() const { return captures().begin(); }
3824 capture_const_iterator capture_end() const { return captures().end(); }
3826 bool capturesCXXThis() const { return CapturesCXXThis; }
3827 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3828 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3830 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3831 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3833 bool capturesVariable(const VarDecl *var) const;
3835 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3836 bool CapturesCXXThis);
3838 unsigned getBlockManglingNumber() const {
3839 return ManglingNumber;
3842 Decl *getBlockManglingContextDecl() const {
3843 return ManglingContextDecl;
3846 void setBlockMangling(unsigned Number, Decl *Ctx) {
3847 ManglingNumber = Number;
3848 ManglingContextDecl = Ctx;
3851 SourceRange getSourceRange() const override LLVM_READONLY;
3853 // Implement isa/cast/dyncast/etc.
3854 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3855 static bool classofKind(Kind K) { return K == Block; }
3856 static DeclContext *castToDeclContext(const BlockDecl *D) {
3857 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3859 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3860 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3864 /// \brief This represents the body of a CapturedStmt, and serves as its
3866 class CapturedDecl final
3869 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3871 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3876 /// \brief The number of parameters to the outlined function.
3879 /// \brief The position of context parameter in list of parameters.
3880 unsigned ContextParam;
3882 /// \brief The body of the outlined function.
3883 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3885 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3887 ImplicitParamDecl *const *getParams() const {
3888 return getTrailingObjects<ImplicitParamDecl *>();
3891 ImplicitParamDecl **getParams() {
3892 return getTrailingObjects<ImplicitParamDecl *>();
3896 friend class ASTDeclReader;
3897 friend class ASTDeclWriter;
3898 friend TrailingObjects;
3900 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3901 unsigned NumParams);
3902 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3903 unsigned NumParams);
3905 Stmt *getBody() const override;
3906 void setBody(Stmt *B);
3908 bool isNothrow() const;
3909 void setNothrow(bool Nothrow = true);
3911 unsigned getNumParams() const { return NumParams; }
3913 ImplicitParamDecl *getParam(unsigned i) const {
3914 assert(i < NumParams);
3915 return getParams()[i];
3917 void setParam(unsigned i, ImplicitParamDecl *P) {
3918 assert(i < NumParams);
3922 // ArrayRef interface to parameters.
3923 ArrayRef<ImplicitParamDecl *> parameters() const {
3924 return {getParams(), getNumParams()};
3926 MutableArrayRef<ImplicitParamDecl *> parameters() {
3927 return {getParams(), getNumParams()};
3930 /// \brief Retrieve the parameter containing captured variables.
3931 ImplicitParamDecl *getContextParam() const {
3932 assert(ContextParam < NumParams);
3933 return getParam(ContextParam);
3935 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3936 assert(i < NumParams);
3940 unsigned getContextParamPosition() const { return ContextParam; }
3942 using param_iterator = ImplicitParamDecl *const *;
3943 using param_range = llvm::iterator_range<param_iterator>;
3945 /// \brief Retrieve an iterator pointing to the first parameter decl.
3946 param_iterator param_begin() const { return getParams(); }
3947 /// \brief Retrieve an iterator one past the last parameter decl.
3948 param_iterator param_end() const { return getParams() + NumParams; }
3950 // Implement isa/cast/dyncast/etc.
3951 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3952 static bool classofKind(Kind K) { return K == Captured; }
3953 static DeclContext *castToDeclContext(const CapturedDecl *D) {
3954 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3956 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3957 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3961 /// \brief Describes a module import declaration, which makes the contents
3962 /// of the named module visible in the current translation unit.
3964 /// An import declaration imports the named module (or submodule). For example:
3966 /// @import std.vector;
3969 /// Import declarations can also be implicitly generated from
3970 /// \#include/\#import directives.
3971 class ImportDecl final : public Decl,
3972 llvm::TrailingObjects<ImportDecl, SourceLocation> {
3973 friend class ASTContext;
3974 friend class ASTDeclReader;
3975 friend class ASTReader;
3976 friend TrailingObjects;
3978 /// \brief The imported module, along with a bit that indicates whether
3979 /// we have source-location information for each identifier in the module
3982 /// When the bit is false, we only have a single source location for the
3983 /// end of the import declaration.
3984 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3986 /// \brief The next import in the list of imports local to the translation
3987 /// unit being parsed (not loaded from an AST file).
3988 ImportDecl *NextLocalImport = nullptr;
3990 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3991 ArrayRef<SourceLocation> IdentifierLocs);
3993 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3994 SourceLocation EndLoc);
3996 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
3999 /// \brief Create a new module import declaration.
4000 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4001 SourceLocation StartLoc, Module *Imported,
4002 ArrayRef<SourceLocation> IdentifierLocs);
4004 /// \brief Create a new module import declaration for an implicitly-generated
4006 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4007 SourceLocation StartLoc, Module *Imported,
4008 SourceLocation EndLoc);
4010 /// \brief Create a new, deserialized module import declaration.
4011 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4012 unsigned NumLocations);
4014 /// \brief Retrieve the module that was imported by the import declaration.
4015 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4017 /// \brief Retrieves the locations of each of the identifiers that make up
4018 /// the complete module name in the import declaration.
4020 /// This will return an empty array if the locations of the individual
4021 /// identifiers aren't available.
4022 ArrayRef<SourceLocation> getIdentifierLocs() const;
4024 SourceRange getSourceRange() const override LLVM_READONLY;
4026 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4027 static bool classofKind(Kind K) { return K == Import; }
4030 /// \brief Represents a C++ Modules TS module export declaration.
4034 /// export void foo();
4036 class ExportDecl final : public Decl, public DeclContext {
4037 virtual void anchor();
4040 friend class ASTDeclReader;
4042 /// \brief The source location for the right brace (if valid).
4043 SourceLocation RBraceLoc;
4045 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4046 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4047 RBraceLoc(SourceLocation()) {}
4050 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4051 SourceLocation ExportLoc);
4052 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4054 SourceLocation getExportLoc() const { return getLocation(); }
4055 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4056 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4058 SourceLocation getLocEnd() const LLVM_READONLY {
4059 if (RBraceLoc.isValid())
4061 // No braces: get the end location of the (only) declaration in context
4063 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
4066 SourceRange getSourceRange() const override LLVM_READONLY {
4067 return SourceRange(getLocation(), getLocEnd());
4070 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4071 static bool classofKind(Kind K) { return K == Export; }
4072 static DeclContext *castToDeclContext(const ExportDecl *D) {
4073 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4075 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4076 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4080 /// \brief Represents an empty-declaration.
4081 class EmptyDecl : public Decl {
4082 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4084 virtual void anchor();
4087 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4089 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4091 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4092 static bool classofKind(Kind K) { return K == Empty; }
4095 /// Insertion operator for diagnostics. This allows sending NamedDecl's
4096 /// into a diagnostic with <<.
4097 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4098 const NamedDecl* ND) {
4099 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4100 DiagnosticsEngine::ak_nameddecl);
4103 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4104 const NamedDecl* ND) {
4105 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4106 DiagnosticsEngine::ak_nameddecl);
4110 template<typename decl_type>
4111 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4112 // Note: This routine is implemented here because we need both NamedDecl
4113 // and Redeclarable to be defined.
4114 assert(RedeclLink.NextIsLatest() &&
4115 "setPreviousDecl on a decl already in a redeclaration chain");
4118 // Point to previous. Make sure that this is actually the most recent
4119 // redeclaration, or we can build invalid chains. If the most recent
4120 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4121 First = PrevDecl->getFirstDecl();
4122 assert(First->RedeclLink.NextIsLatest() && "Expected first");
4123 decl_type *MostRecent = First->getNextRedeclaration();
4124 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4126 // If the declaration was previously visible, a redeclaration of it remains
4127 // visible even if it wouldn't be visible by itself.
4128 static_cast<decl_type*>(this)->IdentifierNamespace |=
4129 MostRecent->getIdentifierNamespace() &
4130 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4133 First = static_cast<decl_type*>(this);
4136 // First one will point to this one as latest.
4137 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4139 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
4140 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
4143 // Inline function definitions.
4145 /// \brief Check if the given decl is complete.
4147 /// We use this function to break a cycle between the inline definitions in
4148 /// Type.h and Decl.h.
4149 inline bool IsEnumDeclComplete(EnumDecl *ED) {
4150 return ED->isComplete();
4153 /// \brief Check if the given decl is scoped.
4155 /// We use this function to break a cycle between the inline definitions in
4156 /// Type.h and Decl.h.
4157 inline bool IsEnumDeclScoped(EnumDecl *ED) {
4158 return ED->isScoped();
4161 } // namespace clang
4163 #endif // LLVM_CLANG_AST_DECL_H