Debian Codegraph @

rpython/translator/backendopt/constfold.py

raw symbols SCIP
1 from rpython.flowspace.model import (Constant, Variable, SpaceOperation,
2 mkentrymap, c_last_exception, copygraph, summary)
3 from rpython.rtyper.lltypesystem import lltype
4 from rpython.rtyper.lltypesystem.lloperation import llop
5 from rpython.translator.unsimplify import insert_empty_block, split_block
6 from rpython.translator import simplify
7 from rpython.rlib import rarithmetic
8
9
10 def fold_op_list(block, constants, exit_early=False, exc_catch=False):
11 operations = block.operations
12 newops = []
13 folded_count = 0
14 for index, spaceop in enumerate(operations):
15 RESTYPE = spaceop.result.concretetype
16 vargsmodif = False
17 vargs = []
18 args = []
19 for v in spaceop.args:
20 if isinstance(v, Constant):
21 args.append(v.value)
22 elif v in constants:
23 v = constants[v]
24 vargsmodif = True
25 args.append(v.value)
26 vargs.append(v)
27 try:
28 op = getattr(llop, spaceop.opname)
29 except AttributeError:
30 pass
31 else:
32 if not op.sideeffects and len(args) == len(vargs):
33 try:
34 result = op(RESTYPE, *args)
35 except TypeError:
36 pass
37 except (KeyboardInterrupt, SystemExit):
38 raise
39 except Exception:
40 pass # turn off reporting these as warnings: useless
41 #log.WARNING('constant-folding %r:' % (spaceop,))
42 #log.WARNING(' %s: %s' % (e.__class__.__name__, e))
43 else:
44 # success in folding this space operation
45 if spaceop.opname in fixup_op_result:
46 result = fixup_op_result[spaceop.opname](result)
47 constants[spaceop.result] = Constant(result, RESTYPE)
48 folded_count += 1
49 continue
50 elif spaceop.opname in ('ptr_eq', 'int_eq'):
51 if spaceop.args[0] == spaceop.args[1]:
52 constants[spaceop.result] = Constant(True, RESTYPE)
53 folded_count += 1
54 continue
55 elif spaceop.opname in ('ptr_ne', 'int_ne'):
56 if spaceop.args[0] == spaceop.args[1]:
57 constants[spaceop.result] = Constant(False, RESTYPE)
58 folded_count += 1
59 continue
60 if (index == len(operations) - 1 and
61 block.exitswitch == c_last_exception and
62 len(args) == len(vargs) == 2 and
63 spaceop.opname.endswith("_ovf") and not exit_early):
64 # deal with int_add_ovf etc but only if exit_early is False
65 RESTYPE = spaceop.result.concretetype
66 result = fold_ovf_op(spaceop, args)
67 if result is None:
68 # always overflows, remove op and link
69 block.exitswitch = None
70 assert block.exits[1].exitcase is OverflowError
71 block.exits[1].exitcase = None
72 block.exits[1].last_exception = None
73 block.exits[1].last_exc_value = None
74 block.recloseblock(block.exits[1])
75 folded_count += 1
76 continue
77 else:
78 block.exitswitch = None
79 block.recloseblock(block.exits[0])
80 constants[spaceop.result] = Constant(result, RESTYPE)
81 folded_count += 1
82 continue
83 # failed to fold an operation, exit early if requested
84 if exit_early:
85 return folded_count
86 else:
87 if vargsmodif:
88 if (spaceop.opname == 'indirect_call'
89 and isinstance(vargs[0], Constant)):
90 spaceop = SpaceOperation('direct_call', vargs[:-1],
91 spaceop.result)
92 else:
93 spaceop = SpaceOperation(spaceop.opname, vargs,
94 spaceop.result)
95 newops.append(spaceop)
96 # end
97 if exit_early:
98 return folded_count
99 else:
100 return newops
101
102 def fold_ovf_op(spaceop, args):
103 a, b = args
104 try:
105 if spaceop.opname in ("int_add_ovf", "int_add_nonneg_ovf"):
106 return rarithmetic.ovfcheck(a + b)
107 elif spaceop.opname == "int_sub_ovf":
108 return rarithmetic.ovfcheck(a - b)
109 else:
110 assert spaceop.opname == "int_mul_ovf"
111 return rarithmetic.ovfcheck(a * b)
112 except OverflowError:
113 return None
114 assert 0, "unreachable"
115
116 def constant_fold_block(block):
117 constants = {}
118 block.operations = fold_op_list(block, constants,
119 exc_catch=block.canraise)
120 if constants:
121 if block.exitswitch in constants:
122 switch = constants[block.exitswitch].value
123 remaining_exits = [link for link in block.exits
124 if link.llexitcase == switch]
125 if not remaining_exits:
126 assert block.exits[-1].exitcase == 'default'
127 remaining_exits = [block.exits[-1]]
128 assert len(remaining_exits) == 1
129 remaining_exits[0].exitcase = None
130 remaining_exits[0].llexitcase = None
131 block.exitswitch = None
132 block.recloseblock(*remaining_exits)
133 for link in block.exits:
134 link.args = [constants.get(v, v) for v in link.args]
135
136
137 def fixup_solid(p):
138 # Operations returning pointers to inlined parts of a constant object
139 # have to be tweaked so that the inlined part keeps the whole object alive.
140 # XXX This is done with a hack. (See test_keepalive_const_*())
141 container = p._obj
142 assert isinstance(container, lltype._parentable)
143 container._keepparent = container._parentstructure()
144 # Instead of 'p', return a solid pointer, to keep the inlined part
145 # itself alive.
146 return container._as_ptr()
147
148 fixup_op_result = {
149 "getsubstruct": fixup_solid,
150 "getarraysubstruct": fixup_solid,
151 "direct_fieldptr": fixup_solid,
152 "direct_arrayitems": fixup_solid,
153 }
154
155
156 def complete_constants(link, constants):
157 # 'constants' maps some Variables of 'block' to Constants.
158 # Some input args of 'block' may be absent from 'constants'
159 # and must be fixed in the link to be passed directly from
160 # 'link.prevblock' instead of via 'block'.
161 for v1, v2 in zip(link.args, link.target.inputargs):
162 if v2 in constants:
163 assert constants[v2] is v1
164 else:
165 constants[v2] = v1
166
167 def rewire_link_for_known_exitswitch(link1, llexitvalue):
168 # For the case where link1.target contains only a switch, rewire link1
169 # to go directly to the correct exit based on a constant switch value.
170 # This is a situation that occurs typically after inlining; see
171 # test_fold_exitswitch_along_one_path.
172 block = link1.target
173 if block.exits[-1].exitcase == "default":
174 defaultexit = block.exits[-1]
175 nondefaultexits = block.exits[:-1]
176 else:
177 defaultexit = None
178 nondefaultexits = block.exits
179 for nextlink in nondefaultexits:
180 if nextlink.llexitcase == llexitvalue:
181 break # found -- the result is in 'nextlink'
182 else:
183 if defaultexit is None:
184 return # exit case not found! just ignore the problem here
185 nextlink = defaultexit
186 blockmapping = dict(zip(block.inputargs, link1.args))
187 newargs = []
188 for v in nextlink.args:
189 if isinstance(v, Variable):
190 v = blockmapping[v]
191 newargs.append(v)
192 link1.target = nextlink.target
193 link1.args = newargs
194
195 def prepare_constant_fold_link(link, constants, splitblocks):
196 block = link.target
197 if not block.operations:
198 # when the target block has no operation, there is nothing we can do
199 # except trying to fold an exitswitch
200 if block.exitswitch is not None and block.exitswitch in constants:
201 llexitvalue = constants[block.exitswitch].value
202 rewire_link_for_known_exitswitch(link, llexitvalue)
203 return
204
205 folded_count = fold_op_list(block, constants, exit_early=True)
206
207 n = len(block.operations)
208 if block.canraise:
209 n -= 1
210 # is the next, non-folded operation an indirect_call?
211 if folded_count < n:
212 nextop = block.operations[folded_count]
213 if nextop.opname == 'indirect_call' and nextop.args[0] in constants:
214 # indirect_call -> direct_call
215 callargs = [constants[nextop.args[0]]]
216 constants1 = constants.copy()
217 complete_constants(link, constants1)
218 for v in nextop.args[1:-1]:
219 callargs.append(constants1.get(v, v))
220 v_result = Variable(nextop.result)
221 v_result.concretetype = nextop.result.concretetype
222 constants[nextop.result] = v_result
223 callop = SpaceOperation('direct_call', callargs, v_result)
224 newblock = insert_empty_block(link, [callop])
225 [link] = newblock.exits
226 assert link.target is block
227 folded_count += 1
228
229 if folded_count > 0:
230 splits = splitblocks.setdefault(block, [])
231 splits.append((folded_count, link, constants))
232
233 def rewire_links(splitblocks, graph):
234 for block, splits in splitblocks.items():
235 # A splitting position is given by how many operations were
236 # folded with the knowledge of an incoming link's constant.
237 # Various incoming links may cause various splitting positions.
238 # We split the block gradually, starting from the end.
239 splits.sort()
240 splits.reverse()
241 for position, link, constants in splits:
242 assert link.target is block
243 if position == len(block.operations) and block.exitswitch is None:
244 # a split here would leave nothing in the 2nd part, so
245 # directly rewire the links
246 assert len(block.exits) == 1
247 splitlink = block.exits[0]
248 else:
249 # split the block at the given position
250 splitlink = split_block(block, position)
251 assert list(block.exits) == [splitlink]
252 assert link.target is block
253 assert splitlink.prevblock is block
254 complete_constants(link, constants)
255 args = [constants.get(v, v) for v in splitlink.args]
256 link.args = args
257 link.target = splitlink.target
258
259
260 def constant_diffuse(graph):
261 count = 0
262 # after 'exitswitch vexit', replace 'vexit' with the corresponding constant
263 # if it also appears on the outgoing links
264 for block in graph.iterblocks():
265 vexit = block.exitswitch
266 if isinstance(vexit, Variable):
267 for link in block.exits:
268 if vexit in link.args and link.exitcase != 'default':
269 remap = {vexit: Constant(link.llexitcase,
270 vexit.concretetype)}
271 link.args = [remap.get(v, v) for v in link.args]
272 count += 1
273 # if the same constants appear at the same positions in all links
274 # into a block remove them from the links, remove the corresponding
275 # input variables and introduce equivalent same_as at the beginning
276 # of the block then try to fold the block further
277 for block, links in mkentrymap(graph).iteritems():
278 if block is graph.startblock:
279 continue
280 if block.exits == ():
281 continue
282 firstlink = links[0]
283 rest = links[1:]
284 diffuse = []
285 for i, c in enumerate(firstlink.args):
286 if not isinstance(c, Constant):
287 continue
288 for lnk in rest:
289 if not same_constant(lnk.args[i], c):
290 break
291 else:
292 diffuse.append((i, c))
293 diffuse.reverse()
294 same_as = []
295 for i, c in diffuse:
296 for lnk in links:
297 del lnk.args[i]
298 v = block.inputargs.pop(i)
299 same_as.append(SpaceOperation('same_as', [c], v))
300 count += 1
301 block.operations = same_as + block.operations
302 if same_as:
303 constant_fold_block(block)
304 return count
305
306 def same_constant(c1, c2):
307 # concretype must be the same, the values flow into the same place
308 assert c1.concretetype == c2.concretetype
309 if not isinstance(c1, Constant) or not isinstance(c2, Constant):
310 return False
311 TYPE = c1.concretetype
312 if isinstance(TYPE, lltype.Ptr) and TYPE.TO._gckind == 'gc':
313 return c1.value == c2.value
314 return c1 == c2
315
316 def constant_fold_graph(graph):
317 # first fold inside the blocks
318 for block in graph.iterblocks():
319 if block.operations:
320 constant_fold_block(block)
321 # then fold along the links - a fixpoint process, because new links
322 # with new constants show up, even though we can probably prove that
323 # a single iteration is enough under some conditions, like the graph
324 # is in a join_blocks() form.
325 while 1:
326 diffused = constant_diffuse(graph)
327 splitblocks = {}
328 for link in list(graph.iterlinks()):
329 constants = {}
330 for v1, v2 in zip(link.args, link.target.inputargs):
331 if isinstance(v1, Constant):
332 constants[v2] = v1
333 if constants:
334 lastop = link.target.operations[-1] if link.target.operations else None
335 ovfflow_block = (len(link.target.operations) == 1 and link.target.canraise
336 and lastop and lastop.opname.endswith("_ovf"))
337 if not ovfflow_block:
338 # normal case
339 prepare_constant_fold_link(link, constants, splitblocks)
340 continue
341 # need to treat the ovf case specially here
342 constargs = []
343 for arg in lastop.args:
344 if isinstance(arg, Constant):
345 constargs.append(arg.value)
346 elif arg in constants:
347 constargs.append(constants[arg].value)
348 else:
349 break
350 else:
351 # can fold
352 res = fold_ovf_op(lastop, constargs)
353 if res is None:
354 # always overflows
355 targetlink = link.target.exits[1]
356 assert targetlink.exitcase is OverflowError
357 else:
358 # doesn't overflow
359 targetlink = link.target.exits[0]
360 assert targetlink.exitcase is None
361 constants[lastop.result] = Constant(res, lastop.result.concretetype)
362 complete_constants(link, constants)
363 link.args = [constants.get(v, v) for v in targetlink.args]
364 link.target = targetlink.target
365 if splitblocks:
366 rewire_links(splitblocks, graph)
367 if not diffused and not splitblocks:
368 break # finished
369 simplify.eliminate_empty_blocks(graph)
370 simplify.join_blocks(graph)
371
372 def replace_symbolic(graph, symbolic, value):
373 result = False
374 for block in graph.iterblocks():
375 for op in block.operations:
376 for i, arg in enumerate(op.args):
377 if isinstance(arg, Constant) and arg.value is symbolic:
378 op.args[i] = value
379 result = True
380 if block.exitswitch is symbolic:
381 block.exitswitch = value
382 result = True
383 return result
384
385 def replace_we_are_jitted(graph):
386 from rpython.rlib import jit
387 replacement = Constant(0)
388 replacement.concretetype = lltype.Signed
389 did_replacement = replace_symbolic(graph, jit._we_are_jitted, replacement)
390 if did_replacement:
391 constant_fold_graph(graph)
392 return did_replacement
393
394