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