9#ifndef FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_
10#define FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_
15#include "flang/Common/indirection.h"
16#include "flang/Common/template.h"
17#include "flang/Common/unwrap.h"
18#include "flang/Evaluate/characteristics.h"
19#include "flang/Evaluate/common.h"
20#include "flang/Evaluate/constant.h"
21#include "flang/Evaluate/expression.h"
22#include "flang/Evaluate/fold.h"
23#include "flang/Evaluate/formatting.h"
24#include "flang/Evaluate/intrinsics-library.h"
25#include "flang/Evaluate/intrinsics.h"
26#include "flang/Evaluate/shape.h"
27#include "flang/Evaluate/tools.h"
28#include "flang/Evaluate/traverse.h"
29#include "flang/Evaluate/type.h"
30#include "flang/Parser/message.h"
31#include "flang/Semantics/scope.h"
32#include "flang/Semantics/symbol.h"
33#include "flang/Semantics/tools.h"
52static constexpr bool useKahanSummation{
false};
58 : context_{c}, forOptionalArgument_{forOptionalArgument} {}
59 std::optional<Constant<T>> GetNamedConstant(
const Symbol &);
60 std::optional<Constant<T>> ApplySubscripts(
const Constant<T> &array,
65 std::optional<Constant<T>> GetConstantComponent(
67 std::optional<Constant<T>> Folding(
ArrayRef &);
68 std::optional<Constant<T>> Folding(
DataRef &);
70 Constant<T> *Folding(std::optional<ActualArgument> &);
85 bool forOptionalArgument_{
false};
88std::optional<Constant<SubscriptInteger>> GetConstantSubscript(
92template <
typename TR,
typename... TA>
93std::optional<std::function<Scalar<TR>(
FoldingContext &, Scalar<TA>...)>>
94GetHostRuntimeWrapper(
const std::string &name) {
95 std::vector<DynamicType> argTypes{TA{}.GetType()...};
96 if (
auto hostWrapper{GetHostRuntimeWrapper(name, TR{}.GetType(), argTypes)}) {
98 FoldingContext &context, Scalar<TA>... args) -> Scalar<TR> {
99 std::vector<Expr<SomeType>> genericArgs{
100 AsGenericExpr(Constant<TA>{args})...};
101 return GetScalarConstantValue<TR>(
102 (*hostWrapper)(context, std::move(genericArgs)))
117common::IfNoLvalue<Expr<ResultType<A>>, A> FoldOperation(
118 FoldingContext &, A &&x) {
119 static_assert(!std::is_same_v<A, Expr<ResultType<A>>>,
120 "call Fold() instead for Expr<>");
121 return Expr<ResultType<A>>{std::move(x)};
124Component FoldOperation(FoldingContext &, Component &&);
125NamedEntity FoldOperation(FoldingContext &, NamedEntity &&);
126Triplet FoldOperation(FoldingContext &, Triplet &&);
127Subscript FoldOperation(FoldingContext &, Subscript &&);
128ArrayRef FoldOperation(FoldingContext &, ArrayRef &&);
129CoarrayRef FoldOperation(FoldingContext &, CoarrayRef &&);
130DataRef FoldOperation(FoldingContext &, DataRef &&);
131Substring FoldOperation(FoldingContext &, Substring &&);
132ComplexPart FoldOperation(FoldingContext &, ComplexPart &&);
134Expr<T> FoldOperation(FoldingContext &, FunctionRef<T> &&);
136Expr<T> FoldOperation(FoldingContext &context, Designator<T> &&designator) {
137 return Folder<T>{context}.Folding(std::move(designator));
139Expr<TypeParamInquiry::Result> FoldOperation(
140 FoldingContext &, TypeParamInquiry &&);
141Expr<ImpliedDoIndex::Result> FoldOperation(
142 FoldingContext &context, ImpliedDoIndex &&);
144Expr<T> FoldOperation(FoldingContext &, ArrayConstructor<T> &&);
145Expr<SomeDerived> FoldOperation(FoldingContext &, StructureConstructor &&);
148std::optional<Constant<T>> Folder<T>::GetNamedConstant(
const Symbol &symbol0) {
149 const Symbol &symbol{ResolveAssociations(symbol0)};
150 if (IsNamedConstant(symbol)) {
151 if (
const auto *
object{
152 symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
153 if (
const auto *constant{UnwrapConstantValue<T>(object->init())}) {
162std::optional<Constant<T>> Folder<T>::Folding(ArrayRef &aRef) {
163 std::vector<Constant<SubscriptInteger>> subscripts;
165 for (Subscript &ss : aRef.subscript()) {
166 if (
auto constant{GetConstantSubscript(context_, ss, aRef.base(), dim++)}) {
167 subscripts.emplace_back(std::move(*constant));
172 if (Component * component{aRef.base().UnwrapComponent()}) {
173 return GetConstantComponent(*component, &subscripts);
174 }
else if (std::optional<Constant<T>> array{
175 GetNamedConstant(aRef.base().GetLastSymbol())}) {
176 return ApplySubscripts(*array, subscripts);
183std::optional<Constant<T>> Folder<T>::Folding(DataRef &ref) {
184 return common::visit(
186 [
this](SymbolRef &sym) {
return GetNamedConstant(*sym); },
187 [
this](Component &comp) {
188 comp = FoldOperation(context_, std::move(comp));
189 return GetConstantComponent(comp);
191 [
this](ArrayRef &aRef) {
192 aRef = FoldOperation(context_, std::move(aRef));
193 return Folding(aRef);
195 [](CoarrayRef &) {
return std::optional<Constant<T>>{}; },
202std::optional<Constant<T>> Folder<T>::ApplySubscripts(
const Constant<T> &array,
203 const std::vector<Constant<SubscriptInteger>> &subscripts) {
204 const auto &shape{array.shape()};
205 const auto &lbounds{array.lbounds()};
206 int rank{GetRank(shape)};
207 CHECK(rank ==
static_cast<int>(subscripts.size()));
208 std::size_t elements{1};
209 ConstantSubscripts resultShape;
210 ConstantSubscripts ssLB;
211 for (
const auto &ss : subscripts) {
212 if (ss.Rank() == 1) {
213 resultShape.push_back(
static_cast<ConstantSubscript
>(ss.size()));
214 elements *= ss.size();
215 ssLB.push_back(ss.lbounds().front());
216 }
else if (ss.Rank() > 1) {
220 ConstantSubscripts ssAt(rank, 0), at(rank, 0), tmp(1, 0);
221 std::vector<Scalar<T>> values;
222 while (elements-- > 0) {
223 bool increment{
true};
225 for (
int j{0}; j < rank; ++j) {
226 if (subscripts[j].Rank() == 0) {
227 at[j] = subscripts[j].GetScalarValue().value().ToInt64();
229 CHECK(k < GetRank(resultShape));
230 tmp[0] = ssLB.at(k) + ssAt.at(k);
231 at[j] = subscripts[j].At(tmp).ToInt64();
233 if (++ssAt[k] == resultShape[k]) {
241 if (at[j] < lbounds[j] || at[j] >= lbounds[j] + shape[j]) {
242 context_.messages().Say(
243 "Subscript value (%jd) is out of range on dimension %d in reference to a constant array value"_err_en_US,
248 values.emplace_back(array.At(at));
249 CHECK(!increment || elements == 0);
250 CHECK(k == GetRank(resultShape));
252 if constexpr (T::category == TypeCategory::Character) {
253 return Constant<T>{array.LEN(), std::move(values), std::move(resultShape)};
254 }
else if constexpr (std::is_same_v<T, SomeDerived>) {
255 return Constant<T>{array.result().derivedTypeSpec(), std::move(values),
256 std::move(resultShape)};
258 return Constant<T>{std::move(values), std::move(resultShape)};
263std::optional<Constant<T>> Folder<T>::ApplyComponent(
264 Constant<SomeDerived> &&structures,
const Symbol &component,
265 const std::vector<Constant<SubscriptInteger>> *subscripts) {
266 if (
auto scalar{structures.GetScalarValue()}) {
267 if (std::optional<Expr<SomeType>> expr{scalar->Find(component)}) {
268 if (
const Constant<T> *value{UnwrapConstantValue<T>(*expr)}) {
270 return ApplySubscripts(*value, *subscripts);
278 std::unique_ptr<ArrayConstructor<T>> array;
279 if (structures.empty()) {
282 ConstantSubscripts at{structures.lbounds()};
284 StructureConstructor scalar{structures.At(at)};
285 if (std::optional<Expr<SomeType>> expr{scalar.Find(component)}) {
286 if (
const Constant<T> *value{UnwrapConstantValue<T>(expr.value())}) {
290 auto *typedExpr{UnwrapExpr<Expr<T>>(expr.value())};
292 array = std::make_unique<ArrayConstructor<T>>(*typedExpr);
295 if (
auto element{ApplySubscripts(*value, *subscripts)}) {
296 CHECK(element->Rank() == 0);
297 array->Push(Expr<T>{std::move(*element)});
302 CHECK(value->Rank() == 0);
303 array->Push(Expr<T>{*value});
309 }
while (structures.IncrementSubscripts(at));
312 Expr<T> result{Fold(context_, Expr<T>{std::move(*array)})};
313 if (
auto *constant{UnwrapConstantValue<T>(result)}) {
314 return constant->Reshape(common::Clone(structures.shape()));
321std::optional<Constant<T>> Folder<T>::GetConstantComponent(Component &component,
322 const std::vector<Constant<SubscriptInteger>> *subscripts) {
323 if (std::optional<Constant<SomeDerived>> structures{common::visit(
325 [&](
const Symbol &symbol) {
326 return Folder<SomeDerived>{context_}.GetNamedConstant(symbol);
328 [&](ArrayRef &aRef) {
329 return Folder<SomeDerived>{context_}.Folding(aRef);
331 [&](Component &base) {
332 return Folder<SomeDerived>{context_}.GetConstantComponent(base);
335 return std::optional<Constant<SomeDerived>>{};
338 component.base().u)}) {
339 return ApplyComponent(
340 std::move(*structures), component.GetLastSymbol(), subscripts);
346template <
typename T> Expr<T> Folder<T>::Folding(Designator<T> &&designator) {
347 if constexpr (T::category == TypeCategory::Character) {
348 if (
auto *substring{common::Unwrap<Substring>(designator.u)}) {
349 if (std::optional<Expr<SomeCharacter>> folded{
350 substring->Fold(context_)}) {
351 if (
const auto *specific{std::get_if<Expr<T>>(&folded->u)}) {
352 return std::move(*specific);
359 }
else if constexpr (T::category == TypeCategory::Real) {
360 if (
auto *zPart{std::get_if<ComplexPart>(&designator.u)}) {
361 *zPart = FoldOperation(context_, std::move(*zPart));
362 using ComplexT = Type<TypeCategory::Complex, T::kind>;
363 if (
auto zConst{Folder<ComplexT>{context_}.Folding(zPart->complex())}) {
364 return Fold(context_,
365 Expr<T>{ComplexComponent<T::kind>{
366 zPart->part() == ComplexPart::Part::IM,
367 Expr<ComplexT>{std::move(*zConst)}}});
369 return Expr<T>{Designator<T>{std::move(*zPart)}};
373 return common::visit(
375 [&](SymbolRef &&symbol) {
376 if (
auto constant{GetNamedConstant(*symbol)}) {
377 return Expr<T>{std::move(*constant)};
379 return Expr<T>{std::move(designator)};
381 [&](ArrayRef &&aRef) {
382 aRef = FoldOperation(context_, std::move(aRef));
383 if (
auto c{Folding(aRef)}) {
384 return Expr<T>{std::move(*c)};
386 return Expr<T>{Designator<T>{std::move(aRef)}};
389 [&](Component &&component) {
390 component = FoldOperation(context_, std::move(component));
391 if (
auto c{GetConstantComponent(component)}) {
392 return Expr<T>{std::move(*c)};
394 return Expr<T>{Designator<T>{std::move(component)}};
399 Designator<T>{FoldOperation(context_, std::move(x))}};
402 std::move(designator.u));
408Constant<T> *Folder<T>::Folding(std::optional<ActualArgument> &arg) {
409 if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
410 if constexpr (T::category != TypeCategory::Derived) {
411 if (!UnwrapExpr<Expr<T>>(*expr)) {
413 var{forOptionalArgument_
414 ? UnwrapWholeSymbolOrComponentDataRef(*expr)
416 var && (IsOptional(*var) || IsAllocatableOrObjectPointer(var))) {
418 }
else if (
auto converted{
419 ConvertToType(T::GetType(), std::move(*expr))}) {
420 *expr = Fold(context_, std::move(*converted));
424 return UnwrapConstantValue<T>(*expr);
429template <
typename... A, std::size_t... I>
430std::optional<std::tuple<const Constant<A> *...>> GetConstantArgumentsHelper(
431 FoldingContext &context, ActualArguments &arguments,
432 bool hasOptionalArgument, std::index_sequence<I...>) {
433 static_assert(
sizeof...(A) > 0);
434 std::tuple<const Constant<A> *...> args{
435 Folder<A>{context, hasOptionalArgument}.Folding(arguments.at(I))...};
436 if ((... && (std::get<I>(args)))) {
443template <
typename... A>
444std::optional<std::tuple<const Constant<A> *...>> GetConstantArguments(
445 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument) {
446 return GetConstantArgumentsHelper<A...>(
447 context, args, hasOptionalArgument, std::index_sequence_for<A...>{});
450template <
typename... A, std::size_t... I>
451std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArgumentsHelper(
452 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument,
453 std::index_sequence<I...>) {
455 GetConstantArguments<A...>(context, args, hasOptionalArgument)}) {
456 return std::tuple<Scalar<A>...>{
457 std::get<I>(*constArgs)->GetScalarValue().value()...};
463template <
typename... A>
464std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArguments(
465 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument) {
466 return GetScalarConstantArgumentsHelper<A...>(
467 context, args, hasOptionalArgument, std::index_sequence_for<A...>{});
474template <
typename TR,
typename... TArgs>
475using ScalarFunc = std::function<Scalar<TR>(
const Scalar<TArgs> &...)>;
476template <
typename TR,
typename... TArgs>
477using ScalarFuncWithContext =
478 std::function<Scalar<TR>(FoldingContext &,
const Scalar<TArgs> &...)>;
480template <
template <
typename,
typename...>
typename WrapperType,
typename TR,
481 typename... TA, std::size_t... I>
482Expr<TR> FoldElementalIntrinsicHelper(FoldingContext &context,
483 FunctionRef<TR> &&funcRef, WrapperType<TR, TA...> func,
484 bool hasOptionalArgument, std::index_sequence<I...>) {
485 if (std::optional<std::tuple<
const Constant<TA> *...>> args{
486 GetConstantArguments<TA...>(
487 context, funcRef.arguments(), hasOptionalArgument)}) {
489 ConstantSubscripts shape;
491 const ConstantSubscripts *shapes[]{&std::get<I>(*args)->shape()...};
492 const int ranks[]{std::get<I>(*args)->Rank()...};
493 for (
unsigned int i{0}; i <
sizeof...(TA); ++i) {
499 if (shape != *shapes[i]) {
504 context.messages().Say(
505 "Arguments in elemental intrinsic function are not conformable"_err_en_US);
506 return Expr<TR>{std::move(funcRef)};
511 CHECK(rank == GetRank(shape));
513 std::vector<Scalar<TR>> results;
514 std::optional<uint64_t> n{TotalElementCount(shape)};
516 context.messages().Say(
517 "Too many elements in elemental intrinsic function result"_err_en_US);
518 return Expr<TR>{std::move(funcRef)};
521 ConstantBounds bounds{shape};
522 ConstantSubscripts resultIndex(rank, 1);
523 ConstantSubscripts argIndex[]{std::get<I>(*args)->lbounds()...};
525 if constexpr (std::is_same_v<WrapperType<TR, TA...>,
526 ScalarFuncWithContext<TR, TA...>>) {
527 results.emplace_back(
528 func(context, std::get<I>(*args)->At(argIndex[I])...));
529 }
else if constexpr (std::is_same_v<WrapperType<TR, TA...>,
530 ScalarFunc<TR, TA...>>) {
531 results.emplace_back(func(std::get<I>(*args)->At(argIndex[I])...));
533 (std::get<I>(*args)->IncrementSubscripts(argIndex[I]), ...);
534 }
while (bounds.IncrementSubscripts(resultIndex));
537 if constexpr (TR::category == TypeCategory::Character) {
538 auto len{
static_cast<ConstantSubscript
>(
539 results.empty() ? 0 : results[0].length())};
540 return Expr<TR>{Constant<TR>{len, std::move(results), std::move(shape)}};
541 }
else if constexpr (TR::category == TypeCategory::Derived) {
542 if (!results.empty()) {
543 return Expr<TR>{rank == 0
544 ? Constant<TR>{results.front()}
545 : Constant<TR>{results.front().derivedTypeSpec(),
546 std::move(results), std::move(shape)}};
549 return Expr<TR>{Constant<TR>{std::move(results), std::move(shape)}};
552 return Expr<TR>{std::move(funcRef)};
555template <
typename TR,
typename... TA>
556Expr<TR> FoldElementalIntrinsic(FoldingContext &context,
557 FunctionRef<TR> &&funcRef, ScalarFunc<TR, TA...> func,
558 bool hasOptionalArgument =
false) {
559 return FoldElementalIntrinsicHelper<ScalarFunc, TR, TA...>(context,
560 std::move(funcRef), func, hasOptionalArgument,
561 std::index_sequence_for<TA...>{});
563template <
typename TR,
typename... TA>
564Expr<TR> FoldElementalIntrinsic(FoldingContext &context,
565 FunctionRef<TR> &&funcRef, ScalarFuncWithContext<TR, TA...> func,
566 bool hasOptionalArgument =
false) {
567 return FoldElementalIntrinsicHelper<ScalarFuncWithContext, TR, TA...>(context,
568 std::move(funcRef), func, hasOptionalArgument,
569 std::index_sequence_for<TA...>{});
572std::optional<std::int64_t> GetInt64ArgOr(
573 const std::optional<ActualArgument> &, std::int64_t defaultValue);
575template <
typename A,
typename B>
576std::optional<std::vector<A>> GetIntegerVector(
const B &x) {
577 static_assert(std::is_integral_v<A>);
578 if (
const auto *someInteger{UnwrapExpr<Expr<SomeInteger>>(x)}) {
579 return common::visit(
580 [](
const auto &typedExpr) -> std::optional<std::vector<A>> {
581 using T = ResultType<
decltype(typedExpr)>;
582 if (
const auto *constant{UnwrapConstantValue<T>(typedExpr)}) {
583 if (constant->Rank() == 1) {
584 std::vector<A> result;
585 for (
const auto &value : constant->values()) {
586 result.push_back(
static_cast<A
>(value.ToInt64()));
602template <
typename T> Expr<T> MakeInvalidIntrinsic(FunctionRef<T> &&funcRef) {
603 SpecificIntrinsic invalid{std::get<SpecificIntrinsic>(funcRef.proc().u)};
604 invalid.name = IntrinsicProcTable::InvalidName;
605 return Expr<T>{FunctionRef<T>{ProcedureDesignator{std::move(invalid)},
606 ActualArguments{std::move(funcRef.arguments())}}};
609template <
typename T> Expr<T> Folder<T>::CSHIFT(FunctionRef<T> &&funcRef) {
610 auto args{funcRef.arguments()};
611 CHECK(args.size() == 3);
612 const auto *array{UnwrapConstantValue<T>(args[0])};
613 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
614 auto dim{GetInt64ArgOr(args[2], 1)};
615 if (!array || !shiftExpr || !dim) {
616 return Expr<T>{std::move(funcRef)};
618 auto convertedShift{Fold(context_,
619 ConvertToType<SubscriptInteger>(Expr<SomeInteger>{*shiftExpr}))};
620 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
622 return Expr<T>{std::move(funcRef)};
625 if (*dim < 1 || *dim > array->Rank()) {
626 context_.messages().Say(
"Invalid 'dim=' argument (%jd) in CSHIFT"_err_en_US,
627 static_cast<std::intmax_t
>(*dim));
628 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
631 int rank{array->Rank()};
632 int zbDim{
static_cast<int>(*dim) - 1};
634 if (shift->Rank() > 0) {
636 for (
int j{0}; j < rank; ++j) {
638 if (array->shape()[j] != shift->shape()[k]) {
639 context_.messages().Say(
640 "Invalid 'shift=' argument in CSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
641 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
642 static_cast<std::intmax_t
>(array->shape()[j]));
650 std::vector<Scalar<T>> resultElements;
651 ConstantSubscripts arrayLB{array->lbounds()};
652 ConstantSubscripts arrayAt{arrayLB};
653 ConstantSubscript &dimIndex{arrayAt[zbDim]};
654 ConstantSubscript dimLB{dimIndex};
655 ConstantSubscript dimExtent{array->shape()[zbDim]};
656 ConstantSubscripts shiftLB{shift->lbounds()};
657 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
658 ConstantSubscript origDimIndex{dimIndex};
659 ConstantSubscripts shiftAt;
660 if (shift->Rank() > 0) {
662 for (
int j{0}; j < rank; ++j) {
664 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
668 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
669 dimIndex = dimLB + ((dimIndex - dimLB + shiftCount) % dimExtent);
670 if (dimIndex < dimLB) {
671 dimIndex += dimExtent;
672 }
else if (dimIndex >= dimLB + dimExtent) {
673 dimIndex -= dimExtent;
675 resultElements.push_back(array->At(arrayAt));
676 dimIndex = origDimIndex;
677 array->IncrementSubscripts(arrayAt);
679 return Expr<T>{PackageConstant<T>(
680 std::move(resultElements), *array, array->shape())};
684 return MakeInvalidIntrinsic(std::move(funcRef));
687template <
typename T> Expr<T> Folder<T>::EOSHIFT(FunctionRef<T> &&funcRef) {
688 auto args{funcRef.arguments()};
689 CHECK(args.size() == 4);
690 const auto *array{UnwrapConstantValue<T>(args[0])};
691 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
692 auto dim{GetInt64ArgOr(args[3], 1)};
693 if (!array || !shiftExpr || !dim) {
694 return Expr<T>{std::move(funcRef)};
697 auto convertedShift{Fold(context_,
698 ConvertToType<SubscriptInteger>(Expr<SomeInteger>{*shiftExpr}))};
699 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
701 return Expr<T>{std::move(funcRef)};
703 const Constant<T> *boundary{
nullptr};
704 std::optional<Expr<SomeType>> convertedBoundary;
705 if (
const auto *boundaryExpr{UnwrapExpr<Expr<SomeType>>(args[2])}) {
706 convertedBoundary = Fold(context_,
707 ConvertToType(array->GetType(), Expr<SomeType>{*boundaryExpr}));
708 boundary = UnwrapExpr<Constant<T>>(convertedBoundary);
710 return Expr<T>{std::move(funcRef)};
714 if (*dim < 1 || *dim > array->Rank()) {
715 context_.messages().Say(
716 "Invalid 'dim=' argument (%jd) in EOSHIFT"_err_en_US,
717 static_cast<std::intmax_t
>(*dim));
718 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
720 }
else if (boundary && boundary->Rank() > 0 &&
721 boundary->Rank() != array->Rank() - 1) {
724 int rank{array->Rank()};
725 int zbDim{
static_cast<int>(*dim) - 1};
727 if (shift->Rank() > 0) {
729 for (
int j{0}; j < rank; ++j) {
731 if (array->shape()[j] != shift->shape()[k]) {
732 context_.messages().Say(
733 "Invalid 'shift=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
734 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
735 static_cast<std::intmax_t
>(array->shape()[j]));
742 if (boundary && boundary->Rank() > 0) {
744 for (
int j{0}; j < rank; ++j) {
746 if (array->shape()[j] != boundary->shape()[k]) {
747 context_.messages().Say(
748 "Invalid 'boundary=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
749 k + 1,
static_cast<std::intmax_t
>(boundary->shape()[k]),
750 static_cast<std::intmax_t
>(array->shape()[j]));
758 std::vector<Scalar<T>> resultElements;
759 ConstantSubscripts arrayLB{array->lbounds()};
760 ConstantSubscripts arrayAt{arrayLB};
761 ConstantSubscript &dimIndex{arrayAt[zbDim]};
762 ConstantSubscript dimLB{dimIndex};
763 ConstantSubscript dimExtent{array->shape()[zbDim]};
764 ConstantSubscripts shiftLB{shift->lbounds()};
765 ConstantSubscripts boundaryLB;
767 boundaryLB = boundary->lbounds();
769 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
770 ConstantSubscript origDimIndex{dimIndex};
771 ConstantSubscripts shiftAt;
772 if (shift->Rank() > 0) {
774 for (
int j{0}; j < rank; ++j) {
776 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
780 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
781 dimIndex += shiftCount;
782 if (dimIndex >= dimLB && dimIndex < dimLB + dimExtent) {
783 resultElements.push_back(array->At(arrayAt));
784 }
else if (boundary) {
785 ConstantSubscripts boundaryAt;
786 if (boundary->Rank() > 0) {
787 for (
int j{0}; j < rank; ++j) {
790 boundaryAt.emplace_back(
791 boundaryLB[k++] + arrayAt[j] - arrayLB[j]);
795 resultElements.push_back(boundary->At(boundaryAt));
796 }
else if constexpr (T::category == TypeCategory::Integer ||
797 T::category == TypeCategory::Unsigned ||
798 T::category == TypeCategory::Real ||
799 T::category == TypeCategory::Complex ||
800 T::category == TypeCategory::Logical) {
801 resultElements.emplace_back();
802 }
else if constexpr (T::category == TypeCategory::Character) {
803 auto len{
static_cast<std::size_t
>(array->LEN())};
804 typename Scalar<T>::value_type space{
' '};
805 resultElements.emplace_back(len, space);
807 DIE(
"no derived type boundary");
809 dimIndex = origDimIndex;
810 array->IncrementSubscripts(arrayAt);
812 return Expr<T>{PackageConstant<T>(
813 std::move(resultElements), *array, array->shape())};
817 return MakeInvalidIntrinsic(std::move(funcRef));
820template <
typename T> Expr<T> Folder<T>::MERGE(FunctionRef<T> &&funcRef) {
821 return FoldElementalIntrinsic<T, T, T, LogicalResult>(context_,
823 ScalarFunc<T, T, T, LogicalResult>(
824 [](
const Scalar<T> &ifTrue,
const Scalar<T> &ifFalse,
825 const Scalar<LogicalResult> &predicate) -> Scalar<T> {
826 return predicate.IsTrue() ? ifTrue : ifFalse;
830template <
typename T> Expr<T> Folder<T>::PACK(FunctionRef<T> &&funcRef) {
831 auto args{funcRef.arguments()};
832 CHECK(args.size() == 3);
833 const auto *array{UnwrapConstantValue<T>(args[0])};
834 const auto *vector{UnwrapConstantValue<T>(args[2])};
835 auto convertedMask{Fold(context_,
836 ConvertToType<LogicalResult>(
837 Expr<SomeLogical>{DEREF(UnwrapExpr<Expr<SomeLogical>>(args[1]))}))};
838 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
839 if (!array || !mask || (args[2] && !vector)) {
840 return Expr<T>{std::move(funcRef)};
843 ConstantSubscript arrayElements{GetSize(array->shape())};
844 ConstantSubscript truths{0};
845 ConstantSubscripts maskAt{mask->lbounds()};
846 if (mask->Rank() == 0) {
847 if (mask->At(maskAt).IsTrue()) {
848 truths = arrayElements;
850 }
else if (array->shape() != mask->shape()) {
852 return MakeInvalidIntrinsic(std::move(funcRef));
854 for (ConstantSubscript j{0}; j < arrayElements;
855 ++j, mask->IncrementSubscripts(maskAt)) {
856 if (mask->At(maskAt).IsTrue()) {
861 std::vector<Scalar<T>> resultElements;
862 ConstantSubscripts arrayAt{array->lbounds()};
863 ConstantSubscript resultSize{truths};
865 resultSize = vector->shape().at(0);
866 if (resultSize < truths) {
867 context_.messages().Say(
868 "Invalid 'vector=' argument in PACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
869 static_cast<std::intmax_t
>(truths),
870 static_cast<std::intmax_t
>(resultSize));
871 return MakeInvalidIntrinsic(std::move(funcRef));
874 for (ConstantSubscript j{0}; j < truths;) {
875 if (mask->At(maskAt).IsTrue()) {
876 resultElements.push_back(array->At(arrayAt));
879 array->IncrementSubscripts(arrayAt);
880 mask->IncrementSubscripts(maskAt);
883 ConstantSubscripts vectorAt{vector->lbounds()};
884 vectorAt.at(0) += truths;
885 for (ConstantSubscript j{truths}; j < resultSize; ++j) {
886 resultElements.push_back(vector->At(vectorAt));
890 return Expr<T>{PackageConstant<T>(std::move(resultElements), *array,
891 ConstantSubscripts{
static_cast<ConstantSubscript
>(resultSize)})};
894template <
typename T> Expr<T> Folder<T>::RESHAPE(FunctionRef<T> &&funcRef) {
895 auto args{funcRef.arguments()};
896 CHECK(args.size() == 4);
897 const auto *source{UnwrapConstantValue<T>(args[0])};
898 const auto *pad{UnwrapConstantValue<T>(args[2])};
899 std::optional<std::vector<ConstantSubscript>> shape{
900 GetIntegerVector<ConstantSubscript>(args[1])};
901 std::optional<std::vector<int>> order{GetIntegerVector<int>(args[3])};
902 std::optional<uint64_t> optResultElement;
903 std::optional<std::vector<int>> dimOrder;
906 if (shape->size() > common::maxRank) {
907 context_.messages().Say(
908 "Size of 'shape=' argument (%zd) must not be greater than %d"_err_en_US,
909 shape->size(), common::maxRank);
911 }
else if (HasNegativeExtent(*shape)) {
912 context_.messages().Say(
913 "'shape=' argument (%s) must not have a negative extent"_err_en_US,
914 DEREF(args[1]->UnwrapExpr()).AsFortran());
917 optResultElement = TotalElementCount(*shape);
918 if (!optResultElement) {
919 context_.messages().Say(
920 "'shape=' argument (%s) specifies an array with too many elements"_err_en_US,
921 DEREF(args[1]->UnwrapExpr()).AsFortran());
926 dimOrder = ValidateDimensionOrder(GetRank(*shape), *order);
928 context_.messages().Say(
929 "Invalid 'order=' argument (%s) in RESHAPE"_err_en_US,
930 DEREF(args[3]->UnwrapExpr()).AsFortran());
937 }
else if (!source || !shape || (args[2] && !pad) || (args[3] && !order)) {
938 return Expr<T>{std::move(funcRef)};
940 uint64_t resultElements{*optResultElement};
941 std::vector<int> *dimOrderPtr{dimOrder ? &dimOrder.value() :
nullptr};
942 if (resultElements > source->size() && (!pad || pad->empty())) {
943 context_.messages().Say(
944 "Too few elements in 'source=' argument and 'pad=' "
945 "argument is not present or has null size"_err_en_US);
948 Constant<T> result{!source->empty() || !pad
949 ? source->Reshape(std::move(shape.value()))
950 : pad->Reshape(std::move(shape.value()))};
951 ConstantSubscripts subscripts{result.lbounds()};
952 auto copied{result.CopyFrom(*source,
953 std::min(
static_cast<uint64_t
>(source->size()), resultElements),
954 subscripts, dimOrderPtr)};
955 if (copied < resultElements) {
957 copied += result.CopyFrom(
958 *pad, resultElements - copied, subscripts, dimOrderPtr);
960 CHECK(copied == resultElements);
961 return Expr<T>{std::move(result)};
965 return MakeInvalidIntrinsic(std::move(funcRef));
968template <
typename T> Expr<T> Folder<T>::SPREAD(FunctionRef<T> &&funcRef) {
969 auto args{funcRef.arguments()};
970 CHECK(args.size() == 3);
971 const Constant<T> *source{UnwrapConstantValue<T>(args[0])};
972 auto dim{ToInt64(args[1])};
973 auto ncopies{ToInt64(args[2])};
974 if (!source || !dim) {
975 return Expr<T>{std::move(funcRef)};
977 int sourceRank{source->Rank()};
978 if (sourceRank >= common::maxRank) {
979 context_.messages().Say(
980 "SOURCE= argument to SPREAD has rank %d but must have rank less than %d"_err_en_US,
981 sourceRank, common::maxRank);
982 }
else if (*dim < 1 || *dim > sourceRank + 1) {
983 context_.messages().Say(
984 "DIM=%d argument to SPREAD must be between 1 and %d"_err_en_US, *dim,
986 }
else if (!ncopies) {
987 return Expr<T>{std::move(funcRef)};
997 ConstantSubscripts shape{source->shape()};
998 shape.insert(shape.begin() + *dim - 1, *ncopies);
999 Constant<T> spread{source->Reshape(std::move(shape))};
1000 std::optional<uint64_t> n{TotalElementCount(spread.shape())};
1002 context_.messages().Say(
"Too many elements in SPREAD result"_err_en_US);
1004 std::vector<int> dimOrder;
1005 for (
int j{0}; j < sourceRank; ++j) {
1006 dimOrder.push_back(j < *dim - 1 ? j : j + 1);
1008 dimOrder.push_back(*dim - 1);
1009 ConstantSubscripts at{spread.lbounds()};
1010 spread.CopyFrom(*source, *n, at, &dimOrder);
1011 return Expr<T>{std::move(spread)};
1015 return MakeInvalidIntrinsic(std::move(funcRef));
1018template <
typename T> Expr<T> Folder<T>::TRANSPOSE(FunctionRef<T> &&funcRef) {
1019 auto args{funcRef.arguments()};
1020 CHECK(args.size() == 1);
1021 const auto *matrix{UnwrapConstantValue<T>(args[0])};
1023 return Expr<T>{std::move(funcRef)};
1026 std::vector<Scalar<T>> resultElements;
1027 ConstantSubscripts at(2);
1028 for (ConstantSubscript j{0}; j < matrix->shape()[0]; ++j) {
1029 at[0] = matrix->lbounds()[0] + j;
1030 for (ConstantSubscript k{0}; k < matrix->shape()[1]; ++k) {
1031 at[1] = matrix->lbounds()[1] + k;
1032 resultElements.push_back(matrix->At(at));
1035 at = matrix->shape();
1036 std::swap(at[0], at[1]);
1037 return Expr<T>{PackageConstant<T>(std::move(resultElements), *matrix, at)};
1040template <
typename T> Expr<T> Folder<T>::UNPACK(FunctionRef<T> &&funcRef) {
1041 auto args{funcRef.arguments()};
1042 CHECK(args.size() == 3);
1043 const auto *vector{UnwrapConstantValue<T>(args[0])};
1044 auto convertedMask{Fold(context_,
1045 ConvertToType<LogicalResult>(
1046 Expr<SomeLogical>{DEREF(UnwrapExpr<Expr<SomeLogical>>(args[1]))}))};
1047 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
1048 const auto *field{UnwrapConstantValue<T>(args[2])};
1049 if (!vector || !mask || !field) {
1050 return Expr<T>{std::move(funcRef)};
1053 if (field->Rank() > 0 && field->shape() != mask->shape()) {
1055 return MakeInvalidIntrinsic(std::move(funcRef));
1057 ConstantSubscript maskElements{GetSize(mask->shape())};
1058 ConstantSubscript truths{0};
1059 ConstantSubscripts maskAt{mask->lbounds()};
1060 for (ConstantSubscript j{0}; j < maskElements;
1061 ++j, mask->IncrementSubscripts(maskAt)) {
1062 if (mask->At(maskAt).IsTrue()) {
1066 if (truths > GetSize(vector->shape())) {
1067 context_.messages().Say(
1068 "Invalid 'vector=' argument in UNPACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
1069 static_cast<std::intmax_t
>(truths),
1070 static_cast<std::intmax_t
>(GetSize(vector->shape())));
1071 return MakeInvalidIntrinsic(std::move(funcRef));
1073 std::vector<Scalar<T>> resultElements;
1074 ConstantSubscripts vectorAt{vector->lbounds()};
1075 ConstantSubscripts fieldAt{field->lbounds()};
1076 for (ConstantSubscript j{0}; j < maskElements; ++j) {
1077 if (mask->At(maskAt).IsTrue()) {
1078 resultElements.push_back(vector->At(vectorAt));
1079 vector->IncrementSubscripts(vectorAt);
1081 resultElements.push_back(field->At(fieldAt));
1083 mask->IncrementSubscripts(maskAt);
1084 field->IncrementSubscripts(fieldAt);
1087 PackageConstant<T>(std::move(resultElements), *vector, mask->shape())};
1090std::optional<Expr<SomeType>> FoldTransfer(
1091 FoldingContext &,
const ActualArguments &);
1093template <
typename T> Expr<T> Folder<T>::TRANSFER(FunctionRef<T> &&funcRef) {
1094 if (
auto folded{FoldTransfer(context_, funcRef.arguments())}) {
1095 return DEREF(UnwrapExpr<Expr<T>>(*folded));
1097 return Expr<T>{std::move(funcRef)};
1101template <
typename T>
1102Expr<T> FoldMINorMAX(
1103 FoldingContext &context, FunctionRef<T> &&funcRef, Ordering order) {
1104 static_assert(T::category == TypeCategory::Integer ||
1105 T::category == TypeCategory::Unsigned ||
1106 T::category == TypeCategory::Real ||
1107 T::category == TypeCategory::Character);
1108 auto &args{funcRef.arguments()};
1110 std::optional<Expr<T>> result;
1111 Folder<T> folder{context};
1112 for (std::optional<ActualArgument> &arg : args) {
1114 if (!folder.Folding(arg)) {
1124 if (!context.moduleFileName()) {
1128 Expr<SomeType> *argExpr{arg ? arg->UnwrapExpr() :
nullptr};
1130 *argExpr = Fold(context, std::move(*argExpr));
1132 if (Expr<T> * tExpr{UnwrapExpr<Expr<T>>(argExpr)}) {
1134 result = FoldOperation(
1135 context, Extremum<T>{order, std::move(*result), Expr<T>{*tExpr}});
1137 result = Expr<T>{*tExpr};
1143 return ok && result ? std::move(*result) : Expr<T>{std::move(funcRef)};
1153template <
typename T>
1154Expr<T> RewriteSpecificMINorMAX(
1155 FoldingContext &context, FunctionRef<T> &&funcRef) {
1156 ActualArguments &args{funcRef.arguments()};
1157 auto &intrinsic{DEREF(std::get_if<SpecificIntrinsic>(&funcRef.proc().u))};
1160 std::optional<DynamicType> resultType;
1161 ActualArgument *resultTypeArg{
nullptr};
1162 for (
auto j{args.size()}; j-- > 0;) {
1164 DynamicType type{args[j]->GetType().value()};
1169 (type.category() == resultType->category() &&
1170 type.kind() > resultType->kind()) ||
1171 resultType->category() == TypeCategory::Integer) {
1173 resultTypeArg = &*args[j];
1178 return Expr<T>{std::move(funcRef)};
1181 intrinsic.name.find(
"max") != std::string::npos ?
"max"s :
"min"s;
1182 intrinsic.characteristics.value().functionResult.value().SetType(*resultType);
1183 auto insertConversion{[&](
const auto &x) -> Expr<T> {
1184 using TR = ResultType<
decltype(x)>;
1185 FunctionRef<TR> maxRef{
1186 ProcedureDesignator{funcRef.proc()}, ActualArguments{args}};
1187 return Fold(context, ConvertToType<T>(AsCategoryExpr(std::move(maxRef))));
1189 if (
auto *sx{UnwrapExpr<Expr<SomeReal>>(*resultTypeArg)}) {
1190 return common::visit(insertConversion, sx->u);
1191 }
else if (
auto *sx{UnwrapExpr<Expr<SomeInteger>>(*resultTypeArg)}) {
1192 return common::visit(insertConversion, sx->u);
1194 return Expr<T>{std::move(funcRef)};
1200Expr<Type<TypeCategory::Integer, KIND>> FoldIntrinsicFunction(
1201 FoldingContext &context, FunctionRef<Type<TypeCategory::Integer, KIND>> &&);
1203Expr<Type<TypeCategory::Unsigned, KIND>> FoldIntrinsicFunction(
1204 FoldingContext &context,
1205 FunctionRef<Type<TypeCategory::Unsigned, KIND>> &&);
1207Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
1208 FoldingContext &context, FunctionRef<Type<TypeCategory::Real, KIND>> &&);
1210Expr<Type<TypeCategory::Complex, KIND>> FoldIntrinsicFunction(
1211 FoldingContext &context, FunctionRef<Type<TypeCategory::Complex, KIND>> &&);
1213Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
1214 FoldingContext &context, FunctionRef<Type<TypeCategory::Logical, KIND>> &&);
1216template <
typename T>
1217Expr<T> FoldOperation(FoldingContext &context, FunctionRef<T> &&funcRef) {
1218 ActualArguments &args{funcRef.arguments()};
1219 const auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
1220 if (!intrinsic || intrinsic->name !=
"kind") {
1223 for (std::optional<ActualArgument> &arg : args) {
1224 if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
1225 *expr = Fold(context, std::move(*expr));
1230 const std::string name{intrinsic->name};
1231 if (name ==
"cshift") {
1232 return Folder<T>{context}.CSHIFT(std::move(funcRef));
1233 }
else if (name ==
"eoshift") {
1234 return Folder<T>{context}.EOSHIFT(std::move(funcRef));
1235 }
else if (name ==
"merge") {
1236 return Folder<T>{context}.MERGE(std::move(funcRef));
1237 }
else if (name ==
"pack") {
1238 return Folder<T>{context}.PACK(std::move(funcRef));
1239 }
else if (name ==
"reshape") {
1240 return Folder<T>{context}.RESHAPE(std::move(funcRef));
1241 }
else if (name ==
"spread") {
1242 return Folder<T>{context}.SPREAD(std::move(funcRef));
1243 }
else if (name ==
"transfer") {
1244 return Folder<T>{context}.TRANSFER(std::move(funcRef));
1245 }
else if (name ==
"transpose") {
1246 return Folder<T>{context}.TRANSPOSE(std::move(funcRef));
1247 }
else if (name ==
"unpack") {
1248 return Folder<T>{context}.UNPACK(std::move(funcRef));
1251 if constexpr (!std::is_same_v<T, SomeDerived>) {
1252 return FoldIntrinsicFunction(context, std::move(funcRef));
1255 return Expr<T>{std::move(funcRef)};
1258Expr<ImpliedDoIndex::Result> FoldOperation(FoldingContext &, ImpliedDoIndex &&);
1267 if (FoldArray(array)) {
1268 auto n{
static_cast<ConstantSubscript
>(elements_.size())};
1269 if constexpr (std::is_same_v<T, SomeDerived>) {
1271 std::move(elements_), ConstantSubscripts{n}}};
1272 }
else if constexpr (T::category == TypeCategory::Character) {
1273 if (
const auto *len{array.LEN()}) {
1274 auto length{Fold(context_, common::Clone(*len))};
1275 if (std::optional<ConstantSubscript> lengthValue{ToInt64(length)}) {
1277 *lengthValue, std::move(elements_), ConstantSubscripts{n}}};
1282 Constant<T>{std::move(elements_), ConstantSubscripts{n}}};
1285 return Expr<T>{std::move(array)};
1289 bool FoldArray(
const Expr<T> &expr) {
1290 Expr<T> folded{Fold(context_, common::Clone(expr))};
1291 if (
const auto *c{UnwrapConstantValue<T>(folded)}) {
1294 ConstantSubscripts index{c->lbounds()};
1296 elements_.emplace_back(c->At(index));
1297 }
while (c->IncrementSubscripts(index));
1305 return FoldArray(expr.value());
1314 std::optional<ConstantSubscript> start{ToInt64(lower)}, end{ToInt64(upper)},
1315 step{ToInt64(stride)};
1316 if (start && end && step && *step != 0) {
1318 ConstantSubscript &j{context_.StartImpliedDo(iDo.name(), *start)};
1320 for (; j <= *end; j += *step) {
1321 result &= FoldArray(iDo.values());
1324 for (; j >= *end; j += *step) {
1325 result &= FoldArray(iDo.values());
1328 context_.EndImpliedDo(iDo.name());
1335 return common::visit([&](
const auto &y) {
return FoldArray(y); }, x.u);
1338 for (
const auto &x : xs) {
1339 if (!FoldArray(x)) {
1347 std::vector<Scalar<T>> elements_;
1350template <
typename T>
1363template <
typename T>
1364bool ArrayConstructorIsFlat(
const ArrayConstructorValues<T> &values) {
1365 for (
const ArrayConstructorValue<T> &x : values) {
1366 if (!std::holds_alternative<Expr<T>>(x.u)) {
1373template <
typename T>
1374std::optional<Expr<T>> AsFlatArrayConstructor(
const Expr<T> &expr) {
1375 if (
const auto *c{UnwrapConstantValue<T>(expr)}) {
1376 ArrayConstructor<T> result{expr};
1378 ConstantSubscripts at{c->lbounds()};
1380 result.Push(Expr<T>{Constant<T>{c->At(at)}});
1381 }
while (c->IncrementSubscripts(at));
1383 return std::make_optional<Expr<T>>(std::move(result));
1384 }
else if (
const auto *a{UnwrapExpr<ArrayConstructor<T>>(expr)}) {
1385 if (ArrayConstructorIsFlat(*a)) {
1386 return std::make_optional<Expr<T>>(expr);
1388 }
else if (
const auto *p{UnwrapExpr<Parentheses<T>>(expr)}) {
1389 return AsFlatArrayConstructor(Expr<T>{p->left()});
1391 return std::nullopt;
1394template <TypeCategory CAT>
1395std::enable_if_t<CAT != TypeCategory::Derived,
1396 std::optional<Expr<SomeKind<CAT>>>>
1397AsFlatArrayConstructor(
const Expr<SomeKind<CAT>> &expr) {
1398 return common::visit(
1399 [&](
const auto &kindExpr) -> std::optional<Expr<SomeKind<CAT>>> {
1400 if (
auto flattened{AsFlatArrayConstructor(kindExpr)}) {
1401 return Expr<SomeKind<CAT>>{std::move(*flattened)};
1403 return std::nullopt;
1413template <
typename T>
1414std::optional<Expr<T>> FromArrayConstructor(
1415 FoldingContext &context, ArrayConstructor<T> &&values,
const Shape &shape) {
1416 if (
auto constShape{AsConstantExtents(context, shape)};
1417 constShape && !HasNegativeExtent(*constShape)) {
1418 Expr<T> result{Fold(context, Expr<T>{std::move(values)})};
1419 if (
auto *constant{UnwrapConstantValue<T>(result)}) {
1421 return Expr<T>{constant->Reshape(std::move(*constShape))};
1423 if (constShape->size() == 1) {
1424 if (
auto elements{GetShape(context, result)}) {
1425 if (
auto constElements{AsConstantExtents(context, *elements)}) {
1426 if (constElements->size() == 1 &&
1427 constElements->at(0) == constShape->at(0)) {
1430 return std::move(result);
1436 return std::nullopt;
1447template <
typename RESULT,
typename OPERAND>
1448std::optional<Expr<RESULT>> MapOperation(FoldingContext &context,
1449 std::function<Expr<RESULT>(Expr<OPERAND> &&)> &&f,
const Shape &shape,
1450 [[maybe_unused]] std::optional<Expr<SubscriptInteger>> &&length,
1451 Expr<OPERAND> &&values) {
1452 ArrayConstructor<RESULT> result{values};
1453 if constexpr (common::HasMember<OPERAND, AllIntrinsicCategoryTypes>) {
1455 [&](
auto &&kindExpr) {
1456 using kindType = ResultType<
decltype(kindExpr)>;
1457 auto &aConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1458 for (
auto &acValue : aConst) {
1459 auto &scalar{std::get<Expr<kindType>>(acValue.u)};
1460 result.Push(Fold(context, f(Expr<OPERAND>{std::move(scalar)})));
1463 std::move(values.u));
1465 auto &aConst{std::get<ArrayConstructor<OPERAND>>(values.u)};
1466 for (
auto &acValue : aConst) {
1467 auto &scalar{std::get<Expr<OPERAND>>(acValue.u)};
1468 result.Push(Fold(context, f(std::move(scalar))));
1471 if constexpr (RESULT::category == TypeCategory::Character) {
1473 result.set_LEN(std::move(*length));
1476 return FromArrayConstructor(context, std::move(result), shape);
1479template <
typename RESULT,
typename A>
1480ArrayConstructor<RESULT> ArrayConstructorFromMold(
1481 const A &prototype, std::optional<Expr<SubscriptInteger>> &&length) {
1482 ArrayConstructor<RESULT> result{prototype};
1483 if constexpr (RESULT::category == TypeCategory::Character) {
1485 result.set_LEN(std::move(*length));
1491template <
typename LEFT,
typename RIGHT>
1492bool ShapesMatch(FoldingContext &context,
1493 const ArrayConstructor<LEFT> &leftArrConst,
1494 const ArrayConstructor<RIGHT> &rightArrConst) {
1495 auto rightIter{rightArrConst.begin()};
1496 for (
auto &leftValue : leftArrConst) {
1497 CHECK(rightIter != rightArrConst.end());
1498 auto &leftExpr{std::get<Expr<LEFT>>(leftValue.u)};
1499 auto &rightExpr{std::get<Expr<RIGHT>>(rightIter->u)};
1500 if (leftExpr.Rank() != rightExpr.Rank()) {
1503 std::optional<Shape> leftShape{GetShape(context, leftExpr)};
1504 std::optional<Shape> rightShape{GetShape(context, rightExpr)};
1505 if (!leftShape || !rightShape || *leftShape != *rightShape) {
1514template <
typename RESULT,
typename LEFT,
typename RIGHT>
1515auto MapOperation(FoldingContext &context,
1516 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f,
1517 const Shape &shape, std::optional<Expr<SubscriptInteger>> &&length,
1518 Expr<LEFT> &&leftValues, Expr<RIGHT> &&rightValues)
1519 -> std::optional<Expr<RESULT>> {
1520 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1521 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1522 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1523 bool mapped{common::visit(
1524 [&](
auto &&kindExpr) ->
bool {
1525 using kindType = ResultType<
decltype(kindExpr)>;
1527 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1528 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1531 auto rightIter{rightArrConst.begin()};
1532 for (
auto &leftValue : leftArrConst) {
1533 CHECK(rightIter != rightArrConst.end());
1534 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1535 auto &rightScalar{std::get<Expr<kindType>>(rightIter->u)};
1536 result.Push(Fold(context,
1537 f(std::move(leftScalar), Expr<RIGHT>{std::move(rightScalar)})));
1542 std::move(rightValues.u))};
1544 return std::nullopt;
1547 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1548 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1549 return std::nullopt;
1551 auto rightIter{rightArrConst.begin()};
1552 for (
auto &leftValue : leftArrConst) {
1553 CHECK(rightIter != rightArrConst.end());
1554 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1555 auto &rightScalar{std::get<Expr<RIGHT>>(rightIter->u)};
1557 Fold(context, f(std::move(leftScalar), std::move(rightScalar))));
1561 return FromArrayConstructor(context, std::move(result), shape);
1565template <
typename RESULT,
typename LEFT,
typename RIGHT>
1566auto MapOperation(FoldingContext &context,
1567 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f,
1568 const Shape &shape, std::optional<Expr<SubscriptInteger>> &&length,
1569 Expr<LEFT> &&leftValues,
const Expr<RIGHT> &rightScalar)
1570 -> std::optional<Expr<RESULT>> {
1571 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1572 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1573 for (
auto &leftValue : leftArrConst) {
1574 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1576 Fold(context, f(std::move(leftScalar), Expr<RIGHT>{rightScalar})));
1578 return FromArrayConstructor(context, std::move(result), shape);
1582template <
typename RESULT,
typename LEFT,
typename RIGHT>
1583auto MapOperation(FoldingContext &context,
1584 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f,
1585 const Shape &shape, std::optional<Expr<SubscriptInteger>> &&length,
1586 const Expr<LEFT> &leftScalar, Expr<RIGHT> &&rightValues)
1587 -> std::optional<Expr<RESULT>> {
1588 auto result{ArrayConstructorFromMold<RESULT>(leftScalar, std::move(length))};
1589 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1591 [&](
auto &&kindExpr) {
1592 using kindType = ResultType<
decltype(kindExpr)>;
1593 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1594 for (
auto &rightValue : rightArrConst) {
1595 auto &rightScalar{std::get<Expr<kindType>>(rightValue.u)};
1596 result.Push(Fold(context,
1597 f(Expr<LEFT>{leftScalar},
1598 Expr<RIGHT>{std::move(rightScalar)})));
1601 std::move(rightValues.u));
1603 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1604 for (
auto &rightValue : rightArrConst) {
1605 auto &rightScalar{std::get<Expr<RIGHT>>(rightValue.u)};
1607 Fold(context, f(Expr<LEFT>{leftScalar}, std::move(rightScalar))));
1610 return FromArrayConstructor(context, std::move(result), shape);
1613template <
typename DERIVED,
typename RESULT,
typename... OPD>
1614std::optional<Expr<SubscriptInteger>> ComputeResultLength(
1615 Operation<DERIVED, RESULT, OPD...> &operation) {
1616 if constexpr (RESULT::category == TypeCategory::Character) {
1617 return Expr<RESULT>{operation.derived()}.LEN();
1619 return std::nullopt;
1626template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1627auto ApplyElementwise(FoldingContext &context,
1628 Operation<DERIVED, RESULT, OPERAND> &operation,
1629 std::function<Expr<RESULT>(Expr<OPERAND> &&)> &&f)
1630 -> std::optional<Expr<RESULT>> {
1631 auto &expr{operation.left()};
1632 expr = Fold(context, std::move(expr));
1633 if (expr.Rank() > 0) {
1634 if (std::optional<Shape> shape{GetShape(context, expr)}) {
1635 if (
auto values{AsFlatArrayConstructor(expr)}) {
1636 return MapOperation(context, std::move(f), *shape,
1637 ComputeResultLength(operation), std::move(*values));
1641 return std::nullopt;
1644template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1645auto ApplyElementwise(
1646 FoldingContext &context, Operation<DERIVED, RESULT, OPERAND> &operation)
1647 -> std::optional<Expr<RESULT>> {
1648 return ApplyElementwise(context, operation,
1649 std::function<Expr<RESULT>(Expr<OPERAND> &&)>{
1650 [](Expr<OPERAND> &&operand) {
1651 return Expr<RESULT>{DERIVED{std::move(operand)}};
1655template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1656auto ApplyElementwise(FoldingContext &context,
1657 Operation<DERIVED, RESULT, LEFT, RIGHT> &operation,
1658 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f)
1659 -> std::optional<Expr<RESULT>> {
1660 auto resultLength{ComputeResultLength(operation)};
1661 auto &leftExpr{operation.left()};
1662 auto &rightExpr{operation.right()};
1663 if (leftExpr.Rank() != rightExpr.Rank() && leftExpr.Rank() != 0 &&
1664 rightExpr.Rank() != 0) {
1665 return std::nullopt;
1667 leftExpr = Fold(context, std::move(leftExpr));
1668 rightExpr = Fold(context, std::move(rightExpr));
1669 if (leftExpr.Rank() > 0) {
1670 if (std::optional<Shape> leftShape{GetShape(context, leftExpr)}) {
1671 if (
auto left{AsFlatArrayConstructor(leftExpr)}) {
1672 if (rightExpr.Rank() > 0) {
1673 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1674 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1675 if (CheckConformance(context.messages(), *leftShape, *rightShape,
1676 CheckConformanceFlags::EitherScalarExpandable)
1677 .value_or(
false )) {
1678 return MapOperation(context, std::move(f), *leftShape,
1679 std::move(resultLength), std::move(*left),
1682 return std::nullopt;
1684 return MapOperation(context, std::move(f), *leftShape,
1685 std::move(resultLength), std::move(*left), std::move(*right));
1688 }
else if (IsExpandableScalar(rightExpr, context, *leftShape)) {
1689 return MapOperation(context, std::move(f), *leftShape,
1690 std::move(resultLength), std::move(*left), rightExpr);
1694 }
else if (rightExpr.Rank() > 0) {
1695 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1696 if (IsExpandableScalar(leftExpr, context, *rightShape)) {
1697 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1698 return MapOperation(context, std::move(f), *rightShape,
1699 std::move(resultLength), leftExpr, std::move(*right));
1704 return std::nullopt;
1707template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1708auto ApplyElementwise(
1709 FoldingContext &context, Operation<DERIVED, RESULT, LEFT, RIGHT> &operation)
1710 -> std::optional<Expr<RESULT>> {
1711 return ApplyElementwise(context, operation,
1712 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)>{
1713 [](Expr<LEFT> &&left, Expr<RIGHT> &&right) {
1714 return Expr<RESULT>{DERIVED{std::move(left), std::move(right)}};
1720template <
typename TO,
typename FROM>
1721common::IfNoLvalue<std::optional<TO>, FROM> ConvertString(FROM &&s) {
1722 if constexpr (std::is_same_v<TO, FROM>) {
1723 return std::make_optional<TO>(std::move(s));
1728 for (
auto iter{s.cbegin()}; iter != s.cend(); ++iter) {
1729 if (
static_cast<std::uint64_t
>(*iter) > 127) {
1730 return std::nullopt;
1732 str.push_back(*iter);
1734 return std::make_optional<TO>(std::move(str));
1738template <
typename TO, TypeCategory FROMCAT>
1739Expr<TO> FoldOperation(
1740 FoldingContext &context, Convert<TO, FROMCAT> &&convert) {
1741 if (
auto array{ApplyElementwise(context, convert)}) {
1745 FoldingContext &context;
1746 Convert<TO, FROMCAT> &convert;
1747 } msvcWorkaround{context, convert};
1748 return common::visit(
1749 [&msvcWorkaround](
auto &kindExpr) -> Expr<TO> {
1750 using Operand = ResultType<
decltype(kindExpr)>;
1753 TypeCategory
constexpr FromCat{FROMCAT};
1754 static_assert(FromCat == Operand::category);
1755 auto &convert{msvcWorkaround.convert};
1756 if (
auto value{GetScalarConstantValue<Operand>(kindExpr)}) {
1757 FoldingContext &ctx{msvcWorkaround.context};
1758 if constexpr (TO::category == TypeCategory::Integer) {
1759 if constexpr (FromCat == TypeCategory::Integer) {
1760 auto converted{Scalar<TO>::ConvertSigned(*value)};
1761 if (converted.overflow &&
1762 msvcWorkaround.context.languageFeatures().ShouldWarn(
1763 common::UsageWarning::FoldingException)) {
1764 ctx.messages().Say(common::UsageWarning::FoldingException,
1765 "conversion of %s_%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1766 value->SignedDecimal(), Operand::kind, TO::kind,
1767 converted.value.SignedDecimal());
1769 return ScalarConstantToExpr(std::move(converted.value));
1770 }
else if constexpr (FromCat == TypeCategory::Unsigned) {
1771 auto converted{Scalar<TO>::ConvertUnsigned(*value)};
1772 if ((converted.overflow || converted.value.IsNegative()) &&
1773 msvcWorkaround.context.languageFeatures().ShouldWarn(
1774 common::UsageWarning::FoldingException)) {
1775 ctx.messages().Say(common::UsageWarning::FoldingException,
1776 "conversion of %s_U%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1777 value->UnsignedDecimal(), Operand::kind, TO::kind,
1778 converted.value.SignedDecimal());
1780 return ScalarConstantToExpr(std::move(converted.value));
1781 }
else if constexpr (FromCat == TypeCategory::Real) {
1782 auto converted{value->template ToInteger<Scalar<TO>>()};
1783 if (msvcWorkaround.context.languageFeatures().ShouldWarn(
1784 common::UsageWarning::FoldingException)) {
1785 if (converted.flags.test(RealFlag::InvalidArgument)) {
1786 ctx.messages().Say(common::UsageWarning::FoldingException,
1787 "REAL(%d) to INTEGER(%d) conversion: invalid argument"_warn_en_US,
1788 Operand::kind, TO::kind);
1789 }
else if (converted.flags.test(RealFlag::Overflow)) {
1791 "REAL(%d) to INTEGER(%d) conversion overflowed"_warn_en_US,
1792 Operand::kind, TO::kind);
1795 return ScalarConstantToExpr(std::move(converted.value));
1797 }
else if constexpr (TO::category == TypeCategory::Unsigned) {
1798 if constexpr (FromCat == TypeCategory::Integer ||
1799 FromCat == TypeCategory::Unsigned) {
1801 Constant<TO>{Scalar<TO>::ConvertUnsigned(*value).value}};
1802 }
else if constexpr (FromCat == TypeCategory::Real) {
1804 Constant<TO>{value->template ToInteger<Scalar<TO>>().value}};
1806 }
else if constexpr (TO::category == TypeCategory::Real) {
1807 if constexpr (FromCat == TypeCategory::Integer ||
1808 FromCat == TypeCategory::Unsigned) {
1809 auto converted{Scalar<TO>::FromInteger(
1810 *value, FromCat == TypeCategory::Unsigned)};
1811 if (!converted.flags.empty()) {
1813 std::snprintf(buffer,
sizeof buffer,
1814 "INTEGER(%d) to REAL(%d) conversion", Operand::kind,
1816 RealFlagWarnings(ctx, converted.flags, buffer);
1818 return ScalarConstantToExpr(std::move(converted.value));
1819 }
else if constexpr (FromCat == TypeCategory::Real) {
1820 auto converted{Scalar<TO>::Convert(*value)};
1822 if (!converted.flags.empty()) {
1823 std::snprintf(buffer,
sizeof buffer,
1824 "REAL(%d) to REAL(%d) conversion", Operand::kind, TO::kind);
1825 RealFlagWarnings(ctx, converted.flags, buffer);
1827 if (ctx.targetCharacteristics().areSubnormalsFlushedToZero()) {
1828 converted.value = converted.value.FlushSubnormalToZero();
1830 return ScalarConstantToExpr(std::move(converted.value));
1832 }
else if constexpr (TO::category == TypeCategory::Complex) {
1833 if constexpr (FromCat == TypeCategory::Complex) {
1834 return FoldOperation(ctx,
1835 ComplexConstructor<TO::kind>{
1836 AsExpr(Convert<typename TO::Part>{AsCategoryExpr(
1837 Constant<typename Operand::Part>{value->REAL()})}),
1838 AsExpr(Convert<typename TO::Part>{AsCategoryExpr(
1839 Constant<typename Operand::Part>{value->AIMAG()})})});
1841 }
else if constexpr (TO::category == TypeCategory::Character &&
1842 FromCat == TypeCategory::Character) {
1843 if (
auto converted{ConvertString<Scalar<TO>>(std::move(*value))}) {
1844 return ScalarConstantToExpr(std::move(*converted));
1846 }
else if constexpr (TO::category == TypeCategory::Logical &&
1847 FromCat == TypeCategory::Logical) {
1848 return Expr<TO>{value->IsTrue()};
1850 }
else if constexpr (TO::category == FromCat &&
1851 FromCat != TypeCategory::Character) {
1853 if constexpr (std::is_same_v<Operand, TO>) {
1854 return std::move(kindExpr);
1855 }
else if constexpr (TO::category == TypeCategory::Logical ||
1856 TO::category == TypeCategory::Integer) {
1857 if (
auto *innerConv{
1858 std::get_if<Convert<Operand, TO::category>>(&kindExpr.u)}) {
1860 if (
auto *x{std::get_if<Expr<TO>>(&innerConv->left().u)}) {
1861 if constexpr (TO::category == TypeCategory::Logical ||
1862 TO::kind <= Operand::kind) {
1863 return std::move(*x);
1865 }
else if constexpr (std::is_same_v<TO,
1866 DescriptorInquiry::Result>) {
1867 if (std::holds_alternative<DescriptorInquiry>(x->u) ||
1868 std::holds_alternative<TypeParamInquiry>(x->u)) {
1870 return std::move(*x);
1877 return Expr<TO>{std::move(convert)};
1882template <
typename T>
1883Expr<T> FoldOperation(FoldingContext &context, Parentheses<T> &&x) {
1884 auto &operand{x.left()};
1885 operand = Fold(context, std::move(operand));
1886 if (
auto value{GetScalarConstantValue<T>(operand)}) {
1888 return Expr<T>{Parentheses<T>{Expr<T>{Constant<T>{*value}}}};
1889 }
else if (std::holds_alternative<Parentheses<T>>(operand.u)) {
1891 return std::move(operand);
1893 return Expr<T>{Parentheses<T>{std::move(operand)}};
1897template <
typename T>
1898Expr<T> FoldOperation(FoldingContext &context, Negate<T> &&x) {
1899 if (
auto array{ApplyElementwise(context, x)}) {
1902 auto &operand{x.left()};
1903 if (
auto *nn{std::get_if<Negate<T>>(&x.left().u)}) {
1905 if (IsVariable(nn->left())) {
1906 return FoldOperation(context, Parentheses<T>{std::move(nn->left())});
1908 return std::move(nn->left());
1910 }
else if (
auto value{GetScalarConstantValue<T>(operand)}) {
1911 if constexpr (T::category == TypeCategory::Integer) {
1912 auto negated{value->Negate()};
1913 if (negated.overflow &&
1914 context.languageFeatures().ShouldWarn(
1915 common::UsageWarning::FoldingException)) {
1916 context.messages().Say(common::UsageWarning::FoldingException,
1917 "INTEGER(%d) negation overflowed"_warn_en_US, T::kind);
1919 return Expr<T>{Constant<T>{std::move(negated.value)}};
1920 }
else if constexpr (T::category == TypeCategory::Unsigned) {
1921 return Expr<T>{Constant<T>{std::move(value->Negate().value)}};
1924 return Expr<T>{Constant<T>{value->Negate()}};
1927 return Expr<T>{std::move(x)};
1932template <
typename LEFT,
typename RIGHT>
1933std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
1934 const Expr<LEFT> &x,
const Expr<RIGHT> &y) {
1935 if (
auto xvalue{GetScalarConstantValue<LEFT>(x)}) {
1936 if (
auto yvalue{GetScalarConstantValue<RIGHT>(y)}) {
1937 return {std::make_pair(*xvalue, *yvalue)};
1940 return std::nullopt;
1943template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1944std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
1945 const Operation<DERIVED, RESULT, LEFT, RIGHT> &operation) {
1946 return OperandsAreConstants(operation.left(), operation.right());
1949template <
typename T>
1950Expr<T> FoldOperation(FoldingContext &context, Add<T> &&x) {
1951 if (
auto array{ApplyElementwise(context, x)}) {
1954 if (
auto folded{OperandsAreConstants(x)}) {
1955 if constexpr (T::category == TypeCategory::Integer) {
1956 auto sum{folded->first.AddSigned(folded->second)};
1958 context.languageFeatures().ShouldWarn(
1959 common::UsageWarning::FoldingException)) {
1960 context.messages().Say(common::UsageWarning::FoldingException,
1961 "INTEGER(%d) addition overflowed"_warn_en_US, T::kind);
1963 return Expr<T>{Constant<T>{sum.value}};
1964 }
else if constexpr (T::category == TypeCategory::Unsigned) {
1966 Constant<T>{folded->first.AddUnsigned(folded->second).value}};
1968 auto sum{folded->first.Add(
1969 folded->second, context.targetCharacteristics().roundingMode())};
1970 RealFlagWarnings(context, sum.flags,
"addition");
1971 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
1972 sum.value = sum.value.FlushSubnormalToZero();
1974 return Expr<T>{Constant<T>{sum.value}};
1977 return Expr<T>{std::move(x)};
1980template <
typename T>
1981Expr<T> FoldOperation(FoldingContext &context, Subtract<T> &&x) {
1982 if (
auto array{ApplyElementwise(context, x)}) {
1985 if (
auto folded{OperandsAreConstants(x)}) {
1986 if constexpr (T::category == TypeCategory::Integer) {
1987 auto difference{folded->first.SubtractSigned(folded->second)};
1988 if (difference.overflow &&
1989 context.languageFeatures().ShouldWarn(
1990 common::UsageWarning::FoldingException)) {
1991 context.messages().Say(common::UsageWarning::FoldingException,
1992 "INTEGER(%d) subtraction overflowed"_warn_en_US, T::kind);
1994 return Expr<T>{Constant<T>{difference.value}};
1995 }
else if constexpr (T::category == TypeCategory::Unsigned) {
1997 Constant<T>{folded->first.SubtractSigned(folded->second).value}};
1999 auto difference{folded->first.Subtract(
2000 folded->second, context.targetCharacteristics().roundingMode())};
2001 RealFlagWarnings(context, difference.flags,
"subtraction");
2002 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2003 difference.value = difference.value.FlushSubnormalToZero();
2005 return Expr<T>{Constant<T>{difference.value}};
2008 return Expr<T>{std::move(x)};
2011template <
typename T>
2012Expr<T> FoldOperation(FoldingContext &context, Multiply<T> &&x) {
2013 if (
auto array{ApplyElementwise(context, x)}) {
2016 if (
auto folded{OperandsAreConstants(x)}) {
2017 if constexpr (T::category == TypeCategory::Integer) {
2018 auto product{folded->first.MultiplySigned(folded->second)};
2019 if (product.SignedMultiplicationOverflowed() &&
2020 context.languageFeatures().ShouldWarn(
2021 common::UsageWarning::FoldingException)) {
2022 context.messages().Say(common::UsageWarning::FoldingException,
2023 "INTEGER(%d) multiplication overflowed"_warn_en_US, T::kind);
2025 return Expr<T>{Constant<T>{product.lower}};
2026 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2028 Constant<T>{folded->first.MultiplyUnsigned(folded->second).lower}};
2030 auto product{folded->first.Multiply(
2031 folded->second, context.targetCharacteristics().roundingMode())};
2032 RealFlagWarnings(context, product.flags,
"multiplication");
2033 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2034 product.value = product.value.FlushSubnormalToZero();
2036 return Expr<T>{Constant<T>{product.value}};
2038 }
else if constexpr (T::category == TypeCategory::Integer) {
2039 if (
auto c{GetScalarConstantValue<T>(x.right())}) {
2040 x.right() = std::move(x.left());
2041 x.left() = Expr<T>{std::move(*c)};
2043 if (
auto c{GetScalarConstantValue<T>(x.left())}) {
2044 if (c->IsZero() && x.right().Rank() == 0) {
2045 return std::move(x.left());
2046 }
else if (c->CompareSigned(Scalar<T>{1}) == Ordering::Equal) {
2047 if (IsVariable(x.right())) {
2048 return FoldOperation(context, Parentheses<T>{std::move(x.right())});
2050 return std::move(x.right());
2052 }
else if (c->CompareSigned(Scalar<T>{-1}) == Ordering::Equal) {
2053 return FoldOperation(context, Negate<T>{std::move(x.right())});
2057 return Expr<T>{std::move(x)};
2060template <
typename T>
2061Expr<T> FoldOperation(FoldingContext &context, Divide<T> &&x) {
2062 if (
auto array{ApplyElementwise(context, x)}) {
2065 if (
auto folded{OperandsAreConstants(x)}) {
2066 if constexpr (T::category == TypeCategory::Integer) {
2067 auto quotAndRem{folded->first.DivideSigned(folded->second)};
2068 if (quotAndRem.divisionByZero) {
2069 if (context.languageFeatures().ShouldWarn(
2070 common::UsageWarning::FoldingException)) {
2071 context.messages().Say(common::UsageWarning::FoldingException,
2072 "INTEGER(%d) division by zero"_warn_en_US, T::kind);
2074 return Expr<T>{std::move(x)};
2076 if (quotAndRem.overflow &&
2077 context.languageFeatures().ShouldWarn(
2078 common::UsageWarning::FoldingException)) {
2079 context.messages().Say(common::UsageWarning::FoldingException,
2080 "INTEGER(%d) division overflowed"_warn_en_US, T::kind);
2082 return Expr<T>{Constant<T>{quotAndRem.quotient}};
2083 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2084 auto quotAndRem{folded->first.DivideUnsigned(folded->second)};
2085 if (quotAndRem.divisionByZero) {
2086 if (context.languageFeatures().ShouldWarn(
2087 common::UsageWarning::FoldingException)) {
2088 context.messages().Say(common::UsageWarning::FoldingException,
2089 "UNSIGNED(%d) division by zero"_warn_en_US, T::kind);
2091 return Expr<T>{std::move(x)};
2093 return Expr<T>{Constant<T>{quotAndRem.quotient}};
2095 auto quotient{folded->first.Divide(
2096 folded->second, context.targetCharacteristics().roundingMode())};
2100 bool isCanonicalNaNOrInf{
false};
2101 if constexpr (T::category == TypeCategory::Real) {
2102 if (folded->second.IsZero() && context.moduleFileName().has_value()) {
2103 using IntType =
typename T::Scalar::Word;
2104 auto intNumerator{folded->first.template ToInteger<IntType>()};
2105 isCanonicalNaNOrInf = intNumerator.flags == RealFlags{} &&
2106 intNumerator.value >= IntType{-1} &&
2107 intNumerator.value <= IntType{1};
2110 if (!isCanonicalNaNOrInf) {
2111 RealFlagWarnings(context, quotient.flags,
"division");
2113 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2114 quotient.value = quotient.value.FlushSubnormalToZero();
2116 return Expr<T>{Constant<T>{quotient.value}};
2119 return Expr<T>{std::move(x)};
2122template <
typename T>
2123Expr<T> FoldOperation(FoldingContext &context, Power<T> &&x) {
2124 if (
auto array{ApplyElementwise(context, x)}) {
2127 if (
auto folded{OperandsAreConstants(x)}) {
2128 if constexpr (T::category == TypeCategory::Integer) {
2129 auto power{folded->first.Power(folded->second)};
2130 if (context.languageFeatures().ShouldWarn(
2131 common::UsageWarning::FoldingException)) {
2132 if (power.divisionByZero) {
2133 context.messages().Say(common::UsageWarning::FoldingException,
2134 "INTEGER(%d) zero to negative power"_warn_en_US, T::kind);
2135 }
else if (power.overflow) {
2136 context.messages().Say(common::UsageWarning::FoldingException,
2137 "INTEGER(%d) power overflowed"_warn_en_US, T::kind);
2138 }
else if (power.zeroToZero) {
2139 context.messages().Say(common::UsageWarning::FoldingException,
2140 "INTEGER(%d) 0**0 is not defined"_warn_en_US, T::kind);
2143 return Expr<T>{Constant<T>{power.power}};
2145 if (
auto callable{GetHostRuntimeWrapper<T, T, T>(
"pow")}) {
2147 Constant<T>{(*callable)(context, folded->first, folded->second)}};
2148 }
else if (context.languageFeatures().ShouldWarn(
2149 common::UsageWarning::FoldingFailure)) {
2150 context.messages().Say(common::UsageWarning::FoldingFailure,
2151 "Power for %s cannot be folded on host"_warn_en_US,
2156 return Expr<T>{std::move(x)};
2159template <
typename T>
2160Expr<T> FoldOperation(FoldingContext &context, RealToIntPower<T> &&x) {
2161 if (
auto array{ApplyElementwise(context, x)}) {
2164 return common::visit(
2165 [&](
auto &y) -> Expr<T> {
2166 if (
auto folded{OperandsAreConstants(x.left(), y)}) {
2167 auto power{evaluate::IntPower(folded->first, folded->second)};
2168 RealFlagWarnings(context, power.flags,
"power with INTEGER exponent");
2169 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2170 power.value = power.value.FlushSubnormalToZero();
2172 return Expr<T>{Constant<T>{power.value}};
2174 return Expr<T>{std::move(x)};
2180template <
typename T>
2181Expr<T> FoldOperation(FoldingContext &context, Extremum<T> &&x) {
2182 if (
auto array{ApplyElementwise(context, x,
2183 std::function<Expr<T>(Expr<T> &&, Expr<T> &&)>{[=](Expr<T> &&l,
2185 return Expr<T>{Extremum<T>{x.ordering, std::move(l), std::move(r)}};
2189 if (
auto folded{OperandsAreConstants(x)}) {
2190 if constexpr (T::category == TypeCategory::Integer) {
2191 if (folded->first.CompareSigned(folded->second) == x.ordering) {
2192 return Expr<T>{Constant<T>{folded->first}};
2194 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2195 if (folded->first.CompareUnsigned(folded->second) == x.ordering) {
2196 return Expr<T>{Constant<T>{folded->first}};
2198 }
else if constexpr (T::category == TypeCategory::Real) {
2199 if (folded->first.IsNotANumber() ||
2200 (folded->first.Compare(folded->second) == Relation::Less) ==
2201 (x.ordering == Ordering::Less)) {
2202 return Expr<T>{Constant<T>{folded->first}};
2205 static_assert(T::category == TypeCategory::Character);
2208 auto maxLen{std::max(folded->first.length(), folded->second.length())};
2209 bool isFirst{x.ordering == Compare(folded->first, folded->second)};
2210 auto res{isFirst ? std::move(folded->first) : std::move(folded->second)};
2211 res = res.length() == maxLen
2213 : CharacterUtils<T::kind>::Resize(res, maxLen);
2214 return Expr<T>{Constant<T>{std::move(res)}};
2216 return Expr<T>{Constant<T>{folded->second}};
2218 return Expr<T>{std::move(x)};
2222Expr<Type<TypeCategory::Real, KIND>> ToReal(
2223 FoldingContext &context, Expr<SomeType> &&expr) {
2224 using Result = Type<TypeCategory::Real, KIND>;
2225 std::optional<Expr<Result>> result;
2228 using From = std::decay_t<
decltype(x)>;
2229 if constexpr (std::is_same_v<From, BOZLiteralConstant>) {
2232 result = ConvertToType<Result>(std::move(x));
2233 const auto *constant{UnwrapExpr<Constant<Result>>(*result)};
2235 Scalar<Result> real{constant->GetScalarValue().value()};
2236 From converted{From::ConvertUnsigned(real.RawBits()).value};
2237 if (original != converted &&
2238 context.languageFeatures().ShouldWarn(
2239 common::UsageWarning::FoldingValueChecks)) {
2240 context.messages().Say(common::UsageWarning::FoldingValueChecks,
2241 "Nonzero bits truncated from BOZ literal constant in REAL intrinsic"_warn_en_US);
2243 }
else if constexpr (IsNumericCategoryExpr<From>()) {
2244 result = Fold(context, ConvertToType<Result>(std::move(x)));
2246 common::die(
"ToReal: bad argument expression");
2250 return result.value();
2255Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
2256 FoldingContext &context, ComplexComponent<KIND> &&x) {
2257 using Operand = Type<TypeCategory::Complex, KIND>;
2258 using Result = Type<TypeCategory::Real, KIND>;
2259 if (
auto array{ApplyElementwise(context, x,
2260 std::function<Expr<Result>(Expr<Operand> &&)>{
2261 [=](Expr<Operand> &&operand) {
2262 return Expr<Result>{ComplexComponent<KIND>{
2263 x.isImaginaryPart, std::move(operand)}};
2267 auto &operand{x.left()};
2268 if (
auto value{GetScalarConstantValue<Operand>(operand)}) {
2269 if (x.isImaginaryPart) {
2270 return Expr<Result>{Constant<Result>{value->AIMAG()}};
2272 return Expr<Result>{Constant<Result>{value->REAL()}};
2275 return Expr<Result>{std::move(x)};
2278template <
typename T>
2279Expr<T> ExpressionBase<T>::Rewrite(FoldingContext &context, Expr<T> &&expr) {
2280 return common::visit(
2281 [&](
auto &&x) -> Expr<T> {
2282 if constexpr (IsSpecificIntrinsicType<T>) {
2283 return FoldOperation(context, std::move(x));
2284 }
else if constexpr (std::is_same_v<T, SomeDerived>) {
2285 return FoldOperation(context, std::move(x));
2286 }
else if constexpr (common::HasMember<
decltype(x),
2287 TypelessExpression>) {
2288 return std::move(expr);
2290 return Expr<T>{Fold(context, std::move(x))};
2296FOR_EACH_TYPE_AND_KIND(
extern template class ExpressionBase, )
Definition: indirection.h:72
Definition: fold-implementation.h:1261
Definition: expression.h:438
Definition: expression.h:466
Definition: variable.h:208
Definition: variable.h:74
Definition: constant.h:141
Definition: variable.h:393
Definition: fold-implementation.h:55
Definition: expression.h:404
Definition: variable.h:104
Definition: expression.h:432
Definition: variable.h:300
Definition: variable.h:194