• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Decl.h - Classes for representing declarations ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the Decl subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_AST_DECL_H
15 #define LLVM_CLANG_AST_DECL_H
16 
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"
25 #include "llvm/Support/Compiler.h"
26 
27 namespace clang {
28 class CXXTemporary;
29 class Expr;
30 class FunctionTemplateDecl;
31 class Stmt;
32 class CompoundStmt;
33 class StringLiteral;
34 class NestedNameSpecifier;
35 class TemplateParameterList;
36 class TemplateArgumentList;
37 struct ASTTemplateArgumentListInfo;
38 class MemberSpecializationInfo;
39 class FunctionTemplateSpecializationInfo;
40 class DependentFunctionTemplateSpecializationInfo;
41 class TypeLoc;
42 class UnresolvedSetImpl;
43 class LabelStmt;
44 class Module;
45 
46 /// \brief A container of type source information.
47 ///
48 /// A client can read the relevant info using TypeLoc wrappers, e.g:
49 /// @code
50 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
51 /// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL))
52 ///   PL->getStarLoc().print(OS, SrcMgr);
53 /// @endcode
54 ///
55 class TypeSourceInfo {
56   QualType Ty;
57   // Contains a memory block after the class, used for type source information,
58   // allocated by ASTContext.
59   friend class ASTContext;
TypeSourceInfo(QualType ty)60   TypeSourceInfo(QualType ty) : Ty(ty) { }
61 public:
62   /// \brief Return the type wrapped by this type source info.
getType()63   QualType getType() const { return Ty; }
64 
65   /// \brief Return the TypeLoc wrapper for the type source info.
66   TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
67 
68   /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
overrideType(QualType T)69   void overrideType(QualType T) { Ty = T; }
70 };
71 
72 /// TranslationUnitDecl - The top declaration context.
73 class TranslationUnitDecl : public Decl, public DeclContext {
74   virtual void anchor();
75   ASTContext &Ctx;
76 
77   /// The (most recently entered) anonymous namespace for this
78   /// translation unit, if one has been created.
79   NamespaceDecl *AnonymousNamespace;
80 
TranslationUnitDecl(ASTContext & ctx)81   explicit TranslationUnitDecl(ASTContext &ctx)
82     : Decl(TranslationUnit, 0, SourceLocation()),
83       DeclContext(TranslationUnit),
84       Ctx(ctx), AnonymousNamespace(0) {}
85 public:
getASTContext()86   ASTContext &getASTContext() const { return Ctx; }
87 
getAnonymousNamespace()88   NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
setAnonymousNamespace(NamespaceDecl * D)89   void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
90 
91   static TranslationUnitDecl *Create(ASTContext &C);
92   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)93   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const TranslationUnitDecl * D)94   static bool classof(const TranslationUnitDecl *D) { return true; }
classofKind(Kind K)95   static bool classofKind(Kind K) { return K == TranslationUnit; }
castToDeclContext(const TranslationUnitDecl * D)96   static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
97     return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
98   }
castFromDeclContext(const DeclContext * DC)99   static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
100     return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
101   }
102 };
103 
104 /// NamedDecl - This represents a decl with a name.  Many decls have names such
105 /// as ObjCMethodDecl, but not @class, etc.
106 class NamedDecl : public Decl {
107   virtual void anchor();
108   /// Name - The name of this declaration, which is typically a normal
109   /// identifier but may also be a special kind of name (C++
110   /// constructor, Objective-C selector, etc.)
111   DeclarationName Name;
112 
113 private:
114   NamedDecl *getUnderlyingDeclImpl();
115 
116 protected:
NamedDecl(Kind DK,DeclContext * DC,SourceLocation L,DeclarationName N)117   NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
118     : Decl(DK, DC, L), Name(N) { }
119 
120 public:
121   /// getIdentifier - Get the identifier that names this declaration,
122   /// if there is one. This will return NULL if this declaration has
123   /// no name (e.g., for an unnamed class) or if the name is a special
124   /// name (C++ constructor, Objective-C selector, etc.).
getIdentifier()125   IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
126 
127   /// getName - Get the name of identifier for this declaration as a StringRef.
128   /// This requires that the declaration have a name and that it be a simple
129   /// identifier.
getName()130   StringRef getName() const {
131     assert(Name.isIdentifier() && "Name is not a simple identifier");
132     return getIdentifier() ? getIdentifier()->getName() : "";
133   }
134 
135   /// getNameAsString - Get a human-readable name for the declaration, even if
136   /// it is one of the special kinds of names (C++ constructor, Objective-C
137   /// selector, etc).  Creating this name requires expensive string
138   /// manipulation, so it should be called only when performance doesn't matter.
139   /// For simple declarations, getNameAsCString() should suffice.
140   //
141   // FIXME: This function should be renamed to indicate that it is not just an
142   // alternate form of getName(), and clients should move as appropriate.
143   //
144   // FIXME: Deprecated, move clients to getName().
getNameAsString()145   std::string getNameAsString() const { return Name.getAsString(); }
146 
printName(raw_ostream & os)147   void printName(raw_ostream &os) const { return Name.printName(os); }
148 
149   /// getDeclName - Get the actual, stored name of the declaration,
150   /// which may be a special name.
getDeclName()151   DeclarationName getDeclName() const { return Name; }
152 
153   /// \brief Set the name of this declaration.
setDeclName(DeclarationName N)154   void setDeclName(DeclarationName N) { Name = N; }
155 
156   /// getQualifiedNameAsString - Returns human-readable qualified name for
157   /// declaration, like A::B::i, for i being member of namespace A::B.
158   /// If declaration is not member of context which can be named (record,
159   /// namespace), it will return same result as getNameAsString().
160   /// Creating this name is expensive, so it should be called only when
161   /// performance doesn't matter.
162   std::string getQualifiedNameAsString() const;
163   std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const;
164 
165   /// getNameForDiagnostic - Appends a human-readable name for this
166   /// declaration into the given string.
167   ///
168   /// This is the method invoked by Sema when displaying a NamedDecl
169   /// in a diagnostic.  It does not necessarily produce the same
170   /// result as getNameAsString(); for example, class template
171   /// specializations are printed with their template arguments.
172   ///
173   /// TODO: use an API that doesn't require so many temporary strings
getNameForDiagnostic(std::string & S,const PrintingPolicy & Policy,bool Qualified)174   virtual void getNameForDiagnostic(std::string &S,
175                                     const PrintingPolicy &Policy,
176                                     bool Qualified) const {
177     if (Qualified)
178       S += getQualifiedNameAsString(Policy);
179     else
180       S += getNameAsString();
181   }
182 
183   /// declarationReplaces - Determine whether this declaration, if
184   /// known to be well-formed within its context, will replace the
185   /// declaration OldD if introduced into scope. A declaration will
186   /// replace another declaration if, for example, it is a
187   /// redeclaration of the same variable or function, but not if it is
188   /// a declaration of a different kind (function vs. class) or an
189   /// overloaded function.
190   bool declarationReplaces(NamedDecl *OldD) const;
191 
192   /// \brief Determine whether this declaration has linkage.
193   bool hasLinkage() const;
194 
195   using Decl::isModulePrivate;
196   using Decl::setModulePrivate;
197 
198   /// \brief Determine whether this declaration is hidden from name lookup.
isHidden()199   bool isHidden() const { return Hidden; }
200 
201   /// \brief Determine whether this declaration is a C++ class member.
isCXXClassMember()202   bool isCXXClassMember() const {
203     const DeclContext *DC = getDeclContext();
204 
205     // C++0x [class.mem]p1:
206     //   The enumerators of an unscoped enumeration defined in
207     //   the class are members of the class.
208     // FIXME: support C++0x scoped enumerations.
209     if (isa<EnumDecl>(DC))
210       DC = DC->getParent();
211 
212     return DC->isRecord();
213   }
214 
215   /// \brief Determine whether the given declaration is an instance member of
216   /// a C++ class.
217   bool isCXXInstanceMember() const;
218 
219   class LinkageInfo {
220     Linkage linkage_;
221     Visibility visibility_;
222     bool explicit_;
223 
224   public:
LinkageInfo()225     LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility),
226                     explicit_(false) {}
LinkageInfo(Linkage L,Visibility V,bool E)227     LinkageInfo(Linkage L, Visibility V, bool E)
228       : linkage_(L), visibility_(V), explicit_(E) {}
229 
external()230     static LinkageInfo external() {
231       return LinkageInfo();
232     }
internal()233     static LinkageInfo internal() {
234       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
235     }
uniqueExternal()236     static LinkageInfo uniqueExternal() {
237       return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false);
238     }
none()239     static LinkageInfo none() {
240       return LinkageInfo(NoLinkage, DefaultVisibility, false);
241     }
242 
linkage()243     Linkage linkage() const { return linkage_; }
visibility()244     Visibility visibility() const { return visibility_; }
visibilityExplicit()245     bool visibilityExplicit() const { return explicit_; }
246 
setLinkage(Linkage L)247     void setLinkage(Linkage L) { linkage_ = L; }
setVisibility(Visibility V,bool E)248     void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; }
249 
mergeLinkage(Linkage L)250     void mergeLinkage(Linkage L) {
251       setLinkage(minLinkage(linkage(), L));
252     }
mergeLinkage(LinkageInfo Other)253     void mergeLinkage(LinkageInfo Other) {
254       mergeLinkage(Other.linkage());
255     }
256 
257     // Merge the visibility V giving preference to explicit ones.
258     // This is used, for example, when merging the visibility of a class
259     // down to one of its members. If the member has no explicit visibility,
260     // the class visibility wins.
261     void mergeVisibility(Visibility V, bool E = false) {
262       // If one has explicit visibility and the other doesn't, keep the
263       // explicit one.
264       if (visibilityExplicit() && !E)
265         return;
266       if (!visibilityExplicit() && E)
267         setVisibility(V, E);
268 
269       // If both are explicit or both are implicit, keep the minimum.
270       setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E);
271     }
272     // Merge the visibility V, keeping the most restrictive one.
273     // This is used for cases like merging the visibility of a template
274     // argument to an instantiation. If we already have a hidden class,
275     // no argument should give it default visibility.
276     void mergeVisibilityWithMin(Visibility V, bool E = false) {
277       // Never increase the visibility
278       if (visibility() < V)
279         return;
280 
281       // If this visibility is explicit, keep it.
282       if (visibilityExplicit() && !E)
283         return;
284       setVisibility(V, E);
285     }
mergeVisibility(LinkageInfo Other)286     void mergeVisibility(LinkageInfo Other) {
287       mergeVisibility(Other.visibility(), Other.visibilityExplicit());
288     }
mergeVisibilityWithMin(LinkageInfo Other)289     void mergeVisibilityWithMin(LinkageInfo Other) {
290       mergeVisibilityWithMin(Other.visibility(), Other.visibilityExplicit());
291     }
292 
merge(LinkageInfo Other)293     void merge(LinkageInfo Other) {
294       mergeLinkage(Other);
295       mergeVisibility(Other);
296     }
mergeWithMin(LinkageInfo Other)297     void mergeWithMin(LinkageInfo Other) {
298       mergeLinkage(Other);
299       mergeVisibilityWithMin(Other);
300     }
301 
merge(LinkageInfo L,LinkageInfo R)302     friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
303       L.merge(R);
304       return L;
305     }
306   };
307 
308   /// \brief Determine what kind of linkage this entity has.
309   Linkage getLinkage() const;
310 
311   /// \brief Determines the visibility of this entity.
getVisibility()312   Visibility getVisibility() const {
313     return getLinkageAndVisibility().visibility();
314   }
315 
316   /// \brief Determines the linkage and visibility of this entity.
317   LinkageInfo getLinkageAndVisibility() const;
318 
319   /// \brief If visibility was explicitly specified for this
320   /// declaration, return that visibility.
321   llvm::Optional<Visibility> getExplicitVisibility() const;
322 
323   /// \brief Clear the linkage cache in response to a change
324   /// to the declaration.
325   void ClearLinkageCache();
326 
327   /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
328   /// the underlying named decl.
getUnderlyingDecl()329   NamedDecl *getUnderlyingDecl() {
330     // Fast-path the common case.
331     if (this->getKind() != UsingShadow &&
332         this->getKind() != ObjCCompatibleAlias)
333       return this;
334 
335     return getUnderlyingDeclImpl();
336   }
getUnderlyingDecl()337   const NamedDecl *getUnderlyingDecl() const {
338     return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
339   }
340 
classof(const Decl * D)341   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const NamedDecl * D)342   static bool classof(const NamedDecl *D) { return true; }
classofKind(Kind K)343   static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
344 };
345 
346 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
347   ND.printName(OS);
348   return OS;
349 }
350 
351 /// LabelDecl - Represents the declaration of a label.  Labels also have a
352 /// corresponding LabelStmt, which indicates the position that the label was
353 /// defined at.  For normal labels, the location of the decl is the same as the
354 /// location of the statement.  For GNU local labels (__label__), the decl
355 /// location is where the __label__ is.
356 class LabelDecl : public NamedDecl {
357   virtual void anchor();
358   LabelStmt *TheStmt;
359   /// LocStart - For normal labels, this is the same as the main declaration
360   /// label, i.e., the location of the identifier; for GNU local labels,
361   /// this is the location of the __label__ keyword.
362   SourceLocation LocStart;
363 
LabelDecl(DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II,LabelStmt * S,SourceLocation StartL)364   LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
365             LabelStmt *S, SourceLocation StartL)
366     : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
367 
368 public:
369   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
370                            SourceLocation IdentL, IdentifierInfo *II);
371   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
372                            SourceLocation IdentL, IdentifierInfo *II,
373                            SourceLocation GnuLabelL);
374   static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
375 
getStmt()376   LabelStmt *getStmt() const { return TheStmt; }
setStmt(LabelStmt * T)377   void setStmt(LabelStmt *T) { TheStmt = T; }
378 
isGnuLocal()379   bool isGnuLocal() const { return LocStart != getLocation(); }
setLocStart(SourceLocation L)380   void setLocStart(SourceLocation L) { LocStart = L; }
381 
getSourceRange()382   SourceRange getSourceRange() const LLVM_READONLY {
383     return SourceRange(LocStart, getLocation());
384   }
385 
386   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)387   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const LabelDecl * D)388   static bool classof(const LabelDecl *D) { return true; }
classofKind(Kind K)389   static bool classofKind(Kind K) { return K == Label; }
390 };
391 
392 /// NamespaceDecl - Represent a C++ namespace.
393 class NamespaceDecl : public NamedDecl, public DeclContext,
394                       public Redeclarable<NamespaceDecl>
395 {
396   virtual void anchor();
397 
398   /// LocStart - The starting location of the source range, pointing
399   /// to either the namespace or the inline keyword.
400   SourceLocation LocStart;
401   /// RBraceLoc - The ending location of the source range.
402   SourceLocation RBraceLoc;
403 
404   /// \brief A pointer to either the anonymous namespace that lives just inside
405   /// this namespace or to the first namespace in the chain (the latter case
406   /// only when this is not the first in the chain), along with a
407   /// boolean value indicating whether this is an inline namespace.
408   llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
409 
410   NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc,
411                 SourceLocation IdLoc, IdentifierInfo *Id,
412                 NamespaceDecl *PrevDecl);
413 
414   typedef Redeclarable<NamespaceDecl> redeclarable_base;
getNextRedeclaration()415   virtual NamespaceDecl *getNextRedeclaration() {
416     return RedeclLink.getNext();
417   }
getPreviousDeclImpl()418   virtual NamespaceDecl *getPreviousDeclImpl() {
419     return getPreviousDecl();
420   }
getMostRecentDeclImpl()421   virtual NamespaceDecl *getMostRecentDeclImpl() {
422     return getMostRecentDecl();
423   }
424 
425 public:
426   static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
427                                bool Inline, SourceLocation StartLoc,
428                                SourceLocation IdLoc, IdentifierInfo *Id,
429                                NamespaceDecl *PrevDecl);
430 
431   static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
432 
433   typedef redeclarable_base::redecl_iterator redecl_iterator;
434   using redeclarable_base::redecls_begin;
435   using redeclarable_base::redecls_end;
436   using redeclarable_base::getPreviousDecl;
437   using redeclarable_base::getMostRecentDecl;
438 
439   /// \brief Returns true if this is an anonymous namespace declaration.
440   ///
441   /// For example:
442   /// \code
443   ///   namespace {
444   ///     ...
445   ///   };
446   /// \endcode
447   /// q.v. C++ [namespace.unnamed]
isAnonymousNamespace()448   bool isAnonymousNamespace() const {
449     return !getIdentifier();
450   }
451 
452   /// \brief Returns true if this is an inline namespace declaration.
isInline()453   bool isInline() const {
454     return AnonOrFirstNamespaceAndInline.getInt();
455   }
456 
457   /// \brief Set whether this is an inline namespace declaration.
setInline(bool Inline)458   void setInline(bool Inline) {
459     AnonOrFirstNamespaceAndInline.setInt(Inline);
460   }
461 
462   /// \brief Get the original (first) namespace declaration.
getOriginalNamespace()463   NamespaceDecl *getOriginalNamespace() {
464     if (isFirstDeclaration())
465       return this;
466 
467     return AnonOrFirstNamespaceAndInline.getPointer();
468   }
469 
470   /// \brief Get the original (first) namespace declaration.
getOriginalNamespace()471   const NamespaceDecl *getOriginalNamespace() const {
472     if (isFirstDeclaration())
473       return this;
474 
475     return AnonOrFirstNamespaceAndInline.getPointer();
476   }
477 
478   /// \brief Return true if this declaration is an original (first) declaration
479   /// of the namespace. This is false for non-original (subsequent) namespace
480   /// declarations and anonymous namespaces.
isOriginalNamespace()481   bool isOriginalNamespace() const {
482     return isFirstDeclaration();
483   }
484 
485   /// \brief Retrieve the anonymous namespace nested inside this namespace,
486   /// if any.
getAnonymousNamespace()487   NamespaceDecl *getAnonymousNamespace() const {
488     return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
489   }
490 
setAnonymousNamespace(NamespaceDecl * D)491   void setAnonymousNamespace(NamespaceDecl *D) {
492     getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
493   }
494 
495   /// Retrieves the canonical declaration of this namespace.
getCanonicalDecl()496   NamespaceDecl *getCanonicalDecl() {
497     return getOriginalNamespace();
498   }
getCanonicalDecl()499   const NamespaceDecl *getCanonicalDecl() const {
500     return getOriginalNamespace();
501   }
502 
getSourceRange()503   virtual SourceRange getSourceRange() const LLVM_READONLY {
504     return SourceRange(LocStart, RBraceLoc);
505   }
506 
getLocStart()507   SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
getRBraceLoc()508   SourceLocation getRBraceLoc() const { return RBraceLoc; }
setLocStart(SourceLocation L)509   void setLocStart(SourceLocation L) { LocStart = L; }
setRBraceLoc(SourceLocation L)510   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
511 
512   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)513   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const NamespaceDecl * D)514   static bool classof(const NamespaceDecl *D) { return true; }
classofKind(Kind K)515   static bool classofKind(Kind K) { return K == Namespace; }
castToDeclContext(const NamespaceDecl * D)516   static DeclContext *castToDeclContext(const NamespaceDecl *D) {
517     return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
518   }
castFromDeclContext(const DeclContext * DC)519   static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
520     return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
521   }
522 
523   friend class ASTDeclReader;
524   friend class ASTDeclWriter;
525 };
526 
527 /// ValueDecl - Represent the declaration of a variable (in which case it is
528 /// an lvalue) a function (in which case it is a function designator) or
529 /// an enum constant.
530 class ValueDecl : public NamedDecl {
531   virtual void anchor();
532   QualType DeclType;
533 
534 protected:
ValueDecl(Kind DK,DeclContext * DC,SourceLocation L,DeclarationName N,QualType T)535   ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
536             DeclarationName N, QualType T)
537     : NamedDecl(DK, DC, L, N), DeclType(T) {}
538 public:
getType()539   QualType getType() const { return DeclType; }
setType(QualType newType)540   void setType(QualType newType) { DeclType = newType; }
541 
542   /// \brief Determine whether this symbol is weakly-imported,
543   ///        or declared with the weak or weak-ref attr.
isWeak()544   bool isWeak() const {
545     return hasAttr<WeakAttr>() || hasAttr<WeakRefAttr>() || isWeakImported();
546   }
547 
548   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)549   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const ValueDecl * D)550   static bool classof(const ValueDecl *D) { return true; }
classofKind(Kind K)551   static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
552 };
553 
554 /// QualifierInfo - A struct with extended info about a syntactic
555 /// name qualifier, to be used for the case of out-of-line declarations.
556 struct QualifierInfo {
557   NestedNameSpecifierLoc QualifierLoc;
558 
559   /// NumTemplParamLists - The number of "outer" template parameter lists.
560   /// The count includes all of the template parameter lists that were matched
561   /// against the template-ids occurring into the NNS and possibly (in the
562   /// case of an explicit specialization) a final "template <>".
563   unsigned NumTemplParamLists;
564 
565   /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
566   /// containing pointers to the "outer" template parameter lists.
567   /// It includes all of the template parameter lists that were matched
568   /// against the template-ids occurring into the NNS and possibly (in the
569   /// case of an explicit specialization) a final "template <>".
570   TemplateParameterList** TemplParamLists;
571 
572   /// Default constructor.
QualifierInfoQualifierInfo573   QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {}
574 
575   /// setTemplateParameterListsInfo - Sets info about "outer" template
576   /// parameter lists.
577   void setTemplateParameterListsInfo(ASTContext &Context,
578                                      unsigned NumTPLists,
579                                      TemplateParameterList **TPLists);
580 
581 private:
582   // Copy constructor and copy assignment are disabled.
583   QualifierInfo(const QualifierInfo&);
584   QualifierInfo& operator=(const QualifierInfo&);
585 };
586 
587 /// \brief Represents a ValueDecl that came out of a declarator.
588 /// Contains type source information through TypeSourceInfo.
589 class DeclaratorDecl : public ValueDecl {
590   // A struct representing both a TInfo and a syntactic qualifier,
591   // to be used for the (uncommon) case of out-of-line declarations.
592   struct ExtInfo : public QualifierInfo {
593     TypeSourceInfo *TInfo;
594   };
595 
596   llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
597 
598   /// InnerLocStart - The start of the source range for this declaration,
599   /// ignoring outer template declarations.
600   SourceLocation InnerLocStart;
601 
hasExtInfo()602   bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
getExtInfo()603   ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
getExtInfo()604   const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
605 
606 protected:
DeclaratorDecl(Kind DK,DeclContext * DC,SourceLocation L,DeclarationName N,QualType T,TypeSourceInfo * TInfo,SourceLocation StartL)607   DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
608                  DeclarationName N, QualType T, TypeSourceInfo *TInfo,
609                  SourceLocation StartL)
610     : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
611   }
612 
613 public:
getTypeSourceInfo()614   TypeSourceInfo *getTypeSourceInfo() const {
615     return hasExtInfo()
616       ? getExtInfo()->TInfo
617       : DeclInfo.get<TypeSourceInfo*>();
618   }
setTypeSourceInfo(TypeSourceInfo * TI)619   void setTypeSourceInfo(TypeSourceInfo *TI) {
620     if (hasExtInfo())
621       getExtInfo()->TInfo = TI;
622     else
623       DeclInfo = TI;
624   }
625 
626   /// getInnerLocStart - Return SourceLocation representing start of source
627   /// range ignoring outer template declarations.
getInnerLocStart()628   SourceLocation getInnerLocStart() const { return InnerLocStart; }
setInnerLocStart(SourceLocation L)629   void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
630 
631   /// getOuterLocStart - Return SourceLocation representing start of source
632   /// range taking into account any outer template declarations.
633   SourceLocation getOuterLocStart() const;
634 
635   virtual SourceRange getSourceRange() const LLVM_READONLY;
getLocStart()636   SourceLocation getLocStart() const LLVM_READONLY {
637     return getOuterLocStart();
638   }
639 
640   /// \brief Retrieve the nested-name-specifier that qualifies the name of this
641   /// declaration, if it was present in the source.
getQualifier()642   NestedNameSpecifier *getQualifier() const {
643     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
644                         : 0;
645   }
646 
647   /// \brief Retrieve the nested-name-specifier (with source-location
648   /// information) that qualifies the name of this declaration, if it was
649   /// present in the source.
getQualifierLoc()650   NestedNameSpecifierLoc getQualifierLoc() const {
651     return hasExtInfo() ? getExtInfo()->QualifierLoc
652                         : NestedNameSpecifierLoc();
653   }
654 
655   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
656 
getNumTemplateParameterLists()657   unsigned getNumTemplateParameterLists() const {
658     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
659   }
getTemplateParameterList(unsigned index)660   TemplateParameterList *getTemplateParameterList(unsigned index) const {
661     assert(index < getNumTemplateParameterLists());
662     return getExtInfo()->TemplParamLists[index];
663   }
664   void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
665                                      TemplateParameterList **TPLists);
666 
667   SourceLocation getTypeSpecStartLoc() const;
668 
669   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)670   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const DeclaratorDecl * D)671   static bool classof(const DeclaratorDecl *D) { return true; }
classofKind(Kind K)672   static bool classofKind(Kind K) {
673     return K >= firstDeclarator && K <= lastDeclarator;
674   }
675 
676   friend class ASTDeclReader;
677   friend class ASTDeclWriter;
678 };
679 
680 /// \brief Structure used to store a statement, the constant value to
681 /// which it was evaluated (if any), and whether or not the statement
682 /// is an integral constant expression (if known).
683 struct EvaluatedStmt {
EvaluatedStmtEvaluatedStmt684   EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
685                     CheckingICE(false), IsICE(false) { }
686 
687   /// \brief Whether this statement was already evaluated.
688   bool WasEvaluated : 1;
689 
690   /// \brief Whether this statement is being evaluated.
691   bool IsEvaluating : 1;
692 
693   /// \brief Whether we already checked whether this statement was an
694   /// integral constant expression.
695   bool CheckedICE : 1;
696 
697   /// \brief Whether we are checking whether this statement is an
698   /// integral constant expression.
699   bool CheckingICE : 1;
700 
701   /// \brief Whether this statement is an integral constant expression,
702   /// or in C++11, whether the statement is a constant expression. Only
703   /// valid if CheckedICE is true.
704   bool IsICE : 1;
705 
706   Stmt *Value;
707   APValue Evaluated;
708 };
709 
710 /// VarDecl - An instance of this class is created to represent a variable
711 /// declaration or definition.
712 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
713 public:
714   typedef clang::StorageClass StorageClass;
715 
716   /// getStorageClassSpecifierString - Return the string used to
717   /// specify the storage class \arg SC.
718   ///
719   /// It is illegal to call this function with SC == None.
720   static const char *getStorageClassSpecifierString(StorageClass SC);
721 
722   /// \brief Initialization styles.
723   enum InitializationStyle {
724     CInit,    ///< C-style initialization with assignment
725     CallInit, ///< Call-style initialization (C++98)
726     ListInit  ///< Direct list-initialization (C++11)
727   };
728 
729 protected:
730   /// \brief Placeholder type used in Init to denote an unparsed C++ default
731   /// argument.
732   struct UnparsedDefaultArgument;
733 
734   /// \brief Placeholder type used in Init to denote an uninstantiated C++
735   /// default argument.
736   struct UninstantiatedDefaultArgument;
737 
738   typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
739                               UnparsedDefaultArgument *,
740                               UninstantiatedDefaultArgument *> InitType;
741 
742   /// \brief The initializer for this variable or, for a ParmVarDecl, the
743   /// C++ default argument.
744   mutable InitType Init;
745 
746 private:
747   class VarDeclBitfields {
748     friend class VarDecl;
749     friend class ASTDeclReader;
750 
751     unsigned SClass : 3;
752     unsigned SClassAsWritten : 3;
753     unsigned ThreadSpecified : 1;
754     unsigned InitStyle : 2;
755 
756     /// \brief Whether this variable is the exception variable in a C++ catch
757     /// or an Objective-C @catch statement.
758     unsigned ExceptionVar : 1;
759 
760     /// \brief Whether this local variable could be allocated in the return
761     /// slot of its function, enabling the named return value optimization
762     /// (NRVO).
763     unsigned NRVOVariable : 1;
764 
765     /// \brief Whether this variable is the for-range-declaration in a C++0x
766     /// for-range statement.
767     unsigned CXXForRangeDecl : 1;
768 
769     /// \brief Whether this variable is an ARC pseudo-__strong
770     /// variable;  see isARCPseudoStrong() for details.
771     unsigned ARCPseudoStrong : 1;
772 
773     /// \brief Whether this variable is (C++0x) constexpr.
774     unsigned IsConstexpr : 1;
775   };
776   enum { NumVarDeclBits = 14 };
777 
778   friend class ASTDeclReader;
779   friend class StmtIteratorBase;
780 
781 protected:
782   enum { NumParameterIndexBits = 8 };
783 
784   class ParmVarDeclBitfields {
785     friend class ParmVarDecl;
786     friend class ASTDeclReader;
787 
788     unsigned : NumVarDeclBits;
789 
790     /// Whether this parameter inherits a default argument from a
791     /// prior declaration.
792     unsigned HasInheritedDefaultArg : 1;
793 
794     /// Whether this parameter undergoes K&R argument promotion.
795     unsigned IsKNRPromoted : 1;
796 
797     /// Whether this parameter is an ObjC method parameter or not.
798     unsigned IsObjCMethodParam : 1;
799 
800     /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
801     /// Otherwise, the number of function parameter scopes enclosing
802     /// the function parameter scope in which this parameter was
803     /// declared.
804     unsigned ScopeDepthOrObjCQuals : 7;
805 
806     /// The number of parameters preceding this parameter in the
807     /// function parameter scope in which it was declared.
808     unsigned ParameterIndex : NumParameterIndexBits;
809   };
810 
811   union {
812     unsigned AllBits;
813     VarDeclBitfields VarDeclBits;
814     ParmVarDeclBitfields ParmVarDeclBits;
815   };
816 
VarDecl(Kind DK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass SC,StorageClass SCAsWritten)817   VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
818           SourceLocation IdLoc, IdentifierInfo *Id,
819           QualType T, TypeSourceInfo *TInfo, StorageClass SC,
820           StorageClass SCAsWritten)
821     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
822     assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
823     assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
824     AllBits = 0;
825     VarDeclBits.SClass = SC;
826     VarDeclBits.SClassAsWritten = SCAsWritten;
827     // Everything else is implicitly initialized to false.
828   }
829 
830   typedef Redeclarable<VarDecl> redeclarable_base;
getNextRedeclaration()831   virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
getPreviousDeclImpl()832   virtual VarDecl *getPreviousDeclImpl() {
833     return getPreviousDecl();
834   }
getMostRecentDeclImpl()835   virtual VarDecl *getMostRecentDeclImpl() {
836     return getMostRecentDecl();
837   }
838 
839 public:
840   typedef redeclarable_base::redecl_iterator redecl_iterator;
841   using redeclarable_base::redecls_begin;
842   using redeclarable_base::redecls_end;
843   using redeclarable_base::getPreviousDecl;
844   using redeclarable_base::getMostRecentDecl;
845 
846   static VarDecl *Create(ASTContext &C, DeclContext *DC,
847                          SourceLocation StartLoc, SourceLocation IdLoc,
848                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
849                          StorageClass S, StorageClass SCAsWritten);
850 
851   static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
852 
853   virtual SourceRange getSourceRange() const LLVM_READONLY;
854 
getStorageClass()855   StorageClass getStorageClass() const {
856     return (StorageClass) VarDeclBits.SClass;
857   }
getStorageClassAsWritten()858   StorageClass getStorageClassAsWritten() const {
859     return (StorageClass) VarDeclBits.SClassAsWritten;
860   }
861   void setStorageClass(StorageClass SC);
setStorageClassAsWritten(StorageClass SC)862   void setStorageClassAsWritten(StorageClass SC) {
863     assert(isLegalForVariable(SC));
864     VarDeclBits.SClassAsWritten = SC;
865   }
866 
setThreadSpecified(bool T)867   void setThreadSpecified(bool T) { VarDeclBits.ThreadSpecified = T; }
isThreadSpecified()868   bool isThreadSpecified() const {
869     return VarDeclBits.ThreadSpecified;
870   }
871 
872   /// hasLocalStorage - Returns true if a variable with function scope
873   ///  is a non-static local variable.
hasLocalStorage()874   bool hasLocalStorage() const {
875     if (getStorageClass() == SC_None)
876       return !isFileVarDecl();
877 
878     // Return true for:  Auto, Register.
879     // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
880 
881     return getStorageClass() >= SC_Auto;
882   }
883 
884   /// isStaticLocal - Returns true if a variable with function scope is a
885   /// static local variable.
isStaticLocal()886   bool isStaticLocal() const {
887     return getStorageClass() == SC_Static && !isFileVarDecl();
888   }
889 
890   /// hasExternStorage - Returns true if a variable has extern or
891   /// __private_extern__ storage.
hasExternalStorage()892   bool hasExternalStorage() const {
893     return getStorageClass() == SC_Extern ||
894            getStorageClass() == SC_PrivateExtern;
895   }
896 
897   /// hasGlobalStorage - Returns true for all variables that do not
898   ///  have local storage.  This includs all global variables as well
899   ///  as static variables declared within a function.
hasGlobalStorage()900   bool hasGlobalStorage() const { return !hasLocalStorage(); }
901 
902   /// \brief Determines whether this variable is a variable with
903   /// external, C linkage.
904   bool isExternC() const;
905 
906   /// isLocalVarDecl - Returns true for local variable declarations
907   /// other than parameters.  Note that this includes static variables
908   /// inside of functions. It also includes variables inside blocks.
909   ///
910   ///   void foo() { int x; static int y; extern int z; }
911   ///
isLocalVarDecl()912   bool isLocalVarDecl() const {
913     if (getKind() != Decl::Var)
914       return false;
915     if (const DeclContext *DC = getDeclContext())
916       return DC->getRedeclContext()->isFunctionOrMethod();
917     return false;
918   }
919 
920   /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
921   /// excludes variables declared in blocks.
isFunctionOrMethodVarDecl()922   bool isFunctionOrMethodVarDecl() const {
923     if (getKind() != Decl::Var)
924       return false;
925     const DeclContext *DC = getDeclContext()->getRedeclContext();
926     return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
927   }
928 
929   /// \brief Determines whether this is a static data member.
930   ///
931   /// This will only be true in C++, and applies to, e.g., the
932   /// variable 'x' in:
933   /// \code
934   /// struct S {
935   ///   static int x;
936   /// };
937   /// \endcode
isStaticDataMember()938   bool isStaticDataMember() const {
939     // If it wasn't static, it would be a FieldDecl.
940     return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
941   }
942 
943   virtual VarDecl *getCanonicalDecl();
getCanonicalDecl()944   const VarDecl *getCanonicalDecl() const {
945     return const_cast<VarDecl*>(this)->getCanonicalDecl();
946   }
947 
948   enum DefinitionKind {
949     DeclarationOnly,      ///< This declaration is only a declaration.
950     TentativeDefinition,  ///< This declaration is a tentative definition.
951     Definition            ///< This declaration is definitely a definition.
952   };
953 
954   /// \brief Check whether this declaration is a definition. If this could be
955   /// a tentative definition (in C), don't check whether there's an overriding
956   /// definition.
957   DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
isThisDeclarationADefinition()958   DefinitionKind isThisDeclarationADefinition() const {
959     return isThisDeclarationADefinition(getASTContext());
960   }
961 
962   /// \brief Check whether this variable is defined in this
963   /// translation unit.
964   DefinitionKind hasDefinition(ASTContext &) const;
hasDefinition()965   DefinitionKind hasDefinition() const {
966     return hasDefinition(getASTContext());
967   }
968 
969   /// \brief Get the tentative definition that acts as the real definition in
970   /// a TU. Returns null if there is a proper definition available.
971   VarDecl *getActingDefinition();
getActingDefinition()972   const VarDecl *getActingDefinition() const {
973     return const_cast<VarDecl*>(this)->getActingDefinition();
974   }
975 
976   /// \brief Determine whether this is a tentative definition of a
977   /// variable in C.
978   bool isTentativeDefinitionNow() const;
979 
980   /// \brief Get the real (not just tentative) definition for this declaration.
981   VarDecl *getDefinition(ASTContext &);
getDefinition(ASTContext & C)982   const VarDecl *getDefinition(ASTContext &C) const {
983     return const_cast<VarDecl*>(this)->getDefinition(C);
984   }
getDefinition()985   VarDecl *getDefinition() {
986     return getDefinition(getASTContext());
987   }
getDefinition()988   const VarDecl *getDefinition() const {
989     return const_cast<VarDecl*>(this)->getDefinition();
990   }
991 
992   /// \brief Determine whether this is or was instantiated from an out-of-line
993   /// definition of a static data member.
994   virtual bool isOutOfLine() const;
995 
996   /// \brief If this is a static data member, find its out-of-line definition.
997   VarDecl *getOutOfLineDefinition();
998 
999   /// isFileVarDecl - Returns true for file scoped variable declaration.
isFileVarDecl()1000   bool isFileVarDecl() const {
1001     if (getKind() != Decl::Var)
1002       return false;
1003 
1004     if (getDeclContext()->getRedeclContext()->isFileContext())
1005       return true;
1006 
1007     if (isStaticDataMember())
1008       return true;
1009 
1010     return false;
1011   }
1012 
1013   /// getAnyInitializer - Get the initializer for this variable, no matter which
1014   /// declaration it is attached to.
getAnyInitializer()1015   const Expr *getAnyInitializer() const {
1016     const VarDecl *D;
1017     return getAnyInitializer(D);
1018   }
1019 
1020   /// getAnyInitializer - Get the initializer for this variable, no matter which
1021   /// declaration it is attached to. Also get that declaration.
1022   const Expr *getAnyInitializer(const VarDecl *&D) const;
1023 
hasInit()1024   bool hasInit() const {
1025     return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
1026   }
getInit()1027   const Expr *getInit() const {
1028     if (Init.isNull())
1029       return 0;
1030 
1031     const Stmt *S = Init.dyn_cast<Stmt *>();
1032     if (!S) {
1033       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1034         S = ES->Value;
1035     }
1036     return (const Expr*) S;
1037   }
getInit()1038   Expr *getInit() {
1039     if (Init.isNull())
1040       return 0;
1041 
1042     Stmt *S = Init.dyn_cast<Stmt *>();
1043     if (!S) {
1044       if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1045         S = ES->Value;
1046     }
1047 
1048     return (Expr*) S;
1049   }
1050 
1051   /// \brief Retrieve the address of the initializer expression.
getInitAddress()1052   Stmt **getInitAddress() {
1053     if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
1054       return &ES->Value;
1055 
1056     // This union hack tip-toes around strict-aliasing rules.
1057     union {
1058       InitType *InitPtr;
1059       Stmt **StmtPtr;
1060     };
1061 
1062     InitPtr = &Init;
1063     return StmtPtr;
1064   }
1065 
1066   void setInit(Expr *I);
1067 
1068   /// \brief Determine whether this variable is a reference that
1069   /// extends the lifetime of its temporary initializer.
1070   ///
1071   /// A reference extends the lifetime of its temporary initializer if
1072   /// it's initializer is an rvalue that would normally go out of scope
1073   /// at the end of the initializer (a full expression). In such cases,
1074   /// the reference itself takes ownership of the temporary, which will
1075   /// be destroyed when the reference goes out of scope. For example:
1076   ///
1077   /// \code
1078   /// const int &r = 1.0; // creates a temporary of type 'int'
1079   /// \endcode
1080   bool extendsLifetimeOfTemporary() const;
1081 
1082   /// \brief Determine whether this variable's value can be used in a
1083   /// constant expression, according to the relevant language standard.
1084   /// This only checks properties of the declaration, and does not check
1085   /// whether the initializer is in fact a constant expression.
1086   bool isUsableInConstantExpressions(ASTContext &C) const;
1087 
1088   EvaluatedStmt *ensureEvaluatedStmt() const;
1089 
1090   /// \brief Attempt to evaluate the value of the initializer attached to this
1091   /// declaration, and produce notes explaining why it cannot be evaluated or is
1092   /// not a constant expression. Returns a pointer to the value if evaluation
1093   /// succeeded, 0 otherwise.
1094   APValue *evaluateValue() const;
1095   APValue *evaluateValue(
1096     llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1097 
1098   /// \brief Return the already-evaluated value of this variable's
1099   /// initializer, or NULL if the value is not yet known. Returns pointer
1100   /// to untyped APValue if the value could not be evaluated.
getEvaluatedValue()1101   APValue *getEvaluatedValue() const {
1102     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1103       if (Eval->WasEvaluated)
1104         return &Eval->Evaluated;
1105 
1106     return 0;
1107   }
1108 
1109   /// \brief Determines whether it is already known whether the
1110   /// initializer is an integral constant expression or not.
isInitKnownICE()1111   bool isInitKnownICE() const {
1112     if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
1113       return Eval->CheckedICE;
1114 
1115     return false;
1116   }
1117 
1118   /// \brief Determines whether the initializer is an integral constant
1119   /// expression, or in C++11, whether the initializer is a constant
1120   /// expression.
1121   ///
1122   /// \pre isInitKnownICE()
isInitICE()1123   bool isInitICE() const {
1124     assert(isInitKnownICE() &&
1125            "Check whether we already know that the initializer is an ICE");
1126     return Init.get<EvaluatedStmt *>()->IsICE;
1127   }
1128 
1129   /// \brief Determine whether the value of the initializer attached to this
1130   /// declaration is an integral constant expression.
1131   bool checkInitIsICE() const;
1132 
setInitStyle(InitializationStyle Style)1133   void setInitStyle(InitializationStyle Style) {
1134     VarDeclBits.InitStyle = Style;
1135   }
1136 
1137   /// \brief The style of initialization for this declaration.
1138   ///
1139   /// C-style initialization is "int x = 1;". Call-style initialization is
1140   /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1141   /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1142   /// expression for class types. List-style initialization is C++11 syntax,
1143   /// e.g. "int x{1};". Clients can distinguish between different forms of
1144   /// initialization by checking this value. In particular, "int x = {1};" is
1145   /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1146   /// Init expression in all three cases is an InitListExpr.
getInitStyle()1147   InitializationStyle getInitStyle() const {
1148     return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1149   }
1150 
1151   /// \brief Whether the initializer is a direct-initializer (list or call).
isDirectInit()1152   bool isDirectInit() const {
1153     return getInitStyle() != CInit;
1154   }
1155 
1156   /// \brief Determine whether this variable is the exception variable in a
1157   /// C++ catch statememt or an Objective-C @catch statement.
isExceptionVariable()1158   bool isExceptionVariable() const {
1159     return VarDeclBits.ExceptionVar;
1160   }
setExceptionVariable(bool EV)1161   void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; }
1162 
1163   /// \brief Determine whether this local variable can be used with the named
1164   /// return value optimization (NRVO).
1165   ///
1166   /// The named return value optimization (NRVO) works by marking certain
1167   /// non-volatile local variables of class type as NRVO objects. These
1168   /// locals can be allocated within the return slot of their containing
1169   /// function, in which case there is no need to copy the object to the
1170   /// return slot when returning from the function. Within the function body,
1171   /// each return that returns the NRVO object will have this variable as its
1172   /// NRVO candidate.
isNRVOVariable()1173   bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; }
setNRVOVariable(bool NRVO)1174   void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; }
1175 
1176   /// \brief Determine whether this variable is the for-range-declaration in
1177   /// a C++0x for-range statement.
isCXXForRangeDecl()1178   bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; }
setCXXForRangeDecl(bool FRD)1179   void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; }
1180 
1181   /// \brief Determine whether this variable is an ARC pseudo-__strong
1182   /// variable.  A pseudo-__strong variable has a __strong-qualified
1183   /// type but does not actually retain the object written into it.
1184   /// Generally such variables are also 'const' for safety.
isARCPseudoStrong()1185   bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
setARCPseudoStrong(bool ps)1186   void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; }
1187 
1188   /// Whether this variable is (C++0x) constexpr.
isConstexpr()1189   bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
setConstexpr(bool IC)1190   void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; }
1191 
1192   /// \brief If this variable is an instantiated static data member of a
1193   /// class template specialization, returns the templated static data member
1194   /// from which it was instantiated.
1195   VarDecl *getInstantiatedFromStaticDataMember() const;
1196 
1197   /// \brief If this variable is a static data member, determine what kind of
1198   /// template specialization or instantiation this is.
1199   TemplateSpecializationKind getTemplateSpecializationKind() const;
1200 
1201   /// \brief If this variable is an instantiation of a static data member of a
1202   /// class template specialization, retrieves the member specialization
1203   /// information.
1204   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1205 
1206   /// \brief For a static data member that was instantiated from a static
1207   /// data member of a class template, set the template specialiation kind.
1208   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1209                         SourceLocation PointOfInstantiation = SourceLocation());
1210 
1211   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)1212   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const VarDecl * D)1213   static bool classof(const VarDecl *D) { return true; }
classofKind(Kind K)1214   static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1215 };
1216 
1217 class ImplicitParamDecl : public VarDecl {
1218   virtual void anchor();
1219 public:
1220   static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1221                                    SourceLocation IdLoc, IdentifierInfo *Id,
1222                                    QualType T);
1223 
1224   static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1225 
ImplicitParamDecl(DeclContext * DC,SourceLocation IdLoc,IdentifierInfo * Id,QualType Type)1226   ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
1227                     IdentifierInfo *Id, QualType Type)
1228     : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
1229               /*tinfo*/ 0, SC_None, SC_None) {
1230     setImplicit();
1231   }
1232 
1233   // Implement isa/cast/dyncast/etc.
classof(const ImplicitParamDecl * D)1234   static bool classof(const ImplicitParamDecl *D) { return true; }
classof(const Decl * D)1235   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1236   static bool classofKind(Kind K) { return K == ImplicitParam; }
1237 };
1238 
1239 /// ParmVarDecl - Represents a parameter to a function.
1240 class ParmVarDecl : public VarDecl {
1241 public:
1242   enum { MaxFunctionScopeDepth = 255 };
1243   enum { MaxFunctionScopeIndex = 255 };
1244 
1245 protected:
ParmVarDecl(Kind DK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S,StorageClass SCAsWritten,Expr * DefArg)1246   ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1247               SourceLocation IdLoc, IdentifierInfo *Id,
1248               QualType T, TypeSourceInfo *TInfo,
1249               StorageClass S, StorageClass SCAsWritten, Expr *DefArg)
1250     : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten) {
1251     assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1252     assert(ParmVarDeclBits.IsKNRPromoted == false);
1253     assert(ParmVarDeclBits.IsObjCMethodParam == false);
1254     setDefaultArg(DefArg);
1255   }
1256 
1257 public:
1258   static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1259                              SourceLocation StartLoc,
1260                              SourceLocation IdLoc, IdentifierInfo *Id,
1261                              QualType T, TypeSourceInfo *TInfo,
1262                              StorageClass S, StorageClass SCAsWritten,
1263                              Expr *DefArg);
1264 
1265   static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1266 
1267   virtual SourceRange getSourceRange() const LLVM_READONLY;
1268 
setObjCMethodScopeInfo(unsigned parameterIndex)1269   void setObjCMethodScopeInfo(unsigned parameterIndex) {
1270     ParmVarDeclBits.IsObjCMethodParam = true;
1271     setParameterIndex(parameterIndex);
1272   }
1273 
setScopeInfo(unsigned scopeDepth,unsigned parameterIndex)1274   void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1275     assert(!ParmVarDeclBits.IsObjCMethodParam);
1276 
1277     ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1278     assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1279            && "truncation!");
1280 
1281     setParameterIndex(parameterIndex);
1282   }
1283 
isObjCMethodParameter()1284   bool isObjCMethodParameter() const {
1285     return ParmVarDeclBits.IsObjCMethodParam;
1286   }
1287 
getFunctionScopeDepth()1288   unsigned getFunctionScopeDepth() const {
1289     if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1290     return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1291   }
1292 
1293   /// Returns the index of this parameter in its prototype or method scope.
getFunctionScopeIndex()1294   unsigned getFunctionScopeIndex() const {
1295     return getParameterIndex();
1296   }
1297 
getObjCDeclQualifier()1298   ObjCDeclQualifier getObjCDeclQualifier() const {
1299     if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1300     return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1301   }
setObjCDeclQualifier(ObjCDeclQualifier QTVal)1302   void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1303     assert(ParmVarDeclBits.IsObjCMethodParam);
1304     ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1305   }
1306 
1307   /// True if the value passed to this parameter must undergo
1308   /// K&R-style default argument promotion:
1309   ///
1310   /// C99 6.5.2.2.
1311   ///   If the expression that denotes the called function has a type
1312   ///   that does not include a prototype, the integer promotions are
1313   ///   performed on each argument, and arguments that have type float
1314   ///   are promoted to double.
isKNRPromoted()1315   bool isKNRPromoted() const {
1316     return ParmVarDeclBits.IsKNRPromoted;
1317   }
setKNRPromoted(bool promoted)1318   void setKNRPromoted(bool promoted) {
1319     ParmVarDeclBits.IsKNRPromoted = promoted;
1320   }
1321 
1322   Expr *getDefaultArg();
getDefaultArg()1323   const Expr *getDefaultArg() const {
1324     return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1325   }
1326 
setDefaultArg(Expr * defarg)1327   void setDefaultArg(Expr *defarg) {
1328     Init = reinterpret_cast<Stmt *>(defarg);
1329   }
1330 
1331   /// \brief Retrieve the source range that covers the entire default
1332   /// argument.
1333   SourceRange getDefaultArgRange() const;
setUninstantiatedDefaultArg(Expr * arg)1334   void setUninstantiatedDefaultArg(Expr *arg) {
1335     Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
1336   }
getUninstantiatedDefaultArg()1337   Expr *getUninstantiatedDefaultArg() {
1338     return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
1339   }
getUninstantiatedDefaultArg()1340   const Expr *getUninstantiatedDefaultArg() const {
1341     return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
1342   }
1343 
1344   /// hasDefaultArg - Determines whether this parameter has a default argument,
1345   /// either parsed or not.
hasDefaultArg()1346   bool hasDefaultArg() const {
1347     return getInit() || hasUnparsedDefaultArg() ||
1348       hasUninstantiatedDefaultArg();
1349   }
1350 
1351   /// hasUnparsedDefaultArg - Determines whether this parameter has a
1352   /// default argument that has not yet been parsed. This will occur
1353   /// during the processing of a C++ class whose member functions have
1354   /// default arguments, e.g.,
1355   /// @code
1356   ///   class X {
1357   ///   public:
1358   ///     void f(int x = 17); // x has an unparsed default argument now
1359   ///   }; // x has a regular default argument now
1360   /// @endcode
hasUnparsedDefaultArg()1361   bool hasUnparsedDefaultArg() const {
1362     return Init.is<UnparsedDefaultArgument*>();
1363   }
1364 
hasUninstantiatedDefaultArg()1365   bool hasUninstantiatedDefaultArg() const {
1366     return Init.is<UninstantiatedDefaultArgument*>();
1367   }
1368 
1369   /// setUnparsedDefaultArg - Specify that this parameter has an
1370   /// unparsed default argument. The argument will be replaced with a
1371   /// real default argument via setDefaultArg when the class
1372   /// definition enclosing the function declaration that owns this
1373   /// default argument is completed.
setUnparsedDefaultArg()1374   void setUnparsedDefaultArg() {
1375     Init = (UnparsedDefaultArgument *)0;
1376   }
1377 
hasInheritedDefaultArg()1378   bool hasInheritedDefaultArg() const {
1379     return ParmVarDeclBits.HasInheritedDefaultArg;
1380   }
1381 
1382   void setHasInheritedDefaultArg(bool I = true) {
1383     ParmVarDeclBits.HasInheritedDefaultArg = I;
1384   }
1385 
getOriginalType()1386   QualType getOriginalType() const {
1387     if (getTypeSourceInfo())
1388       return getTypeSourceInfo()->getType();
1389     return getType();
1390   }
1391 
1392   /// \brief Determine whether this parameter is actually a function
1393   /// parameter pack.
1394   bool isParameterPack() const;
1395 
1396   /// setOwningFunction - Sets the function declaration that owns this
1397   /// ParmVarDecl. Since ParmVarDecls are often created before the
1398   /// FunctionDecls that own them, this routine is required to update
1399   /// the DeclContext appropriately.
setOwningFunction(DeclContext * FD)1400   void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1401 
1402   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)1403   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const ParmVarDecl * D)1404   static bool classof(const ParmVarDecl *D) { return true; }
classofKind(Kind K)1405   static bool classofKind(Kind K) { return K == ParmVar; }
1406 
1407 private:
1408   enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1409 
setParameterIndex(unsigned parameterIndex)1410   void setParameterIndex(unsigned parameterIndex) {
1411     if (parameterIndex >= ParameterIndexSentinel) {
1412       setParameterIndexLarge(parameterIndex);
1413       return;
1414     }
1415 
1416     ParmVarDeclBits.ParameterIndex = parameterIndex;
1417     assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1418   }
getParameterIndex()1419   unsigned getParameterIndex() const {
1420     unsigned d = ParmVarDeclBits.ParameterIndex;
1421     return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1422   }
1423 
1424   void setParameterIndexLarge(unsigned parameterIndex);
1425   unsigned getParameterIndexLarge() const;
1426 };
1427 
1428 /// FunctionDecl - An instance of this class is created to represent a
1429 /// function declaration or definition.
1430 ///
1431 /// Since a given function can be declared several times in a program,
1432 /// there may be several FunctionDecls that correspond to that
1433 /// function. Only one of those FunctionDecls will be found when
1434 /// traversing the list of declarations in the context of the
1435 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1436 /// contains all of the information known about the function. Other,
1437 /// previous declarations of the function are available via the
1438 /// getPreviousDecl() chain.
1439 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1440                      public Redeclarable<FunctionDecl> {
1441 public:
1442   typedef clang::StorageClass StorageClass;
1443 
1444   /// \brief The kind of templated function a FunctionDecl can be.
1445   enum TemplatedKind {
1446     TK_NonTemplate,
1447     TK_FunctionTemplate,
1448     TK_MemberSpecialization,
1449     TK_FunctionTemplateSpecialization,
1450     TK_DependentFunctionTemplateSpecialization
1451   };
1452 
1453 private:
1454   /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1455   /// parameters of this function.  This is null if a prototype or if there are
1456   /// no formals.
1457   ParmVarDecl **ParamInfo;
1458 
1459   /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
1460   /// decls defined in the function prototype that are not parameters. E.g.
1461   /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
1462   llvm::ArrayRef<NamedDecl*> DeclsInPrototypeScope;
1463 
1464   LazyDeclStmtPtr Body;
1465 
1466   // FIXME: This can be packed into the bitfields in Decl.
1467   // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
1468   unsigned SClass : 2;
1469   unsigned SClassAsWritten : 2;
1470   bool IsInline : 1;
1471   bool IsInlineSpecified : 1;
1472   bool IsVirtualAsWritten : 1;
1473   bool IsPure : 1;
1474   bool HasInheritedPrototype : 1;
1475   bool HasWrittenPrototype : 1;
1476   bool IsDeleted : 1;
1477   bool IsTrivial : 1; // sunk from CXXMethodDecl
1478   bool IsDefaulted : 1; // sunk from CXXMethoDecl
1479   bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1480   bool HasImplicitReturnZero : 1;
1481   bool IsLateTemplateParsed : 1;
1482   bool IsConstexpr : 1;
1483 
1484   /// \brief End part of this FunctionDecl's source range.
1485   ///
1486   /// We could compute the full range in getSourceRange(). However, when we're
1487   /// dealing with a function definition deserialized from a PCH/AST file,
1488   /// we can only compute the full range once the function body has been
1489   /// de-serialized, so it's far better to have the (sometimes-redundant)
1490   /// EndRangeLoc.
1491   SourceLocation EndRangeLoc;
1492 
1493   /// \brief The template or declaration that this declaration
1494   /// describes or was instantiated from, respectively.
1495   ///
1496   /// For non-templates, this value will be NULL. For function
1497   /// declarations that describe a function template, this will be a
1498   /// pointer to a FunctionTemplateDecl. For member functions
1499   /// of class template specializations, this will be a MemberSpecializationInfo
1500   /// pointer containing information about the specialization.
1501   /// For function template specializations, this will be a
1502   /// FunctionTemplateSpecializationInfo, which contains information about
1503   /// the template being specialized and the template arguments involved in
1504   /// that specialization.
1505   llvm::PointerUnion4<FunctionTemplateDecl *,
1506                       MemberSpecializationInfo *,
1507                       FunctionTemplateSpecializationInfo *,
1508                       DependentFunctionTemplateSpecializationInfo *>
1509     TemplateOrSpecialization;
1510 
1511   /// DNLoc - Provides source/type location info for the
1512   /// declaration name embedded in the DeclaratorDecl base class.
1513   DeclarationNameLoc DNLoc;
1514 
1515   /// \brief Specify that this function declaration is actually a function
1516   /// template specialization.
1517   ///
1518   /// \param C the ASTContext.
1519   ///
1520   /// \param Template the function template that this function template
1521   /// specialization specializes.
1522   ///
1523   /// \param TemplateArgs the template arguments that produced this
1524   /// function template specialization from the template.
1525   ///
1526   /// \param InsertPos If non-NULL, the position in the function template
1527   /// specialization set where the function template specialization data will
1528   /// be inserted.
1529   ///
1530   /// \param TSK the kind of template specialization this is.
1531   ///
1532   /// \param TemplateArgsAsWritten location info of template arguments.
1533   ///
1534   /// \param PointOfInstantiation point at which the function template
1535   /// specialization was first instantiated.
1536   void setFunctionTemplateSpecialization(ASTContext &C,
1537                                          FunctionTemplateDecl *Template,
1538                                        const TemplateArgumentList *TemplateArgs,
1539                                          void *InsertPos,
1540                                          TemplateSpecializationKind TSK,
1541                           const TemplateArgumentListInfo *TemplateArgsAsWritten,
1542                                          SourceLocation PointOfInstantiation);
1543 
1544   /// \brief Specify that this record is an instantiation of the
1545   /// member function FD.
1546   void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1547                                         TemplateSpecializationKind TSK);
1548 
1549   void setParams(ASTContext &C, llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
1550 
1551 protected:
FunctionDecl(Kind DK,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass S,StorageClass SCAsWritten,bool isInlineSpecified,bool isConstexprSpecified)1552   FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1553                const DeclarationNameInfo &NameInfo,
1554                QualType T, TypeSourceInfo *TInfo,
1555                StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified,
1556                bool isConstexprSpecified)
1557     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1558                      StartLoc),
1559       DeclContext(DK),
1560       ParamInfo(0), Body(),
1561       SClass(S), SClassAsWritten(SCAsWritten),
1562       IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1563       IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
1564       HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
1565       IsDefaulted(false), IsExplicitlyDefaulted(false),
1566       HasImplicitReturnZero(false), IsLateTemplateParsed(false),
1567       IsConstexpr(isConstexprSpecified), EndRangeLoc(NameInfo.getEndLoc()),
1568       TemplateOrSpecialization(),
1569       DNLoc(NameInfo.getInfo()) {}
1570 
1571   typedef Redeclarable<FunctionDecl> redeclarable_base;
getNextRedeclaration()1572   virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
getPreviousDeclImpl()1573   virtual FunctionDecl *getPreviousDeclImpl() {
1574     return getPreviousDecl();
1575   }
getMostRecentDeclImpl()1576   virtual FunctionDecl *getMostRecentDeclImpl() {
1577     return getMostRecentDecl();
1578   }
1579 
1580 public:
1581   typedef redeclarable_base::redecl_iterator redecl_iterator;
1582   using redeclarable_base::redecls_begin;
1583   using redeclarable_base::redecls_end;
1584   using redeclarable_base::getPreviousDecl;
1585   using redeclarable_base::getMostRecentDecl;
1586 
1587   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1588                               SourceLocation StartLoc, SourceLocation NLoc,
1589                               DeclarationName N, QualType T,
1590                               TypeSourceInfo *TInfo,
1591                               StorageClass SC = SC_None,
1592                               StorageClass SCAsWritten = SC_None,
1593                               bool isInlineSpecified = false,
1594                               bool hasWrittenPrototype = true,
1595                               bool isConstexprSpecified = false) {
1596     DeclarationNameInfo NameInfo(N, NLoc);
1597     return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1598                                 SC, SCAsWritten,
1599                                 isInlineSpecified, hasWrittenPrototype,
1600                                 isConstexprSpecified);
1601   }
1602 
1603   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1604                               SourceLocation StartLoc,
1605                               const DeclarationNameInfo &NameInfo,
1606                               QualType T, TypeSourceInfo *TInfo,
1607                               StorageClass SC = SC_None,
1608                               StorageClass SCAsWritten = SC_None,
1609                               bool isInlineSpecified = false,
1610                               bool hasWrittenPrototype = true,
1611                               bool isConstexprSpecified = false);
1612 
1613   static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1614 
getNameInfo()1615   DeclarationNameInfo getNameInfo() const {
1616     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1617   }
1618 
1619   virtual void getNameForDiagnostic(std::string &S,
1620                                     const PrintingPolicy &Policy,
1621                                     bool Qualified) const;
1622 
setRangeEnd(SourceLocation E)1623   void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1624 
1625   virtual SourceRange getSourceRange() const LLVM_READONLY;
1626 
1627   /// \brief Returns true if the function has a body (definition). The
1628   /// function body might be in any of the (re-)declarations of this
1629   /// function. The variant that accepts a FunctionDecl pointer will
1630   /// set that function declaration to the actual declaration
1631   /// containing the body (if there is one).
1632   bool hasBody(const FunctionDecl *&Definition) const;
1633 
hasBody()1634   virtual bool hasBody() const {
1635     const FunctionDecl* Definition;
1636     return hasBody(Definition);
1637   }
1638 
1639   /// hasTrivialBody - Returns whether the function has a trivial body that does
1640   /// not require any specific codegen.
1641   bool hasTrivialBody() const;
1642 
1643   /// isDefined - Returns true if the function is defined at all, including
1644   /// a deleted definition. Except for the behavior when the function is
1645   /// deleted, behaves like hasBody.
1646   bool isDefined(const FunctionDecl *&Definition) const;
1647 
isDefined()1648   virtual bool isDefined() const {
1649     const FunctionDecl* Definition;
1650     return isDefined(Definition);
1651   }
1652 
1653   /// getBody - Retrieve the body (definition) of the function. The
1654   /// function body might be in any of the (re-)declarations of this
1655   /// function. The variant that accepts a FunctionDecl pointer will
1656   /// set that function declaration to the actual declaration
1657   /// containing the body (if there is one).
1658   /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1659   /// unnecessary AST de-serialization of the body.
1660   Stmt *getBody(const FunctionDecl *&Definition) const;
1661 
getBody()1662   virtual Stmt *getBody() const {
1663     const FunctionDecl* Definition;
1664     return getBody(Definition);
1665   }
1666 
1667   /// isThisDeclarationADefinition - Returns whether this specific
1668   /// declaration of the function is also a definition. This does not
1669   /// determine whether the function has been defined (e.g., in a
1670   /// previous definition); for that information, use isDefined. Note
1671   /// that this returns false for a defaulted function unless that function
1672   /// has been implicitly defined (possibly as deleted).
isThisDeclarationADefinition()1673   bool isThisDeclarationADefinition() const {
1674     return IsDeleted || Body || IsLateTemplateParsed;
1675   }
1676 
1677   /// doesThisDeclarationHaveABody - Returns whether this specific
1678   /// declaration of the function has a body - that is, if it is a non-
1679   /// deleted definition.
doesThisDeclarationHaveABody()1680   bool doesThisDeclarationHaveABody() const {
1681     return Body || IsLateTemplateParsed;
1682   }
1683 
1684   void setBody(Stmt *B);
setLazyBody(uint64_t Offset)1685   void setLazyBody(uint64_t Offset) { Body = Offset; }
1686 
1687   /// Whether this function is variadic.
1688   bool isVariadic() const;
1689 
1690   /// Whether this function is marked as virtual explicitly.
isVirtualAsWritten()1691   bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
setVirtualAsWritten(bool V)1692   void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1693 
1694   /// Whether this virtual function is pure, i.e. makes the containing class
1695   /// abstract.
isPure()1696   bool isPure() const { return IsPure; }
1697   void setPure(bool P = true);
1698 
1699   /// Whether this templated function will be late parsed.
isLateTemplateParsed()1700   bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1701   void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1702 
1703   /// Whether this function is "trivial" in some specialized C++ senses.
1704   /// Can only be true for default constructors, copy constructors,
1705   /// copy assignment operators, and destructors.  Not meaningful until
1706   /// the class has been fully built by Sema.
isTrivial()1707   bool isTrivial() const { return IsTrivial; }
setTrivial(bool IT)1708   void setTrivial(bool IT) { IsTrivial = IT; }
1709 
1710   /// Whether this function is defaulted per C++0x. Only valid for
1711   /// special member functions.
isDefaulted()1712   bool isDefaulted() const { return IsDefaulted; }
1713   void setDefaulted(bool D = true) { IsDefaulted = D; }
1714 
1715   /// Whether this function is explicitly defaulted per C++0x. Only valid
1716   /// for special member functions.
isExplicitlyDefaulted()1717   bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1718   void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1719 
1720   /// Whether falling off this function implicitly returns null/zero.
1721   /// If a more specific implicit return value is required, front-ends
1722   /// should synthesize the appropriate return statements.
hasImplicitReturnZero()1723   bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
setHasImplicitReturnZero(bool IRZ)1724   void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1725 
1726   /// \brief Whether this function has a prototype, either because one
1727   /// was explicitly written or because it was "inherited" by merging
1728   /// a declaration without a prototype with a declaration that has a
1729   /// prototype.
hasPrototype()1730   bool hasPrototype() const {
1731     return HasWrittenPrototype || HasInheritedPrototype;
1732   }
1733 
hasWrittenPrototype()1734   bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1735 
1736   /// \brief Whether this function inherited its prototype from a
1737   /// previous declaration.
hasInheritedPrototype()1738   bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1739   void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1740 
1741   /// Whether this is a (C++0x) constexpr function or constexpr constructor.
isConstexpr()1742   bool isConstexpr() const { return IsConstexpr; }
setConstexpr(bool IC)1743   void setConstexpr(bool IC) { IsConstexpr = IC; }
1744 
1745   /// \brief Whether this function has been deleted.
1746   ///
1747   /// A function that is "deleted" (via the C++0x "= delete" syntax)
1748   /// acts like a normal function, except that it cannot actually be
1749   /// called or have its address taken. Deleted functions are
1750   /// typically used in C++ overload resolution to attract arguments
1751   /// whose type or lvalue/rvalue-ness would permit the use of a
1752   /// different overload that would behave incorrectly. For example,
1753   /// one might use deleted functions to ban implicit conversion from
1754   /// a floating-point number to an Integer type:
1755   ///
1756   /// @code
1757   /// struct Integer {
1758   ///   Integer(long); // construct from a long
1759   ///   Integer(double) = delete; // no construction from float or double
1760   ///   Integer(long double) = delete; // no construction from long double
1761   /// };
1762   /// @endcode
1763   // If a function is deleted, its first declaration must be.
isDeleted()1764   bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
isDeletedAsWritten()1765   bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1766   void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1767 
1768   /// \brief Determines whether this function is "main", which is the
1769   /// entry point into an executable program.
1770   bool isMain() const;
1771 
1772   /// \brief Determines whether this operator new or delete is one
1773   /// of the reserved global placement operators:
1774   ///    void *operator new(size_t, void *);
1775   ///    void *operator new[](size_t, void *);
1776   ///    void operator delete(void *, void *);
1777   ///    void operator delete[](void *, void *);
1778   /// These functions have special behavior under [new.delete.placement]:
1779   ///    These functions are reserved, a C++ program may not define
1780   ///    functions that displace the versions in the Standard C++ library.
1781   ///    The provisions of [basic.stc.dynamic] do not apply to these
1782   ///    reserved placement forms of operator new and operator delete.
1783   ///
1784   /// This function must be an allocation or deallocation function.
1785   bool isReservedGlobalPlacementOperator() const;
1786 
1787   /// \brief Determines whether this function is a function with
1788   /// external, C linkage.
1789   bool isExternC() const;
1790 
1791   /// \brief Determines whether this is a global function.
1792   bool isGlobal() const;
1793 
1794   void setPreviousDeclaration(FunctionDecl * PrevDecl);
1795 
1796   virtual const FunctionDecl *getCanonicalDecl() const;
1797   virtual FunctionDecl *getCanonicalDecl();
1798 
1799   unsigned getBuiltinID() const;
1800 
1801   // Iterator access to formal parameters.
param_size()1802   unsigned param_size() const { return getNumParams(); }
1803   typedef ParmVarDecl **param_iterator;
1804   typedef ParmVarDecl * const *param_const_iterator;
1805 
param_begin()1806   param_iterator param_begin() { return ParamInfo; }
param_end()1807   param_iterator param_end()   { return ParamInfo+param_size(); }
1808 
param_begin()1809   param_const_iterator param_begin() const { return ParamInfo; }
param_end()1810   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
1811 
1812   /// getNumParams - Return the number of parameters this function must have
1813   /// based on its FunctionType.  This is the length of the ParamInfo array
1814   /// after it has been created.
1815   unsigned getNumParams() const;
1816 
getParamDecl(unsigned i)1817   const ParmVarDecl *getParamDecl(unsigned i) const {
1818     assert(i < getNumParams() && "Illegal param #");
1819     return ParamInfo[i];
1820   }
getParamDecl(unsigned i)1821   ParmVarDecl *getParamDecl(unsigned i) {
1822     assert(i < getNumParams() && "Illegal param #");
1823     return ParamInfo[i];
1824   }
setParams(llvm::ArrayRef<ParmVarDecl * > NewParamInfo)1825   void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1826     setParams(getASTContext(), NewParamInfo);
1827   }
1828 
getDeclsInPrototypeScope()1829   const llvm::ArrayRef<NamedDecl*> &getDeclsInPrototypeScope() const {
1830     return DeclsInPrototypeScope;
1831   }
1832   void setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls);
1833 
1834   /// getMinRequiredArguments - Returns the minimum number of arguments
1835   /// needed to call this function. This may be fewer than the number of
1836   /// function parameters, if some of the parameters have default
1837   /// arguments (in C++).
1838   unsigned getMinRequiredArguments() const;
1839 
getResultType()1840   QualType getResultType() const {
1841     return getType()->getAs<FunctionType>()->getResultType();
1842   }
1843 
1844   /// \brief Determine the type of an expression that calls this function.
getCallResultType()1845   QualType getCallResultType() const {
1846     return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
1847   }
1848 
getStorageClass()1849   StorageClass getStorageClass() const { return StorageClass(SClass); }
1850   void setStorageClass(StorageClass SC);
1851 
getStorageClassAsWritten()1852   StorageClass getStorageClassAsWritten() const {
1853     return StorageClass(SClassAsWritten);
1854   }
1855 
1856   /// \brief Determine whether the "inline" keyword was specified for this
1857   /// function.
isInlineSpecified()1858   bool isInlineSpecified() const { return IsInlineSpecified; }
1859 
1860   /// Set whether the "inline" keyword was specified for this function.
setInlineSpecified(bool I)1861   void setInlineSpecified(bool I) {
1862     IsInlineSpecified = I;
1863     IsInline = I;
1864   }
1865 
1866   /// Flag that this function is implicitly inline.
setImplicitlyInline()1867   void setImplicitlyInline() {
1868     IsInline = true;
1869   }
1870 
1871   /// \brief Determine whether this function should be inlined, because it is
1872   /// either marked "inline" or "constexpr" or is a member function of a class
1873   /// that was defined in the class body.
1874   bool isInlined() const;
1875 
1876   bool isInlineDefinitionExternallyVisible() const;
1877 
1878   bool doesDeclarationForceExternallyVisibleDefinition() const;
1879 
1880   /// isOverloadedOperator - Whether this function declaration
1881   /// represents an C++ overloaded operator, e.g., "operator+".
isOverloadedOperator()1882   bool isOverloadedOperator() const {
1883     return getOverloadedOperator() != OO_None;
1884   }
1885 
1886   OverloadedOperatorKind getOverloadedOperator() const;
1887 
1888   const IdentifierInfo *getLiteralIdentifier() const;
1889 
1890   /// \brief If this function is an instantiation of a member function
1891   /// of a class template specialization, retrieves the function from
1892   /// which it was instantiated.
1893   ///
1894   /// This routine will return non-NULL for (non-templated) member
1895   /// functions of class templates and for instantiations of function
1896   /// templates. For example, given:
1897   ///
1898   /// \code
1899   /// template<typename T>
1900   /// struct X {
1901   ///   void f(T);
1902   /// };
1903   /// \endcode
1904   ///
1905   /// The declaration for X<int>::f is a (non-templated) FunctionDecl
1906   /// whose parent is the class template specialization X<int>. For
1907   /// this declaration, getInstantiatedFromFunction() will return
1908   /// the FunctionDecl X<T>::A. When a complete definition of
1909   /// X<int>::A is required, it will be instantiated from the
1910   /// declaration returned by getInstantiatedFromMemberFunction().
1911   FunctionDecl *getInstantiatedFromMemberFunction() const;
1912 
1913   /// \brief What kind of templated function this is.
1914   TemplatedKind getTemplatedKind() const;
1915 
1916   /// \brief If this function is an instantiation of a member function of a
1917   /// class template specialization, retrieves the member specialization
1918   /// information.
1919   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1920 
1921   /// \brief Specify that this record is an instantiation of the
1922   /// member function FD.
setInstantiationOfMemberFunction(FunctionDecl * FD,TemplateSpecializationKind TSK)1923   void setInstantiationOfMemberFunction(FunctionDecl *FD,
1924                                         TemplateSpecializationKind TSK) {
1925     setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
1926   }
1927 
1928   /// \brief Retrieves the function template that is described by this
1929   /// function declaration.
1930   ///
1931   /// Every function template is represented as a FunctionTemplateDecl
1932   /// and a FunctionDecl (or something derived from FunctionDecl). The
1933   /// former contains template properties (such as the template
1934   /// parameter lists) while the latter contains the actual
1935   /// description of the template's
1936   /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
1937   /// FunctionDecl that describes the function template,
1938   /// getDescribedFunctionTemplate() retrieves the
1939   /// FunctionTemplateDecl from a FunctionDecl.
getDescribedFunctionTemplate()1940   FunctionTemplateDecl *getDescribedFunctionTemplate() const {
1941     return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
1942   }
1943 
setDescribedFunctionTemplate(FunctionTemplateDecl * Template)1944   void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
1945     TemplateOrSpecialization = Template;
1946   }
1947 
1948   /// \brief Determine whether this function is a function template
1949   /// specialization.
isFunctionTemplateSpecialization()1950   bool isFunctionTemplateSpecialization() const {
1951     return getPrimaryTemplate() != 0;
1952   }
1953 
1954   /// \brief Retrieve the class scope template pattern that this function
1955   ///  template specialization is instantiated from.
1956   FunctionDecl *getClassScopeSpecializationPattern() const;
1957 
1958   /// \brief If this function is actually a function template specialization,
1959   /// retrieve information about this function template specialization.
1960   /// Otherwise, returns NULL.
getTemplateSpecializationInfo()1961   FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
1962     return TemplateOrSpecialization.
1963              dyn_cast<FunctionTemplateSpecializationInfo*>();
1964   }
1965 
1966   /// \brief Determines whether this function is a function template
1967   /// specialization or a member of a class template specialization that can
1968   /// be implicitly instantiated.
1969   bool isImplicitlyInstantiable() const;
1970 
1971   /// \brief Determines if the given function was instantiated from a
1972   /// function template.
1973   bool isTemplateInstantiation() const;
1974 
1975   /// \brief Retrieve the function declaration from which this function could
1976   /// be instantiated, if it is an instantiation (rather than a non-template
1977   /// or a specialization, for example).
1978   FunctionDecl *getTemplateInstantiationPattern() const;
1979 
1980   /// \brief Retrieve the primary template that this function template
1981   /// specialization either specializes or was instantiated from.
1982   ///
1983   /// If this function declaration is not a function template specialization,
1984   /// returns NULL.
1985   FunctionTemplateDecl *getPrimaryTemplate() const;
1986 
1987   /// \brief Retrieve the template arguments used to produce this function
1988   /// template specialization from the primary template.
1989   ///
1990   /// If this function declaration is not a function template specialization,
1991   /// returns NULL.
1992   const TemplateArgumentList *getTemplateSpecializationArgs() const;
1993 
1994   /// \brief Retrieve the template argument list as written in the sources,
1995   /// if any.
1996   ///
1997   /// If this function declaration is not a function template specialization
1998   /// or if it had no explicit template argument list, returns NULL.
1999   /// Note that it an explicit template argument list may be written empty,
2000   /// e.g., template<> void foo<>(char* s);
2001   const ASTTemplateArgumentListInfo*
2002   getTemplateSpecializationArgsAsWritten() const;
2003 
2004   /// \brief Specify that this function declaration is actually a function
2005   /// template specialization.
2006   ///
2007   /// \param Template the function template that this function template
2008   /// specialization specializes.
2009   ///
2010   /// \param TemplateArgs the template arguments that produced this
2011   /// function template specialization from the template.
2012   ///
2013   /// \param InsertPos If non-NULL, the position in the function template
2014   /// specialization set where the function template specialization data will
2015   /// be inserted.
2016   ///
2017   /// \param TSK the kind of template specialization this is.
2018   ///
2019   /// \param TemplateArgsAsWritten location info of template arguments.
2020   ///
2021   /// \param PointOfInstantiation point at which the function template
2022   /// specialization was first instantiated.
2023   void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2024                                       const TemplateArgumentList *TemplateArgs,
2025                                          void *InsertPos,
2026                     TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2027                     const TemplateArgumentListInfo *TemplateArgsAsWritten = 0,
2028                     SourceLocation PointOfInstantiation = SourceLocation()) {
2029     setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2030                                       InsertPos, TSK, TemplateArgsAsWritten,
2031                                       PointOfInstantiation);
2032   }
2033 
2034   /// \brief Specifies that this function declaration is actually a
2035   /// dependent function template specialization.
2036   void setDependentTemplateSpecialization(ASTContext &Context,
2037                              const UnresolvedSetImpl &Templates,
2038                       const TemplateArgumentListInfo &TemplateArgs);
2039 
2040   DependentFunctionTemplateSpecializationInfo *
getDependentSpecializationInfo()2041   getDependentSpecializationInfo() const {
2042     return TemplateOrSpecialization.
2043              dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
2044   }
2045 
2046   /// \brief Determine what kind of template instantiation this function
2047   /// represents.
2048   TemplateSpecializationKind getTemplateSpecializationKind() const;
2049 
2050   /// \brief Determine what kind of template instantiation this function
2051   /// represents.
2052   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2053                         SourceLocation PointOfInstantiation = SourceLocation());
2054 
2055   /// \brief Retrieve the (first) point of instantiation of a function template
2056   /// specialization or a member of a class template specialization.
2057   ///
2058   /// \returns the first point of instantiation, if this function was
2059   /// instantiated from a template; otherwise, returns an invalid source
2060   /// location.
2061   SourceLocation getPointOfInstantiation() const;
2062 
2063   /// \brief Determine whether this is or was instantiated from an out-of-line
2064   /// definition of a member function.
2065   virtual bool isOutOfLine() const;
2066 
2067   /// \brief Identify a memory copying or setting function.
2068   /// If the given function is a memory copy or setting function, returns
2069   /// the corresponding Builtin ID. If the function is not a memory function,
2070   /// returns 0.
2071   unsigned getMemoryFunctionKind() const;
2072 
2073   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2074   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const FunctionDecl * D)2075   static bool classof(const FunctionDecl *D) { return true; }
classofKind(Kind K)2076   static bool classofKind(Kind K) {
2077     return K >= firstFunction && K <= lastFunction;
2078   }
castToDeclContext(const FunctionDecl * D)2079   static DeclContext *castToDeclContext(const FunctionDecl *D) {
2080     return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2081   }
castFromDeclContext(const DeclContext * DC)2082   static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2083     return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2084   }
2085 
2086   friend class ASTDeclReader;
2087   friend class ASTDeclWriter;
2088 };
2089 
2090 
2091 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2092 /// represent a member of a struct/union/class.
2093 class FieldDecl : public DeclaratorDecl {
2094   // FIXME: This can be packed into the bitfields in Decl.
2095   bool Mutable : 1;
2096   mutable unsigned CachedFieldIndex : 31;
2097 
2098   /// \brief A pointer to either the in-class initializer for this field (if
2099   /// the boolean value is false), or the bit width expression for this bit
2100   /// field (if the boolean value is true).
2101   ///
2102   /// We can safely combine these two because in-class initializers are not
2103   /// permitted for bit-fields.
2104   ///
2105   /// If the boolean is false and the initializer is null, then this field has
2106   /// an in-class initializer which has not yet been parsed and attached.
2107   llvm::PointerIntPair<Expr *, 1, bool> InitializerOrBitWidth;
2108 protected:
FieldDecl(Kind DK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,Expr * BW,bool Mutable,bool HasInit)2109   FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2110             SourceLocation IdLoc, IdentifierInfo *Id,
2111             QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2112             bool HasInit)
2113     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2114       Mutable(Mutable), CachedFieldIndex(0),
2115       InitializerOrBitWidth(BW, !HasInit) {
2116     assert(!(BW && HasInit) && "got initializer for bitfield");
2117   }
2118 
2119 public:
2120   static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2121                            SourceLocation StartLoc, SourceLocation IdLoc,
2122                            IdentifierInfo *Id, QualType T,
2123                            TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2124                            bool HasInit);
2125 
2126   static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2127 
2128   /// getFieldIndex - Returns the index of this field within its record,
2129   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2130   unsigned getFieldIndex() const;
2131 
2132   /// isMutable - Determines whether this field is mutable (C++ only).
isMutable()2133   bool isMutable() const { return Mutable; }
2134 
2135   /// \brief Set whether this field is mutable (C++ only).
setMutable(bool M)2136   void setMutable(bool M) { Mutable = M; }
2137 
2138   /// isBitfield - Determines whether this field is a bitfield.
isBitField()2139   bool isBitField() const {
2140     return InitializerOrBitWidth.getInt() && InitializerOrBitWidth.getPointer();
2141   }
2142 
2143   /// @brief Determines whether this is an unnamed bitfield.
isUnnamedBitfield()2144   bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2145 
2146   /// isAnonymousStructOrUnion - Determines whether this field is a
2147   /// representative for an anonymous struct or union. Such fields are
2148   /// unnamed and are implicitly generated by the implementation to
2149   /// store the data for the anonymous union or struct.
2150   bool isAnonymousStructOrUnion() const;
2151 
getBitWidth()2152   Expr *getBitWidth() const {
2153     return isBitField() ? InitializerOrBitWidth.getPointer() : 0;
2154   }
2155   unsigned getBitWidthValue(const ASTContext &Ctx) const;
setBitWidth(Expr * BW)2156   void setBitWidth(Expr *BW) {
2157     assert(!InitializerOrBitWidth.getPointer() &&
2158            "bit width or initializer already set");
2159     InitializerOrBitWidth.setPointer(BW);
2160     InitializerOrBitWidth.setInt(1);
2161   }
2162   /// removeBitWidth - Remove the bitfield width from this member.
removeBitWidth()2163   void removeBitWidth() {
2164     assert(isBitField() && "no bit width to remove");
2165     InitializerOrBitWidth.setPointer(0);
2166   }
2167 
2168   /// hasInClassInitializer - Determine whether this member has a C++0x in-class
2169   /// initializer.
hasInClassInitializer()2170   bool hasInClassInitializer() const {
2171     return !InitializerOrBitWidth.getInt();
2172   }
2173   /// getInClassInitializer - Get the C++0x in-class initializer for this
2174   /// member, or null if one has not been set. If a valid declaration has an
2175   /// in-class initializer, but this returns null, then we have not parsed and
2176   /// attached it yet.
getInClassInitializer()2177   Expr *getInClassInitializer() const {
2178     return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0;
2179   }
2180   /// setInClassInitializer - Set the C++0x in-class initializer for this
2181   /// member.
2182   void setInClassInitializer(Expr *Init);
2183   /// removeInClassInitializer - Remove the C++0x in-class initializer from this
2184   /// member.
removeInClassInitializer()2185   void removeInClassInitializer() {
2186     assert(!InitializerOrBitWidth.getInt() && "no initializer to remove");
2187     InitializerOrBitWidth.setPointer(0);
2188     InitializerOrBitWidth.setInt(1);
2189   }
2190 
2191   /// getParent - Returns the parent of this field declaration, which
2192   /// is the struct in which this method is defined.
getParent()2193   const RecordDecl *getParent() const {
2194     return cast<RecordDecl>(getDeclContext());
2195   }
2196 
getParent()2197   RecordDecl *getParent() {
2198     return cast<RecordDecl>(getDeclContext());
2199   }
2200 
2201   SourceRange getSourceRange() const LLVM_READONLY;
2202 
2203   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2204   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const FieldDecl * D)2205   static bool classof(const FieldDecl *D) { return true; }
classofKind(Kind K)2206   static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2207 };
2208 
2209 /// EnumConstantDecl - An instance of this object exists for each enum constant
2210 /// that is defined.  For example, in "enum X {a,b}", each of a/b are
2211 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2212 /// TagType for the X EnumDecl.
2213 class EnumConstantDecl : public ValueDecl {
2214   Stmt *Init; // an integer constant expression
2215   llvm::APSInt Val; // The value.
2216 protected:
EnumConstantDecl(DeclContext * DC,SourceLocation L,IdentifierInfo * Id,QualType T,Expr * E,const llvm::APSInt & V)2217   EnumConstantDecl(DeclContext *DC, SourceLocation L,
2218                    IdentifierInfo *Id, QualType T, Expr *E,
2219                    const llvm::APSInt &V)
2220     : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2221 
2222 public:
2223 
2224   static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2225                                   SourceLocation L, IdentifierInfo *Id,
2226                                   QualType T, Expr *E,
2227                                   const llvm::APSInt &V);
2228   static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2229 
getInitExpr()2230   const Expr *getInitExpr() const { return (const Expr*) Init; }
getInitExpr()2231   Expr *getInitExpr() { return (Expr*) Init; }
getInitVal()2232   const llvm::APSInt &getInitVal() const { return Val; }
2233 
setInitExpr(Expr * E)2234   void setInitExpr(Expr *E) { Init = (Stmt*) E; }
setInitVal(const llvm::APSInt & V)2235   void setInitVal(const llvm::APSInt &V) { Val = V; }
2236 
2237   SourceRange getSourceRange() const LLVM_READONLY;
2238 
2239   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2240   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const EnumConstantDecl * D)2241   static bool classof(const EnumConstantDecl *D) { return true; }
classofKind(Kind K)2242   static bool classofKind(Kind K) { return K == EnumConstant; }
2243 
2244   friend class StmtIteratorBase;
2245 };
2246 
2247 /// IndirectFieldDecl - An instance of this class is created to represent a
2248 /// field injected from an anonymous union/struct into the parent scope.
2249 /// IndirectFieldDecl are always implicit.
2250 class IndirectFieldDecl : public ValueDecl {
2251   virtual void anchor();
2252   NamedDecl **Chaining;
2253   unsigned ChainingSize;
2254 
IndirectFieldDecl(DeclContext * DC,SourceLocation L,DeclarationName N,QualType T,NamedDecl ** CH,unsigned CHS)2255   IndirectFieldDecl(DeclContext *DC, SourceLocation L,
2256                     DeclarationName N, QualType T,
2257                     NamedDecl **CH, unsigned CHS)
2258     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
2259 
2260 public:
2261   static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2262                                    SourceLocation L, IdentifierInfo *Id,
2263                                    QualType T, NamedDecl **CH, unsigned CHS);
2264 
2265   static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2266 
2267   typedef NamedDecl * const *chain_iterator;
chain_begin()2268   chain_iterator chain_begin() const { return Chaining; }
chain_end()2269   chain_iterator chain_end() const  { return Chaining+ChainingSize; }
2270 
getChainingSize()2271   unsigned getChainingSize() const { return ChainingSize; }
2272 
getAnonField()2273   FieldDecl *getAnonField() const {
2274     assert(ChainingSize >= 2);
2275     return cast<FieldDecl>(Chaining[ChainingSize - 1]);
2276   }
2277 
getVarDecl()2278   VarDecl *getVarDecl() const {
2279     assert(ChainingSize >= 2);
2280     return dyn_cast<VarDecl>(*chain_begin());
2281   }
2282 
2283   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2284   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const IndirectFieldDecl * D)2285   static bool classof(const IndirectFieldDecl *D) { return true; }
classofKind(Kind K)2286   static bool classofKind(Kind K) { return K == IndirectField; }
2287   friend class ASTDeclReader;
2288 };
2289 
2290 /// TypeDecl - Represents a declaration of a type.
2291 ///
2292 class TypeDecl : public NamedDecl {
2293   virtual void anchor();
2294   /// TypeForDecl - This indicates the Type object that represents
2295   /// this TypeDecl.  It is a cache maintained by
2296   /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2297   /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2298   mutable const Type *TypeForDecl;
2299   /// LocStart - The start of the source range for this declaration.
2300   SourceLocation LocStart;
2301   friend class ASTContext;
2302   friend class DeclContext;
2303   friend class TagDecl;
2304   friend class TemplateTypeParmDecl;
2305   friend class TagType;
2306   friend class ASTReader;
2307 
2308 protected:
2309   TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2310            SourceLocation StartL = SourceLocation())
NamedDecl(DK,DC,L,Id)2311     : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {}
2312 
2313 public:
2314   // Low-level accessor
getTypeForDecl()2315   const Type *getTypeForDecl() const { return TypeForDecl; }
setTypeForDecl(const Type * TD)2316   void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2317 
getLocStart()2318   SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
setLocStart(SourceLocation L)2319   void setLocStart(SourceLocation L) { LocStart = L; }
getSourceRange()2320   virtual SourceRange getSourceRange() const LLVM_READONLY {
2321     if (LocStart.isValid())
2322       return SourceRange(LocStart, getLocation());
2323     else
2324       return SourceRange(getLocation());
2325   }
2326 
2327   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2328   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const TypeDecl * D)2329   static bool classof(const TypeDecl *D) { return true; }
classofKind(Kind K)2330   static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2331 };
2332 
2333 
2334 /// Base class for declarations which introduce a typedef-name.
2335 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2336   virtual void anchor();
2337   /// UnderlyingType - This is the type the typedef is set to.
2338   TypeSourceInfo *TInfo;
2339 
2340 protected:
TypedefNameDecl(Kind DK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)2341   TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2342                   SourceLocation IdLoc, IdentifierInfo *Id,
2343                   TypeSourceInfo *TInfo)
2344     : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {}
2345 
2346   typedef Redeclarable<TypedefNameDecl> redeclarable_base;
getNextRedeclaration()2347   virtual TypedefNameDecl *getNextRedeclaration() {
2348     return RedeclLink.getNext();
2349   }
getPreviousDeclImpl()2350   virtual TypedefNameDecl *getPreviousDeclImpl() {
2351     return getPreviousDecl();
2352   }
getMostRecentDeclImpl()2353   virtual TypedefNameDecl *getMostRecentDeclImpl() {
2354     return getMostRecentDecl();
2355   }
2356 
2357 public:
2358   typedef redeclarable_base::redecl_iterator redecl_iterator;
2359   using redeclarable_base::redecls_begin;
2360   using redeclarable_base::redecls_end;
2361   using redeclarable_base::getPreviousDecl;
2362   using redeclarable_base::getMostRecentDecl;
2363 
getTypeSourceInfo()2364   TypeSourceInfo *getTypeSourceInfo() const {
2365     return TInfo;
2366   }
2367 
2368   /// Retrieves the canonical declaration of this typedef-name.
getCanonicalDecl()2369   TypedefNameDecl *getCanonicalDecl() {
2370     return getFirstDeclaration();
2371   }
getCanonicalDecl()2372   const TypedefNameDecl *getCanonicalDecl() const {
2373     return getFirstDeclaration();
2374   }
2375 
getUnderlyingType()2376   QualType getUnderlyingType() const {
2377     return TInfo->getType();
2378   }
setTypeSourceInfo(TypeSourceInfo * newType)2379   void setTypeSourceInfo(TypeSourceInfo *newType) {
2380     TInfo = newType;
2381   }
2382 
2383   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2384   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const TypedefNameDecl * D)2385   static bool classof(const TypedefNameDecl *D) { return true; }
classofKind(Kind K)2386   static bool classofKind(Kind K) {
2387     return K >= firstTypedefName && K <= lastTypedefName;
2388   }
2389 };
2390 
2391 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2392 /// type specifier.
2393 class TypedefDecl : public TypedefNameDecl {
TypedefDecl(DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)2394   TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2395               IdentifierInfo *Id, TypeSourceInfo *TInfo)
2396     : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {}
2397 
2398 public:
2399   static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2400                              SourceLocation StartLoc, SourceLocation IdLoc,
2401                              IdentifierInfo *Id, TypeSourceInfo *TInfo);
2402   static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2403 
2404   SourceRange getSourceRange() const LLVM_READONLY;
2405 
2406   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2407   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const TypedefDecl * D)2408   static bool classof(const TypedefDecl *D) { return true; }
classofKind(Kind K)2409   static bool classofKind(Kind K) { return K == Typedef; }
2410 };
2411 
2412 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2413 /// alias-declaration.
2414 class TypeAliasDecl : public TypedefNameDecl {
TypeAliasDecl(DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)2415   TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2416                 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2417     : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {}
2418 
2419 public:
2420   static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2421                                SourceLocation StartLoc, SourceLocation IdLoc,
2422                                IdentifierInfo *Id, TypeSourceInfo *TInfo);
2423   static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2424 
2425   SourceRange getSourceRange() const LLVM_READONLY;
2426 
2427   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2428   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const TypeAliasDecl * D)2429   static bool classof(const TypeAliasDecl *D) { return true; }
classofKind(Kind K)2430   static bool classofKind(Kind K) { return K == TypeAlias; }
2431 };
2432 
2433 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2434 class TagDecl
2435   : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2436 public:
2437   // This is really ugly.
2438   typedef TagTypeKind TagKind;
2439 
2440 private:
2441   // FIXME: This can be packed into the bitfields in Decl.
2442   /// TagDeclKind - The TagKind enum.
2443   unsigned TagDeclKind : 2;
2444 
2445   /// IsCompleteDefinition - True if this is a definition ("struct foo
2446   /// {};"), false if it is a declaration ("struct foo;").  It is not
2447   /// a definition until the definition has been fully processed.
2448   bool IsCompleteDefinition : 1;
2449 
2450 protected:
2451   /// IsBeingDefined - True if this is currently being defined.
2452   bool IsBeingDefined : 1;
2453 
2454 private:
2455   /// IsEmbeddedInDeclarator - True if this tag declaration is
2456   /// "embedded" (i.e., defined or declared for the very first time)
2457   /// in the syntax of a declarator.
2458   bool IsEmbeddedInDeclarator : 1;
2459 
2460   /// \brief True if this tag is free standing, e.g. "struct foo;".
2461   bool IsFreeStanding : 1;
2462 
2463 protected:
2464   // These are used by (and only defined for) EnumDecl.
2465   unsigned NumPositiveBits : 8;
2466   unsigned NumNegativeBits : 8;
2467 
2468   /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2469   /// possible in C++11 mode.
2470   bool IsScoped : 1;
2471   /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2472   /// then this is true if the scoped enum was declared using the class
2473   /// tag, false if it was declared with the struct tag. No meaning is
2474   /// associated if this tag declaration is not a scoped enum.
2475   bool IsScopedUsingClassTag : 1;
2476 
2477   /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2478   /// possible in C++11 or Microsoft extensions mode.
2479   bool IsFixed : 1;
2480 
2481 private:
2482   SourceLocation RBraceLoc;
2483 
2484   // A struct representing syntactic qualifier info,
2485   // to be used for the (uncommon) case of out-of-line declarations.
2486   typedef QualifierInfo ExtInfo;
2487 
2488   /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name
2489   /// is qualified, it points to the qualifier info (nns and range);
2490   /// otherwise, if the tag declaration is anonymous and it is part of
2491   /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2492   /// otherwise, it is a null (TypedefNameDecl) pointer.
2493   llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier;
2494 
hasExtInfo()2495   bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); }
getExtInfo()2496   ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); }
getExtInfo()2497   const ExtInfo *getExtInfo() const {
2498     return TypedefNameDeclOrQualifier.get<ExtInfo*>();
2499   }
2500 
2501 protected:
TagDecl(Kind DK,TagKind TK,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,TagDecl * PrevDecl,SourceLocation StartL)2502   TagDecl(Kind DK, TagKind TK, DeclContext *DC,
2503           SourceLocation L, IdentifierInfo *Id,
2504           TagDecl *PrevDecl, SourceLocation StartL)
2505     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK),
2506       TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) {
2507     assert((DK != Enum || TK == TTK_Enum) &&
2508            "EnumDecl not matched with TTK_Enum");
2509     TagDeclKind = TK;
2510     IsCompleteDefinition = false;
2511     IsBeingDefined = false;
2512     IsEmbeddedInDeclarator = false;
2513     IsFreeStanding = false;
2514     setPreviousDeclaration(PrevDecl);
2515   }
2516 
2517   typedef Redeclarable<TagDecl> redeclarable_base;
getNextRedeclaration()2518   virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
getPreviousDeclImpl()2519   virtual TagDecl *getPreviousDeclImpl() {
2520     return getPreviousDecl();
2521   }
getMostRecentDeclImpl()2522   virtual TagDecl *getMostRecentDeclImpl() {
2523     return getMostRecentDecl();
2524   }
2525 
2526   /// @brief Completes the definition of this tag declaration.
2527   ///
2528   /// This is a helper function for derived classes.
2529   void completeDefinition();
2530 
2531 public:
2532   typedef redeclarable_base::redecl_iterator redecl_iterator;
2533   using redeclarable_base::redecls_begin;
2534   using redeclarable_base::redecls_end;
2535   using redeclarable_base::getPreviousDecl;
2536   using redeclarable_base::getMostRecentDecl;
2537 
getRBraceLoc()2538   SourceLocation getRBraceLoc() const { return RBraceLoc; }
setRBraceLoc(SourceLocation L)2539   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
2540 
2541   /// getInnerLocStart - Return SourceLocation representing start of source
2542   /// range ignoring outer template declarations.
getInnerLocStart()2543   SourceLocation getInnerLocStart() const { return getLocStart(); }
2544 
2545   /// getOuterLocStart - Return SourceLocation representing start of source
2546   /// range taking into account any outer template declarations.
2547   SourceLocation getOuterLocStart() const;
2548   virtual SourceRange getSourceRange() const LLVM_READONLY;
2549 
2550   virtual TagDecl* getCanonicalDecl();
getCanonicalDecl()2551   const TagDecl* getCanonicalDecl() const {
2552     return const_cast<TagDecl*>(this)->getCanonicalDecl();
2553   }
2554 
2555   /// isThisDeclarationADefinition() - Return true if this declaration
2556   /// is a completion definintion of the type.  Provided for consistency.
isThisDeclarationADefinition()2557   bool isThisDeclarationADefinition() const {
2558     return isCompleteDefinition();
2559   }
2560 
2561   /// isCompleteDefinition - Return true if this decl has its body
2562   /// fully specified.
isCompleteDefinition()2563   bool isCompleteDefinition() const {
2564     return IsCompleteDefinition;
2565   }
2566 
2567   /// isBeingDefined - Return true if this decl is currently being defined.
isBeingDefined()2568   bool isBeingDefined() const {
2569     return IsBeingDefined;
2570   }
2571 
isEmbeddedInDeclarator()2572   bool isEmbeddedInDeclarator() const {
2573     return IsEmbeddedInDeclarator;
2574   }
setEmbeddedInDeclarator(bool isInDeclarator)2575   void setEmbeddedInDeclarator(bool isInDeclarator) {
2576     IsEmbeddedInDeclarator = isInDeclarator;
2577   }
2578 
isFreeStanding()2579   bool isFreeStanding() const { return IsFreeStanding; }
2580   void setFreeStanding(bool isFreeStanding = true) {
2581     IsFreeStanding = isFreeStanding;
2582   }
2583 
2584   /// \brief Whether this declaration declares a type that is
2585   /// dependent, i.e., a type that somehow depends on template
2586   /// parameters.
isDependentType()2587   bool isDependentType() const { return isDependentContext(); }
2588 
2589   /// @brief Starts the definition of this tag declaration.
2590   ///
2591   /// This method should be invoked at the beginning of the definition
2592   /// of this tag declaration. It will set the tag type into a state
2593   /// where it is in the process of being defined.
2594   void startDefinition();
2595 
2596   /// getDefinition - Returns the TagDecl that actually defines this
2597   ///  struct/union/class/enum.  When determining whether or not a
2598   ///  struct/union/class/enum has a definition, one should use this
2599   ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
2600   ///  whether or not a specific TagDecl is defining declaration, not
2601   ///  whether or not the struct/union/class/enum type is defined.
2602   ///  This method returns NULL if there is no TagDecl that defines
2603   ///  the struct/union/class/enum.
2604   TagDecl *getDefinition() const;
2605 
setCompleteDefinition(bool V)2606   void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2607 
getKindName()2608   const char *getKindName() const {
2609     return TypeWithKeyword::getTagTypeKindName(getTagKind());
2610   }
2611 
getTagKind()2612   TagKind getTagKind() const {
2613     return TagKind(TagDeclKind);
2614   }
2615 
setTagKind(TagKind TK)2616   void setTagKind(TagKind TK) { TagDeclKind = TK; }
2617 
isStruct()2618   bool isStruct() const { return getTagKind() == TTK_Struct; }
isClass()2619   bool isClass()  const { return getTagKind() == TTK_Class; }
isUnion()2620   bool isUnion()  const { return getTagKind() == TTK_Union; }
isEnum()2621   bool isEnum()   const { return getTagKind() == TTK_Enum; }
2622 
getTypedefNameForAnonDecl()2623   TypedefNameDecl *getTypedefNameForAnonDecl() const {
2624     return hasExtInfo() ? 0 :
2625            TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
2626   }
2627 
2628   void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2629 
2630   /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2631   /// declaration, if it was present in the source.
getQualifier()2632   NestedNameSpecifier *getQualifier() const {
2633     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2634                         : 0;
2635   }
2636 
2637   /// \brief Retrieve the nested-name-specifier (with source-location
2638   /// information) that qualifies the name of this declaration, if it was
2639   /// present in the source.
getQualifierLoc()2640   NestedNameSpecifierLoc getQualifierLoc() const {
2641     return hasExtInfo() ? getExtInfo()->QualifierLoc
2642                         : NestedNameSpecifierLoc();
2643   }
2644 
2645   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
2646 
getNumTemplateParameterLists()2647   unsigned getNumTemplateParameterLists() const {
2648     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
2649   }
getTemplateParameterList(unsigned i)2650   TemplateParameterList *getTemplateParameterList(unsigned i) const {
2651     assert(i < getNumTemplateParameterLists());
2652     return getExtInfo()->TemplParamLists[i];
2653   }
2654   void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
2655                                      TemplateParameterList **TPLists);
2656 
2657   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2658   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const TagDecl * D)2659   static bool classof(const TagDecl *D) { return true; }
classofKind(Kind K)2660   static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
2661 
castToDeclContext(const TagDecl * D)2662   static DeclContext *castToDeclContext(const TagDecl *D) {
2663     return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
2664   }
castFromDeclContext(const DeclContext * DC)2665   static TagDecl *castFromDeclContext(const DeclContext *DC) {
2666     return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
2667   }
2668 
2669   friend class ASTDeclReader;
2670   friend class ASTDeclWriter;
2671 };
2672 
2673 /// EnumDecl - Represents an enum.  In C++11, enums can be forward-declared
2674 /// with a fixed underlying type, and in C we allow them to be forward-declared
2675 /// with no underlying type as an extension.
2676 class EnumDecl : public TagDecl {
2677   virtual void anchor();
2678   /// IntegerType - This represent the integer type that the enum corresponds
2679   /// to for code generation purposes.  Note that the enumerator constants may
2680   /// have a different type than this does.
2681   ///
2682   /// If the underlying integer type was explicitly stated in the source
2683   /// code, this is a TypeSourceInfo* for that type. Otherwise this type
2684   /// was automatically deduced somehow, and this is a Type*.
2685   ///
2686   /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
2687   /// some cases it won't.
2688   ///
2689   /// The underlying type of an enumeration never has any qualifiers, so
2690   /// we can get away with just storing a raw Type*, and thus save an
2691   /// extra pointer when TypeSourceInfo is needed.
2692 
2693   llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
2694 
2695   /// PromotionType - The integer type that values of this type should
2696   /// promote to.  In C, enumerators are generally of an integer type
2697   /// directly, but gcc-style large enumerators (and all enumerators
2698   /// in C++) are of the enum type instead.
2699   QualType PromotionType;
2700 
2701   /// \brief If this enumeration is an instantiation of a member enumeration
2702   /// of a class template specialization, this is the member specialization
2703   /// information.
2704   MemberSpecializationInfo *SpecializationInfo;
2705 
EnumDecl(DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool Scoped,bool ScopedUsingClassTag,bool Fixed)2706   EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
2707            IdentifierInfo *Id, EnumDecl *PrevDecl,
2708            bool Scoped, bool ScopedUsingClassTag, bool Fixed)
2709     : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
2710       SpecializationInfo(0) {
2711     assert(Scoped || !ScopedUsingClassTag);
2712     IntegerType = (const Type*)0;
2713     NumNegativeBits = 0;
2714     NumPositiveBits = 0;
2715     IsScoped = Scoped;
2716     IsScopedUsingClassTag = ScopedUsingClassTag;
2717     IsFixed = Fixed;
2718   }
2719 
2720   void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2721                                     TemplateSpecializationKind TSK);
2722 public:
getCanonicalDecl()2723   EnumDecl *getCanonicalDecl() {
2724     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2725   }
getCanonicalDecl()2726   const EnumDecl *getCanonicalDecl() const {
2727     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
2728   }
2729 
getPreviousDecl()2730   const EnumDecl *getPreviousDecl() const {
2731     return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2732   }
getPreviousDecl()2733   EnumDecl *getPreviousDecl() {
2734     return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
2735   }
2736 
getMostRecentDecl()2737   const EnumDecl *getMostRecentDecl() const {
2738     return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2739   }
getMostRecentDecl()2740   EnumDecl *getMostRecentDecl() {
2741     return cast<EnumDecl>(TagDecl::getMostRecentDecl());
2742   }
2743 
getDefinition()2744   EnumDecl *getDefinition() const {
2745     return cast_or_null<EnumDecl>(TagDecl::getDefinition());
2746   }
2747 
2748   static EnumDecl *Create(ASTContext &C, DeclContext *DC,
2749                           SourceLocation StartLoc, SourceLocation IdLoc,
2750                           IdentifierInfo *Id, EnumDecl *PrevDecl,
2751                           bool IsScoped, bool IsScopedUsingClassTag,
2752                           bool IsFixed);
2753   static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2754 
2755   /// completeDefinition - When created, the EnumDecl corresponds to a
2756   /// forward-declared enum. This method is used to mark the
2757   /// declaration as being defined; it's enumerators have already been
2758   /// added (via DeclContext::addDecl). NewType is the new underlying
2759   /// type of the enumeration type.
2760   void completeDefinition(QualType NewType,
2761                           QualType PromotionType,
2762                           unsigned NumPositiveBits,
2763                           unsigned NumNegativeBits);
2764 
2765   // enumerator_iterator - Iterates through the enumerators of this
2766   // enumeration.
2767   typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
2768 
enumerator_begin()2769   enumerator_iterator enumerator_begin() const {
2770     const EnumDecl *E = getDefinition();
2771     if (!E)
2772       E = this;
2773     return enumerator_iterator(E->decls_begin());
2774   }
2775 
enumerator_end()2776   enumerator_iterator enumerator_end() const {
2777     const EnumDecl *E = getDefinition();
2778     if (!E)
2779       E = this;
2780     return enumerator_iterator(E->decls_end());
2781   }
2782 
2783   /// getPromotionType - Return the integer type that enumerators
2784   /// should promote to.
getPromotionType()2785   QualType getPromotionType() const { return PromotionType; }
2786 
2787   /// \brief Set the promotion type.
setPromotionType(QualType T)2788   void setPromotionType(QualType T) { PromotionType = T; }
2789 
2790   /// getIntegerType - Return the integer type this enum decl corresponds to.
2791   /// This returns a null qualtype for an enum forward definition.
getIntegerType()2792   QualType getIntegerType() const {
2793     if (!IntegerType)
2794       return QualType();
2795     if (const Type* T = IntegerType.dyn_cast<const Type*>())
2796       return QualType(T, 0);
2797     return IntegerType.get<TypeSourceInfo*>()->getType();
2798   }
2799 
2800   /// \brief Set the underlying integer type.
setIntegerType(QualType T)2801   void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
2802 
2803   /// \brief Set the underlying integer type source info.
setIntegerTypeSourceInfo(TypeSourceInfo * TInfo)2804   void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; }
2805 
2806   /// \brief Return the type source info for the underlying integer type,
2807   /// if no type source info exists, return 0.
getIntegerTypeSourceInfo()2808   TypeSourceInfo* getIntegerTypeSourceInfo() const {
2809     return IntegerType.dyn_cast<TypeSourceInfo*>();
2810   }
2811 
2812   /// \brief Returns the width in bits required to store all the
2813   /// non-negative enumerators of this enum.
getNumPositiveBits()2814   unsigned getNumPositiveBits() const {
2815     return NumPositiveBits;
2816   }
setNumPositiveBits(unsigned Num)2817   void setNumPositiveBits(unsigned Num) {
2818     NumPositiveBits = Num;
2819     assert(NumPositiveBits == Num && "can't store this bitcount");
2820   }
2821 
2822   /// \brief Returns the width in bits required to store all the
2823   /// negative enumerators of this enum.  These widths include
2824   /// the rightmost leading 1;  that is:
2825   ///
2826   /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
2827   /// ------------------------     -------     -----------------
2828   ///                       -1     1111111                     1
2829   ///                      -10     1110110                     5
2830   ///                     -101     1001011                     8
getNumNegativeBits()2831   unsigned getNumNegativeBits() const {
2832     return NumNegativeBits;
2833   }
setNumNegativeBits(unsigned Num)2834   void setNumNegativeBits(unsigned Num) {
2835     NumNegativeBits = Num;
2836   }
2837 
2838   /// \brief Returns true if this is a C++0x scoped enumeration.
isScoped()2839   bool isScoped() const {
2840     return IsScoped;
2841   }
2842 
2843   /// \brief Returns true if this is a C++0x scoped enumeration.
isScopedUsingClassTag()2844   bool isScopedUsingClassTag() const {
2845     return IsScopedUsingClassTag;
2846   }
2847 
2848   /// \brief Returns true if this is a C++0x enumeration with fixed underlying
2849   /// type.
isFixed()2850   bool isFixed() const {
2851     return IsFixed;
2852   }
2853 
2854   /// \brief Returns true if this can be considered a complete type.
isComplete()2855   bool isComplete() const {
2856     return isCompleteDefinition() || isFixed();
2857   }
2858 
2859   /// \brief Returns the enumeration (declared within the template)
2860   /// from which this enumeration type was instantiated, or NULL if
2861   /// this enumeration was not instantiated from any template.
2862   EnumDecl *getInstantiatedFromMemberEnum() const;
2863 
2864   /// \brief If this enumeration is a member of a specialization of a
2865   /// templated class, determine what kind of template specialization
2866   /// or instantiation this is.
2867   TemplateSpecializationKind getTemplateSpecializationKind() const;
2868 
2869   /// \brief For an enumeration member that was instantiated from a member
2870   /// enumeration of a templated class, set the template specialiation kind.
2871   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2872                         SourceLocation PointOfInstantiation = SourceLocation());
2873 
2874   /// \brief If this enumeration is an instantiation of a member enumeration of
2875   /// a class template specialization, retrieves the member specialization
2876   /// information.
getMemberSpecializationInfo()2877   MemberSpecializationInfo *getMemberSpecializationInfo() const {
2878     return SpecializationInfo;
2879   }
2880 
2881   /// \brief Specify that this enumeration is an instantiation of the
2882   /// member enumeration ED.
setInstantiationOfMemberEnum(EnumDecl * ED,TemplateSpecializationKind TSK)2883   void setInstantiationOfMemberEnum(EnumDecl *ED,
2884                                     TemplateSpecializationKind TSK) {
2885     setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
2886   }
2887 
classof(const Decl * D)2888   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const EnumDecl * D)2889   static bool classof(const EnumDecl *D) { return true; }
classofKind(Kind K)2890   static bool classofKind(Kind K) { return K == Enum; }
2891 
2892   friend class ASTDeclReader;
2893 };
2894 
2895 
2896 /// RecordDecl - Represents a struct/union/class.  For example:
2897 ///   struct X;                  // Forward declaration, no "body".
2898 ///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
2899 /// This decl will be marked invalid if *any* members are invalid.
2900 ///
2901 class RecordDecl : public TagDecl {
2902   // FIXME: This can be packed into the bitfields in Decl.
2903   /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
2904   /// array member (e.g. int X[]) or if this union contains a struct that does.
2905   /// If so, this cannot be contained in arrays or other structs as a member.
2906   bool HasFlexibleArrayMember : 1;
2907 
2908   /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
2909   /// or union.
2910   bool AnonymousStructOrUnion : 1;
2911 
2912   /// HasObjectMember - This is true if this struct has at least one member
2913   /// containing an Objective-C object pointer type.
2914   bool HasObjectMember : 1;
2915 
2916   /// \brief Whether the field declarations of this record have been loaded
2917   /// from external storage. To avoid unnecessary deserialization of
2918   /// methods/nested types we allow deserialization of just the fields
2919   /// when needed.
2920   mutable bool LoadedFieldsFromExternalStorage : 1;
2921   friend class DeclContext;
2922 
2923 protected:
2924   RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2925              SourceLocation StartLoc, SourceLocation IdLoc,
2926              IdentifierInfo *Id, RecordDecl *PrevDecl);
2927 
2928 public:
2929   static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2930                             SourceLocation StartLoc, SourceLocation IdLoc,
2931                             IdentifierInfo *Id, RecordDecl* PrevDecl = 0);
2932   static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
2933 
getPreviousDecl()2934   const RecordDecl *getPreviousDecl() const {
2935     return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2936   }
getPreviousDecl()2937   RecordDecl *getPreviousDecl() {
2938     return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
2939   }
2940 
getMostRecentDecl()2941   const RecordDecl *getMostRecentDecl() const {
2942     return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2943   }
getMostRecentDecl()2944   RecordDecl *getMostRecentDecl() {
2945     return cast<RecordDecl>(TagDecl::getMostRecentDecl());
2946   }
2947 
hasFlexibleArrayMember()2948   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
setHasFlexibleArrayMember(bool V)2949   void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
2950 
2951   /// isAnonymousStructOrUnion - Whether this is an anonymous struct
2952   /// or union. To be an anonymous struct or union, it must have been
2953   /// declared without a name and there must be no objects of this
2954   /// type declared, e.g.,
2955   /// @code
2956   ///   union { int i; float f; };
2957   /// @endcode
2958   /// is an anonymous union but neither of the following are:
2959   /// @code
2960   ///  union X { int i; float f; };
2961   ///  union { int i; float f; } obj;
2962   /// @endcode
isAnonymousStructOrUnion()2963   bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
setAnonymousStructOrUnion(bool Anon)2964   void setAnonymousStructOrUnion(bool Anon) {
2965     AnonymousStructOrUnion = Anon;
2966   }
2967 
hasObjectMember()2968   bool hasObjectMember() const { return HasObjectMember; }
setHasObjectMember(bool val)2969   void setHasObjectMember (bool val) { HasObjectMember = val; }
2970 
2971   /// \brief Determines whether this declaration represents the
2972   /// injected class name.
2973   ///
2974   /// The injected class name in C++ is the name of the class that
2975   /// appears inside the class itself. For example:
2976   ///
2977   /// \code
2978   /// struct C {
2979   ///   // C is implicitly declared here as a synonym for the class name.
2980   /// };
2981   ///
2982   /// C::C c; // same as "C c;"
2983   /// \endcode
2984   bool isInjectedClassName() const;
2985 
2986   /// getDefinition - Returns the RecordDecl that actually defines
2987   ///  this struct/union/class.  When determining whether or not a
2988   ///  struct/union/class is completely defined, one should use this
2989   ///  method as opposed to 'isCompleteDefinition'.
2990   ///  'isCompleteDefinition' indicates whether or not a specific
2991   ///  RecordDecl is a completed definition, not whether or not the
2992   ///  record type is defined.  This method returns NULL if there is
2993   ///  no RecordDecl that defines the struct/union/tag.
getDefinition()2994   RecordDecl *getDefinition() const {
2995     return cast_or_null<RecordDecl>(TagDecl::getDefinition());
2996   }
2997 
2998   // Iterator access to field members. The field iterator only visits
2999   // the non-static data members of this class, ignoring any static
3000   // data members, functions, constructors, destructors, etc.
3001   typedef specific_decl_iterator<FieldDecl> field_iterator;
3002 
3003   field_iterator field_begin() const;
3004 
field_end()3005   field_iterator field_end() const {
3006     return field_iterator(decl_iterator());
3007   }
3008 
3009   // field_empty - Whether there are any fields (non-static data
3010   // members) in this record.
field_empty()3011   bool field_empty() const {
3012     return field_begin() == field_end();
3013   }
3014 
3015   /// completeDefinition - Notes that the definition of this type is
3016   /// now complete.
3017   virtual void completeDefinition();
3018 
classof(const Decl * D)3019   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const RecordDecl * D)3020   static bool classof(const RecordDecl *D) { return true; }
classofKind(Kind K)3021   static bool classofKind(Kind K) {
3022     return K >= firstRecord && K <= lastRecord;
3023   }
3024 
3025 private:
3026   /// \brief Deserialize just the fields.
3027   void LoadFieldsFromExternalStorage() const;
3028 };
3029 
3030 class FileScopeAsmDecl : public Decl {
3031   virtual void anchor();
3032   StringLiteral *AsmString;
3033   SourceLocation RParenLoc;
FileScopeAsmDecl(DeclContext * DC,StringLiteral * asmstring,SourceLocation StartL,SourceLocation EndL)3034   FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3035                    SourceLocation StartL, SourceLocation EndL)
3036     : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3037 public:
3038   static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3039                                   StringLiteral *Str, SourceLocation AsmLoc,
3040                                   SourceLocation RParenLoc);
3041 
3042   static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3043 
getAsmLoc()3044   SourceLocation getAsmLoc() const { return getLocation(); }
getRParenLoc()3045   SourceLocation getRParenLoc() const { return RParenLoc; }
setRParenLoc(SourceLocation L)3046   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
getSourceRange()3047   SourceRange getSourceRange() const LLVM_READONLY {
3048     return SourceRange(getAsmLoc(), getRParenLoc());
3049   }
3050 
getAsmString()3051   const StringLiteral *getAsmString() const { return AsmString; }
getAsmString()3052   StringLiteral *getAsmString() { return AsmString; }
setAsmString(StringLiteral * Asm)3053   void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3054 
classof(const Decl * D)3055   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const FileScopeAsmDecl * D)3056   static bool classof(const FileScopeAsmDecl *D) { return true; }
classofKind(Kind K)3057   static bool classofKind(Kind K) { return K == FileScopeAsm; }
3058 };
3059 
3060 /// BlockDecl - This represents a block literal declaration, which is like an
3061 /// unnamed FunctionDecl.  For example:
3062 /// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3063 ///
3064 class BlockDecl : public Decl, public DeclContext {
3065 public:
3066   /// A class which contains all the information about a particular
3067   /// captured value.
3068   class Capture {
3069     enum {
3070       flag_isByRef = 0x1,
3071       flag_isNested = 0x2
3072     };
3073 
3074     /// The variable being captured.
3075     llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3076 
3077     /// The copy expression, expressed in terms of a DeclRef (or
3078     /// BlockDeclRef) to the captured variable.  Only required if the
3079     /// variable has a C++ class type.
3080     Expr *CopyExpr;
3081 
3082   public:
Capture(VarDecl * variable,bool byRef,bool nested,Expr * copy)3083     Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3084       : VariableAndFlags(variable,
3085                   (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3086         CopyExpr(copy) {}
3087 
3088     /// The variable being captured.
getVariable()3089     VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3090 
3091     /// Whether this is a "by ref" capture, i.e. a capture of a __block
3092     /// variable.
isByRef()3093     bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3094 
3095     /// Whether this is a nested capture, i.e. the variable captured
3096     /// is not from outside the immediately enclosing function/block.
isNested()3097     bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3098 
hasCopyExpr()3099     bool hasCopyExpr() const { return CopyExpr != 0; }
getCopyExpr()3100     Expr *getCopyExpr() const { return CopyExpr; }
setCopyExpr(Expr * e)3101     void setCopyExpr(Expr *e) { CopyExpr = e; }
3102   };
3103 
3104 private:
3105   // FIXME: This can be packed into the bitfields in Decl.
3106   bool IsVariadic : 1;
3107   bool CapturesCXXThis : 1;
3108   bool BlockMissingReturnType : 1;
3109   bool IsConversionFromLambda : 1;
3110   /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3111   /// parameters of this function.  This is null if a prototype or if there are
3112   /// no formals.
3113   ParmVarDecl **ParamInfo;
3114   unsigned NumParams;
3115 
3116   Stmt *Body;
3117   TypeSourceInfo *SignatureAsWritten;
3118 
3119   Capture *Captures;
3120   unsigned NumCaptures;
3121 
3122 protected:
BlockDecl(DeclContext * DC,SourceLocation CaretLoc)3123   BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3124     : Decl(Block, DC, CaretLoc), DeclContext(Block),
3125       IsVariadic(false), CapturesCXXThis(false),
3126       BlockMissingReturnType(true), IsConversionFromLambda(false),
3127       ParamInfo(0), NumParams(0), Body(0),
3128       SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
3129 
3130 public:
3131   static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3132   static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3133 
getCaretLocation()3134   SourceLocation getCaretLocation() const { return getLocation(); }
3135 
isVariadic()3136   bool isVariadic() const { return IsVariadic; }
setIsVariadic(bool value)3137   void setIsVariadic(bool value) { IsVariadic = value; }
3138 
getCompoundBody()3139   CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
getBody()3140   Stmt *getBody() const { return (Stmt*) Body; }
setBody(CompoundStmt * B)3141   void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3142 
setSignatureAsWritten(TypeSourceInfo * Sig)3143   void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
getSignatureAsWritten()3144   TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3145 
3146   // Iterator access to formal parameters.
param_size()3147   unsigned param_size() const { return getNumParams(); }
3148   typedef ParmVarDecl **param_iterator;
3149   typedef ParmVarDecl * const *param_const_iterator;
3150 
param_empty()3151   bool param_empty() const { return NumParams == 0; }
param_begin()3152   param_iterator param_begin()  { return ParamInfo; }
param_end()3153   param_iterator param_end()   { return ParamInfo+param_size(); }
3154 
param_begin()3155   param_const_iterator param_begin() const { return ParamInfo; }
param_end()3156   param_const_iterator param_end() const   { return ParamInfo+param_size(); }
3157 
getNumParams()3158   unsigned getNumParams() const { return NumParams; }
getParamDecl(unsigned i)3159   const ParmVarDecl *getParamDecl(unsigned i) const {
3160     assert(i < getNumParams() && "Illegal param #");
3161     return ParamInfo[i];
3162   }
getParamDecl(unsigned i)3163   ParmVarDecl *getParamDecl(unsigned i) {
3164     assert(i < getNumParams() && "Illegal param #");
3165     return ParamInfo[i];
3166   }
3167   void setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo);
3168 
3169   /// hasCaptures - True if this block (or its nested blocks) captures
3170   /// anything of local storage from its enclosing scopes.
hasCaptures()3171   bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3172 
3173   /// getNumCaptures - Returns the number of captured variables.
3174   /// Does not include an entry for 'this'.
getNumCaptures()3175   unsigned getNumCaptures() const { return NumCaptures; }
3176 
3177   typedef const Capture *capture_iterator;
3178   typedef const Capture *capture_const_iterator;
capture_begin()3179   capture_iterator capture_begin() { return Captures; }
capture_end()3180   capture_iterator capture_end() { return Captures + NumCaptures; }
capture_begin()3181   capture_const_iterator capture_begin() const { return Captures; }
capture_end()3182   capture_const_iterator capture_end() const { return Captures + NumCaptures; }
3183 
capturesCXXThis()3184   bool capturesCXXThis() const { return CapturesCXXThis; }
blockMissingReturnType()3185   bool blockMissingReturnType() const { return BlockMissingReturnType; }
setBlockMissingReturnType(bool val)3186   void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3187 
isConversionFromLambda()3188   bool isConversionFromLambda() const { return IsConversionFromLambda; }
setIsConversionFromLambda(bool val)3189   void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3190 
3191   bool capturesVariable(const VarDecl *var) const;
3192 
3193   void setCaptures(ASTContext &Context,
3194                    const Capture *begin,
3195                    const Capture *end,
3196                    bool capturesCXXThis);
3197 
3198   virtual SourceRange getSourceRange() const LLVM_READONLY;
3199 
3200   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)3201   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const BlockDecl * D)3202   static bool classof(const BlockDecl *D) { return true; }
classofKind(Kind K)3203   static bool classofKind(Kind K) { return K == Block; }
castToDeclContext(const BlockDecl * D)3204   static DeclContext *castToDeclContext(const BlockDecl *D) {
3205     return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3206   }
castFromDeclContext(const DeclContext * DC)3207   static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3208     return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3209   }
3210 };
3211 
3212 /// \brief Describes a module import declaration, which makes the contents
3213 /// of the named module visible in the current translation unit.
3214 ///
3215 /// An import declaration imports the named module (or submodule). For example:
3216 /// \code
3217 ///   @__experimental_modules_import std.vector;
3218 /// \endcode
3219 ///
3220 /// Import declarations can also be implicitly generated from #include/#import
3221 /// directives.
3222 class ImportDecl : public Decl {
3223   /// \brief The imported module, along with a bit that indicates whether
3224   /// we have source-location information for each identifier in the module
3225   /// name.
3226   ///
3227   /// When the bit is false, we only have a single source location for the
3228   /// end of the import declaration.
3229   llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3230 
3231   /// \brief The next import in the list of imports local to the translation
3232   /// unit being parsed (not loaded from an AST file).
3233   ImportDecl *NextLocalImport;
3234 
3235   friend class ASTReader;
3236   friend class ASTDeclReader;
3237   friend class ASTContext;
3238 
3239   ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3240              ArrayRef<SourceLocation> IdentifierLocs);
3241 
3242   ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3243              SourceLocation EndLoc);
3244 
ImportDecl(EmptyShell Empty)3245   ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3246 
3247 public:
3248   /// \brief Create a new module import declaration.
3249   static ImportDecl *Create(ASTContext &C, DeclContext *DC,
3250                             SourceLocation StartLoc, Module *Imported,
3251                             ArrayRef<SourceLocation> IdentifierLocs);
3252 
3253   /// \brief Create a new module import declaration for an implicitly-generated
3254   /// import.
3255   static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
3256                                     SourceLocation StartLoc, Module *Imported,
3257                                     SourceLocation EndLoc);
3258 
3259   /// \brief Create a new, deserialized module import declaration.
3260   static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3261                                         unsigned NumLocations);
3262 
3263   /// \brief Retrieve the module that was imported by the import declaration.
getImportedModule()3264   Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3265 
3266   /// \brief Retrieves the locations of each of the identifiers that make up
3267   /// the complete module name in the import declaration.
3268   ///
3269   /// This will return an empty array if the locations of the individual
3270   /// identifiers aren't available.
3271   ArrayRef<SourceLocation> getIdentifierLocs() const;
3272 
3273   virtual SourceRange getSourceRange() const LLVM_READONLY;
3274 
classof(const Decl * D)3275   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classof(const ImportDecl * D)3276   static bool classof(const ImportDecl *D) { return true; }
classofKind(Kind K)3277   static bool classofKind(Kind K) { return K == Import; }
3278 };
3279 
3280 
3281 /// Insertion operator for diagnostics.  This allows sending NamedDecl's
3282 /// into a diagnostic with <<.
3283 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3284                                            const NamedDecl* ND) {
3285   DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3286                   DiagnosticsEngine::ak_nameddecl);
3287   return DB;
3288 }
3289 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3290                                            const NamedDecl* ND) {
3291   PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3292                   DiagnosticsEngine::ak_nameddecl);
3293   return PD;
3294 }
3295 
3296 template<typename decl_type>
setPreviousDeclaration(decl_type * PrevDecl)3297 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
3298   // Note: This routine is implemented here because we need both NamedDecl
3299   // and Redeclarable to be defined.
3300 
3301   decl_type *First;
3302 
3303   if (PrevDecl) {
3304     // Point to previous. Make sure that this is actually the most recent
3305     // redeclaration, or we can build invalid chains. If the most recent
3306     // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3307     RedeclLink = PreviousDeclLink(
3308                    llvm::cast<decl_type>(PrevDecl->getMostRecentDecl()));
3309     First = PrevDecl->getFirstDeclaration();
3310     assert(First->RedeclLink.NextIsLatest() && "Expected first");
3311   } else {
3312     // Make this first.
3313     First = static_cast<decl_type*>(this);
3314   }
3315 
3316   // First one will point to this one as latest.
3317   First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this));
3318   if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
3319     ND->ClearLinkageCache();
3320 }
3321 
3322 // Inline function definitions.
3323 
3324 /// \brief Check if the given decl is complete.
3325 ///
3326 /// We use this function to break a cycle between the inline definitions in
3327 /// Type.h and Decl.h.
IsEnumDeclComplete(EnumDecl * ED)3328 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3329   return ED->isComplete();
3330 }
3331 
3332 /// \brief Check if the given decl is scoped.
3333 ///
3334 /// We use this function to break a cycle between the inline definitions in
3335 /// Type.h and Decl.h.
IsEnumDeclScoped(EnumDecl * ED)3336 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3337   return ED->isScoped();
3338 }
3339 
3340 }  // end namespace clang
3341 
3342 #endif
3343