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/Redeclarable.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/Linkage.h"
24 #include "clang/Basic/Module.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/PragmaKinds.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/TrailingObjects.h"
34 struct ASTTemplateArgumentListInfo;
37 class DependentFunctionTemplateSpecializationInfo;
39 class FunctionTemplateDecl;
40 class FunctionTemplateSpecializationInfo;
42 class MemberSpecializationInfo;
43 class NestedNameSpecifier;
47 class TemplateArgumentList;
48 class TemplateParameterList;
49 class TypeAliasTemplateDecl;
51 class UnresolvedSetImpl;
52 class VarTemplateDecl;
54 /// \brief A container of type source information.
56 /// A client can read the relevant info using TypeLoc wrappers, e.g:
58 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
59 /// TL.getStartLoc().print(OS, SrcMgr);
62 class TypeSourceInfo {
64 // Contains a memory block after the class, used for type source information,
65 // allocated by ASTContext.
66 friend class ASTContext;
67 TypeSourceInfo(QualType ty) : Ty(ty) { }
69 /// \brief Return the type wrapped by this type source info.
70 QualType getType() const { return Ty; }
72 /// \brief Return the TypeLoc wrapper for the type source info.
73 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
75 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
76 void overrideType(QualType T) { Ty = T; }
79 /// TranslationUnitDecl - The top declaration context.
80 class TranslationUnitDecl : public Decl, public DeclContext {
81 virtual void anchor();
84 /// The (most recently entered) anonymous namespace for this
85 /// translation unit, if one has been created.
86 NamespaceDecl *AnonymousNamespace;
88 explicit TranslationUnitDecl(ASTContext &ctx);
90 ASTContext &getASTContext() const { return Ctx; }
92 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
93 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
95 static TranslationUnitDecl *Create(ASTContext &C);
96 // Implement isa/cast/dyncast/etc.
97 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
98 static bool classofKind(Kind K) { return K == TranslationUnit; }
99 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
100 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
102 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
103 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
107 /// \brief Represents a `#pragma comment` line. Always a child of
108 /// TranslationUnitDecl.
109 class PragmaCommentDecl final
111 private llvm::TrailingObjects<PragmaCommentDecl, char> {
112 virtual void anchor();
114 PragmaMSCommentKind CommentKind;
116 friend TrailingObjects;
117 friend class ASTDeclReader;
118 friend class ASTDeclWriter;
120 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
121 PragmaMSCommentKind CommentKind)
122 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
125 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
126 SourceLocation CommentLoc,
127 PragmaMSCommentKind CommentKind,
129 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
132 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
134 StringRef getArg() const { return getTrailingObjects<char>(); }
136 // Implement isa/cast/dyncast/etc.
137 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
138 static bool classofKind(Kind K) { return K == PragmaComment; }
141 /// \brief Represents a `#pragma detect_mismatch` line. Always a child of
142 /// TranslationUnitDecl.
143 class PragmaDetectMismatchDecl final
145 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
146 virtual void anchor();
150 friend TrailingObjects;
151 friend class ASTDeclReader;
152 friend class ASTDeclWriter;
154 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
156 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
159 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
160 TranslationUnitDecl *DC,
161 SourceLocation Loc, StringRef Name,
163 static PragmaDetectMismatchDecl *
164 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
166 StringRef getName() const { return getTrailingObjects<char>(); }
167 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
169 // Implement isa/cast/dyncast/etc.
170 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
171 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
174 /// \brief Declaration context for names declared as extern "C" in C++. This
175 /// is neither the semantic nor lexical context for such declarations, but is
176 /// used to check for conflicts with other extern "C" declarations. Example:
179 /// namespace N { extern "C" void f(); } // #1
180 /// void N::f() {} // #2
181 /// namespace M { extern "C" void f(); } // #3
184 /// The semantic context of #1 is namespace N and its lexical context is the
185 /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
186 /// context is the TU. However, both declarations are also visible in the
187 /// extern "C" context.
189 /// The declaration at #3 finds it is a redeclaration of \c N::f through
190 /// lookup in the extern "C" context.
191 class ExternCContextDecl : public Decl, public DeclContext {
192 virtual void anchor();
194 explicit ExternCContextDecl(TranslationUnitDecl *TU)
195 : Decl(ExternCContext, TU, SourceLocation()),
196 DeclContext(ExternCContext) {}
198 static ExternCContextDecl *Create(const ASTContext &C,
199 TranslationUnitDecl *TU);
200 // Implement isa/cast/dyncast/etc.
201 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
202 static bool classofKind(Kind K) { return K == ExternCContext; }
203 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
204 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
206 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
207 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
211 /// NamedDecl - This represents a decl with a name. Many decls have names such
212 /// as ObjCMethodDecl, but not \@class, etc.
213 class NamedDecl : public Decl {
214 virtual void anchor();
215 /// Name - The name of this declaration, which is typically a normal
216 /// identifier but may also be a special kind of name (C++
217 /// constructor, Objective-C selector, etc.)
218 DeclarationName Name;
221 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
224 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
225 : Decl(DK, DC, L), Name(N) { }
228 /// getIdentifier - Get the identifier that names this declaration,
229 /// if there is one. This will return NULL if this declaration has
230 /// no name (e.g., for an unnamed class) or if the name is a special
231 /// name (C++ constructor, Objective-C selector, etc.).
232 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
234 /// getName - Get the name of identifier for this declaration as a StringRef.
235 /// This requires that the declaration have a name and that it be a simple
237 StringRef getName() const {
238 assert(Name.isIdentifier() && "Name is not a simple identifier");
239 return getIdentifier() ? getIdentifier()->getName() : "";
242 /// getNameAsString - Get a human-readable name for the declaration, even if
243 /// it is one of the special kinds of names (C++ constructor, Objective-C
244 /// selector, etc). Creating this name requires expensive string
245 /// manipulation, so it should be called only when performance doesn't matter.
246 /// For simple declarations, getNameAsCString() should suffice.
248 // FIXME: This function should be renamed to indicate that it is not just an
249 // alternate form of getName(), and clients should move as appropriate.
251 // FIXME: Deprecated, move clients to getName().
252 std::string getNameAsString() const { return Name.getAsString(); }
254 virtual void printName(raw_ostream &os) const;
256 /// getDeclName - Get the actual, stored name of the declaration,
257 /// which may be a special name.
258 DeclarationName getDeclName() const { return Name; }
260 /// \brief Set the name of this declaration.
261 void setDeclName(DeclarationName N) { Name = N; }
263 /// printQualifiedName - Returns human-readable qualified name for
264 /// declaration, like A::B::i, for i being member of namespace A::B.
265 /// If declaration is not member of context which can be named (record,
266 /// namespace), it will return same result as printName().
267 /// Creating this name is expensive, so it should be called only when
268 /// performance doesn't matter.
269 void printQualifiedName(raw_ostream &OS) const;
270 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
272 // FIXME: Remove string version.
273 std::string getQualifiedNameAsString() const;
275 /// getNameForDiagnostic - Appends a human-readable name for this
276 /// declaration into the given stream.
278 /// This is the method invoked by Sema when displaying a NamedDecl
279 /// in a diagnostic. It does not necessarily produce the same
280 /// result as printName(); for example, class template
281 /// specializations are printed with their template arguments.
282 virtual void getNameForDiagnostic(raw_ostream &OS,
283 const PrintingPolicy &Policy,
284 bool Qualified) const;
286 /// \brief Determine whether this declaration, if
287 /// known to be well-formed within its context, will replace the
288 /// declaration OldD if introduced into scope. A declaration will
289 /// replace another declaration if, for example, it is a
290 /// redeclaration of the same variable or function, but not if it is
291 /// a declaration of a different kind (function vs. class) or an
292 /// overloaded function.
294 /// \param IsKnownNewer \c true if this declaration is known to be newer
295 /// than \p OldD (for instance, if this declaration is newly-created).
296 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
298 /// \brief Determine whether this declaration has linkage.
299 bool hasLinkage() const;
301 using Decl::isModulePrivate;
302 using Decl::setModulePrivate;
304 /// \brief Determine whether this declaration is hidden from name lookup.
305 bool isHidden() const { return Hidden; }
307 /// \brief Set whether this declaration is hidden from name lookup.
308 void setHidden(bool Hide) {
309 assert((!Hide || isFromASTFile() || hasLocalOwningModuleStorage()) &&
310 "declaration with no owning module can't be hidden");
314 /// \brief Determine whether this declaration is a C++ class member.
315 bool isCXXClassMember() const {
316 const DeclContext *DC = getDeclContext();
318 // C++0x [class.mem]p1:
319 // The enumerators of an unscoped enumeration defined in
320 // the class are members of the class.
321 if (isa<EnumDecl>(DC))
322 DC = DC->getRedeclContext();
324 return DC->isRecord();
327 /// \brief Determine whether the given declaration is an instance member of
329 bool isCXXInstanceMember() const;
331 /// \brief Determine what kind of linkage this entity has.
332 /// This is not the linkage as defined by the standard or the codegen notion
333 /// of linkage. It is just an implementation detail that is used to compute
335 Linkage getLinkageInternal() const;
337 /// \brief Get the linkage from a semantic point of view. Entities in
338 /// anonymous namespaces are external (in c++98).
339 Linkage getFormalLinkage() const {
340 return clang::getFormalLinkage(getLinkageInternal());
343 /// \brief True if this decl has external linkage.
344 bool hasExternalFormalLinkage() const {
345 return isExternalFormalLinkage(getLinkageInternal());
348 bool isExternallyVisible() const {
349 return clang::isExternallyVisible(getLinkageInternal());
352 /// \brief Determines the visibility of this entity.
353 Visibility getVisibility() const {
354 return getLinkageAndVisibility().getVisibility();
357 /// \brief Determines the linkage and visibility of this entity.
358 LinkageInfo getLinkageAndVisibility() const;
360 /// Kinds of explicit visibility.
361 enum ExplicitVisibilityKind {
366 /// \brief If visibility was explicitly specified for this
367 /// declaration, return that visibility.
369 getExplicitVisibility(ExplicitVisibilityKind kind) const;
371 /// \brief True if the computed linkage is valid. Used for consistency
372 /// checking. Should always return true.
373 bool isLinkageValid() const;
375 /// \brief True if something has required us to compute the linkage
376 /// of this declaration.
378 /// Language features which can retroactively change linkage (like a
379 /// typedef name for linkage purposes) may need to consider this,
380 /// but hopefully only in transitory ways during parsing.
381 bool hasLinkageBeenComputed() const {
382 return hasCachedLinkage();
385 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
386 /// the underlying named decl.
387 NamedDecl *getUnderlyingDecl() {
388 // Fast-path the common case.
389 if (this->getKind() != UsingShadow &&
390 this->getKind() != ConstructorUsingShadow &&
391 this->getKind() != ObjCCompatibleAlias &&
392 this->getKind() != NamespaceAlias)
395 return getUnderlyingDeclImpl();
397 const NamedDecl *getUnderlyingDecl() const {
398 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
401 NamedDecl *getMostRecentDecl() {
402 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
404 const NamedDecl *getMostRecentDecl() const {
405 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
408 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
410 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
411 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
414 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
419 /// LabelDecl - Represents the declaration of a label. Labels also have a
420 /// corresponding LabelStmt, which indicates the position that the label was
421 /// defined at. For normal labels, the location of the decl is the same as the
422 /// location of the statement. For GNU local labels (__label__), the decl
423 /// location is where the __label__ is.
424 class LabelDecl : public NamedDecl {
425 void anchor() override;
428 bool MSAsmNameResolved;
429 /// LocStart - For normal labels, this is the same as the main declaration
430 /// label, i.e., the location of the identifier; for GNU local labels,
431 /// this is the location of the __label__ keyword.
432 SourceLocation LocStart;
434 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
435 LabelStmt *S, SourceLocation StartL)
436 : NamedDecl(Label, DC, IdentL, II),
438 MSAsmNameResolved(false),
442 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
443 SourceLocation IdentL, IdentifierInfo *II);
444 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
445 SourceLocation IdentL, IdentifierInfo *II,
446 SourceLocation GnuLabelL);
447 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
449 LabelStmt *getStmt() const { return TheStmt; }
450 void setStmt(LabelStmt *T) { TheStmt = T; }
452 bool isGnuLocal() const { return LocStart != getLocation(); }
453 void setLocStart(SourceLocation L) { LocStart = L; }
455 SourceRange getSourceRange() const override LLVM_READONLY {
456 return SourceRange(LocStart, getLocation());
459 bool isMSAsmLabel() const { return MSAsmName.size() != 0; }
460 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
461 void setMSAsmLabel(StringRef Name);
462 StringRef getMSAsmLabel() const { return MSAsmName; }
463 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
465 // Implement isa/cast/dyncast/etc.
466 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
467 static bool classofKind(Kind K) { return K == Label; }
470 /// NamespaceDecl - Represent a C++ namespace.
471 class NamespaceDecl : public NamedDecl, public DeclContext,
472 public Redeclarable<NamespaceDecl>
474 /// LocStart - The starting location of the source range, pointing
475 /// to either the namespace or the inline keyword.
476 SourceLocation LocStart;
477 /// RBraceLoc - The ending location of the source range.
478 SourceLocation RBraceLoc;
480 /// \brief A pointer to either the anonymous namespace that lives just inside
481 /// this namespace or to the first namespace in the chain (the latter case
482 /// only when this is not the first in the chain), along with a
483 /// boolean value indicating whether this is an inline namespace.
484 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
486 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
487 SourceLocation StartLoc, SourceLocation IdLoc,
488 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
490 typedef Redeclarable<NamespaceDecl> redeclarable_base;
491 NamespaceDecl *getNextRedeclarationImpl() override;
492 NamespaceDecl *getPreviousDeclImpl() override;
493 NamespaceDecl *getMostRecentDeclImpl() override;
496 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
497 bool Inline, SourceLocation StartLoc,
498 SourceLocation IdLoc, IdentifierInfo *Id,
499 NamespaceDecl *PrevDecl);
501 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
503 typedef redeclarable_base::redecl_range redecl_range;
504 typedef redeclarable_base::redecl_iterator redecl_iterator;
505 using redeclarable_base::redecls_begin;
506 using redeclarable_base::redecls_end;
507 using redeclarable_base::redecls;
508 using redeclarable_base::getPreviousDecl;
509 using redeclarable_base::getMostRecentDecl;
510 using redeclarable_base::isFirstDecl;
512 /// \brief Returns true if this is an anonymous namespace declaration.
520 /// q.v. C++ [namespace.unnamed]
521 bool isAnonymousNamespace() const {
522 return !getIdentifier();
525 /// \brief Returns true if this is an inline namespace declaration.
526 bool isInline() const {
527 return AnonOrFirstNamespaceAndInline.getInt();
530 /// \brief Set whether this is an inline namespace declaration.
531 void setInline(bool Inline) {
532 AnonOrFirstNamespaceAndInline.setInt(Inline);
535 /// \brief Get the original (first) namespace declaration.
536 NamespaceDecl *getOriginalNamespace();
538 /// \brief Get the original (first) namespace declaration.
539 const NamespaceDecl *getOriginalNamespace() const;
541 /// \brief Return true if this declaration is an original (first) declaration
542 /// of the namespace. This is false for non-original (subsequent) namespace
543 /// declarations and anonymous namespaces.
544 bool isOriginalNamespace() const;
546 /// \brief Retrieve the anonymous namespace nested inside this namespace,
548 NamespaceDecl *getAnonymousNamespace() const {
549 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
552 void setAnonymousNamespace(NamespaceDecl *D) {
553 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
556 /// Retrieves the canonical declaration of this namespace.
557 NamespaceDecl *getCanonicalDecl() override {
558 return getOriginalNamespace();
560 const NamespaceDecl *getCanonicalDecl() const {
561 return getOriginalNamespace();
564 SourceRange getSourceRange() const override LLVM_READONLY {
565 return SourceRange(LocStart, RBraceLoc);
568 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
569 SourceLocation getRBraceLoc() const { return RBraceLoc; }
570 void setLocStart(SourceLocation L) { LocStart = L; }
571 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
573 // Implement isa/cast/dyncast/etc.
574 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
575 static bool classofKind(Kind K) { return K == Namespace; }
576 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
577 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
579 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
580 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
583 friend class ASTDeclReader;
584 friend class ASTDeclWriter;
587 /// ValueDecl - Represent the declaration of a variable (in which case it is
588 /// an lvalue) a function (in which case it is a function designator) or
589 /// an enum constant.
590 class ValueDecl : public NamedDecl {
591 void anchor() override;
595 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
596 DeclarationName N, QualType T)
597 : NamedDecl(DK, DC, L, N), DeclType(T) {}
599 QualType getType() const { return DeclType; }
600 void setType(QualType newType) { DeclType = newType; }
602 /// \brief Determine whether this symbol is weakly-imported,
603 /// or declared with the weak or weak-ref attr.
606 // Implement isa/cast/dyncast/etc.
607 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
608 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
611 /// QualifierInfo - A struct with extended info about a syntactic
612 /// name qualifier, to be used for the case of out-of-line declarations.
613 struct QualifierInfo {
614 NestedNameSpecifierLoc QualifierLoc;
616 /// NumTemplParamLists - The number of "outer" template parameter lists.
617 /// The count includes all of the template parameter lists that were matched
618 /// against the template-ids occurring into the NNS and possibly (in the
619 /// case of an explicit specialization) a final "template <>".
620 unsigned NumTemplParamLists;
622 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
623 /// containing pointers to the "outer" template parameter lists.
624 /// It includes all of the template parameter lists that were matched
625 /// against the template-ids occurring into the NNS and possibly (in the
626 /// case of an explicit specialization) a final "template <>".
627 TemplateParameterList** TemplParamLists;
629 /// Default constructor.
631 : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(nullptr) {}
633 /// setTemplateParameterListsInfo - Sets info about "outer" template
635 void setTemplateParameterListsInfo(ASTContext &Context,
636 ArrayRef<TemplateParameterList *> TPLists);
639 // Copy constructor and copy assignment are disabled.
640 QualifierInfo(const QualifierInfo&) = delete;
641 QualifierInfo& operator=(const QualifierInfo&) = delete;
644 /// \brief Represents a ValueDecl that came out of a declarator.
645 /// Contains type source information through TypeSourceInfo.
646 class DeclaratorDecl : public ValueDecl {
647 // A struct representing both a TInfo and a syntactic qualifier,
648 // to be used for the (uncommon) case of out-of-line declarations.
649 struct ExtInfo : public QualifierInfo {
650 TypeSourceInfo *TInfo;
653 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
655 /// InnerLocStart - The start of the source range for this declaration,
656 /// ignoring outer template declarations.
657 SourceLocation InnerLocStart;
659 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
660 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
661 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
664 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
665 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
666 SourceLocation StartL)
667 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
671 TypeSourceInfo *getTypeSourceInfo() const {
673 ? getExtInfo()->TInfo
674 : DeclInfo.get<TypeSourceInfo*>();
676 void setTypeSourceInfo(TypeSourceInfo *TI) {
678 getExtInfo()->TInfo = TI;
683 /// getInnerLocStart - Return SourceLocation representing start of source
684 /// range ignoring outer template declarations.
685 SourceLocation getInnerLocStart() const { return InnerLocStart; }
686 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
688 /// getOuterLocStart - Return SourceLocation representing start of source
689 /// range taking into account any outer template declarations.
690 SourceLocation getOuterLocStart() const;
692 SourceRange getSourceRange() const override LLVM_READONLY;
693 SourceLocation getLocStart() const LLVM_READONLY {
694 return getOuterLocStart();
697 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
698 /// declaration, if it was present in the source.
699 NestedNameSpecifier *getQualifier() const {
700 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
704 /// \brief Retrieve the nested-name-specifier (with source-location
705 /// information) that qualifies the name of this declaration, if it was
706 /// present in the source.
707 NestedNameSpecifierLoc getQualifierLoc() const {
708 return hasExtInfo() ? getExtInfo()->QualifierLoc
709 : NestedNameSpecifierLoc();
712 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
714 unsigned getNumTemplateParameterLists() const {
715 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
717 TemplateParameterList *getTemplateParameterList(unsigned index) const {
718 assert(index < getNumTemplateParameterLists());
719 return getExtInfo()->TemplParamLists[index];
721 void setTemplateParameterListsInfo(ASTContext &Context,
722 ArrayRef<TemplateParameterList *> TPLists);
724 SourceLocation getTypeSpecStartLoc() const;
726 // Implement isa/cast/dyncast/etc.
727 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
728 static bool classofKind(Kind K) {
729 return K >= firstDeclarator && K <= lastDeclarator;
732 friend class ASTDeclReader;
733 friend class ASTDeclWriter;
736 /// \brief Structure used to store a statement, the constant value to
737 /// which it was evaluated (if any), and whether or not the statement
738 /// is an integral constant expression (if known).
739 struct EvaluatedStmt {
740 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
741 CheckingICE(false), IsICE(false) { }
743 /// \brief Whether this statement was already evaluated.
744 bool WasEvaluated : 1;
746 /// \brief Whether this statement is being evaluated.
747 bool IsEvaluating : 1;
749 /// \brief Whether we already checked whether this statement was an
750 /// integral constant expression.
753 /// \brief Whether we are checking whether this statement is an
754 /// integral constant expression.
755 bool CheckingICE : 1;
757 /// \brief Whether this statement is an integral constant expression,
758 /// or in C++11, whether the statement is a constant expression. Only
759 /// valid if CheckedICE is true.
766 /// VarDecl - An instance of this class is created to represent a variable
767 /// declaration or definition.
768 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
770 /// getStorageClassSpecifierString - Return the string used to
771 /// specify the storage class \p SC.
773 /// It is illegal to call this function with SC == None.
774 static const char *getStorageClassSpecifierString(StorageClass SC);
776 /// \brief Initialization styles.
777 enum InitializationStyle {
778 CInit, ///< C-style initialization with assignment
779 CallInit, ///< Call-style initialization (C++98)
780 ListInit ///< Direct list-initialization (C++11)
783 /// \brief Kinds of thread-local storage.
785 TLS_None, ///< Not a TLS variable.
786 TLS_Static, ///< TLS with a known-constant initializer.
787 TLS_Dynamic ///< TLS with a dynamic initializer.
791 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
792 // have allocated the auxiliary struct of information there.
794 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
795 // this as *many* VarDecls are ParmVarDecls that don't have default
796 // arguments. We could save some space by moving this pointer union to be
797 // allocated in trailing space when necessary.
798 typedef llvm::PointerUnion<Stmt *, EvaluatedStmt *> InitType;
800 /// \brief The initializer for this variable or, for a ParmVarDecl, the
801 /// C++ default argument.
802 mutable InitType Init;
805 class VarDeclBitfields {
806 friend class VarDecl;
807 friend class ASTDeclReader;
810 unsigned TSCSpec : 2;
811 unsigned InitStyle : 2;
813 enum { NumVarDeclBits = 7 };
815 friend class ASTDeclReader;
816 friend class StmtIteratorBase;
817 friend class ASTNodeImporter;
820 enum { NumParameterIndexBits = 8 };
822 enum DefaultArgKind {
829 class ParmVarDeclBitfields {
830 friend class ParmVarDecl;
831 friend class ASTDeclReader;
833 unsigned : NumVarDeclBits;
835 /// Whether this parameter inherits a default argument from a
836 /// prior declaration.
837 unsigned HasInheritedDefaultArg : 1;
839 /// Describes the kind of default argument for this parameter. By default
840 /// this is none. If this is normal, then the default argument is stored in
841 /// the \c VarDecl initializer expression unless we were unable to parse
842 /// (even an invalid) expression for the default argument.
843 unsigned DefaultArgKind : 2;
845 /// Whether this parameter undergoes K&R argument promotion.
846 unsigned IsKNRPromoted : 1;
848 /// Whether this parameter is an ObjC method parameter or not.
849 unsigned IsObjCMethodParam : 1;
851 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
852 /// Otherwise, the number of function parameter scopes enclosing
853 /// the function parameter scope in which this parameter was
855 unsigned ScopeDepthOrObjCQuals : 7;
857 /// The number of parameters preceding this parameter in the
858 /// function parameter scope in which it was declared.
859 unsigned ParameterIndex : NumParameterIndexBits;
862 class NonParmVarDeclBitfields {
863 friend class VarDecl;
864 friend class ASTDeclReader;
866 unsigned : NumVarDeclBits;
868 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
869 /// \brief Whether this variable is a definition which was demoted due to
871 unsigned IsThisDeclarationADemotedDefinition : 1;
873 /// \brief Whether this variable is the exception variable in a C++ catch
874 /// or an Objective-C @catch statement.
875 unsigned ExceptionVar : 1;
877 /// \brief Whether this local variable could be allocated in the return
878 /// slot of its function, enabling the named return value optimization
880 unsigned NRVOVariable : 1;
882 /// \brief Whether this variable is the for-range-declaration in a C++0x
883 /// for-range statement.
884 unsigned CXXForRangeDecl : 1;
886 /// \brief Whether this variable is an ARC pseudo-__strong
887 /// variable; see isARCPseudoStrong() for details.
888 unsigned ARCPseudoStrong : 1;
890 /// \brief Whether this variable is (C++1z) inline.
891 unsigned IsInline : 1;
893 /// \brief Whether this variable has (C++1z) inline explicitly specified.
894 unsigned IsInlineSpecified : 1;
896 /// \brief Whether this variable is (C++0x) constexpr.
897 unsigned IsConstexpr : 1;
899 /// \brief Whether this variable is the implicit variable for a lambda
901 unsigned IsInitCapture : 1;
903 /// \brief Whether this local extern variable's previous declaration was
904 /// declared in the same block scope. This controls whether we should merge
905 /// the type of this declaration with its previous declaration.
906 unsigned PreviousDeclInSameBlockScope : 1;
911 VarDeclBitfields VarDeclBits;
912 ParmVarDeclBitfields ParmVarDeclBits;
913 NonParmVarDeclBitfields NonParmVarDeclBits;
916 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
917 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
918 TypeSourceInfo *TInfo, StorageClass SC);
920 typedef Redeclarable<VarDecl> redeclarable_base;
921 VarDecl *getNextRedeclarationImpl() override {
922 return getNextRedeclaration();
924 VarDecl *getPreviousDeclImpl() override {
925 return getPreviousDecl();
927 VarDecl *getMostRecentDeclImpl() override {
928 return getMostRecentDecl();
932 typedef redeclarable_base::redecl_range redecl_range;
933 typedef redeclarable_base::redecl_iterator redecl_iterator;
934 using redeclarable_base::redecls_begin;
935 using redeclarable_base::redecls_end;
936 using redeclarable_base::redecls;
937 using redeclarable_base::getPreviousDecl;
938 using redeclarable_base::getMostRecentDecl;
939 using redeclarable_base::isFirstDecl;
941 static VarDecl *Create(ASTContext &C, DeclContext *DC,
942 SourceLocation StartLoc, SourceLocation IdLoc,
943 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
946 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
948 SourceRange getSourceRange() const override LLVM_READONLY;
950 /// \brief Returns the storage class as written in the source. For the
951 /// computed linkage of symbol, see getLinkage.
952 StorageClass getStorageClass() const {
953 return (StorageClass) VarDeclBits.SClass;
955 void setStorageClass(StorageClass SC);
957 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
958 VarDeclBits.TSCSpec = TSC;
959 assert(VarDeclBits.TSCSpec == TSC && "truncation");
961 ThreadStorageClassSpecifier getTSCSpec() const {
962 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
964 TLSKind getTLSKind() const;
966 /// hasLocalStorage - Returns true if a variable with function scope
967 /// is a non-static local variable.
968 bool hasLocalStorage() const {
969 if (getStorageClass() == SC_None)
970 // Second check is for C++11 [dcl.stc]p4.
971 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
973 // Global Named Register (GNU extension)
974 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
977 // Return true for: Auto, Register.
978 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
980 return getStorageClass() >= SC_Auto;
983 /// isStaticLocal - Returns true if a variable with function scope is a
984 /// static local variable.
985 bool isStaticLocal() const {
986 return (getStorageClass() == SC_Static ||
988 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
992 /// \brief Returns true if a variable has extern or __private_extern__
994 bool hasExternalStorage() const {
995 return getStorageClass() == SC_Extern ||
996 getStorageClass() == SC_PrivateExtern;
999 /// \brief Returns true for all variables that do not have local storage.
1001 /// This includes all global variables as well as static variables declared
1002 /// within a function.
1003 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1005 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1006 StorageDuration getStorageDuration() const {
1007 return hasLocalStorage() ? SD_Automatic :
1008 getTSCSpec() ? SD_Thread : SD_Static;
1011 /// \brief Compute the language linkage.
1012 LanguageLinkage getLanguageLinkage() const;
1014 /// \brief Determines whether this variable is a variable with
1015 /// external, C linkage.
1016 bool isExternC() const;
1018 /// \brief Determines whether this variable's context is, or is nested within,
1019 /// a C++ extern "C" linkage spec.
1020 bool isInExternCContext() const;
1022 /// \brief Determines whether this variable's context is, or is nested within,
1023 /// a C++ extern "C++" linkage spec.
1024 bool isInExternCXXContext() const;
1026 /// isLocalVarDecl - Returns true for local variable declarations
1027 /// other than parameters. Note that this includes static variables
1028 /// inside of functions. It also includes variables inside blocks.
1030 /// void foo() { int x; static int y; extern int z; }
1032 bool isLocalVarDecl() const {
1033 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1035 if (const DeclContext *DC = getLexicalDeclContext())
1036 return DC->getRedeclContext()->isFunctionOrMethod();
1040 /// \brief Similar to isLocalVarDecl but also includes parameters.
1041 bool isLocalVarDeclOrParm() const {
1042 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1045 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1046 /// excludes variables declared in blocks.
1047 bool isFunctionOrMethodVarDecl() const {
1048 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1050 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1051 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1054 /// \brief Determines whether this is a static data member.
1056 /// This will only be true in C++, and applies to, e.g., the
1057 /// variable 'x' in:
1063 bool isStaticDataMember() const {
1064 // If it wasn't static, it would be a FieldDecl.
1065 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1068 VarDecl *getCanonicalDecl() override;
1069 const VarDecl *getCanonicalDecl() const {
1070 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1073 enum DefinitionKind {
1074 DeclarationOnly, ///< This declaration is only a declaration.
1075 TentativeDefinition, ///< This declaration is a tentative definition.
1076 Definition ///< This declaration is definitely a definition.
1079 /// \brief Check whether this declaration is a definition. If this could be
1080 /// a tentative definition (in C), don't check whether there's an overriding
1082 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1083 DefinitionKind isThisDeclarationADefinition() const {
1084 return isThisDeclarationADefinition(getASTContext());
1087 /// \brief Check whether this variable is defined in this
1088 /// translation unit.
1089 DefinitionKind hasDefinition(ASTContext &) const;
1090 DefinitionKind hasDefinition() const {
1091 return hasDefinition(getASTContext());
1094 /// \brief Get the tentative definition that acts as the real definition in
1095 /// a TU. Returns null if there is a proper definition available.
1096 VarDecl *getActingDefinition();
1097 const VarDecl *getActingDefinition() const {
1098 return const_cast<VarDecl*>(this)->getActingDefinition();
1101 /// \brief Get the real (not just tentative) definition for this declaration.
1102 VarDecl *getDefinition(ASTContext &);
1103 const VarDecl *getDefinition(ASTContext &C) const {
1104 return const_cast<VarDecl*>(this)->getDefinition(C);
1106 VarDecl *getDefinition() {
1107 return getDefinition(getASTContext());
1109 const VarDecl *getDefinition() const {
1110 return const_cast<VarDecl*>(this)->getDefinition();
1113 /// \brief Determine whether this is or was instantiated from an out-of-line
1114 /// definition of a static data member.
1115 bool isOutOfLine() const override;
1117 /// isFileVarDecl - Returns true for file scoped variable declaration.
1118 bool isFileVarDecl() const {
1120 if (K == ParmVar || K == ImplicitParam)
1123 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1126 if (isStaticDataMember())
1132 /// getAnyInitializer - Get the initializer for this variable, no matter which
1133 /// declaration it is attached to.
1134 const Expr *getAnyInitializer() const {
1136 return getAnyInitializer(D);
1139 /// getAnyInitializer - Get the initializer for this variable, no matter which
1140 /// declaration it is attached to. Also get that declaration.
1141 const Expr *getAnyInitializer(const VarDecl *&D) const;
1143 bool hasInit() const;
1144 const Expr *getInit() const {
1145 return const_cast<VarDecl *>(this)->getInit();
1149 /// \brief Retrieve the address of the initializer expression.
1150 Stmt **getInitAddress();
1152 void setInit(Expr *I);
1154 /// \brief Determine whether this variable's value can be used in a
1155 /// constant expression, according to the relevant language standard.
1156 /// This only checks properties of the declaration, and does not check
1157 /// whether the initializer is in fact a constant expression.
1158 bool isUsableInConstantExpressions(ASTContext &C) const;
1160 EvaluatedStmt *ensureEvaluatedStmt() const;
1162 /// \brief Attempt to evaluate the value of the initializer attached to this
1163 /// declaration, and produce notes explaining why it cannot be evaluated or is
1164 /// not a constant expression. Returns a pointer to the value if evaluation
1165 /// succeeded, 0 otherwise.
1166 APValue *evaluateValue() const;
1167 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1169 /// \brief Return the already-evaluated value of this variable's
1170 /// initializer, or NULL if the value is not yet known. Returns pointer
1171 /// to untyped APValue if the value could not be evaluated.
1172 APValue *getEvaluatedValue() const;
1174 /// \brief Determines whether it is already known whether the
1175 /// initializer is an integral constant expression or not.
1176 bool isInitKnownICE() const;
1178 /// \brief Determines whether the initializer is an integral constant
1179 /// expression, or in C++11, whether the initializer is a constant
1182 /// \pre isInitKnownICE()
1183 bool isInitICE() const;
1185 /// \brief Determine whether the value of the initializer attached to this
1186 /// declaration is an integral constant expression.
1187 bool checkInitIsICE() const;
1189 void setInitStyle(InitializationStyle Style) {
1190 VarDeclBits.InitStyle = Style;
1193 /// \brief The style of initialization for this declaration.
1195 /// C-style initialization is "int x = 1;". Call-style initialization is
1196 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1197 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1198 /// expression for class types. List-style initialization is C++11 syntax,
1199 /// e.g. "int x{1};". Clients can distinguish between different forms of
1200 /// initialization by checking this value. In particular, "int x = {1};" is
1201 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1202 /// Init expression in all three cases is an InitListExpr.
1203 InitializationStyle getInitStyle() const {
1204 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1206 /// \brief Whether the initializer is a direct-initializer (list or call).
1207 bool isDirectInit() const {
1208 return getInitStyle() != CInit;
1211 /// \brief If this definition should pretend to be a declaration.
1212 bool isThisDeclarationADemotedDefinition() const {
1213 return isa<ParmVarDecl>(this) ? false :
1214 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1217 /// \brief This is a definition which should be demoted to a declaration.
1219 /// In some cases (mostly module merging) we can end up with two visible
1220 /// definitions one of which needs to be demoted to a declaration to keep
1221 /// the AST invariants.
1222 void demoteThisDefinitionToDeclaration() {
1223 assert (isThisDeclarationADefinition() && "Not a definition!");
1224 assert (!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1225 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1228 /// \brief Determine whether this variable is the exception variable in a
1229 /// C++ catch statememt or an Objective-C \@catch statement.
1230 bool isExceptionVariable() const {
1231 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1233 void setExceptionVariable(bool EV) {
1234 assert(!isa<ParmVarDecl>(this));
1235 NonParmVarDeclBits.ExceptionVar = EV;
1238 /// \brief Determine whether this local variable can be used with the named
1239 /// return value optimization (NRVO).
1241 /// The named return value optimization (NRVO) works by marking certain
1242 /// non-volatile local variables of class type as NRVO objects. These
1243 /// locals can be allocated within the return slot of their containing
1244 /// function, in which case there is no need to copy the object to the
1245 /// return slot when returning from the function. Within the function body,
1246 /// each return that returns the NRVO object will have this variable as its
1248 bool isNRVOVariable() const {
1249 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1251 void setNRVOVariable(bool NRVO) {
1252 assert(!isa<ParmVarDecl>(this));
1253 NonParmVarDeclBits.NRVOVariable = NRVO;
1256 /// \brief Determine whether this variable is the for-range-declaration in
1257 /// a C++0x for-range statement.
1258 bool isCXXForRangeDecl() const {
1259 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1261 void setCXXForRangeDecl(bool FRD) {
1262 assert(!isa<ParmVarDecl>(this));
1263 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1266 /// \brief Determine whether this variable is an ARC pseudo-__strong
1267 /// variable. A pseudo-__strong variable has a __strong-qualified
1268 /// type but does not actually retain the object written into it.
1269 /// Generally such variables are also 'const' for safety.
1270 bool isARCPseudoStrong() const {
1271 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1273 void setARCPseudoStrong(bool ps) {
1274 assert(!isa<ParmVarDecl>(this));
1275 NonParmVarDeclBits.ARCPseudoStrong = ps;
1278 /// Whether this variable is (C++1z) inline.
1279 bool isInline() const {
1280 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1282 bool isInlineSpecified() const {
1283 return isa<ParmVarDecl>(this) ? false
1284 : NonParmVarDeclBits.IsInlineSpecified;
1286 void setInlineSpecified() {
1287 assert(!isa<ParmVarDecl>(this));
1288 NonParmVarDeclBits.IsInline = true;
1289 NonParmVarDeclBits.IsInlineSpecified = true;
1291 void setImplicitlyInline() {
1292 assert(!isa<ParmVarDecl>(this));
1293 NonParmVarDeclBits.IsInline = true;
1296 /// Whether this variable is (C++11) constexpr.
1297 bool isConstexpr() const {
1298 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1300 void setConstexpr(bool IC) {
1301 assert(!isa<ParmVarDecl>(this));
1302 NonParmVarDeclBits.IsConstexpr = IC;
1305 /// Whether this variable is the implicit variable for a lambda init-capture.
1306 bool isInitCapture() const {
1307 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1309 void setInitCapture(bool IC) {
1310 assert(!isa<ParmVarDecl>(this));
1311 NonParmVarDeclBits.IsInitCapture = IC;
1314 /// Whether this local extern variable declaration's previous declaration
1315 /// was declared in the same block scope. Only correct in C++.
1316 bool isPreviousDeclInSameBlockScope() const {
1317 return isa<ParmVarDecl>(this)
1319 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1321 void setPreviousDeclInSameBlockScope(bool Same) {
1322 assert(!isa<ParmVarDecl>(this));
1323 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1326 /// \brief Retrieve the variable declaration from which this variable could
1327 /// be instantiated, if it is an instantiation (rather than a non-template).
1328 VarDecl *getTemplateInstantiationPattern() const;
1330 /// \brief If this variable is an instantiated static data member of a
1331 /// class template specialization, returns the templated static data member
1332 /// from which it was instantiated.
1333 VarDecl *getInstantiatedFromStaticDataMember() const;
1335 /// \brief If this variable is an instantiation of a variable template or a
1336 /// static data member of a class template, determine what kind of
1337 /// template specialization or instantiation this is.
1338 TemplateSpecializationKind getTemplateSpecializationKind() const;
1340 /// \brief If this variable is an instantiation of a variable template or a
1341 /// static data member of a class template, determine its point of
1343 SourceLocation getPointOfInstantiation() const;
1345 /// \brief If this variable is an instantiation of a static data member of a
1346 /// class template specialization, retrieves the member specialization
1348 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1350 /// \brief For a static data member that was instantiated from a static
1351 /// data member of a class template, set the template specialiation kind.
1352 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1353 SourceLocation PointOfInstantiation = SourceLocation());
1355 /// \brief Specify that this variable is an instantiation of the
1356 /// static data member VD.
1357 void setInstantiationOfStaticDataMember(VarDecl *VD,
1358 TemplateSpecializationKind TSK);
1360 /// \brief Retrieves the variable template that is described by this
1361 /// variable declaration.
1363 /// Every variable template is represented as a VarTemplateDecl and a
1364 /// VarDecl. The former contains template properties (such as
1365 /// the template parameter lists) while the latter contains the
1366 /// actual description of the template's
1367 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1368 /// VarDecl that from a VarTemplateDecl, while
1369 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1371 VarTemplateDecl *getDescribedVarTemplate() const;
1373 void setDescribedVarTemplate(VarTemplateDecl *Template);
1375 // Implement isa/cast/dyncast/etc.
1376 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1377 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1380 class ImplicitParamDecl : public VarDecl {
1381 void anchor() override;
1383 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1384 SourceLocation IdLoc, IdentifierInfo *Id,
1387 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1389 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1390 IdentifierInfo *Id, QualType Type)
1391 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1392 /*tinfo*/ nullptr, SC_None) {
1396 // Implement isa/cast/dyncast/etc.
1397 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1398 static bool classofKind(Kind K) { return K == ImplicitParam; }
1401 /// ParmVarDecl - Represents a parameter to a function.
1402 class ParmVarDecl : public VarDecl {
1404 enum { MaxFunctionScopeDepth = 255 };
1405 enum { MaxFunctionScopeIndex = 255 };
1408 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1409 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1410 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1411 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1412 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1413 assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1414 assert(ParmVarDeclBits.IsKNRPromoted == false);
1415 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1416 setDefaultArg(DefArg);
1420 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1421 SourceLocation StartLoc,
1422 SourceLocation IdLoc, IdentifierInfo *Id,
1423 QualType T, TypeSourceInfo *TInfo,
1424 StorageClass S, Expr *DefArg);
1426 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1428 SourceRange getSourceRange() const override LLVM_READONLY;
1430 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1431 ParmVarDeclBits.IsObjCMethodParam = true;
1432 setParameterIndex(parameterIndex);
1435 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1436 assert(!ParmVarDeclBits.IsObjCMethodParam);
1438 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1439 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1442 setParameterIndex(parameterIndex);
1445 bool isObjCMethodParameter() const {
1446 return ParmVarDeclBits.IsObjCMethodParam;
1449 unsigned getFunctionScopeDepth() const {
1450 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1451 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1454 /// Returns the index of this parameter in its prototype or method scope.
1455 unsigned getFunctionScopeIndex() const {
1456 return getParameterIndex();
1459 ObjCDeclQualifier getObjCDeclQualifier() const {
1460 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1461 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1463 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1464 assert(ParmVarDeclBits.IsObjCMethodParam);
1465 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1468 /// True if the value passed to this parameter must undergo
1469 /// K&R-style default argument promotion:
1472 /// If the expression that denotes the called function has a type
1473 /// that does not include a prototype, the integer promotions are
1474 /// performed on each argument, and arguments that have type float
1475 /// are promoted to double.
1476 bool isKNRPromoted() const {
1477 return ParmVarDeclBits.IsKNRPromoted;
1479 void setKNRPromoted(bool promoted) {
1480 ParmVarDeclBits.IsKNRPromoted = promoted;
1483 Expr *getDefaultArg();
1484 const Expr *getDefaultArg() const {
1485 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1488 void setDefaultArg(Expr *defarg);
1490 /// \brief Retrieve the source range that covers the entire default
1492 SourceRange getDefaultArgRange() const;
1493 void setUninstantiatedDefaultArg(Expr *arg);
1494 Expr *getUninstantiatedDefaultArg();
1495 const Expr *getUninstantiatedDefaultArg() const {
1496 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1499 /// hasDefaultArg - Determines whether this parameter has a default argument,
1500 /// either parsed or not.
1501 bool hasDefaultArg() const;
1503 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1504 /// default argument that has not yet been parsed. This will occur
1505 /// during the processing of a C++ class whose member functions have
1506 /// default arguments, e.g.,
1510 /// void f(int x = 17); // x has an unparsed default argument now
1511 /// }; // x has a regular default argument now
1513 bool hasUnparsedDefaultArg() const {
1514 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1517 bool hasUninstantiatedDefaultArg() const {
1518 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1521 /// setUnparsedDefaultArg - Specify that this parameter has an
1522 /// unparsed default argument. The argument will be replaced with a
1523 /// real default argument via setDefaultArg when the class
1524 /// definition enclosing the function declaration that owns this
1525 /// default argument is completed.
1526 void setUnparsedDefaultArg() {
1527 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1530 bool hasInheritedDefaultArg() const {
1531 return ParmVarDeclBits.HasInheritedDefaultArg;
1534 void setHasInheritedDefaultArg(bool I = true) {
1535 ParmVarDeclBits.HasInheritedDefaultArg = I;
1538 QualType getOriginalType() const;
1540 /// \brief Determine whether this parameter is actually a function
1542 bool isParameterPack() const;
1544 /// setOwningFunction - Sets the function declaration that owns this
1545 /// ParmVarDecl. Since ParmVarDecls are often created before the
1546 /// FunctionDecls that own them, this routine is required to update
1547 /// the DeclContext appropriately.
1548 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1550 // Implement isa/cast/dyncast/etc.
1551 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1552 static bool classofKind(Kind K) { return K == ParmVar; }
1555 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1557 void setParameterIndex(unsigned parameterIndex) {
1558 if (parameterIndex >= ParameterIndexSentinel) {
1559 setParameterIndexLarge(parameterIndex);
1563 ParmVarDeclBits.ParameterIndex = parameterIndex;
1564 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1566 unsigned getParameterIndex() const {
1567 unsigned d = ParmVarDeclBits.ParameterIndex;
1568 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1571 void setParameterIndexLarge(unsigned parameterIndex);
1572 unsigned getParameterIndexLarge() const;
1575 /// FunctionDecl - An instance of this class is created to represent a
1576 /// function declaration or definition.
1578 /// Since a given function can be declared several times in a program,
1579 /// there may be several FunctionDecls that correspond to that
1580 /// function. Only one of those FunctionDecls will be found when
1581 /// traversing the list of declarations in the context of the
1582 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1583 /// contains all of the information known about the function. Other,
1584 /// previous declarations of the function are available via the
1585 /// getPreviousDecl() chain.
1586 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1587 public Redeclarable<FunctionDecl> {
1589 /// \brief The kind of templated function a FunctionDecl can be.
1590 enum TemplatedKind {
1592 TK_FunctionTemplate,
1593 TK_MemberSpecialization,
1594 TK_FunctionTemplateSpecialization,
1595 TK_DependentFunctionTemplateSpecialization
1599 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1600 /// parameters of this function. This is null if a prototype or if there are
1602 ParmVarDecl **ParamInfo;
1604 LazyDeclStmtPtr Body;
1606 // FIXME: This can be packed into the bitfields in DeclContext.
1607 // NOTE: VC++ packs bitfields poorly if the types differ.
1608 unsigned SClass : 3;
1609 unsigned IsInline : 1;
1610 unsigned IsInlineSpecified : 1;
1612 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1613 // CXXDeductionGuideDecl.
1614 unsigned IsExplicitSpecified : 1;
1616 unsigned IsVirtualAsWritten : 1;
1617 unsigned IsPure : 1;
1618 unsigned HasInheritedPrototype : 1;
1619 unsigned HasWrittenPrototype : 1;
1620 unsigned IsDeleted : 1;
1621 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1622 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1623 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1624 unsigned HasImplicitReturnZero : 1;
1625 unsigned IsLateTemplateParsed : 1;
1626 unsigned IsConstexpr : 1;
1628 /// \brief Indicates if the function uses __try.
1629 unsigned UsesSEHTry : 1;
1631 /// \brief Indicates if the function was a definition but its body was
1633 unsigned HasSkippedBody : 1;
1635 /// Indicates if the function declaration will have a body, once we're done
1636 /// parsing it. (We don't set it to false when we're done parsing, in the
1637 /// hopes this is simpler.)
1638 unsigned WillHaveBody : 1;
1640 /// \brief End part of this FunctionDecl's source range.
1642 /// We could compute the full range in getSourceRange(). However, when we're
1643 /// dealing with a function definition deserialized from a PCH/AST file,
1644 /// we can only compute the full range once the function body has been
1645 /// de-serialized, so it's far better to have the (sometimes-redundant)
1647 SourceLocation EndRangeLoc;
1649 /// \brief The template or declaration that this declaration
1650 /// describes or was instantiated from, respectively.
1652 /// For non-templates, this value will be NULL. For function
1653 /// declarations that describe a function template, this will be a
1654 /// pointer to a FunctionTemplateDecl. For member functions
1655 /// of class template specializations, this will be a MemberSpecializationInfo
1656 /// pointer containing information about the specialization.
1657 /// For function template specializations, this will be a
1658 /// FunctionTemplateSpecializationInfo, which contains information about
1659 /// the template being specialized and the template arguments involved in
1660 /// that specialization.
1661 llvm::PointerUnion4<FunctionTemplateDecl *,
1662 MemberSpecializationInfo *,
1663 FunctionTemplateSpecializationInfo *,
1664 DependentFunctionTemplateSpecializationInfo *>
1665 TemplateOrSpecialization;
1667 /// DNLoc - Provides source/type location info for the
1668 /// declaration name embedded in the DeclaratorDecl base class.
1669 DeclarationNameLoc DNLoc;
1671 /// \brief Specify that this function declaration is actually a function
1672 /// template specialization.
1674 /// \param C the ASTContext.
1676 /// \param Template the function template that this function template
1677 /// specialization specializes.
1679 /// \param TemplateArgs the template arguments that produced this
1680 /// function template specialization from the template.
1682 /// \param InsertPos If non-NULL, the position in the function template
1683 /// specialization set where the function template specialization data will
1686 /// \param TSK the kind of template specialization this is.
1688 /// \param TemplateArgsAsWritten location info of template arguments.
1690 /// \param PointOfInstantiation point at which the function template
1691 /// specialization was first instantiated.
1692 void setFunctionTemplateSpecialization(ASTContext &C,
1693 FunctionTemplateDecl *Template,
1694 const TemplateArgumentList *TemplateArgs,
1696 TemplateSpecializationKind TSK,
1697 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1698 SourceLocation PointOfInstantiation);
1700 /// \brief Specify that this record is an instantiation of the
1701 /// member function FD.
1702 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1703 TemplateSpecializationKind TSK);
1705 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1708 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1709 const DeclarationNameInfo &NameInfo, QualType T,
1710 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1711 bool isConstexprSpecified)
1712 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1714 DeclContext(DK), redeclarable_base(C), ParamInfo(nullptr), Body(),
1715 SClass(S), IsInline(isInlineSpecified),
1716 IsInlineSpecified(isInlineSpecified), IsExplicitSpecified(false),
1717 IsVirtualAsWritten(false), IsPure(false),
1718 HasInheritedPrototype(false), HasWrittenPrototype(true),
1719 IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1720 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1721 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1722 UsesSEHTry(false), HasSkippedBody(false), WillHaveBody(false),
1723 EndRangeLoc(NameInfo.getEndLoc()), TemplateOrSpecialization(),
1724 DNLoc(NameInfo.getInfo()) {}
1726 typedef Redeclarable<FunctionDecl> redeclarable_base;
1727 FunctionDecl *getNextRedeclarationImpl() override {
1728 return getNextRedeclaration();
1730 FunctionDecl *getPreviousDeclImpl() override {
1731 return getPreviousDecl();
1733 FunctionDecl *getMostRecentDeclImpl() override {
1734 return getMostRecentDecl();
1738 typedef redeclarable_base::redecl_range redecl_range;
1739 typedef redeclarable_base::redecl_iterator redecl_iterator;
1740 using redeclarable_base::redecls_begin;
1741 using redeclarable_base::redecls_end;
1742 using redeclarable_base::redecls;
1743 using redeclarable_base::getPreviousDecl;
1744 using redeclarable_base::getMostRecentDecl;
1745 using redeclarable_base::isFirstDecl;
1747 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1748 SourceLocation StartLoc, SourceLocation NLoc,
1749 DeclarationName N, QualType T,
1750 TypeSourceInfo *TInfo,
1752 bool isInlineSpecified = false,
1753 bool hasWrittenPrototype = true,
1754 bool isConstexprSpecified = false) {
1755 DeclarationNameInfo NameInfo(N, NLoc);
1756 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1758 isInlineSpecified, hasWrittenPrototype,
1759 isConstexprSpecified);
1762 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1763 SourceLocation StartLoc,
1764 const DeclarationNameInfo &NameInfo,
1765 QualType T, TypeSourceInfo *TInfo,
1767 bool isInlineSpecified,
1768 bool hasWrittenPrototype,
1769 bool isConstexprSpecified = false);
1771 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1773 DeclarationNameInfo getNameInfo() const {
1774 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1777 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1778 bool Qualified) const override;
1780 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1782 SourceRange getSourceRange() const override LLVM_READONLY;
1784 /// \brief Returns true if the function has a body (definition). The
1785 /// function body might be in any of the (re-)declarations of this
1786 /// function. The variant that accepts a FunctionDecl pointer will
1787 /// set that function declaration to the actual declaration
1788 /// containing the body (if there is one).
1789 bool hasBody(const FunctionDecl *&Definition) const;
1791 bool hasBody() const override {
1792 const FunctionDecl* Definition;
1793 return hasBody(Definition);
1796 /// hasTrivialBody - Returns whether the function has a trivial body that does
1797 /// not require any specific codegen.
1798 bool hasTrivialBody() const;
1800 /// isDefined - Returns true if the function is defined at all, including
1801 /// a deleted definition. Except for the behavior when the function is
1802 /// deleted, behaves like hasBody.
1803 bool isDefined(const FunctionDecl *&Definition) const;
1805 virtual bool isDefined() const {
1806 const FunctionDecl* Definition;
1807 return isDefined(Definition);
1810 /// \brief Get the definition for this declaration.
1811 FunctionDecl *getDefinition() {
1812 const FunctionDecl *Definition;
1813 if (isDefined(Definition))
1814 return const_cast<FunctionDecl *>(Definition);
1817 const FunctionDecl *getDefinition() const {
1818 return const_cast<FunctionDecl *>(this)->getDefinition();
1821 /// getBody - Retrieve the body (definition) of the function. The
1822 /// function body might be in any of the (re-)declarations of this
1823 /// function. The variant that accepts a FunctionDecl pointer will
1824 /// set that function declaration to the actual declaration
1825 /// containing the body (if there is one).
1826 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1827 /// unnecessary AST de-serialization of the body.
1828 Stmt *getBody(const FunctionDecl *&Definition) const;
1830 Stmt *getBody() const override {
1831 const FunctionDecl* Definition;
1832 return getBody(Definition);
1835 /// isThisDeclarationADefinition - Returns whether this specific
1836 /// declaration of the function is also a definition. This does not
1837 /// determine whether the function has been defined (e.g., in a
1838 /// previous definition); for that information, use isDefined. Note
1839 /// that this returns false for a defaulted function unless that function
1840 /// has been implicitly defined (possibly as deleted).
1841 bool isThisDeclarationADefinition() const {
1842 return IsDeleted || Body || IsLateTemplateParsed;
1845 /// doesThisDeclarationHaveABody - Returns whether this specific
1846 /// declaration of the function has a body - that is, if it is a non-
1847 /// deleted definition.
1848 bool doesThisDeclarationHaveABody() const {
1849 return Body || IsLateTemplateParsed;
1852 void setBody(Stmt *B);
1853 void setLazyBody(uint64_t Offset) { Body = Offset; }
1855 /// Whether this function is variadic.
1856 bool isVariadic() const;
1858 /// Whether this function is marked as virtual explicitly.
1859 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1860 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1862 /// Whether this virtual function is pure, i.e. makes the containing class
1864 bool isPure() const { return IsPure; }
1865 void setPure(bool P = true);
1867 /// Whether this templated function will be late parsed.
1868 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1869 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1871 /// Whether this function is "trivial" in some specialized C++ senses.
1872 /// Can only be true for default constructors, copy constructors,
1873 /// copy assignment operators, and destructors. Not meaningful until
1874 /// the class has been fully built by Sema.
1875 bool isTrivial() const { return IsTrivial; }
1876 void setTrivial(bool IT) { IsTrivial = IT; }
1878 /// Whether this function is defaulted per C++0x. Only valid for
1879 /// special member functions.
1880 bool isDefaulted() const { return IsDefaulted; }
1881 void setDefaulted(bool D = true) { IsDefaulted = D; }
1883 /// Whether this function is explicitly defaulted per C++0x. Only valid
1884 /// for special member functions.
1885 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1886 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1888 /// Whether falling off this function implicitly returns null/zero.
1889 /// If a more specific implicit return value is required, front-ends
1890 /// should synthesize the appropriate return statements.
1891 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1892 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1894 /// \brief Whether this function has a prototype, either because one
1895 /// was explicitly written or because it was "inherited" by merging
1896 /// a declaration without a prototype with a declaration that has a
1898 bool hasPrototype() const {
1899 return HasWrittenPrototype || HasInheritedPrototype;
1902 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1904 /// \brief Whether this function inherited its prototype from a
1905 /// previous declaration.
1906 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1907 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1909 /// Whether this is a (C++11) constexpr function or constexpr constructor.
1910 bool isConstexpr() const { return IsConstexpr; }
1911 void setConstexpr(bool IC) { IsConstexpr = IC; }
1913 /// \brief Indicates the function uses __try.
1914 bool usesSEHTry() const { return UsesSEHTry; }
1915 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
1917 /// \brief Whether this function has been deleted.
1919 /// A function that is "deleted" (via the C++0x "= delete" syntax)
1920 /// acts like a normal function, except that it cannot actually be
1921 /// called or have its address taken. Deleted functions are
1922 /// typically used in C++ overload resolution to attract arguments
1923 /// whose type or lvalue/rvalue-ness would permit the use of a
1924 /// different overload that would behave incorrectly. For example,
1925 /// one might use deleted functions to ban implicit conversion from
1926 /// a floating-point number to an Integer type:
1929 /// struct Integer {
1930 /// Integer(long); // construct from a long
1931 /// Integer(double) = delete; // no construction from float or double
1932 /// Integer(long double) = delete; // no construction from long double
1935 // If a function is deleted, its first declaration must be.
1936 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1937 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1938 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1940 /// \brief Determines whether this function is "main", which is the
1941 /// entry point into an executable program.
1942 bool isMain() const;
1944 /// \brief Determines whether this function is a MSVCRT user defined entry
1946 bool isMSVCRTEntryPoint() const;
1948 /// \brief Determines whether this operator new or delete is one
1949 /// of the reserved global placement operators:
1950 /// void *operator new(size_t, void *);
1951 /// void *operator new[](size_t, void *);
1952 /// void operator delete(void *, void *);
1953 /// void operator delete[](void *, void *);
1954 /// These functions have special behavior under [new.delete.placement]:
1955 /// These functions are reserved, a C++ program may not define
1956 /// functions that displace the versions in the Standard C++ library.
1957 /// The provisions of [basic.stc.dynamic] do not apply to these
1958 /// reserved placement forms of operator new and operator delete.
1960 /// This function must be an allocation or deallocation function.
1961 bool isReservedGlobalPlacementOperator() const;
1963 /// \brief Determines whether this function is one of the replaceable
1964 /// global allocation functions:
1965 /// void *operator new(size_t);
1966 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
1967 /// void *operator new[](size_t);
1968 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
1969 /// void operator delete(void *) noexcept;
1970 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
1971 /// void operator delete(void *, const std::nothrow_t &) noexcept;
1972 /// void operator delete[](void *) noexcept;
1973 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
1974 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
1975 /// These functions have special behavior under C++1y [expr.new]:
1976 /// An implementation is allowed to omit a call to a replaceable global
1977 /// allocation function. [...]
1978 bool isReplaceableGlobalAllocationFunction() const;
1980 /// Compute the language linkage.
1981 LanguageLinkage getLanguageLinkage() const;
1983 /// \brief Determines whether this function is a function with
1984 /// external, C linkage.
1985 bool isExternC() const;
1987 /// \brief Determines whether this function's context is, or is nested within,
1988 /// a C++ extern "C" linkage spec.
1989 bool isInExternCContext() const;
1991 /// \brief Determines whether this function's context is, or is nested within,
1992 /// a C++ extern "C++" linkage spec.
1993 bool isInExternCXXContext() const;
1995 /// \brief Determines whether this is a global function.
1996 bool isGlobal() const;
1998 /// \brief Determines whether this function is known to be 'noreturn', through
1999 /// an attribute on its declaration or its type.
2000 bool isNoReturn() const;
2002 /// \brief True if the function was a definition but its body was skipped.
2003 bool hasSkippedBody() const { return HasSkippedBody; }
2004 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2006 /// True if this function will eventually have a body, once it's fully parsed.
2007 bool willHaveBody() const { return WillHaveBody; }
2008 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2010 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2012 FunctionDecl *getCanonicalDecl() override;
2013 const FunctionDecl *getCanonicalDecl() const {
2014 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2017 unsigned getBuiltinID() const;
2019 // ArrayRef interface to parameters.
2020 ArrayRef<ParmVarDecl *> parameters() const {
2021 return {ParamInfo, getNumParams()};
2023 MutableArrayRef<ParmVarDecl *> parameters() {
2024 return {ParamInfo, getNumParams()};
2027 // Iterator access to formal parameters.
2028 typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
2029 typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
2030 bool param_empty() const { return parameters().empty(); }
2031 param_iterator param_begin() { return parameters().begin(); }
2032 param_iterator param_end() { return parameters().end(); }
2033 param_const_iterator param_begin() const { return parameters().begin(); }
2034 param_const_iterator param_end() const { return parameters().end(); }
2035 size_t param_size() const { return parameters().size(); }
2037 /// getNumParams - Return the number of parameters this function must have
2038 /// based on its FunctionType. This is the length of the ParamInfo array
2039 /// after it has been created.
2040 unsigned getNumParams() const;
2042 const ParmVarDecl *getParamDecl(unsigned i) const {
2043 assert(i < getNumParams() && "Illegal param #");
2044 return ParamInfo[i];
2046 ParmVarDecl *getParamDecl(unsigned i) {
2047 assert(i < getNumParams() && "Illegal param #");
2048 return ParamInfo[i];
2050 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2051 setParams(getASTContext(), NewParamInfo);
2054 /// getMinRequiredArguments - Returns the minimum number of arguments
2055 /// needed to call this function. This may be fewer than the number of
2056 /// function parameters, if some of the parameters have default
2057 /// arguments (in C++).
2058 unsigned getMinRequiredArguments() const;
2060 QualType getReturnType() const {
2061 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2062 return getType()->getAs<FunctionType>()->getReturnType();
2065 /// \brief Attempt to compute an informative source range covering the
2066 /// function return type. This may omit qualifiers and other information with
2067 /// limited representation in the AST.
2068 SourceRange getReturnTypeSourceRange() const;
2070 /// \brief Attempt to compute an informative source range covering the
2071 /// function exception specification, if any.
2072 SourceRange getExceptionSpecSourceRange() const;
2074 /// \brief Determine the type of an expression that calls this function.
2075 QualType getCallResultType() const {
2076 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2077 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2080 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2081 /// function, or its return type declaration.
2082 const Attr *getUnusedResultAttr() const;
2084 /// \brief Returns true if this function or its return type has the
2085 /// warn_unused_result attribute.
2086 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2088 /// \brief Returns the storage class as written in the source. For the
2089 /// computed linkage of symbol, see getLinkage.
2090 StorageClass getStorageClass() const { return StorageClass(SClass); }
2092 /// \brief Determine whether the "inline" keyword was specified for this
2094 bool isInlineSpecified() const { return IsInlineSpecified; }
2096 /// Set whether the "inline" keyword was specified for this function.
2097 void setInlineSpecified(bool I) {
2098 IsInlineSpecified = I;
2102 /// Flag that this function is implicitly inline.
2103 void setImplicitlyInline() {
2107 /// \brief Determine whether this function should be inlined, because it is
2108 /// either marked "inline" or "constexpr" or is a member function of a class
2109 /// that was defined in the class body.
2110 bool isInlined() const { return IsInline; }
2112 bool isInlineDefinitionExternallyVisible() const;
2114 bool isMSExternInline() const;
2116 bool doesDeclarationForceExternallyVisibleDefinition() const;
2118 /// isOverloadedOperator - Whether this function declaration
2119 /// represents an C++ overloaded operator, e.g., "operator+".
2120 bool isOverloadedOperator() const {
2121 return getOverloadedOperator() != OO_None;
2124 OverloadedOperatorKind getOverloadedOperator() const;
2126 const IdentifierInfo *getLiteralIdentifier() const;
2128 /// \brief If this function is an instantiation of a member function
2129 /// of a class template specialization, retrieves the function from
2130 /// which it was instantiated.
2132 /// This routine will return non-NULL for (non-templated) member
2133 /// functions of class templates and for instantiations of function
2134 /// templates. For example, given:
2137 /// template<typename T>
2143 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2144 /// whose parent is the class template specialization X<int>. For
2145 /// this declaration, getInstantiatedFromFunction() will return
2146 /// the FunctionDecl X<T>::A. When a complete definition of
2147 /// X<int>::A is required, it will be instantiated from the
2148 /// declaration returned by getInstantiatedFromMemberFunction().
2149 FunctionDecl *getInstantiatedFromMemberFunction() const;
2151 /// \brief What kind of templated function this is.
2152 TemplatedKind getTemplatedKind() const;
2154 /// \brief If this function is an instantiation of a member function of a
2155 /// class template specialization, retrieves the member specialization
2157 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2159 /// \brief Specify that this record is an instantiation of the
2160 /// member function FD.
2161 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2162 TemplateSpecializationKind TSK) {
2163 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2166 /// \brief Retrieves the function template that is described by this
2167 /// function declaration.
2169 /// Every function template is represented as a FunctionTemplateDecl
2170 /// and a FunctionDecl (or something derived from FunctionDecl). The
2171 /// former contains template properties (such as the template
2172 /// parameter lists) while the latter contains the actual
2173 /// description of the template's
2174 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2175 /// FunctionDecl that describes the function template,
2176 /// getDescribedFunctionTemplate() retrieves the
2177 /// FunctionTemplateDecl from a FunctionDecl.
2178 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2180 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2182 /// \brief Determine whether this function is a function template
2184 bool isFunctionTemplateSpecialization() const {
2185 return getPrimaryTemplate() != nullptr;
2188 /// \brief Retrieve the class scope template pattern that this function
2189 /// template specialization is instantiated from.
2190 FunctionDecl *getClassScopeSpecializationPattern() const;
2192 /// \brief If this function is actually a function template specialization,
2193 /// retrieve information about this function template specialization.
2194 /// Otherwise, returns NULL.
2195 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2197 /// \brief Determines whether this function is a function template
2198 /// specialization or a member of a class template specialization that can
2199 /// be implicitly instantiated.
2200 bool isImplicitlyInstantiable() const;
2202 /// \brief Determines if the given function was instantiated from a
2203 /// function template.
2204 bool isTemplateInstantiation() const;
2206 /// \brief Retrieve the function declaration from which this function could
2207 /// be instantiated, if it is an instantiation (rather than a non-template
2208 /// or a specialization, for example).
2209 FunctionDecl *getTemplateInstantiationPattern() const;
2211 /// \brief Retrieve the primary template that this function template
2212 /// specialization either specializes or was instantiated from.
2214 /// If this function declaration is not a function template specialization,
2216 FunctionTemplateDecl *getPrimaryTemplate() const;
2218 /// \brief Retrieve the template arguments used to produce this function
2219 /// template specialization from the primary template.
2221 /// If this function declaration is not a function template specialization,
2223 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2225 /// \brief Retrieve the template argument list as written in the sources,
2228 /// If this function declaration is not a function template specialization
2229 /// or if it had no explicit template argument list, returns NULL.
2230 /// Note that it an explicit template argument list may be written empty,
2231 /// e.g., template<> void foo<>(char* s);
2232 const ASTTemplateArgumentListInfo*
2233 getTemplateSpecializationArgsAsWritten() const;
2235 /// \brief Specify that this function declaration is actually a function
2236 /// template specialization.
2238 /// \param Template the function template that this function template
2239 /// specialization specializes.
2241 /// \param TemplateArgs the template arguments that produced this
2242 /// function template specialization from the template.
2244 /// \param InsertPos If non-NULL, the position in the function template
2245 /// specialization set where the function template specialization data will
2248 /// \param TSK the kind of template specialization this is.
2250 /// \param TemplateArgsAsWritten location info of template arguments.
2252 /// \param PointOfInstantiation point at which the function template
2253 /// specialization was first instantiated.
2254 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2255 const TemplateArgumentList *TemplateArgs,
2257 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2258 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2259 SourceLocation PointOfInstantiation = SourceLocation()) {
2260 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2261 InsertPos, TSK, TemplateArgsAsWritten,
2262 PointOfInstantiation);
2265 /// \brief Specifies that this function declaration is actually a
2266 /// dependent function template specialization.
2267 void setDependentTemplateSpecialization(ASTContext &Context,
2268 const UnresolvedSetImpl &Templates,
2269 const TemplateArgumentListInfo &TemplateArgs);
2271 DependentFunctionTemplateSpecializationInfo *
2272 getDependentSpecializationInfo() const;
2274 /// \brief Determine what kind of template instantiation this function
2276 TemplateSpecializationKind getTemplateSpecializationKind() const;
2278 /// \brief Determine what kind of template instantiation this function
2280 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2281 SourceLocation PointOfInstantiation = SourceLocation());
2283 /// \brief Retrieve the (first) point of instantiation of a function template
2284 /// specialization or a member of a class template specialization.
2286 /// \returns the first point of instantiation, if this function was
2287 /// instantiated from a template; otherwise, returns an invalid source
2289 SourceLocation getPointOfInstantiation() const;
2291 /// \brief Determine whether this is or was instantiated from an out-of-line
2292 /// definition of a member function.
2293 bool isOutOfLine() const override;
2295 /// \brief Identify a memory copying or setting function.
2296 /// If the given function is a memory copy or setting function, returns
2297 /// the corresponding Builtin ID. If the function is not a memory function,
2299 unsigned getMemoryFunctionKind() const;
2301 // Implement isa/cast/dyncast/etc.
2302 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2303 static bool classofKind(Kind K) {
2304 return K >= firstFunction && K <= lastFunction;
2306 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2307 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2309 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2310 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2313 friend class ASTDeclReader;
2314 friend class ASTDeclWriter;
2318 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2319 /// represent a member of a struct/union/class.
2320 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2321 // FIXME: This can be packed into the bitfields in Decl.
2322 unsigned Mutable : 1;
2323 mutable unsigned CachedFieldIndex : 31;
2325 /// The kinds of value we can store in InitializerOrBitWidth.
2327 /// Note that this is compatible with InClassInitStyle except for
2328 /// ISK_CapturedVLAType.
2329 enum InitStorageKind {
2330 /// If the pointer is null, there's nothing special. Otherwise,
2331 /// this is a bitfield and the pointer is the Expr* storing the
2333 ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
2335 /// The pointer is an (optional due to delayed parsing) Expr*
2336 /// holding the copy-initializer.
2337 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2339 /// The pointer is an (optional due to delayed parsing) Expr*
2340 /// holding the list-initializer.
2341 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2343 /// The pointer is a VariableArrayType* that's been captured;
2344 /// the enclosing context is a lambda or captured statement.
2345 ISK_CapturedVLAType,
2348 /// \brief Storage for either the bit-width, the in-class
2349 /// initializer, or the captured variable length array bound.
2351 /// We can safely combine these because in-class initializers are
2352 /// not permitted for bit-fields, and both are exclusive with VLA
2355 /// If the storage kind is ISK_InClassCopyInit or
2356 /// ISK_InClassListInit, but the initializer is null, then this
2357 /// field has an in-class initializer which has not yet been parsed
2359 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2361 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2362 SourceLocation IdLoc, IdentifierInfo *Id,
2363 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2364 InClassInitStyle InitStyle)
2365 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2366 Mutable(Mutable), CachedFieldIndex(0),
2367 InitStorage(BW, (InitStorageKind) InitStyle) {
2368 assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2372 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2373 SourceLocation StartLoc, SourceLocation IdLoc,
2374 IdentifierInfo *Id, QualType T,
2375 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2376 InClassInitStyle InitStyle);
2378 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2380 /// getFieldIndex - Returns the index of this field within its record,
2381 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2382 unsigned getFieldIndex() const;
2384 /// isMutable - Determines whether this field is mutable (C++ only).
2385 bool isMutable() const { return Mutable; }
2387 /// \brief Determines whether this field is a bitfield.
2388 bool isBitField() const {
2389 return InitStorage.getInt() == ISK_BitWidthOrNothing &&
2390 InitStorage.getPointer() != nullptr;
2393 /// @brief Determines whether this is an unnamed bitfield.
2394 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2396 /// isAnonymousStructOrUnion - Determines whether this field is a
2397 /// representative for an anonymous struct or union. Such fields are
2398 /// unnamed and are implicitly generated by the implementation to
2399 /// store the data for the anonymous union or struct.
2400 bool isAnonymousStructOrUnion() const;
2402 Expr *getBitWidth() const {
2404 ? static_cast<Expr *>(InitStorage.getPointer())
2407 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2409 /// setBitWidth - Set the bit-field width for this member.
2410 // Note: used by some clients (i.e., do not remove it).
2411 void setBitWidth(Expr *Width) {
2412 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
2413 InitStorage.getPointer() == nullptr &&
2414 "bit width, initializer or captured type already set");
2415 InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
2418 /// removeBitWidth - Remove the bit-field width from this member.
2419 // Note: used by some clients (i.e., do not remove it).
2420 void removeBitWidth() {
2421 assert(isBitField() && "no bitfield width to remove");
2422 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2425 /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2427 InClassInitStyle getInClassInitStyle() const {
2428 InitStorageKind storageKind = InitStorage.getInt();
2429 return (storageKind == ISK_CapturedVLAType
2430 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2433 /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2435 bool hasInClassInitializer() const {
2436 return getInClassInitStyle() != ICIS_NoInit;
2439 /// getInClassInitializer - Get the C++11 in-class initializer for this
2440 /// member, or null if one has not been set. If a valid declaration has an
2441 /// in-class initializer, but this returns null, then we have not parsed and
2442 /// attached it yet.
2443 Expr *getInClassInitializer() const {
2444 return hasInClassInitializer()
2445 ? static_cast<Expr *>(InitStorage.getPointer())
2449 /// setInClassInitializer - Set the C++11 in-class initializer for this
2451 void setInClassInitializer(Expr *Init) {
2452 assert(hasInClassInitializer() &&
2453 InitStorage.getPointer() == nullptr &&
2454 "bit width, initializer or captured type already set");
2455 InitStorage.setPointer(Init);
2458 /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2460 void removeInClassInitializer() {
2461 assert(hasInClassInitializer() && "no initializer to remove");
2462 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2465 /// \brief Determine whether this member captures the variable length array
2467 bool hasCapturedVLAType() const {
2468 return InitStorage.getInt() == ISK_CapturedVLAType;
2471 /// \brief Get the captured variable length array type.
2472 const VariableArrayType *getCapturedVLAType() const {
2473 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2474 InitStorage.getPointer())
2477 /// \brief Set the captured variable length array type for this field.
2478 void setCapturedVLAType(const VariableArrayType *VLAType);
2480 /// getParent - Returns the parent of this field declaration, which
2481 /// is the struct in which this method is defined.
2482 const RecordDecl *getParent() const {
2483 return cast<RecordDecl>(getDeclContext());
2486 RecordDecl *getParent() {
2487 return cast<RecordDecl>(getDeclContext());
2490 SourceRange getSourceRange() const override LLVM_READONLY;
2492 /// Retrieves the canonical declaration of this field.
2493 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2494 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2496 // Implement isa/cast/dyncast/etc.
2497 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2498 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2500 friend class ASTDeclReader;
2501 friend class ASTDeclWriter;
2504 /// EnumConstantDecl - An instance of this object exists for each enum constant
2505 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2506 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2507 /// TagType for the X EnumDecl.
2508 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2509 Stmt *Init; // an integer constant expression
2510 llvm::APSInt Val; // The value.
2512 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2513 IdentifierInfo *Id, QualType T, Expr *E,
2514 const llvm::APSInt &V)
2515 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2519 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2520 SourceLocation L, IdentifierInfo *Id,
2521 QualType T, Expr *E,
2522 const llvm::APSInt &V);
2523 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2525 const Expr *getInitExpr() const { return (const Expr*) Init; }
2526 Expr *getInitExpr() { return (Expr*) Init; }
2527 const llvm::APSInt &getInitVal() const { return Val; }
2529 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2530 void setInitVal(const llvm::APSInt &V) { Val = V; }
2532 SourceRange getSourceRange() const override LLVM_READONLY;
2534 /// Retrieves the canonical declaration of this enumerator.
2535 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2536 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2538 // Implement isa/cast/dyncast/etc.
2539 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2540 static bool classofKind(Kind K) { return K == EnumConstant; }
2542 friend class StmtIteratorBase;
2545 /// IndirectFieldDecl - An instance of this class is created to represent a
2546 /// field injected from an anonymous union/struct into the parent scope.
2547 /// IndirectFieldDecl are always implicit.
2548 class IndirectFieldDecl : public ValueDecl,
2549 public Mergeable<IndirectFieldDecl> {
2550 void anchor() override;
2551 NamedDecl **Chaining;
2552 unsigned ChainingSize;
2554 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2555 DeclarationName N, QualType T,
2556 MutableArrayRef<NamedDecl *> CH);
2559 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2560 SourceLocation L, IdentifierInfo *Id,
2561 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2563 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2565 typedef ArrayRef<NamedDecl *>::const_iterator chain_iterator;
2567 ArrayRef<NamedDecl *> chain() const {
2568 return llvm::makeArrayRef(Chaining, ChainingSize);
2570 chain_iterator chain_begin() const { return chain().begin(); }
2571 chain_iterator chain_end() const { return chain().end(); }
2573 unsigned getChainingSize() const { return ChainingSize; }
2575 FieldDecl *getAnonField() const {
2576 assert(chain().size() >= 2);
2577 return cast<FieldDecl>(chain().back());
2580 VarDecl *getVarDecl() const {
2581 assert(chain().size() >= 2);
2582 return dyn_cast<VarDecl>(chain().front());
2585 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2586 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2588 // Implement isa/cast/dyncast/etc.
2589 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2590 static bool classofKind(Kind K) { return K == IndirectField; }
2591 friend class ASTDeclReader;
2594 /// TypeDecl - Represents a declaration of a type.
2596 class TypeDecl : public NamedDecl {
2597 void anchor() override;
2598 /// TypeForDecl - This indicates the Type object that represents
2599 /// this TypeDecl. It is a cache maintained by
2600 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2601 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2602 mutable const Type *TypeForDecl;
2603 /// LocStart - The start of the source range for this declaration.
2604 SourceLocation LocStart;
2605 friend class ASTContext;
2608 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2609 SourceLocation StartL = SourceLocation())
2610 : NamedDecl(DK, DC, L, Id), TypeForDecl(nullptr), LocStart(StartL) {}
2613 // Low-level accessor. If you just want the type defined by this node,
2614 // check out ASTContext::getTypeDeclType or one of
2615 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2616 // already know the specific kind of node this is.
2617 const Type *getTypeForDecl() const { return TypeForDecl; }
2618 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2620 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2621 void setLocStart(SourceLocation L) { LocStart = L; }
2622 SourceRange getSourceRange() const override LLVM_READONLY {
2623 if (LocStart.isValid())
2624 return SourceRange(LocStart, getLocation());
2626 return SourceRange(getLocation());
2629 // Implement isa/cast/dyncast/etc.
2630 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2631 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2635 /// Base class for declarations which introduce a typedef-name.
2636 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2637 void anchor() override;
2638 typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
2639 llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
2641 // FIXME: This can be packed into the bitfields in Decl.
2642 /// If 0, we have not computed IsTransparentTag.
2643 /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
2644 mutable unsigned CacheIsTransparentTag : 2;
2647 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2648 SourceLocation StartLoc, SourceLocation IdLoc,
2649 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2650 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2651 MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
2653 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2654 TypedefNameDecl *getNextRedeclarationImpl() override {
2655 return getNextRedeclaration();
2657 TypedefNameDecl *getPreviousDeclImpl() override {
2658 return getPreviousDecl();
2660 TypedefNameDecl *getMostRecentDeclImpl() override {
2661 return getMostRecentDecl();
2665 typedef redeclarable_base::redecl_range redecl_range;
2666 typedef redeclarable_base::redecl_iterator redecl_iterator;
2667 using redeclarable_base::redecls_begin;
2668 using redeclarable_base::redecls_end;
2669 using redeclarable_base::redecls;
2670 using redeclarable_base::getPreviousDecl;
2671 using redeclarable_base::getMostRecentDecl;
2672 using redeclarable_base::isFirstDecl;
2674 bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2676 TypeSourceInfo *getTypeSourceInfo() const {
2678 ? MaybeModedTInfo.get<ModedTInfo*>()->first
2679 : MaybeModedTInfo.get<TypeSourceInfo*>();
2681 QualType getUnderlyingType() const {
2683 ? MaybeModedTInfo.get<ModedTInfo*>()->second
2684 : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2686 void setTypeSourceInfo(TypeSourceInfo *newType) {
2687 MaybeModedTInfo = newType;
2689 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2690 MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2693 /// Retrieves the canonical declaration of this typedef-name.
2694 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2695 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2697 /// Retrieves the tag declaration for which this is the typedef name for
2698 /// linkage purposes, if any.
2700 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2701 /// this typedef declaration.
2702 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2704 /// Determines if this typedef shares a name and spelling location with its
2705 /// underlying tag type, as is the case with the NS_ENUM macro.
2706 bool isTransparentTag() const {
2707 if (CacheIsTransparentTag)
2708 return CacheIsTransparentTag & 0x2;
2709 return isTransparentTagSlow();
2712 // Implement isa/cast/dyncast/etc.
2713 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2714 static bool classofKind(Kind K) {
2715 return K >= firstTypedefName && K <= lastTypedefName;
2719 bool isTransparentTagSlow() const;
2722 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2724 class TypedefDecl : public TypedefNameDecl {
2725 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2726 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2727 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2730 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2731 SourceLocation StartLoc, SourceLocation IdLoc,
2732 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2733 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2735 SourceRange getSourceRange() const override LLVM_READONLY;
2737 // Implement isa/cast/dyncast/etc.
2738 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2739 static bool classofKind(Kind K) { return K == Typedef; }
2742 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2743 /// alias-declaration.
2744 class TypeAliasDecl : public TypedefNameDecl {
2745 /// The template for which this is the pattern, if any.
2746 TypeAliasTemplateDecl *Template;
2748 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2749 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2750 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2751 Template(nullptr) {}
2754 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2755 SourceLocation StartLoc, SourceLocation IdLoc,
2756 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2757 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2759 SourceRange getSourceRange() const override LLVM_READONLY;
2761 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2762 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2764 // Implement isa/cast/dyncast/etc.
2765 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2766 static bool classofKind(Kind K) { return K == TypeAlias; }
2769 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2771 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2773 // This is really ugly.
2774 typedef TagTypeKind TagKind;
2777 // FIXME: This can be packed into the bitfields in Decl.
2778 /// TagDeclKind - The TagKind enum.
2779 unsigned TagDeclKind : 3;
2781 /// IsCompleteDefinition - True if this is a definition ("struct foo
2782 /// {};"), false if it is a declaration ("struct foo;"). It is not
2783 /// a definition until the definition has been fully processed.
2784 unsigned IsCompleteDefinition : 1;
2787 /// IsBeingDefined - True if this is currently being defined.
2788 unsigned IsBeingDefined : 1;
2791 /// IsEmbeddedInDeclarator - True if this tag declaration is
2792 /// "embedded" (i.e., defined or declared for the very first time)
2793 /// in the syntax of a declarator.
2794 unsigned IsEmbeddedInDeclarator : 1;
2796 /// \brief True if this tag is free standing, e.g. "struct foo;".
2797 unsigned IsFreeStanding : 1;
2800 // These are used by (and only defined for) EnumDecl.
2801 unsigned NumPositiveBits : 8;
2802 unsigned NumNegativeBits : 8;
2804 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2805 /// possible in C++11 mode.
2806 unsigned IsScoped : 1;
2807 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2808 /// then this is true if the scoped enum was declared using the class
2809 /// tag, false if it was declared with the struct tag. No meaning is
2810 /// associated if this tag declaration is not a scoped enum.
2811 unsigned IsScopedUsingClassTag : 1;
2813 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2814 /// possible in C++11, Microsoft extensions, or Objective C mode.
2815 unsigned IsFixed : 1;
2817 /// \brief Indicates whether it is possible for declarations of this kind
2818 /// to have an out-of-date definition.
2820 /// This option is only enabled when modules are enabled.
2821 unsigned MayHaveOutOfDateDef : 1;
2823 /// Has the full definition of this type been required by a use somewhere in
2825 unsigned IsCompleteDefinitionRequired : 1;
2827 SourceRange BraceRange;
2829 // A struct representing syntactic qualifier info,
2830 // to be used for the (uncommon) case of out-of-line declarations.
2831 typedef QualifierInfo ExtInfo;
2833 /// \brief If the (out-of-line) tag declaration name
2834 /// is qualified, it points to the qualifier info (nns and range);
2835 /// otherwise, if the tag declaration is anonymous and it is part of
2836 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2837 /// otherwise, if the tag declaration is anonymous and it is used as a
2838 /// declaration specifier for variables, it points to the first VarDecl (used
2840 /// otherwise, it is a null (TypedefNameDecl) pointer.
2841 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
2843 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
2844 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
2845 const ExtInfo *getExtInfo() const {
2846 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
2850 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
2851 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
2852 SourceLocation StartL)
2853 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
2854 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
2855 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
2856 IsCompleteDefinitionRequired(false),
2857 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
2858 assert((DK != Enum || TK == TTK_Enum) &&
2859 "EnumDecl not matched with TTK_Enum");
2860 setPreviousDecl(PrevDecl);
2863 typedef Redeclarable<TagDecl> redeclarable_base;
2864 TagDecl *getNextRedeclarationImpl() override {
2865 return getNextRedeclaration();
2867 TagDecl *getPreviousDeclImpl() override {
2868 return getPreviousDecl();
2870 TagDecl *getMostRecentDeclImpl() override {
2871 return getMostRecentDecl();
2874 /// @brief Completes the definition of this tag declaration.
2876 /// This is a helper function for derived classes.
2877 void completeDefinition();
2880 typedef redeclarable_base::redecl_range redecl_range;
2881 typedef redeclarable_base::redecl_iterator redecl_iterator;
2882 using redeclarable_base::redecls_begin;
2883 using redeclarable_base::redecls_end;
2884 using redeclarable_base::redecls;
2885 using redeclarable_base::getPreviousDecl;
2886 using redeclarable_base::getMostRecentDecl;
2887 using redeclarable_base::isFirstDecl;
2889 SourceRange getBraceRange() const { return BraceRange; }
2890 void setBraceRange(SourceRange R) { BraceRange = R; }
2892 /// getInnerLocStart - Return SourceLocation representing start of source
2893 /// range ignoring outer template declarations.
2894 SourceLocation getInnerLocStart() const { return getLocStart(); }
2896 /// getOuterLocStart - Return SourceLocation representing start of source
2897 /// range taking into account any outer template declarations.
2898 SourceLocation getOuterLocStart() const;
2899 SourceRange getSourceRange() const override LLVM_READONLY;
2901 TagDecl *getCanonicalDecl() override;
2902 const TagDecl *getCanonicalDecl() const {
2903 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2906 /// isThisDeclarationADefinition() - Return true if this declaration
2907 /// is a completion definition of the type. Provided for consistency.
2908 bool isThisDeclarationADefinition() const {
2909 return isCompleteDefinition();
2912 /// isCompleteDefinition - Return true if this decl has its body
2913 /// fully specified.
2914 bool isCompleteDefinition() const {
2915 return IsCompleteDefinition;
2918 /// \brief Return true if this complete decl is
2919 /// required to be complete for some existing use.
2920 bool isCompleteDefinitionRequired() const {
2921 return IsCompleteDefinitionRequired;
2924 /// isBeingDefined - Return true if this decl is currently being defined.
2925 bool isBeingDefined() const {
2926 return IsBeingDefined;
2929 bool isEmbeddedInDeclarator() const {
2930 return IsEmbeddedInDeclarator;
2932 void setEmbeddedInDeclarator(bool isInDeclarator) {
2933 IsEmbeddedInDeclarator = isInDeclarator;
2936 bool isFreeStanding() const { return IsFreeStanding; }
2937 void setFreeStanding(bool isFreeStanding = true) {
2938 IsFreeStanding = isFreeStanding;
2941 /// \brief Whether this declaration declares a type that is
2942 /// dependent, i.e., a type that somehow depends on template
2944 bool isDependentType() const { return isDependentContext(); }
2946 /// @brief Starts the definition of this tag declaration.
2948 /// This method should be invoked at the beginning of the definition
2949 /// of this tag declaration. It will set the tag type into a state
2950 /// where it is in the process of being defined.
2951 void startDefinition();
2953 /// getDefinition - Returns the TagDecl that actually defines this
2954 /// struct/union/class/enum. When determining whether or not a
2955 /// struct/union/class/enum has a definition, one should use this
2956 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
2957 /// whether or not a specific TagDecl is defining declaration, not
2958 /// whether or not the struct/union/class/enum type is defined.
2959 /// This method returns NULL if there is no TagDecl that defines
2960 /// the struct/union/class/enum.
2961 TagDecl *getDefinition() const;
2963 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2965 void setCompleteDefinitionRequired(bool V = true) {
2966 IsCompleteDefinitionRequired = V;
2969 StringRef getKindName() const {
2970 return TypeWithKeyword::getTagTypeKindName(getTagKind());
2973 TagKind getTagKind() const {
2974 return TagKind(TagDeclKind);
2977 void setTagKind(TagKind TK) { TagDeclKind = TK; }
2979 bool isStruct() const { return getTagKind() == TTK_Struct; }
2980 bool isInterface() const { return getTagKind() == TTK_Interface; }
2981 bool isClass() const { return getTagKind() == TTK_Class; }
2982 bool isUnion() const { return getTagKind() == TTK_Union; }
2983 bool isEnum() const { return getTagKind() == TTK_Enum; }
2985 /// Is this tag type named, either directly or via being defined in
2986 /// a typedef of this type?
2988 /// C++11 [basic.link]p8:
2989 /// A type is said to have linkage if and only if:
2990 /// - it is a class or enumeration type that is named (or has a
2991 /// name for linkage purposes) and the name has linkage; ...
2992 /// C++11 [dcl.typedef]p9:
2993 /// If the typedef declaration defines an unnamed class (or enum),
2994 /// the first typedef-name declared by the declaration to be that
2995 /// class type (or enum type) is used to denote the class type (or
2996 /// enum type) for linkage purposes only.
2998 /// C does not have an analogous rule, but the same concept is
2999 /// nonetheless useful in some places.
3000 bool hasNameForLinkage() const {
3001 return (getDeclName() || getTypedefNameForAnonDecl());
3004 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3005 return hasExtInfo() ? nullptr
3006 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3009 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3011 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3012 /// declaration, if it was present in the source.
3013 NestedNameSpecifier *getQualifier() const {
3014 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3018 /// \brief Retrieve the nested-name-specifier (with source-location
3019 /// information) that qualifies the name of this declaration, if it was
3020 /// present in the source.
3021 NestedNameSpecifierLoc getQualifierLoc() const {
3022 return hasExtInfo() ? getExtInfo()->QualifierLoc
3023 : NestedNameSpecifierLoc();
3026 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3028 unsigned getNumTemplateParameterLists() const {
3029 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3031 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3032 assert(i < getNumTemplateParameterLists());
3033 return getExtInfo()->TemplParamLists[i];
3035 void setTemplateParameterListsInfo(ASTContext &Context,
3036 ArrayRef<TemplateParameterList *> TPLists);
3038 // Implement isa/cast/dyncast/etc.
3039 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3040 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3042 static DeclContext *castToDeclContext(const TagDecl *D) {
3043 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3045 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3046 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3049 friend class ASTDeclReader;
3050 friend class ASTDeclWriter;
3053 /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
3054 /// with a fixed underlying type, and in C we allow them to be forward-declared
3055 /// with no underlying type as an extension.
3056 class EnumDecl : public TagDecl {
3057 void anchor() override;
3058 /// IntegerType - This represent the integer type that the enum corresponds
3059 /// to for code generation purposes. Note that the enumerator constants may
3060 /// have a different type than this does.
3062 /// If the underlying integer type was explicitly stated in the source
3063 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3064 /// was automatically deduced somehow, and this is a Type*.
3066 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3067 /// some cases it won't.
3069 /// The underlying type of an enumeration never has any qualifiers, so
3070 /// we can get away with just storing a raw Type*, and thus save an
3071 /// extra pointer when TypeSourceInfo is needed.
3073 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
3075 /// PromotionType - The integer type that values of this type should
3076 /// promote to. In C, enumerators are generally of an integer type
3077 /// directly, but gcc-style large enumerators (and all enumerators
3078 /// in C++) are of the enum type instead.
3079 QualType PromotionType;
3081 /// \brief If this enumeration is an instantiation of a member enumeration
3082 /// of a class template specialization, this is the member specialization
3084 MemberSpecializationInfo *SpecializationInfo;
3086 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3087 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3088 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3089 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3090 SpecializationInfo(nullptr) {
3091 assert(Scoped || !ScopedUsingClassTag);
3092 IntegerType = (const Type *)nullptr;
3093 NumNegativeBits = 0;
3094 NumPositiveBits = 0;
3096 IsScopedUsingClassTag = ScopedUsingClassTag;
3100 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3101 TemplateSpecializationKind TSK);
3103 EnumDecl *getCanonicalDecl() override {
3104 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3106 const EnumDecl *getCanonicalDecl() const {
3107 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3110 EnumDecl *getPreviousDecl() {
3111 return cast_or_null<EnumDecl>(
3112 static_cast<TagDecl *>(this)->getPreviousDecl());
3114 const EnumDecl *getPreviousDecl() const {
3115 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3118 EnumDecl *getMostRecentDecl() {
3119 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3121 const EnumDecl *getMostRecentDecl() const {
3122 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3125 EnumDecl *getDefinition() const {
3126 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3129 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3130 SourceLocation StartLoc, SourceLocation IdLoc,
3131 IdentifierInfo *Id, EnumDecl *PrevDecl,
3132 bool IsScoped, bool IsScopedUsingClassTag,
3134 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3136 /// completeDefinition - When created, the EnumDecl corresponds to a
3137 /// forward-declared enum. This method is used to mark the
3138 /// declaration as being defined; it's enumerators have already been
3139 /// added (via DeclContext::addDecl). NewType is the new underlying
3140 /// type of the enumeration type.
3141 void completeDefinition(QualType NewType,
3142 QualType PromotionType,
3143 unsigned NumPositiveBits,
3144 unsigned NumNegativeBits);
3146 // enumerator_iterator - Iterates through the enumerators of this
3148 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
3149 typedef llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>
3152 enumerator_range enumerators() const {
3153 return enumerator_range(enumerator_begin(), enumerator_end());
3156 enumerator_iterator enumerator_begin() const {
3157 const EnumDecl *E = getDefinition();
3160 return enumerator_iterator(E->decls_begin());
3163 enumerator_iterator enumerator_end() const {
3164 const EnumDecl *E = getDefinition();
3167 return enumerator_iterator(E->decls_end());
3170 /// getPromotionType - Return the integer type that enumerators
3171 /// should promote to.
3172 QualType getPromotionType() const { return PromotionType; }
3174 /// \brief Set the promotion type.
3175 void setPromotionType(QualType T) { PromotionType = T; }
3177 /// getIntegerType - Return the integer type this enum decl corresponds to.
3178 /// This returns a null QualType for an enum forward definition with no fixed
3179 /// underlying type.
3180 QualType getIntegerType() const {
3183 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3184 return QualType(T, 0);
3185 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3188 /// \brief Set the underlying integer type.
3189 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3191 /// \brief Set the underlying integer type source info.
3192 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3194 /// \brief Return the type source info for the underlying integer type,
3195 /// if no type source info exists, return 0.
3196 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3197 return IntegerType.dyn_cast<TypeSourceInfo*>();
3200 /// \brief Retrieve the source range that covers the underlying type if
3202 SourceRange getIntegerTypeRange() const LLVM_READONLY;
3204 /// \brief Returns the width in bits required to store all the
3205 /// non-negative enumerators of this enum.
3206 unsigned getNumPositiveBits() const {
3207 return NumPositiveBits;
3209 void setNumPositiveBits(unsigned Num) {
3210 NumPositiveBits = Num;
3211 assert(NumPositiveBits == Num && "can't store this bitcount");
3214 /// \brief Returns the width in bits required to store all the
3215 /// negative enumerators of this enum. These widths include
3216 /// the rightmost leading 1; that is:
3218 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3219 /// ------------------------ ------- -----------------
3223 unsigned getNumNegativeBits() const {
3224 return NumNegativeBits;
3226 void setNumNegativeBits(unsigned Num) {
3227 NumNegativeBits = Num;
3230 /// \brief Returns true if this is a C++11 scoped enumeration.
3231 bool isScoped() const {
3235 /// \brief Returns true if this is a C++11 scoped enumeration.
3236 bool isScopedUsingClassTag() const {
3237 return IsScopedUsingClassTag;
3240 /// \brief Returns true if this is an Objective-C, C++11, or
3241 /// Microsoft-style enumeration with a fixed underlying type.
3242 bool isFixed() const {
3246 /// \brief Returns true if this can be considered a complete type.
3247 bool isComplete() const {
3248 return isCompleteDefinition() || isFixed();
3251 /// Returns true if this enum is either annotated with
3252 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3253 bool isClosed() const;
3255 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3256 /// with enum_extensibility(open).
3257 bool isClosedFlag() const;
3259 /// Returns true if this enum is annotated with neither flag_enum nor
3260 /// enum_extensibility(open).
3261 bool isClosedNonFlag() const;
3263 /// \brief Retrieve the enum definition from which this enumeration could
3264 /// be instantiated, if it is an instantiation (rather than a non-template).
3265 EnumDecl *getTemplateInstantiationPattern() const;
3267 /// \brief Returns the enumeration (declared within the template)
3268 /// from which this enumeration type was instantiated, or NULL if
3269 /// this enumeration was not instantiated from any template.
3270 EnumDecl *getInstantiatedFromMemberEnum() const;
3272 /// \brief If this enumeration is a member of a specialization of a
3273 /// templated class, determine what kind of template specialization
3274 /// or instantiation this is.
3275 TemplateSpecializationKind getTemplateSpecializationKind() const;
3277 /// \brief For an enumeration member that was instantiated from a member
3278 /// enumeration of a templated class, set the template specialiation kind.
3279 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3280 SourceLocation PointOfInstantiation = SourceLocation());
3282 /// \brief If this enumeration is an instantiation of a member enumeration of
3283 /// a class template specialization, retrieves the member specialization
3285 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3286 return SpecializationInfo;
3289 /// \brief Specify that this enumeration is an instantiation of the
3290 /// member enumeration ED.
3291 void setInstantiationOfMemberEnum(EnumDecl *ED,
3292 TemplateSpecializationKind TSK) {
3293 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3296 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3297 static bool classofKind(Kind K) { return K == Enum; }
3299 friend class ASTDeclReader;
3303 /// RecordDecl - Represents a struct/union/class. For example:
3304 /// struct X; // Forward declaration, no "body".
3305 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3306 /// This decl will be marked invalid if *any* members are invalid.
3308 class RecordDecl : public TagDecl {
3309 // FIXME: This can be packed into the bitfields in Decl.
3310 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3311 /// array member (e.g. int X[]) or if this union contains a struct that does.
3312 /// If so, this cannot be contained in arrays or other structs as a member.
3313 bool HasFlexibleArrayMember : 1;
3315 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3317 bool AnonymousStructOrUnion : 1;
3319 /// HasObjectMember - This is true if this struct has at least one member
3320 /// containing an Objective-C object pointer type.
3321 bool HasObjectMember : 1;
3323 /// HasVolatileMember - This is true if struct has at least one member of
3324 /// 'volatile' type.
3325 bool HasVolatileMember : 1;
3327 /// \brief Whether the field declarations of this record have been loaded
3328 /// from external storage. To avoid unnecessary deserialization of
3329 /// methods/nested types we allow deserialization of just the fields
3331 mutable bool LoadedFieldsFromExternalStorage : 1;
3332 friend class DeclContext;
3335 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3336 SourceLocation StartLoc, SourceLocation IdLoc,
3337 IdentifierInfo *Id, RecordDecl *PrevDecl);
3340 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3341 SourceLocation StartLoc, SourceLocation IdLoc,
3342 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3343 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3345 RecordDecl *getPreviousDecl() {
3346 return cast_or_null<RecordDecl>(
3347 static_cast<TagDecl *>(this)->getPreviousDecl());
3349 const RecordDecl *getPreviousDecl() const {
3350 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3353 RecordDecl *getMostRecentDecl() {
3354 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3356 const RecordDecl *getMostRecentDecl() const {
3357 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3360 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3361 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3363 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3364 /// or union. To be an anonymous struct or union, it must have been
3365 /// declared without a name and there must be no objects of this
3366 /// type declared, e.g.,
3368 /// union { int i; float f; };
3370 /// is an anonymous union but neither of the following are:
3372 /// union X { int i; float f; };
3373 /// union { int i; float f; } obj;
3375 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3376 void setAnonymousStructOrUnion(bool Anon) {
3377 AnonymousStructOrUnion = Anon;
3380 bool hasObjectMember() const { return HasObjectMember; }
3381 void setHasObjectMember (bool val) { HasObjectMember = val; }
3383 bool hasVolatileMember() const { return HasVolatileMember; }
3384 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3386 bool hasLoadedFieldsFromExternalStorage() const {
3387 return LoadedFieldsFromExternalStorage;
3389 void setHasLoadedFieldsFromExternalStorage(bool val) {
3390 LoadedFieldsFromExternalStorage = val;
3393 /// \brief Determines whether this declaration represents the
3394 /// injected class name.
3396 /// The injected class name in C++ is the name of the class that
3397 /// appears inside the class itself. For example:
3401 /// // C is implicitly declared here as a synonym for the class name.
3404 /// C::C c; // same as "C c;"
3406 bool isInjectedClassName() const;
3408 /// \brief Determine whether this record is a class describing a lambda
3409 /// function object.
3410 bool isLambda() const;
3412 /// \brief Determine whether this record is a record for captured variables in
3413 /// CapturedStmt construct.
3414 bool isCapturedRecord() const;
3415 /// \brief Mark the record as a record for captured variables in CapturedStmt
3417 void setCapturedRecord();
3419 /// getDefinition - Returns the RecordDecl that actually defines
3420 /// this struct/union/class. When determining whether or not a
3421 /// struct/union/class is completely defined, one should use this
3422 /// method as opposed to 'isCompleteDefinition'.
3423 /// 'isCompleteDefinition' indicates whether or not a specific
3424 /// RecordDecl is a completed definition, not whether or not the
3425 /// record type is defined. This method returns NULL if there is
3426 /// no RecordDecl that defines the struct/union/tag.
3427 RecordDecl *getDefinition() const {
3428 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3431 // Iterator access to field members. The field iterator only visits
3432 // the non-static data members of this class, ignoring any static
3433 // data members, functions, constructors, destructors, etc.
3434 typedef specific_decl_iterator<FieldDecl> field_iterator;
3435 typedef llvm::iterator_range<specific_decl_iterator<FieldDecl>> field_range;
3437 field_range fields() const { return field_range(field_begin(), field_end()); }
3438 field_iterator field_begin() const;
3440 field_iterator field_end() const {
3441 return field_iterator(decl_iterator());
3444 // field_empty - Whether there are any fields (non-static data
3445 // members) in this record.
3446 bool field_empty() const {
3447 return field_begin() == field_end();
3450 /// completeDefinition - Notes that the definition of this type is
3452 virtual void completeDefinition();
3454 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3455 static bool classofKind(Kind K) {
3456 return K >= firstRecord && K <= lastRecord;
3459 /// isMsStrust - Get whether or not this is an ms_struct which can
3460 /// be turned on with an attribute, pragma, or -mms-bitfields
3461 /// commandline option.
3462 bool isMsStruct(const ASTContext &C) const;
3464 /// \brief Whether we are allowed to insert extra padding between fields.
3465 /// These padding are added to help AddressSanitizer detect
3466 /// intra-object-overflow bugs.
3467 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3469 /// Finds the first data member which has a name.
3470 /// nullptr is returned if no named data member exists.
3471 const FieldDecl *findFirstNamedDataMember() const;
3474 /// \brief Deserialize just the fields.
3475 void LoadFieldsFromExternalStorage() const;
3478 class FileScopeAsmDecl : public Decl {
3479 virtual void anchor();
3480 StringLiteral *AsmString;
3481 SourceLocation RParenLoc;
3482 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3483 SourceLocation StartL, SourceLocation EndL)
3484 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3486 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3487 StringLiteral *Str, SourceLocation AsmLoc,
3488 SourceLocation RParenLoc);
3490 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3492 SourceLocation getAsmLoc() const { return getLocation(); }
3493 SourceLocation getRParenLoc() const { return RParenLoc; }
3494 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3495 SourceRange getSourceRange() const override LLVM_READONLY {
3496 return SourceRange(getAsmLoc(), getRParenLoc());
3499 const StringLiteral *getAsmString() const { return AsmString; }
3500 StringLiteral *getAsmString() { return AsmString; }
3501 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3503 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3504 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3507 /// BlockDecl - This represents a block literal declaration, which is like an
3508 /// unnamed FunctionDecl. For example:
3509 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3511 class BlockDecl : public Decl, public DeclContext {
3513 /// A class which contains all the information about a particular
3521 /// The variable being captured.
3522 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3524 /// The copy expression, expressed in terms of a DeclRef (or
3525 /// BlockDeclRef) to the captured variable. Only required if the
3526 /// variable has a C++ class type.
3530 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3531 : VariableAndFlags(variable,
3532 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3535 /// The variable being captured.
3536 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3538 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3540 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3542 /// Whether this is a nested capture, i.e. the variable captured
3543 /// is not from outside the immediately enclosing function/block.
3544 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3546 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3547 Expr *getCopyExpr() const { return CopyExpr; }
3548 void setCopyExpr(Expr *e) { CopyExpr = e; }
3552 // FIXME: This can be packed into the bitfields in Decl.
3553 bool IsVariadic : 1;
3554 bool CapturesCXXThis : 1;
3555 bool BlockMissingReturnType : 1;
3556 bool IsConversionFromLambda : 1;
3557 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3558 /// parameters of this function. This is null if a prototype or if there are
3560 ParmVarDecl **ParamInfo;
3564 TypeSourceInfo *SignatureAsWritten;
3566 const Capture *Captures;
3567 unsigned NumCaptures;
3569 unsigned ManglingNumber;
3570 Decl *ManglingContextDecl;
3573 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3574 : Decl(Block, DC, CaretLoc), DeclContext(Block),
3575 IsVariadic(false), CapturesCXXThis(false),
3576 BlockMissingReturnType(true), IsConversionFromLambda(false),
3577 ParamInfo(nullptr), NumParams(0), Body(nullptr),
3578 SignatureAsWritten(nullptr), Captures(nullptr), NumCaptures(0),
3579 ManglingNumber(0), ManglingContextDecl(nullptr) {}
3582 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3583 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3585 SourceLocation getCaretLocation() const { return getLocation(); }
3587 bool isVariadic() const { return IsVariadic; }
3588 void setIsVariadic(bool value) { IsVariadic = value; }
3590 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3591 Stmt *getBody() const override { return (Stmt*) Body; }
3592 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3594 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3595 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3597 // ArrayRef access to formal parameters.
3598 ArrayRef<ParmVarDecl *> parameters() const {
3599 return {ParamInfo, getNumParams()};
3601 MutableArrayRef<ParmVarDecl *> parameters() {
3602 return {ParamInfo, getNumParams()};
3605 // Iterator access to formal parameters.
3606 typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
3607 typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
3608 bool param_empty() const { return parameters().empty(); }
3609 param_iterator param_begin() { return parameters().begin(); }
3610 param_iterator param_end() { return parameters().end(); }
3611 param_const_iterator param_begin() const { return parameters().begin(); }
3612 param_const_iterator param_end() const { return parameters().end(); }
3613 size_t param_size() const { return parameters().size(); }
3615 unsigned getNumParams() const { return NumParams; }
3616 const ParmVarDecl *getParamDecl(unsigned i) const {
3617 assert(i < getNumParams() && "Illegal param #");
3618 return ParamInfo[i];
3620 ParmVarDecl *getParamDecl(unsigned i) {
3621 assert(i < getNumParams() && "Illegal param #");
3622 return ParamInfo[i];
3624 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3626 /// hasCaptures - True if this block (or its nested blocks) captures
3627 /// anything of local storage from its enclosing scopes.
3628 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3630 /// getNumCaptures - Returns the number of captured variables.
3631 /// Does not include an entry for 'this'.
3632 unsigned getNumCaptures() const { return NumCaptures; }
3634 typedef ArrayRef<Capture>::const_iterator capture_const_iterator;
3636 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3638 capture_const_iterator capture_begin() const { return captures().begin(); }
3639 capture_const_iterator capture_end() const { return captures().end(); }
3641 bool capturesCXXThis() const { return CapturesCXXThis; }
3642 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3643 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3645 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3646 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3648 bool capturesVariable(const VarDecl *var) const;
3650 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3651 bool CapturesCXXThis);
3653 unsigned getBlockManglingNumber() const {
3654 return ManglingNumber;
3656 Decl *getBlockManglingContextDecl() const {
3657 return ManglingContextDecl;
3660 void setBlockMangling(unsigned Number, Decl *Ctx) {
3661 ManglingNumber = Number;
3662 ManglingContextDecl = Ctx;
3665 SourceRange getSourceRange() const override LLVM_READONLY;
3667 // Implement isa/cast/dyncast/etc.
3668 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3669 static bool classofKind(Kind K) { return K == Block; }
3670 static DeclContext *castToDeclContext(const BlockDecl *D) {
3671 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3673 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3674 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3678 /// \brief This represents the body of a CapturedStmt, and serves as its
3680 class CapturedDecl final
3683 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3685 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3690 /// \brief The number of parameters to the outlined function.
3692 /// \brief The position of context parameter in list of parameters.
3693 unsigned ContextParam;
3694 /// \brief The body of the outlined function.
3695 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3697 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3699 ImplicitParamDecl *const *getParams() const {
3700 return getTrailingObjects<ImplicitParamDecl *>();
3703 ImplicitParamDecl **getParams() {
3704 return getTrailingObjects<ImplicitParamDecl *>();
3708 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3709 unsigned NumParams);
3710 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3711 unsigned NumParams);
3713 Stmt *getBody() const override;
3714 void setBody(Stmt *B);
3716 bool isNothrow() const;
3717 void setNothrow(bool Nothrow = true);
3719 unsigned getNumParams() const { return NumParams; }
3721 ImplicitParamDecl *getParam(unsigned i) const {
3722 assert(i < NumParams);
3723 return getParams()[i];
3725 void setParam(unsigned i, ImplicitParamDecl *P) {
3726 assert(i < NumParams);
3730 // ArrayRef interface to parameters.
3731 ArrayRef<ImplicitParamDecl *> parameters() const {
3732 return {getParams(), getNumParams()};
3734 MutableArrayRef<ImplicitParamDecl *> parameters() {
3735 return {getParams(), getNumParams()};
3738 /// \brief Retrieve the parameter containing captured variables.
3739 ImplicitParamDecl *getContextParam() const {
3740 assert(ContextParam < NumParams);
3741 return getParam(ContextParam);
3743 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3744 assert(i < NumParams);
3748 unsigned getContextParamPosition() const { return ContextParam; }
3750 typedef ImplicitParamDecl *const *param_iterator;
3751 typedef llvm::iterator_range<param_iterator> param_range;
3753 /// \brief Retrieve an iterator pointing to the first parameter decl.
3754 param_iterator param_begin() const { return getParams(); }
3755 /// \brief Retrieve an iterator one past the last parameter decl.
3756 param_iterator param_end() const { return getParams() + NumParams; }
3758 // Implement isa/cast/dyncast/etc.
3759 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3760 static bool classofKind(Kind K) { return K == Captured; }
3761 static DeclContext *castToDeclContext(const CapturedDecl *D) {
3762 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3764 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3765 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3768 friend class ASTDeclReader;
3769 friend class ASTDeclWriter;
3770 friend TrailingObjects;
3773 /// \brief Describes a module import declaration, which makes the contents
3774 /// of the named module visible in the current translation unit.
3776 /// An import declaration imports the named module (or submodule). For example:
3778 /// @import std.vector;
3781 /// Import declarations can also be implicitly generated from
3782 /// \#include/\#import directives.
3783 class ImportDecl final : public Decl,
3784 llvm::TrailingObjects<ImportDecl, SourceLocation> {
3785 /// \brief The imported module, along with a bit that indicates whether
3786 /// we have source-location information for each identifier in the module
3789 /// When the bit is false, we only have a single source location for the
3790 /// end of the import declaration.
3791 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3793 /// \brief The next import in the list of imports local to the translation
3794 /// unit being parsed (not loaded from an AST file).
3795 ImportDecl *NextLocalImport;
3797 friend class ASTReader;
3798 friend class ASTDeclReader;
3799 friend class ASTContext;
3800 friend TrailingObjects;
3802 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3803 ArrayRef<SourceLocation> IdentifierLocs);
3805 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3806 SourceLocation EndLoc);
3808 ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3811 /// \brief Create a new module import declaration.
3812 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3813 SourceLocation StartLoc, Module *Imported,
3814 ArrayRef<SourceLocation> IdentifierLocs);
3816 /// \brief Create a new module import declaration for an implicitly-generated
3818 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3819 SourceLocation StartLoc, Module *Imported,
3820 SourceLocation EndLoc);
3822 /// \brief Create a new, deserialized module import declaration.
3823 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3824 unsigned NumLocations);
3826 /// \brief Retrieve the module that was imported by the import declaration.
3827 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3829 /// \brief Retrieves the locations of each of the identifiers that make up
3830 /// the complete module name in the import declaration.
3832 /// This will return an empty array if the locations of the individual
3833 /// identifiers aren't available.
3834 ArrayRef<SourceLocation> getIdentifierLocs() const;
3836 SourceRange getSourceRange() const override LLVM_READONLY;
3838 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3839 static bool classofKind(Kind K) { return K == Import; }
3842 /// \brief Represents a C++ Modules TS module export declaration.
3846 /// export void foo();
3848 class ExportDecl final : public Decl, public DeclContext {
3849 virtual void anchor();
3851 /// \brief The source location for the right brace (if valid).
3852 SourceLocation RBraceLoc;
3854 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
3855 : Decl(Export, DC, ExportLoc), DeclContext(Export),
3856 RBraceLoc(SourceLocation()) { }
3858 friend class ASTDeclReader;
3861 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
3862 SourceLocation ExportLoc);
3863 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3865 SourceLocation getExportLoc() const { return getLocation(); }
3866 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3867 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
3869 SourceLocation getLocEnd() const LLVM_READONLY {
3870 if (RBraceLoc.isValid())
3872 // No braces: get the end location of the (only) declaration in context
3874 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
3877 SourceRange getSourceRange() const override LLVM_READONLY {
3878 return SourceRange(getLocation(), getLocEnd());
3881 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3882 static bool classofKind(Kind K) { return K == Export; }
3883 static DeclContext *castToDeclContext(const ExportDecl *D) {
3884 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
3886 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
3887 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
3891 /// \brief Represents an empty-declaration.
3892 class EmptyDecl : public Decl {
3893 virtual void anchor();
3894 EmptyDecl(DeclContext *DC, SourceLocation L)
3895 : Decl(Empty, DC, L) { }
3898 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3900 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3902 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3903 static bool classofKind(Kind K) { return K == Empty; }
3906 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3907 /// into a diagnostic with <<.
3908 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3909 const NamedDecl* ND) {
3910 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3911 DiagnosticsEngine::ak_nameddecl);
3914 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3915 const NamedDecl* ND) {
3916 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3917 DiagnosticsEngine::ak_nameddecl);
3921 template<typename decl_type>
3922 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
3923 // Note: This routine is implemented here because we need both NamedDecl
3924 // and Redeclarable to be defined.
3925 assert(RedeclLink.NextIsLatest() &&
3926 "setPreviousDecl on a decl already in a redeclaration chain");
3929 // Point to previous. Make sure that this is actually the most recent
3930 // redeclaration, or we can build invalid chains. If the most recent
3931 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3932 First = PrevDecl->getFirstDecl();
3933 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3934 decl_type *MostRecent = First->getNextRedeclaration();
3935 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3937 // If the declaration was previously visible, a redeclaration of it remains
3938 // visible even if it wouldn't be visible by itself.
3939 static_cast<decl_type*>(this)->IdentifierNamespace |=
3940 MostRecent->getIdentifierNamespace() &
3941 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3944 First = static_cast<decl_type*>(this);
3947 // First one will point to this one as latest.
3948 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
3950 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3951 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3954 // Inline function definitions.
3956 /// \brief Check if the given decl is complete.
3958 /// We use this function to break a cycle between the inline definitions in
3959 /// Type.h and Decl.h.
3960 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3961 return ED->isComplete();
3964 /// \brief Check if the given decl is scoped.
3966 /// We use this function to break a cycle between the inline definitions in
3967 /// Type.h and Decl.h.
3968 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3969 return ED->isScoped();
3972 } // end namespace clang