GH-131798: Narrow the result of _CONTAINS_OP_SET to bool in the JIT (GH-132057)

This commit is contained in:
Tomas R. 2025-04-06 00:56:01 +02:00 committed by GitHub
parent ad6a032ceb
commit 85bc489b64
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 35 additions and 3 deletions

View file

@ -1603,6 +1603,32 @@ class TestUopsOptimization(unittest.TestCase):
self.assertNotIn("_COMPARE_OP_INT", uops)
self.assertIn("_POP_TWO_LOAD_CONST_INLINE_BORROW", uops)
def test_to_bool_bool_contains_op_set(self):
"""
Test that _TO_BOOL_BOOL is removed from code like:
res = foo in some_set
if res:
....
"""
def testfunc(n):
x = 0
s = {1, 2, 3}
for _ in range(n):
a = 2
in_set = a in s
if in_set:
x += 1
return x
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
self.assertEqual(res, TIER2_THRESHOLD)
self.assertIsNotNone(ex)
uops = get_opnames(ex)
self.assertIn("_CONTAINS_OP_SET", uops)
self.assertNotIn("_TO_BOOL_BOOL", uops)
def test_remove_guard_for_known_type_str(self):
def f(n):
for i in range(n):

View file

@ -0,0 +1,2 @@
Allow the JIT to remove an extra ``_TO_BOOL_BOOL`` instruction after
``_CONTAINS_OP_SET`` by setting the return type to bool.

View file

@ -477,6 +477,10 @@ dummy_func(void) {
res = sym_new_type(ctx, &PyBool_Type);
}
op(_CONTAINS_OP_SET, (left, right -- res)) {
res = sym_new_type(ctx, &PyBool_Type);
}
op(_LOAD_CONST, (-- value)) {
PyObject *val = PyTuple_GET_ITEM(co->co_consts, this_instr->oparg);
int opcode = _Py_IsImmortal(val) ? _LOAD_CONST_INLINE_BORROW : _LOAD_CONST_INLINE;

View file

@ -1283,9 +1283,9 @@
}
case _CONTAINS_OP_SET: {
JitOptSymbol *b;
b = sym_new_not_null(ctx);
stack_pointer[-2] = b;
JitOptSymbol *res;
res = sym_new_type(ctx, &PyBool_Type);
stack_pointer[-2] = res;
stack_pointer += -1;
assert(WITHIN_STACK_BOUNDS());
break;