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