[flang] Fix folding of SHAPE(SPREAD(source,dim,ncopies=-1)) (#141146)

The number of copies on the new dimension must be clamped via MAX(0,
ncopies) so that it is no less than zero.

Fixes https://github.com/llvm/llvm-project/issues/141119.
This commit is contained in:
Peter Klausler
2025-05-28 14:01:10 -07:00
committed by GitHub
parent 249301c779
commit a6432b971a
2 changed files with 5 additions and 3 deletions

View File

@@ -1073,8 +1073,8 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
}
}
} else if (intrinsic->name == "spread") {
// SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with NCOPIES inserted
// at position DIM.
// SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with MAX(0,NCOPIES)
// inserted at position DIM.
if (call.arguments().size() == 3) {
auto arrayShape{
(*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
@@ -1086,7 +1086,8 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
if (*dim >= 1 &&
static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {
arrayShape->emplace(arrayShape->begin() + *dim - 1,
ConvertToType<ExtentType>(common::Clone(*nCopies)));
Extremum<SubscriptInteger>{Ordering::Greater, ExtentExpr{0},
ConvertToType<ExtentType>(common::Clone(*nCopies))});
return std::move(*arrayShape);
}
}

View File

@@ -12,4 +12,5 @@ module m1
logical, parameter :: test_log4 = all(any(spread([.false., .true.], 2, 2), dim=2) .eqv. [.false., .true.])
logical, parameter :: test_m2toa3 = all(spread(reshape([(j,j=1,6)],[2,3]),1,4) == &
reshape([((j,k=1,4),j=1,6)],[4,2,3]))
logical, parameter :: test_shape_neg = all(shape(spread(0,1,-1)) == [0])
end module