If you’re finding the LLVM C API a little tough to get started with, here’s a little example.

Say we want to programmatically generate & execute the equivalent LLVM IR for the following C code:

extern printf (const char *, ...);

int
main (void)
{
  printf ("%dn", 10   15);
  return 0;
}

I’ve put the code for doing exactly that in this github repo — i.e. using the LLVM C API, we generate a semantically equivalent LLVM module in-memory and then execute it. (The code will dump out a nice, human readable representation of the IR, too.)

If you look at configure.ac, you can see this code uses the JIT execution engine. Note that the llvm::InitializeNativeTarget call should be unnecessary if you instead build with the interpreted execution engine.

Note that at the time of writing, this code targets LLVM 3.1, but if you look at the tags you can find the slight modifications required for LLVM 3.0 and 2.9. Using #if/#endif guards you could probably trivially write a version that builds under all three.

This should compile with the usual ./configure && make dance, but be sure to install the necessary prerequisites (i.e. llvm) beforehand!

Oh, and I’m not particularly familiar with LLVM, so all suggestions are welcome. :)