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/TemplateBase.h"
20 #include "clang/Frontend/PCHContainerOperations.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/SmallVector.h"
29 #include "llvm/Bitcode/BitstreamWriter.h"
40 class DeclarationName;
43 class NestedNameSpecifier;
44 class CXXBaseSpecifier;
45 class CXXCtorInitializer;
49 class HeaderSearchOptions;
50 class IdentifierResolver;
51 class MacroDefinitionRecord;
54 class OpaqueValueExpr;
58 class ModuleFileExtension;
59 class ModuleFileExtensionWriter;
60 class PreprocessedEntity;
61 class PreprocessingRecord;
66 struct StoredDeclsList;
71 class ASTUnresolvedSet;
73 namespace SrcMgr { class SLocEntry; }
75 /// \brief Writes an AST file containing the contents of a translation unit.
77 /// The ASTWriter class produces a bitstream containing the serialized
78 /// representation of a given abstract syntax tree and its supporting
79 /// data structures. This bitstream can be de-serialized via an
80 /// instance of the ASTReader class.
81 class ASTWriter : public ASTDeserializationListener,
82 public ASTMutationListener {
84 typedef SmallVector<uint64_t, 64> RecordData;
85 typedef SmallVectorImpl<uint64_t> RecordDataImpl;
86 typedef ArrayRef<uint64_t> RecordDataRef;
88 friend class ASTDeclWriter;
89 friend class ASTStmtWriter;
90 friend class ASTTypeWriter;
91 friend class ASTRecordWriter;
93 /// \brief Map that provides the ID numbers of each type within the
94 /// output stream, plus those deserialized from a chained PCH.
96 /// The ID numbers of types are consecutive (in order of discovery)
97 /// and start at 1. 0 is reserved for NULL. When types are actually
98 /// stored in the stream, the ID number is shifted by 2 bits to
99 /// allow for the const/volatile qualifiers.
101 /// Keys in the map never have const/volatile qualifiers.
102 typedef llvm::DenseMap<QualType, serialization::TypeIdx,
103 serialization::UnsafeQualTypeDenseMapInfo>
106 /// \brief The bitstream writer used to emit this precompiled header.
107 llvm::BitstreamWriter &Stream;
109 /// \brief The ASTContext we're writing.
110 ASTContext *Context = nullptr;
112 /// \brief The preprocessor we're writing.
113 Preprocessor *PP = nullptr;
115 /// \brief The reader of existing AST files, if we're chaining.
116 ASTReader *Chain = nullptr;
118 /// \brief The module we're currently writing, if any.
119 Module *WritingModule = nullptr;
121 /// \brief The base directory for any relative paths we emit.
122 std::string BaseDirectory;
124 /// \brief Indicates whether timestamps should be written to the produced
125 /// module file. This is the case for files implicitly written to the
126 /// module cache, where we need the timestamps to determine if the module
127 /// file is up to date, but not otherwise.
128 bool IncludeTimestamps;
130 /// \brief Indicates when the AST writing is actively performing
131 /// serialization, rather than just queueing updates.
132 bool WritingAST = false;
134 /// \brief Indicates that we are done serializing the collection of decls
135 /// and types to emit.
136 bool DoneWritingDeclsAndTypes = false;
138 /// \brief Indicates that the AST contained compiler errors.
139 bool ASTHasCompilerErrors = false;
141 /// \brief Mapping from input file entries to the index into the
142 /// offset table where information about that input file is stored.
143 llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs;
145 /// \brief Stores a declaration or a type to be written to the AST file.
148 DeclOrType(Decl *D) : Stored(D), IsType(false) { }
149 DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
151 bool isType() const { return IsType; }
152 bool isDecl() const { return !IsType; }
154 QualType getType() const {
155 assert(isType() && "Not a type!");
156 return QualType::getFromOpaquePtr(Stored);
159 Decl *getDecl() const {
160 assert(isDecl() && "Not a decl!");
161 return static_cast<Decl *>(Stored);
169 /// \brief The declarations and types to emit.
170 std::queue<DeclOrType> DeclTypesToEmit;
172 /// \brief The first ID number we can use for our own declarations.
173 serialization::DeclID FirstDeclID = serialization::NUM_PREDEF_DECL_IDS;
175 /// \brief The decl ID that will be assigned to the next new decl.
176 serialization::DeclID NextDeclID = FirstDeclID;
178 /// \brief Map that provides the ID numbers of each declaration within
179 /// the output stream, as well as those deserialized from a chained PCH.
181 /// The ID numbers of declarations are consecutive (in order of
182 /// discovery) and start at 2. 1 is reserved for the translation
183 /// unit, while 0 is reserved for NULL.
184 llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs;
186 /// \brief Offset of each declaration in the bitstream, indexed by
187 /// the declaration's ID.
188 std::vector<serialization::DeclOffset> DeclOffsets;
190 /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
191 typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
193 struct DeclIDInFileInfo {
194 LocDeclIDsTy DeclIDs;
195 /// \brief Set when the DeclIDs vectors from all files are joined, this
196 /// indicates the index that this particular vector has in the global one.
197 unsigned FirstDeclIndex;
199 typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
201 /// \brief Map from file SLocEntries to info about the file-level declarations
202 /// that it contains.
203 FileDeclIDsTy FileDeclIDs;
205 void associateDeclWithFile(const Decl *D, serialization::DeclID);
207 /// \brief The first ID number we can use for our own types.
208 serialization::TypeID FirstTypeID = serialization::NUM_PREDEF_TYPE_IDS;
210 /// \brief The type ID that will be assigned to the next new type.
211 serialization::TypeID NextTypeID = FirstTypeID;
213 /// \brief Map that provides the ID numbers of each type within the
214 /// output stream, plus those deserialized from a chained PCH.
216 /// The ID numbers of types are consecutive (in order of discovery)
217 /// and start at 1. 0 is reserved for NULL. When types are actually
218 /// stored in the stream, the ID number is shifted by 2 bits to
219 /// allow for the const/volatile qualifiers.
221 /// Keys in the map never have const/volatile qualifiers.
224 /// \brief Offset of each type in the bitstream, indexed by
226 std::vector<uint32_t> TypeOffsets;
228 /// \brief The first ID number we can use for our own identifiers.
229 serialization::IdentID FirstIdentID = serialization::NUM_PREDEF_IDENT_IDS;
231 /// \brief The identifier ID that will be assigned to the next new identifier.
232 serialization::IdentID NextIdentID = FirstIdentID;
234 /// \brief Map that provides the ID numbers of each identifier in
235 /// the output stream.
237 /// The ID numbers for identifiers are consecutive (in order of
238 /// discovery), starting at 1. An ID of zero refers to a NULL
240 llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
242 /// \brief The first ID number we can use for our own macros.
243 serialization::MacroID FirstMacroID = serialization::NUM_PREDEF_MACRO_IDS;
245 /// \brief The identifier ID that will be assigned to the next new identifier.
246 serialization::MacroID NextMacroID = FirstMacroID;
248 /// \brief Map that provides the ID numbers of each macro.
249 llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
251 struct MacroInfoToEmitData {
252 const IdentifierInfo *Name;
254 serialization::MacroID ID;
256 /// \brief The macro infos to emit.
257 std::vector<MacroInfoToEmitData> MacroInfosToEmit;
259 llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
261 /// @name FlushStmt Caches
264 /// \brief Set of parent Stmts for the currently serializing sub-stmt.
265 llvm::DenseSet<Stmt *> ParentStmts;
267 /// \brief Offsets of sub-stmts already serialized. The offset points
268 /// just after the stmt record.
269 llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
273 /// \brief Offsets of each of the identifier IDs into the identifier
275 std::vector<uint32_t> IdentifierOffsets;
277 /// \brief The first ID number we can use for our own submodules.
278 serialization::SubmoduleID FirstSubmoduleID =
279 serialization::NUM_PREDEF_SUBMODULE_IDS;
281 /// \brief The submodule ID that will be assigned to the next new submodule.
282 serialization::SubmoduleID NextSubmoduleID = FirstSubmoduleID;
284 /// \brief The first ID number we can use for our own selectors.
285 serialization::SelectorID FirstSelectorID =
286 serialization::NUM_PREDEF_SELECTOR_IDS;
288 /// \brief The selector ID that will be assigned to the next new selector.
289 serialization::SelectorID NextSelectorID = FirstSelectorID;
291 /// \brief Map that provides the ID numbers of each Selector.
292 llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
294 /// \brief Offset of each selector within the method pool/selector
295 /// table, indexed by the Selector ID (-1).
296 std::vector<uint32_t> SelectorOffsets;
298 /// \brief Mapping from macro definitions (as they occur in the preprocessing
299 /// record) to the macro IDs.
300 llvm::DenseMap<const MacroDefinitionRecord *,
301 serialization::PreprocessedEntityID> MacroDefinitions;
303 /// \brief Cache of indices of anonymous declarations within their lexical
305 llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
307 /// An update to a Decl.
309 /// A DeclUpdateKind.
317 const Attr *Attribute;
321 DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {}
322 DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {}
323 DeclUpdate(unsigned Kind, QualType Type)
324 : Kind(Kind), Type(Type.getAsOpaquePtr()) {}
325 DeclUpdate(unsigned Kind, SourceLocation Loc)
326 : Kind(Kind), Loc(Loc.getRawEncoding()) {}
327 DeclUpdate(unsigned Kind, unsigned Val)
328 : Kind(Kind), Val(Val) {}
329 DeclUpdate(unsigned Kind, Module *M)
330 : Kind(Kind), Mod(M) {}
331 DeclUpdate(unsigned Kind, const Attr *Attribute)
332 : Kind(Kind), Attribute(Attribute) {}
334 unsigned getKind() const { return Kind; }
335 const Decl *getDecl() const { return Dcl; }
336 QualType getType() const { return QualType::getFromOpaquePtr(Type); }
337 SourceLocation getLoc() const {
338 return SourceLocation::getFromRawEncoding(Loc);
340 unsigned getNumber() const { return Val; }
341 Module *getModule() const { return Mod; }
342 const Attr *getAttr() const { return Attribute; }
345 typedef SmallVector<DeclUpdate, 1> UpdateRecord;
346 typedef llvm::MapVector<const Decl *, UpdateRecord> DeclUpdateMap;
347 /// \brief Mapping from declarations that came from a chained PCH to the
348 /// record containing modifications to them.
349 DeclUpdateMap DeclUpdates;
351 typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap;
352 /// \brief Map of first declarations from a chained PCH that point to the
353 /// most recent declarations in another PCH.
354 FirstLatestDeclMap FirstLatestDecls;
356 /// \brief Declarations encountered that might be external
359 /// We keep track of external definitions and other 'interesting' declarations
360 /// as we are emitting declarations to the AST file. The AST file contains a
361 /// separate record for these declarations, which are provided to the AST
362 /// consumer by the AST reader. This is behavior is required to properly cope with,
363 /// e.g., tentative variable definitions that occur within
364 /// headers. The declarations themselves are stored as declaration
365 /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS
367 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
369 /// \brief DeclContexts that have received extensions since their serialized
372 /// For namespaces, when we're chaining and encountering a namespace, we check
373 /// if its primary namespace comes from the chain. If it does, we add the
374 /// primary to this set, so that we can write out lexical content updates for
376 llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
378 /// \brief Keeps track of declarations that we must emit, even though we're
379 /// not guaranteed to be able to find them by walking the AST starting at the
380 /// translation unit.
381 SmallVector<const Decl *, 16> DeclsToEmitEvenIfUnreferenced;
383 /// \brief The set of Objective-C class that have categories we
384 /// should serialize.
385 llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
387 /// \brief The set of declarations that may have redeclaration chains that
388 /// need to be serialized.
389 llvm::SmallVector<const Decl *, 16> Redeclarations;
391 /// \brief A cache of the first local declaration for "interesting"
392 /// redeclaration chains.
393 llvm::DenseMap<const Decl *, const Decl *> FirstLocalDeclCache;
395 /// \brief Mapping from SwitchCase statements to IDs.
396 llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
398 /// \brief The number of statements written to the AST file.
399 unsigned NumStatements = 0;
401 /// \brief The number of macros written to the AST file.
402 unsigned NumMacros = 0;
404 /// \brief The number of lexical declcontexts written to the AST
406 unsigned NumLexicalDeclContexts = 0;
408 /// \brief The number of visible declcontexts written to the AST
410 unsigned NumVisibleDeclContexts = 0;
412 /// \brief A mapping from each known submodule to its ID number, which will
413 /// be a positive integer.
414 llvm::DenseMap<Module *, unsigned> SubmoduleIDs;
416 /// \brief A list of the module file extension writers.
417 std::vector<std::unique_ptr<ModuleFileExtensionWriter>>
418 ModuleFileExtensionWriters;
420 /// \brief Retrieve or create a submodule ID for this module.
421 unsigned getSubmoduleID(Module *Mod);
423 /// \brief Write the given subexpression to the bitstream.
424 void WriteSubStmt(Stmt *S);
426 void WriteBlockInfoBlock();
427 uint64_t WriteControlBlock(Preprocessor &PP, ASTContext &Context,
428 StringRef isysroot, const std::string &OutputFile);
429 void WriteInputFiles(SourceManager &SourceMgr, HeaderSearchOptions &HSOpts,
431 void WriteSourceManagerBlock(SourceManager &SourceMgr,
432 const Preprocessor &PP);
433 void WritePreprocessor(const Preprocessor &PP, bool IsModule);
434 void WriteHeaderSearch(const HeaderSearch &HS);
435 void WritePreprocessorDetail(PreprocessingRecord &PPRec);
436 void WriteSubmodules(Module *WritingModule);
438 void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
441 unsigned TypeExtQualAbbrev = 0;
442 unsigned TypeFunctionProtoAbbrev = 0;
443 void WriteTypeAbbrevs();
444 void WriteType(QualType T);
446 bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
447 bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
449 void GenerateNameLookupTable(const DeclContext *DC,
450 llvm::SmallVectorImpl<char> &LookupTable);
451 uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
452 uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
453 void WriteTypeDeclOffsets();
454 void WriteFileDeclIDsMap();
455 void WriteComments();
456 void WriteSelectors(Sema &SemaRef);
457 void WriteReferencedSelectorsPool(Sema &SemaRef);
458 void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver,
460 void WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord);
461 void WriteDeclContextVisibleUpdate(const DeclContext *DC);
462 void WriteFPPragmaOptions(const FPOptions &Opts);
463 void WriteOpenCLExtensions(Sema &SemaRef);
464 void WriteOpenCLExtensionTypes(Sema &SemaRef);
465 void WriteOpenCLExtensionDecls(Sema &SemaRef);
466 void WriteCUDAPragmas(Sema &SemaRef);
467 void WriteObjCCategories();
468 void WriteLateParsedTemplates(Sema &SemaRef);
469 void WriteOptimizePragmaOptions(Sema &SemaRef);
470 void WriteMSStructPragmaOptions(Sema &SemaRef);
471 void WriteMSPointersToMembersPragmaOptions(Sema &SemaRef);
472 void WriteModuleFileExtension(Sema &SemaRef,
473 ModuleFileExtensionWriter &Writer);
475 unsigned DeclParmVarAbbrev = 0;
476 unsigned DeclContextLexicalAbbrev = 0;
477 unsigned DeclContextVisibleLookupAbbrev = 0;
478 unsigned UpdateVisibleAbbrev = 0;
479 unsigned DeclRecordAbbrev = 0;
480 unsigned DeclTypedefAbbrev = 0;
481 unsigned DeclVarAbbrev = 0;
482 unsigned DeclFieldAbbrev = 0;
483 unsigned DeclEnumAbbrev = 0;
484 unsigned DeclObjCIvarAbbrev = 0;
485 unsigned DeclCXXMethodAbbrev = 0;
487 unsigned DeclRefExprAbbrev = 0;
488 unsigned CharacterLiteralAbbrev = 0;
489 unsigned IntegerLiteralAbbrev = 0;
490 unsigned ExprImplicitCastAbbrev = 0;
492 void WriteDeclAbbrevs();
493 void WriteDecl(ASTContext &Context, Decl *D);
495 uint64_t WriteASTCore(Sema &SemaRef,
496 StringRef isysroot, const std::string &OutputFile,
497 Module *WritingModule);
500 /// \brief Create a new precompiled header writer that outputs to
501 /// the given bitstream.
502 ASTWriter(llvm::BitstreamWriter &Stream,
503 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
504 bool IncludeTimestamps = true);
505 ~ASTWriter() override;
507 const LangOptions &getLangOpts() const;
509 /// \brief Get a timestamp for output into the AST file. The actual timestamp
510 /// of the specified file may be ignored if we have been instructed to not
511 /// include timestamps in the output file.
512 time_t getTimestampForOutput(const FileEntry *E) const;
514 /// \brief Write a precompiled header for the given semantic analysis.
516 /// \param SemaRef a reference to the semantic analysis object that processed
517 /// the AST to be written into the precompiled header.
519 /// \param WritingModule The module that we are writing. If null, we are
520 /// writing a precompiled header.
522 /// \param isysroot if non-empty, write a relocatable file whose headers
523 /// are relative to the given system root. If we're writing a module, its
524 /// build directory will be used in preference to this if both are available.
526 /// \return the module signature, which eventually will be a hash of
527 /// the module but currently is merely a random 32-bit number.
528 uint64_t WriteAST(Sema &SemaRef, const std::string &OutputFile,
529 Module *WritingModule, StringRef isysroot,
530 bool hasErrors = false);
532 /// \brief Emit a token.
533 void AddToken(const Token &Tok, RecordDataImpl &Record);
535 /// \brief Emit a source location.
536 void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
538 /// \brief Emit a source range.
539 void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
541 /// \brief Emit a reference to an identifier.
542 void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
544 /// \brief Get the unique number used to refer to the given selector.
545 serialization::SelectorID getSelectorRef(Selector Sel);
547 /// \brief Get the unique number used to refer to the given identifier.
548 serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
550 /// \brief Get the unique number used to refer to the given macro.
551 serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
553 /// \brief Determine the ID of an already-emitted macro.
554 serialization::MacroID getMacroID(MacroInfo *MI);
556 uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
558 /// \brief Emit a reference to a type.
559 void AddTypeRef(QualType T, RecordDataImpl &Record);
561 /// \brief Force a type to be emitted and get its ID.
562 serialization::TypeID GetOrCreateTypeID(QualType T);
564 /// \brief Determine the type ID of an already-emitted type.
565 serialization::TypeID getTypeID(QualType T) const;
567 /// \brief Find the first local declaration of a given local redeclarable
569 const Decl *getFirstLocalDecl(const Decl *D);
571 /// \brief Is this a local declaration (that is, one that will be written to
572 /// our AST file)? This is the case for declarations that are neither imported
573 /// from another AST file nor predefined.
574 bool IsLocalDecl(const Decl *D) {
575 if (D->isFromASTFile())
577 auto I = DeclIDs.find(D);
578 return (I == DeclIDs.end() ||
579 I->second >= serialization::NUM_PREDEF_DECL_IDS);
582 /// \brief Emit a reference to a declaration.
583 void AddDeclRef(const Decl *D, RecordDataImpl &Record);
586 /// \brief Force a declaration to be emitted and get its ID.
587 serialization::DeclID GetDeclRef(const Decl *D);
589 /// \brief Determine the declaration ID of an already-emitted
591 serialization::DeclID getDeclID(const Decl *D);
593 unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
595 /// \brief Add a string to the given record.
596 void AddString(StringRef Str, RecordDataImpl &Record);
598 /// \brief Convert a path from this build process into one that is appropriate
599 /// for emission in the module file.
600 bool PreparePathForOutput(SmallVectorImpl<char> &Path);
602 /// \brief Add a path to the given record.
603 void AddPath(StringRef Path, RecordDataImpl &Record);
605 /// \brief Emit the current record with the given path as a blob.
606 void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
609 /// \brief Add a version tuple to the given record
610 void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
612 /// \brief Infer the submodule ID that contains an entity at the given
614 serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
616 /// \brief Retrieve or create a submodule ID for this module, or return 0 if
617 /// the submodule is neither local (a submodle of the currently-written module)
618 /// nor from an imported module.
619 unsigned getLocalOrImportedSubmoduleID(Module *Mod);
621 /// \brief Note that the identifier II occurs at the given offset
622 /// within the identifier table.
623 void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
625 /// \brief Note that the selector Sel occurs at the given offset
626 /// within the method pool/selector table.
627 void SetSelectorOffset(Selector Sel, uint32_t Offset);
629 /// \brief Record an ID for the given switch-case statement.
630 unsigned RecordSwitchCaseID(SwitchCase *S);
632 /// \brief Retrieve the ID for the given switch-case statement.
633 unsigned getSwitchCaseID(SwitchCase *S);
635 void ClearSwitchCaseIDs();
637 unsigned getTypeExtQualAbbrev() const {
638 return TypeExtQualAbbrev;
640 unsigned getTypeFunctionProtoAbbrev() const {
641 return TypeFunctionProtoAbbrev;
644 unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
645 unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
646 unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
647 unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
648 unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
649 unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
650 unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
651 unsigned getDeclCXXMethodAbbrev() const { return DeclCXXMethodAbbrev; }
653 unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
654 unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
655 unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
656 unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
658 bool hasChain() const { return Chain; }
659 ASTReader *getChain() const { return Chain; }
662 // ASTDeserializationListener implementation
663 void ReaderInitialized(ASTReader *Reader) override;
664 void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override;
665 void MacroRead(serialization::MacroID ID, MacroInfo *MI) override;
666 void TypeRead(serialization::TypeIdx Idx, QualType T) override;
667 void SelectorRead(serialization::SelectorID ID, Selector Sel) override;
668 void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
669 MacroDefinitionRecord *MD) override;
670 void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
672 // ASTMutationListener implementation.
673 void CompletedTagDefinition(const TagDecl *D) override;
674 void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
675 void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
676 void AddedCXXTemplateSpecialization(
677 const ClassTemplateDecl *TD,
678 const ClassTemplateSpecializationDecl *D) override;
679 void AddedCXXTemplateSpecialization(
680 const VarTemplateDecl *TD,
681 const VarTemplateSpecializationDecl *D) override;
682 void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
683 const FunctionDecl *D) override;
684 void ResolvedExceptionSpec(const FunctionDecl *FD) override;
685 void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override;
686 void ResolvedOperatorDelete(const CXXDestructorDecl *DD,
687 const FunctionDecl *Delete) override;
688 void CompletedImplicitDefinition(const FunctionDecl *D) override;
689 void StaticDataMemberInstantiated(const VarDecl *D) override;
690 void DefaultArgumentInstantiated(const ParmVarDecl *D) override;
691 void DefaultMemberInitializerInstantiated(const FieldDecl *D) override;
692 void FunctionDefinitionInstantiated(const FunctionDecl *D) override;
693 void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
694 const ObjCInterfaceDecl *IFD) override;
695 void DeclarationMarkedUsed(const Decl *D) override;
696 void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override;
697 void DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
698 const Attr *Attr) override;
699 void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override;
700 void AddedAttributeToRecord(const Attr *Attr,
701 const RecordDecl *Record) override;
704 /// \brief An object for streaming information to a record.
705 class ASTRecordWriter {
707 ASTWriter::RecordDataImpl *Record;
709 /// \brief Statements that we've encountered while serializing a
710 /// declaration or type.
711 SmallVector<Stmt *, 16> StmtsToEmit;
713 /// \brief Indices of record elements that describe offsets within the
714 /// bitcode. These will be converted to offsets relative to the current
715 /// record when emitted.
716 SmallVector<unsigned, 8> OffsetIndices;
718 /// \brief Flush all of the statements and expressions that have
719 /// been added to the queue via AddStmt().
721 void FlushSubStmts();
723 void PrepareToEmit(uint64_t MyOffset) {
724 // Convert offsets into relative form.
725 for (unsigned I : OffsetIndices) {
726 auto &StoredOffset = (*Record)[I];
727 assert(StoredOffset < MyOffset && "invalid offset");
729 StoredOffset = MyOffset - StoredOffset;
731 OffsetIndices.clear();
735 /// Construct a ASTRecordWriter that uses the default encoding scheme.
736 ASTRecordWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
737 : Writer(&Writer), Record(&Record) {}
739 /// Construct a ASTRecordWriter that uses the same encoding scheme as another
741 ASTRecordWriter(ASTRecordWriter &Parent, ASTWriter::RecordDataImpl &Record)
742 : Writer(Parent.Writer), Record(&Record) {}
744 /// Copying an ASTRecordWriter is almost certainly a bug.
745 ASTRecordWriter(const ASTRecordWriter&) = delete;
746 void operator=(const ASTRecordWriter&) = delete;
748 /// \brief Extract the underlying record storage.
749 ASTWriter::RecordDataImpl &getRecordData() const { return *Record; }
751 /// \brief Minimal vector-like interface.
753 void push_back(uint64_t N) { Record->push_back(N); }
754 template<typename InputIterator>
755 void append(InputIterator begin, InputIterator end) {
756 Record->append(begin, end);
758 bool empty() const { return Record->empty(); }
759 size_t size() const { return Record->size(); }
760 uint64_t &operator[](size_t N) { return (*Record)[N]; }
763 /// \brief Emit the record to the stream, followed by its substatements, and
764 /// return its offset.
765 // FIXME: Allow record producers to suggest Abbrevs.
766 uint64_t Emit(unsigned Code, unsigned Abbrev = 0) {
767 uint64_t Offset = Writer->Stream.GetCurrentBitNo();
768 PrepareToEmit(Offset);
769 Writer->Stream.EmitRecord(Code, *Record, Abbrev);
774 /// \brief Emit the record to the stream, preceded by its substatements.
775 uint64_t EmitStmt(unsigned Code, unsigned Abbrev = 0) {
777 PrepareToEmit(Writer->Stream.GetCurrentBitNo());
778 Writer->Stream.EmitRecord(Code, *Record, Abbrev);
779 return Writer->Stream.GetCurrentBitNo();
782 /// \brief Add a bit offset into the record. This will be converted into an
783 /// offset relative to the current record when emitted.
784 void AddOffset(uint64_t BitOffset) {
785 OffsetIndices.push_back(Record->size());
786 Record->push_back(BitOffset);
789 /// \brief Add the given statement or expression to the queue of
790 /// statements to emit.
792 /// This routine should be used when emitting types and declarations
793 /// that have expressions as part of their formulation. Once the
794 /// type or declaration has been written, Emit() will write
795 /// the corresponding statements just after the record.
796 void AddStmt(Stmt *S) {
797 StmtsToEmit.push_back(S);
800 /// \brief Add a definition for the given function to the queue of statements
802 void AddFunctionDefinition(const FunctionDecl *FD);
804 /// \brief Emit a source location.
805 void AddSourceLocation(SourceLocation Loc) {
806 return Writer->AddSourceLocation(Loc, *Record);
809 /// \brief Emit a source range.
810 void AddSourceRange(SourceRange Range) {
811 return Writer->AddSourceRange(Range, *Record);
814 /// \brief Emit an integral value.
815 void AddAPInt(const llvm::APInt &Value);
817 /// \brief Emit a signed integral value.
818 void AddAPSInt(const llvm::APSInt &Value);
820 /// \brief Emit a floating-point value.
821 void AddAPFloat(const llvm::APFloat &Value);
823 /// \brief Emit a reference to an identifier.
824 void AddIdentifierRef(const IdentifierInfo *II) {
825 return Writer->AddIdentifierRef(II, *Record);
828 /// \brief Emit a Selector (which is a smart pointer reference).
829 void AddSelectorRef(Selector S);
831 /// \brief Emit a CXXTemporary.
832 void AddCXXTemporary(const CXXTemporary *Temp);
834 /// \brief Emit a C++ base specifier.
835 void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base);
837 /// \brief Emit a set of C++ base specifiers.
838 void AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases);
840 /// \brief Emit a reference to a type.
841 void AddTypeRef(QualType T) {
842 return Writer->AddTypeRef(T, *Record);
845 /// \brief Emits a reference to a declarator info.
846 void AddTypeSourceInfo(TypeSourceInfo *TInfo);
848 /// \brief Emits a type with source-location information.
849 void AddTypeLoc(TypeLoc TL);
851 /// \brief Emits a template argument location info.
852 void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
853 const TemplateArgumentLocInfo &Arg);
855 /// \brief Emits a template argument location.
856 void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg);
858 /// \brief Emits an AST template argument list info.
859 void AddASTTemplateArgumentListInfo(
860 const ASTTemplateArgumentListInfo *ASTTemplArgList);
862 /// \brief Emit a reference to a declaration.
863 void AddDeclRef(const Decl *D) {
864 return Writer->AddDeclRef(D, *Record);
867 /// \brief Emit a declaration name.
868 void AddDeclarationName(DeclarationName Name);
870 void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
871 DeclarationName Name);
872 void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
874 void AddQualifierInfo(const QualifierInfo &Info);
876 /// \brief Emit a nested name specifier.
877 void AddNestedNameSpecifier(NestedNameSpecifier *NNS);
879 /// \brief Emit a nested name specifier with source-location information.
880 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
882 /// \brief Emit a template name.
883 void AddTemplateName(TemplateName Name);
885 /// \brief Emit a template argument.
886 void AddTemplateArgument(const TemplateArgument &Arg);
888 /// \brief Emit a template parameter list.
889 void AddTemplateParameterList(const TemplateParameterList *TemplateParams);
891 /// \brief Emit a template argument list.
892 void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs);
894 /// \brief Emit a UnresolvedSet structure.
895 void AddUnresolvedSet(const ASTUnresolvedSet &Set);
897 /// \brief Emit a CXXCtorInitializer array.
898 void AddCXXCtorInitializers(ArrayRef<CXXCtorInitializer*> CtorInits);
900 void AddCXXDefinitionData(const CXXRecordDecl *D);
902 /// \brief Emit a string.
903 void AddString(StringRef Str) {
904 return Writer->AddString(Str, *Record);
907 /// \brief Emit a path.
908 void AddPath(StringRef Path) {
909 return Writer->AddPath(Path, *Record);
912 /// \brief Emit a version tuple.
913 void AddVersionTuple(const VersionTuple &Version) {
914 return Writer->AddVersionTuple(Version, *Record);
917 /// \brief Emit a list of attributes.
918 void AddAttributes(ArrayRef<const Attr*> Attrs);
921 /// \brief AST and semantic-analysis consumer that generates a
922 /// precompiled header from the parsed source code.
923 class PCHGenerator : public SemaConsumer {
924 const Preprocessor &PP;
925 std::string OutputFile;
926 std::string isysroot;
928 std::shared_ptr<PCHBuffer> Buffer;
929 llvm::BitstreamWriter Stream;
931 bool AllowASTWithErrors;
934 ASTWriter &getWriter() { return Writer; }
935 const ASTWriter &getWriter() const { return Writer; }
936 SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
939 PCHGenerator(const Preprocessor &PP, StringRef OutputFile, StringRef isysroot,
940 std::shared_ptr<PCHBuffer> Buffer,
941 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
942 bool AllowASTWithErrors = false, bool IncludeTimestamps = true);
943 ~PCHGenerator() override;
944 void InitializeSema(Sema &S) override { SemaPtr = &S; }
945 void HandleTranslationUnit(ASTContext &Ctx) override;
946 ASTMutationListener *GetASTMutationListener() override;
947 ASTDeserializationListener *GetASTDeserializationListener() override;
948 bool hasEmittedPCH() const { return Buffer->IsComplete; }
951 } // end namespace clang