Skip to content

Commit c55af35

Browse files
klauslersivan-shani
authored andcommitted
[flang] Fix folding of SHAPE(SPREAD(source,dim,ncopies=-1)) (llvm#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 llvm#141119.
1 parent 479ff4c commit c55af35

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

flang/lib/Evaluate/shape.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,8 +1073,8 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
10731073
}
10741074
}
10751075
} else if (intrinsic->name == "spread") {
1076-
// SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with NCOPIES inserted
1077-
// at position DIM.
1076+
// SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with MAX(0,NCOPIES)
1077+
// inserted at position DIM.
10781078
if (call.arguments().size() == 3) {
10791079
auto arrayShape{
10801080
(*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
@@ -1086,7 +1086,8 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
10861086
if (*dim >= 1 &&
10871087
static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {
10881088
arrayShape->emplace(arrayShape->begin() + *dim - 1,
1089-
ConvertToType<ExtentType>(common::Clone(*nCopies)));
1089+
Extremum<SubscriptInteger>{Ordering::Greater, ExtentExpr{0},
1090+
ConvertToType<ExtentType>(common::Clone(*nCopies))});
10901091
return std::move(*arrayShape);
10911092
}
10921093
}

flang/test/Evaluate/fold-spread.f90

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ module m1
1212
logical, parameter :: test_log4 = all(any(spread([.false., .true.], 2, 2), dim=2) .eqv. [.false., .true.])
1313
logical, parameter :: test_m2toa3 = all(spread(reshape([(j,j=1,6)],[2,3]),1,4) == &
1414
reshape([((j,k=1,4),j=1,6)],[4,2,3]))
15+
logical, parameter :: test_shape_neg = all(shape(spread(0,1,-1)) == [0])
1516
end module

0 commit comments

Comments
 (0)