1 //===--- ASTWriter.h - AST File Writer --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTWriter class, which writes an AST file
11 // containing a serialized representation of a translation unit.
13 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SERIALIZATION_ASTWRITER_H
15 #define LLVM_CLANG_SERIALIZATION_ASTWRITER_H
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/TemplateBase.h"
21 #include "clang/Sema/SemaConsumer.h"
22 #include "clang/Serialization/ASTBitCodes.h"
23 #include "clang/Serialization/ASTDeserializationListener.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Bitcode/BitstreamWriter.h"
38 class BitstreamWriter;
44 class NestedNameSpecifier;
45 class CXXBaseSpecifier;
46 class CXXCtorInitializer;
50 class HeaderSearchOptions;
51 class IdentifierResolver;
52 class MacroDefinitionRecord;
55 class OpaqueValueExpr;
59 class PreprocessedEntity;
60 class PreprocessingRecord;
64 struct StoredDeclsList;
69 class ASTUnresolvedSet;
71 namespace SrcMgr { class SLocEntry; }
73 /// \brief Writes an AST file containing the contents of a translation unit.
75 /// The ASTWriter class produces a bitstream containing the serialized
76 /// representation of a given abstract syntax tree and its supporting
77 /// data structures. This bitstream can be de-serialized via an
78 /// instance of the ASTReader class.
79 class ASTWriter : public ASTDeserializationListener,
80 public ASTMutationListener {
82 typedef SmallVector<uint64_t, 64> RecordData;
83 typedef SmallVectorImpl<uint64_t> RecordDataImpl;
85 friend class ASTDeclWriter;
86 friend class ASTStmtWriter;
88 /// \brief Map that provides the ID numbers of each type within the
89 /// output stream, plus those deserialized from a chained PCH.
91 /// The ID numbers of types are consecutive (in order of discovery)
92 /// and start at 1. 0 is reserved for NULL. When types are actually
93 /// stored in the stream, the ID number is shifted by 2 bits to
94 /// allow for the const/volatile qualifiers.
96 /// Keys in the map never have const/volatile qualifiers.
97 typedef llvm::DenseMap<QualType, serialization::TypeIdx,
98 serialization::UnsafeQualTypeDenseMapInfo>
101 /// \brief The bitstream writer used to emit this precompiled header.
102 llvm::BitstreamWriter &Stream;
104 /// \brief The ASTContext we're writing.
107 /// \brief The preprocessor we're writing.
110 /// \brief The reader of existing AST files, if we're chaining.
113 /// \brief The module we're currently writing, if any.
114 Module *WritingModule;
116 /// \brief The base directory for any relative paths we emit.
117 std::string BaseDirectory;
119 /// \brief Indicates when the AST writing is actively performing
120 /// serialization, rather than just queueing updates.
123 /// \brief Indicates that we are done serializing the collection of decls
124 /// and types to emit.
125 bool DoneWritingDeclsAndTypes;
127 /// \brief Indicates that the AST contained compiler errors.
128 bool ASTHasCompilerErrors;
130 /// \brief Mapping from input file entries to the index into the
131 /// offset table where information about that input file is stored.
132 llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs;
134 /// \brief Stores a declaration or a type to be written to the AST file.
137 DeclOrType(Decl *D) : Stored(D), IsType(false) { }
138 DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
140 bool isType() const { return IsType; }
141 bool isDecl() const { return !IsType; }
143 QualType getType() const {
144 assert(isType() && "Not a type!");
145 return QualType::getFromOpaquePtr(Stored);
148 Decl *getDecl() const {
149 assert(isDecl() && "Not a decl!");
150 return static_cast<Decl *>(Stored);
158 /// \brief The declarations and types to emit.
159 std::queue<DeclOrType> DeclTypesToEmit;
161 /// \brief The first ID number we can use for our own declarations.
162 serialization::DeclID FirstDeclID;
164 /// \brief The decl ID that will be assigned to the next new decl.
165 serialization::DeclID NextDeclID;
167 /// \brief Map that provides the ID numbers of each declaration within
168 /// the output stream, as well as those deserialized from a chained PCH.
170 /// The ID numbers of declarations are consecutive (in order of
171 /// discovery) and start at 2. 1 is reserved for the translation
172 /// unit, while 0 is reserved for NULL.
173 llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs;
175 /// \brief Offset of each declaration in the bitstream, indexed by
176 /// the declaration's ID.
177 std::vector<serialization::DeclOffset> DeclOffsets;
179 /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
180 typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
182 struct DeclIDInFileInfo {
183 LocDeclIDsTy DeclIDs;
184 /// \brief Set when the DeclIDs vectors from all files are joined, this
185 /// indicates the index that this particular vector has in the global one.
186 unsigned FirstDeclIndex;
188 typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
190 /// \brief Map from file SLocEntries to info about the file-level declarations
191 /// that it contains.
192 FileDeclIDsTy FileDeclIDs;
194 void associateDeclWithFile(const Decl *D, serialization::DeclID);
196 /// \brief The first ID number we can use for our own types.
197 serialization::TypeID FirstTypeID;
199 /// \brief The type ID that will be assigned to the next new type.
200 serialization::TypeID NextTypeID;
202 /// \brief Map that provides the ID numbers of each type within the
203 /// output stream, plus those deserialized from a chained PCH.
205 /// The ID numbers of types are consecutive (in order of discovery)
206 /// and start at 1. 0 is reserved for NULL. When types are actually
207 /// stored in the stream, the ID number is shifted by 2 bits to
208 /// allow for the const/volatile qualifiers.
210 /// Keys in the map never have const/volatile qualifiers.
213 /// \brief Offset of each type in the bitstream, indexed by
215 std::vector<uint32_t> TypeOffsets;
217 /// \brief The first ID number we can use for our own identifiers.
218 serialization::IdentID FirstIdentID;
220 /// \brief The identifier ID that will be assigned to the next new identifier.
221 serialization::IdentID NextIdentID;
223 /// \brief Map that provides the ID numbers of each identifier in
224 /// the output stream.
226 /// The ID numbers for identifiers are consecutive (in order of
227 /// discovery), starting at 1. An ID of zero refers to a NULL
229 llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
231 /// \brief The first ID number we can use for our own macros.
232 serialization::MacroID FirstMacroID;
234 /// \brief The identifier ID that will be assigned to the next new identifier.
235 serialization::MacroID NextMacroID;
237 /// \brief Map that provides the ID numbers of each macro.
238 llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
240 struct MacroInfoToEmitData {
241 const IdentifierInfo *Name;
243 serialization::MacroID ID;
245 /// \brief The macro infos to emit.
246 std::vector<MacroInfoToEmitData> MacroInfosToEmit;
248 llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
250 /// @name FlushStmt Caches
253 /// \brief Set of parent Stmts for the currently serializing sub-stmt.
254 llvm::DenseSet<Stmt *> ParentStmts;
256 /// \brief Offsets of sub-stmts already serialized. The offset points
257 /// just after the stmt record.
258 llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
262 /// \brief Offsets of each of the identifier IDs into the identifier
264 std::vector<uint32_t> IdentifierOffsets;
266 /// \brief The first ID number we can use for our own submodules.
267 serialization::SubmoduleID FirstSubmoduleID;
269 /// \brief The submodule ID that will be assigned to the next new submodule.
270 serialization::SubmoduleID NextSubmoduleID;
272 /// \brief The first ID number we can use for our own selectors.
273 serialization::SelectorID FirstSelectorID;
275 /// \brief The selector ID that will be assigned to the next new selector.
276 serialization::SelectorID NextSelectorID;
278 /// \brief Map that provides the ID numbers of each Selector.
279 llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
281 /// \brief Offset of each selector within the method pool/selector
282 /// table, indexed by the Selector ID (-1).
283 std::vector<uint32_t> SelectorOffsets;
285 /// \brief Mapping from macro definitions (as they occur in the preprocessing
286 /// record) to the macro IDs.
287 llvm::DenseMap<const MacroDefinitionRecord *,
288 serialization::PreprocessedEntityID> MacroDefinitions;
290 /// \brief Cache of indices of anonymous declarations within their lexical
292 llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
294 /// An update to a Decl.
296 /// A DeclUpdateKind.
307 DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {}
308 DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {}
309 DeclUpdate(unsigned Kind, QualType Type)
310 : Kind(Kind), Type(Type.getAsOpaquePtr()) {}
311 DeclUpdate(unsigned Kind, SourceLocation Loc)
312 : Kind(Kind), Loc(Loc.getRawEncoding()) {}
313 DeclUpdate(unsigned Kind, unsigned Val)
314 : Kind(Kind), Val(Val) {}
315 DeclUpdate(unsigned Kind, Module *M)
316 : Kind(Kind), Mod(M) {}
318 unsigned getKind() const { return Kind; }
319 const Decl *getDecl() const { return Dcl; }
320 QualType getType() const { return QualType::getFromOpaquePtr(Type); }
321 SourceLocation getLoc() const {
322 return SourceLocation::getFromRawEncoding(Loc);
324 unsigned getNumber() const { return Val; }
325 Module *getModule() const { return Mod; }
328 typedef SmallVector<DeclUpdate, 1> UpdateRecord;
329 typedef llvm::MapVector<const Decl *, UpdateRecord> DeclUpdateMap;
330 /// \brief Mapping from declarations that came from a chained PCH to the
331 /// record containing modifications to them.
332 DeclUpdateMap DeclUpdates;
334 typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap;
335 /// \brief Map of first declarations from a chained PCH that point to the
336 /// most recent declarations in another PCH.
337 FirstLatestDeclMap FirstLatestDecls;
339 /// \brief Declarations encountered that might be external
342 /// We keep track of external definitions and other 'interesting' declarations
343 /// as we are emitting declarations to the AST file. The AST file contains a
344 /// separate record for these declarations, which are provided to the AST
345 /// consumer by the AST reader. This is behavior is required to properly cope with,
346 /// e.g., tentative variable definitions that occur within
347 /// headers. The declarations themselves are stored as declaration
348 /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS
350 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
352 /// \brief DeclContexts that have received extensions since their serialized
355 /// For namespaces, when we're chaining and encountering a namespace, we check
356 /// if its primary namespace comes from the chain. If it does, we add the
357 /// primary to this set, so that we can write out lexical content updates for
359 llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
361 /// \brief Keeps track of visible decls that were added in DeclContexts
362 /// coming from another AST file.
363 SmallVector<const Decl *, 16> UpdatingVisibleDecls;
365 typedef llvm::SmallSetVector<const Decl *, 16> DeclsToRewriteTy;
366 /// \brief Decls that will be replaced in the current dependent AST file.
367 DeclsToRewriteTy DeclsToRewrite;
369 /// \brief The set of Objective-C class that have categories we
370 /// should serialize.
371 llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
373 struct ReplacedDeclInfo {
374 serialization::DeclID ID;
378 ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {}
379 ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset,
381 : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {}
384 /// \brief Decls that have been replaced in the current dependent AST file.
386 /// When a decl changes fundamentally after being deserialized (this shouldn't
387 /// happen, but the ObjC AST nodes are designed this way), it will be
388 /// serialized again. In this case, it is registered here, so that the reader
389 /// knows to read the updated version.
390 SmallVector<ReplacedDeclInfo, 16> ReplacedDecls;
392 /// \brief The set of declarations that may have redeclaration chains that
393 /// need to be serialized.
394 llvm::SmallSetVector<Decl *, 4> Redeclarations;
396 /// \brief Statements that we've encountered while serializing a
397 /// declaration or type.
398 SmallVector<Stmt *, 16> StmtsToEmit;
400 /// \brief Statements collection to use for ASTWriter::AddStmt().
401 /// It will point to StmtsToEmit unless it is overriden.
402 SmallVector<Stmt *, 16> *CollectedStmts;
404 /// \brief Mapping from SwitchCase statements to IDs.
405 llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
407 /// \brief The number of statements written to the AST file.
408 unsigned NumStatements;
410 /// \brief The number of macros written to the AST file.
413 /// \brief The number of lexical declcontexts written to the AST
415 unsigned NumLexicalDeclContexts;
417 /// \brief The number of visible declcontexts written to the AST
419 unsigned NumVisibleDeclContexts;
421 /// \brief The offset of each CXXBaseSpecifier set within the AST.
422 SmallVector<uint32_t, 16> CXXBaseSpecifiersOffsets;
424 /// \brief The first ID number we can use for our own base specifiers.
425 serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID;
427 /// \brief The base specifiers ID that will be assigned to the next new
428 /// set of C++ base specifiers.
429 serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID;
431 /// \brief A set of C++ base specifiers that is queued to be written into the
433 struct QueuedCXXBaseSpecifiers {
434 QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { }
436 QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID,
437 CXXBaseSpecifier const *Bases,
438 CXXBaseSpecifier const *BasesEnd)
439 : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { }
441 serialization::CXXBaseSpecifiersID ID;
442 CXXBaseSpecifier const * Bases;
443 CXXBaseSpecifier const * BasesEnd;
446 /// \brief Queue of C++ base specifiers to be written to the AST file,
447 /// in the order they should be written.
448 SmallVector<QueuedCXXBaseSpecifiers, 2> CXXBaseSpecifiersToWrite;
450 /// \brief The offset of each CXXCtorInitializer list within the AST.
451 SmallVector<uint32_t, 16> CXXCtorInitializersOffsets;
453 /// \brief The first ID number we can use for our own ctor initializers.
454 serialization::CXXCtorInitializersID FirstCXXCtorInitializersID;
456 /// \brief The ctor initializers ID that will be assigned to the next new
457 /// list of C++ ctor initializers.
458 serialization::CXXCtorInitializersID NextCXXCtorInitializersID;
460 /// \brief A set of C++ ctor initializers that is queued to be written
461 /// into the AST file.
462 struct QueuedCXXCtorInitializers {
463 QueuedCXXCtorInitializers() : ID() {}
465 QueuedCXXCtorInitializers(serialization::CXXCtorInitializersID ID,
466 ArrayRef<CXXCtorInitializer*> Inits)
467 : ID(ID), Inits(Inits) {}
469 serialization::CXXCtorInitializersID ID;
470 ArrayRef<CXXCtorInitializer*> Inits;
473 /// \brief Queue of C++ ctor initializers to be written to the AST file,
474 /// in the order they should be written.
475 SmallVector<QueuedCXXCtorInitializers, 2> CXXCtorInitializersToWrite;
477 /// \brief A mapping from each known submodule to its ID number, which will
478 /// be a positive integer.
479 llvm::DenseMap<Module *, unsigned> SubmoduleIDs;
481 /// \brief Retrieve or create a submodule ID for this module.
482 unsigned getSubmoduleID(Module *Mod);
484 /// \brief Write the given subexpression to the bitstream.
485 void WriteSubStmt(Stmt *S,
486 llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntries,
487 llvm::DenseSet<Stmt *> &ParentStmts);
489 void WriteBlockInfoBlock();
490 void WriteControlBlock(Preprocessor &PP, ASTContext &Context,
491 StringRef isysroot, const std::string &OutputFile);
492 void WriteInputFiles(SourceManager &SourceMgr,
493 HeaderSearchOptions &HSOpts,
495 void WriteSourceManagerBlock(SourceManager &SourceMgr,
496 const Preprocessor &PP);
497 void WritePreprocessor(const Preprocessor &PP, bool IsModule);
498 void WriteHeaderSearch(const HeaderSearch &HS);
499 void WritePreprocessorDetail(PreprocessingRecord &PPRec);
500 void WriteSubmodules(Module *WritingModule);
502 void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
504 void WriteCXXBaseSpecifiersOffsets();
505 void WriteCXXCtorInitializersOffsets();
507 unsigned TypeExtQualAbbrev;
508 unsigned TypeFunctionProtoAbbrev;
509 void WriteTypeAbbrevs();
510 void WriteType(QualType T);
512 bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
513 bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
515 uint32_t GenerateNameLookupTable(const DeclContext *DC,
516 llvm::SmallVectorImpl<char> &LookupTable);
517 uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
518 uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
519 void WriteTypeDeclOffsets();
520 void WriteFileDeclIDsMap();
521 void WriteComments();
522 void WriteSelectors(Sema &SemaRef);
523 void WriteReferencedSelectorsPool(Sema &SemaRef);
524 void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver,
526 void WriteAttributes(ArrayRef<const Attr*> Attrs, RecordDataImpl &Record);
527 void WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord);
528 void WriteDeclReplacementsBlock();
529 void WriteDeclContextVisibleUpdate(const DeclContext *DC);
530 void WriteFPPragmaOptions(const FPOptions &Opts);
531 void WriteOpenCLExtensions(Sema &SemaRef);
532 void WriteObjCCategories();
533 void WriteRedeclarations();
534 void WriteLateParsedTemplates(Sema &SemaRef);
535 void WriteOptimizePragmaOptions(Sema &SemaRef);
537 unsigned DeclParmVarAbbrev;
538 unsigned DeclContextLexicalAbbrev;
539 unsigned DeclContextVisibleLookupAbbrev;
540 unsigned UpdateVisibleAbbrev;
541 unsigned DeclRecordAbbrev;
542 unsigned DeclTypedefAbbrev;
543 unsigned DeclVarAbbrev;
544 unsigned DeclFieldAbbrev;
545 unsigned DeclEnumAbbrev;
546 unsigned DeclObjCIvarAbbrev;
547 unsigned DeclCXXMethodAbbrev;
549 unsigned DeclRefExprAbbrev;
550 unsigned CharacterLiteralAbbrev;
551 unsigned IntegerLiteralAbbrev;
552 unsigned ExprImplicitCastAbbrev;
554 void WriteDeclAbbrevs();
555 void WriteDecl(ASTContext &Context, Decl *D);
556 void AddFunctionDefinition(const FunctionDecl *FD, RecordData &Record);
558 void WriteASTCore(Sema &SemaRef,
559 StringRef isysroot, const std::string &OutputFile,
560 Module *WritingModule);
563 /// \brief Create a new precompiled header writer that outputs to
564 /// the given bitstream.
565 ASTWriter(llvm::BitstreamWriter &Stream);
566 ~ASTWriter() override;
568 const LangOptions &getLangOpts() const;
570 /// \brief Write a precompiled header for the given semantic analysis.
572 /// \param SemaRef a reference to the semantic analysis object that processed
573 /// the AST to be written into the precompiled header.
575 /// \param WritingModule The module that we are writing. If null, we are
576 /// writing a precompiled header.
578 /// \param isysroot if non-empty, write a relocatable file whose headers
579 /// are relative to the given system root. If we're writing a module, its
580 /// build directory will be used in preference to this if both are available.
581 void WriteAST(Sema &SemaRef,
582 const std::string &OutputFile,
583 Module *WritingModule, StringRef isysroot,
584 bool hasErrors = false);
586 /// \brief Emit a token.
587 void AddToken(const Token &Tok, RecordDataImpl &Record);
589 /// \brief Emit a source location.
590 void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
592 /// \brief Emit a source range.
593 void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
595 /// \brief Emit an integral value.
596 void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record);
598 /// \brief Emit a signed integral value.
599 void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record);
601 /// \brief Emit a floating-point value.
602 void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record);
604 /// \brief Emit a reference to an identifier.
605 void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
607 /// \brief Emit a Selector (which is a smart pointer reference).
608 void AddSelectorRef(Selector, RecordDataImpl &Record);
610 /// \brief Emit a CXXTemporary.
611 void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record);
613 /// \brief Emit a set of C++ base specifiers to the record.
614 void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
615 CXXBaseSpecifier const *BasesEnd,
616 RecordDataImpl &Record);
618 /// \brief Get the unique number used to refer to the given selector.
619 serialization::SelectorID getSelectorRef(Selector Sel);
621 /// \brief Get the unique number used to refer to the given identifier.
622 serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
624 /// \brief Get the unique number used to refer to the given macro.
625 serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
627 /// \brief Determine the ID of an already-emitted macro.
628 serialization::MacroID getMacroID(MacroInfo *MI);
630 uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
632 /// \brief Emit a reference to a type.
633 void AddTypeRef(QualType T, RecordDataImpl &Record);
635 /// \brief Force a type to be emitted and get its ID.
636 serialization::TypeID GetOrCreateTypeID(QualType T);
638 /// \brief Determine the type ID of an already-emitted type.
639 serialization::TypeID getTypeID(QualType T) const;
641 /// \brief Emits a reference to a declarator info.
642 void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record);
644 /// \brief Emits a type with source-location information.
645 void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record);
647 /// \brief Emits a template argument location info.
648 void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
649 const TemplateArgumentLocInfo &Arg,
650 RecordDataImpl &Record);
652 /// \brief Emits a template argument location.
653 void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
654 RecordDataImpl &Record);
656 /// \brief Emits an AST template argument list info.
657 void AddASTTemplateArgumentListInfo(
658 const ASTTemplateArgumentListInfo *ASTTemplArgList,
659 RecordDataImpl &Record);
661 /// \brief Emit a reference to a declaration.
662 void AddDeclRef(const Decl *D, RecordDataImpl &Record);
665 /// \brief Force a declaration to be emitted and get its ID.
666 serialization::DeclID GetDeclRef(const Decl *D);
668 /// \brief Determine the declaration ID of an already-emitted
670 serialization::DeclID getDeclID(const Decl *D);
672 /// \brief Emit a declaration name.
673 void AddDeclarationName(DeclarationName Name, RecordDataImpl &Record);
674 void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
675 DeclarationName Name, RecordDataImpl &Record);
676 void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
677 RecordDataImpl &Record);
678 unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
680 void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record);
682 /// \brief Emit a nested name specifier.
683 void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record);
685 /// \brief Emit a nested name specifier with source-location information.
686 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
687 RecordDataImpl &Record);
689 /// \brief Emit a template name.
690 void AddTemplateName(TemplateName Name, RecordDataImpl &Record);
692 /// \brief Emit a template argument.
693 void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record);
695 /// \brief Emit a template parameter list.
696 void AddTemplateParameterList(const TemplateParameterList *TemplateParams,
697 RecordDataImpl &Record);
699 /// \brief Emit a template argument list.
700 void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
701 RecordDataImpl &Record);
703 /// \brief Emit a UnresolvedSet structure.
704 void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record);
706 /// \brief Emit a C++ base specifier.
707 void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
708 RecordDataImpl &Record);
710 /// \brief Emit the ID for a CXXCtorInitializer array and register the array
711 /// for later serialization.
712 void AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
713 RecordDataImpl &Record);
715 /// \brief Emit a CXXCtorInitializer array.
716 void AddCXXCtorInitializers(
717 const CXXCtorInitializer * const *CtorInitializers,
718 unsigned NumCtorInitializers,
719 RecordDataImpl &Record);
721 void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record);
723 /// \brief Add a string to the given record.
724 void AddString(StringRef Str, RecordDataImpl &Record);
726 /// \brief Convert a path from this build process into one that is appropriate
727 /// for emission in the module file.
728 bool PreparePathForOutput(SmallVectorImpl<char> &Path);
730 /// \brief Add a path to the given record.
731 void AddPath(StringRef Path, RecordDataImpl &Record);
733 /// \brief Emit the current record with the given path as a blob.
734 void EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
737 /// \brief Add a version tuple to the given record
738 void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
740 void RewriteDecl(const Decl *D) {
741 DeclsToRewrite.insert(D);
744 bool isRewritten(const Decl *D) const {
745 return DeclsToRewrite.count(D);
748 /// \brief Infer the submodule ID that contains an entity at the given
750 serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
752 /// \brief Retrieve a submodule ID for this module.
753 /// Returns 0 If no ID has been associated with the module.
754 unsigned getExistingSubmoduleID(Module *Mod) const;
756 /// \brief Note that the identifier II occurs at the given offset
757 /// within the identifier table.
758 void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
760 /// \brief Note that the selector Sel occurs at the given offset
761 /// within the method pool/selector table.
762 void SetSelectorOffset(Selector Sel, uint32_t Offset);
764 /// \brief Add the given statement or expression to the queue of
765 /// statements to emit.
767 /// This routine should be used when emitting types and declarations
768 /// that have expressions as part of their formulation. Once the
769 /// type or declaration has been written, call FlushStmts() to write
770 /// the corresponding statements just after the type or
772 void AddStmt(Stmt *S) {
773 CollectedStmts->push_back(S);
776 /// \brief Flush all of the statements and expressions that have
777 /// been added to the queue via AddStmt().
780 /// \brief Flush all of the C++ base specifier sets that have been added
781 /// via \c AddCXXBaseSpecifiersRef().
782 void FlushCXXBaseSpecifiers();
784 /// \brief Flush all of the C++ constructor initializer lists that have been
785 /// added via \c AddCXXCtorInitializersRef().
786 void FlushCXXCtorInitializers();
788 /// \brief Flush all pending records that are tacked onto the end of
789 /// decl and decl update records.
790 void FlushPendingAfterDecl() {
792 FlushCXXBaseSpecifiers();
793 FlushCXXCtorInitializers();
796 /// \brief Record an ID for the given switch-case statement.
797 unsigned RecordSwitchCaseID(SwitchCase *S);
799 /// \brief Retrieve the ID for the given switch-case statement.
800 unsigned getSwitchCaseID(SwitchCase *S);
802 void ClearSwitchCaseIDs();
804 unsigned getTypeExtQualAbbrev() const {
805 return TypeExtQualAbbrev;
807 unsigned getTypeFunctionProtoAbbrev() const {
808 return TypeFunctionProtoAbbrev;
811 unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
812 unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
813 unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
814 unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
815 unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
816 unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
817 unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
818 unsigned getDeclCXXMethodAbbrev() const { return DeclCXXMethodAbbrev; }
820 unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
821 unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
822 unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
823 unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
825 bool hasChain() const { return Chain; }
827 // ASTDeserializationListener implementation
828 void ReaderInitialized(ASTReader *Reader) override;
829 void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override;
830 void MacroRead(serialization::MacroID ID, MacroInfo *MI) override;
831 void TypeRead(serialization::TypeIdx Idx, QualType T) override;
832 void SelectorRead(serialization::SelectorID ID, Selector Sel) override;
833 void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
834 MacroDefinitionRecord *MD) override;
835 void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
837 // ASTMutationListener implementation.
838 void CompletedTagDefinition(const TagDecl *D) override;
839 void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
840 void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
841 void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
842 const ClassTemplateSpecializationDecl *D) override;
843 void AddedCXXTemplateSpecialization(const VarTemplateDecl *TD,
844 const VarTemplateSpecializationDecl *D) override;
845 void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
846 const FunctionDecl *D) override;
847 void ResolvedExceptionSpec(const FunctionDecl *FD) override;
848 void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override;
849 void ResolvedOperatorDelete(const CXXDestructorDecl *DD,
850 const FunctionDecl *Delete) override;
851 void CompletedImplicitDefinition(const FunctionDecl *D) override;
852 void StaticDataMemberInstantiated(const VarDecl *D) override;
853 void FunctionDefinitionInstantiated(const FunctionDecl *D) override;
854 void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
855 const ObjCInterfaceDecl *IFD) override;
856 void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
857 const ObjCPropertyDecl *OrigProp,
858 const ObjCCategoryDecl *ClassExt) override;
859 void DeclarationMarkedUsed(const Decl *D) override;
860 void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override;
861 void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override;
864 /// \brief AST and semantic-analysis consumer that generates a
865 /// precompiled header from the parsed source code.
866 class PCHGenerator : public SemaConsumer {
867 const Preprocessor &PP;
868 std::string OutputFile;
869 clang::Module *Module;
870 std::string isysroot;
873 SmallVector<char, 128> Buffer;
874 llvm::BitstreamWriter Stream;
876 bool AllowASTWithErrors;
880 ASTWriter &getWriter() { return Writer; }
881 const ASTWriter &getWriter() const { return Writer; }
884 PCHGenerator(const Preprocessor &PP, StringRef OutputFile,
885 clang::Module *Module,
886 StringRef isysroot, raw_ostream *Out,
887 bool AllowASTWithErrors = false);
888 ~PCHGenerator() override;
889 void InitializeSema(Sema &S) override { SemaPtr = &S; }
890 void HandleTranslationUnit(ASTContext &Ctx) override;
891 ASTMutationListener *GetASTMutationListener() override;
892 ASTDeserializationListener *GetASTDeserializationListener() override;
894 bool hasEmittedPCH() const { return HasEmittedPCH; }
897 } // end namespace clang