[MLIR] Missed Optimization: Incomplete elimination of a tensor.empty shared by conditional branches
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
@llvm/issue-subscribers-mlir
Author: MonSec-2077
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
This is a known pattern that's worth having documented clearly in the issue tracker.
@MonSec-2077 @Andarwinux Can I work on this issue?
@ashu3103 Sure, please submit a fix.
@MonSec-2077 I have created a draft PR (#228032), I still need to add tests though.