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