1 //===-- lib/Evaluate/fold-real.cpp ----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "fold-implementation.h"
10 #include "fold-reduction.h"
11 
12 namespace Fortran::evaluate {
13 
14 template <int KIND>
FoldIntrinsicFunction(FoldingContext & context,FunctionRef<Type<TypeCategory::Real,KIND>> && funcRef)15 Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
16     FoldingContext &context,
17     FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) {
18   using T = Type<TypeCategory::Real, KIND>;
19   using ComplexT = Type<TypeCategory::Complex, KIND>;
20   ActualArguments &args{funcRef.arguments()};
21   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
22   CHECK(intrinsic);
23   std::string name{intrinsic->name};
24   if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" ||
25       (name == "atan" && args.size() == 1) || name == "atanh" ||
26       name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" ||
27       name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" ||
28       name == "erfc" || name == "erfc_scaled" || name == "exp" ||
29       name == "gamma" || name == "log" || name == "log10" ||
30       name == "log_gamma" || name == "sin" || name == "sinh" || name == "tan" ||
31       name == "tanh") {
32     CHECK(args.size() == 1);
33     if (auto callable{GetHostRuntimeWrapper<T, T>(name)}) {
34       return FoldElementalIntrinsic<T, T>(
35           context, std::move(funcRef), *callable);
36     } else {
37       context.messages().Say(
38           "%s(real(kind=%d)) cannot be folded on host"_en_US, name, KIND);
39     }
40   } else if (name == "amax0" || name == "amin0" || name == "amin1" ||
41       name == "amax1" || name == "dmin1" || name == "dmax1") {
42     return RewriteSpecificMINorMAX(context, std::move(funcRef));
43   } else if (name == "atan" || name == "atan2" || name == "mod") {
44     std::string localName{name == "atan" ? "atan2" : name};
45     CHECK(args.size() == 2);
46     if (auto callable{GetHostRuntimeWrapper<T, T, T>(localName)}) {
47       return FoldElementalIntrinsic<T, T, T>(
48           context, std::move(funcRef), *callable);
49     } else {
50       context.messages().Say(
51           "%s(real(kind=%d), real(kind%d)) cannot be folded on host"_en_US,
52           name, KIND, KIND);
53     }
54   } else if (name == "bessel_jn" || name == "bessel_yn") {
55     if (args.size() == 2) { // elemental
56       // runtime functions use int arg
57       using Int4 = Type<TypeCategory::Integer, 4>;
58       if (auto callable{GetHostRuntimeWrapper<T, Int4, T>(name)}) {
59         return FoldElementalIntrinsic<T, Int4, T>(
60             context, std::move(funcRef), *callable);
61       } else {
62         context.messages().Say(
63             "%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_en_US,
64             name, KIND);
65       }
66     }
67   } else if (name == "abs") {
68     // Argument can be complex or real
69     if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
70       return FoldElementalIntrinsic<T, T>(
71           context, std::move(funcRef), &Scalar<T>::ABS);
72     } else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
73       return FoldElementalIntrinsic<T, ComplexT>(context, std::move(funcRef),
74           ScalarFunc<T, ComplexT>([](const Scalar<ComplexT> &z) -> Scalar<T> {
75             return z.ABS().value;
76           }));
77     } else {
78       common::die(" unexpected argument type inside abs");
79     }
80   } else if (name == "aimag") {
81     return FoldElementalIntrinsic<T, ComplexT>(
82         context, std::move(funcRef), &Scalar<ComplexT>::AIMAG);
83   } else if (name == "aint" || name == "anint") {
84     // ANINT rounds ties away from zero, not to even
85     common::RoundingMode mode{name == "aint"
86             ? common::RoundingMode::ToZero
87             : common::RoundingMode::TiesAwayFromZero};
88     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
89         ScalarFunc<T, T>([&name, &context, mode](
90                              const Scalar<T> &x) -> Scalar<T> {
91           ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)};
92           if (y.flags.test(RealFlag::Overflow)) {
93             context.messages().Say("%s intrinsic folding overflow"_en_US, name);
94           }
95           return y.value;
96         }));
97   } else if (name == "dprod") {
98     if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) {
99       return Fold(context,
100           Expr<T>{Multiply<T>{
101               Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}});
102     }
103   } else if (name == "epsilon") {
104     return Expr<T>{Scalar<T>::EPSILON()};
105   } else if (name == "huge") {
106     return Expr<T>{Scalar<T>::HUGE()};
107   } else if (name == "hypot") {
108     CHECK(args.size() == 2);
109     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
110         ScalarFunc<T, T, T>(
111             [](const Scalar<T> &x, const Scalar<T> &y) -> Scalar<T> {
112               return x.HYPOT(y).value;
113             }));
114   } else if (name == "max") {
115     return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
116   } else if (name == "maxval") {
117     return FoldMaxvalMinval<T>(context, std::move(funcRef),
118         RelationalOperator::GT, T::Scalar::HUGE().Negate());
119   } else if (name == "merge") {
120     return FoldMerge<T>(context, std::move(funcRef));
121   } else if (name == "min") {
122     return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
123   } else if (name == "minval") {
124     return FoldMaxvalMinval<T>(
125         context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE());
126   } else if (name == "product") {
127     auto one{Scalar<T>::FromInteger(value::Integer<8>{1}).value};
128     return FoldProduct<T>(context, std::move(funcRef), one);
129   } else if (name == "real") {
130     if (auto *expr{args[0].value().UnwrapExpr()}) {
131       return ToReal<KIND>(context, std::move(*expr));
132     }
133   } else if (name == "sign") {
134     return FoldElementalIntrinsic<T, T, T>(
135         context, std::move(funcRef), &Scalar<T>::SIGN);
136   } else if (name == "sqrt") {
137     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
138         ScalarFunc<T, T>(
139             [](const Scalar<T> &x) -> Scalar<T> { return x.SQRT().value; }));
140   } else if (name == "sum") {
141     return FoldSum<T>(context, std::move(funcRef));
142   } else if (name == "tiny") {
143     return Expr<T>{Scalar<T>::TINY()};
144   }
145   // TODO: dim, dot_product, fraction, matmul,
146   // modulo, nearest, norm2, rrspacing, scale,
147   // __builtin_next_after/down/up,
148   // set_exponent, spacing, transfer,
149   // bessel_jn (transformational) and bessel_yn (transformational)
150   return Expr<T>{std::move(funcRef)};
151 }
152 
153 template <int KIND>
FoldOperation(FoldingContext & context,ComplexComponent<KIND> && x)154 Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
155     FoldingContext &context, ComplexComponent<KIND> &&x) {
156   using Operand = Type<TypeCategory::Complex, KIND>;
157   using Result = Type<TypeCategory::Real, KIND>;
158   if (auto array{ApplyElementwise(context, x,
159           std::function<Expr<Result>(Expr<Operand> &&)>{
160               [=](Expr<Operand> &&operand) {
161                 return Expr<Result>{ComplexComponent<KIND>{
162                     x.isImaginaryPart, std::move(operand)}};
163               }})}) {
164     return *array;
165   }
166   using Part = Type<TypeCategory::Real, KIND>;
167   auto &operand{x.left()};
168   if (auto value{GetScalarConstantValue<Operand>(operand)}) {
169     if (x.isImaginaryPart) {
170       return Expr<Part>{Constant<Part>{value->AIMAG()}};
171     } else {
172       return Expr<Part>{Constant<Part>{value->REAL()}};
173     }
174   }
175   return Expr<Part>{std::move(x)};
176 }
177 
178 FOR_EACH_REAL_KIND(template class ExpressionBase, )
179 template class ExpressionBase<SomeReal>;
180 } // namespace Fortran::evaluate
181