Coverage Report

Created: 2022-05-14 11:35

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Serialization/ASTWriter.h
Line
Count
Source (jump to first uncovered line)
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
17
#include "clang/AST/ASTMutationListener.h"
18
#include "clang/AST/Decl.h"
19
#include "clang/AST/Type.h"
20
#include "clang/Basic/LLVM.h"
21
#include "clang/Basic/Module.h"
22
#include "clang/Basic/SourceLocation.h"
23
#include "clang/Sema/Sema.h"
24
#include "clang/Sema/SemaConsumer.h"
25
#include "clang/Serialization/ASTBitCodes.h"
26
#include "clang/Serialization/ASTDeserializationListener.h"
27
#include "clang/Serialization/PCHContainerOperations.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
47
namespace clang {
48
49
class ASTContext;
50
class ASTReader;
51
class Attr;
52
class CXXRecordDecl;
53
class FileEntry;
54
class FPOptionsOverride;
55
class FunctionDecl;
56
class HeaderSearch;
57
class HeaderSearchOptions;
58
class IdentifierResolver;
59
class LangOptions;
60
class MacroDefinitionRecord;
61
class MacroInfo;
62
class Module;
63
class InMemoryModuleCache;
64
class ModuleFileExtension;
65
class ModuleFileExtensionWriter;
66
class NamedDecl;
67
class ObjCInterfaceDecl;
68
class PreprocessingRecord;
69
class Preprocessor;
70
class RecordDecl;
71
class Sema;
72
class SourceManager;
73
class Stmt;
74
class StoredDeclsList;
75
class SwitchCase;
76
class Token;
77
78
/// Writes an AST file containing the contents of a translation unit.
79
///
80
/// The ASTWriter class produces a bitstream containing the serialized
81
/// representation of a given abstract syntax tree and its supporting
82
/// data structures. This bitstream can be de-serialized via an
83
/// instance of the ASTReader class.
84
class ASTWriter : public ASTDeserializationListener,
85
                  public ASTMutationListener {
86
public:
87
  friend class ASTDeclWriter;
88
  friend class ASTRecordWriter;
89
90
  using RecordData = SmallVector<uint64_t, 64>;
91
  using RecordDataImpl = SmallVectorImpl<uint64_t>;
92
  using RecordDataRef = ArrayRef<uint64_t>;
93
94
private:
95
  /// Map that provides the ID numbers of each type within the
96
  /// output stream, plus those deserialized from a chained PCH.
97
  ///
98
  /// The ID numbers of types are consecutive (in order of discovery)
99
  /// and start at 1. 0 is reserved for NULL. When types are actually
100
  /// stored in the stream, the ID number is shifted by 2 bits to
101
  /// allow for the const/volatile qualifiers.
102
  ///
103
  /// Keys in the map never have const/volatile qualifiers.
104
  using TypeIdxMap = llvm::DenseMap<QualType, serialization::TypeIdx,
105
                                    serialization::UnsafeQualTypeDenseMapInfo>;
106
107
  /// The bitstream writer used to emit this precompiled header.
108
  llvm::BitstreamWriter &Stream;
109
110
  /// The buffer associated with the bitstream.
111
  const SmallVectorImpl<char> &Buffer;
112
113
  /// The PCM manager which manages memory buffers for pcm files.
114
  InMemoryModuleCache &ModuleCache;
115
116
  /// The ASTContext we're writing.
117
  ASTContext *Context = nullptr;
118
119
  /// The preprocessor we're writing.
120
  Preprocessor *PP = nullptr;
121
122
  /// The reader of existing AST files, if we're chaining.
123
  ASTReader *Chain = nullptr;
124
125
  /// The module we're currently writing, if any.
126
  Module *WritingModule = nullptr;
127
128
  /// The offset of the first bit inside the AST_BLOCK.
129
  uint64_t ASTBlockStartOffset = 0;
130
131
  /// The range representing all the AST_BLOCK.
132
  std::pair<uint64_t, uint64_t> ASTBlockRange;
133
134
  /// The base directory for any relative paths we emit.
135
  std::string BaseDirectory;
136
137
  /// Indicates whether timestamps should be written to the produced
138
  /// module file. This is the case for files implicitly written to the
139
  /// module cache, where we need the timestamps to determine if the module
140
  /// file is up to date, but not otherwise.
141
  bool IncludeTimestamps;
142
143
  /// Indicates when the AST writing is actively performing
144
  /// serialization, rather than just queueing updates.
145
  bool WritingAST = false;
146
147
  /// Indicates that we are done serializing the collection of decls
148
  /// and types to emit.
149
  bool DoneWritingDeclsAndTypes = false;
150
151
  /// Indicates that the AST contained compiler errors.
152
  bool ASTHasCompilerErrors = false;
153
154
  /// Mapping from input file entries to the index into the
155
  /// offset table where information about that input file is stored.
156
  llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs;
157
158
  /// Stores a declaration or a type to be written to the AST file.
159
  class DeclOrType {
160
  public:
161
3.21M
    DeclOrType(Decl *D) : Stored(D), IsType(false) {}
162
1.62M
    DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) {}
163
164
6.46M
    bool isType() const { return IsType; }
165
3.21M
    bool isDecl() const { return !IsType; }
166
167
1.62M
    QualType getType() const {
168
1.62M
      assert(isType() && "Not a type!");
169
0
      return QualType::getFromOpaquePtr(Stored);
170
1.62M
    }
171
172
3.21M
    Decl *getDecl() const {
173
3.21M
      assert(isDecl() && "Not a decl!");
174
0
      return static_cast<Decl *>(Stored);
175
3.21M
    }
176
177
  private:
178
    void *Stored;
179
    bool IsType;
180
  };
181
182
  /// The declarations and types to emit.
183
  std::queue<DeclOrType> DeclTypesToEmit;
184
185
  /// The first ID number we can use for our own declarations.
186
  serialization::DeclID FirstDeclID = serialization::NUM_PREDEF_DECL_IDS;
187
188
  /// The decl ID that will be assigned to the next new decl.
189
  serialization::DeclID NextDeclID = FirstDeclID;
190
191
  /// Map that provides the ID numbers of each declaration within
192
  /// the output stream, as well as those deserialized from a chained PCH.
193
  ///
194
  /// The ID numbers of declarations are consecutive (in order of
195
  /// discovery) and start at 2. 1 is reserved for the translation
196
  /// unit, while 0 is reserved for NULL.
197
  llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs;
198
199
  /// Offset of each declaration in the bitstream, indexed by
200
  /// the declaration's ID.
201
  std::vector<serialization::DeclOffset> DeclOffsets;
202
203
  /// The offset of the DECLTYPES_BLOCK. The offsets in DeclOffsets
204
  /// are relative to this value.
205
  uint64_t DeclTypesBlockStartOffset = 0;
206
207
  /// Sorted (by file offset) vector of pairs of file offset/DeclID.
208
  using LocDeclIDsTy =
209
      SmallVector<std::pair<unsigned, serialization::DeclID>, 64>;
210
  struct DeclIDInFileInfo {
211
    LocDeclIDsTy DeclIDs;
212
213
    /// Set when the DeclIDs vectors from all files are joined, this
214
    /// indicates the index that this particular vector has in the global one.
215
    unsigned FirstDeclIndex;
216
  };
217
  using FileDeclIDsTy =
218
      llvm::DenseMap<FileID, std::unique_ptr<DeclIDInFileInfo>>;
219
220
  /// Map from file SLocEntries to info about the file-level declarations
221
  /// that it contains.
222
  FileDeclIDsTy FileDeclIDs;
223
224
  void associateDeclWithFile(const Decl *D, serialization::DeclID);
225
226
  /// The first ID number we can use for our own types.
227
  serialization::TypeID FirstTypeID = serialization::NUM_PREDEF_TYPE_IDS;
228
229
  /// The type ID that will be assigned to the next new type.
230
  serialization::TypeID NextTypeID = FirstTypeID;
231
232
  /// Map that provides the ID numbers of each type within the
233
  /// output stream, plus those deserialized from a chained PCH.
234
  ///
235
  /// The ID numbers of types are consecutive (in order of discovery)
236
  /// and start at 1. 0 is reserved for NULL. When types are actually
237
  /// stored in the stream, the ID number is shifted by 2 bits to
238
  /// allow for the const/volatile qualifiers.
239
  ///
240
  /// Keys in the map never have const/volatile qualifiers.
241
  TypeIdxMap TypeIdxs;
242
243
  /// Offset of each type in the bitstream, indexed by
244
  /// the type's ID.
245
  std::vector<serialization::UnderalignedInt64> TypeOffsets;
246
247
  /// The first ID number we can use for our own identifiers.
248
  serialization::IdentID FirstIdentID = serialization::NUM_PREDEF_IDENT_IDS;
249
250
  /// The identifier ID that will be assigned to the next new identifier.
251
  serialization::IdentID NextIdentID = FirstIdentID;
252
253
  /// Map that provides the ID numbers of each identifier in
254
  /// the output stream.
255
  ///
256
  /// The ID numbers for identifiers are consecutive (in order of
257
  /// discovery), starting at 1. An ID of zero refers to a NULL
258
  /// IdentifierInfo.
259
  llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
260
261
  /// The first ID number we can use for our own macros.
262
  serialization::MacroID FirstMacroID = serialization::NUM_PREDEF_MACRO_IDS;
263
264
  /// The identifier ID that will be assigned to the next new identifier.
265
  serialization::MacroID NextMacroID = FirstMacroID;
266
267
  /// Map that provides the ID numbers of each macro.
268
  llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
269
270
  struct MacroInfoToEmitData {
271
    const IdentifierInfo *Name;
272
    MacroInfo *MI;
273
    serialization::MacroID ID;
274
  };
275
276
  /// The macro infos to emit.
277
  std::vector<MacroInfoToEmitData> MacroInfosToEmit;
278
279
  llvm::DenseMap<const IdentifierInfo *, uint32_t>
280
      IdentMacroDirectivesOffsetMap;
281
282
  /// @name FlushStmt Caches
283
  /// @{
284
285
  /// Set of parent Stmts for the currently serializing sub-stmt.
286
  llvm::DenseSet<Stmt *> ParentStmts;
287
288
  /// Offsets of sub-stmts already serialized. The offset points
289
  /// just after the stmt record.
290
  llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
291
292
  /// @}
293
294
  /// Offsets of each of the identifier IDs into the identifier
295
  /// table.
296
  std::vector<uint32_t> IdentifierOffsets;
297
298
  /// The first ID number we can use for our own submodules.
299
  serialization::SubmoduleID FirstSubmoduleID =
300
      serialization::NUM_PREDEF_SUBMODULE_IDS;
301
302
  /// The submodule ID that will be assigned to the next new submodule.
303
  serialization::SubmoduleID NextSubmoduleID = FirstSubmoduleID;
304
305
  /// The first ID number we can use for our own selectors.
306
  serialization::SelectorID FirstSelectorID =
307
      serialization::NUM_PREDEF_SELECTOR_IDS;
308
309
  /// The selector ID that will be assigned to the next new selector.
310
  serialization::SelectorID NextSelectorID = FirstSelectorID;
311
312
  /// Map that provides the ID numbers of each Selector.
313
  llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
314
315
  /// Offset of each selector within the method pool/selector
316
  /// table, indexed by the Selector ID (-1).
317
  std::vector<uint32_t> SelectorOffsets;
318
319
  /// Mapping from macro definitions (as they occur in the preprocessing
320
  /// record) to the macro IDs.
321
  llvm::DenseMap<const MacroDefinitionRecord *,
322
                 serialization::PreprocessedEntityID> MacroDefinitions;
323
324
  /// Cache of indices of anonymous declarations within their lexical
325
  /// contexts.
326
  llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
327
328
  /// An update to a Decl.
329
  class DeclUpdate {
330
    /// A DeclUpdateKind.
331
    unsigned Kind;
332
    union {
333
      const Decl *Dcl;
334
      void *Type;
335
      SourceLocation::UIntTy Loc;
336
      unsigned Val;
337
      Module *Mod;
338
      const Attr *Attribute;
339
    };
340
341
  public:
342
1.94k
    DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {}
343
725
    DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {}
344
    DeclUpdate(unsigned Kind, QualType Type)
345
2
        : Kind(Kind), Type(Type.getAsOpaquePtr()) {}
346
    DeclUpdate(unsigned Kind, SourceLocation Loc)
347
7
        : Kind(Kind), Loc(Loc.getRawEncoding()) {}
348
1.33k
    DeclUpdate(unsigned Kind, unsigned Val) : Kind(Kind), Val(Val) {}
349
515
    DeclUpdate(unsigned Kind, Module *M) : Kind(Kind), Mod(M) {}
350
    DeclUpdate(unsigned Kind, const Attr *Attribute)
351
4
          : Kind(Kind), Attribute(Attribute) {}
352
353
4.52k
    unsigned getKind() const { return Kind; }
354
1.44k
    const Decl *getDecl() const { return Dcl; }
355
2
    QualType getType() const { return QualType::getFromOpaquePtr(Type); }
356
357
7
    SourceLocation getLoc() const {
358
7
      return SourceLocation::getFromRawEncoding(Loc);
359
7
    }
360
361
1.33k
    unsigned getNumber() const { return Val; }
362
515
    Module *getModule() const { return Mod; }
363
1
    const Attr *getAttr() const { return Attribute; }
364
  };
365
366
  using UpdateRecord = SmallVector<DeclUpdate, 1>;
367
  using DeclUpdateMap = llvm::MapVector<const Decl *, UpdateRecord>;
368
369
  /// Mapping from declarations that came from a chained PCH to the
370
  /// record containing modifications to them.
371
  DeclUpdateMap DeclUpdates;
372
373
  using FirstLatestDeclMap = llvm::DenseMap<Decl *, Decl *>;
374
375
  /// Map of first declarations from a chained PCH that point to the
376
  /// most recent declarations in another PCH.
377
  FirstLatestDeclMap FirstLatestDecls;
378
379
  /// Declarations encountered that might be external
380
  /// definitions.
381
  ///
382
  /// We keep track of external definitions and other 'interesting' declarations
383
  /// as we are emitting declarations to the AST file. The AST file contains a
384
  /// separate record for these declarations, which are provided to the AST
385
  /// consumer by the AST reader. This is behavior is required to properly cope with,
386
  /// e.g., tentative variable definitions that occur within
387
  /// headers. The declarations themselves are stored as declaration
388
  /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS
389
  /// record.
390
  SmallVector<serialization::DeclID, 16> EagerlyDeserializedDecls;
391
  SmallVector<serialization::DeclID, 16> ModularCodegenDecls;
392
393
  /// DeclContexts that have received extensions since their serialized
394
  /// form.
395
  ///
396
  /// For namespaces, when we're chaining and encountering a namespace, we check
397
  /// if its primary namespace comes from the chain. If it does, we add the
398
  /// primary to this set, so that we can write out lexical content updates for
399
  /// it.
400
  llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
401
402
  /// Keeps track of declarations that we must emit, even though we're
403
  /// not guaranteed to be able to find them by walking the AST starting at the
404
  /// translation unit.
405
  SmallVector<const Decl *, 16> DeclsToEmitEvenIfUnreferenced;
406
407
  /// The set of Objective-C class that have categories we
408
  /// should serialize.
409
  llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
410
411
  /// The set of declarations that may have redeclaration chains that
412
  /// need to be serialized.
413
  llvm::SmallVector<const Decl *, 16> Redeclarations;
414
415
  /// A cache of the first local declaration for "interesting"
416
  /// redeclaration chains.
417
  llvm::DenseMap<const Decl *, const Decl *> FirstLocalDeclCache;
418
419
  /// Mapping from SwitchCase statements to IDs.
420
  llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
421
422
  /// The number of statements written to the AST file.
423
  unsigned NumStatements = 0;
424
425
  /// The number of macros written to the AST file.
426
  unsigned NumMacros = 0;
427
428
  /// The number of lexical declcontexts written to the AST
429
  /// file.
430
  unsigned NumLexicalDeclContexts = 0;
431
432
  /// The number of visible declcontexts written to the AST
433
  /// file.
434
  unsigned NumVisibleDeclContexts = 0;
435
436
  /// A mapping from each known submodule to its ID number, which will
437
  /// be a positive integer.
438
  llvm::DenseMap<const Module *, unsigned> SubmoduleIDs;
439
440
  /// A list of the module file extension writers.
441
  std::vector<std::unique_ptr<ModuleFileExtensionWriter>>
442
      ModuleFileExtensionWriters;
443
444
  /// User ModuleMaps skipped when writing control block.
445
  std::set<const FileEntry *> SkippedModuleMaps;
446
447
  /// Retrieve or create a submodule ID for this module.
448
  unsigned getSubmoduleID(Module *Mod);
449
450
  /// Write the given subexpression to the bitstream.
451
  void WriteSubStmt(Stmt *S);
452
453
  void WriteBlockInfoBlock();
454
  void WriteControlBlock(Preprocessor &PP, ASTContext &Context,
455
                         StringRef isysroot, const std::string &OutputFile);
456
457
  /// Write out the signature and diagnostic options, and return the signature.
458
  ASTFileSignature writeUnhashedControlBlock(Preprocessor &PP,
459
                                             ASTContext &Context);
460
461
  /// Calculate hash of the pcm content.
462
  static std::pair<ASTFileSignature, ASTFileSignature>
463
  createSignature(StringRef AllBytes, StringRef ASTBlockBytes);
464
465
  void WriteInputFiles(SourceManager &SourceMgr, HeaderSearchOptions &HSOpts,
466
                       std::set<const FileEntry *> &AffectingModuleMaps);
467
  void WriteSourceManagerBlock(SourceManager &SourceMgr,
468
                               const Preprocessor &PP);
469
  void writeIncludedFiles(raw_ostream &Out, const Preprocessor &PP);
470
  void WritePreprocessor(const Preprocessor &PP, bool IsModule);
471
  void WriteHeaderSearch(const HeaderSearch &HS);
472
  void WritePreprocessorDetail(PreprocessingRecord &PPRec,
473
                               uint64_t MacroOffsetsBase);
474
  void WriteSubmodules(Module *WritingModule);
475
476
  void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
477
                                     bool isModule);
