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