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