]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-131798: Narrow the return type of isinstance for some known arguments in the JIT...
authorTomas R. <tomas.roun8@gmail.com>
Mon, 19 May 2025 17:19:24 +0000 (13:19 -0400)
committerGitHub <noreply@github.com>
Mon, 19 May 2025 17:19:24 +0000 (13:19 -0400)
Lib/test/test_capi/test_opt.py
Misc/NEWS.d/next/Core_and_Builtins/2025-04-26-17-50-01.gh-issue-131798.XiOgw5.rst [new file with mode: 0644]
Python/optimizer_bytecodes.c
Python/optimizer_cases.c.h

index 651148336f7f2c6104c54b7691a8b79c6125078c..73ce55400adcdfd665bb1190fedd5118ca0d152f 100644 (file)
@@ -1959,6 +1959,121 @@ class TestUopsOptimization(unittest.TestCase):
         self.assertNotIn("_GUARD_THIRD_NULL", uops)
         self.assertNotIn("_GUARD_CALLABLE_ISINSTANCE", uops)
 
+    def test_call_isinstance_is_true(self):
+        def testfunc(n):
+            x = 0
+            for _ in range(n):
+                y = isinstance(42, int)
+                if y:
+                    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("_CALL_ISINSTANCE", uops)
+        self.assertNotIn("_TO_BOOL_BOOL", uops)
+        self.assertNotIn("_GUARD_IS_TRUE_POP", uops)
+
+    def test_call_isinstance_is_false(self):
+        def testfunc(n):
+            x = 0
+            for _ in range(n):
+                y = isinstance(42, str)
+                if not y:
+                    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("_CALL_ISINSTANCE", uops)
+        self.assertNotIn("_TO_BOOL_BOOL", uops)
+        self.assertNotIn("_GUARD_IS_FALSE_POP", uops)
+
+    def test_call_isinstance_subclass(self):
+        def testfunc(n):
+            x = 0
+            for _ in range(n):
+                y = isinstance(True, int)
+                if y:
+                    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("_CALL_ISINSTANCE", uops)
+        self.assertNotIn("_TO_BOOL_BOOL", uops)
+        self.assertNotIn("_GUARD_IS_TRUE_POP", uops)
+
+    def test_call_isinstance_unknown_object(self):
+        def testfunc(n):
+            x = 0
+            for _ in range(n):
+                # The optimizer doesn't know the return type here:
+                bar = eval("42")
+                # This will only narrow to bool:
+                y = isinstance(bar, int)
+                if y:
+                    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("_CALL_ISINSTANCE", uops)
+        self.assertNotIn("_TO_BOOL_BOOL", uops)
+        self.assertIn("_GUARD_IS_TRUE_POP", uops)
+
+    def test_call_isinstance_tuple_of_classes(self):
+        def testfunc(n):
+            x = 0
+            for _ in range(n):
+                # A tuple of classes is currently not optimized,
+                # so this is only narrowed to bool:
+                y = isinstance(42, (int, str))
+                if y:
+                    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("_CALL_ISINSTANCE", uops)
+        self.assertNotIn("_TO_BOOL_BOOL", uops)
+        self.assertIn("_GUARD_IS_TRUE_POP", uops)
+
+    def test_call_isinstance_metaclass(self):
+        class EvenNumberMeta(type):
+            def __instancecheck__(self, number):
+                return number % 2 == 0
+
+        class EvenNumber(metaclass=EvenNumberMeta):
+            pass
+
+        def testfunc(n):
+            x = 0
+            for _ in range(n):
+                # Only narrowed to bool
+                y = isinstance(42, EvenNumber)
+                if y:
+                    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("_CALL_ISINSTANCE", uops)
+        self.assertNotIn("_TO_BOOL_BOOL", uops)
+        self.assertIn("_GUARD_IS_TRUE_POP", uops)
+
 
 def global_identity(x):
     return x
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-04-26-17-50-01.gh-issue-131798.XiOgw5.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-26-17-50-01.gh-issue-131798.XiOgw5.rst
new file mode 100644 (file)
index 0000000..45ab1be
--- /dev/null
@@ -0,0 +1,2 @@
+Narrow the return type and constant-evaluate ``CALL_ISINSTANCE`` for a
+subset of known values in the JIT. Patch by Tomas Roun
index 7c160cdcb0c1491904a9cc9105ac131817783df3..ad25c68e62aab29766ba7609f6035829e946d01c 100644 (file)
@@ -890,6 +890,26 @@ dummy_func(void) {
         }
     }
 
+    op(_CALL_ISINSTANCE, (unused, unused, instance, cls -- res)) {
+        // the result is always a bool, but sometimes we can
+        // narrow it down to True or False
+        res = sym_new_type(ctx, &PyBool_Type);
+        PyTypeObject *inst_type = sym_get_type(instance);
+        PyTypeObject *cls_o = (PyTypeObject *)sym_get_const(ctx, cls);
+        if (inst_type && cls_o && sym_matches_type(cls, &PyType_Type)) {
+            // isinstance(inst, cls) where both inst and cls have
+            // known types, meaning we can deduce either True or False
+
+            // The below check is equivalent to PyObject_TypeCheck(inst, cls)
+            if (inst_type == cls_o || PyType_IsSubtype(inst_type, cls_o)) {
+                sym_set_const(res, Py_True);
+            }
+            else {
+                sym_set_const(res, Py_False);
+            }
+        }
+    }
+
     op(_GUARD_IS_TRUE_POP, (flag -- )) {
         if (sym_is_const(ctx, flag)) {
             PyObject *value = sym_get_const(ctx, flag);
index deb912662e4b0b8bb3efa868f3999dd68350f76a..5d46976520383331806535e51cddeeabeba86474 100644 (file)
         }
 
         case _CALL_ISINSTANCE: {
+            JitOptSymbol *cls;
+            JitOptSymbol *instance;
             JitOptSymbol *res;
-            res = sym_new_not_null(ctx);
+            cls = stack_pointer[-1];
+            instance = stack_pointer[-2];
+            res = sym_new_type(ctx, &PyBool_Type);
+            PyTypeObject *inst_type = sym_get_type(instance);
+            PyTypeObject *cls_o = (PyTypeObject *)sym_get_const(ctx, cls);
+            if (inst_type && cls_o && sym_matches_type(cls, &PyType_Type)) {
+                if (inst_type == cls_o || PyType_IsSubtype(inst_type, cls_o)) {
+                    sym_set_const(res, Py_True);
+                }
+                else {
+                    sym_set_const(res, Py_False);
+                }
+            }
             stack_pointer[-4] = res;
             stack_pointer += -3;
             assert(WITHIN_STACK_BOUNDS());