Debian Codegraph @

pypy/interpreter/astcompiler/assemble.py

raw symbols SCIP
1 """Python control flow graph generation and bytecode assembly."""
2
3 import math
4 import os
5 import sys
6 from rpython.rlib.objectmodel import specialize, we_are_translated
7 from rpython.rlib import rstring
8
9 from pypy.interpreter.astcompiler import ast, consts, misc, symtable
10 from pypy.interpreter.error import OperationError
11 from pypy.interpreter.pycode import PyCode
12 from pypy.interpreter.miscutils import string_sort
13 from pypy.tool import stdlib_opcode as ops
14
15 is_absolute_jump = misc.dict_to_switch(
16 {opcode.index: True
17 for opcode in ops.unrolling_opcode_descs
18 if opcode.index in ops.hasjabs},
19 default=False)
20
21 # Compiler-internal scope markers. Not real opcodes: absent from
22 # lib-python/3/opcode.py and the interpreter dispatch. Values match
23 # CPython's compile.c #defines (negative, so they can never collide with
24 # any real opcode number).
25 _SETUP_FINALLY = -1 # open exception scope, lasti=False
26 _SETUP_CLEANUP = -2 # open exception scope, lasti=True (try/finally/except-as)
27 _SETUP_WITH = -3 # open exception scope, lasti=True, depth_sub=1 (with-blocks)
28 _POP_BLOCK = -4 # close exception scope
29
30 PSEUDO_OPNAMES = ['_SETUP_FINALLY', '_SETUP_CLEANUP', '_SETUP_WITH', '_POP_BLOCK']
31
32 # Pseudo-instructions: present in block.instructions so _build_exceptiontable
33 # and _stacksize can read them, but they contribute zero bytes to the encoded
34 # bytecode and have no interpreter dispatch.
35 is_pseudo_opcode = misc.dict_to_switch(
36 {_SETUP_FINALLY: True,
37 _SETUP_CLEANUP: True,
38 _SETUP_WITH: True,
39 _POP_BLOCK: True},
40 default=False)
41
42
43 class StackDepthComputationError(Exception):
44 pass
45
46 UNKNOWN_POSITION = (-1, -1, -1, -1)
47
48 class Instruction(object):
49 """Represents a single opcode."""
50
51 _stack_depth_after = -99 # used before translation only
52
53 def __init__(self, opcode, arg=0, position_info=UNKNOWN_POSITION):
54 self.opcode = opcode
55 self.arg = arg
56 self.position_info = position_info
57 self.jump = None
58
59 def copy(self):
60 res = Instruction(self.opcode, self.arg, self.position_info)
61 res.jump = self.jump
62 return res
63
64 def size(self):
65 """Return the size of bytes of this instruction when it is
66 encoded.
67 """
68 if is_pseudo_opcode(self.opcode):
69 return 0
70 if self.arg <= 0xff:
71 return 2
72 if self.arg <= 0xffff:
73 return 4
74 if self.arg <= 0xffffff:
75 return 6
76 return 8
77
78 def encode(self, code):
79 if is_pseudo_opcode(self.opcode):
80 return
81 opcode = self.opcode
82
83 arg = self.arg
84 size = self.size()
85 if size == 8:
86 code.append(chr(ops.EXTENDED_ARG))
87 code.append(chr((arg >> 24) & 0xff))
88 assert ((arg >> 24) & 0xff) == (arg >> 24)
89 if size >= 6:
90 code.append(chr(ops.EXTENDED_ARG))
91 code.append(chr((arg >> 16) & 0xff))
92 if size >= 4:
93 code.append(chr(ops.EXTENDED_ARG))
94 code.append(chr((arg >> 8) & 0xff))
95 if size >= 2:
96 code.append(chr(opcode))
97 code.append(chr(arg & 0xff))
98
99
100 def jump_to(self, target):
101 """Indicate the target this jump instruction.
102
103 The opcode must be a JUMP opcode.
104 """
105 self.jump = target
106
107 def update_position_if_not_set(self, position_info):
108 if self.position_info[0] < 0:
109 self.position_info = position_info
110 else:
111 position_info = self.position_info
112 # returns the value of self.position_info, whether it was written to or
113 # not
114 return position_info
115
116 @staticmethod
117 def is_setup_pseudo_code(opcode):
118 return opcode in (_SETUP_FINALLY, _SETUP_CLEANUP, _SETUP_WITH)
119
120 def opname(self):
121 # for debugging
122 if self.opcode >= 0:
123 return ops.opname[self.opcode]
124 else:
125 return PSEUDO_OPNAMES[~self.opcode]
126
127 def __repr__(self):
128 data = ["<", self._opname()]
129 if self.opcode >= ops.HAVE_ARGUMENT:
130 data.append(" ")
131 data.append(str(self.arg))
132 if self.jump is not None:
133 data.append(" ")
134 data.append(str(self.jump))
135 data.append(" lineno=%s>" % (self.position_info[0], ))
136 return "".join(data)
137
138
139 class Block(object):
140 """A basic control flow block.
141
142 It has one entry point and several possible exit points. Its
143 instructions may be jumps to other blocks, or if control flow
144 reaches the end of the block, it continues to next_block.
145 """
146
147 _source = None
148
149 def __init__(self):
150 self.instructions = []
151 self.next_block = None
152 self.marked = 0
153 # is True if instructions[-1] is one that unconditionally leaves the
154 # execution of the instructions in the block (return, raise,
155 # unconditional jumps)
156 self.cant_add_instructions = False
157 self.exits_function = False
158 self.auto_inserted_return = False
159 # set by codegen for exception-handler blocks so _stacksize finds them
160 # even when no SETUP_FINALLY/EXCEPT jump instruction targets them
161 self.forced_initial_depth = -1
162 # set by _build_exceptiontable Phase 1 when this block is a handler target
163 self.exc_lasti = False
164 self.exc_depth_adj = 0
165 self.exc_depth_sub = 0
166
167 def __repr__(self):
168 return "<Block %s>" % (self.instructions, )
169
170 def emit_instr(self, instr):
171 self.instructions.append(instr)
172 op = instr.opcode
173 if (
174 op == ops.RETURN_VALUE or
175 op == ops.RAISE_VARARGS or
176 op == ops.RERAISE
177 ):
178 self.exits_function = True
179 self.cant_add_instructions = True
180 elif (
181 op == ops.JUMP_FORWARD or
182 op == ops.JUMP_ABSOLUTE
183 ):
184 self.cant_add_instructions = True
185
186 def _post_order_see(self, stack):
187 if self.marked == 0:
188 self.marked = 1
189 stack.append(self)
190
191 def copy(self):
192 copy = Block()
193 copy.auto_inserted_return = self.auto_inserted_return
194 for instr in self.instructions:
195 copy.emit_instr(instr.copy())
196 return copy
197
198
199 def post_order(self):
200 """Return this block and its children in post order. This means
201 that the graph of blocks is first cleaned up to ignore
202 back-edges, thus turning it into a DAG. Then the DAG is
203 linearized. For example:
204
205 A --> B -\ => [A, D, B, C]
206 \-> D ---> C
207 """
208 resultblocks = []
209 stack = [self]
210 self.marked = 1
211 while stack:
212 current = stack[-1]
213 if current.marked == 1:
214 current.marked = 2
215 if current.next_block is not None:
216 current.next_block._post_order_see(stack)
217 else:
218 i = current.marked - 2
219 assert i >= 0
220 while i < len(current.instructions):
221 instr = current.instructions[i]
222 i += 1
223 if instr.jump is not None:
224 current.marked = i + 2
225 instr.jump._post_order_see(stack)
226 break
227 else:
228 resultblocks.append(current)
229 stack.pop()
230 resultblocks.reverse()
231 for block in resultblocks:
232 block.marked = 0
233 return resultblocks
234
235 def code_size(self):
236 """Return the encoded size of all the instructions in this
237 block.
238 """
239 i = 0
240 for instr in self.instructions:
241 i += instr.size()
242 return i
243
244 def get_code(self, code):
245 """Encode the instructions in this block into bytecode."""
246 startsize = code.getlength()
247 for instr in self.instructions:
248 instr.encode(code)
249 assert code.getlength() == startsize + self.code_size()
250 assert code.getlength() & 1 == 0
251
252 def jump_thread(self):
253 # do jump threading
254 # 1) skip empty .next_block
255 if not self.cant_add_instructions:
256 while self.next_block is not None and not self.next_block.instructions:
257 self.next_block = self.next_block.next_block
258
259 # 2) jump-thread instructions
260 i = 0
261 while i < len(self.instructions):
262 instr = self.instructions[i]
263 instr_lineno = instr.position_info[0]
264 i += 1
265 target = instr.jump
266 if not target:
267 continue
268 # replace a jump to an empty block with a jump to its successor
269 while not target.instructions:
270 target = instr.jump = target.next_block
271 assert target is not None
272 opcode = instr.opcode
273 target_instr = target.instructions[0]
274 target_lineno = target_instr.position_info[0]
275 target_opcode = target_instr.opcode
276 if ((target_opcode == ops.JUMP_ABSOLUTE or target_opcode == ops.JUMP_FORWARD) and
277 target_instr.jump.instructions and
278 target_instr.jump.instructions[0].position_info[0] == target_lineno):
279 # we have an unconditional jump where the jump instruction and
280 # the target of the jump have the same lineno, so it's safe to
281 # skip the jump
282 pass
283 elif target_lineno != -1 and target_lineno != instr_lineno:
284 continue # don't jump thread to not lose lines
285 if target_instr is instr:
286 continue # it's the same instruction (ie an infinite loop)
287 # Optimize an unconditional jump going to another
288 # unconditional jump.
289 if opcode == ops.JUMP_ABSOLUTE or opcode == ops.JUMP_FORWARD:
290 if target_opcode == ops.JUMP_ABSOLUTE:
291 instr.opcode = ops.JUMP_ABSOLUTE
292 instr.jump = target_instr.jump
293 i -= 1 # look at this instruction again
294 elif target_opcode == ops.JUMP_FORWARD:
295 instr.jump = target_instr.jump
296 i -= 1 # look at this instruction again
297 elif target_opcode == ops.RETURN_VALUE:
298 # Replace JUMP_* to a RETURN into
299 # just a RETURN
300 instr.opcode = ops.RETURN_VALUE
301 instr.jump = None
302 continue
303 if opcode == ops.JUMP_IF_FALSE_OR_POP:
304 if (target_opcode == ops.JUMP_ABSOLUTE or
305 target_opcode == ops.JUMP_FORWARD or
306 target_opcode == ops.JUMP_IF_FALSE_OR_POP):
307 instr.jump = target_instr.jump
308 i -= 1 # look at this instruction again
309 if opcode == ops.JUMP_IF_TRUE_OR_POP:
310 if (target_opcode == ops.JUMP_ABSOLUTE or
311 target_opcode == ops.JUMP_FORWARD or
312 target_opcode == ops.JUMP_IF_TRUE_OR_POP):
313 instr.jump = target_instr.jump
314 i -= 1 # look at this instruction again
315 if (opcode == ops.POP_JUMP_IF_FALSE or
316 opcode == ops.POP_JUMP_IF_TRUE or
317 opcode == ops.POP_JUMP_FORWARD_IF_NONE or
318 opcode == ops.POP_JUMP_FORWARD_IF_NOT_NONE
319 ):
320 if (target_opcode == ops.JUMP_ABSOLUTE or
321 target_opcode == ops.JUMP_FORWARD):
322 instr.jump = target_instr.jump
323 i -= 1 # look at this instruction again
324
325
326 def _make_index_dict_filter(syms, flag1, flag2):
327 names = syms.keys()
328 string_sort(names) # return cell vars in alphabetical order
329 i = 0
330 result = {}
331 for name in names:
332 scope = syms[name]
333 if scope in (flag1, flag2):
334 result[name] = i
335 i += 1
336 return result
337
338
339 @specialize.argtype(0)
340 def _iter_to_dict(iterable, offset=0):
341 result = {}
342 index = offset
343 for item in iterable:
344 result[item] = index
345 index += 1
346 return result
347
348
349 class PythonCodeMaker(ast.ASTVisitor):
350 """Knows how to assemble a PyCode object."""
351 _debug_flag = False
352 qualname = None
353
354 def __init__(self, space, name, first_lineno, scope, compile_info):
355 self.space = space
356 self.name = name
357 self.first_lineno = first_lineno
358 self.compile_info = compile_info
359 self.first_block = self.new_block()
360 self.current_block = self.first_block
361 self._is_dead_code = False
362 self.names = {}
363 self.var_names = _iter_to_dict(scope.varnames)
364 self.cell_vars = _make_index_dict_filter(scope.symbols,
365 symtable.SCOPE_CELL,
366 symtable.SCOPE_CELL_CLASS)
367 string_sort(scope.free_vars) # return free vars in alphabetical order
368 self.free_vars = _iter_to_dict(scope.free_vars, len(self.cell_vars))
369 self.w_consts = space.newdict()
370 self.consts_w = []
371 self.argcount = 0
372 self.posonlyargcount = 0
373 self.kwonlyargcount = 0
374 self.no_position_info()
375 self.add_none_to_final_return = True
376 self.match_context = None
377 self._stack_depth = 0 # running stack depth counter at current emit point
378
379 def __repr__(self):
380 return "<PythonCodeMaker %s in %s:%s>" % (self.name, self.compile_info.filename, self.first_lineno)
381
382 def _check_consistency(self, blocks):
383 current_off = 0
384 for block in blocks:
385 assert block.offset == current_off
386 for instr in block.instructions:
387 current_off += instr.size()
388
389 def view(self, blocks=None):
390 from pypy.interpreter.astcompiler.codegen import view
391 return view(blocks or self.first_block)
392
393 def new_block(self):
394 return Block()
395
396 def use_block(self, block):
397 """Start emitting bytecode into block."""
398 self.current_block = block
399 if block.forced_initial_depth >= 0:
400 self._stack_depth = block.forced_initial_depth
401
402 def use_next_block(self, block=None):
403 """Set this block as the next_block for the last and use it."""
404 if block is None:
405 block = self.new_block()
406 self.current_block.next_block = block
407 self.use_block(block)
408 return block
409
410 def is_dead_code(self):
411 """Return False if any code can be meaningfully added to the
412 current block, or True if it would be dead code."""
413 return self._is_dead_code or self.current_block.cant_add_instructions
414
415 def all_dead_code(self):
416 return DeadCode(self)
417
418 def emit_op(self, op):
419 """Emit an opcode without an argument."""
420 instr = Instruction(op, position_info=self.position_info)
421 if not self.is_dead_code():
422 self.current_block.emit_instr(instr)
423 self._stack_depth += _opcode_stack_effect(op, 0)
424 return instr
425
426 def emit_op_arg(self, op, arg):
427 """Emit an opcode with an integer argument."""
428 instr = Instruction(op, arg, position_info=self.position_info)
429 if not self.is_dead_code():
430 self.current_block.emit_instr(instr)
431 self._stack_depth += _opcode_stack_effect(op, arg)
432
433 def emit_swaps(self, arg):
434 # Emit n-1 SWAPs to rotate TOS to depth n (CPython 3.11 style),
435 # so that apply_static_swaps can eliminate them statically.
436 for i in range(arg, 1, -1):
437 self.emit_op_arg(ops.SWAP, i)
438
439 def emit_op_name(self, op, container, name):
440 """Emit an opcode referencing a name."""
441 self.emit_op_arg(op, self.add_name(container, name))
442
443 def emit_jump(self, op, block_to):
444 """Emit a jump opcode to another block."""
445 was_dead = self.is_dead_code()
446 depth_before = self._stack_depth
447 self.emit_op(op).jump_to(block_to)
448 if not was_dead and Instruction.is_setup_pseudo_code(op):
449 jump_effect = _opcode_stack_effect_jump(op)
450 jump_depth = depth_before + jump_effect
451 if jump_depth > block_to.forced_initial_depth:
452 block_to.forced_initial_depth = jump_depth
453
454 def emit_jump_noline(self, op, block_to):
455 """Emit a jump with no position info, matching CPython's ADDOP_JUMP_NOLINE."""
456 self.no_position_info()
457 self.emit_jump(op, block_to)
458
459 def emit_compare(self, ast_op_kind):
460 from pypy.interpreter.astcompiler.codegen import compare_operations
461 opcode, op_kind = compare_operations(ast_op_kind)
462 self.emit_op_arg(opcode, op_kind)
463
464 def emit_line_tracing_nop(self, node=None):
465 old_position_info = UNKNOWN_POSITION
466 if node:
467 old_position_info = self.position_info
468 self.update_position(node)
469 self.emit_op(ops.NOP)
470 if node:
471 self.position_info = old_position_info
472
473 def add_name(self, container, name):
474 """Get the index of a name in container."""
475 name = self.scope.mangle(name)
476 try:
477 index = container[name]
478 except KeyError:
479 index = len(container)
480 container[name] = index
481 return index
482
483 def add_const(self, w_obj):
484 """Add a W_Root to the constant array and return its location."""
485 space = self.space
486 if isinstance(w_obj, PyCode):
487 # unlike CPython, never share code objects, it's pointless
488 w_key = space.id(w_obj)
489 else:
490 w_key = PyCode.const_comparison_key(self.space, w_obj)
491
492 w_len = space.finditem(self.w_consts, w_key)
493 if w_len is not None:
494 length = space.int_w(w_len)
495 else:
496 length = len(self.consts_w)
497 w_obj = misc.intern_if_common_string(space, w_obj)
498 self.consts_w.append(w_obj)
499 space.setitem(self.w_consts, w_key, space.newint(length))
500 if length == 0:
501 self.scope.doc_removable = False
502 return length
503
504
505 def load_const(self, obj):
506 if self.is_dead_code():
507 return
508 index = self.add_const(obj)
509 self.emit_op_arg(ops.LOAD_CONST, index)
510
511 @specialize.argtype(1)
512 def update_position(self, node):
513 """Change the position for the next instructions to that of node."""
514 if self.is_dead_code():
515 return self.position_info
516 if isinstance(node, tuple):
517 position_info = node
518 else:
519 position_info = (node.lineno, node.end_lineno, node.col_offset, node.end_col_offset)
520 old_position_info = self.position_info
521 self.position_info = position_info
522 return old_position_info
523
524 def no_position_info(self):
525 if self.is_dead_code():
526 return
527 self.position_info = (-1, ) * 4
528
529 def new_match_context(self):
530 return MatchContext(self)
531
532 def sub_pattern_context(self):
533 return SubMatchContext(self)
534
535 def _resolve_block_targets(self, blocks):
536 """Compute the arguments of jump instructions."""
537 # The reason for this loop is extended jumps. EXTENDED_ARG
538 # extends the bytecode size, so it might invalidate the offsets we've
539 # already given. Thus we have to loop until the size of all jump
540 # instructions is stable. Any extended jump at all is extremely rare,
541 # so performance should not be too concerning.
542 while True:
543 offset = 0
544 force_redo = False
545 # Calculate the code offset of each block.
546 for block in blocks:
547 block.offset = offset
548 offset += block.code_size()
549 totalsize = offset
550 for block in blocks:
551 offset = block.offset
552 for instr in block.instructions:
553 size = instr.size()
554 offset += size
555 if instr.jump is not None:
556 target = instr.jump
557 if is_absolute_jump(instr.opcode):
558 jump_arg = target.offset
559 else:
560 jump_arg = target.offset - offset
561 assert jump_arg >= 0
562 jump_arg //= 2
563 instr.arg = jump_arg
564 if instr.size() != size:
565 force_redo = True
566 if not force_redo:
567 self._check_consistency(blocks)
568 return totalsize
569
570 def _get_code_flags(self):
571 """Get an extra flags that should be attached to the code object."""
572 raise NotImplementedError
573
574 def _stacksize_error_pos(self, depth, blocks, block, instr):
575 # This case occurs if this code object uses some
576 # construction for which the stack depth computation
577 # is wrong (too high). If you get here while working
578 # on the astcompiler, then you should at first ignore
579 # the error, and comment out the 'raise' below. Such
580 # an error is not really bad: it is just a bit
581 # wasteful. For release-ready versions, though, we'd
582 # like not to be wasteful. :-)
583 if not we_are_translated():
584 self._stack_depth_debug_print(blocks, block, instr)
585 os.write(2, "StackDepthComputationError(POS) in %s at %s:%s depth %s\n"
586 % (self.compile_info.filename, self.name, self.first_lineno, depth))
587 raise StackDepthComputationError # would-be-nice-not-to-have
588
589 def _stack_depth_debug_print(self, blocks, errorblock, errorinstr):
590 print "\n" * 5
591 print self.name
592 for block in blocks:
593 print "======="
594 print block
595 if block is errorblock:
596 print "ERROR IS IN THIS BLOCK"
597 print "stack depth at start", block.initial_depth
598 if block._source is not None:
599 print "stack depth at start set via", block._source
600 for instr in block.instructions:
601 print "--->" if instr is errorinstr else " ", instr,
602 if instr._stack_depth_after != -99:
603 print "stacksize afterwards: %s" % instr._stack_depth_after
604 else:
605 print
606
607
608 def _stacksize(self, blocks):
609 """Compute co_stacksize."""
610 for block in blocks:
611 block.initial_depth = -99
612 blocks[0].initial_depth = 0
613 # Apply forced depths set by codegen for exception-handler blocks
614 # that are unreachable via the instruction graph (no SETUP_* jump targets them).
615 for block in blocks:
616 if block.forced_initial_depth >= 0 and block.forced_initial_depth > block.initial_depth:
617 block.initial_depth = block.forced_initial_depth
618 # Assumes that it is sufficient to walk the blocks in 'post-order'.
619 # This means we ignore all back-edges, but apart from that, we only
620 # look into a block when all the previous blocks have been done.
621 self._max_depth = 0
622 for block in blocks:
623 depth = self._do_stack_depth_walk(block, blocks)
624 if block.auto_inserted_return and depth != 0:
625 self._stacksize_error_pos(depth, blocks, block, None)
626 return self._max_depth
627
628 def _next_stack_depth_walk(self, nextblock, depth, source):
629 if depth > nextblock.initial_depth:
630 nextblock.initial_depth = depth
631 if not we_are_translated():
632 nextblock._source = source
633
634 def _do_stack_depth_walk(self, block, blocks):
635 depth = block.initial_depth
636 if depth == -99: # this block is never reached, skip
637 return 0
638
639 for instr in block.instructions:
640 orig_depth = depth
641 depth += _opcode_stack_effect(instr.opcode, instr.arg)
642 if not we_are_translated():
643 instr._stack_depth_after = depth
644 if depth < 0:
645 # This is really a fatal error, don't comment out this
646 # 'raise'. It means that the stack depth computation
647 # thinks there is a path that yields a negative stack
648 # depth, which means that it underestimates the space
649 # needed and it would crash when interpreting this
650 # code.
651 if not we_are_translated():
652 instr._stack_depth_after = depth
653 self._stack_depth_debug_print(blocks, block, instr)
654 os.write(2, "StackDepthComputationError(NEG) in %s at %s:%s\n"
655 % (self.compile_info.filename, self.name, self.first_lineno))
656 raise StackDepthComputationError # really fatal error
657 if depth >= self._max_depth:
658 self._max_depth = depth
659 jump_op = instr.opcode
660 if instr.jump is not None:
661 target_depth = orig_depth + _opcode_stack_effect_jump(jump_op)
662 if target_depth > self._max_depth:
663 self._max_depth = target_depth
664 self._next_stack_depth_walk(instr.jump, target_depth, (block, instr))
665 if jump_op == ops.JUMP_ABSOLUTE or jump_op == ops.JUMP_FORWARD:
666 # Nothing more can occur.
667 break
668 elif jump_op == ops.RETURN_VALUE:
669 if depth:
670 self._stacksize_error_pos(depth, blocks, block, instr)
671 break
672 elif jump_op == ops.RAISE_VARARGS:
673 break
674 elif jump_op == ops.RERAISE:
675 break
676 else:
677 if block.next_block:
678 self._next_stack_depth_walk(block.next_block, depth, (block, None))
679 return depth
680
681 def _build_positions(self, blocks):
682 """Build the column offset table (with end column offsets)."""
683 from pypy.interpreter.location import encode_single_position
684 table = rstring.StringBuilder()
685 for block in blocks:
686 for instr in block.instructions:
687 if is_pseudo_opcode(instr.opcode):
688 continue
689 encode_single_position(table, instr.position_info, self.first_lineno)
690 for extra in range((instr.size() - 2) // 2):
691 encode_single_position(table, UNKNOWN_POSITION, self.first_lineno)
692 return table.build()
693
694 def _build_code(self, blocks, size):
695 bytecode = rstring.StringBuilder(size)
696 for block in blocks:
697 block.get_code(bytecode)
698 return bytecode.build()
699
700 def jump_thread(self, blocks):
701 for block in blocks:
702 block.jump_thread()
703
704 def compute_predecessors_in_marked(self, blocks):
705 # compute predecessors, use the 'marked' attribute for it
706 def increase_incoming(block, todo):
707 block.marked += 1
708 if block.marked == 1:
709 todo.append(block)
710 for block in blocks:
711 block.marked = 0
712 self.first_block.marked = 1
713 todo = [self.first_block]
714 while todo:
715 block = todo.pop()
716 # mark next_block, but only if the edge can actually be taken
717 if block.next_block and not block.cant_add_instructions:
718 increase_incoming(block.next_block, todo)
719 for instr in block.instructions:
720 if instr.jump:
721 increase_incoming(instr.jump, todo)
722
723 def propagate_line_numbers(self, blocks):
724 # here block.marked stores the number of predecessor blocks.
725 # use that info to propagate position information
726 for block in blocks:
727 if not block.instructions or block.marked == 0:
728 continue
729 prev_position = UNKNOWN_POSITION
730 for instr in block.instructions:
731 prev_position = instr.update_position_if_not_set(prev_position)
732 if instr.jump is not None and instr.jump.marked == 1 and instr.jump.instructions:
733 if instr.is_setup_pseudo_code(instr.opcode):
734 continue # don't propagate line info into exception handler blocks
735 instr.jump.instructions[0].update_position_if_not_set(prev_position)
736 next_block = block.next_block
737 if (next_block and not block.cant_add_instructions and
738 next_block.marked == 1 and next_block.instructions):
739 next_first_op = next_block.instructions[0]
740 if next_first_op.is_setup_pseudo_code(next_first_op.opcode):
741 next_block.instructions[0].update_position_if_not_set(prev_position)
742
743 def guarantee_lineno_for_exits(self, blocks):
744 # CPython equivalent: guarantee_lineno_for_exits (compile.c).
745 # After propagate_line_numbers, any block ending in RETURN_VALUE whose
746 # last instruction is still UNSET gets the running lineno assigned to
747 # all its UNSET instructions.
748 lineno = self.first_lineno
749 for block in blocks:
750 if not block.instructions:
751 continue
752 last = block.instructions[-1]
753 if last.position_info[0] < 0:
754 if last.opcode == ops.RETURN_VALUE:
755 for instr in block.instructions:
756 if instr.position_info[0] < 0:
757 instr.position_info = (lineno,
758 instr.position_info[1],
759 instr.position_info[2],
760 instr.position_info[3])
761 else:
762 lineno = last.position_info[0]
763
764 def optimize_unreachable_code(self, blocks):
765 # block.marked still stores the predecessor information. use it to
766 # remove all instructions from unreachable blocks, and optimize
767 # JUMP_FORWARD instructions that go to the next block in the sequence
768 # anyway. reset block.marked afterwards
769 last_reachable = None
770 for i, block in enumerate(blocks):
771 # for blocks with 0 predecessors, don't emit any code for them by
772 # setting the instructions to the empty list
773 if block.marked == 0:
774 block.instructions = []
775 block.cant_add_instructions = False
776 block.forced_initial_depth = -1
777 continue
778 last_reachable = block
779 if block.instructions and i < len(blocks) - 1:
780 lastop = block.instructions[-1]
781 if lastop.opcode == ops.JUMP_FORWARD:
782 # find the block we would fall through
783 target = None
784 for j in range(i + 1, len(blocks)):
785 target = blocks[j]
786 if target.marked:
787 break
788 assert target is not None
789 if target is lastop.jump:
790 lastop.opcode = ops.NOP
791 lastop.jump = None
792 block.next_block = blocks[i + 1]
793 block.cant_add_instructions = False
794 block.marked = 0
795 # the last reachable block must have cant_add_instructions
796 assert last_reachable is not None and last_reachable.cant_add_instructions
797
798 def apply_static_swaps(self, blocks):
799 """Eliminate statically-known SWAP sequences (port of CPython's pass)."""
800 for block in blocks:
801 instructions = block.instructions
802 for i in range(len(instructions)):
803 if instructions[i].opcode == ops.SWAP:
804 _apply_static_swaps(instructions, i)
805
806 def _finalize_blocks(self):
807 # Unless it's interactive, every code object must end in a return.
808 if self._debug_flag:
809 import pdb; pdb.set_trace()
810 if not self.current_block.cant_add_instructions:
811 # the implicit return has no position info, unless the function
812 # contains no bytecodes at all. in that case the RETURN_VALUE gets
813 # the firstlineno as the position
814 if (self.current_block is self.first_block and
815 len(self.current_block.instructions) == 0):
816 self.position_info = (self.first_lineno, -1, -1, -1)
817 else:
818 self.no_position_info() # will be duplicated by duplicate_exits_without_lineno
819 if self.add_none_to_final_return:
820 self.load_const(self.space.w_None)
821 self.emit_op(ops.RETURN_VALUE)
822 self.current_block.auto_inserted_return = True
823 blocks = self.first_block.post_order()
824
825 remove_redundant_nops(blocks)
826 self.jump_thread(blocks)
827 self.extend_blocks(blocks)
828 self.apply_static_swaps(blocks)
829 self.compute_predecessors_in_marked(blocks)
830 self.duplicate_exits_without_lineno(blocks)
831 self.propagate_line_numbers(blocks)
832 self.guarantee_lineno_for_exits(blocks)
833 self.optimize_unreachable_code(blocks)
834 mininum_lineno = remove_redundant_nops(blocks)
835 # Set the first lineno if it is not already explicitly set.
836 if self.first_lineno == -1:
837 self.first_lineno = mininum_lineno
838 size = self._resolve_block_targets(blocks)
839 return blocks, size
840
841 def _build_exceptiontable(self, blocks):
842 """Build co_exceptiontable using a CPython-style per-block graph traversal.
843
844 Phase 1: DFS from the entry block (blocks[0]), propagating the handler stack
845 along CFG edges. Each block records the handler stack at its entry point.
846 This correctly handles duplicate_exits_without_lineno: inlined unconditional
847 jumps update the stack only for their own execution path; the fallback branch
848 (reached via a conditional jump from the predecessor) inherits its own copy.
849
850 Phase 2: Scan blocks in bytecode order. At each block boundary, reconcile
851 cur_handler with the block's recorded entry stack. Within a block, SETUP_*/
852 POP_BLOCK pseudo-ops push and pop the stack to emit contiguous table entries.
853
854 handler stack entry: (handler_block, lasti, depth_adjust, depth_sub)
855 lasti = True when the table entry carries the lasti flag (_SETUP_CLEANUP/
856 _SETUP_WITH).
857 depth_adjust = _opcode_stack_effect_jump(op) for the opening SETUP_*.
858 depth_sub = 1 for _SETUP_WITH (__enter__ result consumed before body), 0 otherwise.
859 """
860 # --- Phase 1: graph traversal, compute per-block entry handler stacks ---
861 # Like CPython's label_exception_targets: DFS over the CFG, tracking a
862 # stack of active handler blocks. stk is list of Block (not tuples);
863 # per-handler metadata (lasti, depth_adj, depth_sub) is stored as
864 # attributes on the handler Block itself (CPython: b_lasti, b_exceptdepth).
865 block_entry_stack = {} # Block -> list of Block
866
867 first_block = blocks[0]
868 block_entry_stack[first_block] = []
869 worklist = [first_block]
870
871 while worklist:
872 b = worklist.pop()
873 stk = block_entry_stack[b][:] # mutable working copy (list of Block)
874
875 for instr in b.instructions:
876 op = instr.opcode
877 if instr.is_setup_pseudo_code(op):
878 handler_target = instr.jump
879 # Handler block gets entry stack BEFORE the push.
880 if handler_target not in block_entry_stack:
881 block_entry_stack[handler_target] = stk[:]
882 worklist.append(handler_target)
883 # Record handler metadata on the block (like CPython b_lasti).
884 handler_target.exc_lasti = (op != _SETUP_FINALLY)
885 handler_target.exc_depth_adj = _opcode_stack_effect_jump(op)
886 handler_target.exc_depth_sub = 1 if op == _SETUP_WITH else 0
887 stk.append(handler_target)
888 elif op == _POP_BLOCK:
889 if stk:
890 # Only empty in unreachable blocks or malformed code
891 stk.pop()
892 elif instr.jump is not None:
893 target = instr.jump
894 if target not in block_entry_stack:
895 block_entry_stack[target] = stk[:]
896 worklist.append(target)
897
898 # Propagate to fallthrough successor.
899 # Match CPython's label_exception_targets, which always follows
900 # b_next unconditionally.
901 if b.next_block is not None and b.next_block not in block_entry_stack:
902 block_entry_stack[b.next_block] = stk
903 worklist.append(b.next_block)
904
905 # --- Phase 2: emit exception table entries ---
906 # cur_handler is Block or None (like CPython's basicblock *handler).
907 # all_entries collects (start, end, handler_block) 3-tuples.
908 all_entries = []
909 cur_handler = None # type: Block or None
910 cur_start = -1
911 instr_offset = 0
912
913 def close_dead_block(cur_handler, cur_start, offset, all_entries):
914 # Close any open range
915 if cur_handler is not None and cur_start < offset:
916 all_entries.append((cur_start, offset, cur_handler))
917
918
919 for block in blocks:
920 entry = block_entry_stack.get(block)
921 if entry is None:
922 close_dead_block(cur_handler, cur_start, block.offset, all_entries)
923 cur_handler = None
924 cur_start = -1
925 continue
926
927 # Reconcile cur_handler with this block's entry stack top.
928 new_handler = entry[-1] if entry else None
929 if new_handler is not cur_handler:
930 close_dead_block(cur_handler, cur_start, block.offset, all_entries)
931 cur_handler = new_handler
932 cur_start = block.offset
933
934 stk = entry[:]
935 instr_offset = block.offset
936
937 for instr in block.instructions:
938 op = instr.opcode
939 instr_size = instr.size()
940
941 if instr.is_setup_pseudo_code(op):
942 # All are 0-byte pseudos; close enclosing handler at instr_offset.
943 close_dead_block(cur_handler, cur_start, instr_offset, all_entries)
944 handler_target = instr.jump
945 stk.append(handler_target)
946 cur_handler = handler_target
947 cur_start = instr_offset + instr_size
948
949 elif op == _POP_BLOCK:
950 close_dead_block(cur_handler, cur_start, instr_offset, all_entries)
951 if stk:
952 stk.pop()
953 cur_handler = stk[-1] if stk else None
954 cur_start = instr_offset # _POP_BLOCK encodes as 0 bytes
955
956 instr_offset += instr_size
957
958 if not all_entries:
959 return ''
960 result = []
961 for entry in all_entries:
962 start, end, handler_block = entry[0], entry[1], entry[2]
963 if end <= start:
964 continue
965 lasti = handler_block.exc_lasti
966 depth_adjust = handler_block.exc_depth_adj
967 depth_sub = handler_block.exc_depth_sub
968 # depth = value stack depth just before handle_operation_error pushes
969 # lasti (if lasti=True) and the exception object.
970 # handler_block.initial_depth was seeded by emit_jump:
971 # initial_depth = depth_at_SETUP + depth_adjust
972 # => depth = initial_depth - depth_adjust - depth_sub
973 depth = handler_block.initial_depth - depth_adjust - depth_sub
974 if depth < 0:
975 continue
976 _encode_varint(result, start // 2, msb=0x80)
977 _encode_varint(result, (end - start) // 2)
978 _encode_varint(result, handler_block.offset // 2)
979 dl = (depth << 1) | (1 if lasti else 0)
980 _encode_varint(result, dl)
981 return ''.join(result)
982
983 def assemble(self):
984 """Build a PyCode object."""
985 blocks, size = self._finalize_blocks()
986 stack_depth = self._stacksize(blocks)
987 positions = self._build_positions(blocks)
988 consts_w = self.consts_w[:]
989 names = _list_from_dict(self.names)
990 var_names = _list_from_dict(self.var_names)
991 cell_names = _list_from_dict(self.cell_vars)
992 free_names = _list_from_dict(self.free_vars, len(cell_names))
993 flags = self._get_code_flags()
994 bytecode = self._build_code(blocks, size)
995 # (Only) inherit compilerflags in PyCF_MASK
996 flags |= (self.compile_info.flags & consts.PyCF_MASK)
997 if not we_are_translated():
998 self._final_blocks = blocks
999 exceptiontable = self._build_exceptiontable(blocks)
1000 return PyCode(self.space,
1001 self.argcount,
1002 self.posonlyargcount,
1003 self.kwonlyargcount,
1004 len(self.var_names),
1005 stack_depth,
1006 flags,
1007 bytecode,
1008 list(consts_w),
1009 names,
1010 var_names,
1011 self.compile_info.filename,
1012 self.name,
1013 self.qualname,
1014 self.first_lineno,
1015 positions,
1016 free_names,
1017 cell_names,
1018 self.compile_info.hidden_applevel,
1019 exceptiontable=exceptiontable)
1020
1021 def extend_blocks(self, blocks):
1022 # Inline small unconditional lineno-less RETURN_VALUE blocks into their
1023 # jump predecessors. Equivalent to CPython's extend_block() (compile.c).
1024 # Processing in reverse (leaves first) collapses chains in one pass.
1025 MAX_COPY_SIZE = 4
1026 for idx in range(len(blocks) - 1, -1, -1):
1027 block = blocks[idx]
1028 if not block.instructions or not block.cant_add_instructions:
1029 continue
1030 last = block.instructions[-1]
1031 if last.opcode not in (ops.JUMP_FORWARD, ops.JUMP_ABSOLUTE):
1032 continue
1033 target = last.jump
1034 if target is None or not target.instructions:
1035 continue
1036 if len(target.instructions) > MAX_COPY_SIZE:
1037 continue
1038 for instr in target.instructions:
1039 if instr.opcode == ops.RETURN_VALUE:
1040 break
1041 else:
1042 continue
1043 has_lineno = False
1044 for instr in target.instructions:
1045 if instr.position_info[0] != -1:
1046 has_lineno = True
1047 break
1048 if has_lineno:
1049 continue
1050 # Inline: replace the JUMP with NOP (keeping its lineno, like CPython's
1051 # last->i_opcode = NOP), then append copies of target's instructions.
1052 last.opcode = ops.NOP
1053 last.jump = None
1054 block.cant_add_instructions = False
1055 for instr in target.instructions:
1056 block.emit_instr(instr.copy())
1057
1058 def duplicate_exits_without_lineno(self, blocks):
1059 from pypy.interpreter.astcompiler.codegen import view
1060 def should_mark_block(block):
1061 # CPython: only mark exit blocks (b_exit=1), i.e. blocks containing
1062 # RETURN_VALUE or RERAISE, with all instructions having no lineno.
1063 has_exit = False
1064 for instr in block.instructions:
1065 if instr.opcode in (ops.RETURN_VALUE, ops.RERAISE):
1066 has_exit = True
1067 if instr.position_info[0] != -1:
1068 return False
1069 if instr.jump and (instr.jump.marked & 1) == 0:
1070 return False
1071 if not has_exit:
1072 return False
1073 if block.next_block and not block.cant_add_instructions:
1074 return (block.next_block.marked & 1) == 1
1075 return True
1076 # this is a bit of a mess. we want *two* pieces of info in marked, the
1077 # number of predecessors and the "do I need to duplicate". left-shift
1078 # marked to have a bit free for the latter
1079 for block in blocks:
1080 block.marked <<= 1
1081
1082 # mark blocks that are paths to an exit without meeting an instruction
1083 # with a line number. uses the fact that blocks is a post-order
1084 any_mark = False
1085 for i in range(len(blocks) - 1, -1, -1):
1086 block = blocks[i]
1087 # mark block if all instructions in block have -1 as the lineno
1088 # *and* all target blocks are also marked
1089 mark = should_mark_block(block)
1090 block.marked |= mark
1091 any_mark |= mark
1092
1093 i = 0
1094 if not any_mark:
1095 i = len(blocks)
1096
1097 # Build a successor dict to support O(1) insertion of copied blocks.
1098 # After the while loop we linearise the chain back into blocks[].
1099 # In CPython this is done by via a double linked list
1100 successor = {}
1101 for idx in range(len(blocks) - 1):
1102 successor[blocks[idx]] = blocks[idx + 1]
1103 if blocks:
1104 successor[blocks[-1]] = None
1105 any_copy = False
1106
1107 while i < len(blocks):
1108 block = blocks[i]
1109 i += 1
1110 if (block.marked >> 1) == 0:
1111 # dead block
1112 continue
1113 j = 0
1114 while j < len(block.instructions):
1115 instr = block.instructions[j]
1116 j += 1
1117 target = instr.jump
1118 if target is None:
1119 continue
1120 if instr.is_setup_pseudo_code(instr.opcode):
1121 continue # don't do this for exception handlers
1122 # only do something if the target has no position info (lowest
1123 # bit set)
1124 if not target.marked & 1:
1125 continue
1126
1127 # path leading to automatically inserted return or reraise,
1128 # without line number
1129
1130 # if it's an unconditional jump, inline it (single predecessor)
1131 # or copy it (multiple predecessors, matching CPython behaviour).
1132 if instr.opcode in (ops.JUMP_FORWARD, ops.JUMP_ABSOLUTE) and (target.marked >> 1) <= 1:
1133 # Skip if target is a RERAISE-only block: duplicating it
1134 # INTO this block would place the RERAISE inside the byte
1135 # range of an enclosing try-body's exception-table entry
1136 # (body blocks emitted by _visit_try_except/_visit_try_finally
1137 # have a table entry body.offset...exc.offset, and the
1138 # duplicated RERAISE would incorrectly fall inside that
1139 # range, dispatching to the inner handler instead of the
1140 # outer reraise cleanup). Mirrors the RERAISE-only skip
1141 # in the other branch below.
1142 if (len(target.instructions) == 1 and
1143 target.instructions[0].opcode == ops.RERAISE):
1144 continue
1145 assert block.cant_add_instructions
1146 block.instructions.pop()
1147 block.cant_add_instructions = False
1148 j -= 1
1149 target.marked -= 2 # one fewer incoming links
1150 for target_instr in target.instructions:
1151 target_instr = target_instr.copy()
1152 if target_instr.position_info[0] == -1:
1153 target_instr.position_info = instr.position_info
1154 copy = target_instr.copy()
1155 if copy.jump:
1156 copy.jump.marked += 2
1157 block.emit_instr(copy)
1158 if target.next_block and not block.cant_add_instructions:
1159 new_instr = Instruction(ops.JUMP_ABSOLUTE, position_info=instr.position_info)
1160 new_instr.jump = target.next_block
1161 target.next_block.marked += 2
1162 block.emit_instr(new_instr)
1163
1164 elif (target.marked >> 1) > 1:
1165 # Don't copy blocks whose only instructions are RERAISE.
1166 # Such blocks live inside exception-handler bodies emitted by
1167 # _visit_try_finally (after no_position_info()). Copying them
1168 # appends the copy after all handler blocks, placing the RERAISE
1169 # outside the enclosing try/except exception-table range.
1170 # handle_operation_error then falls back to the block stack and
1171 # creates a SApplicationException that breaks PUSH_EXC_INFO.
1172 # Leaving the original block in place keeps it within range.
1173 # Position accuracy is unaffected: RERAISE uses attach_tb=False
1174 # so no traceback entry is ever generated at the RERAISE site.
1175 if (len(target.instructions) == 1 and
1176 target.instructions[0].opcode == ops.RERAISE):
1177 continue
1178 # copy the block, it has more than one predecessor
1179 target.marked -= 2 # one fewer incoming links for old target
1180 newtarget = target.copy()
1181 newtarget.marked = 1 << 1 # new target has one incoming link
1182 newtarget.instructions[0].position_info = instr.position_info
1183 for copied_op in newtarget.instructions:
1184 if copied_op.jump:
1185 copied_op.jump.marked += 2
1186 # deal with fall-through of copied target block - rare, but
1187 # see test_if_call_or_call_bug
1188 if target.next_block and not newtarget.cant_add_instructions:
1189 new_instr = Instruction(ops.JUMP_ABSOLUTE, position_info=self.position_info)
1190 new_instr.jump = target.next_block
1191 target.next_block.marked += 2
1192 newtarget.emit_instr(new_instr)
1193 instr.jump = newtarget
1194 successor[newtarget] = successor.get(target)
1195 successor[target] = newtarget
1196 blocks.append(newtarget) # add to worklist for outer loop
1197 any_copy = True
1198
1199 if any_copy:
1200 new_blocks = []
1201 current = blocks[0]
1202 while current is not None:
1203 new_blocks.append(current)
1204 current = successor[current]
1205 assert len(new_blocks) == len(blocks)
1206 blocks[0:len(blocks)] = new_blocks
1207
1208 for block in blocks:
1209 if (block.instructions and block.next_block and
1210 not block.cant_add_instructions and
1211 block.next_block.marked & 1):
1212 # now assign the linenumber to the "fallthrough" implicit
1213 # return block too
1214 block.next_block.instructions[0].position_info = block.instructions[-1].position_info
1215 block.marked >>= 1
1216
1217
1218 class DeadCode(object):
1219 def __init__(self, codegen):
1220 self.codegen = codegen
1221
1222 def __enter__(self, *args):
1223 self.old_value = self.codegen._is_dead_code
1224 self.codegen._is_dead_code = True
1225
1226 def __exit__(self, *args):
1227 self.codegen._is_dead_code = self.old_value
1228
1229
1230 class MatchContext(object):
1231 def __init__(self, codegen):
1232 self.codegen = codegen
1233 self._init_names()
1234 self.allow_always_passing = False
1235 # the extra objects currently on the stack that need cleaning up
1236 self.on_top = 0
1237 self._reset_cleanup_blocks()
1238
1239 def _init_names(self):
1240 self.names_stored = {} # name -> int
1241 self.names_list = [] # list of names in order
1242 self.names_origins = [] # ast nodes to blame if a name repeats
1243
1244 def add_name(self, name, node, codegen):
1245 index = self.names_stored.get(name, -1)
1246 if index >= 0:
1247 # already exists
1248 previous_node = self.names_origins[index]
1249 codegen.error(
1250 "multiple assignments to name '%s' in pattern, previous one was on line %s" % (
1251 name, previous_node.lineno), node)
1252 else:
1253 self.names_stored[name] = len(self.names_stored)
1254 self.names_list.append(name)
1255 self.names_origins.append(node)
1256
1257 def _reset_cleanup_blocks(self):
1258 self.next = self.codegen.new_block()
1259 # the cleanup blocks will all be chained in reverse order, each one
1260 # contains a POP_TOP and a jump to the next one
1261 self.cleanup_blocks = [self.next]
1262
1263 def next_case(self, position_node=None):
1264 # add the POP_TOP instructions to the cleanup blocks
1265 for index in range(len(self.cleanup_blocks) - 1, 0, -1):
1266 block = self.cleanup_blocks[index]
1267 self.codegen.use_next_block(block)
1268 if position_node:
1269 self.codegen.update_position(position_node)
1270 self.codegen.emit_op(ops.POP_TOP)
1271 self.codegen.use_next_block(self.next)
1272 self._reset_cleanup_blocks()
1273 self._init_names()
1274
1275 def emit_fail_jump(self, op, cleanup=0):
1276 # emits a (conditional or unconditional) jump to the cleanup block (ie,
1277 # failure) with the right number of POP_TOPs
1278 cleanup += self.on_top + len(self.names_stored)
1279 while cleanup >= len(self.cleanup_blocks):
1280 self.cleanup_blocks.append(self.codegen.new_block())
1281 target = self.cleanup_blocks[cleanup]
1282 self.codegen.emit_jump(op, target)
1283
1284 def __enter__(self, *args):
1285 self.old_context = self.codegen.match_context
1286 self.codegen.match_context = self
1287 return self
1288
1289 def __exit__(self, *args):
1290 self.codegen.match_context = self.old_context
1291
1292 class SubMatchContext(object):
1293 """ context manager for setting allow_always_passing to True and then
1294 restoring the old value on leaving. """
1295 def __init__(self, codegen):
1296 self.codegen = codegen
1297
1298 def __enter__(self, *args):
1299 match_context = self.codegen.match_context
1300 self.old_value = match_context.allow_always_passing
1301 match_context.allow_always_passing = True
1302 return match_context
1303
1304 def __exit__(self, *args):
1305 self.codegen.match_context.allow_always_passing = self.old_value
1306
1307 def _first_real_lineno(instructions):
1308 """Return the position_info[0] of the first non-pseudo instruction, or -1."""
1309 for instr in instructions:
1310 if not is_pseudo_opcode(instr.opcode):
1311 return instr.position_info[0]
1312 return -1
1313
1314
1315 def _remove_redundant_nops(block):
1316 mininum_lineno = sys.maxint
1317 prevlineno = -1
1318 source = 0
1319 dest = 0
1320 instructions = block.instructions
1321 while source < len(instructions):
1322 op = instructions[source]
1323 source += 1
1324 lineno = op.position_info[0]
1325 if 0 < lineno < mininum_lineno:
1326 mininum_lineno = lineno
1327 if op.opcode == ops.NOP:
1328 if lineno == -1 or lineno == prevlineno:
1329 continue
1330 if source < len(instructions):
1331 # skip pseudo instructions to find the next real instruction
1332 next_lineno = _first_real_lineno(instructions[source:])
1333 if next_lineno == -1:
1334 # no real instruction found - fall back to the raw next
1335 # instruction's lineno (old behaviour for non-pseudo cases)
1336 next_lineno = instructions[source].position_info[0]
1337 if is_pseudo_opcode(instructions[source].opcode):
1338 next_lineno = -1 # don't remove on all-pseudo tail
1339 if next_lineno >= 0 and lineno == next_lineno:
1340 continue
1341 else:
1342 # last instruction in block is a NOP, check the next block.
1343 # Use only non-pseudo instructions: pseudo ones (SETUP_FINALLY
1344 # etc.) carry position info from the surrounding code but are
1345 # not emitted in the bytecode, so they must not count as the
1346 # "next instruction" for deduplication purposes.
1347 if block.next_block.instructions:
1348 next_lineno = _first_real_lineno(block.next_block.instructions)
1349 # Only remove if a real (non-pseudo) instruction was found
1350 # with the same line. A block of all-pseudo instructions
1351 # must not count as the "next instruction" here.
1352 if next_lineno >= 0 and lineno == next_lineno:
1353 continue
1354 prevlineno = lineno
1355 instructions[dest] = op
1356 dest += 1
1357 if dest != len(instructions):
1358 del instructions[dest:]
1359 return mininum_lineno
1360
1361 def remove_redundant_nops(blocks):
1362 mininum_lineno = sys.maxint
1363 for block in blocks:
1364 mininum_lineno = min(_remove_redundant_nops(block), mininum_lineno)
1365 if mininum_lineno == sys.maxint:
1366 mininum_lineno = 1
1367 return mininum_lineno
1368
1369
1370 def _is_swappable(opcode):
1371 """Return True if this opcode can be reordered by apply_static_swaps."""
1372 return opcode == ops.STORE_FAST or opcode == ops.POP_TOP
1373
1374
1375 def _stores_to(instr):
1376 """Return the oparg if STORE_FAST, else -1."""
1377 if instr.opcode == ops.STORE_FAST:
1378 return instr.arg
1379 return -1
1380
1381
1382 def _next_swappable(instructions, start, lineno):
1383 """Return index of next swappable instruction after start, or -1."""
1384 i = start + 1
1385 while i < len(instructions):
1386 instr = instructions[i]
1387 if instr.opcode == ops.NOP or is_pseudo_opcode(instr.opcode):
1388 i += 1
1389 continue
1390 if lineno >= 0 and instr.position_info[0] != lineno:
1391 return -1
1392 if _is_swappable(instr.opcode):
1393 return i
1394 return -1
1395 return -1
1396
1397
1398 def _apply_static_swaps(instructions, i):
1399 """Port of CPython's apply_static_swaps (compile.c).
1400
1401 Scan backwards from position i for SWAP instructions and try to
1402 eliminate each one by statically reordering the following
1403 STORE_FAST/POP_TOP instructions instead of swapping at runtime.
1404 """
1405 while i >= 0:
1406 instr = instructions[i]
1407 if instr.opcode == ops.NOP or is_pseudo_opcode(instr.opcode):
1408 i -= 1
1409 continue
1410 if instr.opcode != ops.SWAP:
1411 if _is_swappable(instr.opcode):
1412 i -= 1
1413 continue
1414 return # can't reason past this instruction
1415 # found a SWAP(n): find the j-th and k-th (= n-th) swappable followers
1416 j = _next_swappable(instructions, i, -1)
1417 if j < 0:
1418 return
1419 k = j
1420 lineno = instructions[j].position_info[0]
1421 for _ in range(instr.arg - 1):
1422 k = _next_swappable(instructions, k, lineno)
1423 if k < 0:
1424 return
1425 # check for conflicting stores
1426 store_j = _stores_to(instructions[j])
1427 store_k = _stores_to(instructions[k])
1428 if store_j >= 0 or store_k >= 0:
1429 if store_j == store_k:
1430 return
1431 for idx in range(j + 1, k):
1432 store_idx = _stores_to(instructions[idx])
1433 if store_idx >= 0 and (store_idx == store_j or store_idx == store_k):
1434 return
1435 # success: replace SWAP with NOP and swap the two instructions
1436 instr.opcode = ops.NOP
1437 instructions[j], instructions[k] = instructions[k], instructions[j]
1438 i -= 1
1439
1440
1441 def _encode_varint(result, value, msb=0):
1442 """Append a CPython-3.11-compatible varint encoding of value to result.
1443 Encodes 6 bits per byte, MSB first. Bit 6 (0x40) is the continuation
1444 flag (set on every byte except the last). Bit 7 (0x80) is the
1445 start-of-entry marker; pass msb=0x80 only on the first byte of an
1446 exception-table entry, 0 otherwise (matches CPython 3.11's
1447 assemble_emit_exception_table_item)."""
1448 assert value >= 0
1449 # Find the highest non-zero 6-bit chunk (shift counted in bits).
1450 shift = 0
1451 v = value >> 6
1452 while v:
1453 shift += 6
1454 v >>= 6
1455 # Write from the most-significant chunk down; all but the last get
1456 # the continuation bit. msb (start marker) goes only on the first byte.
1457 while shift > 0:
1458 chunk = (value >> shift) & 63
1459 result.append(chr(chunk | 64 | msb))
1460 msb = 0
1461 shift -= 6
1462 result.append(chr((value & 63) | msb))
1463
1464
1465 def _list_from_dict(d, offset=0):
1466 result = [None] * len(d)
1467 for obj, index in d.iteritems():
1468 result[index - offset] = obj
1469 return result
1470
1471
1472 _static_opcode_stack_effects = {
1473 ops.NOP: 0,
1474
1475 ops.POP_TOP: -1,
1476 ops.ROT_TWO: 0,
1477 ops.ROT_THREE: 0,
1478 ops.ROT_FOUR: 0,
1479 ops.DUP_TOP: 1,
1480 ops.DUP_TOP_TWO: 2,
1481 ops.COPY: 1,
1482
1483 ops.UNARY_POSITIVE: 0,
1484 ops.UNARY_NEGATIVE: 0,
1485 ops.UNARY_NOT: 0,
1486 ops.UNARY_INVERT: 0,
1487
1488 ops.LIST_APPEND: -1,
1489 ops.LIST_EXTEND: -1,
1490 ops.LIST_TO_TUPLE: 0,
1491 ops.SET_ADD: -1,
1492 ops.SET_UPDATE: -1,
1493 ops.MAP_ADD: -2,
1494
1495 ops.BINARY_POWER: -1,
1496 ops.BINARY_MULTIPLY: -1,
1497 ops.BINARY_MODULO: -1,
1498 ops.BINARY_ADD: -1,
1499 ops.BINARY_SUBTRACT: -1,
1500 ops.BINARY_SUBSCR: -1,
1501 ops.BINARY_FLOOR_DIVIDE: -1,
1502 ops.BINARY_TRUE_DIVIDE: -1,
1503 ops.BINARY_MATRIX_MULTIPLY: -1,
1504 ops.BINARY_LSHIFT: -1,
1505 ops.BINARY_RSHIFT: -1,
1506 ops.BINARY_AND: -1,
1507 ops.BINARY_OR: -1,
1508 ops.BINARY_XOR: -1,
1509
1510 ops.INPLACE_FLOOR_DIVIDE: -1,
1511 ops.INPLACE_TRUE_DIVIDE: -1,
1512 ops.INPLACE_ADD: -1,
1513 ops.INPLACE_SUBTRACT: -1,
1514 ops.INPLACE_MULTIPLY: -1,
1515 ops.INPLACE_MODULO: -1,
1516 ops.INPLACE_POWER: -1,
1517 ops.INPLACE_MATRIX_MULTIPLY: -1,
1518 ops.INPLACE_LSHIFT: -1,
1519 ops.INPLACE_RSHIFT: -1,
1520 ops.INPLACE_AND: -1,
1521 ops.INPLACE_OR: -1,
1522 ops.INPLACE_XOR: -1,
1523
1524 ops.STORE_SUBSCR: -3,
1525 ops.DELETE_SUBSCR: -2,
1526
1527 ops.GET_ITER: 0,
1528 ops.FOR_ITER: 1,
1529
1530 ops.PRINT_EXPR: -1,
1531
1532 ops.LOAD_BUILD_CLASS: 1,
1533 ops.POP_EXCEPT: -1,
1534 ops.PUSH_EXC_INFO: 1,
1535 ops.CHECK_EXC_MATCH: 0,
1536 _SETUP_FINALLY: 0, # marker only; handler depth set via forced_initial_depth
1537 _SETUP_CLEANUP: 0, # marker only; handler depth set via forced_initial_depth
1538 _SETUP_WITH: 0, # marker only; handler depth set via forced_initial_depth
1539 _POP_BLOCK: 0, # marker only
1540 ops.BEFORE_WITH: 1,
1541
1542 ops.RETURN_VALUE: -1,
1543 ops.YIELD_VALUE: 0,
1544 ops.YIELD_FROM: -1,
1545 ops.COMPARE_OP: -1,
1546 ops.IS_OP: -1,
1547 ops.CONTAINS_OP: -1,
1548
1549 ops.LOAD_METHOD: 1,
1550
1551 ops.LOAD_NAME: 1,
1552 ops.STORE_NAME: -1,
1553 ops.DELETE_NAME: 0,
1554
1555 ops.LOAD_FAST: 1,
1556 ops.STORE_FAST: -1,
1557 ops.DELETE_FAST: 0,
1558
1559 ops.LOAD_ATTR: 0,
1560 ops.STORE_ATTR: -2,
1561 ops.DELETE_ATTR: -1,
1562
1563 ops.LOAD_GLOBAL: 1,
1564 ops.STORE_GLOBAL: -1,
1565 ops.DELETE_GLOBAL: 0,
1566 ops.DELETE_DEREF: 0,
1567
1568 ops.LOAD_CLOSURE: 1,
1569 ops.LOAD_DEREF: 1,
1570 ops.STORE_DEREF: -1,
1571 ops.DELETE_DEREF: 0,
1572
1573 ops.GET_AWAITABLE: 0,
1574 ops.BEFORE_ASYNC_WITH: 1,
1575 ops.GET_AITER: 0,
1576 ops.GET_ANEXT: 1,
1577 ops.GET_YIELD_FROM_ITER: 0,
1578 ops.END_ASYNC_FOR: -3,
1579
1580 ops.LOAD_CONST: 1,
1581
1582 ops.IMPORT_STAR: -1,
1583 ops.IMPORT_NAME: -1,
1584 ops.IMPORT_FROM: 1,
1585
1586 ops.JUMP_FORWARD: 0,
1587 ops.JUMP_ABSOLUTE: 0,
1588 ops.JUMP_IF_TRUE_OR_POP: -1,
1589 ops.JUMP_IF_FALSE_OR_POP: -1,
1590 ops.POP_JUMP_IF_TRUE: -1,
1591 ops.POP_JUMP_IF_FALSE: -1,
1592 ops.POP_JUMP_FORWARD_IF_NONE: -1,
1593 ops.POP_JUMP_FORWARD_IF_NOT_NONE: -1,
1594 ops.JUMP_IF_NOT_EXC_MATCH: -2,
1595
1596 ops.SETUP_ANNOTATIONS: 0,
1597
1598 ops.DICT_MERGE: -1,
1599 ops.DICT_UPDATE: -1,
1600
1601 # TODO
1602 ops.BUILD_LIST_FROM_ARG: 1,
1603 ops.LOAD_REVDB_VAR: 1,
1604
1605 ops.LOAD_CLASSDEREF: 1,
1606 ops.LOAD_ASSERTION_ERROR: 1,
1607
1608 ops.RERAISE: -1,
1609
1610 ops.WITH_EXCEPT_START: 1,
1611
1612 ops.GET_LEN: 1,
1613 ops.MATCH_MAPPING: 1,
1614 ops.MATCH_SEQUENCE: 1,
1615 ops.MATCH_KEYS: 1,
1616 ops.COPY_DICT_WITHOUT_KEYS: 0,
1617 ops.SWAP: 0,
1618 ops.MATCH_CLASS: -1,
1619
1620 ops.CHECK_EG_MATCH: 0,
1621 ops.PREP_RERAISE_STAR: -1,
1622 }
1623
1624
1625 def _compute_UNPACK_SEQUENCE(arg):
1626 return arg - 1
1627
1628 def _compute_UNPACK_EX(arg):
1629 return (arg & 0xFF) + (arg >> 8)
1630
1631 def _compute_BUILD_TUPLE(arg):
1632 return 1 - arg
1633
1634 def _compute_BUILD_LIST(arg):
1635 return 1 - arg
1636
1637 def _compute_BUILD_SET(arg):
1638 return 1 - arg
1639
1640 def _compute_BUILD_MAP(arg):
1641 return 1 - 2 * arg
1642
1643 def _compute_MAKE_FUNCTION(arg):
1644 return -bool(arg & 0x01) - bool(arg & 0x02) - bool(arg & 0x04) - bool(arg & 0x08)
1645
1646 def _compute_BUILD_SLICE(arg):
1647 if arg == 3:
1648 return -2
1649 else:
1650 return -1
1651
1652 def _compute_RAISE_VARARGS(arg):
1653 return -arg
1654
1655 def _compute_CALL_FUNCTION(arg):
1656 return -arg
1657
1658 def _compute_CALL_FUNCTION_KW(arg):
1659 return -arg - 1
1660
1661 def _compute_CALL_FUNCTION_EX(arg):
1662 assert arg == 0 or arg == 1
1663 # either -1 or -2
1664 return -arg - 1
1665
1666 def _compute_CALL_METHOD(arg):
1667 return -arg - 1
1668
1669 def _compute_CALL_METHOD_KW(arg):
1670 return -arg - 2
1671
1672 def _compute_FORMAT_VALUE(arg):
1673 if (arg & consts.FVS_MASK) == consts.FVS_HAVE_SPEC:
1674 return -1
1675 return 0
1676
1677 def _compute_BUILD_STRING(arg):
1678 return 1 - arg
1679
1680 def _compute_BUILD_CONST_KEY_MAP(arg):
1681 return -arg
1682
1683
1684 _stack_effect_computers = {}
1685 for name, func in globals().items():
1686 if name.startswith("_compute_"):
1687 func._always_inline_ = True
1688 _stack_effect_computers[getattr(ops, name[9:])] = func
1689 for op, value in _static_opcode_stack_effects.iteritems():
1690 def func(arg, _value=value):
1691 return _value
1692 func._always_inline_ = True
1693 _stack_effect_computers[op] = func
1694 del name, func, op, value
1695
1696
1697 def _opcode_stack_effect(op, arg):
1698 """Return the stack effect of a opcode an its argument."""
1699 if Instruction.is_setup_pseudo_code(op) or op == _POP_BLOCK:
1700 return 0
1701 if we_are_translated():
1702 for possible_op in ops.unrolling_opcode_descs:
1703 # EXTENDED_ARG should never get in here.
1704 if possible_op.index == ops.EXTENDED_ARG:
1705 continue
1706 if op == possible_op.index:
1707 return _stack_effect_computers[possible_op.index](arg)
1708 else:
1709 raise KeyError("unknown opcode: %s" % (op,))
1710 else:
1711 try:
1712 return _static_opcode_stack_effects[op]
1713 except KeyError:
1714 try:
1715 return _stack_effect_computers[op](arg)
1716 except KeyError:
1717 raise KeyError("Unknown stack effect for %s (%s)" %
1718 (ops.opname[op], op))
1719
1720 def _opcode_stack_effect_jump(op):
1721 if op == ops.FOR_ITER:
1722 return -1
1723 elif op == _SETUP_FINALLY:
1724 # Handler block receives exc pushed by handle_operation_error.
1725 # lasti=False so only exc is pushed: +1.
1726 return 1
1727 elif op == _SETUP_CLEANUP:
1728 # Like _SETUP_FINALLY but lasti=True: handle_operation_error also pushes
1729 # lasti_int before exc, so +2.
1730 return 2
1731 elif op == _SETUP_WITH:
1732 # lasti=True so handle_operation_error pushes lasti+exc (+2 items), but
1733 # BEFORE_WITH already pushed __enter__result at depth D=N+1. The runtime
1734 # entry stack is N+2, so the jump effect is D+1-D = +1 (not +2). Combined
1735 # with depth_sub=1: table depth = (D+1) - 1 - 1 = D-1 = N (base+__exit__).
1736 return 1
1737 elif op == ops.JUMP_IF_TRUE_OR_POP:
1738 return 0
1739 elif op == ops.JUMP_IF_FALSE_OR_POP:
1740 return 0
1741 elif op == ops.JUMP_IF_NOT_EXC_MATCH:
1742 return -2
1743 elif op == ops.POP_JUMP_IF_TRUE:
1744 return -1
1745 elif op == ops.POP_JUMP_IF_FALSE:
1746 return -1
1747 elif op == ops.POP_JUMP_FORWARD_IF_NONE:
1748 return -1
1749 elif op == ops.POP_JUMP_FORWARD_IF_NOT_NONE:
1750 return -1
1751 elif op == ops.JUMP_FORWARD:
1752 return 0
1753 elif op == ops.JUMP_ABSOLUTE:
1754 return 0
1755 raise KeyError
1756
1757
1758 def _debug_print_blocks(blocks):
1759 labels = {block: i for (i, block) in enumerate(blocks)}
1760 for block in blocks:
1761 print "L%s:" % labels[block]
1762 for instruction in block.instructions:
1763 print instruction