1 //===--- GeneratePCH.cpp - Sema Consumer for PCH Generation -----*- 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 PCHGenerator, which as a SemaConsumer that generates
11 // a PCH file.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Serialization/ASTWriter.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Sema/SemaConsumer.h"
21 #include "llvm/Bitcode/BitstreamWriter.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <string>
24
25 using namespace clang;
26
PCHGenerator(const Preprocessor & PP,StringRef OutputFile,clang::Module * Module,StringRef isysroot,raw_ostream * OS)27 PCHGenerator::PCHGenerator(const Preprocessor &PP,
28 StringRef OutputFile,
29 clang::Module *Module,
30 StringRef isysroot,
31 raw_ostream *OS)
32 : PP(PP), OutputFile(OutputFile), Module(Module),
33 isysroot(isysroot.str()), Out(OS),
34 SemaPtr(0), Stream(Buffer), Writer(Stream) {
35 }
36
~PCHGenerator()37 PCHGenerator::~PCHGenerator() {
38 }
39
HandleTranslationUnit(ASTContext & Ctx)40 void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) {
41 if (PP.getDiagnostics().hasErrorOccurred())
42 return;
43
44 // Emit the PCH file
45 assert(SemaPtr && "No Sema?");
46 Writer.WriteAST(*SemaPtr, OutputFile, Module, isysroot);
47
48 // Write the generated bitstream to "Out".
49 Out->write((char *)&Buffer.front(), Buffer.size());
50
51 // Make sure it hits disk now.
52 Out->flush();
53
54 // Free up some memory, in case the process is kept alive.
55 Buffer.clear();
56 }
57
GetPPMutationListener()58 PPMutationListener *PCHGenerator::GetPPMutationListener() {
59 return &Writer;
60 }
61
GetASTMutationListener()62 ASTMutationListener *PCHGenerator::GetASTMutationListener() {
63 return &Writer;
64 }
65
GetASTDeserializationListener()66 ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() {
67 return &Writer;
68 }
69