Debian Codegraph @

rpython/translator/backendopt/test/test_all.py

raw symbols SCIP
1 import py
2 from rpython.translator.backendopt.all import backend_optimizations
3 from rpython.translator.backendopt.all import INLINE_THRESHOLD_FOR_TEST
4 from rpython.translator.backendopt.support import md5digest
5 from rpython.translator.backendopt.test.test_malloc import TestMallocRemoval as MallocRemovalTest
6 from rpython.translator.translator import TranslationContext, graphof
7 from rpython.flowspace.model import Constant, summary
8 from rpython.rtyper.llinterp import LLInterpreter
9 from rpython.rlib.rarithmetic import intmask
10 from rpython.conftest import option
11
12 class A:
13 def __init__(self, x, y):
14 self.bounds = (x, y)
15 def mean(self, percentage=50):
16 x, y = self.bounds
17 total = x*percentage + y*(100-percentage)
18 return total//100
19
20 def condition(n):
21 return n >= 100
22
23 def firstthat(function, condition):
24 for n in range(101):
25 if condition(function(n)):
26 return n
27 else:
28 return -1
29
30 def myfunction(n):
31 a = A(117, n)
32 return a.mean()
33
34 def big():
35 """This example should be turned into a simple 'while' loop with no
36 malloc nor direct_call by back-end optimizations, given a high enough
37 inlining threshold.
38 """
39 return firstthat(myfunction, condition)
40
41 LARGE_THRESHOLD = 10*INLINE_THRESHOLD_FOR_TEST
42 HUGE_THRESHOLD = 100*INLINE_THRESHOLD_FOR_TEST
43
44 class TestLLType(object):
45 check_malloc_removed = MallocRemovalTest.check_malloc_removed
46
47 def translateopt(self, func, sig, **optflags):
48 t = TranslationContext()
49 opts = {'translation.list_comprehension_operations': True}
50 t.config.set(**opts)
51 t.buildannotator().build_types(func, sig)
52 t.buildrtyper().specialize()
53 if option.view:
54 t.view()
55 backend_optimizations(t, **optflags)
56 if option.view:
57 t.view()
58 return t
59
60 def test_big(self):
61 assert big() == 83
62
63 t = self.translateopt(big, [], inline_threshold=HUGE_THRESHOLD,
64 mallocs=True)
65
66 big_graph = graphof(t, big)
67 self.check_malloc_removed(big_graph)
68
69 interp = LLInterpreter(t.rtyper)
70 res = interp.eval_graph(big_graph, [])
71 assert res == 83
72
73
74 def test_for_loop(self):
75 def f(n):
76 total = 0
77 for i in range(n):
78 total += i
79 return total
80
81 t = self.translateopt(f, [int], mallocs=True)
82 # this also checks that the BASE_INLINE_THRESHOLD is enough
83 # for 'for' loops
84
85 f_graph = graph = graphof(t, f)
86 self.check_malloc_removed(f_graph)
87
88 interp = LLInterpreter(t.rtyper)
89 res = interp.eval_graph(f_graph, [11])
90 assert res == 55
91
92 def test_premature_death(self):
93 import os
94 from rpython.annotator.listdef import s_list_of_strings
95
96 inputtypes = [s_list_of_strings]
97
98 def debug(msg):
99 os.write(2, "debug: " + msg + '\n')
100
101 def entry_point(argv):
102 #debug("entry point starting")
103 for arg in argv:
104 #debug(" argv -> " + arg)
105 r = arg.replace('_', '-')
106 #debug(' replaced -> ' + r)
107 a = r.lower()
108 #debug(" lowered -> " + a)
109 return 0
110
111 t = self.translateopt(entry_point, inputtypes, mallocs=True)
112
113 entry_point_graph = graphof(t, entry_point)
114
115 argv = t.rtyper.getrepr(inputtypes[0]).convert_const(['./pypy-c'])
116
117 interp = LLInterpreter(t.rtyper)
118 interp.eval_graph(entry_point_graph, [argv])
119
120
121 def test_idempotent(self):
122 def s(x):
123 res = 0
124 i = 1
125 while i <= x:
126 res += i
127 i += 1
128 return res
129
130 def g(x):
131 return s(100) + s(1) + x
132
133 def idempotent(n1, n2):
134 c = [i for i in range(n2)]
135 return 33 + big() + g(10)
136
137 t = self.translateopt(idempotent, [int, int],
138 constfold=False)
139 #backend_optimizations(t, inline_threshold=0, constfold=False)
140
141 digest1 = md5digest(t)
142
143 digest2 = md5digest(t)
144 def compare(digest1, digest2):
145 diffs = []
146 assert digest1.keys() == digest2.keys()
147 for name in digest1:
148 if digest1[name] != digest2[name]:
149 diffs.append(name)
150 assert not diffs
151
152 compare(digest1, digest2)
153
154 #XXX Inlining and constfold are currently non-idempotent.
155 # Maybe they just renames variables but the graph changes in some way.
156 backend_optimizations(t, inline_threshold=0, constfold=False)
157 digest3 = md5digest(t)
158 compare(digest1, digest3)
159
160 def test_bug_inlined_if(self):
161 def f(x, flag):
162 if flag:
163 y = x
164 else:
165 y = x+1
166 return y*5
167 def myfunc(x):
168 return f(x, False) - f(x, True)
169
170 assert myfunc(10) == 5
171
172 t = self.translateopt(myfunc, [int], inline_threshold=HUGE_THRESHOLD)
173 interp = LLInterpreter(t.rtyper)
174 res = interp.eval_graph(graphof(t, myfunc), [10])
175 assert res == 5
176
177 def test_range_iter(self):
178 def fn(start, stop, step):
179 res = 0
180 if step == 0:
181 if stop >= start:
182 r = range(start, stop, 1)
183 else:
184 r = range(start, stop, -1)
185 else:
186 r = range(start, stop, step)
187 for i in r:
188 res = res * 51 + i
189 return res
190 t = self.translateopt(fn, [int, int, int], merge_if_blocks=True)
191 interp = LLInterpreter(t.rtyper)
192 for args in [2, 7, 0], [7, 2, 0], [10, 50, 7], [50, -10, -3]:
193 assert interp.eval_graph(graphof(t, fn), args) == intmask(fn(*args))
194
195 def test_constant_diffuse(self):
196 def g(x,y):
197 if x < 0:
198 return 0
199 return x + y
200
201 def f(x):
202 return g(x,7)+g(x,11)
203
204 t = self.translateopt(f, [int])
205 fgraph = graphof(t, f)
206
207 for link in fgraph.iterlinks():
208 assert Constant(7) not in link.args
209 assert Constant(11) not in link.args
210
211 def test_isinstance(self):
212 class A:
213 pass
214 class B(A):
215 pass
216 def g(n):
217 if n > 10:
218 return A()
219 else:
220 b = B()
221 b.value = 321
222 return b
223 def fn(n):
224 x = g(n)
225 assert isinstance(x, B)
226 return x.value
227 t = self.translateopt(fn, [int], really_remove_asserts=True,
228 remove_asserts=True)
229 graph = graphof(t, fn)
230 assert "direct_call" not in summary(graph)
231
232 def test_list_comp(self):
233 def f(n1, n2):
234 c = [i for i in range(n2)]
235 return 33
236
237 t = self.translateopt(f, [int, int], inline_threshold=LARGE_THRESHOLD,
238 mallocs=True)
239
240 f_graph = graphof(t, f)
241 self.check_malloc_removed(f_graph)
242
243 interp = LLInterpreter(t.rtyper)
244 res = interp.eval_graph(f_graph, [11, 22])
245 assert res == 33
246
247 def test_secondary_backendopt(self):
248 # checks an issue with a newly added graph that calls an
249 # already-exception-transformed graph. This can occur e.g.
250 # from a late-seen destructor added by the GC transformer
251 # which ends up calling existing code.
252 def common(n):
253 if n > 5:
254 raise ValueError
255 def main(n):
256 common(n)
257 def later(n):
258 try:
259 common(n)
260 return 0
261 except ValueError:
262 return 1
263
264 t = TranslationContext()
265 t.buildannotator().build_types(main, [int])
266 t.buildrtyper().specialize()
267 exctransformer = t.getexceptiontransformer()
268 exctransformer.create_exception_handling(graphof(t, common))
269 from rpython.annotator import model as annmodel
270 from rpython.rtyper.annlowlevel import MixLevelHelperAnnotator
271 annhelper = MixLevelHelperAnnotator(t.rtyper)
272 later_graph = annhelper.getgraph(later, [annmodel.SomeInteger()],
273 annmodel.SomeInteger())
274 annhelper.finish()
275 annhelper.backend_optimize()
276 # ^^^ as the inliner can't handle exception-transformed graphs,
277 # this should *not* inline common() into later().
278 if option.view:
279 later_graph.show()
280 common_graph = graphof(t, common)
281 found = False
282 for block in later_graph.iterblocks():
283 for op in block.operations:
284 if (op.opname == 'direct_call' and
285 op.args[0].value._obj.graph is common_graph):
286 found = True
287 assert found, "cannot find the call (buggily inlined?)"
288 from rpython.rtyper.llinterp import LLInterpreter
289 llinterp = LLInterpreter(t.rtyper)
290 res = llinterp.eval_graph(later_graph, [10])
291 assert res == 1
292
293 def test_replace_we_are_jitted(self):
294 from rpython.rlib import jit
295 def f():
296 if jit.we_are_jitted():
297 return 1
298 return 2 + jit.we_are_jitted()
299
300 t = self.translateopt(f, [])
301 graph = graphof(t, f)
302 # by default, replace_we_are_jitted is off
303 assert graph.startblock.operations[0].args[0].value is jit._we_are_jitted
304
305 t = self.translateopt(f, [], replace_we_are_jitted=True)
306 graph = graphof(t, f)
307 assert graph.startblock.exits[0].args[0].value == 2
308
309 def test_getfield_vtable(self):
310 class Base(object):
311 pass
312 class A(Base):
313 def f(self):
314 return 1
315 class B(Base):
316 def f(self):
317 return 2
318 def g(i):
319 if i > 0:
320 return A()
321 return B()
322 def f(i):
323 if i > 0:
324 a = g(5)
325 return a.f()
326 else:
327 a = g(-5)
328 return a.f()
329 t = self.translateopt(f, [int])
330 graph = graphof(t, f)
331 s = summary(graph)
332 assert 'getfield' not in s