1235633Sdim//===--- GeneratePCH.cpp - Sema Consumer for PCH Generation -----*- C++ -*-===// 2212795Sdim// 3212795Sdim// The LLVM Compiler Infrastructure 4212795Sdim// 5212795Sdim// This file is distributed under the University of Illinois Open Source 6212795Sdim// License. See LICENSE.TXT for details. 7212795Sdim// 8212795Sdim//===----------------------------------------------------------------------===// 9212795Sdim// 10235633Sdim// This file defines the PCHGenerator, which as a SemaConsumer that generates 11235633Sdim// a PCH file. 12212795Sdim// 13212795Sdim//===----------------------------------------------------------------------===// 14212795Sdim 15212795Sdim#include "clang/Serialization/ASTWriter.h" 16252723Sdim#include "clang/AST/ASTConsumer.h" 17212795Sdim#include "clang/AST/ASTContext.h" 18252723Sdim#include "clang/Basic/FileManager.h" 19212795Sdim#include "clang/Lex/Preprocessor.h" 20252723Sdim#include "clang/Sema/SemaConsumer.h" 21212795Sdim#include "llvm/Bitcode/BitstreamWriter.h" 22212795Sdim#include "llvm/Support/raw_ostream.h" 23212795Sdim#include <string> 24212795Sdim 25212795Sdimusing namespace clang; 26212795Sdim 27212795SdimPCHGenerator::PCHGenerator(const Preprocessor &PP, 28226890Sdim StringRef OutputFile, 29235633Sdim clang::Module *Module, 30226890Sdim StringRef isysroot, 31263509Sdim raw_ostream *OS, bool AllowASTWithErrors) 32235633Sdim : PP(PP), OutputFile(OutputFile), Module(Module), 33226890Sdim isysroot(isysroot.str()), Out(OS), 34263509Sdim SemaPtr(0), Stream(Buffer), Writer(Stream), 35263509Sdim AllowASTWithErrors(AllowASTWithErrors), 36263509Sdim HasEmittedPCH(false) { 37212795Sdim} 38212795Sdim 39226890SdimPCHGenerator::~PCHGenerator() { 40226890Sdim} 41226890Sdim 42212795Sdimvoid PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) { 43263509Sdim // Don't create a PCH if there were fatal failures during module loading. 44263509Sdim if (PP.getModuleLoader().HadFatalFailure) 45212795Sdim return; 46263509Sdim 47263509Sdim bool hasErrors = PP.getDiagnostics().hasErrorOccurred(); 48263509Sdim if (hasErrors && !AllowASTWithErrors) 49263509Sdim return; 50218893Sdim 51212795Sdim // Emit the PCH file 52212795Sdim assert(SemaPtr && "No Sema?"); 53263509Sdim Writer.WriteAST(*SemaPtr, OutputFile, Module, isysroot, hasErrors); 54212795Sdim 55212795Sdim // Write the generated bitstream to "Out". 56212795Sdim Out->write((char *)&Buffer.front(), Buffer.size()); 57212795Sdim 58212795Sdim // Make sure it hits disk now. 59212795Sdim Out->flush(); 60212795Sdim 61212795Sdim // Free up some memory, in case the process is kept alive. 62212795Sdim Buffer.clear(); 63263509Sdim 64263509Sdim HasEmittedPCH = true; 65212795Sdim} 66212795Sdim 67218893SdimASTMutationListener *PCHGenerator::GetASTMutationListener() { 68226890Sdim return &Writer; 69218893Sdim} 70218893Sdim 71212795SdimASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() { 72212795Sdim return &Writer; 73212795Sdim} 74