Warning: That file was not part of the compilation database. It may have many parsing errors.

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

Warning: That file was not part of the compilation database. It may have many parsing errors.