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. If the return type has the attribute and
2086 /// this function is a method of the return type's class, then false will be
2087 /// returned to avoid spurious warnings on member methods such as assignment
2089 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2091 /// \brief Returns the storage class as written in the source. For the
2092 /// computed linkage of symbol, see getLinkage.
2093 StorageClass getStorageClass() const { return StorageClass(SClass); }
2095 /// \brief Determine whether the "inline" keyword was specified for this
2097 bool isInlineSpecified() const { return IsInlineSpecified; }
2099 /// Set whether the "inline" keyword was specified for this function.
2100 void setInlineSpecified(bool I) {
2101 IsInlineSpecified = I;
2105 /// Flag that this function is implicitly inline.
2106 void setImplicitlyInline() {
2110 /// \brief Determine whether this function should be inlined, because it is
2111 /// either marked "inline" or "constexpr" or is a member function of a class
2112 /// that was defined in the class body.
2113 bool isInlined() const { return IsInline; }
2115 bool isInlineDefinitionExternallyVisible() const;
2117 bool isMSExternInline() const;
2119 bool doesDeclarationForceExternallyVisibleDefinition() const;
2121 /// isOverloadedOperator - Whether this function declaration
2122 /// represents an C++ overloaded operator, e.g., "operator+".
2123 bool isOverloadedOperator() const {
2124 return getOverloadedOperator() != OO_None;
2127 OverloadedOperatorKind getOverloadedOperator() const;
2129 const IdentifierInfo *getLiteralIdentifier() const;
2131 /// \brief If this function is an instantiation of a member function
2132 /// of a class template specialization, retrieves the function from
2133 /// which it was instantiated.
2135 /// This routine will return non-NULL for (non-templated) member
2136 /// functions of class templates and for instantiations of function
2137 /// templates. For example, given:
2140 /// template<typename T>
2146 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2147 /// whose parent is the class template specialization X<int>. For
2148 /// this declaration, getInstantiatedFromFunction() will return
2149 /// the FunctionDecl X<T>::A. When a complete definition of
2150 /// X<int>::A is required, it will be instantiated from the
2151 /// declaration returned by getInstantiatedFromMemberFunction().
2152 FunctionDecl *getInstantiatedFromMemberFunction() const;
2154 /// \brief What kind of templated function this is.
2155 TemplatedKind getTemplatedKind() const;
2157 /// \brief If this function is an instantiation of a member function of a
2158 /// class template specialization, retrieves the member specialization
2160 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2162 /// \brief Specify that this record is an instantiation of the
2163 /// member function FD.
2164 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2165 TemplateSpecializationKind TSK) {
2166 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2169 /// \brief Retrieves the function template that is described by this
2170 /// function declaration.
2172 /// Every function template is represented as a FunctionTemplateDecl
2173 /// and a FunctionDecl (or something derived from FunctionDecl). The
2174 /// former contains template properties (such as the template
2175 /// parameter lists) while the latter contains the actual
2176 /// description of the template's
2177 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2178 /// FunctionDecl that describes the function template,
2179 /// getDescribedFunctionTemplate() retrieves the
2180 /// FunctionTemplateDecl from a FunctionDecl.
2181 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2183 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2185 /// \brief Determine whether this function is a function template
2187 bool isFunctionTemplateSpecialization() const {
2188 return getPrimaryTemplate() != nullptr;
2191 /// \brief Retrieve the class scope template pattern that this function
2192 /// template specialization is instantiated from.
2193 FunctionDecl *getClassScopeSpecializationPattern() const;
2195 /// \brief If this function is actually a function template specialization,
2196 /// retrieve information about this function template specialization.
2197 /// Otherwise, returns NULL.
2198 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2200 /// \brief Determines whether this function is a function template
2201 /// specialization or a member of a class template specialization that can
2202 /// be implicitly instantiated.
2203 bool isImplicitlyInstantiable() const;
2205 /// \brief Determines if the given function was instantiated from a
2206 /// function template.
2207 bool isTemplateInstantiation() const;
2209 /// \brief Retrieve the function declaration from which this function could
2210 /// be instantiated, if it is an instantiation (rather than a non-template
2211 /// or a specialization, for example).
2212 FunctionDecl *getTemplateInstantiationPattern() const;
2214 /// \brief Retrieve the primary template that this function template
2215 /// specialization either specializes or was instantiated from.
2217 /// If this function declaration is not a function template specialization,
2219 FunctionTemplateDecl *getPrimaryTemplate() const;
2221 /// \brief Retrieve the template arguments used to produce this function
2222 /// template specialization from the primary template.
2224 /// If this function declaration is not a function template specialization,
2226 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2228 /// \brief Retrieve the template argument list as written in the sources,
2231 /// If this function declaration is not a function template specialization
2232 /// or if it had no explicit template argument list, returns NULL.
2233 /// Note that it an explicit template argument list may be written empty,
2234 /// e.g., template<> void foo<>(char* s);
2235 const ASTTemplateArgumentListInfo*
2236 getTemplateSpecializationArgsAsWritten() const;
2238 /// \brief Specify that this function declaration is actually a function
2239 /// template specialization.
2241 /// \param Template the function template that this function template
2242 /// specialization specializes.
2244 /// \param TemplateArgs the template arguments that produced this
2245 /// function template specialization from the template.
2247 /// \param InsertPos If non-NULL, the position in the function template
2248 /// specialization set where the function template specialization data will
2251 /// \param TSK the kind of template specialization this is.
2253 /// \param TemplateArgsAsWritten location info of template arguments.
2255 /// \param PointOfInstantiation point at which the function template
2256 /// specialization was first instantiated.
2257 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2258 const TemplateArgumentList *TemplateArgs,
2260 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2261 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2262 SourceLocation PointOfInstantiation = SourceLocation()) {
2263 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2264 InsertPos, TSK, TemplateArgsAsWritten,
2265 PointOfInstantiation);
2268 /// \brief Specifies that this function declaration is actually a
2269 /// dependent function template specialization.
2270 void setDependentTemplateSpecialization(ASTContext &Context,
2271 const UnresolvedSetImpl &Templates,
2272 const TemplateArgumentListInfo &TemplateArgs);
2274 DependentFunctionTemplateSpecializationInfo *
2275 getDependentSpecializationInfo() const;
2277 /// \brief Determine what kind of template instantiation this function
2279 TemplateSpecializationKind getTemplateSpecializationKind() const;
2281 /// \brief Determine what kind of template instantiation this function
2283 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2284 SourceLocation PointOfInstantiation = SourceLocation());
2286 /// \brief Retrieve the (first) point of instantiation of a function template
2287 /// specialization or a member of a class template specialization.
2289 /// \returns the first point of instantiation, if this function was
2290 /// instantiated from a template; otherwise, returns an invalid source
2292 SourceLocation getPointOfInstantiation() const;
2294 /// \brief Determine whether this is or was instantiated from an out-of-line
2295 /// definition of a member function.
2296 bool isOutOfLine() const override;
2298 /// \brief Identify a memory copying or setting function.
2299 /// If the given function is a memory copy or setting function, returns
2300 /// the corresponding Builtin ID. If the function is not a memory function,
2302 unsigned getMemoryFunctionKind() const;
2304 // Implement isa/cast/dyncast/etc.
2305 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2306 static bool classofKind(Kind K) {
2307 return K >= firstFunction && K <= lastFunction;
2309 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2310 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2312 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2313 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2316 friend class ASTDeclReader;
2317 friend class ASTDeclWriter;
2321 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2322 /// represent a member of a struct/union/class.
2323 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2324 // FIXME: This can be packed into the bitfields in Decl.
2325 unsigned Mutable : 1;
2326 mutable unsigned CachedFieldIndex : 31;
2328 /// The kinds of value we can store in InitializerOrBitWidth.
2330 /// Note that this is compatible with InClassInitStyle except for
2331 /// ISK_CapturedVLAType.
2332 enum InitStorageKind {
2333 /// If the pointer is null, there's nothing special. Otherwise,
2334 /// this is a bitfield and the pointer is the Expr* storing the
2336 ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
2338 /// The pointer is an (optional due to delayed parsing) Expr*
2339 /// holding the copy-initializer.
2340 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2342 /// The pointer is an (optional due to delayed parsing) Expr*
2343 /// holding the list-initializer.
2344 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2346 /// The pointer is a VariableArrayType* that's been captured;
2347 /// the enclosing context is a lambda or captured statement.
2348 ISK_CapturedVLAType,
2351 /// \brief Storage for either the bit-width, the in-class
2352 /// initializer, or the captured variable length array bound.
2354 /// We can safely combine these because in-class initializers are
2355 /// not permitted for bit-fields, and both are exclusive with VLA
2358 /// If the storage kind is ISK_InClassCopyInit or
2359 /// ISK_InClassListInit, but the initializer is null, then this
2360 /// field has an in-class initializer which has not yet been parsed
2362 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2364 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2365 SourceLocation IdLoc, IdentifierInfo *Id,
2366 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2367 InClassInitStyle InitStyle)
2368 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2369 Mutable(Mutable), CachedFieldIndex(0),
2370 InitStorage(BW, (InitStorageKind) InitStyle) {
2371 assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2375 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2376 SourceLocation StartLoc, SourceLocation IdLoc,
2377 IdentifierInfo *Id, QualType T,
2378 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2379 InClassInitStyle InitStyle);
2381 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2383 /// getFieldIndex - Returns the index of this field within its record,
2384 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2385 unsigned getFieldIndex() const;
2387 /// isMutable - Determines whether this field is mutable (C++ only).
2388 bool isMutable() const { return Mutable; }
2390 /// \brief Determines whether this field is a bitfield.
2391 bool isBitField() const {
2392 return InitStorage.getInt() == ISK_BitWidthOrNothing &&
2393 InitStorage.getPointer() != nullptr;
2396 /// @brief Determines whether this is an unnamed bitfield.
2397 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2399 /// isAnonymousStructOrUnion - Determines whether this field is a
2400 /// representative for an anonymous struct or union. Such fields are
2401 /// unnamed and are implicitly generated by the implementation to
2402 /// store the data for the anonymous union or struct.
2403 bool isAnonymousStructOrUnion() const;
2405 Expr *getBitWidth() const {
2407 ? static_cast<Expr *>(InitStorage.getPointer())
2410 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2412 /// setBitWidth - Set the bit-field width for this member.
2413 // Note: used by some clients (i.e., do not remove it).
2414 void setBitWidth(Expr *Width) {
2415 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
2416 InitStorage.getPointer() == nullptr &&
2417 "bit width, initializer or captured type already set");
2418 InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
2421 /// removeBitWidth - Remove the bit-field width from this member.
2422 // Note: used by some clients (i.e., do not remove it).
2423 void removeBitWidth() {
2424 assert(isBitField() && "no bitfield width to remove");
2425 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2428 /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2430 InClassInitStyle getInClassInitStyle() const {
2431 InitStorageKind storageKind = InitStorage.getInt();
2432 return (storageKind == ISK_CapturedVLAType
2433 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2436 /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2438 bool hasInClassInitializer() const {
2439 return getInClassInitStyle() != ICIS_NoInit;
2442 /// getInClassInitializer - Get the C++11 in-class initializer for this
2443 /// member, or null if one has not been set. If a valid declaration has an
2444 /// in-class initializer, but this returns null, then we have not parsed and
2445 /// attached it yet.
2446 Expr *getInClassInitializer() const {
2447 return hasInClassInitializer()
2448 ? static_cast<Expr *>(InitStorage.getPointer())
2452 /// setInClassInitializer - Set the C++11 in-class initializer for this
2454 void setInClassInitializer(Expr *Init) {
2455 assert(hasInClassInitializer() &&
2456 InitStorage.getPointer() == nullptr &&
2457 "bit width, initializer or captured type already set");
2458 InitStorage.setPointer(Init);
2461 /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2463 void removeInClassInitializer() {
2464 assert(hasInClassInitializer() && "no initializer to remove");
2465 InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2468 /// \brief Determine whether this member captures the variable length array
2470 bool hasCapturedVLAType() const {
2471 return InitStorage.getInt() == ISK_CapturedVLAType;
2474 /// \brief Get the captured variable length array type.
2475 const VariableArrayType *getCapturedVLAType() const {
2476 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2477 InitStorage.getPointer())
2480 /// \brief Set the captured variable length array type for this field.
2481 void setCapturedVLAType(const VariableArrayType *VLAType);
2483 /// getParent - Returns the parent of this field declaration, which
2484 /// is the struct in which this method is defined.
2485 const RecordDecl *getParent() const {
2486 return cast<RecordDecl>(getDeclContext());
2489 RecordDecl *getParent() {
2490 return cast<RecordDecl>(getDeclContext());
2493 SourceRange getSourceRange() const override LLVM_READONLY;
2495 /// Retrieves the canonical declaration of this field.
2496 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2497 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2499 // Implement isa/cast/dyncast/etc.
2500 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2501 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2503 friend class ASTDeclReader;
2504 friend class ASTDeclWriter;
2507 /// EnumConstantDecl - An instance of this object exists for each enum constant
2508 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2509 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2510 /// TagType for the X EnumDecl.
2511 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2512 Stmt *Init; // an integer constant expression
2513 llvm::APSInt Val; // The value.
2515 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2516 IdentifierInfo *Id, QualType T, Expr *E,
2517 const llvm::APSInt &V)
2518 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2522 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2523 SourceLocation L, IdentifierInfo *Id,
2524 QualType T, Expr *E,
2525 const llvm::APSInt &V);
2526 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2528 const Expr *getInitExpr() const { return (const Expr*) Init; }
2529 Expr *getInitExpr() { return (Expr*) Init; }
2530 const llvm::APSInt &getInitVal() const { return Val; }
2532 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2533 void setInitVal(const llvm::APSInt &V) { Val = V; }
2535 SourceRange getSourceRange() const override LLVM_READONLY;
2537 /// Retrieves the canonical declaration of this enumerator.
2538 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2539 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2541 // Implement isa/cast/dyncast/etc.
2542 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2543 static bool classofKind(Kind K) { return K == EnumConstant; }
2545 friend class StmtIteratorBase;
2548 /// IndirectFieldDecl - An instance of this class is created to represent a
2549 /// field injected from an anonymous union/struct into the parent scope.
2550 /// IndirectFieldDecl are always implicit.
2551 class IndirectFieldDecl : public ValueDecl,
2552 public Mergeable<IndirectFieldDecl> {
2553 void anchor() override;
2554 NamedDecl **Chaining;
2555 unsigned ChainingSize;
2557 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2558 DeclarationName N, QualType T,
2559 MutableArrayRef<NamedDecl *> CH);
2562 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2563 SourceLocation L, IdentifierInfo *Id,
2564 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2566 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2568 typedef ArrayRef<NamedDecl *>::const_iterator chain_iterator;
2570 ArrayRef<NamedDecl *> chain() const {
2571 return llvm::makeArrayRef(Chaining, ChainingSize);
2573 chain_iterator chain_begin() const { return chain().begin(); }
2574 chain_iterator chain_end() const { return chain().end(); }
2576 unsigned getChainingSize() const { return ChainingSize; }
2578 FieldDecl *getAnonField() const {
2579 assert(chain().size() >= 2);
2580 return cast<FieldDecl>(chain().back());
2583 VarDecl *getVarDecl() const {
2584 assert(chain().size() >= 2);
2585 return dyn_cast<VarDecl>(chain().front());
2588 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2589 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2591 // Implement isa/cast/dyncast/etc.
2592 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2593 static bool classofKind(Kind K) { return K == IndirectField; }
2594 friend class ASTDeclReader;
2597 /// TypeDecl - Represents a declaration of a type.
2599 class TypeDecl : public NamedDecl {
2600 void anchor() override;
2601 /// TypeForDecl - This indicates the Type object that represents
2602 /// this TypeDecl. It is a cache maintained by
2603 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2604 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2605 mutable const Type *TypeForDecl;
2606 /// LocStart - The start of the source range for this declaration.
2607 SourceLocation LocStart;
2608 friend class ASTContext;
2611 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2612 SourceLocation StartL = SourceLocation())
2613 : NamedDecl(DK, DC, L, Id), TypeForDecl(nullptr), LocStart(StartL) {}
2616 // Low-level accessor. If you just want the type defined by this node,
2617 // check out ASTContext::getTypeDeclType or one of
2618 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2619 // already know the specific kind of node this is.
2620 const Type *getTypeForDecl() const { return TypeForDecl; }
2621 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2623 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2624 void setLocStart(SourceLocation L) { LocStart = L; }
2625 SourceRange getSourceRange() const override LLVM_READONLY {
2626 if (LocStart.isValid())
2627 return SourceRange(LocStart, getLocation());
2629 return SourceRange(getLocation());
2632 // Implement isa/cast/dyncast/etc.
2633 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2634 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2638 /// Base class for declarations which introduce a typedef-name.
2639 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2640 void anchor() override;
2641 typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
2642 llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
2644 // FIXME: This can be packed into the bitfields in Decl.
2645 /// If 0, we have not computed IsTransparentTag.
2646 /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
2647 mutable unsigned CacheIsTransparentTag : 2;
2650 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2651 SourceLocation StartLoc, SourceLocation IdLoc,
2652 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2653 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2654 MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
2656 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2657 TypedefNameDecl *getNextRedeclarationImpl() override {
2658 return getNextRedeclaration();
2660 TypedefNameDecl *getPreviousDeclImpl() override {
2661 return getPreviousDecl();
2663 TypedefNameDecl *getMostRecentDeclImpl() override {
2664 return getMostRecentDecl();
2668 typedef redeclarable_base::redecl_range redecl_range;
2669 typedef redeclarable_base::redecl_iterator redecl_iterator;
2670 using redeclarable_base::redecls_begin;
2671 using redeclarable_base::redecls_end;
2672 using redeclarable_base::redecls;
2673 using redeclarable_base::getPreviousDecl;
2674 using redeclarable_base::getMostRecentDecl;
2675 using redeclarable_base::isFirstDecl;
2677 bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2679 TypeSourceInfo *getTypeSourceInfo() const {
2681 ? MaybeModedTInfo.get<ModedTInfo*>()->first
2682 : MaybeModedTInfo.get<TypeSourceInfo*>();
2684 QualType getUnderlyingType() const {
2686 ? MaybeModedTInfo.get<ModedTInfo*>()->second
2687 : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2689 void setTypeSourceInfo(TypeSourceInfo *newType) {
2690 MaybeModedTInfo = newType;
2692 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2693 MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2696 /// Retrieves the canonical declaration of this typedef-name.
2697 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2698 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2700 /// Retrieves the tag declaration for which this is the typedef name for
2701 /// linkage purposes, if any.
2703 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2704 /// this typedef declaration.
2705 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2707 /// Determines if this typedef shares a name and spelling location with its
2708 /// underlying tag type, as is the case with the NS_ENUM macro.
2709 bool isTransparentTag() const {
2710 if (CacheIsTransparentTag)
2711 return CacheIsTransparentTag & 0x2;
2712 return isTransparentTagSlow();
2715 // Implement isa/cast/dyncast/etc.
2716 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2717 static bool classofKind(Kind K) {
2718 return K >= firstTypedefName && K <= lastTypedefName;
2722 bool isTransparentTagSlow() const;
2725 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2727 class TypedefDecl : public TypedefNameDecl {
2728 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2729 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2730 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2733 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2734 SourceLocation StartLoc, SourceLocation IdLoc,
2735 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2736 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2738 SourceRange getSourceRange() const override LLVM_READONLY;
2740 // Implement isa/cast/dyncast/etc.
2741 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2742 static bool classofKind(Kind K) { return K == Typedef; }
2745 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2746 /// alias-declaration.
2747 class TypeAliasDecl : public TypedefNameDecl {
2748 /// The template for which this is the pattern, if any.
2749 TypeAliasTemplateDecl *Template;
2751 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2752 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2753 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2754 Template(nullptr) {}
2757 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2758 SourceLocation StartLoc, SourceLocation IdLoc,
2759 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2760 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2762 SourceRange getSourceRange() const override LLVM_READONLY;
2764 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2765 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2767 // Implement isa/cast/dyncast/etc.
2768 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2769 static bool classofKind(Kind K) { return K == TypeAlias; }
2772 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2774 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2776 // This is really ugly.
2777 typedef TagTypeKind TagKind;
2780 // FIXME: This can be packed into the bitfields in Decl.
2781 /// TagDeclKind - The TagKind enum.
2782 unsigned TagDeclKind : 3;
2784 /// IsCompleteDefinition - True if this is a definition ("struct foo
2785 /// {};"), false if it is a declaration ("struct foo;"). It is not
2786 /// a definition until the definition has been fully processed.
2787 unsigned IsCompleteDefinition : 1;
2790 /// IsBeingDefined - True if this is currently being defined.
2791 unsigned IsBeingDefined : 1;
2794 /// IsEmbeddedInDeclarator - True if this tag declaration is
2795 /// "embedded" (i.e., defined or declared for the very first time)
2796 /// in the syntax of a declarator.
2797 unsigned IsEmbeddedInDeclarator : 1;
2799 /// \brief True if this tag is free standing, e.g. "struct foo;".
2800 unsigned IsFreeStanding : 1;
2803 // These are used by (and only defined for) EnumDecl.
2804 unsigned NumPositiveBits : 8;
2805 unsigned NumNegativeBits : 8;
2807 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2808 /// possible in C++11 mode.
2809 unsigned IsScoped : 1;
2810 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2811 /// then this is true if the scoped enum was declared using the class
2812 /// tag, false if it was declared with the struct tag. No meaning is
2813 /// associated if this tag declaration is not a scoped enum.
2814 unsigned IsScopedUsingClassTag : 1;
2816 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2817 /// possible in C++11, Microsoft extensions, or Objective C mode.
2818 unsigned IsFixed : 1;
2820 /// \brief Indicates whether it is possible for declarations of this kind
2821 /// to have an out-of-date definition.
2823 /// This option is only enabled when modules are enabled.
2824 unsigned MayHaveOutOfDateDef : 1;
2826 /// Has the full definition of this type been required by a use somewhere in
2828 unsigned IsCompleteDefinitionRequired : 1;
2830 SourceRange BraceRange;
2832 // A struct representing syntactic qualifier info,
2833 // to be used for the (uncommon) case of out-of-line declarations.
2834 typedef QualifierInfo ExtInfo;
2836 /// \brief If the (out-of-line) tag declaration name
2837 /// is qualified, it points to the qualifier info (nns and range);
2838 /// otherwise, if the tag declaration is anonymous and it is part of
2839 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2840 /// otherwise, if the tag declaration is anonymous and it is used as a
2841 /// declaration specifier for variables, it points to the first VarDecl (used
2843 /// otherwise, it is a null (TypedefNameDecl) pointer.
2844 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
2846 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
2847 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
2848 const ExtInfo *getExtInfo() const {
2849 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
2853 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
2854 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
2855 SourceLocation StartL)
2856 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
2857 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
2858 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
2859 IsCompleteDefinitionRequired(false),
2860 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
2861 assert((DK != Enum || TK == TTK_Enum) &&
2862 "EnumDecl not matched with TTK_Enum");
2863 setPreviousDecl(PrevDecl);
2866 typedef Redeclarable<TagDecl> redeclarable_base;
2867 TagDecl *getNextRedeclarationImpl() override {
2868 return getNextRedeclaration();
2870 TagDecl *getPreviousDeclImpl() override {
2871 return getPreviousDecl();
2873 TagDecl *getMostRecentDeclImpl() override {
2874 return getMostRecentDecl();
2877 /// @brief Completes the definition of this tag declaration.
2879 /// This is a helper function for derived classes.
2880 void completeDefinition();
2883 typedef redeclarable_base::redecl_range redecl_range;
2884 typedef redeclarable_base::redecl_iterator redecl_iterator;
2885 using redeclarable_base::redecls_begin;
2886 using redeclarable_base::redecls_end;
2887 using redeclarable_base::redecls;
2888 using redeclarable_base::getPreviousDecl;
2889 using redeclarable_base::getMostRecentDecl;
2890 using redeclarable_base::isFirstDecl;
2892 SourceRange getBraceRange() const { return BraceRange; }
2893 void setBraceRange(SourceRange R) { BraceRange = R; }
2895 /// getInnerLocStart - Return SourceLocation representing start of source
2896 /// range ignoring outer template declarations.
2897 SourceLocation getInnerLocStart() const { return getLocStart(); }
2899 /// getOuterLocStart - Return SourceLocation representing start of source
2900 /// range taking into account any outer template declarations.
2901 SourceLocation getOuterLocStart() const;
2902 SourceRange getSourceRange() const override LLVM_READONLY;
2904 TagDecl *getCanonicalDecl() override;
2905 const TagDecl *getCanonicalDecl() const {
2906 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2909 /// isThisDeclarationADefinition() - Return true if this declaration
2910 /// is a completion definition of the type. Provided for consistency.
2911 bool isThisDeclarationADefinition() const {
2912 return isCompleteDefinition();
2915 /// isCompleteDefinition - Return true if this decl has its body
2916 /// fully specified.
2917 bool isCompleteDefinition() const {
2918 return IsCompleteDefinition;
2921 /// \brief Return true if this complete decl is
2922 /// required to be complete for some existing use.
2923 bool isCompleteDefinitionRequired() const {
2924 return IsCompleteDefinitionRequired;
2927 /// isBeingDefined - Return true if this decl is currently being defined.
2928 bool isBeingDefined() const {
2929 return IsBeingDefined;
2932 bool isEmbeddedInDeclarator() const {
2933 return IsEmbeddedInDeclarator;
2935 void setEmbeddedInDeclarator(bool isInDeclarator) {
2936 IsEmbeddedInDeclarator = isInDeclarator;
2939 bool isFreeStanding() const { return IsFreeStanding; }
2940 void setFreeStanding(bool isFreeStanding = true) {
2941 IsFreeStanding = isFreeStanding;
2944 /// \brief Whether this declaration declares a type that is
2945 /// dependent, i.e., a type that somehow depends on template
2947 bool isDependentType() const { return isDependentContext(); }
2949 /// @brief Starts the definition of this tag declaration.
2951 /// This method should be invoked at the beginning of the definition
2952 /// of this tag declaration. It will set the tag type into a state
2953 /// where it is in the process of being defined.
2954 void startDefinition();
2956 /// getDefinition - Returns the TagDecl that actually defines this
2957 /// struct/union/class/enum. When determining whether or not a
2958 /// struct/union/class/enum has a definition, one should use this
2959 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
2960 /// whether or not a specific TagDecl is defining declaration, not
2961 /// whether or not the struct/union/class/enum type is defined.
2962 /// This method returns NULL if there is no TagDecl that defines
2963 /// the struct/union/class/enum.
2964 TagDecl *getDefinition() const;
2966 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2968 void setCompleteDefinitionRequired(bool V = true) {
2969 IsCompleteDefinitionRequired = V;
2972 StringRef getKindName() const {
2973 return TypeWithKeyword::getTagTypeKindName(getTagKind());
2976 TagKind getTagKind() const {
2977 return TagKind(TagDeclKind);
2980 void setTagKind(TagKind TK) { TagDeclKind = TK; }
2982 bool isStruct() const { return getTagKind() == TTK_Struct; }
2983 bool isInterface() const { return getTagKind() == TTK_Interface; }
2984 bool isClass() const { return getTagKind() == TTK_Class; }
2985 bool isUnion() const { return getTagKind() == TTK_Union; }
2986 bool isEnum() const { return getTagKind() == TTK_Enum; }
2988 /// Is this tag type named, either directly or via being defined in
2989 /// a typedef of this type?
2991 /// C++11 [basic.link]p8:
2992 /// A type is said to have linkage if and only if:
2993 /// - it is a class or enumeration type that is named (or has a
2994 /// name for linkage purposes) and the name has linkage; ...
2995 /// C++11 [dcl.typedef]p9:
2996 /// If the typedef declaration defines an unnamed class (or enum),
2997 /// the first typedef-name declared by the declaration to be that
2998 /// class type (or enum type) is used to denote the class type (or
2999 /// enum type) for linkage purposes only.
3001 /// C does not have an analogous rule, but the same concept is
3002 /// nonetheless useful in some places.
3003 bool hasNameForLinkage() const {
3004 return (getDeclName() || getTypedefNameForAnonDecl());
3007 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3008 return hasExtInfo() ? nullptr
3009 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3012 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3014 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3015 /// declaration, if it was present in the source.
3016 NestedNameSpecifier *getQualifier() const {
3017 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3021 /// \brief Retrieve the nested-name-specifier (with source-location
3022 /// information) that qualifies the name of this declaration, if it was
3023 /// present in the source.
3024 NestedNameSpecifierLoc getQualifierLoc() const {
3025 return hasExtInfo() ? getExtInfo()->QualifierLoc
3026 : NestedNameSpecifierLoc();
3029 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3031 unsigned getNumTemplateParameterLists() const {
3032 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3034 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3035 assert(i < getNumTemplateParameterLists());
3036 return getExtInfo()->TemplParamLists[i];
3038 void setTemplateParameterListsInfo(ASTContext &Context,
3039 ArrayRef<TemplateParameterList *> TPLists);
3041 // Implement isa/cast/dyncast/etc.
3042 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3043 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3045 static DeclContext *castToDeclContext(const TagDecl *D) {
3046 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3048 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3049 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3052 friend class ASTDeclReader;
3053 friend class ASTDeclWriter;
3056 /// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
3057 /// with a fixed underlying type, and in C we allow them to be forward-declared
3058 /// with no underlying type as an extension.
3059 class EnumDecl : public TagDecl {
3060 void anchor() override;
3061 /// IntegerType - This represent the integer type that the enum corresponds
3062 /// to for code generation purposes. Note that the enumerator constants may
3063 /// have a different type than this does.
3065 /// If the underlying integer type was explicitly stated in the source
3066 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3067 /// was automatically deduced somehow, and this is a Type*.
3069 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3070 /// some cases it won't.
3072 /// The underlying type of an enumeration never has any qualifiers, so
3073 /// we can get away with just storing a raw Type*, and thus save an
3074 /// extra pointer when TypeSourceInfo is needed.
3076 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
3078 /// PromotionType - The integer type that values of this type should
3079 /// promote to. In C, enumerators are generally of an integer type
3080 /// directly, but gcc-style large enumerators (and all enumerators
3081 /// in C++) are of the enum type instead.
3082 QualType PromotionType;
3084 /// \brief If this enumeration is an instantiation of a member enumeration
3085 /// of a class template specialization, this is the member specialization
3087 MemberSpecializationInfo *SpecializationInfo;
3089 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3090 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3091 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3092 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3093 SpecializationInfo(nullptr) {
3094 assert(Scoped || !ScopedUsingClassTag);
3095 IntegerType = (const Type *)nullptr;
3096 NumNegativeBits = 0;
3097 NumPositiveBits = 0;
3099 IsScopedUsingClassTag = ScopedUsingClassTag;
3103 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3104 TemplateSpecializationKind TSK);
3106 EnumDecl *getCanonicalDecl() override {
3107 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3109 const EnumDecl *getCanonicalDecl() const {
3110 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3113 EnumDecl *getPreviousDecl() {
3114 return cast_or_null<EnumDecl>(
3115 static_cast<TagDecl *>(this)->getPreviousDecl());
3117 const EnumDecl *getPreviousDecl() const {
3118 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3121 EnumDecl *getMostRecentDecl() {
3122 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3124 const EnumDecl *getMostRecentDecl() const {
3125 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3128 EnumDecl *getDefinition() const {
3129 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3132 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3133 SourceLocation StartLoc, SourceLocation IdLoc,
3134 IdentifierInfo *Id, EnumDecl *PrevDecl,
3135 bool IsScoped, bool IsScopedUsingClassTag,
3137 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3139 /// completeDefinition - When created, the EnumDecl corresponds to a
3140 /// forward-declared enum. This method is used to mark the
3141 /// declaration as being defined; it's enumerators have already been
3142 /// added (via DeclContext::addDecl). NewType is the new underlying
3143 /// type of the enumeration type.
3144 void completeDefinition(QualType NewType,
3145 QualType PromotionType,
3146 unsigned NumPositiveBits,
3147 unsigned NumNegativeBits);
3149 // enumerator_iterator - Iterates through the enumerators of this
3151 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
3152 typedef llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>
3155 enumerator_range enumerators() const {
3156 return enumerator_range(enumerator_begin(), enumerator_end());
3159 enumerator_iterator enumerator_begin() const {
3160 const EnumDecl *E = getDefinition();
3163 return enumerator_iterator(E->decls_begin());
3166 enumerator_iterator enumerator_end() const {
3167 const EnumDecl *E = getDefinition();
3170 return enumerator_iterator(E->decls_end());
3173 /// getPromotionType - Return the integer type that enumerators
3174 /// should promote to.
3175 QualType getPromotionType() const { return PromotionType; }
3177 /// \brief Set the promotion type.
3178 void setPromotionType(QualType T) { PromotionType = T; }
3180 /// getIntegerType - Return the integer type this enum decl corresponds to.
3181 /// This returns a null QualType for an enum forward definition with no fixed
3182 /// underlying type.
3183 QualType getIntegerType() const {
3186 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3187 return QualType(T, 0);
3188 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3191 /// \brief Set the underlying integer type.
3192 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3194 /// \brief Set the underlying integer type source info.
3195 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3197 /// \brief Return the type source info for the underlying integer type,
3198 /// if no type source info exists, return 0.
3199 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3200 return IntegerType.dyn_cast<TypeSourceInfo*>();
3203 /// \brief Retrieve the source range that covers the underlying type if
3205 SourceRange getIntegerTypeRange() const LLVM_READONLY;
3207 /// \brief Returns the width in bits required to store all the
3208 /// non-negative enumerators of this enum.
3209 unsigned getNumPositiveBits() const {
3210 return NumPositiveBits;
3212 void setNumPositiveBits(unsigned Num) {
3213 NumPositiveBits = Num;
3214 assert(NumPositiveBits == Num && "can't store this bitcount");
3217 /// \brief Returns the width in bits required to store all the
3218 /// negative enumerators of this enum. These widths include
3219 /// the rightmost leading 1; that is:
3221 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3222 /// ------------------------ ------- -----------------
3226 unsigned getNumNegativeBits() const {
3227 return NumNegativeBits;
3229 void setNumNegativeBits(unsigned Num) {
3230 NumNegativeBits = Num;
3233 /// \brief Returns true if this is a C++11 scoped enumeration.
3234 bool isScoped() const {
3238 /// \brief Returns true if this is a C++11 scoped enumeration.
3239 bool isScopedUsingClassTag() const {
3240 return IsScopedUsingClassTag;
3243 /// \brief Returns true if this is an Objective-C, C++11, or
3244 /// Microsoft-style enumeration with a fixed underlying type.
3245 bool isFixed() const {
3249 /// \brief Returns true if this can be considered a complete type.
3250 bool isComplete() const {
3251 return isCompleteDefinition() || isFixed();
3254 /// Returns true if this enum is either annotated with
3255 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3256 bool isClosed() const;
3258 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3259 /// with enum_extensibility(open).
3260 bool isClosedFlag() const;
3262 /// Returns true if this enum is annotated with neither flag_enum nor
3263 /// enum_extensibility(open).
3264 bool isClosedNonFlag() const;
3266 /// \brief Retrieve the enum definition from which this enumeration could
3267 /// be instantiated, if it is an instantiation (rather than a non-template).
3268 EnumDecl *getTemplateInstantiationPattern() const;
3270 /// \brief Returns the enumeration (declared within the template)
3271 /// from which this enumeration type was instantiated, or NULL if
3272 /// this enumeration was not instantiated from any template.
3273 EnumDecl *getInstantiatedFromMemberEnum() const;
3275 /// \brief If this enumeration is a member of a specialization of a
3276 /// templated class, determine what kind of template specialization
3277 /// or instantiation this is.
3278 TemplateSpecializationKind getTemplateSpecializationKind() const;
3280 /// \brief For an enumeration member that was instantiated from a member
3281 /// enumeration of a templated class, set the template specialiation kind.
3282 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3283 SourceLocation PointOfInstantiation = SourceLocation());
3285 /// \brief If this enumeration is an instantiation of a member enumeration of
3286 /// a class template specialization, retrieves the member specialization
3288 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3289 return SpecializationInfo;
3292 /// \brief Specify that this enumeration is an instantiation of the
3293 /// member enumeration ED.
3294 void setInstantiationOfMemberEnum(EnumDecl *ED,
3295 TemplateSpecializationKind TSK) {
3296 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3299 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3300 static bool classofKind(Kind K) { return K == Enum; }
3302 friend class ASTDeclReader;
3306 /// RecordDecl - Represents a struct/union/class. For example:
3307 /// struct X; // Forward declaration, no "body".
3308 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3309 /// This decl will be marked invalid if *any* members are invalid.
3311 class RecordDecl : public TagDecl {
3312 // FIXME: This can be packed into the bitfields in Decl.
3313 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3314 /// array member (e.g. int X[]) or if this union contains a struct that does.
3315 /// If so, this cannot be contained in arrays or other structs as a member.
3316 bool HasFlexibleArrayMember : 1;
3318 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3320 bool AnonymousStructOrUnion : 1;
3322 /// HasObjectMember - This is true if this struct has at least one member
3323 /// containing an Objective-C object pointer type.
3324 bool HasObjectMember : 1;
3326 /// HasVolatileMember - This is true if struct has at least one member of
3327 /// 'volatile' type.
3328 bool HasVolatileMember : 1;
3330 /// \brief Whether the field declarations of this record have been loaded
3331 /// from external storage. To avoid unnecessary deserialization of
3332 /// methods/nested types we allow deserialization of just the fields
3334 mutable bool LoadedFieldsFromExternalStorage : 1;
3335 friend class DeclContext;
3338 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3339 SourceLocation StartLoc, SourceLocation IdLoc,
3340 IdentifierInfo *Id, RecordDecl *PrevDecl);
3343 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3344 SourceLocation StartLoc, SourceLocation IdLoc,
3345 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3346 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3348 RecordDecl *getPreviousDecl() {
3349 return cast_or_null<RecordDecl>(
3350 static_cast<TagDecl *>(this)->getPreviousDecl());
3352 const RecordDecl *getPreviousDecl() const {
3353 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3356 RecordDecl *getMostRecentDecl() {
3357 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3359 const RecordDecl *getMostRecentDecl() const {
3360 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3363 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3364 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3366 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3367 /// or union. To be an anonymous struct or union, it must have been
3368 /// declared without a name and there must be no objects of this
3369 /// type declared, e.g.,
3371 /// union { int i; float f; };
3373 /// is an anonymous union but neither of the following are:
3375 /// union X { int i; float f; };
3376 /// union { int i; float f; } obj;
3378 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3379 void setAnonymousStructOrUnion(bool Anon) {
3380 AnonymousStructOrUnion = Anon;
3383 bool hasObjectMember() const { return HasObjectMember; }
3384 void setHasObjectMember (bool val) { HasObjectMember = val; }
3386 bool hasVolatileMember() const { return HasVolatileMember; }
3387 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3389 bool hasLoadedFieldsFromExternalStorage() const {
3390 return LoadedFieldsFromExternalStorage;
3392 void setHasLoadedFieldsFromExternalStorage(bool val) {
3393 LoadedFieldsFromExternalStorage = val;
3396 /// \brief Determines whether this declaration represents the
3397 /// injected class name.
3399 /// The injected class name in C++ is the name of the class that
3400 /// appears inside the class itself. For example:
3404 /// // C is implicitly declared here as a synonym for the class name.
3407 /// C::C c; // same as "C c;"
3409 bool isInjectedClassName() const;
3411 /// \brief Determine whether this record is a class describing a lambda
3412 /// function object.
3413 bool isLambda() const;
3415 /// \brief Determine whether this record is a record for captured variables in
3416 /// CapturedStmt construct.
3417 bool isCapturedRecord() const;
3418 /// \brief Mark the record as a record for captured variables in CapturedStmt
3420 void setCapturedRecord();
3422 /// getDefinition - Returns the RecordDecl that actually defines
3423 /// this struct/union/class. When determining whether or not a
3424 /// struct/union/class is completely defined, one should use this
3425 /// method as opposed to 'isCompleteDefinition'.
3426 /// 'isCompleteDefinition' indicates whether or not a specific
3427 /// RecordDecl is a completed definition, not whether or not the
3428 /// record type is defined. This method returns NULL if there is
3429 /// no RecordDecl that defines the struct/union/tag.
3430 RecordDecl *getDefinition() const {
3431 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3434 // Iterator access to field members. The field iterator only visits
3435 // the non-static data members of this class, ignoring any static
3436 // data members, functions, constructors, destructors, etc.
3437 typedef specific_decl_iterator<FieldDecl> field_iterator;
3438 typedef llvm::iterator_range<specific_decl_iterator<FieldDecl>> field_range;
3440 field_range fields() const { return field_range(field_begin(), field_end()); }
3441 field_iterator field_begin() const;
3443 field_iterator field_end() const {
3444 return field_iterator(decl_iterator());
3447 // field_empty - Whether there are any fields (non-static data
3448 // members) in this record.
3449 bool field_empty() const {
3450 return field_begin() == field_end();
3453 /// completeDefinition - Notes that the definition of this type is
3455 virtual void completeDefinition();
3457 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3458 static bool classofKind(Kind K) {
3459 return K >= firstRecord && K <= lastRecord;
3462 /// isMsStrust - Get whether or not this is an ms_struct which can
3463 /// be turned on with an attribute, pragma, or -mms-bitfields
3464 /// commandline option.
3465 bool isMsStruct(const ASTContext &C) const;
3467 /// \brief Whether we are allowed to insert extra padding between fields.
3468 /// These padding are added to help AddressSanitizer detect
3469 /// intra-object-overflow bugs.
3470 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3472 /// Finds the first data member which has a name.
3473 /// nullptr is returned if no named data member exists.
3474 const FieldDecl *findFirstNamedDataMember() const;
3477 /// \brief Deserialize just the fields.
3478 void LoadFieldsFromExternalStorage() const;
3481 class FileScopeAsmDecl : public Decl {
3482 virtual void anchor();
3483 StringLiteral *AsmString;
3484 SourceLocation RParenLoc;
3485 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3486 SourceLocation StartL, SourceLocation EndL)
3487 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3489 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3490 StringLiteral *Str, SourceLocation AsmLoc,
3491 SourceLocation RParenLoc);
3493 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3495 SourceLocation getAsmLoc() const { return getLocation(); }
3496 SourceLocation getRParenLoc() const { return RParenLoc; }
3497 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3498 SourceRange getSourceRange() const override LLVM_READONLY {
3499 return SourceRange(getAsmLoc(), getRParenLoc());
3502 const StringLiteral *getAsmString() const { return AsmString; }
3503 StringLiteral *getAsmString() { return AsmString; }
3504 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3506 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3507 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3510 /// BlockDecl - This represents a block literal declaration, which is like an
3511 /// unnamed FunctionDecl. For example:
3512 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3514 class BlockDecl : public Decl, public DeclContext {
3516 /// A class which contains all the information about a particular
3524 /// The variable being captured.
3525 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3527 /// The copy expression, expressed in terms of a DeclRef (or
3528 /// BlockDeclRef) to the captured variable. Only required if the
3529 /// variable has a C++ class type.
3533 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3534 : VariableAndFlags(variable,
3535 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3538 /// The variable being captured.
3539 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3541 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3543 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3545 /// Whether this is a nested capture, i.e. the variable captured
3546 /// is not from outside the immediately enclosing function/block.
3547 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3549 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3550 Expr *getCopyExpr() const { return CopyExpr; }
3551 void setCopyExpr(Expr *e) { CopyExpr = e; }
3555 // FIXME: This can be packed into the bitfields in Decl.
3556 bool IsVariadic : 1;
3557 bool CapturesCXXThis : 1;
3558 bool BlockMissingReturnType : 1;
3559 bool IsConversionFromLambda : 1;
3560 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3561 /// parameters of this function. This is null if a prototype or if there are
3563 ParmVarDecl **ParamInfo;
3567 TypeSourceInfo *SignatureAsWritten;
3569 const Capture *Captures;
3570 unsigned NumCaptures;
3572 unsigned ManglingNumber;
3573 Decl *ManglingContextDecl;
3576 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3577 : Decl(Block, DC, CaretLoc), DeclContext(Block),
3578 IsVariadic(false), CapturesCXXThis(false),
3579 BlockMissingReturnType(true), IsConversionFromLambda(false),
3580 ParamInfo(nullptr), NumParams(0), Body(nullptr),
3581 SignatureAsWritten(nullptr), Captures(nullptr), NumCaptures(0),
3582 ManglingNumber(0), ManglingContextDecl(nullptr) {}
3585 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3586 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3588 SourceLocation getCaretLocation() const { return getLocation(); }
3590 bool isVariadic() const { return IsVariadic; }
3591 void setIsVariadic(bool value) { IsVariadic = value; }
3593 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3594 Stmt *getBody() const override { return (Stmt*) Body; }
3595 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3597 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3598 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3600 // ArrayRef access to formal parameters.
3601 ArrayRef<ParmVarDecl *> parameters() const {
3602 return {ParamInfo, getNumParams()};
3604 MutableArrayRef<ParmVarDecl *> parameters() {
3605 return {ParamInfo, getNumParams()};
3608 // Iterator access to formal parameters.
3609 typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
3610 typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
3611 bool param_empty() const { return parameters().empty(); }
3612 param_iterator param_begin() { return parameters().begin(); }
3613 param_iterator param_end() { return parameters().end(); }
3614 param_const_iterator param_begin() const { return parameters().begin(); }
3615 param_const_iterator param_end() const { return parameters().end(); }
3616 size_t param_size() const { return parameters().size(); }
3618 unsigned getNumParams() const { return NumParams; }
3619 const ParmVarDecl *getParamDecl(unsigned i) const {
3620 assert(i < getNumParams() && "Illegal param #");
3621 return ParamInfo[i];
3623 ParmVarDecl *getParamDecl(unsigned i) {
3624 assert(i < getNumParams() && "Illegal param #");
3625 return ParamInfo[i];
3627 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3629 /// hasCaptures - True if this block (or its nested blocks) captures
3630 /// anything of local storage from its enclosing scopes.
3631 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3633 /// getNumCaptures - Returns the number of captured variables.
3634 /// Does not include an entry for 'this'.
3635 unsigned getNumCaptures() const { return NumCaptures; }
3637 typedef ArrayRef<Capture>::const_iterator capture_const_iterator;
3639 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3641 capture_const_iterator capture_begin() const { return captures().begin(); }
3642 capture_const_iterator capture_end() const { return captures().end(); }
3644 bool capturesCXXThis() const { return CapturesCXXThis; }
3645 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3646 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3648 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3649 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3651 bool capturesVariable(const VarDecl *var) const;
3653 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3654 bool CapturesCXXThis);
3656 unsigned getBlockManglingNumber() const {
3657 return ManglingNumber;
3659 Decl *getBlockManglingContextDecl() const {
3660 return ManglingContextDecl;
3663 void setBlockMangling(unsigned Number, Decl *Ctx) {
3664 ManglingNumber = Number;
3665 ManglingContextDecl = Ctx;
3668 SourceRange getSourceRange() const override LLVM_READONLY;
3670 // Implement isa/cast/dyncast/etc.
3671 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3672 static bool classofKind(Kind K) { return K == Block; }
3673 static DeclContext *castToDeclContext(const BlockDecl *D) {
3674 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3676 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3677 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3681 /// \brief This represents the body of a CapturedStmt, and serves as its
3683 class CapturedDecl final
3686 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3688 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3693 /// \brief The number of parameters to the outlined function.
3695 /// \brief The position of context parameter in list of parameters.
3696 unsigned ContextParam;
3697 /// \brief The body of the outlined function.
3698 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3700 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3702 ImplicitParamDecl *const *getParams() const {
3703 return getTrailingObjects<ImplicitParamDecl *>();
3706 ImplicitParamDecl **getParams() {
3707 return getTrailingObjects<ImplicitParamDecl *>();
3711 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3712 unsigned NumParams);
3713 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3714 unsigned NumParams);
3716 Stmt *getBody() const override;
3717 void setBody(Stmt *B);
3719 bool isNothrow() const;
3720 void setNothrow(bool Nothrow = true);
3722 unsigned getNumParams() const { return NumParams; }
3724 ImplicitParamDecl *getParam(unsigned i) const {
3725 assert(i < NumParams);
3726 return getParams()[i];
3728 void setParam(unsigned i, ImplicitParamDecl *P) {
3729 assert(i < NumParams);
3733 // ArrayRef interface to parameters.
3734 ArrayRef<ImplicitParamDecl *> parameters() const {
3735 return {getParams(), getNumParams()};
3737 MutableArrayRef<ImplicitParamDecl *> parameters() {
3738 return {getParams(), getNumParams()};
3741 /// \brief Retrieve the parameter containing captured variables.
3742 ImplicitParamDecl *getContextParam() const {
3743 assert(ContextParam < NumParams);
3744 return getParam(ContextParam);
3746 void setContextParam(unsigned i, ImplicitParamDecl *P) {
3747 assert(i < NumParams);
3751 unsigned getContextParamPosition() const { return ContextParam; }
3753 typedef ImplicitParamDecl *const *param_iterator;
3754 typedef llvm::iterator_range<param_iterator> param_range;
3756 /// \brief Retrieve an iterator pointing to the first parameter decl.
3757 param_iterator param_begin() const { return getParams(); }
3758 /// \brief Retrieve an iterator one past the last parameter decl.
3759 param_iterator param_end() const { return getParams() + NumParams; }
3761 // Implement isa/cast/dyncast/etc.
3762 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3763 static bool classofKind(Kind K) { return K == Captured; }
3764 static DeclContext *castToDeclContext(const CapturedDecl *D) {
3765 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3767 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3768 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3771 friend class ASTDeclReader;
3772 friend class ASTDeclWriter;
3773 friend TrailingObjects;
3776 /// \brief Describes a module import declaration, which makes the contents
3777 /// of the named module visible in the current translation unit.
3779 /// An import declaration imports the named module (or submodule). For example:
3781 /// @import std.vector;
3784 /// Import declarations can also be implicitly generated from
3785 /// \#include/\#import directives.
3786 class ImportDecl final : public Decl,
3787 llvm::TrailingObjects<ImportDecl, SourceLocation> {
3788 /// \brief The imported module, along with a bit that indicates whether
3789 /// we have source-location information for each identifier in the module
3792 /// When the bit is false, we only have a single source location for the
3793 /// end of the import declaration.
3794 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3796 /// \brief The next import in the list of imports local to the translation
3797 /// unit being parsed (not loaded from an AST file).
3798 ImportDecl *NextLocalImport;
3800 friend class ASTReader;
3801 friend class ASTDeclReader;
3802 friend class ASTContext;
3803 friend TrailingObjects;
3805 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3806 ArrayRef<SourceLocation> IdentifierLocs);
3808 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3809 SourceLocation EndLoc);
3811 ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3814 /// \brief Create a new module import declaration.
3815 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3816 SourceLocation StartLoc, Module *Imported,
3817 ArrayRef<SourceLocation> IdentifierLocs);
3819 /// \brief Create a new module import declaration for an implicitly-generated
3821 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3822 SourceLocation StartLoc, Module *Imported,
3823 SourceLocation EndLoc);
3825 /// \brief Create a new, deserialized module import declaration.
3826 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3827 unsigned NumLocations);
3829 /// \brief Retrieve the module that was imported by the import declaration.
3830 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3832 /// \brief Retrieves the locations of each of the identifiers that make up
3833 /// the complete module name in the import declaration.
3835 /// This will return an empty array if the locations of the individual
3836 /// identifiers aren't available.
3837 ArrayRef<SourceLocation> getIdentifierLocs() const;
3839 SourceRange getSourceRange() const override LLVM_READONLY;
3841 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3842 static bool classofKind(Kind K) { return K == Import; }
3845 /// \brief Represents a C++ Modules TS module export declaration.
3849 /// export void foo();
3851 class ExportDecl final : public Decl, public DeclContext {
3852 virtual void anchor();
3854 /// \brief The source location for the right brace (if valid).
3855 SourceLocation RBraceLoc;
3857 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
3858 : Decl(Export, DC, ExportLoc), DeclContext(Export),
3859 RBraceLoc(SourceLocation()) { }
3861 friend class ASTDeclReader;
3864 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
3865 SourceLocation ExportLoc);
3866 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3868 SourceLocation getExportLoc() const { return getLocation(); }
3869 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3870 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
3872 SourceLocation getLocEnd() const LLVM_READONLY {
3873 if (RBraceLoc.isValid())
3875 // No braces: get the end location of the (only) declaration in context
3877 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
3880 SourceRange getSourceRange() const override LLVM_READONLY {
3881 return SourceRange(getLocation(), getLocEnd());
3884 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3885 static bool classofKind(Kind K) { return K == Export; }
3886 static DeclContext *castToDeclContext(const ExportDecl *D) {
3887 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
3889 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
3890 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
3894 /// \brief Represents an empty-declaration.
3895 class EmptyDecl : public Decl {
3896 virtual void anchor();
3897 EmptyDecl(DeclContext *DC, SourceLocation L)
3898 : Decl(Empty, DC, L) { }
3901 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3903 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3905 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3906 static bool classofKind(Kind K) { return K == Empty; }
3909 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3910 /// into a diagnostic with <<.
3911 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3912 const NamedDecl* ND) {
3913 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3914 DiagnosticsEngine::ak_nameddecl);
3917 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3918 const NamedDecl* ND) {
3919 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3920 DiagnosticsEngine::ak_nameddecl);
3924 template<typename decl_type>
3925 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
3926 // Note: This routine is implemented here because we need both NamedDecl
3927 // and Redeclarable to be defined.
3928 assert(RedeclLink.NextIsLatest() &&
3929 "setPreviousDecl on a decl already in a redeclaration chain");
3932 // Point to previous. Make sure that this is actually the most recent
3933 // redeclaration, or we can build invalid chains. If the most recent
3934 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3935 First = PrevDecl->getFirstDecl();
3936 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3937 decl_type *MostRecent = First->getNextRedeclaration();
3938 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3940 // If the declaration was previously visible, a redeclaration of it remains
3941 // visible even if it wouldn't be visible by itself.
3942 static_cast<decl_type*>(this)->IdentifierNamespace |=
3943 MostRecent->getIdentifierNamespace() &
3944 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3947 First = static_cast<decl_type*>(this);
3950 // First one will point to this one as latest.
3951 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
3953 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3954 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3957 // Inline function definitions.
3959 /// \brief Check if the given decl is complete.
3961 /// We use this function to break a cycle between the inline definitions in
3962 /// Type.h and Decl.h.
3963 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3964 return ED->isComplete();
3967 /// \brief Check if the given decl is scoped.
3969 /// We use this function to break a cycle between the inline definitions in
3970 /// Type.h and Decl.h.
3971 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3972 return ED->isScoped();
3975 } // end namespace clang