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 == "index" || name == "scan" || name == "verify") { 566 if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) { 567 return std::visit( 568 [&](const auto &kch) -> Expr<T> { 569 using TC = typename std::decay_t<decltype(kch)>::Result; 570 if (UnwrapExpr<Expr<SomeLogical>>(args[2])) { // BACK= 571 return FoldElementalIntrinsic<T, TC, TC, LogicalResult>(context, 572 std::move(funcRef), 573 ScalarFunc<T, TC, TC, LogicalResult>{ 574 [&name](const Scalar<TC> &str, const Scalar<TC> &other, 575 const Scalar<LogicalResult> &back) -> Scalar<T> { 576 return name == "index" 577 ? CharacterUtils<TC::kind>::INDEX( 578 str, other, back.IsTrue()) 579 : name == "scan" ? CharacterUtils<TC::kind>::SCAN( 580 str, other, back.IsTrue()) 581 : CharacterUtils<TC::kind>::VERIFY( 582 str, other, back.IsTrue()); 583 }}); 584 } else { 585 return FoldElementalIntrinsic<T, TC, TC>(context, 586 std::move(funcRef), 587 ScalarFunc<T, TC, TC>{ 588 [&name](const Scalar<TC> &str, 589 const Scalar<TC> &other) -> Scalar<T> { 590 return name == "index" 591 ? CharacterUtils<TC::kind>::INDEX(str, other) 592 : name == "scan" 593 ? CharacterUtils<TC::kind>::SCAN(str, other) 594 : CharacterUtils<TC::kind>::VERIFY(str, other); 595 }}); 596 } 597 }, 598 charExpr->u); 599 } else { 600 DIE("first argument must be CHARACTER"); 601 } 602 } else if (name == "int") { 603 if (auto *expr{UnwrapExpr<Expr<SomeType>>(args[0])}) { 604 return std::visit( 605 [&](auto &&x) -> Expr<T> { 606 using From = std::decay_t<decltype(x)>; 607 if constexpr (std::is_same_v<From, BOZLiteralConstant> || 608 IsNumericCategoryExpr<From>()) { 609 return Fold(context, ConvertToType<T>(std::move(x))); 610 } 611 DIE("int() argument type not valid"); 612 }, 613 std::move(expr->u)); 614 } 615 } else if (name == "int_ptr_kind") { 616 return Expr<T>{8}; 617 } else if (name == "kind") { 618 if constexpr (common::HasMember<T, IntegerTypes>) { 619 return Expr<T>{args[0].value().GetType()->kind()}; 620 } else { 621 DIE("kind() result not integral"); 622 } 623 } else if (name == "iparity") { 624 return FoldBitReduction( 625 context, std::move(funcRef), &Scalar<T>::IEOR, Scalar<T>{}); 626 } else if (name == "ishft") { 627 return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef), 628 ScalarFunc<T, T, Int4>([&](const Scalar<T> &i, 629 const Scalar<Int4> &pos) -> Scalar<T> { 630 auto posVal{static_cast<int>(pos.ToInt64())}; 631 if (posVal < -i.bits) { 632 context.messages().Say( 633 "SHIFT=%d count for ishft is less than %d"_err_en_US, posVal, 634 -i.bits); 635 } else if (posVal > i.bits) { 636 context.messages().Say( 637 "SHIFT=%d count for ishft is greater than %d"_err_en_US, posVal, 638 i.bits); 639 } 640 return i.ISHFT(posVal); 641 })); 642 } else if (name == "lbound") { 643 return LBOUND(context, std::move(funcRef)); 644 } else if (name == "leadz" || name == "trailz" || name == "poppar" || 645 name == "popcnt") { 646 if (auto *sn{UnwrapExpr<Expr<SomeInteger>>(args[0])}) { 647 return std::visit( 648 [&funcRef, &context, &name](const auto &n) -> Expr<T> { 649 using TI = typename std::decay_t<decltype(n)>::Result; 650 if (name == "poppar") { 651 return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef), 652 ScalarFunc<T, TI>([](const Scalar<TI> &i) -> Scalar<T> { 653 return Scalar<T>{i.POPPAR() ? 1 : 0}; 654 })); 655 } 656 auto fptr{&Scalar<TI>::LEADZ}; 657 if (name == "leadz") { // done in fptr definition 658 } else if (name == "trailz") { 659 fptr = &Scalar<TI>::TRAILZ; 660 } else if (name == "popcnt") { 661 fptr = &Scalar<TI>::POPCNT; 662 } else { 663 common::die( 664 "missing case to fold intrinsic function %s", name.c_str()); 665 } 666 return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef), 667 ScalarFunc<T, TI>([&fptr](const Scalar<TI> &i) -> Scalar<T> { 668 return Scalar<T>{std::invoke(fptr, i)}; 669 })); 670 }, 671 sn->u); 672 } else { 673 DIE("leadz argument must be integer"); 674 } 675 } else if (name == "len") { 676 if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) { 677 return std::visit( 678 [&](auto &kx) { 679 if (auto len{kx.LEN()}) { 680 if (IsScopeInvariantExpr(*len)) { 681 return Fold(context, ConvertToType<T>(*std::move(len))); 682 } else { 683 return Expr<T>{std::move(funcRef)}; 684 } 685 } else { 686 return Expr<T>{std::move(funcRef)}; 687 } 688 }, 689 charExpr->u); 690 } else { 691 DIE("len() argument must be of character type"); 692 } 693 } else if (name == "len_trim") { 694 if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) { 695 return std::visit( 696 [&](const auto &kch) -> Expr<T> { 697 using TC = typename std::decay_t<decltype(kch)>::Result; 698 return FoldElementalIntrinsic<T, TC>(context, std::move(funcRef), 699 ScalarFunc<T, TC>{[](const Scalar<TC> &str) -> Scalar<T> { 700 return CharacterUtils<TC::kind>::LEN_TRIM(str); 701 }}); 702 }, 703 charExpr->u); 704 } else { 705 DIE("len_trim() argument must be of character type"); 706 } 707 } else if (name == "maskl" || name == "maskr") { 708 // Argument can be of any kind but value has to be smaller than BIT_SIZE. 709 // It can be safely converted to Int4 to simplify. 710 const auto fptr{name == "maskl" ? &Scalar<T>::MASKL : &Scalar<T>::MASKR}; 711 return FoldElementalIntrinsic<T, Int4>(context, std::move(funcRef), 712 ScalarFunc<T, Int4>([&fptr](const Scalar<Int4> &places) -> Scalar<T> { 713 return fptr(static_cast<int>(places.ToInt64())); 714 })); 715 } else if (name == "max") { 716 return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater); 717 } else if (name == "max0" || name == "max1") { 718 return RewriteSpecificMINorMAX(context, std::move(funcRef)); 719 } else if (name == "maxexponent") { 720 if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) { 721 return std::visit( 722 [](const auto &x) { 723 using TR = typename std::decay_t<decltype(x)>::Result; 724 return Expr<T>{Scalar<TR>::MAXEXPONENT}; 725 }, 726 sx->u); 727 } 728 } else if (name == "maxloc") { 729 return FoldLocation<WhichLocation::Maxloc, T>(context, std::move(funcRef)); 730 } else if (name == "maxval") { 731 return FoldMaxvalMinval<T>(context, std::move(funcRef), 732 RelationalOperator::GT, T::Scalar::Least()); 733 } else if (name == "merge") { 734 return FoldMerge<T>(context, std::move(funcRef)); 735 } else if (name == "merge_bits") { 736 return FoldElementalIntrinsic<T, T, T, T>( 737 context, std::move(funcRef), &Scalar<T>::MERGE_BITS); 738 } else if (name == "min") { 739 return FoldMINorMAX(context, std::move(funcRef), Ordering::Less); 740 } else if (name == "min0" || name == "min1") { 741 return RewriteSpecificMINorMAX(context, std::move(funcRef)); 742 } else if (name == "minexponent") { 743 if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) { 744 return std::visit( 745 [](const auto &x) { 746 using TR = typename std::decay_t<decltype(x)>::Result; 747 return Expr<T>{Scalar<TR>::MINEXPONENT}; 748 }, 749 sx->u); 750 } 751 } else if (name == "minloc") { 752 return FoldLocation<WhichLocation::Minloc, T>(context, std::move(funcRef)); 753 } else if (name == "minval") { 754 return FoldMaxvalMinval<T>( 755 context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE()); 756 } else if (name == "mod") { 757 return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef), 758 ScalarFuncWithContext<T, T, T>( 759 [](FoldingContext &context, const Scalar<T> &x, 760 const Scalar<T> &y) -> Scalar<T> { 761 auto quotRem{x.DivideSigned(y)}; 762 if (quotRem.divisionByZero) { 763 context.messages().Say("mod() by zero"_warn_en_US); 764 } else if (quotRem.overflow) { 765 context.messages().Say("mod() folding overflowed"_warn_en_US); 766 } 767 return quotRem.remainder; 768 })); 769 } else if (name == "modulo") { 770 return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef), 771 ScalarFuncWithContext<T, T, T>( 772 [](FoldingContext &context, const Scalar<T> &x, 773 const Scalar<T> &y) -> Scalar<T> { 774 auto result{x.MODULO(y)}; 775 if (result.overflow) { 776 context.messages().Say( 777 "modulo() folding overflowed"_warn_en_US); 778 } 779 return result.value; 780 })); 781 } else if (name == "not") { 782 return FoldElementalIntrinsic<T, T>( 783 context, std::move(funcRef), &Scalar<T>::NOT); 784 } else if (name == "precision") { 785 if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) { 786 return Expr<T>{std::visit( 787 [](const auto &kx) { 788 return Scalar<ResultType<decltype(kx)>>::PRECISION; 789 }, 790 cx->u)}; 791 } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) { 792 return Expr<T>{std::visit( 793 [](const auto &kx) { 794 return Scalar<typename ResultType<decltype(kx)>::Part>::PRECISION; 795 }, 796 cx->u)}; 797 } 798 } else if (name == "product") { 799 return FoldProduct<T>(context, std::move(funcRef), Scalar<T>{1}); 800 } else if (name == "radix") { 801 return Expr<T>{2}; 802 } else if (name == "range") { 803 if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) { 804 return Expr<T>{std::visit( 805 [](const auto &kx) { 806 return Scalar<ResultType<decltype(kx)>>::RANGE; 807 }, 808 cx->u)}; 809 } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) { 810 return Expr<T>{std::visit( 811 [](const auto &kx) { 812 return Scalar<ResultType<decltype(kx)>>::RANGE; 813 }, 814 cx->u)}; 815 } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) { 816 return Expr<T>{std::visit( 817 [](const auto &kx) { 818 return Scalar<typename ResultType<decltype(kx)>::Part>::RANGE; 819 }, 820 cx->u)}; 821 } 822 } else if (name == "rank") { 823 if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) { 824 if (auto named{ExtractNamedEntity(*array)}) { 825 const Symbol &symbol{named->GetLastSymbol()}; 826 if (IsAssumedRank(symbol)) { 827 // DescriptorInquiry can only be placed in expression of kind 828 // DescriptorInquiry::Result::kind. 829 return ConvertToType<T>(Expr< 830 Type<TypeCategory::Integer, DescriptorInquiry::Result::kind>>{ 831 DescriptorInquiry{*named, DescriptorInquiry::Field::Rank}}); 832 } 833 } 834 return Expr<T>{args[0].value().Rank()}; 835 } 836 return Expr<T>{args[0].value().Rank()}; 837 } else if (name == "selected_char_kind") { 838 if (const auto *chCon{UnwrapExpr<Constant<TypeOf<std::string>>>(args[0])}) { 839 if (std::optional<std::string> value{chCon->GetScalarValue()}) { 840 int defaultKind{ 841 context.defaults().GetDefaultKind(TypeCategory::Character)}; 842 return Expr<T>{SelectedCharKind(*value, defaultKind)}; 843 } 844 } 845 } else if (name == "selected_int_kind") { 846 if (auto p{GetInt64Arg(args[0])}) { 847 return Expr<T>{SelectedIntKind(*p)}; 848 } 849 } else if (name == "selected_real_kind" || 850 name == "__builtin_ieee_selected_real_kind") { 851 if (auto p{GetInt64ArgOr(args[0], 0)}) { 852 if (auto r{GetInt64ArgOr(args[1], 0)}) { 853 if (auto radix{GetInt64ArgOr(args[2], 2)}) { 854 return Expr<T>{SelectedRealKind(*p, *r, *radix)}; 855 } 856 } 857 } 858 } else if (name == "shape") { 859 if (auto shape{GetContextFreeShape(context, args[0])}) { 860 if (auto shapeExpr{AsExtentArrayExpr(*shape)}) { 861 return Fold(context, ConvertToType<T>(std::move(*shapeExpr))); 862 } 863 } 864 } else if (name == "shifta" || name == "shiftr" || name == "shiftl") { 865 // Second argument can be of any kind. However, it must be smaller or 866 // equal than BIT_SIZE. It can be converted to Int4 to simplify. 867 auto fptr{&Scalar<T>::SHIFTA}; 868 if (name == "shifta") { // done in fptr definition 869 } else if (name == "shiftr") { 870 fptr = &Scalar<T>::SHIFTR; 871 } else if (name == "shiftl") { 872 fptr = &Scalar<T>::SHIFTL; 873 } else { 874 common::die("missing case to fold intrinsic function %s", name.c_str()); 875 } 876 return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef), 877 ScalarFunc<T, T, Int4>([&](const Scalar<T> &i, 878 const Scalar<Int4> &pos) -> Scalar<T> { 879 auto posVal{static_cast<int>(pos.ToInt64())}; 880 if (posVal < 0) { 881 context.messages().Say( 882 "SHIFT=%d count for %s is negative"_err_en_US, posVal, name); 883 } else if (posVal > i.bits) { 884 context.messages().Say( 885 "SHIFT=%d count for %s is greater than %d"_err_en_US, posVal, 886 name, i.bits); 887 } 888 return std::invoke(fptr, i, posVal); 889 })); 890 } else if (name == "sign") { 891 return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef), 892 ScalarFunc<T, T, T>( 893 [&context](const Scalar<T> &j, const Scalar<T> &k) -> Scalar<T> { 894 typename Scalar<T>::ValueWithOverflow result{j.SIGN(k)}; 895 if (result.overflow) { 896 context.messages().Say( 897 "sign(integer(kind=%d)) folding overflowed"_warn_en_US, 898 KIND); 899 } 900 return result.value; 901 })); 902 } else if (name == "size") { 903 if (auto shape{GetContextFreeShape(context, args[0])}) { 904 if (auto &dimArg{args[1]}) { // DIM= is present, get one extent 905 if (auto dim{GetInt64Arg(args[1])}) { 906 int rank{GetRank(*shape)}; 907 if (*dim >= 1 && *dim <= rank) { 908 const Symbol *symbol{UnwrapWholeSymbolDataRef(args[0])}; 909 if (symbol && IsAssumedSizeArray(*symbol) && *dim == rank) { 910 context.messages().Say( 911 "size(array,dim=%jd) of last dimension is not available for rank-%d assumed-size array dummy argument"_err_en_US, 912 *dim, rank); 913 return MakeInvalidIntrinsic<T>(std::move(funcRef)); 914 } else if (auto &extent{shape->at(*dim - 1)}) { 915 return Fold(context, ConvertToType<T>(std::move(*extent))); 916 } 917 } else { 918 context.messages().Say( 919 "size(array,dim=%jd) dimension is out of range for rank-%d array"_warn_en_US, 920 *dim, rank); 921 } 922 } 923 } else if (auto extents{common::AllElementsPresent(std::move(*shape))}) { 924 // DIM= is absent; compute PRODUCT(SHAPE()) 925 ExtentExpr product{1}; 926 for (auto &&extent : std::move(*extents)) { 927 product = std::move(product) * std::move(extent); 928 } 929 return Expr<T>{ConvertToType<T>(Fold(context, std::move(product)))}; 930 } 931 } 932 } else if (name == "sizeof") { // in bytes; extension 933 if (auto info{ 934 characteristics::TypeAndShape::Characterize(args[0], context)}) { 935 if (auto bytes{info->MeasureSizeInBytes(context)}) { 936 return Expr<T>{Fold(context, ConvertToType<T>(std::move(*bytes)))}; 937 } 938 } 939 } else if (name == "storage_size") { // in bits 940 if (auto info{ 941 characteristics::TypeAndShape::Characterize(args[0], context)}) { 942 if (auto bytes{info->MeasureElementSizeInBytes(context, true)}) { 943 return Expr<T>{ 944 Fold(context, Expr<T>{8} * ConvertToType<T>(std::move(*bytes)))}; 945 } 946 } 947 } else if (name == "sum") { 948 return FoldSum<T>(context, std::move(funcRef)); 949 } else if (name == "ubound") { 950 return UBOUND(context, std::move(funcRef)); 951 } 952 // TODO: dot_product, ibits, ishftc, matmul, sign, transfer 953 return Expr<T>{std::move(funcRef)}; 954 } 955 956 // Substitutes a bare type parameter reference with its value if it has one now 957 // in an instantiation. Bare LEN type parameters are substituted only when 958 // the known value is constant. 959 Expr<TypeParamInquiry::Result> FoldOperation( 960 FoldingContext &context, TypeParamInquiry &&inquiry) { 961 std::optional<NamedEntity> base{inquiry.base()}; 962 parser::CharBlock parameterName{inquiry.parameter().name()}; 963 if (base) { 964 // Handling "designator%typeParam". Get the value of the type parameter 965 // from the instantiation of the base 966 if (const semantics::DeclTypeSpec * 967 declType{base->GetLastSymbol().GetType()}) { 968 if (const semantics::ParamValue * 969 paramValue{ 970 declType->derivedTypeSpec().FindParameter(parameterName)}) { 971 const semantics::MaybeIntExpr ¶mExpr{paramValue->GetExplicit()}; 972 if (paramExpr && IsConstantExpr(*paramExpr)) { 973 Expr<SomeInteger> intExpr{*paramExpr}; 974 return Fold(context, 975 ConvertToType<TypeParamInquiry::Result>(std::move(intExpr))); 976 } 977 } 978 } 979 } else { 980 // A "bare" type parameter: replace with its value, if that's now known 981 // in a current derived type instantiation, for KIND type parameters. 982 if (const auto *pdt{context.pdtInstance()}) { 983 bool isLen{false}; 984 if (const semantics::Scope * scope{context.pdtInstance()->scope()}) { 985 auto iter{scope->find(parameterName)}; 986 if (iter != scope->end()) { 987 const Symbol &symbol{*iter->second}; 988 const auto *details{symbol.detailsIf<semantics::TypeParamDetails>()}; 989 if (details) { 990 isLen = details->attr() == common::TypeParamAttr::Len; 991 const semantics::MaybeIntExpr &initExpr{details->init()}; 992 if (initExpr && IsConstantExpr(*initExpr) && 993 (!isLen || ToInt64(*initExpr))) { 994 Expr<SomeInteger> expr{*initExpr}; 995 return Fold(context, 996 ConvertToType<TypeParamInquiry::Result>(std::move(expr))); 997 } 998 } 999 } 1000 } 1001 if (const auto *value{pdt->FindParameter(parameterName)}) { 1002 if (value->isExplicit()) { 1003 auto folded{Fold(context, 1004 AsExpr(ConvertToType<TypeParamInquiry::Result>( 1005 Expr<SomeInteger>{value->GetExplicit().value()})))}; 1006 if (!isLen || ToInt64(folded)) { 1007 return folded; 1008 } 1009 } 1010 } 1011 } 1012 } 1013 return AsExpr(std::move(inquiry)); 1014 } 1015 1016 std::optional<std::int64_t> ToInt64(const Expr<SomeInteger> &expr) { 1017 return std::visit( 1018 [](const auto &kindExpr) { return ToInt64(kindExpr); }, expr.u); 1019 } 1020 1021 std::optional<std::int64_t> ToInt64(const Expr<SomeType> &expr) { 1022 if (const auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(expr)}) { 1023 return ToInt64(*intExpr); 1024 } else { 1025 return std::nullopt; 1026 } 1027 } 1028 1029 #ifdef _MSC_VER // disable bogus warning about missing definitions 1030 #pragma warning(disable : 4661) 1031 #endif 1032 FOR_EACH_INTEGER_KIND(template class ExpressionBase, ) 1033 template class ExpressionBase<SomeInteger>; 1034 } // namespace Fortran::evaluate 1035