163 lines · cpp
1//===--- LLJITWithLazyReexports.cpp - LLJIT example with custom laziness --===//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-exception6//7//===----------------------------------------------------------------------===//8//9// In this example we will use the lazy re-exports utility to lazily compile10// IR modules. We will do this in seven steps:11//12// 1. Create an LLJIT instance.13// 2. Install a transform so that we can see what is being compiled.14// 3. Create an indirect stubs manager and lazy call-through manager.15// 4. Add two modules that will be conditionally compiled, plus a main module.16// 5. Add lazy-rexports of the symbols in the conditionally compiled modules.17// 6. Dump the ExecutionSession state to see the symbol table prior to18// executing any code.19// 7. Verify that only modules containing executed code are compiled.20//21//===----------------------------------------------------------------------===//22 23#include "llvm/ADT/StringMap.h"24#include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"25#include "llvm/ExecutionEngine/Orc/LLJIT.h"26#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"27#include "llvm/Support/InitLLVM.h"28#include "llvm/Support/TargetSelect.h"29#include "llvm/Support/raw_ostream.h"30 31#include "../ExampleModules.h"32 33using namespace llvm;34using namespace llvm::orc;35 36ExitOnError ExitOnErr;37 38// Example IR modules.39//40// Note that in the conditionally compiled modules, FooMod and BarMod, functions41// have been given an _body suffix. This is to ensure that their names do not42// clash with their lazy-reexports.43// For clients who do not wish to rename function bodies (e.g. because they want44// to re-use cached objects between static and JIT compiles) techniques exist to45// avoid renaming. See the lazy-reexports section of the ORCv2 design doc.46 47const llvm::StringRef FooMod =48 R"(49 define i32 @foo_body() {50 entry:51 ret i32 152 }53)";54 55const llvm::StringRef BarMod =56 R"(57 define i32 @bar_body() {58 entry:59 ret i32 260 }61)";62 63const llvm::StringRef MainMod =64 R"(65 66 define i32 @entry(i32 %argc) {67 entry:68 %and = and i32 %argc, 169 %tobool = icmp eq i32 %and, 070 br i1 %tobool, label %if.end, label %if.then71 72 if.then: ; preds = %entry73 %call = tail call i32 @foo() #274 br label %return75 76 if.end: ; preds = %entry77 %call1 = tail call i32 @bar() #278 br label %return79 80 return: ; preds = %if.end, %if.then81 %retval.0 = phi i32 [ %call, %if.then ], [ %call1, %if.end ]82 ret i32 %retval.083 }84 85 declare i32 @foo()86 declare i32 @bar()87)";88 89static cl::list<std::string> InputArgv(cl::Positional,90 cl::desc("<program arguments>..."));91 92int main(int argc, char *argv[]) {93 // Initialize LLVM.94 InitLLVM X(argc, argv);95 96 InitializeNativeTarget();97 InitializeNativeTargetAsmPrinter();98 99 cl::ParseCommandLineOptions(argc, argv, "LLJITWithLazyReexports");100 ExitOnErr.setBanner(std::string(argv[0]) + ": ");101 102 // (1) Create LLJIT instance.103 auto J = ExitOnErr(LLJITBuilder().create());104 105 // (2) Install transform to print modules as they are compiled:106 J->getIRTransformLayer().setTransform(107 [](ThreadSafeModule TSM,108 const MaterializationResponsibility &R) -> Expected<ThreadSafeModule> {109 TSM.withModuleDo([](Module &M) { dbgs() << "---Compiling---\n" << M; });110 return std::move(TSM); // Not a redundant move: fix build on gcc-7.5111 });112 113 // (3) Create stubs and call-through managers:114 std::unique_ptr<IndirectStubsManager> ISM;115 {116 auto ISMBuilder =117 createLocalIndirectStubsManagerBuilder(J->getTargetTriple());118 if (!ISMBuilder())119 ExitOnErr(make_error<StringError>("Could not create stubs manager for " +120 J->getTargetTriple().str(),121 inconvertibleErrorCode()));122 ISM = ISMBuilder();123 }124 auto LCTM = ExitOnErr(createLocalLazyCallThroughManager(125 J->getTargetTriple(), J->getExecutionSession(), ExecutorAddr()));126 127 // (4) Add modules.128 ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(FooMod, "foo-mod"))));129 ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(BarMod, "bar-mod"))));130 ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(MainMod, "main-mod"))));131 132 // (5) Add lazy reexports.133 SymbolAliasMap ReExports(134 {{J->mangleAndIntern("foo"),135 {J->mangleAndIntern("foo_body"),136 JITSymbolFlags::Exported | JITSymbolFlags::Callable}},137 {J->mangleAndIntern("bar"),138 {J->mangleAndIntern("bar_body"),139 JITSymbolFlags::Exported | JITSymbolFlags::Callable}}});140 ExitOnErr(J->getMainJITDylib().define(141 lazyReexports(*LCTM, *ISM, J->getMainJITDylib(), std::move(ReExports))));142 143 // (6) Dump the ExecutionSession state.144 dbgs() << "---Session state---\n";145 J->getExecutionSession().dump(dbgs());146 dbgs() << "\n";147 148 // (7) Execute the JIT'd main function and pass the example's command line149 // arguments unmodified. This should cause either ExampleMod1 or ExampleMod2150 // to be compiled, and either "1" or "2" returned depending on the number of151 // arguments passed.152 153 // Look up the JIT'd function, cast it to a function pointer, then call it.154 auto EntryAddr = ExitOnErr(J->lookup("entry"));155 auto *Entry = EntryAddr.toPtr<int(int)>();156 157 int Result = Entry(argc);158 outs() << "---Result---\n"159 << "entry(" << argc << ") = " << Result << "\n";160 161 return 0;162}163