1 //===-- lib/Evaluate/fold-integer.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 // Class to retrieve the constant lower bound of an expression which is an
16 // array that devolves to a type of Constant<T>
17 class GetConstantArrayLboundHelper {
18 public:
19   GetConstantArrayLboundHelper(ConstantSubscript dim) : dim_{dim} {}
20 
21   template <typename T> ConstantSubscript GetLbound(const T &) {
22     // The method is needed for template expansion, but we should never get
23     // here in practice.
24     CHECK(false);
25     return 0;
26   }
27 
28   template <typename T> ConstantSubscript GetLbound(const Constant<T> &x) {
29     // Return the lower bound
30     return x.lbounds()[dim_];
31   }
32 
33   template <typename T> ConstantSubscript GetLbound(const Parentheses<T> &x) {
34     // Strip off the parentheses
35     return GetLbound(x.left());
36   }
37 
38   template <typename T> ConstantSubscript GetLbound(const Expr<T> &x) {
39     // recurse through Expr<T>'a until we hit a constant
40     return std::visit([&](const auto &inner) { return GetLbound(inner); },
41         //      [&](const auto &) { return 0; },
42         x.u);
43   }
44 
45 private:
46   ConstantSubscript dim_;
47 };
48 
49 template <int KIND>
50 Expr<Type<TypeCategory::Integer, KIND>> LBOUND(FoldingContext &context,
51     FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
52   using T = Type<TypeCategory::Integer, KIND>;
53   ActualArguments &args{funcRef.arguments()};
54   if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
55     if (int rank{array->Rank()}; rank > 0) {
56       std::optional<int> dim;
57       if (funcRef.Rank() == 0) {
58         // Optional DIM= argument is present: result is scalar.
59         if (auto dim64{GetInt64Arg(args[1])}) {
60           if (*dim64 < 1 || *dim64 > rank) {
61             context.messages().Say("DIM=%jd dimension is out of range for "
62                                    "rank-%d array"_err_en_US,
63                 *dim64, rank);
64             return MakeInvalidIntrinsic<T>(std::move(funcRef));
65           } else {
66             dim = *dim64 - 1; // 1-based to 0-based
67           }
68         } else {
69           // DIM= is present but not constant
70           return Expr<T>{std::move(funcRef)};
71         }
72       }
73       bool lowerBoundsAreOne{true};
74       if (auto named{ExtractNamedEntity(*array)}) {
75         const Symbol &symbol{named->GetLastSymbol()};
76         if (symbol.Rank() == rank) {
77           lowerBoundsAreOne = false;
78           if (dim) {
79             return Fold(context,
80                 ConvertToType<T>(GetLowerBound(context, *named, *dim)));
81           } else if (auto extents{
82                          AsExtentArrayExpr(GetLowerBounds(context, *named))}) {
83             return Fold(context,
84                 ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
85           }
86         } else {
87           lowerBoundsAreOne = symbol.Rank() == 0; // LBOUND(array%component)
88         }
89       }
90       if (IsActuallyConstant(*array)) {
91         return Expr<T>{GetConstantArrayLboundHelper{*dim}.GetLbound(*array)};
92       }
93       if (lowerBoundsAreOne) {
94         if (dim) {
95           return Expr<T>{1};
96         } else {
97           std::vector<Scalar<T>> ones(rank, Scalar<T>{1});
98           return Expr<T>{
99               Constant<T>{std::move(ones), ConstantSubscripts{rank}}};
100         }
101       }
102     }
103   }
104   return Expr<T>{std::move(funcRef)};
105 }
106 
107 template <int KIND>
108 Expr<Type<TypeCategory::Integer, KIND>> UBOUND(FoldingContext &context,
109     FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
110   using T = Type<TypeCategory::Integer, KIND>;
111   ActualArguments &args{funcRef.arguments()};
112   if (auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
113     if (int rank{array->Rank()}; rank > 0) {
114       std::optional<int> dim;
115       if (funcRef.Rank() == 0) {
116         // Optional DIM= argument is present: result is scalar.
117         if (auto dim64{GetInt64Arg(args[1])}) {
118           if (*dim64 < 1 || *dim64 > rank) {
119             context.messages().Say("DIM=%jd dimension is out of range for "
120                                    "rank-%d array"_err_en_US,
121                 *dim64, rank);
122             return MakeInvalidIntrinsic<T>(std::move(funcRef));
123           } else {
124             dim = *dim64 - 1; // 1-based to 0-based
125           }
126         } else {
127           // DIM= is present but not constant
128           return Expr<T>{std::move(funcRef)};
129         }
130       }
131       bool takeBoundsFromShape{true};
132       if (auto named{ExtractNamedEntity(*array)}) {
133         const Symbol &symbol{named->GetLastSymbol()};
134         if (symbol.Rank() == rank) {
135           takeBoundsFromShape = false;
136           if (dim) {
137             if (semantics::IsAssumedSizeArray(symbol) && *dim == rank - 1) {
138               context.messages().Say("DIM=%jd dimension is out of range for "
139                                      "rank-%d assumed-size array"_err_en_US,
140                   rank, rank);
141               return MakeInvalidIntrinsic<T>(std::move(funcRef));
142             } else if (auto ub{GetUpperBound(context, *named, *dim)}) {
143               return Fold(context, ConvertToType<T>(std::move(*ub)));
144             }
145           } else {
146             Shape ubounds{GetUpperBounds(context, *named)};
147             if (semantics::IsAssumedSizeArray(symbol)) {
148               CHECK(!ubounds.back());
149               ubounds.back() = ExtentExpr{-1};
150             }
151             if (auto extents{AsExtentArrayExpr(ubounds)}) {
152               return Fold(context,
153                   ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
154             }
155           }
156         } else {
157           takeBoundsFromShape = symbol.Rank() == 0; // UBOUND(array%component)
158         }
159       }
160       if (takeBoundsFromShape) {
161         if (auto shape{GetShape(context, *array)}) {
162           if (dim) {
163             if (auto &dimSize{shape->at(*dim)}) {
164               return Fold(context,
165                   ConvertToType<T>(Expr<ExtentType>{std::move(*dimSize)}));
166             }
167           } else if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
168             return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
169           }
170         }
171       }
172     }
173   }
174   return Expr<T>{std::move(funcRef)};
175 }
176 
177 // COUNT()
178 template <typename T>
179 static Expr<T> FoldCount(FoldingContext &context, FunctionRef<T> &&ref) {
180   static_assert(T::category == TypeCategory::Integer);
181   ActualArguments &arg{ref.arguments()};
182   if (const Constant<LogicalResult> *mask{arg.empty()
183               ? nullptr
184               : Folder<LogicalResult>{context}.Folding(arg[0])}) {
185     std::optional<int> dim;
186     if (CheckReductionDIM(dim, context, arg, 1, mask->Rank())) {
187       auto accumulator{[&](Scalar<T> &element, const ConstantSubscripts &at) {
188         if (mask->At(at).IsTrue()) {
189           element = element.AddSigned(Scalar<T>{1}).value;
190         }
191       }};
192       return Expr<T>{DoReduction<T>(*mask, dim, Scalar<T>{}, accumulator)};
193     }
194   }
195   return Expr<T>{std::move(ref)};
196 }
197 
198 // FINDLOC(), MAXLOC(), & MINLOC()
199 enum class WhichLocation { Findloc, Maxloc, Minloc };
200 template <WhichLocation WHICH> class LocationHelper {
201 public:
202   LocationHelper(
203       DynamicType &&type, ActualArguments &arg, FoldingContext &context)
204       : type_{type}, arg_{arg}, context_{context} {}
205   using Result = std::optional<Constant<SubscriptInteger>>;
206   using Types = std::conditional_t<WHICH == WhichLocation::Findloc,
207       AllIntrinsicTypes, RelationalTypes>;
208 
209   template <typename T> Result Test() const {
210     if (T::category != type_.category() || T::kind != type_.kind()) {
211       return std::nullopt;
212     }
213     CHECK(arg_.size() == (WHICH == WhichLocation::Findloc ? 6 : 5));
214     Folder<T> folder{context_};
215     Constant<T> *array{folder.Folding(arg_[0])};
216     if (!array) {
217       return std::nullopt;
218     }
219     std::optional<Constant<T>> value;
220     if constexpr (WHICH == WhichLocation::Findloc) {
221       if (const Constant<T> *p{folder.Folding(arg_[1])}) {
222         value.emplace(*p);
223       } else {
224         return std::nullopt;
225       }
226     }
227     std::optional<int> dim;
228     Constant<LogicalResult> *mask{
229         GetReductionMASK(arg_[maskArg], array->shape(), context_)};
230     if ((!mask && arg_[maskArg]) ||
231         !CheckReductionDIM(dim, context_, arg_, dimArg, array->Rank())) {
232       return std::nullopt;
233     }
234     bool back{false};
235     if (arg_[backArg]) {
236       const auto *backConst{
237           Folder<LogicalResult>{context_}.Folding(arg_[backArg])};
238       if (backConst) {
239         back = backConst->GetScalarValue().value().IsTrue();
240       } else {
241         return std::nullopt;
242       }
243     }
244     const RelationalOperator relation{WHICH == WhichLocation::Findloc
245             ? RelationalOperator::EQ
246             : WHICH == WhichLocation::Maxloc
247             ? (back ? RelationalOperator::GE : RelationalOperator::GT)
248             : back ? RelationalOperator::LE
249                    : RelationalOperator::LT};
250     // Use lower bounds of 1 exclusively.
251     array->SetLowerBoundsToOne();
252     ConstantSubscripts at{array->lbounds()}, maskAt, resultIndices, resultShape;
253     if (mask) {
254       mask->SetLowerBoundsToOne();
255       maskAt = mask->lbounds();
256     }
257     if (dim) { // DIM=
258       if (*dim < 1 || *dim > array->Rank()) {
259         context_.messages().Say("DIM=%d is out of range"_err_en_US, *dim);
260         return std::nullopt;
261       }
262       int zbDim{*dim - 1};
263       resultShape = array->shape();
264       resultShape.erase(
265           resultShape.begin() + zbDim); // scalar if array is vector
266       ConstantSubscript dimLength{array->shape()[zbDim]};
267       ConstantSubscript n{GetSize(resultShape)};
268       for (ConstantSubscript j{0}; j < n; ++j) {
269         ConstantSubscript hit{0};
270         if constexpr (WHICH == WhichLocation::Maxloc ||
271             WHICH == WhichLocation::Minloc) {
272           value.reset();
273         }
274         for (ConstantSubscript k{0}; k < dimLength;
275              ++k, ++at[zbDim], mask && ++maskAt[zbDim]) {
276           if ((!mask || mask->At(maskAt).IsTrue()) &&
277               IsHit(array->At(at), value, relation)) {
278             hit = at[zbDim];
279             if constexpr (WHICH == WhichLocation::Findloc) {
280               if (!back) {
281                 break;
282               }
283             }
284           }
285         }
286         resultIndices.emplace_back(hit);
287         at[zbDim] = dimLength;
288         array->IncrementSubscripts(at);
289         at[zbDim] = 1;
290         if (mask) {
291           maskAt[zbDim] = mask->lbounds()[zbDim] + dimLength - 1;
292           mask->IncrementSubscripts(maskAt);
293           maskAt[zbDim] = mask->lbounds()[zbDim];
294         }
295       }
296     } else { // no DIM=
297       resultShape = ConstantSubscripts{array->Rank()}; // always a vector
298       ConstantSubscript n{GetSize(array->shape())};
299       resultIndices = ConstantSubscripts(array->Rank(), 0);
300       for (ConstantSubscript j{0}; j < n; ++j, array->IncrementSubscripts(at),
301            mask && mask->IncrementSubscripts(maskAt)) {
302         if ((!mask || mask->At(maskAt).IsTrue()) &&
303             IsHit(array->At(at), value, relation)) {
304           resultIndices = at;
305           if constexpr (WHICH == WhichLocation::Findloc) {
306             if (!back) {
307               break;
308             }
309           }
310         }
311       }
312     }
313     std::vector<Scalar<SubscriptInteger>> resultElements;
314     for (ConstantSubscript j : resultIndices) {
315       resultElements.emplace_back(j);
316     }
317     return Constant<SubscriptInteger>{
318         std::move(resultElements), std::move(resultShape)};
319   }
320 
321 private:
322   template <typename T>
323   bool IsHit(typename Constant<T>::Element element,
324       std::optional<Constant<T>> &value,
325       [[maybe_unused]] RelationalOperator relation) const {
326     std::optional<Expr<LogicalResult>> cmp;
327     bool result{true};
328     if (value) {
329       if constexpr (T::category == TypeCategory::Logical) {
330         // array(at) .EQV. value?
331         static_assert(WHICH == WhichLocation::Findloc);
332         cmp.emplace(
333             ConvertToType<LogicalResult>(Expr<T>{LogicalOperation<T::kind>{
334                 LogicalOperator::Eqv, Expr<T>{Constant<T>{std::move(element)}},
335                 Expr<T>{Constant<T>{*value}}}}));
336       } else { // compare array(at) to value
337         cmp.emplace(
338             PackageRelation(relation, Expr<T>{Constant<T>{std::move(element)}},
339                 Expr<T>{Constant<T>{*value}}));
340       }
341       Expr<LogicalResult> folded{Fold(context_, std::move(*cmp))};
342       result = GetScalarConstantValue<LogicalResult>(folded).value().IsTrue();
343     } else {
344       // first unmasked element for MAXLOC/MINLOC - always take it
345     }
346     if constexpr (WHICH == WhichLocation::Maxloc ||
347         WHICH == WhichLocation::Minloc) {
348       if (result) {
349         value.emplace(std::move(element));
350       }
351     }
352     return result;
353   }
354 
355   static constexpr int dimArg{WHICH == WhichLocation::Findloc ? 2 : 1};
356   static constexpr int maskArg{dimArg + 1};
357   static constexpr int backArg{maskArg + 2};
358 
359   DynamicType type_;
360   ActualArguments &arg_;
361   FoldingContext &context_;
362 };
363 
364 template <WhichLocation which>
365 static std::optional<Constant<SubscriptInteger>> FoldLocationCall(
366     ActualArguments &arg, FoldingContext &context) {
367   if (arg[0]) {
368     if (auto type{arg[0]->GetType()}) {
369       return common::SearchTypes(
370           LocationHelper<which>{std::move(*type), arg, context});
371     }
372   }
373   return std::nullopt;
374 }
375 
376 template <WhichLocation which, typename T>
377 static Expr<T> FoldLocation(FoldingContext &context, FunctionRef<T> &&ref) {
378   static_assert(T::category == TypeCategory::Integer);
379   if (std::optional<Constant<SubscriptInteger>> found{
380           FoldLocationCall<which>(ref.arguments(), context)}) {
381     return Expr<T>{Fold(
382         context, ConvertToType<T>(Expr<SubscriptInteger>{std::move(*found)}))};
383   } else {
384     return Expr<T>{std::move(ref)};
385   }
386 }
387 
388 // for IALL, IANY, & IPARITY
389 template <typename T>
390 static Expr<T> FoldBitReduction(FoldingContext &context, FunctionRef<T> &&ref,
391     Scalar<T> (Scalar<T>::*operation)(const Scalar<T> &) const,
392     Scalar<T> identity) {
393   static_assert(T::category == TypeCategory::Integer);
394   std::optional<int> dim;
395   if (std::optional<Constant<T>> array{
396           ProcessReductionArgs<T>(context, ref.arguments(), dim, identity,
397               /*ARRAY=*/0, /*DIM=*/1, /*MASK=*/2)}) {
398     auto accumulator{[&](Scalar<T> &element, const ConstantSubscripts &at) {
399       element = (element.*operation)(array->At(at));
400     }};
401     return Expr<T>{DoReduction<T>(*array, dim, identity, accumulator)};
402   }
403   return Expr<T>{std::move(ref)};
404 }
405 
406 template <int KIND>
407 Expr<Type<TypeCategory::Integer, KIND>> FoldIntrinsicFunction(
408     FoldingContext &context,
409     FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
410   using T = Type<TypeCategory::Integer, KIND>;
411   using Int4 = Type<TypeCategory::Integer, 4>;
412   ActualArguments &args{funcRef.arguments()};
413   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
414   CHECK(intrinsic);
415   std::string name{intrinsic->name};
416   if (name == "abs") {
417     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
418         ScalarFunc<T, T>([&context](const Scalar<T> &i) -> Scalar<T> {
419           typename Scalar<T>::ValueWithOverflow j{i.ABS()};
420           if (j.overflow) {
421             context.messages().Say(
422                 "abs(integer(kind=%d)) folding overflowed"_en_US, KIND);
423           }
424           return j.value;
425         }));
426   } else if (name == "bit_size") {
427     return Expr<T>{Scalar<T>::bits};
428   } else if (name == "ceiling" || name == "floor" || name == "nint") {
429     if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
430       // NINT rounds ties away from zero, not to even
431       common::RoundingMode mode{name == "ceiling" ? common::RoundingMode::Up
432               : name == "floor"                   ? common::RoundingMode::Down
433                                 : common::RoundingMode::TiesAwayFromZero};
434       return std::visit(
435           [&](const auto &kx) {
436             using TR = ResultType<decltype(kx)>;
437             return FoldElementalIntrinsic<T, TR>(context, std::move(funcRef),
438                 ScalarFunc<T, TR>([&](const Scalar<TR> &x) {
439                   auto y{x.template ToInteger<Scalar<T>>(mode)};
440                   if (y.flags.test(RealFlag::Overflow)) {
441                     context.messages().Say(
442                         "%s intrinsic folding overflow"_en_US, name);
443                   }
444                   return y.value;
445                 }));
446           },
447           cx->u);
448     }
449   } else if (name == "count") {
450     return FoldCount<T>(context, std::move(funcRef));
451   } else if (name == "digits") {
452     if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
453       return Expr<T>{std::visit(
454           [](const auto &kx) {
455             return Scalar<ResultType<decltype(kx)>>::DIGITS;
456           },
457           cx->u)};
458     } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
459       return Expr<T>{std::visit(
460           [](const auto &kx) {
461             return Scalar<ResultType<decltype(kx)>>::DIGITS;
462           },
463           cx->u)};
464     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
465       return Expr<T>{std::visit(
466           [](const auto &kx) {
467             return Scalar<typename ResultType<decltype(kx)>::Part>::DIGITS;
468           },
469           cx->u)};
470     }
471   } else if (name == "dim") {
472     return FoldElementalIntrinsic<T, T, T>(
473         context, std::move(funcRef), &Scalar<T>::DIM);
474   } else if (name == "dshiftl" || name == "dshiftr") {
475     const auto fptr{
476         name == "dshiftl" ? &Scalar<T>::DSHIFTL : &Scalar<T>::DSHIFTR};
477     // Third argument can be of any kind. However, it must be smaller or equal
478     // than BIT_SIZE. It can be converted to Int4 to simplify.
479     return FoldElementalIntrinsic<T, T, T, Int4>(context, std::move(funcRef),
480         ScalarFunc<T, T, T, Int4>(
481             [&fptr](const Scalar<T> &i, const Scalar<T> &j,
482                 const Scalar<Int4> &shift) -> Scalar<T> {
483               return std::invoke(fptr, i, j, static_cast<int>(shift.ToInt64()));
484             }));
485   } else if (name == "exponent") {
486     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
487       return std::visit(
488           [&funcRef, &context](const auto &x) -> Expr<T> {
489             using TR = typename std::decay_t<decltype(x)>::Result;
490             return FoldElementalIntrinsic<T, TR>(context, std::move(funcRef),
491                 &Scalar<TR>::template EXPONENT<Scalar<T>>);
492           },
493           sx->u);
494     } else {
495       DIE("exponent argument must be real");
496     }
497   } else if (name == "findloc") {
498     return FoldLocation<WhichLocation::Findloc, T>(context, std::move(funcRef));
499   } else if (name == "huge") {
500     return Expr<T>{Scalar<T>::HUGE()};
501   } else if (name == "iachar" || name == "ichar") {
502     auto *someChar{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
503     CHECK(someChar);
504     if (auto len{ToInt64(someChar->LEN())}) {
505       if (len.value() != 1) {
506         // Do not die, this was not checked before
507         context.messages().Say(
508             "Character in intrinsic function %s must have length one"_en_US,
509             name);
510       } else {
511         return std::visit(
512             [&funcRef, &context](const auto &str) -> Expr<T> {
513               using Char = typename std::decay_t<decltype(str)>::Result;
514               return FoldElementalIntrinsic<T, Char>(context,
515                   std::move(funcRef),
516                   ScalarFunc<T, Char>([](const Scalar<Char> &c) {
517                     return Scalar<T>{CharacterUtils<Char::kind>::ICHAR(c)};
518                   }));
519             },
520             someChar->u);
521       }
522     }
523   } else if (name == "iand" || name == "ior" || name == "ieor") {
524     auto fptr{&Scalar<T>::IAND};
525     if (name == "iand") { // done in fptr declaration
526     } else if (name == "ior") {
527       fptr = &Scalar<T>::IOR;
528     } else if (name == "ieor") {
529       fptr = &Scalar<T>::IEOR;
530     } else {
531       common::die("missing case to fold intrinsic function %s", name.c_str());
532     }
533     return FoldElementalIntrinsic<T, T, T>(
534         context, std::move(funcRef), ScalarFunc<T, T, T>(fptr));
535   } else if (name == "iall") {
536     return FoldBitReduction(
537         context, std::move(funcRef), &Scalar<T>::IAND, Scalar<T>{}.NOT());
538   } else if (name == "iany") {
539     return FoldBitReduction(
540         context, std::move(funcRef), &Scalar<T>::IOR, Scalar<T>{});
541   } else if (name == "ibclr" || name == "ibset") {
542     // Second argument can be of any kind. However, it must be smaller
543     // than BIT_SIZE. It can be converted to Int4 to simplify.
544     auto fptr{&Scalar<T>::IBCLR};
545     if (name == "ibclr") { // done in fptr definition
546     } else if (name == "ibset") {
547       fptr = &Scalar<T>::IBSET;
548     } else {
549       common::die("missing case to fold intrinsic function %s", name.c_str());
550     }
551     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
552         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
553                                    const Scalar<Int4> &pos) -> Scalar<T> {
554           auto posVal{static_cast<int>(pos.ToInt64())};
555           if (posVal < 0) {
556             context.messages().Say(
557                 "bit position for %s (%d) is negative"_err_en_US, name, posVal);
558           } else if (posVal >= i.bits) {
559             context.messages().Say(
560                 "bit position for %s (%d) is not less than %d"_err_en_US, name,
561                 posVal, i.bits);
562           }
563           return std::invoke(fptr, i, posVal);
564         }));
565   } else if (name == "index" || name == "scan" || name == "verify") {
566     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
567       return std::visit(
568           [&](const auto &kch) -> Expr<T> {
569             using TC = typename std::decay_t<decltype(kch)>::Result;
570             if (UnwrapExpr<Expr<SomeLogical>>(args[2])) { // BACK=
571               return FoldElementalIntrinsic<T, TC, TC, LogicalResult>(context,
572                   std::move(funcRef),
573                   ScalarFunc<T, TC, TC, LogicalResult>{
574                       [&name](const Scalar<TC> &str, const Scalar<TC> &other,
575                           const Scalar<LogicalResult> &back) -> Scalar<T> {
576                         return name == "index"
577                             ? CharacterUtils<TC::kind>::INDEX(
578                                   str, other, back.IsTrue())
579                             : name == "scan" ? CharacterUtils<TC::kind>::SCAN(
580                                                    str, other, back.IsTrue())
581                                              : CharacterUtils<TC::kind>::VERIFY(
582                                                    str, other, back.IsTrue());
583                       }});
584             } else {
585               return FoldElementalIntrinsic<T, TC, TC>(context,
586                   std::move(funcRef),
587                   ScalarFunc<T, TC, TC>{
588                       [&name](const Scalar<TC> &str,
589                           const Scalar<TC> &other) -> Scalar<T> {
590                         return name == "index"
591                             ? CharacterUtils<TC::kind>::INDEX(str, other)
592                             : name == "scan"
593                             ? CharacterUtils<TC::kind>::SCAN(str, other)
594                             : CharacterUtils<TC::kind>::VERIFY(str, other);
595                       }});
596             }
597           },
598           charExpr->u);
599     } else {
600       DIE("first argument must be CHARACTER");
601     }
602   } else if (name == "int") {
603     if (auto *expr{UnwrapExpr<Expr<SomeType>>(args[0])}) {
604       return std::visit(
605           [&](auto &&x) -> Expr<T> {
606             using From = std::decay_t<decltype(x)>;
607             if constexpr (std::is_same_v<From, BOZLiteralConstant> ||
608                 IsNumericCategoryExpr<From>()) {
609               return Fold(context, ConvertToType<T>(std::move(x)));
610             }
611             DIE("int() argument type not valid");
612           },
613           std::move(expr->u));
614     }
615   } else if (name == "int_ptr_kind") {
616     return Expr<T>{8};
617   } else if (name == "kind") {
618     if constexpr (common::HasMember<T, IntegerTypes>) {
619       return Expr<T>{args[0].value().GetType()->kind()};
620     } else {
621       DIE("kind() result not integral");
622     }
623   } else if (name == "iparity") {
624     return FoldBitReduction(
625         context, std::move(funcRef), &Scalar<T>::IEOR, Scalar<T>{});
626   } else if (name == "ishft") {
627     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
628         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
629                                    const Scalar<Int4> &pos) -> Scalar<T> {
630           auto posVal{static_cast<int>(pos.ToInt64())};
631           if (posVal < -i.bits) {
632             context.messages().Say(
633                 "SHIFT=%d count for ishft is less than %d"_err_en_US, posVal,
634                 -i.bits);
635           } else if (posVal > i.bits) {
636             context.messages().Say(
637                 "SHIFT=%d count for ishft is greater than %d"_err_en_US, posVal,
638                 i.bits);
639           }
640           return i.ISHFT(posVal);
641         }));
642   } else if (name == "lbound") {
643     return LBOUND(context, std::move(funcRef));
644   } else if (name == "leadz" || name == "trailz" || name == "poppar" ||
645       name == "popcnt") {
646     if (auto *sn{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
647       return std::visit(
648           [&funcRef, &context, &name](const auto &n) -> Expr<T> {
649             using TI = typename std::decay_t<decltype(n)>::Result;
650             if (name == "poppar") {
651               return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
652                   ScalarFunc<T, TI>([](const Scalar<TI> &i) -> Scalar<T> {
653                     return Scalar<T>{i.POPPAR() ? 1 : 0};
654                   }));
655             }
656             auto fptr{&Scalar<TI>::LEADZ};
657             if (name == "leadz") { // done in fptr definition
658             } else if (name == "trailz") {
659               fptr = &Scalar<TI>::TRAILZ;
660             } else if (name == "popcnt") {
661               fptr = &Scalar<TI>::POPCNT;
662             } else {
663               common::die(
664                   "missing case to fold intrinsic function %s", name.c_str());
665             }
666             return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
667                 ScalarFunc<T, TI>([&fptr](const Scalar<TI> &i) -> Scalar<T> {
668                   return Scalar<T>{std::invoke(fptr, i)};
669                 }));
670           },
671           sn->u);
672     } else {
673       DIE("leadz argument must be integer");
674     }
675   } else if (name == "len") {
676     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
677       return std::visit(
678           [&](auto &kx) {
679             if (auto len{kx.LEN()}) {
680               return Fold(context, ConvertToType<T>(*std::move(len)));
681             } else {
682               return Expr<T>{std::move(funcRef)};
683             }
684           },
685           charExpr->u);
686     } else {
687       DIE("len() argument must be of character type");
688     }
689   } else if (name == "len_trim") {
690     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
691       return std::visit(
692           [&](const auto &kch) -> Expr<T> {
693             using TC = typename std::decay_t<decltype(kch)>::Result;
694             return FoldElementalIntrinsic<T, TC>(context, std::move(funcRef),
695                 ScalarFunc<T, TC>{[](const Scalar<TC> &str) -> Scalar<T> {
696                   return CharacterUtils<TC::kind>::LEN_TRIM(str);
697                 }});
698           },
699           charExpr->u);
700     } else {
701       DIE("len_trim() argument must be of character type");
702     }
703   } else if (name == "maskl" || name == "maskr") {
704     // Argument can be of any kind but value has to be smaller than BIT_SIZE.
705     // It can be safely converted to Int4 to simplify.
706     const auto fptr{name == "maskl" ? &Scalar<T>::MASKL : &Scalar<T>::MASKR};
707     return FoldElementalIntrinsic<T, Int4>(context, std::move(funcRef),
708         ScalarFunc<T, Int4>([&fptr](const Scalar<Int4> &places) -> Scalar<T> {
709           return fptr(static_cast<int>(places.ToInt64()));
710         }));
711   } else if (name == "max") {
712     return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
713   } else if (name == "max0" || name == "max1") {
714     return RewriteSpecificMINorMAX(context, std::move(funcRef));
715   } else if (name == "maxexponent") {
716     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
717       return std::visit(
718           [](const auto &x) {
719             using TR = typename std::decay_t<decltype(x)>::Result;
720             return Expr<T>{Scalar<TR>::MAXEXPONENT};
721           },
722           sx->u);
723     }
724   } else if (name == "maxloc") {
725     return FoldLocation<WhichLocation::Maxloc, T>(context, std::move(funcRef));
726   } else if (name == "maxval") {
727     return FoldMaxvalMinval<T>(context, std::move(funcRef),
728         RelationalOperator::GT, T::Scalar::Least());
729   } else if (name == "merge") {
730     return FoldMerge<T>(context, std::move(funcRef));
731   } else if (name == "merge_bits") {
732     return FoldElementalIntrinsic<T, T, T, T>(
733         context, std::move(funcRef), &Scalar<T>::MERGE_BITS);
734   } else if (name == "min") {
735     return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
736   } else if (name == "min0" || name == "min1") {
737     return RewriteSpecificMINorMAX(context, std::move(funcRef));
738   } else if (name == "minexponent") {
739     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
740       return std::visit(
741           [](const auto &x) {
742             using TR = typename std::decay_t<decltype(x)>::Result;
743             return Expr<T>{Scalar<TR>::MINEXPONENT};
744           },
745           sx->u);
746     }
747   } else if (name == "minloc") {
748     return FoldLocation<WhichLocation::Minloc, T>(context, std::move(funcRef));
749   } else if (name == "minval") {
750     return FoldMaxvalMinval<T>(
751         context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE());
752   } else if (name == "mod") {
753     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
754         ScalarFuncWithContext<T, T, T>(
755             [](FoldingContext &context, const Scalar<T> &x,
756                 const Scalar<T> &y) -> Scalar<T> {
757               auto quotRem{x.DivideSigned(y)};
758               if (quotRem.divisionByZero) {
759                 context.messages().Say("mod() by zero"_en_US);
760               } else if (quotRem.overflow) {
761                 context.messages().Say("mod() folding overflowed"_en_US);
762               }
763               return quotRem.remainder;
764             }));
765   } else if (name == "modulo") {
766     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
767         ScalarFuncWithContext<T, T, T>(
768             [](FoldingContext &context, const Scalar<T> &x,
769                 const Scalar<T> &y) -> Scalar<T> {
770               auto result{x.MODULO(y)};
771               if (result.overflow) {
772                 context.messages().Say("modulo() folding overflowed"_en_US);
773               }
774               return result.value;
775             }));
776   } else if (name == "not") {
777     return FoldElementalIntrinsic<T, T>(
778         context, std::move(funcRef), &Scalar<T>::NOT);
779   } else if (name == "precision") {
780     if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
781       return Expr<T>{std::visit(
782           [](const auto &kx) {
783             return Scalar<ResultType<decltype(kx)>>::PRECISION;
784           },
785           cx->u)};
786     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
787       return Expr<T>{std::visit(
788           [](const auto &kx) {
789             return Scalar<typename ResultType<decltype(kx)>::Part>::PRECISION;
790           },
791           cx->u)};
792     }
793   } else if (name == "product") {
794     return FoldProduct<T>(context, std::move(funcRef), Scalar<T>{1});
795   } else if (name == "radix") {
796     return Expr<T>{2};
797   } else if (name == "range") {
798     if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
799       return Expr<T>{std::visit(
800           [](const auto &kx) {
801             return Scalar<ResultType<decltype(kx)>>::RANGE;
802           },
803           cx->u)};
804     } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
805       return Expr<T>{std::visit(
806           [](const auto &kx) {
807             return Scalar<ResultType<decltype(kx)>>::RANGE;
808           },
809           cx->u)};
810     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
811       return Expr<T>{std::visit(
812           [](const auto &kx) {
813             return Scalar<typename ResultType<decltype(kx)>::Part>::RANGE;
814           },
815           cx->u)};
816     }
817   } else if (name == "rank") {
818     if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
819       if (auto named{ExtractNamedEntity(*array)}) {
820         const Symbol &symbol{named->GetLastSymbol()};
821         if (IsAssumedRank(symbol)) {
822           // DescriptorInquiry can only be placed in expression of kind
823           // DescriptorInquiry::Result::kind.
824           return ConvertToType<T>(Expr<
825               Type<TypeCategory::Integer, DescriptorInquiry::Result::kind>>{
826               DescriptorInquiry{*named, DescriptorInquiry::Field::Rank}});
827         }
828       }
829       return Expr<T>{args[0].value().Rank()};
830     }
831     return Expr<T>{args[0].value().Rank()};
832   } else if (name == "selected_char_kind") {
833     if (const auto *chCon{UnwrapExpr<Constant<TypeOf<std::string>>>(args[0])}) {
834       if (std::optional<std::string> value{chCon->GetScalarValue()}) {
835         int defaultKind{
836             context.defaults().GetDefaultKind(TypeCategory::Character)};
837         return Expr<T>{SelectedCharKind(*value, defaultKind)};
838       }
839     }
840   } else if (name == "selected_int_kind") {
841     if (auto p{GetInt64Arg(args[0])}) {
842       return Expr<T>{SelectedIntKind(*p)};
843     }
844   } else if (name == "selected_real_kind" ||
845       name == "__builtin_ieee_selected_real_kind") {
846     if (auto p{GetInt64ArgOr(args[0], 0)}) {
847       if (auto r{GetInt64ArgOr(args[1], 0)}) {
848         if (auto radix{GetInt64ArgOr(args[2], 2)}) {
849           return Expr<T>{SelectedRealKind(*p, *r, *radix)};
850         }
851       }
852     }
853   } else if (name == "shape") {
854     if (auto shape{GetShape(context, args[0])}) {
855       if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
856         return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
857       }
858     }
859   } else if (name == "shifta" || name == "shiftr" || name == "shiftl") {
860     // Second argument can be of any kind. However, it must be smaller or
861     // equal than BIT_SIZE. It can be converted to Int4 to simplify.
862     auto fptr{&Scalar<T>::SHIFTA};
863     if (name == "shifta") { // done in fptr definition
864     } else if (name == "shiftr") {
865       fptr = &Scalar<T>::SHIFTR;
866     } else if (name == "shiftl") {
867       fptr = &Scalar<T>::SHIFTL;
868     } else {
869       common::die("missing case to fold intrinsic function %s", name.c_str());
870     }
871     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
872         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
873                                    const Scalar<Int4> &pos) -> Scalar<T> {
874           auto posVal{static_cast<int>(pos.ToInt64())};
875           if (posVal < 0) {
876             context.messages().Say(
877                 "SHIFT=%d count for %s is negative"_err_en_US, posVal, name);
878           } else if (posVal > i.bits) {
879             context.messages().Say(
880                 "SHIFT=%d count for %s is greater than %d"_err_en_US, posVal,
881                 name, i.bits);
882           }
883           return std::invoke(fptr, i, posVal);
884         }));
885   } else if (name == "sign") {
886     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
887         ScalarFunc<T, T, T>(
888             [&context](const Scalar<T> &j, const Scalar<T> &k) -> Scalar<T> {
889               typename Scalar<T>::ValueWithOverflow result{j.SIGN(k)};
890               if (result.overflow) {
891                 context.messages().Say(
892                     "sign(integer(kind=%d)) folding overflowed"_en_US, KIND);
893               }
894               return result.value;
895             }));
896   } else if (name == "size") {
897     if (auto shape{GetShape(context, args[0])}) {
898       if (auto &dimArg{args[1]}) { // DIM= is present, get one extent
899         if (auto dim{GetInt64Arg(args[1])}) {
900           int rank{GetRank(*shape)};
901           if (*dim >= 1 && *dim <= rank) {
902             const Symbol *symbol{UnwrapWholeSymbolDataRef(args[0])};
903             if (symbol && IsAssumedSizeArray(*symbol) && *dim == rank) {
904               context.messages().Say(
905                   "size(array,dim=%jd) of last dimension is not available for rank-%d assumed-size array dummy argument"_err_en_US,
906                   *dim, rank);
907               return MakeInvalidIntrinsic<T>(std::move(funcRef));
908             } else if (auto &extent{shape->at(*dim - 1)}) {
909               return Fold(context, ConvertToType<T>(std::move(*extent)));
910             }
911           } else {
912             context.messages().Say(
913                 "size(array,dim=%jd) dimension is out of range for rank-%d array"_en_US,
914                 *dim, rank);
915           }
916         }
917       } else if (auto extents{common::AllElementsPresent(std::move(*shape))}) {
918         // DIM= is absent; compute PRODUCT(SHAPE())
919         ExtentExpr product{1};
920         for (auto &&extent : std::move(*extents)) {
921           product = std::move(product) * std::move(extent);
922         }
923         return Expr<T>{ConvertToType<T>(Fold(context, std::move(product)))};
924       }
925     }
926   } else if (name == "sizeof") { // in bytes; extension
927     if (auto info{
928             characteristics::TypeAndShape::Characterize(args[0], context)}) {
929       if (auto bytes{info->MeasureSizeInBytes(context)}) {
930         return Expr<T>{Fold(context, ConvertToType<T>(std::move(*bytes)))};
931       }
932     }
933   } else if (name == "storage_size") { // in bits
934     if (auto info{
935             characteristics::TypeAndShape::Characterize(args[0], context)}) {
936       if (auto bytes{info->MeasureElementSizeInBytes(context, true)}) {
937         return Expr<T>{
938             Fold(context, Expr<T>{8} * ConvertToType<T>(std::move(*bytes)))};
939       }
940     }
941   } else if (name == "sum") {
942     return FoldSum<T>(context, std::move(funcRef));
943   } else if (name == "ubound") {
944     return UBOUND(context, std::move(funcRef));
945   }
946   // TODO: dot_product, ibits, ishftc, matmul, sign, transfer
947   return Expr<T>{std::move(funcRef)};
948 }
949 
950 // Substitutes a bare type parameter reference with its value if it has one now
951 // in an instantiation.  Bare LEN type parameters are substituted only when
952 // the known value is constant.
953 Expr<TypeParamInquiry::Result> FoldOperation(
954     FoldingContext &context, TypeParamInquiry &&inquiry) {
955   std::optional<NamedEntity> base{inquiry.base()};
956   parser::CharBlock parameterName{inquiry.parameter().name()};
957   if (base) {
958     // Handling "designator%typeParam".  Get the value of the type parameter
959     // from the instantiation of the base
960     if (const semantics::DeclTypeSpec *
961         declType{base->GetLastSymbol().GetType()}) {
962       if (const semantics::ParamValue *
963           paramValue{
964               declType->derivedTypeSpec().FindParameter(parameterName)}) {
965         const semantics::MaybeIntExpr &paramExpr{paramValue->GetExplicit()};
966         if (paramExpr && IsConstantExpr(*paramExpr)) {
967           Expr<SomeInteger> intExpr{*paramExpr};
968           return Fold(context,
969               ConvertToType<TypeParamInquiry::Result>(std::move(intExpr)));
970         }
971       }
972     }
973   } else {
974     // A "bare" type parameter: replace with its value, if that's now known
975     // in a current derived type instantiation, for KIND type parameters.
976     if (const auto *pdt{context.pdtInstance()}) {
977       bool isLen{false};
978       if (const semantics::Scope * scope{context.pdtInstance()->scope()}) {
979         auto iter{scope->find(parameterName)};
980         if (iter != scope->end()) {
981           const Symbol &symbol{*iter->second};
982           const auto *details{symbol.detailsIf<semantics::TypeParamDetails>()};
983           if (details) {
984             isLen = details->attr() == common::TypeParamAttr::Len;
985             const semantics::MaybeIntExpr &initExpr{details->init()};
986             if (initExpr && IsConstantExpr(*initExpr) &&
987                 (!isLen || ToInt64(*initExpr))) {
988               Expr<SomeInteger> expr{*initExpr};
989               return Fold(context,
990                   ConvertToType<TypeParamInquiry::Result>(std::move(expr)));
991             }
992           }
993         }
994       }
995       if (const auto *value{pdt->FindParameter(parameterName)}) {
996         if (value->isExplicit()) {
997           auto folded{Fold(context,
998               AsExpr(ConvertToType<TypeParamInquiry::Result>(
999                   Expr<SomeInteger>{value->GetExplicit().value()})))};
1000           if (!isLen || ToInt64(folded)) {
1001             return folded;
1002           }
1003         }
1004       }
1005     }
1006   }
1007   return AsExpr(std::move(inquiry));
1008 }
1009 
1010 std::optional<std::int64_t> ToInt64(const Expr<SomeInteger> &expr) {
1011   return std::visit(
1012       [](const auto &kindExpr) { return ToInt64(kindExpr); }, expr.u);
1013 }
1014 
1015 std::optional<std::int64_t> ToInt64(const Expr<SomeType> &expr) {
1016   if (const auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(expr)}) {
1017     return ToInt64(*intExpr);
1018   } else {
1019     return std::nullopt;
1020   }
1021 }
1022 
1023 FOR_EACH_INTEGER_KIND(template class ExpressionBase, )
1024 template class ExpressionBase<SomeInteger>;
1025 } // namespace Fortran::evaluate
1026