]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Serialization/ASTWriter.h
Merge ^/head r313644 through r313895.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Serialization / ASTWriter.h
1 //===--- ASTWriter.h - AST File Writer --------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ASTWriter class, which writes an AST file
11 //  containing a serialized representation of a translation unit.
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/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"
30 #include <queue>
31 #include <vector>
32
33 namespace llvm {
34   class APFloat;
35   class APInt;
36 }
37
38 namespace clang {
39
40 class DeclarationName;
41 class ASTContext;
42 class Attr;
43 class NestedNameSpecifier;
44 class CXXBaseSpecifier;
45 class CXXCtorInitializer;
46 class FileEntry;
47 class FPOptions;
48 class HeaderSearch;
49 class HeaderSearchOptions;
50 class IdentifierResolver;
51 class MacroDefinitionRecord;
52 class MacroDirective;
53 class MacroInfo;
54 class OpaqueValueExpr;
55 class OpenCLOptions;
56 class ASTReader;
57 class Module;
58 class ModuleFileExtension;
59 class ModuleFileExtensionWriter;
60 class PreprocessedEntity;
61 class PreprocessingRecord;
62 class Preprocessor;
63 class RecordDecl;
64 class Sema;
65 class SourceManager;
66 struct StoredDeclsList;
67 class SwitchCase;
68 class TargetInfo;
69 class Token;
70 class VersionTuple;
71 class ASTUnresolvedSet;
72
73 namespace SrcMgr { class SLocEntry; }
74
75 /// \brief Writes an AST file containing the contents of a translation unit.
76 ///
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 {
83 public:
84   typedef SmallVector<uint64_t, 64> RecordData;
85   typedef SmallVectorImpl<uint64_t> RecordDataImpl;
86   typedef ArrayRef<uint64_t> RecordDataRef;
87
88   friend class ASTDeclWriter;
89   friend class ASTStmtWriter;
90   friend class ASTTypeWriter;
91   friend class ASTRecordWriter;
92 private:
93   /// \brief Map that provides the ID numbers of each type within the
94   /// output stream, plus those deserialized from a chained PCH.
95   ///
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.
100   ///
101   /// Keys in the map never have const/volatile qualifiers.
102   typedef llvm::DenseMap<QualType, serialization::TypeIdx,
103                          serialization::UnsafeQualTypeDenseMapInfo>
104     TypeIdxMap;
105
106   /// \brief The bitstream writer used to emit this precompiled header.
107   llvm::BitstreamWriter &Stream;
108
109   /// \brief The ASTContext we're writing.
110   ASTContext *Context = nullptr;
111
112   /// \brief The preprocessor we're writing.
113   Preprocessor *PP = nullptr;
114
115   /// \brief The reader of existing AST files, if we're chaining.
116   ASTReader *Chain = nullptr;
117
118   /// \brief The module we're currently writing, if any.
119   Module *WritingModule = nullptr;
120
121   /// \brief The base directory for any relative paths we emit.
122   std::string BaseDirectory;
123
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;
129
130   /// \brief Indicates when the AST writing is actively performing
131   /// serialization, rather than just queueing updates.
132   bool WritingAST = false;
133
134   /// \brief Indicates that we are done serializing the collection of decls
135   /// and types to emit.
136   bool DoneWritingDeclsAndTypes = false;
137
138   /// \brief Indicates that the AST contained compiler errors.
139   bool ASTHasCompilerErrors = false;
140
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;
144
145   /// \brief Stores a declaration or a type to be written to the AST file.
146   class DeclOrType {
147   public:
148     DeclOrType(Decl *D) : Stored(D), IsType(false) { }
149     DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
150
151     bool isType() const { return IsType; }
152     bool isDecl() const { return !IsType; }
153
154     QualType getType() const {
155       assert(isType() && "Not a type!");
156       return QualType::getFromOpaquePtr(Stored);
157     }
158
159     Decl *getDecl() const {
160       assert(isDecl() && "Not a decl!");
161       return static_cast<Decl *>(Stored);
162     }
163
164   private:
165     void *Stored;
166     bool IsType;
167   };
168
169   /// \brief The declarations and types to emit.
170   std::queue<DeclOrType> DeclTypesToEmit;
171
172   /// \brief The first ID number we can use for our own declarations.
173   serialization::DeclID FirstDeclID = serialization::NUM_PREDEF_DECL_IDS;
174
175   /// \brief The decl ID that will be assigned to the next new decl.
176   serialization::DeclID NextDeclID = FirstDeclID;
177
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.
180   ///
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;
185
186   /// \brief Offset of each declaration in the bitstream, indexed by
187   /// the declaration's ID.
188   std::vector<serialization::DeclOffset> DeclOffsets;
189
190   /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
191   typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
192     LocDeclIDsTy;
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;
198   };
199   typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
200
201   /// \brief Map from file SLocEntries to info about the file-level declarations
202   /// that it contains.
203   FileDeclIDsTy FileDeclIDs;
204
205   void associateDeclWithFile(const Decl *D, serialization::DeclID);
206
207   /// \brief The first ID number we can use for our own types.
208   serialization::TypeID FirstTypeID = serialization::NUM_PREDEF_TYPE_IDS;
209
210   /// \brief The type ID that will be assigned to the next new type.
211   serialization::TypeID NextTypeID = FirstTypeID;
212
213   /// \brief Map that provides the ID numbers of each type within the
214   /// output stream, plus those deserialized from a chained PCH.
215   ///
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.
220   ///
221   /// Keys in the map never have const/volatile qualifiers.
222   TypeIdxMap TypeIdxs;
223
224   /// \brief Offset of each type in the bitstream, indexed by
225   /// the type's ID.
226   std::vector<uint32_t> TypeOffsets;
227
228   /// \brief The first ID number we can use for our own identifiers.
229   serialization::IdentID FirstIdentID = serialization::NUM_PREDEF_IDENT_IDS;
230
231   /// \brief The identifier ID that will be assigned to the next new identifier.
232   serialization::IdentID NextIdentID = FirstIdentID;
233
234   /// \brief Map that provides the ID numbers of each identifier in
235   /// the output stream.
236   ///
237   /// The ID numbers for identifiers are consecutive (in order of
238   /// discovery), starting at 1. An ID of zero refers to a NULL
239   /// IdentifierInfo.
240   llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
241
242   /// \brief The first ID number we can use for our own macros.
243   serialization::MacroID FirstMacroID = serialization::NUM_PREDEF_MACRO_IDS;
244
245   /// \brief The identifier ID that will be assigned to the next new identifier.
246   serialization::MacroID NextMacroID = FirstMacroID;
247
248   /// \brief Map that provides the ID numbers of each macro.
249   llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
250
251   struct MacroInfoToEmitData {
252     const IdentifierInfo *Name;
253     MacroInfo *MI;
254     serialization::MacroID ID;
255   };
256   /// \brief The macro infos to emit.
257   std::vector<MacroInfoToEmitData> MacroInfosToEmit;
258
259   llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
260
261   /// @name FlushStmt Caches
262   /// @{
263
264   /// \brief Set of parent Stmts for the currently serializing sub-stmt.
265   llvm::DenseSet<Stmt *> ParentStmts;
266
267   /// \brief Offsets of sub-stmts already serialized. The offset points
268   /// just after the stmt record.
269   llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
270
271   /// @}
272
273   /// \brief Offsets of each of the identifier IDs into the identifier
274   /// table.
275   std::vector<uint32_t> IdentifierOffsets;
276
277   /// \brief The first ID number we can use for our own submodules.
278   serialization::SubmoduleID FirstSubmoduleID =
279       serialization::NUM_PREDEF_SUBMODULE_IDS;
280
281   /// \brief The submodule ID that will be assigned to the next new submodule.
282   serialization::SubmoduleID NextSubmoduleID = FirstSubmoduleID;
283
284   /// \brief The first ID number we can use for our own selectors.
285   serialization::SelectorID FirstSelectorID =
286       serialization::NUM_PREDEF_SELECTOR_IDS;
287
288   /// \brief The selector ID that will be assigned to the next new selector.
289   serialization::SelectorID NextSelectorID = FirstSelectorID;
290
291   /// \brief Map that provides the ID numbers of each Selector.
292   llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
293
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;
297
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;
302
303   /// \brief Cache of indices of anonymous declarations within their lexical
304   /// contexts.
305   llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
306
307   /// An update to a Decl.
308   class DeclUpdate {
309     /// A DeclUpdateKind.
310     unsigned Kind;
311     union {
312       const Decl *Dcl;
313       void *Type;
314       unsigned Loc;
315       unsigned Val;
316       Module *Mod;
317       const Attr *Attribute;
318     };
319
320   public:
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) {}
333
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);
339     }
340     unsigned getNumber() const { return Val; }
341     Module *getModule() const { return Mod; }
342     const Attr *getAttr() const { return Attribute; }
343   };
344
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;
350
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;
355
356   /// \brief Declarations encountered that might be external
357   /// definitions.
358   ///
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
366   /// record.
367   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
368
369   /// \brief DeclContexts that have received extensions since their serialized
370   /// form.
371   ///
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
375   /// it.
376   llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
377
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;
382
383   /// \brief The set of Objective-C class that have categories we
384   /// should serialize.
385   llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
386                     
387   /// \brief The set of declarations that may have redeclaration chains that
388   /// need to be serialized.
389   llvm::SmallVector<const Decl *, 16> Redeclarations;
390
391   /// \brief A cache of the first local declaration for "interesting"
392   /// redeclaration chains.
393   llvm::DenseMap<const Decl *, const Decl *> FirstLocalDeclCache;
394                                       
395   /// \brief Mapping from SwitchCase statements to IDs.
396   llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
397
398   /// \brief The number of statements written to the AST file.
399   unsigned NumStatements = 0;
400
401   /// \brief The number of macros written to the AST file.
402   unsigned NumMacros = 0;
403
404   /// \brief The number of lexical declcontexts written to the AST
405   /// file.
406   unsigned NumLexicalDeclContexts = 0;
407
408   /// \brief The number of visible declcontexts written to the AST
409   /// file.
410   unsigned NumVisibleDeclContexts = 0;
411
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;
415
416   /// \brief A list of the module file extension writers.
417   std::vector<std::unique_ptr<ModuleFileExtensionWriter>>
418     ModuleFileExtensionWriters;
419
420   /// \brief Retrieve or create a submodule ID for this module.
421   unsigned getSubmoduleID(Module *Mod);
422
423   /// \brief Write the given subexpression to the bitstream.
424   void WriteSubStmt(Stmt *S);
425
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,
430                        bool Modules);
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);
437                                         
438   void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
439                                      bool isModule);
440
441   unsigned TypeExtQualAbbrev = 0;
442   unsigned TypeFunctionProtoAbbrev = 0;
443   void WriteTypeAbbrevs();
444   void WriteType(QualType T);
445
446   bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
447   bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
448
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,
459                             bool IsModule);
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);
474
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;
486
487   unsigned DeclRefExprAbbrev = 0;
488   unsigned CharacterLiteralAbbrev = 0;
489   unsigned IntegerLiteralAbbrev = 0;
490   unsigned ExprImplicitCastAbbrev = 0;
491
492   void WriteDeclAbbrevs();
493   void WriteDecl(ASTContext &Context, Decl *D);
494
495   uint64_t WriteASTCore(Sema &SemaRef,
496                         StringRef isysroot, const std::string &OutputFile,
497                         Module *WritingModule);
498
499 public:
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;
506
507   const LangOptions &getLangOpts() const;
508
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;
513
514   /// \brief Write a precompiled header for the given semantic analysis.
515   ///
516   /// \param SemaRef a reference to the semantic analysis object that processed
517   /// the AST to be written into the precompiled header.
518   ///
519   /// \param WritingModule The module that we are writing. If null, we are
520   /// writing a precompiled header.
521   ///
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.
525   ///
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);
531
532   /// \brief Emit a token.
533   void AddToken(const Token &Tok, RecordDataImpl &Record);
534
535   /// \brief Emit a source location.
536   void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
537
538   /// \brief Emit a source range.
539   void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
540
541   /// \brief Emit a reference to an identifier.
542   void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
543
544   /// \brief Get the unique number used to refer to the given selector.
545   serialization::SelectorID getSelectorRef(Selector Sel);
546
547   /// \brief Get the unique number used to refer to the given identifier.
548   serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
549
550   /// \brief Get the unique number used to refer to the given macro.
551   serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
552
553   /// \brief Determine the ID of an already-emitted macro.
554   serialization::MacroID getMacroID(MacroInfo *MI);
555
556   uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
557
558   /// \brief Emit a reference to a type.
559   void AddTypeRef(QualType T, RecordDataImpl &Record);
560
561   /// \brief Force a type to be emitted and get its ID.
562   serialization::TypeID GetOrCreateTypeID(QualType T);
563
564   /// \brief Determine the type ID of an already-emitted type.
565   serialization::TypeID getTypeID(QualType T) const;
566
567   /// \brief Find the first local declaration of a given local redeclarable
568   /// decl.
569   const Decl *getFirstLocalDecl(const Decl *D);
570
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())
576       return false;
577     auto I = DeclIDs.find(D);
578     return (I == DeclIDs.end() ||
579             I->second >= serialization::NUM_PREDEF_DECL_IDS);
580   };
581
582   /// \brief Emit a reference to a declaration.
583   void AddDeclRef(const Decl *D, RecordDataImpl &Record);
584
585
586   /// \brief Force a declaration to be emitted and get its ID.
587   serialization::DeclID GetDeclRef(const Decl *D);
588
589   /// \brief Determine the declaration ID of an already-emitted
590   /// declaration.
591   serialization::DeclID getDeclID(const Decl *D);
592
593   unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
594
595   /// \brief Add a string to the given record.
596   void AddString(StringRef Str, RecordDataImpl &Record);
597
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);
601
602   /// \brief Add a path to the given record.
603   void AddPath(StringRef Path, RecordDataImpl &Record);
604
605   /// \brief Emit the current record with the given path as a blob.
606   void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
607                           StringRef Path);
608
609   /// \brief Add a version tuple to the given record
610   void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
611
612   /// \brief Infer the submodule ID that contains an entity at the given
613   /// source location.
614   serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
615
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);
620
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);
624
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);
628
629   /// \brief Record an ID for the given switch-case statement.
630   unsigned RecordSwitchCaseID(SwitchCase *S);
631
632   /// \brief Retrieve the ID for the given switch-case statement.
633   unsigned getSwitchCaseID(SwitchCase *S);
634
635   void ClearSwitchCaseIDs();
636
637   unsigned getTypeExtQualAbbrev() const {
638     return TypeExtQualAbbrev;
639   }
640   unsigned getTypeFunctionProtoAbbrev() const {
641     return TypeFunctionProtoAbbrev;
642   }
643
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; }
652
653   unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
654   unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
655   unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
656   unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
657
658   bool hasChain() const { return Chain; }
659   ASTReader *getChain() const { return Chain; }
660
661 private:
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;
671
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;
702 };
703
704 /// \brief An object for streaming information to a record.
705 class ASTRecordWriter {
706   ASTWriter *Writer;
707   ASTWriter::RecordDataImpl *Record;
708
709   /// \brief Statements that we've encountered while serializing a
710   /// declaration or type.
711   SmallVector<Stmt *, 16> StmtsToEmit;
712
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;
717
718   /// \brief Flush all of the statements and expressions that have
719   /// been added to the queue via AddStmt().
720   void FlushStmts();
721   void FlushSubStmts();
722
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");
728       if (StoredOffset)
729         StoredOffset = MyOffset - StoredOffset;
730     }
731     OffsetIndices.clear();
732   }
733
734 public:
735   /// Construct a ASTRecordWriter that uses the default encoding scheme.
736   ASTRecordWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
737       : Writer(&Writer), Record(&Record) {}
738
739   /// Construct a ASTRecordWriter that uses the same encoding scheme as another
740   /// ASTRecordWriter.
741   ASTRecordWriter(ASTRecordWriter &Parent, ASTWriter::RecordDataImpl &Record)
742       : Writer(Parent.Writer), Record(&Record) {}
743
744   /// Copying an ASTRecordWriter is almost certainly a bug.
745   ASTRecordWriter(const ASTRecordWriter&) = delete;
746   void operator=(const ASTRecordWriter&) = delete;
747
748   /// \brief Extract the underlying record storage.
749   ASTWriter::RecordDataImpl &getRecordData() const { return *Record; }
750
751   /// \brief Minimal vector-like interface.
752   /// @{
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);
757   }
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]; }
761   /// @}
762
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);
770     FlushStmts();
771     return Offset;
772   }
773
774   /// \brief Emit the record to the stream, preceded by its substatements.
775   uint64_t EmitStmt(unsigned Code, unsigned Abbrev = 0) {
776     FlushSubStmts();
777     PrepareToEmit(Writer->Stream.GetCurrentBitNo());
778     Writer->Stream.EmitRecord(Code, *Record, Abbrev);
779     return Writer->Stream.GetCurrentBitNo();
780   }
781
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);
787   }
788
789   /// \brief Add the given statement or expression to the queue of
790   /// statements to emit.
791   ///
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);
798   }
799
800   /// \brief Add a definition for the given function to the queue of statements
801   /// to emit.
802   void AddFunctionDefinition(const FunctionDecl *FD);
803
804   /// \brief Emit a source location.
805   void AddSourceLocation(SourceLocation Loc) {
806     return Writer->AddSourceLocation(Loc, *Record);
807   }
808
809   /// \brief Emit a source range.
810   void AddSourceRange(SourceRange Range) {
811     return Writer->AddSourceRange(Range, *Record);
812   }
813
814   /// \brief Emit an integral value.
815   void AddAPInt(const llvm::APInt &Value);
816
817   /// \brief Emit a signed integral value.
818   void AddAPSInt(const llvm::APSInt &Value);
819
820   /// \brief Emit a floating-point value.
821   void AddAPFloat(const llvm::APFloat &Value);
822
823   /// \brief Emit a reference to an identifier.
824   void AddIdentifierRef(const IdentifierInfo *II) {
825     return Writer->AddIdentifierRef(II, *Record);
826   }
827
828   /// \brief Emit a Selector (which is a smart pointer reference).
829   void AddSelectorRef(Selector S);
830
831   /// \brief Emit a CXXTemporary.
832   void AddCXXTemporary(const CXXTemporary *Temp);
833
834   /// \brief Emit a C++ base specifier.
835   void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base);
836
837   /// \brief Emit a set of C++ base specifiers.
838   void AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases);
839
840   /// \brief Emit a reference to a type.
841   void AddTypeRef(QualType T) {
842     return Writer->AddTypeRef(T, *Record);
843   }
844
845   /// \brief Emits a reference to a declarator info.
846   void AddTypeSourceInfo(TypeSourceInfo *TInfo);
847
848   /// \brief Emits a type with source-location information.
849   void AddTypeLoc(TypeLoc TL);
850
851   /// \brief Emits a template argument location info.
852   void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
853                                   const TemplateArgumentLocInfo &Arg);
854
855   /// \brief Emits a template argument location.
856   void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg);
857
858   /// \brief Emits an AST template argument list info.
859   void AddASTTemplateArgumentListInfo(
860       const ASTTemplateArgumentListInfo *ASTTemplArgList);
861
862   /// \brief Emit a reference to a declaration.
863   void AddDeclRef(const Decl *D) {
864     return Writer->AddDeclRef(D, *Record);
865   }
866
867   /// \brief Emit a declaration name.
868   void AddDeclarationName(DeclarationName Name);
869
870   void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
871                              DeclarationName Name);
872   void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
873
874   void AddQualifierInfo(const QualifierInfo &Info);
875
876   /// \brief Emit a nested name specifier.
877   void AddNestedNameSpecifier(NestedNameSpecifier *NNS);
878
879   /// \brief Emit a nested name specifier with source-location information.
880   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
881
882   /// \brief Emit a template name.
883   void AddTemplateName(TemplateName Name);
884
885   /// \brief Emit a template argument.
886   void AddTemplateArgument(const TemplateArgument &Arg);
887
888   /// \brief Emit a template parameter list.
889   void AddTemplateParameterList(const TemplateParameterList *TemplateParams);
890
891   /// \brief Emit a template argument list.
892   void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs);
893
894   /// \brief Emit a UnresolvedSet structure.
895   void AddUnresolvedSet(const ASTUnresolvedSet &Set);
896
897   /// \brief Emit a CXXCtorInitializer array.
898   void AddCXXCtorInitializers(ArrayRef<CXXCtorInitializer*> CtorInits);
899
900   void AddCXXDefinitionData(const CXXRecordDecl *D);
901
902   /// \brief Emit a string.
903   void AddString(StringRef Str) {
904     return Writer->AddString(Str, *Record);
905   }
906
907   /// \brief Emit a path.
908   void AddPath(StringRef Path) {
909     return Writer->AddPath(Path, *Record);
910   }
911
912   /// \brief Emit a version tuple.
913   void AddVersionTuple(const VersionTuple &Version) {
914     return Writer->AddVersionTuple(Version, *Record);
915   }
916
917   /// \brief Emit a list of attributes.
918   void AddAttributes(ArrayRef<const Attr*> Attrs);
919 };
920
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;
927   Sema *SemaPtr;
928   std::shared_ptr<PCHBuffer> Buffer;
929   llvm::BitstreamWriter Stream;
930   ASTWriter Writer;
931   bool AllowASTWithErrors;
932
933 protected:
934   ASTWriter &getWriter() { return Writer; }
935   const ASTWriter &getWriter() const { return Writer; }
936   SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
937
938 public:
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; }
949 };
950
951 } // end namespace clang
952
953 #endif