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