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