diff --git a/Lib/test/test_capi/test_opt.py b/Lib/test/test_capi/test_opt.py index 437cc340fc90e3..9463e5d5594d47 100644 --- a/Lib/test/test_capi/test_opt.py +++ b/Lib/test/test_capi/test_opt.py @@ -2030,6 +2030,23 @@ def f(n): self.assertNotIn("_GUARD_NOS_TUPLE", uops) self.assertIn("_BINARY_OP_SUBSCR_TUPLE_INT", uops) + def test_remove_guard_for_known_type_slice(self): + def f(n): + x = 0 + for _ in range(n): + l = [1, 2, 3] + slice_obj = slice(0, 1) + x += l[slice_obj][0] # guarded + x += l[slice_obj][0] # unguarded + return x + res, ex = self._run_with_optimizer(f, TIER2_THRESHOLD) + self.assertEqual(res, TIER2_THRESHOLD * 2) + uops = get_opnames(ex) + + count = count_ops(ex, "_GUARD_TOS_SLICE") + self.assertEqual(count, 1) + self.assertIn("_BINARY_OP_SUBSCR_LIST_INT", uops) + def test_remove_guard_for_tuple_bounds_check(self): def f(n): x = 0 diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-02-04-12-19-48.gh-issue-131798.My5jLy.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-02-04-12-19-48.gh-issue-131798.My5jLy.rst new file mode 100644 index 00000000000000..849889f81fc323 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-02-04-12-19-48.gh-issue-131798.My5jLy.rst @@ -0,0 +1 @@ +Optimise ``_GUARD_TOS_SLICE`` in the JIT. diff --git a/Python/optimizer_bytecodes.c b/Python/optimizer_bytecodes.c index 89c6707160326c..3a2af7d9198175 100644 --- a/Python/optimizer_bytecodes.c +++ b/Python/optimizer_bytecodes.c @@ -1417,6 +1417,13 @@ dummy_func(void) { } } + op(_GUARD_TOS_SLICE, (tos -- tos)){ + if (sym_matches_type(tos, &PySlice_Type)){ + ADD_OP(_NOP, 0, 0); + } + sym_set_type(tos, &PySlice_Type); + } + op(_GUARD_NOS_NULL, (null, unused -- null, unused)) { if (sym_is_null(null)) { ADD_OP(_NOP, 0, 0); diff --git a/Python/optimizer_cases.c.h b/Python/optimizer_cases.c.h index 61a30314c21789..259cf2a1c32dc7 100644 --- a/Python/optimizer_cases.c.h +++ b/Python/optimizer_cases.c.h @@ -370,6 +370,12 @@ } case _GUARD_TOS_SLICE: { + JitOptRef tos; + tos = stack_pointer[-1]; + if (sym_matches_type(tos, &PySlice_Type)){ + ADD_OP(_NOP, 0, 0); + } + sym_set_type(tos, &PySlice_Type); break; }