[mlir][scf] Fix ForOpTensorCastFolder on loops that change shape (#234422)
`ForOpTensorCastFolder` folds a `tensor.cast` into a `scf.for` without
checking what the loop yields, so a non-shape-preserving loop gets a
cast to a static type it may not actually have, which is UB. The
`matmul_on_tensors` test was one example of such a loop.
This change makes the fold check two things to avoid UB:
1. The loop yields a `tensor.cast` from the static shape, or
2. The loop is shape-preserving
If either is true, the fold is legal.
A loop which happened to fold to the same shape it has at runtime and
execute as expected may no longer receive this fold. Such a loop will
continue to execute correctly, but it no longer carries a static shape
and therefore may be less optimized by downstream passes.
`isShapePreserving` already existed in `LoopCanonicalization.cpp`, so it
moves into `SCF.cpp` as a public function so both clients can use it.
Also, `isShapePreserving` now accepts any `DestinationStyleOpInterface`
instead of just `tensor.insert_slice` since these ops return their
destination tensor with the same type. This also allows the uses in
`LoopCanonicalization` to support such ops.
Now, `matmul_on_tensors` yields a cast from the static type. Also adds
tests for a nested loop that still folds and two loops that must not
fold.
Assisted-by: Claude