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_FRONTEND_AST_WRITER_H
15#define LLVM_CLANG_FRONTEND_AST_WRITER_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
35namespace llvm {
36  class APFloat;
37  class APInt;
38  class BitstreamWriter;
39}
40
41namespace clang {
42
43class ASTContext;
44class NestedNameSpecifier;
45class CXXBaseSpecifier;
46class CXXCtorInitializer;
47class FileEntry;
48class FPOptions;
49class HeaderSearch;
50class HeaderSearchOptions;
51class IdentifierResolver;
52class MacroDefinition;
53class MacroDirective;
54class MacroInfo;
55class OpaqueValueExpr;
56class OpenCLOptions;
57class ASTReader;
58class Module;
59class PreprocessedEntity;
60class PreprocessingRecord;
61class Preprocessor;
62class Sema;
63class SourceManager;
64class SwitchCase;
65class TargetInfo;
66class Token;
67class VersionTuple;
68class ASTUnresolvedSet;
69
70namespace SrcMgr { class SLocEntry; }
71
72/// \brief Writes an AST file containing the contents of a translation unit.
73///
74/// The ASTWriter class produces a bitstream containing the serialized
75/// representation of a given abstract syntax tree and its supporting
76/// data structures. This bitstream can be de-serialized via an
77/// instance of the ASTReader class.
78class ASTWriter : public ASTDeserializationListener,
79                  public ASTMutationListener {
80public:
81  typedef SmallVector<uint64_t, 64> RecordData;
82  typedef SmallVectorImpl<uint64_t> RecordDataImpl;
83
84  friend class ASTDeclWriter;
85  friend class ASTStmtWriter;
86private:
87  /// \brief Map that provides the ID numbers of each type within the
88  /// output stream, plus those deserialized from a chained PCH.
89  ///
90  /// The ID numbers of types are consecutive (in order of discovery)
91  /// and start at 1. 0 is reserved for NULL. When types are actually
92  /// stored in the stream, the ID number is shifted by 2 bits to
93  /// allow for the const/volatile qualifiers.
94  ///
95  /// Keys in the map never have const/volatile qualifiers.
96  typedef llvm::DenseMap<QualType, serialization::TypeIdx,
97                         serialization::UnsafeQualTypeDenseMapInfo>
98    TypeIdxMap;
99
100  /// \brief The bitstream writer used to emit this precompiled header.
101  llvm::BitstreamWriter &Stream;
102
103  /// \brief The ASTContext we're writing.
104  ASTContext *Context;
105
106  /// \brief The preprocessor we're writing.
107  Preprocessor *PP;
108
109  /// \brief The reader of existing AST files, if we're chaining.
110  ASTReader *Chain;
111
112  /// \brief The module we're currently writing, if any.
113  Module *WritingModule;
114
115  /// \brief Indicates when the AST writing is actively performing
116  /// serialization, rather than just queueing updates.
117  bool WritingAST;
118
119  /// \brief Indicates that we are done serializing the collection of decls
120  /// and types to emit.
121  bool DoneWritingDeclsAndTypes;
122
123  /// \brief Indicates that the AST contained compiler errors.
124  bool ASTHasCompilerErrors;
125
126  /// \brief Mapping from input file entries to the index into the
127  /// offset table where information about that input file is stored.
128  llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs;
129
130  /// \brief Stores a declaration or a type to be written to the AST file.
131  class DeclOrType {
132  public:
133    DeclOrType(Decl *D) : Stored(D), IsType(false) { }
134    DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
135
136    bool isType() const { return IsType; }
137    bool isDecl() const { return !IsType; }
138
139    QualType getType() const {
140      assert(isType() && "Not a type!");
141      return QualType::getFromOpaquePtr(Stored);
142    }
143
144    Decl *getDecl() const {
145      assert(isDecl() && "Not a decl!");
146      return static_cast<Decl *>(Stored);
147    }
148
149  private:
150    void *Stored;
151    bool IsType;
152  };
153
154  /// \brief The declarations and types to emit.
155  std::queue<DeclOrType> DeclTypesToEmit;
156
157  /// \brief The first ID number we can use for our own declarations.
158  serialization::DeclID FirstDeclID;
159
160  /// \brief The decl ID that will be assigned to the next new decl.
161  serialization::DeclID NextDeclID;
162
163  /// \brief Map that provides the ID numbers of each declaration within
164  /// the output stream, as well as those deserialized from a chained PCH.
165  ///
166  /// The ID numbers of declarations are consecutive (in order of
167  /// discovery) and start at 2. 1 is reserved for the translation
168  /// unit, while 0 is reserved for NULL.
169  llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs;
170
171  /// \brief Offset of each declaration in the bitstream, indexed by
172  /// the declaration's ID.
173  std::vector<serialization::DeclOffset> DeclOffsets;
174
175  /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
176  typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
177    LocDeclIDsTy;
178  struct DeclIDInFileInfo {
179    LocDeclIDsTy DeclIDs;
180    /// \brief Set when the DeclIDs vectors from all files are joined, this
181    /// indicates the index that this particular vector has in the global one.
182    unsigned FirstDeclIndex;
183  };
184  typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
185
186  /// \brief Map from file SLocEntries to info about the file-level declarations
187  /// that it contains.
188  FileDeclIDsTy FileDeclIDs;
189
190  void associateDeclWithFile(const Decl *D, serialization::DeclID);
191
192  /// \brief The first ID number we can use for our own types.
193  serialization::TypeID FirstTypeID;
194
195  /// \brief The type ID that will be assigned to the next new type.
196  serialization::TypeID NextTypeID;
197
198  /// \brief Map that provides the ID numbers of each type within the
199  /// output stream, plus those deserialized from a chained PCH.
200  ///
201  /// The ID numbers of types are consecutive (in order of discovery)
202  /// and start at 1. 0 is reserved for NULL. When types are actually
203  /// stored in the stream, the ID number is shifted by 2 bits to
204  /// allow for the const/volatile qualifiers.
205  ///
206  /// Keys in the map never have const/volatile qualifiers.
207  TypeIdxMap TypeIdxs;
208
209  /// \brief Offset of each type in the bitstream, indexed by
210  /// the type's ID.
211  std::vector<uint32_t> TypeOffsets;
212
213  /// \brief The first ID number we can use for our own identifiers.
214  serialization::IdentID FirstIdentID;
215
216  /// \brief The identifier ID that will be assigned to the next new identifier.
217  serialization::IdentID NextIdentID;
218
219  /// \brief Map that provides the ID numbers of each identifier in
220  /// the output stream.
221  ///
222  /// The ID numbers for identifiers are consecutive (in order of
223  /// discovery), starting at 1. An ID of zero refers to a NULL
224  /// IdentifierInfo.
225  llvm::DenseMap<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
226
227  /// \brief The first ID number we can use for our own macros.
228  serialization::MacroID FirstMacroID;
229
230  /// \brief The identifier ID that will be assigned to the next new identifier.
231  serialization::MacroID NextMacroID;
232
233  /// \brief Map that provides the ID numbers of each macro.
234  llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
235
236  struct MacroInfoToEmitData {
237    const IdentifierInfo *Name;
238    MacroInfo *MI;
239    serialization::MacroID ID;
240  };
241  /// \brief The macro infos to emit.
242  std::vector<MacroInfoToEmitData> MacroInfosToEmit;
243
244  llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
245
246  /// @name FlushStmt Caches
247  /// @{
248
249  /// \brief Set of parent Stmts for the currently serializing sub stmt.
250  llvm::DenseSet<Stmt *> ParentStmts;
251
252  /// \brief Offsets of sub stmts already serialized. The offset points
253  /// just after the stmt record.
254  llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
255
256  /// @}
257
258  /// \brief Offsets of each of the identifier IDs into the identifier
259  /// table.
260  std::vector<uint32_t> IdentifierOffsets;
261
262  /// \brief The first ID number we can use for our own submodules.
263  serialization::SubmoduleID FirstSubmoduleID;
264
265  /// \brief The submodule ID that will be assigned to the next new submodule.
266  serialization::SubmoduleID NextSubmoduleID;
267
268  /// \brief The first ID number we can use for our own selectors.
269  serialization::SelectorID FirstSelectorID;
270
271  /// \brief The selector ID that will be assigned to the next new selector.
272  serialization::SelectorID NextSelectorID;
273
274  /// \brief Map that provides the ID numbers of each Selector.
275  llvm::DenseMap<Selector, serialization::SelectorID> SelectorIDs;
276
277  /// \brief Offset of each selector within the method pool/selector
278  /// table, indexed by the Selector ID (-1).
279  std::vector<uint32_t> SelectorOffsets;
280
281  /// \brief Mapping from macro definitions (as they occur in the preprocessing
282  /// record) to the macro IDs.
283  llvm::DenseMap<const MacroDefinition *, serialization::PreprocessedEntityID>
284      MacroDefinitions;
285
286  typedef SmallVector<uint64_t, 2> UpdateRecord;
287  typedef llvm::DenseMap<const Decl *, UpdateRecord> DeclUpdateMap;
288  /// \brief Mapping from declarations that came from a chained PCH to the
289  /// record containing modifications to them.
290  DeclUpdateMap DeclUpdates;
291
292  typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap;
293  /// \brief Map of first declarations from a chained PCH that point to the
294  /// most recent declarations in another PCH.
295  FirstLatestDeclMap FirstLatestDecls;
296
297  /// \brief Declarations encountered that might be external
298  /// definitions.
299  ///
300  /// We keep track of external definitions (as well as tentative
301  /// definitions) as we are emitting declarations to the AST
302  /// file. The AST file contains a separate record for these external
303  /// definitions, which are provided to the AST consumer by the AST
304  /// reader. This is behavior is required to properly cope with,
305  /// e.g., tentative variable definitions that occur within
306  /// headers. The declarations themselves are stored as declaration
307  /// IDs, since they will be written out to an EXTERNAL_DEFINITIONS
308  /// record.
309  SmallVector<uint64_t, 16> ExternalDefinitions;
310
311  /// \brief DeclContexts that have received extensions since their serialized
312  /// form.
313  ///
314  /// For namespaces, when we're chaining and encountering a namespace, we check
315  /// if its primary namespace comes from the chain. If it does, we add the
316  /// primary to this set, so that we can write out lexical content updates for
317  /// it.
318  llvm::SmallPtrSet<const DeclContext *, 16> UpdatedDeclContexts;
319
320  /// \brief Keeps track of visible decls that were added in DeclContexts
321  /// coming from another AST file.
322  SmallVector<const Decl *, 16> UpdatingVisibleDecls;
323
324  typedef llvm::SmallPtrSet<const Decl *, 16> DeclsToRewriteTy;
325  /// \brief Decls that will be replaced in the current dependent AST file.
326  DeclsToRewriteTy DeclsToRewrite;
327
328  /// \brief The set of Objective-C class that have categories we
329  /// should serialize.
330  llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
331
332  struct ReplacedDeclInfo {
333    serialization::DeclID ID;
334    uint64_t Offset;
335    unsigned Loc;
336
337    ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {}
338    ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset,
339                     SourceLocation Loc)
340      : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {}
341  };
342
343  /// \brief Decls that have been replaced in the current dependent AST file.
344  ///
345  /// When a decl changes fundamentally after being deserialized (this shouldn't
346  /// happen, but the ObjC AST nodes are designed this way), it will be
347  /// serialized again. In this case, it is registered here, so that the reader
348  /// knows to read the updated version.
349  SmallVector<ReplacedDeclInfo, 16> ReplacedDecls;
350
351  /// \brief The set of declarations that may have redeclaration chains that
352  /// need to be serialized.
353  llvm::SetVector<Decl *, SmallVector<Decl *, 4>,
354                  llvm::SmallPtrSet<Decl *, 4> > Redeclarations;
355
356  /// \brief Statements that we've encountered while serializing a
357  /// declaration or type.
358  SmallVector<Stmt *, 16> StmtsToEmit;
359
360  /// \brief Statements collection to use for ASTWriter::AddStmt().
361  /// It will point to StmtsToEmit unless it is overriden.
362  SmallVector<Stmt *, 16> *CollectedStmts;
363
364  /// \brief Mapping from SwitchCase statements to IDs.
365  llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
366
367  /// \brief The number of statements written to the AST file.
368  unsigned NumStatements;
369
370  /// \brief The number of macros written to the AST file.
371  unsigned NumMacros;
372
373  /// \brief The number of lexical declcontexts written to the AST
374  /// file.
375  unsigned NumLexicalDeclContexts;
376
377  /// \brief The number of visible declcontexts written to the AST
378  /// file.
379  unsigned NumVisibleDeclContexts;
380
381  /// \brief The offset of each CXXBaseSpecifier set within the AST.
382  SmallVector<uint32_t, 4> CXXBaseSpecifiersOffsets;
383
384  /// \brief The first ID number we can use for our own base specifiers.
385  serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID;
386
387  /// \brief The base specifiers ID that will be assigned to the next new
388  /// set of C++ base specifiers.
389  serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID;
390
391  /// \brief A set of C++ base specifiers that is queued to be written into the
392  /// AST file.
393  struct QueuedCXXBaseSpecifiers {
394    QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { }
395
396    QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID,
397                            CXXBaseSpecifier const *Bases,
398                            CXXBaseSpecifier const *BasesEnd)
399      : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { }
400
401    serialization::CXXBaseSpecifiersID ID;
402    CXXBaseSpecifier const * Bases;
403    CXXBaseSpecifier const * BasesEnd;
404  };
405
406  /// \brief Queue of C++ base specifiers to be written to the AST file,
407  /// in the order they should be written.
408  SmallVector<QueuedCXXBaseSpecifiers, 2> CXXBaseSpecifiersToWrite;
409
410  /// \brief A mapping from each known submodule to its ID number, which will
411  /// be a positive integer.
412  llvm::DenseMap<Module *, unsigned> SubmoduleIDs;
413
414  /// \brief Retrieve or create a submodule ID for this module.
415  unsigned getSubmoduleID(Module *Mod);
416
417  /// \brief Write the given subexpression to the bitstream.
418  void WriteSubStmt(Stmt *S,
419                    llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntries,
420                    llvm::DenseSet<Stmt *> &ParentStmts);
421
422  void WriteBlockInfoBlock();
423  void WriteControlBlock(Preprocessor &PP, ASTContext &Context,
424                         StringRef isysroot, const std::string &OutputFile);
425  void WriteInputFiles(SourceManager &SourceMgr,
426                       HeaderSearchOptions &HSOpts,
427                       StringRef isysroot,
428                       bool Modules);
429  void WriteSourceManagerBlock(SourceManager &SourceMgr,
430                               const Preprocessor &PP,
431                               StringRef isysroot);
432  void WritePreprocessor(const Preprocessor &PP, bool IsModule);
433  void WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot);
434  void WritePreprocessorDetail(PreprocessingRecord &PPRec);
435  void WriteSubmodules(Module *WritingModule);
436
437  void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
438                                     bool isModule);
439  void WriteCXXBaseSpecifiersOffsets();
440  void WriteType(QualType T);
441  uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
442  uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
443  void WriteTypeDeclOffsets();
444  void WriteFileDeclIDsMap();
445  void WriteComments();
446  void WriteSelectors(Sema &SemaRef);
447  void WriteReferencedSelectorsPool(Sema &SemaRef);
448  void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver,
449                            bool IsModule);
450  void WriteAttributes(ArrayRef<const Attr*> Attrs, RecordDataImpl &Record);
451  void ResolveDeclUpdatesBlocks();
452  void WriteDeclUpdatesBlocks();
453  void WriteDeclReplacementsBlock();
454  void WriteDeclContextVisibleUpdate(const DeclContext *DC);
455  void WriteFPPragmaOptions(const FPOptions &Opts);
456  void WriteOpenCLExtensions(Sema &SemaRef);
457  void WriteObjCCategories();
458  void WriteRedeclarations();
459  void WriteMergedDecls();
460  void WriteLateParsedTemplates(Sema &SemaRef);
461
462  unsigned DeclParmVarAbbrev;
463  unsigned DeclContextLexicalAbbrev;
464  unsigned DeclContextVisibleLookupAbbrev;
465  unsigned UpdateVisibleAbbrev;
466  unsigned DeclRefExprAbbrev;
467  unsigned CharacterLiteralAbbrev;
468  unsigned DeclRecordAbbrev;
469  unsigned IntegerLiteralAbbrev;
470  unsigned DeclTypedefAbbrev;
471  unsigned DeclVarAbbrev;
472  unsigned DeclFieldAbbrev;
473  unsigned DeclEnumAbbrev;
474  unsigned DeclObjCIvarAbbrev;
475
476  void WriteDeclsBlockAbbrevs();
477  void WriteDecl(ASTContext &Context, Decl *D);
478
479  void WriteASTCore(Sema &SemaRef,
480                    StringRef isysroot, const std::string &OutputFile,
481                    Module *WritingModule);
482
483public:
484  /// \brief Create a new precompiled header writer that outputs to
485  /// the given bitstream.
486  ASTWriter(llvm::BitstreamWriter &Stream);
487  ~ASTWriter();
488
489  /// \brief Write a precompiled header for the given semantic analysis.
490  ///
491  /// \param SemaRef a reference to the semantic analysis object that processed
492  /// the AST to be written into the precompiled header.
493  ///
494  /// \param WritingModule The module that we are writing. If null, we are
495  /// writing a precompiled header.
496  ///
497  /// \param isysroot if non-empty, write a relocatable file whose headers
498  /// are relative to the given system root.
499  void WriteAST(Sema &SemaRef,
500                const std::string &OutputFile,
501                Module *WritingModule, StringRef isysroot,
502                bool hasErrors = false);
503
504  /// \brief Emit a token.
505  void AddToken(const Token &Tok, RecordDataImpl &Record);
506
507  /// \brief Emit a source location.
508  void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
509
510  /// \brief Emit a source range.
511  void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
512
513  /// \brief Emit an integral value.
514  void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record);
515
516  /// \brief Emit a signed integral value.
517  void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record);
518
519  /// \brief Emit a floating-point value.
520  void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record);
521
522  /// \brief Emit a reference to an identifier.
523  void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
524
525  /// \brief Emit a Selector (which is a smart pointer reference).
526  void AddSelectorRef(Selector, RecordDataImpl &Record);
527
528  /// \brief Emit a CXXTemporary.
529  void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record);
530
531  /// \brief Emit a set of C++ base specifiers to the record.
532  void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
533                               CXXBaseSpecifier const *BasesEnd,
534                               RecordDataImpl &Record);
535
536  /// \brief Get the unique number used to refer to the given selector.
537  serialization::SelectorID getSelectorRef(Selector Sel);
538
539  /// \brief Get the unique number used to refer to the given identifier.
540  serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
541
542  /// \brief Get the unique number used to refer to the given macro.
543  serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
544
545  /// \brief Determine the ID of an already-emitted macro.
546  serialization::MacroID getMacroID(MacroInfo *MI);
547
548  uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
549
550  /// \brief Emit a reference to a type.
551  void AddTypeRef(QualType T, RecordDataImpl &Record);
552
553  /// \brief Force a type to be emitted and get its ID.
554  serialization::TypeID GetOrCreateTypeID(QualType T);
555
556  /// \brief Determine the type ID of an already-emitted type.
557  serialization::TypeID getTypeID(QualType T) const;
558
559  /// \brief Force a type to be emitted and get its index.
560  serialization::TypeIdx GetOrCreateTypeIdx( QualType T);
561
562  /// \brief Determine the type index of an already-emitted type.
563  serialization::TypeIdx getTypeIdx(QualType T) const;
564
565  /// \brief Emits a reference to a declarator info.
566  void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record);
567
568  /// \brief Emits a type with source-location information.
569  void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record);
570
571  /// \brief Emits a template argument location info.
572  void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
573                                  const TemplateArgumentLocInfo &Arg,
574                                  RecordDataImpl &Record);
575
576  /// \brief Emits a template argument location.
577  void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
578                              RecordDataImpl &Record);
579
580  /// \brief Emits an AST template argument list info.
581  void AddASTTemplateArgumentListInfo(
582                          const ASTTemplateArgumentListInfo *ASTTemplArgList,
583                          RecordDataImpl &Record);
584
585  /// \brief Emit a reference to a declaration.
586  void AddDeclRef(const Decl *D, RecordDataImpl &Record);
587
588
589  /// \brief Force a declaration to be emitted and get its ID.
590  serialization::DeclID GetDeclRef(const Decl *D);
591
592  /// \brief Determine the declaration ID of an already-emitted
593  /// declaration.
594  serialization::DeclID getDeclID(const Decl *D);
595
596  /// \brief Emit a declaration name.
597  void AddDeclarationName(DeclarationName Name, RecordDataImpl &Record);
598  void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
599                             DeclarationName Name, RecordDataImpl &Record);
600  void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
601                              RecordDataImpl &Record);
602
603  void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record);
604
605  /// \brief Emit a nested name specifier.
606  void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record);
607
608  /// \brief Emit a nested name specifier with source-location information.
609  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
610                                 RecordDataImpl &Record);
611
612  /// \brief Emit a template name.
613  void AddTemplateName(TemplateName Name, RecordDataImpl &Record);
614
615  /// \brief Emit a template argument.
616  void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record);
617
618  /// \brief Emit a template parameter list.
619  void AddTemplateParameterList(const TemplateParameterList *TemplateParams,
620                                RecordDataImpl &Record);
621
622  /// \brief Emit a template argument list.
623  void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
624                                RecordDataImpl &Record);
625
626  /// \brief Emit a UnresolvedSet structure.
627  void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record);
628
629  /// \brief Emit a C++ base specifier.
630  void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
631                           RecordDataImpl &Record);
632
633  /// \brief Emit a CXXCtorInitializer array.
634  void AddCXXCtorInitializers(
635                             const CXXCtorInitializer * const *CtorInitializers,
636                             unsigned NumCtorInitializers,
637                             RecordDataImpl &Record);
638
639  void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record);
640
641  /// \brief Add a string to the given record.
642  void AddString(StringRef Str, RecordDataImpl &Record);
643
644  /// \brief Add a version tuple to the given record
645  void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
646
647  /// \brief Mark a declaration context as needing an update.
648  void AddUpdatedDeclContext(const DeclContext *DC) {
649    UpdatedDeclContexts.insert(DC);
650  }
651
652  void RewriteDecl(const Decl *D) {
653    DeclsToRewrite.insert(D);
654  }
655
656  bool isRewritten(const Decl *D) const {
657    return DeclsToRewrite.count(D);
658  }
659
660  /// \brief Infer the submodule ID that contains an entity at the given
661  /// source location.
662  serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
663
664  /// \brief Retrieve a submodule ID for this module.
665  /// Returns 0 If no ID has been associated with the module.
666  unsigned getExistingSubmoduleID(Module *Mod) const;
667
668  /// \brief Note that the identifier II occurs at the given offset
669  /// within the identifier table.
670  void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
671
672  /// \brief Note that the selector Sel occurs at the given offset
673  /// within the method pool/selector table.
674  void SetSelectorOffset(Selector Sel, uint32_t Offset);
675
676  /// \brief Add the given statement or expression to the queue of
677  /// statements to emit.
678  ///
679  /// This routine should be used when emitting types and declarations
680  /// that have expressions as part of their formulation. Once the
681  /// type or declaration has been written, call FlushStmts() to write
682  /// the corresponding statements just after the type or
683  /// declaration.
684  void AddStmt(Stmt *S) {
685      CollectedStmts->push_back(S);
686  }
687
688  /// \brief Flush all of the statements and expressions that have
689  /// been added to the queue via AddStmt().
690  void FlushStmts();
691
692  /// \brief Flush all of the C++ base specifier sets that have been added
693  /// via \c AddCXXBaseSpecifiersRef().
694  void FlushCXXBaseSpecifiers();
695
696  /// \brief Record an ID for the given switch-case statement.
697  unsigned RecordSwitchCaseID(SwitchCase *S);
698
699  /// \brief Retrieve the ID for the given switch-case statement.
700  unsigned getSwitchCaseID(SwitchCase *S);
701
702  void ClearSwitchCaseIDs();
703
704  unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
705  unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
706  unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
707  unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
708  unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
709  unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
710  unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
711  unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
712  unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
713  unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
714
715  bool hasChain() const { return Chain; }
716
717  // ASTDeserializationListener implementation
718  void ReaderInitialized(ASTReader *Reader);
719  void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II);
720  void MacroRead(serialization::MacroID ID, MacroInfo *MI);
721  void TypeRead(serialization::TypeIdx Idx, QualType T);
722  void SelectorRead(serialization::SelectorID ID, Selector Sel);
723  void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
724                           MacroDefinition *MD);
725  void ModuleRead(serialization::SubmoduleID ID, Module *Mod);
726
727  // ASTMutationListener implementation.
728  virtual void CompletedTagDefinition(const TagDecl *D);
729  virtual void AddedVisibleDecl(const DeclContext *DC, const Decl *D);
730  virtual void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D);
731  virtual void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
732                                    const ClassTemplateSpecializationDecl *D);
733  virtual void
734  AddedCXXTemplateSpecialization(const VarTemplateDecl *TD,
735                                 const VarTemplateSpecializationDecl *D);
736  virtual void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
737                                              const FunctionDecl *D);
738  virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType);
739  virtual void CompletedImplicitDefinition(const FunctionDecl *D);
740  virtual void StaticDataMemberInstantiated(const VarDecl *D);
741  virtual void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
742                                            const ObjCInterfaceDecl *IFD);
743  virtual void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
744                                            const ObjCPropertyDecl *OrigProp,
745                                            const ObjCCategoryDecl *ClassExt);
746  void DeclarationMarkedUsed(const Decl *D) LLVM_OVERRIDE;
747};
748
749/// \brief AST and semantic-analysis consumer that generates a
750/// precompiled header from the parsed source code.
751class PCHGenerator : public SemaConsumer {
752  const Preprocessor &PP;
753  std::string OutputFile;
754  clang::Module *Module;
755  std::string isysroot;
756  raw_ostream *Out;
757  Sema *SemaPtr;
758  SmallVector<char, 128> Buffer;
759  llvm::BitstreamWriter Stream;
760  ASTWriter Writer;
761  bool AllowASTWithErrors;
762  bool HasEmittedPCH;
763
764protected:
765  ASTWriter &getWriter() { return Writer; }
766  const ASTWriter &getWriter() const { return Writer; }
767
768public:
769  PCHGenerator(const Preprocessor &PP, StringRef OutputFile,
770               clang::Module *Module,
771               StringRef isysroot, raw_ostream *Out,
772               bool AllowASTWithErrors = false);
773  ~PCHGenerator();
774  virtual void InitializeSema(Sema &S) { SemaPtr = &S; }
775  virtual void HandleTranslationUnit(ASTContext &Ctx);
776  virtual ASTMutationListener *GetASTMutationListener();
777  virtual ASTDeserializationListener *GetASTDeserializationListener();
778
779  bool hasEmittedPCH() const { return HasEmittedPCH; }
780};
781
782} // end namespace clang
783
784#endif
785