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/Redeclarable.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/ExternalASTSource.h"
22 #include "clang/Basic/Linkage.h"
23 #include "llvm/ADT/Optional.h"
28 class FunctionTemplateDecl;
32 class NestedNameSpecifier;
33 class TemplateParameterList;
34 class TemplateArgumentList;
35 class MemberSpecializationInfo;
36 class FunctionTemplateSpecializationInfo;
37 class DependentFunctionTemplateSpecializationInfo;
39 class UnresolvedSetImpl;
42 /// \brief A container of type source information.
44 /// A client can read the relevant info using TypeLoc wrappers, e.g:
46 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
47 /// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
48 /// PL->getStarLoc().print(OS, SrcMgr);
51 class TypeSourceInfo {
53 // Contains a memory block after the class, used for type source information,
54 // allocated by ASTContext.
55 friend class ASTContext;
56 TypeSourceInfo(QualType ty) : Ty(ty) { }
58 /// \brief Return the type wrapped by this type source info.
59 QualType getType() const { return Ty; }
61 /// \brief Return the TypeLoc wrapper for the type source info.
62 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
65 /// TranslationUnitDecl - The top declaration context.
66 class TranslationUnitDecl : public Decl, public DeclContext {
69 /// The (most recently entered) anonymous namespace for this
70 /// translation unit, if one has been created.
71 NamespaceDecl *AnonymousNamespace;
73 explicit TranslationUnitDecl(ASTContext &ctx)
74 : Decl(TranslationUnit, 0, SourceLocation()),
75 DeclContext(TranslationUnit),
76 Ctx(ctx), AnonymousNamespace(0) {}
78 ASTContext &getASTContext() const { return Ctx; }
80 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
81 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
83 static TranslationUnitDecl *Create(ASTContext &C);
84 // Implement isa/cast/dyncast/etc.
85 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
86 static bool classof(const TranslationUnitDecl *D) { return true; }
87 static bool classofKind(Kind K) { return K == TranslationUnit; }
88 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
89 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
91 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
92 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
96 /// NamedDecl - This represents a decl with a name. Many decls have names such
97 /// as ObjCMethodDecl, but not @class, etc.
98 class NamedDecl : public Decl {
99 /// Name - The name of this declaration, which is typically a normal
100 /// identifier but may also be a special kind of name (C++
101 /// constructor, Objective-C selector, etc.)
102 DeclarationName Name;
105 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
106 : Decl(DK, DC, L), Name(N) { }
109 /// getIdentifier - Get the identifier that names this declaration,
110 /// if there is one. This will return NULL if this declaration has
111 /// no name (e.g., for an unnamed class) or if the name is a special
112 /// name (C++ constructor, Objective-C selector, etc.).
113 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
115 /// getName - Get the name of identifier for this declaration as a StringRef.
116 /// This requires that the declaration have a name and that it be a simple
118 llvm::StringRef getName() const {
119 assert(Name.isIdentifier() && "Name is not a simple identifier");
120 return getIdentifier() ? getIdentifier()->getName() : "";
123 /// getNameAsString - Get a human-readable name for the declaration, even if
124 /// it is one of the special kinds of names (C++ constructor, Objective-C
125 /// selector, etc). Creating this name requires expensive string
126 /// manipulation, so it should be called only when performance doesn't matter.
127 /// For simple declarations, getNameAsCString() should suffice.
129 // FIXME: This function should be renamed to indicate that it is not just an
130 // alternate form of getName(), and clients should move as appropriate.
132 // FIXME: Deprecated, move clients to getName().
133 std::string getNameAsString() const { return Name.getAsString(); }
135 void printName(llvm::raw_ostream &os) const { return Name.printName(os); }
137 /// getDeclName - Get the actual, stored name of the declaration,
138 /// which may be a special name.
139 DeclarationName getDeclName() const { return Name; }
141 /// \brief Set the name of this declaration.
142 void setDeclName(DeclarationName N) { Name = N; }
144 /// getQualifiedNameAsString - Returns human-readable qualified name for
145 /// declaration, like A::B::i, for i being member of namespace A::B.
146 /// If declaration is not member of context which can be named (record,
147 /// namespace), it will return same result as getNameAsString().
148 /// Creating this name is expensive, so it should be called only when
149 /// performance doesn't matter.
150 std::string getQualifiedNameAsString() const;
151 std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
153 /// getNameForDiagnostic - Appends a human-readable name for this
154 /// declaration into the given string.
156 /// This is the method invoked by Sema when displaying a NamedDecl
157 /// in a diagnostic. It does not necessarily produce the same
158 /// result as getNameAsString(); for example, class template
159 /// specializations are printed with their template arguments.
161 /// TODO: use an API that doesn't require so many temporary strings
162 virtual void getNameForDiagnostic(std::string &S,
163 const PrintingPolicy &Policy,
164 bool Qualified) const {
166 S += getQualifiedNameAsString(Policy);
168 S += getNameAsString();
171 /// declarationReplaces - Determine whether this declaration, if
172 /// known to be well-formed within its context, will replace the
173 /// declaration OldD if introduced into scope. A declaration will
174 /// replace another declaration if, for example, it is a
175 /// redeclaration of the same variable or function, but not if it is
176 /// a declaration of a different kind (function vs. class) or an
177 /// overloaded function.
178 bool declarationReplaces(NamedDecl *OldD) const;
180 /// \brief Determine whether this declaration has linkage.
181 bool hasLinkage() const;
183 /// \brief Determine whether this declaration is a C++ class member.
184 bool isCXXClassMember() const {
185 const DeclContext *DC = getDeclContext();
187 // C++0x [class.mem]p1:
188 // The enumerators of an unscoped enumeration defined in
189 // the class are members of the class.
190 // FIXME: support C++0x scoped enumerations.
191 if (isa<EnumDecl>(DC))
192 DC = DC->getParent();
194 return DC->isRecord();
197 /// \brief Given that this declaration is a C++ class member,
198 /// determine whether it's an instance member of its class.
199 bool isCXXInstanceMember() const;
203 Visibility visibility_;
207 LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility),
209 LinkageInfo(Linkage L, Visibility V, bool E)
210 : linkage_(L), visibility_(V), explicit_(E) {}
212 static LinkageInfo external() {
213 return LinkageInfo();
215 static LinkageInfo internal() {
216 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
218 static LinkageInfo uniqueExternal() {
219 return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false);
221 static LinkageInfo none() {
222 return LinkageInfo(NoLinkage, DefaultVisibility, false);
225 Linkage linkage() const { return linkage_; }
226 Visibility visibility() const { return visibility_; }
227 bool visibilityExplicit() const { return explicit_; }
229 void setLinkage(Linkage L) { linkage_ = L; }
230 void setVisibility(Visibility V) { visibility_ = V; }
231 void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; }
232 void setVisibility(LinkageInfo Other) {
233 setVisibility(Other.visibility(), Other.visibilityExplicit());
236 void mergeLinkage(Linkage L) {
237 setLinkage(minLinkage(linkage(), L));
239 void mergeLinkage(LinkageInfo Other) {
240 setLinkage(minLinkage(linkage(), Other.linkage()));
243 void mergeVisibility(Visibility V) {
244 setVisibility(minVisibility(visibility(), V));
246 void mergeVisibility(Visibility V, bool E) {
247 setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E);
249 void mergeVisibility(LinkageInfo Other) {
250 mergeVisibility(Other.visibility(), Other.visibilityExplicit());
253 void merge(LinkageInfo Other) {
255 mergeVisibility(Other);
257 void merge(std::pair<Linkage,Visibility> LV) {
258 mergeLinkage(LV.first);
259 mergeVisibility(LV.second);
262 friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
268 /// \brief Determine what kind of linkage this entity has.
269 Linkage getLinkage() const;
271 /// \brief Determines the visibility of this entity.
272 Visibility getVisibility() const { return getLinkageAndVisibility().visibility(); }
274 /// \brief Determines the linkage and visibility of this entity.
275 LinkageInfo getLinkageAndVisibility() const;
277 /// \brief If visibility was explicitly specified for this
278 /// declaration, return that visibility.
279 llvm::Optional<Visibility> getExplicitVisibility() const;
281 /// \brief Clear the linkage cache in response to a change
282 /// to the declaration.
283 void ClearLinkageCache();
285 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
286 /// the underlying named decl.
287 NamedDecl *getUnderlyingDecl();
288 const NamedDecl *getUnderlyingDecl() const {
289 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
292 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
293 static bool classof(const NamedDecl *D) { return true; }
294 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
297 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
298 const NamedDecl *ND) {
299 ND->getDeclName().printName(OS);
303 /// LabelDecl - Represents the declaration of a label. Labels also have a
304 /// corresponding LabelStmt, which indicates the position that the label was
305 /// defined at. For normal labels, the location of the decl is the same as the
306 /// location of the statement. For GNU local labels (__label__), the decl
307 /// location is where the __label__ is.
308 class LabelDecl : public NamedDecl {
310 /// LocStart - For normal labels, this is the same as the main declaration
311 /// label, i.e., the location of the identifier; for GNU local labels,
312 /// this is the location of the __label__ keyword.
313 SourceLocation LocStart;
315 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
316 LabelStmt *S, SourceLocation StartL)
317 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
320 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
321 SourceLocation IdentL, IdentifierInfo *II);
322 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
323 SourceLocation IdentL, IdentifierInfo *II,
324 SourceLocation GnuLabelL);
326 LabelStmt *getStmt() const { return TheStmt; }
327 void setStmt(LabelStmt *T) { TheStmt = T; }
329 bool isGnuLocal() const { return LocStart != getLocation(); }
330 void setLocStart(SourceLocation L) { LocStart = L; }
332 SourceRange getSourceRange() const {
333 return SourceRange(LocStart, getLocation());
336 // Implement isa/cast/dyncast/etc.
337 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
338 static bool classof(const LabelDecl *D) { return true; }
339 static bool classofKind(Kind K) { return K == Label; }
342 /// NamespaceDecl - Represent a C++ namespace.
343 class NamespaceDecl : public NamedDecl, public DeclContext {
346 /// LocStart - The starting location of the source range, pointing
347 /// to either the namespace or the inline keyword.
348 SourceLocation LocStart;
349 /// RBraceLoc - The ending location of the source range.
350 SourceLocation RBraceLoc;
352 // For extended namespace definitions:
354 // namespace A { int x; }
355 // namespace A { int y; }
357 // there will be one NamespaceDecl for each declaration.
358 // NextNamespace points to the next extended declaration.
359 // OrigNamespace points to the original namespace declaration.
360 // OrigNamespace of the first namespace decl points to its anonymous namespace
361 LazyDeclPtr NextNamespace;
363 /// \brief A pointer to either the original namespace definition for
364 /// this namespace (if the boolean value is false) or the anonymous
365 /// namespace that lives just inside this namespace (if the boolean
368 /// We can combine these two notions because the anonymous namespace
369 /// must only be stored in one of the namespace declarations (so all
370 /// of the namespace declarations can find it). We therefore choose
371 /// the original namespace declaration, since all of the namespace
372 /// declarations have a link directly to it; the original namespace
373 /// declaration itself only needs to know that it is the original
374 /// namespace declaration (which the boolean indicates).
375 llvm::PointerIntPair<NamespaceDecl *, 1, bool> OrigOrAnonNamespace;
377 NamespaceDecl(DeclContext *DC, SourceLocation StartLoc,
378 SourceLocation IdLoc, IdentifierInfo *Id)
379 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
380 IsInline(false), LocStart(StartLoc), RBraceLoc(),
381 NextNamespace(), OrigOrAnonNamespace(0, true) { }
384 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
385 SourceLocation StartLoc,
386 SourceLocation IdLoc, IdentifierInfo *Id);
388 /// \brief Returns true if this is an anonymous namespace declaration.
396 /// q.v. C++ [namespace.unnamed]
397 bool isAnonymousNamespace() const {
398 return !getIdentifier();
401 /// \brief Returns true if this is an inline namespace declaration.
402 bool isInline() const {
406 /// \brief Set whether this is an inline namespace declaration.
407 void setInline(bool Inline) {
411 /// \brief Return the next extended namespace declaration or null if there
413 NamespaceDecl *getNextNamespace();
414 const NamespaceDecl *getNextNamespace() const {
415 return const_cast<NamespaceDecl *>(this)->getNextNamespace();
418 /// \brief Set the next extended namespace declaration.
419 void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; }
421 /// \brief Get the original (first) namespace declaration.
422 NamespaceDecl *getOriginalNamespace() const {
423 if (OrigOrAnonNamespace.getInt())
424 return const_cast<NamespaceDecl *>(this);
426 return OrigOrAnonNamespace.getPointer();
429 /// \brief Return true if this declaration is an original (first) declaration
430 /// of the namespace. This is false for non-original (subsequent) namespace
431 /// declarations and anonymous namespaces.
432 bool isOriginalNamespace() const {
433 return getOriginalNamespace() == this;
436 /// \brief Set the original (first) namespace declaration.
437 void setOriginalNamespace(NamespaceDecl *ND) {
439 OrigOrAnonNamespace.setPointer(ND);
440 OrigOrAnonNamespace.setInt(false);
444 NamespaceDecl *getAnonymousNamespace() const {
445 return getOriginalNamespace()->OrigOrAnonNamespace.getPointer();
448 void setAnonymousNamespace(NamespaceDecl *D) {
449 assert(!D || D->isAnonymousNamespace());
450 assert(!D || D->getParent()->getRedeclContext() == this);
451 getOriginalNamespace()->OrigOrAnonNamespace.setPointer(D);
454 virtual NamespaceDecl *getCanonicalDecl() { return getOriginalNamespace(); }
455 const NamespaceDecl *getCanonicalDecl() const {
456 return getOriginalNamespace();
459 virtual SourceRange getSourceRange() const {
460 return SourceRange(LocStart, RBraceLoc);
463 SourceLocation getLocStart() const { return LocStart; }
464 SourceLocation getRBraceLoc() const { return RBraceLoc; }
465 void setLocStart(SourceLocation L) { LocStart = L; }
466 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
468 // Implement isa/cast/dyncast/etc.
469 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
470 static bool classof(const NamespaceDecl *D) { return true; }
471 static bool classofKind(Kind K) { return K == Namespace; }
472 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
473 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
475 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
476 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
479 friend class ASTDeclReader;
480 friend class ASTDeclWriter;
483 /// ValueDecl - Represent the declaration of a variable (in which case it is
484 /// an lvalue) a function (in which case it is a function designator) or
485 /// an enum constant.
486 class ValueDecl : public NamedDecl {
490 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
491 DeclarationName N, QualType T)
492 : NamedDecl(DK, DC, L, N), DeclType(T) {}
494 QualType getType() const { return DeclType; }
495 void setType(QualType newType) { DeclType = newType; }
497 // Implement isa/cast/dyncast/etc.
498 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
499 static bool classof(const ValueDecl *D) { return true; }
500 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
503 /// QualifierInfo - A struct with extended info about a syntactic
504 /// name qualifier, to be used for the case of out-of-line declarations.
505 struct QualifierInfo {
506 NestedNameSpecifierLoc QualifierLoc;
508 /// NumTemplParamLists - The number of "outer" template parameter lists.
509 /// The count includes all of the template parameter lists that were matched
510 /// against the template-ids occurring into the NNS and possibly (in the
511 /// case of an explicit specialization) a final "template <>".
512 unsigned NumTemplParamLists;
514 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
515 /// containing pointers to the "outer" template parameter lists.
516 /// It includes all of the template parameter lists that were matched
517 /// against the template-ids occurring into the NNS and possibly (in the
518 /// case of an explicit specialization) a final "template <>".
519 TemplateParameterList** TemplParamLists;
521 /// Default constructor.
522 QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
524 /// setTemplateParameterListsInfo - Sets info about "outer" template
526 void setTemplateParameterListsInfo(ASTContext &Context,
528 TemplateParameterList **TPLists);
531 // Copy constructor and copy assignment are disabled.
532 QualifierInfo(const QualifierInfo&);
533 QualifierInfo& operator=(const QualifierInfo&);
536 /// \brief Represents a ValueDecl that came out of a declarator.
537 /// Contains type source information through TypeSourceInfo.
538 class DeclaratorDecl : public ValueDecl {
539 // A struct representing both a TInfo and a syntactic qualifier,
540 // to be used for the (uncommon) case of out-of-line declarations.
541 struct ExtInfo : public QualifierInfo {
542 TypeSourceInfo *TInfo;
545 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
547 /// InnerLocStart - The start of the source range for this declaration,
548 /// ignoring outer template declarations.
549 SourceLocation InnerLocStart;
551 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
552 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
553 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
556 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
557 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
558 SourceLocation StartL)
559 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
563 TypeSourceInfo *getTypeSourceInfo() const {
565 ? getExtInfo()->TInfo
566 : DeclInfo.get<TypeSourceInfo*>();
568 void setTypeSourceInfo(TypeSourceInfo *TI) {
570 getExtInfo()->TInfo = TI;
575 /// getInnerLocStart - Return SourceLocation representing start of source
576 /// range ignoring outer template declarations.
577 SourceLocation getInnerLocStart() const { return InnerLocStart; }
578 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
580 /// getOuterLocStart - Return SourceLocation representing start of source
581 /// range taking into account any outer template declarations.
582 SourceLocation getOuterLocStart() const;
584 virtual SourceRange getSourceRange() const;
586 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
587 /// declaration, if it was present in the source.
588 NestedNameSpecifier *getQualifier() const {
589 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
593 /// \brief Retrieve the nested-name-specifier (with source-location
594 /// information) that qualifies the name of this declaration, if it was
595 /// present in the source.
596 NestedNameSpecifierLoc getQualifierLoc() const {
597 return hasExtInfo() ? getExtInfo()->QualifierLoc
598 : NestedNameSpecifierLoc();
601 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
603 unsigned getNumTemplateParameterLists() const {
604 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
606 TemplateParameterList *getTemplateParameterList(unsigned index) const {
607 assert(index < getNumTemplateParameterLists());
608 return getExtInfo()->TemplParamLists[index];
610 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
611 TemplateParameterList **TPLists);
613 SourceLocation getTypeSpecStartLoc() const;
615 // Implement isa/cast/dyncast/etc.
616 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
617 static bool classof(const DeclaratorDecl *D) { return true; }
618 static bool classofKind(Kind K) {
619 return K >= firstDeclarator && K <= lastDeclarator;
622 friend class ASTDeclReader;
623 friend class ASTDeclWriter;
626 /// \brief Structure used to store a statement, the constant value to
627 /// which it was evaluated (if any), and whether or not the statement
628 /// is an integral constant expression (if known).
629 struct EvaluatedStmt {
630 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
631 CheckingICE(false), IsICE(false) { }
633 /// \brief Whether this statement was already evaluated.
634 bool WasEvaluated : 1;
636 /// \brief Whether this statement is being evaluated.
637 bool IsEvaluating : 1;
639 /// \brief Whether we already checked whether this statement was an
640 /// integral constant expression.
643 /// \brief Whether we are checking whether this statement is an
644 /// integral constant expression.
645 bool CheckingICE : 1;
647 /// \brief Whether this statement is an integral constant
648 /// expression. Only valid if CheckedICE is true.
655 /// VarDecl - An instance of this class is created to represent a variable
656 /// declaration or definition.
657 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
659 typedef clang::StorageClass StorageClass;
661 /// getStorageClassSpecifierString - Return the string used to
662 /// specify the storage class \arg SC.
664 /// It is illegal to call this function with SC == None.
665 static const char *getStorageClassSpecifierString(StorageClass SC);
668 /// \brief Placeholder type used in Init to denote an unparsed C++ default
670 struct UnparsedDefaultArgument;
672 /// \brief Placeholder type used in Init to denote an uninstantiated C++
673 /// default argument.
674 struct UninstantiatedDefaultArgument;
676 typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
677 UnparsedDefaultArgument *,
678 UninstantiatedDefaultArgument *> InitType;
680 /// \brief The initializer for this variable or, for a ParmVarDecl, the
681 /// C++ default argument.
682 mutable InitType Init;
685 class VarDeclBitfields {
686 friend class VarDecl;
687 friend class ASTDeclReader;
690 unsigned SClassAsWritten : 3;
691 unsigned ThreadSpecified : 1;
692 unsigned HasCXXDirectInit : 1;
694 /// \brief Whether this variable is the exception variable in a C++ catch
695 /// or an Objective-C @catch statement.
696 unsigned ExceptionVar : 1;
698 /// \brief Whether this local variable could be allocated in the return
699 /// slot of its function, enabling the named return value optimization (NRVO).
700 unsigned NRVOVariable : 1;
702 /// \brief Whether this variable is the for-range-declaration in a C++0x
703 /// for-range statement.
704 unsigned CXXForRangeDecl : 1;
706 /// \brief Whether this variable is an ARC pseudo-__strong
707 /// variable; see isARCPseudoStrong() for details.
708 unsigned ARCPseudoStrong : 1;
710 enum { NumVarDeclBits = 13 }; // one reserved bit
712 friend class ASTDeclReader;
713 friend class StmtIteratorBase;
716 class ParmVarDeclBitfields {
717 friend class ParmVarDecl;
718 friend class ASTDeclReader;
720 unsigned : NumVarDeclBits;
722 /// Whether this parameter inherits a default argument from a
723 /// prior declaration.
724 unsigned HasInheritedDefaultArg : 1;
726 /// Whether this parameter undergoes K&R argument promotion.
727 unsigned IsKNRPromoted : 1;
729 /// Whether this parameter is an ObjC method parameter or not.
730 unsigned IsObjCMethodParam : 1;
732 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
733 /// Otherwise, the number of function parameter scopes enclosing
734 /// the function parameter scope in which this parameter was
736 unsigned ScopeDepthOrObjCQuals : 8;
738 /// The number of parameters preceding this parameter in the
739 /// function parameter scope in which it was declared.
740 unsigned ParameterIndex : 8;
745 VarDeclBitfields VarDeclBits;
746 ParmVarDeclBitfields ParmVarDeclBits;
749 VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
750 SourceLocation IdLoc, IdentifierInfo *Id,
751 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
752 StorageClass SCAsWritten)
753 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
754 assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
755 assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
757 VarDeclBits.SClass = SC;
758 VarDeclBits.SClassAsWritten = SCAsWritten;
759 // Everything else is implicitly initialized to false.
762 typedef Redeclarable<VarDecl> redeclarable_base;
763 virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
766 typedef redeclarable_base::redecl_iterator redecl_iterator;
767 redecl_iterator redecls_begin() const {
768 return redeclarable_base::redecls_begin();
770 redecl_iterator redecls_end() const {
771 return redeclarable_base::redecls_end();
774 static VarDecl *Create(ASTContext &C, DeclContext *DC,
775 SourceLocation StartLoc, SourceLocation IdLoc,
776 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
777 StorageClass S, StorageClass SCAsWritten);
779 virtual SourceRange getSourceRange() const;
781 StorageClass getStorageClass() const {
782 return (StorageClass) VarDeclBits.SClass;
784 StorageClass getStorageClassAsWritten() const {
785 return (StorageClass) VarDeclBits.SClassAsWritten;
787 void setStorageClass(StorageClass SC);
788 void setStorageClassAsWritten(StorageClass SC) {
789 assert(isLegalForVariable(SC));
790 VarDeclBits.SClassAsWritten = SC;
793 void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
794 bool isThreadSpecified() const {
795 return VarDeclBits.ThreadSpecified;
798 /// hasLocalStorage - Returns true if a variable with function scope
799 /// is a non-static local variable.
800 bool hasLocalStorage() const {
801 if (getStorageClass() == SC_None)
802 return !isFileVarDecl();
804 // Return true for: Auto, Register.
805 // Return false for: Extern, Static, PrivateExtern.
807 return getStorageClass() >= SC_Auto;
810 /// isStaticLocal - Returns true if a variable with function scope is a
811 /// static local variable.
812 bool isStaticLocal() const {
813 return getStorageClass() == SC_Static && !isFileVarDecl();
816 /// hasExternStorage - Returns true if a variable has extern or
817 /// __private_extern__ storage.
818 bool hasExternalStorage() const {
819 return getStorageClass() == SC_Extern ||
820 getStorageClass() == SC_PrivateExtern;
823 /// hasGlobalStorage - Returns true for all variables that do not
824 /// have local storage. This includs all global variables as well
825 /// as static variables declared within a function.
826 bool hasGlobalStorage() const { return !hasLocalStorage(); }
828 /// \brief Determines whether this variable is a variable with
829 /// external, C linkage.
830 bool isExternC() const;
832 /// isLocalVarDecl - Returns true for local variable declarations
833 /// other than parameters. Note that this includes static variables
834 /// inside of functions. It also includes variables inside blocks.
836 /// void foo() { int x; static int y; extern int z; }
838 bool isLocalVarDecl() const {
839 if (getKind() != Decl::Var)
841 if (const DeclContext *DC = getDeclContext())
842 return DC->getRedeclContext()->isFunctionOrMethod();
846 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
847 /// excludes variables declared in blocks.
848 bool isFunctionOrMethodVarDecl() const {
849 if (getKind() != Decl::Var)
851 const DeclContext *DC = getDeclContext()->getRedeclContext();
852 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
855 /// \brief Determines whether this is a static data member.
857 /// This will only be true in C++, and applies to, e.g., the
864 bool isStaticDataMember() const {
865 // If it wasn't static, it would be a FieldDecl.
866 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
869 virtual VarDecl *getCanonicalDecl();
870 const VarDecl *getCanonicalDecl() const {
871 return const_cast<VarDecl*>(this)->getCanonicalDecl();
874 enum DefinitionKind {
875 DeclarationOnly, ///< This declaration is only a declaration.
876 TentativeDefinition, ///< This declaration is a tentative definition.
877 Definition ///< This declaration is definitely a definition.
880 /// \brief Check whether this declaration is a definition. If this could be
881 /// a tentative definition (in C), don't check whether there's an overriding
883 DefinitionKind isThisDeclarationADefinition() const;
885 /// \brief Check whether this variable is defined in this
886 /// translation unit.
887 DefinitionKind hasDefinition() const;
889 /// \brief Get the tentative definition that acts as the real definition in
890 /// a TU. Returns null if there is a proper definition available.
891 VarDecl *getActingDefinition();
892 const VarDecl *getActingDefinition() const {
893 return const_cast<VarDecl*>(this)->getActingDefinition();
896 /// \brief Determine whether this is a tentative definition of a
898 bool isTentativeDefinitionNow() const;
900 /// \brief Get the real (not just tentative) definition for this declaration.
901 VarDecl *getDefinition();
902 const VarDecl *getDefinition() const {
903 return const_cast<VarDecl*>(this)->getDefinition();
906 /// \brief Determine whether this is or was instantiated from an out-of-line
907 /// definition of a static data member.
908 virtual bool isOutOfLine() const;
910 /// \brief If this is a static data member, find its out-of-line definition.
911 VarDecl *getOutOfLineDefinition();
913 /// isFileVarDecl - Returns true for file scoped variable declaration.
914 bool isFileVarDecl() const {
915 if (getKind() != Decl::Var)
918 if (getDeclContext()->getRedeclContext()->isFileContext())
921 if (isStaticDataMember())
927 /// getAnyInitializer - Get the initializer for this variable, no matter which
928 /// declaration it is attached to.
929 const Expr *getAnyInitializer() const {
931 return getAnyInitializer(D);
934 /// getAnyInitializer - Get the initializer for this variable, no matter which
935 /// declaration it is attached to. Also get that declaration.
936 const Expr *getAnyInitializer(const VarDecl *&D) const;
938 bool hasInit() const {
939 return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
941 const Expr *getInit() const {
945 const Stmt *S = Init.dyn_cast<Stmt *>();
947 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
950 return (const Expr*) S;
956 Stmt *S = Init.dyn_cast<Stmt *>();
958 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
965 /// \brief Retrieve the address of the initializer expression.
966 Stmt **getInitAddress() {
967 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
970 // This union hack tip-toes around strict-aliasing rules.
980 void setInit(Expr *I);
982 /// \brief Determine whether this variable is a reference that
983 /// extends the lifetime of its temporary initializer.
985 /// A reference extends the lifetime of its temporary initializer if
986 /// it's initializer is an rvalue that would normally go out of scope
987 /// at the end of the initializer (a full expression). In such cases,
988 /// the reference itself takes ownership of the temporary, which will
989 /// be destroyed when the reference goes out of scope. For example:
992 /// const int &r = 1.0; // creates a temporary of type 'int'
994 bool extendsLifetimeOfTemporary() const;
996 EvaluatedStmt *EnsureEvaluatedStmt() const {
997 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
999 Stmt *S = Init.get<Stmt *>();
1000 Eval = new (getASTContext()) EvaluatedStmt;
1007 /// \brief Check whether we are in the process of checking whether the
1008 /// initializer can be evaluated.
1009 bool isEvaluatingValue() const {
1010 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1011 return Eval->IsEvaluating;
1016 /// \brief Note that we now are checking whether the initializer can be
1018 void setEvaluatingValue() const {
1019 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1020 Eval->IsEvaluating = true;
1023 /// \brief Note that constant evaluation has computed the given
1024 /// value for this variable's initializer.
1025 void setEvaluatedValue(const APValue &Value) const {
1026 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1027 Eval->IsEvaluating = false;
1028 Eval->WasEvaluated = true;
1029 Eval->Evaluated = Value;
1032 /// \brief Return the already-evaluated value of this variable's
1033 /// initializer, or NULL if the value is not yet known. Returns pointer
1034 /// to untyped APValue if the value could not be evaluated.
1035 APValue *getEvaluatedValue() const {
1036 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1037 if (Eval->WasEvaluated)
1038 return &Eval->Evaluated;
1043 /// \brief Determines whether it is already known whether the
1044 /// initializer is an integral constant expression or not.
1045 bool isInitKnownICE() const {
1046 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1047 return Eval->CheckedICE;
1052 /// \brief Determines whether the initializer is an integral
1053 /// constant expression.
1055 /// \pre isInitKnownICE()
1056 bool isInitICE() const {
1057 assert(isInitKnownICE() &&
1058 "Check whether we already know that the initializer is an ICE");
1059 return Init.get<EvaluatedStmt *>()->IsICE;
1062 /// \brief Check whether we are in the process of checking the initializer
1063 /// is an integral constant expression.
1064 bool isCheckingICE() const {
1065 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1066 return Eval->CheckingICE;
1071 /// \brief Note that we now are checking whether the initializer is an
1072 /// integral constant expression.
1073 void setCheckingICE() const {
1074 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1075 Eval->CheckingICE = true;
1078 /// \brief Note that we now know whether the initializer is an
1079 /// integral constant expression.
1080 void setInitKnownICE(bool IsICE) const {
1081 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1082 Eval->CheckingICE = false;
1083 Eval->CheckedICE = true;
1084 Eval->IsICE = IsICE;
1087 void setCXXDirectInitializer(bool T) { VarDeclBits.HasCXXDirectInit = T; }
1089 /// hasCXXDirectInitializer - If true, the initializer was a direct
1090 /// initializer, e.g: "int x(1);". The Init expression will be the expression
1091 /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
1092 /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
1093 /// by checking hasCXXDirectInitializer.
1095 bool hasCXXDirectInitializer() const {
1096 return VarDeclBits.HasCXXDirectInit;
1099 /// \brief Determine whether this variable is the exception variable in a
1100 /// C++ catch statememt or an Objective-C @catch statement.
1101 bool isExceptionVariable() const {
1102 return VarDeclBits.ExceptionVar;
1104 void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1106 /// \brief Determine whether this local variable can be used with the named
1107 /// return value optimization (NRVO).
1109 /// The named return value optimization (NRVO) works by marking certain
1110 /// non-volatile local variables of class type as NRVO objects. These
1111 /// locals can be allocated within the return slot of their containing
1112 /// function, in which case there is no need to copy the object to the
1113 /// return slot when returning from the function. Within the function body,
1114 /// each return that returns the NRVO object will have this variable as its
1116 bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1117 void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1119 /// \brief Determine whether this variable is the for-range-declaration in
1120 /// a C++0x for-range statement.
1121 bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1122 void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1124 /// \brief Determine whether this variable is an ARC pseudo-__strong
1125 /// variable. A pseudo-__strong variable has a __strong-qualified
1126 /// type but does not actually retain the object written into it.
1127 /// Generally such variables are also 'const' for safety.
1128 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1129 void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1131 /// \brief If this variable is an instantiated static data member of a
1132 /// class template specialization, returns the templated static data member
1133 /// from which it was instantiated.
1134 VarDecl *getInstantiatedFromStaticDataMember() const;
1136 /// \brief If this variable is a static data member, determine what kind of
1137 /// template specialization or instantiation this is.
1138 TemplateSpecializationKind getTemplateSpecializationKind() const;
1140 /// \brief If this variable is an instantiation of a static data member of a
1141 /// class template specialization, retrieves the member specialization
1143 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1145 /// \brief For a static data member that was instantiated from a static
1146 /// data member of a class template, set the template specialiation kind.
1147 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1148 SourceLocation PointOfInstantiation = SourceLocation());
1150 // Implement isa/cast/dyncast/etc.
1151 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1152 static bool classof(const VarDecl *D) { return true; }
1153 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1156 class ImplicitParamDecl : public VarDecl {
1158 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1159 SourceLocation IdLoc, IdentifierInfo *Id,
1162 ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1163 IdentifierInfo *Id, QualType Type)
1164 : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1165 /*tinfo*/ 0, SC_None, SC_None) {
1169 // Implement isa/cast/dyncast/etc.
1170 static bool classof(const ImplicitParamDecl *D) { return true; }
1171 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1172 static bool classofKind(Kind K) { return K == ImplicitParam; }
1175 /// ParmVarDecl - Represents a parameter to a function.
1176 class ParmVarDecl : public VarDecl {
1178 enum { MaxFunctionScopeDepth = 255 };
1179 enum { MaxFunctionScopeIndex = 255 };
1182 ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1183 SourceLocation IdLoc, IdentifierInfo *Id,
1184 QualType T, TypeSourceInfo *TInfo,
1185 StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
1186 : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) {
1187 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1188 assert(ParmVarDeclBits.IsKNRPromoted == false);
1189 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1190 setDefaultArg(DefArg);
1194 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1195 SourceLocation StartLoc,
1196 SourceLocation IdLoc, IdentifierInfo *Id,
1197 QualType T, TypeSourceInfo *TInfo,
1198 StorageClass S, StorageClass SCAsWritten,
1201 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1202 ParmVarDeclBits.IsObjCMethodParam = true;
1204 ParmVarDeclBits.ParameterIndex = parameterIndex;
1205 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1208 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1209 assert(!ParmVarDeclBits.IsObjCMethodParam);
1211 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1212 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!");
1214 ParmVarDeclBits.ParameterIndex = parameterIndex;
1215 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1218 bool isObjCMethodParameter() const {
1219 return ParmVarDeclBits.IsObjCMethodParam;
1222 unsigned getFunctionScopeDepth() const {
1223 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1224 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1227 /// Returns the index of this parameter in its prototype or method scope.
1228 unsigned getFunctionScopeIndex() const {
1229 return ParmVarDeclBits.ParameterIndex;
1232 ObjCDeclQualifier getObjCDeclQualifier() const {
1233 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1234 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1236 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1237 assert(ParmVarDeclBits.IsObjCMethodParam);
1238 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1241 /// True if the value passed to this parameter must undergo
1242 /// K&R-style default argument promotion:
1245 /// If the expression that denotes the called function has a type
1246 /// that does not include a prototype, the integer promotions are
1247 /// performed on each argument, and arguments that have type float
1248 /// are promoted to double.
1249 bool isKNRPromoted() const {
1250 return ParmVarDeclBits.IsKNRPromoted;
1252 void setKNRPromoted(bool promoted) {
1253 ParmVarDeclBits.IsKNRPromoted = promoted;
1256 Expr *getDefaultArg();
1257 const Expr *getDefaultArg() const {
1258 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1261 void setDefaultArg(Expr *defarg) {
1262 Init = reinterpret_cast<Stmt *>(defarg);
1265 unsigned getNumDefaultArgTemporaries() const;
1266 CXXTemporary *getDefaultArgTemporary(unsigned i);
1267 const CXXTemporary *getDefaultArgTemporary(unsigned i) const {
1268 return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i);
1271 /// \brief Retrieve the source range that covers the entire default
1273 SourceRange getDefaultArgRange() const;
1274 void setUninstantiatedDefaultArg(Expr *arg) {
1275 Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1277 Expr *getUninstantiatedDefaultArg() {
1278 return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1280 const Expr *getUninstantiatedDefaultArg() const {
1281 return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1284 /// hasDefaultArg - Determines whether this parameter has a default argument,
1285 /// either parsed or not.
1286 bool hasDefaultArg() const {
1287 return getInit() || hasUnparsedDefaultArg() ||
1288 hasUninstantiatedDefaultArg();
1291 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1292 /// default argument that has not yet been parsed. This will occur
1293 /// during the processing of a C++ class whose member functions have
1294 /// default arguments, e.g.,
1298 /// void f(int x = 17); // x has an unparsed default argument now
1299 /// }; // x has a regular default argument now
1301 bool hasUnparsedDefaultArg() const {
1302 return Init.is<UnparsedDefaultArgument*>();
1305 bool hasUninstantiatedDefaultArg() const {
1306 return Init.is<UninstantiatedDefaultArgument*>();
1309 /// setUnparsedDefaultArg - Specify that this parameter has an
1310 /// unparsed default argument. The argument will be replaced with a
1311 /// real default argument via setDefaultArg when the class
1312 /// definition enclosing the function declaration that owns this
1313 /// default argument is completed.
1314 void setUnparsedDefaultArg() {
1315 Init = (UnparsedDefaultArgument *)0;
1318 bool hasInheritedDefaultArg() const {
1319 return ParmVarDeclBits.HasInheritedDefaultArg;
1322 void setHasInheritedDefaultArg(bool I = true) {
1323 ParmVarDeclBits.HasInheritedDefaultArg = I;
1326 QualType getOriginalType() const {
1327 if (getTypeSourceInfo())
1328 return getTypeSourceInfo()->getType();
1332 /// \brief Determine whether this parameter is actually a function
1334 bool isParameterPack() const;
1336 /// setOwningFunction - Sets the function declaration that owns this
1337 /// ParmVarDecl. Since ParmVarDecls are often created before the
1338 /// FunctionDecls that own them, this routine is required to update
1339 /// the DeclContext appropriately.
1340 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1342 // Implement isa/cast/dyncast/etc.
1343 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1344 static bool classof(const ParmVarDecl *D) { return true; }
1345 static bool classofKind(Kind K) { return K == ParmVar; }
1348 /// FunctionDecl - An instance of this class is created to represent a
1349 /// function declaration or definition.
1351 /// Since a given function can be declared several times in a program,
1352 /// there may be several FunctionDecls that correspond to that
1353 /// function. Only one of those FunctionDecls will be found when
1354 /// traversing the list of declarations in the context of the
1355 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1356 /// contains all of the information known about the function. Other,
1357 /// previous declarations of the function are available via the
1358 /// getPreviousDeclaration() chain.
1359 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1360 public Redeclarable<FunctionDecl> {
1362 typedef clang::StorageClass StorageClass;
1364 /// \brief The kind of templated function a FunctionDecl can be.
1365 enum TemplatedKind {
1367 TK_FunctionTemplate,
1368 TK_MemberSpecialization,
1369 TK_FunctionTemplateSpecialization,
1370 TK_DependentFunctionTemplateSpecialization
1374 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1375 /// parameters of this function. This is null if a prototype or if there are
1377 ParmVarDecl **ParamInfo;
1379 LazyDeclStmtPtr Body;
1381 // FIXME: This can be packed into the bitfields in Decl.
1382 // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1383 unsigned SClass : 2;
1384 unsigned SClassAsWritten : 2;
1386 bool IsInlineSpecified : 1;
1387 bool IsVirtualAsWritten : 1;
1389 bool HasInheritedPrototype : 1;
1390 bool HasWrittenPrototype : 1;
1392 bool IsTrivial : 1; // sunk from CXXMethodDecl
1393 bool IsDefaulted : 1; // sunk from CXXMethoDecl
1394 bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1395 bool HasImplicitReturnZero : 1;
1396 bool IsLateTemplateParsed : 1;
1398 /// \brief End part of this FunctionDecl's source range.
1400 /// We could compute the full range in getSourceRange(). However, when we're
1401 /// dealing with a function definition deserialized from a PCH/AST file,
1402 /// we can only compute the full range once the function body has been
1403 /// de-serialized, so it's far better to have the (sometimes-redundant)
1405 SourceLocation EndRangeLoc;
1407 /// \brief The template or declaration that this declaration
1408 /// describes or was instantiated from, respectively.
1410 /// For non-templates, this value will be NULL. For function
1411 /// declarations that describe a function template, this will be a
1412 /// pointer to a FunctionTemplateDecl. For member functions
1413 /// of class template specializations, this will be a MemberSpecializationInfo
1414 /// pointer containing information about the specialization.
1415 /// For function template specializations, this will be a
1416 /// FunctionTemplateSpecializationInfo, which contains information about
1417 /// the template being specialized and the template arguments involved in
1418 /// that specialization.
1419 llvm::PointerUnion4<FunctionTemplateDecl *,
1420 MemberSpecializationInfo *,
1421 FunctionTemplateSpecializationInfo *,
1422 DependentFunctionTemplateSpecializationInfo *>
1423 TemplateOrSpecialization;
1425 /// DNLoc - Provides source/type location info for the
1426 /// declaration name embedded in the DeclaratorDecl base class.
1427 DeclarationNameLoc DNLoc;
1429 /// \brief Specify that this function declaration is actually a function
1430 /// template specialization.
1432 /// \param C the ASTContext.
1434 /// \param Template the function template that this function template
1435 /// specialization specializes.
1437 /// \param TemplateArgs the template arguments that produced this
1438 /// function template specialization from the template.
1440 /// \param InsertPos If non-NULL, the position in the function template
1441 /// specialization set where the function template specialization data will
1444 /// \param TSK the kind of template specialization this is.
1446 /// \param TemplateArgsAsWritten location info of template arguments.
1448 /// \param PointOfInstantiation point at which the function template
1449 /// specialization was first instantiated.
1450 void setFunctionTemplateSpecialization(ASTContext &C,
1451 FunctionTemplateDecl *Template,
1452 const TemplateArgumentList *TemplateArgs,
1454 TemplateSpecializationKind TSK,
1455 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1456 SourceLocation PointOfInstantiation);
1458 /// \brief Specify that this record is an instantiation of the
1459 /// member function FD.
1460 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1461 TemplateSpecializationKind TSK);
1463 void setParams(ASTContext &C, ParmVarDecl **NewParamInfo, unsigned NumParams);
1466 FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1467 const DeclarationNameInfo &NameInfo,
1468 QualType T, TypeSourceInfo *TInfo,
1469 StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified)
1470 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1473 ParamInfo(0), Body(),
1474 SClass(S), SClassAsWritten(SCAsWritten),
1475 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1476 IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1477 HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1478 IsDefaulted(false), IsExplicitlyDefaulted(false),
1479 HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1480 EndRangeLoc(NameInfo.getEndLoc()),
1481 TemplateOrSpecialization(),
1482 DNLoc(NameInfo.getInfo()) {}
1484 typedef Redeclarable<FunctionDecl> redeclarable_base;
1485 virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1488 typedef redeclarable_base::redecl_iterator redecl_iterator;
1489 redecl_iterator redecls_begin() const {
1490 return redeclarable_base::redecls_begin();
1492 redecl_iterator redecls_end() const {
1493 return redeclarable_base::redecls_end();
1496 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1497 SourceLocation StartLoc, SourceLocation NLoc,
1498 DeclarationName N, QualType T,
1499 TypeSourceInfo *TInfo,
1500 StorageClass SC = SC_None,
1501 StorageClass SCAsWritten = SC_None,
1502 bool isInlineSpecified = false,
1503 bool hasWrittenPrototype = true) {
1504 DeclarationNameInfo NameInfo(N, NLoc);
1505 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1507 isInlineSpecified, hasWrittenPrototype);
1510 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1511 SourceLocation StartLoc,
1512 const DeclarationNameInfo &NameInfo,
1513 QualType T, TypeSourceInfo *TInfo,
1514 StorageClass SC = SC_None,
1515 StorageClass SCAsWritten = SC_None,
1516 bool isInlineSpecified = false,
1517 bool hasWrittenPrototype = true);
1519 DeclarationNameInfo getNameInfo() const {
1520 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1523 virtual void getNameForDiagnostic(std::string &S,
1524 const PrintingPolicy &Policy,
1525 bool Qualified) const;
1527 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1529 virtual SourceRange getSourceRange() const;
1531 /// \brief Returns true if the function has a body (definition). The
1532 /// function body might be in any of the (re-)declarations of this
1533 /// function. The variant that accepts a FunctionDecl pointer will
1534 /// set that function declaration to the actual declaration
1535 /// containing the body (if there is one).
1536 bool hasBody(const FunctionDecl *&Definition) const;
1538 virtual bool hasBody() const {
1539 const FunctionDecl* Definition;
1540 return hasBody(Definition);
1543 /// hasTrivialBody - Returns whether the function has a trivial body that does
1544 /// not require any specific codegen.
1545 bool hasTrivialBody() const;
1547 /// isDefined - Returns true if the function is defined at all, including
1548 /// a deleted definition. Except for the behavior when the function is
1549 /// deleted, behaves like hasBody.
1550 bool isDefined(const FunctionDecl *&Definition) const;
1552 virtual bool isDefined() const {
1553 const FunctionDecl* Definition;
1554 return isDefined(Definition);
1557 /// getBody - Retrieve the body (definition) of the function. The
1558 /// function body might be in any of the (re-)declarations of this
1559 /// function. The variant that accepts a FunctionDecl pointer will
1560 /// set that function declaration to the actual declaration
1561 /// containing the body (if there is one).
1562 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1563 /// unnecessary AST de-serialization of the body.
1564 Stmt *getBody(const FunctionDecl *&Definition) const;
1566 virtual Stmt *getBody() const {
1567 const FunctionDecl* Definition;
1568 return getBody(Definition);
1571 /// isThisDeclarationADefinition - Returns whether this specific
1572 /// declaration of the function is also a definition. This does not
1573 /// determine whether the function has been defined (e.g., in a
1574 /// previous definition); for that information, use isDefined. Note
1575 /// that this returns false for a defaulted function unless that function
1576 /// has been implicitly defined (possibly as deleted).
1577 bool isThisDeclarationADefinition() const {
1578 return IsDeleted || Body || IsLateTemplateParsed;
1581 /// doesThisDeclarationHaveABody - Returns whether this specific
1582 /// declaration of the function has a body - that is, if it is a non-
1583 /// deleted definition.
1584 bool doesThisDeclarationHaveABody() const {
1585 return Body || IsLateTemplateParsed;
1588 void setBody(Stmt *B);
1589 void setLazyBody(uint64_t Offset) { Body = Offset; }
1591 /// Whether this function is variadic.
1592 bool isVariadic() const;
1594 /// Whether this function is marked as virtual explicitly.
1595 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1596 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1598 /// Whether this virtual function is pure, i.e. makes the containing class
1600 bool isPure() const { return IsPure; }
1601 void setPure(bool P = true);
1603 /// Whether this is a constexpr function or constexpr constructor.
1604 // FIXME: C++0x: Implement tracking of the constexpr specifier.
1605 bool isConstExpr() const { return false; }
1607 /// Whether this templated function will be late parsed.
1608 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1609 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1611 /// Whether this function is "trivial" in some specialized C++ senses.
1612 /// Can only be true for default constructors, copy constructors,
1613 /// copy assignment operators, and destructors. Not meaningful until
1614 /// the class has been fully built by Sema.
1615 bool isTrivial() const { return IsTrivial; }
1616 void setTrivial(bool IT) { IsTrivial = IT; }
1618 /// Whether this function is defaulted per C++0x. Only valid for
1619 /// special member functions.
1620 bool isDefaulted() const { return IsDefaulted; }
1621 void setDefaulted(bool D = true) { IsDefaulted = D; }
1623 /// Whether this function is explicitly defaulted per C++0x. Only valid
1624 /// for special member functions.
1625 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1626 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1628 /// Whether falling off this function implicitly returns null/zero.
1629 /// If a more specific implicit return value is required, front-ends
1630 /// should synthesize the appropriate return statements.
1631 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1632 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1634 /// \brief Whether this function has a prototype, either because one
1635 /// was explicitly written or because it was "inherited" by merging
1636 /// a declaration without a prototype with a declaration that has a
1638 bool hasPrototype() const {
1639 return HasWrittenPrototype || HasInheritedPrototype;
1642 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1644 /// \brief Whether this function inherited its prototype from a
1645 /// previous declaration.
1646 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1647 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1649 /// \brief Whether this function has been deleted.
1651 /// A function that is "deleted" (via the C++0x "= delete" syntax)
1652 /// acts like a normal function, except that it cannot actually be
1653 /// called or have its address taken. Deleted functions are
1654 /// typically used in C++ overload resolution to attract arguments
1655 /// whose type or lvalue/rvalue-ness would permit the use of a
1656 /// different overload that would behave incorrectly. For example,
1657 /// one might use deleted functions to ban implicit conversion from
1658 /// a floating-point number to an Integer type:
1661 /// struct Integer {
1662 /// Integer(long); // construct from a long
1663 /// Integer(double) = delete; // no construction from float or double
1664 /// Integer(long double) = delete; // no construction from long double
1667 // If a function is deleted, its first declaration must be.
1668 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1669 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1670 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1672 /// \brief Determines whether this function is "main", which is the
1673 /// entry point into an executable program.
1674 bool isMain() const;
1676 /// \brief Determines whether this operator new or delete is one
1677 /// of the reserved global placement operators:
1678 /// void *operator new(size_t, void *);
1679 /// void *operator new[](size_t, void *);
1680 /// void operator delete(void *, void *);
1681 /// void operator delete[](void *, void *);
1682 /// These functions have special behavior under [new.delete.placement]:
1683 /// These functions are reserved, a C++ program may not define
1684 /// functions that displace the versions in the Standard C++ library.
1685 /// The provisions of [basic.stc.dynamic] do not apply to these
1686 /// reserved placement forms of operator new and operator delete.
1688 /// This function must be an allocation or deallocation function.
1689 bool isReservedGlobalPlacementOperator() const;
1691 /// \brief Determines whether this function is a function with
1692 /// external, C linkage.
1693 bool isExternC() const;
1695 /// \brief Determines whether this is a global function.
1696 bool isGlobal() const;
1698 void setPreviousDeclaration(FunctionDecl * PrevDecl);
1700 virtual const FunctionDecl *getCanonicalDecl() const;
1701 virtual FunctionDecl *getCanonicalDecl();
1703 unsigned getBuiltinID() const;
1705 // Iterator access to formal parameters.
1706 unsigned param_size() const { return getNumParams(); }
1707 typedef ParmVarDecl **param_iterator;
1708 typedef ParmVarDecl * const *param_const_iterator;
1710 param_iterator param_begin() { return ParamInfo; }
1711 param_iterator param_end() { return ParamInfo+param_size(); }
1713 param_const_iterator param_begin() const { return ParamInfo; }
1714 param_const_iterator param_end() const { return ParamInfo+param_size(); }
1716 /// getNumParams - Return the number of parameters this function must have
1717 /// based on its FunctionType. This is the length of the ParamInfo array
1718 /// after it has been created.
1719 unsigned getNumParams() const;
1721 const ParmVarDecl *getParamDecl(unsigned i) const {
1722 assert(i < getNumParams() && "Illegal param #");
1723 return ParamInfo[i];
1725 ParmVarDecl *getParamDecl(unsigned i) {
1726 assert(i < getNumParams() && "Illegal param #");
1727 return ParamInfo[i];
1729 void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams) {
1730 setParams(getASTContext(), NewParamInfo, NumParams);
1733 /// getMinRequiredArguments - Returns the minimum number of arguments
1734 /// needed to call this function. This may be fewer than the number of
1735 /// function parameters, if some of the parameters have default
1736 /// arguments (in C++).
1737 unsigned getMinRequiredArguments() const;
1739 QualType getResultType() const {
1740 return getType()->getAs<FunctionType>()->getResultType();
1743 /// \brief Determine the type of an expression that calls this function.
1744 QualType getCallResultType() const {
1745 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1748 StorageClass getStorageClass() const { return StorageClass(SClass); }
1749 void setStorageClass(StorageClass SC);
1751 StorageClass getStorageClassAsWritten() const {
1752 return StorageClass(SClassAsWritten);
1755 /// \brief Determine whether the "inline" keyword was specified for this
1757 bool isInlineSpecified() const { return IsInlineSpecified; }
1759 /// Set whether the "inline" keyword was specified for this function.
1760 void setInlineSpecified(bool I) {
1761 IsInlineSpecified = I;
1765 /// Flag that this function is implicitly inline.
1766 void setImplicitlyInline() {
1770 /// \brief Determine whether this function should be inlined, because it is
1771 /// either marked "inline" or is a member function of a C++ class that
1772 /// was defined in the class body.
1773 bool isInlined() const;
1775 bool isInlineDefinitionExternallyVisible() const;
1777 /// isOverloadedOperator - Whether this function declaration
1778 /// represents an C++ overloaded operator, e.g., "operator+".
1779 bool isOverloadedOperator() const {
1780 return getOverloadedOperator() != OO_None;
1783 OverloadedOperatorKind getOverloadedOperator() const;
1785 const IdentifierInfo *getLiteralIdentifier() const;
1787 /// \brief If this function is an instantiation of a member function
1788 /// of a class template specialization, retrieves the function from
1789 /// which it was instantiated.
1791 /// This routine will return non-NULL for (non-templated) member
1792 /// functions of class templates and for instantiations of function
1793 /// templates. For example, given:
1796 /// template<typename T>
1802 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1803 /// whose parent is the class template specialization X<int>. For
1804 /// this declaration, getInstantiatedFromFunction() will return
1805 /// the FunctionDecl X<T>::A. When a complete definition of
1806 /// X<int>::A is required, it will be instantiated from the
1807 /// declaration returned by getInstantiatedFromMemberFunction().
1808 FunctionDecl *getInstantiatedFromMemberFunction() const;
1810 /// \brief What kind of templated function this is.
1811 TemplatedKind getTemplatedKind() const;
1813 /// \brief If this function is an instantiation of a member function of a
1814 /// class template specialization, retrieves the member specialization
1816 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1818 /// \brief Specify that this record is an instantiation of the
1819 /// member function FD.
1820 void setInstantiationOfMemberFunction(FunctionDecl *FD,
1821 TemplateSpecializationKind TSK) {
1822 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1825 /// \brief Retrieves the function template that is described by this
1826 /// function declaration.
1828 /// Every function template is represented as a FunctionTemplateDecl
1829 /// and a FunctionDecl (or something derived from FunctionDecl). The
1830 /// former contains template properties (such as the template
1831 /// parameter lists) while the latter contains the actual
1832 /// description of the template's
1833 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1834 /// FunctionDecl that describes the function template,
1835 /// getDescribedFunctionTemplate() retrieves the
1836 /// FunctionTemplateDecl from a FunctionDecl.
1837 FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1838 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1841 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1842 TemplateOrSpecialization = Template;
1845 /// \brief Determine whether this function is a function template
1847 bool isFunctionTemplateSpecialization() const {
1848 return getPrimaryTemplate() != 0;
1851 /// \brief If this function is actually a function template specialization,
1852 /// retrieve information about this function template specialization.
1853 /// Otherwise, returns NULL.
1854 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1855 return TemplateOrSpecialization.
1856 dyn_cast<FunctionTemplateSpecializationInfo*>();
1859 /// \brief Determines whether this function is a function template
1860 /// specialization or a member of a class template specialization that can
1861 /// be implicitly instantiated.
1862 bool isImplicitlyInstantiable() const;
1864 /// \brief Retrieve the function declaration from which this function could
1865 /// be instantiated, if it is an instantiation (rather than a non-template
1866 /// or a specialization, for example).
1867 FunctionDecl *getTemplateInstantiationPattern() const;
1869 /// \brief Retrieve the primary template that this function template
1870 /// specialization either specializes or was instantiated from.
1872 /// If this function declaration is not a function template specialization,
1874 FunctionTemplateDecl *getPrimaryTemplate() const;
1876 /// \brief Retrieve the template arguments used to produce this function
1877 /// template specialization from the primary template.
1879 /// If this function declaration is not a function template specialization,
1881 const TemplateArgumentList *getTemplateSpecializationArgs() const;
1883 /// \brief Retrieve the template argument list as written in the sources,
1886 /// If this function declaration is not a function template specialization
1887 /// or if it had no explicit template argument list, returns NULL.
1888 /// Note that it an explicit template argument list may be written empty,
1889 /// e.g., template<> void foo<>(char* s);
1890 const TemplateArgumentListInfo*
1891 getTemplateSpecializationArgsAsWritten() const;
1893 /// \brief Specify that this function declaration is actually a function
1894 /// template specialization.
1896 /// \param Template the function template that this function template
1897 /// specialization specializes.
1899 /// \param TemplateArgs the template arguments that produced this
1900 /// function template specialization from the template.
1902 /// \param InsertPos If non-NULL, the position in the function template
1903 /// specialization set where the function template specialization data will
1906 /// \param TSK the kind of template specialization this is.
1908 /// \param TemplateArgsAsWritten location info of template arguments.
1910 /// \param PointOfInstantiation point at which the function template
1911 /// specialization was first instantiated.
1912 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1913 const TemplateArgumentList *TemplateArgs,
1915 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
1916 const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
1917 SourceLocation PointOfInstantiation = SourceLocation()) {
1918 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
1919 InsertPos, TSK, TemplateArgsAsWritten,
1920 PointOfInstantiation);
1923 /// \brief Specifies that this function declaration is actually a
1924 /// dependent function template specialization.
1925 void setDependentTemplateSpecialization(ASTContext &Context,
1926 const UnresolvedSetImpl &Templates,
1927 const TemplateArgumentListInfo &TemplateArgs);
1929 DependentFunctionTemplateSpecializationInfo *
1930 getDependentSpecializationInfo() const {
1931 return TemplateOrSpecialization.
1932 dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
1935 /// \brief Determine what kind of template instantiation this function
1937 TemplateSpecializationKind getTemplateSpecializationKind() const;
1939 /// \brief Determine what kind of template instantiation this function
1941 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1942 SourceLocation PointOfInstantiation = SourceLocation());
1944 /// \brief Retrieve the (first) point of instantiation of a function template
1945 /// specialization or a member of a class template specialization.
1947 /// \returns the first point of instantiation, if this function was
1948 /// instantiated from a template; otherwie, returns an invalid source
1950 SourceLocation getPointOfInstantiation() const;
1952 /// \brief Determine whether this is or was instantiated from an out-of-line
1953 /// definition of a member function.
1954 virtual bool isOutOfLine() const;
1956 // Implement isa/cast/dyncast/etc.
1957 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1958 static bool classof(const FunctionDecl *D) { return true; }
1959 static bool classofKind(Kind K) {
1960 return K >= firstFunction && K <= lastFunction;
1962 static DeclContext *castToDeclContext(const FunctionDecl *D) {
1963 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
1965 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
1966 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
1969 friend class ASTDeclReader;
1970 friend class ASTDeclWriter;
1974 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
1975 /// represent a member of a struct/union/class.
1976 class FieldDecl : public DeclaratorDecl {
1977 // FIXME: This can be packed into the bitfields in Decl.
1979 mutable unsigned CachedFieldIndex : 31;
1981 /// \brief A pointer to either the in-class initializer for this field (if
1982 /// the boolean value is false), or the bit width expression for this bit
1983 /// field (if the boolean value is true).
1985 /// We can safely combine these two because in-class initializers are not
1986 /// permitted for bit-fields.
1988 /// If the boolean is false and the initializer is null, then this field has
1989 /// an in-class initializer which has not yet been parsed and attached.
1990 llvm::PointerIntPair<Expr *, 1, bool> InitializerOrBitWidth;
1992 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1993 SourceLocation IdLoc, IdentifierInfo *Id,
1994 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
1996 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1997 Mutable(Mutable), CachedFieldIndex(0),
1998 InitializerOrBitWidth(BW, !HasInit) {
1999 assert(!(BW && HasInit) && "got initializer for bitfield");
2003 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2004 SourceLocation StartLoc, SourceLocation IdLoc,
2005 IdentifierInfo *Id, QualType T,
2006 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2009 /// getFieldIndex - Returns the index of this field within its record,
2010 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2011 unsigned getFieldIndex() const;
2013 /// isMutable - Determines whether this field is mutable (C++ only).
2014 bool isMutable() const { return Mutable; }
2016 /// \brief Set whether this field is mutable (C++ only).
2017 void setMutable(bool M) { Mutable = M; }
2019 /// isBitfield - Determines whether this field is a bitfield.
2020 bool isBitField() const {
2021 return InitializerOrBitWidth.getInt() && InitializerOrBitWidth.getPointer();
2024 /// @brief Determines whether this is an unnamed bitfield.
2025 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2027 /// isAnonymousStructOrUnion - Determines whether this field is a
2028 /// representative for an anonymous struct or union. Such fields are
2029 /// unnamed and are implicitly generated by the implementation to
2030 /// store the data for the anonymous union or struct.
2031 bool isAnonymousStructOrUnion() const;
2033 Expr *getBitWidth() const {
2034 return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2036 void setBitWidth(Expr *BW) {
2037 assert(!InitializerOrBitWidth.getPointer() &&
2038 "bit width or initializer already set");
2039 InitializerOrBitWidth.setPointer(BW);
2040 InitializerOrBitWidth.setInt(1);
2042 /// removeBitWidth - Remove the bitfield width from this member.
2043 void removeBitWidth() {
2044 assert(isBitField() && "no bit width to remove");
2045 InitializerOrBitWidth.setPointer(0);
2048 /// hasInClassInitializer - Determine whether this member has a C++0x in-class
2050 bool hasInClassInitializer() const {
2051 return !InitializerOrBitWidth.getInt();
2053 /// getInClassInitializer - Get the C++0x in-class initializer for this
2054 /// member, or null if one has not been set. If a valid declaration has an
2055 /// in-class initializer, but this returns null, then we have not parsed and
2056 /// attached it yet.
2057 Expr *getInClassInitializer() const {
2058 return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2060 /// setInClassInitializer - Set the C++0x in-class initializer for this member.
2061 void setInClassInitializer(Expr *Init);
2062 /// removeInClassInitializer - Remove the C++0x in-class initializer from this
2064 void removeInClassInitializer() {
2065 assert(!InitializerOrBitWidth.getInt() && "no initializer to remove");
2066 InitializerOrBitWidth.setPointer(0);
2067 InitializerOrBitWidth.setInt(1);
2070 /// getParent - Returns the parent of this field declaration, which
2071 /// is the struct in which this method is defined.
2072 const RecordDecl *getParent() const {
2073 return cast<RecordDecl>(getDeclContext());
2076 RecordDecl *getParent() {
2077 return cast<RecordDecl>(getDeclContext());
2080 SourceRange getSourceRange() const;
2082 // Implement isa/cast/dyncast/etc.
2083 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2084 static bool classof(const FieldDecl *D) { return true; }
2085 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2088 /// EnumConstantDecl - An instance of this object exists for each enum constant
2089 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2090 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2091 /// TagType for the X EnumDecl.
2092 class EnumConstantDecl : public ValueDecl {
2093 Stmt *Init; // an integer constant expression
2094 llvm::APSInt Val; // The value.
2096 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2097 IdentifierInfo *Id, QualType T, Expr *E,
2098 const llvm::APSInt &V)
2099 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2103 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2104 SourceLocation L, IdentifierInfo *Id,
2105 QualType T, Expr *E,
2106 const llvm::APSInt &V);
2108 const Expr *getInitExpr() const { return (const Expr*) Init; }
2109 Expr *getInitExpr() { return (Expr*) Init; }
2110 const llvm::APSInt &getInitVal() const { return Val; }
2112 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2113 void setInitVal(const llvm::APSInt &V) { Val = V; }
2115 SourceRange getSourceRange() const;
2117 // Implement isa/cast/dyncast/etc.
2118 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2119 static bool classof(const EnumConstantDecl *D) { return true; }
2120 static bool classofKind(Kind K) { return K == EnumConstant; }
2122 friend class StmtIteratorBase;
2125 /// IndirectFieldDecl - An instance of this class is created to represent a
2126 /// field injected from an anonymous union/struct into the parent scope.
2127 /// IndirectFieldDecl are always implicit.
2128 class IndirectFieldDecl : public ValueDecl {
2129 NamedDecl **Chaining;
2130 unsigned ChainingSize;
2132 IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2133 DeclarationName N, QualType T,
2134 NamedDecl **CH, unsigned CHS)
2135 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2138 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2139 SourceLocation L, IdentifierInfo *Id,
2140 QualType T, NamedDecl **CH, unsigned CHS);
2142 typedef NamedDecl * const *chain_iterator;
2143 chain_iterator chain_begin() const { return Chaining; }
2144 chain_iterator chain_end() const { return Chaining+ChainingSize; }
2146 unsigned getChainingSize() const { return ChainingSize; }
2148 FieldDecl *getAnonField() const {
2149 assert(ChainingSize >= 2);
2150 return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2153 VarDecl *getVarDecl() const {
2154 assert(ChainingSize >= 2);
2155 return dyn_cast<VarDecl>(*chain_begin());
2158 // Implement isa/cast/dyncast/etc.
2159 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2160 static bool classof(const IndirectFieldDecl *D) { return true; }
2161 static bool classofKind(Kind K) { return K == IndirectField; }
2162 friend class ASTDeclReader;
2165 /// TypeDecl - Represents a declaration of a type.
2167 class TypeDecl : public NamedDecl {
2168 /// TypeForDecl - This indicates the Type object that represents
2169 /// this TypeDecl. It is a cache maintained by
2170 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2171 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2172 mutable const Type *TypeForDecl;
2173 /// LocStart - The start of the source range for this declaration.
2174 SourceLocation LocStart;
2175 friend class ASTContext;
2176 friend class DeclContext;
2177 friend class TagDecl;
2178 friend class TemplateTypeParmDecl;
2179 friend class TagType;
2182 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2183 SourceLocation StartL = SourceLocation())
2184 : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2187 // Low-level accessor
2188 const Type *getTypeForDecl() const { return TypeForDecl; }
2189 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2191 SourceLocation getLocStart() const { return LocStart; }
2192 void setLocStart(SourceLocation L) { LocStart = L; }
2193 virtual SourceRange getSourceRange() const {
2194 if (LocStart.isValid())
2195 return SourceRange(LocStart, getLocation());
2197 return SourceRange(getLocation());
2200 // Implement isa/cast/dyncast/etc.
2201 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2202 static bool classof(const TypeDecl *D) { return true; }
2203 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2207 /// Base class for declarations which introduce a typedef-name.
2208 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2209 /// UnderlyingType - This is the type the typedef is set to.
2210 TypeSourceInfo *TInfo;
2213 TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2214 SourceLocation IdLoc, IdentifierInfo *Id,
2215 TypeSourceInfo *TInfo)
2216 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
2218 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2219 virtual TypedefNameDecl *getNextRedeclaration() {
2220 return RedeclLink.getNext();
2224 typedef redeclarable_base::redecl_iterator redecl_iterator;
2225 redecl_iterator redecls_begin() const {
2226 return redeclarable_base::redecls_begin();
2228 redecl_iterator redecls_end() const {
2229 return redeclarable_base::redecls_end();
2232 TypeSourceInfo *getTypeSourceInfo() const {
2236 /// Retrieves the canonical declaration of this typedef-name.
2237 TypedefNameDecl *getCanonicalDecl() {
2238 return getFirstDeclaration();
2240 const TypedefNameDecl *getCanonicalDecl() const {
2241 return getFirstDeclaration();
2244 QualType getUnderlyingType() const {
2245 return TInfo->getType();
2247 void setTypeSourceInfo(TypeSourceInfo *newType) {
2251 // Implement isa/cast/dyncast/etc.
2252 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2253 static bool classof(const TypedefNameDecl *D) { return true; }
2254 static bool classofKind(Kind K) {
2255 return K >= firstTypedefName && K <= lastTypedefName;
2259 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2261 class TypedefDecl : public TypedefNameDecl {
2262 TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2263 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2264 : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2267 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2268 SourceLocation StartLoc, SourceLocation IdLoc,
2269 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2271 SourceRange getSourceRange() const;
2273 // Implement isa/cast/dyncast/etc.
2274 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2275 static bool classof(const TypedefDecl *D) { return true; }
2276 static bool classofKind(Kind K) { return K == Typedef; }
2279 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2280 /// alias-declaration.
2281 class TypeAliasDecl : public TypedefNameDecl {
2282 TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2283 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2284 : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2287 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2288 SourceLocation StartLoc, SourceLocation IdLoc,
2289 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2291 SourceRange getSourceRange() const;
2293 // Implement isa/cast/dyncast/etc.
2294 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2295 static bool classof(const TypeAliasDecl *D) { return true; }
2296 static bool classofKind(Kind K) { return K == TypeAlias; }
2299 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2301 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2303 // This is really ugly.
2304 typedef TagTypeKind TagKind;
2307 // FIXME: This can be packed into the bitfields in Decl.
2308 /// TagDeclKind - The TagKind enum.
2309 unsigned TagDeclKind : 2;
2311 /// IsDefinition - True if this is a definition ("struct foo {};"), false if
2312 /// it is a declaration ("struct foo;").
2313 bool IsDefinition : 1;
2315 /// IsBeingDefined - True if this is currently being defined.
2316 bool IsBeingDefined : 1;
2318 /// IsEmbeddedInDeclarator - True if this tag declaration is
2319 /// "embedded" (i.e., defined or declared for the very first time)
2320 /// in the syntax of a declarator.
2321 bool IsEmbeddedInDeclarator : 1;
2324 // These are used by (and only defined for) EnumDecl.
2325 unsigned NumPositiveBits : 8;
2326 unsigned NumNegativeBits : 8;
2328 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2329 /// possible in C++0x mode.
2331 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2332 /// then this is true if the scoped enum was declared using the class
2333 /// tag, false if it was declared with the struct tag. No meaning is
2334 /// associated if this tag declaration is not a scoped enum.
2335 bool IsScopedUsingClassTag : 1;
2337 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2338 /// possible in C++0x mode.
2342 SourceLocation RBraceLoc;
2344 // A struct representing syntactic qualifier info,
2345 // to be used for the (uncommon) case of out-of-line declarations.
2346 typedef QualifierInfo ExtInfo;
2348 /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
2349 /// is qualified, it points to the qualifier info (nns and range);
2350 /// otherwise, if the tag declaration is anonymous and it is part of
2351 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2352 /// otherwise, it is a null (TypedefNameDecl) pointer.
2353 llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
2355 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
2356 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
2357 const ExtInfo *getExtInfo() const {
2358 return TypedefNameDeclOrQualifier.get<ExtInfo*>();
2362 TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2363 SourceLocation L, IdentifierInfo *Id,
2364 TagDecl *PrevDecl, SourceLocation StartL)
2365 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
2366 TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
2367 assert((DK != Enum || TK == TTK_Enum) &&
2368 "EnumDecl not matched with TTK_Enum");
2370 IsDefinition = false;
2371 IsBeingDefined = false;
2372 IsEmbeddedInDeclarator = false;
2373 setPreviousDeclaration(PrevDecl);
2376 typedef Redeclarable<TagDecl> redeclarable_base;
2377 virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2379 /// @brief Completes the definition of this tag declaration.
2381 /// This is a helper function for derived classes.
2382 void completeDefinition();
2385 typedef redeclarable_base::redecl_iterator redecl_iterator;
2386 redecl_iterator redecls_begin() const {
2387 return redeclarable_base::redecls_begin();
2389 redecl_iterator redecls_end() const {
2390 return redeclarable_base::redecls_end();
2393 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2394 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2396 /// getInnerLocStart - Return SourceLocation representing start of source
2397 /// range ignoring outer template declarations.
2398 SourceLocation getInnerLocStart() const { return getLocStart(); }
2400 /// getOuterLocStart - Return SourceLocation representing start of source
2401 /// range taking into account any outer template declarations.
2402 SourceLocation getOuterLocStart() const;
2403 virtual SourceRange getSourceRange() const;
2405 virtual TagDecl* getCanonicalDecl();
2406 const TagDecl* getCanonicalDecl() const {
2407 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2410 /// isThisDeclarationADefinition() - Return true if this declaration
2411 /// defines the type. Provided for consistency.
2412 bool isThisDeclarationADefinition() const {
2413 return isDefinition();
2416 /// isDefinition - Return true if this decl has its body specified.
2417 bool isDefinition() const {
2418 return IsDefinition;
2421 /// isBeingDefined - Return true if this decl is currently being defined.
2422 bool isBeingDefined() const {
2423 return IsBeingDefined;
2426 bool isEmbeddedInDeclarator() const {
2427 return IsEmbeddedInDeclarator;
2429 void setEmbeddedInDeclarator(bool isInDeclarator) {
2430 IsEmbeddedInDeclarator = isInDeclarator;
2433 /// \brief Whether this declaration declares a type that is
2434 /// dependent, i.e., a type that somehow depends on template
2436 bool isDependentType() const { return isDependentContext(); }
2438 /// @brief Starts the definition of this tag declaration.
2440 /// This method should be invoked at the beginning of the definition
2441 /// of this tag declaration. It will set the tag type into a state
2442 /// where it is in the process of being defined.
2443 void startDefinition();
2445 /// getDefinition - Returns the TagDecl that actually defines this
2446 /// struct/union/class/enum. When determining whether or not a
2447 /// struct/union/class/enum is completely defined, one should use this method
2448 /// as opposed to 'isDefinition'. 'isDefinition' indicates whether or not a
2449 /// specific TagDecl is defining declaration, not whether or not the
2450 /// struct/union/class/enum type is defined. This method returns NULL if
2451 /// there is no TagDecl that defines the struct/union/class/enum.
2452 TagDecl* getDefinition() const;
2454 void setDefinition(bool V) { IsDefinition = V; }
2456 const char *getKindName() const {
2457 return TypeWithKeyword::getTagTypeKindName(getTagKind());
2460 TagKind getTagKind() const {
2461 return TagKind(TagDeclKind);
2464 void setTagKind(TagKind TK) { TagDeclKind = TK; }
2466 bool isStruct() const { return getTagKind() == TTK_Struct; }
2467 bool isClass() const { return getTagKind() == TTK_Class; }
2468 bool isUnion() const { return getTagKind() == TTK_Union; }
2469 bool isEnum() const { return getTagKind() == TTK_Enum; }
2471 TypedefNameDecl *getTypedefNameForAnonDecl() const {
2472 return hasExtInfo() ? 0 : TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
2475 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2477 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2478 /// declaration, if it was present in the source.
2479 NestedNameSpecifier *getQualifier() const {
2480 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2484 /// \brief Retrieve the nested-name-specifier (with source-location
2485 /// information) that qualifies the name of this declaration, if it was
2486 /// present in the source.
2487 NestedNameSpecifierLoc getQualifierLoc() const {
2488 return hasExtInfo() ? getExtInfo()->QualifierLoc
2489 : NestedNameSpecifierLoc();
2492 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2494 unsigned getNumTemplateParameterLists() const {
2495 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2497 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2498 assert(i < getNumTemplateParameterLists());
2499 return getExtInfo()->TemplParamLists[i];
2501 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2502 TemplateParameterList **TPLists);
2504 // Implement isa/cast/dyncast/etc.
2505 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2506 static bool classof(const TagDecl *D) { return true; }
2507 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2509 static DeclContext *castToDeclContext(const TagDecl *D) {
2510 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2512 static TagDecl *castFromDeclContext(const DeclContext *DC) {
2513 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2516 friend class ASTDeclReader;
2517 friend class ASTDeclWriter;
2520 /// EnumDecl - Represents an enum. As an extension, we allow forward-declared
2522 class EnumDecl : public TagDecl {
2523 /// IntegerType - This represent the integer type that the enum corresponds
2524 /// to for code generation purposes. Note that the enumerator constants may
2525 /// have a different type than this does.
2527 /// If the underlying integer type was explicitly stated in the source
2528 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2529 /// was automatically deduced somehow, and this is a Type*.
2531 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2532 /// some cases it won't.
2534 /// The underlying type of an enumeration never has any qualifiers, so
2535 /// we can get away with just storing a raw Type*, and thus save an
2536 /// extra pointer when TypeSourceInfo is needed.
2538 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2540 /// PromotionType - The integer type that values of this type should
2541 /// promote to. In C, enumerators are generally of an integer type
2542 /// directly, but gcc-style large enumerators (and all enumerators
2543 /// in C++) are of the enum type instead.
2544 QualType PromotionType;
2546 /// \brief If the enumeration was instantiated from an enumeration
2547 /// within a class or function template, this pointer refers to the
2548 /// enumeration declared within the template.
2549 EnumDecl *InstantiatedFrom;
2551 // The number of positive and negative bits required by the
2552 // enumerators are stored in the SubclassBits field.
2555 NumBitsMask = (1 << NumBitsWidth) - 1
2558 EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2559 IdentifierInfo *Id, EnumDecl *PrevDecl,
2560 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2561 : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2562 InstantiatedFrom(0) {
2563 assert(Scoped || !ScopedUsingClassTag);
2564 IntegerType = (const Type*)0;
2565 NumNegativeBits = 0;
2566 NumPositiveBits = 0;
2568 IsScopedUsingClassTag = ScopedUsingClassTag;
2572 EnumDecl *getCanonicalDecl() {
2573 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2575 const EnumDecl *getCanonicalDecl() const {
2576 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2579 const EnumDecl *getPreviousDeclaration() const {
2580 return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
2582 EnumDecl *getPreviousDeclaration() {
2583 return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
2586 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2587 SourceLocation StartLoc, SourceLocation IdLoc,
2588 IdentifierInfo *Id, EnumDecl *PrevDecl,
2589 bool IsScoped, bool IsScopedUsingClassTag,
2591 static EnumDecl *Create(ASTContext &C, EmptyShell Empty);
2593 /// completeDefinition - When created, the EnumDecl corresponds to a
2594 /// forward-declared enum. This method is used to mark the
2595 /// declaration as being defined; it's enumerators have already been
2596 /// added (via DeclContext::addDecl). NewType is the new underlying
2597 /// type of the enumeration type.
2598 void completeDefinition(QualType NewType,
2599 QualType PromotionType,
2600 unsigned NumPositiveBits,
2601 unsigned NumNegativeBits);
2603 // enumerator_iterator - Iterates through the enumerators of this
2605 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2607 enumerator_iterator enumerator_begin() const {
2608 const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
2611 return enumerator_iterator(E->decls_begin());
2614 enumerator_iterator enumerator_end() const {
2615 const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
2618 return enumerator_iterator(E->decls_end());
2621 /// getPromotionType - Return the integer type that enumerators
2622 /// should promote to.
2623 QualType getPromotionType() const { return PromotionType; }
2625 /// \brief Set the promotion type.
2626 void setPromotionType(QualType T) { PromotionType = T; }
2628 /// getIntegerType - Return the integer type this enum decl corresponds to.
2629 /// This returns a null qualtype for an enum forward definition.
2630 QualType getIntegerType() const {
2633 if (const Type* T = IntegerType.dyn_cast<const Type*>())
2634 return QualType(T, 0);
2635 return IntegerType.get<TypeSourceInfo*>()->getType();
2638 /// \brief Set the underlying integer type.
2639 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2641 /// \brief Set the underlying integer type source info.
2642 void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2644 /// \brief Return the type source info for the underlying integer type,
2645 /// if no type source info exists, return 0.
2646 TypeSourceInfo* getIntegerTypeSourceInfo() const {
2647 return IntegerType.dyn_cast<TypeSourceInfo*>();
2650 /// \brief Returns the width in bits required to store all the
2651 /// non-negative enumerators of this enum.
2652 unsigned getNumPositiveBits() const {
2653 return NumPositiveBits;
2655 void setNumPositiveBits(unsigned Num) {
2656 NumPositiveBits = Num;
2657 assert(NumPositiveBits == Num && "can't store this bitcount");
2660 /// \brief Returns the width in bits required to store all the
2661 /// negative enumerators of this enum. These widths include
2662 /// the rightmost leading 1; that is:
2664 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
2665 /// ------------------------ ------- -----------------
2669 unsigned getNumNegativeBits() const {
2670 return NumNegativeBits;
2672 void setNumNegativeBits(unsigned Num) {
2673 NumNegativeBits = Num;
2676 /// \brief Returns true if this is a C++0x scoped enumeration.
2677 bool isScoped() const {
2681 /// \brief Returns true if this is a C++0x scoped enumeration.
2682 bool isScopedUsingClassTag() const {
2683 return IsScopedUsingClassTag;
2686 /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2688 bool isFixed() const {
2692 /// \brief Returns true if this can be considered a complete type.
2693 bool isComplete() const {
2694 return isDefinition() || isFixed();
2697 /// \brief Returns the enumeration (declared within the template)
2698 /// from which this enumeration type was instantiated, or NULL if
2699 /// this enumeration was not instantiated from any template.
2700 EnumDecl *getInstantiatedFromMemberEnum() const {
2701 return InstantiatedFrom;
2704 void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; }
2706 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2707 static bool classof(const EnumDecl *D) { return true; }
2708 static bool classofKind(Kind K) { return K == Enum; }
2710 friend class ASTDeclReader;
2714 /// RecordDecl - Represents a struct/union/class. For example:
2715 /// struct X; // Forward declaration, no "body".
2716 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
2717 /// This decl will be marked invalid if *any* members are invalid.
2719 class RecordDecl : public TagDecl {
2720 // FIXME: This can be packed into the bitfields in Decl.
2721 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2722 /// array member (e.g. int X[]) or if this union contains a struct that does.
2723 /// If so, this cannot be contained in arrays or other structs as a member.
2724 bool HasFlexibleArrayMember : 1;
2726 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2728 bool AnonymousStructOrUnion : 1;
2730 /// HasObjectMember - This is true if this struct has at least one member
2731 /// containing an object.
2732 bool HasObjectMember : 1;
2734 /// \brief Whether the field declarations of this record have been loaded
2735 /// from external storage. To avoid unnecessary deserialization of
2736 /// methods/nested types we allow deserialization of just the fields
2738 mutable bool LoadedFieldsFromExternalStorage : 1;
2739 friend class DeclContext;
2742 RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2743 SourceLocation StartLoc, SourceLocation IdLoc,
2744 IdentifierInfo *Id, RecordDecl *PrevDecl);
2747 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2748 SourceLocation StartLoc, SourceLocation IdLoc,
2749 IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
2750 static RecordDecl *Create(const ASTContext &C, EmptyShell Empty);
2752 const RecordDecl *getPreviousDeclaration() const {
2753 return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
2755 RecordDecl *getPreviousDeclaration() {
2756 return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
2759 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
2760 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2762 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2763 /// or union. To be an anonymous struct or union, it must have been
2764 /// declared without a name and there must be no objects of this
2765 /// type declared, e.g.,
2767 /// union { int i; float f; };
2769 /// is an anonymous union but neither of the following are:
2771 /// union X { int i; float f; };
2772 /// union { int i; float f; } obj;
2774 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
2775 void setAnonymousStructOrUnion(bool Anon) {
2776 AnonymousStructOrUnion = Anon;
2779 bool hasObjectMember() const { return HasObjectMember; }
2780 void setHasObjectMember (bool val) { HasObjectMember = val; }
2782 /// \brief Determines whether this declaration represents the
2783 /// injected class name.
2785 /// The injected class name in C++ is the name of the class that
2786 /// appears inside the class itself. For example:
2790 /// // C is implicitly declared here as a synonym for the class name.
2793 /// C::C c; // same as "C c;"
2795 bool isInjectedClassName() const;
2797 /// getDefinition - Returns the RecordDecl that actually defines this
2798 /// struct/union/class. When determining whether or not a struct/union/class
2799 /// is completely defined, one should use this method as opposed to
2800 /// 'isDefinition'. 'isDefinition' indicates whether or not a specific
2801 /// RecordDecl is defining declaration, not whether or not the record
2802 /// type is defined. This method returns NULL if there is no RecordDecl
2803 /// that defines the struct/union/tag.
2804 RecordDecl* getDefinition() const {
2805 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2808 // Iterator access to field members. The field iterator only visits
2809 // the non-static data members of this class, ignoring any static
2810 // data members, functions, constructors, destructors, etc.
2811 typedef specific_decl_iterator<FieldDecl> field_iterator;
2813 field_iterator field_begin() const;
2815 field_iterator field_end() const {
2816 return field_iterator(decl_iterator());
2819 // field_empty - Whether there are any fields (non-static data
2820 // members) in this record.
2821 bool field_empty() const {
2822 return field_begin() == field_end();
2825 /// completeDefinition - Notes that the definition of this type is
2827 virtual void completeDefinition();
2829 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2830 static bool classof(const RecordDecl *D) { return true; }
2831 static bool classofKind(Kind K) {
2832 return K >= firstRecord && K <= lastRecord;
2836 /// \brief Deserialize just the fields.
2837 void LoadFieldsFromExternalStorage() const;
2840 class FileScopeAsmDecl : public Decl {
2841 StringLiteral *AsmString;
2842 SourceLocation RParenLoc;
2843 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
2844 SourceLocation StartL, SourceLocation EndL)
2845 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
2847 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
2848 StringLiteral *Str, SourceLocation AsmLoc,
2849 SourceLocation RParenLoc);
2851 SourceLocation getAsmLoc() const { return getLocation(); }
2852 SourceLocation getRParenLoc() const { return RParenLoc; }
2853 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2854 SourceRange getSourceRange() const {
2855 return SourceRange(getAsmLoc(), getRParenLoc());
2858 const StringLiteral *getAsmString() const { return AsmString; }
2859 StringLiteral *getAsmString() { return AsmString; }
2860 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
2862 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2863 static bool classof(const FileScopeAsmDecl *D) { return true; }
2864 static bool classofKind(Kind K) { return K == FileScopeAsm; }
2867 /// BlockDecl - This represents a block literal declaration, which is like an
2868 /// unnamed FunctionDecl. For example:
2869 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
2871 class BlockDecl : public Decl, public DeclContext {
2873 /// A class which contains all the information about a particular
2881 /// The variable being captured.
2882 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
2884 /// The copy expression, expressed in terms of a DeclRef (or
2885 /// BlockDeclRef) to the captured variable. Only required if the
2886 /// variable has a C++ class type.
2890 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
2891 : VariableAndFlags(variable,
2892 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
2895 /// The variable being captured.
2896 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
2898 /// Whether this is a "by ref" capture, i.e. a capture of a __block
2900 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
2902 /// Whether this is a nested capture, i.e. the variable captured
2903 /// is not from outside the immediately enclosing function/block.
2904 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
2906 bool hasCopyExpr() const { return CopyExpr != 0; }
2907 Expr *getCopyExpr() const { return CopyExpr; }
2908 void setCopyExpr(Expr *e) { CopyExpr = e; }
2912 // FIXME: This can be packed into the bitfields in Decl.
2913 bool IsVariadic : 1;
2914 bool CapturesCXXThis : 1;
2915 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
2916 /// parameters of this function. This is null if a prototype or if there are
2918 ParmVarDecl **ParamInfo;
2922 TypeSourceInfo *SignatureAsWritten;
2925 unsigned NumCaptures;
2928 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
2929 : Decl(Block, DC, CaretLoc), DeclContext(Block),
2930 IsVariadic(false), CapturesCXXThis(false),
2931 ParamInfo(0), NumParams(0), Body(0),
2932 SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
2935 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
2937 SourceLocation getCaretLocation() const { return getLocation(); }
2939 bool isVariadic() const { return IsVariadic; }
2940 void setIsVariadic(bool value) { IsVariadic = value; }
2942 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
2943 Stmt *getBody() const { return (Stmt*) Body; }
2944 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
2946 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
2947 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
2949 // Iterator access to formal parameters.
2950 unsigned param_size() const { return getNumParams(); }
2951 typedef ParmVarDecl **param_iterator;
2952 typedef ParmVarDecl * const *param_const_iterator;
2954 bool param_empty() const { return NumParams == 0; }
2955 param_iterator param_begin() { return ParamInfo; }
2956 param_iterator param_end() { return ParamInfo+param_size(); }
2958 param_const_iterator param_begin() const { return ParamInfo; }
2959 param_const_iterator param_end() const { return ParamInfo+param_size(); }
2961 unsigned getNumParams() const { return NumParams; }
2962 const ParmVarDecl *getParamDecl(unsigned i) const {
2963 assert(i < getNumParams() && "Illegal param #");
2964 return ParamInfo[i];
2966 ParmVarDecl *getParamDecl(unsigned i) {
2967 assert(i < getNumParams() && "Illegal param #");
2968 return ParamInfo[i];
2970 void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams);
2972 /// hasCaptures - True if this block (or its nested blocks) captures
2973 /// anything of local storage from its enclosing scopes.
2974 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
2976 /// getNumCaptures - Returns the number of captured variables.
2977 /// Does not include an entry for 'this'.
2978 unsigned getNumCaptures() const { return NumCaptures; }
2980 typedef const Capture *capture_iterator;
2981 typedef const Capture *capture_const_iterator;
2982 capture_iterator capture_begin() { return Captures; }
2983 capture_iterator capture_end() { return Captures + NumCaptures; }
2984 capture_const_iterator capture_begin() const { return Captures; }
2985 capture_const_iterator capture_end() const { return Captures + NumCaptures; }
2987 bool capturesCXXThis() const { return CapturesCXXThis; }
2989 bool capturesVariable(const VarDecl *var) const;
2991 void setCaptures(ASTContext &Context,
2992 const Capture *begin,
2994 bool capturesCXXThis);
2996 virtual SourceRange getSourceRange() const;
2998 // Implement isa/cast/dyncast/etc.
2999 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3000 static bool classof(const BlockDecl *D) { return true; }
3001 static bool classofKind(Kind K) { return K == Block; }
3002 static DeclContext *castToDeclContext(const BlockDecl *D) {
3003 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3005 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3006 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3010 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3011 /// into a diagnostic with <<.
3012 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3014 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), Diagnostic::ak_nameddecl);
3018 template<typename decl_type>
3019 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3020 // Note: This routine is implemented here because we need both NamedDecl
3021 // and Redeclarable to be defined.
3026 // Point to previous. Make sure that this is actually the most recent
3027 // redeclaration, or we can build invalid chains. If the most recent
3028 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3029 RedeclLink = PreviousDeclLink(llvm::cast<decl_type>(
3030 PrevDecl->getMostRecentDeclaration()));
3031 First = PrevDecl->getFirstDeclaration();
3032 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3035 First = static_cast<decl_type*>(this);
3038 // First one will point to this one as latest.
3039 First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3040 if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
3041 ND->ClearLinkageCache();
3044 } // end namespace clang