Debian Codegraph @

flang/lib/Evaluate/fold-integer.cpp

raw
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-matmul.h"
11 #include "fold-reduction.h"
12 #include "flang/Evaluate/check-expression.h"
13
14 namespace Fortran::evaluate {
15
16 // Given a collection of ConstantSubscripts values, package them as a Constant.
17 // Return scalar value if asScalar == true and shape-dim array otherwise.
18 template <typename T>
19 Expr<T> PackageConstantBounds(
20 const ConstantSubscripts &&bounds, bool asScalar = false) {
21 if (asScalar) {
22 return Expr<T>{Constant<T>{bounds.at(0)}};
23 } else {
24 // As rank-dim array
25 const int rank{GetRank(bounds)};
26 std::vector<Scalar<T>> packed(rank);
27 std::transform(bounds.begin(), bounds.end(), packed.begin(),
28 [](ConstantSubscript x) { return Scalar<T>(x); });
29 return Expr<T>{Constant<T>{std::move(packed), ConstantSubscripts{rank}}};
30 }
31 }
32
33 // If a DIM= argument to LBOUND(), UBOUND(), or SIZE() exists and has a valid
34 // constant value, return in "dimVal" that value, less 1 (to make it suitable
35 // for use as a C++ vector<> index). Also check for erroneous constant values
36 // and returns false on error.
37 static bool CheckDimArg(const std::optional<ActualArgument> &dimArg,
38 const Expr<SomeType> &array, parser::ContextualMessages &messages,
39 bool isLBound, std::optional<int> &dimVal) {
40 dimVal.reset();
41 if (int rank{array.Rank()}; rank > 0 || IsAssumedRank(array)) {
42 auto named{ExtractNamedEntity(array)};
43 if (auto dim64{ToInt64(dimArg)}) {
44 if (*dim64 < 1) {
45 messages.Say("DIM=%jd dimension must be positive"_err_en_US, *dim64);
46 return false;
47 } else if (!IsAssumedRank(array) && *dim64 > rank) {
48 messages.Say(
49 "DIM=%jd dimension is out of range for rank-%d array"_err_en_US,
50 *dim64, rank);
51 return false;
52 } else if (!isLBound && named &&
53 semantics::IsAssumedSizeArray(named->GetLastSymbol()) &&
54 *dim64 == rank) {
55 messages.Say(
56 "DIM=%jd dimension is out of range for rank-%d assumed-size array"_err_en_US,
57 *dim64, rank);
58 return false;
59 } else if (IsAssumedRank(array)) {
60 if (*dim64 > common::maxRank) {
61 messages.Say(
62 "DIM=%jd dimension is too large for any array (maximum rank %d)"_err_en_US,
63 *dim64, common::maxRank);
64 return false;
65 }
66 } else {
67 dimVal = static_cast<int>(*dim64 - 1); // 1-based to 0-based
68 }
69 }
70 }
71 return true;
72 }
73
74 // Class to retrieve the constant bound of an expression which is an
75 // array that devolves to a type of Constant<T>
76 class GetConstantArrayBoundHelper {
77 public:
78 template <typename T>
79 static Expr<T> GetLbound(
80 const Expr<SomeType> &array, std::optional<int> dim) {
81 return PackageConstantBounds<T>(
82 GetConstantArrayBoundHelper(dim, /*getLbound=*/true).Get(array),
83 dim.has_value());
84 }
85
86 template <typename T>
87 static Expr<T> GetUbound(
88 const Expr<SomeType> &array, std::optional<int> dim) {
89 return PackageConstantBounds<T>(
90 GetConstantArrayBoundHelper(dim, /*getLbound=*/false).Get(array),
91 dim.has_value());
92 }
93
94 private:
95 GetConstantArrayBoundHelper(
96 std::optional<ConstantSubscript> dim, bool getLbound)
97 : dim_{dim}, getLbound_{getLbound} {}
98
99 template <typename T> ConstantSubscripts Get(const T &) {
100 // The method is needed for template expansion, but we should never get
101 // here in practice.
102 CHECK(false);
103 return {0};
104 }
105
106 template <typename T> ConstantSubscripts Get(const Constant<T> &x) {
107 if (getLbound_) {
108 // Return the lower bound
109 if (dim_) {
110 return {x.lbounds().at(*dim_)};
111 } else {
112 return x.lbounds();
113 }
114 } else {
115 // Return the upper bound
116 if (arrayFromParenthesesExpr) {
117 // Underlying array comes from (x) expression - return shapes
118 if (dim_) {
119 return {x.shape().at(*dim_)};
120 } else {
121 return x.shape();
122 }
123 } else {
124 return x.ComputeUbounds(dim_);
125 }
126 }
127 }
128
129 template <typename T> ConstantSubscripts Get(const Parentheses<T> &x) {
130 // Case of temp variable inside parentheses - return [1, ... 1] for lower
131 // bounds and shape for upper bounds
132 if (getLbound_) {
133 return ConstantSubscripts(x.Rank(), ConstantSubscript{1});
134 } else {
135 // Indicate that underlying array comes from parentheses expression.
136 // Continue to unwrap expression until we hit a constant
137 arrayFromParenthesesExpr = true;
138 return Get(x.left());
139 }
140 }
141
142 template <typename T> ConstantSubscripts Get(const Expr<T> &x) {
143 // recurse through Expr<T>'a until we hit a constant
144 return common::visit([&](const auto &inner) { return Get(inner); },
145 // [&](const auto &) { return 0; },
146 x.u);
147 }
148
149 const std::optional<ConstantSubscript> dim_;
150 const bool getLbound_;
151 bool arrayFromParenthesesExpr{false};
152 };
153
154 template <int KIND>
155 Expr<Type<TypeCategory::Integer, KIND>> LBOUND(FoldingContext &context,
156 FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
157 using T = Type<TypeCategory::Integer, KIND>;
158 ActualArguments &args{funcRef.arguments()};
159 if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
160 std::optional<int> dim;
161 if (funcRef.Rank() == 0) {
162 // Optional DIM= argument is present: result is scalar.
163 if (!CheckDimArg(args[1], *array, context.messages(), true, dim)) {
164 return MakeInvalidIntrinsic<T>(std::move(funcRef));
165 } else if (!dim) {
166 // DIM= is present but not constant, or error
167 return Expr<T>{std::move(funcRef)};
168 }
169 }
170 if (IsAssumedRank(*array)) {
171 // Would like to return 1 if DIM=.. is present, but that would be
172 // hiding a runtime error if the DIM= were too large (including
173 // the case of an assumed-rank argument that's scalar).
174 } else if (int rank{array->Rank()}; rank > 0) {
175 bool lowerBoundsAreOne{true};
176 if (auto named{ExtractNamedEntity(*array)}) {
177 const Symbol &symbol{named->GetLastSymbol()};
178 if (symbol.Rank() == rank) {
179 lowerBoundsAreOne = false;
180 if (dim) {
181 if (auto lb{GetLBOUND(context, *named, *dim)}) {
182 return Fold(context, ConvertToType<T>(std::move(*lb)));
183 }
184 } else if (auto extents{
185 AsExtentArrayExpr(GetLBOUNDs(context, *named))}) {
186 return Fold(context,
187 ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
188 }
189 } else {
190 lowerBoundsAreOne = symbol.Rank() == 0; // LBOUND(array%component)
191 }
192 }
193 if (IsActuallyConstant(*array)) {
194 return GetConstantArrayBoundHelper::GetLbound<T>(*array, dim);
195 }
196 if (lowerBoundsAreOne) {
197 ConstantSubscripts ones(rank, ConstantSubscript{1});
198 return PackageConstantBounds<T>(std::move(ones), dim.has_value());
199 }
200 }
201 }
202 return Expr<T>{std::move(funcRef)};
203 }
204
205 template <int KIND>
206 Expr<Type<TypeCategory::Integer, KIND>> UBOUND(FoldingContext &context,
207 FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
208 using T = Type<TypeCategory::Integer, KIND>;
209 ActualArguments &args{funcRef.arguments()};
210 if (auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
211 std::optional<int> dim;
212 if (funcRef.Rank() == 0) {
213 // Optional DIM= argument is present: result is scalar.
214 if (!CheckDimArg(args[1], *array, context.messages(), false, dim)) {
215 return MakeInvalidIntrinsic<T>(std::move(funcRef));
216 } else if (!dim) {
217 // DIM= is present but not constant, or error
218 return Expr<T>{std::move(funcRef)};
219 }
220 }
221 if (IsAssumedRank(*array)) {
222 } else if (int rank{array->Rank()}; rank > 0) {
223 bool takeBoundsFromShape{true};
224 if (auto named{ExtractNamedEntity(*array)}) {
225 const Symbol &symbol{named->GetLastSymbol()};
226 if (symbol.Rank() == rank) {
227 takeBoundsFromShape = false;
228 if (dim) {
229 if (auto ub{GetUBOUND(context, *named, *dim)}) {
230 return Fold(context, ConvertToType<T>(std::move(*ub)));
231 }
232 } else {
233 Shape ubounds{GetUBOUNDs(context, *named)};
234 if (semantics::IsAssumedSizeArray(symbol)) {
235 CHECK(!ubounds.back());
236 ubounds.back() = ExtentExpr{-1};
237 }
238 if (auto extents{AsExtentArrayExpr(ubounds)}) {
239 return Fold(context,
240 ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
241 }
242 }
243 } else {
244 takeBoundsFromShape = symbol.Rank() == 0; // UBOUND(array%component)
245 }
246 }
247 if (IsActuallyConstant(*array)) {
248 return GetConstantArrayBoundHelper::GetUbound<T>(*array, dim);
249 }
250 if (takeBoundsFromShape) {
251 if (auto shape{GetContextFreeShape(context, *array)}) {
252 if (dim) {
253 if (auto &dimSize{shape->at(*dim)}) {
254 return Fold(context,
255 ConvertToType<T>(Expr<ExtentType>{std::move(*dimSize)}));
256 }
257 } else if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
258 return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
259 }
260 }
261 }
262 }
263 }
264 return Expr<T>{std::move(funcRef)};
265 }
266
267 // COUNT()
268 template <typename T, int MASK_KIND> class CountAccumulator {
269 using MaskT = Type<TypeCategory::Logical, MASK_KIND>;
270
271 public:
272 CountAccumulator(const Constant<MaskT> &mask) : mask_{mask} {}
273 void operator()(
274 Scalar<T> &element, const ConstantSubscripts &at, bool /*first*/) {
275 if (mask_.At(at).IsTrue()) {
276 auto incremented{element.AddSigned(Scalar<T>{1})};
277 overflow_ |= incremented.overflow;
278 element = incremented.value;
279 }
280 }
281 bool overflow() const { return overflow_; }
282 void Done(Scalar<T> &) const {}
283
284 private:
285 const Constant<MaskT> &mask_;
286 bool overflow_{false};
287 };
288
289 template <typename T, int maskKind>
290 static Expr<T> FoldCount(FoldingContext &context, FunctionRef<T> &&ref) {
291 using KindLogical = Type<TypeCategory::Logical, maskKind>;
292 static_assert(T::category == TypeCategory::Integer);
293 std::optional<int> dim;
294 if (std::optional<ArrayAndMask<KindLogical>> arrayAndMask{
295 ProcessReductionArgs<KindLogical>(
296 context, ref.arguments(), dim, /*ARRAY=*/0, /*DIM=*/1)}) {
297 CountAccumulator<T, maskKind> accumulator{arrayAndMask->array};
298 Constant<T> result{DoReduction<T>(arrayAndMask->array, arrayAndMask->mask,
299 dim, Scalar<T>{}, accumulator)};
300 if (accumulator.overflow() &&
301 context.languageFeatures().ShouldWarn(
302 common::UsageWarning::FoldingException)) {
303 context.messages().Say(
304 "Result of intrinsic function COUNT overflows its result type"_warn_en_US);
305 }
306 return Expr<T>{std::move(result)};
307 }
308 return Expr<T>{std::move(ref)};
309 }
310
311 // FINDLOC(), MAXLOC(), & MINLOC()
312 enum class WhichLocation { Findloc, Maxloc, Minloc };
313 template <WhichLocation WHICH> class LocationHelper {
314 public:
315 LocationHelper(
316 DynamicType &&type, ActualArguments &arg, FoldingContext &context)
317 : type_{type}, arg_{arg}, context_{context} {}
318 using Result = std::optional<Constant<SubscriptInteger>>;
319 using Types = std::conditional_t<WHICH == WhichLocation::Findloc,
320 AllIntrinsicTypes, RelationalTypes>;
321
322 template <typename T> Result Test() const {
323 if (T::category != type_.category() || T::kind != type_.kind()) {
324 return std::nullopt;
325 }
326 CHECK(arg_.size() == (WHICH == WhichLocation::Findloc ? 6 : 5));
327 Folder<T> folder{context_};
328 Constant<T> *array{folder.Folding(arg_[0])};
329 if (!array) {
330 return std::nullopt;
331 }
332 std::optional<Constant<T>> value;
333 if constexpr (WHICH == WhichLocation::Findloc) {
334 if (const Constant<T> *p{folder.Folding(arg_[1])}) {
335 value.emplace(*p);
336 } else {
337 return std::nullopt;
338 }
339 }
340 std::optional<int> dim;
341 Constant<LogicalResult> *mask{
342 GetReductionMASK(arg_[maskArg], array->shape(), context_)};
343 if ((!mask && arg_[maskArg]) ||
344 !CheckReductionDIM(dim, context_, arg_, dimArg, array->Rank())) {
345 return std::nullopt;
346 }
347 bool back{false};
348 if (arg_[backArg]) {
349 const auto *backConst{
350 Folder<LogicalResult>{context_}.Folding(arg_[backArg])};
351 if (backConst) {
352 back = backConst->GetScalarValue().value().IsTrue();
353 } else {
354 return std::nullopt;
355 }
356 }
357 const RelationalOperator relation{WHICH == WhichLocation::Findloc
358 ? RelationalOperator::EQ
359 : WHICH == WhichLocation::Maxloc
360 ? (back ? RelationalOperator::GE : RelationalOperator::GT)
361 : back ? RelationalOperator::LE
362 : RelationalOperator::LT};
363 // Use lower bounds of 1 exclusively.
364 array->SetLowerBoundsToOne();
365 ConstantSubscripts at{array->lbounds()}, maskAt, resultIndices, resultShape;
366 if (mask) {
367 if (auto scalarMask{mask->GetScalarValue()}) {
368 // Convert into array in case of scalar MASK= (for
369 // MAXLOC/MINLOC/FINDLOC mask should be conformable)
370 ConstantSubscript n{GetSize(array->shape())};
371 std::vector<Scalar<LogicalResult>> mask_elements(
372 n, Scalar<LogicalResult>{scalarMask.value()});
373 *mask = Constant<LogicalResult>{
374 std::move(mask_elements), ConstantSubscripts{array->shape()}};
375 }
376 mask->SetLowerBoundsToOne();
377 maskAt = mask->lbounds();
378 }
379 if (dim) { // DIM=
380 if (*dim < 1 || *dim > array->Rank()) {
381 context_.messages().Say("DIM=%d is out of range"_err_en_US, *dim);
382 return std::nullopt;
383 }
384 int zbDim{*dim - 1};
385 resultShape = array->shape();
386 resultShape.erase(
387 resultShape.begin() + zbDim); // scalar if array is vector
388 ConstantSubscript dimLength{array->shape()[zbDim]};
389 ConstantSubscript n{GetSize(resultShape)};
390 for (ConstantSubscript j{0}; j < n; ++j) {
391 ConstantSubscript hit{0};
392 if constexpr (WHICH == WhichLocation::Maxloc ||
393 WHICH == WhichLocation::Minloc) {
394 value.reset();
395 }
396 for (ConstantSubscript k{0}; k < dimLength;
397 ++k, ++at[zbDim], mask && ++maskAt[zbDim]) {
398 if ((!mask || mask->At(maskAt).IsTrue()) &&
399 IsHit(array->At(at), value, relation, back)) {
400 hit = at[zbDim];
401 if constexpr (WHICH == WhichLocation::Findloc) {
402 if (!back) {
403 break;
404 }
405 }
406 }
407 }
408 resultIndices.emplace_back(hit);
409 at[zbDim] = std::max<ConstantSubscript>(dimLength, 1);
410 array->IncrementSubscripts(at);
411 at[zbDim] = 1;
412 if (mask) {
413 maskAt[zbDim] = mask->lbounds()[zbDim] +
414 std::max<ConstantSubscript>(dimLength, 1) - 1;
415 mask->IncrementSubscripts(maskAt);
416 maskAt[zbDim] = mask->lbounds()[zbDim];
417 }
418 }
419 } else { // no DIM=
420 resultShape = ConstantSubscripts{array->Rank()}; // always a vector
421 ConstantSubscript n{GetSize(array->shape())};
422 resultIndices = ConstantSubscripts(array->Rank(), 0);
423 for (ConstantSubscript j{0}; j < n; ++j, array->IncrementSubscripts(at),
424 mask && mask->IncrementSubscripts(maskAt)) {
425 if ((!mask || mask->At(maskAt).IsTrue()) &&
426 IsHit(array->At(at), value, relation, back)) {
427 resultIndices = at;
428 if constexpr (WHICH == WhichLocation::Findloc) {
429 if (!back) {
430 break;
431 }
432 }
433 }
434 }
435 }
436 std::vector<Scalar<SubscriptInteger>> resultElements;
437 for (ConstantSubscript j : resultIndices) {
438 resultElements.emplace_back(j);
439 }
440 return Constant<SubscriptInteger>{
441 std::move(resultElements), std::move(resultShape)};
442 }
443
444 private:
445 template <typename T>
446 bool IsHit(typename Constant<T>::Element element,
447 std::optional<Constant<T>> &value,
448 [[maybe_unused]] RelationalOperator relation,
449 [[maybe_unused]] bool back) const {
450 std::optional<Expr<LogicalResult>> cmp;
451 bool result{true};
452 if (value) {
453 if constexpr (T::category == TypeCategory::Logical) {
454 // array(at) .EQV. value?
455 static_assert(WHICH == WhichLocation::Findloc);
456 cmp.emplace(ConvertToType<LogicalResult>(
457 Expr<T>{LogicalOperation<T::kind>{LogicalOperator::Eqv,
458 Expr<T>{Constant<T>{element}}, Expr<T>{Constant<T>{*value}}}}));
459 } else { // compare array(at) to value
460 if constexpr (T::category == TypeCategory::Real &&
461 (WHICH == WhichLocation::Maxloc ||
462 WHICH == WhichLocation::Minloc)) {
463 if (value && value->GetScalarValue().value().IsNotANumber() &&
464 (back || !element.IsNotANumber())) {
465 // Replace NaN
466 cmp.emplace(Constant<LogicalResult>{Scalar<LogicalResult>{true}});
467 }
468 }
469 if (!cmp) {
470 cmp.emplace(PackageRelation(relation, Expr<T>{Constant<T>{element}},
471 Expr<T>{Constant<T>{*value}}));
472 }
473 }
474 Expr<LogicalResult> folded{Fold(context_, std::move(*cmp))};
475 result = GetScalarConstantValue<LogicalResult>(folded).value().IsTrue();
476 } else {
477 // first unmasked element for MAXLOC/MINLOC - always take it
478 }
479 if constexpr (WHICH == WhichLocation::Maxloc ||
480 WHICH == WhichLocation::Minloc) {
481 if (result) {
482 value.emplace(std::move(element));
483 }
484 }
485 return result;
486 }
487
488 static constexpr int dimArg{WHICH == WhichLocation::Findloc ? 2 : 1};
489 static constexpr int maskArg{dimArg + 1};
490 static constexpr int backArg{maskArg + 2};
491
492 DynamicType type_;
493 ActualArguments &arg_;
494 FoldingContext &context_;
495 };
496
497 template <WhichLocation which>
498 static std::optional<Constant<SubscriptInteger>> FoldLocationCall(
499 ActualArguments &arg, FoldingContext &context) {
500 if (arg[0]) {
501 if (auto type{arg[0]->GetType()}) {
502 if constexpr (which == WhichLocation::Findloc) {
503 // Both ARRAY and VALUE are susceptible to conversion to a common
504 // comparison type.
505 if (arg[1]) {
506 if (auto valType{arg[1]->GetType()}) {
507 if (auto compareType{ComparisonType(*type, *valType)}) {
508 type = compareType;
509 }
510 }
511 }
512 }
513 return common::SearchTypes(
514 LocationHelper<which>{std::move(*type), arg, context});
515 }
516 }
517 return std::nullopt;
518 }
519
520 template <WhichLocation which, typename T>
521 static Expr<T> FoldLocation(FoldingContext &context, FunctionRef<T> &&ref) {
522 static_assert(T::category == TypeCategory::Integer);
523 if (std::optional<Constant<SubscriptInteger>> found{
524 FoldLocationCall<which>(ref.arguments(), context)}) {
525 return Expr<T>{Fold(
526 context, ConvertToType<T>(Expr<SubscriptInteger>{std::move(*found)}))};
527 } else {
528 return Expr<T>{std::move(ref)};
529 }
530 }
531
532 // for IALL, IANY, & IPARITY
533 template <typename T>
534 static Expr<T> FoldBitReduction(FoldingContext &context, FunctionRef<T> &&ref,
535 Scalar<T> (Scalar<T>::*operation)(const Scalar<T> &) const,
536 Scalar<T> identity) {
537 static_assert(T::category == TypeCategory::Integer);
538 std::optional<int> dim;
539 if (std::optional<ArrayAndMask<T>> arrayAndMask{
540 ProcessReductionArgs<T>(context, ref.arguments(), dim,
541 /*ARRAY=*/0, /*DIM=*/1, /*MASK=*/2)}) {
542 OperationAccumulator<T> accumulator{arrayAndMask->array, operation};
543 return Expr<T>{DoReduction<T>(
544 arrayAndMask->array, arrayAndMask->mask, dim, identity, accumulator)};
545 }
546 return Expr<T>{std::move(ref)};
547 }
548
549 template <int KIND>
550 Expr<Type<TypeCategory::Integer, KIND>> FoldIntrinsicFunction(
551 FoldingContext &context,
552 FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
553 using T = Type<TypeCategory::Integer, KIND>;
554 using Int4 = Type<TypeCategory::Integer, 4>;
555 ActualArguments &args{funcRef.arguments()};
556 auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
557 CHECK(intrinsic);
558 std::string name{intrinsic->name};
559 auto FromInt64{[&name, &context](std::int64_t n) {
560 Scalar<T> result{n};
561 if (result.ToInt64() != n &&
562 context.languageFeatures().ShouldWarn(
563 common::UsageWarning::FoldingException)) {
564 context.messages().Say(
565 "Result of intrinsic function '%s' (%jd) overflows its result type"_warn_en_US,
566 name, std::intmax_t{n});
567 }
568 return result;
569 }};
570 if (name == "abs") { // incl. babs, iiabs, jiaabs, & kiabs
571 return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
572 ScalarFunc<T, T>([&context](const Scalar<T> &i) -> Scalar<T> {
573 typename Scalar<T>::ValueWithOverflow j{i.ABS()};
574 if (j.overflow &&
575 context.languageFeatures().ShouldWarn(
576 common::UsageWarning::FoldingException)) {
577 context.messages().Say(
578 "abs(integer(kind=%d)) folding overflowed"_warn_en_US, KIND);
579 }
580 return j.value;
581 }));
582 } else if (name == "bit_size") {
583 return Expr<T>{Scalar<T>::bits};
584 } else if (name == "ceiling" || name == "floor" || name == "nint") {
585 if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
586 // NINT rounds ties away from zero, not to even
587 common::RoundingMode mode{name == "ceiling" ? common::RoundingMode::Up
588 : name == "floor" ? common::RoundingMode::Down
589 : common::RoundingMode::TiesAwayFromZero};
590 return common::visit(
591 [&](const auto &kx) {
592 using TR = ResultType<decltype(kx)>;
593 return FoldElementalIntrinsic<T, TR>(context, std::move(funcRef),
594 ScalarFunc<T, TR>([&](const Scalar<TR> &x) {
595 auto y{x.template ToInteger<Scalar<T>>(mode)};
596 if (y.flags.test(RealFlag::Overflow) &&
597 context.languageFeatures().ShouldWarn(
598 common::UsageWarning::FoldingException)) {
599 context.messages().Say(
600 "%s intrinsic folding overflow"_warn_en_US, name);
601 }
602 return y.value;
603 }));
604 },
605 cx->u);
606 }
607 } else if (name == "count") {
608 int maskKind = args[0]->GetType()->kind();
609 switch (maskKind) {
610 SWITCH_COVERS_ALL_CASES
611 case 1:
612 return FoldCount<T, 1>(context, std::move(funcRef));
613 case 2:
614 return FoldCount<T, 2>(context, std::move(funcRef));
615 case 4:
616 return FoldCount<T, 4>(context, std::move(funcRef));
617 case 8:
618 return FoldCount<T, 8>(context, std::move(funcRef));
619 }
620 } else if (name == "digits") {
621 if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
622 return Expr<T>{common::visit(
623 [](const auto &kx) {
624 return Scalar<ResultType<decltype(kx)>>::DIGITS;
625 },
626 cx->u)};
627 } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
628 return Expr<T>{common::visit(
629 [](const auto &kx) {
630 return Scalar<ResultType<decltype(kx)>>::DIGITS;
631 },
632 cx->u)};
633 } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
634 return Expr<T>{common::visit(
635 [](const auto &kx) {
636 return Scalar<typename ResultType<decltype(kx)>::Part>::DIGITS;
637 },
638 cx->u)};
639 }
640 } else if (name == "dim") {
641 return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
642 ScalarFunc<T, T, T>([&context](const Scalar<T> &x,
643 const Scalar<T> &y) -> Scalar<T> {
644 auto result{x.DIM(y)};
645 if (result.overflow &&
646 context.languageFeatures().ShouldWarn(
647 common::UsageWarning::FoldingException)) {
648 context.messages().Say("DIM intrinsic folding overflow"_warn_en_US);
649 }
650 return result.value;
651 }));
652 } else if (name == "dot_product") {
653 return FoldDotProduct<T>(context, std::move(funcRef));
654 } else if (name == "dshiftl" || name == "dshiftr") {
655 const auto fptr{
656 name == "dshiftl" ? &Scalar<T>::DSHIFTL : &Scalar<T>::DSHIFTR};
657 // Third argument can be of any kind. However, it must be smaller or equal
658 // than BIT_SIZE. It can be converted to Int4 to simplify.
659 if (const auto *argCon{Folder<T>(context).Folding(args[0])};
660 argCon && argCon->empty()) {
661 } else if (const auto *shiftCon{Folder<Int4>(context).Folding(args[2])}) {
662 for (const auto &scalar : shiftCon->values()) {
663 std::int64_t shiftVal{scalar.ToInt64()};
664 if (shiftVal < 0) {
665 context.messages().Say("SHIFT=%jd count for %s is negative"_err_en_US,
666 std::intmax_t{shiftVal}, name);
667 break;
668 } else if (shiftVal > T::Scalar::bits) {
669 context.messages().Say(
670 "SHIFT=%jd count for %s is greater than %d"_err_en_US,
671 std::intmax_t{shiftVal}, name, T::Scalar::bits);
672 break;
673 }
674 }
675 }
676 return FoldElementalIntrinsic<T, T, T, Int4>(context, std::move(funcRef),
677 ScalarFunc<T, T, T, Int4>(
678 [&fptr](const Scalar<T> &i, const Scalar<T> &j,
679 const Scalar<Int4> &shift) -> Scalar<T> {
680 return std::invoke(fptr, i, j, static_cast<int>(shift.ToInt64()));
681 }));
682 } else if (name == "exponent") {
683 if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
684 return common::visit(
685 [&funcRef, &context](const auto &x) -> Expr<T> {
686 using TR = typename std::decay_t<decltype(x)>::Result;
687 return FoldElementalIntrinsic<T, TR>(context, std::move(funcRef),
688 &Scalar<TR>::template EXPONENT<Scalar<T>>);
689 },
690 sx->u);
691 } else {
692 DIE("exponent argument must be real");
693 }
694 } else if (name == "findloc") {
695 return FoldLocation<WhichLocation::Findloc, T>(context, std::move(funcRef));
696 } else if (name == "huge") {
697 return Expr<T>{Scalar<T>::HUGE()};
698 } else if (name == "iachar" || name == "ichar") {
699 auto *someChar{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
700 CHECK(someChar);
701 if (auto len{ToInt64(someChar->LEN())}) {
702 if (len.value() < 1) {
703 context.messages().Say(
704 "Character in intrinsic function %s must have length one"_err_en_US,
705 name);
706 } else if (len.value() > 1 &&
707 context.languageFeatures().ShouldWarn(
708 common::UsageWarning::Portability)) {
709 // Do not die, this was not checked before
710 context.messages().Say(
711 "Character in intrinsic function %s should have length one"_port_en_US,
712 name);
713 } else {
714 return common::visit(
715 [&funcRef, &context, &FromInt64](const auto &str) -> Expr<T> {
716 using Char = typename std::decay_t<decltype(str)>::Result;
717 (void)FromInt64;
718 return FoldElementalIntrinsic<T, Char>(context,
719 std::move(funcRef),
720 ScalarFunc<T, Char>(
721 #ifndef _MSC_VER
722 [&FromInt64](const Scalar<Char> &c) {
723 return FromInt64(CharacterUtils<Char::kind>::ICHAR(
724 CharacterUtils<Char::kind>::Resize(c, 1)));
725 }));
726 #else // _MSC_VER
727 // MSVC 14 get confused by the original code above and
728 // ends up emitting an error about passing a std::string
729 // to the std::u16string instantiation of
730 // CharacterUtils<2>::ICHAR(). Can't find a work-around,
731 // so remove the FromInt64 error checking lambda that
732 // seems to have caused the proble.
733 [](const Scalar<Char> &c) {
734 return CharacterUtils<Char::kind>::ICHAR(
735 CharacterUtils<Char::kind>::Resize(c, 1));
736 }));
737 #endif // _MSC_VER
738 },
739 someChar->u);
740 }
741 }
742 } else if (name == "iand" || name == "ior" || name == "ieor") {
743 auto fptr{&Scalar<T>::IAND};
744 if (name == "iand") { // done in fptr declaration
745 } else if (name == "ior") {
746 fptr = &Scalar<T>::IOR;
747 } else if (name == "ieor") {
748 fptr = &Scalar<T>::IEOR;
749 } else {
750 common::die("missing case to fold intrinsic function %s", name.c_str());
751 }
752 return FoldElementalIntrinsic<T, T, T>(
753 context, std::move(funcRef), ScalarFunc<T, T, T>(fptr));
754 } else if (name == "iall") {
755 return FoldBitReduction(
756 context, std::move(funcRef), &Scalar<T>::IAND, Scalar<T>{}.NOT());
757 } else if (name == "iany") {
758 return FoldBitReduction(
759 context, std::move(funcRef), &Scalar<T>::IOR, Scalar<T>{});
760 } else if (name == "ibclr" || name == "ibset") {
761 // Second argument can be of any kind. However, it must be smaller
762 // than BIT_SIZE. It can be converted to Int4 to simplify.
763 auto fptr{&Scalar<T>::IBCLR};
764 if (name == "ibclr") { // done in fptr definition
765 } else if (name == "ibset") {
766 fptr = &Scalar<T>::IBSET;
767 } else {
768 common::die("missing case to fold intrinsic function %s", name.c_str());
769 }
770 if (const auto *argCon{Folder<T>(context).Folding(args[0])};
771 argCon && argCon->empty()) {
772 } else if (const auto *posCon{Folder<Int4>(context).Folding(args[1])}) {
773 for (const auto &scalar : posCon->values()) {
774 std::int64_t posVal{scalar.ToInt64()};
775 if (posVal < 0) {
776 context.messages().Say(
777 "bit position for %s (%jd) is negative"_err_en_US, name,
778 std::intmax_t{posVal});
779 break;
780 } else if (posVal >= T::Scalar::bits) {
781 context.messages().Say(
782 "bit position for %s (%jd) is not less than %d"_err_en_US, name,
783 std::intmax_t{posVal}, T::Scalar::bits);
784 break;
785 }
786 }
787 }
788 return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
789 ScalarFunc<T, T, Int4>(
790 [&](const Scalar<T> &i, const Scalar<Int4> &pos) -> Scalar<T> {
791 return std::invoke(fptr, i, static_cast<int>(pos.ToInt64()));
792 }));
793 } else if (name == "ibits") {
794 const auto *posCon{Folder<Int4>(context).Folding(args[1])};
795 const auto *lenCon{Folder<Int4>(context).Folding(args[2])};
796 if (const auto *argCon{Folder<T>(context).Folding(args[0])};
797 argCon && argCon->empty()) {
798 } else {
799 std::size_t posCt{posCon ? posCon->size() : 0};
800 std::size_t lenCt{lenCon ? lenCon->size() : 0};
801 std::size_t n{std::max(posCt, lenCt)};
802 for (std::size_t j{0}; j < n; ++j) {
803 int posVal{j < posCt || posCt == 1
804 ? static_cast<int>(posCon->values()[j % posCt].ToInt64())
805 : 0};
806 int lenVal{j < lenCt || lenCt == 1
807 ? static_cast<int>(lenCon->values()[j % lenCt].ToInt64())
808 : 0};
809 if (posVal < 0) {
810 context.messages().Say(
811 "bit position for IBITS(POS=%jd) is negative"_err_en_US,
812 std::intmax_t{posVal});
813 break;
814 } else if (lenVal < 0) {
815 context.messages().Say(
816 "bit length for IBITS(LEN=%jd) is negative"_err_en_US,
817 std::intmax_t{lenVal});
818 break;
819 } else if (posVal + lenVal > T::Scalar::bits) {
820 context.messages().Say(
821 "IBITS() must have POS+LEN (>=%jd) no greater than %d"_err_en_US,
822 std::intmax_t{posVal + lenVal}, T::Scalar::bits);
823 break;
824 }
825 }
826 }
827 return FoldElementalIntrinsic<T, T, Int4, Int4>(context, std::move(funcRef),
828 ScalarFunc<T, T, Int4, Int4>(
829 [&](const Scalar<T> &i, const Scalar<Int4> &pos,
830 const Scalar<Int4> &len) -> Scalar<T> {
831 return i.IBITS(static_cast<int>(pos.ToInt64()),
832 static_cast<int>(len.ToInt64()));
833 }));
834 } else if (name == "index" || name == "scan" || name == "verify") {
835 if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
836 return common::visit(
837 [&](const auto &kch) -> Expr<T> {
838 using TC = typename std::decay_t<decltype(kch)>::Result;
839 if (UnwrapExpr<Expr<SomeLogical>>(args[2])) { // BACK=
840 return FoldElementalIntrinsic<T, TC, TC, LogicalResult>(context,
841 std::move(funcRef),
842 ScalarFunc<T, TC, TC, LogicalResult>{
843 [&name, &FromInt64](const Scalar<TC> &str,
844 const Scalar<TC> &other,
845 const Scalar<LogicalResult> &back) {
846 return FromInt64(name == "index"
847 ? CharacterUtils<TC::kind>::INDEX(
848 str, other, back.IsTrue())
849 : name == "scan"
850 ? CharacterUtils<TC::kind>::SCAN(
851 str, other, back.IsTrue())
852 : CharacterUtils<TC::kind>::VERIFY(
853 str, other, back.IsTrue()));
854 }});
855 } else {
856 return FoldElementalIntrinsic<T, TC, TC>(context,
857 std::move(funcRef),
858 ScalarFunc<T, TC, TC>{
859 [&name, &FromInt64](
860 const Scalar<TC> &str, const Scalar<TC> &other) {
861 return FromInt64(name == "index"
862 ? CharacterUtils<TC::kind>::INDEX(str, other)
863 : name == "scan"
864 ? CharacterUtils<TC::kind>::SCAN(str, other)
865 : CharacterUtils<TC::kind>::VERIFY(str, other));
866 }});
867 }
868 },
869 charExpr->u);
870 } else {
871 DIE("first argument must be CHARACTER");
872 }
873 } else if (name == "int") {
874 if (auto *expr{UnwrapExpr<Expr<SomeType>>(args[0])}) {
875 return common::visit(
876 [&](auto &&x) -> Expr<T> {
877 using From = std::decay_t<decltype(x)>;
878 if constexpr (std::is_same_v<From, BOZLiteralConstant> ||
879 IsNumericCategoryExpr<From>()) {
880 return Fold(context, ConvertToType<T>(std::move(x)));
881 }
882 DIE("int() argument type not valid");
883 },
884 std::move(expr->u));
885 }
886 } else if (name == "int_ptr_kind") {
887 return Expr<T>{8};
888 } else if (name == "kind") {
889 // FoldOperation(FunctionRef &&) in fold-implementation.h will not
890 // have folded the argument; in the case of TypeParamInquiry,
891 // try to get the type of the parameter itself.
892 if (const auto *expr{args[0] ? args[0]->UnwrapExpr() : nullptr}) {
893 if (const auto *inquiry{UnwrapExpr<TypeParamInquiry>(*expr)}) {
894 if (const auto *typeSpec{inquiry->parameter().GetType()}) {
895 if (const auto *intrinType{typeSpec->AsIntrinsic()}) {
896 if (auto k{ToInt64(Fold(
897 context, Expr<SubscriptInteger>{intrinType->kind()}))}) {
898 return Expr<T>{*k};
899 }
900 }
901 }
902 } else if (auto dyType{expr->GetType()}) {
903 return Expr<T>{dyType->kind()};
904 }
905 }
906 } else if (name == "iparity") {
907 return FoldBitReduction(
908 context, std::move(funcRef), &Scalar<T>::IEOR, Scalar<T>{});
909 } else if (name == "ishft" || name == "ishftc") {
910 const auto *argCon{Folder<T>(context).Folding(args[0])};
911 const auto *shiftCon{Folder<Int4>(context).Folding(args[1])};
912 const auto *shiftVals{shiftCon ? &shiftCon->values() : nullptr};
913 const auto *sizeCon{
914 args.size() == 3 ? Folder<Int4>(context).Folding(args[2]) : nullptr};
915 const auto *sizeVals{sizeCon ? &sizeCon->values() : nullptr};
916 if ((argCon && argCon->empty()) || !shiftVals || shiftVals->empty() ||
917 (sizeVals && sizeVals->empty())) {
918 // size= and shift= values don't need to be checked
919 } else {
920 for (const auto &scalar : *shiftVals) {
921 std::int64_t shiftVal{scalar.ToInt64()};
922 if (shiftVal < -T::Scalar::bits) {
923 context.messages().Say(
924 "SHIFT=%jd count for %s is less than %d"_err_en_US,
925 std::intmax_t{shiftVal}, name, -T::Scalar::bits);
926 break;
927 } else if (shiftVal > T::Scalar::bits) {
928 context.messages().Say(
929 "SHIFT=%jd count for %s is greater than %d"_err_en_US,
930 std::intmax_t{shiftVal}, name, T::Scalar::bits);
931 break;
932 }
933 }
934 if (sizeVals) {
935 for (const auto &scalar : *sizeVals) {
936 std::int64_t sizeVal{scalar.ToInt64()};
937 if (sizeVal <= 0) {
938 context.messages().Say(
939 "SIZE=%jd count for ishftc is not positive"_err_en_US,
940 std::intmax_t{sizeVal}, name);
941 break;
942 } else if (sizeVal > T::Scalar::bits) {
943 context.messages().Say(
944 "SIZE=%jd count for ishftc is greater than %d"_err_en_US,
945 std::intmax_t{sizeVal}, T::Scalar::bits);
946 break;
947 }
948 }
949 if (shiftVals->size() == 1 || sizeVals->size() == 1 ||
950 shiftVals->size() == sizeVals->size()) {
951 auto iters{std::max(shiftVals->size(), sizeVals->size())};
952 for (std::size_t j{0}; j < iters; ++j) {
953 auto shiftVal{static_cast<int>(
954 (*shiftVals)[j % shiftVals->size()].ToInt64())};
955 auto sizeVal{
956 static_cast<int>((*sizeVals)[j % sizeVals->size()].ToInt64())};
957 if (sizeVal > 0 && std::abs(shiftVal) > sizeVal) {
958 context.messages().Say(
959 "SHIFT=%jd count for ishftc is greater in magnitude than SIZE=%jd"_err_en_US,
960 std::intmax_t{shiftVal}, std::intmax_t{sizeVal});
961 break;
962 }
963 }
964 }
965 }
966 }
967 if (name == "ishft") {
968 return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
969 ScalarFunc<T, T, Int4>(
970 [&](const Scalar<T> &i, const Scalar<Int4> &shift) -> Scalar<T> {
971 return i.ISHFT(static_cast<int>(shift.ToInt64()));
972 }));
973 } else if (!args.at(2)) { // ISHFTC(no SIZE=)
974 return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
975 ScalarFunc<T, T, Int4>(
976 [&](const Scalar<T> &i, const Scalar<Int4> &shift) -> Scalar<T> {
977 return i.ISHFTC(static_cast<int>(shift.ToInt64()));
978 }));
979 } else { // ISHFTC(with SIZE=)
980 return FoldElementalIntrinsic<T, T, Int4, Int4>(context,
981 std::move(funcRef),
982 ScalarFunc<T, T, Int4, Int4>(
983 [&](const Scalar<T> &i, const Scalar<Int4> &shift,
984 const Scalar<Int4> &size) -> Scalar<T> {
985 auto shiftVal{static_cast<int>(shift.ToInt64())};
986 auto sizeVal{static_cast<int>(size.ToInt64())};
987 return i.ISHFTC(shiftVal, sizeVal);
988 }));
989 }
990 } else if (name == "izext" || name == "jzext") {
991 if (args.size() == 1) {
992 if (auto *expr{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
993 // Rewrite to IAND(INT(n,k),255_k) for k=KIND(T)
994 intrinsic->name = "iand";
995 auto converted{ConvertToType<T>(std::move(*expr))};
996 *expr = Fold(context, Expr<SomeInteger>{std::move(converted)});
997 args.emplace_back(AsGenericExpr(Expr<T>{Scalar<T>{255}}));
998 return FoldIntrinsicFunction(context, std::move(funcRef));
999 }
1000 }
1001 } else if (name == "lbound") {
1002 return LBOUND(context, std::move(funcRef));
1003 } else if (name == "leadz" || name == "trailz" || name == "poppar" ||
1004 name == "popcnt") {
1005 if (auto *sn{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
1006 return common::visit(
1007 [&funcRef, &context, &name](const auto &n) -> Expr<T> {
1008 using TI = typename std::decay_t<decltype(n)>::Result;
1009 if (name == "poppar") {
1010 return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
1011 ScalarFunc<T, TI>([](const Scalar<TI> &i) -> Scalar<T> {
1012 return Scalar<T>{i.POPPAR() ? 1 : 0};
1013 }));
1014 }
1015 auto fptr{&Scalar<TI>::LEADZ};
1016 if (name == "leadz") { // done in fptr definition
1017 } else if (name == "trailz") {
1018 fptr = &Scalar<TI>::TRAILZ;
1019 } else if (name == "popcnt") {
1020 fptr = &Scalar<TI>::POPCNT;
1021 } else {
1022 common::die(
1023 "missing case to fold intrinsic function %s", name.c_str());
1024 }
1025 return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
1026 // `i` should be declared as `const Scalar<TI>&`.
1027 // We declare it as `auto` to workaround an msvc bug:
1028 // https://developercommunity.visualstudio.com/t/Regression:-nested-closure-assumes-wrong/10130223
1029 ScalarFunc<T, TI>([&fptr](const auto &i) -> Scalar<T> {
1030 return Scalar<T>{std::invoke(fptr, i)};
1031 }));
1032 },
1033 sn->u);
1034 } else {
1035 DIE("leadz argument must be integer");
1036 }
1037 } else if (name == "len") {
1038 if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
1039 return common::visit(
1040 [&](auto &kx) {
1041 if (auto len{kx.LEN()}) {
1042 if (IsScopeInvariantExpr(*len)) {
1043 return Fold(context, ConvertToType<T>(*std::move(len)));
1044 } else {
1045 return Expr<T>{std::move(funcRef)};
1046 }
1047 } else {
1048 return Expr<T>{std::move(funcRef)};
1049 }
1050 },
1051 charExpr->u);
1052 } else {
1053 DIE("len() argument must be of character type");
1054 }
1055 } else if (name == "len_trim") {
1056 if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
1057 return common::visit(
1058 [&](const auto &kch) -> Expr<T> {
1059 using TC = typename std::decay_t<decltype(kch)>::Result;
1060 return FoldElementalIntrinsic<T, TC>(context, std::move(funcRef),
1061 ScalarFunc<T, TC>{[&FromInt64](const Scalar<TC> &str) {
1062 return FromInt64(CharacterUtils<TC::kind>::LEN_TRIM(str));
1063 }});
1064 },
1065 charExpr->u);
1066 } else {
1067 DIE("len_trim() argument must be of character type");
1068 }
1069 } else if (name == "maskl" || name == "maskr") {
1070 // Argument can be of any kind but value has to be smaller than BIT_SIZE.
1071 // It can be safely converted to Int4 to simplify.
1072 const auto fptr{name == "maskl" ? &Scalar<T>::MASKL : &Scalar<T>::MASKR};
1073 return FoldElementalIntrinsic<T, Int4>(context, std::move(funcRef),
1074 ScalarFunc<T, Int4>([&fptr](const Scalar<Int4> &places) -> Scalar<T> {
1075 return fptr(static_cast<int>(places.ToInt64()));
1076 }));
1077 } else if (name == "matmul") {
1078 return FoldMatmul(context, std::move(funcRef));
1079 } else if (name == "max") {
1080 return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
1081 } else if (name == "max0" || name == "max1") {
1082 return RewriteSpecificMINorMAX(context, std::move(funcRef));
1083 } else if (name == "maxexponent") {
1084 if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
1085 return common::visit(
1086 [](const auto &x) {
1087 using TR = typename std::decay_t<decltype(x)>::Result;
1088 return Expr<T>{Scalar<TR>::MAXEXPONENT};
1089 },
1090 sx->u);
1091 }
1092 } else if (name == "maxloc") {
1093 return FoldLocation<WhichLocation::Maxloc, T>(context, std::move(funcRef));
1094 } else if (name == "maxval") {
1095 return FoldMaxvalMinval<T>(context, std::move(funcRef),
1096 RelationalOperator::GT, T::Scalar::Least());
1097 } else if (name == "merge_bits") {
1098 return FoldElementalIntrinsic<T, T, T, T>(
1099 context, std::move(funcRef), &Scalar<T>::MERGE_BITS);
1100 } else if (name == "min") {
1101 return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
1102 } else if (name == "min0" || name == "min1") {
1103 return RewriteSpecificMINorMAX(context, std::move(funcRef));
1104 } else if (name == "minexponent") {
1105 if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
1106 return common::visit(
1107 [](const auto &x) {
1108 using TR = typename std::decay_t<decltype(x)>::Result;
1109 return Expr<T>{Scalar<TR>::MINEXPONENT};
1110 },
1111 sx->u);
1112 }
1113 } else if (name == "minloc") {
1114 return FoldLocation<WhichLocation::Minloc, T>(context, std::move(funcRef));
1115 } else if (name == "minval") {
1116 return FoldMaxvalMinval<T>(
1117 context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE());
1118 } else if (name == "mod") {
1119 bool badPConst{false};
1120 if (auto *pExpr{UnwrapExpr<Expr<T>>(args[1])}) {
1121 *pExpr = Fold(context, std::move(*pExpr));
1122 if (auto pConst{GetScalarConstantValue<T>(*pExpr)}; pConst &&
1123 pConst->IsZero() &&
1124 context.languageFeatures().ShouldWarn(
1125 common::UsageWarning::FoldingAvoidsRuntimeCrash)) {
1126 context.messages().Say("MOD: P argument is zero"_warn_en_US);
1127 badPConst = true;
1128 }
1129 }
1130 return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
1131 ScalarFuncWithContext<T, T, T>(
1132 [badPConst](FoldingContext &context, const Scalar<T> &x,
1133 const Scalar<T> &y) -> Scalar<T> {
1134 auto quotRem{x.DivideSigned(y)};
1135 if (context.languageFeatures().ShouldWarn(
1136 common::UsageWarning::FoldingAvoidsRuntimeCrash)) {
1137 if (!badPConst && quotRem.divisionByZero) {
1138 context.messages().Say("mod() by zero"_warn_en_US);
1139 } else if (quotRem.overflow) {
1140 context.messages().Say("mod() folding overflowed"_warn_en_US);
1141 }
1142 }
1143 return quotRem.remainder;
1144 }));
1145 } else if (name == "modulo") {
1146 bool badPConst{false};
1147 if (auto *pExpr{UnwrapExpr<Expr<T>>(args[1])}) {
1148 *pExpr = Fold(context, std::move(*pExpr));
1149 if (auto pConst{GetScalarConstantValue<T>(*pExpr)}; pConst &&
1150 pConst->IsZero() &&
1151 context.languageFeatures().ShouldWarn(
1152 common::UsageWarning::FoldingAvoidsRuntimeCrash)) {
1153 context.messages().Say("MODULO: P argument is zero"_warn_en_US);
1154 badPConst = true;
1155 }
1156 }
1157 return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
1158 ScalarFuncWithContext<T, T, T>([badPConst](FoldingContext &context,
1159 const Scalar<T> &x,
1160 const Scalar<T> &y) -> Scalar<T> {
1161 auto result{x.MODULO(y)};
1162 if (!badPConst && result.overflow &&
1163 context.languageFeatures().ShouldWarn(
1164 common::UsageWarning::FoldingException)) {
1165 context.messages().Say("modulo() folding overflowed"_warn_en_US);
1166 }
1167 return result.value;
1168 }));
1169 } else if (name == "not") {
1170 return FoldElementalIntrinsic<T, T>(
1171 context, std::move(funcRef), &Scalar<T>::NOT);
1172 } else if (name == "precision") {
1173 if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
1174 return Expr<T>{common::visit(
1175 [](const auto &kx) {
1176 return Scalar<ResultType<decltype(kx)>>::PRECISION;
1177 },
1178 cx->u)};
1179 } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
1180 return Expr<T>{common::visit(
1181 [](const auto &kx) {
1182 return Scalar<typename ResultType<decltype(kx)>::Part>::PRECISION;
1183 },
1184 cx->u)};
1185 }
1186 } else if (name == "product") {
1187 return FoldProduct<T>(context, std::move(funcRef), Scalar<T>{1});
1188 } else if (name == "radix") {
1189 return Expr<T>{2};
1190 } else if (name == "range") {
1191 if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
1192 return Expr<T>{common::visit(
1193 [](const auto &kx) {
1194 return Scalar<ResultType<decltype(kx)>>::RANGE;
1195 },
1196 cx->u)};
1197 } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
1198 return Expr<T>{common::visit(
1199 [](const auto &kx) {
1200 return Scalar<ResultType<decltype(kx)>>::RANGE;
1201 },
1202 cx->u)};
1203 } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
1204 return Expr<T>{common::visit(
1205 [](const auto &kx) {
1206 return Scalar<typename ResultType<decltype(kx)>::Part>::RANGE;
1207 },
1208 cx->u)};
1209 }
1210 } else if (name == "rank") {
1211 if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
1212 if (auto named{ExtractNamedEntity(*array)}) {
1213 const Symbol &symbol{named->GetLastSymbol()};
1214 if (IsAssumedRank(symbol)) {
1215 // DescriptorInquiry can only be placed in expression of kind
1216 // DescriptorInquiry::Result::kind.
1217 return ConvertToType<T>(Expr<
1218 Type<TypeCategory::Integer, DescriptorInquiry::Result::kind>>{
1219 DescriptorInquiry{*named, DescriptorInquiry::Field::Rank}});
1220 }
1221 }
1222 return Expr<T>{args[0].value().Rank()};
1223 }
1224 return Expr<T>{args[0].value().Rank()};
1225 } else if (name == "selected_char_kind") {
1226 if (const auto *chCon{UnwrapExpr<Constant<TypeOf<std::string>>>(args[0])}) {
1227 if (std::optional<std::string> value{chCon->GetScalarValue()}) {
1228 int defaultKind{
1229 context.defaults().GetDefaultKind(TypeCategory::Character)};
1230 return Expr<T>{SelectedCharKind(*value, defaultKind)};
1231 }
1232 }
1233 } else if (name == "selected_int_kind") {
1234 if (auto p{ToInt64(args[0])}) {
1235 return Expr<T>{context.targetCharacteristics().SelectedIntKind(*p)};
1236 }
1237 } else if (name == "selected_logical_kind") {
1238 if (auto p{ToInt64(args[0])}) {
1239 return Expr<T>{context.targetCharacteristics().SelectedLogicalKind(*p)};
1240 }
1241 } else if (name == "selected_real_kind" ||
1242 name == "__builtin_ieee_selected_real_kind") {
1243 if (auto p{GetInt64ArgOr(args[0], 0)}) {
1244 if (auto r{GetInt64ArgOr(args[1], 0)}) {
1245 if (auto radix{GetInt64ArgOr(args[2], 2)}) {
1246 return Expr<T>{
1247 context.targetCharacteristics().SelectedRealKind(*p, *r, *radix)};
1248 }
1249 }
1250 }
1251 } else if (name == "shape") {
1252 if (auto shape{GetContextFreeShape(context, args[0])}) {
1253 if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
1254 return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
1255 }
1256 }
1257 } else if (name == "shifta" || name == "shiftr" || name == "shiftl") {
1258 // Second argument can be of any kind. However, it must be smaller or
1259 // equal than BIT_SIZE. It can be converted to Int4 to simplify.
1260 auto fptr{&Scalar<T>::SHIFTA};
1261 if (name == "shifta") { // done in fptr definition
1262 } else if (name == "shiftr") {
1263 fptr = &Scalar<T>::SHIFTR;
1264 } else if (name == "shiftl") {
1265 fptr = &Scalar<T>::SHIFTL;
1266 } else {
1267 common::die("missing case to fold intrinsic function %s", name.c_str());
1268 }
1269 if (const auto *argCon{Folder<T>(context).Folding(args[0])};
1270 argCon && argCon->empty()) {
1271 } else if (const auto *shiftCon{Folder<Int4>(context).Folding(args[1])}) {
1272 for (const auto &scalar : shiftCon->values()) {
1273 std::int64_t shiftVal{scalar.ToInt64()};
1274 if (shiftVal < 0) {
1275 context.messages().Say("SHIFT=%jd count for %s is negative"_err_en_US,
1276 std::intmax_t{shiftVal}, name, -T::Scalar::bits);
1277 break;
1278 } else if (shiftVal > T::Scalar::bits) {
1279 context.messages().Say(
1280 "SHIFT=%jd count for %s is greater than %d"_err_en_US,
1281 std::intmax_t{shiftVal}, name, T::Scalar::bits);
1282 break;
1283 }
1284 }
1285 }
1286 return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
1287 ScalarFunc<T, T, Int4>(
1288 [&](const Scalar<T> &i, const Scalar<Int4> &shift) -> Scalar<T> {
1289 return std::invoke(fptr, i, static_cast<int>(shift.ToInt64()));
1290 }));
1291 } else if (name == "sign") {
1292 return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
1293 ScalarFunc<T, T, T>([&context](const Scalar<T> &j,
1294 const Scalar<T> &k) -> Scalar<T> {
1295 typename Scalar<T>::ValueWithOverflow result{j.SIGN(k)};
1296 if (result.overflow &&
1297 context.languageFeatures().ShouldWarn(
1298 common::UsageWarning::FoldingException)) {
1299 context.messages().Say(
1300 "sign(integer(kind=%d)) folding overflowed"_warn_en_US, KIND);
1301 }
1302 return result.value;
1303 }));
1304 } else if (name == "size") {
1305 if (auto shape{GetContextFreeShape(context, args[0])}) {
1306 if (args[1]) { // DIM= is present, get one extent
1307 std::optional<int> dim;
1308 if (const auto *array{args[0].value().UnwrapExpr()}; array &&
1309 !CheckDimArg(args[1], *array, context.messages(), false, dim)) {
1310 return MakeInvalidIntrinsic<T>(std::move(funcRef));
1311 } else if (dim) {
1312 if (auto &extent{shape->at(*dim)}) {
1313 return Fold(context, ConvertToType<T>(std::move(*extent)));
1314 }
1315 }
1316 } else if (auto extents{common::AllElementsPresent(std::move(*shape))}) {
1317 // DIM= is absent; compute PRODUCT(SHAPE())
1318 ExtentExpr product{1};
1319 for (auto &&extent : std::move(*extents)) {
1320 product = std::move(product) * std::move(extent);
1321 }
1322 return Expr<T>{ConvertToType<T>(Fold(context, std::move(product)))};
1323 }
1324 }
1325 } else if (name == "sizeof") { // in bytes; extension
1326 if (auto info{
1327 characteristics::TypeAndShape::Characterize(args[0], context)}) {
1328 if (auto bytes{info->MeasureSizeInBytes(context)}) {
1329 return Expr<T>{Fold(context, ConvertToType<T>(std::move(*bytes)))};
1330 }
1331 }
1332 } else if (name == "storage_size") { // in bits
1333 if (auto info{
1334 characteristics::TypeAndShape::Characterize(args[0], context)}) {
1335 if (auto bytes{info->MeasureElementSizeInBytes(context, true)}) {
1336 return Expr<T>{
1337 Fold(context, Expr<T>{8} * ConvertToType<T>(std::move(*bytes)))};
1338 }
1339 }
1340 } else if (name == "sum") {
1341 return FoldSum<T>(context, std::move(funcRef));
1342 } else if (name == "ubound") {
1343 return UBOUND(context, std::move(funcRef));
1344 } else if (name == "__builtin_numeric_storage_size") {
1345 if (!context.moduleFileName()) {
1346 // Don't fold this reference until it appears in the module file
1347 // for ISO_FORTRAN_ENV -- the value depends on the compiler options
1348 // that might be in force.
1349 } else {
1350 auto intBytes{
1351 context.targetCharacteristics().GetByteSize(TypeCategory::Integer,
1352 context.defaults().GetDefaultKind(TypeCategory::Integer))};
1353 auto realBytes{
1354 context.targetCharacteristics().GetByteSize(TypeCategory::Real,
1355 context.defaults().GetDefaultKind(TypeCategory::Real))};
1356 if (intBytes != realBytes &&
1357 context.languageFeatures().ShouldWarn(
1358 common::UsageWarning::FoldingValueChecks)) {
1359 context.messages().Say(*context.moduleFileName(),
1360 "NUMERIC_STORAGE_SIZE from ISO_FORTRAN_ENV is not well-defined when default INTEGER and REAL are not consistent due to compiler options"_warn_en_US);
1361 }
1362 return Expr<T>{8 * std::min(intBytes, realBytes)};
1363 }
1364 }
1365 return Expr<T>{std::move(funcRef)};
1366 }
1367
1368 // Substitutes a bare type parameter reference with its value if it has one now
1369 // in an instantiation. Bare LEN type parameters are substituted only when
1370 // the known value is constant.
1371 Expr<TypeParamInquiry::Result> FoldOperation(
1372 FoldingContext &context, TypeParamInquiry &&inquiry) {
1373 std::optional<NamedEntity> base{inquiry.base()};
1374 parser::CharBlock parameterName{inquiry.parameter().name()};
1375 if (base) {
1376 // Handling "designator%typeParam". Get the value of the type parameter
1377 // from the instantiation of the base
1378 if (const semantics::DeclTypeSpec *
1379 declType{base->GetLastSymbol().GetType()}) {
1380 if (const semantics::ParamValue *
1381 paramValue{
1382 declType->derivedTypeSpec().FindParameter(parameterName)}) {
1383 const semantics::MaybeIntExpr &paramExpr{paramValue->GetExplicit()};
1384 if (paramExpr && IsConstantExpr(*paramExpr)) {
1385 Expr<SomeInteger> intExpr{*paramExpr};
1386 return Fold(context,
1387 ConvertToType<TypeParamInquiry::Result>(std::move(intExpr)));
1388 }
1389 }
1390 }
1391 } else {
1392 // A "bare" type parameter: replace with its value, if that's now known
1393 // in a current derived type instantiation.
1394 if (const auto *pdt{context.pdtInstance()}) {
1395 auto restorer{context.WithoutPDTInstance()}; // don't loop
1396 bool isLen{false};
1397 if (const semantics::Scope * scope{pdt->scope()}) {
1398 auto iter{scope->find(parameterName)};
1399 if (iter != scope->end()) {
1400 const Symbol &symbol{*iter->second};
1401 const auto *details{symbol.detailsIf<semantics::TypeParamDetails>()};
1402 if (details) {
1403 isLen = details->attr() == common::TypeParamAttr::Len;
1404 const semantics::MaybeIntExpr &initExpr{details->init()};
1405 if (initExpr && IsConstantExpr(*initExpr) &&
1406 (!isLen || ToInt64(*initExpr))) {
1407 Expr<SomeInteger> expr{*initExpr};
1408 return Fold(context,
1409 ConvertToType<TypeParamInquiry::Result>(std::move(expr)));
1410 }
1411 }
1412 }
1413 }
1414 if (const auto *value{pdt->FindParameter(parameterName)}) {
1415 if (value->isExplicit()) {
1416 auto folded{Fold(context,
1417 AsExpr(ConvertToType<TypeParamInquiry::Result>(
1418 Expr<SomeInteger>{value->GetExplicit().value()})))};
1419 if (!isLen || ToInt64(folded)) {
1420 return folded;
1421 }
1422 }
1423 }
1424 }
1425 }
1426 return AsExpr(std::move(inquiry));
1427 }
1428
1429 std::optional<std::int64_t> ToInt64(const Expr<SomeInteger> &expr) {
1430 return common::visit(
1431 [](const auto &kindExpr) { return ToInt64(kindExpr); }, expr.u);
1432 }
1433
1434 std::optional<std::int64_t> ToInt64(const Expr<SomeType> &expr) {
1435 return ToInt64(UnwrapExpr<Expr<SomeInteger>>(expr));
1436 }
1437
1438 std::optional<std::int64_t> ToInt64(const ActualArgument &arg) {
1439 return ToInt64(arg.UnwrapExpr());
1440 }
1441
1442 #ifdef _MSC_VER // disable bogus warning about missing definitions
1443 #pragma warning(disable : 4661)
1444 #endif
1445 FOR_EACH_INTEGER_KIND(template class ExpressionBase, )
1446 template class ExpressionBase<SomeInteger>;
1447 } // namespace Fortran::evaluate