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

[MLIR] SROA misses optimization on `alloca` with `getelementptr`

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

MLIR SROA optmization fails to promote memory locations created by llvm.alloca when memory accesses go through llvm.getelementptr instructions.

Even though all accesses are to fixed, non-escaping scalar fields of the structure, SROA leaves the llvm.alloca, llvm.store, and llvm.load intact. Ideally, SROA should promote the accessed scalar field and fold the store/load sequence to a direct return of the constant.

Minimal Reproducer

test.mlir

module {
  func.func @nested_struct() -> i32 {
    %c1_i64 = arith.constant 1 : i64
    %c7_i32 = arith.constant 7 : i32
    %0 = llvm.alloca %c1_i64 x !llvm.struct<(i32, i32)> : (i64) -> !llvm.ptr
    %1 = llvm.getelementptr %0[0] : (!llvm.ptr) -> !llvm.ptr, !llvm.struct<(i32, i32)>
    %2 = llvm.getelementptr %1[0, 1] : (!llvm.ptr) -> !llvm.ptr, !llvm.struct<(i32, i32)>
    llvm.store %c7_i32, %2 : i32, !llvm.ptr
    %3 = llvm.load %2 : !llvm.ptr -> i32
    return %3 : i32
  }
}

Command for Reproduction

mlir-opt --sroa test.mlir

Version: ef88536bbf62469eb2396d719d237b3191cf4843

MonSec-2077 avatar Aug 18 '26 12:08 MonSec-2077

@llvm/issue-subscribers-mlir

Author: MonSec-2077

MLIR SROA optmization fails to promote memory locations created by `llvm.alloca` when memory accesses go through `llvm.getelementptr` instructions.

Even though all accesses are to fixed, non-escaping scalar fields of the structure, SROA leaves the llvm.alloca, llvm.store, and llvm.load intact. Ideally, SROA should promote the accessed scalar field and fold the store/load sequence to a direct return of the constant.

Minimal Reproducer

test.mlir

module {
  func.func @<!-- -->nested_struct() -&gt; i32 {
    %c1_i64 = arith.constant 1 : i64
    %c7_i32 = arith.constant 7 : i32
    %0 = llvm.alloca %c1_i64 x !llvm.struct&lt;(i32, i32)&gt; : (i64) -&gt; !llvm.ptr
    %1 = llvm.getelementptr %0[0] : (!llvm.ptr) -&gt; !llvm.ptr, !llvm.struct&lt;(i32, i32)&gt;
    %2 = llvm.getelementptr %1[0, 1] : (!llvm.ptr) -&gt; !llvm.ptr, !llvm.struct&lt;(i32, i32)&gt;
    llvm.store %c7_i32, %2 : i32, !llvm.ptr
    %3 = llvm.load %2 : !llvm.ptr -&gt; i32
    return %3 : i32
  }
}

Command for Reproduction

mlir-opt --sroa test.mlir

Version: ef88536bbf62469eb2396d719d237b3191cf4843

I can take a look.

prometheusfma-llvm avatar Aug 23 '26 10:08 prometheusfma-llvm