<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/134291>134291</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [mlir] -remove-dead-values generates invalid MLIR for affine.for with iter_args, which executes only once.
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            mlir
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          yyong120
      </td>
    </tr>
</table>

<pre>
    To reproduce: `mlir-opt -remove-dead-values test.mlir`

`test.mlir`:
```
func.func @test_affine_for() {
    %c1_i32 = arith.constant 1 : i32
    %alloca = memref.alloca() : memref<16xi32>
 %0 = affine.for %arg0 = 0 to 16 step 64 iter_args(%arg1 = %c1_i32) -> (i32) {
        %1 = arith.addi %arg1, %c1_i32 : i32
        memref.store %1, %alloca[%arg0] : memref<16xi32>
        affine.yield %1 : i32
    }
 return
}
```

The generated `result.mlir`:
```
func.func @test_for() {
    %c1_i32 = arith.constant 1 : i32
    %alloca = memref.alloca() : memref<16xi32>
    affine.for %arg0 = 0 to 16 step 64 iter_args(%arg1 = %c1_i32) -> () {
        %0 = arith.addi %arg1, %c1_i32 : i32
 memref.store %0, %alloca[%arg0] : memref<16xi32>
        affine.yield
 }
    return
}
```
Run `mlir-opt --verify-diagnostics result.mlir`, the error is

```
result_1.mlir:4:5: error: unexpected error: custom op 'affine.for' mismatch between the number of loop-carried values and results
 affine.for %arg0 = 0 to 16 step 64 iter_args(%arg1 = %c1_i32) -> () {
 ^
```

This issue happens when an `affine.for` only executes once. Since the loop-carried arguments (`iter_args`) will not be updated, remove-dead-values pass will remove the return values of `affine.yield`. However, `iter_args` are still left in the for loop, which leads to an invalid mlir.
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJzEVUuvozgT_TXOpgQy5pFkwSL3pe-TZjY9vY8MLsAjYyPbJDf_fmRDXq2rllrq0SB0Lzh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