GeneratePCH.cpp revision 4947e25dd9f7ac1f2176d63262563ba3e96538fe
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#include <string.h> 27#include <stdlib.h> 28 29using namespace clang; 30 31PCHGenerator::PCHGenerator(const Preprocessor &PP, 32 const std::string &OutputFile, 33 bool Chaining, 34 const char *isysroot, 35 llvm::raw_ostream *OS) 36 : PP(PP), OutputFile(OutputFile), isysroot(0), Out(OS), SemaPtr(0), 37 StatCalls(0), Stream(Buffer), Writer(Stream), Chaining(Chaining) { 38 // Install a stat() listener to keep track of all of the stat() 39 // calls. 40 StatCalls = new MemorizeStatCalls(); 41 // If we have a chain, we want new stat calls only, so install the memorizer 42 // *after* the already installed ASTReader's stat cache. 43 PP.getFileManager().addStatCache(StatCalls, 44 /*AtBeginning=*/!Chaining); 45 46 if (isysroot) 47 this->isysroot = strdup(isysroot); 48} 49 50PCHGenerator::~PCHGenerator() { 51 free((void*)isysroot); 52} 53 54void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) { 55 if (PP.getDiagnostics().hasErrorOccurred()) 56 return; 57 58 // Set up the serialization listener. 59 Writer.SetSerializationListener(GetASTSerializationListener()); 60 61 // Emit the PCH file 62 assert(SemaPtr && "No Sema?"); 63 Writer.WriteAST(*SemaPtr, StatCalls, OutputFile, isysroot); 64 65 // Write the generated bitstream to "Out". 66 Out->write((char *)&Buffer.front(), Buffer.size()); 67 68 // Make sure it hits disk now. 69 Out->flush(); 70 71 // Free up some memory, in case the process is kept alive. 72 Buffer.clear(); 73} 74 75ASTMutationListener *PCHGenerator::GetASTMutationListener() { 76 if (Chaining) 77 return &Writer; 78 return 0; 79} 80 81ASTSerializationListener *PCHGenerator::GetASTSerializationListener() { 82 return 0; 83} 84 85ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() { 86 return &Writer; 87} 88