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