Debian Codegraph @

rpython/translator/test/test_simplify.py

raw symbols SCIP
1 import py
2 from rpython.translator.translator import TranslationContext, graphof
3 from rpython.translator.backendopt.all import backend_optimizations
4 from rpython.translator.simplify import get_graph, transform_dead_op_vars
5 from rpython.flowspace.model import Block, Constant, summary
6 from rpython.conftest import option
7
8 def translate(func, argtypes, backend_optimize=True):
9 t = TranslationContext()
10 t.buildannotator().build_types(func, argtypes)
11 t.buildrtyper().specialize()
12 if backend_optimize:
13 backend_optimizations(t)
14 if option.view:
15 t.view()
16 return graphof(t, func), t
17
18 def test_remove_ovfcheck_1():
19 # check that ovfcheck() is handled
20 from rpython.rlib.rarithmetic import ovfcheck
21 def f(x):
22 try:
23 return ovfcheck(x*2)
24 except OverflowError:
25 return -42
26 graph, _ = translate(f, [int])
27 assert len(graph.startblock.operations) == 1
28 assert graph.startblock.operations[0].opname == 'int_mul_ovf'
29 assert len(graph.startblock.exits) == 2
30 assert [link.target.operations for link in graph.startblock.exits] == \
31 [(), ()]
32
33 def test_remove_ovfcheck_bug():
34 # check that ovfcheck() is correctly handled even if there is no
35 # try:except: immediately around it
36 from rpython.rlib.rarithmetic import ovfcheck
37 def f(x):
38 return ovfcheck(x*2) - 1
39 graph, _ = translate(f, [int])
40 assert len(graph.startblock.operations) == 2
41 assert graph.startblock.operations[0].opname == 'int_mul_ovf'
42 assert graph.startblock.operations[1].opname == 'int_sub'
43
44 def test_remove_ovfcheck_floordiv():
45 # check that ovfcheck() is handled even if the operation raises
46 # and catches another exception too, here ZeroDivisionError
47 from rpython.rlib.rarithmetic import ovfcheck
48 def f(x, y):
49 try:
50 return ovfcheck(x // y)
51 except OverflowError:
52 return -42
53 except ZeroDivisionError:
54 return -43
55 graph, _ = translate(f, [int, int], backend_optimize=False)
56 assert len(graph.startblock.operations) == 1
57 assert graph.startblock.operations[0].opname == 'direct_call'
58 assert 'int_py_div_ovf_zer' in repr(
59 graph.startblock.operations[0].args[0].value)
60 assert len(graph.startblock.exits) == 3
61 assert [link.target.operations for link in graph.startblock.exits[1:]] == \
62 [(), ()]
63
64 def test_remove_ovfcheck_floordiv_2():
65 # check that ovfcheck() is handled even if the operation raises
66 # and catches only another exception, here ZeroDivisionError
67 from rpython.rlib.rarithmetic import ovfcheck
68 def f(x, y):
69 try:
70 return ovfcheck(x // y)
71 except ZeroDivisionError:
72 return -43
73 graph, _ = translate(f, [int, int], backend_optimize=False)
74 assert len(graph.startblock.operations) == 1
75 assert graph.startblock.operations[0].opname == 'direct_call'
76 assert 'int_py_div_ovf_zer' in repr(
77 graph.startblock.operations[0].args[0].value)
78 assert len(graph.startblock.exits) == 3
79 assert [link.target.operations for link in graph.startblock.exits[1:]] == \
80 [(), ()]
81
82 def test_remove_direct_call_without_side_effects():
83 def f(x):
84 return x + 123
85 def g(x):
86 a = f(x)
87 return x * 12
88 graph, _ = translate(g, [int])
89 assert len(graph.startblock.operations) == 1
90
91 def test_dont_remove_external_calls():
92 import os
93 def f(x):
94 os.close(x)
95 graph, _ = translate(f, [int])
96 assert len(graph.startblock.operations) > 0
97
98 def test_remove_recursive_call():
99 def rec(a):
100 if a <= 1:
101 return 0
102 else:
103 return rec(a - 1) + 1
104 def f(x):
105 a = rec(x)
106 return x + 12
107 graph, _ = translate(f, [int])
108 assert len(graph.startblock.operations) == 1
109
110 def test_remove_call_with_indirect_call():
111 def f1(x):
112 return x + 1
113 def f2(x):
114 return x + 2
115 def g(x):
116 if x == 32:
117 f = f1
118 else:
119 f = f2
120 return f(x)
121 def h(x):
122 a = g(x)
123 return x + 42
124 graph, t = translate(h, [int])
125 assert len(graph.startblock.operations) == 1
126
127 def test_dont_remove_if_exception_guarded():
128 def f(x):
129 a = {} #do some stuff to prevent inlining
130 a['123'] = 123
131 a['1123'] = 1234
132 return x + 1
133 def g(x):
134 try:
135 a = f(x)
136 except OverflowError:
137 raise
138 else:
139 return 1
140 graph, _ = translate(g, [int])
141 assert graph.startblock.operations[-1].opname == 'direct_call'
142
143
144 def test_remove_identical_variables():
145 def g(code):
146 pc = 0
147 while pc < len(code):
148 pc += 1
149 return pc
150
151 graph = TranslationContext().buildflowgraph(g)
152 for block in graph.iterblocks():
153 assert len(block.inputargs) <= 2 # at most 'pc' and 'code'
154
155 def test_get_graph():
156 import os
157 def list_basic_ops(i, j):
158 l = [1,2,3]
159 l.insert(0, 42)
160 del l[1]
161 l.append(i)
162 listlen = len(l)
163 l.extend(l)
164 del l[listlen:]
165 l += [5,6]
166 l[1] = i
167 return l[j]
168 def external_function():
169 return os.system("ls")
170 graph, t = translate(list_basic_ops, [int, int], False)
171 for block in graph.iterblocks():
172 for op in block.operations:
173 if op.opname == "direct_call":
174 print op
175 graph = get_graph(op.args[0], t)
176 assert graph is not None
177 # an external function in RPython turns currently into
178 # a call to a wrapper function which itself contains the
179 # real call to a graph-less external ll function, so
180 # we check recursively
181 graph, t = translate(external_function, [], False)
182 found = []
183 def walkgraph(graph):
184 for block in graph.iterblocks():
185 for op in block.operations:
186 if op.opname == "direct_call":
187 print op
188 subgraph = get_graph(op.args[0], t)
189 if subgraph is None:
190 # ignore 'get_errno' and 'set_errno', and
191 # 'RPyGilRelease' and 'RPyGilAcquire'
192 if ('et_errno' not in repr(op.args[0]) and
193 'RPyGil' not in repr(op.args[0])):
194 found.append(op)
195 else:
196 walkgraph(subgraph)
197 walkgraph(graph)
198 assert len(found) == 1
199
200 def addone(x):
201 return x + 1
202
203 def test_huge_func():
204 g = None
205 gstring = "def g(x):\n%s%s" % (" x = x + 1\n" * 1000, " return x\n")
206 exec(gstring)
207 assert g(1) == 1001
208 # does not crash: previously join_blocks would barf on this
209 graph, t = translate(g, [int])
210
211 def test_join_blocks_cleans_links():
212 from rpython.rtyper.lltypesystem import lltype
213 from rpython.flowspace.model import Constant
214 from rpython.translator.backendopt.removenoops import remove_same_as
215 def f(x):
216 return bool(x + 2)
217 def g(x):
218 if f(x):
219 return 1
220 else:
221 return 2
222 graph, t = translate(g, [int], backend_optimize=False)
223 fgraph = graphof(t, f)
224 fgraph.startblock.exits[0].args = [Constant(True, lltype.Bool)]
225 # does not crash: previously join_blocks would barf on this
226 remove_same_as(graph)
227 backend_optimizations(t)
228
229 def test_transform_dead_op_vars_bug():
230 from rpython.rtyper.llinterp import LLInterpreter, LLException
231 exc = ValueError()
232 def f1():
233 raise exc # this function used to be considered side-effects-free
234 def f2():
235 f1() # <- so this call was removed
236
237 graph, t = translate(f2, [], backend_optimize=False)
238 transform_dead_op_vars(graph, t)
239 interp = LLInterpreter(t.rtyper)
240 e = py.test.raises(LLException, 'interp.eval_graph(graph, [])')
241 assert 'ValueError' in str(e.value)
242
243 class TestDetectListComprehension:
244 def check(self, f1, expected):
245 t = TranslationContext(list_comprehension_operations=True)
246 graph = t.buildflowgraph(f1)
247 if option.view:
248 graph.show()
249 assert summary(graph) == expected
250
251 def test_simple(self):
252 def f1(l):
253 return [x*17 for x in l]
254 self.check(f1, {
255 'newlist': 1,
256 'iter': 1,
257 'next': 1,
258 'mul': 1,
259 'getattr': 1,
260 'simple_call': 1,
261 'hint': 2,
262 })
263
264 def test_with_exc(self):
265 def g(x):
266 return x * 17
267 def free_some_stuff():
268 pass
269 def f1(l):
270 try:
271 return [g(x) for x in l]
272 finally:
273 free_some_stuff()
274 self.check(f1, {
275 'newlist': 1,
276 'iter': 1,
277 'next': 1,
278 'getattr': 1,
279 'simple_call': 4,
280 'hint': 2,
281 })
282
283 def test_canraise_before_iter(self):
284 def g(l):
285 return l
286 def f1(l):
287 try:
288 return [x*17 for x in g(l)]
289 except ValueError:
290 return []
291 self.check(f1, {
292 'newlist': 2,
293 'iter': 1,
294 'next': 1,
295 'mul': 1,
296 'getattr': 1,
297 'simple_call': 2,
298 'hint': 2,
299 })
300
301 def test_iterate_over_list(self):
302 def wrap(elem):
303 return elem
304
305 def f(i):
306 new_l = []
307 l = range(4)
308 for elem in l:
309 new_l.append(wrap(elem))
310 return new_l
311
312 self.check(f, {
313 'hint': 2,
314 'newlist': 1,
315 'iter': 1,
316 'next': 1,
317 'getattr': 1,
318 'simple_call': 3,
319 })
320
321
322 class TestLLSpecializeListComprehension:
323 typesystem = 'lltype'
324
325 def specialize(self, func, argtypes):
326 from rpython.rtyper.llinterp import LLInterpreter
327 t = TranslationContext(list_comprehension_operations=True)
328 t.buildannotator().build_types(func, argtypes)
329 if option.view:
330 t.view()
331 t.buildrtyper().specialize()
332 backend_optimizations(t)
333 if option.view:
334 t.view()
335 graph = graphof(t, func)
336 interp = LLInterpreter(t.rtyper)
337 return interp, graph
338
339 def no_resize(self, graph, expect_resize=0):
340 found_resize = 0
341 for block in graph.iterblocks():
342 for op in block.operations:
343 if op.opname == 'direct_call':
344 if 'list_resize' in repr(op.args[0]):
345 found_resize += 1
346 assert found_resize == expect_resize
347
348 def test_simple(self):
349 def main(n):
350 lst = [x*17 for x in range(n)]
351 return lst[5]
352 interp, graph = self.specialize(main, [int])
353 res = interp.eval_graph(graph, [10])
354 assert res == 5 * 17
355 self.no_resize(graph)
356
357 def test_str2list(self):
358 def main(n):
359 lst = [c for c in str(n)]
360 return len(lst)
361 interp, graph = self.specialize(main, [int])
362 res = interp.eval_graph(graph, [1091283])
363 assert res == 7
364 self.no_resize(graph)
365
366 def test_simple_non_exact(self):
367 def main(n):
368 lst = [x*17 for x in range(n) if x < 5]
369 return len(lst)
370 interp, graph = self.specialize(main, [int])
371 res = interp.eval_graph(graph, [10])
372 assert res == 5
373 self.no_resize(graph, expect_resize=1)
374 # the non-exactness disables preallocating now, for sanity
375
376 def test_mutated_after_listcomp(self):
377 def main(n):
378 lst = [x*17 for x in range(n)]
379 lst.append(-42)
380 return lst[5]
381 interp, graph = self.specialize(main, [int])
382 res = interp.eval_graph(graph, [10])
383 assert res == 5 * 17
384 res = interp.eval_graph(graph, [5])
385 assert res == -42
386 self.no_resize(graph, expect_resize=1) # after the loop
387
388 def test_two_loops(self):
389 def main(n, m):
390 lst1 = []
391 lst2 = []
392 for i in range(n):
393 lst1.append(i)
394 for i in range(m):
395 lst2.append(i)
396 sum = 0
397 for i in lst1:
398 sum += i
399 for i in lst2:
400 sum -= i
401 return sum
402 interp, graph = self.specialize(main, [int, int])
403 res = interp.eval_graph(graph, [8, 3])
404 assert res == 28 - 3
405 self.no_resize(graph)
406
407 def test_dict(self):
408 def main(n, m):
409 d = {n: m, m: n}
410 lst = [i*17 for i in d]
411 return len(lst) + lst[0] + lst[-1]
412 interp, graph = self.specialize(main, [int, int])
413 res = interp.eval_graph(graph, [8, 5])
414 assert res == 2 + 8 * 17 + 5 * 17
415 res = interp.eval_graph(graph, [4, 4])
416 assert res == 1 + 4 * 17 + 4 * 17
417 self.no_resize(graph)
418
419
420 def test_list_iterator(self):
421 # for now, this is not optimized as a list comp
422 def main(n):
423 r = range(n)
424 lst = [i*17 for i in iter(r)]
425 return lst[5]
426 interp, graph = self.specialize(main, [int])
427 res = interp.eval_graph(graph, [8])
428 assert res == 5 * 17
429
430 def test_list_iterator_mutated_after_listcomp(self):
431 # for now, this is not optimized as a list comp
432 def main(n):
433 r = range(n)
434 lst = [i*17 for i in iter(r)]
435 lst.append(42)
436 return lst[5]
437 interp, graph = self.specialize(main, [int])
438 res = interp.eval_graph(graph, [8])
439 assert res == 5 * 17
440
441
442 def test_dict_iterator(self):
443 # for now, this is not optimized as a list comp
444 def main(n, m):
445 d = {n: m, m: n}
446 lst = [i*17 for i in d.iterkeys()]
447 return len(lst) + lst[0] + lst[-1]
448 interp, graph = self.specialize(main, [int, int])
449 res = interp.eval_graph(graph, [8, 5])
450 assert res == 2 + 8 * 17 + 5 * 17
451 res = interp.eval_graph(graph, [4, 4])
452 assert res == 1 + 4 * 17 + 4 * 17
453
454 def test_iterate_over_constant(self):
455 CONST = range(10)
456 def main(n):
457 lst = [x*17 for x in CONST]
458 return lst[5]
459 interp, graph = self.specialize(main, [int])
460 res = interp.eval_graph(graph, [10])
461 assert res == 5 * 17
462 self.no_resize(graph)