Debian Codegraph @

rpython/jit/codewriter/test/test_flatten.py

raw symbols SCIP
1 import py, sys
2 from rpython.jit.codewriter import support
3 from rpython.jit.codewriter.flatten import flatten_graph, reorder_renaming_list
4 from rpython.jit.codewriter.flatten import GraphFlattener, ListOfKind, Register
5 from rpython.jit.codewriter.format import assert_format
6 from rpython.jit.codewriter import longlong
7 from rpython.jit.codewriter.effectinfo import EffectInfo
8 from rpython.jit.metainterp.history import AbstractDescr
9 from rpython.jit.metainterp.support import int_signext
10 from rpython.rtyper.lltypesystem import lltype, rstr, rffi
11 from rpython.rtyper import rclass
12 from rpython.flowspace.model import SpaceOperation, Variable, Constant
13 from rpython.translator.unsimplify import varoftype
14 from rpython.rlib.rarithmetic import ovfcheck, r_uint, r_longlong, r_ulonglong
15 from rpython.rlib.jit import dont_look_inside, _we_are_jitted, JitDriver
16 from rpython.rlib.objectmodel import keepalive_until_here
17 from rpython.rlib import jit, debug
18
19 _WIN32 = sys.platform == "win32"
20
21 class FakeRegAlloc:
22 # a RegAllocator that answers "0, 1, 2, 3, 4..." for the colors
23 def __init__(self):
24 self.seen = {}
25 self.num_colors = 0
26 def getcolor(self, v):
27 if v not in self.seen:
28 self.seen[v] = self.num_colors
29 self.num_colors += 1
30 return self.seen[v]
31
32 def fake_regallocs():
33 return {'int': FakeRegAlloc(),
34 'ref': FakeRegAlloc(),
35 'float': FakeRegAlloc()}
36
37 class FakeDescr(AbstractDescr):
38 _for_tests_only = True
39 def __init__(self, oopspecindex=None):
40 self.oopspecindex = oopspecindex
41 def __repr__(self):
42 return '<Descr>'
43
44 class FakeDict(object):
45 def __getitem__(self, key):
46 F = lltype.FuncType([lltype.Signed, lltype.Signed], lltype.Signed)
47 f = lltype.functionptr(F, key[0])
48 c_func = Constant(f, lltype.typeOf(f))
49 return c_func, lltype.Signed
50
51 class FakeCPU:
52 class tracker:
53 pass
54
55 def __init__(self, rtyper):
56 rtyper._builtin_func_for_spec_cache = FakeDict()
57 self.rtyper = rtyper
58 def calldescrof(self, FUNC, ARGS, RESULT, effectinfo):
59 return FakeDescr()
60 def fielddescrof(self, STRUCT, name):
61 return FakeDescr()
62 def sizeof(self, STRUCT, vtable=None):
63 return FakeDescr()
64 def arraydescrof(self, ARRAY):
65 return FakeDescr()
66
67 class FakeCallInfoCollection:
68 def add(self, *args):
69 pass
70
71 class FakeCallControl:
72 _descr_cannot_raise = FakeDescr()
73 callinfocollection = FakeCallInfoCollection()
74 def guess_call_kind(self, op):
75 return 'residual'
76 def getcalldescr(self, op, oopspecindex=EffectInfo.OS_NONE,
77 extraeffect=None, extradescr=None, calling_graph=None):
78 try:
79 name = op.args[0].value._obj._name
80 if 'cannot_raise' in name or name.startswith('cast_'):
81 return self._descr_cannot_raise
82 except AttributeError:
83 pass
84 return FakeDescr(oopspecindex)
85 def calldescr_canraise(self, calldescr):
86 return calldescr is not self._descr_cannot_raise and calldescr.oopspecindex == EffectInfo.OS_NONE
87 def get_vinfo(self, VTYPEPTR):
88 if hasattr(VTYPEPTR.TO, 'inst_vlist'):
89 return FakeVInfo()
90 return None
91
92 class FakeCallControlWithVRefInfo:
93 class virtualref_info:
94 JIT_VIRTUAL_REF = lltype.GcStruct('VREF', ('parent', rclass.OBJECT))
95 jit_virtual_ref_vtable = lltype.malloc(rclass.OBJECT_VTABLE,
96 immortal=True)
97 def guess_call_kind(self, op):
98 if op.args[0].value._obj._name == 'jit_force_virtual':
99 return 'residual'
100 return 'builtin'
101 def getcalldescr(self, op, **kwds):
102 return FakeDescr()
103 def calldescr_canraise(self, calldescr):
104 return False
105
106 class FakeVInfo:
107 static_field_to_extra_box = {}
108 array_fields = {'inst_vlist': '?'}
109 array_field_counter = {'inst_vlist': 0}
110 array_field_descrs = [FakeDescr()]
111 array_descrs = [FakeDescr()]
112
113 # ____________________________________________________________
114
115 def test_reorder_renaming_list():
116 result = reorder_renaming_list([], [])
117 assert result == []
118 result = reorder_renaming_list([1, 2, 3], [4, 5, 6])
119 assert result == [(1, 4), (2, 5), (3, 6)]
120 result = reorder_renaming_list([4, 5, 1, 2], [1, 2, 3, 4])
121 assert result == [(1, 3), (4, 1), (2, 4), (5, 2)]
122 result = reorder_renaming_list([1, 2], [2, 1])
123 assert result == [(1, None), (2, 1), (None, 2)]
124 result = reorder_renaming_list([4, 3, 6, 1, 2, 5, 7],
125 [1, 2, 5, 3, 4, 6, 8])
126 assert result == [(7, 8),
127 (4, None), (2, 4), (3, 2), (1, 3), (None, 1),
128 (6, None), (5, 6), (None, 5)]
129
130 def test_repr():
131 assert repr(Register('int', 13)) == '%i13'
132
133 # ____________________________________________________________
134
135
136 class TestFlatten:
137
138 def make_graphs(self, func, values):
139 self.rtyper = support.annotate(func, values)
140 return self.rtyper.annotator.translator.graphs
141
142 def encoding_test(self, func, args, expected,
143 transform=False, liveness=False, cc=None, jd=None):
144 graphs = self.make_graphs(func, args)
145 #graphs[0].show()
146 if transform:
147 from rpython.jit.codewriter.jtransform import transform_graph
148 cc = cc or FakeCallControl()
149 transform_graph(graphs[0], FakeCPU(self.rtyper), cc, jd)
150 ssarepr = flatten_graph(graphs[0], fake_regallocs(),
151 _include_all_exc_links=not transform,
152 cpu=FakeCPU(self.rtyper))
153 if liveness:
154 from rpython.jit.codewriter.liveness import compute_liveness
155 compute_liveness(ssarepr)
156 if expected is not None:
157 assert_format(ssarepr, expected)
158
159 def test_simple(self):
160 def f(n):
161 return n + 10
162 self.encoding_test(f, [5], """
163 int_add %i0, $10 -> %i1
164 int_return %i1
165 """)
166
167 def test_if(self):
168 def f(n):
169 if n > 0:
170 n -= 3
171 return n + 1
172 self.encoding_test(f, [10], """
173 int_gt %i0, $0 -> %i1
174 -live-
175 goto_if_not %i1, L1
176 int_copy %i0 -> %i2
177 int_sub %i2, $3 -> %i3
178 int_copy %i3 -> %i4
179 L2:
180 int_add %i4, $1 -> %i5
181 int_return %i5
182 ---
183 L1:
184 int_copy %i0 -> %i4
185 goto L2
186 """)
187
188 def test_loop(self):
189 def f(a, b):
190 while a > 0:
191 b += a
192 a -= 1
193 return b
194 self.encoding_test(f, [5, 6], """
195 int_copy %i0 -> %i2
196 int_copy %i1 -> %i3
197 L1:
198 int_gt %i2, $0 -> %i4
199 -live-
200 goto_if_not %i4, L2
201 int_copy %i2 -> %i5
202 int_copy %i3 -> %i6
203 int_add %i6, %i5 -> %i7
204 int_sub %i5, $1 -> %i8
205 int_copy %i8 -> %i2
206 int_copy %i7 -> %i3
207 goto L1
208 ---
209 L2:
210 int_return %i3
211 """)
212
213 def test_loop_opt(self):
214 def f(a, b):
215 while a > 0:
216 b += a
217 a -= 1
218 return b
219 self.encoding_test(f, [5, 6], """
220 int_copy %i0 -> %i2
221 int_copy %i1 -> %i3
222 L1:
223 -live-
224 goto_if_not_int_gt %i2, $0, L2
225 int_copy %i2 -> %i4
226 int_copy %i3 -> %i5
227 int_add %i5, %i4 -> %i6
228 int_sub %i4, $1 -> %i7
229 int_copy %i7 -> %i2
230 int_copy %i6 -> %i3
231 goto L1
232 ---
233 L2:
234 int_return %i3
235 """, transform=True)
236
237 def test_float(self):
238 def f(i, f):
239 return (i*5) + (f*0.25)
240 self.encoding_test(f, [4, 7.5], """
241 int_mul %i0, $5 -> %i1
242 float_mul %f0, $0.25 -> %f1
243 cast_int_to_float %i1 -> %f2
244 float_add %f2, %f1 -> %f3
245 float_return %f3
246 """)
247
248 def test_arg_sublist_1(self):
249 v1 = varoftype(lltype.Signed)
250 v2 = varoftype(lltype.Char)
251 v3 = varoftype(rclass.OBJECTPTR)
252 v4 = varoftype(lltype.Ptr(rstr.STR))
253 v5 = varoftype(lltype.Float)
254 op = SpaceOperation('residual_call_ir_f',
255 [Constant(12345, lltype.Signed), # function ptr
256 ListOfKind('int', [v1, v2]), # int args
257 ListOfKind('ref', [v3, v4])], # ref args
258 v5) # result
259 flattener = GraphFlattener(None, fake_regallocs())
260 flattener.serialize_op(op)
261 assert_format(flattener.ssarepr, """
262 residual_call_ir_f $12345, I[%i0, %i1], R[%r0, %r1] -> %f0
263 """)
264
265 def test_same_as_removal(self):
266 def f(a):
267 b = chr(a)
268 return ord(b) + a
269 self.encoding_test(f, [65], """
270 int_add %i0, %i0 -> %i1
271 int_return %i1
272 """, transform=True)
273
274 def test_descr(self):
275 class FooDescr(AbstractDescr):
276 def __repr__(self):
277 return 'hi_there!'
278 op = SpaceOperation('foobar', [FooDescr()], None)
279 flattener = GraphFlattener(None, fake_regallocs())
280 flattener.serialize_op(op)
281 assert_format(flattener.ssarepr, """
282 foobar hi_there!
283 """)
284
285 def test_switch_dict(self):
286 def f(x):
287 if x == 1: return 61
288 elif x == 2: return 511
289 elif x == 3: return -22
290 elif x == 4: return 81
291 elif x == 5: return 17
292 elif x == 6: return 54
293 return -1
294 self.encoding_test(f, [65], """
295 -live-
296 switch %i0, <SwitchDictDescr 1:L1, 2:L2, 3:L3, 4:L4, 5:L5, 6:L6>
297 int_return $-1
298 ---
299 L1:
300 -live-
301 int_return $61
302 ---
303 L2:
304 -live-
305 int_return $511
306 ---
307 L3:
308 -live-
309 int_return $-22
310 ---
311 L4:
312 -live-
313 int_return $81
314 ---
315 L5:
316 -live-
317 int_return $17
318 ---
319 L6:
320 -live-
321 int_return $54
322 """)
323
324 def test_switch_longlong(self):
325 def f(n):
326 n = r_longlong(n)
327 if n == r_longlong(-5): return 12
328 elif n == r_longlong(2): return 51
329 elif n == r_longlong(7): return 1212
330 else: return 42
331 self.encoding_test(f, [65], None)
332
333 def test_exc_exitswitch(self):
334 def g(i):
335 pass
336
337 def f(i):
338 try:
339 g(i)
340 except ValueError:
341 return 1
342 except KeyError:
343 return 2
344 else:
345 return 3
346
347 self.encoding_test(f, [65], """
348 direct_call $<* fn g>, %i0
349 catch_exception L1
350 int_return $3
351 ---
352 L1:
353 goto_if_exception_mismatch $<* struct object_vtable>, L2
354 int_return $1
355 ---
356 L2:
357 goto_if_exception_mismatch $<* struct object_vtable>, L3
358 int_return $2
359 ---
360 L3:
361 reraise
362 """)
363
364 def test_exc_exitswitch_2(self):
365 class FooError(Exception):
366 pass
367 @dont_look_inside
368 def g(i):
369 FooError().num = 1
370 FooError().num = 2
371 def f(i):
372 try:
373 g(i)
374 except FooError as e:
375 return e.num
376 except Exception:
377 return 3
378 else:
379 return 4
380
381 self.encoding_test(f, [65], """
382 residual_call_ir_v $<* fn g>, I[%i0], R[], <Descr>
383 -live-
384 catch_exception L1
385 int_return $4
386 ---
387 L1:
388 goto_if_exception_mismatch $<* struct object_vtable>, L2
389 last_exc_value -> %r0
390 getfield_gc_i %r0, <Descr> -> %i1
391 int_return %i1
392 ---
393 L2:
394 int_return $3
395 """, transform=True)
396
397 def test_exc_raise_1(self):
398 class FooError(Exception):
399 pass
400 fooerror = FooError()
401 def f(i):
402 raise fooerror
403
404 self.encoding_test(f, [65], """
405 raise $<* struct object>
406 """, transform=True)
407
408 def test_exc_raise_2(self):
409 def g(i):
410 pass
411 def f(i):
412 try:
413 g(i)
414 except Exception:
415 raise KeyError
416
417 self.encoding_test(f, [65], """
418 direct_call $<* fn g>, %i0
419 catch_exception L1
420 void_return
421 ---
422 L1:
423 raise $<* struct object>
424 """)
425
426 def test_exc_finally(self):
427 def get_exception(n):
428 if n > 5:
429 raise ValueError
430 class Foo:
431 pass
432 Foo.__module__ = "test"
433 foo = Foo()
434 def f(i):
435 try:
436 get_exception(i)
437 finally:
438 foo.sideeffect = 5
439
440 self.encoding_test(f, [65], """
441 residual_call_ir_v $<* fn get_exception>, I[%i0], R[], <Descr>
442 -live-
443 catch_exception L1
444 setfield_gc_i $<* struct test.Foo>, $5, <Descr>
445 void_return
446 ---
447 L1:
448 last_exception -> %i1
449 last_exc_value -> %r0
450 setfield_gc_i $<* struct test.Foo>, $5, <Descr>
451 -live-
452 raise %r0
453 """, transform=True)
454
455 def test_goto_if_not_int_is_true(self):
456 def f(i):
457 return not i
458
459 # note that 'goto_if_not_int_is_true' is not the same thing
460 # as just 'goto_if_not', because the last one expects a boolean
461 self.encoding_test(f, [7], """
462 -live-
463 goto_if_not_int_is_true %i0, L1
464 int_return $False
465 ---
466 L1:
467 int_return $True
468 """, transform=True)
469
470 def test_assert_disappears(self):
471 def f(i):
472 assert i > 5
473 return i
474 self.encoding_test(f, [7], """
475 int_return %i0
476 """)
477
478 def test_int_floordiv_ovf_zer(self):
479 def f(i, j):
480 assert i >= 0
481 assert j >= 0
482 try:
483 return ovfcheck(i // j)
484 except OverflowError:
485 return 42
486 except ZeroDivisionError:
487 return -42
488 self.encoding_test(f, [7, 2], """
489 residual_call_ir_i $<* fn ll_int_py_div_ovf_zer__Signed_Signed>, I[%i0, %i1], R[], <Descr> -> %i2
490 -live-
491 catch_exception L1
492 int_return %i2
493 ---
494 L1:
495 goto_if_exception_mismatch $<* struct object_vtable>, L2
496 int_return $42
497 ---
498 L2:
499 goto_if_exception_mismatch $<* struct object_vtable>, L3
500 int_return $-42
501 ---
502 L3:
503 reraise
504 """, transform=True)
505
506 def test_int_mod_ovf(self):
507 def f(i, j):
508 assert i >= 0
509 assert j >= 0
510 try:
511 return ovfcheck(i % j)
512 except OverflowError:
513 return 42
514 # XXX so far, this really produces a int_mod_ovf_zer...
515 self.encoding_test(f, [7, 2], """
516 residual_call_ir_i $<* fn ll_int_py_mod_ovf_zer__Signed_Signed>, I[%i0, %i1], R[], <Descr> -> %i2
517 -live-
518 catch_exception L1
519 int_return %i2
520 ---
521 L1:
522 goto_if_exception_mismatch $<* struct object_vtable>, L2
523 int_return $42
524 ---
525 L2:
526 reraise
527 """, transform=True)
528
529 def test_simple_branch(self):
530 def f(n, m1, m2):
531 if n:
532 return m1
533 else:
534 return m2
535 self.encoding_test(f, [4, 5, 6], """
536 -live- %i0, %i1, %i2
537 goto_if_not_int_is_true %i0, L1
538 int_return %i1
539 ---
540 L1:
541 int_return %i2
542 """, transform=True, liveness=True)
543
544 def test_int_add_ovf(self):
545 def f(i, j):
546 try:
547 return ovfcheck(i + j)
548 except OverflowError:
549 return 42
550 self.encoding_test(f, [7, 2], """
551 -live- %i0, %i1
552 int_add_jump_if_ovf L1, %i0, %i1 -> %i2
553 int_return %i2
554 ---
555 L1:
556 int_return $42
557 """, transform=True, liveness=True)
558
559 def test_int_sub_ovf(self):
560 def f(i, j):
561 try:
562 return ovfcheck(i - j)
563 except OverflowError:
564 return 42
565 self.encoding_test(f, [7, 2], """
566 -live- %i0, %i1
567 int_sub_jump_if_ovf L1, %i0, %i1 -> %i2
568 int_return %i2
569 ---
570 L1:
571 int_return $42
572 """, transform=True, liveness=True)
573
574 def test_int_mul_ovf(self):
575 def f(i, j):
576 try:
577 return ovfcheck(i * j)
578 except OverflowError:
579 return 42
580 self.encoding_test(f, [7, 2], """
581 -live- %i0, %i1
582 int_mul_jump_if_ovf L1, %i0, %i1 -> %i2
583 int_return %i2
584 ---
585 L1:
586 int_return $42
587 """, transform=True, liveness=True)
588
589 def test_multiple_int_add_ovf(self):
590 def f(i, j):
591 try:
592 ovfcheck(j + i)
593 return ovfcheck(i + j)
594 except OverflowError:
595 return 42
596 self.encoding_test(f, [7, 2], """
597 -live- %i0, %i1
598 int_add_jump_if_ovf L1, %i1, %i0 -> %i2
599 int_copy %i1 -> %i3
600 int_copy %i0 -> %i4
601 -live- %i3, %i4
602 int_add_jump_if_ovf L2, %i4, %i3 -> %i5
603 int_return %i5
604 ---
605 L2:
606 int_return $42
607 ---
608 L1:
609 int_return $42
610 """, transform=True, liveness=True)
611
612 def test_ovfcheck_no_catch(self):
613 def f(i, j):
614 return ovfcheck(i + j)
615 err = py.test.raises(Exception, "self.encoding_test(f, [7, 2], '',"
616 "transform=True, liveness=True)")
617 assert "ovfcheck()" in str(err.value)
618
619 def test_ovfcheck_reraise(self):
620 def f(i, j):
621 try:
622 ovfcheck(j + i)
623 except OverflowError:
624 raise
625 self.encoding_test(f, [7, 2], """
626 -live- %i0, %i1
627 int_add_jump_if_ovf L1, %i1, %i0 -> %i2
628 void_return
629 ---
630 L1:
631 raise $<* struct object>
632 """, transform=True, liveness=True)
633
634 def test_residual_call_raising(self):
635 @dont_look_inside
636 def g(i, j):
637 return ovfcheck(i + j)
638 def f(i, j):
639 try:
640 return g(i, j)
641 except Exception:
642 return 42 + j
643 self.encoding_test(f, [7, 2], """
644 residual_call_ir_i $<* fn g>, I[%i0, %i1], R[], <Descr> -> %i2
645 -live- %i1, %i2
646 catch_exception L1
647 int_return %i2
648 ---
649 L1:
650 int_copy %i1 -> %i3
651 int_add %i3, $42 -> %i4
652 int_return %i4
653 """, transform=True, liveness=True)
654
655 def test_residual_call_nonraising(self):
656 @dont_look_inside
657 def cannot_raise(i, j):
658 return i + j
659 def f(i, j):
660 try:
661 return cannot_raise(i, j)
662 except Exception:
663 return 42 + j
664 self.encoding_test(f, [7, 2], """
665 residual_call_ir_i $<* fn cannot_raise>, I[%i0, %i1], R[], <Descr> -> %i2
666 int_return %i2
667 """, transform=True, liveness=True)
668
669 def test_we_are_jitted(self):
670 def f(x):
671 if _we_are_jitted:
672 return 2
673 else:
674 return 3 + x
675 self.encoding_test(f, [5], """
676 int_return $2
677 """, transform=True)
678
679 def test_jitdriver(self):
680 myjitdriver = JitDriver(greens = ['x'], reds = ['y'])
681 def f(x, y):
682 myjitdriver.jit_merge_point(x=x, y=y)
683 myjitdriver.can_enter_jit(x=y, y=x)
684 class FakeJitDriverSD:
685 jitdriver = myjitdriver
686 index = 27
687 jd = FakeJitDriverSD()
688 class MyFakeCallControl(FakeCallControl):
689 def jitdriver_sd_from_jitdriver(self, jitdriver):
690 assert jitdriver == myjitdriver
691 return jd
692 self.encoding_test(f, [4, 5], """
693 -live- %i0, %i1
694 int_guard_value %i0
695 -live- %i0, %i1
696 jit_merge_point $27, I[%i0], R[], F[], I[%i1], R[], F[]
697 -live-
698 loop_header $27
699 void_return
700 """, transform=True, liveness=True, cc=MyFakeCallControl(), jd=jd)
701
702 def test_keepalive(self):
703 S = lltype.GcStruct('S')
704 def g():
705 return lltype.malloc(S)
706 def f(x):
707 p = g()
708 q = g()
709 keepalive_until_here(p)
710 keepalive_until_here(q)
711 return x
712 self.encoding_test(f, [5], """
713 residual_call_r_r $<* fn g>, R[], <Descr> -> %r0
714 -live-
715 residual_call_r_r $<* fn g>, R[], <Descr> -> %r1
716 -live-
717 -live- %r0
718 -live- %r1
719 int_return %i0
720 """, transform=True)
721 self.encoding_test(f, [5], """
722 residual_call_r_r $<* fn g>, R[], <Descr> -> %r0
723 -live- %i0, %r0
724 residual_call_r_r $<* fn g>, R[], <Descr> -> %r1
725 -live- %i0, %r0, %r1
726 int_return %i0
727 """, transform=True, liveness=True)
728
729 def test_ptr_nonzero(self):
730 def f(p):
731 if p:
732 return 12
733 return 34
734 S = lltype.GcStruct('S')
735 self.encoding_test(f, [lltype.malloc(S)], """
736 -live- %r0
737 goto_if_not_ptr_nonzero %r0, L1
738 int_return $12
739 ---
740 L1:
741 int_return $34
742 """, transform=True, liveness=True)
743
744 def test_vref_simple(self):
745 class X:
746 pass
747 def f():
748 return jit.virtual_ref(X())
749 self.encoding_test(f, [], """
750 new_with_vtable <Descr> -> %r0
751 virtual_ref %r0 -> %r1
752 ref_return %r1
753 """, transform=True, cc=FakeCallControlWithVRefInfo())
754
755 def test_vref_forced(self):
756 class X:
757 pass
758 def f():
759 vref = jit.virtual_ref(X())
760 return vref()
761 # The call vref() is a jit_force_virtual operation in the original
762 # graph. It becomes in the JitCode a residual call to a helper that
763 # contains itself a jit_force_virtual.
764 self.encoding_test(f, [], """
765 new_with_vtable <Descr> -> %r0
766 virtual_ref %r0 -> %r1
767 -live-
768 residual_call_r_r $<* fn jit_force_virtual>, R[%r1], <Descr> -> %r2
769 ref_return %r2
770 """, transform=True, cc=FakeCallControlWithVRefInfo())
771
772 def test_array_operations(self):
773 A = lltype.GcArray(lltype.Signed)
774 def f():
775 array = lltype.malloc(A, 5)
776 array[2] = 5
777 return array[2] + len(array)
778 self.encoding_test(f, [], """
779 new_array $5, <Descr> -> %r0
780 setarrayitem_gc_i %r0, $2, $5, <Descr>
781 getarrayitem_gc_i %r0, $2, <Descr> -> %i0
782 arraylen_gc %r0, <Descr> -> %i1
783 int_add %i0, %i1 -> %i2
784 int_return %i2
785 """, transform=True)
786
787 def test_void_array_operations(self):
788 A = lltype.GcArray(lltype.Void)
789 def f():
790 array = lltype.malloc(A, 5)
791 array[2] = None
792 x = array[2]
793 return len(array)
794 self.encoding_test(f, [], """
795 new_array $5, <Descr> -> %r0
796 arraylen_gc %r0, <Descr> -> %i0
797 int_return %i0
798 """, transform=True)
799
800 def test_string_operations(self):
801 from rpython.rtyper.lltypesystem import rstr
802 def f(n):
803 s = lltype.malloc(rstr.STR, 2)
804 s.chars[1] = chr(n)
805 return ord(s.chars[1]) + len(s.chars)
806 self.encoding_test(f, [512], """
807 newstr $2 -> %r0
808 strsetitem %r0, $1, %i0
809 strgetitem %r0, $1 -> %i1
810 strlen %r0 -> %i2
811 int_add %i1, %i2 -> %i3
812 int_return %i3
813 """, transform=True)
814
815 def test_uint_operations(self):
816 def f(n):
817 return ((r_uint(n) - 123) >> 1) <= r_uint(456)
818 self.encoding_test(f, [200], """
819 int_sub %i0, $123L -> %i1
820 uint_rshift %i1, $1 -> %i2
821 uint_le %i2, $456L -> %i3
822 int_return %i3
823 """, transform=True)
824
825 def test_int_between(self):
826 from rpython.rtyper.lltypesystem.lloperation import llop
827 def f(n, m, p):
828 return llop.int_between(lltype.Bool, n, m, p)
829 self.encoding_test(f, [5, 6, 7], """
830 int_between %i0, %i1, %i2 -> %i3
831 int_return %i3
832 """, transform=True)
833
834 def test_force_cast_ints(self):
835 # NB: we don't need to test for INT here, the logic in jtransform is
836 # general enough so that if we have the below cases it should
837 # generalize also to INT
838
839 # windows: ULONG is UINT which is shorter than Signed
840 if _WIN32:
841 ulong_cast = "int_and %i0, $4294967295 -> %i1"
842 ulong_sign = "int_signext %i0, $4 -> %i1"
843 else:
844 ulong_cast = ""
845 ulong_sign = ""
846 for FROM, TO, expected in [
847 (rffi.SIGNEDCHAR, rffi.SIGNEDCHAR, ""),
848 (rffi.SIGNEDCHAR, rffi.UCHAR, "int_and %i0, $255 -> %i1"),
849 (rffi.SIGNEDCHAR, rffi.SHORT, ""),
850 (rffi.SIGNEDCHAR, rffi.USHORT, "int_and %i0, $65535 -> %i1"),
851 (rffi.SIGNEDCHAR, rffi.LONG, ""),
852 (rffi.SIGNEDCHAR, rffi.ULONG, ulong_cast),
853
854 (rffi.UCHAR, rffi.SIGNEDCHAR, "int_signext %i0, $1 -> %i1"),
855 (rffi.UCHAR, rffi.UCHAR, ""),
856 (rffi.UCHAR, rffi.SHORT, ""),
857 (rffi.UCHAR, rffi.USHORT, ""),
858 (rffi.UCHAR, rffi.LONG, ""),
859 (rffi.UCHAR, rffi.ULONG, ""),
860
861 (rffi.SHORT, rffi.SIGNEDCHAR, "int_signext %i0, $1 -> %i1"),
862 (rffi.SHORT, rffi.UCHAR, "int_and %i0, $255 -> %i1"),
863 (rffi.SHORT, rffi.SHORT, ""),
864 (rffi.SHORT, rffi.USHORT, "int_and %i0, $65535 -> %i1"),
865 (rffi.SHORT, rffi.LONG, ""),
866 (rffi.SHORT, rffi.ULONG, ulong_cast),
867
868 (rffi.USHORT, rffi.SIGNEDCHAR, "int_signext %i0, $1 -> %i1"),
869 (rffi.USHORT, rffi.UCHAR, "int_and %i0, $255 -> %i1"),
870 (rffi.USHORT, rffi.SHORT, "int_signext %i0, $2 -> %i1"),
871 (rffi.USHORT, rffi.USHORT, ""),
872 (rffi.USHORT, rffi.LONG, ""),
873 (rffi.USHORT, rffi.ULONG, ""),
874 (rffi.USHORT, lltype.Bool, "int_is_true %i0 -> %i1"),
875
876 (rffi.LONG, rffi.SIGNEDCHAR, "int_signext %i0, $1 -> %i1"),
877 (rffi.LONG, rffi.UCHAR, "int_and %i0, $255 -> %i1"),
878 (rffi.LONG, rffi.SHORT, "int_signext %i0, $2 -> %i1"),
879 (rffi.LONG, rffi.USHORT, "int_and %i0, $65535 -> %i1"),
880 (rffi.LONG, lltype.Bool, "int_is_true %i0 -> %i1"),
881 (rffi.LONG, rffi.LONG, ""),
882 (rffi.LONG, rffi.ULONG, ulong_cast),
883
884 (rffi.ULONG, rffi.SIGNEDCHAR, "int_signext %i0, $1 -> %i1"),
885 (rffi.ULONG, rffi.UCHAR, "int_and %i0, $255 -> %i1"),
886 (rffi.ULONG, rffi.SHORT, "int_signext %i0, $2 -> %i1"),
887 (rffi.ULONG, rffi.USHORT, "int_and %i0, $65535 -> %i1"),
888 (rffi.ULONG, lltype.Bool, "int_is_true %i0 -> %i1"),
889 (rffi.ULONG, rffi.LONG, ulong_sign),
890 (rffi.ULONG, rffi.ULONG, ""),
891 ]:
892 expected = [s.strip() for s in expected.splitlines()]
893 check_force_cast(FROM, TO, expected, 42)
894 check_force_cast(FROM, TO, expected, -42)
895 returnvar = "%i" + str(len(expected))
896 expected.append('int_return ' + returnvar)
897 expectedstr = '\n'.join(expected)
898 #
899 def f(n):
900 return rffi.cast(TO, n)
901 self.encoding_test(f, [rffi.cast(FROM, 42)], expectedstr,
902 transform=True)
903
904 if not longlong.is_64_bit:
905 if FROM in (rffi.LONG, rffi.ULONG):
906 if FROM == rffi.LONG:
907 FROM = rffi.LONGLONG
908 else:
909 FROM = rffi.ULONGLONG
910 if TO == lltype.Bool:
911 prefix = 'u' if FROM == rffi.ULONGLONG else ''
912 expected = [
913 "residual_call_irf_i $<* fn %sllong_ne>, I[], R[], F[%%f0, $0L], <Descr> -> %%i0" % prefix,
914 "int_return %i0",
915 ]
916 else:
917 expected.insert(0,
918 "residual_call_irf_i $<* fn llong_to_int>, I[], R[], F[%f0], <Descr> -> %i0")
919 expectedstr = '\n'.join(expected)
920 self.encoding_test(f, [rffi.cast(FROM, 42)], expectedstr,
921 transform=True)
922 elif TO in (rffi.LONG, rffi.ULONG):
923 if rffi.cast(FROM, -1) < 0:
924 fnname = "llong_from_int"
925 else:
926 fnname = "llong_from_uint"
927 if TO == rffi.LONG:
928 TO = rffi.LONGLONG
929 else:
930 TO = rffi.ULONGLONG
931 fnname = "u" + fnname
932 expected.pop() # remove int_return
933 expected.append(
934 "residual_call_irf_f $<* fn %s>, I[%s], R[], F[], <Descr> -> %%f0"
935 % (fnname, returnvar))
936 expected.append("float_return %f0")
937 expectedstr = '\n'.join(expected)
938 self.encoding_test(f, [rffi.cast(FROM, 42)], expectedstr,
939 transform=True)
940
941 def test_force_cast_pointer(self):
942 def h(p):
943 return rffi.cast(rffi.VOIDP, p)
944 self.encoding_test(h, [lltype.nullptr(rffi.CCHARP.TO)], """
945 int_return %i0
946 """, transform=True)
947
948 def test_force_cast_floats(self):
949 # Caststs to lltype.Float
950 def f(n):
951 return rffi.cast(lltype.Float, n)
952 self.encoding_test(f, [12.456], """
953 float_return %f0
954 """, transform=True)
955 self.encoding_test(f, [rffi.cast(rffi.SIGNEDCHAR, 42)], """
956 cast_int_to_float %i0 -> %f0
957 float_return %f0
958 """, transform=True)
959 def f(n):
960 return rffi.cast(lltype.Bool, n)
961 self.encoding_test(f, [0.1], """
962 float_ne %f0, $0.0 -> %i0
963 int_return %i0
964 """, transform=True)
965 self.encoding_test(f, [rffi.cast(lltype.SingleFloat, 0.5)], """
966 cast_singlefloat_to_float %i0 -> %f0
967 float_ne %f0, $0.0 -> %i1
968 int_return %i1
969 """, transform=True)
970
971 # Casts to lltype.SingleFloat
972 def g(n):
973 return rffi.cast(lltype.SingleFloat, n)
974 self.encoding_test(g, [12.456], """
975 cast_float_to_singlefloat %f0 -> %i0
976 int_return %i0
977 """, transform=True)
978 self.encoding_test(g, [rffi.cast(rffi.SIGNEDCHAR, 42)], """
979 cast_int_to_float %i0 -> %f0
980 cast_float_to_singlefloat %f0 -> %i1
981 int_return %i1
982 """, transform=True)
983
984 # Casts from floats
985 def f(n):
986 return rffi.cast(rffi.SIGNEDCHAR, n)
987 self.encoding_test(f, [12.456], """
988 cast_float_to_int %f0 -> %i0
989 int_signext %i0, $1 -> %i1
990 int_return %i1
991 """, transform=True)
992 self.encoding_test(f, [rffi.cast(lltype.SingleFloat, 12.456)], """
993 cast_singlefloat_to_float %i0 -> %f0
994 cast_float_to_int %f0 -> %i1
995 int_signext %i1, $1 -> %i2
996 int_return %i2
997 """, transform=True)
998
999 def f(dbl):
1000 return rffi.cast(rffi.UCHAR, dbl)
1001 self.encoding_test(f, [12.456], """
1002 cast_float_to_int %f0 -> %i0
1003 int_and %i0, $255 -> %i1
1004 int_return %i1
1005 """, transform=True)
1006
1007 def f(dbl):
1008 return rffi.cast(lltype.Unsigned, dbl)
1009 self.encoding_test(f, [12.456], """
1010 residual_call_irf_i $<* fn cast_float_to_uint>, I[], R[], F[%f0], <Descr> -> %i0
1011 int_return %i0
1012 """, transform=True)
1013
1014 def f(i):
1015 return rffi.cast(lltype.Float, chr(i)) # "char -> float"
1016 self.encoding_test(f, [12], """
1017 cast_int_to_float %i0 -> %f0
1018 float_return %f0
1019 """, transform=True)
1020
1021 def f(i):
1022 return rffi.cast(lltype.Float, r_uint(i)) # "uint -> float"
1023 self.encoding_test(f, [12], """
1024 residual_call_irf_f $<* fn cast_uint_to_float>, I[%i0], R[], F[], <Descr> -> %f0
1025 float_return %f0
1026 """, transform=True)
1027
1028 if not longlong.is_64_bit:
1029 def f(dbl):
1030 return rffi.cast(lltype.SignedLongLong, dbl)
1031 self.encoding_test(f, [12.3], """
1032 residual_call_irf_f $<* fn llong_from_float>, I[], R[], F[%f0], <Descr> -> %f1
1033 float_return %f1
1034 """, transform=True)
1035
1036 def f(dbl):
1037 return rffi.cast(lltype.UnsignedLongLong, dbl)
1038 self.encoding_test(f, [12.3], """
1039 residual_call_irf_f $<* fn ullong_from_float>, I[], R[], F[%f0], <Descr> -> %f1
1040 float_return %f1
1041 """, transform=True)
1042
1043 def f(x):
1044 ll = r_longlong(x)
1045 return rffi.cast(lltype.Float, ll)
1046 self.encoding_test(f, [12], """
1047 residual_call_irf_f $<* fn llong_from_int>, I[%i0], R[], F[], <Descr> -> %f0
1048 residual_call_irf_f $<* fn llong_to_float>, I[], R[], F[%f0], <Descr> -> %f1
1049 float_return %f1
1050 """, transform=True)
1051
1052 def f(x):
1053 ll = r_ulonglong(x)
1054 return rffi.cast(lltype.Float, ll)
1055 self.encoding_test(f, [12], """
1056 residual_call_irf_f $<* fn ullong_from_int>, I[%i0], R[], F[], <Descr> -> %f0
1057 residual_call_irf_f $<* fn ullong_u_to_float>, I[], R[], F[%f0], <Descr> -> %f1
1058 float_return %f1
1059 """, transform=True)
1060
1061 def test_direct_ptradd(self):
1062 def f(p, n):
1063 return lltype.direct_ptradd(p, n)
1064 self.encoding_test(f, [lltype.nullptr(rffi.CCHARP.TO), 123], """
1065 int_add %i0, %i1 -> %i2
1066 int_return %i2
1067 """, transform=True)
1068
1069 def test_direct_ptradd_2(self):
1070 def f(p, n):
1071 return lltype.direct_ptradd(p, n + 2)
1072 self.encoding_test(f, [lltype.nullptr(rffi.SHORTP.TO), 123], """
1073 int_add %i1, $2 -> %i2
1074 int_mul %i2, $<ItemOffset <SHORT> 1> -> %i3
1075 int_add %i0, %i3 -> %i4
1076 int_return %i4
1077 """, transform=True)
1078
1079 def test_convert_float_bytes(self):
1080 from rpython.rlib.longlong2float import float2longlong, longlong2float
1081 def f(x):
1082 ll = float2longlong(x)
1083 return longlong2float(ll)
1084 if longlong.is_64_bit:
1085 tmp_var = "%i0"
1086 result_var = "%f1"
1087 else:
1088 tmp_var = "%f1"
1089 result_var = "%f2"
1090 self.encoding_test(f, [25.0], """
1091 convert_float_bytes_to_longlong %%f0 -> %(tmp_var)s
1092 convert_longlong_bytes_to_float %(tmp_var)s -> %(result_var)s
1093 float_return %(result_var)s
1094 """ % {"result_var": result_var, "tmp_var": tmp_var}, transform=True)
1095
1096 def test_vable_attribute_list_is_not_None(self):
1097 class F:
1098 _virtualizable_ = ['vlist[*]']
1099 vlist = None
1100 def __init__(self, x):
1101 self.vlist = [x]
1102 def g():
1103 return F(42)
1104 def f():
1105 f = g()
1106 if f.vlist is not None:
1107 pass
1108 e = py.test.raises(AssertionError, self.encoding_test, f, [], "!",
1109 transform=True)
1110 assert str(e.value).startswith("A virtualizable array is passed aroun")
1111 assert "<Descr>" in str(e.value)
1112
1113 def test_vable_attribute_list_copied_around(self):
1114 class F:
1115 _virtualizable_ = ['vlist[*]']
1116 vlist = None
1117 def __init__(self, x):
1118 self.vlist = [x]
1119 def g():
1120 return F(42)
1121 def f():
1122 f = g()
1123 f.extrastuff = f.vlist
1124 e = py.test.raises(AssertionError, self.encoding_test, f, [], "!",
1125 transform=True)
1126 assert str(e.value).startswith("A virtualizable array is passed aroun")
1127 assert "<Descr>" in str(e.value)
1128
1129 def test_rvmprof_code(self):
1130 from rpython.rlib.rvmprof import cintf
1131 class MyFakeCallControl(FakeCallControl):
1132 def guess_call_kind(self, op):
1133 if 'jitted' in repr(op):
1134 return 'builtin'
1135 return 'residual'
1136 class X:
1137 pass
1138 def g(x, y):
1139 debug.debug_print("foo")
1140 return X()
1141 @jit.oopspec("rvmprof.jitted(unique_id)")
1142 def decorated_jitted_function(unique_id, *args):
1143 return g(*args)
1144 def f(id, x, y):
1145 return decorated_jitted_function(id, x, y)
1146 self.encoding_test(f, [42, 56, 74], """
1147 rvmprof_code $0, %i0
1148 residual_call_ir_r $<* fn g>, I[%i1, %i2], R[], <Descr> -> %r0
1149 -live-
1150 rvmprof_code $1, %i0
1151 ref_return %r0
1152 """, transform=True, cc=MyFakeCallControl())
1153
1154
1155 def check_force_cast(FROM, TO, operations, value):
1156 """Check that the test is correctly written..."""
1157 import re
1158 r = re.compile('(\w+) \%i\d, \$(-?\d+)')
1159 r2 = re.compile('(\w+) \%i\d')
1160 #
1161 value = rffi.cast(FROM, value)
1162 value = rffi.cast(lltype.Signed, value)
1163 #
1164 expected_value = rffi.cast(TO, value)
1165 expected_value = rffi.cast(lltype.Signed, expected_value)
1166 #
1167 for op in operations:
1168 match = r.match(op)
1169 if match is None:
1170 match = r2.match(op)
1171 assert match, "line %r does not match regexp" % (op,)
1172 opname = match.group(1)
1173 if opname == 'int_and':
1174 value &= int(match.group(2))
1175 elif opname == 'int_signext':
1176 numbytes = int(match.group(2))
1177 value = int_signext(value, numbytes)
1178 elif opname == 'int_is_true':
1179 value = bool(value)
1180 else:
1181 assert 0, opname
1182 #
1183 assert rffi.cast(lltype.Signed, value) == expected_value