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