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