[Mlir-commits] [mlir] [mlir][memref] Move dealloc for unused memref to after alloc (PR #227975)

Pranav Alavandi llvmlistbot at llvm.org
Wed Sep 30 23:28:39 PDT 2026


https://github.com/pranavalavandi created https://github.com/llvm/llvm-project/pull/227975

Addresses issue https://github.com/llvm/llvm-project/issues/227363

As I understand only a small change is needed when a `lastUser` does not exist, implying the `memref` is unused, we can just hoist the `dealloc` to be right after the `allocOp`

>From c048f1a1819f68cd5209943e992b98d4b936099e Mon Sep 17 00:00:00 2001
From: pranavalavandi <pranav.alavandi at q-ctrl.com>
Date: Thu, 1 Oct 2026 16:25:30 +1000
Subject: [PATCH] [mlir][memref] Move dealloc for unused memref to after alloc

---
 .../Transforms/OptimizeAllocationLiveness.cpp     |  3 +++
 .../Transforms/optimize-allocation-liveness.mlir  | 15 +++++++++++++++
 2 files changed, 18 insertions(+)

diff --git a/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp b/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp
index 28ee5b8e32b9913..3d4b8d2adb9117c 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp
@@ -155,6 +155,9 @@ struct OptimizeAllocationLiveness
         }
       }
       if (lastUser == nullptr) {
+        LDBG() << "Last user not found ";
+        LDBG() << "Moved dealloc op after alloc: " << *allocOp;
+        deallocOp->moveAfter(allocOp);
         return WalkResult::advance();
       }
       LDBG() << "Last user found: " << *lastUser;
diff --git a/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir b/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir
index b8fcccda8833aef..07620859cc0bb0a 100644
--- a/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir
+++ b/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir
@@ -234,3 +234,18 @@ func.func private @test_alloc_with_multiple_results() -> () {
   memref.dealloc %alloc2 : memref<64xf32>
   return
 }
+
+// -----
+func.func private @work()
+// CHECK-LABEL:   func.func private @test_alloc_with_no_uses() {
+// CHECK:           %[[ALLOC_0:.*]] = memref.alloc() : memref<1048576xi32>
+// CHECK:           memref.dealloc %[[ALLOC_0]] : memref<1048576xi32>
+// CHECK:           call @work() : () -> ()
+// CHECK:           return
+// CHECK:         }
+func.func private @test_alloc_with_no_uses() -> () {
+    %alloc = memref.alloc() : memref<1048576xi32>
+    call @work() : () -> ()
+    memref.dealloc %alloc : memref<1048576xi32>
+    return
+}



More information about the Mlir-commits mailing list