blob: 9b8651408678b472037f0a9c16cda3b10a46ed9d [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- 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
Chris Lattner0b1fb982009-04-10 17:15:23 +000015#include "ASTConsumers.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000016#include "clang/Frontend/PCHWriter.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTConsumer.h"
Chris Lattner0b1fb982009-04-10 17:15:23 +000019#include "clang/Lex/Preprocessor.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "llvm/Bitcode/BitstreamWriter.h"
21#include "llvm/System/Path.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/raw_ostream.h"
24#include "llvm/Support/Streams.h"
25#include <string>
26
27using namespace clang;
28using namespace llvm;
29
30namespace {
31 class VISIBILITY_HIDDEN PCHGenerator : public ASTConsumer {
Chris Lattnerdf961c22009-04-10 18:08:30 +000032 const Preprocessor &PP;
Douglas Gregor2cf26342009-04-09 22:27:44 +000033 std::string OutFile;
34
35 public:
Chris Lattnerdf961c22009-04-10 18:08:30 +000036 explicit PCHGenerator(const Preprocessor &PP, const std::string &OutFile)
Chris Lattner0b1fb982009-04-10 17:15:23 +000037 : PP(PP), OutFile(OutFile) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +000038
39 virtual void HandleTranslationUnit(ASTContext &Ctx);
40 };
41}
42
43void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) {
Chris Lattner0b1fb982009-04-10 17:15:23 +000044 if (PP.getDiagnostics().hasErrorOccurred())
Douglas Gregor2cf26342009-04-09 22:27:44 +000045 return;
46
47 // Write the PCH contents into a buffer
48 std::vector<unsigned char> Buffer;
49 BitstreamWriter Stream(Buffer);
50 PCHWriter Writer(Stream);
51
52 // Emit the PCH file
Chris Lattner0b1fb982009-04-10 17:15:23 +000053 Writer.WritePCH(Ctx, PP);
Douglas Gregor2cf26342009-04-09 22:27:44 +000054
55 // Open up the PCH file.
56 std::string ErrMsg;
57 llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg);
58
59 if (!ErrMsg.empty()) {
60 llvm::errs() << "PCH error: " << ErrMsg << "\n";
61 return;
62 }
63
64 // Write the generated bitstream to "Out".
65 Out.write((char *)&Buffer.front(), Buffer.size());
66
67 // Make sure it hits disk now.
68 Out.flush();
69}
70
Chris Lattnerdf961c22009-04-10 18:08:30 +000071ASTConsumer *clang::CreatePCHGenerator(const Preprocessor &PP,
Chris Lattner0b1fb982009-04-10 17:15:23 +000072 const std::string &OutFile) {
73 return new PCHGenerator(PP, OutFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +000074}