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