478
479
  unsigned TypeExtQualAbbrev = 0;
480
  void WriteTypeAbbrevs();
481
  void WriteType(QualType T);
482
483
  bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
484
  bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
485
486
  void GenerateNameLookupTable(const DeclContext *DC,
487
                               llvm::SmallVectorImpl<char> &LookupTable);
488
  uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
489
  uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
490
  void WriteTypeDeclOffsets();
491
  void WriteFileDeclIDsMap();
492
  void WriteComments();
493
  void WriteSelectors(Sema &SemaRef);
494
  void WriteReferencedSelectorsPool(Sema &SemaRef);
495
  void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver,
496
                            bool IsModule);
497
  void WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord);
498
  void WriteDeclContextVisibleUpdate(const DeclContext *DC);
499
  void WriteFPPragmaOptions(const FPOptionsOverride &Opts);
500
  void WriteOpenCLExtensions(Sema &SemaRef);
501
  void WriteCUDAPragmas(Sema &SemaRef);
502
  void WriteObjCCategories();
503
  void WriteLateParsedTemplates(Sema &SemaRef);
504
  void WriteOptimizePragmaOptions(Sema &SemaRef);
505
  void WriteMSStructPragmaOptions(Sema &SemaRef);
506
  void WriteMSPointersToMembersPragmaOptions(Sema &SemaRef);
