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             if (auto lb{GetLBOUND(context, *named, *dim)}) {
80               return Fold(context, ConvertToType<T>(std::move(*lb)));
81             }
82           } else if (auto extents{
83                          AsExtentArrayExpr(GetLBOUNDs(context, *named))}) {
84             return Fold(context,
85                 ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
86           }
87         } else {
88           lowerBoundsAreOne = symbol.Rank() == 0; // LBOUND(array%component)
89         }
90       }
91       if (IsActuallyConstant(*array)) {
92         return Expr<T>{GetConstantArrayLboundHelper{*dim}.GetLbound(*array)};
93       }
94       if (lowerBoundsAreOne) {
95         if (dim) {
96           return Expr<T>{1};
97         } else {
98           std::vector<Scalar<T>> ones(rank, Scalar<T>{1});
99           return Expr<T>{
100               Constant<T>{std::move(ones), ConstantSubscripts{rank}}};
101         }
102       }
103     }
104   }
105   return Expr<T>{std::move(funcRef)};
106 }
107 
108 template <int KIND>
109 Expr<Type<TypeCategory::Integer, KIND>> UBOUND(FoldingContext &context,
110     FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
111   using T = Type<TypeCategory::Integer, KIND>;
112   ActualArguments &args{funcRef.arguments()};
113   if (auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
114     if (int rank{array->Rank()}; rank > 0) {
115       std::optional<int> dim;
116       if (funcRef.Rank() == 0) {
117         // Optional DIM= argument is present: result is scalar.
118         if (auto dim64{GetInt64Arg(args[1])}) {
119           if (*dim64 < 1 || *dim64 > rank) {
120             context.messages().Say("DIM=%jd dimension is out of range for "
121                                    "rank-%d array"_err_en_US,
122                 *dim64, rank);
123             return MakeInvalidIntrinsic<T>(std::move(funcRef));
124           } else {
125             dim = *dim64 - 1; // 1-based to 0-based
126           }
127         } else {
128           // DIM= is present but not constant
129           return Expr<T>{std::move(funcRef)};
130         }
131       }
132       bool takeBoundsFromShape{true};
133       if (auto named{ExtractNamedEntity(*array)}) {
134         const Symbol &symbol{named->GetLastSymbol()};
135         if (symbol.Rank() == rank) {
136           takeBoundsFromShape = false;
137           if (dim) {
138             if (semantics::IsAssumedSizeArray(symbol) && *dim == rank - 1) {
139               context.messages().Say("DIM=%jd dimension is out of range for "
140                                      "rank-%d assumed-size array"_err_en_US,
141                   rank, rank);
142               return MakeInvalidIntrinsic<T>(std::move(funcRef));
143             } else if (auto ub{GetUBOUND(context, *named, *dim)}) {
144               return Fold(context, ConvertToType<T>(std::move(*ub)));
145             }
146           } else {
147             Shape ubounds{GetUBOUNDs(context, *named)};
148             if (semantics::IsAssumedSizeArray(symbol)) {
149               CHECK(!ubounds.back());
150               ubounds.back() = ExtentExpr{-1};
151             }
152             if (auto extents{AsExtentArrayExpr(ubounds)}) {
153               return Fold(context,
154                   ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
155             }
156           }
157         } else {
158           takeBoundsFromShape = symbol.Rank() == 0; // UBOUND(array%component)
159         }
160       }
161       if (takeBoundsFromShape) {
162         if (auto shape{GetContextFreeShape(context, *array)}) {
163           if (dim) {
164             if (auto &dimSize{shape->at(*dim)}) {
165               return Fold(context,
166                   ConvertToType<T>(Expr<ExtentType>{std::move(*dimSize)}));
167             }
168           } else if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
169             return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
170           }
171         }
172       }
173     }
174   }
175   return Expr<T>{std::move(funcRef)};
176 }
177 
178 // COUNT()
179 template <typename T>
180 static Expr<T> FoldCount(FoldingContext &context, FunctionRef<T> &&ref) {
181   static_assert(T::category == TypeCategory::Integer);
182   ActualArguments &arg{ref.arguments()};
183   if (const Constant<LogicalResult> *mask{arg.empty()
184               ? nullptr
185               : Folder<LogicalResult>{context}.Folding(arg[0])}) {
186     std::optional<int> dim;
187     if (CheckReductionDIM(dim, context, arg, 1, mask->Rank())) {
188       auto accumulator{[&](Scalar<T> &element, const ConstantSubscripts &at) {
189         if (mask->At(at).IsTrue()) {
190           element = element.AddSigned(Scalar<T>{1}).value;
191         }
192       }};
193       return Expr<T>{DoReduction<T>(*mask, dim, Scalar<T>{}, accumulator)};
194     }
195   }
196   return Expr<T>{std::move(ref)};
197 }
198 
199 // FINDLOC(), MAXLOC(), & MINLOC()
200 enum class WhichLocation { Findloc, Maxloc, Minloc };
201 template <WhichLocation WHICH> class LocationHelper {
202 public:
203   LocationHelper(
204       DynamicType &&type, ActualArguments &arg, FoldingContext &context)
205       : type_{type}, arg_{arg}, context_{context} {}
206   using Result = std::optional<Constant<SubscriptInteger>>;
207   using Types = std::conditional_t<WHICH == WhichLocation::Findloc,
208       AllIntrinsicTypes, RelationalTypes>;
209 
210   template <typename T> Result Test() const {
211     if (T::category != type_.category() || T::kind != type_.kind()) {
212       return std::nullopt;
213     }
214     CHECK(arg_.size() == (WHICH == WhichLocation::Findloc ? 6 : 5));
215     Folder<T> folder{context_};
216     Constant<T> *array{folder.Folding(arg_[0])};
217     if (!array) {
218       return std::nullopt;
219     }
220     std::optional<Constant<T>> value;
221     if constexpr (WHICH == WhichLocation::Findloc) {
222       if (const Constant<T> *p{folder.Folding(arg_[1])}) {
223         value.emplace(*p);
224       } else {
225         return std::nullopt;
226       }
227     }
228     std::optional<int> dim;
229     Constant<LogicalResult> *mask{
230         GetReductionMASK(arg_[maskArg], array->shape(), context_)};
231     if ((!mask && arg_[maskArg]) ||
232         !CheckReductionDIM(dim, context_, arg_, dimArg, array->Rank())) {
233       return std::nullopt;
234     }
235     bool back{false};
236     if (arg_[backArg]) {
237       const auto *backConst{
238           Folder<LogicalResult>{context_}.Folding(arg_[backArg])};
239       if (backConst) {
240         back = backConst->GetScalarValue().value().IsTrue();
241       } else {
242         return std::nullopt;
243       }
244     }
245     const RelationalOperator relation{WHICH == WhichLocation::Findloc
246             ? RelationalOperator::EQ
247             : WHICH == WhichLocation::Maxloc
248             ? (back ? RelationalOperator::GE : RelationalOperator::GT)
249             : back ? RelationalOperator::LE
250                    : RelationalOperator::LT};
251     // Use lower bounds of 1 exclusively.
252     array->SetLowerBoundsToOne();
253     ConstantSubscripts at{array->lbounds()}, maskAt, resultIndices, resultShape;
254     if (mask) {
255       mask->SetLowerBoundsToOne();
256       maskAt = mask->lbounds();
257     }
258     if (dim) { // DIM=
259       if (*dim < 1 || *dim > array->Rank()) {
260         context_.messages().Say("DIM=%d is out of range"_err_en_US, *dim);
261         return std::nullopt;
262       }
263       int zbDim{*dim - 1};
264       resultShape = array->shape();
265       resultShape.erase(
266           resultShape.begin() + zbDim); // scalar if array is vector
267       ConstantSubscript dimLength{array->shape()[zbDim]};
268       ConstantSubscript n{GetSize(resultShape)};
269       for (ConstantSubscript j{0}; j < n; ++j) {
270         ConstantSubscript hit{0};
271         if constexpr (WHICH == WhichLocation::Maxloc ||
272             WHICH == WhichLocation::Minloc) {
273           value.reset();
274         }
275         for (ConstantSubscript k{0}; k < dimLength;
276              ++k, ++at[zbDim], mask && ++maskAt[zbDim]) {
277           if ((!mask || mask->At(maskAt).IsTrue()) &&
278               IsHit(array->At(at), value, relation)) {
279             hit = at[zbDim];
280             if constexpr (WHICH == WhichLocation::Findloc) {
281               if (!back) {
282                 break;
283               }
284             }
285           }
286         }
287         resultIndices.emplace_back(hit);
288         at[zbDim] = std::max<ConstantSubscript>(dimLength, 1);
289         array->IncrementSubscripts(at);
290         at[zbDim] = 1;
291         if (mask) {
292           maskAt[zbDim] = mask->lbounds()[zbDim] +
293               std::max<ConstantSubscript>(dimLength, 1) - 1;
294           mask->IncrementSubscripts(maskAt);
295           maskAt[zbDim] = mask->lbounds()[zbDim];
296         }
297       }
298     } else { // no DIM=
299       resultShape = ConstantSubscripts{array->Rank()}; // always a vector
300       ConstantSubscript n{GetSize(array->shape())};
301       resultIndices = ConstantSubscripts(array->Rank(), 0);
302       for (ConstantSubscript j{0}; j < n; ++j, array->IncrementSubscripts(at),
303            mask && mask->IncrementSubscripts(maskAt)) {
304         if ((!mask || mask->At(maskAt).IsTrue()) &&
305             IsHit(array->At(at), value, relation)) {
306           resultIndices = at;
307           if constexpr (WHICH == WhichLocation::Findloc) {
308             if (!back) {
309               break;
310             }
311           }
312         }
313       }
314     }
315     std::vector<Scalar<SubscriptInteger>> resultElements;
316     for (ConstantSubscript j : resultIndices) {
317       resultElements.emplace_back(j);
318     }
319     return Constant<SubscriptInteger>{
320         std::move(resultElements), std::move(resultShape)};
321   }
322 
323 private:
324   template <typename T>
325   bool IsHit(typename Constant<T>::Element element,
326       std::optional<Constant<T>> &value,
327       [[maybe_unused]] RelationalOperator relation) const {
328     std::optional<Expr<LogicalResult>> cmp;
329     bool result{true};
330     if (value) {
331       if constexpr (T::category == TypeCategory::Logical) {
332         // array(at) .EQV. value?
333         static_assert(WHICH == WhichLocation::Findloc);
334         cmp.emplace(ConvertToType<LogicalResult>(
335             Expr<T>{LogicalOperation<T::kind>{LogicalOperator::Eqv,
336                 Expr<T>{Constant<T>{element}}, Expr<T>{Constant<T>{*value}}}}));
337       } else { // compare array(at) to value
338         cmp.emplace(PackageRelation(relation, Expr<T>{Constant<T>{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") { // incl. babs, iiabs, jiaabs, & kiabs
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"_warn_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"_warn_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"_warn_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 == "ibits") {
566     return FoldElementalIntrinsic<T, T, Int4, Int4>(context, std::move(funcRef),
567         ScalarFunc<T, T, Int4, Int4>([&](const Scalar<T> &i,
568                                          const Scalar<Int4> &pos,
569                                          const Scalar<Int4> &len) -> Scalar<T> {
570           auto posVal{static_cast<int>(pos.ToInt64())};
571           auto lenVal{static_cast<int>(len.ToInt64())};
572           if (posVal < 0) {
573             context.messages().Say(
574                 "bit position for IBITS(POS=%d,LEN=%d) is negative"_err_en_US,
575                 posVal, lenVal);
576           } else if (lenVal < 0) {
577             context.messages().Say(
578                 "bit length for IBITS(POS=%d,LEN=%d) is negative"_err_en_US,
579                 posVal, lenVal);
580           } else if (posVal + lenVal > i.bits) {
581             context.messages().Say(
582                 "IBITS(POS=%d,LEN=%d) must have POS+LEN no greater than %d"_err_en_US,
583                 posVal + lenVal, i.bits);
584           }
585           return i.IBITS(posVal, lenVal);
586         }));
587   } else if (name == "index" || name == "scan" || name == "verify") {
588     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
589       return std::visit(
590           [&](const auto &kch) -> Expr<T> {
591             using TC = typename std::decay_t<decltype(kch)>::Result;
592             if (UnwrapExpr<Expr<SomeLogical>>(args[2])) { // BACK=
593               return FoldElementalIntrinsic<T, TC, TC, LogicalResult>(context,
594                   std::move(funcRef),
595                   ScalarFunc<T, TC, TC, LogicalResult>{
596                       [&name](const Scalar<TC> &str, const Scalar<TC> &other,
597                           const Scalar<LogicalResult> &back) -> Scalar<T> {
598                         return name == "index"
599                             ? CharacterUtils<TC::kind>::INDEX(
600                                   str, other, back.IsTrue())
601                             : name == "scan" ? CharacterUtils<TC::kind>::SCAN(
602                                                    str, other, back.IsTrue())
603                                              : CharacterUtils<TC::kind>::VERIFY(
604                                                    str, other, back.IsTrue());
605                       }});
606             } else {
607               return FoldElementalIntrinsic<T, TC, TC>(context,
608                   std::move(funcRef),
609                   ScalarFunc<T, TC, TC>{
610                       [&name](const Scalar<TC> &str,
611                           const Scalar<TC> &other) -> Scalar<T> {
612                         return name == "index"
613                             ? CharacterUtils<TC::kind>::INDEX(str, other)
614                             : name == "scan"
615                             ? CharacterUtils<TC::kind>::SCAN(str, other)
616                             : CharacterUtils<TC::kind>::VERIFY(str, other);
617                       }});
618             }
619           },
620           charExpr->u);
621     } else {
622       DIE("first argument must be CHARACTER");
623     }
624   } else if (name == "int") {
625     if (auto *expr{UnwrapExpr<Expr<SomeType>>(args[0])}) {
626       return std::visit(
627           [&](auto &&x) -> Expr<T> {
628             using From = std::decay_t<decltype(x)>;
629             if constexpr (std::is_same_v<From, BOZLiteralConstant> ||
630                 IsNumericCategoryExpr<From>()) {
631               return Fold(context, ConvertToType<T>(std::move(x)));
632             }
633             DIE("int() argument type not valid");
634           },
635           std::move(expr->u));
636     }
637   } else if (name == "int_ptr_kind") {
638     return Expr<T>{8};
639   } else if (name == "kind") {
640     if constexpr (common::HasMember<T, IntegerTypes>) {
641       return Expr<T>{args[0].value().GetType()->kind()};
642     } else {
643       DIE("kind() result not integral");
644     }
645   } else if (name == "iparity") {
646     return FoldBitReduction(
647         context, std::move(funcRef), &Scalar<T>::IEOR, Scalar<T>{});
648   } else if (name == "ishft") {
649     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
650         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
651                                    const Scalar<Int4> &pos) -> Scalar<T> {
652           auto posVal{static_cast<int>(pos.ToInt64())};
653           if (posVal < -i.bits) {
654             context.messages().Say(
655                 "SHIFT=%d count for ishft is less than %d"_err_en_US, posVal,
656                 -i.bits);
657           } else if (posVal > i.bits) {
658             context.messages().Say(
659                 "SHIFT=%d count for ishft is greater than %d"_err_en_US, posVal,
660                 i.bits);
661           }
662           return i.ISHFT(posVal);
663         }));
664   } else if (name == "lbound") {
665     return LBOUND(context, std::move(funcRef));
666   } else if (name == "leadz" || name == "trailz" || name == "poppar" ||
667       name == "popcnt") {
668     if (auto *sn{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
669       return std::visit(
670           [&funcRef, &context, &name](const auto &n) -> Expr<T> {
671             using TI = typename std::decay_t<decltype(n)>::Result;
672             if (name == "poppar") {
673               return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
674                   ScalarFunc<T, TI>([](const Scalar<TI> &i) -> Scalar<T> {
675                     return Scalar<T>{i.POPPAR() ? 1 : 0};
676                   }));
677             }
678             auto fptr{&Scalar<TI>::LEADZ};
679             if (name == "leadz") { // done in fptr definition
680             } else if (name == "trailz") {
681               fptr = &Scalar<TI>::TRAILZ;
682             } else if (name == "popcnt") {
683               fptr = &Scalar<TI>::POPCNT;
684             } else {
685               common::die(
686                   "missing case to fold intrinsic function %s", name.c_str());
687             }
688             return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
689                 ScalarFunc<T, TI>([&fptr](const Scalar<TI> &i) -> Scalar<T> {
690                   return Scalar<T>{std::invoke(fptr, i)};
691                 }));
692           },
693           sn->u);
694     } else {
695       DIE("leadz argument must be integer");
696     }
697   } else if (name == "len") {
698     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
699       return std::visit(
700           [&](auto &kx) {
701             if (auto len{kx.LEN()}) {
702               if (IsScopeInvariantExpr(*len)) {
703                 return Fold(context, ConvertToType<T>(*std::move(len)));
704               } else {
705                 return Expr<T>{std::move(funcRef)};
706               }
707             } else {
708               return Expr<T>{std::move(funcRef)};
709             }
710           },
711           charExpr->u);
712     } else {
713       DIE("len() argument must be of character type");
714     }
715   } else if (name == "len_trim") {
716     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
717       return std::visit(
718           [&](const auto &kch) -> Expr<T> {
719             using TC = typename std::decay_t<decltype(kch)>::Result;
720             return FoldElementalIntrinsic<T, TC>(context, std::move(funcRef),
721                 ScalarFunc<T, TC>{[](const Scalar<TC> &str) -> Scalar<T> {
722                   return CharacterUtils<TC::kind>::LEN_TRIM(str);
723                 }});
724           },
725           charExpr->u);
726     } else {
727       DIE("len_trim() argument must be of character type");
728     }
729   } else if (name == "maskl" || name == "maskr") {
730     // Argument can be of any kind but value has to be smaller than BIT_SIZE.
731     // It can be safely converted to Int4 to simplify.
732     const auto fptr{name == "maskl" ? &Scalar<T>::MASKL : &Scalar<T>::MASKR};
733     return FoldElementalIntrinsic<T, Int4>(context, std::move(funcRef),
734         ScalarFunc<T, Int4>([&fptr](const Scalar<Int4> &places) -> Scalar<T> {
735           return fptr(static_cast<int>(places.ToInt64()));
736         }));
737   } else if (name == "max") {
738     return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
739   } else if (name == "max0" || name == "max1") {
740     return RewriteSpecificMINorMAX(context, std::move(funcRef));
741   } else if (name == "maxexponent") {
742     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
743       return std::visit(
744           [](const auto &x) {
745             using TR = typename std::decay_t<decltype(x)>::Result;
746             return Expr<T>{Scalar<TR>::MAXEXPONENT};
747           },
748           sx->u);
749     }
750   } else if (name == "maxloc") {
751     return FoldLocation<WhichLocation::Maxloc, T>(context, std::move(funcRef));
752   } else if (name == "maxval") {
753     return FoldMaxvalMinval<T>(context, std::move(funcRef),
754         RelationalOperator::GT, T::Scalar::Least());
755   } else if (name == "merge") {
756     return FoldMerge<T>(context, std::move(funcRef));
757   } else if (name == "merge_bits") {
758     return FoldElementalIntrinsic<T, T, T, T>(
759         context, std::move(funcRef), &Scalar<T>::MERGE_BITS);
760   } else if (name == "min") {
761     return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
762   } else if (name == "min0" || name == "min1") {
763     return RewriteSpecificMINorMAX(context, std::move(funcRef));
764   } else if (name == "minexponent") {
765     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
766       return std::visit(
767           [](const auto &x) {
768             using TR = typename std::decay_t<decltype(x)>::Result;
769             return Expr<T>{Scalar<TR>::MINEXPONENT};
770           },
771           sx->u);
772     }
773   } else if (name == "minloc") {
774     return FoldLocation<WhichLocation::Minloc, T>(context, std::move(funcRef));
775   } else if (name == "minval") {
776     return FoldMaxvalMinval<T>(
777         context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE());
778   } else if (name == "mod") {
779     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
780         ScalarFuncWithContext<T, T, T>(
781             [](FoldingContext &context, const Scalar<T> &x,
782                 const Scalar<T> &y) -> Scalar<T> {
783               auto quotRem{x.DivideSigned(y)};
784               if (quotRem.divisionByZero) {
785                 context.messages().Say("mod() by zero"_warn_en_US);
786               } else if (quotRem.overflow) {
787                 context.messages().Say("mod() folding overflowed"_warn_en_US);
788               }
789               return quotRem.remainder;
790             }));
791   } else if (name == "modulo") {
792     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
793         ScalarFuncWithContext<T, T, T>(
794             [](FoldingContext &context, const Scalar<T> &x,
795                 const Scalar<T> &y) -> Scalar<T> {
796               auto result{x.MODULO(y)};
797               if (result.overflow) {
798                 context.messages().Say(
799                     "modulo() folding overflowed"_warn_en_US);
800               }
801               return result.value;
802             }));
803   } else if (name == "not") {
804     return FoldElementalIntrinsic<T, T>(
805         context, std::move(funcRef), &Scalar<T>::NOT);
806   } else if (name == "precision") {
807     if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
808       return Expr<T>{std::visit(
809           [](const auto &kx) {
810             return Scalar<ResultType<decltype(kx)>>::PRECISION;
811           },
812           cx->u)};
813     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
814       return Expr<T>{std::visit(
815           [](const auto &kx) {
816             return Scalar<typename ResultType<decltype(kx)>::Part>::PRECISION;
817           },
818           cx->u)};
819     }
820   } else if (name == "product") {
821     return FoldProduct<T>(context, std::move(funcRef), Scalar<T>{1});
822   } else if (name == "radix") {
823     return Expr<T>{2};
824   } else if (name == "range") {
825     if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
826       return Expr<T>{std::visit(
827           [](const auto &kx) {
828             return Scalar<ResultType<decltype(kx)>>::RANGE;
829           },
830           cx->u)};
831     } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
832       return Expr<T>{std::visit(
833           [](const auto &kx) {
834             return Scalar<ResultType<decltype(kx)>>::RANGE;
835           },
836           cx->u)};
837     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
838       return Expr<T>{std::visit(
839           [](const auto &kx) {
840             return Scalar<typename ResultType<decltype(kx)>::Part>::RANGE;
841           },
842           cx->u)};
843     }
844   } else if (name == "rank") {
845     if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
846       if (auto named{ExtractNamedEntity(*array)}) {
847         const Symbol &symbol{named->GetLastSymbol()};
848         if (IsAssumedRank(symbol)) {
849           // DescriptorInquiry can only be placed in expression of kind
850           // DescriptorInquiry::Result::kind.
851           return ConvertToType<T>(Expr<
852               Type<TypeCategory::Integer, DescriptorInquiry::Result::kind>>{
853               DescriptorInquiry{*named, DescriptorInquiry::Field::Rank}});
854         }
855       }
856       return Expr<T>{args[0].value().Rank()};
857     }
858     return Expr<T>{args[0].value().Rank()};
859   } else if (name == "selected_char_kind") {
860     if (const auto *chCon{UnwrapExpr<Constant<TypeOf<std::string>>>(args[0])}) {
861       if (std::optional<std::string> value{chCon->GetScalarValue()}) {
862         int defaultKind{
863             context.defaults().GetDefaultKind(TypeCategory::Character)};
864         return Expr<T>{SelectedCharKind(*value, defaultKind)};
865       }
866     }
867   } else if (name == "selected_int_kind") {
868     if (auto p{GetInt64Arg(args[0])}) {
869       return Expr<T>{SelectedIntKind(*p)};
870     }
871   } else if (name == "selected_real_kind" ||
872       name == "__builtin_ieee_selected_real_kind") {
873     if (auto p{GetInt64ArgOr(args[0], 0)}) {
874       if (auto r{GetInt64ArgOr(args[1], 0)}) {
875         if (auto radix{GetInt64ArgOr(args[2], 2)}) {
876           return Expr<T>{SelectedRealKind(*p, *r, *radix)};
877         }
878       }
879     }
880   } else if (name == "shape") {
881     if (auto shape{GetContextFreeShape(context, args[0])}) {
882       if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
883         return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
884       }
885     }
886   } else if (name == "shifta" || name == "shiftr" || name == "shiftl") {
887     // Second argument can be of any kind. However, it must be smaller or
888     // equal than BIT_SIZE. It can be converted to Int4 to simplify.
889     auto fptr{&Scalar<T>::SHIFTA};
890     if (name == "shifta") { // done in fptr definition
891     } else if (name == "shiftr") {
892       fptr = &Scalar<T>::SHIFTR;
893     } else if (name == "shiftl") {
894       fptr = &Scalar<T>::SHIFTL;
895     } else {
896       common::die("missing case to fold intrinsic function %s", name.c_str());
897     }
898     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
899         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
900                                    const Scalar<Int4> &pos) -> Scalar<T> {
901           auto posVal{static_cast<int>(pos.ToInt64())};
902           if (posVal < 0) {
903             context.messages().Say(
904                 "SHIFT=%d count for %s is negative"_err_en_US, posVal, name);
905           } else if (posVal > i.bits) {
906             context.messages().Say(
907                 "SHIFT=%d count for %s is greater than %d"_err_en_US, posVal,
908                 name, i.bits);
909           }
910           return std::invoke(fptr, i, posVal);
911         }));
912   } else if (name == "sign") {
913     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
914         ScalarFunc<T, T, T>(
915             [&context](const Scalar<T> &j, const Scalar<T> &k) -> Scalar<T> {
916               typename Scalar<T>::ValueWithOverflow result{j.SIGN(k)};
917               if (result.overflow) {
918                 context.messages().Say(
919                     "sign(integer(kind=%d)) folding overflowed"_warn_en_US,
920                     KIND);
921               }
922               return result.value;
923             }));
924   } else if (name == "size") {
925     if (auto shape{GetContextFreeShape(context, args[0])}) {
926       if (auto &dimArg{args[1]}) { // DIM= is present, get one extent
927         if (auto dim{GetInt64Arg(args[1])}) {
928           int rank{GetRank(*shape)};
929           if (*dim >= 1 && *dim <= rank) {
930             const Symbol *symbol{UnwrapWholeSymbolDataRef(args[0])};
931             if (symbol && IsAssumedSizeArray(*symbol) && *dim == rank) {
932               context.messages().Say(
933                   "size(array,dim=%jd) of last dimension is not available for rank-%d assumed-size array dummy argument"_err_en_US,
934                   *dim, rank);
935               return MakeInvalidIntrinsic<T>(std::move(funcRef));
936             } else if (auto &extent{shape->at(*dim - 1)}) {
937               return Fold(context, ConvertToType<T>(std::move(*extent)));
938             }
939           } else {
940             context.messages().Say(
941                 "size(array,dim=%jd) dimension is out of range for rank-%d array"_warn_en_US,
942                 *dim, rank);
943           }
944         }
945       } else if (auto extents{common::AllElementsPresent(std::move(*shape))}) {
946         // DIM= is absent; compute PRODUCT(SHAPE())
947         ExtentExpr product{1};
948         for (auto &&extent : std::move(*extents)) {
949           product = std::move(product) * std::move(extent);
950         }
951         return Expr<T>{ConvertToType<T>(Fold(context, std::move(product)))};
952       }
953     }
954   } else if (name == "sizeof") { // in bytes; extension
955     if (auto info{
956             characteristics::TypeAndShape::Characterize(args[0], context)}) {
957       if (auto bytes{info->MeasureSizeInBytes(context)}) {
958         return Expr<T>{Fold(context, ConvertToType<T>(std::move(*bytes)))};
959       }
960     }
961   } else if (name == "storage_size") { // in bits
962     if (auto info{
963             characteristics::TypeAndShape::Characterize(args[0], context)}) {
964       if (auto bytes{info->MeasureElementSizeInBytes(context, true)}) {
965         return Expr<T>{
966             Fold(context, Expr<T>{8} * ConvertToType<T>(std::move(*bytes)))};
967       }
968     }
969   } else if (name == "sum") {
970     return FoldSum<T>(context, std::move(funcRef));
971   } else if (name == "ubound") {
972     return UBOUND(context, std::move(funcRef));
973   }
974   // TODO: dot_product, ishftc, matmul, sign, transfer
975   return Expr<T>{std::move(funcRef)};
976 }
977 
978 // Substitutes a bare type parameter reference with its value if it has one now
979 // in an instantiation.  Bare LEN type parameters are substituted only when
980 // the known value is constant.
981 Expr<TypeParamInquiry::Result> FoldOperation(
982     FoldingContext &context, TypeParamInquiry &&inquiry) {
983   std::optional<NamedEntity> base{inquiry.base()};
984   parser::CharBlock parameterName{inquiry.parameter().name()};
985   if (base) {
986     // Handling "designator%typeParam".  Get the value of the type parameter
987     // from the instantiation of the base
988     if (const semantics::DeclTypeSpec *
989         declType{base->GetLastSymbol().GetType()}) {
990       if (const semantics::ParamValue *
991           paramValue{
992               declType->derivedTypeSpec().FindParameter(parameterName)}) {
993         const semantics::MaybeIntExpr &paramExpr{paramValue->GetExplicit()};
994         if (paramExpr && IsConstantExpr(*paramExpr)) {
995           Expr<SomeInteger> intExpr{*paramExpr};
996           return Fold(context,
997               ConvertToType<TypeParamInquiry::Result>(std::move(intExpr)));
998         }
999       }
1000     }
1001   } else {
1002     // A "bare" type parameter: replace with its value, if that's now known
1003     // in a current derived type instantiation, for KIND type parameters.
1004     if (const auto *pdt{context.pdtInstance()}) {
1005       bool isLen{false};
1006       if (const semantics::Scope * scope{context.pdtInstance()->scope()}) {
1007         auto iter{scope->find(parameterName)};
1008         if (iter != scope->end()) {
1009           const Symbol &symbol{*iter->second};
1010           const auto *details{symbol.detailsIf<semantics::TypeParamDetails>()};
1011           if (details) {
1012             isLen = details->attr() == common::TypeParamAttr::Len;
1013             const semantics::MaybeIntExpr &initExpr{details->init()};
1014             if (initExpr && IsConstantExpr(*initExpr) &&
1015                 (!isLen || ToInt64(*initExpr))) {
1016               Expr<SomeInteger> expr{*initExpr};
1017               return Fold(context,
1018                   ConvertToType<TypeParamInquiry::Result>(std::move(expr)));
1019             }
1020           }
1021         }
1022       }
1023       if (const auto *value{pdt->FindParameter(parameterName)}) {
1024         if (value->isExplicit()) {
1025           auto folded{Fold(context,
1026               AsExpr(ConvertToType<TypeParamInquiry::Result>(
1027                   Expr<SomeInteger>{value->GetExplicit().value()})))};
1028           if (!isLen || ToInt64(folded)) {
1029             return folded;
1030           }
1031         }
1032       }
1033     }
1034   }
1035   return AsExpr(std::move(inquiry));
1036 }
1037 
1038 std::optional<std::int64_t> ToInt64(const Expr<SomeInteger> &expr) {
1039   return std::visit(
1040       [](const auto &kindExpr) { return ToInt64(kindExpr); }, expr.u);
1041 }
1042 
1043 std::optional<std::int64_t> ToInt64(const Expr<SomeType> &expr) {
1044   if (const auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(expr)}) {
1045     return ToInt64(*intExpr);
1046   } else {
1047     return std::nullopt;
1048   }
1049 }
1050 
1051 #ifdef _MSC_VER // disable bogus warning about missing definitions
1052 #pragma warning(disable : 4661)
1053 #endif
1054 FOR_EACH_INTEGER_KIND(template class ExpressionBase, )
1055 template class ExpressionBase<SomeInteger>;
1056 } // namespace Fortran::evaluate
1057