ThreadSafeModule.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //===-- ThreadSafeModule.cpp - Thread safe Module, Context, and Utilities
  2. //h-===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/ExecutionEngine/Orc/ThreadSafeModule.h"
  10. #include "llvm/Bitcode/BitcodeReader.h"
  11. #include "llvm/Bitcode/BitcodeWriter.h"
  12. #include "llvm/Transforms/Utils/Cloning.h"
  13. namespace llvm {
  14. namespace orc {
  15. ThreadSafeModule cloneToNewContext(const ThreadSafeModule &TSM,
  16. GVPredicate ShouldCloneDef,
  17. GVModifier UpdateClonedDefSource) {
  18. assert(TSM && "Can not clone null module");
  19. if (!ShouldCloneDef)
  20. ShouldCloneDef = [](const GlobalValue &) { return true; };
  21. return TSM.withModuleDo([&](Module &M) {
  22. SmallVector<char, 1> ClonedModuleBuffer;
  23. {
  24. std::set<GlobalValue *> ClonedDefsInSrc;
  25. ValueToValueMapTy VMap;
  26. auto Tmp = CloneModule(M, VMap, [&](const GlobalValue *GV) {
  27. if (ShouldCloneDef(*GV)) {
  28. ClonedDefsInSrc.insert(const_cast<GlobalValue *>(GV));
  29. return true;
  30. }
  31. return false;
  32. });
  33. if (UpdateClonedDefSource)
  34. for (auto *GV : ClonedDefsInSrc)
  35. UpdateClonedDefSource(*GV);
  36. BitcodeWriter BCWriter(ClonedModuleBuffer);
  37. BCWriter.writeModule(*Tmp);
  38. BCWriter.writeSymtab();
  39. BCWriter.writeStrtab();
  40. }
  41. MemoryBufferRef ClonedModuleBufferRef(
  42. StringRef(ClonedModuleBuffer.data(), ClonedModuleBuffer.size()),
  43. "cloned module buffer");
  44. ThreadSafeContext NewTSCtx(std::make_unique<LLVMContext>());
  45. auto ClonedModule = cantFail(
  46. parseBitcodeFile(ClonedModuleBufferRef, *NewTSCtx.getContext()));
  47. ClonedModule->setModuleIdentifier(M.getName());
  48. return ThreadSafeModule(std::move(ClonedModule), std::move(NewTSCtx));
  49. });
  50. }
  51. } // end namespace orc
  52. } // end namespace llvm