Debian Codegraph @

rpython/translator/backendopt/malloc.py

raw symbols SCIP
1 from rpython.flowspace.model import Variable, Constant, SpaceOperation
2 from rpython.tool.algo.unionfind import UnionFind
3 from rpython.rtyper.lltypesystem import lltype
4 from rpython.translator import simplify
5 from rpython.translator.backendopt import removenoops
6 from rpython.translator.backendopt.support import log
7
8
9 class LifeTime:
10
11 def __init__(self, (block, var)):
12 assert isinstance(var, Variable)
13 self.variables = {(block, var)}
14 self.creationpoints = set() # set of ("type of creation point", ...)
15 self.usepoints = set() # set of ("type of use point", ...)
16
17 def absorb(self, other):
18 self.variables.update(other.variables)
19 self.creationpoints.update(other.creationpoints)
20 self.usepoints.update(other.usepoints)
21
22 def __repr__(self):
23 return "<LifeTime creationpoints=%r usepoints=%r variables=%r>" % (self.creationpoints, self.usepoints, self.variables)
24
25
26 class BaseMallocRemover(object):
27
28 IDENTITY_OPS = ('same_as',)
29 SUBSTRUCT_OPS = ()
30 MALLOC_OP = None
31 FIELD_ACCESS = {}
32 SUBSTRUCT_ACCESS = {}
33 CHECK_ARRAY_INDEX = {}
34
35 def __init__(self, verbose=True):
36 self.verbose = verbose
37
38 def check_malloc(self, op):
39 return op.opname == self.MALLOC_OP
40
41 def recreate_malloc(self, c, v):
42 return SpaceOperation(self.MALLOC_OP, [c], v)
43
44 def get_STRUCT(self, TYPE):
45 raise NotImplementedError
46
47 def visit_substruct_op(self, node, union, op):
48 raise NotImplementedError
49
50 def do_substruct_access(self, op):
51 raise NotImplementedError
52
53 def union_wrapper(self, S):
54 return False
55
56 def RTTI_dtor(self, STRUCT):
57 return False
58
59 def flatten(self, S):
60 raise NotImplementedError
61
62 def key_for_field_access(self, S, fldname):
63 raise NotImplementedError
64
65 def inline_type(self, TYPE):
66 raise NotImplementedError
67
68 def flowin(self, block, count, vars, newvarsmap):
69 # in this 'block', follow where the 'var' goes to and replace
70 # it by a flattened-out family of variables. This family is given
71 # by newvarsmap, whose keys are the 'flatnames'.
72
73 def list_newvars():
74 return [newvarsmap[key] for key in self.flatnames]
75
76 assert block.operations != ()
77 self.newops = []
78 for op in block.operations:
79 for arg in op.args[1:]: # should be the first arg only
80 assert arg not in vars
81 if op.args and op.args[0] in vars:
82 self.flowin_op(op, vars, newvarsmap)
83 elif op.result in vars:
84 assert op.opname == self.MALLOC_OP
85 progress = True
86 # drop the "malloc" operation
87 newvarsmap = self.flatconstants.copy() # zero initial values
88 # if there are substructures, they are now individually
89 # malloc'ed in an exploded way. (They will typically be
90 # removed again by the next malloc removal pass.)
91 for key in self.needsubmallocs:
92 v = Variable()
93 v.concretetype = self.newvarstype[key]
94 c = Constant(v.concretetype.TO, lltype.Void)
95 if c.value == op.args[0].value:
96 progress = False # replacing a malloc with
97 # the same malloc!
98 newop = self.recreate_malloc(c, v)
99 self.newops.append(newop)
100 newvarsmap[key] = v
101 count[0] += progress
102 else:
103 self.newops.append(op)
104
105 assert block.exitswitch not in vars
106
107 for link in block.exits:
108 appended = False
109 newargs = []
110 for arg in link.args:
111 if arg in vars:
112 if not appended:
113 newargs += list_newvars()
114 appended = True
115 else:
116 newargs.append(arg)
117 link.args[:] = newargs
118
119 block.operations[:] = self.newops
120
121 def compute_lifetimes(self, graph):
122 """Compute the static data flow of the graph: returns a list of LifeTime
123 instances, each of which corresponds to a set of Variables from the graph.
124 The variables are grouped in the same LifeTime if a value can pass from
125 one to the other by following the links. Each LifeTime also records all
126 places where a Variable in the set is used (read) or build (created).
127 """
128 lifetimes = UnionFind(LifeTime)
129
130 def set_creation_point(block, var, *cp):
131 _, _, info = lifetimes.find((block, var))
132 info.creationpoints.add(cp)
133
134 def set_use_point(block, var, *usepoint):
135 _, _, info = lifetimes.find((block, var))
136 info.usepoints.add(usepoint)
137
138 def union(block1, var1, block2, var2):
139 if isinstance(var1, Variable):
140 lifetimes.union((block1, var1), (block2, var2))
141 elif isinstance(var1, Constant):
142 set_creation_point(block2, var2, "constant", var1)
143 else:
144 raise TypeError(var1)
145
146 for var in graph.startblock.inputargs:
147 set_creation_point(graph.startblock, var, "inputargs")
148 set_use_point(graph.returnblock, graph.returnblock.inputargs[0], "return")
149 set_use_point(graph.exceptblock, graph.exceptblock.inputargs[0], "except")
150 set_use_point(graph.exceptblock, graph.exceptblock.inputargs[1], "except")
151
152 for node in graph.iterblocks():
153 for op in node.operations:
154 if op.opname in self.IDENTITY_OPS:
155 # special-case these operations to identify their input
156 # and output variables
157 union(node, op.args[0], node, op.result)
158 continue
159 if op.opname in self.SUBSTRUCT_OPS:
160 if self.visit_substruct_op(node, union, op):
161 continue
162 for i in range(len(op.args)):
163 if isinstance(op.args[i], Variable):
164 set_use_point(node, op.args[i], "op", node, op, i)
165 set_creation_point(node, op.result, "op", node, op)
166 if isinstance(node.exitswitch, Variable):
167 set_use_point(node, node.exitswitch, "exitswitch", node)
168
169 for node in graph.iterlinks():
170 if isinstance(node.last_exception, Variable):
171 set_creation_point(node.prevblock, node.last_exception,
172 "last_exception")
173 if isinstance(node.last_exc_value, Variable):
174 set_creation_point(node.prevblock, node.last_exc_value,
175 "last_exc_value")
176 duplicate_info = set()
177 for i, arg in enumerate(node.args):
178 union(node.prevblock, arg,
179 node.target, node.target.inputargs[i])
180 if isinstance(arg, Variable):
181
182 _, _, info = lifetimes.find((node.prevblock, arg))
183 if info in duplicate_info and len(info.creationpoints) > 1:
184 # same variable (up to renaming via same_as or
185 # cast_pointer) present several times in link.args, and
186 # the variable is created in two different places:
187 # consider it as a 'use' of the variable, which will
188 # disable malloc optimization (aliasing problems)
189 set_use_point(node.prevblock, arg, "dup", node, i)
190 else:
191 duplicate_info.add(info)
192
193 return lifetimes.infos()
194
195 def _try_inline_malloc(self, info):
196 """Try to inline the mallocs creation and manipulation of the Variables
197 in the given LifeTime."""
198 # the values must be only ever created by a "malloc"
199 lltypes = set()
200 for cp in info.creationpoints:
201 if cp[0] != "op":
202 return False
203 op = cp[2]
204 if not self.check_malloc(op):
205 return False
206 if not self.inline_type(op.args[0].value):
207 return False
208
209 lltypes.add(op.result.concretetype)
210
211 # there must be a single largest malloced GcStruct;
212 # all variables can point to it or to initial substructures
213 if len(lltypes) != 1:
214 return False
215 concretetype, = lltypes
216 STRUCT = self.get_STRUCT(concretetype)
217
218 # must be only ever accessed via getfield/setfield/getsubstruct/
219 # direct_fieldptr, or touched by ptr_iszero/ptr_nonzero.
220 # Note that same_as and cast_pointer are not recorded in usepoints.
221 self.accessed_substructs = set()
222
223 for usepoint in info.usepoints:
224 if usepoint[0] != "op":
225 return False
226 kind, node, op, index = usepoint
227 if index != 0:
228 return False
229 if op.opname in self.CHECK_ARRAY_INDEX:
230 if not isinstance(op.args[1], Constant):
231 return False # non-constant array index
232 if op.opname in self.FIELD_ACCESS:
233 pass # ok
234 elif op.opname in self.SUBSTRUCT_ACCESS:
235 self.do_substruct_access(op)
236 else:
237 return False
238
239 # must not remove mallocs of structures that have a RTTI with a destructor
240 if self.RTTI_dtor(STRUCT):
241 return False
242
243 # must not remove unions inlined as the only field of a GcStruct
244 if self.union_wrapper(STRUCT):
245 return False
246
247 # success: replace each variable with a family of variables (one per field)
248
249 # 'flatnames' is a list of (STRUCTTYPE, fieldname_in_that_struct) that
250 # describes the list of variables that should replace the single
251 # malloc'ed pointer variable that we are about to remove. For primitive
252 # or pointer fields, the new corresponding variable just stores the
253 # actual value. For substructures, if pointers to them are "equivalent"
254 # to pointers to the parent structure (see equivalent_substruct()) then
255 # they are just merged, and flatnames will also list the fields within
256 # that substructure. Other substructures are replaced by a single new
257 # variable which is a pointer to a GcStruct-wrapper; each is malloc'ed
258 # individually, in an exploded way. (The next malloc removal pass will
259 # get rid of them again, in the typical case.)
260 self.flatnames = []
261 self.flatconstants = {}
262 self.needsubmallocs = []
263 self.newvarstype = {} # map {item-of-flatnames: concretetype}
264 self.direct_fieldptr_key = {}
265 self.flatten(STRUCT)
266 assert len(self.direct_fieldptr_key) <= 1
267
268 variables_by_block = {}
269 for block, var in info.variables:
270 vars = variables_by_block.setdefault(block, set())
271 vars.add(var)
272
273 count = [0]
274
275 for block, vars in variables_by_block.items():
276
277 # look for variables arriving from outside the block
278 newvarsmap = None
279 newinputargs = []
280 inputvars = set()
281 for var in block.inputargs:
282 if var in vars:
283 inputvars.add(var)
284 if newvarsmap is None:
285 newvarsmap = {}
286 for key in self.flatnames:
287 newvar = Variable()
288 newvar.concretetype = self.newvarstype[key]
289 newvarsmap[key] = newvar
290 newinputargs.append(newvar)
291 else:
292 newinputargs.append(var)
293 block.inputargs[:] = newinputargs
294 if inputvars:
295 self.flowin(block, count, inputvars, newvarsmap)
296
297 # look for variables created inside the block by a malloc
298 vars_created_here = []
299 for op in block.operations:
300 if self.check_malloc(op) and op.result in vars:
301 vars_created_here.append(op.result)
302 for var in vars_created_here:
303 self.flowin(block, count, {var}, newvarsmap=None)
304
305 return count[0]
306
307 def remove_mallocs_once(self, graph):
308 """Perform one iteration of malloc removal."""
309 simplify.remove_identical_vars(graph)
310 self.graph = graph # to make it possible to find in the debugger
311 lifetimes = self.compute_lifetimes(graph)
312 progress = 0
313 for info in lifetimes:
314 progress += self._try_inline_malloc(info)
315 return progress
316
317 def remove_simple_mallocs(self, graph):
318 """Iteratively remove (inline) the mallocs that can be simplified away."""
319 tot = 0
320 while True:
321 count = self.remove_mallocs_once(graph)
322 if count:
323 if self.verbose:
324 log.malloc('%d simple mallocs removed in %r' % (count, graph.name))
325 else:
326 log.dot()
327 tot += count
328 else:
329 break
330 return tot
331
332
333 class LLTypeMallocRemover(BaseMallocRemover):
334
335 IDENTITY_OPS = ("same_as", "cast_pointer")
336 SUBSTRUCT_OPS = ("getsubstruct", "direct_fieldptr")
337 MALLOC_OP = "malloc"
338 FIELD_ACCESS = dict.fromkeys(["getfield",
339 "setfield",
340 "ptr_iszero",
341 "ptr_nonzero",
342 "getarrayitem",
343 "setarrayitem"])
344 SUBSTRUCT_ACCESS = dict.fromkeys(["getsubstruct",
345 "direct_fieldptr",
346 "getarraysubstruct"])
347 CHECK_ARRAY_INDEX = dict.fromkeys(["getarrayitem",
348 "setarrayitem",
349 "getarraysubstruct"])
350
351 def check_malloc(self, op):
352 if op.opname == 'malloc':
353 flags = op.args[1].value
354 if flags == {'flavor': 'gc'}:
355 return True
356 return False
357
358 def recreate_malloc(self, c, v):
359 return SpaceOperation(self.MALLOC_OP, [c,
360 Constant({'flavor': 'gc'},
361 lltype.Void)],
362 v)
363
364 def get_STRUCT(self, TYPE):
365 STRUCT = TYPE.TO
366 assert isinstance(STRUCT, lltype.GcStruct)
367 return STRUCT
368
369 def visit_substruct_op(self, node, union, op):
370 S = op.args[0].concretetype.TO
371 if self.equivalent_substruct(S, op.args[1].value):
372 # assumed to be similar to a cast_pointer
373 union(node, op.args[0], node, op.result)
374 return True
375 return False
376
377 def do_substruct_access(self, op):
378 S = op.args[0].concretetype.TO
379 name = op.args[1].value
380 if not isinstance(name, str): # access by index
381 name = 'item%d' % (name,)
382 self.accessed_substructs.add((S, name))
383
384 def inline_type(self, TYPE):
385 return True
386
387 def equivalent_substruct(self, S, fieldname):
388 # we consider a pointer to a GcStruct S as equivalent to a
389 # pointer to a substructure 'S.fieldname' if it's the first
390 # inlined sub-GcStruct. As an extension we also allow a pointer
391 # to a GcStruct containing just one field to be equivalent to
392 # a pointer to that field only (although a mere cast_pointer
393 # would not allow casting). This is needed to malloc-remove
394 # the 'wrapper' GcStructs introduced by previous passes of
395 # malloc removal.
396 if not isinstance(S, lltype.GcStruct):
397 return False
398 if fieldname != S._names[0]:
399 return False
400 FIELDTYPE = S._flds[fieldname]
401 if isinstance(FIELDTYPE, lltype.GcStruct):
402 if FIELDTYPE._hints.get('union'):
403 return False
404 return True
405 if len(S._names) == 1:
406 return True
407 return False
408
409 def union_wrapper(self, S):
410 # check if 'S' is a GcStruct containing a single inlined *union* Struct
411 if not isinstance(S, lltype.GcStruct):
412 return False
413 assert not S._hints.get('union') # not supported: "GcUnion"
414 return (len(S._names) == 1 and
415 isinstance(S._flds[S._names[0]], lltype.Struct) and
416 S._flds[S._names[0]]._hints.get('union'))
417
418 def RTTI_dtor(self, STRUCT):
419 try:
420 destr_ptr = lltype.getRuntimeTypeInfo(STRUCT)._obj.destructor_funcptr
421 if destr_ptr:
422 return True
423 except (ValueError, AttributeError):
424 pass
425 return False
426
427 def flatten(self, S):
428 start = 0
429 if S._names and self.equivalent_substruct(S, S._names[0]):
430 SUBTYPE = S._flds[S._names[0]]
431 if isinstance(SUBTYPE, lltype.Struct):
432 self.flatten(SUBTYPE)
433 start = 1
434 else:
435 ARRAY = lltype.FixedSizeArray(SUBTYPE, 1)
436 self.direct_fieldptr_key[ARRAY, 'item0'] = S, S._names[0]
437 for name in S._names[start:]:
438 key = S, name
439 FIELDTYPE = S._flds[name]
440 if key in self.accessed_substructs:
441 self.needsubmallocs.append(key)
442 self.flatnames.append(key)
443 self.newvarstype[key] = lltype.Ptr(lltype.GcStruct('wrapper',
444 ('data', FIELDTYPE)))
445 elif not isinstance(FIELDTYPE, lltype.ContainerType):
446 example = FIELDTYPE._defl()
447 constant = Constant(example)
448 constant.concretetype = FIELDTYPE
449 self.flatconstants[key] = constant
450 self.flatnames.append(key)
451 self.newvarstype[key] = FIELDTYPE
452 #else:
453 # the inlined substructure is never accessed, drop it
454
455 def key_for_field_access(self, S, fldname):
456 if isinstance(S, lltype.FixedSizeArray):
457 if not isinstance(fldname, str): # access by index
458 fldname = 'item%d' % (fldname,)
459 try:
460 return self.direct_fieldptr_key[S, fldname]
461 except KeyError:
462 pass
463 return S, fldname
464
465 def handle_unreachable(self, v_result):
466 from rpython.rtyper.lltypesystem.rstr import string_repr
467 msg = "unreachable operation (from malloc.py)"
468 ll_msg = string_repr.convert_const(msg)
469 c_msg = Constant(ll_msg, lltype.typeOf(ll_msg))
470 return SpaceOperation("debug_fatalerror", [c_msg], v_result)
471
472 def flowin_op(self, op, vars, newvarsmap):
473 if op.opname in ("getfield", "getarrayitem"):
474 S = op.args[0].concretetype.TO
475 fldname = op.args[1].value
476 key = self.key_for_field_access(S, fldname)
477 if key not in newvarsmap:
478 newop = self.handle_unreachable(op.result)
479 elif key in self.accessed_substructs:
480 c_name = Constant('data', lltype.Void)
481 newop = SpaceOperation("getfield",
482 [newvarsmap[key], c_name],
483 op.result)
484 else:
485 newop = SpaceOperation("same_as",
486 [newvarsmap[key]],
487 op.result)
488 self.newops.append(newop)
489 elif op.opname in ("setfield", "setarrayitem"):
490 S = op.args[0].concretetype.TO
491 fldname = op.args[1].value
492 key = self.key_for_field_access(S, fldname)
493 if key not in newvarsmap:
494 newop = self.handle_unreachable(op.result)
495 self.newops.append(newop)
496 elif key in self.accessed_substructs:
497 c_name = Constant('data', lltype.Void)
498 newop = SpaceOperation("setfield",
499 [newvarsmap[key], c_name, op.args[2]],
500 op.result)
501 self.newops.append(newop)
502 else:
503 newvarsmap[key] = op.args[2]
504 elif op.opname in ("same_as", "cast_pointer"):
505 vars.add(op.result)
506 # Consider the two pointers (input and result) as
507 # equivalent. We can, and indeed must, use the same
508 # flattened list of variables for both, as a "setfield"
509 # via one pointer must be reflected in the other.
510 elif op.opname in ("getsubstruct", "getarraysubstruct",
511 "direct_fieldptr"):
512 S = op.args[0].concretetype.TO
513 fldname = op.args[1].value
514 if op.opname == "getarraysubstruct":
515 fldname = 'item%d' % fldname
516 equiv = self.equivalent_substruct(S, fldname)
517 if equiv:
518 # exactly like a cast_pointer
519 assert op.result not in vars
520 vars.add(op.result)
521 else:
522 # do it with a getsubstruct on the independently
523 # malloc'ed GcStruct
524 if op.opname == "direct_fieldptr":
525 opname = "direct_fieldptr"
526 else:
527 opname = "getsubstruct"
528 try:
529 v = newvarsmap[S, fldname]
530 except KeyError:
531 newop = self.handle_unreachable(op.result)
532 else:
533 cname = Constant('data', lltype.Void)
534 newop = SpaceOperation(opname,
535 [v, cname],
536 op.result)
537 self.newops.append(newop)
538 elif op.opname in ("ptr_iszero", "ptr_nonzero"):
539 # we know the pointer is not NULL if it comes from
540 # a successful malloc
541 c = Constant(op.opname == "ptr_nonzero", lltype.Bool)
542 newop = SpaceOperation('same_as', [c], op.result)
543 self.newops.append(newop)
544 else:
545 raise AssertionError(op.opname)
546
547
548 def remove_simple_mallocs(graph, verbose=True):
549 remover = LLTypeMallocRemover(verbose)
550 return remover.remove_simple_mallocs(graph)
551
552
553 def remove_mallocs(translator, graphs=None):
554 if graphs is None:
555 graphs = translator.graphs
556 tot = 0
557 for graph in graphs:
558 count = remove_simple_mallocs(graph, verbose=translator.config.translation.verbose)
559 if count:
560 # remove typical leftovers from malloc removal
561 removenoops.remove_same_as(graph)
562 simplify.eliminate_empty_blocks(graph)
563 simplify.transform_dead_op_vars(graph, translator)
564 tot += count
565 log.malloc("removed %d simple mallocs in total" % tot)
566 return tot