llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[MLIR] Missed Optimization: Constants defined inside loops prevent loop range folding

Open MonSec-2077 opened this issue 2 months ago • 6 comments

The operand check requires the offset to be defined outside the loop, rejecting even a literal constant defined in the loop body.

In this example, materializing %c4 outside the loop would allow shifting the range to [4, 12) while preserving step 1 and eliminating the addition.

Code Example

func.func @local_constant(%out: memref<16xi32>, %v: i32) {
  %c0 = arith.constant 0 : index
  %c1 = arith.constant 1 : index
  %c8 = arith.constant 8 : index

  scf.for %i = %c0 to %c8 step %c1 {
    %c4 = arith.constant 4 : index
    %idx = arith.addi %i, %c4 : index
    memref.store %v, %out[%idx] : memref<16xi32>
  }
  return
}

Command

mlir-opt input.mlir --scf-for-loop-range-folding

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

MonSec-2077 avatar Oct 03 '26 03:10 MonSec-2077

@llvm/issue-subscribers-mlir

Author: MonSec-2077

The operand check requires the offset to be defined outside the loop, rejecting even a literal constant defined in the loop body.

In this example, materializing %c4 outside the loop would allow shifting the range to [4, 12) while preserving step 1 and eliminating the addition.

Code Example

func.func @<!-- -->local_constant(%out: memref&lt;16xi32&gt;, %v: i32) {
  %c0 = arith.constant 0 : index
  %c1 = arith.constant 1 : index
  %c8 = arith.constant 8 : index

  scf.for %i = %c0 to %c8 step %c1 {
    %c4 = arith.constant 4 : index
    %idx = arith.addi %i, %c4 : index
    memref.store %v, %out[%idx] : memref&lt;16xi32&gt;
  }
  return
}

Command

mlir-opt input.mlir --scf-for-loop-range-folding

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

running loop-invariant code motion pass before scf-for-loop-range-folding solves this and it is the only job of the pass, do we need scf-for-loop-range-folding to handle it? @banach-space @matthias-springer

StarOne01 avatar Oct 04 '26 01:10 StarOne01

I would rely on LICM here.

matthias-springer avatar Oct 05 '26 01:10 matthias-springer

I would rely on LICM here.

+1

banach-space avatar Oct 05 '26 09:10 banach-space

So close this issue?

StarOne01 avatar Oct 05 '26 12:10 StarOne01

i don't have the permission to close this, i request someone with access to do so.

StarOne01 avatar Oct 06 '26 05:10 StarOne01