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

[MLIR] Missed Optimization: Incomplete elimination of a tensor.empty shared by conditional branches

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

When both branches of scf.if use the same tensor.empty, the reverse traversal finds both uses, but the replacement logic selects only one. Both fills could use the destination slice because the branches are mutually exclusive, eliminating the temporary initializer entirely.

Input Program

input.mlir

module {
  func.func @shared_empty(%arg0: i1, %arg1: f32, %arg2: f32, %arg3: tensor<16xf32>) -> tensor<16xf32> {
    %0 = tensor.empty() : tensor<4xf32>
    %1 = scf.if %arg0 -> (tensor<4xf32>) {
      %2 = linalg.fill ins(%arg1 : f32) outs(%0 : tensor<4xf32>) -> tensor<4xf32>
      scf.yield %2 : tensor<4xf32>
    } else {
      %2 = linalg.fill ins(%arg2 : f32) outs(%0 : tensor<4xf32>) -> tensor<4xf32>
      scf.yield %2 : tensor<4xf32>
    }
    %inserted_slice = tensor.insert_slice %1 into %arg3[4] [4] [1] : tensor<4xf32> into tensor<16xf32>
    return %inserted_slice : tensor<16xf32>
  }
}

Command

mlir-opt input.mlir --eliminate-empty-tensors

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

MonSec-2077 avatar Sep 27 '26 07:09 MonSec-2077

@llvm/issue-subscribers-mlir

Author: MonSec-2077

When both branches of `scf.if` use the same `tensor.empty`, the reverse traversal finds both uses, but the replacement logic selects only one. Both fills could use the destination slice because the branches are mutually exclusive, eliminating the temporary initializer entirely.

Input Program

input.mlir

module {
  func.func @<!-- -->shared_empty(%arg0: i1, %arg1: f32, %arg2: f32, %arg3: tensor&lt;16xf32&gt;) -&gt; tensor&lt;16xf32&gt; {
    %0 = tensor.empty() : tensor&lt;4xf32&gt;
    %1 = scf.if %arg0 -&gt; (tensor&lt;4xf32&gt;) {
      %2 = linalg.fill ins(%arg1 : f32) outs(%0 : tensor&lt;4xf32&gt;) -&gt; tensor&lt;4xf32&gt;
      scf.yield %2 : tensor&lt;4xf32&gt;
    } else {
      %2 = linalg.fill ins(%arg2 : f32) outs(%0 : tensor&lt;4xf32&gt;) -&gt; tensor&lt;4xf32&gt;
      scf.yield %2 : tensor&lt;4xf32&gt;
    }
    %inserted_slice = tensor.insert_slice %1 into %arg3[4] [4] [1] : tensor&lt;4xf32&gt; into tensor&lt;16xf32&gt;
    return %inserted_slice : tensor&lt;16xf32&gt;
  }
}

Command

mlir-opt input.mlir --eliminate-empty-tensors

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

This is a known pattern that's worth having documented clearly in the issue tracker.

goransh-walia avatar Sep 27 '26 09:09 goransh-walia

@MonSec-2077 @Andarwinux Can I work on this issue?

ashu3103 avatar Sep 27 '26 16:09 ashu3103

@ashu3103 Sure, please submit a fix.

MonSec-2077 avatar Sep 28 '26 02:09 MonSec-2077

@MonSec-2077 I have created a draft PR (#228032), I still need to add tests though.

ashu3103 avatar Oct 01 '26 10:10 ashu3103