PageRenderTime 38ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/translator/backendopt/test/test_malloc.py

https://bitbucket.org/pypy/pypy/
Python | 383 lines | 327 code | 44 blank | 12 comment | 28 complexity | fbd3373aaf2d69d5c9cccac463ab9b33 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. import py
  2. from pypy.translator.backendopt.malloc import LLTypeMallocRemover, OOTypeMallocRemover
  3. from pypy.translator.backendopt.all import backend_optimizations
  4. from pypy.translator.translator import TranslationContext, graphof
  5. from pypy.translator import simplify
  6. from pypy.objspace.flow.model import checkgraph, Block, mkentrymap
  7. from pypy.rpython.llinterp import LLInterpreter
  8. from pypy.rpython.lltypesystem import lltype, llmemory
  9. from pypy.rpython.ootypesystem import ootype
  10. from pypy.rlib import objectmodel
  11. from pypy.conftest import option
  12. class BaseMallocRemovalTest(object):
  13. type_system = None
  14. MallocRemover = None
  15. def _skip_oo(self, msg):
  16. if self.type_system == 'ootype':
  17. py.test.skip(msg)
  18. def check_malloc_removed(cls, graph):
  19. remover = cls.MallocRemover()
  20. checkgraph(graph)
  21. count1 = count2 = 0
  22. for node in graph.iterblocks():
  23. for op in node.operations:
  24. if op.opname == cls.MallocRemover.MALLOC_OP:
  25. S = op.args[0].value
  26. if not remover.union_wrapper(S): # union wrappers are fine
  27. count1 += 1
  28. if op.opname in ('direct_call', 'indirect_call'):
  29. count2 += 1
  30. assert count1 == 0 # number of mallocs left
  31. assert count2 == 0 # number of calls left
  32. check_malloc_removed = classmethod(check_malloc_removed)
  33. def check(self, fn, signature, args, expected_result, must_be_removed=True,
  34. inline=None):
  35. remover = self.MallocRemover()
  36. t = TranslationContext()
  37. t.buildannotator().build_types(fn, signature)
  38. t.buildrtyper(type_system=self.type_system).specialize()
  39. graph = graphof(t, fn)
  40. if inline is not None:
  41. from pypy.translator.backendopt.inline import auto_inline_graphs
  42. auto_inline_graphs(t, t.graphs, inline)
  43. if option.view:
  44. t.view()
  45. # to detect broken intermediate graphs,
  46. # we do the loop ourselves instead of calling remove_simple_mallocs()
  47. while True:
  48. progress = remover.remove_mallocs_once(graph)
  49. simplify.transform_dead_op_vars_in_blocks(list(graph.iterblocks()),
  50. [graph])
  51. if progress and option.view:
  52. t.view()
  53. if expected_result is not Ellipsis:
  54. interp = LLInterpreter(t.rtyper)
  55. res = interp.eval_graph(graph, args)
  56. assert res == expected_result
  57. if not progress:
  58. break
  59. if must_be_removed:
  60. self.check_malloc_removed(graph)
  61. return graph
  62. def test_fn1(self):
  63. def fn1(x, y):
  64. if x > 0:
  65. t = x+y, x-y
  66. else:
  67. t = x-y, x+y
  68. s, d = t
  69. return s*d
  70. self.check(fn1, [int, int], [15, 10], 125)
  71. def test_fn2(self):
  72. class T:
  73. pass
  74. def fn2(x, y):
  75. t = T()
  76. t.x = x
  77. t.y = y
  78. if x > 0:
  79. return t.x + t.y
  80. else:
  81. return t.x - t.y
  82. self.check(fn2, [int, int], [-6, 7], -13)
  83. def test_fn3(self):
  84. def fn3(x):
  85. a, ((b, c), d, e) = x+1, ((x+2, x+3), x+4, x+5)
  86. return a+b+c+d+e
  87. self.check(fn3, [int], [10], 65)
  88. def test_fn4(self):
  89. class A:
  90. pass
  91. class B(A):
  92. pass
  93. def fn4(i):
  94. a = A()
  95. b = B()
  96. a.b = b
  97. b.i = i
  98. return a.b.i
  99. self.check(fn4, [int], [42], 42)
  100. def test_fn5(self):
  101. class A:
  102. attr = 666
  103. class B(A):
  104. attr = 42
  105. def fn5():
  106. b = B()
  107. return b.attr
  108. self.check(fn5, [], [], 42)
  109. def test_aliasing(self):
  110. class A:
  111. pass
  112. def fn6(n):
  113. a1 = A()
  114. a1.x = 5
  115. a2 = A()
  116. a2.x = 6
  117. if n > 0:
  118. a = a1
  119. else:
  120. a = a2
  121. a.x = 12
  122. return a1.x
  123. self.check(fn6, [int], [1], 12, must_be_removed=False)
  124. def test_bogus_cast_pointer(self):
  125. class S:
  126. pass
  127. class T(S):
  128. def f(self):
  129. self.y += 1
  130. def f(x):
  131. T().y = 5
  132. s = S()
  133. s.x = 123
  134. if x < 0:
  135. s.f()
  136. return s.x
  137. graph = self.check(f, [int], [5], 123, inline=20)
  138. found_operations = {}
  139. for block in graph.iterblocks():
  140. for op in block.operations:
  141. found_operations[op.opname] = True
  142. assert 'debug_fatalerror' in found_operations
  143. class TestLLTypeMallocRemoval(BaseMallocRemovalTest):
  144. type_system = 'lltype'
  145. MallocRemover = LLTypeMallocRemover
  146. def test_dont_remove_with__del__(self):
  147. import os
  148. delcalls = [0]
  149. class A(object):
  150. nextid = 0
  151. def __init__(self):
  152. self.id = self.nextid
  153. self.nextid += 1
  154. def __del__(self):
  155. delcalls[0] += 1
  156. os.write(1, "__del__\n")
  157. def f(x=int):
  158. a = A()
  159. i = 0
  160. while i < x:
  161. a = A()
  162. os.write(1, str(delcalls[0]) + "\n")
  163. i += 1
  164. return 1
  165. t = TranslationContext()
  166. t.buildannotator().build_types(f, [int])
  167. t.buildrtyper().specialize()
  168. graph = graphof(t, f)
  169. backend_optimizations(t)
  170. op = graph.startblock.exits[0].target.exits[1].target.operations[0]
  171. assert op.opname == "malloc"
  172. def test_wrapper_cannot_be_removed(self):
  173. SMALL = lltype.OpaqueType('SMALL')
  174. BIG = lltype.GcStruct('BIG', ('z', lltype.Signed), ('s', SMALL))
  175. def g(small):
  176. return -1
  177. def fn():
  178. b = lltype.malloc(BIG)
  179. g(b.s)
  180. self.check(fn, [], [], None, must_be_removed=False)
  181. def test_direct_fieldptr(self):
  182. S = lltype.GcStruct('S', ('x', lltype.Signed))
  183. def fn():
  184. s = lltype.malloc(S)
  185. s.x = 11
  186. p = lltype.direct_fieldptr(s, 'x')
  187. return p[0]
  188. self.check(fn, [], [], 11)
  189. def test_direct_fieldptr_2(self):
  190. T = lltype.GcStruct('T', ('z', lltype.Signed))
  191. S = lltype.GcStruct('S', ('t', T),
  192. ('x', lltype.Signed),
  193. ('y', lltype.Signed))
  194. def fn():
  195. s = lltype.malloc(S)
  196. s.x = 10
  197. s.t.z = 1
  198. px = lltype.direct_fieldptr(s, 'x')
  199. py = lltype.direct_fieldptr(s, 'y')
  200. pz = lltype.direct_fieldptr(s.t, 'z')
  201. py[0] = 31
  202. return px[0] + s.y + pz[0]
  203. self.check(fn, [], [], 42)
  204. def test_getarraysubstruct(self):
  205. py.test.skip("fails because of the interior structure changes")
  206. U = lltype.Struct('U', ('n', lltype.Signed))
  207. for length in [1, 2]:
  208. S = lltype.GcStruct('S', ('a', lltype.FixedSizeArray(U, length)))
  209. for index in range(length):
  210. def fn():
  211. s = lltype.malloc(S)
  212. s.a[index].n = 12
  213. return s.a[index].n
  214. self.check(fn, [], [], 12)
  215. def test_ptr_nonzero(self):
  216. S = lltype.GcStruct('S')
  217. def fn():
  218. s = lltype.malloc(S)
  219. return bool(s)
  220. self.check(fn, [], [], True)
  221. def test_substruct_not_accessed(self):
  222. SMALL = lltype.Struct('SMALL', ('x', lltype.Signed))
  223. BIG = lltype.GcStruct('BIG', ('z', lltype.Signed), ('s', SMALL))
  224. def fn():
  225. x = lltype.malloc(BIG)
  226. while x.z < 10: # makes several blocks
  227. x.z += 3
  228. return x.z
  229. self.check(fn, [], [], 12)
  230. def test_union(self):
  231. py.test.skip("fails because of the interior structure changes")
  232. UNION = lltype.Struct('UNION', ('a', lltype.Signed), ('b', lltype.Signed),
  233. hints = {'union': True})
  234. BIG = lltype.GcStruct('BIG', ('u1', UNION), ('u2', UNION))
  235. def fn():
  236. x = lltype.malloc(BIG)
  237. x.u1.a = 3
  238. x.u2.b = 6
  239. return x.u1.b * x.u2.a
  240. self.check(fn, [], [], Ellipsis)
  241. def test_keep_all_keepalives(self):
  242. SIZE = llmemory.sizeof(lltype.Signed)
  243. PARRAY = lltype.Ptr(lltype.FixedSizeArray(lltype.Signed, 1))
  244. class A:
  245. def __init__(self):
  246. self.addr = llmemory.raw_malloc(SIZE)
  247. def __del__(self):
  248. llmemory.raw_free(self.addr)
  249. class B:
  250. pass
  251. def myfunc():
  252. b = B()
  253. b.keep = A()
  254. b.data = llmemory.cast_adr_to_ptr(b.keep.addr, PARRAY)
  255. b.data[0] = 42
  256. ptr = b.data
  257. # normally 'b' could go away as early as here, which would free
  258. # the memory held by the instance of A in b.keep...
  259. res = ptr[0]
  260. # ...so we explicitly keep 'b' alive until here
  261. objectmodel.keepalive_until_here(b)
  262. return res
  263. graph = self.check(myfunc, [], [], 42,
  264. must_be_removed=False) # 'A' instance left
  265. # there is a getarrayitem near the end of the graph of myfunc.
  266. # However, the memory it accesses must still be protected by the
  267. # following keepalive, even after malloc removal
  268. entrymap = mkentrymap(graph)
  269. [link] = entrymap[graph.returnblock]
  270. assert link.prevblock.operations[-1].opname == 'keepalive'
  271. def test_nested_struct(self):
  272. S = lltype.GcStruct("S", ('x', lltype.Signed))
  273. T = lltype.GcStruct("T", ('s', S))
  274. def f(x):
  275. t = lltype.malloc(T)
  276. s = t.s
  277. if x:
  278. s.x = x
  279. return t.s.x + s.x
  280. graph = self.check(f, [int], [42], 2 * 42)
  281. def test_interior_ptr(self):
  282. py.test.skip("fails")
  283. S = lltype.Struct("S", ('x', lltype.Signed))
  284. T = lltype.GcStruct("T", ('s', S))
  285. def f(x):
  286. t = lltype.malloc(T)
  287. t.s.x = x
  288. return t.s.x
  289. graph = self.check(f, [int], [42], 42)
  290. def test_interior_ptr_with_index(self):
  291. S = lltype.Struct("S", ('x', lltype.Signed))
  292. T = lltype.GcArray(S)
  293. def f(x):
  294. t = lltype.malloc(T, 1)
  295. t[0].x = x
  296. return t[0].x
  297. graph = self.check(f, [int], [42], 42)
  298. def test_interior_ptr_with_field_and_index(self):
  299. S = lltype.Struct("S", ('x', lltype.Signed))
  300. T = lltype.GcStruct("T", ('items', lltype.Array(S)))
  301. def f(x):
  302. t = lltype.malloc(T, 1)
  303. t.items[0].x = x
  304. return t.items[0].x
  305. graph = self.check(f, [int], [42], 42)
  306. def test_interior_ptr_with_index_and_field(self):
  307. S = lltype.Struct("S", ('x', lltype.Signed))
  308. T = lltype.Struct("T", ('s', S))
  309. U = lltype.GcArray(T)
  310. def f(x):
  311. u = lltype.malloc(U, 1)
  312. u[0].s.x = x
  313. return u[0].s.x
  314. graph = self.check(f, [int], [42], 42)
  315. class TestOOTypeMallocRemoval(BaseMallocRemovalTest):
  316. type_system = 'ootype'
  317. MallocRemover = OOTypeMallocRemover
  318. def test_oononnull(self):
  319. FOO = ootype.Instance('Foo', ootype.ROOT)
  320. def fn():
  321. s = ootype.new(FOO)
  322. return bool(s)
  323. self.check(fn, [], [], True)
  324. def test_classattr_as_defaults(self):
  325. class Bar:
  326. foo = 41
  327. def fn():
  328. x = Bar()
  329. x.foo += 1
  330. return x.foo
  331. self.check(fn, [], [], 42)
  332. def test_fn5(self):
  333. # don't test this in ootype because the class attribute access
  334. # is turned into an oosend which prevents malloc removal to
  335. # work unless we inline first. See test_classattr in
  336. # test_inline.py
  337. py.test.skip("oosend prevents malloc removal")
  338. def test_bogus_cast_pointer(self):
  339. py.test.skip("oosend prevents malloc removal")