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