507
  void WritePackPragmaOptions(Sema &SemaRef);
508
  void WriteFloatControlPragmaOptions(Sema &SemaRef);
509
  void WriteModuleFileExtension(Sema &SemaRef,
510
                                ModuleFileExtensionWriter &Writer);
511
512
  unsigned DeclParmVarAbbrev = 0;
513
  unsigned DeclContextLexicalAbbrev = 0;
514
  unsigned DeclContextVisibleLookupAbbrev = 0;
515
  unsigned UpdateVisibleAbbrev = 0;
516
  unsigned DeclRecordAbbrev = 0;
517
  unsigned DeclTypedefAbbrev = 0;
518
  unsigned DeclVarAbbrev = 0;
519
  unsigned DeclFieldAbbrev = 0;
520
  unsigned DeclEnumAbbrev = 0;
521
  unsigned DeclObjCIvarAbbrev = 0;
522
  unsigned DeclCXXMethodAbbrev = 0;
523
524
  unsigned DeclRefExprAbbrev = 0;
525
  unsigned CharacterLiteralAbbrev = 0;
526
  unsigned IntegerLiteralAbbrev = 0;
527
  unsigned ExprImplicitCastAbbrev = 0;
528
529
  void WriteDeclAbbrevs();
530
  void WriteDecl(ASTContext &Context, Decl *D);
