blob: 6251bac04758550f837892f55d7e13a4e847ef14 [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- 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// ASTConsume that generates a PCH file.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Frontend/ASTConsumers.h"
16#include "clang/Frontend/PCHWriter.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 "llvm/Bitcode/BitstreamWriter.h"
23#include "llvm/Support/raw_ostream.h"
24#include <string>
25
26using namespace clang;
27
28namespace {
29 class PCHGenerator : public SemaConsumer {
30 const Preprocessor &PP;
31 const char *isysroot;
32 llvm::raw_ostream *Out;
33 Sema *SemaPtr;
34 MemorizeStatCalls *StatCalls; // owned by the FileManager
35
36 public:
37 explicit PCHGenerator(const Preprocessor &PP,
38 const char *isysroot,
39 llvm::raw_ostream *Out);
40 virtual void InitializeSema(Sema &S) { SemaPtr = &S; }
41 virtual void HandleTranslationUnit(ASTContext &Ctx);
42 };
43}
44
45PCHGenerator::PCHGenerator(const Preprocessor &PP,
46 const char *isysroot,
47 llvm::raw_ostream *OS)
48 : PP(PP), isysroot(isysroot), Out(OS), SemaPtr(0), StatCalls(0) {
49
50 // Install a stat() listener to keep track of all of the stat()
51 // calls.
52 StatCalls = new MemorizeStatCalls;
53 PP.getFileManager().addStatCache(StatCalls, /*AtBeginning=*/true);
54}
55
56void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) {
57 if (PP.getDiagnostics().hasErrorOccurred())
58 return;
59
60 // Write the PCH contents into a buffer
61 std::vector<unsigned char> Buffer;
62 llvm::BitstreamWriter Stream(Buffer);
63 PCHWriter Writer(Stream);
64
65 // Emit the PCH file
66 assert(SemaPtr && "No Sema?");
67 Writer.WritePCH(*SemaPtr, StatCalls, isysroot);
68
69 // Write the generated bitstream to "Out".
70 Out->write((char *)&Buffer.front(), Buffer.size());
71
72 // Make sure it hits disk now.
73 Out->flush();
74}
75
76ASTConsumer *clang::CreatePCHGenerator(const Preprocessor &PP,
77 llvm::raw_ostream *OS,
78 const char *isysroot) {
79 return new PCHGenerator(PP, isysroot, OS);
80}