]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Serialization/ASTWriter.h
Update Makefiles and other build glue for llvm/clang 3.7.0, as of trunk
[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/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"
31 #include <map>
32 #include <queue>
33 #include <vector>
34
35 namespace llvm {
36   class APFloat;
37   class APInt;
38   class BitstreamWriter;
39 }
40
41 namespace clang {
42
43 class ASTContext;
44 class NestedNameSpecifier;
45 class CXXBaseSpecifier;
46 class CXXCtorInitializer;
47 class FileEntry;
48 class FPOptions;
49 class HeaderSearch;
50 class HeaderSearchOptions;
51 class IdentifierResolver;
52 class MacroDefinitionRecord;
53 class MacroDirective;
54 class MacroInfo;
55 class OpaqueValueExpr;
56 class OpenCLOptions;
57 class ASTReader;
58 class Module;
59 class PreprocessedEntity;
60 class PreprocessingRecord;
61 class Preprocessor;
62 class Sema;
63 class SourceManager;
64 struct StoredDeclsList;
65 class SwitchCase;
66 class TargetInfo;
67 class Token;
68 class VersionTuple;
69 class ASTUnresolvedSet;
70
71 namespace SrcMgr { class SLocEntry; }
72
73 /// \brief Writes an AST file containing the contents of a translation unit.
74 ///
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 {
81 public:
82   typedef SmallVector<uint64_t, 64> RecordData;
83   typedef SmallVectorImpl<uint64_t> RecordDataImpl;
84
85   friend class ASTDeclWriter;
86   friend class ASTStmtWriter;
87 private:
88   /// \brief Map that provides the ID numbers of each type within the
89   /// output stream, plus those deserialized from a chained PCH.
90   ///
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.
95   ///
96   /// Keys in the map never have const/volatile qualifiers.
97   typedef llvm::DenseMap<QualType, serialization::TypeIdx,
98                          serialization::UnsafeQualTypeDenseMapInfo>
99     TypeIdxMap;
100
101   /// \brief The bitstream writer used to emit this precompiled header.
102   llvm::BitstreamWriter &Stream;
103
104   /// \brief The ASTContext we're writing.
105   ASTContext *Context;
106
107   /// \brief The preprocessor we're writing.
108   Preprocessor *PP;
109
110   /// \brief The reader of existing AST files, if we're chaining.
111   ASTReader *Chain;
112
113   /// \brief The module we're currently writing, if any.
114   Module *WritingModule;
115
116   /// \brief The base directory for any relative paths we emit.
117   std::string BaseDirectory;
118
119   /// \brief Indicates when the AST writing is actively performing
120   /// serialization, rather than just queueing updates.
121   bool WritingAST;
122
123   /// \brief Indicates that we are done serializing the collection of decls
124   /// and types to emit.
125   bool DoneWritingDeclsAndTypes;
126
127   /// \brief Indicates that the AST contained compiler errors.
128   bool ASTHasCompilerErrors;
129
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;
133
134   /// \brief Stores a declaration or a type to be written to the AST file.
135   class DeclOrType {
136   public:
137     DeclOrType(Decl *D) : Stored(D), IsType(false) { }
138     DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
139
140     bool isType() const { return IsType; }
141     bool isDecl() const { return !IsType; }
142
143     QualType getType() const {
144       assert(isType() && "Not a type!");
145       return QualType::getFromOpaquePtr(Stored);
146     }
147
148     Decl *getDecl() const {
149       assert(isDecl() && "Not a decl!");
150       return static_cast<Decl *>(Stored);
151     }
152
153   private:
154     void *Stored;
155     bool IsType;
156   };
157
158   /// \brief The declarations and types to emit.
159   std::queue<DeclOrType> DeclTypesToEmit;
160
161   /// \brief The first ID number we can use for our own declarations.
162   serialization::DeclID FirstDeclID;
163
164   /// \brief The decl ID that will be assigned to the next new decl.
165   serialization::DeclID NextDeclID;
166
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.
169   ///
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;
174
175   /// \brief Offset of each declaration in the bitstream, indexed by
176   /// the declaration's ID.
177   std::vector<serialization::DeclOffset> DeclOffsets;
178
179   /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
180   typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
181     LocDeclIDsTy;
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;
187   };
188   typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
189
190   /// \brief Map from file SLocEntries to info about the file-level declarations
191   /// that it contains.
192   FileDeclIDsTy FileDeclIDs;
193
194   void associateDeclWithFile(const Decl *D, serialization::DeclID);
195
196   /// \brief The first ID number we can use for our own types.
197   serialization::TypeID FirstTypeID;
198
199   /// \brief The type ID that will be assigned to the next new type.
200   serialization::TypeID NextTypeID;
201
202   /// \brief Map that provides the ID numbers of each type within the
203   /// output stream, plus those deserialized from a chained PCH.
204   ///
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.
209   ///
210   /// Keys in the map never have const/volatile qualifiers.
211   TypeIdxMap TypeIdxs;
212
213   /// \brief Offset of each type in the bitstream, indexed by
214   /// the type's ID.
215   std::vector<uint32_t> TypeOffsets;
216
217   /// \brief The first ID number we can use for our own identifiers.
218   serialization::IdentID FirstIdentID;
219
220   /// \brief The identifier ID that will be assigned to the next new identifier.
221   serialization::IdentID NextIdentID;
222
223   /// \brief Map that provides the ID numbers of each identifier in
224   /// the output stream.
225   ///
226   /// The ID numbers for identifiers are consecutive (in order of
227   /// discovery), starting at 1. An ID of zero refers to a NULL
228   /// IdentifierInfo.
229   llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
230
231   /// \brief The first ID number we can use for our own macros.
232   serialization::MacroID FirstMacroID;
233
234   /// \brief The identifier ID that will be assigned to the next new identifier.
235   serialization::MacroID NextMacroID;
236
237   /// \brief Map that provides the ID numbers of each macro.
238   llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
239
240   struct MacroInfoToEmitData {
241     const IdentifierInfo *Name;
242     MacroInfo *MI;
243     serialization::MacroID ID;
244   };
245   /// \brief The macro infos to emit.
246   std::vector<MacroInfoToEmitData> MacroInfosToEmit;
247
248   llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
249
250   /// @name FlushStmt Caches
251   /// @{
252
253   /// \brief Set of parent Stmts for the currently serializing sub-stmt.
254   llvm::DenseSet<Stmt *> ParentStmts;
255
256   /// \brief Offsets of sub-stmts already serialized. The offset points
257   /// just after the stmt record.
258   llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
259
260   /// @}
261
262   /// \brief Offsets of each of the identifier IDs into the identifier
263   /// table.
264   std::vector<uint32_t> IdentifierOffsets;
265
266   /// \brief The first ID number we can use for our own submodules.
267   serialization::SubmoduleID FirstSubmoduleID;
268   
269   /// \brief The submodule ID that will be assigned to the next new submodule.
270   serialization::SubmoduleID NextSubmoduleID;
271
272   /// \brief The first ID number we can use for our own selectors.
273   serialization::SelectorID FirstSelectorID;
274
275   /// \brief The selector ID that will be assigned to the next new selector.
276   serialization::SelectorID NextSelectorID;
277
278   /// \brief Map that provides the ID numbers of each Selector.
279   llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
280
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;
284
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;
289
290   /// \brief Cache of indices of anonymous declarations within their lexical
291   /// contexts.
292   llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
293
294   /// An update to a Decl.
295   class DeclUpdate {
296     /// A DeclUpdateKind.
297     unsigned Kind;
298     union {
299       const Decl *Dcl;
300       void *Type;
301       unsigned Loc;
302       unsigned Val;
303       Module *Mod;
304     };
305
306   public:
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) {}
317
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);
323     }
324     unsigned getNumber() const { return Val; }
325     Module *getModule() const { return Mod; }
326   };
327
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;
333
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;
338
339   /// \brief Declarations encountered that might be external
340   /// definitions.
341   ///
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
349   /// record.
350   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
351
352   /// \brief DeclContexts that have received extensions since their serialized
353   /// form.
354   ///
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
358   /// it.
359   llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
360
361   /// \brief Keeps track of visible decls that were added in DeclContexts
362   /// coming from another AST file.
363   SmallVector<const Decl *, 16> UpdatingVisibleDecls;
364
365   typedef llvm::SmallSetVector<const Decl *, 16> DeclsToRewriteTy;
366   /// \brief Decls that will be replaced in the current dependent AST file.
367   DeclsToRewriteTy DeclsToRewrite;
368
369   /// \brief The set of Objective-C class that have categories we
370   /// should serialize.
371   llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
372                     
373   struct ReplacedDeclInfo {
374     serialization::DeclID ID;
375     uint64_t Offset;
376     unsigned Loc;
377
378     ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {}
379     ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset,
380                      SourceLocation Loc)
381       : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {}
382   };
383
384   /// \brief Decls that have been replaced in the current dependent AST file.
385   ///
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;
391                  
392   /// \brief The set of declarations that may have redeclaration chains that
393   /// need to be serialized.
394   llvm::SmallSetVector<Decl *, 4> Redeclarations;
395                                       
396   /// \brief Statements that we've encountered while serializing a
397   /// declaration or type.
398   SmallVector<Stmt *, 16> StmtsToEmit;
399
400   /// \brief Statements collection to use for ASTWriter::AddStmt().
401   /// It will point to StmtsToEmit unless it is overriden.
402   SmallVector<Stmt *, 16> *CollectedStmts;
403
404   /// \brief Mapping from SwitchCase statements to IDs.
405   llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
406
407   /// \brief The number of statements written to the AST file.
408   unsigned NumStatements;
409
410   /// \brief The number of macros written to the AST file.
411   unsigned NumMacros;
412
413   /// \brief The number of lexical declcontexts written to the AST
414   /// file.
415   unsigned NumLexicalDeclContexts;
416
417   /// \brief The number of visible declcontexts written to the AST
418   /// file.
419   unsigned NumVisibleDeclContexts;
420
421   /// \brief The offset of each CXXBaseSpecifier set within the AST.
422   SmallVector<uint32_t, 16> CXXBaseSpecifiersOffsets;
423
424   /// \brief The first ID number we can use for our own base specifiers.
425   serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID;
426
427   /// \brief The base specifiers ID that will be assigned to the next new
428   /// set of C++ base specifiers.
429   serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID;
430
431   /// \brief A set of C++ base specifiers that is queued to be written into the
432   /// AST file.
433   struct QueuedCXXBaseSpecifiers {
434     QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { }
435
436     QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID,
437                             CXXBaseSpecifier const *Bases,
438                             CXXBaseSpecifier const *BasesEnd)
439       : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { }
440
441     serialization::CXXBaseSpecifiersID ID;
442     CXXBaseSpecifier const * Bases;
443     CXXBaseSpecifier const * BasesEnd;
444   };
445
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;
449
450   /// \brief The offset of each CXXCtorInitializer list within the AST.
451   SmallVector<uint32_t, 16> CXXCtorInitializersOffsets;
452
453   /// \brief The first ID number we can use for our own ctor initializers.
454   serialization::CXXCtorInitializersID FirstCXXCtorInitializersID;
455
456   /// \brief The ctor initializers ID that will be assigned to the next new
457   /// list of C++ ctor initializers.
458   serialization::CXXCtorInitializersID NextCXXCtorInitializersID;
459
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() {}
464
465     QueuedCXXCtorInitializers(serialization::CXXCtorInitializersID ID,
466                               ArrayRef<CXXCtorInitializer*> Inits)
467         : ID(ID), Inits(Inits) {}
468
469     serialization::CXXCtorInitializersID ID;
470     ArrayRef<CXXCtorInitializer*> Inits;
471   };
472
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;
476
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;
480                     
481   /// \brief Retrieve or create a submodule ID for this module.
482   unsigned getSubmoduleID(Module *Mod);
483                     
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);
488
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,
494                        bool Modules);
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);
501                                         
502   void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
503                                      bool isModule);
504   void WriteCXXBaseSpecifiersOffsets();
505   void WriteCXXCtorInitializersOffsets();
506
507   unsigned TypeExtQualAbbrev;
508   unsigned TypeFunctionProtoAbbrev;
509   void WriteTypeAbbrevs();
510   void WriteType(QualType T);
511
512   bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
513   bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
514
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,
525                             bool IsModule);
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);
536
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;
548
549   unsigned DeclRefExprAbbrev;
550   unsigned CharacterLiteralAbbrev;
551   unsigned IntegerLiteralAbbrev;
552   unsigned ExprImplicitCastAbbrev;
553
554   void WriteDeclAbbrevs();
555   void WriteDecl(ASTContext &Context, Decl *D);
556   void AddFunctionDefinition(const FunctionDecl *FD, RecordData &Record);
557
558   void WriteASTCore(Sema &SemaRef,
559                     StringRef isysroot, const std::string &OutputFile,
560                     Module *WritingModule);
561
562 public:
563   /// \brief Create a new precompiled header writer that outputs to
564   /// the given bitstream.
565   ASTWriter(llvm::BitstreamWriter &Stream);
566   ~ASTWriter() override;
567
568   const LangOptions &getLangOpts() const;
569
570   /// \brief Write a precompiled header for the given semantic analysis.
571   ///
572   /// \param SemaRef a reference to the semantic analysis object that processed
573   /// the AST to be written into the precompiled header.
574   ///
575   /// \param WritingModule The module that we are writing. If null, we are
576   /// writing a precompiled header.
577   ///
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);
585
586   /// \brief Emit a token.
587   void AddToken(const Token &Tok, RecordDataImpl &Record);
588
589   /// \brief Emit a source location.
590   void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
591
592   /// \brief Emit a source range.
593   void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
594
595   /// \brief Emit an integral value.
596   void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record);
597
598   /// \brief Emit a signed integral value.
599   void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record);
600
601   /// \brief Emit a floating-point value.
602   void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record);
603
604   /// \brief Emit a reference to an identifier.
605   void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
606
607   /// \brief Emit a Selector (which is a smart pointer reference).
608   void AddSelectorRef(Selector, RecordDataImpl &Record);
609
610   /// \brief Emit a CXXTemporary.
611   void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record);
612
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);
617
618   /// \brief Get the unique number used to refer to the given selector.
619   serialization::SelectorID getSelectorRef(Selector Sel);
620
621   /// \brief Get the unique number used to refer to the given identifier.
622   serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
623
624   /// \brief Get the unique number used to refer to the given macro.
625   serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
626
627   /// \brief Determine the ID of an already-emitted macro.
628   serialization::MacroID getMacroID(MacroInfo *MI);
629
630   uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
631
632   /// \brief Emit a reference to a type.
633   void AddTypeRef(QualType T, RecordDataImpl &Record);
634
635   /// \brief Force a type to be emitted and get its ID.
636   serialization::TypeID GetOrCreateTypeID(QualType T);
637
638   /// \brief Determine the type ID of an already-emitted type.
639   serialization::TypeID getTypeID(QualType T) const;
640
641   /// \brief Emits a reference to a declarator info.
642   void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record);
643
644   /// \brief Emits a type with source-location information.
645   void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record);
646
647   /// \brief Emits a template argument location info.
648   void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
649                                   const TemplateArgumentLocInfo &Arg,
650                                   RecordDataImpl &Record);
651
652   /// \brief Emits a template argument location.
653   void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
654                               RecordDataImpl &Record);
655
656   /// \brief Emits an AST template argument list info.
657   void AddASTTemplateArgumentListInfo(
658                           const ASTTemplateArgumentListInfo *ASTTemplArgList,
659                           RecordDataImpl &Record);
660
661   /// \brief Emit a reference to a declaration.
662   void AddDeclRef(const Decl *D, RecordDataImpl &Record);
663
664
665   /// \brief Force a declaration to be emitted and get its ID.
666   serialization::DeclID GetDeclRef(const Decl *D);
667
668   /// \brief Determine the declaration ID of an already-emitted
669   /// declaration.
670   serialization::DeclID getDeclID(const Decl *D);
671
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);
679
680   void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record);
681
682   /// \brief Emit a nested name specifier.
683   void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record);
684
685   /// \brief Emit a nested name specifier with source-location information.
686   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
687                                  RecordDataImpl &Record);
688
689   /// \brief Emit a template name.
690   void AddTemplateName(TemplateName Name, RecordDataImpl &Record);
691
692   /// \brief Emit a template argument.
693   void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record);
694
695   /// \brief Emit a template parameter list.
696   void AddTemplateParameterList(const TemplateParameterList *TemplateParams,
697                                 RecordDataImpl &Record);
698
699   /// \brief Emit a template argument list.
700   void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
701                                 RecordDataImpl &Record);
702
703   /// \brief Emit a UnresolvedSet structure.
704   void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record);
705
706   /// \brief Emit a C++ base specifier.
707   void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
708                            RecordDataImpl &Record);
709
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);
714
715   /// \brief Emit a CXXCtorInitializer array.
716   void AddCXXCtorInitializers(
717                              const CXXCtorInitializer * const *CtorInitializers,
718                              unsigned NumCtorInitializers,
719                              RecordDataImpl &Record);
720
721   void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record);
722
723   /// \brief Add a string to the given record.
724   void AddString(StringRef Str, RecordDataImpl &Record);
725
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);
729
730   /// \brief Add a path to the given record.
731   void AddPath(StringRef Path, RecordDataImpl &Record);
732
733   /// \brief Emit the current record with the given path as a blob.
734   void EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
735                           StringRef Path);
736
737   /// \brief Add a version tuple to the given record
738   void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
739
740   void RewriteDecl(const Decl *D) {
741     DeclsToRewrite.insert(D);
742   }
743
744   bool isRewritten(const Decl *D) const {
745     return DeclsToRewrite.count(D);
746   }
747
748   /// \brief Infer the submodule ID that contains an entity at the given
749   /// source location.
750   serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
751
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;
755
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);
759
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);
763
764   /// \brief Add the given statement or expression to the queue of
765   /// statements to emit.
766   ///
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
771   /// declaration.
772   void AddStmt(Stmt *S) {
773       CollectedStmts->push_back(S);
774   }
775
776   /// \brief Flush all of the statements and expressions that have
777   /// been added to the queue via AddStmt().
778   void FlushStmts();
779
780   /// \brief Flush all of the C++ base specifier sets that have been added
781   /// via \c AddCXXBaseSpecifiersRef().
782   void FlushCXXBaseSpecifiers();
783
784   /// \brief Flush all of the C++ constructor initializer lists that have been
785   /// added via \c AddCXXCtorInitializersRef().
786   void FlushCXXCtorInitializers();
787
788   /// \brief Flush all pending records that are tacked onto the end of
789   /// decl and decl update records.
790   void FlushPendingAfterDecl() {
791     FlushStmts();
792     FlushCXXBaseSpecifiers();
793     FlushCXXCtorInitializers();
794   }
795
796   /// \brief Record an ID for the given switch-case statement.
797   unsigned RecordSwitchCaseID(SwitchCase *S);
798
799   /// \brief Retrieve the ID for the given switch-case statement.
800   unsigned getSwitchCaseID(SwitchCase *S);
801
802   void ClearSwitchCaseIDs();
803
804   unsigned getTypeExtQualAbbrev() const {
805     return TypeExtQualAbbrev;
806   }
807   unsigned getTypeFunctionProtoAbbrev() const {
808     return TypeFunctionProtoAbbrev;
809   }
810
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; }
819
820   unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
821   unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
822   unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
823   unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
824
825   bool hasChain() const { return Chain; }
826
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;
836
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;
862 };
863
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;
871   raw_ostream *Out;
872   Sema *SemaPtr;
873   SmallVector<char, 128> Buffer;
874   llvm::BitstreamWriter Stream;
875   ASTWriter Writer;
876   bool AllowASTWithErrors;
877   bool HasEmittedPCH;
878
879 protected:
880   ASTWriter &getWriter() { return Writer; }
881   const ASTWriter &getWriter() const { return Writer; }
882
883 public:
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;
893
894   bool hasEmittedPCH() const { return HasEmittedPCH; }
895 };
896
897 } // end namespace clang
898
899 #endif