clang 22.0.0git
ASTWriter.h
Go to the documentation of this file.
1//===- ASTWriter.h - AST File Writer ----------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTWriter class, which writes an AST file
10// containing a serialized representation of a translation unit.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SERIALIZATION_ASTWRITER_H
15#define LLVM_CLANG_SERIALIZATION_ASTWRITER_H
16
18#include "clang/AST/Decl.h"
19#include "clang/AST/Type.h"
20#include "clang/Basic/LLVM.h"
22#include "clang/Sema/Sema.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/MapVector.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SetVector.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/Bitstream/BitstreamWriter.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <ctime>
41#include <memory>
42#include <queue>
43#include <string>
44#include <utility>
45#include <vector>
46
47namespace clang {
48
49class ASTContext;
50class ASTReader;
51class Attr;
52class CodeGenOptions;
53class CXXRecordDecl;
54class FileEntry;
56class FunctionDecl;
57class HeaderSearch;
60class LangOptions;
62class MacroInfo;
63class Module;
64class ModuleCache;
67class NamedDecl;
70class Preprocessor;
71class RecordDecl;
72class Sema;
73class SourceManager;
74class Stmt;
75class StoredDeclsList;
76class SwitchCase;
77class Token;
78
81
82namespace serialization {
83enum class DeclUpdateKind;
84} // namespace serialization
85
86namespace SrcMgr {
87class FileInfo;
88} // namespace SrcMgr
89
90/// Writes an AST file containing the contents of a translation unit.
91///
92/// The ASTWriter class produces a bitstream containing the serialized
93/// representation of a given abstract syntax tree and its supporting
94/// data structures. This bitstream can be de-serialized via an
95/// instance of the ASTReader class.
97 public ASTMutationListener {
98public:
99 friend class ASTDeclWriter;
100 friend class ASTRecordWriter;
101
105
106private:
107 /// Map that provides the ID numbers of each type within the
108 /// output stream, plus those deserialized from a chained PCH.
109 ///
110 /// The ID numbers of types are consecutive (in order of discovery)
111 /// and start at 1. 0 is reserved for NULL. When types are actually
112 /// stored in the stream, the ID number is shifted by 2 bits to
113 /// allow for the const/volatile qualifiers.
114 ///
115 /// Keys in the map never have const/volatile qualifiers.
116 using TypeIdxMap = llvm::DenseMap<QualType, serialization::TypeIdx,
118
119 /// The bitstream writer used to emit this precompiled header.
120 llvm::BitstreamWriter &Stream;
121
122 /// The buffer associated with the bitstream.
123 const SmallVectorImpl<char> &Buffer;
124
125 /// The PCM manager which manages memory buffers for pcm files.
126 ModuleCache &ModCache;
127
128 const CodeGenOptions &CodeGenOpts;
129
130 /// The preprocessor we're writing.
131 Preprocessor *PP = nullptr;
132
133 /// The reader of existing AST files, if we're chaining.
134 ASTReader *Chain = nullptr;
135
136 /// The module we're currently writing, if any.
137 Module *WritingModule = nullptr;
138
139 /// The byte range representing all the UNHASHED_CONTROL_BLOCK.
140 std::pair<uint64_t, uint64_t> UnhashedControlBlockRange;
141 /// The bit offset of the AST block hash blob.
142 uint64_t ASTBlockHashOffset = 0;
143 /// The bit offset of the signature blob.
144 uint64_t SignatureOffset = 0;
145
146 /// The bit offset of the first bit inside the AST_BLOCK.
147 uint64_t ASTBlockStartOffset = 0;
148
149 /// The byte range representing all the AST_BLOCK.
150 std::pair<uint64_t, uint64_t> ASTBlockRange;
151
152 /// The base directory for any relative paths we emit.
153 std::string BaseDirectory;
154
155 /// Indicates whether timestamps should be written to the produced
156 /// module file. This is the case for files implicitly written to the
157 /// module cache, where we need the timestamps to determine if the module
158 /// file is up to date, but not otherwise.
159 bool IncludeTimestamps;
160
161 /// Indicates whether the AST file being written is an implicit module.
162 /// If that's the case, we may be able to skip writing some information that
163 /// are guaranteed to be the same in the importer by the context hash.
164 bool BuildingImplicitModule = false;
165
166 /// Indicates when the AST writing is actively performing
167 /// serialization, rather than just queueing updates.
168 bool WritingAST = false;
169
170 /// Indicates that we are done serializing the collection of decls
171 /// and types to emit.
172 bool DoneWritingDeclsAndTypes = false;
173
174 /// Indicates that the AST contained compiler errors.
175 bool ASTHasCompilerErrors = false;
176
177 /// Indicates that we're going to generate the reduced BMI for C++20
178 /// named modules.
179 bool GeneratingReducedBMI = false;
180
181 /// Mapping from input file entries to the index into the
182 /// offset table where information about that input file is stored.
183 llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs;
184
185 /// Stores a declaration or a type to be written to the AST file.
186 class DeclOrType {
187 public:
188 DeclOrType(Decl *D) : Stored(D), IsType(false) {}
189 DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) {}
190
191 bool isType() const { return IsType; }
192 bool isDecl() const { return !IsType; }
193
194 QualType getType() const {
195 assert(isType() && "Not a type!");
196 return QualType::getFromOpaquePtr(Stored);
197 }
198
199 Decl *getDecl() const {
200 assert(isDecl() && "Not a decl!");
201 return static_cast<Decl *>(Stored);
202 }
203
204 private:
205 void *Stored;
206 bool IsType;
207 };
208
209 /// The declarations and types to emit.
210 std::queue<DeclOrType> DeclTypesToEmit;
211
212 /// The delayed namespace to emit. Only meaningful for reduced BMI.
213 ///
214 /// In reduced BMI, we want to elide the unreachable declarations in
215 /// the global module fragment. However, in ASTWriterDecl, when we see
216 /// a namespace, all the declarations in the namespace would be emitted.
217 /// So the optimization become meaningless. To solve the issue, we
218 /// delay recording all the declarations until we emit all the declarations.
219 /// Then we can safely record the reached declarations only.
221
222 /// The first ID number we can use for our own declarations.
224
225 /// The decl ID that will be assigned to the next new decl.
226 LocalDeclID NextDeclID = FirstDeclID;
227
228 /// Map that provides the ID numbers of each declaration within
229 /// the output stream, as well as those deserialized from a chained PCH.
230 ///
231 /// The ID numbers of declarations are consecutive (in order of
232 /// discovery) and start at 2. 1 is reserved for the translation
233 /// unit, while 0 is reserved for NULL.
234 llvm::DenseMap<const Decl *, LocalDeclID> DeclIDs;
235
236 /// Set of predefined decls. This is a helper data to determine if a decl
237 /// is predefined. It should be more clear and safer to query the set
238 /// instead of comparing the result of `getDeclID()` or `GetDeclRef()`.
240
241 /// Mapping from the main decl to related decls inside the main decls.
242 ///
243 /// These related decls have to be loaded right after the main decl they
244 /// belong to. In order to have canonical declaration for related decls from
245 /// the same module as the main decl during deserialization.
246 llvm::DenseMap<LocalDeclID, SmallVector<LocalDeclID, 4>> RelatedDeclsMap;
247
248 /// Offset of each declaration in the bitstream, indexed by
249 /// the declaration's ID.
250 std::vector<serialization::DeclOffset> DeclOffsets;
251
252 /// The offset of the DECLTYPES_BLOCK. The offsets in DeclOffsets
253 /// are relative to this value.
254 uint64_t DeclTypesBlockStartOffset = 0;
255
256 /// Sorted (by file offset) vector of pairs of file offset/LocalDeclID.
257 using LocDeclIDsTy = SmallVector<std::pair<unsigned, LocalDeclID>, 64>;
258 struct DeclIDInFileInfo {
259 LocDeclIDsTy DeclIDs;
260
261 /// Set when the DeclIDs vectors from all files are joined, this
262 /// indicates the index that this particular vector has in the global one.
263 unsigned FirstDeclIndex;
264 };
265 using FileDeclIDsTy =
266 llvm::DenseMap<FileID, std::unique_ptr<DeclIDInFileInfo>>;
267
268 /// Map from file SLocEntries to info about the file-level declarations
269 /// that it contains.
270 FileDeclIDsTy FileDeclIDs;
271
272 void associateDeclWithFile(const Decl *D, LocalDeclID);
273
274 /// The first ID number we can use for our own types.
276
277 /// The type ID that will be assigned to the next new type.
278 serialization::TypeID NextTypeID = FirstTypeID;
279
280 /// Map that provides the ID numbers of each type within the
281 /// output stream, plus those deserialized from a chained PCH.
282 ///
283 /// The ID numbers of types are consecutive (in order of discovery)
284 /// and start at 1. 0 is reserved for NULL. When types are actually
285 /// stored in the stream, the ID number is shifted by 2 bits to
286 /// allow for the const/volatile qualifiers.
287 ///
288 /// Keys in the map never have const/volatile qualifiers.
289 TypeIdxMap TypeIdxs;
290
291 /// Offset of each type in the bitstream, indexed by
292 /// the type's ID.
293 std::vector<serialization::UnalignedUInt64> TypeOffsets;
294
295 /// The first ID number we can use for our own identifiers.
297
298 /// The identifier ID that will be assigned to the next new identifier.
299 serialization::IdentifierID NextIdentID = FirstIdentID;
300
301 /// Map that provides the ID numbers of each identifier in
302 /// the output stream.
303 ///
304 /// The ID numbers for identifiers are consecutive (in order of
305 /// discovery), starting at 1. An ID of zero refers to a NULL
306 /// IdentifierInfo.
307 llvm::MapVector<const IdentifierInfo *, serialization::IdentifierID> IdentifierIDs;
308
309 /// The first ID number we can use for our own macros.
311
312 /// The identifier ID that will be assigned to the next new identifier.
313 serialization::MacroID NextMacroID = FirstMacroID;
314
315 /// Map that provides the ID numbers of each macro.
316 llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
317
318 struct MacroInfoToEmitData {
319 const IdentifierInfo *Name;
320 MacroInfo *MI;
322 };
323
324 /// The macro infos to emit.
325 std::vector<MacroInfoToEmitData> MacroInfosToEmit;
326
327 llvm::DenseMap<const IdentifierInfo *, uint32_t>
328 IdentMacroDirectivesOffsetMap;
329
330 /// @name FlushStmt Caches
331 /// @{
332
333 /// Set of parent Stmts for the currently serializing sub-stmt.
334 llvm::DenseSet<Stmt *> ParentStmts;
335
336 /// Offsets of sub-stmts already serialized. The offset points
337 /// just after the stmt record.
338 llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
339
340 /// @}
341
342 /// Offsets of each of the identifier IDs into the identifier
343 /// table.
344 std::vector<uint32_t> IdentifierOffsets;
345
346 /// The first ID number we can use for our own submodules.
347 serialization::SubmoduleID FirstSubmoduleID =
349
350 /// The submodule ID that will be assigned to the next new submodule.
351 serialization::SubmoduleID NextSubmoduleID = FirstSubmoduleID;
352
353 /// The first ID number we can use for our own selectors.
354 serialization::SelectorID FirstSelectorID =
356
357 /// The selector ID that will be assigned to the next new selector.
358 serialization::SelectorID NextSelectorID = FirstSelectorID;
359
360 /// Map that provides the ID numbers of each Selector.
361 llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
362
363 /// Offset of each selector within the method pool/selector
364 /// table, indexed by the Selector ID (-1).
365 std::vector<uint32_t> SelectorOffsets;
366
367 /// Mapping from macro definitions (as they occur in the preprocessing
368 /// record) to the macro IDs.
369 llvm::DenseMap<const MacroDefinitionRecord *,
370 serialization::PreprocessedEntityID> MacroDefinitions;
371
372 /// Cache of indices of anonymous declarations within their lexical
373 /// contexts.
374 llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
375
376 /// The external top level module during the writing process. Used to
377 /// generate signature for the module file being written.
378 ///
379 /// Only meaningful for standard C++ named modules. See the comments in
380 /// createSignatureForNamedModule() for details.
381 llvm::SetVector<Module *> TouchedTopLevelModules;
382 llvm::SetVector<serialization::ModuleFile *> TouchedModuleFiles;
383
384 /// An update to a Decl.
385 class DeclUpdate {
387 union {
388 const Decl *Dcl;
389 void *Type;
391 unsigned Val;
392 Module *Mod;
393 const Attr *Attribute;
394 };
395
396 public:
397 DeclUpdate(serialization::DeclUpdateKind Kind) : Kind(Kind), Dcl(nullptr) {}
398 DeclUpdate(serialization::DeclUpdateKind Kind, const Decl *Dcl)
399 : Kind(Kind), Dcl(Dcl) {}
400 DeclUpdate(serialization::DeclUpdateKind Kind, QualType Type)
401 : Kind(Kind), Type(Type.getAsOpaquePtr()) {}
402 DeclUpdate(serialization::DeclUpdateKind Kind, SourceLocation Loc)
403 : Kind(Kind), Loc(Loc.getRawEncoding()) {}
404 DeclUpdate(serialization::DeclUpdateKind Kind, unsigned Val)
405 : Kind(Kind), Val(Val) {}
406 DeclUpdate(serialization::DeclUpdateKind Kind, Module *M)
407 : Kind(Kind), Mod(M) {}
408 DeclUpdate(serialization::DeclUpdateKind Kind, const Attr *Attribute)
409 : Kind(Kind), Attribute(Attribute) {}
410
411 serialization::DeclUpdateKind getKind() const { return Kind; }
412 const Decl *getDecl() const { return Dcl; }
413 QualType getType() const { return QualType::getFromOpaquePtr(Type); }
414
415 SourceLocation getLoc() const {
417 }
418
419 unsigned getNumber() const { return Val; }
420 Module *getModule() const { return Mod; }
421 const Attr *getAttr() const { return Attribute; }
422 };
423
424 using UpdateRecord = SmallVector<DeclUpdate, 1>;
425 using DeclUpdateMap = llvm::MapVector<const Decl *, UpdateRecord>;
426
427 /// Mapping from declarations that came from a chained PCH to the
428 /// record containing modifications to them.
429 DeclUpdateMap DeclUpdates;
430
431 /// DeclUpdates added during parsing the GMF. We split these from
432 /// DeclUpdates since we want to add these updates in GMF on need.
433 /// Only meaningful for reduced BMI.
434 DeclUpdateMap DeclUpdatesFromGMF;
435
436 /// Mapping from decl templates and its new specialization in the
437 /// current TU.
438 using SpecializationUpdateMap =
439 llvm::MapVector<const NamedDecl *, SmallVector<const Decl *>>;
440 SpecializationUpdateMap SpecializationsUpdates;
441 SpecializationUpdateMap PartialSpecializationsUpdates;
442
443 using FirstLatestDeclMap = llvm::DenseMap<Decl *, Decl *>;
444
445 /// Map of first declarations from a chained PCH that point to the
446 /// most recent declarations in another PCH.
447 FirstLatestDeclMap FirstLatestDecls;
448
449 /// Declarations encountered that might be external
450 /// definitions.
451 ///
452 /// We keep track of external definitions and other 'interesting' declarations
453 /// as we are emitting declarations to the AST file. The AST file contains a
454 /// separate record for these declarations, which are provided to the AST
455 /// consumer by the AST reader. This is behavior is required to properly cope with,
456 /// e.g., tentative variable definitions that occur within
457 /// headers. The declarations themselves are stored as declaration
458 /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS
459 /// record.
460 RecordData EagerlyDeserializedDecls;
461 RecordData ModularCodegenDecls;
462
463 /// DeclContexts that have received extensions since their serialized
464 /// form.
465 ///
466 /// For namespaces, when we're chaining and encountering a namespace, we check
467 /// if its primary namespace comes from the chain. If it does, we add the
468 /// primary to this set, so that we can write out lexical content updates for
469 /// it.
470 llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
471
472 /// Keeps track of declarations that we must emit, even though we're
473 /// not guaranteed to be able to find them by walking the AST starting at the
474 /// translation unit.
475 SmallVector<const Decl *, 16> DeclsToEmitEvenIfUnreferenced;
476
477 /// The set of Objective-C class that have categories we
478 /// should serialize.
479 llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
480
481 /// The set of declarations that may have redeclaration chains that
482 /// need to be serialized.
483 llvm::SmallVector<const Decl *, 16> Redeclarations;
484
485 /// A cache of the first local declaration for "interesting"
486 /// redeclaration chains.
487 llvm::DenseMap<const Decl *, const Decl *> FirstLocalDeclCache;
488
489 /// Mapping from SwitchCase statements to IDs.
490 llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
491
492 /// The number of statements written to the AST file.
493 unsigned NumStatements = 0;
494
495 /// The number of macros written to the AST file.
496 unsigned NumMacros = 0;
497
498 /// The number of lexical declcontexts written to the AST
499 /// file.
500 unsigned NumLexicalDeclContexts = 0;
501
502 /// The number of visible declcontexts written to the AST
503 /// file.
504 unsigned NumVisibleDeclContexts = 0;
505
506 /// The number of module local visible declcontexts written to the AST
507 /// file.
508 unsigned NumModuleLocalDeclContexts = 0;
509
510 /// The number of TULocal declcontexts written to the AST file.
511 unsigned NumTULocalDeclContexts = 0;
512
513 /// A mapping from each known submodule to its ID number, which will
514 /// be a positive integer.
515 llvm::DenseMap<const Module *, unsigned> SubmoduleIDs;
516
517 /// A list of the module file extension writers.
518 std::vector<std::unique_ptr<ModuleFileExtensionWriter>>
519 ModuleFileExtensionWriters;
520
521 /// Mapping from a source location entry to whether it is affecting or not.
522 llvm::BitVector IsSLocAffecting;
523 /// Mapping from a source location entry to whether it must be included as
524 /// input file.
525 llvm::BitVector IsSLocFileEntryAffecting;
526
527 /// Mapping from \c FileID to an index into the FileID adjustment table.
528 std::vector<FileID> NonAffectingFileIDs;
529 std::vector<unsigned> NonAffectingFileIDAdjustments;
530
531 /// Mapping from an offset to an index into the offset adjustment table.
532 std::vector<SourceRange> NonAffectingRanges;
533 std::vector<SourceLocation::UIntTy> NonAffectingOffsetAdjustments;
534
535 /// A list of classes in named modules which need to emit the VTable in
536 /// the corresponding object file.
537 llvm::SmallVector<CXXRecordDecl *> PendingEmittingVTables;
538
539 /// Computes input files that didn't affect compilation of the current module,
540 /// and initializes data structures necessary for leaving those files out
541 /// during \c SourceManager serialization.
542 void computeNonAffectingInputFiles();
543
544 /// Some affecting files can be included from files that are not affecting.
545 /// This function erases source locations pointing into such files.
546 SourceLocation getAffectingIncludeLoc(const SourceManager &SourceMgr,
547 const SrcMgr::FileInfo &File);
548
549 /// Returns an adjusted \c FileID, accounting for any non-affecting input
550 /// files.
551 FileID getAdjustedFileID(FileID FID) const;
552 /// Returns an adjusted number of \c FileIDs created within the specified \c
553 /// FileID, accounting for any non-affecting input files.
554 unsigned getAdjustedNumCreatedFIDs(FileID FID) const;
555 /// Returns an adjusted \c SourceLocation, accounting for any non-affecting
556 /// input files.
557 SourceLocation getAdjustedLocation(SourceLocation Loc) const;
558 /// Returns an adjusted \c SourceRange, accounting for any non-affecting input
559 /// files.
560 SourceRange getAdjustedRange(SourceRange Range) const;
561 /// Returns an adjusted \c SourceLocation offset, accounting for any
562 /// non-affecting input files.
563 SourceLocation::UIntTy getAdjustedOffset(SourceLocation::UIntTy Offset) const;
564 /// Returns an adjustment for offset into SourceManager, accounting for any
565 /// non-affecting input files.
566 SourceLocation::UIntTy getAdjustment(SourceLocation::UIntTy Offset) const;
567
568 /// Retrieve or create a submodule ID for this module.
569 unsigned getSubmoduleID(Module *Mod);
570
571 /// Write the given subexpression to the bitstream.
572 void WriteSubStmt(ASTContext &Context, Stmt *S);
573
574 void WriteBlockInfoBlock();
575 void WriteControlBlock(Preprocessor &PP, StringRef isysroot);
576
577 /// Write out the signature and diagnostic options, and return the signature.
578 void writeUnhashedControlBlock(Preprocessor &PP);
579 ASTFileSignature backpatchSignature();
580
581 /// Calculate hash of the pcm content.
582 std::pair<ASTFileSignature, ASTFileSignature> createSignature() const;
583 ASTFileSignature createSignatureForNamedModule() const;
584
585 void WriteInputFiles(SourceManager &SourceMgr);
586 void WriteSourceManagerBlock(SourceManager &SourceMgr);
587 void WritePreprocessor(const Preprocessor &PP, bool IsModule);
588 void WriteHeaderSearch(const HeaderSearch &HS);
589 void WritePreprocessorDetail(PreprocessingRecord &PPRec,
590 uint64_t MacroOffsetsBase);
591 void WriteSubmodules(Module *WritingModule, ASTContext *Context);
592
593 void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
594 bool isModule);
595
596 unsigned TypeExtQualAbbrev = 0;
597 void WriteTypeAbbrevs();
598 void WriteType(ASTContext &Context, QualType T);
599
600 void GenerateSpecializationInfoLookupTable(
601 const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
602 llvm::SmallVectorImpl<char> &LookupTable, bool IsPartial);
603 uint64_t WriteSpecializationInfoLookupTable(
604 const NamedDecl *D, llvm::SmallVectorImpl<const Decl *> &Specializations,
605 bool IsPartial);
606 void
607 GenerateNameLookupTable(ASTContext &Context, const DeclContext *DC,
608 llvm::SmallVectorImpl<char> &LookupTable,
609 llvm::SmallVectorImpl<char> &ModuleLocalLookupTable,
610 llvm::SmallVectorImpl<char> &TULocalLookupTable);
611 uint64_t WriteDeclContextLexicalBlock(ASTContext &Context,
612 const DeclContext *DC);
613 void WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC,
614 VisibleLookupBlockOffsets &Offsets);
615 void WriteTypeDeclOffsets();
616 void WriteFileDeclIDsMap();
617 void WriteComments(ASTContext &Context);
618 void WriteSelectors(Sema &SemaRef);
619 void WriteReferencedSelectorsPool(Sema &SemaRef);
620 void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver *IdResolver,
621 bool IsModule);
622 void WriteDeclAndTypes(ASTContext &Context);
623 void PrepareWritingSpecialDecls(Sema &SemaRef);
624 void WriteSpecialDeclRecords(Sema &SemaRef);
625 void WriteSpecializationsUpdates(bool IsPartial);
626 void WriteDeclUpdatesBlocks(ASTContext &Context,
627 RecordDataImpl &OffsetsRecord);
628 void WriteDeclContextVisibleUpdate(ASTContext &Context,
629 const DeclContext *DC);
630 void WriteFPPragmaOptions(const FPOptionsOverride &Opts);
631 void WriteOpenCLExtensions(Sema &SemaRef);
632 void WriteCUDAPragmas(Sema &SemaRef);
633 void WriteObjCCategories();
634 void WriteLateParsedTemplates(Sema &SemaRef);
635 void WriteOptimizePragmaOptions(Sema &SemaRef);
636 void WriteMSStructPragmaOptions(Sema &SemaRef);
637 void WriteMSPointersToMembersPragmaOptions(Sema &SemaRef);
638 void WritePackPragmaOptions(Sema &SemaRef);
639 void WriteFloatControlPragmaOptions(Sema &SemaRef);
640 void WriteDeclsWithEffectsToVerify(Sema &SemaRef);
641 void WriteModuleFileExtension(Sema &SemaRef,
642 ModuleFileExtensionWriter &Writer);
643
644 unsigned DeclParmVarAbbrev = 0;
645 unsigned DeclContextLexicalAbbrev = 0;
646 unsigned DeclContextVisibleLookupAbbrev = 0;
647 unsigned DeclModuleLocalVisibleLookupAbbrev = 0;
648 unsigned DeclTULocalLookupAbbrev = 0;
649 unsigned UpdateVisibleAbbrev = 0;
650 unsigned ModuleLocalUpdateVisibleAbbrev = 0;
651 unsigned TULocalUpdateVisibleAbbrev = 0;
652 unsigned DeclRecordAbbrev = 0;
653 unsigned DeclTypedefAbbrev = 0;
654 unsigned DeclVarAbbrev = 0;
655 unsigned DeclFieldAbbrev = 0;
656 unsigned DeclEnumAbbrev = 0;
657 unsigned DeclObjCIvarAbbrev = 0;
658 unsigned DeclCXXMethodAbbrev = 0;
659 unsigned DeclSpecializationsAbbrev = 0;
660 unsigned DeclPartialSpecializationsAbbrev = 0;
661
662 unsigned DeclDependentNonTemplateCXXMethodAbbrev = 0;
663 unsigned DeclTemplateCXXMethodAbbrev = 0;
664 unsigned DeclMemberSpecializedCXXMethodAbbrev = 0;
665 unsigned DeclTemplateSpecializedCXXMethodAbbrev = 0;
666 unsigned DeclDependentSpecializationCXXMethodAbbrev = 0;
667 unsigned DeclTemplateTypeParmAbbrev = 0;
668 unsigned DeclUsingShadowAbbrev = 0;
669
670 unsigned DeclRefExprAbbrev = 0;
671 unsigned CharacterLiteralAbbrev = 0;
672 unsigned IntegerLiteralAbbrev = 0;
673 unsigned ExprImplicitCastAbbrev = 0;
674 unsigned BinaryOperatorAbbrev = 0;
675 unsigned CompoundAssignOperatorAbbrev = 0;
676 unsigned CallExprAbbrev = 0;
677 unsigned CXXOperatorCallExprAbbrev = 0;
678 unsigned CXXMemberCallExprAbbrev = 0;
679
680 unsigned CompoundStmtAbbrev = 0;
681
682 void WriteDeclAbbrevs();
683 void WriteDecl(ASTContext &Context, Decl *D);
684
685 ASTFileSignature WriteASTCore(Sema *SemaPtr, StringRef isysroot,
686 Module *WritingModule);
687
688public:
689 /// Create a new precompiled header writer that outputs to
690 /// the given bitstream.
691 ASTWriter(llvm::BitstreamWriter &Stream, SmallVectorImpl<char> &Buffer,
692 ModuleCache &ModCache, const CodeGenOptions &CodeGenOpts,
693 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
694 bool IncludeTimestamps = true, bool BuildingImplicitModule = false,
695 bool GeneratingReducedBMI = false);
696 ~ASTWriter() override;
697
698 const LangOptions &getLangOpts() const;
699 const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
700
701 /// Get a timestamp for output into the AST file. The actual timestamp
702 /// of the specified file may be ignored if we have been instructed to not
703 /// include timestamps in the output file.
704 time_t getTimestampForOutput(const FileEntry *E) const;
705
706 /// Write a precompiled header or a module with the AST produced by the
707 /// \c Sema object, or a dependency scanner module with the preprocessor state
708 /// produced by the \c Preprocessor object.
709 ///
710 /// \param Subject The \c Sema object that processed the AST to be written, or
711 /// in the case of a dependency scanner module the \c Preprocessor that holds
712 /// the state.
713 ///
714 /// \param WritingModule The module that we are writing. If null, we are
715 /// writing a precompiled header.
716 ///
717 /// \param isysroot if non-empty, write a relocatable file whose headers
718 /// are relative to the given system root. If we're writing a module, its
719 /// build directory will be used in preference to this if both are available.
720 ///
721 /// \return the module signature, which eventually will be a hash of
722 /// the module but currently is merely a random 32-bit number.
723 ASTFileSignature WriteAST(llvm::PointerUnion<Sema *, Preprocessor *> Subject,
724 StringRef OutputFile, Module *WritingModule,
725 StringRef isysroot,
726 bool ShouldCacheASTInMemory = false);
727
728 /// Emit a token.
729 void AddToken(const Token &Tok, RecordDataImpl &Record);
730
731 /// Emit a AlignPackInfo.
732 void AddAlignPackInfo(const Sema::AlignPackInfo &Info,
734
735 /// Emit a FileID.
737
738 /// Emit a source location.
740
741 /// Return the raw encodings for source locations.
744
745 /// Emit a source range.
747
748 /// Emit a reference to an identifier.
750
751 /// Get the unique number used to refer to the given selector.
753
754 /// Get the unique number used to refer to the given identifier.
756
757 /// Get the unique number used to refer to the given macro.
759
760 uint32_t getMacroDirectivesOffset(const IdentifierInfo *Name);
761
762 /// Emit a reference to a type.
764
765 /// Force a type to be emitted and get its ID.
767
768 /// Find the first local declaration of a given local redeclarable
769 /// decl.
770 const Decl *getFirstLocalDecl(const Decl *D);
771
772 /// Is this a local declaration (that is, one that will be written to
773 /// our AST file)? This is the case for declarations that are neither imported
774 /// from another AST file nor predefined.
775 bool IsLocalDecl(const Decl *D) {
776 if (D->isFromASTFile())
777 return false;
778 auto I = DeclIDs.find(D);
779 return (I == DeclIDs.end() || I->second >= clang::NUM_PREDEF_DECL_IDS);
780 };
781
782 void AddLookupOffsets(const LookupBlockOffsets &Offsets,
784
785 /// Emit a reference to a macro.
786 void AddMacroRef(MacroInfo *MI, const IdentifierInfo *Name,
788
789 /// Emit a reference to a declaration.
790 void AddDeclRef(const Decl *D, RecordDataImpl &Record);
791 // Emit a reference to a declaration if the declaration was emitted.
793
794 /// Force a declaration to be emitted and get its local ID to the module file
795 /// been writing.
796 LocalDeclID GetDeclRef(const Decl *D);
797
798 /// Determine the local declaration ID of an already-emitted
799 /// declaration.
800 LocalDeclID getDeclID(const Decl *D);
801
802 /// Whether or not the declaration got emitted. If not, it wouldn't be
803 /// emitted.
804 ///
805 /// This may only be called after we've done the job to write the
806 /// declarations (marked by DoneWritingDeclsAndTypes).
807 ///
808 /// A declaration may only be omitted in reduced BMI.
809 bool wasDeclEmitted(const Decl *D) const;
810
811 unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
812
813 /// Add a string to the given record.
814 void AddString(StringRef Str, RecordDataImpl &Record);
815 void AddStringBlob(StringRef Str, RecordDataImpl &Record,
817
818 /// Convert a path from this build process into one that is appropriate
819 /// for emission in the module file.
821
822 /// Add a path to the given record.
823 void AddPath(StringRef Path, RecordDataImpl &Record);
824 void AddPathBlob(StringRef Str, RecordDataImpl &Record,
826
827 /// Emit the current record with the given path as a blob.
828 void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
829 StringRef Path);
830
831 /// Add a version tuple to the given record
832 void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
833
834 /// Retrieve or create a submodule ID for this module, or return 0 if
835 /// the submodule is neither local (a submodle of the currently-written module)
836 /// nor from an imported module.
837 unsigned getLocalOrImportedSubmoduleID(const Module *Mod);
838
839 /// Note that the identifier II occurs at the given offset
840 /// within the identifier table.
841 void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
842
843 /// Note that the selector Sel occurs at the given offset
844 /// within the method pool/selector table.
845 void SetSelectorOffset(Selector Sel, uint32_t Offset);
846
847 /// Record an ID for the given switch-case statement.
848 unsigned RecordSwitchCaseID(SwitchCase *S);
849
850 /// Retrieve the ID for the given switch-case statement.
851 unsigned getSwitchCaseID(SwitchCase *S);
852
853 void ClearSwitchCaseIDs();
854
855 unsigned getTypeExtQualAbbrev() const {
856 return TypeExtQualAbbrev;
857 }
858
859 unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
860 unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
861 unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
862 unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
863 unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
864 unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
865 unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
867 switch (Kind) {
869 return DeclCXXMethodAbbrev;
871 return DeclTemplateCXXMethodAbbrev;
873 return DeclMemberSpecializedCXXMethodAbbrev;
875 return DeclTemplateSpecializedCXXMethodAbbrev;
877 return DeclDependentNonTemplateCXXMethodAbbrev;
879 return DeclDependentSpecializationCXXMethodAbbrev;
880 }
881 llvm_unreachable("Unknwon Template Kind!");
882 }
884 return DeclTemplateTypeParmAbbrev;
885 }
886 unsigned getDeclUsingShadowAbbrev() const { return DeclUsingShadowAbbrev; }
887
888 unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
889 unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
890 unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
891 unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
892 unsigned getBinaryOperatorAbbrev() const { return BinaryOperatorAbbrev; }
894 return CompoundAssignOperatorAbbrev;
895 }
896 unsigned getCallExprAbbrev() const { return CallExprAbbrev; }
897 unsigned getCXXOperatorCallExprAbbrev() { return CXXOperatorCallExprAbbrev; }
898 unsigned getCXXMemberCallExprAbbrev() { return CXXMemberCallExprAbbrev; }
899
900 unsigned getCompoundStmtAbbrev() const { return CompoundStmtAbbrev; }
901
902 bool hasChain() const { return Chain; }
903 ASTReader *getChain() const { return Chain; }
904
905 bool isWritingModule() const { return WritingModule; }
906
908 return WritingModule && WritingModule->isNamedModule();
909 }
910
912 return WritingModule && WritingModule->isHeaderUnit();
913 }
914
915 bool isGeneratingReducedBMI() const { return GeneratingReducedBMI; }
916
917 bool getDoneWritingDeclsAndTypes() const { return DoneWritingDeclsAndTypes; }
918
919 bool isDeclPredefined(const Decl *D) const {
920 return PredefinedDecls.count(D);
921 }
922
923 void handleVTable(CXXRecordDecl *RD);
924
926
927private:
928 // ASTDeserializationListener implementation
929 void ReaderInitialized(ASTReader *Reader) override;
930 void IdentifierRead(serialization::IdentifierID ID, IdentifierInfo *II) override;
931 void MacroRead(serialization::MacroID ID, MacroInfo *MI) override;
932 void TypeRead(serialization::TypeIdx Idx, QualType T) override;
933 void PredefinedDeclBuilt(PredefinedDeclIDs ID, const Decl *D) override;
934 void SelectorRead(serialization::SelectorID ID, Selector Sel) override;
935 void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
936 MacroDefinitionRecord *MD) override;
937 void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
938
939 // ASTMutationListener implementation.
940 void CompletedTagDefinition(const TagDecl *D) override;
941 void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
942 void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
943 void AddedCXXTemplateSpecialization(
944 const ClassTemplateDecl *TD,
945 const ClassTemplateSpecializationDecl *D) override;
946 void AddedCXXTemplateSpecialization(
947 const VarTemplateDecl *TD,
948 const VarTemplateSpecializationDecl *D) override;
949 void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
950 const FunctionDecl *D) override;
951 void ResolvedExceptionSpec(const FunctionDecl *FD) override;
952 void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override;
953 void ResolvedOperatorDelete(const CXXDestructorDecl *DD,
954 const FunctionDecl *Delete,
955 Expr *ThisArg) override;
956 void ResolvedOperatorGlobDelete(const CXXDestructorDecl *DD,
957 const FunctionDecl *Delete) override;
958 void CompletedImplicitDefinition(const FunctionDecl *D) override;
959 void InstantiationRequested(const ValueDecl *D) override;
960 void VariableDefinitionInstantiated(const VarDecl *D) override;
961 void FunctionDefinitionInstantiated(const FunctionDecl *D) override;
962 void DefaultArgumentInstantiated(const ParmVarDecl *D) override;
963 void DefaultMemberInitializerInstantiated(const FieldDecl *D) override;
964 void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
965 const ObjCInterfaceDecl *IFD) override;
966 void DeclarationMarkedUsed(const Decl *D) override;
967 void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override;
968 void DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
969 const Attr *Attr) override;
970 void DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) override;
971 void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override;
972 void AddedAttributeToRecord(const Attr *Attr,
973 const RecordDecl *Record) override;
974 void EnteringModulePurview() override;
975 void AddedManglingNumber(const Decl *D, unsigned) override;
976 void AddedStaticLocalNumbers(const Decl *D, unsigned) override;
977 void AddedAnonymousNamespace(const TranslationUnitDecl *,
978 NamespaceDecl *AnonNamespace) override;
979};
980
981/// AST and semantic-analysis consumer that generates a
982/// precompiled header from the parsed source code.
984 void anchor() override;
985
986 Preprocessor &PP;
987 llvm::PointerUnion<Sema *, Preprocessor *> Subject;
988 std::string OutputFile;
989 std::string isysroot;
990 std::shared_ptr<PCHBuffer> Buffer;
991 llvm::BitstreamWriter Stream;
992 ASTWriter Writer;
993 bool AllowASTWithErrors;
994 bool ShouldCacheASTInMemory;
995
996protected:
997 ASTWriter &getWriter() { return Writer; }
998 const ASTWriter &getWriter() const { return Writer; }
999 SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
1000
1001 bool isComplete() const { return Buffer->IsComplete; }
1002 PCHBuffer *getBufferPtr() { return Buffer.get(); }
1003 StringRef getOutputFile() const { return OutputFile; }
1006
1007 virtual Module *getEmittingModule(ASTContext &Ctx);
1008
1009public:
1010 PCHGenerator(Preprocessor &PP, ModuleCache &ModCache, StringRef OutputFile,
1011 StringRef isysroot, std::shared_ptr<PCHBuffer> Buffer,
1012 const CodeGenOptions &CodeGenOpts,
1013 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
1014 bool AllowASTWithErrors = false, bool IncludeTimestamps = true,
1015 bool BuildingImplicitModule = false,
1016 bool ShouldCacheASTInMemory = false,
1017 bool GeneratingReducedBMI = false);
1018 ~PCHGenerator() override;
1019
1020 void InitializeSema(Sema &S) override;
1021 void HandleTranslationUnit(ASTContext &Ctx) override;
1022 void HandleVTable(CXXRecordDecl *RD) override { Writer.handleVTable(RD); }
1025 bool hasEmittedPCH() const { return Buffer->IsComplete; }
1026};
1027
1029 void anchor() override;
1030
1031protected:
1032 virtual Module *getEmittingModule(ASTContext &Ctx) override;
1033
1035 StringRef OutputFile, const CodeGenOptions &CodeGenOpts,
1036 bool GeneratingReducedBMI, bool AllowASTWithErrors);
1037
1038public:
1040 StringRef OutputFile, const CodeGenOptions &CodeGenOpts,
1041 bool AllowASTWithErrors = false)
1042 : CXX20ModulesGenerator(PP, ModCache, OutputFile, CodeGenOpts,
1043 /*GeneratingReducedBMI=*/false,
1044 AllowASTWithErrors) {}
1045
1046 void HandleTranslationUnit(ASTContext &Ctx) override;
1047};
1048
1050 void anchor() override;
1051
1052public:
1054 StringRef OutputFile, const CodeGenOptions &CodeGenOpts,
1055 bool AllowASTWithErrors = false)
1056 : CXX20ModulesGenerator(PP, ModCache, OutputFile, CodeGenOpts,
1057 /*GeneratingReducedBMI=*/true,
1058 AllowASTWithErrors) {}
1059};
1060
1061/// If we can elide the definition of \param D in reduced BMI.
1062///
1063/// Generally, we can elide the definition of a declaration if it won't affect
1064/// the ABI. e.g., the non-inline function bodies.
1065bool CanElideDeclDef(const Decl *D);
1066
1067/// A simple helper class to pack several bits in order into (a) 32 bit
1068/// integer(s).
1070 constexpr static uint32_t BitIndexUpbound = 32u;
1071
1072public:
1073 BitsPacker() = default;
1074 BitsPacker(const BitsPacker &) = delete;
1078 ~BitsPacker() = default;
1079
1080 bool canWriteNextNBits(uint32_t BitsWidth) const {
1081 return CurrentBitIndex + BitsWidth < BitIndexUpbound;
1082 }
1083
1084 void reset(uint32_t Value) {
1085 UnderlyingValue = Value;
1086 CurrentBitIndex = 0;
1087 }
1088
1089 void addBit(bool Value) { addBits(Value, 1); }
1090 void addBits(uint32_t Value, uint32_t BitsWidth) {
1091 assert(BitsWidth < BitIndexUpbound);
1092 assert((Value < (1u << BitsWidth)) && "Passing narrower bit width!");
1093 assert(canWriteNextNBits(BitsWidth) &&
1094 "Inserting too much bits into a value!");
1095
1096 UnderlyingValue |= Value << CurrentBitIndex;
1097 CurrentBitIndex += BitsWidth;
1098 }
1099
1100 operator uint32_t() { return UnderlyingValue; }
1101
1102private:
1103 uint32_t UnderlyingValue = 0;
1104 uint32_t CurrentBitIndex = 0;
1105};
1106
1107} // namespace clang
1108
1109#endif // LLVM_CLANG_SERIALIZATION_ASTWRITER_H
TokenType getType() const
Returns the token's type, e.g.
Token Tok
The Token.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::SourceLocation class and associated facilities.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void EnteringModulePurview()
The parser find the named module declaration.
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:430
Writes an AST file containing the contents of a translation unit.
Definition ASTWriter.h:97
unsigned getDeclParmVarAbbrev() const
Definition ASTWriter.h:859
void AddEmittedDeclRef(const Decl *D, RecordDataImpl &Record)
friend class ASTRecordWriter
Definition ASTWriter.h:100
unsigned getBinaryOperatorAbbrev() const
Definition ASTWriter.h:892
unsigned getDeclTemplateTypeParmAbbrev() const
Definition ASTWriter.h:883
bool isWritingStdCXXNamedModules() const
Definition ASTWriter.h:907
ArrayRef< uint64_t > RecordDataRef
Definition ASTWriter.h:104
void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, StringRef Path)
Emit the current record with the given path as a blob.
void AddFileID(FileID FID, RecordDataImpl &Record)
Emit a FileID.
unsigned getDeclObjCIvarAbbrev() const
Definition ASTWriter.h:865
unsigned getExprImplicitCastAbbrev() const
Definition ASTWriter.h:891
bool isDeclPredefined(const Decl *D) const
Definition ASTWriter.h:919
unsigned getDeclTypedefAbbrev() const
Definition ASTWriter.h:861
bool hasChain() const
Definition ASTWriter.h:902
unsigned getSwitchCaseID(SwitchCase *S)
Retrieve the ID for the given switch-case statement.
void AddPath(StringRef Path, RecordDataImpl &Record)
Add a path to the given record.
SmallVectorImpl< uint64_t > RecordDataImpl
Definition ASTWriter.h:103
unsigned getDeclUsingShadowAbbrev() const
Definition ASTWriter.h:886
unsigned getTypeExtQualAbbrev() const
Definition ASTWriter.h:855
void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record)
Add a version tuple to the given record.
bool isGeneratingReducedBMI() const
Definition ASTWriter.h:915
uint32_t getMacroDirectivesOffset(const IdentifierInfo *Name)
unsigned getDeclVarAbbrev() const
Definition ASTWriter.h:862
unsigned getDeclEnumAbbrev() const
Definition ASTWriter.h:864
void AddAlignPackInfo(const Sema::AlignPackInfo &Info, RecordDataImpl &Record)
Emit a AlignPackInfo.
void AddPathBlob(StringRef Str, RecordDataImpl &Record, SmallVectorImpl< char > &Blob)
bool IsLocalDecl(const Decl *D)
Is this a local declaration (that is, one that will be written to our AST file)?
Definition ASTWriter.h:775
unsigned getDeclRefExprAbbrev() const
Definition ASTWriter.h:888
void AddTypeRef(ASTContext &Context, QualType T, RecordDataImpl &Record)
Emit a reference to a type.
unsigned getCXXOperatorCallExprAbbrev()
Definition ASTWriter.h:897
bool wasDeclEmitted(const Decl *D) const
Whether or not the declaration got emitted.
void AddString(StringRef Str, RecordDataImpl &Record)
Add a string to the given record.
time_t getTimestampForOutput(const FileEntry *E) const
Get a timestamp for output into the AST file.
~ASTWriter() override
bool isWritingModule() const
Definition ASTWriter.h:905
LocalDeclID GetDeclRef(const Decl *D)
Force a declaration to be emitted and get its local ID to the module file been writing.
void AddSourceRange(SourceRange Range, RecordDataImpl &Record)
Emit a source range.
LocalDeclID getDeclID(const Decl *D)
Determine the local declaration ID of an already-emitted declaration.
void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record)
Emit a source location.
void addTouchedModuleFile(serialization::ModuleFile *)
void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record)
Emit a reference to an identifier.
const CodeGenOptions & getCodeGenOpts() const
Definition ASTWriter.h:699
serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name)
Get the unique number used to refer to the given macro.
SourceLocationEncoding::RawLocEncoding getRawSourceLocationEncoding(SourceLocation Loc)
Return the raw encodings for source locations.
unsigned getCXXMemberCallExprAbbrev()
Definition ASTWriter.h:898
ASTFileSignature WriteAST(llvm::PointerUnion< Sema *, Preprocessor * > Subject, StringRef OutputFile, Module *WritingModule, StringRef isysroot, bool ShouldCacheASTInMemory=false)
Write a precompiled header or a module with the AST produced by the Sema object, or a dependency scan...
ASTReader * getChain() const
Definition ASTWriter.h:903
unsigned getCompoundAssignOperatorAbbrev() const
Definition ASTWriter.h:893
bool getDoneWritingDeclsAndTypes() const
Definition ASTWriter.h:917
friend class ASTDeclWriter
Definition ASTWriter.h:99
serialization::IdentifierID getIdentifierRef(const IdentifierInfo *II)
Get the unique number used to refer to the given identifier.
unsigned RecordSwitchCaseID(SwitchCase *S)
Record an ID for the given switch-case statement.
ASTWriter(llvm::BitstreamWriter &Stream, SmallVectorImpl< char > &Buffer, ModuleCache &ModCache, const CodeGenOptions &CodeGenOpts, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, bool IncludeTimestamps=true, bool BuildingImplicitModule=false, bool GeneratingReducedBMI=false)
Create a new precompiled header writer that outputs to the given bitstream.
unsigned getCharacterLiteralAbbrev() const
Definition ASTWriter.h:889
unsigned getDeclCXXMethodAbbrev(FunctionDecl::TemplatedKind Kind) const
Definition ASTWriter.h:866
void handleVTable(CXXRecordDecl *RD)
bool isWritingStdCXXHeaderUnit() const
Definition ASTWriter.h:911
unsigned getCompoundStmtAbbrev() const
Definition ASTWriter.h:900
unsigned getLocalOrImportedSubmoduleID(const Module *Mod)
Retrieve or create a submodule ID for this module, or return 0 if the submodule is neither local (a s...
const Decl * getFirstLocalDecl(const Decl *D)
Find the first local declaration of a given local redeclarable decl.
void AddToken(const Token &Tok, RecordDataImpl &Record)
Emit a token.
void AddLookupOffsets(const LookupBlockOffsets &Offsets, RecordDataImpl &Record)
serialization::SelectorID getSelectorRef(Selector Sel)
Get the unique number used to refer to the given selector.
SmallVector< uint64_t, 64 > RecordData
Definition ASTWriter.h:102
serialization::TypeID GetOrCreateTypeID(ASTContext &Context, QualType T)
Force a type to be emitted and get its ID.
unsigned getAnonymousDeclarationNumber(const NamedDecl *D)
unsigned getDeclFieldAbbrev() const
Definition ASTWriter.h:863
void AddMacroRef(MacroInfo *MI, const IdentifierInfo *Name, RecordDataImpl &Record)
Emit a reference to a macro.
const LangOptions & getLangOpts() const
void SetSelectorOffset(Selector Sel, uint32_t Offset)
Note that the selector Sel occurs at the given offset within the method pool/selector table.
bool PreparePathForOutput(SmallVectorImpl< char > &Path)
Convert a path from this build process into one that is appropriate for emission in the module file.
unsigned getCallExprAbbrev() const
Definition ASTWriter.h:896
void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset)
Note that the identifier II occurs at the given offset within the identifier table.
unsigned getDeclRecordAbbrev() const
Definition ASTWriter.h:860
void AddDeclRef(const Decl *D, RecordDataImpl &Record)
Emit a reference to a declaration.
void AddStringBlob(StringRef Str, RecordDataImpl &Record, SmallVectorImpl< char > &Blob)
unsigned getIntegerLiteralAbbrev() const
Definition ASTWriter.h:890
Attr - This represents one attribute.
Definition Attr.h:45
~BitsPacker()=default
void addBit(bool Value)
Definition ASTWriter.h:1089
bool canWriteNextNBits(uint32_t BitsWidth) const
Definition ASTWriter.h:1080
BitsPacker operator=(BitsPacker &&)=delete
BitsPacker(BitsPacker &&)=delete
BitsPacker()=default
void addBits(uint32_t Value, uint32_t BitsWidth)
Definition ASTWriter.h:1090
void reset(uint32_t Value)
Definition ASTWriter.h:1084
BitsPacker(const BitsPacker &)=delete
BitsPacker operator=(const BitsPacker &)=delete
CXX20ModulesGenerator(Preprocessor &PP, ModuleCache &ModCache, StringRef OutputFile, const CodeGenOptions &CodeGenOpts, bool GeneratingReducedBMI, bool AllowASTWithErrors)
void HandleTranslationUnit(ASTContext &Ctx) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
virtual Module * getEmittingModule(ASTContext &Ctx) override
CXX20ModulesGenerator(Preprocessor &PP, ModuleCache &ModCache, StringRef OutputFile, const CodeGenOptions &CodeGenOpts, bool AllowASTWithErrors=false)
Definition ASTWriter.h:1039
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition DeclBase.h:793
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
This represents one expression.
Definition Expr.h:112
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition Decl.h:2000
TemplatedKind
The kind of templated function a FunctionDecl can be.
Definition Decl.h:2005
@ TK_FunctionTemplateSpecialization
Definition Decl.h:2016
@ TK_DependentFunctionTemplateSpecialization
Definition Decl.h:2019
Declaration of a template function.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
One of these records is kept for each identifier that is lexed.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Record the location of a macro definition.
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:26
Abstract base class that writes a module file extension block into a module file.
An abstract superclass that describes a custom extension to the module/precompiled header file format...
Describes a module or submodule.
Definition Module.h:144
This represents a decl that may have a name.
Definition Decl.h:274
Represent a C++ namespace.
Definition Decl.h:592
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ASTMutationListener * GetASTMutationListener() override
If the consumer is interested in entities getting modified after their initial creation,...
void InitializeSema(Sema &S) override
Initialize the semantic consumer with the Sema instance being used to perform semantic analysis on th...
PCHBuffer * getBufferPtr()
Definition ASTWriter.h:1002
Preprocessor & getPreprocessor()
Definition ASTWriter.h:1005
virtual Module * getEmittingModule(ASTContext &Ctx)
SmallVectorImpl< char > & getPCH() const
Definition ASTWriter.h:999
StringRef getOutputFile() const
Definition ASTWriter.h:1003
~PCHGenerator() override
PCHGenerator(Preprocessor &PP, ModuleCache &ModCache, StringRef OutputFile, StringRef isysroot, std::shared_ptr< PCHBuffer > Buffer, const CodeGenOptions &CodeGenOpts, ArrayRef< std::shared_ptr< ModuleFileExtension > > Extensions, bool AllowASTWithErrors=false, bool IncludeTimestamps=true, bool BuildingImplicitModule=false, bool ShouldCacheASTInMemory=false, bool GeneratingReducedBMI=false)
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
Definition ASTWriter.h:1022
ASTDeserializationListener * GetASTDeserializationListener() override
If the consumer is interested in entities being deserialized from AST files, it should return a point...
const ASTWriter & getWriter() const
Definition ASTWriter.h:998
void HandleTranslationUnit(ASTContext &Ctx) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
bool hasEmittedPCH() const
Definition ASTWriter.h:1025
ASTWriter & getWriter()
Definition ASTWriter.h:997
bool isComplete() const
Definition ASTWriter.h:1001
DiagnosticsEngine & getDiagnostics() const
Represents a parameter to a function.
Definition Decl.h:1790
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
static QualType getFromOpaquePtr(const void *Ptr)
Definition TypeBase.h:986
Represents a struct/union/class.
Definition Decl.h:4312
ReducedBMIGenerator(Preprocessor &PP, ModuleCache &ModCache, StringRef OutputFile, const CodeGenOptions &CodeGenOpts, bool AllowASTWithErrors=false)
Definition ASTWriter.h:1053
Smart pointer class that efficiently represents Objective-C method names.
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Information about a FileID, basically just the logical file that it represents and include stack info...
Stmt - This represents one statement.
Definition Stmt.h:85
An array of decls optimized for the common case of only containing one entry.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
Token - This structure provides full information about a lexed token.
Definition Token.h:36
The top declaration context.
Definition Decl.h:105
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:926
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:130
A type index; the type ID with the qualifier bits removed.
Definition ASTBitCodes.h:99
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Public enums and private classes that are part of the SourceManager implementation.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition ASTBitCodes.h:66
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
uint64_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
uint64_t MacroID
An ID number that refers to a macro in an AST file.
uint64_t TypeID
An ID number that refers to a type in an AST file.
Definition ASTBitCodes.h:88
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
uint64_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition ASTBitCodes.h:63
The JSON file list parser is used to communicate input to InstallAPI.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
PredefinedDeclIDs
Predefined declaration IDs.
Definition DeclID.h:31
@ NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition DeclID.h:87
const FunctionProtoType * T
bool CanElideDeclDef(const Decl *D)
If we can elide the definition of.
unsigned long uint64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
The signature of a module, which is a hash of the AST content.
Definition Module.h:58
A structure for putting "fast"-unqualified QualTypes into a DenseMap.