ObjectFilePCHContainerOperations.cpp 10 KB

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