GeneratePCH.cpp revision 10e286aa8d39fb51a21412850265d9dae74613ee
1//===--- GeneratePCH.cpp - AST 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 CreatePCHGenerate function, which creates an
11//  ASTConsumer that generates a PCH file.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Frontend/ASTConsumers.h"
16#include "clang/Serialization/ASTWriter.h"
17#include "clang/Sema/SemaConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTConsumer.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Basic/FileManager.h"
22#include "clang/Basic/FileSystemStatCache.h"
23#include "llvm/Bitcode/BitstreamWriter.h"
24#include "llvm/Support/raw_ostream.h"
25#include <string>
26
27using namespace clang;
28
29PCHGenerator::PCHGenerator(const Preprocessor &PP,
30                           bool Chaining,
31                           const char *isysroot,
32                           llvm::raw_ostream *OS)
33  : PP(PP), isysroot(isysroot), Out(OS), SemaPtr(0),
34    StatCalls(0), Stream(Buffer), Writer(Stream), Chaining(Chaining) {
35
36  // Install a stat() listener to keep track of all of the stat()
37  // calls.
38  StatCalls = new MemorizeStatCalls();
39  // If we have a chain, we want new stat calls only, so install the memorizer
40  // *after* the already installed ASTReader's stat cache.
41  PP.getFileManager().addStatCache(StatCalls,
42    /*AtBeginning=*/!Chaining);
43}
44
45void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) {
46  if (PP.getDiagnostics().hasErrorOccurred())
47    return;
48
49  // Emit the PCH file
50  assert(SemaPtr && "No Sema?");
51  Writer.WriteAST(*SemaPtr, StatCalls, isysroot);
52
53  // Write the generated bitstream to "Out".
54  Out->write((char *)&Buffer.front(), Buffer.size());
55
56  // Make sure it hits disk now.
57  Out->flush();
58
59  // Free up some memory, in case the process is kept alive.
60  Buffer.clear();
61}
62
63ASTMutationListener *PCHGenerator::GetASTMutationListener() {
64  if (Chaining)
65    return &Writer;
66  return 0;
67}
68
69ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() {
70  return &Writer;
71}
72