[Mlir-commits] [mlir] [mlir][SCF]: promote one-iteration loops with equal ub and step values (PR #205826)

Ege Beysel llvmlistbot at llvm.org
Thu Jun 25 07:28:41 PDT 2026


https://github.com/egebeysel created https://github.com/llvm/llvm-project/pull/205826

Adds a fast-path to `constantTripCount` to return 1 on single-iteration loops of the form:

```
scf.for %j = %c0 to %val step %val ... { ... }
```

>From e2dada2794337600d01776d55f3a3d78babad78c Mon Sep 17 00:00:00 2001
From: Ege Beysel <beyselege at gmail.com>
Date: Thu, 25 Jun 2026 14:14:54 +0000
Subject: [PATCH] feat(SCF): promote one-iteration loops with equal ub and step
 SSA values

Signed-off-by: Ege Beysel <beyselege at gmail.com>
---
 mlir/lib/Dialect/Utils/StaticValueUtils.cpp |  6 ++++++
 mlir/test/Dialect/SCF/transform-ops.mlir    | 14 ++++++++++++++
 2 files changed, 20 insertions(+)

diff --git a/mlir/lib/Dialect/Utils/StaticValueUtils.cpp b/mlir/lib/Dialect/Utils/StaticValueUtils.cpp
index a826f56a69d92..4e30693353440 100644
--- a/mlir/lib/Dialect/Utils/StaticValueUtils.cpp
+++ b/mlir/lib/Dialect/Utils/StaticValueUtils.cpp
@@ -322,6 +322,12 @@ std::optional<APInt> constantTripCount(
     // SSA values. That case cannot be detected here.
     return APInt(bitwidth, 0);
   }
+  if (isZeroInteger(lb) && ub == step) {
+    // Fast path: LB == 0 && UB == step. The loop has a single iteration.
+    // Note: LB and UB could match at runtime, even though they are different
+    // SSA values. That case cannot be detected here.
+    return APInt(bitwidth, 1);
+  }
 
   std::optional<std::pair<APInt, bool>> maybeStepCst =
       getConstantAPIntValue(step);
diff --git a/mlir/test/Dialect/SCF/transform-ops.mlir b/mlir/test/Dialect/SCF/transform-ops.mlir
index 0e5a4a98a98ea..c8be2d2b3a883 100644
--- a/mlir/test/Dialect/SCF/transform-ops.mlir
+++ b/mlir/test/Dialect/SCF/transform-ops.mlir
@@ -449,6 +449,20 @@ func.func @test_promote_if_one_iteration(%a: index) -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: func @test_promote_if_one_iteration_dynamic(
+//   CHECK-NOT:   scf.for
+//       CHECK:   %[[r:.*]] = "test.foo"
+//       CHECK:   return %[[r]]
+func.func @test_promote_if_one_iteration_dynamic(%a: index, %val: index) -> index {
+  %c0 = arith.constant 0 : index
+  %c1 = arith.constant 1 : index
+  %0 = scf.for %j = %c0 to %val step %val iter_args(%arg0 = %a) -> index {
+    %1 = "test.foo"(%a) : (index) -> (index)
+    scf.yield %1 : index
+  }
+  return %0 : index
+}
+
 module attributes {transform.with_named_sequence} {
   transform.named_sequence @__transform_main(%arg1: !transform.any_op {transform.readonly}) {
     %0 = transform.structured.match ops{["scf.for"]} in %arg1 : (!transform.any_op) -> !transform.any_op



More information about the Mlir-commits mailing list