Skip to content

Commit 5292179

Browse files
authored
[3.7] bpo-37269: Correctly optimise conditionals with constant booleans (GH-14071) (GH-14073)
Fix a regression introduced by af8646c that was causing code of the form: if True and False: do_something() to be optimized incorrectly, eliminating the block.. (cherry picked from commit 05f8318) Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
1 parent 6a433f5 commit 5292179

3 files changed

Lines changed: 14 additions & 0 deletions

File tree

Lib/test/test_peepholer.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,13 @@ def test_constant_folding(self):
311311
self.assertFalse(instr.opname.startswith('BINARY_'))
312312
self.assertFalse(instr.opname.startswith('BUILD_'))
313313

314+
def test_condition_with_binop_with_bools(self):
315+
def f():
316+
if True or False:
317+
return 1
318+
return 0
319+
self.assertEqual(f(), 1)
320+
314321

315322
class TestBuglets(unittest.TestCase):
316323

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a bug in the peephole optimizer that was not treating correctly constant
2+
conditions with binary operators. Patch by Pablo Galindo.

Python/peephole.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,11 @@ PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
313313
fill_nops(codestr, op_start, nexti + 1);
314314
cumlc = 0;
315315
} else if (is_true == 0) {
316+
if (i > 1 &&
317+
(_Py_OPCODE(codestr[i - 1]) == POP_JUMP_IF_TRUE ||
318+
_Py_OPCODE(codestr[i - 1]) == POP_JUMP_IF_FALSE)) {
319+
break;
320+
}
316321
h = get_arg(codestr, nexti) / sizeof(_Py_CODEUNIT);
317322
tgt = find_op(codestr, codelen, h);
318323
fill_nops(codestr, op_start, tgt);

0 commit comments

Comments
 (0)