I’m toying around with the LLVM C++ API. I’d like to JIT compile code and run it.
However, I need to call a C++ method from said JIT-compiled code. Normally, LLVM treats method calls as function calls with the object pointer passed as the first argument, so calling shouldn’t be a problem. The real problem is to get that function into LLVM.
As far as I can see, it’s possible to use external linkage for functions and get it by its name. Problem is, since it’s a C++ method, its name is going to be mangled, so I don’t think it’s a good idea to go that way.
Making the FunctionType object is easy enough. But from there, how can I inform LLVM of my method and get a Function object for it?
The dudes from the LLVM mailing list were helpful enough to provide a better solution. They didn’t say how to get the pointer from the method to the function, but I’ve already figured out this part so it’s okay.
EDIT A clean way to do this is simply to wrap your method into a function:
Then use
Foo_Bar‘s address instead of trying to getFoo::bar‘s. Usellvm::ExecutionEngine::addGlobalMappingto add the mapping as shown below.As usual, the simplest solution has some interesting benefits. For instance, it works with virtual functions without a hiccup. (But it’s so much less entertaining. The rest of the answer is kept for historical purposes, mainly because I had a lot of fun poking at the internals of my C++ runtime. Also note that it’s non-portable.)
You’ll need something along these lines to figure the address of a method (be warned, that’s a dirty hack that probably will only be compatible with the Itanium ABI):
Then use
llvm::ExecutionEngine::addGlobalMappingto map a function to the address you’ve gotten. To call it, pass it your object as the first parameter, and the rest as usual. Here’s a quick example.