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