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

llvmlistbot at llvm.org llvmlistbot at llvm.org
Mon Sep 29 01:07:44 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-mlir

Author: Matthias Springer (matthias-springer)

<details>
<summary>Changes</summary>

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


---
Full diff: https://github.com/llvm/llvm-project/pull/161145.diff


2 Files Affected:

- (modified) mlir/lib/Transforms/Utils/GreedyPatternRewriteDriver.cpp (+2-1) 
- (modified) mlir/test/Transforms/canonicalize.mlir (+9) 


``````````diff
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

``````````

</details>


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


More information about the Mlir-commits mailing list