]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-131798: Optimize `_GUARD_TOS_SLICE` (GH-144470)
authorSacul <183588943+Sacul0457@users.noreply.github.com>
Sun, 8 Feb 2026 18:08:26 +0000 (02:08 +0800)
committerGitHub <noreply@github.com>
Sun, 8 Feb 2026 18:08:26 +0000 (18:08 +0000)
Lib/test/test_capi/test_opt.py
Misc/NEWS.d/next/Core_and_Builtins/2026-02-04-12-19-48.gh-issue-131798.My5jLy.rst [new file with mode: 0644]
Python/optimizer_bytecodes.c
Python/optimizer_cases.c.h

index 43b268b0206a4688cff86b2d0c6c0dfe206625d2..765cb69dc04df18a599565afd486b7d39c93c395 100644 (file)
@@ -1986,6 +1986,23 @@ class TestUopsOptimization(unittest.TestCase):
         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 (file)
index 0000000..849889f
--- /dev/null
@@ -0,0 +1 @@
+Optimise ``_GUARD_TOS_SLICE`` in the JIT.
index 0863d5dd8f8df73e8e45939c15f86c3554af1f11..e82770742a356c4c3be4b73b73b1b1d3c485c071 100644 (file)
@@ -1374,6 +1374,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);
index 9a51d2fa366661243427fb8fba82f6133baa7c56..cc1d28f49442b406f3eec11a981d0a6f7f4f0f28 100644 (file)
         }
 
         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;
         }