xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/ObjectFilePCHContainerOperations.cpp (revision 1f1e2261e341e6ca6862f82261066ef1705f0a7a)
1 //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
10 #include "CGDebugInfo.h"
11 #include "CodeGenModule.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclObjC.h"
14 #include "clang/AST/Expr.h"
15 #include "clang/AST/RecursiveASTVisitor.h"
16 #include "clang/Basic/CodeGenOptions.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/CodeGen/BackendUtil.h"
20 #include "clang/Frontend/CompilerInstance.h"
21 #include "clang/Lex/HeaderSearch.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Bitstream/BitstreamReader.h"
25 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/MC/TargetRegistry.h"
31 #include "llvm/Object/COFF.h"
32 #include "llvm/Object/ObjectFile.h"
33 #include "llvm/Support/Path.h"
34 #include <memory>
35 #include <utility>
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   const std::string OutputFileName;
46   ASTContext *Ctx;
47   ModuleMap &MMap;
48   const HeaderSearchOptions &HeaderSearchOpts;
49   const PreprocessorOptions &PreprocessorOpts;
50   CodeGenOptions CodeGenOpts;
51   const TargetOptions TargetOpts;
52   LangOptions LangOpts;
53   std::unique_ptr<llvm::LLVMContext> VMContext;
54   std::unique_ptr<llvm::Module> M;
55   std::unique_ptr<CodeGen::CodeGenModule> Builder;
56   std::unique_ptr<raw_pwrite_stream> OS;
57   std::shared_ptr<PCHBuffer> Buffer;
58 
59   /// Visit every type and emit debug info for it.
60   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
61     clang::CodeGen::CGDebugInfo &DI;
62     ASTContext &Ctx;
63     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
64         : DI(DI), Ctx(Ctx) {}
65 
66     /// Determine whether this type can be represented in DWARF.
67     static bool CanRepresent(const Type *Ty) {
68       return !Ty->isDependentType() && !Ty->isUndeducedType();
69     }
70 
71     bool VisitImportDecl(ImportDecl *D) {
72       if (!D->getImportedOwningModule())
73         DI.EmitImportDecl(*D);
74       return true;
75     }
76 
77     bool VisitTypeDecl(TypeDecl *D) {
78       // TagDecls may be deferred until after all decls have been merged and we
79       // know the complete type. Pure forward declarations will be skipped, but
80       // they don't need to be emitted into the module anyway.
81       if (auto *TD = dyn_cast<TagDecl>(D))
82         if (!TD->isCompleteDefinition())
83           return true;
84 
85       QualType QualTy = Ctx.getTypeDeclType(D);
86       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
87         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
88       return true;
89     }
90 
91     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
92       QualType QualTy(D->getTypeForDecl(), 0);
93       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
94         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
95       return true;
96     }
97 
98     bool VisitFunctionDecl(FunctionDecl *D) {
99       if (isa<CXXMethodDecl>(D))
100         // This is not yet supported. Constructing the `this' argument
101         // mandates a CodeGenFunction.
102         return true;
103 
104       SmallVector<QualType, 16> ArgTypes;
105       for (auto i : D->parameters())
106         ArgTypes.push_back(i->getType());
107       QualType RetTy = D->getReturnType();
108       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
109                                           FunctionProtoType::ExtProtoInfo());
110       if (CanRepresent(FnTy.getTypePtr()))
111         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
112       return true;
113     }
114 
115     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
116       if (!D->getClassInterface())
117         return true;
118 
119       bool selfIsPseudoStrong, selfIsConsumed;
120       SmallVector<QualType, 16> ArgTypes;
121       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
122                                         selfIsPseudoStrong, selfIsConsumed));
123       ArgTypes.push_back(Ctx.getObjCSelType());
124       for (auto i : D->parameters())
125         ArgTypes.push_back(i->getType());
126       QualType RetTy = D->getReturnType();
127       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
128                                           FunctionProtoType::ExtProtoInfo());
129       if (CanRepresent(FnTy.getTypePtr()))
130         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
131       return true;
132     }
133   };
134 
135 public:
136   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
137                         const std::string &OutputFileName,
138                         std::unique_ptr<raw_pwrite_stream> OS,
139                         std::shared_ptr<PCHBuffer> Buffer)
140       : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
141         OutputFileName(OutputFileName), Ctx(nullptr),
142         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
143         HeaderSearchOpts(CI.getHeaderSearchOpts()),
144         PreprocessorOpts(CI.getPreprocessorOpts()),
145         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
146         OS(std::move(OS)), Buffer(std::move(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     LangOpts.setThreadModel(LangOptions::ThreadModelKind::Single);
151     CodeGenOpts.DebugTypeExtRefs = true;
152     // When building a module MainFileName is the name of the modulemap file.
153     CodeGenOpts.MainFileName =
154         LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
155     CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
156     CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
157     CodeGenOpts.DebugPrefixMap =
158         CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
159     CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
160   }
161 
162   ~PCHContainerGenerator() override = default;
163 
164   void Initialize(ASTContext &Context) override {
165     assert(!Ctx && "initialized multiple times");
166 
167     Ctx = &Context;
168     VMContext.reset(new llvm::LLVMContext());
169     M.reset(new llvm::Module(MainFileName, *VMContext));
170     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
171     Builder.reset(new CodeGen::CodeGenModule(
172         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
173 
174     // Prepare CGDebugInfo to emit debug info for a clang module.
175     auto *DI = Builder->getModuleDebugInfo();
176     StringRef ModuleName = llvm::sys::path::filename(MainFileName);
177     DI->setPCHDescriptor(
178         {ModuleName, "", OutputFileName, ASTFileSignature::createDISentinel()});
179     DI->setModuleMap(MMap);
180   }
181 
182   bool HandleTopLevelDecl(DeclGroupRef D) override {
183     if (Diags.hasErrorOccurred())
184       return true;
185 
186     // Collect debug info for all decls in this group.
187     for (auto *I : D)
188       if (!I->isFromASTFile()) {
189         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
190         DTV.TraverseDecl(I);
191       }
192     return true;
193   }
194 
195   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
196     HandleTopLevelDecl(D);
197   }
198 
199   void HandleTagDeclDefinition(TagDecl *D) override {
200     if (Diags.hasErrorOccurred())
201       return;
202 
203     if (D->isFromASTFile())
204       return;
205 
206     // Anonymous tag decls are deferred until we are building their declcontext.
207     if (D->getName().empty())
208       return;
209 
210     // Defer tag decls until their declcontext is complete.
211     auto *DeclCtx = D->getDeclContext();
212     while (DeclCtx) {
213       if (auto *D = dyn_cast<TagDecl>(DeclCtx))
214         if (!D->isCompleteDefinition())
215           return;
216       DeclCtx = DeclCtx->getParent();
217     }
218 
219     DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
220     DTV.TraverseDecl(D);
221     Builder->UpdateCompletedType(D);
222   }
223 
224   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
225     if (Diags.hasErrorOccurred())
226       return;
227 
228     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
229       Builder->getModuleDebugInfo()->completeRequiredType(RD);
230   }
231 
232   void HandleImplicitImportDecl(ImportDecl *D) override {
233     if (!D->getImportedOwningModule())
234       Builder->getModuleDebugInfo()->EmitImportDecl(*D);
235   }
236 
237   /// Emit a container holding the serialized AST.
238   void HandleTranslationUnit(ASTContext &Ctx) override {
239     assert(M && VMContext && Builder);
240     // Delete these on function exit.
241     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
242     std::unique_ptr<llvm::Module> M = std::move(this->M);
243     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
244 
245     if (Diags.hasErrorOccurred())
246       return;
247 
248     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
249     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
250 
251     // PCH files don't have a signature field in the control block,
252     // but LLVM detects DWO CUs by looking for a non-zero DWO id.
253     // We use the lower 64 bits for debug info.
254 
255     uint64_t Signature =
256         Buffer->Signature ? Buffer->Signature.truncatedValue() : ~1ULL;
257 
258     Builder->getModuleDebugInfo()->setDwoId(Signature);
259 
260     // Finalize the Builder.
261     if (Builder)
262       Builder->Release();
263 
264     // Ensure the target exists.
265     std::string Error;
266     auto Triple = Ctx.getTargetInfo().getTriple();
267     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
268       llvm::report_fatal_error(llvm::Twine(Error));
269 
270     // Emit the serialized Clang AST into its own section.
271     assert(Buffer->IsComplete && "serialization did not complete");
272     auto &SerializedAST = Buffer->Data;
273     auto Size = SerializedAST.size();
274 
275     if (Triple.isOSBinFormatWasm()) {
276       // Emit __clangast in custom section instead of named data segment
277       // to find it while iterating sections.
278       // This could be avoided if all data segements (the wasm sense) were
279       // represented as their own sections (in the llvm sense).
280       // TODO: https://github.com/WebAssembly/tool-conventions/issues/138
281       llvm::NamedMDNode *MD =
282           M->getOrInsertNamedMetadata("wasm.custom_sections");
283       llvm::Metadata *Ops[2] = {
284           llvm::MDString::get(*VMContext, "__clangast"),
285           llvm::MDString::get(*VMContext,
286                               StringRef(SerializedAST.data(), Size))};
287       auto *NameAndContent = llvm::MDTuple::get(*VMContext, Ops);
288       MD->addOperand(NameAndContent);
289     } else {
290       auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
291       auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
292       auto *Data = llvm::ConstantDataArray::getString(
293           *VMContext, StringRef(SerializedAST.data(), Size),
294           /*AddNull=*/false);
295       auto *ASTSym = new llvm::GlobalVariable(
296           *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage,
297           Data, "__clang_ast");
298       // The on-disk hashtable needs to be aligned.
299       ASTSym->setAlignment(llvm::Align(8));
300 
301       // Mach-O also needs a segment name.
302       if (Triple.isOSBinFormatMachO())
303         ASTSym->setSection("__CLANG,__clangast");
304       // COFF has an eight character length limit.
305       else if (Triple.isOSBinFormatCOFF())
306         ASTSym->setSection("clangast");
307       else
308         ASTSym->setSection("__clangast");
309     }
310 
311     LLVM_DEBUG({
312       // Print the IR for the PCH container to the debug output.
313       llvm::SmallString<0> Buffer;
314       clang::EmitBackendOutput(
315           Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
316           Ctx.getTargetInfo().getDataLayoutString(), M.get(),
317           BackendAction::Backend_EmitLL,
318           std::make_unique<llvm::raw_svector_ostream>(Buffer));
319       llvm::dbgs() << Buffer;
320     });
321 
322     // Use the LLVM backend to emit the pch container.
323     clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
324                              LangOpts,
325                              Ctx.getTargetInfo().getDataLayoutString(), M.get(),
326                              BackendAction::Backend_EmitObj, std::move(OS));
327 
328     // Free the memory for the temporary buffer.
329     llvm::SmallVector<char, 0> Empty;
330     SerializedAST = std::move(Empty);
331   }
332 };
333 
334 } // anonymous namespace
335 
336 std::unique_ptr<ASTConsumer>
337 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
338     CompilerInstance &CI, const std::string &MainFileName,
339     const std::string &OutputFileName,
340     std::unique_ptr<llvm::raw_pwrite_stream> OS,
341     std::shared_ptr<PCHBuffer> Buffer) const {
342   return std::make_unique<PCHContainerGenerator>(
343       CI, MainFileName, OutputFileName, std::move(OS), Buffer);
344 }
345 
346 StringRef
347 ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
348   StringRef PCH;
349   auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
350   if (OFOrErr) {
351     auto &OF = OFOrErr.get();
352     bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
353     // Find the clang AST section in the container.
354     for (auto &Section : OF->sections()) {
355       StringRef Name;
356       if (Expected<StringRef> NameOrErr = Section.getName())
357         Name = *NameOrErr;
358       else
359         consumeError(NameOrErr.takeError());
360 
361       if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
362         if (Expected<StringRef> E = Section.getContents())
363           return *E;
364         else {
365           handleAllErrors(E.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
366             EIB.log(llvm::errs());
367           });
368           return "";
369         }
370       }
371     }
372   }
373   handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
374     if (EIB.convertToErrorCode() ==
375         llvm::object::object_error::invalid_file_type)
376       // As a fallback, treat the buffer as a raw AST.
377       PCH = Buffer.getBuffer();
378     else
379       EIB.log(llvm::errs());
380   });
381   return PCH;
382 }
383