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/check-expression.h"
20#include "flang/Evaluate/common.h"
21#include "flang/Evaluate/constant.h"
22#include "flang/Evaluate/expression.h"
23#include "flang/Evaluate/fold.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"
51static constexpr bool useKahanSummation{
false};
54template <
typename T>
class Folder {
56 explicit Folder(
int kind,
FoldingContext &c,
bool forOptionalArgument =
false)
57 : kind_{kind}, context_{c}, forOptionalArgument_{forOptionalArgument} {}
58 template <
typename U = T,
60 std::enable_if_t<std::is_same_v<U, Type<TypeCategory::Derived>>>>
61 explicit Folder(
FoldingContext &c,
bool forOptionalArgument =
false)
62 : Folder(0, c, forOptionalArgument) {}
64 std::optional<Constant<T>> GetNamedConstant(
const Symbol &);
65 std::optional<Constant<T>> ApplySubscripts(
const Constant<T> &array,
67 std::optional<Constant<T>> ApplyComponent(
70 std::optional<Constant<T>> GetConstantComponent(
72 std::optional<Constant<T>> Folding(
ArrayRef &);
73 std::optional<Constant<T>> Folding(
DataRef &);
75 Constant<T> *Folding(std::optional<ActualArgument> &);
91 bool forOptionalArgument_{
false};
94std::optional<Constant<SubscriptInteger>> GetConstantSubscript(
97template <
typename TR,
typename... TA, std::size_t... I>
98std::optional<std::function<Scalar<TR>(
FoldingContext &, Scalar<TA>...)>>
99GetHostRuntimeWrapperHelper(
int resultKind,
100 std::array<
int,
sizeof...(TA)> argKinds,
const std::string &name,
101 std::index_sequence<I...>) {
102 std::vector<DynamicType> argTypes{
DynamicType{TA::category, argKinds[I]}...};
103 if (
auto hostWrapper{GetHostRuntimeWrapper(
104 name, DynamicType{TR::category, resultKind}, argTypes)}) {
105 return [hostWrapper, resultKind, argKinds](
107 std::vector<Expr<SomeType>> genericArgs{
109 return GetScalarConstantValue<TR>(
110 resultKind, (*hostWrapper)(context, std::move(genericArgs)))
118template <
typename TR,
typename... TA>
119static std::optional<std::function<Scalar<TR>(
FoldingContext &, Scalar<TA>...)>>
120GetHostRuntimeWrapper(
int resultKind, std::array<
int,
sizeof...(TA)> argKinds,
121 const std::string &name) {
122 return GetHostRuntimeWrapperHelper<TR, TA...>(
123 resultKind, argKinds, name, std::index_sequence_for<TA...>{});
134common::IfNoLvalue<Expr<ResultType<A>>, A> FoldOperation(
136 static_assert(!std::is_same_v<A, Expr<ResultType<A>>>,
137 "call Fold() instead for Expr<>");
160 const int kind{designator.kind()};
161 return Folder<T>{kind, context}.Folding(std::move(designator));
177std::optional<Constant<T>> Folder<T>::GetNamedConstant(
const Symbol &symbol0) {
178 const Symbol &symbol{ResolveAssociations(symbol0)};
179 if (IsNamedConstant(symbol)) {
180 if (
const auto *
object{
181 symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
182 if (
const auto *constant{UnwrapConstantValue<T>(kind_, object->init())}) {
191std::optional<Constant<T>> Folder<T>::Folding(
ArrayRef &aRef) {
192 std::vector<Constant<SubscriptInteger>> subscripts;
195 if (
auto constant{GetConstantSubscript(context_, ss, aRef.base(), dim++)}) {
196 subscripts.emplace_back(std::move(*constant));
201 if (
Component * component{aRef.base().UnwrapComponent()}) {
202 return GetConstantComponent(*component, &subscripts);
204 GetNamedConstant(aRef.base().GetLastSymbol())}) {
205 return ApplySubscripts(*array, subscripts);
212std::optional<Constant<T>> Folder<T>::Folding(
DataRef &ref) {
213 return common::visit(
215 [
this](SymbolRef &sym) {
return GetNamedConstant(*sym); },
217 comp = FoldOperation(context_, std::move(comp));
218 return GetConstantComponent(comp);
221 aRef = FoldOperation(context_, std::move(aRef));
222 return Folding(aRef);
224 [](
CoarrayRef &) {
return std::optional<Constant<T>>{}; },
231std::optional<Constant<T>> Folder<T>::ApplySubscripts(
const Constant<T> &array,
233 const int kind{array.kind()};
234 const auto &shape{array.shape()};
235 const auto &lbounds{array.lbounds()};
236 int rank{GetRank(shape)};
237 CHECK(rank ==
static_cast<int>(subscripts.size()));
238 std::size_t elements{1};
239 ConstantSubscripts resultShape;
240 ConstantSubscripts ssLB;
241 for (
const auto &ss : subscripts) {
242 if (ss.Rank() == 1) {
243 resultShape.push_back(
static_cast<ConstantSubscript
>(ss.size()));
244 elements *= ss.size();
245 ssLB.push_back(ss.lbounds().front());
246 }
else if (ss.Rank() > 1) {
250 ConstantSubscripts ssAt(rank, 0), at(rank, 0), tmp(1, 0);
251 std::vector<Scalar<T>> values;
252 while (elements-- > 0) {
253 bool increment{
true};
255 for (
int j{0}; j < rank; ++j) {
256 if (subscripts[j].Rank() == 0) {
257 at[j] = subscripts[j].GetScalarValue().value().ToInt64();
259 CHECK(k < GetRank(resultShape));
260 tmp[0] = ssLB.at(k) + ssAt.at(k);
261 at[j] = subscripts[j].At(tmp).ToInt64();
263 if (++ssAt[k] == resultShape[k]) {
271 if (at[j] < lbounds[j] || at[j] >= lbounds[j] + shape[j]) {
272 context_.messages().Say(
273 "Subscript value (%jd) is out of range on dimension %d in reference to a constant array value"_err_en_US,
278 values.emplace_back(array.At(at));
279 CHECK(!increment || elements == 0);
280 CHECK(k == GetRank(resultShape));
282 if constexpr (T::category == TypeCategory::Character) {
284 kind, array.LEN(), std::move(values), std::move(resultShape)};
285 }
else if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
287 return Constant<T>{array.result().derivedTypeSpec(), std::move(values),
288 std::move(resultShape)};
290 return Constant<T>{kind, std::move(values), std::move(resultShape)};
295std::optional<Constant<T>> Folder<T>::ApplyComponent(
298 if (
auto scalar{structures.GetScalarValue()}) {
299 if (std::optional<
Expr<SomeType>> expr{scalar->Find(component)}) {
300 if (
const Constant<T> *value{UnwrapConstantValue<T>(kind_, *expr)}) {
302 return ApplySubscripts(*value, *subscripts);
310 std::unique_ptr<ArrayConstructor<T>> array;
311 if (structures.empty()) {
314 ConstantSubscripts at{structures.lbounds()};
319 UnwrapConstantValue<T>(kind_, expr.value())}) {
323 auto *typedExpr{UnwrapExpr<Expr<T>>(kind_, expr.value())};
325 array = std::make_unique<ArrayConstructor<T>>(kind_, *typedExpr);
326 if constexpr (T::category == TypeCategory::Character) {
327 array->set_LEN(MakeSubscriptIntExpr(value->LEN()));
331 if (
auto element{ApplySubscripts(*value, *subscripts)}) {
332 CHECK(element->Rank() == 0);
333 array->Push(
Expr<T>{std::move(*element)});
338 CHECK(value->Rank() == 0);
345 }
while (structures.IncrementSubscripts(at));
349 if (
auto *constant{UnwrapConstantValue<T>(kind_, result)}) {
350 return constant->Reshape(common::Clone(structures.shape()));
357std::optional<Constant<T>> Folder<T>::GetConstantComponent(
Component &component,
362 [&](
const Symbol &symbol) {
364 .GetNamedConstant(symbol);
372 .GetConstantComponent(base);
375 return std::optional<
379 component.base().u)}) {
380 return ApplyComponent(
381 std::move(*structures), component.GetLastSymbol(), subscripts);
388 const int kind{designator.kind()};
389 if constexpr (T::category == TypeCategory::Character) {
390 if (
auto *substring{common::Unwrap<Substring>(designator.u)}) {
392 substring->Fold(context_)};
393 folded && folded->kind() == kind) {
394 return std::move(*folded);
400 }
else if constexpr (T::category == TypeCategory::Real) {
401 if (
auto *zPart{std::get_if<ComplexPart>(&designator.u)}) {
402 *zPart = FoldOperation(context_, std::move(*zPart));
406 return Fold(context_,
414 return common::visit(
416 [&](SymbolRef &&symbol) {
417 if (
auto constant{GetNamedConstant(*symbol)}) {
418 return Expr<T>{std::move(*constant)};
420 return Expr<T>{std::move(designator)};
423 aRef = FoldOperation(context_, std::move(aRef));
424 if (
auto c{Folding(aRef)}) {
431 component = FoldOperation(context_, std::move(component));
432 if (
auto c{GetConstantComponent(component)}) {
438 [&, kind](
auto &&x) {
443 std::move(designator.u));
449Constant<T> *Folder<T>::Folding(std::optional<ActualArgument> &arg) {
450 if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
451 *expr = Fold(context_, std::move(*expr));
452 if constexpr (T::category != TypeCategory::Derived) {
453 if (!UnwrapExpr<
Expr<T>>(kind_, *expr)) {
455 var{forOptionalArgument_
456 ? UnwrapWholeSymbolOrComponentDataRef(*expr)
458 var && (IsOptional(*var) || IsAllocatableOrObjectPointer(var))) {
460 }
else if (
auto converted{ConvertToType(
461 DynamicType{T::category, kind_}, std::move(*expr))}) {
462 *expr = Fold(context_, std::move(*converted));
466 return UnwrapConstantValue<T>(kind_, *expr);
471template <
typename... A, std::size_t... I>
472std::optional<std::tuple<const Constant<A> *...>> GetConstantArgumentsHelper(
473 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
474 ActualArguments &arguments,
bool hasOptionalArgument,
475 std::index_sequence<I...>) {
476 static_assert(
sizeof...(A) > 0);
477 std::tuple<const Constant<A> *...> args{
478 Folder<A>{kinds[I], context, hasOptionalArgument}.Folding(
479 arguments.at(I))...};
480 if ((... && (std::get<I>(args)))) {
487template <
typename... A>
488std::optional<std::tuple<const Constant<A> *...>> GetConstantArguments(
489 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
490 ActualArguments &args,
bool hasOptionalArgument) {
491 return GetConstantArgumentsHelper<A...>(kinds, context, args,
492 hasOptionalArgument, std::index_sequence_for<A...>{});
495template <
typename... A, std::size_t... I>
496std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArgumentsHelper(
497 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
498 ActualArguments &args,
bool hasOptionalArgument,
499 std::index_sequence<I...>) {
500 if (
auto constArgs{GetConstantArguments<A...>(
501 kinds, context, args, hasOptionalArgument)}) {
502 return std::tuple<Scalar<A>...>{
503 std::get<I>(*constArgs)->GetScalarValue().value()...};
509template <
typename... A>
510std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArguments(
511 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
512 ActualArguments &args,
bool hasOptionalArgument) {
513 return GetScalarConstantArgumentsHelper<A...>(kinds, context, args,
514 hasOptionalArgument, std::index_sequence_for<A...>{});
521template <
typename TR,
typename... TArgs>
522using ScalarFunc = std::function<Scalar<TR>(
const Scalar<TArgs> &...)>;
523template <
typename TR,
typename... TArgs>
524using ScalarFuncWithContext =
525 std::function<Scalar<TR>(
FoldingContext &,
const Scalar<TArgs> &...)>;
527template <
template <
typename,
typename...>
typename WrapperType,
typename TR,
528 typename... TA, std::size_t... I>
529Expr<TR> FoldElementalIntrinsicHelper(
int resultKind,
530 const std::array<
int,
sizeof...(TA)> &argKinds,
FoldingContext &context,
532 bool hasOptionalArgument, std::index_sequence<I...>) {
533 CHECK(funcRef.kind() == resultKind);
534 if (std::optional<std::tuple<
const Constant<TA> *...>> args{
535 GetConstantArguments<TA...>({argKinds[I]...}, context,
536 funcRef.arguments(), hasOptionalArgument)}) {
538 ConstantSubscripts shape;
540 const ConstantSubscripts *shapes[]{&std::get<I>(*args)->shape()...};
541 const int ranks[]{std::get<I>(*args)->Rank()...};
542 for (
unsigned int i{0}; i <
sizeof...(TA); ++i) {
548 if (shape != *shapes[i]) {
553 context.messages().Say(
554 "Arguments in elemental intrinsic function are not conformable"_err_en_US);
555 return Expr<TR>{std::move(funcRef)};
560 CHECK(rank == GetRank(shape));
562 std::vector<Scalar<TR>> results;
563 std::optional<uint64_t> n{TotalElementCount(shape)};
565 context.messages().Say(
566 "Too many elements in elemental intrinsic function result"_err_en_US);
567 return Expr<TR>{std::move(funcRef)};
571 ConstantSubscripts resultIndex(rank, 1);
572 ConstantSubscripts argIndex[]{std::get<I>(*args)->lbounds()...};
574 if constexpr (std::is_same_v<WrapperType<TR, TA...>,
575 ScalarFuncWithContext<TR, TA...>>) {
576 results.emplace_back(
577 func(context, std::get<I>(*args)->At(argIndex[I])...));
578 }
else if constexpr (std::is_same_v<WrapperType<TR, TA...>,
579 ScalarFunc<TR, TA...>>) {
580 results.emplace_back(func(std::get<I>(*args)->At(argIndex[I])...));
582 (std::get<I>(*args)->IncrementSubscripts(argIndex[I]), ...);
583 }
while (bounds.IncrementSubscripts(resultIndex));
586 if constexpr (TR::category == TypeCategory::Character) {
587 auto len{
static_cast<ConstantSubscript
>(
588 results.empty() ? 0 : results[0].length())};
590 Constant<TR>{resultKind, len, std::move(results), std::move(shape)}};
591 }
else if constexpr (TR::category == TypeCategory::Derived) {
592 if (!results.empty()) {
596 std::move(results), std::move(shape)}};
600 Constant<TR>{resultKind, std::move(results), std::move(shape)}};
603 return Expr<TR>{std::move(funcRef)};
606template <
typename TR,
typename... TA>
607Expr<TR> FoldElementalIntrinsic(
int resultKind,
608 const std::array<
int,
sizeof...(TA)> &argKinds,
FoldingContext &context,
610 bool hasOptionalArgument =
false) {
611 return FoldElementalIntrinsicHelper<ScalarFunc, TR, TA...>(resultKind,
612 argKinds, context, std::move(funcRef), func, hasOptionalArgument,
613 std::index_sequence_for<TA...>{});
615template <
typename TR,
typename... TA>
616Expr<TR> FoldElementalIntrinsic(
int resultKind,
617 const std::array<
int,
sizeof...(TA)> &argKinds,
FoldingContext &context,
619 bool hasOptionalArgument =
false) {
620 return FoldElementalIntrinsicHelper<ScalarFuncWithContext, TR, TA...>(
621 resultKind, argKinds, context, std::move(funcRef), func,
622 hasOptionalArgument, std::index_sequence_for<TA...>{});
625std::optional<std::int64_t> GetInt64ArgOr(
626 const std::optional<ActualArgument> &, std::int64_t defaultValue);
628template <
typename A,
typename B>
629std::optional<std::vector<A>> GetIntegerVector(
const B &x) {
630 static_assert(common::is_integral_v<A>);
631 if (
const auto *someInteger{
632 UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(x)}) {
633 if (
const auto *constant{
634 UnwrapConstantValue<Type<TypeCategory::Integer>>(*someInteger)}) {
635 if (constant->Rank() == 1) {
636 std::vector<A> result;
637 for (
const auto &value : constant->values()) {
638 result.push_back(
static_cast<A
>(value.ToInt64()));
652 const int kind{funcRef.kind()};
654 invalid.name = IntrinsicProcTable::InvalidName;
656 ActualArguments{std::move(funcRef.arguments())}}};
660 const int kind{funcRef.kind()};
661 auto args{funcRef.arguments()};
662 CHECK(args.size() == 3);
663 const auto *array{UnwrapConstantValue<T>(kind, args[0])};
664 const auto *shiftExpr{UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(args[1])};
665 auto dim{GetInt64ArgOr(args[2], 1)};
666 if (!array || !shiftExpr || !dim) {
667 return Expr<T>{std::move(funcRef)};
669 auto convertedShift{Fold(context_,
670 ConvertToType<SubscriptInteger>(SubscriptIntegerKind,
672 const auto *shift{UnwrapConstantValue<SubscriptInteger>(
673 SubscriptIntegerKind, convertedShift)};
675 return Expr<T>{std::move(funcRef)};
678 if (*dim < 1 || *dim > array->Rank()) {
679 context_.messages().Say(
"Invalid 'dim=' argument (%jd) in CSHIFT"_err_en_US,
680 static_cast<std::intmax_t
>(*dim));
681 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
684 int rank{array->Rank()};
685 int zbDim{
static_cast<int>(*dim) - 1};
687 if (shift->Rank() > 0) {
689 for (
int j{0}; j < rank; ++j) {
691 if (array->shape()[j] != shift->shape()[k]) {
692 context_.messages().Say(
693 "Invalid 'shift=' argument in CSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
694 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
695 static_cast<std::intmax_t
>(array->shape()[j]));
703 std::vector<Scalar<T>> resultElements;
704 ConstantSubscripts arrayLB{array->lbounds()};
705 ConstantSubscripts arrayAt{arrayLB};
706 ConstantSubscript &dimIndex{arrayAt[zbDim]};
707 ConstantSubscript dimLB{dimIndex};
708 ConstantSubscript dimExtent{array->shape()[zbDim]};
709 ConstantSubscripts shiftLB{shift->lbounds()};
710 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
711 ConstantSubscript origDimIndex{dimIndex};
712 ConstantSubscripts shiftAt;
713 if (shift->Rank() > 0) {
715 for (
int j{0}; j < rank; ++j) {
717 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
721 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
722 dimIndex = dimLB + ((dimIndex - dimLB + shiftCount) % dimExtent);
723 if (dimIndex < dimLB) {
724 dimIndex += dimExtent;
725 }
else if (dimIndex >= dimLB + dimExtent) {
726 dimIndex -= dimExtent;
728 resultElements.push_back(array->At(arrayAt));
729 dimIndex = origDimIndex;
730 array->IncrementSubscripts(arrayAt);
732 return Expr<T>{PackageConstant<T>(
733 kind, std::move(resultElements), *array, array->shape())};
737 return MakeInvalidIntrinsic(std::move(funcRef));
741 const int kind{funcRef.kind()};
742 auto args{funcRef.arguments()};
743 CHECK(args.size() == 4);
744 const auto *array{UnwrapConstantValue<T>(kind, args[0])};
745 const auto *shiftExpr{UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(args[1])};
746 auto dim{GetInt64ArgOr(args[3], 1)};
747 if (!array || !shiftExpr || !dim) {
748 return Expr<T>{std::move(funcRef)};
751 auto convertedShift{Fold(context_,
752 ConvertToType<SubscriptInteger>(SubscriptIntegerKind,
754 const auto *shift{UnwrapConstantValue<SubscriptInteger>(
755 SubscriptIntegerKind, convertedShift)};
757 return Expr<T>{std::move(funcRef)};
760 std::optional<Expr<SomeType>> convertedBoundary;
761 if (
const auto *boundaryExpr{UnwrapExpr<Expr<SomeType>>(args[2])}) {
762 convertedBoundary = Fold(context_,
764 boundary = UnwrapExpr<Constant<T>>(kind, convertedBoundary);
766 return Expr<T>{std::move(funcRef)};
770 if (*dim < 1 || *dim > array->Rank()) {
771 context_.messages().Say(
772 "Invalid 'dim=' argument (%jd) in EOSHIFT"_err_en_US,
773 static_cast<std::intmax_t
>(*dim));
774 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
776 }
else if (boundary && boundary->Rank() > 0 &&
777 boundary->Rank() != array->Rank() - 1) {
780 int rank{array->Rank()};
781 int zbDim{
static_cast<int>(*dim) - 1};
783 if (shift->Rank() > 0) {
785 for (
int j{0}; j < rank; ++j) {
787 if (array->shape()[j] != shift->shape()[k]) {
788 context_.messages().Say(
789 "Invalid 'shift=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
790 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
791 static_cast<std::intmax_t
>(array->shape()[j]));
798 if (boundary && boundary->Rank() > 0) {
800 for (
int j{0}; j < rank; ++j) {
802 if (array->shape()[j] != boundary->shape()[k]) {
803 context_.messages().Say(
804 "Invalid 'boundary=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
805 k + 1,
static_cast<std::intmax_t
>(boundary->shape()[k]),
806 static_cast<std::intmax_t
>(array->shape()[j]));
814 std::vector<Scalar<T>> resultElements;
815 ConstantSubscripts arrayLB{array->lbounds()};
816 ConstantSubscripts arrayAt{arrayLB};
817 ConstantSubscript &dimIndex{arrayAt[zbDim]};
818 ConstantSubscript dimLB{dimIndex};
819 ConstantSubscript dimExtent{array->shape()[zbDim]};
820 ConstantSubscripts shiftLB{shift->lbounds()};
821 ConstantSubscripts boundaryLB;
823 boundaryLB = boundary->lbounds();
825 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
826 ConstantSubscript origDimIndex{dimIndex};
827 ConstantSubscripts shiftAt;
828 if (shift->Rank() > 0) {
830 for (
int j{0}; j < rank; ++j) {
832 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
836 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
837 dimIndex += shiftCount;
838 if (dimIndex >= dimLB && dimIndex < dimLB + dimExtent) {
839 resultElements.push_back(array->At(arrayAt));
840 }
else if (boundary) {
841 ConstantSubscripts boundaryAt;
842 if (boundary->Rank() > 0) {
843 for (
int j{0}; j < rank; ++j) {
846 boundaryAt.emplace_back(
847 boundaryLB[k++] + arrayAt[j] - arrayLB[j]);
851 resultElements.push_back(boundary->At(boundaryAt));
852 }
else if constexpr (T::category == TypeCategory::Integer ||
853 T::category == TypeCategory::Unsigned ||
854 T::category == TypeCategory::Real ||
855 T::category == TypeCategory::Complex ||
856 T::category == TypeCategory::Logical) {
857 resultElements.emplace_back(Scalar<T>::Zero(kind));
858 }
else if constexpr (T::category == TypeCategory::Character) {
859 auto len{
static_cast<std::size_t
>(array->LEN())};
860 resultElements.emplace_back(kind, len,
' ');
862 DIE(
"no derived type boundary");
864 dimIndex = origDimIndex;
865 array->IncrementSubscripts(arrayAt);
867 return Expr<T>{PackageConstant<T>(
868 kind, std::move(resultElements), *array, array->shape())};
872 return MakeInvalidIntrinsic(std::move(funcRef));
876 const int kind{funcRef.kind()};
877 return FoldElementalIntrinsic<T, T, T, LogicalResult>(kind,
878 {kind, kind, LogicalResultKind}, context_, std::move(funcRef),
879 ScalarFunc<T, T, T, LogicalResult>(
880 [](
const Scalar<T> &ifTrue,
const Scalar<T> &ifFalse,
881 const Scalar<LogicalResult> &predicate) -> Scalar<T> {
882 return predicate.IsTrue() ? ifTrue : ifFalse;
887 const int kind{funcRef.kind()};
888 auto args{funcRef.arguments()};
889 CHECK(args.size() == 3);
890 const auto *array{UnwrapConstantValue<T>(kind, args[0])};
891 const auto *vector{UnwrapConstantValue<T>(kind, args[2])};
892 auto convertedMask{Fold(context_,
893 ConvertToType<LogicalResult>(LogicalResultKind,
897 UnwrapConstantValue<LogicalResult>(LogicalResultKind, convertedMask)};
898 if (!array || !mask || (args[2] && !vector)) {
899 return Expr<T>{std::move(funcRef)};
902 ConstantSubscript arrayElements{GetSize(array->shape())};
903 ConstantSubscript truths{0};
904 ConstantSubscripts maskAt{mask->lbounds()};
905 if (mask->Rank() == 0) {
906 if (mask->At(maskAt).IsTrue()) {
907 truths = arrayElements;
909 }
else if (array->shape() != mask->shape()) {
911 return MakeInvalidIntrinsic(std::move(funcRef));
913 for (ConstantSubscript j{0}; j < arrayElements;
914 ++j, mask->IncrementSubscripts(maskAt)) {
915 if (mask->At(maskAt).IsTrue()) {
920 std::vector<Scalar<T>> resultElements;
921 ConstantSubscripts arrayAt{array->lbounds()};
922 ConstantSubscript resultSize{truths};
924 resultSize = vector->shape().at(0);
925 if (resultSize < truths) {
926 context_.messages().Say(
927 "Invalid 'vector=' argument in PACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
928 static_cast<std::intmax_t
>(truths),
929 static_cast<std::intmax_t
>(resultSize));
930 return MakeInvalidIntrinsic(std::move(funcRef));
933 for (ConstantSubscript j{0}; j < truths;) {
934 if (mask->At(maskAt).IsTrue()) {
935 resultElements.push_back(array->At(arrayAt));
938 array->IncrementSubscripts(arrayAt);
939 mask->IncrementSubscripts(maskAt);
942 ConstantSubscripts vectorAt{vector->lbounds()};
943 vectorAt.at(0) += truths;
944 for (ConstantSubscript j{truths}; j < resultSize; ++j) {
945 resultElements.push_back(vector->At(vectorAt));
949 return Expr<T>{PackageConstant<T>(kind, std::move(resultElements), *array,
950 ConstantSubscripts{
static_cast<ConstantSubscript
>(resultSize)})};
954 auto args{funcRef.arguments()};
955 CHECK(args.size() == 4);
956 const auto *source{UnwrapConstantValue<T>(funcRef.kind(), args[0])};
957 const auto *pad{UnwrapConstantValue<T>(funcRef.kind(), args[2])};
958 std::optional<std::vector<ConstantSubscript>> shape{
959 GetIntegerVector<ConstantSubscript>(args[1])};
960 std::optional<std::vector<int>> order{GetIntegerVector<int>(args[3])};
961 std::optional<uint64_t> optResultElement;
962 std::optional<std::vector<int>> dimOrder;
965 if (shape->size() > common::maxRank) {
966 context_.messages().Say(
967 "Size of 'shape=' argument (%zd) must not be greater than %d"_err_en_US,
968 shape->size(), common::maxRank);
970 }
else if (HasNegativeExtent(*shape)) {
971 context_.messages().Say(
972 "'shape=' argument (%s) must not have a negative extent"_err_en_US,
973 DEREF(args[1]->UnwrapExpr()).AsFortran());
976 optResultElement = TotalElementCount(*shape);
977 if (!optResultElement) {
978 context_.messages().Say(
979 "'shape=' argument (%s) specifies an array with too many elements"_err_en_US,
980 DEREF(args[1]->UnwrapExpr()).AsFortran());
985 dimOrder = ValidateDimensionOrder(GetRank(*shape), *order);
987 context_.messages().Say(
988 "Invalid 'order=' argument (%s) in RESHAPE"_err_en_US,
989 DEREF(args[3]->UnwrapExpr()).AsFortran());
996 }
else if (!source || !shape || (args[2] && !pad) || (args[3] && !order)) {
997 return Expr<T>{std::move(funcRef)};
999 uint64_t resultElements{*optResultElement};
1000 std::vector<int> *dimOrderPtr{dimOrder ? &dimOrder.value() :
nullptr};
1001 if (resultElements > source->size() && (!pad || pad->empty())) {
1002 context_.messages().Say(
1003 "Too few elements in 'source=' argument and 'pad=' "
1004 "argument is not present or has null size"_err_en_US);
1008 ? source->Reshape(std::move(shape.value()))
1009 : pad->Reshape(std::move(shape.value()))};
1010 ConstantSubscripts subscripts{result.lbounds()};
1011 auto copied{result.CopyFrom(*source,
1012 std::min(
static_cast<uint64_t
>(source->size()), resultElements),
1013 subscripts, dimOrderPtr)};
1014 if (copied < resultElements) {
1016 copied += result.CopyFrom(
1017 *pad, resultElements - copied, subscripts, dimOrderPtr);
1019 CHECK(copied == resultElements);
1020 return Expr<T>{std::move(result)};
1024 return MakeInvalidIntrinsic(std::move(funcRef));
1028 auto args{funcRef.arguments()};
1029 CHECK(args.size() == 3);
1030 const Constant<T> *source{UnwrapConstantValue<T>(funcRef.kind(), args[0])};
1031 auto dim{ToInt64(args[1])};
1032 auto ncopies{ToInt64(args[2])};
1033 if (!source || !dim) {
1034 return Expr<T>{std::move(funcRef)};
1036 int sourceRank{source->Rank()};
1037 if (sourceRank >= common::maxRank) {
1038 context_.messages().Say(
1039 "SOURCE= argument to SPREAD has rank %d but must have rank less than %d"_err_en_US,
1040 sourceRank, common::maxRank);
1041 }
else if (*dim < 1 || *dim > sourceRank + 1) {
1042 context_.messages().Say(
1043 "DIM=%d argument to SPREAD must be between 1 and %d"_err_en_US, *dim,
1045 }
else if (!ncopies) {
1046 return Expr<T>{std::move(funcRef)};
1056 ConstantSubscripts shape{source->shape()};
1057 shape.insert(shape.begin() + *dim - 1, *ncopies);
1058 Constant<T> spread{source->Reshape(std::move(shape))};
1059 std::optional<uint64_t> n{TotalElementCount(spread.shape())};
1061 context_.messages().Say(
"Too many elements in SPREAD result"_err_en_US);
1063 std::vector<int> dimOrder;
1064 for (
int j{0}; j < sourceRank; ++j) {
1065 dimOrder.push_back(j < *dim - 1 ? j : j + 1);
1067 dimOrder.push_back(*dim - 1);
1068 ConstantSubscripts at{spread.lbounds()};
1069 spread.CopyFrom(*source, *n, at, &dimOrder);
1070 return Expr<T>{std::move(spread)};
1074 return MakeInvalidIntrinsic(std::move(funcRef));
1078 const int kind{funcRef.kind()};
1079 auto args{funcRef.arguments()};
1080 CHECK(args.size() == 1);
1081 const auto *matrix{UnwrapConstantValue<T>(kind, args[0])};
1083 return Expr<T>{std::move(funcRef)};
1086 std::vector<Scalar<T>> resultElements;
1087 ConstantSubscripts at(2);
1088 for (ConstantSubscript j{0}; j < matrix->shape()[0]; ++j) {
1089 at[0] = matrix->lbounds()[0] + j;
1090 for (ConstantSubscript k{0}; k < matrix->shape()[1]; ++k) {
1091 at[1] = matrix->lbounds()[1] + k;
1092 resultElements.push_back(matrix->At(at));
1095 at = matrix->shape();
1096 std::swap(at[0], at[1]);
1098 PackageConstant<T>(kind, std::move(resultElements), *matrix, at)};
1102 const int kind{funcRef.kind()};
1103 auto args{funcRef.arguments()};
1104 CHECK(args.size() == 3);
1105 const auto *vector{UnwrapConstantValue<T>(kind, args[0])};
1106 auto convertedMask{Fold(context_,
1107 ConvertToType<LogicalResult>(LogicalResultKind,
1111 UnwrapConstantValue<LogicalResult>(LogicalResultKind, convertedMask)};
1112 const auto *field{UnwrapConstantValue<T>(kind, args[2])};
1113 if (!vector || !mask || !field) {
1114 return Expr<T>{std::move(funcRef)};
1117 if (field->Rank() > 0 && field->shape() != mask->shape()) {
1119 return MakeInvalidIntrinsic(std::move(funcRef));
1121 ConstantSubscript maskElements{GetSize(mask->shape())};
1122 ConstantSubscript truths{0};
1123 ConstantSubscripts maskAt{mask->lbounds()};
1124 for (ConstantSubscript j{0}; j < maskElements;
1125 ++j, mask->IncrementSubscripts(maskAt)) {
1126 if (mask->At(maskAt).IsTrue()) {
1130 if (truths > GetSize(vector->shape())) {
1131 context_.messages().Say(
1132 "Invalid 'vector=' argument in UNPACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
1133 static_cast<std::intmax_t
>(truths),
1134 static_cast<std::intmax_t
>(GetSize(vector->shape())));
1135 return MakeInvalidIntrinsic(std::move(funcRef));
1137 std::vector<Scalar<T>> resultElements;
1138 ConstantSubscripts vectorAt{vector->lbounds()};
1139 ConstantSubscripts fieldAt{field->lbounds()};
1140 for (ConstantSubscript j{0}; j < maskElements; ++j) {
1141 if (mask->At(maskAt).IsTrue()) {
1142 resultElements.push_back(vector->At(vectorAt));
1143 vector->IncrementSubscripts(vectorAt);
1145 resultElements.push_back(field->At(fieldAt));
1147 mask->IncrementSubscripts(maskAt);
1148 field->IncrementSubscripts(fieldAt);
1150 return Expr<T>{PackageConstant<T>(
1151 kind, std::move(resultElements), *vector, mask->shape())};
1154std::optional<Expr<SomeType>> FoldTransfer(
1158 if (
auto folded{FoldTransfer(context_, funcRef.arguments())}) {
1159 return DEREF(UnwrapExpr<
Expr<T>>(funcRef.kind(), *folded));
1161 return Expr<T>{std::move(funcRef)};
1167template <
typename T>
1170 const int kind{funcRef.kind()};
1171 static_assert(T::category == TypeCategory::Integer ||
1172 T::category == TypeCategory::Unsigned ||
1173 T::category == TypeCategory::Real ||
1174 T::category == TypeCategory::Character);
1197 auto &args{funcRef.arguments()};
1198 std::size_t nargs{args.size()};
1199 bool allArgsConstant{
true};
1200 bool extremumAnyway{nargs == 2 && T::category != TypeCategory::Character};
1204 if (!folder.Folding(args[0])) {
1205 allArgsConstant =
false;
1207 if (!folder.Folding(args[1])) {
1208 allArgsConstant =
false;
1214 for (std::size_t i{2}; i < nargs; ++i) {
1216 if (!folder.Folding(args[i])) {
1217 allArgsConstant =
false;
1225 if (allArgsConstant || extremumAnyway) {
1228 if (
const auto *resultp{UnwrapExpr<Expr<T>>(kind, args[0])}) {
1230 for (std::size_t i{1}; i < nargs; ++i) {
1231 if (
const auto *tExpr{UnwrapExpr<Expr<T>>(kind, args[i])}) {
1232 result = FoldOperation(
1233 context,
Extremum<T>{order, std::move(result), *tExpr});
1236 return Expr<T>{std::move(funcRef)};
1244 return Expr<T>{std::move(funcRef)};
1254template <
typename T>
1255Expr<T> RewriteSpecificMINorMAX(
1257 int kind{funcRef.kind()};
1258 ActualArguments &args{funcRef.arguments()};
1259 auto &intrinsic{DEREF(std::get_if<SpecificIntrinsic>(&funcRef.proc().u))};
1262 std::optional<DynamicType> resultType;
1264 for (
auto j{args.size()}; j-- > 0;) {
1271 (type.category() == resultType->category() &&
1272 type.kind() > resultType->kind()) ||
1273 resultType->category() == TypeCategory::Integer) {
1275 resultTypeArg = &*args[j];
1280 return Expr<T>{std::move(funcRef)};
1283 intrinsic.name.find(
"max") != std::string::npos ?
"max"s :
"min"s;
1284 intrinsic.characteristics.value().functionResult.value().SetType(*resultType);
1285 auto insertConversion{[&](
const auto &x) ->
Expr<T> {
1286 using TR = ResultType<
decltype(x)>;
1287 const int rKind{x.kind()};
1291 context, ConvertToType<T>(kind, AsCategoryExpr(std::move(maxRef))));
1293 if (
auto *sx{UnwrapExpr<Expr<Type<TypeCategory::Real>>>(*resultTypeArg)}) {
1294 return insertConversion(*sx);
1295 }
else if (
auto *sx{UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(
1297 return insertConversion(*sx);
1299 return Expr<T>{std::move(funcRef)};
1331template <
typename T>
1333 const int kind{funcRef.kind()};
1334 ActualArguments &args{funcRef.arguments()};
1335 const auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
1336 if (!intrinsic || intrinsic->name !=
"kind") {
1339 for (std::optional<ActualArgument> &arg : args) {
1340 if (arg && arg->GetConditionalArg()) {
1341 FoldConditionalArg(context, arg);
1342 }
else if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
1343 if (!intrinsic && IsNamedConstantDesignator(*expr)) {
1353 *expr = Fold(context, std::move(*expr));
1379 const bool intrinsicIsIS_CONTIGUOUS{intrinsic->name ==
"is_contiguous"};
1380 std::optional<FunctionRef<T>> viaRepresentative;
1381 for (std::size_t j{0}; j < args.size(); ++j) {
1382 if (args[j] && args[j]->isConditionalArg() && !intrinsicIsIS_CONTIGUOUS) {
1384 DEREF(args[j]->GetConditionalArg())};
1388 if (condArg.HasNilConsequent() ||
1389 !IsTypeOnlyInquiryArg(*intrinsic, j)) {
1390 return Expr<T>{std::move(funcRef)};
1392 if (!viaRepresentative) {
1393 viaRepresentative.emplace(funcRef);
1396 *viaRepresentative->arguments()[j] =
1397 common::Clone(DEREF(condArg.FirstNonNilConsequent()));
1400 if (viaRepresentative) {
1401 Expr<T> folded{FoldOperation(context, std::move(*viaRepresentative))};
1405 return std::holds_alternative<Constant<T>>(folded.u)
1407 :
Expr<T>{std::move(funcRef)};
1409 const std::string name{intrinsic->name};
1410 if (name ==
"cshift") {
1411 return Folder<T>{kind, context}.CSHIFT(std::move(funcRef));
1412 }
else if (name ==
"eoshift") {
1413 return Folder<T>{kind, context}.EOSHIFT(std::move(funcRef));
1414 }
else if (name ==
"merge") {
1415 return Folder<T>{kind, context}.MERGE(std::move(funcRef));
1416 }
else if (name ==
"pack") {
1417 return Folder<T>{kind, context}.PACK(std::move(funcRef));
1418 }
else if (name ==
"reshape") {
1419 return Folder<T>{kind, context}.RESHAPE(std::move(funcRef));
1420 }
else if (name ==
"spread") {
1421 return Folder<T>{kind, context}.SPREAD(std::move(funcRef));
1422 }
else if (name ==
"transfer") {
1423 return Folder<T>{kind, context}.TRANSFER(std::move(funcRef));
1424 }
else if (name ==
"transpose") {
1425 return Folder<T>{kind, context}.TRANSPOSE(std::move(funcRef));
1426 }
else if (name ==
"unpack") {
1427 return Folder<T>{kind, context}.UNPACK(std::move(funcRef));
1430 if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
1433 if (name ==
"huge") {
1435 if (args.size() >= 1 && args[0]) {
1437 UnwrapExpr<Expr<Type<TypeCategory::Derived>>>(args[0])}) {
1438 return std::move(*expr);
1441 }
else if (name ==
"next" || name ==
"previous") {
1442 return FoldEnumerationNextOrPrevious(
1443 context, std::move(funcRef), name ==
"next");
1446 return FoldIntrinsicFunction(context, std::move(funcRef));
1449 return Expr<T>{std::move(funcRef)};
1453template <
typename T>
class ArrayConstructorFolder {
1456 : context_{c}, resultInfo_{kind} {}
1459 const int kind{array.kind()};
1460 if constexpr (T::category == TypeCategory::Character) {
1461 if (
const auto *len{array.LEN()}) {
1462 charLength_ = ToInt64(Fold(context_, common::Clone(*len)));
1463 knownCharLength_ = charLength_.has_value();
1467 if (FoldArray(array)) {
1468 auto n{
static_cast<ConstantSubscript
>(elements_.size())};
1469 if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
1472 std::move(elements_), ConstantSubscripts{n}}};
1473 }
else if constexpr (T::category == TypeCategory::Character) {
1476 kind, *charLength_, std::move(elements_), ConstantSubscripts{n}}};
1479 CHECK(resultInfo_.kind() == kind);
1481 kind, std::move(elements_), ConstantSubscripts{n}, resultInfo_}};
1484 return Expr<T>{std::move(array)};
1488 bool FoldArray(
const Expr<T> &expr) {
1489 const int kind{expr.kind()};
1490 Expr<T> folded{Fold(context_, common::Clone(expr))};
1491 if (
const auto *c{UnwrapConstantValue<T>(kind, folded)}) {
1494 ConstantSubscripts index{c->lbounds()};
1496 elements_.emplace_back(c->At(index));
1497 }
while (c->IncrementSubscripts(index));
1499 if constexpr (T::category == TypeCategory::Character) {
1500 if (!knownCharLength_) {
1501 charLength_ = std::max(c->LEN(), charLength_.value_or(-1));
1503 }
else if constexpr (T::category == TypeCategory::Real ||
1504 T::category == TypeCategory::Complex) {
1505 if (c->result().isFromInexactLiteralConversion()) {
1506 resultInfo_.set_isFromInexactLiteralConversion();
1514 bool FoldArray(
const common::CopyableIndirection<
Expr<T>> &expr) {
1515 return FoldArray(expr.value());
1524 std::optional<ConstantSubscript> start{ToInt64(
lower)}, end{ToInt64(upper)},
1525 step{ToInt64(stride)};
1526 if (start && end && step && *step != 0) {
1528 ConstantSubscript &j{context_.StartImpliedDo(iDo.name(), *start)};
1530 for (; j <= *end; j += *step) {
1531 result &= FoldArray(iDo.values());
1534 for (; j >= *end; j += *step) {
1535 result &= FoldArray(iDo.values());
1538 context_.EndImpliedDo(iDo.name());
1545 return common::visit([&](
const auto &y) {
return FoldArray(y); }, x.u);
1548 for (
const auto &x : xs) {
1549 if (!FoldArray(x)) {
1557 std::vector<Scalar<T>> elements_;
1558 std::optional<ConstantSubscript> charLength_;
1559 bool knownCharLength_{
false};
1560 typename Constant<T>::Result resultInfo_;
1563template <
typename T>
1565 const int kind{array.kind()};
1566 return ArrayConstructorFolder<T>{kind, context}.FoldArray(std::move(array));
1577template <
typename T>
1580 if (!std::holds_alternative<
Expr<T>>(x.u)) {
1587template <
typename T>
1588std::optional<Expr<T>> AsFlatArrayConstructor(
const Expr<T> &expr) {
1589 const int kind{expr.kind()};
1590 if (
const auto *c{UnwrapConstantValue<T>(kind, expr)}) {
1593 ConstantSubscripts at{c->lbounds()};
1595 result.Push(MakeConstantExpr<T>(kind, c->At(at)));
1596 }
while (c->IncrementSubscripts(at));
1598 return std::make_optional<Expr<T>>(std::move(result));
1599 }
else if (
const auto *a{UnwrapExpr<ArrayConstructor<T>>(expr)}) {
1600 if (ArrayConstructorIsFlat(*a)) {
1601 return std::make_optional<Expr<T>>(expr);
1603 }
else if (
const auto *p{UnwrapExpr<Parentheses<T>>(expr)}) {
1604 return AsFlatArrayConstructor(
Expr<T>{p->left()});
1606 return std::nullopt;
1613template <
typename T>
1614std::optional<Expr<T>> FromArrayConstructor(
1616 const int kind{values.kind()};
1617 if (
auto constShape{AsConstantExtents(context, shape)};
1618 constShape && !HasNegativeExtent(*constShape)) {
1620 if (
auto *constant{UnwrapConstantValue<T>(kind, result)}) {
1622 return Expr<T>{constant->Reshape(std::move(*constShape))};
1624 if (constShape->size() == 1) {
1625 if (
auto elements{GetShape(context, result)}) {
1626 if (
auto constElements{AsConstantExtents(context, *elements)}) {
1627 if (constElements->size() == 1 &&
1628 constElements->at(0) == constShape->at(0)) {
1631 return std::move(result);
1637 return std::nullopt;
1648template <
typename RESULT,
typename OPERAND>
1649std::optional<Expr<RESULT>> MapOperation(
int kind,
FoldingContext &context,
1654 auto &aConst{std::get<ArrayConstructor<OPERAND>>(values.u)};
1655 for (
auto &acValue : aConst) {
1656 auto &scalar{std::get<Expr<OPERAND>>(acValue.u)};
1657 result.Push(Fold(context, f(std::move(scalar))));
1659 if constexpr (RESULT::category == TypeCategory::Character) {
1661 result.set_LEN(std::move(*length));
1664 return FromArrayConstructor(context, std::move(result), shape);
1667template <
typename RESULT,
typename A>
1671 if constexpr (RESULT::category == TypeCategory::Character) {
1673 result.set_LEN(std::move(*length));
1679template <
typename LEFT,
typename RIGHT>
1683 auto rightIter{rightArrConst.begin()};
1684 for (
auto &leftValue : leftArrConst) {
1685 CHECK(rightIter != rightArrConst.end());
1686 auto &leftExpr{std::get<Expr<LEFT>>(leftValue.u)};
1687 auto &rightExpr{std::get<Expr<RIGHT>>(rightIter->u)};
1688 if (leftExpr.Rank() != rightExpr.Rank()) {
1691 std::optional<Shape> leftShape{GetShape(context, leftExpr)};
1692 std::optional<Shape> rightShape{GetShape(context, rightExpr)};
1693 if (!leftShape || !rightShape || *leftShape != *rightShape) {
1702template <
typename RESULT,
typename LEFT,
typename RIGHT>
1707 -> std::optional<Expr<RESULT>> {
1709 ArrayConstructorFromMold<RESULT>(kind, leftValues, std::move(length))};
1710 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1711 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1712 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1713 return std::nullopt;
1715 auto rightIter{rightArrConst.begin()};
1716 for (
auto &leftValue : leftArrConst) {
1717 CHECK(rightIter != rightArrConst.end());
1718 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1719 auto &rightScalar{std::get<Expr<RIGHT>>(rightIter->u)};
1721 Fold(context, f(std::move(leftScalar), std::move(rightScalar))));
1724 return FromArrayConstructor(context, std::move(result), shape);
1728template <
typename RESULT,
typename LEFT,
typename RIGHT>
1733 -> std::optional<Expr<RESULT>> {
1735 ArrayConstructorFromMold<RESULT>(kind, leftValues, std::move(length))};
1736 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1737 for (
auto &leftValue : leftArrConst) {
1738 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1740 Fold(context, f(std::move(leftScalar),
Expr<RIGHT>{rightScalar})));
1742 return FromArrayConstructor(context, std::move(result), shape);
1746template <
typename RESULT,
typename LEFT,
typename RIGHT>
1751 -> std::optional<Expr<RESULT>> {
1753 ArrayConstructorFromMold<RESULT>(kind, leftScalar, std::move(length))};
1754 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1755 for (
auto &rightValue : rightArrConst) {
1756 auto &rightScalar{std::get<Expr<RIGHT>>(rightValue.u)};
1758 Fold(context, f(
Expr<LEFT>{leftScalar}, std::move(rightScalar))));
1760 return FromArrayConstructor(context, std::move(result), shape);
1763template <
typename DERIVED,
typename RESULT,
typename... OPD>
1764std::optional<Expr<SubscriptInteger>> ComputeResultLength(
1766 if constexpr (RESULT::category == TypeCategory::Character) {
1769 return std::nullopt;
1776template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1780 -> std::optional<Expr<RESULT>> {
1781 const int kind{operation.kind()};
1782 auto &expr{operation.left()};
1783 expr = Fold(context, std::move(expr));
1784 if (expr.Rank() > 0) {
1785 if (std::optional<Shape> shape{GetShape(context, expr)}) {
1786 if (
auto values{AsFlatArrayConstructor(expr)}) {
1787 return MapOperation(kind, context, std::move(f), *shape,
1788 ComputeResultLength(operation), std::move(*values));
1792 return std::nullopt;
1795template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1796auto ApplyElementwise(
1798 -> std::optional<Expr<RESULT>> {
1799 const int kind{operation.kind()};
1800 return ApplyElementwise(context, operation,
1803 return Expr<RESULT>{DERIVED{kind, std::move(operand)}};
1807template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1811 -> std::optional<Expr<RESULT>> {
1812 const int kind{operation.kind()};
1813 auto resultLength{ComputeResultLength(operation)};
1814 auto &leftExpr{operation.left()};
1815 auto &rightExpr{operation.right()};
1816 if (leftExpr.Rank() != rightExpr.Rank() && leftExpr.Rank() != 0 &&
1817 rightExpr.Rank() != 0) {
1818 return std::nullopt;
1820 leftExpr = Fold(context, std::move(leftExpr));
1821 rightExpr = Fold(context, std::move(rightExpr));
1822 if (leftExpr.Rank() > 0) {
1823 if (std::optional<Shape> leftShape{GetShape(context, leftExpr)}) {
1824 if (
auto left{AsFlatArrayConstructor(leftExpr)}) {
1825 if (rightExpr.Rank() > 0) {
1826 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1827 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1828 if (CheckConformance(context.messages(), *leftShape, *rightShape,
1829 CheckConformanceFlags::EitherScalarExpandable)
1830 .value_or(
false )) {
1831 return MapOperation(kind, context, std::move(f), *leftShape,
1832 std::move(resultLength), std::move(*left),
1835 return std::nullopt;
1837 return MapOperation(kind, context, std::move(f), *leftShape,
1838 std::move(resultLength), std::move(*left), std::move(*right));
1841 }
else if (IsExpandableScalar(rightExpr, context, *leftShape)) {
1842 return MapOperation(kind, context, std::move(f), *leftShape,
1843 std::move(resultLength), std::move(*left), rightExpr);
1847 }
else if (rightExpr.Rank() > 0) {
1848 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1849 if (IsExpandableScalar(leftExpr, context, *rightShape)) {
1850 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1851 return MapOperation(kind, context, std::move(f), *rightShape,
1852 std::move(resultLength), leftExpr, std::move(*right));
1857 return std::nullopt;
1860template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1861auto ApplyElementwise(
1863 -> std::optional<Expr<RESULT>> {
1864 const int kind{operation.kind()};
1865 return ApplyElementwise(context, operation,
1869 DERIVED{kind, std::move(left), std::move(right)}};
1875template <
typename TO,
typename FROM>
1876common::IfNoLvalue<std::optional<TO>, FROM> ConvertString(
1877 int toKind, FROM &&s) {
1878 const int fromKind{s.kind()};
1879 if (std::is_same_v<TO, FROM> && toKind == fromKind) {
1880 return std::make_optional<TO>(std::move(s));
1882 return s.ToAscii(toKind);
1886template <
typename TO, TypeCategory FROMCAT>
1889 const int toKind{convert.kind()};
1890 if (
auto array{ApplyElementwise(context, convert)}) {
1891 return std::move(*array);
1894 auto &operand{convert.left()};
1895 const int operandKind{operand.kind()};
1898 TypeCategory
constexpr FromCat{FROMCAT};
1899 if (
auto value{GetScalarConstantValue<Operand>(operand)}) {
1901 const int fromKind{value->kind()};
1902 if constexpr (TO::category == TypeCategory::Integer) {
1903 if constexpr (FromCat == TypeCategory::Integer) {
1904 auto converted{Scalar<TO>::ConvertSigned(toKind, *value)};
1905 if (converted.overflow) {
1906 ctx.Warn(common::UsageWarning::FoldingException,
1907 "conversion of %s_%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1908 value->SignedDecimal(), fromKind, toKind,
1909 converted.value.SignedDecimal());
1911 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1912 }
else if constexpr (FromCat == TypeCategory::Unsigned) {
1913 auto converted{Scalar<TO>::ConvertUnsigned(toKind, *value)};
1914 if ((converted.overflow || converted.value.IsNegative())) {
1915 ctx.Warn(common::UsageWarning::FoldingException,
1916 "conversion of %s_U%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1917 value->UnsignedDecimal(), fromKind, toKind,
1918 converted.value.SignedDecimal());
1920 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1921 }
else if constexpr (FromCat == TypeCategory::Real) {
1922 auto converted{value->ToInteger(
1923 common::RoundingMode::ToZero, Scalar<TO>::bits(toKind))};
1924 if (converted.flags.test(RealFlag::InvalidArgument)) {
1925 ctx.Warn(common::UsageWarning::FoldingException,
1926 "REAL(%d) to INTEGER(%d) conversion: invalid argument"_warn_en_US,
1928 }
else if (converted.flags.test(RealFlag::Overflow)) {
1929 ctx.Warn(common::UsageWarning::FoldingException,
1930 "REAL(%d) to INTEGER(%d) conversion overflowed"_warn_en_US,
1933 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1935 }
else if constexpr (TO::category == TypeCategory::Unsigned) {
1936 if constexpr (FromCat == TypeCategory::Integer ||
1937 FromCat == TypeCategory::Unsigned) {
1938 return MakeConstantExpr<TO>(
1939 toKind, Scalar<TO>::ConvertUnsigned(toKind, *value).value);
1940 }
else if constexpr (FromCat == TypeCategory::Real) {
1941 return MakeConstantExpr<TO>(toKind,
1944 common::RoundingMode::ToZero, Scalar<TO>::bits(toKind))
1947 }
else if constexpr (TO::category == TypeCategory::Real) {
1948 if constexpr (FromCat == TypeCategory::Integer ||
1949 FromCat == TypeCategory::Unsigned) {
1950 auto converted{Scalar<TO>::FromInteger(
1951 toKind, *value, FromCat == TypeCategory::Unsigned)};
1952 if (!converted.flags.empty()) {
1954 std::snprintf(buffer,
sizeof buffer,
1955 "INTEGER(%d) to REAL(%d) conversion", fromKind, toKind);
1956 ctx.RealFlagWarnings(converted.flags, buffer);
1958 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1959 }
else if constexpr (FromCat == TypeCategory::Real) {
1960 auto converted{Scalar<TO>::Convert(toKind, *value)};
1962 if (!converted.flags.empty()) {
1963 std::snprintf(buffer,
sizeof buffer,
1964 "REAL(%d) to REAL(%d) conversion", fromKind, toKind);
1965 ctx.RealFlagWarnings(converted.flags, buffer);
1967 if (ctx.targetCharacteristics().areSubnormalsFlushedToZero()) {
1968 converted.value = converted.value.FlushSubnormalToZero();
1970 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1972 }
else if constexpr (TO::category == TypeCategory::Complex) {
1973 if constexpr (FromCat == TypeCategory::Complex) {
1974 auto real{value->REAL()};
1975 auto imag{value->AIMAG()};
1976 return FoldOperation(ctx,
1981 real.kind(), real})))),
1985 imag.kind(), imag}))))});
1987 }
else if constexpr (TO::category == TypeCategory::Character &&
1988 FromCat == TypeCategory::Character) {
1990 ConvertString<Scalar<TO>>(toKind, std::move(*value))}) {
1991 return ScalarConstantToExpr(std::move(*converted));
1993 }
else if constexpr (TO::category == TypeCategory::Logical &&
1994 FromCat == TypeCategory::Logical) {
1995 return MakeConstantExpr<TO>(toKind, value->IsTrue());
1997 }
else if constexpr (TO::category == FromCat &&
1998 FromCat != TypeCategory::Character) {
2000 if (Operand::category == TO::category && toKind == operandKind) {
2001 return std::move(operand);
2002 }
else if constexpr (TO::category == TypeCategory::Logical ||
2003 TO::category == TypeCategory::Integer) {
2004 if (
auto *innerConv{
2005 std::get_if<Convert<Operand, TO::category>>(&operand.u)}) {
2007 if (
auto *x{&innerConv->left()}; x->kind() == toKind) {
2008 if (TO::category == TypeCategory::Logical || toKind <= operandKind) {
2009 return std::move(*x);
2011 }
else if constexpr (std::is_same_v<TO, DescriptorInquiry::Result>) {
2012 if (toKind == DescriptorInquiry::kind()) {
2013 if (std::holds_alternative<DescriptorInquiry>(x->u) ||
2014 std::holds_alternative<TypeParamInquiry>(x->u)) {
2016 return std::move(*x);
2024 return Expr<TO>{std::move(convert)};
2027template <
typename T>
2029 const int kind{x.kind()};
2030 auto &operand{x.left()};
2031 operand = Fold(context, std::move(operand));
2032 if (
auto value{GetScalarConstantValue<T>(kind, operand)}) {
2037 return std::move(operand);
2043template <
typename T>
2045 const int kind{x.kind()};
2046 if (
auto array{ApplyElementwise(context, x)}) {
2047 return std::move(*array);
2049 auto &operand{x.left()};
2050 if (
auto *nn{std::get_if<Negate<T>>(&x.left().u)}; nn && nn->kind() == kind) {
2052 if (IsVariable(nn->left())) {
2053 return FoldOperation(context,
Parentheses<T>{std::move(nn->left())});
2055 return std::move(nn->left());
2057 }
else if (
auto value{GetScalarConstantValue<T>(kind, operand)}) {
2058 if constexpr (T::category == TypeCategory::Integer) {
2059 auto negated{value->Negate()};
2060 if (negated.overflow) {
2061 context.Warn(common::UsageWarning::FoldingException,
2062 "INTEGER(%d) negation overflowed"_warn_en_US, kind);
2065 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2077template <
typename LEFT,
typename RIGHT>
2078std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2080 if (
auto xvalue{GetScalarConstantValue<LEFT>(x)}) {
2081 if (
auto yvalue{GetScalarConstantValue<RIGHT>(y)}) {
2082 return {std::make_pair(*xvalue, *yvalue)};
2085 return std::nullopt;
2088template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
2089std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2091 return OperandsAreConstants(operation.left(), operation.right());
2094template <
typename T>
2096 const int kind{x.kind()};
2097 if (
auto array{ApplyElementwise(context, x)}) {
2098 return std::move(*array);
2100 if (
auto folded{OperandsAreConstants(x)}) {
2101 if constexpr (T::category == TypeCategory::Integer) {
2102 auto sum{folded->first.AddSigned(folded->second)};
2104 context.Warn(common::UsageWarning::FoldingException,
2105 "INTEGER(%d) addition overflowed"_warn_en_US, kind);
2108 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2110 Constant<T>{kind, folded->first.AddUnsigned(folded->second).value}};
2112 auto sum{folded->first.Add(
2113 folded->second, context.targetCharacteristics().roundingMode())};
2114 context.RealFlagWarnings(sum.flags,
"addition");
2115 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2116 sum.value = sum.value.FlushSubnormalToZero();
2120 }
else if constexpr (T::category == TypeCategory::Integer ||
2121 T::category == TypeCategory::Unsigned) {
2122 if (
auto c{GetScalarConstantValue<T>(kind, x.right())}) {
2123 if (c->IsZero() && x.left().Rank() == 0) {
2124 if (IsVariable(x.left())) {
2125 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2127 return std::move(x.left());
2130 }
else if (
auto c{GetScalarConstantValue<T>(kind, x.left())}) {
2131 if (c->IsZero() && x.right().Rank() == 0) {
2132 if (IsVariable(x.right())) {
2133 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2135 return std::move(x.right());
2143template <
typename T>
2145 const int kind{x.kind()};
2146 if (
auto array{ApplyElementwise(context, x)}) {
2147 return std::move(*array);
2149 if (
auto folded{OperandsAreConstants(x)}) {
2150 if constexpr (T::category == TypeCategory::Integer) {
2151 auto difference{folded->first.SubtractSigned(folded->second)};
2152 if (difference.overflow) {
2153 context.Warn(common::UsageWarning::FoldingException,
2154 "INTEGER(%d) subtraction overflowed"_warn_en_US, kind);
2157 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2159 kind, folded->first.SubtractSigned(folded->second).value}};
2161 auto difference{folded->first.Subtract(
2162 folded->second, context.targetCharacteristics().roundingMode())};
2163 context.RealFlagWarnings(difference.flags,
"subtraction");
2164 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2165 difference.value = difference.value.FlushSubnormalToZero();
2169 }
else if constexpr (T::category == TypeCategory::Integer ||
2170 T::category == TypeCategory::Unsigned) {
2171 if (
auto c{GetScalarConstantValue<T>(kind, x.right())}) {
2172 if (c->IsZero() && x.left().Rank() == 0) {
2173 if (IsVariable(x.left())) {
2174 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2176 return std::move(x.left());
2184template <
typename T>
2186 const int kind{x.kind()};
2187 if (
auto array{ApplyElementwise(context, x)}) {
2188 return std::move(*array);
2190 if (
auto folded{OperandsAreConstants(x)}) {
2191 if constexpr (T::category == TypeCategory::Integer) {
2192 auto product{folded->first.MultiplySigned(folded->second)};
2193 if (product.SignedMultiplicationOverflowed()) {
2194 context.Warn(common::UsageWarning::FoldingException,
2195 "INTEGER(%d) multiplication overflowed"_warn_en_US, kind);
2198 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2200 kind, folded->first.MultiplyUnsigned(folded->second).lower}};
2202 auto product{folded->first.Multiply(
2203 folded->second, context.targetCharacteristics().roundingMode())};
2204 context.RealFlagWarnings(product.flags,
"multiplication");
2205 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2206 product.value = product.value.FlushSubnormalToZero();
2210 }
else if constexpr (T::category == TypeCategory::Integer) {
2211 if (
auto c{GetScalarConstantValue<T>(kind, x.right())}) {
2212 x.right() = std::move(x.left());
2213 x.left() = MakeConstantExpr<T>(kind, *c);
2215 if (
auto c{GetScalarConstantValue<T>(kind, x.left())}) {
2216 if (c->IsZero() && x.right().Rank() == 0) {
2217 return std::move(x.left());
2220 if (IsVariable(x.right())) {
2221 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2223 return std::move(x.right());
2227 return FoldOperation(context,
Negate<T>{std::move(x.right())});
2234template <
typename T>
2236 const int kind{x.kind()};
2237 if (
auto array{ApplyElementwise(context, x)}) {
2238 return std::move(*array);
2240 if (
auto folded{OperandsAreConstants(x)}) {
2241 if constexpr (T::category == TypeCategory::Integer) {
2242 auto quotAndRem{folded->first.DivideSigned(folded->second)};
2243 if (quotAndRem.divisionByZero) {
2244 context.Warn(common::UsageWarning::FoldingException,
2245 "INTEGER(%d) division by zero"_warn_en_US, kind);
2248 if (quotAndRem.overflow) {
2249 context.Warn(common::UsageWarning::FoldingException,
2250 "INTEGER(%d) division overflowed"_warn_en_US, kind);
2253 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2254 auto quotAndRem{folded->first.DivideUnsigned(folded->second)};
2255 if (quotAndRem.divisionByZero) {
2256 context.Warn(common::UsageWarning::FoldingException,
2257 "UNSIGNED(%d) division by zero"_warn_en_US, kind);
2262 auto quotient{folded->first.Divide(
2263 folded->second, context.targetCharacteristics().roundingMode())};
2267 bool isCanonicalNaNOrInf{
false};
2268 if constexpr (T::category == TypeCategory::Real) {
2269 if (folded->second.IsZero() && context.moduleFileName().has_value()) {
2270 using IntType =
typename T::Scalar::Word;
2271 auto intNumerator{folded->first.ToInteger()};
2272 const int intKind{intNumerator.value.kind()};
2273 isCanonicalNaNOrInf = intNumerator.flags == RealFlags{} &&
2274 intNumerator.value >= IntType{intKind, -1} &&
2275 intNumerator.value <= IntType{intKind, 1};
2278 if (!isCanonicalNaNOrInf) {
2279 context.RealFlagWarnings(quotient.flags,
"division");
2281 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2282 quotient.value = quotient.value.FlushSubnormalToZero();
2290template <
typename T>
2292 const int kind{x.kind()};
2293 if (
auto array{ApplyElementwise(context, x)}) {
2294 return std::move(*array);
2296 if (
auto folded{OperandsAreConstants(x)}) {
2297 if constexpr (T::category == TypeCategory::Integer) {
2298 auto power{folded->first.Power(folded->second)};
2299 if (power.divisionByZero) {
2300 context.Warn(common::UsageWarning::FoldingException,
2301 "INTEGER(%d) zero to negative power"_warn_en_US, kind);
2302 }
else if (power.overflow) {
2303 context.Warn(common::UsageWarning::FoldingException,
2304 "INTEGER(%d) power overflowed"_warn_en_US, kind);
2305 }
else if (power.zeroToZero) {
2306 context.Warn(common::UsageWarning::FoldingException,
2307 "INTEGER(%d) 0**0 is not defined"_warn_en_US, kind);
2311 if (folded->first.IsZero()) {
2312 if (folded->second.IsZero()) {
2313 context.Warn(common::UsageWarning::FoldingException,
2314 "REAL/COMPLEX 0**0 is not defined"_warn_en_US);
2319 }
else if (
auto callable{GetHostRuntimeWrapper<T, T, T>(
2320 kind, {kind, kind},
"pow")}) {
2322 kind, (*callable)(context, folded->first, folded->second)}};
2324 context.Warn(common::UsageWarning::FoldingFailure,
2325 "Power for %s cannot be folded on host"_warn_en_US,
2333template <
typename T>
2335 const int kind{x.kind()};
2336 if (
auto array{ApplyElementwise(context, x)}) {
2337 return std::move(*array);
2339 if (
auto folded{OperandsAreConstants(x.left(), x.right())}) {
2341 if constexpr (T::category == TypeCategory::Complex) {
2346 using DoubleComplex = Scalar<Type<TypeCategory::Complex>>;
2347 using DoublePart = DoubleComplex::Part;
2348 using SinglePart =
typename Scalar<T>::Part;
2350 DoubleComplex wideBase{
2351 DoublePart::Convert(8, folded->first.REAL()).value,
2352 DoublePart::Convert(8, folded->first.AIMAG()).value};
2353 auto wide{evaluate::IntPower(wideBase, folded->second)};
2354 power.flags = wide.flags;
2355 power.value = Scalar<T>{SinglePart::Convert(kind, wide.value.REAL())
2356 .AccumulateFlags(power.flags),
2357 SinglePart::Convert(kind, wide.value.AIMAG())
2358 .AccumulateFlags(power.flags)};
2360 power = evaluate::IntPower(folded->first, folded->second);
2363 power = evaluate::IntPower(folded->first, folded->second);
2365 context.RealFlagWarnings(power.flags,
"power with INTEGER exponent");
2366 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2367 power.value = power.value.FlushSubnormalToZero();
2374template <
typename T>
2376 x.condition() = Fold(context, std::move(x.condition()));
2378 if (
auto cst{GetScalarConstantValue<LogicalResult>(
2379 LogicalResultKind, x.condition())}) {
2380 return cst->IsTrue() ? Fold(context, std::move(x.thenValue()))
2381 : Fold(context, std::move(x.elseValue()));
2386template <
typename T>
2388 const int kind{x.kind()};
2389 if (
auto array{ApplyElementwise(context, x,
2393 Extremum<T>{ordering, std::move(l), std::move(r)}};
2395 return std::move(*array);
2397 if (
auto folded{OperandsAreConstants(x)}) {
2398 if constexpr (T::category == TypeCategory::Integer) {
2399 if (folded->first.CompareSigned(folded->second) == x.ordering) {
2402 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2403 if (folded->first.CompareUnsigned(folded->second) == x.ordering) {
2406 }
else if constexpr (T::category == TypeCategory::Real) {
2407 if (folded->first.IsNotANumber() ||
2408 (folded->first.Compare(folded->second) == Relation::Less) ==
2409 (x.ordering == Ordering::Less)) {
2413 static_assert(T::category == TypeCategory::Character);
2416 auto maxLen{std::max(folded->first.length(), folded->second.length())};
2417 bool isFirst{x.ordering == Compare(folded->first, folded->second)};
2418 auto res{isFirst ? std::move(folded->first) : std::move(folded->second)};
2419 res = res.length() == maxLen ? std::move(res)
2420 : CharacterUtils::Resize(res, maxLen);
2435 if constexpr (T::category == TypeCategory::Integer ||
2436 T::category == TypeCategory::Unsigned) {
2437 auto absorbs{[&](
const Expr<T> &operand,
const Expr<T> &nested) {
2438 const auto *c{std::get_if<Constant<T>>(&operand.u)};
2439 const auto *inner{std::get_if<Extremum<T>>(&nested.u)};
2440 if (!c || !inner || inner->ordering != x.ordering) {
2443 auto isSameConstant{[&](
const Expr<T> &y) {
2444 const auto *ic{std::get_if<Constant<T>>(&y.u)};
2445 return ic && *ic == *c;
2447 return isSameConstant(inner->left()) || isSameConstant(inner->right());
2449 if (absorbs(x.left(), x.right())) {
2450 return Expr<T>{std::move(x.right())};
2451 }
else if (absorbs(x.right(), x.left())) {
2452 return Expr<T>{std::move(x.left())};
2461template <
typename T>
2463 return common::visit(
2465 if constexpr (IsSpecificIntrinsicType<T>) {
2466 return FoldOperation(context, std::move(x));
2467 }
else if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
2468 return FoldOperation(context, std::move(x));
2469 }
else if constexpr (common::HasMember<
decltype(x),
2470 TypelessExpression>) {
2471 return std::move(expr);
2473 return Expr<T>{Fold(context, std::move(x))};
Definition expression.h:512
Definition expression.h:540
Definition variable.h:209
Definition variable.h:247
Definition variable.h:362
Definition expression.h:415
Definition constant.h:181
Definition variable.h:386
Definition expression.h:64
Definition fold-implementation.h:54
Definition expression.h:478
Definition variable.h:101
Definition expression.h:114
Definition variable.h:488
Definition expression.h:853
Definition variable.h:309
Definition variable.h:165
Definition variable.h:136
Definition integer-value.h:35
Definition ParserActions.h:24
Definition expression.h:309
Definition expression.h:506
Definition expression.h:275
Definition expression.h:373
Definition expression.h:218
Definition variable.h:293
Definition expression.h:330
Definition expression.h:354
Definition expression.h:464
Definition expression.h:323
Definition expression.h:263
Definition expression.h:237
Definition expression.h:337
Definition expression.h:346
Definition variable.h:196
Definition expression.h:316