531
532
  ASTFileSignature WriteASTCore(Sema &SemaRef, StringRef isysroot,
533
                                const std::string &OutputFile,
534
                                Module *WritingModule);
535
536
public:
537
  /// Create a new precompiled header writer that outputs to
538
  /// the given bitstream.
539
  ASTWriter(llvm::BitstreamWriter &Stream, SmallVectorImpl<char> &Buffer,
540
            InMemoryModuleCache &ModuleCache,
541
            ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
542
            bool IncludeTimestamps = true);
543
  ~ASTWriter() override;
544
545
10.5M
  ASTContext &getASTContext() const {
546
10.5M
    assert(Context && "requested AST context when not writing AST");
547
0
    return *Context;
548
10.5M
  }
549
550
  const LangOptions &getLangOpts() const;
551
552
  /// Get a timestamp for output into the AST file. The actual timestamp
553
  /// of the specified file may be ignored if we have been instructed to not
554
  /// include timestamps in the output file.
555
  time_t getTimestampForOutput(const FileEntry *E) const;
556
557
  /// Write a precompiled header for the given semantic analysis.
558
  ///
559
  /// \param SemaRef a reference to the semantic analysis object that processed
560
  /// the AST to be written into the precompiled header.
561
  ///
562
  /// \param WritingModule The module that we are writing. If null, we are
