#include "llvm/ADT/StringMap.h"
#include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
#include "llvm/ExecutionEngine/Orc/LLJIT.h"
#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "../ExampleModules.h"
using namespace llvm;
using namespace llvm::orc;
ExitOnError ExitOnErr;
const llvm::StringRef FooMod =
R"(
define i32 @foo_body() {
entry:
ret i32 1
}
)";
const llvm::StringRef BarMod =
R"(
define i32 @bar_body() {
entry:
ret i32 2
}
)";
const llvm::StringRef MainMod =
R"(
define i32 @entry(i32 %argc) {
entry:
%and = and i32 %argc, 1
%tobool = icmp eq i32 %and, 0
br i1 %tobool, label %if.end, label %if.then
if.then: ; preds = %entry
%call = tail call i32 @foo() #2
br label %return
if.end: ; preds = %entry
%call1 = tail call i32 @bar() #2
br label %return
return: ; preds = %if.end, %if.then
%retval.0 = phi i32 [ %call, %if.then ], [ %call1, %if.end ]
ret i32 %retval.0
}
declare i32 @foo()
declare i32 @bar()
)";
cl::list<std::string> InputArgv(cl::Positional,
cl::desc("<program arguments>..."));
int main(int argc, char *argv[]) {
InitLLVM X(argc, argv);
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
cl::ParseCommandLineOptions(argc, argv, "LLJITWithLazyReexports");
ExitOnErr.setBanner(std::string(argv[0]) + ": ");
auto J = ExitOnErr(LLJITBuilder().create());
J->getIRTransformLayer().setTransform(
[](ThreadSafeModule TSM,
const MaterializationResponsibility &R) -> Expected<ThreadSafeModule> {
TSM.withModuleDo([](Module &M) { dbgs() << "---Compiling---\n" << M; });
return std::move(TSM); });
std::unique_ptr<IndirectStubsManager> ISM;
{
auto ISMBuilder =
createLocalIndirectStubsManagerBuilder(J->getTargetTriple());
if (!ISMBuilder())
ExitOnErr(make_error<StringError>("Could not create stubs manager for " +
J->getTargetTriple().str(),
inconvertibleErrorCode()));
ISM = ISMBuilder();
}
auto LCTM = ExitOnErr(createLocalLazyCallThroughManager(
J->getTargetTriple(), J->getExecutionSession(), 0));
ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(FooMod, "foo-mod"))));
ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(BarMod, "bar-mod"))));
ExitOnErr(J->addIRModule(ExitOnErr(parseExampleModule(MainMod, "main-mod"))));
MangleAndInterner Mangle(J->getExecutionSession(), J->getDataLayout());
SymbolAliasMap ReExports(
{{Mangle("foo"),
{Mangle("foo_body"),
JITSymbolFlags::Exported | JITSymbolFlags::Callable}},
{Mangle("bar"),
{Mangle("bar_body"),
JITSymbolFlags::Exported | JITSymbolFlags::Callable}}});
ExitOnErr(J->getMainJITDylib().define(
lazyReexports(*LCTM, *ISM, J->getMainJITDylib(), std::move(ReExports))));
dbgs() << "---Session state---\n";
J->getExecutionSession().dump(dbgs());
dbgs() << "\n";
auto EntryAddr = ExitOnErr(J->lookup("entry"));
auto *Entry = EntryAddr.toPtr<int(int)>();
int Result = Entry(argc);
outs() << "---Result---\n"
<< "entry(" << argc << ") = " << Result << "\n";
return 0;
}