Debian Codegraph @

rpython/translator/simplify.py

raw symbols SCIP
1 """Flow Graph Simplification
2
3 'Syntactic-ish' simplifications on a flow graph.
4
5 simplify_graph() applies all simplifications defined in this file.
6 """
7 import py
8 from collections import defaultdict
9
10 from rpython.tool.algo.unionfind import UnionFind
11 from rpython.flowspace.model import (
12 Variable, Constant, checkgraph, mkentrymap)
13 from rpython.flowspace.operation import OverflowingOperation, op
14 from rpython.rlib import rarithmetic
15 from rpython.translator import unsimplify
16 from rpython.rtyper.lltypesystem import lloperation, lltype
17 from rpython.translator.backendopt.ssa import (
18 SSA_to_SSI, DataFlowFamilyBuilder)
19
20 def get_graph(arg, translator):
21 if isinstance(arg, Variable):
22 return None
23 f = arg.value
24 if not isinstance(f, lltype._ptr):
25 return None
26 try:
27 funcobj = f._obj
28 except lltype.DelayedPointer:
29 return None
30 try:
31 return funcobj.graph
32 except AttributeError:
33 return None
34
35
36 def replace_exitswitch_by_constant(block, const):
37 newexits = [link for link in block.exits
38 if link.exitcase == const.value]
39 if len(newexits) == 0:
40 newexits = [link for link in block.exits
41 if link.exitcase == 'default']
42 assert len(newexits) == 1
43 newexits[0].exitcase = None
44 if hasattr(newexits[0], 'llexitcase'):
45 newexits[0].llexitcase = None
46 block.exitswitch = None
47 block.recloseblock(*newexits)
48 return newexits
49
50 # ____________________________________________________________
51
52 def eliminate_empty_blocks(graph):
53 """Eliminate basic blocks that do not contain any operations.
54 When this happens, we need to replace the preceeding link with the
55 following link. Arguments of the links should be updated."""
56 for link in list(graph.iterlinks()):
57 while not link.target.operations:
58 block1 = link.target
59 if block1.exitswitch is not None:
60 break
61 if not block1.exits:
62 break
63 exit = block1.exits[0]
64 assert block1 is not exit.target, (
65 "the graph contains an empty infinite loop")
66 subst = dict(zip(block1.inputargs, link.args))
67 link.args = [v.replace(subst) for v in exit.args]
68 link.target = exit.target
69 # the while loop above will simplify recursively the new link
70
71 def transform_ovfcheck(graph):
72 """The special function calls ovfcheck needs to
73 be translated into primitive operations. ovfcheck is called directly
74 after an operation that should be turned into an overflow-checked
75 version. It is considered a syntax error if the resulting <op>_ovf
76 is not defined in objspace/flow/objspace.py.
77 """
78 covf = Constant(rarithmetic.ovfcheck)
79
80 for block in graph.iterblocks():
81 for i in range(len(block.operations)-1, -1, -1):
82 op = block.operations[i]
83 if op.opname != 'simple_call':
84 continue
85 if op.args[0] == covf:
86 if i == 0:
87 # hard case: ovfcheck() on an operation that occurs
88 # in the previous block, like 'floordiv'. The generic
89 # exception handling around the ovfcheck() is enough
90 # to cover all cases; kill the one around the previous op.
91 entrymap = mkentrymap(graph)
92 links = entrymap[block]
93 assert len(links) == 1
94 prevblock = links[0].prevblock
95 assert prevblock.exits[0].target is block
96 prevblock.exitswitch = None
97 prevblock.exits = (links[0],)
98 join_blocks(graph) # merge the two blocks together
99 transform_ovfcheck(graph) # ...and try again
100 return
101 op1 = block.operations[i - 1]
102 if not isinstance(op1, OverflowingOperation):
103 raise Exception("ovfcheck in %s: Operation %s has no "
104 "overflow variant" % (graph.name, op1.opname))
105 op1_ovf = op1.ovfchecked()
106 block.operations[i - 1] = op1_ovf
107 del block.operations[i]
108 block.renamevariables({op.result: op1_ovf.result})
109
110 def simplify_exceptions(graph):
111 """The exception handling caused by non-implicit exceptions
112 starts with an exitswitch on Exception, followed by a lengthy
113 chain of is_/issubtype tests. We collapse them all into
114 the block's single list of exits.
115 """
116 renaming = {}
117 for block in graph.iterblocks():
118 if not (block.canraise
119 and block.exits[-1].exitcase is Exception):
120 continue
121 covered = [link.exitcase for link in block.exits[1:-1]]
122 seen = []
123 preserve = list(block.exits[:-1])
124 exc = block.exits[-1]
125 last_exception = exc.last_exception
126 last_exc_value = exc.last_exc_value
127 query = exc.target
128 switches = []
129 # collect the targets
130 while len(query.exits) == 2:
131 newrenaming = {}
132 for lprev, ltarg in zip(exc.args, query.inputargs):
133 newrenaming[ltarg] = lprev.replace(renaming)
134 op = query.operations[0]
135 if not (op.opname in ("is_", "issubtype") and
136 op.args[0].replace(newrenaming) == last_exception):
137 break
138 renaming.update(newrenaming)
139 case = query.operations[0].args[-1].value
140 assert issubclass(case, py.builtin.BaseException)
141 lno, lyes = query.exits
142 assert lno.exitcase == False and lyes.exitcase == True
143 if case not in seen:
144 is_covered = False
145 for cov in covered:
146 if issubclass(case, cov):
147 is_covered = True
148 break
149 if not is_covered:
150 switches.append( (case, lyes) )
151 seen.append(case)
152 exc = lno
153 query = exc.target
154 if Exception not in seen:
155 switches.append( (Exception, exc) )
156 # construct the block's new exits
157 exits = []
158 for case, oldlink in switches:
159 link = oldlink.replace(renaming)
160 assert case is not None
161 link.last_exception = last_exception
162 link.last_exc_value = last_exc_value
163 # make the above two variables unique
164 renaming2 = {}
165 for v in link.getextravars():
166 renaming2[v] = Variable(v)
167 link = link.replace(renaming2)
168 link.exitcase = case
169 exits.append(link)
170 block.recloseblock(*(preserve + exits))
171
172 def transform_xxxitem(graph):
173 # xxx setitem too
174 for block in graph.iterblocks():
175 if block.canraise:
176 last_op = block.raising_op
177 if last_op.opname == 'getitem':
178 postfx = []
179 for exit in block.exits:
180 if exit.exitcase is IndexError:
181 postfx.append('idx')
182 if postfx:
183 Op = getattr(op, '_'.join(['getitem'] + postfx))
184 newop = Op(*last_op.args)
185 newop.result = last_op.result
186 block.operations[-1] = newop
187
188
189 def remove_dead_exceptions(graph):
190 """Exceptions can be removed if they are unreachable"""
191 def issubclassofmember(cls, seq):
192 for member in seq:
193 if member and issubclass(cls, member):
194 return True
195 return False
196
197 for block in list(graph.iterblocks()):
198 if not block.canraise:
199 continue
200 exits = []
201 seen = []
202 for link in block.exits:
203 case = link.exitcase
204 # check whether exceptions are shadowed
205 if issubclassofmember(case, seen):
206 continue
207 # see if the previous case can be merged
208 while len(exits) > 1:
209 prev = exits[-1]
210 if not (issubclass(prev.exitcase, link.exitcase) and
211 prev.target is link.target and prev.args == link.args):
212 break
213 exits.pop()
214 exits.append(link)
215 seen.append(case)
216 block.recloseblock(*exits)
217
218 def constfold_exitswitch(graph):
219 """Remove trivial links by merging their source and target blocks
220
221 A link is trivial if it has no arguments, is the single exit of its
222 source and the single parent of its target.
223 """
224 block = graph.startblock
225 seen = set([block])
226 stack = list(block.exits)
227 while stack:
228 link = stack.pop()
229 target = link.target
230 if target in seen:
231 continue
232 source = link.prevblock
233 switch = source.exitswitch
234 if (isinstance(switch, Constant) and not source.canraise):
235 exits = replace_exitswitch_by_constant(source, switch)
236 stack.extend(exits)
237 else:
238 seen.add(target)
239 stack.extend(target.exits)
240
241
242 def remove_trivial_links(graph):
243 """Remove trivial links by merging their source and target blocks
244
245 A link is trivial if it has no arguments, is the single exit of its
246 source and the single parent of its target.
247 """
248 entrymap = mkentrymap(graph)
249 block = graph.startblock
250 seen = set([block])
251 stack = list(block.exits)
252 while stack:
253 link = stack.pop()
254 if link.target in seen:
255 continue
256 source = link.prevblock
257 target = link.target
258 if (not link.args and source.exitswitch is None and
259 len(entrymap[target]) == 1 and
260 target.exits): # stop at the returnblock
261 assert len(source.exits) == 1
262 source.operations.extend(target.operations)
263 source.exitswitch = newexitswitch = target.exitswitch
264 source.recloseblock(*target.exits)
265 stack.extend(source.exits)
266 else:
267 seen.add(target)
268 stack.extend(target.exits)
269
270
271 def join_blocks(graph):
272 """Links can be deleted if they are the single exit of a block and
273 the single entry point of the next block. When this happens, we can
274 append all the operations of the following block to the preceeding
275 block (but renaming variables with the appropriate arguments.)
276 """
277 entrymap = mkentrymap(graph)
278 block = graph.startblock
279 seen = {block: True}
280 stack = list(block.exits)
281 while stack:
282 link = stack.pop()
283 if (link.prevblock.exitswitch is None and
284 len(entrymap[link.target]) == 1 and
285 link.target.exits): # stop at the returnblock
286 assert len(link.prevblock.exits) == 1
287 renaming = {}
288 for vprev, vtarg in zip(link.args, link.target.inputargs):
289 renaming[vtarg] = vprev
290 def rename_op(op):
291 op = op.replace(renaming)
292 # special case...
293 if op.opname == 'indirect_call':
294 if isinstance(op.args[0], Constant):
295 assert isinstance(op.args[-1], Constant)
296 del op.args[-1]
297 op.opname = 'direct_call'
298 return op
299 for op in link.target.operations:
300 link.prevblock.operations.append(rename_op(op))
301 exits = []
302 for exit in link.target.exits:
303 newexit = exit.replace(renaming)
304 exits.append(newexit)
305 if link.target.exitswitch:
306 newexitswitch = link.target.exitswitch.replace(renaming)
307 else:
308 newexitswitch = None
309 link.prevblock.exitswitch = newexitswitch
310 link.prevblock.recloseblock(*exits)
311 if (isinstance(newexitswitch, Constant) and
312 not link.prevblock.canraise):
313 exits = replace_exitswitch_by_constant(link.prevblock,
314 newexitswitch)
315 stack.extend(exits)
316 else:
317 if link.target not in seen:
318 stack.extend(link.target.exits)
319 seen[link.target] = True
320
321 def remove_assertion_errors(graph):
322 """Remove branches that go directly to raising an AssertionError,
323 assuming that AssertionError shouldn't occur at run-time. Note that
324 this is how implicit exceptions are removed (see _implicit_ in
325 flowcontext.py).
326 """
327 for block in list(graph.iterblocks()):
328 for i in range(len(block.exits)-1, -1, -1):
329 exit = block.exits[i]
330 if not (exit.target is graph.exceptblock and
331 exit.args[0] == Constant(AssertionError)):
332 continue
333 # can we remove this exit without breaking the graph?
334 if len(block.exits) < 2:
335 break
336 if block.canraise:
337 if exit.exitcase is None:
338 break
339 if len(block.exits) == 2:
340 # removing the last non-exceptional exit
341 block.exitswitch = None
342 exit.exitcase = None
343 # remove this exit
344 lst = list(block.exits)
345 del lst[i]
346 block.recloseblock(*lst)
347
348
349 # _____________________________________________________________________
350 # decide whether a function has side effects
351
352 def op_has_side_effects(op):
353 return lloperation.LL_OPERATIONS[op.opname].sideeffects
354
355 def has_no_side_effects(translator, graph, seen=None):
356 #is the graph specialized? if no we can't say anything
357 #don't cache the result though
358 if translator.rtyper is None:
359 return False
360 else:
361 if graph.startblock not in translator.rtyper.already_seen:
362 return False
363 if seen is None:
364 seen = {}
365 elif graph in seen:
366 return True
367 newseen = seen.copy()
368 newseen[graph] = True
369 for block in graph.iterblocks():
370 if block is graph.exceptblock:
371 return False # graphs explicitly raising have side-effects
372 for op in block.operations:
373 if rec_op_has_side_effects(translator, op, newseen):
374 return False
375 return True
376
377 def rec_op_has_side_effects(translator, op, seen=None):
378 if op.opname == "direct_call":
379 g = get_graph(op.args[0], translator)
380 if g is None:
381 return True
382 if not has_no_side_effects(translator, g, seen):
383 return True
384 elif op.opname == "indirect_call":
385 graphs = op.args[-1].value
386 if graphs is None:
387 return True
388 for g in graphs:
389 if not has_no_side_effects(translator, g, seen):
390 return True
391 else:
392 return op_has_side_effects(op)
393
394 # ___________________________________________________________________________
395 # remove operations if their result is not used and they have no side effects
396
397 def transform_dead_op_vars(graph, translator=None):
398 """Remove dead operations and variables that are passed over a link
399 but not used in the target block. Input is a graph."""
400 return transform_dead_op_vars_in_blocks(list(graph.iterblocks()),
401 [graph], translator)
402
403 # the set of operations that can safely be removed
404 # (they have no side effects, at least in R-Python)
405 CanRemove = {}
406 for _op in '''
407 newtuple newlist newdict bool
408 is_ id type issubtype isinstance repr str len hash getattr getitem
409 pos neg abs hex oct ord invert add sub mul
410 truediv floordiv div mod divmod pow lshift rshift and_ or_
411 xor int float long lt le eq ne gt ge cmp coerce contains
412 iter get'''.split():
413 CanRemove[_op] = True
414 from rpython.rtyper.lltypesystem.lloperation import enum_ops_without_sideeffects
415 for _op in enum_ops_without_sideeffects():
416 CanRemove[_op] = True
417 del _op
418 CanRemoveBuiltins = {
419 hasattr: True,
420 }
421
422 def transform_dead_op_vars_in_blocks(blocks, graphs, translator=None):
423 """Remove dead operations and variables that are passed over a link
424 but not used in the target block. Input is a set of blocks"""
425 read_vars = set() # set of variables really used
426 dependencies = defaultdict(set) # map {Var: list-of-Vars-it-depends-on}
427 set_of_blocks = set(blocks)
428 if len(graphs) == 1:
429 start_blocks = {graphs[0].startblock}
430 else:
431 assert translator
432 start_blocks = {translator.annotator.annotated[block].startblock
433 for block in blocks}
434
435 def canremove(op, block):
436 return op.opname in CanRemove and op is not block.raising_op
437
438 # compute dependencies and an initial read_vars
439 for block in blocks:
440 # figure out which variables are ever read
441 for op in block.operations:
442 if not canremove(op, block): # the inputs are always needed
443 read_vars.update(op.args)
444 else:
445 dependencies[op.result].update(op.args)
446
447 if isinstance(block.exitswitch, Variable):
448 read_vars.add(block.exitswitch)
449
450 if block.exits:
451 for link in block.exits:
452 if link.target not in set_of_blocks:
453 for arg, targetarg in zip(link.args, link.target.inputargs):
454 read_vars.add(arg)
455 read_vars.add(targetarg)
456 else:
457 for arg, targetarg in zip(link.args, link.target.inputargs):
458 dependencies[targetarg].add(arg)
459 else:
460 # return and except blocks implicitely use their input variable(s)
461 for arg in block.inputargs:
462 read_vars.add(arg)
463 # a start block's inputargs should not be modified, even if some
464 # of the function's input arguments are not actually used
465 if block in start_blocks:
466 for arg in block.inputargs:
467 read_vars.add(arg)
468
469 # flow read_vars backwards so that any variable on which a read_vars
470 # depends is also included in read_vars
471 def flow_read_var_backward(pending):
472 while pending:
473 var = pending.pop()
474 for prevvar in dependencies[var]:
475 if prevvar not in read_vars:
476 read_vars.add(prevvar)
477 pending.add(prevvar)
478
479 flow_read_var_backward(set(read_vars))
480
481 for block in blocks:
482
483 # look for removable operations whose result is never used
484 for i in range(len(block.operations)-1, -1, -1):
485 op = block.operations[i]
486 if op.result not in read_vars:
487 if canremove(op, block):
488 del block.operations[i]
489 elif op.opname == 'simple_call':
490 # XXX we want to have a more effective and safe
491 # way to check if this operation has side effects
492 # ...
493 if op.args and isinstance(op.args[0], Constant):
494 func = op.args[0].value
495 try:
496 if func in CanRemoveBuiltins:
497 del block.operations[i]
498 except TypeError: # func is not hashable
499 pass
500 elif op.opname == 'direct_call':
501 if translator is not None:
502 graph = get_graph(op.args[0], translator)
503 if (graph is not None and
504 has_no_side_effects(translator, graph) and
505 op is not block.raising_op):
506 del block.operations[i]
507 # look for output variables never used
508 # warning: this must be completely done *before* we attempt to
509 # remove the corresponding variables from block.inputargs!
510 # Otherwise the link.args get out of sync with the
511 # link.target.inputargs.
512 for link in block.exits:
513 assert len(link.args) == len(link.target.inputargs)
514 for i in range(len(link.args)-1, -1, -1):
515 if link.target.inputargs[i] not in read_vars:
516 del link.args[i]
517 # the above assert would fail here
518
519 for block in blocks:
520 # look for input variables never used
521 # The corresponding link.args have already been all removed above
522 for i in range(len(block.inputargs)-1, -1, -1):
523 if block.inputargs[i] not in read_vars:
524 del block.inputargs[i]
525
526 class Representative(object):
527 def __init__(self, var):
528 self.rep = var
529
530 def absorb(self, other):
531 pass
532
533 def all_equal(lst):
534 first = lst[0]
535 return all(first == x for x in lst[1:])
536
537 def isspecialvar(v):
538 return isinstance(v, Variable) and v._name in ('last_exception_', 'last_exc_value_')
539
540 def remove_identical_vars_SSA(graph):
541 """When the same variable is passed multiple times into the next block,
542 pass it only once. This enables further optimizations by the annotator,
543 which otherwise doesn't realize that tests performed on one of the copies
544 of the variable also affect the other."""
545 uf = UnionFind(Representative)
546 entrymap = mkentrymap(graph)
547 del entrymap[graph.startblock]
548 entrymap.pop(graph.returnblock, None)
549 entrymap.pop(graph.exceptblock, None)
550 inputs = {}
551 for block, links in entrymap.items():
552 phis = zip(block.inputargs, zip(*[link.args for link in links]))
553 inputs[block] = phis
554
555 def simplify_phis(block):
556 phis = inputs[block]
557 to_remove = []
558 unique_phis = {}
559 for i, (input, phi_args) in enumerate(phis):
560 new_args = [uf.find_rep(arg) for arg in phi_args]
561 if all_equal(new_args) and not isspecialvar(new_args[0]):
562 uf.union(new_args[0], input)
563 to_remove.append(i)
564 else:
565 t = tuple(new_args)
566 if t in unique_phis:
567 uf.union(unique_phis[t], input)
568 to_remove.append(i)
569 else:
570 unique_phis[t] = input
571 for i in reversed(to_remove):
572 del phis[i]
573 return bool(to_remove)
574
575 progress = True
576 while progress:
577 progress = False
578 for block in inputs:
579 if simplify_phis(block):
580 progress = True
581
582 renaming = dict((key, uf[key].rep) for key in uf)
583 for block, links in entrymap.items():
584 if inputs[block]:
585 new_inputs, new_args = zip(*inputs[block])
586 new_args = map(list, zip(*new_args))
587 else:
588 new_inputs = []
589 new_args = [[] for _ in links]
590 block.inputargs = new_inputs
591 assert len(links) == len(new_args)
592 for link, args in zip(links, new_args):
593 link.args = args
594 for block in entrymap:
595 block.renamevariables(renaming)
596
597 def remove_identical_vars(graph):
598 """When the same variable is passed multiple times into the next block,
599 pass it only once. This enables further optimizations by the annotator,
600 which otherwise doesn't realize that tests performed on one of the copies
601 of the variable also affect the other."""
602
603 # This algorithm is based on DataFlowFamilyBuilder, used as a
604 # "phi node remover" (in the SSA sense). 'variable_families' is a
605 # UnionFind object that groups variables by families; variables from the
606 # same family can be identified, and if two input arguments of a block
607 # end up in the same family, then we really remove one of them in favor
608 # of the other.
609 #
610 # The idea is to identify as much variables as possible by trying
611 # iteratively two kinds of phi node removal:
612 #
613 # * "vertical", by identifying variables from different blocks, when
614 # we see that a value just flows unmodified into the next block without
615 # needing any merge (this is what backendopt.ssa.SSI_to_SSA() would do
616 # as well);
617 #
618 # * "horizontal", by identifying two input variables of the same block,
619 # when these two variables' phi nodes have the same argument -- i.e.
620 # when for all possible incoming paths they would get twice the same
621 # value (this is really the purpose of remove_identical_vars()).
622 #
623 builder = DataFlowFamilyBuilder(graph)
624 variable_families = builder.get_variable_families() # vertical removal
625 while True:
626 if not builder.merge_identical_phi_nodes(): # horizontal removal
627 break
628 if not builder.complete(): # vertical removal
629 break
630
631 for block, links in mkentrymap(graph).items():
632 if block is graph.startblock:
633 continue
634 renaming = {}
635 family2blockvar = {}
636 kills = []
637 for i, v in enumerate(block.inputargs):
638 v1 = variable_families.find_rep(v)
639 if v1 in family2blockvar:
640 # already seen -- this variable can be shared with the
641 # previous one
642 renaming[v] = family2blockvar[v1]
643 kills.append(i)
644 else:
645 family2blockvar[v1] = v
646 if renaming:
647 block.renamevariables(renaming)
648 # remove the now-duplicate input variables
649 kills.reverse() # starting from the end
650 for i in kills:
651 del block.inputargs[i]
652 for link in links:
653 del link.args[i]
654
655
656 def coalesce_bool(graph):
657 """coalesce paths that go through an bool and a directly successive
658 bool both on the same value, transforming the link into the
659 second bool from the first to directly jump to the correct
660 target out of the second."""
661 candidates = []
662
663 def has_bool_exitpath(block):
664 tgts = []
665 start_op = block.operations[-1]
666 cond_v = start_op.args[0]
667 if block.exitswitch == start_op.result:
668 for exit in block.exits:
669 tgt = exit.target
670 if tgt == block:
671 continue
672 rrenaming = dict(zip(tgt.inputargs,exit.args))
673 if len(tgt.operations) == 1 and tgt.operations[0].opname == 'bool':
674 tgt_op = tgt.operations[0]
675 if tgt.exitswitch == tgt_op.result and rrenaming.get(tgt_op.args[0]) == cond_v:
676 tgts.append((exit.exitcase, tgt))
677 return tgts
678
679 for block in graph.iterblocks():
680 if block.operations and block.operations[-1].opname == 'bool':
681 tgts = has_bool_exitpath(block)
682 if tgts:
683 candidates.append((block, tgts))
684
685 while candidates:
686 cand, tgts = candidates.pop()
687 newexits = list(cand.exits)
688 for case, tgt in tgts:
689 exit = cand.exits[case]
690 rrenaming = dict(zip(tgt.inputargs,exit.args))
691 rrenaming[tgt.operations[0].result] = cand.operations[-1].result
692 def rename(v):
693 return rrenaming.get(v,v)
694 newlink = tgt.exits[case].copy(rename)
695 newexits[case] = newlink
696 cand.recloseblock(*newexits)
697 newtgts = has_bool_exitpath(cand)
698 if newtgts:
699 candidates.append((cand, newtgts))
700
701 # ____________________________________________________________
702
703 def detect_list_comprehension(graph):
704 """Look for the pattern: Replace it with marker operations:
705
706 v0 = newlist()
707 v2 = newlist() v1 = hint(v0, iterable, {'maxlength'})
708 loop start loop start
709 ... ...
710 exactly one append per loop v1.append(..)
711 and nothing else done with v2
712 ... ...
713 loop end v2 = hint(v1, {'fence'})
714 """
715 # NB. this assumes RPythonicity: we can only iterate over something
716 # that has a len(), and this len() cannot change as long as we are
717 # using the iterator.
718 builder = DataFlowFamilyBuilder(graph)
719 variable_families = builder.get_variable_families()
720 c_append = Constant('append')
721 newlist_v = {}
722 iter_v = {}
723 append_v = []
724 loopnextblocks = []
725
726 # collect relevant operations based on the family of their result
727 for block in graph.iterblocks():
728 if (len(block.operations) == 1 and
729 block.operations[0].opname == 'next' and
730 block.canraise and len(block.exits) >= 2):
731 cases = [link.exitcase for link in block.exits]
732 if None in cases and StopIteration in cases:
733 # it's a straightforward loop start block
734 loopnextblocks.append((block, block.operations[0].args[0]))
735 continue
736 for op in block.operations:
737 if op.opname == 'newlist' and not op.args:
738 vlist = variable_families.find_rep(op.result)
739 newlist_v[vlist] = block
740 if op.opname == 'iter':
741 viter = variable_families.find_rep(op.result)
742 iter_v[viter] = block
743 loops = []
744 for block, viter in loopnextblocks:
745 viterfamily = variable_families.find_rep(viter)
746 if viterfamily in iter_v:
747 # we have a next(viter) operation where viter comes from a
748 # single known iter() operation. Check that the iter()
749 # operation is in the block just before.
750 iterblock = iter_v[viterfamily]
751 if (len(iterblock.exits) == 1 and iterblock.exitswitch is None
752 and iterblock.exits[0].target is block):
753 # yes - simple case.
754 loops.append((block, iterblock, viterfamily))
755 if not newlist_v or not loops:
756 return
757
758 # XXX works with Python >= 2.4 only: find calls to append encoded as
759 # getattr/simple_call pairs, as produced by the LIST_APPEND bytecode.
760 for block in graph.iterblocks():
761 for i in range(len(block.operations)-1):
762 op = block.operations[i]
763 if op.opname == 'getattr' and op.args[1] == c_append:
764 vlist = variable_families.find_rep(op.args[0])
765 if vlist in newlist_v:
766 for j in range(i + 1, len(block.operations)):
767 op2 = block.operations[j]
768 if (op2.opname == 'simple_call' and len(op2.args) == 2
769 and op2.args[0] is op.result):
770 append_v.append((op.args[0], op.result, block))
771 break
772 if not append_v:
773 return
774 detector = ListComprehensionDetector(graph, loops, newlist_v,
775 variable_families)
776 graphmutated = False
777 for location in append_v:
778 if graphmutated:
779 # new variables introduced, must restart the whole process
780 return detect_list_comprehension(graph)
781 try:
782 detector.run(*location)
783 except DetectorFailed:
784 pass
785 else:
786 graphmutated = True
787
788 class DetectorFailed(Exception):
789 pass
790
791 class ListComprehensionDetector(object):
792
793 def __init__(self, graph, loops, newlist_v, variable_families):
794 self.graph = graph
795 self.loops = loops
796 self.newlist_v = newlist_v
797 self.variable_families = variable_families
798 self.reachable_cache = {}
799
800 def enum_blocks_with_vlist_from(self, fromblock, avoid):
801 found = {avoid: True}
802 pending = [fromblock]
803 while pending:
804 block = pending.pop()
805 if block in found:
806 continue
807 if not self.vlist_alive(block):
808 continue
809 yield block
810 found[block] = True
811 for exit in block.exits:
812 pending.append(exit.target)
813
814 def enum_reachable_blocks(self, fromblock, stop_at, stay_within=None):
815 if fromblock is stop_at:
816 return
817 found = {stop_at: True}
818 pending = [fromblock]
819 while pending:
820 block = pending.pop()
821 if block in found:
822 continue
823 found[block] = True
824 for exit in block.exits:
825 if stay_within is None or exit.target in stay_within:
826 yield exit.target
827 pending.append(exit.target)
828
829 def reachable_within(self, fromblock, toblock, avoid, stay_within):
830 if toblock is avoid:
831 return False
832 for block in self.enum_reachable_blocks(fromblock, avoid, stay_within):
833 if block is toblock:
834 return True
835 return False
836
837 def reachable(self, fromblock, toblock, avoid):
838 if toblock is avoid:
839 return False
840 try:
841 return self.reachable_cache[fromblock, toblock, avoid]
842 except KeyError:
843 pass
844 future = [fromblock]
845 for block in self.enum_reachable_blocks(fromblock, avoid):
846 self.reachable_cache[fromblock, block, avoid] = True
847 if block is toblock:
848 return True
849 future.append(block)
850 # 'toblock' is unreachable from 'fromblock', so it is also
851 # unreachable from any of the 'future' blocks
852 for block in future:
853 self.reachable_cache[block, toblock, avoid] = False
854 return False
855
856 def vlist_alive(self, block):
857 # check if 'block' is in the "cone" of blocks where
858 # the vlistfamily lives
859 try:
860 return self.vlistcone[block]
861 except KeyError:
862 result = bool(self.contains_vlist(block.inputargs))
863 self.vlistcone[block] = result
864 return result
865
866 def vlist_escapes(self, block):
867 # check if the vlist "escapes" to uncontrolled places in that block
868 try:
869 return self.escapes[block]
870 except KeyError:
871 for op in block.operations:
872 if op.result is self.vmeth:
873 continue # the single getattr(vlist, 'append') is ok
874 if op.opname == 'getitem':
875 continue # why not allow getitem(vlist, index) too
876 if self.contains_vlist(op.args):
877 result = True
878 break
879 else:
880 result = False
881 self.escapes[block] = result
882 return result
883
884 def contains_vlist(self, args):
885 for arg in args:
886 if self.variable_families.find_rep(arg) is self.vlistfamily:
887 return arg
888 else:
889 return None
890
891 def remove_vlist(self, args):
892 removed = 0
893 for i in range(len(args)-1, -1, -1):
894 arg = self.variable_families.find_rep(args[i])
895 if arg is self.vlistfamily:
896 del args[i]
897 removed += 1
898 assert removed == 1
899
900 def run(self, vlist, vmeth, appendblock):
901 # first check that the 'append' method object doesn't escape
902 for hlop in appendblock.operations:
903 if hlop.opname == 'simple_call' and hlop.args[0] is vmeth:
904 pass
905 elif vmeth in hlop.args:
906 raise DetectorFailed # used in another operation
907 for link in appendblock.exits:
908 if vmeth in link.args:
909 raise DetectorFailed # escapes to a next block
910
911 self.vmeth = vmeth
912 self.vlistfamily = self.variable_families.find_rep(vlist)
913 newlistblock = self.newlist_v[self.vlistfamily]
914 self.vlistcone = {newlistblock: True}
915 self.escapes = {self.graph.returnblock: True,
916 self.graph.exceptblock: True}
917
918 # in which loop are we?
919 for loopnextblock, iterblock, viterfamily in self.loops:
920 # check that the vlist is alive across the loop head block,
921 # which ensures that we have a whole loop where the vlist
922 # doesn't change
923 if not self.vlist_alive(loopnextblock):
924 continue # no - unrelated loop
925
926 # check that we cannot go from 'newlist' to 'append' without
927 # going through the 'iter' of our loop (and the following 'next').
928 # This ensures that the lifetime of vlist is cleanly divided in
929 # "before" and "after" the loop...
930 if self.reachable(newlistblock, appendblock, avoid=iterblock):
931 continue
932
933 # ... with the possible exception of links from the loop
934 # body jumping back to the loop prologue, between 'newlist' and
935 # 'iter', which we must forbid too:
936 if self.reachable(loopnextblock, iterblock, avoid=newlistblock):
937 continue
938
939 # there must not be a larger number of calls to 'append' than
940 # the number of elements that 'next' returns, so we must ensure
941 # that we cannot go from 'append' to 'append' again without
942 # passing 'next'...
943 if self.reachable(appendblock, appendblock, avoid=loopnextblock):
944 continue
945
946 # ... and when the iterator is exhausted, we should no longer
947 # reach 'append' at all.
948 stopblocks = [link.target for link in loopnextblock.exits
949 if link.exitcase is not None]
950 accepted = True
951 for stopblock1 in stopblocks:
952 if self.reachable(stopblock1, appendblock, avoid=newlistblock):
953 accepted = False
954 if not accepted:
955 continue
956
957 # now explicitly find the "loop body" blocks: they are the ones
958 # from which we can reach 'append' without going through 'iter'.
959 # (XXX inefficient)
960 loopbody = {}
961 for block in self.graph.iterblocks():
962 if (self.vlist_alive(block) and
963 self.reachable(block, appendblock, iterblock)):
964 loopbody[block] = True
965
966 # if the 'append' is actually after a 'break' or on a path that
967 # can only end up in a 'break', then it won't be recorded as part
968 # of the loop body at all. This is a strange case where we have
969 # basically proved that the list will be of length 1... too
970 # uncommon to worry about, I suspect
971 if appendblock not in loopbody:
972 continue
973
974 # This candidate loop is acceptable if the list is not escaping
975 # too early, i.e. in the loop header or in the loop body.
976 loopheader = list(self.enum_blocks_with_vlist_from(newlistblock,
977 avoid=loopnextblock))
978 assert loopheader[0] is newlistblock
979 escapes = False
980 for block in loopheader + loopbody.keys():
981 assert self.vlist_alive(block)
982 if self.vlist_escapes(block):
983 escapes = True
984 break
985
986 if not escapes:
987 break # accept this loop!
988
989 else:
990 raise DetectorFailed # no suitable loop
991
992 # Found a suitable loop, let's patch the graph:
993 assert iterblock not in loopbody
994 assert loopnextblock in loopbody
995 for stopblock1 in stopblocks:
996 assert stopblock1 not in loopbody
997
998 # at StopIteration, the new list is exactly of the same length as
999 # the one we iterate over if it's not possible to skip the appendblock
1000 # in the body:
1001 exactlength = not self.reachable_within(loopnextblock, loopnextblock,
1002 avoid = appendblock,
1003 stay_within = loopbody)
1004
1005 # - add a hint(vlist, iterable, {'maxlength'}) in the iterblock,
1006 # where we can compute the known maximum length
1007 # - new in June 2017: we do that only if 'exactlength' is True.
1008 # found some real use cases where the over-allocation scheme
1009 # was over-allocating far too much: the loop would only append
1010 # an item to the list after 'if some rare condition:'. By
1011 # dropping this hint, we disable preallocation and cause the
1012 # append() to be done by checking the size, but still, after
1013 # the loop, we will turn the list into a fixed-size one.
1014 # ('maxlength_inexact' is never processed elsewhere; the hint
1015 # is still needed to prevent this function from being entered
1016 # in an infinite loop)
1017 link = iterblock.exits[0]
1018 vlist = self.contains_vlist(link.args)
1019 assert vlist
1020 for hlop in iterblock.operations:
1021 res = self.variable_families.find_rep(hlop.result)
1022 if res is viterfamily:
1023 break
1024 else:
1025 raise AssertionError("lost 'iter' operation")
1026 chint = Constant({'maxlength' if exactlength else 'maxlength_inexact':
1027 True})
1028 hint = op.hint(vlist, hlop.args[0], chint)
1029 iterblock.operations.append(hint)
1030 link.args = list(link.args)
1031 for i in range(len(link.args)):
1032 if link.args[i] is vlist:
1033 link.args[i] = hint.result
1034
1035 # - wherever the list exits the loop body, add a 'hint({fence})'
1036 for block in loopbody:
1037 for link in block.exits:
1038 if link.target not in loopbody:
1039 vlist = self.contains_vlist(link.args)
1040 if vlist is None:
1041 continue # list not passed along this link anyway
1042 hints = {'fence': True}
1043 if (exactlength and block is loopnextblock and
1044 link.target in stopblocks):
1045 hints['exactlength'] = True
1046 chints = Constant(hints)
1047 newblock = unsimplify.insert_empty_block(link)
1048 index = link.args.index(vlist)
1049 vlist2 = newblock.inputargs[index]
1050 vlist3 = Variable(vlist2)
1051 newblock.inputargs[index] = vlist3
1052 hint = op.hint(vlist3, chints)
1053 hint.result = vlist2
1054 newblock.operations.append(hint)
1055 # done!
1056
1057
1058 # ____ all passes & simplify_graph
1059
1060 all_passes = [
1061 transform_dead_op_vars,
1062 eliminate_empty_blocks,
1063 remove_assertion_errors,
1064 remove_identical_vars_SSA,
1065 constfold_exitswitch,
1066 remove_trivial_links,
1067 SSA_to_SSI,
1068 coalesce_bool,
1069 transform_ovfcheck,
1070 simplify_exceptions,
1071 transform_xxxitem,
1072 remove_dead_exceptions,
1073 ]
1074
1075 def simplify_graph(graph, passes=True): # can take a list of passes to apply, True meaning all
1076 """inplace-apply all the existing optimisations to the graph."""
1077 if passes is True:
1078 passes = all_passes
1079 for pass_ in passes:
1080 pass_(graph)
1081 checkgraph(graph)
1082
1083 def cleanup_graph(graph):
1084 checkgraph(graph)
1085 eliminate_empty_blocks(graph)
1086 join_blocks(graph)
1087 remove_identical_vars(graph)
1088 checkgraph(graph)