Skip to content

[ThroughMLIR] Lowering C arrays as function arguments #1729

@JosseVanDelm

Description

@JosseVanDelm

Hi,

I'm trying to lower an array as a function argument to core MLIR dialects, but I'm a bit stuck.
The problem is that code as simple as:

int myfunc(int *myarray, int myindex) {
    return myarray[myindex];
}

fails to lower to core MILR dialects.
The clangir emitted looks like this:

!s32i = !cir.int<s, 32>
module @"mymodule"
  cir.func dso_local @_Z6myfuncPii(%arg0: !cir.ptr<!s32i>), %arg1: !s32i) -> !s32i {
    %0 = cir.alloca !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>, ["myarray", init] {alignment = 8 : i64}
    %1 = cir.alloca !s32i, !cir.ptr<!s32i>, ["myindex", init] {alignment = 4 : i64}
    %2 = cir.alloca !s32i, !cir.ptr<!s32i>, ["__retval"] {alignment = 4 : i64}
    cir.store %arg0, %0 : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
    cir.store %arg1, %1 : !s32i, !cir.ptr<!s32i>
    %3 = cir.load align(8) %0 : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
    %4 = cir.load align(4) %1 : !cir.ptr<!s32i>, !s32i
    %5 = cir.ptr_stride(%3 : !cir.ptr<!s32i>, %4 : !s32i), !cir.ptr<!s32i>
    %6 = cir.load align(4) %5 : !cir.ptr<!s32i>, !s32i
    cir.store %6, %2 : !s32i, !cir.ptr<!s32i>
    %7 = cir.load %2 : !cir.ptr<!s32i>,
    cir.return %7 : !s32i
  }
}

This fails to lower, because the cir.ptr_stride operation fails to legalize (it is not the result of a cir.cast with array_to_ptrdecay and hence the conversion pattern for cir.ptr_stride in cir-to-mlir fails.
If I disable the additional checks in the conversion pattern, it seems that there's a type conversion mismatch, because the !cir.ptr<i32> is converted to a memref<i32> to which no offset can be applied, as it is a 0-dimensional memref.

Polygeist seems to solve this issue by assuming memref<?xi32> for all pointer types. But IIUC correctly C completely loses any semantic information w.r.t. array dimensionality and sizing when passing it as a function argument.

As the above code seems quite trivial and I was not able to find any test code that seems to supports converting this into core mlir dialects, I was wondering if I'm overlooking something. Is lowering arrays as function arguments supported? If not, what would be the best way to convert this type of code to mlir core dialects? Would the polygeist way work?

Thanks so much!
Best regards :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions