xref: /llvm-project/flang/lib/Evaluate/fold-logical.cpp (revision 6965a776ee192cb4c1a2618c270254fbf70879df)
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   if (name == "all") {
44     return FoldAllAny(
45         context, std::move(funcRef), &Scalar<T>::AND, Scalar<T>{true});
46   } else if (name == "any") {
47     return FoldAllAny(
48         context, std::move(funcRef), &Scalar<T>::OR, Scalar<T>{false});
49   } else if (name == "associated") {
50     bool gotConstant{true};
51     const Expr<SomeType> *firstArgExpr{args[0]->UnwrapExpr()};
52     if (!firstArgExpr || !IsNullPointer(*firstArgExpr)) {
53       gotConstant = false;
54     } else if (args[1]) { // There's a second argument
55       const Expr<SomeType> *secondArgExpr{args[1]->UnwrapExpr()};
56       if (!secondArgExpr || !IsNullPointer(*secondArgExpr)) {
57         gotConstant = false;
58       }
59     }
60     return gotConstant ? Expr<T>{false} : Expr<T>{std::move(funcRef)};
61   } else if (name == "bge" || name == "bgt" || name == "ble" || name == "blt") {
62     using LargestInt = Type<TypeCategory::Integer, 16>;
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 == "isnan" || name == "__builtin_ieee_is_nan") {
93     // A warning about an invalid argument is discarded from converting
94     // the argument of isnan() / IEEE_IS_NAN().
95     auto restorer{context.messages().DiscardMessages()};
96     using DefaultReal = Type<TypeCategory::Real, 4>;
97     return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
98         ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
99           return Scalar<T>{x.IsNotANumber()};
100         }));
101   } else if (name == "is_contiguous") {
102     if (args.at(0)) {
103       if (auto *expr{args[0]->UnwrapExpr()}) {
104         if (IsSimplyContiguous(*expr, context)) {
105           return Expr<T>{true};
106         }
107       }
108     }
109   } else if (name == "lge" || name == "lgt" || name == "lle" || name == "llt") {
110     // Rewrite LGE/LGT/LLE/LLT into ASCII character relations
111     auto *cx0{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
112     auto *cx1{UnwrapExpr<Expr<SomeCharacter>>(args[1])};
113     if (cx0 && cx1) {
114       return Fold(context,
115           ConvertToType<T>(
116               PackageRelation(name == "lge" ? RelationalOperator::GE
117                       : name == "lgt"       ? RelationalOperator::GT
118                       : name == "lle"       ? RelationalOperator::LE
119                                             : RelationalOperator::LT,
120                   ConvertToType<Ascii>(std::move(*cx0)),
121                   ConvertToType<Ascii>(std::move(*cx1)))));
122     }
123   } else if (name == "logical") {
124     if (auto *expr{UnwrapExpr<Expr<SomeLogical>>(args[0])}) {
125       return Fold(context, ConvertToType<T>(std::move(*expr)));
126     }
127   } else if (name == "merge") {
128     return FoldMerge<T>(context, std::move(funcRef));
129   } else if (name == "__builtin_ieee_support_datatype" ||
130       name == "__builtin_ieee_support_denormal" ||
131       name == "__builtin_ieee_support_divide" ||
132       name == "__builtin_ieee_support_divide" ||
133       name == "__builtin_ieee_support_inf" ||
134       name == "__builtin_ieee_support_io" ||
135       name == "__builtin_ieee_support_nan" ||
136       name == "__builtin_ieee_support_sqrt" ||
137       name == "__builtin_ieee_support_standard" ||
138       name == "__builtin_ieee_support_subnormal" ||
139       name == "__builtin_ieee_support_underflow_control") {
140     return Expr<T>{true};
141   }
142   // TODO: btest, dot_product, is_iostat_end,
143   // is_iostat_eor, logical, matmul, out_of_range,
144   // parity, transfer
145   return Expr<T>{std::move(funcRef)};
146 }
147 
148 template <typename T>
149 Expr<LogicalResult> FoldOperation(
150     FoldingContext &context, Relational<T> &&relation) {
151   if (auto array{ApplyElementwise(context, relation,
152           std::function<Expr<LogicalResult>(Expr<T> &&, Expr<T> &&)>{
153               [=](Expr<T> &&x, Expr<T> &&y) {
154                 return Expr<LogicalResult>{Relational<SomeType>{
155                     Relational<T>{relation.opr, std::move(x), std::move(y)}}};
156               }})}) {
157     return *array;
158   }
159   if (auto folded{OperandsAreConstants(relation)}) {
160     bool result{};
161     if constexpr (T::category == TypeCategory::Integer) {
162       result =
163           Satisfies(relation.opr, folded->first.CompareSigned(folded->second));
164     } else if constexpr (T::category == TypeCategory::Real) {
165       result = Satisfies(relation.opr, folded->first.Compare(folded->second));
166     } else if constexpr (T::category == TypeCategory::Complex) {
167       result = (relation.opr == RelationalOperator::EQ) ==
168           folded->first.Equals(folded->second);
169     } else if constexpr (T::category == TypeCategory::Character) {
170       result = Satisfies(relation.opr, Compare(folded->first, folded->second));
171     } else {
172       static_assert(T::category != TypeCategory::Logical);
173     }
174     return Expr<LogicalResult>{Constant<LogicalResult>{result}};
175   }
176   return Expr<LogicalResult>{Relational<SomeType>{std::move(relation)}};
177 }
178 
179 Expr<LogicalResult> FoldOperation(
180     FoldingContext &context, Relational<SomeType> &&relation) {
181   return std::visit(
182       [&](auto &&x) {
183         return Expr<LogicalResult>{FoldOperation(context, std::move(x))};
184       },
185       std::move(relation.u));
186 }
187 
188 template <int KIND>
189 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
190     FoldingContext &context, Not<KIND> &&x) {
191   if (auto array{ApplyElementwise(context, x)}) {
192     return *array;
193   }
194   using Ty = Type<TypeCategory::Logical, KIND>;
195   auto &operand{x.left()};
196   if (auto value{GetScalarConstantValue<Ty>(operand)}) {
197     return Expr<Ty>{Constant<Ty>{!value->IsTrue()}};
198   }
199   return Expr<Ty>{x};
200 }
201 
202 template <int KIND>
203 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
204     FoldingContext &context, LogicalOperation<KIND> &&operation) {
205   using LOGICAL = Type<TypeCategory::Logical, KIND>;
206   if (auto array{ApplyElementwise(context, operation,
207           std::function<Expr<LOGICAL>(Expr<LOGICAL> &&, Expr<LOGICAL> &&)>{
208               [=](Expr<LOGICAL> &&x, Expr<LOGICAL> &&y) {
209                 return Expr<LOGICAL>{LogicalOperation<KIND>{
210                     operation.logicalOperator, std::move(x), std::move(y)}};
211               }})}) {
212     return *array;
213   }
214   if (auto folded{OperandsAreConstants(operation)}) {
215     bool xt{folded->first.IsTrue()}, yt{folded->second.IsTrue()}, result{};
216     switch (operation.logicalOperator) {
217     case LogicalOperator::And:
218       result = xt && yt;
219       break;
220     case LogicalOperator::Or:
221       result = xt || yt;
222       break;
223     case LogicalOperator::Eqv:
224       result = xt == yt;
225       break;
226     case LogicalOperator::Neqv:
227       result = xt != yt;
228       break;
229     case LogicalOperator::Not:
230       DIE("not a binary operator");
231     }
232     return Expr<LOGICAL>{Constant<LOGICAL>{result}};
233   }
234   return Expr<LOGICAL>{std::move(operation)};
235 }
236 
237 FOR_EACH_LOGICAL_KIND(template class ExpressionBase, )
238 template class ExpressionBase<SomeLogical>;
239 } // namespace Fortran::evaluate
240