Debian Codegraph @

rpython/jit/backend/llsupport/test/ztranslation_test.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import os, sys, py
4 from rpython.tool.udir import udir
5 from rpython.rlib.jit import JitDriver, unroll_parameters, set_param
6 from rpython.rlib.jit import PARAMETERS, dont_look_inside
7 from rpython.rlib.jit import promote, _get_virtualizable_token
8 from rpython.rlib import jit_hooks, rposix, rgc
9 from rpython.rlib.objectmodel import keepalive_until_here
10 from rpython.rlib.rthread import ThreadLocalReference, ThreadLocalField
11 from rpython.jit.backend.detect_cpu import getcpuclass
12 from rpython.jit.backend.test.support import CCompiledMixin
13 from rpython.jit.codewriter.policy import StopAtXPolicy
14 from rpython.config.config import ConfigError
15 from rpython.translator.tool.cbuild import ExternalCompilationInfo
16 from rpython.rtyper.lltypesystem import lltype, rffi, rstr
17 from rpython.rlib.rjitlog import rjitlog as jl
18
19
20 class TranslationTest(CCompiledMixin):
21 CPUClass = getcpuclass()
22
23 def test_stuff_translates(self):
24 # this is a basic test that tries to hit a number of features and their
25 # translation:
26 # - jitting of loops and bridges
27 # - two virtualizable types
28 # - set_param interface
29 # - profiler
30 # - full optimizer
31 # - floats neg and abs
32 # - cast_int_to_float
33 # - llexternal with macro=True
34 # - extra place for the zero after STR instances
35
36 class BasicFrame(object):
37 _virtualizable_ = ['i']
38
39 def __init__(self, i):
40 self.i = i
41
42 class Frame(BasicFrame):
43 pass
44
45 eci = ExternalCompilationInfo(post_include_bits=['''
46 #define pypy_my_fabs(x) fabs(x)
47 '''], includes=['math.h'])
48 myabs1 = rffi.llexternal('pypy_my_fabs', [lltype.Float],
49 lltype.Float, macro=True, releasegil=False,
50 compilation_info=eci)
51 myabs2 = rffi.llexternal('pypy_my_fabs', [lltype.Float],
52 lltype.Float, macro=True, releasegil=True,
53 compilation_info=eci)
54
55 @jl.returns(jl.MP_FILENAME,
56 jl.MP_LINENO,
57 jl.MP_INDEX)
58 def get_location():
59 return ("/home.py",0,0)
60
61 jitdriver = JitDriver(greens = [],
62 reds = ['total', 'frame', 'prev_s', 'j'],
63 virtualizables = ['frame'],
64 get_location = get_location)
65 def f(i, j):
66 for param, _ in unroll_parameters:
67 defl = PARAMETERS[param]
68 set_param(jitdriver, param, defl)
69 set_param(jitdriver, "threshold", 3)
70 set_param(jitdriver, "trace_eagerness", 2)
71 total = 0
72 frame = Frame(i)
73 j = float(j)
74 prev_s = rstr.mallocstr(16)
75 while frame.i > 3:
76 jitdriver.can_enter_jit(frame=frame, total=total, j=j,
77 prev_s=prev_s)
78 jitdriver.jit_merge_point(frame=frame, total=total, j=j,
79 prev_s=prev_s)
80 _get_virtualizable_token(frame)
81 total += frame.i
82 if frame.i >= 20:
83 frame.i -= 2
84 frame.i -= 1
85 j *= -0.712
86 if j + (-j): raise ValueError
87 j += frame.i
88 k = myabs1(myabs2(j))
89 if k - abs(j): raise ValueError
90 if k - abs(-j): raise ValueError
91 s = rstr.mallocstr(16)
92 rgc.ll_write_final_null_char(s)
93 rgc.ll_write_final_null_char(prev_s)
94 if (frame.i & 3) == 0:
95 prev_s = s
96 return chr(total % 253)
97 #
98 class Virt2(object):
99 _virtualizable_ = ['i']
100 def __init__(self, i):
101 self.i = i
102 from rpython.rlib.libffi import types, CDLL, ArgChain
103 from rpython.rlib.test.test_clibffi import get_libm_name
104 libm_name = get_libm_name(sys.platform)
105 jitdriver2 = JitDriver(greens=[], reds = ['v2', 'func', 'res', 'x'],
106 virtualizables = ['v2'])
107 def libffi_stuff(i, j):
108 lib = CDLL(libm_name)
109 func = lib.getpointer('fabs', [types.double], types.double)
110 res = 0.0
111 x = float(j)
112 v2 = Virt2(i)
113 while v2.i > 0:
114 jitdriver2.jit_merge_point(v2=v2, res=res, func=func, x=x)
115 promote(func)
116 argchain = ArgChain()
117 argchain.arg(x)
118 res = func.call(argchain, rffi.DOUBLE)
119 v2.i -= 1
120 return res
121 #
122 def main(i, j):
123 a_char = f(i, j)
124 a_float = libffi_stuff(i, j)
125 return ord(a_char) * 10 + int(a_float)
126 expected = main(40, -49)
127 res = self.meta_interp(main, [40, -49])
128 assert res == expected
129
130
131 class TranslationTestCallAssembler(CCompiledMixin):
132 CPUClass = getcpuclass()
133
134 def test_direct_assembler_call_translates(self):
135 """Test CALL_ASSEMBLER and the recursion limit"""
136 # - also tests threadlocalref_get
137 from rpython.rlib.rstackovf import StackOverflow
138
139 class Thing(object):
140 def __init__(self, val):
141 self.val = val
142
143 class Frame(object):
144 _virtualizable_ = ['thing']
145
146 driver = JitDriver(greens = ['codeno'], reds = ['i', 'frame'],
147 virtualizables = ['frame'],
148 get_printable_location = lambda codeno: str(codeno))
149 class SomewhereElse(object):
150 pass
151
152 somewhere_else = SomewhereElse()
153
154 class Foo(object):
155 pass
156 t = ThreadLocalReference(Foo, loop_invariant=True)
157 tf = ThreadLocalField(lltype.Char, "test_call_assembler_")
158
159 def change(newthing):
160 somewhere_else.frame.thing = newthing
161
162 def main(codeno):
163 frame = Frame()
164 somewhere_else.frame = frame
165 frame.thing = Thing(0)
166 portal(codeno, frame)
167 return frame.thing.val
168
169 def portal(codeno, frame):
170 i = 0
171 while i < 10:
172 driver.can_enter_jit(frame=frame, codeno=codeno, i=i)
173 driver.jit_merge_point(frame=frame, codeno=codeno, i=i)
174 nextval = frame.thing.val
175 if codeno == 0:
176 subframe = Frame()
177 subframe.thing = Thing(nextval)
178 nextval = portal(1, subframe)
179 elif frame.thing.val > 40:
180 change(Thing(13))
181 nextval = 13
182 frame.thing = Thing(nextval + 1)
183 i += 1
184 if t.get().nine != 9: raise ValueError
185 if ord(tf.getraw()) != 0x92: raise ValueError
186 return frame.thing.val
187
188 driver2 = JitDriver(greens = [], reds = ['n'])
189
190 def main2(bound):
191 try:
192 while portal2(bound) == -bound+1:
193 bound *= 2
194 except StackOverflow:
195 pass
196 return bound
197
198 def portal2(n):
199 while True:
200 driver2.jit_merge_point(n=n)
201 n -= 1
202 if n <= 0:
203 return n
204 n = portal2(n)
205 assert portal2(10) == -9
206
207 def setup(value):
208 foo = Foo()
209 foo.nine = value
210 t.set(foo)
211 tf.setraw("\x92")
212 return foo
213
214 def mainall(codeno, bound):
215 foo = setup(bound + 8)
216 result = main(codeno) + main2(bound)
217 keepalive_until_here(foo)
218 return result
219
220 tmp_obj = setup(9)
221 expected_1 = main(0)
222 res = self.meta_interp(mainall, [0, 1], inline=True,
223 policy=StopAtXPolicy(change))
224 print(hex(res))
225 assert res & 255 == expected_1
226 bound = res & ~255
227 assert 1024 <= bound <= 131072
228 assert bound & (bound-1) == 0 # a power of two
229
230
231 class TranslationTestJITStats(CCompiledMixin):
232 CPUClass = getcpuclass()
233
234 def test_jit_get_stats(self):
235 py.test.skip("disabled feature")
236
237 driver = JitDriver(greens = [], reds = ['i'])
238
239 def f():
240 i = 0
241 while i < 100000:
242 driver.jit_merge_point(i=i)
243 i += 1
244
245 def main():
246 jit_hooks.stats_set_debug(None, True)
247 f()
248 ll_times = jit_hooks.stats_get_loop_run_times(None)
249 return len(ll_times)
250
251 res = self.meta_interp(main, [])
252 assert res == 2
253 # one for loop and one for the prologue, no unrolling
254
255 def test_flush_trace_counts(self):
256 driver = JitDriver(greens = [], reds = ['i'])
257
258 def f():
259 i = 0
260 while i < 100000:
261 driver.jit_merge_point(i=i)
262 i += 1
263
264 def main():
265 jit_hooks.stats_set_debug(None, True)
266 f()
267 jl.stats_flush_trace_counts(None)
268 return 0
269
270 res = self.meta_interp(main, [])
271 assert res == 0
272
273 class TranslationRemoveTypePtrTest(CCompiledMixin):
274 CPUClass = getcpuclass()
275
276 def test_external_exception_handling_translates(self):
277 jitdriver = JitDriver(greens = [], reds = ['n', 'total'])
278
279 class ImDone(Exception):
280 def __init__(self, resvalue):
281 self.resvalue = resvalue
282
283 @dont_look_inside
284 def f(x, total):
285 if x <= 30:
286 raise ImDone(total * 10)
287 if x > 200:
288 return 2
289 raise ValueError
290 @dont_look_inside
291 def g(x):
292 if x > 150:
293 raise ValueError
294 return 2
295 class Base:
296 def meth(self):
297 return 2
298 class Sub(Base):
299 def meth(self):
300 return 1
301 @dont_look_inside
302 def h(x):
303 if x < 20000:
304 return Sub()
305 else:
306 return Base()
307 def myportal(i):
308 set_param(jitdriver, "threshold", 3)
309 set_param(jitdriver, "trace_eagerness", 2)
310 total = 0
311 n = i
312 while True:
313 jitdriver.can_enter_jit(n=n, total=total)
314 jitdriver.jit_merge_point(n=n, total=total)
315 try:
316 total += f(n, total)
317 except ValueError:
318 total += 1
319 try:
320 total += g(n)
321 except ValueError:
322 total -= 1
323 n -= h(n).meth() # this is to force a GUARD_CLASS
324 def main(i):
325 try:
326 myportal(i)
327 except ImDone as e:
328 return e.resvalue
329
330 # XXX custom fishing, depends on the exact env var and format
331 logfile = udir.join('test_ztranslation.log')
332 os.environ['PYPYLOG'] = 'jit-log-opt:%s' % (logfile,)
333 try:
334 res = self.meta_interp(main, [400])
335 assert res == main(400)
336 finally:
337 del os.environ['PYPYLOG']
338
339 guard_class = 0
340 for line in open(str(logfile)):
341 if 'guard_class' in line:
342 guard_class += 1
343 # if we get many more guard_classes (~93), it means that we generate
344 # guards that always fail (the following assert's original purpose
345 # is to catch the following case: each GUARD_CLASS is misgenerated
346 # and always fails with "gcremovetypeptr")
347 assert 0 < guard_class < 10