JIT session error : Symbols not found


I’m learning about how to use JIT. Refer to Kaleidpscope-Ch4 and HowToUseLLJIT, I wrote a demo to invoke a c++ function via LLJIT. Now I encountered a problem: An error message ‘JIT session error : Symbols not found: [ func ]’ is reported when call Jit->lookup(func). Demo codes are mainly copied from HowToSUeLLJIT.cpp, and some differences as below:

#inlcude "..."
extern "C" DLLEXPORT int func(int x) { return x + 1;}
ThreadSafeModule createDemoModule() {
Function *func = Function::create(FunctionType::get(Type::getInt32Ty(*Context), {Type::getInt32Ty(*Context)}, false), Function::ExternalLinkage, "func", M.get());

Function *func2 = Function::create(FunctionType::get(Type::getInt32Ty(*Context), {}, false), Function::ExternalLinkage, "func2", M.get());

BasicBlock *BB = BasicBlock::Create(*Context, "entry", func2);

std::vector<Value *> args;
Value *retValue = Builder->CreateCall(func, args, "calltmp");

return ThreadSafeModule(std::move(M), std::move(Context));

int main(int argc, char *argv[])
auto J = ExitOnErr(LLJITBuilder().create());
auto Mo = createDemoModule();

auto funcSym = ExitOnErr(J->lookup("func"));
int (\* callFunc)() = (int (\*) ())funcSym.getAddress();
int Result = callFunc();

return 0

And I also dumped the module:

; ModuleID = 'test'
source_filename = "test"

declare i32 @func(i32 %0)

define i32 @func2() {
  %calltmp = call i32 @func(i32 1)
   ret i32 %calltmp

From the dump, it seem be OK. So I suspect that issue is about some initialization work of JIT? I’m not clear on the mechanism of JIT. Any one can give some hints? Thanks in advance. (Demo is based on llvm 13.0.1)

Best Regards,

Your IR only declare func but does not define it, it is defined in your C++ code as a native symbol. I am not sure if J->lookup("func") is supposed to resolve symbols that aren’t JITed. Did you mean J->lookup("func2") ?

Thanks for your reminder. Yes, it’s a typo. I want to look up func2 there. And I have resolved this case. Before do the lookup, add a statement :

J->getMainJITDylib().define(absoluteSymbols({{J->mangleAndIntern(“func”, JITEvaluatedSymbol::fromPointer(&func))}}));

Then func() could be triggered successfully when activate callFunc(). Hope that can help others who encounter the same issue as me.