Search code examples
pythonccompiler-constructionllvmllvmlite

Link C in llvmlite


Im writing an compiler in Python, using llvmlite to generate intermediate LLVM IR. Lexer and parser are finished, now im doing code generation. The compiler will be dynamic and weakly typed, so i will need to do somethings at runtime, like allocation. For this, i've already implemented some functions in C, and now i want to call these functions using builder.call from llvmlite.

I have not found documentation or examples of how to do this.

This function its just an simple example, the real ones are much larger.

C:

int some_function(int a)
{
     return a + 4;
}

Python:

...

    main_ty = ir.FunctionType(ir.IntType(32), [])
    func = ir.Function(module, main_ty, 'main')
    block = func.append_basic_block('entry')
    builder = ir.IRBuilder(block)

    # I want to do something like this...

    ret = builder.call(some_function, [ir.Constant(ir.IntType(32), 34)]);

...

I could write the functions directly using llvmlite builders, but will be much quick, cleaner and easy do it in C. Any help are welcome!


Solution

  • You could import a dynamic library containing the runtime.

    llvmlite.binding.load_library_permanently("runtime.so")
    

    Then you could simply generate normal function calls.