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/intrinsics-library.h"
24#include "flang/Evaluate/intrinsics.h"
25#include "flang/Evaluate/shape.h"
26#include "flang/Evaluate/tools.h"
27#include "flang/Evaluate/traverse.h"
28#include "flang/Evaluate/type.h"
29#include "flang/Parser/message.h"
30#include "flang/Semantics/scope.h"
31#include "flang/Semantics/symbol.h"
32#include "flang/Semantics/tools.h"
50static constexpr bool useKahanSummation{
false};
53template <
typename T>
class Folder {
55 explicit Folder(
FoldingContext &c,
bool forOptionalArgument =
false)
56 : context_{c}, forOptionalArgument_{forOptionalArgument} {}
57 std::optional<Constant<T>> GetNamedConstant(
const Symbol &);
58 std::optional<Constant<T>> ApplySubscripts(
const Constant<T> &array,
63 std::optional<Constant<T>> GetConstantComponent(
65 std::optional<Constant<T>> Folding(
ArrayRef &);
66 std::optional<Constant<T>> Folding(
DataRef &);
68 Constant<T> *Folding(std::optional<ActualArgument> &);
83 bool forOptionalArgument_{
false};
86std::optional<Constant<SubscriptInteger>> GetConstantSubscript(
90template <
typename TR,
typename... TA>
91std::optional<std::function<Scalar<TR>(
FoldingContext &, Scalar<TA>...)>>
92GetHostRuntimeWrapper(
const std::string &name) {
93 std::vector<DynamicType> argTypes{TA{}.GetType()...};
94 if (
auto hostWrapper{GetHostRuntimeWrapper(name, TR{}.GetType(), argTypes)}) {
97 std::vector<Expr<SomeType>> genericArgs{
99 return GetScalarConstantValue<TR>(
100 (*hostWrapper)(context, std::move(genericArgs)))
115common::IfNoLvalue<Expr<ResultType<A>>, A> FoldOperation(
117 static_assert(!std::is_same_v<A, Expr<ResultType<A>>>,
118 "call Fold() instead for Expr<>");
135 return Folder<T>{context}.Folding(std::move(designator));
150std::optional<Constant<T>> Folder<T>::GetNamedConstant(
const Symbol &symbol0) {
151 const Symbol &symbol{ResolveAssociations(symbol0)};
152 if (IsNamedConstant(symbol)) {
153 if (
const auto *
object{
154 symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
155 if (
const auto *constant{UnwrapConstantValue<T>(object->init())}) {
164std::optional<Constant<T>> Folder<T>::Folding(
ArrayRef &aRef) {
165 std::vector<Constant<SubscriptInteger>> subscripts;
168 if (
auto constant{GetConstantSubscript(context_, ss, aRef.base(), dim++)}) {
169 subscripts.emplace_back(std::move(*constant));
174 if (
Component * component{aRef.base().UnwrapComponent()}) {
175 return GetConstantComponent(*component, &subscripts);
177 GetNamedConstant(aRef.base().GetLastSymbol())}) {
178 return ApplySubscripts(*array, subscripts);
185std::optional<Constant<T>> Folder<T>::Folding(
DataRef &ref) {
186 return common::visit(
188 [
this](SymbolRef &sym) {
return GetNamedConstant(*sym); },
190 comp = FoldOperation(context_, std::move(comp));
191 return GetConstantComponent(comp);
194 aRef = FoldOperation(context_, std::move(aRef));
195 return Folding(aRef);
197 [](
CoarrayRef &) {
return std::optional<Constant<T>>{}; },
204std::optional<Constant<T>> Folder<T>::ApplySubscripts(
const Constant<T> &array,
206 const auto &shape{array.shape()};
207 const auto &lbounds{array.lbounds()};
208 int rank{GetRank(shape)};
209 CHECK(rank ==
static_cast<int>(subscripts.size()));
210 std::size_t elements{1};
211 ConstantSubscripts resultShape;
212 ConstantSubscripts ssLB;
213 for (
const auto &ss : subscripts) {
214 if (ss.Rank() == 1) {
215 resultShape.push_back(
static_cast<ConstantSubscript
>(ss.size()));
216 elements *= ss.size();
217 ssLB.push_back(ss.lbounds().front());
218 }
else if (ss.Rank() > 1) {
222 ConstantSubscripts ssAt(rank, 0), at(rank, 0), tmp(1, 0);
223 std::vector<Scalar<T>> values;
224 while (elements-- > 0) {
225 bool increment{
true};
227 for (
int j{0}; j < rank; ++j) {
228 if (subscripts[j].Rank() == 0) {
229 at[j] = subscripts[j].GetScalarValue().value().ToInt64();
231 CHECK(k < GetRank(resultShape));
232 tmp[0] = ssLB.at(k) + ssAt.at(k);
233 at[j] = subscripts[j].At(tmp).ToInt64();
235 if (++ssAt[k] == resultShape[k]) {
243 if (at[j] < lbounds[j] || at[j] >= lbounds[j] + shape[j]) {
244 context_.messages().Say(
245 "Subscript value (%jd) is out of range on dimension %d in reference to a constant array value"_err_en_US,
250 values.emplace_back(array.At(at));
251 CHECK(!increment || elements == 0);
252 CHECK(k == GetRank(resultShape));
254 if constexpr (T::category == TypeCategory::Character) {
255 return Constant<T>{array.LEN(), std::move(values), std::move(resultShape)};
256 }
else if constexpr (std::is_same_v<T, SomeDerived>) {
257 return Constant<T>{array.result().derivedTypeSpec(), std::move(values),
258 std::move(resultShape)};
260 return Constant<T>{std::move(values), std::move(resultShape)};
265std::optional<Constant<T>> Folder<T>::ApplyComponent(
268 if (
auto scalar{structures.GetScalarValue()}) {
269 if (std::optional<
Expr<SomeType>> expr{scalar->Find(component)}) {
270 if (
const Constant<T> *value{UnwrapConstantValue<T>(*expr)}) {
272 return ApplySubscripts(*value, *subscripts);
280 std::unique_ptr<ArrayConstructor<T>> array;
281 if (structures.empty()) {
284 ConstantSubscripts at{structures.lbounds()};
288 if (
const Constant<T> *value{UnwrapConstantValue<T>(expr.value())}) {
292 auto *typedExpr{UnwrapExpr<Expr<T>>(expr.value())};
294 array = std::make_unique<ArrayConstructor<T>>(*typedExpr);
295 if constexpr (T::category == TypeCategory::Character) {
300 if (
auto element{ApplySubscripts(*value, *subscripts)}) {
301 CHECK(element->Rank() == 0);
302 array->Push(
Expr<T>{std::move(*element)});
307 CHECK(value->Rank() == 0);
314 }
while (structures.IncrementSubscripts(at));
318 if (
auto *constant{UnwrapConstantValue<T>(result)}) {
319 return constant->Reshape(common::Clone(structures.shape()));
326std::optional<Constant<T>> Folder<T>::GetConstantComponent(
Component &component,
330 [&](
const Symbol &symbol) {
340 return std::optional<Constant<SomeDerived>>{};
343 component.base().u)}) {
344 return ApplyComponent(
345 std::move(*structures), component.GetLastSymbol(), subscripts);
352 if constexpr (T::category == TypeCategory::Character) {
353 if (
auto *substring{common::Unwrap<Substring>(designator.u)}) {
355 substring->Fold(context_)}) {
356 if (
const auto *specific{std::get_if<Expr<T>>(&folded->u)}) {
357 return std::move(*specific);
364 }
else if constexpr (T::category == TypeCategory::Real) {
365 if (
auto *zPart{std::get_if<ComplexPart>(&designator.u)}) {
366 *zPart = FoldOperation(context_, std::move(*zPart));
369 return Fold(context_,
371 zPart->part() == ComplexPart::Part::IM,
378 return common::visit(
380 [&](SymbolRef &&symbol) {
381 if (
auto constant{GetNamedConstant(*symbol)}) {
382 return Expr<T>{std::move(*constant)};
384 return Expr<T>{std::move(designator)};
387 aRef = FoldOperation(context_, std::move(aRef));
388 if (
auto c{Folding(aRef)}) {
395 component = FoldOperation(context_, std::move(component));
396 if (
auto c{GetConstantComponent(component)}) {
407 std::move(designator.u));
413Constant<T> *Folder<T>::Folding(std::optional<ActualArgument> &arg) {
414 if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
415 *expr = Fold(context_, std::move(*expr));
416 if constexpr (T::category != TypeCategory::Derived) {
417 if (!UnwrapExpr<
Expr<T>>(*expr)) {
419 var{forOptionalArgument_
420 ? UnwrapWholeSymbolOrComponentDataRef(*expr)
422 var && (IsOptional(*var) || IsAllocatableOrObjectPointer(var))) {
424 }
else if (
auto converted{
425 ConvertToType(T::GetType(), std::move(*expr))}) {
426 *expr = Fold(context_, std::move(*converted));
430 return UnwrapConstantValue<T>(*expr);
435template <
typename... A, std::size_t... I>
436std::optional<std::tuple<const Constant<A> *...>> GetConstantArgumentsHelper(
438 bool hasOptionalArgument, std::index_sequence<I...>) {
439 static_assert(
sizeof...(A) > 0);
440 std::tuple<const Constant<A> *...> args{
441 Folder<A>{context, hasOptionalArgument}.Folding(arguments.at(I))...};
442 if ((... && (std::get<I>(args)))) {
449template <
typename... A>
450std::optional<std::tuple<const Constant<A> *...>> GetConstantArguments(
451 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument) {
452 return GetConstantArgumentsHelper<A...>(
453 context, args, hasOptionalArgument, std::index_sequence_for<A...>{});
456template <
typename... A, std::size_t... I>
457std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArgumentsHelper(
458 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument,
459 std::index_sequence<I...>) {
461 GetConstantArguments<A...>(context, args, hasOptionalArgument)}) {
462 return std::tuple<Scalar<A>...>{
463 std::get<I>(*constArgs)->GetScalarValue().value()...};
469template <
typename... A>
470std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArguments(
471 FoldingContext &context, ActualArguments &args,
bool hasOptionalArgument) {
472 return GetScalarConstantArgumentsHelper<A...>(
473 context, args, hasOptionalArgument, std::index_sequence_for<A...>{});
480template <
typename TR,
typename... TArgs>
481using ScalarFunc = std::function<Scalar<TR>(
const Scalar<TArgs> &...)>;
482template <
typename TR,
typename... TArgs>
483using ScalarFuncWithContext =
484 std::function<Scalar<TR>(
FoldingContext &,
const Scalar<TArgs> &...)>;
486template <
template <
typename,
typename...>
typename WrapperType,
typename TR,
487 typename... TA, std::size_t... I>
490 bool hasOptionalArgument, std::index_sequence<I...>) {
491 if (std::optional<std::tuple<
const Constant<TA> *...>> args{
492 GetConstantArguments<TA...>(
493 context, funcRef.arguments(), hasOptionalArgument)}) {
495 ConstantSubscripts shape;
497 const ConstantSubscripts *shapes[]{&std::get<I>(*args)->shape()...};
498 const int ranks[]{std::get<I>(*args)->Rank()...};
499 for (
unsigned int i{0}; i <
sizeof...(TA); ++i) {
505 if (shape != *shapes[i]) {
510 context.messages().Say(
511 "Arguments in elemental intrinsic function are not conformable"_err_en_US);
512 return Expr<TR>{std::move(funcRef)};
517 CHECK(rank == GetRank(shape));
519 std::vector<Scalar<TR>> results;
520 std::optional<uint64_t> n{TotalElementCount(shape)};
522 context.messages().Say(
523 "Too many elements in elemental intrinsic function result"_err_en_US);
524 return Expr<TR>{std::move(funcRef)};
528 ConstantSubscripts resultIndex(rank, 1);
529 ConstantSubscripts argIndex[]{std::get<I>(*args)->lbounds()...};
531 if constexpr (std::is_same_v<WrapperType<TR, TA...>,
532 ScalarFuncWithContext<TR, TA...>>) {
533 results.emplace_back(
534 func(context, std::get<I>(*args)->At(argIndex[I])...));
535 }
else if constexpr (std::is_same_v<WrapperType<TR, TA...>,
536 ScalarFunc<TR, TA...>>) {
537 results.emplace_back(func(std::get<I>(*args)->At(argIndex[I])...));
539 (std::get<I>(*args)->IncrementSubscripts(argIndex[I]), ...);
540 }
while (bounds.IncrementSubscripts(resultIndex));
543 if constexpr (TR::category == TypeCategory::Character) {
544 auto len{
static_cast<ConstantSubscript
>(
545 results.empty() ? 0 : results[0].length())};
547 }
else if constexpr (TR::category == TypeCategory::Derived) {
548 if (!results.empty()) {
552 std::move(results), std::move(shape)}};
558 return Expr<TR>{std::move(funcRef)};
561template <
typename TR,
typename... TA>
564 bool hasOptionalArgument =
false) {
565 return FoldElementalIntrinsicHelper<ScalarFunc, TR, TA...>(context,
566 std::move(funcRef), func, hasOptionalArgument,
567 std::index_sequence_for<TA...>{});
569template <
typename TR,
typename... TA>
572 bool hasOptionalArgument =
false) {
573 return FoldElementalIntrinsicHelper<ScalarFuncWithContext, TR, TA...>(context,
574 std::move(funcRef), func, hasOptionalArgument,
575 std::index_sequence_for<TA...>{});
578std::optional<std::int64_t> GetInt64ArgOr(
579 const std::optional<ActualArgument> &, std::int64_t defaultValue);
581template <
typename A,
typename B>
582std::optional<std::vector<A>> GetIntegerVector(
const B &x) {
583 static_assert(std::is_integral_v<A>);
584 if (
const auto *someInteger{UnwrapExpr<Expr<SomeInteger>>(x)}) {
585 return common::visit(
586 [](
const auto &typedExpr) -> std::optional<std::vector<A>> {
587 using T = ResultType<
decltype(typedExpr)>;
588 if (
const auto *constant{UnwrapConstantValue<T>(typedExpr)}) {
589 if (constant->Rank() == 1) {
590 std::vector<A> result;
591 for (
const auto &value : constant->values()) {
592 result.push_back(
static_cast<A
>(value.ToInt64()));
610 invalid.name = IntrinsicProcTable::InvalidName;
612 ActualArguments{std::move(funcRef.arguments())}}};
616 auto args{funcRef.arguments()};
617 CHECK(args.size() == 3);
618 const auto *array{UnwrapConstantValue<T>(args[0])};
619 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
620 auto dim{GetInt64ArgOr(args[2], 1)};
621 if (!array || !shiftExpr || !dim) {
622 return Expr<T>{std::move(funcRef)};
624 auto convertedShift{Fold(context_,
626 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
628 return Expr<T>{std::move(funcRef)};
631 if (*dim < 1 || *dim > array->Rank()) {
632 context_.messages().Say(
"Invalid 'dim=' argument (%jd) in CSHIFT"_err_en_US,
633 static_cast<std::intmax_t
>(*dim));
634 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
637 int rank{array->Rank()};
638 int zbDim{
static_cast<int>(*dim) - 1};
640 if (shift->Rank() > 0) {
642 for (
int j{0}; j < rank; ++j) {
644 if (array->shape()[j] != shift->shape()[k]) {
645 context_.messages().Say(
646 "Invalid 'shift=' argument in CSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
647 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
648 static_cast<std::intmax_t
>(array->shape()[j]));
656 std::vector<Scalar<T>> resultElements;
657 ConstantSubscripts arrayLB{array->lbounds()};
658 ConstantSubscripts arrayAt{arrayLB};
659 ConstantSubscript &dimIndex{arrayAt[zbDim]};
660 ConstantSubscript dimLB{dimIndex};
661 ConstantSubscript dimExtent{array->shape()[zbDim]};
662 ConstantSubscripts shiftLB{shift->lbounds()};
663 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
664 ConstantSubscript origDimIndex{dimIndex};
665 ConstantSubscripts shiftAt;
666 if (shift->Rank() > 0) {
668 for (
int j{0}; j < rank; ++j) {
670 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
674 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
675 dimIndex = dimLB + ((dimIndex - dimLB + shiftCount) % dimExtent);
676 if (dimIndex < dimLB) {
677 dimIndex += dimExtent;
678 }
else if (dimIndex >= dimLB + dimExtent) {
679 dimIndex -= dimExtent;
681 resultElements.push_back(array->At(arrayAt));
682 dimIndex = origDimIndex;
683 array->IncrementSubscripts(arrayAt);
685 return Expr<T>{PackageConstant<T>(
686 std::move(resultElements), *array, array->shape())};
690 return MakeInvalidIntrinsic(std::move(funcRef));
694 auto args{funcRef.arguments()};
695 CHECK(args.size() == 4);
696 const auto *array{UnwrapConstantValue<T>(args[0])};
697 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
698 auto dim{GetInt64ArgOr(args[3], 1)};
699 if (!array || !shiftExpr || !dim) {
700 return Expr<T>{std::move(funcRef)};
703 auto convertedShift{Fold(context_,
705 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
707 return Expr<T>{std::move(funcRef)};
710 std::optional<Expr<SomeType>> convertedBoundary;
711 if (
const auto *boundaryExpr{UnwrapExpr<Expr<SomeType>>(args[2])}) {
712 convertedBoundary = Fold(context_,
714 boundary = UnwrapExpr<Constant<T>>(convertedBoundary);
716 return Expr<T>{std::move(funcRef)};
720 if (*dim < 1 || *dim > array->Rank()) {
721 context_.messages().Say(
722 "Invalid 'dim=' argument (%jd) in EOSHIFT"_err_en_US,
723 static_cast<std::intmax_t
>(*dim));
724 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
726 }
else if (boundary && boundary->Rank() > 0 &&
727 boundary->Rank() != array->Rank() - 1) {
730 int rank{array->Rank()};
731 int zbDim{
static_cast<int>(*dim) - 1};
733 if (shift->Rank() > 0) {
735 for (
int j{0}; j < rank; ++j) {
737 if (array->shape()[j] != shift->shape()[k]) {
738 context_.messages().Say(
739 "Invalid 'shift=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
740 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
741 static_cast<std::intmax_t
>(array->shape()[j]));
748 if (boundary && boundary->Rank() > 0) {
750 for (
int j{0}; j < rank; ++j) {
752 if (array->shape()[j] != boundary->shape()[k]) {
753 context_.messages().Say(
754 "Invalid 'boundary=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
755 k + 1,
static_cast<std::intmax_t
>(boundary->shape()[k]),
756 static_cast<std::intmax_t
>(array->shape()[j]));
764 std::vector<Scalar<T>> resultElements;
765 ConstantSubscripts arrayLB{array->lbounds()};
766 ConstantSubscripts arrayAt{arrayLB};
767 ConstantSubscript &dimIndex{arrayAt[zbDim]};
768 ConstantSubscript dimLB{dimIndex};
769 ConstantSubscript dimExtent{array->shape()[zbDim]};
770 ConstantSubscripts shiftLB{shift->lbounds()};
771 ConstantSubscripts boundaryLB;
773 boundaryLB = boundary->lbounds();
775 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
776 ConstantSubscript origDimIndex{dimIndex};
777 ConstantSubscripts shiftAt;
778 if (shift->Rank() > 0) {
780 for (
int j{0}; j < rank; ++j) {
782 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
786 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
787 dimIndex += shiftCount;
788 if (dimIndex >= dimLB && dimIndex < dimLB + dimExtent) {
789 resultElements.push_back(array->At(arrayAt));
790 }
else if (boundary) {
791 ConstantSubscripts boundaryAt;
792 if (boundary->Rank() > 0) {
793 for (
int j{0}; j < rank; ++j) {
796 boundaryAt.emplace_back(
797 boundaryLB[k++] + arrayAt[j] - arrayLB[j]);
801 resultElements.push_back(boundary->At(boundaryAt));
802 }
else if constexpr (T::category == TypeCategory::Integer ||
803 T::category == TypeCategory::Unsigned ||
804 T::category == TypeCategory::Real ||
805 T::category == TypeCategory::Complex ||
806 T::category == TypeCategory::Logical) {
807 resultElements.emplace_back();
808 }
else if constexpr (T::category == TypeCategory::Character) {
809 auto len{
static_cast<std::size_t
>(array->LEN())};
810 typename Scalar<T>::value_type space{
' '};
811 resultElements.emplace_back(len, space);
813 DIE(
"no derived type boundary");
815 dimIndex = origDimIndex;
816 array->IncrementSubscripts(arrayAt);
818 return Expr<T>{PackageConstant<T>(
819 std::move(resultElements), *array, array->shape())};
823 return MakeInvalidIntrinsic(std::move(funcRef));
827 return FoldElementalIntrinsic<T, T, T, LogicalResult>(context_,
829 ScalarFunc<T, T, T, LogicalResult>(
830 [](
const Scalar<T> &ifTrue,
const Scalar<T> &ifFalse,
831 const Scalar<LogicalResult> &predicate) -> Scalar<T> {
832 return predicate.IsTrue() ? ifTrue : ifFalse;
837 auto args{funcRef.arguments()};
838 CHECK(args.size() == 3);
839 const auto *array{UnwrapConstantValue<T>(args[0])};
840 const auto *vector{UnwrapConstantValue<T>(args[2])};
841 auto convertedMask{Fold(context_,
842 ConvertToType<LogicalResult>(
844 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
845 if (!array || !mask || (args[2] && !vector)) {
846 return Expr<T>{std::move(funcRef)};
849 ConstantSubscript arrayElements{GetSize(array->shape())};
850 ConstantSubscript truths{0};
851 ConstantSubscripts maskAt{mask->lbounds()};
852 if (mask->Rank() == 0) {
853 if (mask->At(maskAt).IsTrue()) {
854 truths = arrayElements;
856 }
else if (array->shape() != mask->shape()) {
858 return MakeInvalidIntrinsic(std::move(funcRef));
860 for (ConstantSubscript j{0}; j < arrayElements;
861 ++j, mask->IncrementSubscripts(maskAt)) {
862 if (mask->At(maskAt).IsTrue()) {
867 std::vector<Scalar<T>> resultElements;
868 ConstantSubscripts arrayAt{array->lbounds()};
869 ConstantSubscript resultSize{truths};
871 resultSize = vector->shape().at(0);
872 if (resultSize < truths) {
873 context_.messages().Say(
874 "Invalid 'vector=' argument in PACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
875 static_cast<std::intmax_t
>(truths),
876 static_cast<std::intmax_t
>(resultSize));
877 return MakeInvalidIntrinsic(std::move(funcRef));
880 for (ConstantSubscript j{0}; j < truths;) {
881 if (mask->At(maskAt).IsTrue()) {
882 resultElements.push_back(array->At(arrayAt));
885 array->IncrementSubscripts(arrayAt);
886 mask->IncrementSubscripts(maskAt);
889 ConstantSubscripts vectorAt{vector->lbounds()};
890 vectorAt.at(0) += truths;
891 for (ConstantSubscript j{truths}; j < resultSize; ++j) {
892 resultElements.push_back(vector->At(vectorAt));
896 return Expr<T>{PackageConstant<T>(std::move(resultElements), *array,
897 ConstantSubscripts{
static_cast<ConstantSubscript
>(resultSize)})};
901 auto args{funcRef.arguments()};
902 CHECK(args.size() == 4);
903 const auto *source{UnwrapConstantValue<T>(args[0])};
904 const auto *pad{UnwrapConstantValue<T>(args[2])};
905 std::optional<std::vector<ConstantSubscript>> shape{
906 GetIntegerVector<ConstantSubscript>(args[1])};
907 std::optional<std::vector<int>> order{GetIntegerVector<int>(args[3])};
908 std::optional<uint64_t> optResultElement;
909 std::optional<std::vector<int>> dimOrder;
912 if (shape->size() > common::maxRank) {
913 context_.messages().Say(
914 "Size of 'shape=' argument (%zd) must not be greater than %d"_err_en_US,
915 shape->size(), common::maxRank);
917 }
else if (HasNegativeExtent(*shape)) {
918 context_.messages().Say(
919 "'shape=' argument (%s) must not have a negative extent"_err_en_US,
920 DEREF(args[1]->UnwrapExpr()).AsFortran());
923 optResultElement = TotalElementCount(*shape);
924 if (!optResultElement) {
925 context_.messages().Say(
926 "'shape=' argument (%s) specifies an array with too many elements"_err_en_US,
927 DEREF(args[1]->UnwrapExpr()).AsFortran());
932 dimOrder = ValidateDimensionOrder(GetRank(*shape), *order);
934 context_.messages().Say(
935 "Invalid 'order=' argument (%s) in RESHAPE"_err_en_US,
936 DEREF(args[3]->UnwrapExpr()).AsFortran());
943 }
else if (!source || !shape || (args[2] && !pad) || (args[3] && !order)) {
944 return Expr<T>{std::move(funcRef)};
946 uint64_t resultElements{*optResultElement};
947 std::vector<int> *dimOrderPtr{dimOrder ? &dimOrder.value() :
nullptr};
948 if (resultElements > source->size() && (!pad || pad->empty())) {
949 context_.messages().Say(
950 "Too few elements in 'source=' argument and 'pad=' "
951 "argument is not present or has null size"_err_en_US);
955 ? source->Reshape(std::move(shape.value()))
956 : pad->Reshape(std::move(shape.value()))};
957 ConstantSubscripts subscripts{result.lbounds()};
958 auto copied{result.CopyFrom(*source,
959 std::min(
static_cast<uint64_t
>(source->size()), resultElements),
960 subscripts, dimOrderPtr)};
961 if (copied < resultElements) {
963 copied += result.CopyFrom(
964 *pad, resultElements - copied, subscripts, dimOrderPtr);
966 CHECK(copied == resultElements);
967 return Expr<T>{std::move(result)};
971 return MakeInvalidIntrinsic(std::move(funcRef));
975 auto args{funcRef.arguments()};
976 CHECK(args.size() == 3);
977 const Constant<T> *source{UnwrapConstantValue<T>(args[0])};
978 auto dim{ToInt64(args[1])};
979 auto ncopies{ToInt64(args[2])};
980 if (!source || !dim) {
981 return Expr<T>{std::move(funcRef)};
983 int sourceRank{source->Rank()};
984 if (sourceRank >= common::maxRank) {
985 context_.messages().Say(
986 "SOURCE= argument to SPREAD has rank %d but must have rank less than %d"_err_en_US,
987 sourceRank, common::maxRank);
988 }
else if (*dim < 1 || *dim > sourceRank + 1) {
989 context_.messages().Say(
990 "DIM=%d argument to SPREAD must be between 1 and %d"_err_en_US, *dim,
992 }
else if (!ncopies) {
993 return Expr<T>{std::move(funcRef)};
1003 ConstantSubscripts shape{source->shape()};
1004 shape.insert(shape.begin() + *dim - 1, *ncopies);
1005 Constant<T> spread{source->Reshape(std::move(shape))};
1006 std::optional<uint64_t> n{TotalElementCount(spread.shape())};
1008 context_.messages().Say(
"Too many elements in SPREAD result"_err_en_US);
1010 std::vector<int> dimOrder;
1011 for (
int j{0}; j < sourceRank; ++j) {
1012 dimOrder.push_back(j < *dim - 1 ? j : j + 1);
1014 dimOrder.push_back(*dim - 1);
1015 ConstantSubscripts at{spread.lbounds()};
1016 spread.CopyFrom(*source, *n, at, &dimOrder);
1017 return Expr<T>{std::move(spread)};
1021 return MakeInvalidIntrinsic(std::move(funcRef));
1025 auto args{funcRef.arguments()};
1026 CHECK(args.size() == 1);
1027 const auto *matrix{UnwrapConstantValue<T>(args[0])};
1029 return Expr<T>{std::move(funcRef)};
1032 std::vector<Scalar<T>> resultElements;
1033 ConstantSubscripts at(2);
1034 for (ConstantSubscript j{0}; j < matrix->shape()[0]; ++j) {
1035 at[0] = matrix->lbounds()[0] + j;
1036 for (ConstantSubscript k{0}; k < matrix->shape()[1]; ++k) {
1037 at[1] = matrix->lbounds()[1] + k;
1038 resultElements.push_back(matrix->At(at));
1041 at = matrix->shape();
1042 std::swap(at[0], at[1]);
1043 return Expr<T>{PackageConstant<T>(std::move(resultElements), *matrix, at)};
1047 auto args{funcRef.arguments()};
1048 CHECK(args.size() == 3);
1049 const auto *vector{UnwrapConstantValue<T>(args[0])};
1050 auto convertedMask{Fold(context_,
1051 ConvertToType<LogicalResult>(
1053 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
1054 const auto *field{UnwrapConstantValue<T>(args[2])};
1055 if (!vector || !mask || !field) {
1056 return Expr<T>{std::move(funcRef)};
1059 if (field->Rank() > 0 && field->shape() != mask->shape()) {
1061 return MakeInvalidIntrinsic(std::move(funcRef));
1063 ConstantSubscript maskElements{GetSize(mask->shape())};
1064 ConstantSubscript truths{0};
1065 ConstantSubscripts maskAt{mask->lbounds()};
1066 for (ConstantSubscript j{0}; j < maskElements;
1067 ++j, mask->IncrementSubscripts(maskAt)) {
1068 if (mask->At(maskAt).IsTrue()) {
1072 if (truths > GetSize(vector->shape())) {
1073 context_.messages().Say(
1074 "Invalid 'vector=' argument in UNPACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
1075 static_cast<std::intmax_t
>(truths),
1076 static_cast<std::intmax_t
>(GetSize(vector->shape())));
1077 return MakeInvalidIntrinsic(std::move(funcRef));
1079 std::vector<Scalar<T>> resultElements;
1080 ConstantSubscripts vectorAt{vector->lbounds()};
1081 ConstantSubscripts fieldAt{field->lbounds()};
1082 for (ConstantSubscript j{0}; j < maskElements; ++j) {
1083 if (mask->At(maskAt).IsTrue()) {
1084 resultElements.push_back(vector->At(vectorAt));
1085 vector->IncrementSubscripts(vectorAt);
1087 resultElements.push_back(field->At(fieldAt));
1089 mask->IncrementSubscripts(maskAt);
1090 field->IncrementSubscripts(fieldAt);
1093 PackageConstant<T>(std::move(resultElements), *vector, mask->shape())};
1096std::optional<Expr<SomeType>> FoldTransfer(
1100 if (
auto folded{FoldTransfer(context_, funcRef.arguments())}) {
1101 return DEREF(UnwrapExpr<
Expr<T>>(*folded));
1103 return Expr<T>{std::move(funcRef)};
1109template <
typename T>
1112 static_assert(T::category == TypeCategory::Integer ||
1113 T::category == TypeCategory::Unsigned ||
1114 T::category == TypeCategory::Real ||
1115 T::category == TypeCategory::Character);
1138 auto &args{funcRef.arguments()};
1139 std::size_t nargs{args.size()};
1140 bool allArgsConstant{
true};
1141 bool extremumAnyway{nargs == 2 && T::category != TypeCategory::Character};
1145 if (!folder.Folding(args[0])) {
1146 allArgsConstant =
false;
1148 if (!folder.Folding(args[1])) {
1149 allArgsConstant =
false;
1155 for (std::size_t i{2}; i < nargs; ++i) {
1157 if (!folder.Folding(args[i])) {
1158 allArgsConstant =
false;
1166 if (allArgsConstant || extremumAnyway) {
1169 if (
const auto *resultp{UnwrapExpr<Expr<T>>(args[0])}) {
1171 for (std::size_t i{1}; i < nargs; ++i) {
1172 if (
const auto *tExpr{UnwrapExpr<Expr<T>>(args[i])}) {
1173 result = FoldOperation(
1174 context,
Extremum<T>{order, std::move(result), *tExpr});
1177 return Expr<T>{std::move(funcRef)};
1185 return Expr<T>{std::move(funcRef)};
1195template <
typename T>
1196Expr<T> RewriteSpecificMINorMAX(
1198 ActualArguments &args{funcRef.arguments()};
1199 auto &intrinsic{DEREF(std::get_if<SpecificIntrinsic>(&funcRef.proc().u))};
1202 std::optional<DynamicType> resultType;
1204 for (
auto j{args.size()}; j-- > 0;) {
1211 (type.category() == resultType->category() &&
1212 type.kind() > resultType->kind()) ||
1213 resultType->category() == TypeCategory::Integer) {
1215 resultTypeArg = &*args[j];
1220 return Expr<T>{std::move(funcRef)};
1223 intrinsic.name.find(
"max") != std::string::npos ?
"max"s :
"min"s;
1224 intrinsic.characteristics.value().functionResult.value().SetType(*resultType);
1225 auto insertConversion{[&](
const auto &x) ->
Expr<T> {
1226 using TR = ResultType<
decltype(x)>;
1229 return Fold(context, ConvertToType<T>(AsCategoryExpr(std::move(maxRef))));
1231 if (
auto *sx{UnwrapExpr<Expr<SomeReal>>(*resultTypeArg)}) {
1232 return common::visit(insertConversion, sx->u);
1233 }
else if (
auto *sx{UnwrapExpr<Expr<SomeInteger>>(*resultTypeArg)}) {
1234 return common::visit(insertConversion, sx->u);
1236 return Expr<T>{std::move(funcRef)};
1258template <
typename T>
1260 ActualArguments &args{funcRef.arguments()};
1261 const auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
1262 if (!intrinsic || intrinsic->name !=
"kind") {
1265 for (std::optional<ActualArgument> &arg : args) {
1266 if (arg && arg->GetConditionalArg()) {
1267 FoldConditionalArg(context, arg);
1268 }
else if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
1269 *expr = Fold(context, std::move(*expr));
1309 for (
const std::optional<ActualArgument> &arg : args) {
1310 if (arg && arg->isConditionalArg()) {
1311 return Expr<T>{std::move(funcRef)};
1314 const std::string name{intrinsic->name};
1315 if (name ==
"cshift") {
1316 return Folder<T>{context}.CSHIFT(std::move(funcRef));
1317 }
else if (name ==
"eoshift") {
1318 return Folder<T>{context}.EOSHIFT(std::move(funcRef));
1319 }
else if (name ==
"merge") {
1320 return Folder<T>{context}.MERGE(std::move(funcRef));
1321 }
else if (name ==
"pack") {
1322 return Folder<T>{context}.PACK(std::move(funcRef));
1323 }
else if (name ==
"reshape") {
1324 return Folder<T>{context}.RESHAPE(std::move(funcRef));
1325 }
else if (name ==
"spread") {
1326 return Folder<T>{context}.SPREAD(std::move(funcRef));
1327 }
else if (name ==
"transfer") {
1328 return Folder<T>{context}.TRANSFER(std::move(funcRef));
1329 }
else if (name ==
"transpose") {
1330 return Folder<T>{context}.TRANSPOSE(std::move(funcRef));
1331 }
else if (name ==
"unpack") {
1332 return Folder<T>{context}.UNPACK(std::move(funcRef));
1335 if constexpr (!std::is_same_v<T, SomeDerived>) {
1336 return FoldIntrinsicFunction(context, std::move(funcRef));
1339 return Expr<T>{std::move(funcRef)};
1343template <
typename T>
class ArrayConstructorFolder {
1345 explicit ArrayConstructorFolder(
FoldingContext &c) : context_{c} {}
1348 if constexpr (T::category == TypeCategory::Character) {
1349 if (
const auto *len{array.LEN()}) {
1350 charLength_ = ToInt64(Fold(context_, common::Clone(*len)));
1351 knownCharLength_ = charLength_.has_value();
1355 if (FoldArray(array)) {
1356 auto n{
static_cast<ConstantSubscript
>(elements_.size())};
1357 if constexpr (std::is_same_v<T, SomeDerived>) {
1359 std::move(elements_), ConstantSubscripts{n}}};
1360 }
else if constexpr (T::category == TypeCategory::Character) {
1363 *charLength_, std::move(elements_), ConstantSubscripts{n}}};
1367 std::move(elements_), ConstantSubscripts{n}, resultInfo_}};
1370 return Expr<T>{std::move(array)};
1374 bool FoldArray(
const Expr<T> &expr) {
1375 Expr<T> folded{Fold(context_, common::Clone(expr))};
1376 if (
const auto *c{UnwrapConstantValue<T>(folded)}) {
1379 ConstantSubscripts index{c->lbounds()};
1381 elements_.emplace_back(c->At(index));
1382 }
while (c->IncrementSubscripts(index));
1384 if constexpr (T::category == TypeCategory::Character) {
1385 if (!knownCharLength_) {
1386 charLength_ = std::max(c->LEN(), charLength_.value_or(-1));
1388 }
else if constexpr (T::category == TypeCategory::Real ||
1389 T::category == TypeCategory::Complex) {
1390 if (c->result().isFromInexactLiteralConversion()) {
1391 resultInfo_.set_isFromInexactLiteralConversion();
1399 bool FoldArray(
const common::CopyableIndirection<
Expr<T>> &expr) {
1400 return FoldArray(expr.value());
1409 std::optional<ConstantSubscript> start{ToInt64(
lower)}, end{ToInt64(upper)},
1410 step{ToInt64(stride)};
1411 if (start && end && step && *step != 0) {
1413 ConstantSubscript &j{context_.StartImpliedDo(iDo.name(), *start)};
1415 for (; j <= *end; j += *step) {
1416 result &= FoldArray(iDo.values());
1419 for (; j >= *end; j += *step) {
1420 result &= FoldArray(iDo.values());
1423 context_.EndImpliedDo(iDo.name());
1430 return common::visit([&](
const auto &y) {
return FoldArray(y); }, x.u);
1433 for (
const auto &x : xs) {
1434 if (!FoldArray(x)) {
1442 std::vector<Scalar<T>> elements_;
1443 std::optional<ConstantSubscript> charLength_;
1444 bool knownCharLength_{
false};
1445 typename Constant<T>::Result resultInfo_;
1448template <
typename T>
1461template <
typename T>
1462bool ArrayConstructorIsFlat(
const ArrayConstructorValues<T> &values) {
1463 for (
const ArrayConstructorValue<T> &x : values) {
1464 if (!std::holds_alternative<Expr<T>>(x.u)) {
1471template <
typename T>
1472std::optional<Expr<T>> AsFlatArrayConstructor(
const Expr<T> &expr) {
1473 if (
const auto *c{UnwrapConstantValue<T>(expr)}) {
1476 ConstantSubscripts at{c->lbounds()};
1479 }
while (c->IncrementSubscripts(at));
1481 return std::make_optional<Expr<T>>(std::move(result));
1482 }
else if (
const auto *a{UnwrapExpr<ArrayConstructor<T>>(expr)}) {
1483 if (ArrayConstructorIsFlat(*a)) {
1484 return std::make_optional<Expr<T>>(expr);
1486 }
else if (
const auto *p{UnwrapExpr<Parentheses<T>>(expr)}) {
1487 return AsFlatArrayConstructor(
Expr<T>{p->left()});
1489 return std::nullopt;
1492template <TypeCategory CAT>
1493std::enable_if_t<CAT != TypeCategory::Derived,
1494 std::optional<Expr<SomeKind<CAT>>>>
1496 return common::visit(
1498 if (
auto flattened{AsFlatArrayConstructor(kindExpr)}) {
1501 return std::nullopt;
1511template <
typename T>
1512std::optional<Expr<T>> FromArrayConstructor(
1514 if (
auto constShape{AsConstantExtents(context, shape)};
1515 constShape && !HasNegativeExtent(*constShape)) {
1517 if (
auto *constant{UnwrapConstantValue<T>(result)}) {
1519 return Expr<T>{constant->Reshape(std::move(*constShape))};
1521 if (constShape->size() == 1) {
1522 if (
auto elements{GetShape(context, result)}) {
1523 if (
auto constElements{AsConstantExtents(context, *elements)}) {
1524 if (constElements->size() == 1 &&
1525 constElements->at(0) == constShape->at(0)) {
1528 return std::move(result);
1534 return std::nullopt;
1545template <
typename RESULT,
typename OPERAND>
1551 if constexpr (common::HasMember<OPERAND, AllIntrinsicCategoryTypes>) {
1553 [&](
auto &&kindExpr) {
1554 using kindType = ResultType<
decltype(kindExpr)>;
1555 auto &aConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1556 for (
auto &acValue : aConst) {
1557 auto &scalar{std::get<Expr<kindType>>(acValue.u)};
1558 result.Push(Fold(context, f(
Expr<OPERAND>{std::move(scalar)})));
1561 std::move(values.u));
1563 auto &aConst{std::get<ArrayConstructor<OPERAND>>(values.u)};
1564 for (
auto &acValue : aConst) {
1565 auto &scalar{std::get<Expr<OPERAND>>(acValue.u)};
1566 result.Push(Fold(context, f(std::move(scalar))));
1569 if constexpr (RESULT::category == TypeCategory::Character) {
1571 result.set_LEN(std::move(*length));
1574 return FromArrayConstructor(context, std::move(result), shape);
1577template <
typename RESULT,
typename A>
1581 if constexpr (RESULT::category == TypeCategory::Character) {
1583 result.set_LEN(std::move(*length));
1589template <
typename LEFT,
typename RIGHT>
1593 auto rightIter{rightArrConst.begin()};
1594 for (
auto &leftValue : leftArrConst) {
1595 CHECK(rightIter != rightArrConst.end());
1596 auto &leftExpr{std::get<Expr<LEFT>>(leftValue.u)};
1597 auto &rightExpr{std::get<Expr<RIGHT>>(rightIter->u)};
1598 if (leftExpr.Rank() != rightExpr.Rank()) {
1601 std::optional<Shape> leftShape{GetShape(context, leftExpr)};
1602 std::optional<Shape> rightShape{GetShape(context, rightExpr)};
1603 if (!leftShape || !rightShape || *leftShape != *rightShape) {
1612template <
typename RESULT,
typename LEFT,
typename RIGHT>
1617 -> std::optional<Expr<RESULT>> {
1618 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1619 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1620 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1621 bool mapped{common::visit(
1622 [&](
auto &&kindExpr) ->
bool {
1623 using kindType = ResultType<
decltype(kindExpr)>;
1625 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1626 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1629 auto rightIter{rightArrConst.begin()};
1630 for (
auto &leftValue : leftArrConst) {
1631 CHECK(rightIter != rightArrConst.end());
1632 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1633 auto &rightScalar{std::get<Expr<kindType>>(rightIter->u)};
1634 result.Push(Fold(context,
1635 f(std::move(leftScalar),
Expr<RIGHT>{std::move(rightScalar)})));
1640 std::move(rightValues.u))};
1642 return std::nullopt;
1645 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1646 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1647 return std::nullopt;
1649 auto rightIter{rightArrConst.begin()};
1650 for (
auto &leftValue : leftArrConst) {
1651 CHECK(rightIter != rightArrConst.end());
1652 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1653 auto &rightScalar{std::get<Expr<RIGHT>>(rightIter->u)};
1655 Fold(context, f(std::move(leftScalar), std::move(rightScalar))));
1659 return FromArrayConstructor(context, std::move(result), shape);
1663template <
typename RESULT,
typename LEFT,
typename RIGHT>
1668 -> std::optional<Expr<RESULT>> {
1669 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1670 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1671 for (
auto &leftValue : leftArrConst) {
1672 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1674 Fold(context, f(std::move(leftScalar),
Expr<RIGHT>{rightScalar})));
1676 return FromArrayConstructor(context, std::move(result), shape);
1680template <
typename RESULT,
typename LEFT,
typename RIGHT>
1685 -> std::optional<Expr<RESULT>> {
1686 auto result{ArrayConstructorFromMold<RESULT>(leftScalar, std::move(length))};
1687 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1689 [&](
auto &&kindExpr) {
1690 using kindType = ResultType<
decltype(kindExpr)>;
1691 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1692 for (
auto &rightValue : rightArrConst) {
1693 auto &rightScalar{std::get<Expr<kindType>>(rightValue.u)};
1694 result.Push(Fold(context,
1699 std::move(rightValues.u));
1701 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1702 for (
auto &rightValue : rightArrConst) {
1703 auto &rightScalar{std::get<Expr<RIGHT>>(rightValue.u)};
1705 Fold(context, f(
Expr<LEFT>{leftScalar}, std::move(rightScalar))));
1708 return FromArrayConstructor(context, std::move(result), shape);
1711template <
typename DERIVED,
typename RESULT,
typename... OPD>
1712std::optional<Expr<SubscriptInteger>> ComputeResultLength(
1714 if constexpr (RESULT::category == TypeCategory::Character) {
1717 return std::nullopt;
1724template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1728 -> std::optional<Expr<RESULT>> {
1729 auto &expr{operation.left()};
1730 expr = Fold(context, std::move(expr));
1731 if (expr.Rank() > 0) {
1732 if (std::optional<Shape> shape{GetShape(context, expr)}) {
1733 if (
auto values{AsFlatArrayConstructor(expr)}) {
1734 return MapOperation(context, std::move(f), *shape,
1735 ComputeResultLength(operation), std::move(*values));
1739 return std::nullopt;
1742template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1743auto ApplyElementwise(
1745 -> std::optional<Expr<RESULT>> {
1746 return ApplyElementwise(context, operation,
1753template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1757 -> std::optional<Expr<RESULT>> {
1758 auto resultLength{ComputeResultLength(operation)};
1759 auto &leftExpr{operation.left()};
1760 auto &rightExpr{operation.right()};
1761 if (leftExpr.Rank() != rightExpr.Rank() && leftExpr.Rank() != 0 &&
1762 rightExpr.Rank() != 0) {
1763 return std::nullopt;
1765 leftExpr = Fold(context, std::move(leftExpr));
1766 rightExpr = Fold(context, std::move(rightExpr));
1767 if (leftExpr.Rank() > 0) {
1768 if (std::optional<Shape> leftShape{GetShape(context, leftExpr)}) {
1769 if (
auto left{AsFlatArrayConstructor(leftExpr)}) {
1770 if (rightExpr.Rank() > 0) {
1771 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1772 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1773 if (CheckConformance(context.messages(), *leftShape, *rightShape,
1774 CheckConformanceFlags::EitherScalarExpandable)
1775 .value_or(
false )) {
1776 return MapOperation(context, std::move(f), *leftShape,
1777 std::move(resultLength), std::move(*left),
1780 return std::nullopt;
1782 return MapOperation(context, std::move(f), *leftShape,
1783 std::move(resultLength), std::move(*left), std::move(*right));
1786 }
else if (IsExpandableScalar(rightExpr, context, *leftShape)) {
1787 return MapOperation(context, std::move(f), *leftShape,
1788 std::move(resultLength), std::move(*left), rightExpr);
1792 }
else if (rightExpr.Rank() > 0) {
1793 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1794 if (IsExpandableScalar(leftExpr, context, *rightShape)) {
1795 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1796 return MapOperation(context, std::move(f), *rightShape,
1797 std::move(resultLength), leftExpr, std::move(*right));
1802 return std::nullopt;
1805template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1806auto ApplyElementwise(
1808 -> std::optional<Expr<RESULT>> {
1809 return ApplyElementwise(context, operation,
1812 return Expr<RESULT>{DERIVED{std::move(left), std::move(right)}};
1818template <
typename TO,
typename FROM>
1819common::IfNoLvalue<std::optional<TO>, FROM> ConvertString(FROM &&s) {
1820 if constexpr (std::is_same_v<TO, FROM>) {
1821 return std::make_optional<TO>(std::move(s));
1826 for (
auto iter{s.cbegin()}; iter != s.cend(); ++iter) {
1827 if (
static_cast<std::uint64_t
>(*iter) > 127) {
1828 return std::nullopt;
1830 str.push_back(
static_cast<typename TO::value_type
>(*iter));
1832 return std::make_optional<TO>(std::move(str));
1836template <
typename TO, TypeCategory FROMCAT>
1839 if (
auto array{ApplyElementwise(context, convert)}) {
1845 } msvcWorkaround{context, convert};
1846 return common::visit(
1847 [&msvcWorkaround](
auto &kindExpr) ->
Expr<TO> {
1848 using Operand = ResultType<
decltype(kindExpr)>;
1851 TypeCategory
constexpr FromCat{FROMCAT};
1852 static_assert(FromCat == Operand::category);
1853 auto &convert{msvcWorkaround.convert};
1854 if (
auto value{GetScalarConstantValue<Operand>(kindExpr)}) {
1856 if constexpr (TO::category == TypeCategory::Integer) {
1857 if constexpr (FromCat == TypeCategory::Integer) {
1858 auto converted{Scalar<TO>::ConvertSigned(*value)};
1859 if (converted.overflow) {
1860 ctx.Warn(common::UsageWarning::FoldingException,
1861 "conversion of %s_%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1862 value->SignedDecimal(), Operand::kind, TO::kind,
1863 converted.value.SignedDecimal());
1865 return ScalarConstantToExpr(std::move(converted.value));
1866 }
else if constexpr (FromCat == TypeCategory::Unsigned) {
1867 auto converted{Scalar<TO>::ConvertUnsigned(*value)};
1868 if ((converted.overflow || converted.value.IsNegative())) {
1869 ctx.Warn(common::UsageWarning::FoldingException,
1870 "conversion of %s_U%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1871 value->UnsignedDecimal(), Operand::kind, TO::kind,
1872 converted.value.SignedDecimal());
1874 return ScalarConstantToExpr(std::move(converted.value));
1875 }
else if constexpr (FromCat == TypeCategory::Real) {
1876 auto converted{value->template ToInteger<Scalar<TO>>()};
1877 if (converted.flags.test(RealFlag::InvalidArgument)) {
1878 ctx.Warn(common::UsageWarning::FoldingException,
1879 "REAL(%d) to INTEGER(%d) conversion: invalid argument"_warn_en_US,
1880 Operand::kind, TO::kind);
1881 }
else if (converted.flags.test(RealFlag::Overflow)) {
1882 ctx.Warn(common::UsageWarning::FoldingException,
1883 "REAL(%d) to INTEGER(%d) conversion overflowed"_warn_en_US,
1884 Operand::kind, TO::kind);
1886 return ScalarConstantToExpr(std::move(converted.value));
1888 }
else if constexpr (TO::category == TypeCategory::Unsigned) {
1889 if constexpr (FromCat == TypeCategory::Integer ||
1890 FromCat == TypeCategory::Unsigned) {
1892 Constant<TO>{Scalar<TO>::ConvertUnsigned(*value).value}};
1893 }
else if constexpr (FromCat == TypeCategory::Real) {
1895 Constant<TO>{value->template ToInteger<Scalar<TO>>().value}};
1897 }
else if constexpr (TO::category == TypeCategory::Real) {
1898 if constexpr (FromCat == TypeCategory::Integer ||
1899 FromCat == TypeCategory::Unsigned) {
1900 auto converted{Scalar<TO>::FromInteger(
1901 *value, FromCat == TypeCategory::Unsigned)};
1902 if (!converted.flags.empty()) {
1904 std::snprintf(buffer,
sizeof buffer,
1905 "INTEGER(%d) to REAL(%d) conversion", Operand::kind,
1907 ctx.RealFlagWarnings(converted.flags, buffer);
1909 return ScalarConstantToExpr(std::move(converted.value));
1910 }
else if constexpr (FromCat == TypeCategory::Real) {
1911 auto converted{Scalar<TO>::Convert(*value)};
1913 if (!converted.flags.empty()) {
1914 std::snprintf(buffer,
sizeof buffer,
1915 "REAL(%d) to REAL(%d) conversion", Operand::kind, TO::kind);
1916 ctx.RealFlagWarnings(converted.flags, buffer);
1918 if (ctx.targetCharacteristics().areSubnormalsFlushedToZero()) {
1919 converted.value = converted.value.FlushSubnormalToZero();
1921 return ScalarConstantToExpr(std::move(converted.value));
1923 }
else if constexpr (TO::category == TypeCategory::Complex) {
1924 if constexpr (FromCat == TypeCategory::Complex) {
1925 return FoldOperation(ctx,
1932 }
else if constexpr (TO::category == TypeCategory::Character &&
1933 FromCat == TypeCategory::Character) {
1934 if (
auto converted{ConvertString<Scalar<TO>>(std::move(*value))}) {
1935 return ScalarConstantToExpr(std::move(*converted));
1937 }
else if constexpr (TO::category == TypeCategory::Logical &&
1938 FromCat == TypeCategory::Logical) {
1941 }
else if constexpr (TO::category == FromCat &&
1942 FromCat != TypeCategory::Character) {
1944 if constexpr (std::is_same_v<Operand, TO>) {
1945 return std::move(kindExpr);
1946 }
else if constexpr (TO::category == TypeCategory::Logical ||
1947 TO::category == TypeCategory::Integer) {
1948 if (
auto *innerConv{
1949 std::get_if<Convert<Operand, TO::category>>(&kindExpr.u)}) {
1951 if (
auto *x{std::get_if<Expr<TO>>(&innerConv->left().u)}) {
1952 if constexpr (TO::category == TypeCategory::Logical ||
1953 TO::kind <= Operand::kind) {
1954 return std::move(*x);
1956 }
else if constexpr (std::is_same_v<TO,
1957 DescriptorInquiry::Result>) {
1958 if (std::holds_alternative<DescriptorInquiry>(x->u) ||
1959 std::holds_alternative<TypeParamInquiry>(x->u)) {
1961 return std::move(*x);
1968 return Expr<TO>{std::move(convert)};
1973template <
typename T>
1975 auto &operand{x.left()};
1976 operand = Fold(context, std::move(operand));
1977 if (
auto value{GetScalarConstantValue<T>(operand)}) {
1982 return std::move(operand);
1988template <
typename T>
1990 if (
auto array{ApplyElementwise(context, x)}) {
1993 auto &operand{x.left()};
1994 if (
auto *nn{std::get_if<Negate<T>>(&x.left().u)}) {
1996 if (IsVariable(nn->left())) {
1997 return FoldOperation(context,
Parentheses<T>{std::move(nn->left())});
1999 return std::move(nn->left());
2001 }
else if (
auto value{GetScalarConstantValue<T>(operand)}) {
2002 if constexpr (T::category == TypeCategory::Integer) {
2003 auto negated{value->Negate()};
2004 if (negated.overflow) {
2005 context.Warn(common::UsageWarning::FoldingException,
2006 "INTEGER(%d) negation overflowed"_warn_en_US, T::kind);
2009 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2021template <
typename LEFT,
typename RIGHT>
2022std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2024 if (
auto xvalue{GetScalarConstantValue<LEFT>(x)}) {
2025 if (
auto yvalue{GetScalarConstantValue<RIGHT>(y)}) {
2026 return {std::make_pair(*xvalue, *yvalue)};
2029 return std::nullopt;
2032template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
2033std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2035 return OperandsAreConstants(operation.left(), operation.right());
2038template <
typename T>
2040 if (
auto array{ApplyElementwise(context, x)}) {
2043 if (
auto folded{OperandsAreConstants(x)}) {
2044 if constexpr (T::category == TypeCategory::Integer) {
2045 auto sum{folded->first.AddSigned(folded->second)};
2047 context.Warn(common::UsageWarning::FoldingException,
2048 "INTEGER(%d) addition overflowed"_warn_en_US, T::kind);
2051 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2053 Constant<T>{folded->first.AddUnsigned(folded->second).value}};
2055 auto sum{folded->first.Add(
2056 folded->second, context.targetCharacteristics().roundingMode())};
2057 context.RealFlagWarnings(sum.flags,
"addition");
2058 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2059 sum.value = sum.value.FlushSubnormalToZero();
2063 }
else if constexpr (T::category == TypeCategory::Integer ||
2064 T::category == TypeCategory::Unsigned) {
2065 if (
auto c{GetScalarConstantValue<T>(x.right())}) {
2066 if (c->IsZero() && x.left().Rank() == 0) {
2067 if (IsVariable(x.left())) {
2068 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2070 return std::move(x.left());
2073 }
else if (
auto c{GetScalarConstantValue<T>(x.left())}) {
2074 if (c->IsZero() && x.right().Rank() == 0) {
2075 if (IsVariable(x.right())) {
2076 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2078 return std::move(x.right());
2086template <
typename T>
2088 if (
auto array{ApplyElementwise(context, x)}) {
2091 if (
auto folded{OperandsAreConstants(x)}) {
2092 if constexpr (T::category == TypeCategory::Integer) {
2093 auto difference{folded->first.SubtractSigned(folded->second)};
2094 if (difference.overflow) {
2095 context.Warn(common::UsageWarning::FoldingException,
2096 "INTEGER(%d) subtraction overflowed"_warn_en_US, T::kind);
2099 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2101 Constant<T>{folded->first.SubtractSigned(folded->second).value}};
2103 auto difference{folded->first.Subtract(
2104 folded->second, context.targetCharacteristics().roundingMode())};
2105 context.RealFlagWarnings(difference.flags,
"subtraction");
2106 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2107 difference.value = difference.value.FlushSubnormalToZero();
2111 }
else if constexpr (T::category == TypeCategory::Integer ||
2112 T::category == TypeCategory::Unsigned) {
2113 if (
auto c{GetScalarConstantValue<T>(x.right())}) {
2114 if (c->IsZero() && x.left().Rank() == 0) {
2115 if (IsVariable(x.left())) {
2116 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2118 return std::move(x.left());
2126template <
typename T>
2128 if (
auto array{ApplyElementwise(context, x)}) {
2131 if (
auto folded{OperandsAreConstants(x)}) {
2132 if constexpr (T::category == TypeCategory::Integer) {
2133 auto product{folded->first.MultiplySigned(folded->second)};
2134 if (product.SignedMultiplicationOverflowed()) {
2135 context.Warn(common::UsageWarning::FoldingException,
2136 "INTEGER(%d) multiplication overflowed"_warn_en_US, T::kind);
2139 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2141 Constant<T>{folded->first.MultiplyUnsigned(folded->second).lower}};
2143 auto product{folded->first.Multiply(
2144 folded->second, context.targetCharacteristics().roundingMode())};
2145 context.RealFlagWarnings(product.flags,
"multiplication");
2146 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2147 product.value = product.value.FlushSubnormalToZero();
2151 }
else if constexpr (T::category == TypeCategory::Integer) {
2152 if (
auto c{GetScalarConstantValue<T>(x.right())}) {
2153 x.right() = std::move(x.left());
2154 x.left() =
Expr<T>{std::move(*c)};
2156 if (
auto c{GetScalarConstantValue<T>(x.left())}) {
2157 if (c->IsZero() && x.right().Rank() == 0) {
2158 return std::move(x.left());
2159 }
else if (c->CompareSigned(Scalar<T>{1}) == Ordering::Equal) {
2160 if (IsVariable(x.right())) {
2161 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2163 return std::move(x.right());
2165 }
else if (c->CompareSigned(Scalar<T>{-1}) == Ordering::Equal) {
2166 return FoldOperation(context,
Negate<T>{std::move(x.right())});
2173template <
typename T>
2175 if (
auto array{ApplyElementwise(context, x)}) {
2178 if (
auto folded{OperandsAreConstants(x)}) {
2179 if constexpr (T::category == TypeCategory::Integer) {
2180 auto quotAndRem{folded->first.DivideSigned(folded->second)};
2181 if (quotAndRem.divisionByZero) {
2182 context.Warn(common::UsageWarning::FoldingException,
2183 "INTEGER(%d) division by zero"_warn_en_US, T::kind);
2186 if (quotAndRem.overflow) {
2187 context.Warn(common::UsageWarning::FoldingException,
2188 "INTEGER(%d) division overflowed"_warn_en_US, T::kind);
2191 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2192 auto quotAndRem{folded->first.DivideUnsigned(folded->second)};
2193 if (quotAndRem.divisionByZero) {
2194 context.Warn(common::UsageWarning::FoldingException,
2195 "UNSIGNED(%d) division by zero"_warn_en_US, T::kind);
2200 auto quotient{folded->first.Divide(
2201 folded->second, context.targetCharacteristics().roundingMode())};
2205 bool isCanonicalNaNOrInf{
false};
2206 if constexpr (T::category == TypeCategory::Real) {
2207 if (folded->second.IsZero() && context.moduleFileName().has_value()) {
2208 using IntType =
typename T::Scalar::Word;
2209 auto intNumerator{folded->first.template ToInteger<IntType>()};
2210 isCanonicalNaNOrInf = intNumerator.flags == RealFlags{} &&
2211 intNumerator.value >= IntType{-1} &&
2212 intNumerator.value <= IntType{1};
2215 if (!isCanonicalNaNOrInf) {
2216 context.RealFlagWarnings(quotient.flags,
"division");
2218 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2219 quotient.value = quotient.value.FlushSubnormalToZero();
2227template <
typename T>
2229 if (
auto array{ApplyElementwise(context, x)}) {
2232 if (
auto folded{OperandsAreConstants(x)}) {
2233 if constexpr (T::category == TypeCategory::Integer) {
2234 auto power{folded->first.Power(folded->second)};
2235 if (power.divisionByZero) {
2236 context.Warn(common::UsageWarning::FoldingException,
2237 "INTEGER(%d) zero to negative power"_warn_en_US, T::kind);
2238 }
else if (power.overflow) {
2239 context.Warn(common::UsageWarning::FoldingException,
2240 "INTEGER(%d) power overflowed"_warn_en_US, T::kind);
2241 }
else if (power.zeroToZero) {
2242 context.Warn(common::UsageWarning::FoldingException,
2243 "INTEGER(%d) 0**0 is not defined"_warn_en_US, T::kind);
2247 if (folded->first.IsZero()) {
2248 if (folded->second.IsZero()) {
2249 context.Warn(common::UsageWarning::FoldingException,
2250 "REAL/COMPLEX 0**0 is not defined"_warn_en_US);
2254 }
else if (
auto callable{GetHostRuntimeWrapper<T, T, T>(
"pow")}) {
2256 Constant<T>{(*callable)(context, folded->first, folded->second)}};
2258 context.Warn(common::UsageWarning::FoldingFailure,
2259 "Power for %s cannot be folded on host"_warn_en_US,
2267template <
typename T>
2269 if (
auto array{ApplyElementwise(context, x)}) {
2272 return common::visit(
2274 if (
auto folded{OperandsAreConstants(x.left(), y)}) {
2275 auto power{evaluate::IntPower(folded->first, folded->second)};
2276 context.RealFlagWarnings(power.flags,
"power with INTEGER exponent");
2277 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2278 power.value = power.value.FlushSubnormalToZero();
2288template <
typename T>
2290 x.condition() = Fold(context, std::move(x.condition()));
2292 if (
auto cst{GetScalarConstantValue<LogicalResult>(x.condition())}) {
2293 return cst->IsTrue() ? Fold(context, std::move(x.thenValue()))
2294 : Fold(context, std::move(x.elseValue()));
2299template <
typename T>
2301 if (
auto array{ApplyElementwise(context, x,
2308 if (
auto folded{OperandsAreConstants(x)}) {
2309 if constexpr (T::category == TypeCategory::Integer) {
2310 if (folded->first.CompareSigned(folded->second) == x.ordering) {
2313 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2314 if (folded->first.CompareUnsigned(folded->second) == x.ordering) {
2317 }
else if constexpr (T::category == TypeCategory::Real) {
2318 if (folded->first.IsNotANumber() ||
2319 (folded->first.Compare(folded->second) == Relation::Less) ==
2320 (x.ordering == Ordering::Less)) {
2324 static_assert(T::category == TypeCategory::Character);
2327 auto maxLen{std::max(folded->first.length(), folded->second.length())};
2328 bool isFirst{x.ordering == Compare(folded->first, folded->second)};
2329 auto res{isFirst ? std::move(folded->first) : std::move(folded->second)};
2330 res = res.length() == maxLen
2332 : CharacterUtils<T::kind>::Resize(res, maxLen);
2344 std::optional<Expr<Result>> result;
2347 using From = std::decay_t<
decltype(x)>;
2348 if constexpr (std::is_same_v<From, BOZLiteralConstant>) {
2351 result = ConvertToType<Result>(std::move(x));
2352 const auto *constant{UnwrapExpr<Constant<Result>>(*result)};
2354 Scalar<Result> real{constant->GetScalarValue().value()};
2355 From converted{From::ConvertUnsigned(real.RawBits()).value};
2356 if (original != converted) {
2357 context.Warn(common::UsageWarning::FoldingValueChecks,
2358 "Nonzero bits truncated from BOZ literal constant in REAL intrinsic"_warn_en_US);
2360 }
else if constexpr (IsNumericCategoryExpr<From>()) {
2361 result = Fold(context, ConvertToType<Result>(std::move(x)));
2363 common::die(
"ToReal: bad argument expression");
2367 return result.value();
2376 if (
auto array{ApplyElementwise(context, x,
2380 x.isImaginaryPart, std::move(operand)}};
2384 auto &operand{x.left()};
2385 if (
auto value{GetScalarConstantValue<Operand>(operand)}) {
2386 if (x.isImaginaryPart) {
2395template <
typename T>
2397 return common::visit(
2399 if constexpr (IsSpecificIntrinsicType<T>) {
2400 return FoldOperation(context, std::move(x));
2401 }
else if constexpr (std::is_same_v<T, SomeDerived>) {
2402 return FoldOperation(context, std::move(x));
2403 }
else if constexpr (common::HasMember<
decltype(x),
2404 TypelessExpression>) {
2405 return std::move(expr);
2407 return Expr<T>{Fold(context, std::move(x))};
Definition fold-implementation.h:1343
Definition expression.h:478
Definition expression.h:506
Definition variable.h:205
Definition variable.h:243
Definition variable.h:357
Definition expression.h:394
Definition constant.h:147
Definition variable.h:381
Definition expression.h:65
Definition fold-implementation.h:53
Definition expression.h:444
Definition variable.h:101
Definition expression.h:113
Definition variable.h:442
Definition expression.h:784
Definition variable.h:304
Definition variable.h:160
Definition variable.h:136
Definition ParserActions.h:24
Definition expression.h:295
Definition expression.h:472
Definition expression.h:256
Definition expression.h:356
Definition expression.h:210
Definition variable.h:288
Definition expression.h:316
Definition expression.h:339
Definition expression.h:436
Definition expression.h:309
Definition expression.h:246
Definition expression.h:228
Definition expression.h:323
Definition expression.h:331
Definition variable.h:191
Definition expression.h:302