Coverage Report

Created: 2022-01-18 06:27

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