<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/61158>61158</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[mlir] clean-up memref.collapse_shape with dynamic dimension of size 1
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue,
mlir
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
qcolombet
</td>
</tr>
</table>
<pre>
The lowering of `memref.collapse_shape` may return the wrong stride if some of the collapsed dimensions are dynamic at compile time and `1` at runtime.
The issue stems from the fact that dimensions of size `1` are supposed to be skipped (see the comment below from
`computeCollapsedLayoutMap`) when computing the resulting stride of the collapsed dimensions, but we don't generate the code that does that for dynamic dimensions.
This was a deliberate choice when refactoring the lowering of `memref.collapse_shape` (see 64f99842a6c03fdb57349fcaed3f4821ef612ed1 and https://reviews.llvm.org/D136483#3909856) because:
- Supporting that would greatly pessimism codegen: to compute the stride of a collapsed dimension we would need to filter out the size-1 dimensions from the reassociation group and take the `min` of the resulting set of strides (i.e., a bunch of branchy code), and more importantly
- Dimension of size 1 where this kind of gymnastics are required are arguably not truly contiguous (and thus fall into UB as described in the documentation of `memref.collpase_shape`)
Anyhow, we need to decide if non-contiguous dimensions of size 1 are allowed and either fix the expansion of `memref.collapse_shape` (in `expand-strided-metadata`) or document clearly that they are not supported and suggest an alternative (in particular to front-end writers).
Note: Static non-contiguous dimensions of size 1 are currently correctly expanded, but this is a band aid to the bigger problem (i.e., we saw them happen in practice). If we decide that dimensions of size 1 shouldn't be used in `memref.collapse_shape` we should get rid of that code too.
---
Comment in `computeCollapsedLayoutMap`:
```
The result stride of a reassociation group is the stride of the last entry
of the reassociation. (...) Dimensions of size 1 should be skipped, because
their strides are meaningless and could have any arbitrary value
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVl1v27gS_TXyy8CGTNmK9eCHNEGAC9x7X7r7vBiRI4lbilT5Ed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