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