LLJITWithJITLink.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //===-- LLJITWithJITLink.cpp - Configure LLJIT to use ObjectLinkingLayer --===//
  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. //
  9. // This file shows how to switch LLJIT to use ObjectLinkingLayer (which is
  10. // backed by JITLink) rather than RTDyldObjectLinkingLayer (which is backed by
  11. // RuntimeDyld). Using JITLink as the underlying allocator enables use of
  12. // small code model in JIT'd code.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/StringMap.h"
  16. #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
  17. #include "llvm/ExecutionEngine/Orc/LLJIT.h"
  18. #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
  19. #include "llvm/Support/InitLLVM.h"
  20. #include "llvm/Support/TargetSelect.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include "../ExampleModules.h"
  23. using namespace llvm;
  24. using namespace llvm::orc;
  25. ExitOnError ExitOnErr;
  26. int main(int argc, char *argv[]) {
  27. // Initialize LLVM.
  28. InitLLVM X(argc, argv);
  29. InitializeNativeTarget();
  30. InitializeNativeTargetAsmPrinter();
  31. cl::ParseCommandLineOptions(argc, argv, "HowToUseLLJIT");
  32. ExitOnErr.setBanner(std::string(argv[0]) + ": ");
  33. // Define an in-process JITLink memory manager.
  34. jitlink::InProcessMemoryManager MemMgr;
  35. // Detect the host and set code model to small.
  36. auto JTMB = ExitOnErr(JITTargetMachineBuilder::detectHost());
  37. JTMB.setCodeModel(CodeModel::Small);
  38. // Create an LLJIT instance with an ObjectLinkingLayer as the base layer.
  39. auto J =
  40. ExitOnErr(LLJITBuilder()
  41. .setJITTargetMachineBuilder(std::move(JTMB))
  42. .setObjectLinkingLayerCreator([&](ExecutionSession &ES,
  43. const Triple &TT) {
  44. return std::make_unique<ObjectLinkingLayer>(ES, MemMgr);
  45. })
  46. .create());
  47. auto M = ExitOnErr(parseExampleModule(Add1Example, "add1"));
  48. ExitOnErr(J->addIRModule(std::move(M)));
  49. // Look up the JIT'd function, cast it to a function pointer, then call it.
  50. auto Add1Sym = ExitOnErr(J->lookup("add1"));
  51. int (*Add1)(int) = (int (*)(int))Add1Sym.getAddress();
  52. int Result = Add1(42);
  53. outs() << "add1(42) = " << Result << "\n";
  54. return 0;
  55. }