563
  /// writing a precompiled header.
564
  ///
565
  /// \param isysroot if non-empty, write a relocatable file whose headers
566
  /// are relative to the given system root. If we're writing a module, its
567
  /// build directory will be used in preference to this if both are available.
568
  ///
569
  /// \return the module signature, which eventually will be a hash of
570
  /// the module but currently is merely a random 32-bit number.
571
  ASTFileSignature WriteAST(Sema &SemaRef, const std::string &OutputFile,
572
                            Module *WritingModule, StringRef isysroot,
573
                            bool hasErrors = false,
574
                            bool ShouldCacheASTInMemory = false);
575
576
  /// Emit a token.
577
  void AddToken(const Token &Tok, RecordDataImpl &Record);
578
579
  /// Emit a AlignPackInfo.
580
  void AddAlignPackInfo(const Sema::AlignPackInfo &Info,
581
                        RecordDataImpl &Record);
582
583
  /// Emit a source location.
584
  void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
585
586
  /// Emit a source range.
587
  void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
588
589
  /// Emit a reference to an identifier.
590
  void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
591
592
  /// Get the unique number used to refer to the given selector.
593
  serialization::SelectorID getSelectorRef(Selector Sel);
594
595
  /// Get the unique number used to refer to the given identifier.
596
  serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
