ObjectFilePCHContainerOperations.cpp 12 KB

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