[Mlir-commits] [mlir] [mlir][toy] Use `make_early_inc_range` when erasing ops during iteration (PR #146892)

Matthias Springer llvmlistbot at llvm.org
Thu Jul 3 06:54:50 PDT 2025


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

Use `make_early_inc_range` when erasing operations from a block to make sure that the iterator is not invalidated. The previous implementation happened to work on a "normal" dialect conversion because some IR modifications are delayed. It no longer works with a One-Shot Dialect Conversion. The new One-Shot Dialect Conversion API is more similar to the normal rewriter API.


>From 790448f09b2181836436d06a4ee76c75db39ac49 Mon Sep 17 00:00:00 2001
From: Matthias Springer <me at m-sp.org>
Date: Thu, 3 Jul 2025 13:51:49 +0000
Subject: [PATCH] [mlir][toy] Use `make_early_inc_range` when erasing ops
 during iteration

---
 mlir/examples/toy/Ch6/mlir/LowerToLLVM.cpp | 2 +-
 mlir/examples/toy/Ch7/mlir/LowerToLLVM.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/mlir/examples/toy/Ch6/mlir/LowerToLLVM.cpp b/mlir/examples/toy/Ch6/mlir/LowerToLLVM.cpp
index de1eafc4d8678..22f75e042fe08 100644
--- a/mlir/examples/toy/Ch6/mlir/LowerToLLVM.cpp
+++ b/mlir/examples/toy/Ch6/mlir/LowerToLLVM.cpp
@@ -92,7 +92,7 @@ class PrintOpLowering : public ConversionPattern {
       auto step = rewriter.create<arith::ConstantIndexOp>(loc, 1);
       auto loop =
           rewriter.create<scf::ForOp>(loc, lowerBound, upperBound, step);
-      for (Operation &nested : *loop.getBody())
+      for (Operation &nested : make_early_inc_range(*loop.getBody()))
         rewriter.eraseOp(&nested);
       loopIvs.push_back(loop.getInductionVar());
 
diff --git a/mlir/examples/toy/Ch7/mlir/LowerToLLVM.cpp b/mlir/examples/toy/Ch7/mlir/LowerToLLVM.cpp
index a20a2c888a175..54eeb275ae85e 100644
--- a/mlir/examples/toy/Ch7/mlir/LowerToLLVM.cpp
+++ b/mlir/examples/toy/Ch7/mlir/LowerToLLVM.cpp
@@ -92,7 +92,7 @@ class PrintOpLowering : public ConversionPattern {
       auto step = rewriter.create<arith::ConstantIndexOp>(loc, 1);
       auto loop =
           rewriter.create<scf::ForOp>(loc, lowerBound, upperBound, step);
-      for (Operation &nested : *loop.getBody())
+      for (Operation &nested : make_early_inc_range(*loop.getBody()))
         rewriter.eraseOp(&nested);
       loopIvs.push_back(loop.getInductionVar());
 



More information about the Mlir-commits mailing list