597
598
  /// Get the unique number used to refer to the given macro.
599
  serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
600
601
  /// Determine the ID of an already-emitted macro.
602
  serialization::MacroID getMacroID(MacroInfo *MI);
603
604
  uint32_t getMacroDirectivesOffset(const IdentifierInfo *Name);
605
606
  /// Emit a reference to a type.
607
  void AddTypeRef(QualType T, RecordDataImpl &Record);
608
609
  /// Force a type to be emitted and get its ID.
610
  serialization::TypeID GetOrCreateTypeID(QualType T);
611
612
  /// Determine the type ID of an already-emitted type.
613
  serialization::TypeID getTypeID(QualType T) const;
614
615
  /// Find the first local declaration of a given local redeclarable
616
  /// decl.
617
  const Decl *getFirstLocalDecl(const Decl *D);
618
619
  /// Is this a local declaration (that is, one that will be written to
620
  /// our AST file)? This is the case for declarations that are neither imported
621
  /// from another AST file nor predefined.
622
539k
  bool IsLocalDecl(const Decl *D) {
623
539k
    if (D->isFromASTFile())
624
21.5k
      return false;
625
518k
    auto I = DeclIDs.find(D);
626
518k
    return (I == DeclIDs.end() ||
627
518k
            
I->second >= serialization::NUM_PREDEF_DECL_IDS200k
);
628
539k
  };
