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