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