629
630
  /// Emit a reference to a declaration.
631
  void AddDeclRef(const Decl *D, RecordDataImpl &Record);
632
633
  /// Force a declaration to be emitted and get its ID.
634
  serialization::DeclID GetDeclRef(const Decl *D);
635
636
  /// Determine the declaration ID of an already-emitted
637
  /// declaration.
638
  serialization::DeclID getDeclID(const Decl *D);
639
640
  unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
641
642
  /// Add a string to the given record.
643
  void AddString(StringRef Str, RecordDataImpl &Record);
644
645
  /// Convert a path from this build process into one that is appropriate
646
  /// for emission in the module file.
647
  bool PreparePathForOutput(SmallVectorImpl<char> &Path);
648
649
  /// Add a path to the given record.
650
  void AddPath(StringRef Path, RecordDataImpl &Record);
651
652
  /// Emit the current record with the given path as a blob.
653
  void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
654
                          StringRef Path);
655
656
  /// Add a version tuple to the given record
657
  void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
658
659
  /// Retrieve or create a submodule ID for this module, or return 0 if
660
  /// the submodule is neither local (a submodle of the currently-written module)
661
  /// nor from an imported module.
662
  unsigned getLocalOrImportedSubmoduleID(const Module *Mod);
663
664
  /// Note that the identifier II occurs at the given offset
665
  /// within the identifier table.
666
  void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
667
668
  /// Note that the selector Sel occurs at the given offset
669
  /// within the method pool/selector table.
670
  void SetSelectorOffset(Selector Sel, uint32_t Offset);
671
672
  /// Record an ID for the given switch-case statement.
673
  unsigned RecordSwitchCaseID(SwitchCase *S);
674
675
  /// Retrieve the ID for the given switch-case statement.
676
  unsigned getSwitchCaseID(SwitchCase *S);
677
678
  void ClearSwitchCaseIDs();
679
680
6.20k
  unsigned getTypeExtQualAbbrev() const {
681
6.20k
    return TypeExtQualAbbrev;
682
6.20k
  }
683
684
631k
  unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
685
6.55k
  unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
686
104k
  unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
687
2.34k
  unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
688
215k
  unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
689
14.0k
  unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
690
3.16k
  unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
691
21.3k
  unsigned getDeclCXXMethodAbbrev() const { return DeclCXXMethodAbbrev; }
692
693
869k
  unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
694
30.3k
  unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
695
382k
  unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
