[Mlir-commits] [mlir] [mlir][LLVM] Add support for constant struct with multiple fields (PR #102752)

Tobias Gysi llvmlistbot at llvm.org
Mon Aug 12 00:29:33 PDT 2024


https://github.com/gysit commented:

Can you elaborate on the use case for this change? 

I think the constant operation is only meant to produce constants of non-aggregate types. The complex type is an exception bcs there is some support for builtin complex attributes which produces an array attribute with two elements.

Note that proper struct support is not possible bcs a struct can contain pointers which cannot be modeled as attributes. Additionally, they can be nested, which may be modeled with attributes but things get complex.

Instead if you want to produce a constant struct, the preferred way is to use the undef operation and then set the individual fields of the struct. 

You can test this by writing some example:
```
define { i32, i32 } @test() {
   ret {i32, i32} { i32 -1, i32 0}
}
```
And then call  `./bin/mlir-translate --import-llvm ./test.ll` to import into MLIR:
```
  llvm.func @test() -> !llvm.struct<(i32, i32)> {
    %0 = llvm.mlir.constant(0 : i32) : i32
    %1 = llvm.mlir.constant(-1 : i32) : i32
    %2 = llvm.mlir.undef : !llvm.struct<(i32, i32)>
    %3 = llvm.insertvalue %1, %2[0] : !llvm.struct<(i32, i32)> 
    %4 = llvm.insertvalue %0, %3[1] : !llvm.struct<(i32, i32)> 
    llvm.return %4 : !llvm.struct<(i32, i32)>
  }
```
This represents an struct constant in LLVM dialect. While this particular example could be supported things will fail as soon as there are pointers:
```
  llvm.func @test() -> !llvm.struct<(ptr, i32)> {
    %0 = llvm.mlir.constant(0 : i32) : i32
    %1 = llvm.mlir.zero : !llvm.ptr
    %2 = llvm.mlir.undef : !llvm.struct<(ptr, i32)>
    %3 = llvm.insertvalue %1, %2[0] : !llvm.struct<(ptr, i32)> 
    %4 = llvm.insertvalue %0, %3[1] : !llvm.struct<(ptr, i32)> 
    llvm.return %4 : !llvm.struct<(ptr, i32)>
  }
```
I would thus stick to the current limitations of constant op and represent aggregate constants using a sequence of operations. Otherwise there will be multiple ways of representing the same thing which would require a good argument why this is necessary.


https://github.com/llvm/llvm-project/pull/102752


More information about the Mlir-commits mailing list