[Mlir-commits] [mlir] [mlir][python] Propagate error diagnostics when an op couldn't be created. (PR #169499)

Benjamin Chetioui llvmlistbot at llvm.org
Tue Nov 25 09:32:25 PST 2025


https://github.com/bchetioui updated https://github.com/llvm/llvm-project/pull/169499

>From 3dd68cd139388f5d9148ceef657f371093ee288d Mon Sep 17 00:00:00 2001
From: Benjamin Chetioui <bchetioui at google.com>
Date: Tue, 25 Nov 2025 14:33:20 +0000
Subject: [PATCH] [mlir][python] Propagate error diagnostics when an op
 couldn't be created.

---
 mlir/lib/Bindings/Python/IRCore.cpp |  3 ++-
 mlir/test/python/ir/operation.py    | 17 ++++++++++++++++-
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/mlir/lib/Bindings/Python/IRCore.cpp b/mlir/lib/Bindings/Python/IRCore.cpp
index 03b540de97d4f..2e0c2b895216f 100644
--- a/mlir/lib/Bindings/Python/IRCore.cpp
+++ b/mlir/lib/Bindings/Python/IRCore.cpp
@@ -1411,9 +1411,10 @@ nb::object PyOperation::create(std::string_view name,
   }
 
   // Construct the operation.
+  PyMlirContext::ErrorCapture errors(location.getContext());
   MlirOperation operation = mlirOperationCreate(&state);
   if (!operation.ptr)
-    throw nb::value_error("Operation creation failed");
+    throw MLIRError("Operation creation failed", errors.take());
   PyOperationRef created =
       PyOperation::createDetached(location.getContext(), operation);
   maybeInsertOperation(created, maybeIp);
diff --git a/mlir/test/python/ir/operation.py b/mlir/test/python/ir/operation.py
index 66ba5d28e49b2..ca99c2a985242 100644
--- a/mlir/test/python/ir/operation.py
+++ b/mlir/test/python/ir/operation.py
@@ -5,7 +5,7 @@
 from tempfile import NamedTemporaryFile
 from mlir.ir import *
 from mlir.dialects.builtin import ModuleOp
-from mlir.dialects import arith, func, scf
+from mlir.dialects import arith, func, scf, shape
 from mlir.dialects._ods_common import _cext
 from mlir.extras import types as T
 
@@ -774,6 +774,21 @@ def __init__(self, result, value, *, loc=None, ip=None):
         print(repr(constant))
 
 
+# CHECK-LABEL: TEST: testFailedGenericOperationCreationReportsError
+ at run
+def testFailedGenericOperationCreationReportsError():
+    with Context(), Location.unknown():
+        c0 = shape.const_shape([])
+        c1 = shape.const_shape([1, 2, 3])
+        try:
+            shape.MeetOp.build_generic(operands=[c0, c1])
+        except MLIRError as e:
+            # CHECK: unequal shape cardinality
+            print(e)
+        else:
+            assert False, "Expected exception"
+
+
 # CHECK-LABEL: TEST: testSingleResultProperty
 @run
 def testSingleResultProperty():



More information about the Mlir-commits mailing list