[Mlir-commits] [mlir] [MLIR][SCF] Sink scf.if from scf.while before region into after region. (PR #165216)

Ming Yan llvmlistbot at llvm.org
Mon Oct 27 19:28:15 PDT 2025


NexMing wrote:

> What further optimizations did you have in mind?

The motivation is that I want to lift `cf` to `scf.for`.
For example, I want to convert the following control flow into an `scf.for`.
```
  func.func @test(%arg0: memref<100xf32>) {
    %c100 = arith.constant 100 : index
    %c0 = arith.constant 0 : index
    %c1 = arith.constant 1 : index
    %cst = arith.constant 0.000000e+00 : f32
    cf.br ^bb1(%c0 : index)
  ^bb1(%0: index):  // 2 preds: ^bb0, ^bb2
    %1 = arith.cmpi slt, %0, %c100 : index
    cf.cond_br %1, ^bb2, ^bb3
  ^bb2:  // pred: ^bb1
    memref.store %cst, %arg0[%0] : memref<100xf32>
    %2 = arith.addi %0, %c1 : index
    cf.br ^bb1(%2 : index)
  ^bb3:  // pred: ^bb1
    return
  }
```
When I use the `lift-cf-to-scf` pass, I get:
```
  func.func @test(%arg0: memref<100xf32>) {
    %0 = ub.poison : index
    %c100 = arith.constant 100 : index
    %c0 = arith.constant 0 : index
    %c1 = arith.constant 1 : index
    %cst = arith.constant 0.000000e+00 : f32
    %1 = scf.while (%arg1 = %c0) : (index) -> index {
      %2 = arith.cmpi slt, %arg1, %c100 : index
      %3 = scf.if %2 -> (index) {
        memref.store %cst, %arg0[%arg1] : memref<100xf32>
        %4 = arith.addi %arg1, %c1 : index
        scf.yield %4 : index
      } else {
        scf.yield %0 : index
      }
      scf.condition(%2) %3 : index
    } do {
    ^bb0(%arg1: index):
      scf.yield %arg1 : index
    }
    return
  }
```
When I continued using `test-scf-uplift-while-to-for`, the attempt to lift `scf.while` to `scf.for` failed.
After the current optimizations, `test-scf-uplift-while-to-for` can successfully lift `scf.while` to `scf.for`.
I believe the current optimization always simplifies the control flow, so I think it belongs to canonicalization.
I don’t quite understand in what situations there would be a need to hoist the if condition.
If needed, I will consider moving it into test-scf-uplift-while-to-for.

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


More information about the Mlir-commits mailing list