[mlir][arith] canonicalization pattern causes miscompilation on `arith.index_cast`
similar issue to: https://github.com/llvm/llvm-project/issues/90238
The following code:
module {
func.func @main() {
%3 = call @gt_i8_max() : () -> index
%4 = arith.index_cast %3 : index to i8
%5 = arith.index_cast %4 : i8 to index
vector.print str "%3="
vector.print %3 : index
vector.print str "%4="
vector.print %4 : i8
vector.print str "%5="
vector.print %5 : index // Bug: expect "%5=0".
return
}
func.func @gt_i8_max() -> index {
%max = arith.constant 256 : index
return %max : index
}
}
incorrectly prints out %5=256 (correct result should be %5=0) when compiled and executed with:
mlir-opt --canonicalize --arith-expand --convert-arith-to-llvm --convert-scf-to-cf --convert-cf-to-llvm --convert-vector-to-llvm --convert-func-to-llvm --reconcile-unrealized-casts | mlir-cpu-runner -e main --shared-libs ~/lib/mlir/libmlir_c_runner_utils.so --entry-point-result void
This appears to be caused by the canonicalization for arith.index_cast folding the sequence:
%3 = call @gt_i8_max() : () -> index
%4 = arith.index_cast %3 : index to i8
%5 = arith.index_cast %4 : i8 to index
into:
%3 = call @gt_i8_max() : () -> index
%4 = arith.index_cast %3 : index to i8
// effectively: %5 = %3
Reproduction here: https://godbolt.org/z/oW318xzE5
According to the arith.index_cast doc, it says
If casting to a wider integer, the value is sign-extended. If casting to a narrower integer, the value is truncated.
So if the i8 is narrower than the index type in this platform, 256 should be truncated which is 0 in this case.
This is handled by IndexCastOfIndexCast. If the source type and destination type are identical, they are folded.
I think we should not naively fold such consecutive index_cast even if they have the identical source and destination type. as long as the truncation by the index_cast is clearly documented.
Should we check the bit width too? We do not fold them if the bit width is different.