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/ArrayRef.h"
24 #include "llvm/ADT/Optional.h"
29 class FunctionTemplateDecl;
33 class NestedNameSpecifier;
34 class TemplateParameterList;
35 class TemplateArgumentList;
36 struct ASTTemplateArgumentListInfo;
37 class MemberSpecializationInfo;
38 class FunctionTemplateSpecializationInfo;
39 class DependentFunctionTemplateSpecializationInfo;
41 class UnresolvedSetImpl;
44 /// \brief A container of type source information.
46 /// A client can read the relevant info using TypeLoc wrappers, e.g:
48 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
49 /// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
50 /// PL->getStarLoc().print(OS, SrcMgr);
53 class TypeSourceInfo {
55 // Contains a memory block after the class, used for type source information,
56 // allocated by ASTContext.
57 friend class ASTContext;
58 TypeSourceInfo(QualType ty) : Ty(ty) { }
60 /// \brief Return the type wrapped by this type source info.
61 QualType getType() const { return Ty; }
63 /// \brief Return the TypeLoc wrapper for the type source info.
64 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
67 /// TranslationUnitDecl - The top declaration context.
68 class TranslationUnitDecl : public Decl, public DeclContext {
71 /// The (most recently entered) anonymous namespace for this
72 /// translation unit, if one has been created.
73 NamespaceDecl *AnonymousNamespace;
75 explicit TranslationUnitDecl(ASTContext &ctx)
76 : Decl(TranslationUnit, 0, SourceLocation()),
77 DeclContext(TranslationUnit),
78 Ctx(ctx), AnonymousNamespace(0) {}
80 ASTContext &getASTContext() const { return Ctx; }
82 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
83 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
85 static TranslationUnitDecl *Create(ASTContext &C);
86 // Implement isa/cast/dyncast/etc.
87 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
88 static bool classof(const TranslationUnitDecl *D) { return true; }
89 static bool classofKind(Kind K) { return K == TranslationUnit; }
90 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
91 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
93 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
94 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
98 /// NamedDecl - This represents a decl with a name. Many decls have names such
99 /// as ObjCMethodDecl, but not @class, etc.
100 class NamedDecl : public Decl {
101 /// Name - The name of this declaration, which is typically a normal
102 /// identifier but may also be a special kind of name (C++
103 /// constructor, Objective-C selector, etc.)
104 DeclarationName Name;
107 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
108 : Decl(DK, DC, L), Name(N) { }
111 /// getIdentifier - Get the identifier that names this declaration,
112 /// if there is one. This will return NULL if this declaration has
113 /// no name (e.g., for an unnamed class) or if the name is a special
114 /// name (C++ constructor, Objective-C selector, etc.).
115 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
117 /// getName - Get the name of identifier for this declaration as a StringRef.
118 /// This requires that the declaration have a name and that it be a simple
120 StringRef getName() const {
121 assert(Name.isIdentifier() && "Name is not a simple identifier");
122 return getIdentifier() ? getIdentifier()->getName() : "";
125 /// getNameAsString - Get a human-readable name for the declaration, even if
126 /// it is one of the special kinds of names (C++ constructor, Objective-C
127 /// selector, etc). Creating this name requires expensive string
128 /// manipulation, so it should be called only when performance doesn't matter.
129 /// For simple declarations, getNameAsCString() should suffice.
131 // FIXME: This function should be renamed to indicate that it is not just an
132 // alternate form of getName(), and clients should move as appropriate.
134 // FIXME: Deprecated, move clients to getName().
135 std::string getNameAsString() const { return Name.getAsString(); }
137 void printName(raw_ostream &os) const { return Name.printName(os); }
139 /// getDeclName - Get the actual, stored name of the declaration,
140 /// which may be a special name.
141 DeclarationName getDeclName() const { return Name; }
143 /// \brief Set the name of this declaration.
144 void setDeclName(DeclarationName N) { Name = N; }
146 /// getQualifiedNameAsString - Returns human-readable qualified name for
147 /// declaration, like A::B::i, for i being member of namespace A::B.
148 /// If declaration is not member of context which can be named (record,
149 /// namespace), it will return same result as getNameAsString().
150 /// Creating this name is expensive, so it should be called only when
151 /// performance doesn't matter.
152 std::string getQualifiedNameAsString() const;
153 std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
155 /// getNameForDiagnostic - Appends a human-readable name for this
156 /// declaration into the given string.
158 /// This is the method invoked by Sema when displaying a NamedDecl
159 /// in a diagnostic. It does not necessarily produce the same
160 /// result as getNameAsString(); for example, class template
161 /// specializations are printed with their template arguments.
163 /// TODO: use an API that doesn't require so many temporary strings
164 virtual void getNameForDiagnostic(std::string &S,
165 const PrintingPolicy &Policy,
166 bool Qualified) const {
168 S += getQualifiedNameAsString(Policy);
170 S += getNameAsString();
173 /// declarationReplaces - Determine whether this declaration, if
174 /// known to be well-formed within its context, will replace the
175 /// declaration OldD if introduced into scope. A declaration will
176 /// replace another declaration if, for example, it is a
177 /// redeclaration of the same variable or function, but not if it is
178 /// a declaration of a different kind (function vs. class) or an
179 /// overloaded function.
180 bool declarationReplaces(NamedDecl *OldD) const;
182 /// \brief Determine whether this declaration has linkage.
183 bool hasLinkage() const;
185 /// \brief Whether this declaration was marked as being private to the
186 /// module in which it was defined.
187 bool isModulePrivate() const { return ModulePrivate; }
189 /// \brief Specify whether this declaration was marked as being private
190 /// to the module in which it was defined.
191 void setModulePrivate(bool MP = true) {
195 /// \brief Determine whether this declaration is a C++ class member.
196 bool isCXXClassMember() const {
197 const DeclContext *DC = getDeclContext();
199 // C++0x [class.mem]p1:
200 // The enumerators of an unscoped enumeration defined in
201 // the class are members of the class.
202 // FIXME: support C++0x scoped enumerations.
203 if (isa<EnumDecl>(DC))
204 DC = DC->getParent();
206 return DC->isRecord();
209 /// \brief Given that this declaration is a C++ class member,
210 /// determine whether it's an instance member of its class.
211 bool isCXXInstanceMember() const;
215 Visibility visibility_;
219 LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility),
221 LinkageInfo(Linkage L, Visibility V, bool E)
222 : linkage_(L), visibility_(V), explicit_(E) {}
224 static LinkageInfo external() {
225 return LinkageInfo();
227 static LinkageInfo internal() {
228 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
230 static LinkageInfo uniqueExternal() {
231 return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false);
233 static LinkageInfo none() {
234 return LinkageInfo(NoLinkage, DefaultVisibility, false);
237 Linkage linkage() const { return linkage_; }
238 Visibility visibility() const { return visibility_; }
239 bool visibilityExplicit() const { return explicit_; }
241 void setLinkage(Linkage L) { linkage_ = L; }
242 void setVisibility(Visibility V) { visibility_ = V; }
243 void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; }
244 void setVisibility(LinkageInfo Other) {
245 setVisibility(Other.visibility(), Other.visibilityExplicit());
248 void mergeLinkage(Linkage L) {
249 setLinkage(minLinkage(linkage(), L));
251 void mergeLinkage(LinkageInfo Other) {
252 setLinkage(minLinkage(linkage(), Other.linkage()));
255 void mergeVisibility(Visibility V) {
256 setVisibility(minVisibility(visibility(), V));
258 void mergeVisibility(Visibility V, bool E) {
259 setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E);
261 void mergeVisibility(LinkageInfo Other) {
262 mergeVisibility(Other.visibility(), Other.visibilityExplicit());
265 void merge(LinkageInfo Other) {
267 mergeVisibility(Other);
269 void merge(std::pair<Linkage,Visibility> LV) {
270 mergeLinkage(LV.first);
271 mergeVisibility(LV.second);
274 friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
280 /// \brief Determine what kind of linkage this entity has.
281 Linkage getLinkage() const;
283 /// \brief Determines the visibility of this entity.
284 Visibility getVisibility() const { return getLinkageAndVisibility().visibility(); }
286 /// \brief Determines the linkage and visibility of this entity.
287 LinkageInfo getLinkageAndVisibility() const;
289 /// \brief If visibility was explicitly specified for this
290 /// declaration, return that visibility.
291 llvm::Optional<Visibility> getExplicitVisibility() const;
293 /// \brief Clear the linkage cache in response to a change
294 /// to the declaration.
295 void ClearLinkageCache();
297 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
298 /// the underlying named decl.
299 NamedDecl *getUnderlyingDecl();
300 const NamedDecl *getUnderlyingDecl() const {
301 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
304 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
305 static bool classof(const NamedDecl *D) { return true; }
306 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
309 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
314 /// LabelDecl - Represents the declaration of a label. Labels also have a
315 /// corresponding LabelStmt, which indicates the position that the label was
316 /// defined at. For normal labels, the location of the decl is the same as the
317 /// location of the statement. For GNU local labels (__label__), the decl
318 /// location is where the __label__ is.
319 class LabelDecl : public NamedDecl {
321 /// LocStart - For normal labels, this is the same as the main declaration
322 /// label, i.e., the location of the identifier; for GNU local labels,
323 /// this is the location of the __label__ keyword.
324 SourceLocation LocStart;
326 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
327 LabelStmt *S, SourceLocation StartL)
328 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
331 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
332 SourceLocation IdentL, IdentifierInfo *II);
333 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
334 SourceLocation IdentL, IdentifierInfo *II,
335 SourceLocation GnuLabelL);
337 LabelStmt *getStmt() const { return TheStmt; }
338 void setStmt(LabelStmt *T) { TheStmt = T; }
340 bool isGnuLocal() const { return LocStart != getLocation(); }
341 void setLocStart(SourceLocation L) { LocStart = L; }
343 SourceRange getSourceRange() const {
344 return SourceRange(LocStart, getLocation());
347 // Implement isa/cast/dyncast/etc.
348 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
349 static bool classof(const LabelDecl *D) { return true; }
350 static bool classofKind(Kind K) { return K == Label; }
353 /// NamespaceDecl - Represent a C++ namespace.
354 class NamespaceDecl : public NamedDecl, public DeclContext {
357 /// LocStart - The starting location of the source range, pointing
358 /// to either the namespace or the inline keyword.
359 SourceLocation LocStart;
360 /// RBraceLoc - The ending location of the source range.
361 SourceLocation RBraceLoc;
363 // For extended namespace definitions:
365 // namespace A { int x; }
366 // namespace A { int y; }
368 // there will be one NamespaceDecl for each declaration.
369 // NextNamespace points to the next extended declaration.
370 // OrigNamespace points to the original namespace declaration.
371 // OrigNamespace of the first namespace decl points to its anonymous namespace
372 LazyDeclPtr NextNamespace;
374 /// \brief A pointer to either the original namespace definition for
375 /// this namespace (if the boolean value is false) or the anonymous
376 /// namespace that lives just inside this namespace (if the boolean
379 /// We can combine these two notions because the anonymous namespace
380 /// must only be stored in one of the namespace declarations (so all
381 /// of the namespace declarations can find it). We therefore choose
382 /// the original namespace declaration, since all of the namespace
383 /// declarations have a link directly to it; the original namespace
384 /// declaration itself only needs to know that it is the original
385 /// namespace declaration (which the boolean indicates).
386 llvm::PointerIntPair<NamespaceDecl *, 1, bool> OrigOrAnonNamespace;
388 NamespaceDecl(DeclContext *DC, SourceLocation StartLoc,
389 SourceLocation IdLoc, IdentifierInfo *Id)
390 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
391 IsInline(false), LocStart(StartLoc), RBraceLoc(),
392 NextNamespace(), OrigOrAnonNamespace(0, true) { }
395 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
396 SourceLocation StartLoc,
397 SourceLocation IdLoc, IdentifierInfo *Id);
399 /// \brief Returns true if this is an anonymous namespace declaration.
407 /// q.v. C++ [namespace.unnamed]
408 bool isAnonymousNamespace() const {
409 return !getIdentifier();
412 /// \brief Returns true if this is an inline namespace declaration.
413 bool isInline() const {
417 /// \brief Set whether this is an inline namespace declaration.
418 void setInline(bool Inline) {
422 /// \brief Return the next extended namespace declaration or null if there
424 NamespaceDecl *getNextNamespace();
425 const NamespaceDecl *getNextNamespace() const {
426 return const_cast<NamespaceDecl *>(this)->getNextNamespace();
429 /// \brief Set the next extended namespace declaration.
430 void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; }
432 /// \brief Get the original (first) namespace declaration.
433 NamespaceDecl *getOriginalNamespace() const {
434 if (OrigOrAnonNamespace.getInt())
435 return const_cast<NamespaceDecl *>(this);
437 return OrigOrAnonNamespace.getPointer();
440 /// \brief Return true if this declaration is an original (first) declaration
441 /// of the namespace. This is false for non-original (subsequent) namespace
442 /// declarations and anonymous namespaces.
443 bool isOriginalNamespace() const {
444 return getOriginalNamespace() == this;
447 /// \brief Set the original (first) namespace declaration.
448 void setOriginalNamespace(NamespaceDecl *ND) {
450 OrigOrAnonNamespace.setPointer(ND);
451 OrigOrAnonNamespace.setInt(false);
455 NamespaceDecl *getAnonymousNamespace() const {
456 return getOriginalNamespace()->OrigOrAnonNamespace.getPointer();
459 void setAnonymousNamespace(NamespaceDecl *D) {
460 assert(!D || D->isAnonymousNamespace());
461 assert(!D || D->getParent()->getRedeclContext() == this);
462 getOriginalNamespace()->OrigOrAnonNamespace.setPointer(D);
465 virtual NamespaceDecl *getCanonicalDecl() { return getOriginalNamespace(); }
466 const NamespaceDecl *getCanonicalDecl() const {
467 return getOriginalNamespace();
470 virtual SourceRange getSourceRange() const {
471 return SourceRange(LocStart, RBraceLoc);
474 SourceLocation getLocStart() const { return LocStart; }
475 SourceLocation getRBraceLoc() const { return RBraceLoc; }
476 void setLocStart(SourceLocation L) { LocStart = L; }
477 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
479 // Implement isa/cast/dyncast/etc.
480 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
481 static bool classof(const NamespaceDecl *D) { return true; }
482 static bool classofKind(Kind K) { return K == Namespace; }
483 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
484 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
486 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
487 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
490 friend class ASTDeclReader;
491 friend class ASTDeclWriter;
494 /// ValueDecl - Represent the declaration of a variable (in which case it is
495 /// an lvalue) a function (in which case it is a function designator) or
496 /// an enum constant.
497 class ValueDecl : public NamedDecl {
501 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
502 DeclarationName N, QualType T)
503 : NamedDecl(DK, DC, L, N), DeclType(T) {}
505 QualType getType() const { return DeclType; }
506 void setType(QualType newType) { DeclType = newType; }
508 // Implement isa/cast/dyncast/etc.
509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
510 static bool classof(const ValueDecl *D) { return true; }
511 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
514 /// QualifierInfo - A struct with extended info about a syntactic
515 /// name qualifier, to be used for the case of out-of-line declarations.
516 struct QualifierInfo {
517 NestedNameSpecifierLoc QualifierLoc;
519 /// NumTemplParamLists - The number of "outer" template parameter lists.
520 /// The count includes all of the template parameter lists that were matched
521 /// against the template-ids occurring into the NNS and possibly (in the
522 /// case of an explicit specialization) a final "template <>".
523 unsigned NumTemplParamLists;
525 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
526 /// containing pointers to the "outer" template parameter lists.
527 /// It includes all of the template parameter lists that were matched
528 /// against the template-ids occurring into the NNS and possibly (in the
529 /// case of an explicit specialization) a final "template <>".
530 TemplateParameterList** TemplParamLists;
532 /// Default constructor.
533 QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
535 /// setTemplateParameterListsInfo - Sets info about "outer" template
537 void setTemplateParameterListsInfo(ASTContext &Context,
539 TemplateParameterList **TPLists);
542 // Copy constructor and copy assignment are disabled.
543 QualifierInfo(const QualifierInfo&);
544 QualifierInfo& operator=(const QualifierInfo&);
547 /// \brief Represents a ValueDecl that came out of a declarator.
548 /// Contains type source information through TypeSourceInfo.
549 class DeclaratorDecl : public ValueDecl {
550 // A struct representing both a TInfo and a syntactic qualifier,
551 // to be used for the (uncommon) case of out-of-line declarations.
552 struct ExtInfo : public QualifierInfo {
553 TypeSourceInfo *TInfo;
556 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
558 /// InnerLocStart - The start of the source range for this declaration,
559 /// ignoring outer template declarations.
560 SourceLocation InnerLocStart;
562 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
563 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
564 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
567 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
568 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
569 SourceLocation StartL)
570 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
574 TypeSourceInfo *getTypeSourceInfo() const {
576 ? getExtInfo()->TInfo
577 : DeclInfo.get<TypeSourceInfo*>();
579 void setTypeSourceInfo(TypeSourceInfo *TI) {
581 getExtInfo()->TInfo = TI;
586 /// getInnerLocStart - Return SourceLocation representing start of source
587 /// range ignoring outer template declarations.
588 SourceLocation getInnerLocStart() const { return InnerLocStart; }
589 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
591 /// getOuterLocStart - Return SourceLocation representing start of source
592 /// range taking into account any outer template declarations.
593 SourceLocation getOuterLocStart() const;
595 virtual SourceRange getSourceRange() const;
597 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
598 /// declaration, if it was present in the source.
599 NestedNameSpecifier *getQualifier() const {
600 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
604 /// \brief Retrieve the nested-name-specifier (with source-location
605 /// information) that qualifies the name of this declaration, if it was
606 /// present in the source.
607 NestedNameSpecifierLoc getQualifierLoc() const {
608 return hasExtInfo() ? getExtInfo()->QualifierLoc
609 : NestedNameSpecifierLoc();
612 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
614 unsigned getNumTemplateParameterLists() const {
615 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
617 TemplateParameterList *getTemplateParameterList(unsigned index) const {
618 assert(index < getNumTemplateParameterLists());
619 return getExtInfo()->TemplParamLists[index];
621 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
622 TemplateParameterList **TPLists);
624 SourceLocation getTypeSpecStartLoc() const;
626 // Implement isa/cast/dyncast/etc.
627 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
628 static bool classof(const DeclaratorDecl *D) { return true; }
629 static bool classofKind(Kind K) {
630 return K >= firstDeclarator && K <= lastDeclarator;
633 friend class ASTDeclReader;
634 friend class ASTDeclWriter;
637 /// \brief Structure used to store a statement, the constant value to
638 /// which it was evaluated (if any), and whether or not the statement
639 /// is an integral constant expression (if known).
640 struct EvaluatedStmt {
641 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
642 CheckingICE(false), IsICE(false) { }
644 /// \brief Whether this statement was already evaluated.
645 bool WasEvaluated : 1;
647 /// \brief Whether this statement is being evaluated.
648 bool IsEvaluating : 1;
650 /// \brief Whether we already checked whether this statement was an
651 /// integral constant expression.
654 /// \brief Whether we are checking whether this statement is an
655 /// integral constant expression.
656 bool CheckingICE : 1;
658 /// \brief Whether this statement is an integral constant
659 /// expression. Only valid if CheckedICE is true.
666 /// VarDecl - An instance of this class is created to represent a variable
667 /// declaration or definition.
668 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
670 typedef clang::StorageClass StorageClass;
672 /// getStorageClassSpecifierString - Return the string used to
673 /// specify the storage class \arg SC.
675 /// It is illegal to call this function with SC == None.
676 static const char *getStorageClassSpecifierString(StorageClass SC);
679 /// \brief Placeholder type used in Init to denote an unparsed C++ default
681 struct UnparsedDefaultArgument;
683 /// \brief Placeholder type used in Init to denote an uninstantiated C++
684 /// default argument.
685 struct UninstantiatedDefaultArgument;
687 typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
688 UnparsedDefaultArgument *,
689 UninstantiatedDefaultArgument *> InitType;
691 /// \brief The initializer for this variable or, for a ParmVarDecl, the
692 /// C++ default argument.
693 mutable InitType Init;
696 class VarDeclBitfields {
697 friend class VarDecl;
698 friend class ASTDeclReader;
701 unsigned SClassAsWritten : 3;
702 unsigned ThreadSpecified : 1;
703 unsigned HasCXXDirectInit : 1;
705 /// \brief Whether this variable is the exception variable in a C++ catch
706 /// or an Objective-C @catch statement.
707 unsigned ExceptionVar : 1;
709 /// \brief Whether this local variable could be allocated in the return
710 /// slot of its function, enabling the named return value optimization (NRVO).
711 unsigned NRVOVariable : 1;
713 /// \brief Whether this variable is the for-range-declaration in a C++0x
714 /// for-range statement.
715 unsigned CXXForRangeDecl : 1;
717 /// \brief Whether this variable is an ARC pseudo-__strong
718 /// variable; see isARCPseudoStrong() for details.
719 unsigned ARCPseudoStrong : 1;
721 /// \brief Whether this variable is (C++0x) constexpr.
722 unsigned IsConstexpr : 1;
724 enum { NumVarDeclBits = 13 };
726 friend class ASTDeclReader;
727 friend class StmtIteratorBase;
730 enum { NumParameterIndexBits = 8 };
732 class ParmVarDeclBitfields {
733 friend class ParmVarDecl;
734 friend class ASTDeclReader;
736 unsigned : NumVarDeclBits;
738 /// Whether this parameter inherits a default argument from a
739 /// prior declaration.
740 unsigned HasInheritedDefaultArg : 1;
742 /// Whether this parameter undergoes K&R argument promotion.
743 unsigned IsKNRPromoted : 1;
745 /// Whether this parameter is an ObjC method parameter or not.
746 unsigned IsObjCMethodParam : 1;
748 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
749 /// Otherwise, the number of function parameter scopes enclosing
750 /// the function parameter scope in which this parameter was
752 unsigned ScopeDepthOrObjCQuals : 8;
754 /// The number of parameters preceding this parameter in the
755 /// function parameter scope in which it was declared.
756 unsigned ParameterIndex : NumParameterIndexBits;
761 VarDeclBitfields VarDeclBits;
762 ParmVarDeclBitfields ParmVarDeclBits;
765 VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
766 SourceLocation IdLoc, IdentifierInfo *Id,
767 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
768 StorageClass SCAsWritten)
769 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
770 assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
771 assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
773 VarDeclBits.SClass = SC;
774 VarDeclBits.SClassAsWritten = SCAsWritten;
775 // Everything else is implicitly initialized to false.
778 typedef Redeclarable<VarDecl> redeclarable_base;
779 virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
782 typedef redeclarable_base::redecl_iterator redecl_iterator;
783 redecl_iterator redecls_begin() const {
784 return redeclarable_base::redecls_begin();
786 redecl_iterator redecls_end() const {
787 return redeclarable_base::redecls_end();
790 static VarDecl *Create(ASTContext &C, DeclContext *DC,
791 SourceLocation StartLoc, SourceLocation IdLoc,
792 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
793 StorageClass S, StorageClass SCAsWritten);
795 virtual SourceRange getSourceRange() const;
797 StorageClass getStorageClass() const {
798 return (StorageClass) VarDeclBits.SClass;
800 StorageClass getStorageClassAsWritten() const {
801 return (StorageClass) VarDeclBits.SClassAsWritten;
803 void setStorageClass(StorageClass SC);
804 void setStorageClassAsWritten(StorageClass SC) {
805 assert(isLegalForVariable(SC));
806 VarDeclBits.SClassAsWritten = SC;
809 void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
810 bool isThreadSpecified() const {
811 return VarDeclBits.ThreadSpecified;
814 /// hasLocalStorage - Returns true if a variable with function scope
815 /// is a non-static local variable.
816 bool hasLocalStorage() const {
817 if (getStorageClass() == SC_None)
818 return !isFileVarDecl();
820 // Return true for: Auto, Register.
821 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
823 return getStorageClass() >= SC_Auto;
826 /// isStaticLocal - Returns true if a variable with function scope is a
827 /// static local variable.
828 bool isStaticLocal() const {
829 return getStorageClass() == SC_Static && !isFileVarDecl();
832 /// hasExternStorage - Returns true if a variable has extern or
833 /// __private_extern__ storage.
834 bool hasExternalStorage() const {
835 return getStorageClass() == SC_Extern ||
836 getStorageClass() == SC_PrivateExtern;
839 /// hasGlobalStorage - Returns true for all variables that do not
840 /// have local storage. This includs all global variables as well
841 /// as static variables declared within a function.
842 bool hasGlobalStorage() const { return !hasLocalStorage(); }
844 /// \brief Determines whether this variable is a variable with
845 /// external, C linkage.
846 bool isExternC() const;
848 /// isLocalVarDecl - Returns true for local variable declarations
849 /// other than parameters. Note that this includes static variables
850 /// inside of functions. It also includes variables inside blocks.
852 /// void foo() { int x; static int y; extern int z; }
854 bool isLocalVarDecl() const {
855 if (getKind() != Decl::Var)
857 if (const DeclContext *DC = getDeclContext())
858 return DC->getRedeclContext()->isFunctionOrMethod();
862 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
863 /// excludes variables declared in blocks.
864 bool isFunctionOrMethodVarDecl() const {
865 if (getKind() != Decl::Var)
867 const DeclContext *DC = getDeclContext()->getRedeclContext();
868 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
871 /// \brief Determines whether this is a static data member.
873 /// This will only be true in C++, and applies to, e.g., the
880 bool isStaticDataMember() const {
881 // If it wasn't static, it would be a FieldDecl.
882 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
885 virtual VarDecl *getCanonicalDecl();
886 const VarDecl *getCanonicalDecl() const {
887 return const_cast<VarDecl*>(this)->getCanonicalDecl();
890 enum DefinitionKind {
891 DeclarationOnly, ///< This declaration is only a declaration.
892 TentativeDefinition, ///< This declaration is a tentative definition.
893 Definition ///< This declaration is definitely a definition.
896 /// \brief Check whether this declaration is a definition. If this could be
897 /// a tentative definition (in C), don't check whether there's an overriding
899 DefinitionKind isThisDeclarationADefinition() const;
901 /// \brief Check whether this variable is defined in this
902 /// translation unit.
903 DefinitionKind hasDefinition() const;
905 /// \brief Get the tentative definition that acts as the real definition in
906 /// a TU. Returns null if there is a proper definition available.
907 VarDecl *getActingDefinition();
908 const VarDecl *getActingDefinition() const {
909 return const_cast<VarDecl*>(this)->getActingDefinition();
912 /// \brief Determine whether this is a tentative definition of a
914 bool isTentativeDefinitionNow() const;
916 /// \brief Get the real (not just tentative) definition for this declaration.
917 VarDecl *getDefinition();
918 const VarDecl *getDefinition() const {
919 return const_cast<VarDecl*>(this)->getDefinition();
922 /// \brief Determine whether this is or was instantiated from an out-of-line
923 /// definition of a static data member.
924 virtual bool isOutOfLine() const;
926 /// \brief If this is a static data member, find its out-of-line definition.
927 VarDecl *getOutOfLineDefinition();
929 /// isFileVarDecl - Returns true for file scoped variable declaration.
930 bool isFileVarDecl() const {
931 if (getKind() != Decl::Var)
934 if (getDeclContext()->getRedeclContext()->isFileContext())
937 if (isStaticDataMember())
943 /// getAnyInitializer - Get the initializer for this variable, no matter which
944 /// declaration it is attached to.
945 const Expr *getAnyInitializer() const {
947 return getAnyInitializer(D);
950 /// getAnyInitializer - Get the initializer for this variable, no matter which
951 /// declaration it is attached to. Also get that declaration.
952 const Expr *getAnyInitializer(const VarDecl *&D) const;
954 bool hasInit() const {
955 return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
957 const Expr *getInit() const {
961 const Stmt *S = Init.dyn_cast<Stmt *>();
963 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
966 return (const Expr*) S;
972 Stmt *S = Init.dyn_cast<Stmt *>();
974 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
981 /// \brief Retrieve the address of the initializer expression.
982 Stmt **getInitAddress() {
983 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
986 // This union hack tip-toes around strict-aliasing rules.
996 void setInit(Expr *I);
998 /// \brief Determine whether this variable is a reference that
999 /// extends the lifetime of its temporary initializer.
1001 /// A reference extends the lifetime of its temporary initializer if
1002 /// it's initializer is an rvalue that would normally go out of scope
1003 /// at the end of the initializer (a full expression). In such cases,
1004 /// the reference itself takes ownership of the temporary, which will
1005 /// be destroyed when the reference goes out of scope. For example:
1008 /// const int &r = 1.0; // creates a temporary of type 'int'
1010 bool extendsLifetimeOfTemporary() const;
1012 EvaluatedStmt *EnsureEvaluatedStmt() const {
1013 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1015 Stmt *S = Init.get<Stmt *>();
1016 Eval = new (getASTContext()) EvaluatedStmt;
1023 /// \brief Check whether we are in the process of checking whether the
1024 /// initializer can be evaluated.
1025 bool isEvaluatingValue() const {
1026 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1027 return Eval->IsEvaluating;
1032 /// \brief Note that we now are checking whether the initializer can be
1034 void setEvaluatingValue() const {
1035 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1036 Eval->IsEvaluating = true;
1039 /// \brief Note that constant evaluation has computed the given
1040 /// value for this variable's initializer.
1041 void setEvaluatedValue(const APValue &Value) const {
1042 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1043 Eval->IsEvaluating = false;
1044 Eval->WasEvaluated = true;
1045 Eval->Evaluated = Value;
1048 /// \brief Return the already-evaluated value of this variable's
1049 /// initializer, or NULL if the value is not yet known. Returns pointer
1050 /// to untyped APValue if the value could not be evaluated.
1051 APValue *getEvaluatedValue() const {
1052 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1053 if (Eval->WasEvaluated)
1054 return &Eval->Evaluated;
1059 /// \brief Determines whether it is already known whether the
1060 /// initializer is an integral constant expression or not.
1061 bool isInitKnownICE() const {
1062 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1063 return Eval->CheckedICE;
1068 /// \brief Determines whether the initializer is an integral
1069 /// constant expression.
1071 /// \pre isInitKnownICE()
1072 bool isInitICE() const {
1073 assert(isInitKnownICE() &&
1074 "Check whether we already know that the initializer is an ICE");
1075 return Init.get<EvaluatedStmt *>()->IsICE;
1078 /// \brief Check whether we are in the process of checking the initializer
1079 /// is an integral constant expression.
1080 bool isCheckingICE() const {
1081 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1082 return Eval->CheckingICE;
1087 /// \brief Note that we now are checking whether the initializer is an
1088 /// integral constant expression.
1089 void setCheckingICE() const {
1090 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1091 Eval->CheckingICE = true;
1094 /// \brief Note that we now know whether the initializer is an
1095 /// integral constant expression.
1096 void setInitKnownICE(bool IsICE) const {
1097 EvaluatedStmt *Eval = EnsureEvaluatedStmt();
1098 Eval->CheckingICE = false;
1099 Eval->CheckedICE = true;
1100 Eval->IsICE = IsICE;
1103 void setCXXDirectInitializer(bool T) { VarDeclBits.HasCXXDirectInit = T; }
1105 /// hasCXXDirectInitializer - If true, the initializer was a direct
1106 /// initializer, e.g: "int x(1);". The Init expression will be the expression
1107 /// inside the parens or a "ClassType(a,b,c)" class constructor expression for
1108 /// class types. Clients can distinguish between "int x(1);" and "int x=1;"
1109 /// by checking hasCXXDirectInitializer.
1111 bool hasCXXDirectInitializer() const {
1112 return VarDeclBits.HasCXXDirectInit;
1115 /// \brief Determine whether this variable is the exception variable in a
1116 /// C++ catch statememt or an Objective-C @catch statement.
1117 bool isExceptionVariable() const {
1118 return VarDeclBits.ExceptionVar;
1120 void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1122 /// \brief Determine whether this local variable can be used with the named
1123 /// return value optimization (NRVO).
1125 /// The named return value optimization (NRVO) works by marking certain
1126 /// non-volatile local variables of class type as NRVO objects. These
1127 /// locals can be allocated within the return slot of their containing
1128 /// function, in which case there is no need to copy the object to the
1129 /// return slot when returning from the function. Within the function body,
1130 /// each return that returns the NRVO object will have this variable as its
1132 bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
1133 void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1135 /// \brief Determine whether this variable is the for-range-declaration in
1136 /// a C++0x for-range statement.
1137 bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
1138 void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1140 /// \brief Determine whether this variable is an ARC pseudo-__strong
1141 /// variable. A pseudo-__strong variable has a __strong-qualified
1142 /// type but does not actually retain the object written into it.
1143 /// Generally such variables are also 'const' for safety.
1144 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1145 void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1147 /// Whether this variable is (C++0x) constexpr.
1148 bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
1149 void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1151 /// \brief If this variable is an instantiated static data member of a
1152 /// class template specialization, returns the templated static data member
1153 /// from which it was instantiated.
1154 VarDecl *getInstantiatedFromStaticDataMember() const;
1156 /// \brief If this variable is a static data member, determine what kind of
1157 /// template specialization or instantiation this is.
1158 TemplateSpecializationKind getTemplateSpecializationKind() const;
1160 /// \brief If this variable is an instantiation of a static data member of a
1161 /// class template specialization, retrieves the member specialization
1163 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1165 /// \brief For a static data member that was instantiated from a static
1166 /// data member of a class template, set the template specialiation kind.
1167 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1168 SourceLocation PointOfInstantiation = SourceLocation());
1170 // Implement isa/cast/dyncast/etc.
1171 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1172 static bool classof(const VarDecl *D) { return true; }
1173 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1176 class ImplicitParamDecl : public VarDecl {
1178 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1179 SourceLocation IdLoc, IdentifierInfo *Id,
1182 ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1183 IdentifierInfo *Id, QualType Type)
1184 : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1185 /*tinfo*/ 0, SC_None, SC_None) {
1189 // Implement isa/cast/dyncast/etc.
1190 static bool classof(const ImplicitParamDecl *D) { return true; }
1191 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1192 static bool classofKind(Kind K) { return K == ImplicitParam; }
1195 /// ParmVarDecl - Represents a parameter to a function.
1196 class ParmVarDecl : public VarDecl {
1198 enum { MaxFunctionScopeDepth = 255 };
1199 enum { MaxFunctionScopeIndex = 255 };
1202 ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1203 SourceLocation IdLoc, IdentifierInfo *Id,
1204 QualType T, TypeSourceInfo *TInfo,
1205 StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
1206 : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) {
1207 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1208 assert(ParmVarDeclBits.IsKNRPromoted == false);
1209 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1210 setDefaultArg(DefArg);
1214 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1215 SourceLocation StartLoc,
1216 SourceLocation IdLoc, IdentifierInfo *Id,
1217 QualType T, TypeSourceInfo *TInfo,
1218 StorageClass S, StorageClass SCAsWritten,
1221 virtual SourceRange getSourceRange() const;
1223 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1224 ParmVarDeclBits.IsObjCMethodParam = true;
1225 setParameterIndex(parameterIndex);
1228 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1229 assert(!ParmVarDeclBits.IsObjCMethodParam);
1231 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1232 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!");
1234 setParameterIndex(parameterIndex);
1237 bool isObjCMethodParameter() const {
1238 return ParmVarDeclBits.IsObjCMethodParam;
1241 unsigned getFunctionScopeDepth() const {
1242 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1243 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1246 /// Returns the index of this parameter in its prototype or method scope.
1247 unsigned getFunctionScopeIndex() const {
1248 return getParameterIndex();
1251 ObjCDeclQualifier getObjCDeclQualifier() const {
1252 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1253 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1255 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1256 assert(ParmVarDeclBits.IsObjCMethodParam);
1257 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1260 /// True if the value passed to this parameter must undergo
1261 /// K&R-style default argument promotion:
1264 /// If the expression that denotes the called function has a type
1265 /// that does not include a prototype, the integer promotions are
1266 /// performed on each argument, and arguments that have type float
1267 /// are promoted to double.
1268 bool isKNRPromoted() const {
1269 return ParmVarDeclBits.IsKNRPromoted;
1271 void setKNRPromoted(bool promoted) {
1272 ParmVarDeclBits.IsKNRPromoted = promoted;
1275 Expr *getDefaultArg();
1276 const Expr *getDefaultArg() const {
1277 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1280 void setDefaultArg(Expr *defarg) {
1281 Init = reinterpret_cast<Stmt *>(defarg);
1284 unsigned getNumDefaultArgTemporaries() const;
1285 CXXTemporary *getDefaultArgTemporary(unsigned i);
1286 const CXXTemporary *getDefaultArgTemporary(unsigned i) const {
1287 return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i);
1290 /// \brief Retrieve the source range that covers the entire default
1292 SourceRange getDefaultArgRange() const;
1293 void setUninstantiatedDefaultArg(Expr *arg) {
1294 Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1296 Expr *getUninstantiatedDefaultArg() {
1297 return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1299 const Expr *getUninstantiatedDefaultArg() const {
1300 return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1303 /// hasDefaultArg - Determines whether this parameter has a default argument,
1304 /// either parsed or not.
1305 bool hasDefaultArg() const {
1306 return getInit() || hasUnparsedDefaultArg() ||
1307 hasUninstantiatedDefaultArg();
1310 /// hasUnparsedDefaultArg - Determines whether this parameter has a
1311 /// default argument that has not yet been parsed. This will occur
1312 /// during the processing of a C++ class whose member functions have
1313 /// default arguments, e.g.,
1317 /// void f(int x = 17); // x has an unparsed default argument now
1318 /// }; // x has a regular default argument now
1320 bool hasUnparsedDefaultArg() const {
1321 return Init.is<UnparsedDefaultArgument*>();
1324 bool hasUninstantiatedDefaultArg() const {
1325 return Init.is<UninstantiatedDefaultArgument*>();
1328 /// setUnparsedDefaultArg - Specify that this parameter has an
1329 /// unparsed default argument. The argument will be replaced with a
1330 /// real default argument via setDefaultArg when the class
1331 /// definition enclosing the function declaration that owns this
1332 /// default argument is completed.
1333 void setUnparsedDefaultArg() {
1334 Init = (UnparsedDefaultArgument *)0;
1337 bool hasInheritedDefaultArg() const {
1338 return ParmVarDeclBits.HasInheritedDefaultArg;
1341 void setHasInheritedDefaultArg(bool I = true) {
1342 ParmVarDeclBits.HasInheritedDefaultArg = I;
1345 QualType getOriginalType() const {
1346 if (getTypeSourceInfo())
1347 return getTypeSourceInfo()->getType();
1351 /// \brief Determine whether this parameter is actually a function
1353 bool isParameterPack() const;
1355 /// setOwningFunction - Sets the function declaration that owns this
1356 /// ParmVarDecl. Since ParmVarDecls are often created before the
1357 /// FunctionDecls that own them, this routine is required to update
1358 /// the DeclContext appropriately.
1359 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1361 // Implement isa/cast/dyncast/etc.
1362 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1363 static bool classof(const ParmVarDecl *D) { return true; }
1364 static bool classofKind(Kind K) { return K == ParmVar; }
1367 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1369 void setParameterIndex(unsigned parameterIndex) {
1370 if (parameterIndex >= ParameterIndexSentinel) {
1371 setParameterIndexLarge(parameterIndex);
1375 ParmVarDeclBits.ParameterIndex = parameterIndex;
1376 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1378 unsigned getParameterIndex() const {
1379 unsigned d = ParmVarDeclBits.ParameterIndex;
1380 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1383 void setParameterIndexLarge(unsigned parameterIndex);
1384 unsigned getParameterIndexLarge() const;
1387 /// FunctionDecl - An instance of this class is created to represent a
1388 /// function declaration or definition.
1390 /// Since a given function can be declared several times in a program,
1391 /// there may be several FunctionDecls that correspond to that
1392 /// function. Only one of those FunctionDecls will be found when
1393 /// traversing the list of declarations in the context of the
1394 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1395 /// contains all of the information known about the function. Other,
1396 /// previous declarations of the function are available via the
1397 /// getPreviousDeclaration() chain.
1398 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1399 public Redeclarable<FunctionDecl> {
1401 typedef clang::StorageClass StorageClass;
1403 /// \brief The kind of templated function a FunctionDecl can be.
1404 enum TemplatedKind {
1406 TK_FunctionTemplate,
1407 TK_MemberSpecialization,
1408 TK_FunctionTemplateSpecialization,
1409 TK_DependentFunctionTemplateSpecialization
1413 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1414 /// parameters of this function. This is null if a prototype or if there are
1416 ParmVarDecl **ParamInfo;
1418 LazyDeclStmtPtr Body;
1420 // FIXME: This can be packed into the bitfields in Decl.
1421 // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1422 unsigned SClass : 2;
1423 unsigned SClassAsWritten : 2;
1425 bool IsInlineSpecified : 1;
1426 bool IsVirtualAsWritten : 1;
1428 bool HasInheritedPrototype : 1;
1429 bool HasWrittenPrototype : 1;
1431 bool IsTrivial : 1; // sunk from CXXMethodDecl
1432 bool IsDefaulted : 1; // sunk from CXXMethoDecl
1433 bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1434 bool HasImplicitReturnZero : 1;
1435 bool IsLateTemplateParsed : 1;
1436 bool IsConstexpr : 1;
1438 /// \brief End part of this FunctionDecl's source range.
1440 /// We could compute the full range in getSourceRange(). However, when we're
1441 /// dealing with a function definition deserialized from a PCH/AST file,
1442 /// we can only compute the full range once the function body has been
1443 /// de-serialized, so it's far better to have the (sometimes-redundant)
1445 SourceLocation EndRangeLoc;
1447 /// \brief The template or declaration that this declaration
1448 /// describes or was instantiated from, respectively.
1450 /// For non-templates, this value will be NULL. For function
1451 /// declarations that describe a function template, this will be a
1452 /// pointer to a FunctionTemplateDecl. For member functions
1453 /// of class template specializations, this will be a MemberSpecializationInfo
1454 /// pointer containing information about the specialization.
1455 /// For function template specializations, this will be a
1456 /// FunctionTemplateSpecializationInfo, which contains information about
1457 /// the template being specialized and the template arguments involved in
1458 /// that specialization.
1459 llvm::PointerUnion4<FunctionTemplateDecl *,
1460 MemberSpecializationInfo *,
1461 FunctionTemplateSpecializationInfo *,
1462 DependentFunctionTemplateSpecializationInfo *>
1463 TemplateOrSpecialization;
1465 /// DNLoc - Provides source/type location info for the
1466 /// declaration name embedded in the DeclaratorDecl base class.
1467 DeclarationNameLoc DNLoc;
1469 /// \brief Specify that this function declaration is actually a function
1470 /// template specialization.
1472 /// \param C the ASTContext.
1474 /// \param Template the function template that this function template
1475 /// specialization specializes.
1477 /// \param TemplateArgs the template arguments that produced this
1478 /// function template specialization from the template.
1480 /// \param InsertPos If non-NULL, the position in the function template
1481 /// specialization set where the function template specialization data will
1484 /// \param TSK the kind of template specialization this is.
1486 /// \param TemplateArgsAsWritten location info of template arguments.
1488 /// \param PointOfInstantiation point at which the function template
1489 /// specialization was first instantiated.
1490 void setFunctionTemplateSpecialization(ASTContext &C,
1491 FunctionTemplateDecl *Template,
1492 const TemplateArgumentList *TemplateArgs,
1494 TemplateSpecializationKind TSK,
1495 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1496 SourceLocation PointOfInstantiation);
1498 /// \brief Specify that this record is an instantiation of the
1499 /// member function FD.
1500 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1501 TemplateSpecializationKind TSK);
1503 void setParams(ASTContext &C, llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
1506 FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1507 const DeclarationNameInfo &NameInfo,
1508 QualType T, TypeSourceInfo *TInfo,
1509 StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified,
1510 bool isConstexprSpecified)
1511 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1514 ParamInfo(0), Body(),
1515 SClass(S), SClassAsWritten(SCAsWritten),
1516 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1517 IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1518 HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1519 IsDefaulted(false), IsExplicitlyDefaulted(false),
1520 HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1521 IsConstexpr(isConstexprSpecified), EndRangeLoc(NameInfo.getEndLoc()),
1522 TemplateOrSpecialization(),
1523 DNLoc(NameInfo.getInfo()) {}
1525 typedef Redeclarable<FunctionDecl> redeclarable_base;
1526 virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
1529 typedef redeclarable_base::redecl_iterator redecl_iterator;
1530 redecl_iterator redecls_begin() const {
1531 return redeclarable_base::redecls_begin();
1533 redecl_iterator redecls_end() const {
1534 return redeclarable_base::redecls_end();
1537 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1538 SourceLocation StartLoc, SourceLocation NLoc,
1539 DeclarationName N, QualType T,
1540 TypeSourceInfo *TInfo,
1541 StorageClass SC = SC_None,
1542 StorageClass SCAsWritten = SC_None,
1543 bool isInlineSpecified = false,
1544 bool hasWrittenPrototype = true,
1545 bool isConstexprSpecified = false) {
1546 DeclarationNameInfo NameInfo(N, NLoc);
1547 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1549 isInlineSpecified, hasWrittenPrototype,
1550 isConstexprSpecified);
1553 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1554 SourceLocation StartLoc,
1555 const DeclarationNameInfo &NameInfo,
1556 QualType T, TypeSourceInfo *TInfo,
1557 StorageClass SC = SC_None,
1558 StorageClass SCAsWritten = SC_None,
1559 bool isInlineSpecified = false,
1560 bool hasWrittenPrototype = true,
1561 bool isConstexprSpecified = false);
1563 DeclarationNameInfo getNameInfo() const {
1564 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1567 virtual void getNameForDiagnostic(std::string &S,
1568 const PrintingPolicy &Policy,
1569 bool Qualified) const;
1571 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1573 virtual SourceRange getSourceRange() const;
1575 /// \brief Returns true if the function has a body (definition). The
1576 /// function body might be in any of the (re-)declarations of this
1577 /// function. The variant that accepts a FunctionDecl pointer will
1578 /// set that function declaration to the actual declaration
1579 /// containing the body (if there is one).
1580 bool hasBody(const FunctionDecl *&Definition) const;
1582 virtual bool hasBody() const {
1583 const FunctionDecl* Definition;
1584 return hasBody(Definition);
1587 /// hasTrivialBody - Returns whether the function has a trivial body that does
1588 /// not require any specific codegen.
1589 bool hasTrivialBody() const;
1591 /// isDefined - Returns true if the function is defined at all, including
1592 /// a deleted definition. Except for the behavior when the function is
1593 /// deleted, behaves like hasBody.
1594 bool isDefined(const FunctionDecl *&Definition) const;
1596 virtual bool isDefined() const {
1597 const FunctionDecl* Definition;
1598 return isDefined(Definition);
1601 /// getBody - Retrieve the body (definition) of the function. The
1602 /// function body might be in any of the (re-)declarations of this
1603 /// function. The variant that accepts a FunctionDecl pointer will
1604 /// set that function declaration to the actual declaration
1605 /// containing the body (if there is one).
1606 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1607 /// unnecessary AST de-serialization of the body.
1608 Stmt *getBody(const FunctionDecl *&Definition) const;
1610 virtual Stmt *getBody() const {
1611 const FunctionDecl* Definition;
1612 return getBody(Definition);
1615 /// isThisDeclarationADefinition - Returns whether this specific
1616 /// declaration of the function is also a definition. This does not
1617 /// determine whether the function has been defined (e.g., in a
1618 /// previous definition); for that information, use isDefined. Note
1619 /// that this returns false for a defaulted function unless that function
1620 /// has been implicitly defined (possibly as deleted).
1621 bool isThisDeclarationADefinition() const {
1622 return IsDeleted || Body || IsLateTemplateParsed;
1625 /// doesThisDeclarationHaveABody - Returns whether this specific
1626 /// declaration of the function has a body - that is, if it is a non-
1627 /// deleted definition.
1628 bool doesThisDeclarationHaveABody() const {
1629 return Body || IsLateTemplateParsed;
1632 void setBody(Stmt *B);
1633 void setLazyBody(uint64_t Offset) { Body = Offset; }
1635 /// Whether this function is variadic.
1636 bool isVariadic() const;
1638 /// Whether this function is marked as virtual explicitly.
1639 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1640 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1642 /// Whether this virtual function is pure, i.e. makes the containing class
1644 bool isPure() const { return IsPure; }
1645 void setPure(bool P = true);
1647 /// Whether this templated function will be late parsed.
1648 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1649 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1651 /// Whether this function is "trivial" in some specialized C++ senses.
1652 /// Can only be true for default constructors, copy constructors,
1653 /// copy assignment operators, and destructors. Not meaningful until
1654 /// the class has been fully built by Sema.
1655 bool isTrivial() const { return IsTrivial; }
1656 void setTrivial(bool IT) { IsTrivial = IT; }
1658 /// Whether this function is defaulted per C++0x. Only valid for
1659 /// special member functions.
1660 bool isDefaulted() const { return IsDefaulted; }
1661 void setDefaulted(bool D = true) { IsDefaulted = D; }
1663 /// Whether this function is explicitly defaulted per C++0x. Only valid
1664 /// for special member functions.
1665 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1666 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1668 /// Whether falling off this function implicitly returns null/zero.
1669 /// If a more specific implicit return value is required, front-ends
1670 /// should synthesize the appropriate return statements.
1671 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1672 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1674 /// \brief Whether this function has a prototype, either because one
1675 /// was explicitly written or because it was "inherited" by merging
1676 /// a declaration without a prototype with a declaration that has a
1678 bool hasPrototype() const {
1679 return HasWrittenPrototype || HasInheritedPrototype;
1682 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1684 /// \brief Whether this function inherited its prototype from a
1685 /// previous declaration.
1686 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1687 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1689 /// Whether this is a (C++0x) constexpr function or constexpr constructor.
1690 bool isConstexpr() const { return IsConstexpr; }
1691 void setConstexpr(bool IC) { IsConstexpr = IC; }
1693 /// \brief Whether this function has been deleted.
1695 /// A function that is "deleted" (via the C++0x "= delete" syntax)
1696 /// acts like a normal function, except that it cannot actually be
1697 /// called or have its address taken. Deleted functions are
1698 /// typically used in C++ overload resolution to attract arguments
1699 /// whose type or lvalue/rvalue-ness would permit the use of a
1700 /// different overload that would behave incorrectly. For example,
1701 /// one might use deleted functions to ban implicit conversion from
1702 /// a floating-point number to an Integer type:
1705 /// struct Integer {
1706 /// Integer(long); // construct from a long
1707 /// Integer(double) = delete; // no construction from float or double
1708 /// Integer(long double) = delete; // no construction from long double
1711 // If a function is deleted, its first declaration must be.
1712 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1713 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1714 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1716 /// \brief Determines whether this function is "main", which is the
1717 /// entry point into an executable program.
1718 bool isMain() const;
1720 /// \brief Determines whether this operator new or delete is one
1721 /// of the reserved global placement operators:
1722 /// void *operator new(size_t, void *);
1723 /// void *operator new[](size_t, void *);
1724 /// void operator delete(void *, void *);
1725 /// void operator delete[](void *, void *);
1726 /// These functions have special behavior under [new.delete.placement]:
1727 /// These functions are reserved, a C++ program may not define
1728 /// functions that displace the versions in the Standard C++ library.
1729 /// The provisions of [basic.stc.dynamic] do not apply to these
1730 /// reserved placement forms of operator new and operator delete.
1732 /// This function must be an allocation or deallocation function.
1733 bool isReservedGlobalPlacementOperator() const;
1735 /// \brief Determines whether this function is a function with
1736 /// external, C linkage.
1737 bool isExternC() const;
1739 /// \brief Determines whether this is a global function.
1740 bool isGlobal() const;
1742 void setPreviousDeclaration(FunctionDecl * PrevDecl);
1744 virtual const FunctionDecl *getCanonicalDecl() const;
1745 virtual FunctionDecl *getCanonicalDecl();
1747 unsigned getBuiltinID() const;
1749 // Iterator access to formal parameters.
1750 unsigned param_size() const { return getNumParams(); }
1751 typedef ParmVarDecl **param_iterator;
1752 typedef ParmVarDecl * const *param_const_iterator;
1754 param_iterator param_begin() { return ParamInfo; }
1755 param_iterator param_end() { return ParamInfo+param_size(); }
1757 param_const_iterator param_begin() const { return ParamInfo; }
1758 param_const_iterator param_end() const { return ParamInfo+param_size(); }
1760 /// getNumParams - Return the number of parameters this function must have
1761 /// based on its FunctionType. This is the length of the ParamInfo array
1762 /// after it has been created.
1763 unsigned getNumParams() const;
1765 const ParmVarDecl *getParamDecl(unsigned i) const {
1766 assert(i < getNumParams() && "Illegal param #");
1767 return ParamInfo[i];
1769 ParmVarDecl *getParamDecl(unsigned i) {
1770 assert(i < getNumParams() && "Illegal param #");
1771 return ParamInfo[i];
1773 void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1774 setParams(getASTContext(), NewParamInfo);
1777 /// getMinRequiredArguments - Returns the minimum number of arguments
1778 /// needed to call this function. This may be fewer than the number of
1779 /// function parameters, if some of the parameters have default
1780 /// arguments (in C++).
1781 unsigned getMinRequiredArguments() const;
1783 QualType getResultType() const {
1784 return getType()->getAs<FunctionType>()->getResultType();
1787 /// \brief Determine the type of an expression that calls this function.
1788 QualType getCallResultType() const {
1789 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1792 StorageClass getStorageClass() const { return StorageClass(SClass); }
1793 void setStorageClass(StorageClass SC);
1795 StorageClass getStorageClassAsWritten() const {
1796 return StorageClass(SClassAsWritten);
1799 /// \brief Determine whether the "inline" keyword was specified for this
1801 bool isInlineSpecified() const { return IsInlineSpecified; }
1803 /// Set whether the "inline" keyword was specified for this function.
1804 void setInlineSpecified(bool I) {
1805 IsInlineSpecified = I;
1809 /// Flag that this function is implicitly inline.
1810 void setImplicitlyInline() {
1814 /// \brief Determine whether this function should be inlined, because it is
1815 /// either marked "inline" or "constexpr" or is a member function of a class
1816 /// that was defined in the class body.
1817 bool isInlined() const;
1819 bool isInlineDefinitionExternallyVisible() const;
1821 bool doesDeclarationForceExternallyVisibleDefinition() const;
1823 /// isOverloadedOperator - Whether this function declaration
1824 /// represents an C++ overloaded operator, e.g., "operator+".
1825 bool isOverloadedOperator() const {
1826 return getOverloadedOperator() != OO_None;
1829 OverloadedOperatorKind getOverloadedOperator() const;
1831 const IdentifierInfo *getLiteralIdentifier() const;
1833 /// \brief If this function is an instantiation of a member function
1834 /// of a class template specialization, retrieves the function from
1835 /// which it was instantiated.
1837 /// This routine will return non-NULL for (non-templated) member
1838 /// functions of class templates and for instantiations of function
1839 /// templates. For example, given:
1842 /// template<typename T>
1848 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1849 /// whose parent is the class template specialization X<int>. For
1850 /// this declaration, getInstantiatedFromFunction() will return
1851 /// the FunctionDecl X<T>::A. When a complete definition of
1852 /// X<int>::A is required, it will be instantiated from the
1853 /// declaration returned by getInstantiatedFromMemberFunction().
1854 FunctionDecl *getInstantiatedFromMemberFunction() const;
1856 /// \brief What kind of templated function this is.
1857 TemplatedKind getTemplatedKind() const;
1859 /// \brief If this function is an instantiation of a member function of a
1860 /// class template specialization, retrieves the member specialization
1862 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1864 /// \brief Specify that this record is an instantiation of the
1865 /// member function FD.
1866 void setInstantiationOfMemberFunction(FunctionDecl *FD,
1867 TemplateSpecializationKind TSK) {
1868 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1871 /// \brief Retrieves the function template that is described by this
1872 /// function declaration.
1874 /// Every function template is represented as a FunctionTemplateDecl
1875 /// and a FunctionDecl (or something derived from FunctionDecl). The
1876 /// former contains template properties (such as the template
1877 /// parameter lists) while the latter contains the actual
1878 /// description of the template's
1879 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1880 /// FunctionDecl that describes the function template,
1881 /// getDescribedFunctionTemplate() retrieves the
1882 /// FunctionTemplateDecl from a FunctionDecl.
1883 FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1884 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1887 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1888 TemplateOrSpecialization = Template;
1891 /// \brief Determine whether this function is a function template
1893 bool isFunctionTemplateSpecialization() const {
1894 return getPrimaryTemplate() != 0;
1897 /// \brief Retrieve the class scope template pattern that this function
1898 /// template specialization is instantiated from.
1899 FunctionDecl *getClassScopeSpecializationPattern() const;
1901 /// \brief If this function is actually a function template specialization,
1902 /// retrieve information about this function template specialization.
1903 /// Otherwise, returns NULL.
1904 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1905 return TemplateOrSpecialization.
1906 dyn_cast<FunctionTemplateSpecializationInfo*>();
1909 /// \brief Determines whether this function is a function template
1910 /// specialization or a member of a class template specialization that can
1911 /// be implicitly instantiated.
1912 bool isImplicitlyInstantiable() const;
1914 /// \brief Retrieve the function declaration from which this function could
1915 /// be instantiated, if it is an instantiation (rather than a non-template
1916 /// or a specialization, for example).
1917 FunctionDecl *getTemplateInstantiationPattern() const;
1919 /// \brief Retrieve the primary template that this function template
1920 /// specialization either specializes or was instantiated from.
1922 /// If this function declaration is not a function template specialization,
1924 FunctionTemplateDecl *getPrimaryTemplate() const;
1926 /// \brief Retrieve the template arguments used to produce this function
1927 /// template specialization from the primary template.
1929 /// If this function declaration is not a function template specialization,
1931 const TemplateArgumentList *getTemplateSpecializationArgs() const;
1933 /// \brief Retrieve the template argument list as written in the sources,
1936 /// If this function declaration is not a function template specialization
1937 /// or if it had no explicit template argument list, returns NULL.
1938 /// Note that it an explicit template argument list may be written empty,
1939 /// e.g., template<> void foo<>(char* s);
1940 const ASTTemplateArgumentListInfo*
1941 getTemplateSpecializationArgsAsWritten() const;
1943 /// \brief Specify that this function declaration is actually a function
1944 /// template specialization.
1946 /// \param Template the function template that this function template
1947 /// specialization specializes.
1949 /// \param TemplateArgs the template arguments that produced this
1950 /// function template specialization from the template.
1952 /// \param InsertPos If non-NULL, the position in the function template
1953 /// specialization set where the function template specialization data will
1956 /// \param TSK the kind of template specialization this is.
1958 /// \param TemplateArgsAsWritten location info of template arguments.
1960 /// \param PointOfInstantiation point at which the function template
1961 /// specialization was first instantiated.
1962 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1963 const TemplateArgumentList *TemplateArgs,
1965 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
1966 const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
1967 SourceLocation PointOfInstantiation = SourceLocation()) {
1968 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
1969 InsertPos, TSK, TemplateArgsAsWritten,
1970 PointOfInstantiation);
1973 /// \brief Specifies that this function declaration is actually a
1974 /// dependent function template specialization.
1975 void setDependentTemplateSpecialization(ASTContext &Context,
1976 const UnresolvedSetImpl &Templates,
1977 const TemplateArgumentListInfo &TemplateArgs);
1979 DependentFunctionTemplateSpecializationInfo *
1980 getDependentSpecializationInfo() const {
1981 return TemplateOrSpecialization.
1982 dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
1985 /// \brief Determine what kind of template instantiation this function
1987 TemplateSpecializationKind getTemplateSpecializationKind() const;
1989 /// \brief Determine what kind of template instantiation this function
1991 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1992 SourceLocation PointOfInstantiation = SourceLocation());
1994 /// \brief Retrieve the (first) point of instantiation of a function template
1995 /// specialization or a member of a class template specialization.
1997 /// \returns the first point of instantiation, if this function was
1998 /// instantiated from a template; otherwise, returns an invalid source
2000 SourceLocation getPointOfInstantiation() const;
2002 /// \brief Determine whether this is or was instantiated from an out-of-line
2003 /// definition of a member function.
2004 virtual bool isOutOfLine() const;
2006 // Implement isa/cast/dyncast/etc.
2007 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2008 static bool classof(const FunctionDecl *D) { return true; }
2009 static bool classofKind(Kind K) {
2010 return K >= firstFunction && K <= lastFunction;
2012 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2013 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2015 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2016 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2019 friend class ASTDeclReader;
2020 friend class ASTDeclWriter;
2024 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2025 /// represent a member of a struct/union/class.
2026 class FieldDecl : public DeclaratorDecl {
2027 // FIXME: This can be packed into the bitfields in Decl.
2029 mutable unsigned CachedFieldIndex : 31;
2031 /// \brief A pointer to either the in-class initializer for this field (if
2032 /// the boolean value is false), or the bit width expression for this bit
2033 /// field (if the boolean value is true).
2035 /// We can safely combine these two because in-class initializers are not
2036 /// permitted for bit-fields.
2038 /// If the boolean is false and the initializer is null, then this field has
2039 /// an in-class initializer which has not yet been parsed and attached.
2040 llvm::PointerIntPair<Expr *, 1, bool> InitializerOrBitWidth;
2042 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2043 SourceLocation IdLoc, IdentifierInfo *Id,
2044 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2046 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2047 Mutable(Mutable), CachedFieldIndex(0),
2048 InitializerOrBitWidth(BW, !HasInit) {
2049 assert(!(BW && HasInit) && "got initializer for bitfield");
2053 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2054 SourceLocation StartLoc, SourceLocation IdLoc,
2055 IdentifierInfo *Id, QualType T,
2056 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2059 /// getFieldIndex - Returns the index of this field within its record,
2060 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2061 unsigned getFieldIndex() const;
2063 /// isMutable - Determines whether this field is mutable (C++ only).
2064 bool isMutable() const { return Mutable; }
2066 /// \brief Set whether this field is mutable (C++ only).
2067 void setMutable(bool M) { Mutable = M; }
2069 /// isBitfield - Determines whether this field is a bitfield.
2070 bool isBitField() const {
2071 return InitializerOrBitWidth.getInt() && InitializerOrBitWidth.getPointer();
2074 /// @brief Determines whether this is an unnamed bitfield.
2075 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2077 /// isAnonymousStructOrUnion - Determines whether this field is a
2078 /// representative for an anonymous struct or union. Such fields are
2079 /// unnamed and are implicitly generated by the implementation to
2080 /// store the data for the anonymous union or struct.
2081 bool isAnonymousStructOrUnion() const;
2083 Expr *getBitWidth() const {
2084 return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2086 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2087 void setBitWidth(Expr *BW) {
2088 assert(!InitializerOrBitWidth.getPointer() &&
2089 "bit width or initializer already set");
2090 InitializerOrBitWidth.setPointer(BW);
2091 InitializerOrBitWidth.setInt(1);
2093 /// removeBitWidth - Remove the bitfield width from this member.
2094 void removeBitWidth() {
2095 assert(isBitField() && "no bit width to remove");
2096 InitializerOrBitWidth.setPointer(0);
2099 /// hasInClassInitializer - Determine whether this member has a C++0x in-class
2101 bool hasInClassInitializer() const {
2102 return !InitializerOrBitWidth.getInt();
2104 /// getInClassInitializer - Get the C++0x in-class initializer for this
2105 /// member, or null if one has not been set. If a valid declaration has an
2106 /// in-class initializer, but this returns null, then we have not parsed and
2107 /// attached it yet.
2108 Expr *getInClassInitializer() const {
2109 return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2111 /// setInClassInitializer - Set the C++0x in-class initializer for this member.
2112 void setInClassInitializer(Expr *Init);
2113 /// removeInClassInitializer - Remove the C++0x in-class initializer from this
2115 void removeInClassInitializer() {
2116 assert(!InitializerOrBitWidth.getInt() && "no initializer to remove");
2117 InitializerOrBitWidth.setPointer(0);
2118 InitializerOrBitWidth.setInt(1);
2121 /// getParent - Returns the parent of this field declaration, which
2122 /// is the struct in which this method is defined.
2123 const RecordDecl *getParent() const {
2124 return cast<RecordDecl>(getDeclContext());
2127 RecordDecl *getParent() {
2128 return cast<RecordDecl>(getDeclContext());
2131 SourceRange getSourceRange() const;
2133 // Implement isa/cast/dyncast/etc.
2134 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2135 static bool classof(const FieldDecl *D) { return true; }
2136 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2139 /// EnumConstantDecl - An instance of this object exists for each enum constant
2140 /// that is defined. For example, in "enum X {a,b}", each of a/b are
2141 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2142 /// TagType for the X EnumDecl.
2143 class EnumConstantDecl : public ValueDecl {
2144 Stmt *Init; // an integer constant expression
2145 llvm::APSInt Val; // The value.
2147 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2148 IdentifierInfo *Id, QualType T, Expr *E,
2149 const llvm::APSInt &V)
2150 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2154 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2155 SourceLocation L, IdentifierInfo *Id,
2156 QualType T, Expr *E,
2157 const llvm::APSInt &V);
2159 const Expr *getInitExpr() const { return (const Expr*) Init; }
2160 Expr *getInitExpr() { return (Expr*) Init; }
2161 const llvm::APSInt &getInitVal() const { return Val; }
2163 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2164 void setInitVal(const llvm::APSInt &V) { Val = V; }
2166 SourceRange getSourceRange() const;
2168 // Implement isa/cast/dyncast/etc.
2169 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2170 static bool classof(const EnumConstantDecl *D) { return true; }
2171 static bool classofKind(Kind K) { return K == EnumConstant; }
2173 friend class StmtIteratorBase;
2176 /// IndirectFieldDecl - An instance of this class is created to represent a
2177 /// field injected from an anonymous union/struct into the parent scope.
2178 /// IndirectFieldDecl are always implicit.
2179 class IndirectFieldDecl : public ValueDecl {
2180 NamedDecl **Chaining;
2181 unsigned ChainingSize;
2183 IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2184 DeclarationName N, QualType T,
2185 NamedDecl **CH, unsigned CHS)
2186 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2189 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2190 SourceLocation L, IdentifierInfo *Id,
2191 QualType T, NamedDecl **CH, unsigned CHS);
2193 typedef NamedDecl * const *chain_iterator;
2194 chain_iterator chain_begin() const { return Chaining; }
2195 chain_iterator chain_end() const { return Chaining+ChainingSize; }
2197 unsigned getChainingSize() const { return ChainingSize; }
2199 FieldDecl *getAnonField() const {
2200 assert(ChainingSize >= 2);
2201 return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2204 VarDecl *getVarDecl() const {
2205 assert(ChainingSize >= 2);
2206 return dyn_cast<VarDecl>(*chain_begin());
2209 // Implement isa/cast/dyncast/etc.
2210 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2211 static bool classof(const IndirectFieldDecl *D) { return true; }
2212 static bool classofKind(Kind K) { return K == IndirectField; }
2213 friend class ASTDeclReader;
2216 /// TypeDecl - Represents a declaration of a type.
2218 class TypeDecl : public NamedDecl {
2219 /// TypeForDecl - This indicates the Type object that represents
2220 /// this TypeDecl. It is a cache maintained by
2221 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2222 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2223 mutable const Type *TypeForDecl;
2224 /// LocStart - The start of the source range for this declaration.
2225 SourceLocation LocStart;
2226 friend class ASTContext;
2227 friend class DeclContext;
2228 friend class TagDecl;
2229 friend class TemplateTypeParmDecl;
2230 friend class TagType;
2233 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2234 SourceLocation StartL = SourceLocation())
2235 : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2238 // Low-level accessor
2239 const Type *getTypeForDecl() const { return TypeForDecl; }
2240 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2242 SourceLocation getLocStart() const { return LocStart; }
2243 void setLocStart(SourceLocation L) { LocStart = L; }
2244 virtual SourceRange getSourceRange() const {
2245 if (LocStart.isValid())
2246 return SourceRange(LocStart, getLocation());
2248 return SourceRange(getLocation());
2251 // Implement isa/cast/dyncast/etc.
2252 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2253 static bool classof(const TypeDecl *D) { return true; }
2254 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2258 /// Base class for declarations which introduce a typedef-name.
2259 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2260 /// UnderlyingType - This is the type the typedef is set to.
2261 TypeSourceInfo *TInfo;
2264 TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2265 SourceLocation IdLoc, IdentifierInfo *Id,
2266 TypeSourceInfo *TInfo)
2267 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
2269 typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2270 virtual TypedefNameDecl *getNextRedeclaration() {
2271 return RedeclLink.getNext();
2275 typedef redeclarable_base::redecl_iterator redecl_iterator;
2276 redecl_iterator redecls_begin() const {
2277 return redeclarable_base::redecls_begin();
2279 redecl_iterator redecls_end() const {
2280 return redeclarable_base::redecls_end();
2283 TypeSourceInfo *getTypeSourceInfo() const {
2287 /// Retrieves the canonical declaration of this typedef-name.
2288 TypedefNameDecl *getCanonicalDecl() {
2289 return getFirstDeclaration();
2291 const TypedefNameDecl *getCanonicalDecl() const {
2292 return getFirstDeclaration();
2295 QualType getUnderlyingType() const {
2296 return TInfo->getType();
2298 void setTypeSourceInfo(TypeSourceInfo *newType) {
2302 // Implement isa/cast/dyncast/etc.
2303 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2304 static bool classof(const TypedefNameDecl *D) { return true; }
2305 static bool classofKind(Kind K) {
2306 return K >= firstTypedefName && K <= lastTypedefName;
2310 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2312 class TypedefDecl : public TypedefNameDecl {
2313 TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2314 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2315 : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2318 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2319 SourceLocation StartLoc, SourceLocation IdLoc,
2320 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2322 SourceRange getSourceRange() const;
2324 // Implement isa/cast/dyncast/etc.
2325 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2326 static bool classof(const TypedefDecl *D) { return true; }
2327 static bool classofKind(Kind K) { return K == Typedef; }
2330 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2331 /// alias-declaration.
2332 class TypeAliasDecl : public TypedefNameDecl {
2333 TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2334 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2335 : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2338 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2339 SourceLocation StartLoc, SourceLocation IdLoc,
2340 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2342 SourceRange getSourceRange() const;
2344 // Implement isa/cast/dyncast/etc.
2345 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2346 static bool classof(const TypeAliasDecl *D) { return true; }
2347 static bool classofKind(Kind K) { return K == TypeAlias; }
2350 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2352 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2354 // This is really ugly.
2355 typedef TagTypeKind TagKind;
2358 // FIXME: This can be packed into the bitfields in Decl.
2359 /// TagDeclKind - The TagKind enum.
2360 unsigned TagDeclKind : 2;
2362 /// IsCompleteDefinition - True if this is a definition ("struct foo
2363 /// {};"), false if it is a declaration ("struct foo;"). It is not
2364 /// a definition until the definition has been fully processed.
2365 bool IsCompleteDefinition : 1;
2367 /// IsBeingDefined - True if this is currently being defined.
2368 bool IsBeingDefined : 1;
2370 /// IsEmbeddedInDeclarator - True if this tag declaration is
2371 /// "embedded" (i.e., defined or declared for the very first time)
2372 /// in the syntax of a declarator.
2373 bool IsEmbeddedInDeclarator : 1;
2375 /// /brief True if this tag is free standing, e.g. "struct foo;".
2376 bool IsFreeStanding : 1;
2379 // These are used by (and only defined for) EnumDecl.
2380 unsigned NumPositiveBits : 8;
2381 unsigned NumNegativeBits : 8;
2383 /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2384 /// possible in C++0x mode.
2386 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2387 /// then this is true if the scoped enum was declared using the class
2388 /// tag, false if it was declared with the struct tag. No meaning is
2389 /// associated if this tag declaration is not a scoped enum.
2390 bool IsScopedUsingClassTag : 1;
2392 /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2393 /// possible in C++0x mode.
2397 SourceLocation RBraceLoc;
2399 // A struct representing syntactic qualifier info,
2400 // to be used for the (uncommon) case of out-of-line declarations.
2401 typedef QualifierInfo ExtInfo;
2403 /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
2404 /// is qualified, it points to the qualifier info (nns and range);
2405 /// otherwise, if the tag declaration is anonymous and it is part of
2406 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2407 /// otherwise, it is a null (TypedefNameDecl) pointer.
2408 llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
2410 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
2411 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
2412 const ExtInfo *getExtInfo() const {
2413 return TypedefNameDeclOrQualifier.get<ExtInfo*>();
2417 TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2418 SourceLocation L, IdentifierInfo *Id,
2419 TagDecl *PrevDecl, SourceLocation StartL)
2420 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
2421 TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
2422 assert((DK != Enum || TK == TTK_Enum) &&
2423 "EnumDecl not matched with TTK_Enum");
2425 IsCompleteDefinition = false;
2426 IsBeingDefined = false;
2427 IsEmbeddedInDeclarator = false;
2428 IsFreeStanding = false;
2429 setPreviousDeclaration(PrevDecl);
2432 typedef Redeclarable<TagDecl> redeclarable_base;
2433 virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
2435 /// @brief Completes the definition of this tag declaration.
2437 /// This is a helper function for derived classes.
2438 void completeDefinition();
2441 typedef redeclarable_base::redecl_iterator redecl_iterator;
2442 redecl_iterator redecls_begin() const {
2443 return redeclarable_base::redecls_begin();
2445 redecl_iterator redecls_end() const {
2446 return redeclarable_base::redecls_end();
2449 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2450 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2452 /// getInnerLocStart - Return SourceLocation representing start of source
2453 /// range ignoring outer template declarations.
2454 SourceLocation getInnerLocStart() const { return getLocStart(); }
2456 /// getOuterLocStart - Return SourceLocation representing start of source
2457 /// range taking into account any outer template declarations.
2458 SourceLocation getOuterLocStart() const;
2459 virtual SourceRange getSourceRange() const;
2461 virtual TagDecl* getCanonicalDecl();
2462 const TagDecl* getCanonicalDecl() const {
2463 return const_cast<TagDecl*>(this)->getCanonicalDecl();
2466 /// isThisDeclarationADefinition() - Return true if this declaration
2467 /// is a completion definintion of the type. Provided for consistency.
2468 bool isThisDeclarationADefinition() const {
2469 return isCompleteDefinition();
2472 /// isCompleteDefinition - Return true if this decl has its body
2473 /// fully specified.
2474 bool isCompleteDefinition() const {
2475 return IsCompleteDefinition;
2478 /// isBeingDefined - Return true if this decl is currently being defined.
2479 bool isBeingDefined() const {
2480 return IsBeingDefined;
2483 bool isEmbeddedInDeclarator() const {
2484 return IsEmbeddedInDeclarator;
2486 void setEmbeddedInDeclarator(bool isInDeclarator) {
2487 IsEmbeddedInDeclarator = isInDeclarator;
2490 bool isFreeStanding() const { return IsFreeStanding; }
2491 void setFreeStanding(bool isFreeStanding = true) {
2492 IsFreeStanding = isFreeStanding;
2495 /// \brief Whether this declaration declares a type that is
2496 /// dependent, i.e., a type that somehow depends on template
2498 bool isDependentType() const { return isDependentContext(); }
2500 /// @brief Starts the definition of this tag declaration.
2502 /// This method should be invoked at the beginning of the definition
2503 /// of this tag declaration. It will set the tag type into a state
2504 /// where it is in the process of being defined.
2505 void startDefinition();
2507 /// getDefinition - Returns the TagDecl that actually defines this
2508 /// struct/union/class/enum. When determining whether or not a
2509 /// struct/union/class/enum has a definition, one should use this
2510 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
2511 /// whether or not a specific TagDecl is defining declaration, not
2512 /// whether or not the struct/union/class/enum type is defined.
2513 /// This method returns NULL if there is no TagDecl that defines
2514 /// the struct/union/class/enum.
2515 TagDecl *getDefinition() const;
2517 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2519 const char *getKindName() const {
2520 return TypeWithKeyword::getTagTypeKindName(getTagKind());
2523 TagKind getTagKind() const {
2524 return TagKind(TagDeclKind);
2527 void setTagKind(TagKind TK) { TagDeclKind = TK; }
2529 bool isStruct() const { return getTagKind() == TTK_Struct; }
2530 bool isClass() const { return getTagKind() == TTK_Class; }
2531 bool isUnion() const { return getTagKind() == TTK_Union; }
2532 bool isEnum() const { return getTagKind() == TTK_Enum; }
2534 TypedefNameDecl *getTypedefNameForAnonDecl() const {
2535 return hasExtInfo() ? 0 : TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
2538 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2540 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2541 /// declaration, if it was present in the source.
2542 NestedNameSpecifier *getQualifier() const {
2543 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2547 /// \brief Retrieve the nested-name-specifier (with source-location
2548 /// information) that qualifies the name of this declaration, if it was
2549 /// present in the source.
2550 NestedNameSpecifierLoc getQualifierLoc() const {
2551 return hasExtInfo() ? getExtInfo()->QualifierLoc
2552 : NestedNameSpecifierLoc();
2555 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2557 unsigned getNumTemplateParameterLists() const {
2558 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2560 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2561 assert(i < getNumTemplateParameterLists());
2562 return getExtInfo()->TemplParamLists[i];
2564 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2565 TemplateParameterList **TPLists);
2567 // Implement isa/cast/dyncast/etc.
2568 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2569 static bool classof(const TagDecl *D) { return true; }
2570 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2572 static DeclContext *castToDeclContext(const TagDecl *D) {
2573 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2575 static TagDecl *castFromDeclContext(const DeclContext *DC) {
2576 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2579 friend class ASTDeclReader;
2580 friend class ASTDeclWriter;
2583 /// EnumDecl - Represents an enum. As an extension, we allow forward-declared
2585 class EnumDecl : public TagDecl {
2586 /// IntegerType - This represent the integer type that the enum corresponds
2587 /// to for code generation purposes. Note that the enumerator constants may
2588 /// have a different type than this does.
2590 /// If the underlying integer type was explicitly stated in the source
2591 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2592 /// was automatically deduced somehow, and this is a Type*.
2594 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2595 /// some cases it won't.
2597 /// The underlying type of an enumeration never has any qualifiers, so
2598 /// we can get away with just storing a raw Type*, and thus save an
2599 /// extra pointer when TypeSourceInfo is needed.
2601 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2603 /// PromotionType - The integer type that values of this type should
2604 /// promote to. In C, enumerators are generally of an integer type
2605 /// directly, but gcc-style large enumerators (and all enumerators
2606 /// in C++) are of the enum type instead.
2607 QualType PromotionType;
2609 /// \brief If the enumeration was instantiated from an enumeration
2610 /// within a class or function template, this pointer refers to the
2611 /// enumeration declared within the template.
2612 EnumDecl *InstantiatedFrom;
2614 // The number of positive and negative bits required by the
2615 // enumerators are stored in the SubclassBits field.
2618 NumBitsMask = (1 << NumBitsWidth) - 1
2621 EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2622 IdentifierInfo *Id, EnumDecl *PrevDecl,
2623 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2624 : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2625 InstantiatedFrom(0) {
2626 assert(Scoped || !ScopedUsingClassTag);
2627 IntegerType = (const Type*)0;
2628 NumNegativeBits = 0;
2629 NumPositiveBits = 0;
2631 IsScopedUsingClassTag = ScopedUsingClassTag;
2635 EnumDecl *getCanonicalDecl() {
2636 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2638 const EnumDecl *getCanonicalDecl() const {
2639 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2642 const EnumDecl *getPreviousDeclaration() const {
2643 return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
2645 EnumDecl *getPreviousDeclaration() {
2646 return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
2649 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2650 SourceLocation StartLoc, SourceLocation IdLoc,
2651 IdentifierInfo *Id, EnumDecl *PrevDecl,
2652 bool IsScoped, bool IsScopedUsingClassTag,
2654 static EnumDecl *Create(ASTContext &C, EmptyShell Empty);
2656 /// completeDefinition - When created, the EnumDecl corresponds to a
2657 /// forward-declared enum. This method is used to mark the
2658 /// declaration as being defined; it's enumerators have already been
2659 /// added (via DeclContext::addDecl). NewType is the new underlying
2660 /// type of the enumeration type.
2661 void completeDefinition(QualType NewType,
2662 QualType PromotionType,
2663 unsigned NumPositiveBits,
2664 unsigned NumNegativeBits);
2666 // enumerator_iterator - Iterates through the enumerators of this
2668 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2670 enumerator_iterator enumerator_begin() const {
2671 const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
2674 return enumerator_iterator(E->decls_begin());
2677 enumerator_iterator enumerator_end() const {
2678 const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition());
2681 return enumerator_iterator(E->decls_end());
2684 /// getPromotionType - Return the integer type that enumerators
2685 /// should promote to.
2686 QualType getPromotionType() const { return PromotionType; }
2688 /// \brief Set the promotion type.
2689 void setPromotionType(QualType T) { PromotionType = T; }
2691 /// getIntegerType - Return the integer type this enum decl corresponds to.
2692 /// This returns a null qualtype for an enum forward definition.
2693 QualType getIntegerType() const {
2696 if (const Type* T = IntegerType.dyn_cast<const Type*>())
2697 return QualType(T, 0);
2698 return IntegerType.get<TypeSourceInfo*>()->getType();
2701 /// \brief Set the underlying integer type.
2702 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2704 /// \brief Set the underlying integer type source info.
2705 void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2707 /// \brief Return the type source info for the underlying integer type,
2708 /// if no type source info exists, return 0.
2709 TypeSourceInfo* getIntegerTypeSourceInfo() const {
2710 return IntegerType.dyn_cast<TypeSourceInfo*>();
2713 /// \brief Returns the width in bits required to store all the
2714 /// non-negative enumerators of this enum.
2715 unsigned getNumPositiveBits() const {
2716 return NumPositiveBits;
2718 void setNumPositiveBits(unsigned Num) {
2719 NumPositiveBits = Num;
2720 assert(NumPositiveBits == Num && "can't store this bitcount");
2723 /// \brief Returns the width in bits required to store all the
2724 /// negative enumerators of this enum. These widths include
2725 /// the rightmost leading 1; that is:
2727 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
2728 /// ------------------------ ------- -----------------
2732 unsigned getNumNegativeBits() const {
2733 return NumNegativeBits;
2735 void setNumNegativeBits(unsigned Num) {
2736 NumNegativeBits = Num;
2739 /// \brief Returns true if this is a C++0x scoped enumeration.
2740 bool isScoped() const {
2744 /// \brief Returns true if this is a C++0x scoped enumeration.
2745 bool isScopedUsingClassTag() const {
2746 return IsScopedUsingClassTag;
2749 /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2751 bool isFixed() const {
2755 /// \brief Returns true if this can be considered a complete type.
2756 bool isComplete() const {
2757 return isCompleteDefinition() || isFixed();
2760 /// \brief Returns the enumeration (declared within the template)
2761 /// from which this enumeration type was instantiated, or NULL if
2762 /// this enumeration was not instantiated from any template.
2763 EnumDecl *getInstantiatedFromMemberEnum() const {
2764 return InstantiatedFrom;
2767 void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; }
2769 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2770 static bool classof(const EnumDecl *D) { return true; }
2771 static bool classofKind(Kind K) { return K == Enum; }
2773 friend class ASTDeclReader;
2777 /// RecordDecl - Represents a struct/union/class. For example:
2778 /// struct X; // Forward declaration, no "body".
2779 /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
2780 /// This decl will be marked invalid if *any* members are invalid.
2782 class RecordDecl : public TagDecl {
2783 // FIXME: This can be packed into the bitfields in Decl.
2784 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2785 /// array member (e.g. int X[]) or if this union contains a struct that does.
2786 /// If so, this cannot be contained in arrays or other structs as a member.
2787 bool HasFlexibleArrayMember : 1;
2789 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2791 bool AnonymousStructOrUnion : 1;
2793 /// HasObjectMember - This is true if this struct has at least one member
2794 /// containing an object.
2795 bool HasObjectMember : 1;
2797 /// \brief Whether the field declarations of this record have been loaded
2798 /// from external storage. To avoid unnecessary deserialization of
2799 /// methods/nested types we allow deserialization of just the fields
2801 mutable bool LoadedFieldsFromExternalStorage : 1;
2802 friend class DeclContext;
2805 RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2806 SourceLocation StartLoc, SourceLocation IdLoc,
2807 IdentifierInfo *Id, RecordDecl *PrevDecl);
2810 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2811 SourceLocation StartLoc, SourceLocation IdLoc,
2812 IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
2813 static RecordDecl *Create(const ASTContext &C, EmptyShell Empty);
2815 const RecordDecl *getPreviousDeclaration() const {
2816 return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
2818 RecordDecl *getPreviousDeclaration() {
2819 return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
2822 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
2823 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2825 /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2826 /// or union. To be an anonymous struct or union, it must have been
2827 /// declared without a name and there must be no objects of this
2828 /// type declared, e.g.,
2830 /// union { int i; float f; };
2832 /// is an anonymous union but neither of the following are:
2834 /// union X { int i; float f; };
2835 /// union { int i; float f; } obj;
2837 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
2838 void setAnonymousStructOrUnion(bool Anon) {
2839 AnonymousStructOrUnion = Anon;
2842 bool hasObjectMember() const { return HasObjectMember; }
2843 void setHasObjectMember (bool val) { HasObjectMember = val; }
2845 /// \brief Determines whether this declaration represents the
2846 /// injected class name.
2848 /// The injected class name in C++ is the name of the class that
2849 /// appears inside the class itself. For example:
2853 /// // C is implicitly declared here as a synonym for the class name.
2856 /// C::C c; // same as "C c;"
2858 bool isInjectedClassName() const;
2860 /// getDefinition - Returns the RecordDecl that actually defines
2861 /// this struct/union/class. When determining whether or not a
2862 /// struct/union/class is completely defined, one should use this
2863 /// method as opposed to 'isCompleteDefinition'.
2864 /// 'isCompleteDefinition' indicates whether or not a specific
2865 /// RecordDecl is a completed definition, not whether or not the
2866 /// record type is defined. This method returns NULL if there is
2867 /// no RecordDecl that defines the struct/union/tag.
2868 RecordDecl *getDefinition() const {
2869 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2872 // Iterator access to field members. The field iterator only visits
2873 // the non-static data members of this class, ignoring any static
2874 // data members, functions, constructors, destructors, etc.
2875 typedef specific_decl_iterator<FieldDecl> field_iterator;
2877 field_iterator field_begin() const;
2879 field_iterator field_end() const {
2880 return field_iterator(decl_iterator());
2883 // field_empty - Whether there are any fields (non-static data
2884 // members) in this record.
2885 bool field_empty() const {
2886 return field_begin() == field_end();
2889 /// completeDefinition - Notes that the definition of this type is
2891 virtual void completeDefinition();
2893 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2894 static bool classof(const RecordDecl *D) { return true; }
2895 static bool classofKind(Kind K) {
2896 return K >= firstRecord && K <= lastRecord;
2900 /// \brief Deserialize just the fields.
2901 void LoadFieldsFromExternalStorage() const;
2904 class FileScopeAsmDecl : public Decl {
2905 StringLiteral *AsmString;
2906 SourceLocation RParenLoc;
2907 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
2908 SourceLocation StartL, SourceLocation EndL)
2909 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
2911 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
2912 StringLiteral *Str, SourceLocation AsmLoc,
2913 SourceLocation RParenLoc);
2915 SourceLocation getAsmLoc() const { return getLocation(); }
2916 SourceLocation getRParenLoc() const { return RParenLoc; }
2917 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2918 SourceRange getSourceRange() const {
2919 return SourceRange(getAsmLoc(), getRParenLoc());
2922 const StringLiteral *getAsmString() const { return AsmString; }
2923 StringLiteral *getAsmString() { return AsmString; }
2924 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
2926 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2927 static bool classof(const FileScopeAsmDecl *D) { return true; }
2928 static bool classofKind(Kind K) { return K == FileScopeAsm; }
2931 /// BlockDecl - This represents a block literal declaration, which is like an
2932 /// unnamed FunctionDecl. For example:
2933 /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
2935 class BlockDecl : public Decl, public DeclContext {
2937 /// A class which contains all the information about a particular
2945 /// The variable being captured.
2946 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
2948 /// The copy expression, expressed in terms of a DeclRef (or
2949 /// BlockDeclRef) to the captured variable. Only required if the
2950 /// variable has a C++ class type.
2954 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
2955 : VariableAndFlags(variable,
2956 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
2959 /// The variable being captured.
2960 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
2962 /// Whether this is a "by ref" capture, i.e. a capture of a __block
2964 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
2966 /// Whether this is a nested capture, i.e. the variable captured
2967 /// is not from outside the immediately enclosing function/block.
2968 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
2970 bool hasCopyExpr() const { return CopyExpr != 0; }
2971 Expr *getCopyExpr() const { return CopyExpr; }
2972 void setCopyExpr(Expr *e) { CopyExpr = e; }
2976 // FIXME: This can be packed into the bitfields in Decl.
2977 bool IsVariadic : 1;
2978 bool CapturesCXXThis : 1;
2979 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
2980 /// parameters of this function. This is null if a prototype or if there are
2982 ParmVarDecl **ParamInfo;
2986 TypeSourceInfo *SignatureAsWritten;
2989 unsigned NumCaptures;
2992 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
2993 : Decl(Block, DC, CaretLoc), DeclContext(Block),
2994 IsVariadic(false), CapturesCXXThis(false),
2995 ParamInfo(0), NumParams(0), Body(0),
2996 SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
2999 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3001 SourceLocation getCaretLocation() const { return getLocation(); }
3003 bool isVariadic() const { return IsVariadic; }
3004 void setIsVariadic(bool value) { IsVariadic = value; }
3006 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3007 Stmt *getBody() const { return (Stmt*) Body; }
3008 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3010 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3011 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3013 // Iterator access to formal parameters.
3014 unsigned param_size() const { return getNumParams(); }
3015 typedef ParmVarDecl **param_iterator;
3016 typedef ParmVarDecl * const *param_const_iterator;
3018 bool param_empty() const { return NumParams == 0; }
3019 param_iterator param_begin() { return ParamInfo; }
3020 param_iterator param_end() { return ParamInfo+param_size(); }
3022 param_const_iterator param_begin() const { return ParamInfo; }
3023 param_const_iterator param_end() const { return ParamInfo+param_size(); }
3025 unsigned getNumParams() const { return NumParams; }
3026 const ParmVarDecl *getParamDecl(unsigned i) const {
3027 assert(i < getNumParams() && "Illegal param #");
3028 return ParamInfo[i];
3030 ParmVarDecl *getParamDecl(unsigned i) {
3031 assert(i < getNumParams() && "Illegal param #");
3032 return ParamInfo[i];
3034 void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
3036 /// hasCaptures - True if this block (or its nested blocks) captures
3037 /// anything of local storage from its enclosing scopes.
3038 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3040 /// getNumCaptures - Returns the number of captured variables.
3041 /// Does not include an entry for 'this'.
3042 unsigned getNumCaptures() const { return NumCaptures; }
3044 typedef const Capture *capture_iterator;
3045 typedef const Capture *capture_const_iterator;
3046 capture_iterator capture_begin() { return Captures; }
3047 capture_iterator capture_end() { return Captures + NumCaptures; }
3048 capture_const_iterator capture_begin() const { return Captures; }
3049 capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3051 bool capturesCXXThis() const { return CapturesCXXThis; }
3053 bool capturesVariable(const VarDecl *var) const;
3055 void setCaptures(ASTContext &Context,
3056 const Capture *begin,
3058 bool capturesCXXThis);
3060 virtual SourceRange getSourceRange() const;
3062 // Implement isa/cast/dyncast/etc.
3063 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3064 static bool classof(const BlockDecl *D) { return true; }
3065 static bool classofKind(Kind K) { return K == Block; }
3066 static DeclContext *castToDeclContext(const BlockDecl *D) {
3067 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3069 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3070 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3074 /// Insertion operator for diagnostics. This allows sending NamedDecl's
3075 /// into a diagnostic with <<.
3076 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3077 const NamedDecl* ND) {
3078 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3079 DiagnosticsEngine::ak_nameddecl);
3083 template<typename decl_type>
3084 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3085 // Note: This routine is implemented here because we need both NamedDecl
3086 // and Redeclarable to be defined.
3091 // Point to previous. Make sure that this is actually the most recent
3092 // redeclaration, or we can build invalid chains. If the most recent
3093 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3094 RedeclLink = PreviousDeclLink(llvm::cast<decl_type>(
3095 PrevDecl->getMostRecentDeclaration()));
3096 First = PrevDecl->getFirstDeclaration();
3097 assert(First->RedeclLink.NextIsLatest() && "Expected first");
3100 First = static_cast<decl_type*>(this);
3103 // First one will point to this one as latest.
3104 First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3105 if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
3106 ND->ClearLinkageCache();
3109 } // end namespace clang