Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
numba
GitHub Repository: numba/llvmlite
Path: blob/main/examples/opaque_pointers/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
18
llvmlite.ir_layer_typed_pointers_enabled = False
19
20
import llvmlite.ir as ll
21
import llvmlite.binding as llvm
22
23
24
llvm.initialize_native_target()
25
llvm.initialize_native_asmprinter()
26
27
28
t1 = time()
29
30
# Pointers are opaque, so we should define them as such here.
31
fnty = ll.FunctionType(ll.IntType(32), [ll.PointerType(), ll.IntType(32)])
32
module = ll.Module()
33
34
func = ll.Function(module, fnty, name="sum")
35
36
bb_entry = func.append_basic_block()
37
bb_loop = func.append_basic_block()
38
bb_exit = func.append_basic_block()
39
40
builder = ll.IRBuilder()
41
builder.position_at_end(bb_entry)
42
43
builder.branch(bb_loop)
44
builder.position_at_end(bb_loop)
45
46
index = builder.phi(ll.IntType(32))
47
index.add_incoming(ll.Constant(index.type, 0), bb_entry)
48
accum = builder.phi(ll.IntType(32))
49
accum.add_incoming(ll.Constant(accum.type, 0), bb_entry)
50
51
# These GEP and load need an excplicit type.
52
ptr = builder.gep(func.args[0], [index], source_etype=ll.IntType(32))
53
value = builder.load(ptr, typ=ll.IntType(32))
54
55
added = builder.add(accum, value)
56
accum.add_incoming(added, bb_loop)
57
58
indexp1 = builder.add(index, ll.Constant(index.type, 1))
59
index.add_incoming(indexp1, bb_loop)
60
61
cond = builder.icmp_unsigned('<', indexp1, func.args[1])
62
builder.cbranch(cond, bb_loop, bb_exit)
63
64
builder.position_at_end(bb_exit)
65
builder.ret(added)
66
67
strmod = str(module)
68
69
t2 = time()
70
71
print("-- generate IR:", t2-t1)
72
73
t3 = time()
74
75
llmod = llvm.parse_assembly(strmod)
76
77
t4 = time()
78
79
print("-- parse assembly:", t4-t3)
80
81
print(llmod)
82
83
target_machine = llvm.Target.from_default_triple().create_target_machine()
84
pto = llvm.create_pipeline_tuning_options(speed_level=2)
85
pb = llvm.create_pass_builder(target_machine, pto)
86
pm = pb.getModulePassManager()
87
88
t5 = time()
89
90
pm.run(llmod, pb)
91
92
t6 = time()
93
94
print("-- optimize:", t6-t5)
95
96
t7 = time()
97
98
with llvm.create_mcjit_compiler(llmod, target_machine) as ee:
99
ee.finalize_object()
100
cfptr = ee.get_function_address("sum")
101
102
t8 = time()
103
print("-- JIT compile:", t8 - t7)
104
105
print(target_machine.emit_assembly(llmod))
106
107
cfunc = CFUNCTYPE(c_int, POINTER(c_int), c_int)(cfptr)
108
A = np.arange(10, dtype=np.int32)
109
res = cfunc(A.ctypes.data_as(POINTER(c_int)), A.size)
110
111
print(res, A.sum())
112
113
114