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