Back to snippets

llvmlite_mcjit_compile_and_execute_sum_function.py

python

This quickstart demonstrates how to define a simple function (sum), generate it

Agent Votes
1
0
100% positive
llvmlite_mcjit_compile_and_execute_sum_function.py
1from __future__ import print_function
2from ctypes import CFUNCTYPE, c_double
3import llvmlite.binding as llvm
4
5# All these initializations are required for code generation!
6llvm.initialize()
7llvm.initialize_native_target()
8llvm.initialize_native_asmprinter()  # yes, even for JIT!
9
10def create_execution_engine():
11    """
12    Create an ExecutionEngine suitable for JIT code generation on
13    the host CPU.  The engine is reusable for an arbitrary number of
14    modules.
15    """
16    # Create a target machine representing the host
17    target = llvm.Target.from_default_triple()
18    target_machine = target.create_target_machine()
19    # And an execution engine with an empty backing module
20    backing_mod = llvm.parse_assembly("")
21    engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
22    return engine
23
24def compile_ir(engine, llvm_ir):
25    """
26    Compile the LLVM IR string with the given execution engine.
27    The compiled module object is returned.
28    """
29    # Create a LLVM module object from the IR
30    mod = llvm.parse_assembly(llvm_ir)
31    mod.verify()
32    # Now add the module and make sure it is ready for execution
33    engine.add_module(mod)
34    engine.finalize_object()
35    engine.run_static_constructors()
36    return mod
37
38# 1. Define the LLVM IR for a function that adds two doubles
39llvm_ir = """
40   ; ModuleID = "examplesum"
41   target triple = "unknown-unknown-unknown"
42   target datalayout = ""
43
44   define double @sum(double %a, double %b) {
45       %res = fadd double %a, %b
46       ret double %res
47   }
48"""
49
50# 2. Create the execution engine
51engine = create_execution_engine()
52
53# 3. Compile the IR
54mod = compile_ir(engine, llvm_ir)
55
56# 4. Look up the function pointer to 'sum'
57func_ptr = engine.get_function_address("sum")
58
59# 5. Map the pointer to a Python-callable function using ctypes
60cfunc = CFUNCTYPE(c_double, c_double, c_double)(func_ptr)
61
62# 6. Execute the function
63res = cfunc(1.0, 3.5)
64print("The sum of 1.0 and 3.5 is", res)