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