Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
numba
GitHub Repository: numba/llvmlite
Path: blob/main/examples/sum.py
1154 views
1
from __future__ import print_function
2
3
from ctypes import CFUNCTYPE, c_int, POINTER
4
import sys
5
try:
6
from time import perf_counter as time
7
except ImportError:
8
from time import time
9
10
import numpy as np
11
12
try:
13
import faulthandler; faulthandler.enable()
14
except ImportError:
15
pass
16
17
import llvmlite.ir as ll
18
import llvmlite.binding as llvm
19
20
21
llvm.initialize_native_target()
22
llvm.initialize_native_asmprinter()
23
24
25
t1 = time()
26
27
fnty = ll.FunctionType(ll.IntType(32), [ll.IntType(32).as_pointer(),
28
ll.IntType(32)])
29
module = ll.Module()
30
31
func = ll.Function(module, fnty, name="sum")
32
33
bb_entry = func.append_basic_block()
34
bb_loop = func.append_basic_block()
35
bb_exit = func.append_basic_block()
36
37
builder = ll.IRBuilder()
38
builder.position_at_end(bb_entry)
39
40
builder.branch(bb_loop)
41
builder.position_at_end(bb_loop)
42
43
index = builder.phi(ll.IntType(32))
44
index.add_incoming(ll.Constant(index.type, 0), bb_entry)
45
accum = builder.phi(ll.IntType(32))
46
accum.add_incoming(ll.Constant(accum.type, 0), bb_entry)
47
48
ptr = builder.gep(func.args[0], [index])
49
value = builder.load(ptr)
50
51
added = builder.add(accum, value)
52
accum.add_incoming(added, bb_loop)
53
54
indexp1 = builder.add(index, ll.Constant(index.type, 1))
55
index.add_incoming(indexp1, bb_loop)
56
57
cond = builder.icmp_unsigned('<', indexp1, func.args[1])
58
builder.cbranch(cond, bb_loop, bb_exit)
59
60
builder.position_at_end(bb_exit)
61
builder.ret(added)
62
63
strmod = str(module)
64
65
t2 = time()
66
67
print("-- generate IR:", t2-t1)
68
69
t3 = time()
70
71
llmod = llvm.parse_assembly(strmod)
72
73
t4 = time()
74
75
print("-- parse assembly:", t4-t3)
76
77
print(llmod)
78
79
target_machine = llvm.Target.from_default_triple().create_target_machine()
80
pto = llvm.create_pipeline_tuning_options(speed_level=2)
81
pb = llvm.create_pass_builder(target_machine, pto)
82
pm = pb.getModulePassManager()
83
84
t5 = time()
85
86
pm.run(llmod, pb)
87
88
t6 = time()
89
90
print("-- optimize:", t6-t5)
91
92
t7 = time()
93
94
95
with llvm.create_mcjit_compiler(llmod, target_machine) as ee:
96
ee.finalize_object()
97
cfptr = ee.get_function_address("sum")
98
99
t8 = time()
100
print("-- JIT compile:", t8 - t7)
101
102
print(target_machine.emit_assembly(llmod))
103
104
cfunc = CFUNCTYPE(c_int, POINTER(c_int), c_int)(cfptr)
105
A = np.arange(10, dtype=np.int32)
106
res = cfunc(A.ctypes.data_as(POINTER(c_int)), A.size)
107
108
print(res, A.sum())
109
110
111