xref: /llvm-project/flang/lib/Evaluate/fold-logical.cpp (revision 2f80b73e0cf03ddfebc5d0851d5fae29fe1de5d0)
1 //===-- lib/Evaluate/fold-logical.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 #include "flang/Evaluate/check-expression.h"
12 
13 namespace Fortran::evaluate {
14 
15 // for ALL & ANY
16 template <typename T>
17 static Expr<T> FoldAllAny(FoldingContext &context, FunctionRef<T> &&ref,
18     Scalar<T> (Scalar<T>::*operation)(const Scalar<T> &) const,
19     Scalar<T> identity) {
20   static_assert(T::category == TypeCategory::Logical);
21   using Element = Scalar<T>;
22   std::optional<int> dim;
23   if (std::optional<Constant<T>> array{
24           ProcessReductionArgs<T>(context, ref.arguments(), dim, identity,
25               /*ARRAY(MASK)=*/0, /*DIM=*/1)}) {
26     auto accumulator{[&](Element &element, const ConstantSubscripts &at) {
27       element = (element.*operation)(array->At(at));
28     }};
29     return Expr<T>{DoReduction<T>(*array, dim, identity, accumulator)};
30   }
31   return Expr<T>{std::move(ref)};
32 }
33 
34 template <int KIND>
35 Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
36     FoldingContext &context,
37     FunctionRef<Type<TypeCategory::Logical, KIND>> &&funcRef) {
38   using T = Type<TypeCategory::Logical, KIND>;
39   ActualArguments &args{funcRef.arguments()};
40   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
41   CHECK(intrinsic);
42   std::string name{intrinsic->name};
43   using SameInt = Type<TypeCategory::Integer, KIND>;
44   if (name == "all") {
45     return FoldAllAny(
46         context, std::move(funcRef), &Scalar<T>::AND, Scalar<T>{true});
47   } else if (name == "any") {
48     return FoldAllAny(
49         context, std::move(funcRef), &Scalar<T>::OR, Scalar<T>{false});
50   } else if (name == "associated") {
51     bool gotConstant{true};
52     const Expr<SomeType> *firstArgExpr{args[0]->UnwrapExpr()};
53     if (!firstArgExpr || !IsNullPointer(*firstArgExpr)) {
54       gotConstant = false;
55     } else if (args[1]) { // There's a second argument
56       const Expr<SomeType> *secondArgExpr{args[1]->UnwrapExpr()};
57       if (!secondArgExpr || !IsNullPointer(*secondArgExpr)) {
58         gotConstant = false;
59       }
60     }
61     return gotConstant ? Expr<T>{false} : Expr<T>{std::move(funcRef)};
62   } else if (name == "bge" || name == "bgt" || name == "ble" || name == "blt") {
63     static_assert(std::is_same_v<Scalar<LargestInt>, BOZLiteralConstant>);
64     // Arguments do not have to be of the same integer type. Convert all
65     // arguments to the biggest integer type before comparing them to
66     // simplify.
67     for (int i{0}; i <= 1; ++i) {
68       if (auto *x{UnwrapExpr<Expr<SomeInteger>>(args[i])}) {
69         *args[i] = AsGenericExpr(
70             Fold(context, ConvertToType<LargestInt>(std::move(*x))));
71       } else if (auto *x{UnwrapExpr<BOZLiteralConstant>(args[i])}) {
72         *args[i] = AsGenericExpr(Constant<LargestInt>{std::move(*x)});
73       }
74     }
75     auto fptr{&Scalar<LargestInt>::BGE};
76     if (name == "bge") { // done in fptr declaration
77     } else if (name == "bgt") {
78       fptr = &Scalar<LargestInt>::BGT;
79     } else if (name == "ble") {
80       fptr = &Scalar<LargestInt>::BLE;
81     } else if (name == "blt") {
82       fptr = &Scalar<LargestInt>::BLT;
83     } else {
84       common::die("missing case to fold intrinsic function %s", name.c_str());
85     }
86     return FoldElementalIntrinsic<T, LargestInt, LargestInt>(context,
87         std::move(funcRef),
88         ScalarFunc<T, LargestInt, LargestInt>(
89             [&fptr](const Scalar<LargestInt> &i, const Scalar<LargestInt> &j) {
90               return Scalar<T>{std::invoke(fptr, i, j)};
91             }));
92   } else if (name == "btest") {
93     if (const auto *ix{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
94       return std::visit(
95           [&](const auto &x) {
96             using IT = ResultType<decltype(x)>;
97             return FoldElementalIntrinsic<T, IT, SameInt>(context,
98                 std::move(funcRef),
99                 ScalarFunc<T, IT, SameInt>(
100                     [&](const Scalar<IT> &x, const Scalar<SameInt> &pos) {
101                       auto posVal{pos.ToInt64()};
102                       if (posVal < 0 || posVal >= x.bits) {
103                         context.messages().Say(
104                             "POS=%jd out of range for BTEST"_err_en_US,
105                             static_cast<std::intmax_t>(posVal));
106                       }
107                       return Scalar<T>{x.BTEST(posVal)};
108                     }));
109           },
110           ix->u);
111     }
112   } else if (name == "isnan" || name == "__builtin_ieee_is_nan") {
113     // A warning about an invalid argument is discarded from converting
114     // the argument of isnan() / IEEE_IS_NAN().
115     auto restorer{context.messages().DiscardMessages()};
116     using DefaultReal = Type<TypeCategory::Real, 4>;
117     return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
118         ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
119           return Scalar<T>{x.IsNotANumber()};
120         }));
121   } else if (name == "is_contiguous") {
122     if (args.at(0)) {
123       if (auto *expr{args[0]->UnwrapExpr()}) {
124         if (IsSimplyContiguous(*expr, context)) {
125           return Expr<T>{true};
126         }
127       }
128     }
129   } else if (name == "lge" || name == "lgt" || name == "lle" || name == "llt") {
130     // Rewrite LGE/LGT/LLE/LLT into ASCII character relations
131     auto *cx0{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
132     auto *cx1{UnwrapExpr<Expr<SomeCharacter>>(args[1])};
133     if (cx0 && cx1) {
134       return Fold(context,
135           ConvertToType<T>(
136               PackageRelation(name == "lge" ? RelationalOperator::GE
137                       : name == "lgt"       ? RelationalOperator::GT
138                       : name == "lle"       ? RelationalOperator::LE
139                                             : RelationalOperator::LT,
140                   ConvertToType<Ascii>(std::move(*cx0)),
141                   ConvertToType<Ascii>(std::move(*cx1)))));
142     }
143   } else if (name == "logical") {
144     if (auto *expr{UnwrapExpr<Expr<SomeLogical>>(args[0])}) {
145       return Fold(context, ConvertToType<T>(std::move(*expr)));
146     }
147   } else if (name == "merge") {
148     return FoldMerge<T>(context, std::move(funcRef));
149   } else if (name == "__builtin_ieee_support_datatype" ||
150       name == "__builtin_ieee_support_denormal" ||
151       name == "__builtin_ieee_support_divide" ||
152       name == "__builtin_ieee_support_divide" ||
153       name == "__builtin_ieee_support_inf" ||
154       name == "__builtin_ieee_support_io" ||
155       name == "__builtin_ieee_support_nan" ||
156       name == "__builtin_ieee_support_sqrt" ||
157       name == "__builtin_ieee_support_standard" ||
158       name == "__builtin_ieee_support_subnormal" ||
159       name == "__builtin_ieee_support_underflow_control") {
160     return Expr<T>{true};
161   }
162   // TODO: dot_product, is_iostat_end,
163   // is_iostat_eor, logical, matmul, out_of_range,
164   // parity, transfer
165   return Expr<T>{std::move(funcRef)};
166 }
167 
168 template <typename T>
169 Expr<LogicalResult> FoldOperation(
170     FoldingContext &context, Relational<T> &&relation) {
171   if (auto array{ApplyElementwise(context, relation,
172           std::function<Expr<LogicalResult>(Expr<T> &&, Expr<T> &&)>{
173               [=](Expr<T> &&x, Expr<T> &&y) {
174                 return Expr<LogicalResult>{Relational<SomeType>{
175                     Relational<T>{relation.opr, std::move(x), std::move(y)}}};
176               }})}) {
177     return *array;
178   }
179   if (auto folded{OperandsAreConstants(relation)}) {
180     bool result{};
181     if constexpr (T::category == TypeCategory::Integer) {
182       result =
183           Satisfies(relation.opr, folded->first.CompareSigned(folded->second));
184     } else if constexpr (T::category == TypeCategory::Real) {
185       result = Satisfies(relation.opr, folded->first.Compare(folded->second));
186     } else if constexpr (T::category == TypeCategory::Complex) {
187       result = (relation.opr == RelationalOperator::EQ) ==
188           folded->first.Equals(folded->second);
189     } else if constexpr (T::category == TypeCategory::Character) {
190       result = Satisfies(relation.opr, Compare(folded->first, folded->second));
191     } else {
192       static_assert(T::category != TypeCategory::Logical);
193     }
194     return Expr<LogicalResult>{Constant<LogicalResult>{result}};
195   }
196   return Expr<LogicalResult>{Relational<SomeType>{std::move(relation)}};
197 }
198 
199 Expr<LogicalResult> FoldOperation(
200     FoldingContext &context, Relational<SomeType> &&relation) {
201   return std::visit(
202       [&](auto &&x) {
203         return Expr<LogicalResult>{FoldOperation(context, std::move(x))};
204       },
205       std::move(relation.u));
206 }
207 
208 template <int KIND>
209 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
210     FoldingContext &context, Not<KIND> &&x) {
211   if (auto array{ApplyElementwise(context, x)}) {
212     return *array;
213   }
214   using Ty = Type<TypeCategory::Logical, KIND>;
215   auto &operand{x.left()};
216   if (auto value{GetScalarConstantValue<Ty>(operand)}) {
217     return Expr<Ty>{Constant<Ty>{!value->IsTrue()}};
218   }
219   return Expr<Ty>{x};
220 }
221 
222 template <int KIND>
223 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
224     FoldingContext &context, LogicalOperation<KIND> &&operation) {
225   using LOGICAL = Type<TypeCategory::Logical, KIND>;
226   if (auto array{ApplyElementwise(context, operation,
227           std::function<Expr<LOGICAL>(Expr<LOGICAL> &&, Expr<LOGICAL> &&)>{
228               [=](Expr<LOGICAL> &&x, Expr<LOGICAL> &&y) {
229                 return Expr<LOGICAL>{LogicalOperation<KIND>{
230                     operation.logicalOperator, std::move(x), std::move(y)}};
231               }})}) {
232     return *array;
233   }
234   if (auto folded{OperandsAreConstants(operation)}) {
235     bool xt{folded->first.IsTrue()}, yt{folded->second.IsTrue()}, result{};
236     switch (operation.logicalOperator) {
237     case LogicalOperator::And:
238       result = xt && yt;
239       break;
240     case LogicalOperator::Or:
241       result = xt || yt;
242       break;
243     case LogicalOperator::Eqv:
244       result = xt == yt;
245       break;
246     case LogicalOperator::Neqv:
247       result = xt != yt;
248       break;
249     case LogicalOperator::Not:
250       DIE("not a binary operator");
251     }
252     return Expr<LOGICAL>{Constant<LOGICAL>{result}};
253   }
254   return Expr<LOGICAL>{std::move(operation)};
255 }
256 
257 FOR_EACH_LOGICAL_KIND(template class ExpressionBase, )
258 template class ExpressionBase<SomeLogical>;
259 } // namespace Fortran::evaluate
260