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