Can I create an llvm::Function from a function pointer (for JIT)

I’m working through the Kaleidoscope tutorial. The mini language has a JIT and it can call out to C functions by creating an llvm::Function with the C function’s name. The JIT then looks up the implementation in the current process’s symbol table.

But I’ve added types to my mini-language, so I wanted to write some overloaded functions like:

func print(x: Int) { ... }
func print(s: String) { ... }

It’s simple to define those in C++, but then I don’t know the mangled name to give to the Function::Create(...) constructor.

Is there a way to either:

  1. Create the llvm::Function with a function pointer, so it doesn’t use the name to look up the implementation.
  2. Get the mangled name of a C++ function at runtime?

I know how to get a mangled name by running nm and looking at the output. But that would be a bit weird - I’d have to compile once, then use nm to look at function names, then add them as strings in my code and compile again.


You can’t create an actual Function without a name (it’s intrinsically a named global variable of some kind in LLVM), but you can inject the pointer as something like inttoptr(i64 <real world pointer> to ptr) and then call that like you would any for any indirect function call.

That’s hard, really only a C++ front-end knows how it’s going to mangle names, so for example the Swift language embeds a whole Clang front-end to do that job.

The reverse is significantly easier: surround the C++ definition with extern "C" and it won’t be mangled at all. This is often useful for languages that want to implemennt fixed runtime support functions in C++.

1 Like