[Mlir-commits] [mlir] [mlir][UB] Add `ub.unreachable` canonicalization (PR #169873)

Matthias Springer llvmlistbot at llvm.org
Sat Nov 29 18:21:00 PST 2025


================
@@ -57,8 +58,33 @@ Operation *UBDialect::materializeConstant(OpBuilder &builder, Attribute value,
   return nullptr;
 }
 
+//===----------------------------------------------------------------------===//
+// PoisonOp
+//===----------------------------------------------------------------------===//
+
 OpFoldResult PoisonOp::fold(FoldAdaptor /*adaptor*/) { return getValue(); }
 
+//===----------------------------------------------------------------------===//
+// UnreachableOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult UnreachableOp::canonicalize(UnreachableOp unreachableOp,
+                                          PatternRewriter &rewriter) {
+  Block *block = unreachableOp->getBlock();
+  if (llvm::hasSingleElement(*block))
+    return rewriter.notifyMatchFailure(
+        unreachableOp, "unreachable op is the only operation in the block");
+
+  // Erase all other operations in the block. They must be dead.
+  for (Operation &op : llvm::make_early_inc_range(*block)) {
+    if (&op == unreachableOp.getOperation())
+      continue;
+    op.dropAllUses();
+    rewriter.eraseOp(&op);
+  }
----------------
matthias-springer wrote:

I didn't think of infinite loops. I am wondering if this canonicalization is actually safe. I'm just merging the `cf.cond_br` canonicalization for now, so we can discuss further.


https://github.com/llvm/llvm-project/pull/169873


More information about the Mlir-commits mailing list