Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 802b645

Browse files
authored
Only eliminate jumps to successor block if jump is unconditional. (GH-24417)
* Prevents elimination of the sole test of a value in statements like: if x or True: ...
1 parent 9eb11a1 commit 802b645

2 files changed

Lines changed: 20 additions & 17 deletions

File tree

Lib/test/test_bool.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,22 @@ def test_real_and_imag(self):
354354
self.assertIs(type(False.real), int)
355355
self.assertIs(type(False.imag), int)
356356

357+
def test_bool_called_at_least_once(self):
358+
class X:
359+
def __init__(self):
360+
self.count = 0
361+
def __bool__(self):
362+
self.count += 1
363+
return True
364+
365+
def f(x):
366+
if x or True:
367+
pass
368+
369+
x = X()
370+
f(x)
371+
self.assertGreaterEqual(x.count, 1)
372+
357373
def test_main():
358374
support.run_unittest(BoolTest)
359375

Python/compile.c

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6586,27 +6586,14 @@ optimize_cfg(struct assembler *a, PyObject *consts)
65866586
for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
65876587
if (b->b_iused > 0) {
65886588
struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
6589-
if (b_last_instr->i_opcode == POP_JUMP_IF_FALSE ||
6590-
b_last_instr->i_opcode == POP_JUMP_IF_TRUE ||
6591-
b_last_instr->i_opcode == JUMP_ABSOLUTE ||
6589+
if (b_last_instr->i_opcode == JUMP_ABSOLUTE ||
65926590
b_last_instr->i_opcode == JUMP_FORWARD) {
65936591
if (b_last_instr->i_target == b->b_next) {
65946592
assert(b->b_next->b_iused);
65956593
b->b_nofallthrough = 0;
6596-
switch(b_last_instr->i_opcode) {
6597-
case POP_JUMP_IF_FALSE:
6598-
case POP_JUMP_IF_TRUE:
6599-
b_last_instr->i_opcode = POP_TOP;
6600-
b_last_instr->i_target = NULL;
6601-
b_last_instr->i_oparg = 0;
6602-
break;
6603-
case JUMP_ABSOLUTE:
6604-
case JUMP_FORWARD:
6605-
b_last_instr->i_opcode = NOP;
6606-
clean_basic_block(b, -1);
6607-
maybe_empty_blocks = 1;
6608-
break;
6609-
}
6594+
b_last_instr->i_opcode = NOP;
6595+
clean_basic_block(b, -1);
6596+
maybe_empty_blocks = 1;
66106597
}
66116598
}
66126599
}

0 commit comments

Comments
 (0)