ObjectFilePCHContainerOperations.cpp 14 KB

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