696
795k
  unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
697
698
12.9k
  bool hasChain() const { return Chain; }
699
397
  ASTReader *getChain() const { return Chain; }
700
701
private:
702
  // ASTDeserializationListener implementation
703
  void ReaderInitialized(ASTReader *Reader) override;
704
  void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override;
705
  void MacroRead(serialization::MacroID ID, MacroInfo *MI) override;
706
  void TypeRead(serialization::TypeIdx Idx, QualType T) override;
707
  void SelectorRead(serialization::SelectorID ID, Selector Sel) override;
708
  void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
709
                           MacroDefinitionRecord *MD) override;
710
  void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
711
712
  // ASTMutationListener implementation.
713
  void CompletedTagDefinition(const TagDecl *D) override;
714
  void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
715
  void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
716
  void AddedCXXTemplateSpecialization(
717
      const ClassTemplateDecl *TD,
718
      const ClassTemplateSpecializationDecl *D) override;
719
  void AddedCXXTemplateSpecialization(
720
      const VarTemplateDecl *TD,
721
      const VarTemplateSpecializationDecl *D) override;
722
  void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
723
                                      const FunctionDecl *D) override;
724
  void ResolvedExceptionSpec(const FunctionDecl *FD) override;
725
  void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override;
726
  void ResolvedOperatorDelete(const CXXDestructorDecl *DD,
727
                              const FunctionDecl *Delete,
728
                              Expr *ThisArg) override;
729
  void CompletedImplicitDefinition(const FunctionDecl *D) override;
730
  void InstantiationRequested(const ValueDecl *D) override;
731
  void VariableDefinitionInstantiated(const VarDecl *D) override;
732
  void FunctionDefinitionInstantiated(const FunctionDecl *D) override;
733
  void DefaultArgumentInstantiated(const ParmVarDecl *D) override;
734
  void DefaultMemberInitializerInstantiated(const FieldDecl *D) override;
735
  void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
736
                                    const ObjCInterfaceDecl *IFD) override;
737
  void DeclarationMarkedUsed(const Decl *D) override;
738
  void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override;
739
  void DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
740
                                            const Attr *Attr) override;
741
  void DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) override;
742
  void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override;
743
  void AddedAttributeToRecord(const Attr *Attr,
744
                              const RecordDecl *Record) override;
745
};
746
747
/// AST and semantic-analysis consumer that generates a
748
/// precompiled header from the parsed source code.
749
class PCHGenerator : public SemaConsumer {
750
  const Preprocessor &PP;
751
  std::string OutputFile;
752
  std::string isysroot;
753
  Sema *SemaPtr;
754
  std::shared_ptr<PCHBuffer> Buffer;
755
  llvm::BitstreamWriter Stream;
756
  ASTWriter Writer;
757
  bool AllowASTWithErrors;
758
  bool ShouldCacheASTInMemory;
759
760
protected:
761
91
  ASTWriter &getWriter() { return Writer; }
762
0
  const ASTWriter &getWriter() const { return Writer; }
763
0
  SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
764
765
public:
766
  PCHGenerator(const Preprocessor &PP, InMemoryModuleCache &ModuleCache,
767
               StringRef OutputFile, StringRef isysroot,
768
               std::shared_ptr<PCHBuffer> Buffer,
769
               ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
770
               bool AllowASTWithErrors = false, bool IncludeTimestamps = true,
771
               bool ShouldCacheASTInMemory = false);
772
  ~PCHGenerator() override;
773
774
5.57k
  void InitializeSema(Sema &S) override { SemaPtr = &S; }
775
  void HandleTranslationUnit(ASTContext &Ctx) override;
776
  ASTMutationListener *GetASTMutationListener() override;
777
  ASTDeserializationListener *GetASTDeserializationListener() override;
778
91
  bool hasEmittedPCH() const { return Buffer->IsComplete; }
779
};
780
781
} // namespace clang
782
783
#endif // LLVM_CLANG_SERIALIZATION_ASTWRITER_H