]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-131798: Optimize `_UNARY_INVERT` (GH-135222)
authorNoam Cohen <noam@noam.me>
Mon, 9 Jun 2025 10:33:18 +0000 (13:33 +0300)
committerGitHub <noreply@github.com>
Mon, 9 Jun 2025 10:33:18 +0000 (18:33 +0800)
Lib/test/test_capi/test_opt.py
Misc/NEWS.d/next/Core_and_Builtins/2025-06-06-01-09-44.gh-issue-131798.1SuxO9.rst [new file with mode: 0644]
Python/optimizer_bytecodes.c
Python/optimizer_cases.c.h

index 8a3819dabe44ce41949a30892cff4e1624611d24..bf22ef2a5922e7c28ff6dbc9bfff4dcf44319f00 100644 (file)
@@ -2275,6 +2275,21 @@ class TestUopsOptimization(unittest.TestCase):
         self.assertIn("_UNPACK_SEQUENCE_TWO_TUPLE", uops)
         self.assertNotIn("_GUARD_TOS_TUPLE", uops)
 
+    def test_unary_invert_long_type(self):
+        def testfunc(n):
+            for _ in range(n):
+                a = 9397
+                x = ~a + ~a
+
+        testfunc(TIER2_THRESHOLD)
+
+        ex = get_first_executor(testfunc)
+        self.assertIsNotNone(ex)
+        uops = get_opnames(ex)
+
+        self.assertNotIn("_GUARD_TOS_INT", uops)
+        self.assertNotIn("_GUARD_NOS_INT", uops)
+
 
 def global_identity(x):
     return x
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-06-06-01-09-44.gh-issue-131798.1SuxO9.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-06-06-01-09-44.gh-issue-131798.1SuxO9.rst
new file mode 100644 (file)
index 0000000..a377526
--- /dev/null
@@ -0,0 +1 @@
+Optimize ``_UNARY_INVERT`` in JIT-compiled code.
index fbf4dfd3db629c33bac1b40ba09be8441ff3cc6a..a9d5e92ca02a5901103fbb94a773b5ebe316053a 100644 (file)
@@ -467,6 +467,15 @@ dummy_func(void) {
         res = sym_new_truthiness(ctx, value, false);
     }
 
+    op(_UNARY_INVERT, (value -- res)) {
+        if (sym_matches_type(value, &PyLong_Type)) {
+            res = sym_new_type(ctx, &PyLong_Type);
+        }
+        else {
+            res = sym_new_not_null(ctx);
+        }
+    }
+
     op(_COMPARE_OP, (left, right -- res)) {
         if (oparg & 16) {
             res = sym_new_type(ctx, &PyBool_Type);
index b42f47c75eaf50b9070537c3b0b13945a409848f..4780e492f61d74544224be0341ec9f7184d74832 100644 (file)
         }
 
         case _UNARY_INVERT: {
+            JitOptSymbol *value;
             JitOptSymbol *res;
-            res = sym_new_not_null(ctx);
+            value = stack_pointer[-1];
+            if (sym_matches_type(value, &PyLong_Type)) {
+                res = sym_new_type(ctx, &PyLong_Type);
+            }
+            else {
+                res = sym_new_not_null(ctx);
+            }
             stack_pointer[-1] = res;
             break;
         }