Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
numba
GitHub Repository: numba/llvmlite
Path: blob/main/examples/ll_fpadd.py
1154 views
1
from __future__ import print_function
2
3
from ctypes import CFUNCTYPE, c_double
4
5
import llvmlite.binding as llvm
6
7
8
# All these initializations are required for code generation!
9
llvm.initialize_native_target()
10
llvm.initialize_native_asmprinter() # yes, even this one
11
12
llvm_ir = """
13
; ModuleID = "examples/ir_fpadd.py"
14
target triple = "unknown-unknown-unknown"
15
target datalayout = ""
16
17
define double @"fpadd"(double %".1", double %".2")
18
{
19
entry:
20
%"res" = fadd double %".1", %".2"
21
ret double %"res"
22
}
23
"""
24
25
def create_execution_engine():
26
"""
27
Create an ExecutionEngine suitable for JIT code generation on
28
the host CPU. The engine is reusable for an arbitrary number of
29
modules.
30
"""
31
# Create a target machine representing the host
32
target = llvm.Target.from_default_triple()
33
target_machine = target.create_target_machine()
34
# And an execution engine with an empty backing module
35
backing_mod = llvm.parse_assembly("")
36
engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
37
return engine
38
39
40
def compile_ir(engine, llvm_ir):
41
"""
42
Compile the LLVM IR string with the given engine.
43
The compiled module object is returned.
44
"""
45
# Create a LLVM module object from the IR
46
mod = llvm.parse_assembly(llvm_ir)
47
mod.verify()
48
# Now add the module and make sure it is ready for execution
49
engine.add_module(mod)
50
engine.finalize_object()
51
return mod
52
53
54
engine = create_execution_engine()
55
mod = compile_ir(engine, llvm_ir)
56
57
# Look up the function pointer (a Python int)
58
func_ptr = engine.get_function_address("fpadd")
59
60
# Run the function via ctypes
61
cfunc = CFUNCTYPE(c_double, c_double, c_double)(func_ptr)
62
res = cfunc(1.0, 3.5)
63
print("fpadd(...) =", res)
64
65