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