ObjectFilePCHContainerOperations.cpp 13 KB

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