1 //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
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 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
11 #include "CGDebugInfo.h"
12 #include "CodeGenModule.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/RecursiveASTVisitor.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/CodeGen/BackendUtil.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Serialization/ASTWriter.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Bitcode/BitstreamReader.h"
27 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Object/COFF.h"
33 #include "llvm/Object/ObjectFile.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include <memory>
36 
37 using namespace clang;
38 
39 #define DEBUG_TYPE "pchcontainer"
40 
41 namespace {
42 class PCHContainerGenerator : public ASTConsumer {
43   DiagnosticsEngine &Diags;
44   const std::string MainFileName;
45   ASTContext *Ctx;
46   ModuleMap &MMap;
47   const HeaderSearchOptions &HeaderSearchOpts;
48   const PreprocessorOptions &PreprocessorOpts;
49   CodeGenOptions CodeGenOpts;
50   const TargetOptions TargetOpts;
51   const LangOptions LangOpts;
52   std::unique_ptr<llvm::LLVMContext> VMContext;
53   std::unique_ptr<llvm::Module> M;
54   std::unique_ptr<CodeGen::CodeGenModule> Builder;
55   raw_pwrite_stream *OS;
56   std::shared_ptr<PCHBuffer> Buffer;
57 
58   /// Visit every type and emit debug info for it.
59   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
60     clang::CodeGen::CGDebugInfo &DI;
61     ASTContext &Ctx;
62     bool SkipTagDecls;
63     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx,
64                      bool SkipTagDecls)
65         : DI(DI), Ctx(Ctx), SkipTagDecls(SkipTagDecls) {}
66 
67     /// Determine whether this type can be represented in DWARF.
68     static bool CanRepresent(const Type *Ty) {
69       return !Ty->isDependentType() && !Ty->isUndeducedType();
70     }
71 
72     bool VisitImportDecl(ImportDecl *D) {
73       auto *Import = cast<ImportDecl>(D);
74       if (!Import->getImportedOwningModule())
75         DI.EmitImportDecl(*Import);
76       return true;
77     }
78 
79     bool VisitTypeDecl(TypeDecl *D) {
80       // TagDecls may be deferred until after all decls have been merged and we
81       // know the complete type. Pure forward declarations will be skipped, but
82       // they don't need to be emitted into the module anyway.
83       if (SkipTagDecls && isa<TagDecl>(D))
84           return true;
85 
86       QualType QualTy = Ctx.getTypeDeclType(D);
87       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
88         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
89       return true;
90     }
91 
92     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
93       QualType QualTy(D->getTypeForDecl(), 0);
94       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
95         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
96       return true;
97     }
98 
99     bool VisitFunctionDecl(FunctionDecl *D) {
100       if (isa<CXXMethodDecl>(D))
101         // This is not yet supported. Constructing the `this' argument
102         // mandates a CodeGenFunction.
103         return true;
104 
105       SmallVector<QualType, 16> ArgTypes;
106       for (auto i : D->params())
107         ArgTypes.push_back(i->getType());
108       QualType RetTy = D->getReturnType();
109       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
110                                           FunctionProtoType::ExtProtoInfo());
111       if (CanRepresent(FnTy.getTypePtr()))
112         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
113       return true;
114     }
115 
116     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
117       if (!D->getClassInterface())
118         return true;
119 
120       bool selfIsPseudoStrong, selfIsConsumed;
121       SmallVector<QualType, 16> ArgTypes;
122       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
123                                         selfIsPseudoStrong, selfIsConsumed));
124       ArgTypes.push_back(Ctx.getObjCSelType());
125       for (auto i : D->params())
126         ArgTypes.push_back(i->getType());
127       QualType RetTy = D->getReturnType();
128       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
129                                           FunctionProtoType::ExtProtoInfo());
130       if (CanRepresent(FnTy.getTypePtr()))
131         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
132       return true;
133     }
134   };
135 
136 public:
137   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
138                         const std::string &OutputFileName,
139                         raw_pwrite_stream *OS,
140                         std::shared_ptr<PCHBuffer> Buffer)
141       : Diags(CI.getDiagnostics()), Ctx(nullptr),
142         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
143         HeaderSearchOpts(CI.getHeaderSearchOpts()),
144         PreprocessorOpts(CI.getPreprocessorOpts()),
145         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
146         Buffer(Buffer) {
147     // The debug info output isn't affected by CodeModel and
148     // ThreadModel, but the backend expects them to be nonempty.
149     CodeGenOpts.CodeModel = "default";
150     CodeGenOpts.ThreadModel = "single";
151     CodeGenOpts.DebugTypeExtRefs = true;
152     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
153   }
154 
155   ~PCHContainerGenerator() override = default;
156 
157   void Initialize(ASTContext &Context) override {
158     assert(!Ctx && "initialized multiple times");
159 
160     Ctx = &Context;
161     VMContext.reset(new llvm::LLVMContext());
162     M.reset(new llvm::Module(MainFileName, *VMContext));
163     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
164     Builder.reset(new CodeGen::CodeGenModule(
165         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
166     Builder->getModuleDebugInfo()->setModuleMap(MMap);
167   }
168 
169   bool HandleTopLevelDecl(DeclGroupRef D) override {
170     if (Diags.hasErrorOccurred())
171       return true;
172 
173     // Collect debug info for all decls in this group.
174     for (auto *I : D)
175       if (!I->isFromASTFile()) {
176         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx, true);
177         DTV.TraverseDecl(I);
178       }
179     return true;
180   }
181 
182   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
183     HandleTopLevelDecl(D);
184   }
185 
186   void HandleTagDeclDefinition(TagDecl *D) override {
187     if (Diags.hasErrorOccurred())
188       return;
189 
190     if (D->isFromASTFile())
191       return;
192 
193     // Anonymous tag decls are deferred until we are building their declcontext.
194     if (D->getName().empty())
195       return;
196 
197     DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx, false);
198     DTV.TraverseDecl(D);
199     Builder->UpdateCompletedType(D);
200   }
201 
202   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
203     if (Diags.hasErrorOccurred())
204       return;
205 
206     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
207       Builder->getModuleDebugInfo()->completeRequiredType(RD);
208   }
209 
210   /// Emit a container holding the serialized AST.
211   void HandleTranslationUnit(ASTContext &Ctx) override {
212     assert(M && VMContext && Builder);
213     // Delete these on function exit.
214     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
215     std::unique_ptr<llvm::Module> M = std::move(this->M);
216     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
217 
218     if (Diags.hasErrorOccurred())
219       return;
220 
221     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
222     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
223     Builder->getModuleDebugInfo()->setDwoId(Buffer->Signature);
224 
225     // Finalize the Builder.
226     if (Builder)
227       Builder->Release();
228 
229     // Ensure the target exists.
230     std::string Error;
231     auto Triple = Ctx.getTargetInfo().getTriple();
232     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
233       llvm::report_fatal_error(Error);
234 
235     // Emit the serialized Clang AST into its own section.
236     assert(Buffer->IsComplete && "serialization did not complete");
237     auto &SerializedAST = Buffer->Data;
238     auto Size = SerializedAST.size();
239     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
240     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
241     auto *Data = llvm::ConstantDataArray::getString(
242         *VMContext, StringRef(SerializedAST.data(), Size),
243         /*AddNull=*/false);
244     auto *ASTSym = new llvm::GlobalVariable(
245         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
246         "__clang_ast");
247     // The on-disk hashtable needs to be aligned.
248     ASTSym->setAlignment(8);
249 
250     // Mach-O also needs a segment name.
251     if (Triple.isOSBinFormatMachO())
252       ASTSym->setSection("__CLANG,__clangast");
253     // COFF has an eight character length limit.
254     else if (Triple.isOSBinFormatCOFF())
255       ASTSym->setSection("clangast");
256     else
257       ASTSym->setSection("__clangast");
258 
259     DEBUG({
260       // Print the IR for the PCH container to the debug output.
261       llvm::SmallString<0> Buffer;
262       llvm::raw_svector_ostream OS(Buffer);
263       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
264                                Ctx.getTargetInfo().getDataLayoutString(),
265                                M.get(), BackendAction::Backend_EmitLL, &OS);
266       llvm::dbgs() << Buffer;
267     });
268 
269     // Use the LLVM backend to emit the pch container.
270     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
271                              Ctx.getTargetInfo().getDataLayoutString(),
272                              M.get(), BackendAction::Backend_EmitObj, OS);
273 
274     // Make sure the pch container hits disk.
275     OS->flush();
276 
277     // Free the memory for the temporary buffer.
278     llvm::SmallVector<char, 0> Empty;
279     SerializedAST = std::move(Empty);
280   }
281 };
282 
283 } // anonymous namespace
284 
285 std::unique_ptr<ASTConsumer>
286 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
287     CompilerInstance &CI, const std::string &MainFileName,
288     const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
289     std::shared_ptr<PCHBuffer> Buffer) const {
290   return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
291                                                   OutputFileName, OS, Buffer);
292 }
293 
294 void ObjectFilePCHContainerReader::ExtractPCH(
295     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
296   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
297     auto *Obj = OF.get().get();
298     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
299     // Find the clang AST section in the container.
300     for (auto &Section : OF->get()->sections()) {
301       StringRef Name;
302       Section.getName(Name);
303       if ((!IsCOFF && Name == "__clangast") ||
304           ( IsCOFF && Name ==   "clangast")) {
305         StringRef Buf;
306         Section.getContents(Buf);
307         StreamFile.init((const unsigned char *)Buf.begin(),
308                         (const unsigned char *)Buf.end());
309         return;
310       }
311     }
312   }
313 
314   // As a fallback, treat the buffer as a raw AST.
315   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
316                   (const unsigned char *)Buffer.getBufferEnd());
317 }
318