[Mlir-commits] [mlir] [mlir][Transforms] Greedy pattern rewriter: fix infinite folding loop (PR #161145)

Matthias Springer llvmlistbot at llvm.org
Mon Sep 29 01:07:05 PDT 2025


https://github.com/matthias-springer created https://github.com/llvm/llvm-project/pull/161145

Fix an infinite folding loop when the result of a folding is identical to the folded operation.


>From 05d8247883ec57c283adb7326393e6ed18ed2d82 Mon Sep 17 00:00:00 2001
From: Matthias Springer <me at m-sp.org>
Date: Mon, 29 Sep 2025 08:05:59 +0000
Subject: [PATCH] [mlir][Transforms] Greedy pattern rewriter: fix infinite
 folding loop

---
 mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp | 3 ++-
 mlir/test/Transforms/canonicalize.mlir                   | 9 +++++++++
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp b/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp
index 74e4a822b4fd7..93468dd79808f 100644
--- a/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp
+++ b/mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp
@@ -555,7 +555,8 @@ bool GreedyPatternRewriteDriver::processWorklist() {
           replacements.push_back(constOp->getResult(0));
         }
 
-        if (materializationSucceeded) {
+        if (materializationSucceeded &&
+            !llvm::equal(replacements, op->getResults())) {
           rewriter.replaceOp(op, replacements);
           changed = true;
           LLVM_DEBUG(logSuccessfulFolding(dumpRootOp));
diff --git a/mlir/test/Transforms/canonicalize.mlir b/mlir/test/Transforms/canonicalize.mlir
index 8e02c06a0a293..ed987e555926c 100644
--- a/mlir/test/Transforms/canonicalize.mlir
+++ b/mlir/test/Transforms/canonicalize.mlir
@@ -1248,3 +1248,12 @@ func.func @test_materialize_failure() -> i64 {
   %u = index.castu %const : index to i64
   return %u: i64
 }
+
+// -----
+
+// Make sure that the canonicalizer does not fold infinitely.
+
+// CHECK: %[[c0:.*]] = arith.constant 0 : index
+%c0 = arith.constant 0 : index
+// CHECK: %[[add:.*]] = arith.addi %[[c0]], %[[add]] : index
+%0 = arith.addi %c0, %0 : index



More information about the Mlir-commits mailing list