[Mlir-commits] [mlir] Amortize cost of block op index lookups (PR #156027)

Samarth Narang llvmlistbot at llvm.org
Fri Aug 29 07:08:10 PDT 2025


https://github.com/snarang181 created https://github.com/llvm/llvm-project/pull/156027

None

>From 27909ee9b51637eb6f0938b49dbd9c6118fce522 Mon Sep 17 00:00:00 2001
From: Samarth Narang <snarang at umass.edu>
Date: Fri, 29 Aug 2025 10:07:31 -0400
Subject: [PATCH] Amortize cost of block op index lookups

---
 mlir/lib/Dialect/Affine/Analysis/Utils.cpp | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
index 99ea20bf13b49..dbb02015fe0aa 100644
--- a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
+++ b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
@@ -1442,16 +1442,26 @@ template LogicalResult
 mlir::affine::boundCheckLoadOrStoreOp(AffineWriteOpInterface storeOp,
                                       bool emitError);
 
+static inline unsigned getIndexInBlock(Operation *op, llvm::DenseMap<Block*, llvm::DenseMap<Operation*, unsigned>> &cache) {
+  Block *block = op->getBlock();
+  auto &blockMap = cache[block];
+  if(blockMap.empty()) {
+    unsigned idx = 0;
+    for (Operation &it: *block)
+      blockMap[&it] = idx++;
+  }
+  return blockMap.lookup(op);
+}
+
 // Returns in 'positions' the Block positions of 'op' in each ancestor
 // Block from the Block containing operation, stopping at 'limitBlock'.
 static void findInstPosition(Operation *op, Block *limitBlock,
                              SmallVectorImpl<unsigned> *positions) {
+  llvm::DenseMap<Block*, llvm::DenseMap<Operation*, unsigned>> indexCache;
+
   Block *block = op->getBlock();
   while (block != limitBlock) {
-    // FIXME: This algorithm is unnecessarily O(n) and should be improved to not
-    // rely on linear scans.
-    int instPosInBlock = std::distance(block->begin(), op->getIterator());
-    positions->push_back(instPosInBlock);
+    positions->push_back(getIndexInBlock(op, indexCache));
     op = block->getParentOp();
     block = op->getBlock();
   }



More information about the Mlir-commits mailing list