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 
53*4aa2b3a3SAdrian Prantl   /// Visit every type and emit debug info for it.
54*4aa2b3a3SAdrian Prantl   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
55*4aa2b3a3SAdrian Prantl     clang::CodeGen::CGDebugInfo &DI;
56*4aa2b3a3SAdrian Prantl     ASTContext &Ctx;
57*4aa2b3a3SAdrian Prantl     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
58*4aa2b3a3SAdrian Prantl         : DI(DI), Ctx(Ctx) {}
59*4aa2b3a3SAdrian Prantl 
60*4aa2b3a3SAdrian Prantl     /// Determine whether this type can be represented in DWARF.
61*4aa2b3a3SAdrian Prantl     static bool CanRepresent(const Type *Ty) {
62*4aa2b3a3SAdrian Prantl       return !Ty->isDependentType() && !Ty->isUndeducedType();
63*4aa2b3a3SAdrian Prantl     }
64*4aa2b3a3SAdrian Prantl 
65*4aa2b3a3SAdrian Prantl     bool VisitTypeDecl(TypeDecl *D) {
66*4aa2b3a3SAdrian Prantl       QualType QualTy = Ctx.getTypeDeclType(D);
67*4aa2b3a3SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
68*4aa2b3a3SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
69*4aa2b3a3SAdrian Prantl       return true;
70*4aa2b3a3SAdrian Prantl     }
71*4aa2b3a3SAdrian Prantl 
72*4aa2b3a3SAdrian Prantl     bool VisitValueDecl(ValueDecl *D) {
73*4aa2b3a3SAdrian Prantl       QualType QualTy = D->getType();
74*4aa2b3a3SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
75*4aa2b3a3SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
76*4aa2b3a3SAdrian Prantl       return true;
77*4aa2b3a3SAdrian Prantl     }
78*4aa2b3a3SAdrian Prantl 
79*4aa2b3a3SAdrian Prantl   };
80*4aa2b3a3SAdrian Prantl 
81bc068586SAdrian Prantl public:
825a88e1a8SAdrian Prantl   PCHContainerGenerator(DiagnosticsEngine &diags,
835a88e1a8SAdrian Prantl                         const HeaderSearchOptions &HSO,
845a88e1a8SAdrian Prantl                         const PreprocessorOptions &PPO, const TargetOptions &TO,
855a88e1a8SAdrian Prantl                         const LangOptions &LO, const std::string &MainFileName,
865a88e1a8SAdrian Prantl                         const std::string &OutputFileName,
875a88e1a8SAdrian Prantl                         raw_pwrite_stream *OS,
885a88e1a8SAdrian Prantl                         std::shared_ptr<PCHBuffer> Buffer)
890f99d6a4SRichard Smith       : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO), PreprocessorOpts(PPO),
905a88e1a8SAdrian Prantl         TargetOpts(TO), LangOpts(LO), OS(OS), Buffer(Buffer) {
91bc068586SAdrian Prantl     // The debug info output isn't affected by CodeModel and
92bc068586SAdrian Prantl     // ThreadModel, but the backend expects them to be nonempty.
93bc068586SAdrian Prantl     CodeGenOpts.CodeModel = "default";
94bc068586SAdrian Prantl     CodeGenOpts.ThreadModel = "single";
956b21ab21SAdrian Prantl     CodeGenOpts.DebugTypeExtRefs = true;
96bc068586SAdrian Prantl     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
97bc068586SAdrian Prantl     CodeGenOpts.SplitDwarfFile = OutputFileName;
98bc068586SAdrian Prantl   }
99bc068586SAdrian Prantl 
1005a88e1a8SAdrian Prantl   virtual ~PCHContainerGenerator() {}
101bc068586SAdrian Prantl 
102bc068586SAdrian Prantl   void Initialize(ASTContext &Context) override {
103293534b1SRichard Smith     assert(!Ctx && "initialized multiple times");
1040f99d6a4SRichard Smith 
105bc068586SAdrian Prantl     Ctx = &Context;
106bc068586SAdrian Prantl     VMContext.reset(new llvm::LLVMContext());
107bc068586SAdrian Prantl     M.reset(new llvm::Module(MainFileName, *VMContext));
108964a5f3bSEric Christopher     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
109ca3cf9e6SMehdi Amini     Builder.reset(new CodeGen::CodeGenModule(
110ca3cf9e6SMehdi Amini         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
111bc068586SAdrian Prantl   }
112bc068586SAdrian Prantl 
113*4aa2b3a3SAdrian Prantl   bool HandleTopLevelDecl(DeclGroupRef D) override {
114*4aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred() ||
115*4aa2b3a3SAdrian Prantl         (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo))
116*4aa2b3a3SAdrian Prantl       return true;
117*4aa2b3a3SAdrian Prantl 
118*4aa2b3a3SAdrian Prantl     // Collect debug info for all decls in this group.
119*4aa2b3a3SAdrian Prantl     for (auto *I : D)
120*4aa2b3a3SAdrian Prantl       if (!I->isFromASTFile()) {
121*4aa2b3a3SAdrian Prantl         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
122*4aa2b3a3SAdrian Prantl         DTV.TraverseDecl(I);
123*4aa2b3a3SAdrian Prantl       }
124*4aa2b3a3SAdrian Prantl     return true;
125*4aa2b3a3SAdrian Prantl   }
126*4aa2b3a3SAdrian Prantl 
127*4aa2b3a3SAdrian Prantl   void HandleTagDeclDefinition(TagDecl *D) override {
128*4aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
129*4aa2b3a3SAdrian Prantl       return;
130*4aa2b3a3SAdrian Prantl 
131*4aa2b3a3SAdrian Prantl     Builder->UpdateCompletedType(D);
132*4aa2b3a3SAdrian Prantl   }
133*4aa2b3a3SAdrian Prantl 
134*4aa2b3a3SAdrian Prantl   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
135*4aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
136*4aa2b3a3SAdrian Prantl       return;
137*4aa2b3a3SAdrian Prantl 
138*4aa2b3a3SAdrian Prantl     if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
139*4aa2b3a3SAdrian Prantl       if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
140*4aa2b3a3SAdrian Prantl         DI->completeRequiredType(RD);
141*4aa2b3a3SAdrian Prantl   }
142*4aa2b3a3SAdrian Prantl 
143bc068586SAdrian Prantl   /// Emit a container holding the serialized AST.
144bc068586SAdrian Prantl   void HandleTranslationUnit(ASTContext &Ctx) override {
145bc068586SAdrian Prantl     assert(M && VMContext && Builder);
146bc068586SAdrian Prantl     // Delete these on function exit.
147bc068586SAdrian Prantl     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
148bc068586SAdrian Prantl     std::unique_ptr<llvm::Module> M = std::move(this->M);
149bc068586SAdrian Prantl     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
150bc068586SAdrian Prantl 
151bc068586SAdrian Prantl     if (Diags.hasErrorOccurred())
152bc068586SAdrian Prantl       return;
153bc068586SAdrian Prantl 
154bc068586SAdrian Prantl     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
155964a5f3bSEric Christopher     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
156bc068586SAdrian Prantl 
157bc068586SAdrian Prantl     // Finalize the Builder.
158bc068586SAdrian Prantl     if (Builder)
159bc068586SAdrian Prantl       Builder->Release();
160bc068586SAdrian Prantl 
161bc068586SAdrian Prantl     // Ensure the target exists.
162bc068586SAdrian Prantl     std::string Error;
163bc068586SAdrian Prantl     auto Triple = Ctx.getTargetInfo().getTriple();
164bc068586SAdrian Prantl     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
165bc068586SAdrian Prantl       llvm::report_fatal_error(Error);
166bc068586SAdrian Prantl 
167bc068586SAdrian Prantl     // Emit the serialized Clang AST into its own section.
168bc068586SAdrian Prantl     assert(Buffer->IsComplete && "serialization did not complete");
169bc068586SAdrian Prantl     auto &SerializedAST = Buffer->Data;
170bc068586SAdrian Prantl     auto Size = SerializedAST.size();
171bc068586SAdrian Prantl     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
172bc068586SAdrian Prantl     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
1735a88e1a8SAdrian Prantl     auto *Data = llvm::ConstantDataArray::getString(
1745a88e1a8SAdrian Prantl         *VMContext, StringRef(SerializedAST.data(), Size),
175bc068586SAdrian Prantl         /*AddNull=*/false);
176bc068586SAdrian Prantl     auto *ASTSym = new llvm::GlobalVariable(
177bc068586SAdrian Prantl         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
178bc068586SAdrian Prantl         "__clang_ast");
179bc068586SAdrian Prantl     // The on-disk hashtable needs to be aligned.
180bc068586SAdrian Prantl     ASTSym->setAlignment(8);
181bc068586SAdrian Prantl 
182bc068586SAdrian Prantl     // Mach-O also needs a segment name.
183bc068586SAdrian Prantl     if (Triple.isOSBinFormatMachO())
184bc068586SAdrian Prantl       ASTSym->setSection("__CLANG,__clangast");
185bc068586SAdrian Prantl     // COFF has an eight character length limit.
186bc068586SAdrian Prantl     else if (Triple.isOSBinFormatCOFF())
187bc068586SAdrian Prantl       ASTSym->setSection("clangast");
188bc068586SAdrian Prantl     else
189bc068586SAdrian Prantl       ASTSym->setSection("__clangast");
190bc068586SAdrian Prantl 
191bc068586SAdrian Prantl     DEBUG({
192bc068586SAdrian Prantl       // Print the IR for the PCH container to the debug output.
193bc068586SAdrian Prantl       llvm::SmallString<0> Buffer;
194bc068586SAdrian Prantl       llvm::raw_svector_ostream OS(Buffer);
195bc068586SAdrian Prantl       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
196964a5f3bSEric Christopher                                Ctx.getTargetInfo().getDataLayoutString(),
197bc068586SAdrian Prantl                                M.get(), BackendAction::Backend_EmitLL, &OS);
198bc068586SAdrian Prantl       llvm::dbgs() << Buffer;
199bc068586SAdrian Prantl     });
200bc068586SAdrian Prantl 
201bc068586SAdrian Prantl     // Use the LLVM backend to emit the pch container.
202bc068586SAdrian Prantl     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
203964a5f3bSEric Christopher                              Ctx.getTargetInfo().getDataLayoutString(),
204bc068586SAdrian Prantl                              M.get(), BackendAction::Backend_EmitObj, OS);
205bc068586SAdrian Prantl 
206bc068586SAdrian Prantl     // Make sure the pch container hits disk.
207bc068586SAdrian Prantl     OS->flush();
208bc068586SAdrian Prantl 
209bc068586SAdrian Prantl     // Free the memory for the temporary buffer.
210bc068586SAdrian Prantl     llvm::SmallVector<char, 0> Empty;
211bc068586SAdrian Prantl     SerializedAST = std::move(Empty);
212bc068586SAdrian Prantl   }
213bc068586SAdrian Prantl };
2145a88e1a8SAdrian Prantl 
2155a88e1a8SAdrian Prantl } // namespace
216bc068586SAdrian Prantl 
217bc068586SAdrian Prantl std::unique_ptr<ASTConsumer>
218fb2398d0SAdrian Prantl ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
219bc068586SAdrian Prantl     DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
220bc068586SAdrian Prantl     const PreprocessorOptions &PPO, const TargetOptions &TO,
221bc068586SAdrian Prantl     const LangOptions &LO, const std::string &MainFileName,
222bc068586SAdrian Prantl     const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
223bc068586SAdrian Prantl     std::shared_ptr<PCHBuffer> Buffer) const {
2245a88e1a8SAdrian Prantl   return llvm::make_unique<PCHContainerGenerator>(
2255a88e1a8SAdrian Prantl       Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer);
226bc068586SAdrian Prantl }
227bc068586SAdrian Prantl 
228fb2398d0SAdrian Prantl void ObjectFilePCHContainerReader::ExtractPCH(
229bc068586SAdrian Prantl     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
230bc068586SAdrian Prantl   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
231bc068586SAdrian Prantl     auto *Obj = OF.get().get();
232bc068586SAdrian Prantl     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
233bc068586SAdrian Prantl     // Find the clang AST section in the container.
234bc068586SAdrian Prantl     for (auto &Section : OF->get()->sections()) {
235bc068586SAdrian Prantl       StringRef Name;
236bc068586SAdrian Prantl       Section.getName(Name);
237bc068586SAdrian Prantl       if ((!IsCOFF && Name == "__clangast") ||
238bc068586SAdrian Prantl           ( IsCOFF && Name ==   "clangast")) {
239bc068586SAdrian Prantl         StringRef Buf;
240bc068586SAdrian Prantl         Section.getContents(Buf);
241bc068586SAdrian Prantl         StreamFile.init((const unsigned char *)Buf.begin(),
242bc068586SAdrian Prantl                         (const unsigned char *)Buf.end());
243bc068586SAdrian Prantl         return;
244bc068586SAdrian Prantl       }
245bc068586SAdrian Prantl     }
246bc068586SAdrian Prantl   }
247bc068586SAdrian Prantl 
248bc068586SAdrian Prantl   // As a fallback, treat the buffer as a raw AST.
249bc068586SAdrian Prantl   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
250bc068586SAdrian Prantl                   (const unsigned char *)Buffer.getBufferEnd());
251bc068586SAdrian Prantl   return;
252bc068586SAdrian Prantl }
253