<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/89770>89770</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [mlir] `fold` in Dialect conversion operates on IR that does not verify after signature conversion
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            mlir
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          zero9178
      </td>
    </tr>
</table>

<pre>
    Signature conversion performed by `ConversionPatternRewriter::convertRegionTypes` causes all block arguments of blocks of a region to be converted. This is done by creating new blocks, moving all operations into the new block, followed by "erasing" the old block (this is in reality an unlink operation in the dialect conversion in case of needing to rollback). 

However, one problem this causes is that `BlockArgument`s are not remapped until the conversion has been comitted. In my case I had basically the following IR with a type conversion of `!custom.type`:
```mlir
custom.func @test(%arg0 : !custom.type) {
   custom.user %arg0 : !custom.type
}
```
where cruically `custom.user` implemented `fold` roughly like this:
```cpp
OpFoldResult User::fold(FoldAdaptor adaptor) 
   if (auto blockArgument = dyn_cast<BlockArgument>(getInput()) {
 return BoolAttr::get(getContext(), blockArgument.getOwner()->isEntryBlock());
   return nullptr;
}
```

This crashes in dialect conversion as the block argument `%arg0` has not been replaced yet with the new block argument or the `builtin.unrealized_conversion_cast` produced by the type conversion and the basic block returned by `blockArgument.getOwner()` still refers to the old unlinked basic block that has no region as parent. This leads to a crash in `isEntryBlock` due to a nullptr dereference.

I am now left wondering whether 1) the block argument replacement should be done immediately, 2) whether dialect conversion should be calling `fold` or 3) whether at least the operands of an operation should be changed to at least prior to the `fold` happening.

cc @matthias-springer 
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJx8VkFv4zgP_TXKhWjgyImTHHJI2ym-nuZDd_Y8UCza1o4sGRLdrOfXLyg5k2SmKFAkriiSj4_ki1WMpnWIB7F5FJvnhRqp8-HwE4Pfr7a7xcnr6fCXaZ2iMSD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