1bc068586SAdrian Prantl //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
2bc068586SAdrian Prantl //
3bc068586SAdrian Prantl //                     The LLVM Compiler Infrastructure
4bc068586SAdrian Prantl //
5bc068586SAdrian Prantl // This file is distributed under the University of Illinois Open Source
6bc068586SAdrian Prantl // License. See LICENSE.TXT for details.
7bc068586SAdrian Prantl //
8bc068586SAdrian Prantl //===----------------------------------------------------------------------===//
9bc068586SAdrian Prantl 
10bc068586SAdrian Prantl #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
11bc068586SAdrian Prantl #include "CGDebugInfo.h"
12bc068586SAdrian Prantl #include "CodeGenModule.h"
13bc068586SAdrian Prantl #include "clang/AST/ASTContext.h"
14bc068586SAdrian Prantl #include "clang/AST/DeclObjC.h"
15bc068586SAdrian Prantl #include "clang/AST/Expr.h"
16bc068586SAdrian Prantl #include "clang/AST/RecursiveASTVisitor.h"
17bc068586SAdrian Prantl #include "clang/Basic/Diagnostic.h"
18bc068586SAdrian Prantl #include "clang/Basic/TargetInfo.h"
19bc068586SAdrian Prantl #include "clang/CodeGen/BackendUtil.h"
20bc068586SAdrian Prantl #include "clang/Frontend/CodeGenOptions.h"
21bc068586SAdrian Prantl #include "clang/Serialization/ASTWriter.h"
22bc068586SAdrian Prantl #include "llvm/ADT/StringRef.h"
23bc068586SAdrian Prantl #include "llvm/Bitcode/BitstreamReader.h"
24bc068586SAdrian Prantl #include "llvm/DebugInfo/DWARF/DWARFContext.h"
25bc068586SAdrian Prantl #include "llvm/IR/Constants.h"
26bc068586SAdrian Prantl #include "llvm/IR/DataLayout.h"
27bc068586SAdrian Prantl #include "llvm/IR/LLVMContext.h"
28bc068586SAdrian Prantl #include "llvm/IR/Module.h"
29bc068586SAdrian Prantl #include "llvm/Object/COFF.h"
30bc068586SAdrian Prantl #include "llvm/Object/ObjectFile.h"
31bc068586SAdrian Prantl #include "llvm/Support/TargetRegistry.h"
32bc068586SAdrian Prantl #include <memory>
33bc068586SAdrian Prantl using namespace clang;
34bc068586SAdrian Prantl 
35bc068586SAdrian Prantl #define DEBUG_TYPE "pchcontainer"
36bc068586SAdrian Prantl 
37bc068586SAdrian Prantl namespace {
385a88e1a8SAdrian Prantl class PCHContainerGenerator : public ASTConsumer {
39bc068586SAdrian Prantl   DiagnosticsEngine &Diags;
40bc068586SAdrian Prantl   const std::string MainFileName;
41bc068586SAdrian Prantl   ASTContext *Ctx;
42bc068586SAdrian Prantl   const HeaderSearchOptions &HeaderSearchOpts;
43bc068586SAdrian Prantl   const PreprocessorOptions &PreprocessorOpts;
44bc068586SAdrian Prantl   CodeGenOptions CodeGenOpts;
45bc068586SAdrian Prantl   const TargetOptions TargetOpts;
46bc068586SAdrian Prantl   const LangOptions LangOpts;
47bc068586SAdrian Prantl   std::unique_ptr<llvm::LLVMContext> VMContext;
48bc068586SAdrian Prantl   std::unique_ptr<llvm::Module> M;
49bc068586SAdrian Prantl   std::unique_ptr<CodeGen::CodeGenModule> Builder;
50bc068586SAdrian Prantl   raw_pwrite_stream *OS;
51bc068586SAdrian Prantl   std::shared_ptr<PCHBuffer> Buffer;
52bc068586SAdrian Prantl 
53bc068586SAdrian Prantl public:
545a88e1a8SAdrian Prantl   PCHContainerGenerator(DiagnosticsEngine &diags,
555a88e1a8SAdrian Prantl                         const HeaderSearchOptions &HSO,
565a88e1a8SAdrian Prantl                         const PreprocessorOptions &PPO, const TargetOptions &TO,
575a88e1a8SAdrian Prantl                         const LangOptions &LO, const std::string &MainFileName,
585a88e1a8SAdrian Prantl                         const std::string &OutputFileName,
595a88e1a8SAdrian Prantl                         raw_pwrite_stream *OS,
605a88e1a8SAdrian Prantl                         std::shared_ptr<PCHBuffer> Buffer)
61bc068586SAdrian Prantl       : Diags(diags), HeaderSearchOpts(HSO), PreprocessorOpts(PPO),
625a88e1a8SAdrian Prantl         TargetOpts(TO), LangOpts(LO), OS(OS), Buffer(Buffer) {
63bc068586SAdrian Prantl     // The debug info output isn't affected by CodeModel and
64bc068586SAdrian Prantl     // ThreadModel, but the backend expects them to be nonempty.
65bc068586SAdrian Prantl     CodeGenOpts.CodeModel = "default";
66bc068586SAdrian Prantl     CodeGenOpts.ThreadModel = "single";
67bc068586SAdrian Prantl     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
68bc068586SAdrian Prantl     CodeGenOpts.SplitDwarfFile = OutputFileName;
69bc068586SAdrian Prantl   }
70bc068586SAdrian Prantl 
715a88e1a8SAdrian Prantl   virtual ~PCHContainerGenerator() {}
72bc068586SAdrian Prantl 
73bc068586SAdrian Prantl   void Initialize(ASTContext &Context) override {
74bc068586SAdrian Prantl     Ctx = &Context;
75bc068586SAdrian Prantl     VMContext.reset(new llvm::LLVMContext());
76bc068586SAdrian Prantl     M.reset(new llvm::Module(MainFileName, *VMContext));
77bc068586SAdrian Prantl     M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
78*ca3cf9e6SMehdi Amini     Builder.reset(new CodeGen::CodeGenModule(
79*ca3cf9e6SMehdi Amini         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
80bc068586SAdrian Prantl   }
81bc068586SAdrian Prantl 
82bc068586SAdrian Prantl   /// Emit a container holding the serialized AST.
83bc068586SAdrian Prantl   void HandleTranslationUnit(ASTContext &Ctx) override {
84bc068586SAdrian Prantl     assert(M && VMContext && Builder);
85bc068586SAdrian Prantl     // Delete these on function exit.
86bc068586SAdrian Prantl     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
87bc068586SAdrian Prantl     std::unique_ptr<llvm::Module> M = std::move(this->M);
88bc068586SAdrian Prantl     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
89bc068586SAdrian Prantl 
90bc068586SAdrian Prantl     if (Diags.hasErrorOccurred())
91bc068586SAdrian Prantl       return;
92bc068586SAdrian Prantl 
93bc068586SAdrian Prantl     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
94bc068586SAdrian Prantl     M->setDataLayout(Ctx.getTargetInfo().getTargetDescription());
95bc068586SAdrian Prantl 
96bc068586SAdrian Prantl     // Finalize the Builder.
97bc068586SAdrian Prantl     if (Builder)
98bc068586SAdrian Prantl       Builder->Release();
99bc068586SAdrian Prantl 
100bc068586SAdrian Prantl     // Ensure the target exists.
101bc068586SAdrian Prantl     std::string Error;
102bc068586SAdrian Prantl     auto Triple = Ctx.getTargetInfo().getTriple();
103bc068586SAdrian Prantl     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
104bc068586SAdrian Prantl       llvm::report_fatal_error(Error);
105bc068586SAdrian Prantl 
106bc068586SAdrian Prantl     // Emit the serialized Clang AST into its own section.
107bc068586SAdrian Prantl     assert(Buffer->IsComplete && "serialization did not complete");
108bc068586SAdrian Prantl     auto &SerializedAST = Buffer->Data;
109bc068586SAdrian Prantl     auto Size = SerializedAST.size();
110bc068586SAdrian Prantl     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
111bc068586SAdrian Prantl     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
1125a88e1a8SAdrian Prantl     auto *Data = llvm::ConstantDataArray::getString(
1135a88e1a8SAdrian Prantl         *VMContext, StringRef(SerializedAST.data(), Size),
114bc068586SAdrian Prantl         /*AddNull=*/false);
115bc068586SAdrian Prantl     auto *ASTSym = new llvm::GlobalVariable(
116bc068586SAdrian Prantl         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
117bc068586SAdrian Prantl         "__clang_ast");
118bc068586SAdrian Prantl     // The on-disk hashtable needs to be aligned.
119bc068586SAdrian Prantl     ASTSym->setAlignment(8);
120bc068586SAdrian Prantl 
121bc068586SAdrian Prantl     // Mach-O also needs a segment name.
122bc068586SAdrian Prantl     if (Triple.isOSBinFormatMachO())
123bc068586SAdrian Prantl       ASTSym->setSection("__CLANG,__clangast");
124bc068586SAdrian Prantl     // COFF has an eight character length limit.
125bc068586SAdrian Prantl     else if (Triple.isOSBinFormatCOFF())
126bc068586SAdrian Prantl       ASTSym->setSection("clangast");
127bc068586SAdrian Prantl     else
128bc068586SAdrian Prantl       ASTSym->setSection("__clangast");
129bc068586SAdrian Prantl 
130bc068586SAdrian Prantl     DEBUG({
131bc068586SAdrian Prantl       // Print the IR for the PCH container to the debug output.
132bc068586SAdrian Prantl       llvm::SmallString<0> Buffer;
133bc068586SAdrian Prantl       llvm::raw_svector_ostream OS(Buffer);
134bc068586SAdrian Prantl       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
135bc068586SAdrian Prantl                                Ctx.getTargetInfo().getTargetDescription(),
136bc068586SAdrian Prantl                                M.get(), BackendAction::Backend_EmitLL, &OS);
137bc068586SAdrian Prantl       OS.flush();
138bc068586SAdrian Prantl       llvm::dbgs() << Buffer;
139bc068586SAdrian Prantl     });
140bc068586SAdrian Prantl 
141bc068586SAdrian Prantl     // Use the LLVM backend to emit the pch container.
142bc068586SAdrian Prantl     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
143bc068586SAdrian Prantl                              Ctx.getTargetInfo().getTargetDescription(),
144bc068586SAdrian Prantl                              M.get(), BackendAction::Backend_EmitObj, OS);
145bc068586SAdrian Prantl 
146bc068586SAdrian Prantl     // Make sure the pch container hits disk.
147bc068586SAdrian Prantl     OS->flush();
148bc068586SAdrian Prantl 
149bc068586SAdrian Prantl     // Free the memory for the temporary buffer.
150bc068586SAdrian Prantl     llvm::SmallVector<char, 0> Empty;
151bc068586SAdrian Prantl     SerializedAST = std::move(Empty);
152bc068586SAdrian Prantl   }
153bc068586SAdrian Prantl };
1545a88e1a8SAdrian Prantl 
1555a88e1a8SAdrian Prantl } // namespace
156bc068586SAdrian Prantl 
157bc068586SAdrian Prantl std::unique_ptr<ASTConsumer>
158fb2398d0SAdrian Prantl ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
159bc068586SAdrian Prantl     DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
160bc068586SAdrian Prantl     const PreprocessorOptions &PPO, const TargetOptions &TO,
161bc068586SAdrian Prantl     const LangOptions &LO, const std::string &MainFileName,
162bc068586SAdrian Prantl     const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
163bc068586SAdrian Prantl     std::shared_ptr<PCHBuffer> Buffer) const {
1645a88e1a8SAdrian Prantl   return llvm::make_unique<PCHContainerGenerator>(
1655a88e1a8SAdrian Prantl       Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer);
166bc068586SAdrian Prantl }
167bc068586SAdrian Prantl 
168fb2398d0SAdrian Prantl void ObjectFilePCHContainerReader::ExtractPCH(
169bc068586SAdrian Prantl     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
170bc068586SAdrian Prantl   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
171bc068586SAdrian Prantl     auto *Obj = OF.get().get();
172bc068586SAdrian Prantl     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
173bc068586SAdrian Prantl     // Find the clang AST section in the container.
174bc068586SAdrian Prantl     for (auto &Section : OF->get()->sections()) {
175bc068586SAdrian Prantl       StringRef Name;
176bc068586SAdrian Prantl       Section.getName(Name);
177bc068586SAdrian Prantl       if ((!IsCOFF && Name == "__clangast") ||
178bc068586SAdrian Prantl           ( IsCOFF && Name ==   "clangast")) {
179bc068586SAdrian Prantl         StringRef Buf;
180bc068586SAdrian Prantl         Section.getContents(Buf);
181bc068586SAdrian Prantl         StreamFile.init((const unsigned char *)Buf.begin(),
182bc068586SAdrian Prantl                         (const unsigned char *)Buf.end());
183bc068586SAdrian Prantl         return;
184bc068586SAdrian Prantl       }
185bc068586SAdrian Prantl     }
186bc068586SAdrian Prantl   }
187bc068586SAdrian Prantl 
188bc068586SAdrian Prantl   // As a fallback, treat the buffer as a raw AST.
189bc068586SAdrian Prantl   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
190bc068586SAdrian Prantl                   (const unsigned char *)Buffer.getBufferEnd());
191bc068586SAdrian Prantl   return;
192bc068586SAdrian Prantl }
193