1 //===-- ConvertExpr.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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/ 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "flang/Lower/ConvertExpr.h" 14 #include "flang/Common/default-kinds.h" 15 #include "flang/Common/unwrap.h" 16 #include "flang/Evaluate/fold.h" 17 #include "flang/Evaluate/real.h" 18 #include "flang/Evaluate/traverse.h" 19 #include "flang/Lower/Allocatable.h" 20 #include "flang/Lower/Bridge.h" 21 #include "flang/Lower/BuiltinModules.h" 22 #include "flang/Lower/CallInterface.h" 23 #include "flang/Lower/Coarray.h" 24 #include "flang/Lower/ComponentPath.h" 25 #include "flang/Lower/ConvertType.h" 26 #include "flang/Lower/ConvertVariable.h" 27 #include "flang/Lower/CustomIntrinsicCall.h" 28 #include "flang/Lower/DumpEvaluateExpr.h" 29 #include "flang/Lower/IntrinsicCall.h" 30 #include "flang/Lower/Mangler.h" 31 #include "flang/Lower/Runtime.h" 32 #include "flang/Lower/Support/Utils.h" 33 #include "flang/Optimizer/Builder/Character.h" 34 #include "flang/Optimizer/Builder/Complex.h" 35 #include "flang/Optimizer/Builder/Factory.h" 36 #include "flang/Optimizer/Builder/Runtime/Character.h" 37 #include "flang/Optimizer/Builder/Runtime/RTBuilder.h" 38 #include "flang/Optimizer/Builder/Runtime/Ragged.h" 39 #include "flang/Optimizer/Builder/Todo.h" 40 #include "flang/Optimizer/Dialect/FIRAttr.h" 41 #include "flang/Optimizer/Dialect/FIRDialect.h" 42 #include "flang/Optimizer/Dialect/FIROpsSupport.h" 43 #include "flang/Optimizer/Support/FatalError.h" 44 #include "flang/Semantics/expression.h" 45 #include "flang/Semantics/symbol.h" 46 #include "flang/Semantics/tools.h" 47 #include "flang/Semantics/type.h" 48 #include "mlir/Dialect/Func/IR/FuncOps.h" 49 #include "llvm/ADT/TypeSwitch.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include <algorithm> 55 56 #define DEBUG_TYPE "flang-lower-expr" 57 58 //===----------------------------------------------------------------------===// 59 // The composition and structure of Fortran::evaluate::Expr is defined in 60 // the various header files in include/flang/Evaluate. You are referred 61 // there for more information on these data structures. Generally speaking, 62 // these data structures are a strongly typed family of abstract data types 63 // that, composed as trees, describe the syntax of Fortran expressions. 64 // 65 // This part of the bridge can traverse these tree structures and lower them 66 // to the correct FIR representation in SSA form. 67 //===----------------------------------------------------------------------===// 68 69 static llvm::cl::opt<bool> generateArrayCoordinate( 70 "gen-array-coor", 71 llvm::cl::desc("in lowering create ArrayCoorOp instead of CoordinateOp"), 72 llvm::cl::init(false)); 73 74 // The default attempts to balance a modest allocation size with expected user 75 // input to minimize bounds checks and reallocations during dynamic array 76 // construction. Some user codes may have very large array constructors for 77 // which the default can be increased. 78 static llvm::cl::opt<unsigned> clInitialBufferSize( 79 "array-constructor-initial-buffer-size", 80 llvm::cl::desc( 81 "set the incremental array construction buffer size (default=32)"), 82 llvm::cl::init(32u)); 83 84 /// The various semantics of a program constituent (or a part thereof) as it may 85 /// appear in an expression. 86 /// 87 /// Given the following Fortran declarations. 88 /// ```fortran 89 /// REAL :: v1, v2, v3 90 /// REAL, POINTER :: vp1 91 /// REAL :: a1(c), a2(c) 92 /// REAL ELEMENTAL FUNCTION f1(arg) ! array -> array 93 /// FUNCTION f2(arg) ! array -> array 94 /// vp1 => v3 ! 1 95 /// v1 = v2 * vp1 ! 2 96 /// a1 = a1 + a2 ! 3 97 /// a1 = f1(a2) ! 4 98 /// a1 = f2(a2) ! 5 99 /// ``` 100 /// 101 /// In line 1, `vp1` is a BoxAddr to copy a box value into. The box value is 102 /// constructed from the DataAddr of `v3`. 103 /// In line 2, `v1` is a DataAddr to copy a value into. The value is constructed 104 /// from the DataValue of `v2` and `vp1`. DataValue is implicitly a double 105 /// dereference in the `vp1` case. 106 /// In line 3, `a1` and `a2` on the rhs are RefTransparent. The `a1` on the lhs 107 /// is CopyInCopyOut as `a1` is replaced elementally by the additions. 108 /// In line 4, `a2` can be RefTransparent, ByValueArg, RefOpaque, or BoxAddr if 109 /// `arg` is declared as C-like pass-by-value, VALUE, INTENT(?), or ALLOCATABLE/ 110 /// POINTER, respectively. `a1` on the lhs is CopyInCopyOut. 111 /// In line 5, `a2` may be DataAddr or BoxAddr assuming f2 is transformational. 112 /// `a1` on the lhs is again CopyInCopyOut. 113 enum class ConstituentSemantics { 114 // Scalar data reference semantics. 115 // 116 // For these let `v` be the location in memory of a variable with value `x` 117 DataValue, // refers to the value `x` 118 DataAddr, // refers to the address `v` 119 BoxValue, // refers to a box value containing `v` 120 BoxAddr, // refers to the address of a box value containing `v` 121 122 // Array data reference semantics. 123 // 124 // For these let `a` be the location in memory of a sequence of value `[xs]`. 125 // Let `x_i` be the `i`-th value in the sequence `[xs]`. 126 127 // Referentially transparent. Refers to the array's value, `[xs]`. 128 RefTransparent, 129 // Refers to an ephemeral address `tmp` containing value `x_i` (15.5.2.3.p7 130 // note 2). (Passing a copy by reference to simulate pass-by-value.) 131 ByValueArg, 132 // Refers to the merge of array value `[xs]` with another array value `[ys]`. 133 // This merged array value will be written into memory location `a`. 134 CopyInCopyOut, 135 // Similar to CopyInCopyOut but `a` may be a transient projection (rather than 136 // a whole array). 137 ProjectedCopyInCopyOut, 138 // Similar to ProjectedCopyInCopyOut, except the merge value is not assigned 139 // automatically by the framework. Instead, and address for `[xs]` is made 140 // accessible so that custom assignments to `[xs]` can be implemented. 141 CustomCopyInCopyOut, 142 // Referentially opaque. Refers to the address of `x_i`. 143 RefOpaque 144 }; 145 146 /// Convert parser's INTEGER relational operators to MLIR. TODO: using 147 /// unordered, but we may want to cons ordered in certain situation. 148 static mlir::arith::CmpIPredicate 149 translateRelational(Fortran::common::RelationalOperator rop) { 150 switch (rop) { 151 case Fortran::common::RelationalOperator::LT: 152 return mlir::arith::CmpIPredicate::slt; 153 case Fortran::common::RelationalOperator::LE: 154 return mlir::arith::CmpIPredicate::sle; 155 case Fortran::common::RelationalOperator::EQ: 156 return mlir::arith::CmpIPredicate::eq; 157 case Fortran::common::RelationalOperator::NE: 158 return mlir::arith::CmpIPredicate::ne; 159 case Fortran::common::RelationalOperator::GT: 160 return mlir::arith::CmpIPredicate::sgt; 161 case Fortran::common::RelationalOperator::GE: 162 return mlir::arith::CmpIPredicate::sge; 163 } 164 llvm_unreachable("unhandled INTEGER relational operator"); 165 } 166 167 /// Convert parser's REAL relational operators to MLIR. 168 /// The choice of order (O prefix) vs unorder (U prefix) follows Fortran 2018 169 /// requirements in the IEEE context (table 17.1 of F2018). This choice is 170 /// also applied in other contexts because it is easier and in line with 171 /// other Fortran compilers. 172 /// FIXME: The signaling/quiet aspect of the table 17.1 requirement is not 173 /// fully enforced. FIR and LLVM `fcmp` instructions do not give any guarantee 174 /// whether the comparison will signal or not in case of quiet NaN argument. 175 static mlir::arith::CmpFPredicate 176 translateFloatRelational(Fortran::common::RelationalOperator rop) { 177 switch (rop) { 178 case Fortran::common::RelationalOperator::LT: 179 return mlir::arith::CmpFPredicate::OLT; 180 case Fortran::common::RelationalOperator::LE: 181 return mlir::arith::CmpFPredicate::OLE; 182 case Fortran::common::RelationalOperator::EQ: 183 return mlir::arith::CmpFPredicate::OEQ; 184 case Fortran::common::RelationalOperator::NE: 185 return mlir::arith::CmpFPredicate::UNE; 186 case Fortran::common::RelationalOperator::GT: 187 return mlir::arith::CmpFPredicate::OGT; 188 case Fortran::common::RelationalOperator::GE: 189 return mlir::arith::CmpFPredicate::OGE; 190 } 191 llvm_unreachable("unhandled REAL relational operator"); 192 } 193 194 static mlir::Value genActualIsPresentTest(fir::FirOpBuilder &builder, 195 mlir::Location loc, 196 fir::ExtendedValue actual) { 197 if (const auto *ptrOrAlloc = actual.getBoxOf<fir::MutableBoxValue>()) 198 return fir::factory::genIsAllocatedOrAssociatedTest(builder, loc, 199 *ptrOrAlloc); 200 // Optional case (not that optional allocatable/pointer cannot be absent 201 // when passed to CMPLX as per 15.5.2.12 point 3 (7) and (8)). It is 202 // therefore possible to catch them in the `then` case above. 203 return builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), 204 fir::getBase(actual)); 205 } 206 207 /// Convert the array_load, `load`, to an extended value. If `path` is not 208 /// empty, then traverse through the components designated. The base value is 209 /// `newBase`. This does not accept an array_load with a slice operand. 210 static fir::ExtendedValue 211 arrayLoadExtValue(fir::FirOpBuilder &builder, mlir::Location loc, 212 fir::ArrayLoadOp load, llvm::ArrayRef<mlir::Value> path, 213 mlir::Value newBase, mlir::Value newLen = {}) { 214 // Recover the extended value from the load. 215 if (load.getSlice()) 216 fir::emitFatalError(loc, "array_load with slice is not allowed"); 217 mlir::Type arrTy = load.getType(); 218 if (!path.empty()) { 219 mlir::Type ty = fir::applyPathToType(arrTy, path); 220 if (!ty) 221 fir::emitFatalError(loc, "path does not apply to type"); 222 if (!ty.isa<fir::SequenceType>()) { 223 if (fir::isa_char(ty)) { 224 mlir::Value len = newLen; 225 if (!len) 226 len = fir::factory::CharacterExprHelper{builder, loc}.getLength( 227 load.getMemref()); 228 if (!len) { 229 assert(load.getTypeparams().size() == 1 && 230 "length must be in array_load"); 231 len = load.getTypeparams()[0]; 232 } 233 return fir::CharBoxValue{newBase, len}; 234 } 235 return newBase; 236 } 237 arrTy = ty.cast<fir::SequenceType>(); 238 } 239 240 auto arrayToExtendedValue = 241 [&](const llvm::SmallVector<mlir::Value> &extents, 242 const llvm::SmallVector<mlir::Value> &origins) -> fir::ExtendedValue { 243 mlir::Type eleTy = fir::unwrapSequenceType(arrTy); 244 if (fir::isa_char(eleTy)) { 245 mlir::Value len = newLen; 246 if (!len) 247 len = fir::factory::CharacterExprHelper{builder, loc}.getLength( 248 load.getMemref()); 249 if (!len) { 250 assert(load.getTypeparams().size() == 1 && 251 "length must be in array_load"); 252 len = load.getTypeparams()[0]; 253 } 254 return fir::CharArrayBoxValue(newBase, len, extents, origins); 255 } 256 return fir::ArrayBoxValue(newBase, extents, origins); 257 }; 258 // Use the shape op, if there is one. 259 mlir::Value shapeVal = load.getShape(); 260 if (shapeVal) { 261 if (!mlir::isa<fir::ShiftOp>(shapeVal.getDefiningOp())) { 262 auto extents = fir::factory::getExtents(shapeVal); 263 auto origins = fir::factory::getOrigins(shapeVal); 264 return arrayToExtendedValue(extents, origins); 265 } 266 if (!fir::isa_box_type(load.getMemref().getType())) 267 fir::emitFatalError(loc, "shift op is invalid in this context"); 268 } 269 270 // If we're dealing with the array_load op (not a subobject) and the load does 271 // not have any type parameters, then read the extents from the original box. 272 // The origin may be either from the box or a shift operation. Create and 273 // return the array extended value. 274 if (path.empty() && load.getTypeparams().empty()) { 275 auto oldBox = load.getMemref(); 276 fir::ExtendedValue exv = fir::factory::readBoxValue(builder, loc, oldBox); 277 auto extents = fir::factory::getExtents(loc, builder, exv); 278 auto origins = fir::factory::getNonDefaultLowerBounds(builder, loc, exv); 279 if (shapeVal) { 280 // shapeVal is a ShiftOp and load.memref() is a boxed value. 281 newBase = builder.create<fir::ReboxOp>(loc, oldBox.getType(), oldBox, 282 shapeVal, /*slice=*/mlir::Value{}); 283 origins = fir::factory::getOrigins(shapeVal); 284 } 285 return fir::substBase(arrayToExtendedValue(extents, origins), newBase); 286 } 287 TODO(loc, "path to a POINTER, ALLOCATABLE, or other component that requires " 288 "dereferencing; generating the type parameters is a hard " 289 "requirement for correctness."); 290 } 291 292 /// Place \p exv in memory if it is not already a memory reference. If 293 /// \p forceValueType is provided, the value is first casted to the provided 294 /// type before being stored (this is mainly intended for logicals whose value 295 /// may be `i1` but needed to be stored as Fortran logicals). 296 static fir::ExtendedValue 297 placeScalarValueInMemory(fir::FirOpBuilder &builder, mlir::Location loc, 298 const fir::ExtendedValue &exv, 299 mlir::Type storageType) { 300 mlir::Value valBase = fir::getBase(exv); 301 if (fir::conformsWithPassByRef(valBase.getType())) 302 return exv; 303 304 assert(!fir::hasDynamicSize(storageType) && 305 "only expect statically sized scalars to be by value"); 306 307 // Since `a` is not itself a valid referent, determine its value and 308 // create a temporary location at the beginning of the function for 309 // referencing. 310 mlir::Value val = builder.createConvert(loc, storageType, valBase); 311 mlir::Value temp = builder.createTemporary( 312 loc, storageType, 313 llvm::ArrayRef<mlir::NamedAttribute>{ 314 Fortran::lower::getAdaptToByRefAttr(builder)}); 315 builder.create<fir::StoreOp>(loc, val, temp); 316 return fir::substBase(exv, temp); 317 } 318 319 // Copy a copy of scalar \p exv in a new temporary. 320 static fir::ExtendedValue 321 createInMemoryScalarCopy(fir::FirOpBuilder &builder, mlir::Location loc, 322 const fir::ExtendedValue &exv) { 323 assert(exv.rank() == 0 && "input to scalar memory copy must be a scalar"); 324 if (exv.getCharBox() != nullptr) 325 return fir::factory::CharacterExprHelper{builder, loc}.createTempFrom(exv); 326 if (fir::isDerivedWithLenParameters(exv)) 327 TODO(loc, "copy derived type with length parameters"); 328 mlir::Type type = fir::unwrapPassByRefType(fir::getBase(exv).getType()); 329 fir::ExtendedValue temp = builder.createTemporary(loc, type); 330 fir::factory::genScalarAssignment(builder, loc, temp, exv); 331 return temp; 332 } 333 334 // An expression with non-zero rank is an array expression. 335 template <typename A> 336 static bool isArray(const A &x) { 337 return x.Rank() != 0; 338 } 339 340 /// Is this a variable wrapped in parentheses? 341 template <typename A> 342 static bool isParenthesizedVariable(const A &) { 343 return false; 344 } 345 template <typename T> 346 static bool isParenthesizedVariable(const Fortran::evaluate::Expr<T> &expr) { 347 using ExprVariant = decltype(Fortran::evaluate::Expr<T>::u); 348 using Parentheses = Fortran::evaluate::Parentheses<T>; 349 if constexpr (Fortran::common::HasMember<Parentheses, ExprVariant>) { 350 if (const auto *parentheses = std::get_if<Parentheses>(&expr.u)) 351 return Fortran::evaluate::IsVariable(parentheses->left()); 352 return false; 353 } else { 354 return std::visit([&](const auto &x) { return isParenthesizedVariable(x); }, 355 expr.u); 356 } 357 } 358 359 /// Does \p expr only refer to symbols that are mapped to IR values in \p symMap 360 /// ? 361 static bool allSymbolsInExprPresentInMap(const Fortran::lower::SomeExpr &expr, 362 Fortran::lower::SymMap &symMap) { 363 for (const auto &sym : Fortran::evaluate::CollectSymbols(expr)) 364 if (!symMap.lookupSymbol(sym)) 365 return false; 366 return true; 367 } 368 369 /// Generate a load of a value from an address. Beware that this will lose 370 /// any dynamic type information for polymorphic entities (note that unlimited 371 /// polymorphic cannot be loaded and must not be provided here). 372 static fir::ExtendedValue genLoad(fir::FirOpBuilder &builder, 373 mlir::Location loc, 374 const fir::ExtendedValue &addr) { 375 return addr.match( 376 [](const fir::CharBoxValue &box) -> fir::ExtendedValue { return box; }, 377 [&](const fir::UnboxedValue &v) -> fir::ExtendedValue { 378 if (fir::unwrapRefType(fir::getBase(v).getType()) 379 .isa<fir::RecordType>()) 380 return v; 381 return builder.create<fir::LoadOp>(loc, fir::getBase(v)); 382 }, 383 [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue { 384 return genLoad(builder, loc, 385 fir::factory::genMutableBoxRead(builder, loc, box)); 386 }, 387 [&](const fir::BoxValue &box) -> fir::ExtendedValue { 388 if (box.isUnlimitedPolymorphic()) 389 fir::emitFatalError( 390 loc, 391 "lowering attempting to load an unlimited polymorphic entity"); 392 return genLoad(builder, loc, 393 fir::factory::readBoxValue(builder, loc, box)); 394 }, 395 [&](const auto &) -> fir::ExtendedValue { 396 fir::emitFatalError( 397 loc, "attempting to load whole array or procedure address"); 398 }); 399 } 400 401 /// Create an optional dummy argument value from entity \p exv that may be 402 /// absent. This can only be called with numerical or logical scalar \p exv. 403 /// If \p exv is considered absent according to 15.5.2.12 point 1., the returned 404 /// value is zero (or false), otherwise it is the value of \p exv. 405 static fir::ExtendedValue genOptionalValue(fir::FirOpBuilder &builder, 406 mlir::Location loc, 407 const fir::ExtendedValue &exv, 408 mlir::Value isPresent) { 409 mlir::Type eleType = fir::getBaseTypeOf(exv); 410 assert(exv.rank() == 0 && fir::isa_trivial(eleType) && 411 "must be a numerical or logical scalar"); 412 return builder 413 .genIfOp(loc, {eleType}, isPresent, 414 /*withElseRegion=*/true) 415 .genThen([&]() { 416 mlir::Value val = fir::getBase(genLoad(builder, loc, exv)); 417 builder.create<fir::ResultOp>(loc, val); 418 }) 419 .genElse([&]() { 420 mlir::Value zero = fir::factory::createZeroValue(builder, loc, eleType); 421 builder.create<fir::ResultOp>(loc, zero); 422 }) 423 .getResults()[0]; 424 } 425 426 /// Create an optional dummy argument address from entity \p exv that may be 427 /// absent. If \p exv is considered absent according to 15.5.2.12 point 1., the 428 /// returned value is a null pointer, otherwise it is the address of \p exv. 429 static fir::ExtendedValue genOptionalAddr(fir::FirOpBuilder &builder, 430 mlir::Location loc, 431 const fir::ExtendedValue &exv, 432 mlir::Value isPresent) { 433 // If it is an exv pointer/allocatable, then it cannot be absent 434 // because it is passed to a non-pointer/non-allocatable. 435 if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>()) 436 return fir::factory::genMutableBoxRead(builder, loc, *box); 437 // If this is not a POINTER or ALLOCATABLE, then it is already an OPTIONAL 438 // address and can be passed directly. 439 return exv; 440 } 441 442 /// Create an optional dummy argument address from entity \p exv that may be 443 /// absent. If \p exv is considered absent according to 15.5.2.12 point 1., the 444 /// returned value is an absent fir.box, otherwise it is a fir.box describing \p 445 /// exv. 446 static fir::ExtendedValue genOptionalBox(fir::FirOpBuilder &builder, 447 mlir::Location loc, 448 const fir::ExtendedValue &exv, 449 mlir::Value isPresent) { 450 // Non allocatable/pointer optional box -> simply forward 451 if (exv.getBoxOf<fir::BoxValue>()) 452 return exv; 453 454 fir::ExtendedValue newExv = exv; 455 // Optional allocatable/pointer -> Cannot be absent, but need to translate 456 // unallocated/diassociated into absent fir.box. 457 if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>()) 458 newExv = fir::factory::genMutableBoxRead(builder, loc, *box); 459 460 // createBox will not do create any invalid memory dereferences if exv is 461 // absent. The created fir.box will not be usable, but the SelectOp below 462 // ensures it won't be. 463 mlir::Value box = builder.createBox(loc, newExv); 464 mlir::Type boxType = box.getType(); 465 auto absent = builder.create<fir::AbsentOp>(loc, boxType); 466 auto boxOrAbsent = builder.create<mlir::arith::SelectOp>( 467 loc, boxType, isPresent, box, absent); 468 return fir::BoxValue(boxOrAbsent); 469 } 470 471 /// Is this a call to an elemental procedure with at least one array argument? 472 static bool 473 isElementalProcWithArrayArgs(const Fortran::evaluate::ProcedureRef &procRef) { 474 if (procRef.IsElemental()) 475 for (const std::optional<Fortran::evaluate::ActualArgument> &arg : 476 procRef.arguments()) 477 if (arg && arg->Rank() != 0) 478 return true; 479 return false; 480 } 481 template <typename T> 482 static bool isElementalProcWithArrayArgs(const Fortran::evaluate::Expr<T> &) { 483 return false; 484 } 485 template <> 486 bool isElementalProcWithArrayArgs(const Fortran::lower::SomeExpr &x) { 487 if (const auto *procRef = std::get_if<Fortran::evaluate::ProcedureRef>(&x.u)) 488 return isElementalProcWithArrayArgs(*procRef); 489 return false; 490 } 491 492 /// Some auxiliary data for processing initialization in ScalarExprLowering 493 /// below. This is currently used for generating dense attributed global 494 /// arrays. 495 struct InitializerData { 496 explicit InitializerData(bool getRawVals = false) : genRawVals{getRawVals} {} 497 llvm::SmallVector<mlir::Attribute> rawVals; // initialization raw values 498 mlir::Type rawType; // Type of elements processed for rawVals vector. 499 bool genRawVals; // generate the rawVals vector if set. 500 }; 501 502 /// If \p arg is the address of a function with a denoted host-association tuple 503 /// argument, then return the host-associations tuple value of the current 504 /// procedure. Otherwise, return nullptr. 505 static mlir::Value 506 argumentHostAssocs(Fortran::lower::AbstractConverter &converter, 507 mlir::Value arg) { 508 if (auto addr = mlir::dyn_cast_or_null<fir::AddrOfOp>(arg.getDefiningOp())) { 509 auto &builder = converter.getFirOpBuilder(); 510 if (auto funcOp = builder.getNamedFunction(addr.getSymbol())) 511 if (fir::anyFuncArgsHaveAttr(funcOp, fir::getHostAssocAttrName())) 512 return converter.hostAssocTupleValue(); 513 } 514 return {}; 515 } 516 517 /// \p argTy must be a tuple (pair) of boxproc and integral types. Convert the 518 /// \p funcAddr argument to a boxproc value, with the host-association as 519 /// required. Call the factory function to finish creating the tuple value. 520 static mlir::Value 521 createBoxProcCharTuple(Fortran::lower::AbstractConverter &converter, 522 mlir::Type argTy, mlir::Value funcAddr, 523 mlir::Value charLen) { 524 auto boxTy = 525 argTy.cast<mlir::TupleType>().getType(0).cast<fir::BoxProcType>(); 526 mlir::Location loc = converter.getCurrentLocation(); 527 auto &builder = converter.getFirOpBuilder(); 528 auto boxProc = [&]() -> mlir::Value { 529 if (auto host = argumentHostAssocs(converter, funcAddr)) 530 return builder.create<fir::EmboxProcOp>( 531 loc, boxTy, llvm::ArrayRef<mlir::Value>{funcAddr, host}); 532 return builder.create<fir::EmboxProcOp>(loc, boxTy, funcAddr); 533 }(); 534 return fir::factory::createCharacterProcedureTuple(builder, loc, argTy, 535 boxProc, charLen); 536 } 537 538 // Helper to get the ultimate first symbol. This works around the fact that 539 // symbol resolution in the front end doesn't always resolve a symbol to its 540 // ultimate symbol but may leave placeholder indirections for use and host 541 // associations. 542 template <typename A> 543 const Fortran::semantics::Symbol &getFirstSym(const A &obj) { 544 return obj.GetFirstSymbol().GetUltimate(); 545 } 546 547 // Helper to get the ultimate last symbol. 548 template <typename A> 549 const Fortran::semantics::Symbol &getLastSym(const A &obj) { 550 return obj.GetLastSymbol().GetUltimate(); 551 } 552 553 namespace { 554 555 /// Lowering of Fortran::evaluate::Expr<T> expressions 556 class ScalarExprLowering { 557 public: 558 using ExtValue = fir::ExtendedValue; 559 560 explicit ScalarExprLowering(mlir::Location loc, 561 Fortran::lower::AbstractConverter &converter, 562 Fortran::lower::SymMap &symMap, 563 Fortran::lower::StatementContext &stmtCtx, 564 InitializerData *initializer = nullptr) 565 : location{loc}, converter{converter}, 566 builder{converter.getFirOpBuilder()}, stmtCtx{stmtCtx}, symMap{symMap}, 567 inInitializer{initializer} {} 568 569 ExtValue genExtAddr(const Fortran::lower::SomeExpr &expr) { 570 return gen(expr); 571 } 572 573 /// Lower `expr` to be passed as a fir.box argument. Do not create a temp 574 /// for the expr if it is a variable that can be described as a fir.box. 575 ExtValue genBoxArg(const Fortran::lower::SomeExpr &expr) { 576 bool saveUseBoxArg = useBoxArg; 577 useBoxArg = true; 578 ExtValue result = gen(expr); 579 useBoxArg = saveUseBoxArg; 580 return result; 581 } 582 583 ExtValue genExtValue(const Fortran::lower::SomeExpr &expr) { 584 return genval(expr); 585 } 586 587 /// Lower an expression that is a pointer or an allocatable to a 588 /// MutableBoxValue. 589 fir::MutableBoxValue 590 genMutableBoxValue(const Fortran::lower::SomeExpr &expr) { 591 // Pointers and allocatables can only be: 592 // - a simple designator "x" 593 // - a component designator "a%b(i,j)%x" 594 // - a function reference "foo()" 595 // - result of NULL() or NULL(MOLD) intrinsic. 596 // NULL() requires some context to be lowered, so it is not handled 597 // here and must be lowered according to the context where it appears. 598 ExtValue exv = std::visit( 599 [&](const auto &x) { return genMutableBoxValueImpl(x); }, expr.u); 600 const fir::MutableBoxValue *mutableBox = 601 exv.getBoxOf<fir::MutableBoxValue>(); 602 if (!mutableBox) 603 fir::emitFatalError(getLoc(), "expr was not lowered to MutableBoxValue"); 604 return *mutableBox; 605 } 606 607 template <typename T> 608 ExtValue genMutableBoxValueImpl(const T &) { 609 // NULL() case should not be handled here. 610 fir::emitFatalError(getLoc(), "NULL() must be lowered in its context"); 611 } 612 613 /// A `NULL()` in a position where a mutable box is expected has the same 614 /// semantics as an absent optional box value. 615 ExtValue genMutableBoxValueImpl(const Fortran::evaluate::NullPointer &) { 616 mlir::Location loc = getLoc(); 617 auto nullConst = builder.createNullConstant(loc); 618 auto noneTy = mlir::NoneType::get(builder.getContext()); 619 auto polyRefTy = fir::LLVMPointerType::get(noneTy); 620 // MutableBoxValue will dereference the box, so create a bogus temporary for 621 // the `nullptr`. The LLVM optimizer will garbage collect the temp. 622 auto temp = 623 builder.createTemporary(loc, polyRefTy, /*shape=*/mlir::ValueRange{}); 624 auto nullPtr = builder.createConvert(loc, polyRefTy, nullConst); 625 builder.create<fir::StoreOp>(loc, nullPtr, temp); 626 auto nullBoxTy = builder.getRefType(fir::BoxType::get(noneTy)); 627 return fir::MutableBoxValue(builder.createConvert(loc, nullBoxTy, temp), 628 /*lenParameters=*/mlir::ValueRange{}, 629 /*mutableProperties=*/{}); 630 } 631 632 template <typename T> 633 ExtValue 634 genMutableBoxValueImpl(const Fortran::evaluate::FunctionRef<T> &funRef) { 635 return genRawProcedureRef(funRef, converter.genType(toEvExpr(funRef))); 636 } 637 638 template <typename T> 639 ExtValue 640 genMutableBoxValueImpl(const Fortran::evaluate::Designator<T> &designator) { 641 return std::visit( 642 Fortran::common::visitors{ 643 [&](const Fortran::evaluate::SymbolRef &sym) -> ExtValue { 644 return symMap.lookupSymbol(*sym).toExtendedValue(); 645 }, 646 [&](const Fortran::evaluate::Component &comp) -> ExtValue { 647 return genComponent(comp); 648 }, 649 [&](const auto &) -> ExtValue { 650 fir::emitFatalError(getLoc(), 651 "not an allocatable or pointer designator"); 652 }}, 653 designator.u); 654 } 655 656 template <typename T> 657 ExtValue genMutableBoxValueImpl(const Fortran::evaluate::Expr<T> &expr) { 658 return std::visit([&](const auto &x) { return genMutableBoxValueImpl(x); }, 659 expr.u); 660 } 661 662 mlir::Location getLoc() { return location; } 663 664 template <typename A> 665 mlir::Value genunbox(const A &expr) { 666 ExtValue e = genval(expr); 667 if (const fir::UnboxedValue *r = e.getUnboxed()) 668 return *r; 669 fir::emitFatalError(getLoc(), "unboxed expression expected"); 670 } 671 672 /// Generate an integral constant of `value` 673 template <int KIND> 674 mlir::Value genIntegerConstant(mlir::MLIRContext *context, 675 std::int64_t value) { 676 mlir::Type type = 677 converter.genType(Fortran::common::TypeCategory::Integer, KIND); 678 return builder.createIntegerConstant(getLoc(), type, value); 679 } 680 681 /// Generate a logical/boolean constant of `value` 682 mlir::Value genBoolConstant(bool value) { 683 return builder.createBool(getLoc(), value); 684 } 685 686 /// Generate a real constant with a value `value`. 687 template <int KIND> 688 mlir::Value genRealConstant(mlir::MLIRContext *context, 689 const llvm::APFloat &value) { 690 mlir::Type fltTy = Fortran::lower::convertReal(context, KIND); 691 return builder.createRealConstant(getLoc(), fltTy, value); 692 } 693 694 mlir::Type getSomeKindInteger() { return builder.getIndexType(); } 695 696 mlir::func::FuncOp getFunction(llvm::StringRef name, 697 mlir::FunctionType funTy) { 698 if (mlir::func::FuncOp func = builder.getNamedFunction(name)) 699 return func; 700 return builder.createFunction(getLoc(), name, funTy); 701 } 702 703 template <typename OpTy> 704 mlir::Value createCompareOp(mlir::arith::CmpIPredicate pred, 705 const ExtValue &left, const ExtValue &right) { 706 if (const fir::UnboxedValue *lhs = left.getUnboxed()) 707 if (const fir::UnboxedValue *rhs = right.getUnboxed()) 708 return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs); 709 fir::emitFatalError(getLoc(), "array compare should be handled in genarr"); 710 } 711 template <typename OpTy, typename A> 712 mlir::Value createCompareOp(const A &ex, mlir::arith::CmpIPredicate pred) { 713 ExtValue left = genval(ex.left()); 714 return createCompareOp<OpTy>(pred, left, genval(ex.right())); 715 } 716 717 template <typename OpTy> 718 mlir::Value createFltCmpOp(mlir::arith::CmpFPredicate pred, 719 const ExtValue &left, const ExtValue &right) { 720 if (const fir::UnboxedValue *lhs = left.getUnboxed()) 721 if (const fir::UnboxedValue *rhs = right.getUnboxed()) 722 return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs); 723 fir::emitFatalError(getLoc(), "array compare should be handled in genarr"); 724 } 725 template <typename OpTy, typename A> 726 mlir::Value createFltCmpOp(const A &ex, mlir::arith::CmpFPredicate pred) { 727 ExtValue left = genval(ex.left()); 728 return createFltCmpOp<OpTy>(pred, left, genval(ex.right())); 729 } 730 731 /// Create a call to the runtime to compare two CHARACTER values. 732 /// Precondition: This assumes that the two values have `fir.boxchar` type. 733 mlir::Value createCharCompare(mlir::arith::CmpIPredicate pred, 734 const ExtValue &left, const ExtValue &right) { 735 return fir::runtime::genCharCompare(builder, getLoc(), pred, left, right); 736 } 737 738 template <typename A> 739 mlir::Value createCharCompare(const A &ex, mlir::arith::CmpIPredicate pred) { 740 ExtValue left = genval(ex.left()); 741 return createCharCompare(pred, left, genval(ex.right())); 742 } 743 744 /// Returns a reference to a symbol or its box/boxChar descriptor if it has 745 /// one. 746 ExtValue gen(Fortran::semantics::SymbolRef sym) { 747 if (Fortran::lower::SymbolBox val = symMap.lookupSymbol(sym)) 748 return val.match( 749 [&](const Fortran::lower::SymbolBox::PointerOrAllocatable &boxAddr) { 750 return fir::factory::genMutableBoxRead(builder, getLoc(), boxAddr); 751 }, 752 [&val](auto &) { return val.toExtendedValue(); }); 753 LLVM_DEBUG(llvm::dbgs() 754 << "unknown symbol: " << sym << "\nmap: " << symMap << '\n'); 755 fir::emitFatalError(getLoc(), "symbol is not mapped to any IR value"); 756 } 757 758 ExtValue genLoad(const ExtValue &exv) { 759 return ::genLoad(builder, getLoc(), exv); 760 } 761 762 ExtValue genval(Fortran::semantics::SymbolRef sym) { 763 mlir::Location loc = getLoc(); 764 ExtValue var = gen(sym); 765 if (const fir::UnboxedValue *s = var.getUnboxed()) 766 if (fir::isa_ref_type(s->getType())) { 767 // A function with multiple entry points returning different types 768 // tags all result variables with one of the largest types to allow 769 // them to share the same storage. A reference to a result variable 770 // of one of the other types requires conversion to the actual type. 771 fir::UnboxedValue addr = *s; 772 if (Fortran::semantics::IsFunctionResult(sym)) { 773 mlir::Type resultType = converter.genType(*sym); 774 if (addr.getType() != resultType) 775 addr = builder.createConvert(loc, builder.getRefType(resultType), 776 addr); 777 } 778 return genLoad(addr); 779 } 780 return var; 781 } 782 783 ExtValue genval(const Fortran::evaluate::BOZLiteralConstant &) { 784 TODO(getLoc(), "BOZ"); 785 } 786 787 /// Return indirection to function designated in ProcedureDesignator. 788 /// The type of the function indirection is not guaranteed to match the one 789 /// of the ProcedureDesignator due to Fortran implicit typing rules. 790 ExtValue genval(const Fortran::evaluate::ProcedureDesignator &proc) { 791 mlir::Location loc = getLoc(); 792 if (const Fortran::evaluate::SpecificIntrinsic *intrinsic = 793 proc.GetSpecificIntrinsic()) { 794 mlir::FunctionType signature = 795 Fortran::lower::translateSignature(proc, converter); 796 // Intrinsic lowering is based on the generic name, so retrieve it here in 797 // case it is different from the specific name. The type of the specific 798 // intrinsic is retained in the signature. 799 std::string genericName = 800 converter.getFoldingContext().intrinsics().GetGenericIntrinsicName( 801 intrinsic->name); 802 mlir::SymbolRefAttr symbolRefAttr = 803 Fortran::lower::getUnrestrictedIntrinsicSymbolRefAttr( 804 builder, loc, genericName, signature); 805 mlir::Value funcPtr = 806 builder.create<fir::AddrOfOp>(loc, signature, symbolRefAttr); 807 return funcPtr; 808 } 809 const Fortran::semantics::Symbol *symbol = proc.GetSymbol(); 810 assert(symbol && "expected symbol in ProcedureDesignator"); 811 mlir::Value funcPtr; 812 mlir::Value funcPtrResultLength; 813 if (Fortran::semantics::IsDummy(*symbol)) { 814 Fortran::lower::SymbolBox val = symMap.lookupSymbol(*symbol); 815 assert(val && "Dummy procedure not in symbol map"); 816 funcPtr = val.getAddr(); 817 if (fir::isCharacterProcedureTuple(funcPtr.getType(), 818 /*acceptRawFunc=*/false)) 819 std::tie(funcPtr, funcPtrResultLength) = 820 fir::factory::extractCharacterProcedureTuple(builder, loc, funcPtr); 821 } else { 822 std::string name = converter.mangleName(*symbol); 823 mlir::func::FuncOp func = 824 Fortran::lower::getOrDeclareFunction(name, proc, converter); 825 // Abstract results require later rewrite of the function type. 826 // This currently does not happen inside GloalOps, causing LLVM 827 // IR verification failure. This helper is only here to catch these 828 // cases and emit a TODOs for now. 829 if (inInitializer && fir::hasAbstractResult(func.getFunctionType())) 830 TODO(converter.genLocation(symbol->name()), 831 "static description of non trivial procedure bindings"); 832 funcPtr = builder.create<fir::AddrOfOp>(loc, func.getFunctionType(), 833 builder.getSymbolRefAttr(name)); 834 } 835 if (Fortran::lower::mustPassLengthWithDummyProcedure(proc, converter)) { 836 // The result length, if available here, must be propagated along the 837 // procedure address so that call sites where the result length is assumed 838 // can retrieve the length. 839 Fortran::evaluate::DynamicType resultType = proc.GetType().value(); 840 if (const auto &lengthExpr = resultType.GetCharLength()) { 841 // The length expression may refer to dummy argument symbols that are 842 // meaningless without any actual arguments. Leave the length as 843 // unknown in that case, it be resolved on the call site 844 // with the actual arguments. 845 if (allSymbolsInExprPresentInMap(toEvExpr(*lengthExpr), symMap)) { 846 mlir::Value rawLen = fir::getBase(genval(*lengthExpr)); 847 // F2018 7.4.4.2 point 5. 848 funcPtrResultLength = 849 fir::factory::genMaxWithZero(builder, getLoc(), rawLen); 850 } 851 } 852 if (!funcPtrResultLength) 853 funcPtrResultLength = builder.createIntegerConstant( 854 loc, builder.getCharacterLengthType(), -1); 855 return fir::CharBoxValue{funcPtr, funcPtrResultLength}; 856 } 857 return funcPtr; 858 } 859 ExtValue genval(const Fortran::evaluate::NullPointer &) { 860 return builder.createNullConstant(getLoc()); 861 } 862 863 static bool 864 isDerivedTypeWithLengthParameters(const Fortran::semantics::Symbol &sym) { 865 if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType()) 866 if (const Fortran::semantics::DerivedTypeSpec *derived = 867 declTy->AsDerived()) 868 return Fortran::semantics::CountLenParameters(*derived) > 0; 869 return false; 870 } 871 872 static bool isBuiltinCPtr(const Fortran::semantics::Symbol &sym) { 873 if (const Fortran::semantics::DeclTypeSpec *declType = sym.GetType()) 874 if (const Fortran::semantics::DerivedTypeSpec *derived = 875 declType->AsDerived()) 876 return Fortran::semantics::IsIsoCType(derived); 877 return false; 878 } 879 880 /// Lower structure constructor without a temporary. This can be used in 881 /// fir::GloablOp, and assumes that the structure component is a constant. 882 ExtValue genStructComponentInInitializer( 883 const Fortran::evaluate::StructureConstructor &ctor) { 884 mlir::Location loc = getLoc(); 885 mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor)); 886 auto recTy = ty.cast<fir::RecordType>(); 887 auto fieldTy = fir::FieldType::get(ty.getContext()); 888 mlir::Value res = builder.create<fir::UndefOp>(loc, recTy); 889 890 for (const auto &[sym, expr] : ctor.values()) { 891 // Parent components need more work because they do not appear in the 892 // fir.rec type. 893 if (sym->test(Fortran::semantics::Symbol::Flag::ParentComp)) 894 TODO(loc, "parent component in structure constructor"); 895 896 llvm::StringRef name = toStringRef(sym->name()); 897 mlir::Type componentTy = recTy.getType(name); 898 // FIXME: type parameters must come from the derived-type-spec 899 auto field = builder.create<fir::FieldIndexOp>( 900 loc, fieldTy, name, ty, 901 /*typeParams=*/mlir::ValueRange{} /*TODO*/); 902 903 if (Fortran::semantics::IsAllocatable(sym)) 904 TODO(loc, "allocatable component in structure constructor"); 905 906 if (Fortran::semantics::IsPointer(sym)) { 907 mlir::Value initialTarget = Fortran::lower::genInitialDataTarget( 908 converter, loc, componentTy, expr.value()); 909 res = builder.create<fir::InsertValueOp>( 910 loc, recTy, res, initialTarget, 911 builder.getArrayAttr(field.getAttributes())); 912 continue; 913 } 914 915 if (isDerivedTypeWithLengthParameters(sym)) 916 TODO(loc, "component with length parameters in structure constructor"); 917 918 if (isBuiltinCPtr(sym)) { 919 // Builtin c_ptr and c_funptr have special handling because initial 920 // value are handled for them as an extension. 921 mlir::Value addr = fir::getBase(Fortran::lower::genExtAddrInInitializer( 922 converter, loc, expr.value())); 923 if (addr.getType() == componentTy) { 924 // Do nothing. The Ev::Expr was returned as a value that can be 925 // inserted directly to the component without an intermediary. 926 } else { 927 // The Ev::Expr returned is an initializer that is a pointer (e.g., 928 // null) that must be inserted into an intermediate cptr record 929 // value's address field, which ought to be an intptr_t on the target. 930 assert((fir::isa_ref_type(addr.getType()) || 931 addr.getType().isa<mlir::FunctionType>()) && 932 "expect reference type for address field"); 933 assert(fir::isa_derived(componentTy) && 934 "expect C_PTR, C_FUNPTR to be a record"); 935 auto cPtrRecTy = componentTy.cast<fir::RecordType>(); 936 llvm::StringRef addrFieldName = 937 Fortran::lower::builtin::cptrFieldName; 938 mlir::Type addrFieldTy = cPtrRecTy.getType(addrFieldName); 939 auto addrField = builder.create<fir::FieldIndexOp>( 940 loc, fieldTy, addrFieldName, componentTy, 941 /*typeParams=*/mlir::ValueRange{}); 942 mlir::Value castAddr = builder.createConvert(loc, addrFieldTy, addr); 943 auto undef = builder.create<fir::UndefOp>(loc, componentTy); 944 addr = builder.create<fir::InsertValueOp>( 945 loc, componentTy, undef, castAddr, 946 builder.getArrayAttr(addrField.getAttributes())); 947 } 948 res = builder.create<fir::InsertValueOp>( 949 loc, recTy, res, addr, builder.getArrayAttr(field.getAttributes())); 950 continue; 951 } 952 953 mlir::Value val = fir::getBase(genval(expr.value())); 954 assert(!fir::isa_ref_type(val.getType()) && "expecting a constant value"); 955 mlir::Value castVal = builder.createConvert(loc, componentTy, val); 956 res = builder.create<fir::InsertValueOp>( 957 loc, recTy, res, castVal, 958 builder.getArrayAttr(field.getAttributes())); 959 } 960 return res; 961 } 962 963 /// A structure constructor is lowered two ways. In an initializer context, 964 /// the entire structure must be constant, so the aggregate value is 965 /// constructed inline. This allows it to be the body of a GlobalOp. 966 /// Otherwise, the structure constructor is in an expression. In that case, a 967 /// temporary object is constructed in the stack frame of the procedure. 968 ExtValue genval(const Fortran::evaluate::StructureConstructor &ctor) { 969 if (inInitializer) 970 return genStructComponentInInitializer(ctor); 971 mlir::Location loc = getLoc(); 972 mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor)); 973 auto recTy = ty.cast<fir::RecordType>(); 974 auto fieldTy = fir::FieldType::get(ty.getContext()); 975 mlir::Value res = builder.createTemporary(loc, recTy); 976 977 for (const auto &value : ctor.values()) { 978 const Fortran::semantics::Symbol &sym = *value.first; 979 const Fortran::lower::SomeExpr &expr = value.second.value(); 980 // Parent components need more work because they do not appear in the 981 // fir.rec type. 982 if (sym.test(Fortran::semantics::Symbol::Flag::ParentComp)) 983 TODO(loc, "parent component in structure constructor"); 984 985 if (isDerivedTypeWithLengthParameters(sym)) 986 TODO(loc, "component with length parameters in structure constructor"); 987 988 llvm::StringRef name = toStringRef(sym.name()); 989 // FIXME: type parameters must come from the derived-type-spec 990 mlir::Value field = builder.create<fir::FieldIndexOp>( 991 loc, fieldTy, name, ty, 992 /*typeParams=*/mlir::ValueRange{} /*TODO*/); 993 mlir::Type coorTy = builder.getRefType(recTy.getType(name)); 994 auto coor = builder.create<fir::CoordinateOp>(loc, coorTy, 995 fir::getBase(res), field); 996 ExtValue to = fir::factory::componentToExtendedValue(builder, loc, coor); 997 to.match( 998 [&](const fir::UnboxedValue &toPtr) { 999 ExtValue value = genval(expr); 1000 fir::factory::genScalarAssignment(builder, loc, to, value); 1001 }, 1002 [&](const fir::CharBoxValue &) { 1003 ExtValue value = genval(expr); 1004 fir::factory::genScalarAssignment(builder, loc, to, value); 1005 }, 1006 [&](const fir::ArrayBoxValue &) { 1007 Fortran::lower::createSomeArrayAssignment(converter, to, expr, 1008 symMap, stmtCtx); 1009 }, 1010 [&](const fir::CharArrayBoxValue &) { 1011 Fortran::lower::createSomeArrayAssignment(converter, to, expr, 1012 symMap, stmtCtx); 1013 }, 1014 [&](const fir::BoxValue &toBox) { 1015 fir::emitFatalError(loc, "derived type components must not be " 1016 "represented by fir::BoxValue"); 1017 }, 1018 [&](const fir::MutableBoxValue &toBox) { 1019 if (toBox.isPointer()) { 1020 Fortran::lower::associateMutableBox( 1021 converter, loc, toBox, expr, /*lbounds=*/llvm::None, stmtCtx); 1022 return; 1023 } 1024 // For allocatable components, a deep copy is needed. 1025 TODO(loc, "allocatable components in derived type assignment"); 1026 }, 1027 [&](const fir::ProcBoxValue &toBox) { 1028 TODO(loc, "procedure pointer component in derived type assignment"); 1029 }); 1030 } 1031 return res; 1032 } 1033 1034 /// Lowering of an <i>ac-do-variable</i>, which is not a Symbol. 1035 ExtValue genval(const Fortran::evaluate::ImpliedDoIndex &var) { 1036 return converter.impliedDoBinding(toStringRef(var.name)); 1037 } 1038 1039 ExtValue genval(const Fortran::evaluate::DescriptorInquiry &desc) { 1040 ExtValue exv = desc.base().IsSymbol() ? gen(getLastSym(desc.base())) 1041 : gen(desc.base().GetComponent()); 1042 mlir::IndexType idxTy = builder.getIndexType(); 1043 mlir::Location loc = getLoc(); 1044 auto castResult = [&](mlir::Value v) { 1045 using ResTy = Fortran::evaluate::DescriptorInquiry::Result; 1046 return builder.createConvert( 1047 loc, converter.genType(ResTy::category, ResTy::kind), v); 1048 }; 1049 switch (desc.field()) { 1050 case Fortran::evaluate::DescriptorInquiry::Field::Len: 1051 return castResult(fir::factory::readCharLen(builder, loc, exv)); 1052 case Fortran::evaluate::DescriptorInquiry::Field::LowerBound: 1053 return castResult(fir::factory::readLowerBound( 1054 builder, loc, exv, desc.dimension(), 1055 builder.createIntegerConstant(loc, idxTy, 1))); 1056 case Fortran::evaluate::DescriptorInquiry::Field::Extent: 1057 return castResult( 1058 fir::factory::readExtent(builder, loc, exv, desc.dimension())); 1059 case Fortran::evaluate::DescriptorInquiry::Field::Rank: 1060 TODO(loc, "rank inquiry on assumed rank"); 1061 case Fortran::evaluate::DescriptorInquiry::Field::Stride: 1062 // So far the front end does not generate this inquiry. 1063 TODO(loc, "stride inquiry"); 1064 } 1065 llvm_unreachable("unknown descriptor inquiry"); 1066 } 1067 1068 ExtValue genval(const Fortran::evaluate::TypeParamInquiry &) { 1069 TODO(getLoc(), "type parameter inquiry"); 1070 } 1071 1072 mlir::Value extractComplexPart(mlir::Value cplx, bool isImagPart) { 1073 return fir::factory::Complex{builder, getLoc()}.extractComplexPart( 1074 cplx, isImagPart); 1075 } 1076 1077 template <int KIND> 1078 ExtValue genval(const Fortran::evaluate::ComplexComponent<KIND> &part) { 1079 return extractComplexPart(genunbox(part.left()), part.isImaginaryPart); 1080 } 1081 1082 template <int KIND> 1083 ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type< 1084 Fortran::common::TypeCategory::Integer, KIND>> &op) { 1085 mlir::Value input = genunbox(op.left()); 1086 // Like LLVM, integer negation is the binary op "0 - value" 1087 mlir::Value zero = genIntegerConstant<KIND>(builder.getContext(), 0); 1088 return builder.create<mlir::arith::SubIOp>(getLoc(), zero, input); 1089 } 1090 template <int KIND> 1091 ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type< 1092 Fortran::common::TypeCategory::Real, KIND>> &op) { 1093 return builder.create<mlir::arith::NegFOp>(getLoc(), genunbox(op.left())); 1094 } 1095 template <int KIND> 1096 ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type< 1097 Fortran::common::TypeCategory::Complex, KIND>> &op) { 1098 return builder.create<fir::NegcOp>(getLoc(), genunbox(op.left())); 1099 } 1100 1101 template <typename OpTy> 1102 mlir::Value createBinaryOp(const ExtValue &left, const ExtValue &right) { 1103 assert(fir::isUnboxedValue(left) && fir::isUnboxedValue(right)); 1104 mlir::Value lhs = fir::getBase(left); 1105 mlir::Value rhs = fir::getBase(right); 1106 assert(lhs.getType() == rhs.getType() && "types must be the same"); 1107 return builder.create<OpTy>(getLoc(), lhs, rhs); 1108 } 1109 1110 template <typename OpTy, typename A> 1111 mlir::Value createBinaryOp(const A &ex) { 1112 ExtValue left = genval(ex.left()); 1113 return createBinaryOp<OpTy>(left, genval(ex.right())); 1114 } 1115 1116 #undef GENBIN 1117 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp) \ 1118 template <int KIND> \ 1119 ExtValue genval(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \ 1120 Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) { \ 1121 return createBinaryOp<GenBinFirOp>(x); \ 1122 } 1123 1124 GENBIN(Add, Integer, mlir::arith::AddIOp) 1125 GENBIN(Add, Real, mlir::arith::AddFOp) 1126 GENBIN(Add, Complex, fir::AddcOp) 1127 GENBIN(Subtract, Integer, mlir::arith::SubIOp) 1128 GENBIN(Subtract, Real, mlir::arith::SubFOp) 1129 GENBIN(Subtract, Complex, fir::SubcOp) 1130 GENBIN(Multiply, Integer, mlir::arith::MulIOp) 1131 GENBIN(Multiply, Real, mlir::arith::MulFOp) 1132 GENBIN(Multiply, Complex, fir::MulcOp) 1133 GENBIN(Divide, Integer, mlir::arith::DivSIOp) 1134 GENBIN(Divide, Real, mlir::arith::DivFOp) 1135 GENBIN(Divide, Complex, fir::DivcOp) 1136 1137 template <Fortran::common::TypeCategory TC, int KIND> 1138 ExtValue genval( 1139 const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &op) { 1140 mlir::Type ty = converter.genType(TC, KIND); 1141 mlir::Value lhs = genunbox(op.left()); 1142 mlir::Value rhs = genunbox(op.right()); 1143 return Fortran::lower::genPow(builder, getLoc(), ty, lhs, rhs); 1144 } 1145 1146 template <Fortran::common::TypeCategory TC, int KIND> 1147 ExtValue genval( 1148 const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>> 1149 &op) { 1150 mlir::Type ty = converter.genType(TC, KIND); 1151 mlir::Value lhs = genunbox(op.left()); 1152 mlir::Value rhs = genunbox(op.right()); 1153 return Fortran::lower::genPow(builder, getLoc(), ty, lhs, rhs); 1154 } 1155 1156 template <int KIND> 1157 ExtValue genval(const Fortran::evaluate::ComplexConstructor<KIND> &op) { 1158 mlir::Value realPartValue = genunbox(op.left()); 1159 return fir::factory::Complex{builder, getLoc()}.createComplex( 1160 KIND, realPartValue, genunbox(op.right())); 1161 } 1162 1163 template <int KIND> 1164 ExtValue genval(const Fortran::evaluate::Concat<KIND> &op) { 1165 ExtValue lhs = genval(op.left()); 1166 ExtValue rhs = genval(op.right()); 1167 const fir::CharBoxValue *lhsChar = lhs.getCharBox(); 1168 const fir::CharBoxValue *rhsChar = rhs.getCharBox(); 1169 if (lhsChar && rhsChar) 1170 return fir::factory::CharacterExprHelper{builder, getLoc()} 1171 .createConcatenate(*lhsChar, *rhsChar); 1172 TODO(getLoc(), "character array concatenate"); 1173 } 1174 1175 /// MIN and MAX operations 1176 template <Fortran::common::TypeCategory TC, int KIND> 1177 ExtValue 1178 genval(const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>> 1179 &op) { 1180 mlir::Value lhs = genunbox(op.left()); 1181 mlir::Value rhs = genunbox(op.right()); 1182 switch (op.ordering) { 1183 case Fortran::evaluate::Ordering::Greater: 1184 return Fortran::lower::genMax(builder, getLoc(), 1185 llvm::ArrayRef<mlir::Value>{lhs, rhs}); 1186 case Fortran::evaluate::Ordering::Less: 1187 return Fortran::lower::genMin(builder, getLoc(), 1188 llvm::ArrayRef<mlir::Value>{lhs, rhs}); 1189 case Fortran::evaluate::Ordering::Equal: 1190 llvm_unreachable("Equal is not a valid ordering in this context"); 1191 } 1192 llvm_unreachable("unknown ordering"); 1193 } 1194 1195 // Change the dynamic length information without actually changing the 1196 // underlying character storage. 1197 fir::ExtendedValue 1198 replaceScalarCharacterLength(const fir::ExtendedValue &scalarChar, 1199 mlir::Value newLenValue) { 1200 mlir::Location loc = getLoc(); 1201 const fir::CharBoxValue *charBox = scalarChar.getCharBox(); 1202 if (!charBox) 1203 fir::emitFatalError(loc, "expected scalar character"); 1204 mlir::Value charAddr = charBox->getAddr(); 1205 auto charType = 1206 fir::unwrapPassByRefType(charAddr.getType()).cast<fir::CharacterType>(); 1207 if (charType.hasConstantLen()) { 1208 // Erase previous constant length from the base type. 1209 fir::CharacterType::LenType newLen = fir::CharacterType::unknownLen(); 1210 mlir::Type newCharTy = fir::CharacterType::get( 1211 builder.getContext(), charType.getFKind(), newLen); 1212 mlir::Type newType = fir::ReferenceType::get(newCharTy); 1213 charAddr = builder.createConvert(loc, newType, charAddr); 1214 return fir::CharBoxValue{charAddr, newLenValue}; 1215 } 1216 return fir::CharBoxValue{charAddr, newLenValue}; 1217 } 1218 1219 template <int KIND> 1220 ExtValue genval(const Fortran::evaluate::SetLength<KIND> &x) { 1221 mlir::Value newLenValue = genunbox(x.right()); 1222 fir::ExtendedValue lhs = gen(x.left()); 1223 return replaceScalarCharacterLength(lhs, newLenValue); 1224 } 1225 1226 template <int KIND> 1227 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 1228 Fortran::common::TypeCategory::Integer, KIND>> &op) { 1229 return createCompareOp<mlir::arith::CmpIOp>(op, 1230 translateRelational(op.opr)); 1231 } 1232 template <int KIND> 1233 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 1234 Fortran::common::TypeCategory::Real, KIND>> &op) { 1235 return createFltCmpOp<mlir::arith::CmpFOp>( 1236 op, translateFloatRelational(op.opr)); 1237 } 1238 template <int KIND> 1239 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 1240 Fortran::common::TypeCategory::Complex, KIND>> &op) { 1241 return createFltCmpOp<fir::CmpcOp>(op, translateFloatRelational(op.opr)); 1242 } 1243 template <int KIND> 1244 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 1245 Fortran::common::TypeCategory::Character, KIND>> &op) { 1246 return createCharCompare(op, translateRelational(op.opr)); 1247 } 1248 1249 ExtValue 1250 genval(const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &op) { 1251 return std::visit([&](const auto &x) { return genval(x); }, op.u); 1252 } 1253 1254 template <Fortran::common::TypeCategory TC1, int KIND, 1255 Fortran::common::TypeCategory TC2> 1256 ExtValue 1257 genval(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>, 1258 TC2> &convert) { 1259 mlir::Type ty = converter.genType(TC1, KIND); 1260 auto fromExpr = genval(convert.left()); 1261 auto loc = getLoc(); 1262 return fromExpr.match( 1263 [&](const fir::CharBoxValue &boxchar) -> ExtValue { 1264 if constexpr (TC1 == Fortran::common::TypeCategory::Character && 1265 TC2 == TC1) { 1266 // Use char_convert. Each code point is translated from a 1267 // narrower/wider encoding to the target encoding. For example, 'A' 1268 // may be translated from 0x41 : i8 to 0x0041 : i16. The symbol 1269 // for euro (0x20AC : i16) may be translated from a wide character 1270 // to "0xE2 0x82 0xAC" : UTF-8. 1271 mlir::Value bufferSize = boxchar.getLen(); 1272 auto kindMap = builder.getKindMap(); 1273 auto fromBits = kindMap.getCharacterBitsize( 1274 fir::unwrapRefType(boxchar.getAddr().getType()) 1275 .cast<fir::CharacterType>() 1276 .getFKind()); 1277 auto toBits = kindMap.getCharacterBitsize( 1278 ty.cast<fir::CharacterType>().getFKind()); 1279 if (toBits < fromBits) { 1280 // Scale by relative ratio to give a buffer of the same length. 1281 auto ratio = builder.createIntegerConstant( 1282 loc, bufferSize.getType(), fromBits / toBits); 1283 bufferSize = 1284 builder.create<mlir::arith::MulIOp>(loc, bufferSize, ratio); 1285 } 1286 auto dest = builder.create<fir::AllocaOp>( 1287 loc, ty, mlir::ValueRange{bufferSize}); 1288 builder.create<fir::CharConvertOp>(loc, boxchar.getAddr(), 1289 boxchar.getLen(), dest); 1290 return fir::CharBoxValue{dest, boxchar.getLen()}; 1291 } else { 1292 fir::emitFatalError( 1293 loc, "unsupported evaluate::Convert between CHARACTER type " 1294 "category and non-CHARACTER category"); 1295 } 1296 }, 1297 [&](const fir::UnboxedValue &value) -> ExtValue { 1298 return builder.convertWithSemantics(loc, ty, value); 1299 }, 1300 [&](auto &) -> ExtValue { 1301 fir::emitFatalError(loc, "unsupported evaluate::Convert"); 1302 }); 1303 } 1304 1305 template <typename A> 1306 ExtValue genval(const Fortran::evaluate::Parentheses<A> &op) { 1307 ExtValue input = genval(op.left()); 1308 mlir::Value base = fir::getBase(input); 1309 mlir::Value newBase = 1310 builder.create<fir::NoReassocOp>(getLoc(), base.getType(), base); 1311 return fir::substBase(input, newBase); 1312 } 1313 1314 template <int KIND> 1315 ExtValue genval(const Fortran::evaluate::Not<KIND> &op) { 1316 mlir::Value logical = genunbox(op.left()); 1317 mlir::Value one = genBoolConstant(true); 1318 mlir::Value val = 1319 builder.createConvert(getLoc(), builder.getI1Type(), logical); 1320 return builder.create<mlir::arith::XOrIOp>(getLoc(), val, one); 1321 } 1322 1323 template <int KIND> 1324 ExtValue genval(const Fortran::evaluate::LogicalOperation<KIND> &op) { 1325 mlir::IntegerType i1Type = builder.getI1Type(); 1326 mlir::Value slhs = genunbox(op.left()); 1327 mlir::Value srhs = genunbox(op.right()); 1328 mlir::Value lhs = builder.createConvert(getLoc(), i1Type, slhs); 1329 mlir::Value rhs = builder.createConvert(getLoc(), i1Type, srhs); 1330 switch (op.logicalOperator) { 1331 case Fortran::evaluate::LogicalOperator::And: 1332 return createBinaryOp<mlir::arith::AndIOp>(lhs, rhs); 1333 case Fortran::evaluate::LogicalOperator::Or: 1334 return createBinaryOp<mlir::arith::OrIOp>(lhs, rhs); 1335 case Fortran::evaluate::LogicalOperator::Eqv: 1336 return createCompareOp<mlir::arith::CmpIOp>( 1337 mlir::arith::CmpIPredicate::eq, lhs, rhs); 1338 case Fortran::evaluate::LogicalOperator::Neqv: 1339 return createCompareOp<mlir::arith::CmpIOp>( 1340 mlir::arith::CmpIPredicate::ne, lhs, rhs); 1341 case Fortran::evaluate::LogicalOperator::Not: 1342 // lib/evaluate expression for .NOT. is Fortran::evaluate::Not<KIND>. 1343 llvm_unreachable(".NOT. is not a binary operator"); 1344 } 1345 llvm_unreachable("unhandled logical operation"); 1346 } 1347 1348 /// Convert a scalar literal constant to IR. 1349 template <Fortran::common::TypeCategory TC, int KIND> 1350 ExtValue genScalarLit( 1351 const Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>> 1352 &value) { 1353 if constexpr (TC == Fortran::common::TypeCategory::Integer) { 1354 return genIntegerConstant<KIND>(builder.getContext(), value.ToInt64()); 1355 } else if constexpr (TC == Fortran::common::TypeCategory::Logical) { 1356 return genBoolConstant(value.IsTrue()); 1357 } else if constexpr (TC == Fortran::common::TypeCategory::Real) { 1358 std::string str = value.DumpHexadecimal(); 1359 if constexpr (KIND == 2) { 1360 llvm::APFloat floatVal{llvm::APFloatBase::IEEEhalf(), str}; 1361 return genRealConstant<KIND>(builder.getContext(), floatVal); 1362 } else if constexpr (KIND == 3) { 1363 llvm::APFloat floatVal{llvm::APFloatBase::BFloat(), str}; 1364 return genRealConstant<KIND>(builder.getContext(), floatVal); 1365 } else if constexpr (KIND == 4) { 1366 llvm::APFloat floatVal{llvm::APFloatBase::IEEEsingle(), str}; 1367 return genRealConstant<KIND>(builder.getContext(), floatVal); 1368 } else if constexpr (KIND == 10) { 1369 llvm::APFloat floatVal{llvm::APFloatBase::x87DoubleExtended(), str}; 1370 return genRealConstant<KIND>(builder.getContext(), floatVal); 1371 } else if constexpr (KIND == 16) { 1372 llvm::APFloat floatVal{llvm::APFloatBase::IEEEquad(), str}; 1373 return genRealConstant<KIND>(builder.getContext(), floatVal); 1374 } else { 1375 // convert everything else to double 1376 llvm::APFloat floatVal{llvm::APFloatBase::IEEEdouble(), str}; 1377 return genRealConstant<KIND>(builder.getContext(), floatVal); 1378 } 1379 } else if constexpr (TC == Fortran::common::TypeCategory::Complex) { 1380 using TR = 1381 Fortran::evaluate::Type<Fortran::common::TypeCategory::Real, KIND>; 1382 Fortran::evaluate::ComplexConstructor<KIND> ctor( 1383 Fortran::evaluate::Expr<TR>{ 1384 Fortran::evaluate::Constant<TR>{value.REAL()}}, 1385 Fortran::evaluate::Expr<TR>{ 1386 Fortran::evaluate::Constant<TR>{value.AIMAG()}}); 1387 return genunbox(ctor); 1388 } else /*constexpr*/ { 1389 llvm_unreachable("unhandled constant"); 1390 } 1391 } 1392 1393 /// Generate a raw literal value and store it in the rawVals vector. 1394 template <Fortran::common::TypeCategory TC, int KIND> 1395 void 1396 genRawLit(const Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>> 1397 &value) { 1398 mlir::Attribute val; 1399 assert(inInitializer != nullptr); 1400 if constexpr (TC == Fortran::common::TypeCategory::Integer) { 1401 inInitializer->rawType = converter.genType(TC, KIND); 1402 val = builder.getIntegerAttr(inInitializer->rawType, value.ToInt64()); 1403 } else if constexpr (TC == Fortran::common::TypeCategory::Logical) { 1404 inInitializer->rawType = 1405 converter.genType(Fortran::common::TypeCategory::Integer, KIND); 1406 val = builder.getIntegerAttr(inInitializer->rawType, value.IsTrue()); 1407 } else if constexpr (TC == Fortran::common::TypeCategory::Real) { 1408 std::string str = value.DumpHexadecimal(); 1409 inInitializer->rawType = converter.genType(TC, KIND); 1410 llvm::APFloat floatVal{builder.getKindMap().getFloatSemantics(KIND), str}; 1411 val = builder.getFloatAttr(inInitializer->rawType, floatVal); 1412 } else if constexpr (TC == Fortran::common::TypeCategory::Complex) { 1413 std::string strReal = value.REAL().DumpHexadecimal(); 1414 std::string strImg = value.AIMAG().DumpHexadecimal(); 1415 inInitializer->rawType = converter.genType(TC, KIND); 1416 llvm::APFloat realVal{builder.getKindMap().getFloatSemantics(KIND), 1417 strReal}; 1418 val = builder.getFloatAttr(inInitializer->rawType, realVal); 1419 inInitializer->rawVals.push_back(val); 1420 llvm::APFloat imgVal{builder.getKindMap().getFloatSemantics(KIND), 1421 strImg}; 1422 val = builder.getFloatAttr(inInitializer->rawType, imgVal); 1423 } 1424 inInitializer->rawVals.push_back(val); 1425 } 1426 1427 /// Convert a scalar literal CHARACTER to IR. 1428 template <int KIND> 1429 ExtValue 1430 genScalarLit(const Fortran::evaluate::Scalar<Fortran::evaluate::Type< 1431 Fortran::common::TypeCategory::Character, KIND>> &value, 1432 int64_t len) { 1433 using ET = typename std::decay_t<decltype(value)>::value_type; 1434 if constexpr (KIND == 1) { 1435 assert(value.size() == static_cast<std::uint64_t>(len)); 1436 // Outline character constant in ro data if it is not in an initializer. 1437 if (!inInitializer) 1438 return fir::factory::createStringLiteral(builder, getLoc(), value); 1439 // When in an initializer context, construct the literal op itself and do 1440 // not construct another constant object in rodata. 1441 fir::StringLitOp stringLit = builder.createStringLitOp(getLoc(), value); 1442 mlir::Value lenp = builder.createIntegerConstant( 1443 getLoc(), builder.getCharacterLengthType(), len); 1444 return fir::CharBoxValue{stringLit.getResult(), lenp}; 1445 } 1446 fir::CharacterType type = 1447 fir::CharacterType::get(builder.getContext(), KIND, len); 1448 auto consLit = [&]() -> fir::StringLitOp { 1449 mlir::MLIRContext *context = builder.getContext(); 1450 std::int64_t size = static_cast<std::int64_t>(value.size()); 1451 mlir::ShapedType shape = mlir::RankedTensorType::get( 1452 llvm::ArrayRef<std::int64_t>{size}, 1453 mlir::IntegerType::get(builder.getContext(), sizeof(ET) * 8)); 1454 auto denseAttr = mlir::DenseElementsAttr::get( 1455 shape, llvm::ArrayRef<ET>{value.data(), value.size()}); 1456 auto denseTag = mlir::StringAttr::get(context, fir::StringLitOp::xlist()); 1457 mlir::NamedAttribute dataAttr(denseTag, denseAttr); 1458 auto sizeTag = mlir::StringAttr::get(context, fir::StringLitOp::size()); 1459 mlir::NamedAttribute sizeAttr(sizeTag, builder.getI64IntegerAttr(len)); 1460 llvm::SmallVector<mlir::NamedAttribute> attrs = {dataAttr, sizeAttr}; 1461 return builder.create<fir::StringLitOp>( 1462 getLoc(), llvm::ArrayRef<mlir::Type>{type}, llvm::None, attrs); 1463 }; 1464 1465 mlir::Value lenp = builder.createIntegerConstant( 1466 getLoc(), builder.getCharacterLengthType(), len); 1467 // When in an initializer context, construct the literal op itself and do 1468 // not construct another constant object in rodata. 1469 if (inInitializer) 1470 return fir::CharBoxValue{consLit().getResult(), lenp}; 1471 1472 // Otherwise, the string is in a plain old expression so "outline" the value 1473 // by hashconsing it to a constant literal object. 1474 1475 std::string globalName = 1476 fir::factory::uniqueCGIdent("cl", (const char *)value.c_str()); 1477 fir::GlobalOp global = builder.getNamedGlobal(globalName); 1478 if (!global) 1479 global = builder.createGlobalConstant( 1480 getLoc(), type, globalName, 1481 [&](fir::FirOpBuilder &builder) { 1482 fir::StringLitOp str = consLit(); 1483 builder.create<fir::HasValueOp>(getLoc(), str); 1484 }, 1485 builder.createLinkOnceLinkage()); 1486 auto addr = builder.create<fir::AddrOfOp>(getLoc(), global.resultType(), 1487 global.getSymbol()); 1488 return fir::CharBoxValue{addr, lenp}; 1489 } 1490 1491 template <Fortran::common::TypeCategory TC, int KIND> 1492 ExtValue genArrayLit( 1493 const Fortran::evaluate::Constant<Fortran::evaluate::Type<TC, KIND>> 1494 &con) { 1495 mlir::Location loc = getLoc(); 1496 mlir::IndexType idxTy = builder.getIndexType(); 1497 Fortran::evaluate::ConstantSubscript size = 1498 Fortran::evaluate::GetSize(con.shape()); 1499 fir::SequenceType::Shape shape(con.shape().begin(), con.shape().end()); 1500 mlir::Type eleTy; 1501 if constexpr (TC == Fortran::common::TypeCategory::Character) 1502 eleTy = converter.genType(TC, KIND, {con.LEN()}); 1503 else 1504 eleTy = converter.genType(TC, KIND); 1505 auto arrayTy = fir::SequenceType::get(shape, eleTy); 1506 mlir::Value array; 1507 llvm::SmallVector<mlir::Value> lbounds; 1508 llvm::SmallVector<mlir::Value> extents; 1509 if (!inInitializer || !inInitializer->genRawVals) { 1510 array = builder.create<fir::UndefOp>(loc, arrayTy); 1511 for (auto [lb, extent] : llvm::zip(con.lbounds(), shape)) { 1512 lbounds.push_back(builder.createIntegerConstant(loc, idxTy, lb - 1)); 1513 extents.push_back(builder.createIntegerConstant(loc, idxTy, extent)); 1514 } 1515 } 1516 if (size == 0) { 1517 if constexpr (TC == Fortran::common::TypeCategory::Character) { 1518 mlir::Value len = builder.createIntegerConstant(loc, idxTy, con.LEN()); 1519 return fir::CharArrayBoxValue{array, len, extents, lbounds}; 1520 } else { 1521 return fir::ArrayBoxValue{array, extents, lbounds}; 1522 } 1523 } 1524 Fortran::evaluate::ConstantSubscripts subscripts = con.lbounds(); 1525 auto createIdx = [&]() { 1526 llvm::SmallVector<mlir::Attribute> idx; 1527 for (size_t i = 0; i < subscripts.size(); ++i) 1528 idx.push_back( 1529 builder.getIntegerAttr(idxTy, subscripts[i] - con.lbounds()[i])); 1530 return idx; 1531 }; 1532 if constexpr (TC == Fortran::common::TypeCategory::Character) { 1533 assert(array && "array must not be nullptr"); 1534 do { 1535 mlir::Value elementVal = 1536 fir::getBase(genScalarLit<KIND>(con.At(subscripts), con.LEN())); 1537 array = builder.create<fir::InsertValueOp>( 1538 loc, arrayTy, array, elementVal, builder.getArrayAttr(createIdx())); 1539 } while (con.IncrementSubscripts(subscripts)); 1540 mlir::Value len = builder.createIntegerConstant(loc, idxTy, con.LEN()); 1541 return fir::CharArrayBoxValue{array, len, extents, lbounds}; 1542 } else { 1543 llvm::SmallVector<mlir::Attribute> rangeStartIdx; 1544 uint64_t rangeSize = 0; 1545 do { 1546 if (inInitializer && inInitializer->genRawVals) { 1547 genRawLit<TC, KIND>(con.At(subscripts)); 1548 continue; 1549 } 1550 auto getElementVal = [&]() { 1551 return builder.createConvert( 1552 loc, eleTy, 1553 fir::getBase(genScalarLit<TC, KIND>(con.At(subscripts)))); 1554 }; 1555 Fortran::evaluate::ConstantSubscripts nextSubscripts = subscripts; 1556 bool nextIsSame = con.IncrementSubscripts(nextSubscripts) && 1557 con.At(subscripts) == con.At(nextSubscripts); 1558 if (!rangeSize && !nextIsSame) { // single (non-range) value 1559 array = builder.create<fir::InsertValueOp>( 1560 loc, arrayTy, array, getElementVal(), 1561 builder.getArrayAttr(createIdx())); 1562 } else if (!rangeSize) { // start a range 1563 rangeStartIdx = createIdx(); 1564 rangeSize = 1; 1565 } else if (nextIsSame) { // expand a range 1566 ++rangeSize; 1567 } else { // end a range 1568 llvm::SmallVector<int64_t> rangeBounds; 1569 llvm::SmallVector<mlir::Attribute> idx = createIdx(); 1570 for (size_t i = 0; i < idx.size(); ++i) { 1571 rangeBounds.push_back(rangeStartIdx[i] 1572 .cast<mlir::IntegerAttr>() 1573 .getValue() 1574 .getSExtValue()); 1575 rangeBounds.push_back( 1576 idx[i].cast<mlir::IntegerAttr>().getValue().getSExtValue()); 1577 } 1578 array = builder.create<fir::InsertOnRangeOp>( 1579 loc, arrayTy, array, getElementVal(), 1580 builder.getIndexVectorAttr(rangeBounds)); 1581 rangeSize = 0; 1582 } 1583 } while (con.IncrementSubscripts(subscripts)); 1584 return fir::ArrayBoxValue{array, extents, lbounds}; 1585 } 1586 } 1587 1588 fir::ExtendedValue genArrayLit( 1589 const Fortran::evaluate::Constant<Fortran::evaluate::SomeDerived> &con) { 1590 mlir::Location loc = getLoc(); 1591 mlir::IndexType idxTy = builder.getIndexType(); 1592 Fortran::evaluate::ConstantSubscript size = 1593 Fortran::evaluate::GetSize(con.shape()); 1594 fir::SequenceType::Shape shape(con.shape().begin(), con.shape().end()); 1595 mlir::Type eleTy = converter.genType(con.GetType().GetDerivedTypeSpec()); 1596 auto arrayTy = fir::SequenceType::get(shape, eleTy); 1597 mlir::Value array = builder.create<fir::UndefOp>(loc, arrayTy); 1598 llvm::SmallVector<mlir::Value> lbounds; 1599 llvm::SmallVector<mlir::Value> extents; 1600 for (auto [lb, extent] : llvm::zip(con.lbounds(), con.shape())) { 1601 lbounds.push_back(builder.createIntegerConstant(loc, idxTy, lb - 1)); 1602 extents.push_back(builder.createIntegerConstant(loc, idxTy, extent)); 1603 } 1604 if (size == 0) 1605 return fir::ArrayBoxValue{array, extents, lbounds}; 1606 Fortran::evaluate::ConstantSubscripts subscripts = con.lbounds(); 1607 do { 1608 mlir::Value derivedVal = fir::getBase(genval(con.At(subscripts))); 1609 llvm::SmallVector<mlir::Attribute> idx; 1610 for (auto [dim, lb] : llvm::zip(subscripts, con.lbounds())) 1611 idx.push_back(builder.getIntegerAttr(idxTy, dim - lb)); 1612 array = builder.create<fir::InsertValueOp>( 1613 loc, arrayTy, array, derivedVal, builder.getArrayAttr(idx)); 1614 } while (con.IncrementSubscripts(subscripts)); 1615 return fir::ArrayBoxValue{array, extents, lbounds}; 1616 } 1617 1618 template <Fortran::common::TypeCategory TC, int KIND> 1619 ExtValue 1620 genval(const Fortran::evaluate::Constant<Fortran::evaluate::Type<TC, KIND>> 1621 &con) { 1622 if (con.Rank() > 0) 1623 return genArrayLit(con); 1624 std::optional<Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>>> 1625 opt = con.GetScalarValue(); 1626 assert(opt.has_value() && "constant has no value"); 1627 if constexpr (TC == Fortran::common::TypeCategory::Character) { 1628 return genScalarLit<KIND>(opt.value(), con.LEN()); 1629 } else { 1630 return genScalarLit<TC, KIND>(opt.value()); 1631 } 1632 } 1633 fir::ExtendedValue genval( 1634 const Fortran::evaluate::Constant<Fortran::evaluate::SomeDerived> &con) { 1635 if (con.Rank() > 0) 1636 return genArrayLit(con); 1637 if (auto ctor = con.GetScalarValue()) 1638 return genval(ctor.value()); 1639 fir::emitFatalError(getLoc(), 1640 "constant of derived type has no constructor"); 1641 } 1642 1643 template <typename A> 1644 ExtValue genval(const Fortran::evaluate::ArrayConstructor<A> &) { 1645 fir::emitFatalError(getLoc(), 1646 "array constructor: lowering should not reach here"); 1647 } 1648 1649 ExtValue gen(const Fortran::evaluate::ComplexPart &x) { 1650 mlir::Location loc = getLoc(); 1651 auto idxTy = builder.getI32Type(); 1652 ExtValue exv = gen(x.complex()); 1653 mlir::Value base = fir::getBase(exv); 1654 fir::factory::Complex helper{builder, loc}; 1655 mlir::Type eleTy = 1656 helper.getComplexPartType(fir::dyn_cast_ptrEleTy(base.getType())); 1657 mlir::Value offset = builder.createIntegerConstant( 1658 loc, idxTy, 1659 x.part() == Fortran::evaluate::ComplexPart::Part::RE ? 0 : 1); 1660 mlir::Value result = builder.create<fir::CoordinateOp>( 1661 loc, builder.getRefType(eleTy), base, mlir::ValueRange{offset}); 1662 return {result}; 1663 } 1664 ExtValue genval(const Fortran::evaluate::ComplexPart &x) { 1665 return genLoad(gen(x)); 1666 } 1667 1668 /// Reference to a substring. 1669 ExtValue gen(const Fortran::evaluate::Substring &s) { 1670 // Get base string 1671 auto baseString = std::visit( 1672 Fortran::common::visitors{ 1673 [&](const Fortran::evaluate::DataRef &x) { return gen(x); }, 1674 [&](const Fortran::evaluate::StaticDataObject::Pointer &p) 1675 -> ExtValue { 1676 if (std::optional<std::string> str = p->AsString()) 1677 return fir::factory::createStringLiteral(builder, getLoc(), 1678 *str); 1679 // TODO: convert StaticDataObject to Constant<T> and use normal 1680 // constant path. Beware that StaticDataObject data() takes into 1681 // account build machine endianness. 1682 TODO(getLoc(), 1683 "StaticDataObject::Pointer substring with kind > 1"); 1684 }, 1685 }, 1686 s.parent()); 1687 llvm::SmallVector<mlir::Value> bounds; 1688 mlir::Value lower = genunbox(s.lower()); 1689 bounds.push_back(lower); 1690 if (Fortran::evaluate::MaybeExtentExpr upperBound = s.upper()) { 1691 mlir::Value upper = genunbox(*upperBound); 1692 bounds.push_back(upper); 1693 } 1694 fir::factory::CharacterExprHelper charHelper{builder, getLoc()}; 1695 return baseString.match( 1696 [&](const fir::CharBoxValue &x) -> ExtValue { 1697 return charHelper.createSubstring(x, bounds); 1698 }, 1699 [&](const fir::CharArrayBoxValue &) -> ExtValue { 1700 fir::emitFatalError( 1701 getLoc(), 1702 "array substring should be handled in array expression"); 1703 }, 1704 [&](const auto &) -> ExtValue { 1705 fir::emitFatalError(getLoc(), "substring base is not a CharBox"); 1706 }); 1707 } 1708 1709 /// The value of a substring. 1710 ExtValue genval(const Fortran::evaluate::Substring &ss) { 1711 // FIXME: why is the value of a substring being lowered the same as the 1712 // address of a substring? 1713 return gen(ss); 1714 } 1715 1716 ExtValue genval(const Fortran::evaluate::Subscript &subs) { 1717 if (auto *s = std::get_if<Fortran::evaluate::IndirectSubscriptIntegerExpr>( 1718 &subs.u)) { 1719 if (s->value().Rank() > 0) 1720 fir::emitFatalError(getLoc(), "vector subscript is not scalar"); 1721 return {genval(s->value())}; 1722 } 1723 fir::emitFatalError(getLoc(), "subscript triple notation is not scalar"); 1724 } 1725 ExtValue genSubscript(const Fortran::evaluate::Subscript &subs) { 1726 return genval(subs); 1727 } 1728 1729 ExtValue gen(const Fortran::evaluate::DataRef &dref) { 1730 return std::visit([&](const auto &x) { return gen(x); }, dref.u); 1731 } 1732 ExtValue genval(const Fortran::evaluate::DataRef &dref) { 1733 return std::visit([&](const auto &x) { return genval(x); }, dref.u); 1734 } 1735 1736 // Helper function to turn the Component structure into a list of nested 1737 // components, ordered from largest/leftmost to smallest/rightmost: 1738 // - where only the smallest/rightmost item may be allocatable or a pointer 1739 // (nested allocatable/pointer components require nested coordinate_of ops) 1740 // - that does not contain any parent components 1741 // (the front end places parent components directly in the object) 1742 // Return the object used as the base coordinate for the component chain. 1743 static Fortran::evaluate::DataRef const * 1744 reverseComponents(const Fortran::evaluate::Component &cmpt, 1745 std::list<const Fortran::evaluate::Component *> &list) { 1746 if (!getLastSym(cmpt).test(Fortran::semantics::Symbol::Flag::ParentComp)) 1747 list.push_front(&cmpt); 1748 return std::visit( 1749 Fortran::common::visitors{ 1750 [&](const Fortran::evaluate::Component &x) { 1751 if (Fortran::semantics::IsAllocatableOrPointer(getLastSym(x))) 1752 return &cmpt.base(); 1753 return reverseComponents(x, list); 1754 }, 1755 [&](auto &) { return &cmpt.base(); }, 1756 }, 1757 cmpt.base().u); 1758 } 1759 1760 // Return the coordinate of the component reference 1761 ExtValue genComponent(const Fortran::evaluate::Component &cmpt) { 1762 std::list<const Fortran::evaluate::Component *> list; 1763 const Fortran::evaluate::DataRef *base = reverseComponents(cmpt, list); 1764 llvm::SmallVector<mlir::Value> coorArgs; 1765 ExtValue obj = gen(*base); 1766 mlir::Type ty = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(obj).getType()); 1767 mlir::Location loc = getLoc(); 1768 auto fldTy = fir::FieldType::get(&converter.getMLIRContext()); 1769 // FIXME: need to thread the LEN type parameters here. 1770 for (const Fortran::evaluate::Component *field : list) { 1771 auto recTy = ty.cast<fir::RecordType>(); 1772 const Fortran::semantics::Symbol &sym = getLastSym(*field); 1773 llvm::StringRef name = toStringRef(sym.name()); 1774 coorArgs.push_back(builder.create<fir::FieldIndexOp>( 1775 loc, fldTy, name, recTy, fir::getTypeParams(obj))); 1776 ty = recTy.getType(name); 1777 } 1778 ty = builder.getRefType(ty); 1779 return fir::factory::componentToExtendedValue( 1780 builder, loc, 1781 builder.create<fir::CoordinateOp>(loc, ty, fir::getBase(obj), 1782 coorArgs)); 1783 } 1784 1785 ExtValue gen(const Fortran::evaluate::Component &cmpt) { 1786 // Components may be pointer or allocatable. In the gen() path, the mutable 1787 // aspect is lost to simplify handling on the client side. To retain the 1788 // mutable aspect, genMutableBoxValue should be used. 1789 return genComponent(cmpt).match( 1790 [&](const fir::MutableBoxValue &mutableBox) { 1791 return fir::factory::genMutableBoxRead(builder, getLoc(), mutableBox); 1792 }, 1793 [](auto &box) -> ExtValue { return box; }); 1794 } 1795 1796 ExtValue genval(const Fortran::evaluate::Component &cmpt) { 1797 return genLoad(gen(cmpt)); 1798 } 1799 1800 // Determine the result type after removing `dims` dimensions from the array 1801 // type `arrTy` 1802 mlir::Type genSubType(mlir::Type arrTy, unsigned dims) { 1803 mlir::Type unwrapTy = fir::dyn_cast_ptrOrBoxEleTy(arrTy); 1804 assert(unwrapTy && "must be a pointer or box type"); 1805 auto seqTy = unwrapTy.cast<fir::SequenceType>(); 1806 llvm::ArrayRef<int64_t> shape = seqTy.getShape(); 1807 assert(shape.size() > 0 && "removing columns for sequence sans shape"); 1808 assert(dims <= shape.size() && "removing more columns than exist"); 1809 fir::SequenceType::Shape newBnds; 1810 // follow Fortran semantics and remove columns (from right) 1811 std::size_t e = shape.size() - dims; 1812 for (decltype(e) i = 0; i < e; ++i) 1813 newBnds.push_back(shape[i]); 1814 if (!newBnds.empty()) 1815 return fir::SequenceType::get(newBnds, seqTy.getEleTy()); 1816 return seqTy.getEleTy(); 1817 } 1818 1819 // Generate the code for a Bound value. 1820 ExtValue genval(const Fortran::semantics::Bound &bound) { 1821 if (bound.isExplicit()) { 1822 Fortran::semantics::MaybeSubscriptIntExpr sub = bound.GetExplicit(); 1823 if (sub.has_value()) 1824 return genval(*sub); 1825 return genIntegerConstant<8>(builder.getContext(), 1); 1826 } 1827 TODO(getLoc(), "non explicit semantics::Bound lowering"); 1828 } 1829 1830 static bool isSlice(const Fortran::evaluate::ArrayRef &aref) { 1831 for (const Fortran::evaluate::Subscript &sub : aref.subscript()) 1832 if (std::holds_alternative<Fortran::evaluate::Triplet>(sub.u)) 1833 return true; 1834 return false; 1835 } 1836 1837 /// Lower an ArrayRef to a fir.coordinate_of given its lowered base. 1838 ExtValue genCoordinateOp(const ExtValue &array, 1839 const Fortran::evaluate::ArrayRef &aref) { 1840 mlir::Location loc = getLoc(); 1841 // References to array of rank > 1 with non constant shape that are not 1842 // fir.box must be collapsed into an offset computation in lowering already. 1843 // The same is needed with dynamic length character arrays of all ranks. 1844 mlir::Type baseType = 1845 fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(array).getType()); 1846 if ((array.rank() > 1 && fir::hasDynamicSize(baseType)) || 1847 fir::characterWithDynamicLen(fir::unwrapSequenceType(baseType))) 1848 if (!array.getBoxOf<fir::BoxValue>()) 1849 return genOffsetAndCoordinateOp(array, aref); 1850 // Generate a fir.coordinate_of with zero based array indexes. 1851 llvm::SmallVector<mlir::Value> args; 1852 for (const auto &subsc : llvm::enumerate(aref.subscript())) { 1853 ExtValue subVal = genSubscript(subsc.value()); 1854 assert(fir::isUnboxedValue(subVal) && "subscript must be simple scalar"); 1855 mlir::Value val = fir::getBase(subVal); 1856 mlir::Type ty = val.getType(); 1857 mlir::Value lb = getLBound(array, subsc.index(), ty); 1858 args.push_back(builder.create<mlir::arith::SubIOp>(loc, ty, val, lb)); 1859 } 1860 1861 mlir::Value base = fir::getBase(array); 1862 auto seqTy = 1863 fir::dyn_cast_ptrOrBoxEleTy(base.getType()).cast<fir::SequenceType>(); 1864 assert(args.size() == seqTy.getDimension()); 1865 mlir::Type ty = builder.getRefType(seqTy.getEleTy()); 1866 auto addr = builder.create<fir::CoordinateOp>(loc, ty, base, args); 1867 return fir::factory::arrayElementToExtendedValue(builder, loc, array, addr); 1868 } 1869 1870 /// Lower an ArrayRef to a fir.coordinate_of using an element offset instead 1871 /// of array indexes. 1872 /// This generates offset computation from the indexes and length parameters, 1873 /// and use the offset to access the element with a fir.coordinate_of. This 1874 /// must only be used if it is not possible to generate a normal 1875 /// fir.coordinate_of using array indexes (i.e. when the shape information is 1876 /// unavailable in the IR). 1877 ExtValue genOffsetAndCoordinateOp(const ExtValue &array, 1878 const Fortran::evaluate::ArrayRef &aref) { 1879 mlir::Location loc = getLoc(); 1880 mlir::Value addr = fir::getBase(array); 1881 mlir::Type arrTy = fir::dyn_cast_ptrEleTy(addr.getType()); 1882 auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); 1883 mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(eleTy)); 1884 mlir::Type refTy = builder.getRefType(eleTy); 1885 mlir::Value base = builder.createConvert(loc, seqTy, addr); 1886 mlir::IndexType idxTy = builder.getIndexType(); 1887 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1); 1888 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0); 1889 auto getLB = [&](const auto &arr, unsigned dim) -> mlir::Value { 1890 return arr.getLBounds().empty() ? one : arr.getLBounds()[dim]; 1891 }; 1892 auto genFullDim = [&](const auto &arr, mlir::Value delta) -> mlir::Value { 1893 mlir::Value total = zero; 1894 assert(arr.getExtents().size() == aref.subscript().size()); 1895 delta = builder.createConvert(loc, idxTy, delta); 1896 unsigned dim = 0; 1897 for (auto [ext, sub] : llvm::zip(arr.getExtents(), aref.subscript())) { 1898 ExtValue subVal = genSubscript(sub); 1899 assert(fir::isUnboxedValue(subVal)); 1900 mlir::Value val = 1901 builder.createConvert(loc, idxTy, fir::getBase(subVal)); 1902 mlir::Value lb = builder.createConvert(loc, idxTy, getLB(arr, dim)); 1903 mlir::Value diff = builder.create<mlir::arith::SubIOp>(loc, val, lb); 1904 mlir::Value prod = 1905 builder.create<mlir::arith::MulIOp>(loc, delta, diff); 1906 total = builder.create<mlir::arith::AddIOp>(loc, prod, total); 1907 if (ext) 1908 delta = builder.create<mlir::arith::MulIOp>(loc, delta, ext); 1909 ++dim; 1910 } 1911 mlir::Type origRefTy = refTy; 1912 if (fir::factory::CharacterExprHelper::isCharacterScalar(refTy)) { 1913 fir::CharacterType chTy = 1914 fir::factory::CharacterExprHelper::getCharacterType(refTy); 1915 if (fir::characterWithDynamicLen(chTy)) { 1916 mlir::MLIRContext *ctx = builder.getContext(); 1917 fir::KindTy kind = 1918 fir::factory::CharacterExprHelper::getCharacterKind(chTy); 1919 fir::CharacterType singleTy = 1920 fir::CharacterType::getSingleton(ctx, kind); 1921 refTy = builder.getRefType(singleTy); 1922 mlir::Type seqRefTy = 1923 builder.getRefType(builder.getVarLenSeqTy(singleTy)); 1924 base = builder.createConvert(loc, seqRefTy, base); 1925 } 1926 } 1927 auto coor = builder.create<fir::CoordinateOp>( 1928 loc, refTy, base, llvm::ArrayRef<mlir::Value>{total}); 1929 // Convert to expected, original type after address arithmetic. 1930 return builder.createConvert(loc, origRefTy, coor); 1931 }; 1932 return array.match( 1933 [&](const fir::ArrayBoxValue &arr) -> ExtValue { 1934 // FIXME: this check can be removed when slicing is implemented 1935 if (isSlice(aref)) 1936 fir::emitFatalError( 1937 getLoc(), 1938 "slice should be handled in array expression context"); 1939 return genFullDim(arr, one); 1940 }, 1941 [&](const fir::CharArrayBoxValue &arr) -> ExtValue { 1942 mlir::Value delta = arr.getLen(); 1943 // If the length is known in the type, fir.coordinate_of will 1944 // already take the length into account. 1945 if (fir::factory::CharacterExprHelper::hasConstantLengthInType(arr)) 1946 delta = one; 1947 return fir::CharBoxValue(genFullDim(arr, delta), arr.getLen()); 1948 }, 1949 [&](const fir::BoxValue &arr) -> ExtValue { 1950 // CoordinateOp for BoxValue is not generated here. The dimensions 1951 // must be kept in the fir.coordinate_op so that potential fir.box 1952 // strides can be applied by codegen. 1953 fir::emitFatalError( 1954 loc, "internal: BoxValue in dim-collapsed fir.coordinate_of"); 1955 }, 1956 [&](const auto &) -> ExtValue { 1957 fir::emitFatalError(loc, "internal: array lowering failed"); 1958 }); 1959 } 1960 1961 /// Lower an ArrayRef to a fir.array_coor. 1962 ExtValue genArrayCoorOp(const ExtValue &exv, 1963 const Fortran::evaluate::ArrayRef &aref) { 1964 mlir::Location loc = getLoc(); 1965 mlir::Value addr = fir::getBase(exv); 1966 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType()); 1967 mlir::Type eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); 1968 mlir::Type refTy = builder.getRefType(eleTy); 1969 mlir::IndexType idxTy = builder.getIndexType(); 1970 llvm::SmallVector<mlir::Value> arrayCoorArgs; 1971 // The ArrayRef is expected to be scalar here, arrays are handled in array 1972 // expression lowering. So no vector subscript or triplet is expected here. 1973 for (const auto &sub : aref.subscript()) { 1974 ExtValue subVal = genSubscript(sub); 1975 assert(fir::isUnboxedValue(subVal)); 1976 arrayCoorArgs.push_back( 1977 builder.createConvert(loc, idxTy, fir::getBase(subVal))); 1978 } 1979 mlir::Value shape = builder.createShape(loc, exv); 1980 mlir::Value elementAddr = builder.create<fir::ArrayCoorOp>( 1981 loc, refTy, addr, shape, /*slice=*/mlir::Value{}, arrayCoorArgs, 1982 fir::getTypeParams(exv)); 1983 return fir::factory::arrayElementToExtendedValue(builder, loc, exv, 1984 elementAddr); 1985 } 1986 1987 /// Return the coordinate of the array reference. 1988 ExtValue gen(const Fortran::evaluate::ArrayRef &aref) { 1989 ExtValue base = aref.base().IsSymbol() ? gen(getFirstSym(aref.base())) 1990 : gen(aref.base().GetComponent()); 1991 // Check for command-line override to use array_coor op. 1992 if (generateArrayCoordinate) 1993 return genArrayCoorOp(base, aref); 1994 // Otherwise, use coordinate_of op. 1995 return genCoordinateOp(base, aref); 1996 } 1997 1998 /// Return lower bounds of \p box in dimension \p dim. The returned value 1999 /// has type \ty. 2000 mlir::Value getLBound(const ExtValue &box, unsigned dim, mlir::Type ty) { 2001 assert(box.rank() > 0 && "must be an array"); 2002 mlir::Location loc = getLoc(); 2003 mlir::Value one = builder.createIntegerConstant(loc, ty, 1); 2004 mlir::Value lb = fir::factory::readLowerBound(builder, loc, box, dim, one); 2005 return builder.createConvert(loc, ty, lb); 2006 } 2007 2008 ExtValue genval(const Fortran::evaluate::ArrayRef &aref) { 2009 return genLoad(gen(aref)); 2010 } 2011 2012 ExtValue gen(const Fortran::evaluate::CoarrayRef &coref) { 2013 return Fortran::lower::CoarrayExprHelper{converter, getLoc(), symMap} 2014 .genAddr(coref); 2015 } 2016 2017 ExtValue genval(const Fortran::evaluate::CoarrayRef &coref) { 2018 return Fortran::lower::CoarrayExprHelper{converter, getLoc(), symMap} 2019 .genValue(coref); 2020 } 2021 2022 template <typename A> 2023 ExtValue gen(const Fortran::evaluate::Designator<A> &des) { 2024 return std::visit([&](const auto &x) { return gen(x); }, des.u); 2025 } 2026 template <typename A> 2027 ExtValue genval(const Fortran::evaluate::Designator<A> &des) { 2028 return std::visit([&](const auto &x) { return genval(x); }, des.u); 2029 } 2030 2031 mlir::Type genType(const Fortran::evaluate::DynamicType &dt) { 2032 if (dt.category() != Fortran::common::TypeCategory::Derived) 2033 return converter.genType(dt.category(), dt.kind()); 2034 return converter.genType(dt.GetDerivedTypeSpec()); 2035 } 2036 2037 /// Lower a function reference 2038 template <typename A> 2039 ExtValue genFunctionRef(const Fortran::evaluate::FunctionRef<A> &funcRef) { 2040 if (!funcRef.GetType().has_value()) 2041 fir::emitFatalError(getLoc(), "a function must have a type"); 2042 mlir::Type resTy = genType(*funcRef.GetType()); 2043 return genProcedureRef(funcRef, {resTy}); 2044 } 2045 2046 /// Lower function call `funcRef` and return a reference to the resultant 2047 /// value. This is required for lowering expressions such as `f1(f2(v))`. 2048 template <typename A> 2049 ExtValue gen(const Fortran::evaluate::FunctionRef<A> &funcRef) { 2050 ExtValue retVal = genFunctionRef(funcRef); 2051 mlir::Type resultType = converter.genType(toEvExpr(funcRef)); 2052 return placeScalarValueInMemory(builder, getLoc(), retVal, resultType); 2053 } 2054 2055 /// Helper to lower intrinsic arguments for inquiry intrinsic. 2056 ExtValue 2057 lowerIntrinsicArgumentAsInquired(const Fortran::lower::SomeExpr &expr) { 2058 if (Fortran::evaluate::IsAllocatableOrPointerObject( 2059 expr, converter.getFoldingContext())) 2060 return genMutableBoxValue(expr); 2061 /// Do not create temps for array sections whose properties only need to be 2062 /// inquired: create a descriptor that will be inquired. 2063 if (Fortran::evaluate::IsVariable(expr) && isArray(expr) && 2064 !Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(expr)) 2065 return lowerIntrinsicArgumentAsBox(expr); 2066 return gen(expr); 2067 } 2068 2069 /// Helper to lower intrinsic arguments to a fir::BoxValue. 2070 /// It preserves all the non default lower bounds/non deferred length 2071 /// parameter information. 2072 ExtValue lowerIntrinsicArgumentAsBox(const Fortran::lower::SomeExpr &expr) { 2073 mlir::Location loc = getLoc(); 2074 ExtValue exv = genBoxArg(expr); 2075 mlir::Value box = builder.createBox(loc, exv); 2076 return fir::BoxValue( 2077 box, fir::factory::getNonDefaultLowerBounds(builder, loc, exv), 2078 fir::factory::getNonDeferredLengthParams(exv)); 2079 } 2080 2081 /// Generate a call to an intrinsic function. 2082 ExtValue 2083 genIntrinsicRef(const Fortran::evaluate::ProcedureRef &procRef, 2084 const Fortran::evaluate::SpecificIntrinsic &intrinsic, 2085 llvm::Optional<mlir::Type> resultType) { 2086 llvm::SmallVector<ExtValue> operands; 2087 2088 llvm::StringRef name = intrinsic.name; 2089 mlir::Location loc = getLoc(); 2090 if (Fortran::lower::intrinsicRequiresCustomOptionalHandling( 2091 procRef, intrinsic, converter)) { 2092 using ExvAndPresence = std::pair<ExtValue, llvm::Optional<mlir::Value>>; 2093 llvm::SmallVector<ExvAndPresence, 4> operands; 2094 auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) { 2095 ExtValue optionalArg = lowerIntrinsicArgumentAsInquired(expr); 2096 mlir::Value isPresent = 2097 genActualIsPresentTest(builder, loc, optionalArg); 2098 operands.emplace_back(optionalArg, isPresent); 2099 }; 2100 auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr) { 2101 operands.emplace_back(genval(expr), llvm::None); 2102 }; 2103 Fortran::lower::prepareCustomIntrinsicArgument( 2104 procRef, intrinsic, resultType, prepareOptionalArg, prepareOtherArg, 2105 converter); 2106 2107 auto getArgument = [&](std::size_t i) -> ExtValue { 2108 if (fir::conformsWithPassByRef( 2109 fir::getBase(operands[i].first).getType())) 2110 return genLoad(operands[i].first); 2111 return operands[i].first; 2112 }; 2113 auto isPresent = [&](std::size_t i) -> llvm::Optional<mlir::Value> { 2114 return operands[i].second; 2115 }; 2116 return Fortran::lower::lowerCustomIntrinsic( 2117 builder, loc, name, resultType, isPresent, getArgument, 2118 operands.size(), stmtCtx); 2119 } 2120 2121 const Fortran::lower::IntrinsicArgumentLoweringRules *argLowering = 2122 Fortran::lower::getIntrinsicArgumentLowering(name); 2123 for (const auto &[arg, dummy] : 2124 llvm::zip(procRef.arguments(), 2125 intrinsic.characteristics.value().dummyArguments)) { 2126 auto *expr = Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg); 2127 if (!expr) { 2128 // Absent optional. 2129 operands.emplace_back(Fortran::lower::getAbsentIntrinsicArgument()); 2130 continue; 2131 } 2132 if (!argLowering) { 2133 // No argument lowering instruction, lower by value. 2134 operands.emplace_back(genval(*expr)); 2135 continue; 2136 } 2137 // Ad-hoc argument lowering handling. 2138 Fortran::lower::ArgLoweringRule argRules = 2139 Fortran::lower::lowerIntrinsicArgumentAs(loc, *argLowering, 2140 dummy.name); 2141 if (argRules.handleDynamicOptional && 2142 Fortran::evaluate::MayBePassedAsAbsentOptional( 2143 *expr, converter.getFoldingContext())) { 2144 ExtValue optional = lowerIntrinsicArgumentAsInquired(*expr); 2145 mlir::Value isPresent = genActualIsPresentTest(builder, loc, optional); 2146 switch (argRules.lowerAs) { 2147 case Fortran::lower::LowerIntrinsicArgAs::Value: 2148 operands.emplace_back( 2149 genOptionalValue(builder, loc, optional, isPresent)); 2150 continue; 2151 case Fortran::lower::LowerIntrinsicArgAs::Addr: 2152 operands.emplace_back( 2153 genOptionalAddr(builder, loc, optional, isPresent)); 2154 continue; 2155 case Fortran::lower::LowerIntrinsicArgAs::Box: 2156 operands.emplace_back( 2157 genOptionalBox(builder, loc, optional, isPresent)); 2158 continue; 2159 case Fortran::lower::LowerIntrinsicArgAs::Inquired: 2160 operands.emplace_back(optional); 2161 continue; 2162 } 2163 llvm_unreachable("bad switch"); 2164 } 2165 switch (argRules.lowerAs) { 2166 case Fortran::lower::LowerIntrinsicArgAs::Value: 2167 operands.emplace_back(genval(*expr)); 2168 continue; 2169 case Fortran::lower::LowerIntrinsicArgAs::Addr: 2170 operands.emplace_back(gen(*expr)); 2171 continue; 2172 case Fortran::lower::LowerIntrinsicArgAs::Box: 2173 operands.emplace_back(lowerIntrinsicArgumentAsBox(*expr)); 2174 continue; 2175 case Fortran::lower::LowerIntrinsicArgAs::Inquired: 2176 operands.emplace_back(lowerIntrinsicArgumentAsInquired(*expr)); 2177 continue; 2178 } 2179 llvm_unreachable("bad switch"); 2180 } 2181 // Let the intrinsic library lower the intrinsic procedure call 2182 return Fortran::lower::genIntrinsicCall(builder, getLoc(), name, resultType, 2183 operands, stmtCtx); 2184 } 2185 2186 template <typename A> 2187 bool isCharacterType(const A &exp) { 2188 if (auto type = exp.GetType()) 2189 return type->category() == Fortran::common::TypeCategory::Character; 2190 return false; 2191 } 2192 2193 /// helper to detect statement functions 2194 static bool 2195 isStatementFunctionCall(const Fortran::evaluate::ProcedureRef &procRef) { 2196 if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol()) 2197 if (const auto *details = 2198 symbol->detailsIf<Fortran::semantics::SubprogramDetails>()) 2199 return details->stmtFunction().has_value(); 2200 return false; 2201 } 2202 /// Generate Statement function calls 2203 ExtValue genStmtFunctionRef(const Fortran::evaluate::ProcedureRef &procRef) { 2204 const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol(); 2205 assert(symbol && "expected symbol in ProcedureRef of statement functions"); 2206 const auto &details = symbol->get<Fortran::semantics::SubprogramDetails>(); 2207 2208 // Statement functions have their own scope, we just need to associate 2209 // the dummy symbols to argument expressions. They are no 2210 // optional/alternate return arguments. Statement functions cannot be 2211 // recursive (directly or indirectly) so it is safe to add dummy symbols to 2212 // the local map here. 2213 symMap.pushScope(); 2214 for (auto [arg, bind] : 2215 llvm::zip(details.dummyArgs(), procRef.arguments())) { 2216 assert(arg && "alternate return in statement function"); 2217 assert(bind && "optional argument in statement function"); 2218 const auto *expr = bind->UnwrapExpr(); 2219 // TODO: assumed type in statement function, that surprisingly seems 2220 // allowed, probably because nobody thought of restricting this usage. 2221 // gfortran/ifort compiles this. 2222 assert(expr && "assumed type used as statement function argument"); 2223 // As per Fortran 2018 C1580, statement function arguments can only be 2224 // scalars, so just pass the box with the address. The only care is to 2225 // to use the dummy character explicit length if any instead of the 2226 // actual argument length (that can be bigger). 2227 if (const Fortran::semantics::DeclTypeSpec *type = arg->GetType()) 2228 if (type->category() == Fortran::semantics::DeclTypeSpec::Character) 2229 if (const Fortran::semantics::MaybeIntExpr &lenExpr = 2230 type->characterTypeSpec().length().GetExplicit()) { 2231 mlir::Value len = fir::getBase(genval(*lenExpr)); 2232 // F2018 7.4.4.2 point 5. 2233 len = fir::factory::genMaxWithZero(builder, getLoc(), len); 2234 symMap.addSymbol(*arg, 2235 replaceScalarCharacterLength(gen(*expr), len)); 2236 continue; 2237 } 2238 symMap.addSymbol(*arg, gen(*expr)); 2239 } 2240 2241 // Explicitly map statement function host associated symbols to their 2242 // parent scope lowered symbol box. 2243 for (const Fortran::semantics::SymbolRef &sym : 2244 Fortran::evaluate::CollectSymbols(*details.stmtFunction())) 2245 if (const auto *details = 2246 sym->detailsIf<Fortran::semantics::HostAssocDetails>()) 2247 if (!symMap.lookupSymbol(*sym)) 2248 symMap.addSymbol(*sym, gen(details->symbol())); 2249 2250 ExtValue result = genval(details.stmtFunction().value()); 2251 LLVM_DEBUG(llvm::dbgs() << "stmt-function: " << result << '\n'); 2252 symMap.popScope(); 2253 return result; 2254 } 2255 2256 /// Helper to package a Value and its properties into an ExtendedValue. 2257 static ExtValue toExtendedValue(mlir::Location loc, mlir::Value base, 2258 llvm::ArrayRef<mlir::Value> extents, 2259 llvm::ArrayRef<mlir::Value> lengths) { 2260 mlir::Type type = base.getType(); 2261 if (type.isa<fir::BoxType>()) 2262 return fir::BoxValue(base, /*lbounds=*/{}, lengths, extents); 2263 type = fir::unwrapRefType(type); 2264 if (type.isa<fir::BoxType>()) 2265 return fir::MutableBoxValue(base, lengths, /*mutableProperties*/ {}); 2266 if (auto seqTy = type.dyn_cast<fir::SequenceType>()) { 2267 if (seqTy.getDimension() != extents.size()) 2268 fir::emitFatalError(loc, "incorrect number of extents for array"); 2269 if (seqTy.getEleTy().isa<fir::CharacterType>()) { 2270 if (lengths.empty()) 2271 fir::emitFatalError(loc, "missing length for character"); 2272 assert(lengths.size() == 1); 2273 return fir::CharArrayBoxValue(base, lengths[0], extents); 2274 } 2275 return fir::ArrayBoxValue(base, extents); 2276 } 2277 if (type.isa<fir::CharacterType>()) { 2278 if (lengths.empty()) 2279 fir::emitFatalError(loc, "missing length for character"); 2280 assert(lengths.size() == 1); 2281 return fir::CharBoxValue(base, lengths[0]); 2282 } 2283 return base; 2284 } 2285 2286 // Find the argument that corresponds to the host associations. 2287 // Verify some assumptions about how the signature was built here. 2288 [[maybe_unused]] static unsigned 2289 findHostAssocTuplePos(mlir::func::FuncOp fn) { 2290 // Scan the argument list from last to first as the host associations are 2291 // appended for now. 2292 for (unsigned i = fn.getNumArguments(); i > 0; --i) 2293 if (fn.getArgAttr(i - 1, fir::getHostAssocAttrName())) { 2294 // Host assoc tuple must be last argument (for now). 2295 assert(i == fn.getNumArguments() && "tuple must be last"); 2296 return i - 1; 2297 } 2298 llvm_unreachable("anyFuncArgsHaveAttr failed"); 2299 } 2300 2301 /// Create a contiguous temporary array with the same shape, 2302 /// length parameters and type as mold. It is up to the caller to deallocate 2303 /// the temporary. 2304 ExtValue genArrayTempFromMold(const ExtValue &mold, 2305 llvm::StringRef tempName) { 2306 mlir::Type type = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(mold).getType()); 2307 assert(type && "expected descriptor or memory type"); 2308 mlir::Location loc = getLoc(); 2309 llvm::SmallVector<mlir::Value> extents = 2310 fir::factory::getExtents(loc, builder, mold); 2311 llvm::SmallVector<mlir::Value> allocMemTypeParams = 2312 fir::getTypeParams(mold); 2313 mlir::Value charLen; 2314 mlir::Type elementType = fir::unwrapSequenceType(type); 2315 if (auto charType = elementType.dyn_cast<fir::CharacterType>()) { 2316 charLen = allocMemTypeParams.empty() 2317 ? fir::factory::readCharLen(builder, loc, mold) 2318 : allocMemTypeParams[0]; 2319 if (charType.hasDynamicLen() && allocMemTypeParams.empty()) 2320 allocMemTypeParams.push_back(charLen); 2321 } else if (fir::hasDynamicSize(elementType)) { 2322 TODO(loc, "creating temporary for derived type with length parameters"); 2323 } 2324 2325 mlir::Value temp = builder.create<fir::AllocMemOp>( 2326 loc, type, tempName, allocMemTypeParams, extents); 2327 if (fir::unwrapSequenceType(type).isa<fir::CharacterType>()) 2328 return fir::CharArrayBoxValue{temp, charLen, extents}; 2329 return fir::ArrayBoxValue{temp, extents}; 2330 } 2331 2332 /// Copy \p source array into \p dest array. Both arrays must be 2333 /// conforming, but neither array must be contiguous. 2334 void genArrayCopy(ExtValue dest, ExtValue source) { 2335 return createSomeArrayAssignment(converter, dest, source, symMap, stmtCtx); 2336 } 2337 2338 /// Lower a non-elemental procedure reference and read allocatable and pointer 2339 /// results into normal values. 2340 ExtValue genProcedureRef(const Fortran::evaluate::ProcedureRef &procRef, 2341 llvm::Optional<mlir::Type> resultType) { 2342 ExtValue res = genRawProcedureRef(procRef, resultType); 2343 // In most contexts, pointers and allocatable do not appear as allocatable 2344 // or pointer variable on the caller side (see 8.5.3 note 1 for 2345 // allocatables). The few context where this can happen must call 2346 // genRawProcedureRef directly. 2347 if (const auto *box = res.getBoxOf<fir::MutableBoxValue>()) 2348 return fir::factory::genMutableBoxRead(builder, getLoc(), *box); 2349 return res; 2350 } 2351 2352 /// Given a call site for which the arguments were already lowered, generate 2353 /// the call and return the result. This function deals with explicit result 2354 /// allocation and lowering if needed. It also deals with passing the host 2355 /// link to internal procedures. 2356 ExtValue genCallOpAndResult(Fortran::lower::CallerInterface &caller, 2357 mlir::FunctionType callSiteType, 2358 llvm::Optional<mlir::Type> resultType) { 2359 mlir::Location loc = getLoc(); 2360 using PassBy = Fortran::lower::CallerInterface::PassEntityBy; 2361 // Handle cases where caller must allocate the result or a fir.box for it. 2362 bool mustPopSymMap = false; 2363 if (caller.mustMapInterfaceSymbols()) { 2364 symMap.pushScope(); 2365 mustPopSymMap = true; 2366 Fortran::lower::mapCallInterfaceSymbols(converter, caller, symMap); 2367 } 2368 // If this is an indirect call, retrieve the function address. Also retrieve 2369 // the result length if this is a character function (note that this length 2370 // will be used only if there is no explicit length in the local interface). 2371 mlir::Value funcPointer; 2372 mlir::Value charFuncPointerLength; 2373 if (const Fortran::semantics::Symbol *sym = 2374 caller.getIfIndirectCallSymbol()) { 2375 funcPointer = symMap.lookupSymbol(*sym).getAddr(); 2376 if (!funcPointer) 2377 fir::emitFatalError(loc, "failed to find indirect call symbol address"); 2378 if (fir::isCharacterProcedureTuple(funcPointer.getType(), 2379 /*acceptRawFunc=*/false)) 2380 std::tie(funcPointer, charFuncPointerLength) = 2381 fir::factory::extractCharacterProcedureTuple(builder, loc, 2382 funcPointer); 2383 } 2384 2385 mlir::IndexType idxTy = builder.getIndexType(); 2386 auto lowerSpecExpr = [&](const auto &expr) -> mlir::Value { 2387 return builder.createConvert( 2388 loc, idxTy, fir::getBase(converter.genExprValue(expr, stmtCtx))); 2389 }; 2390 llvm::SmallVector<mlir::Value> resultLengths; 2391 auto allocatedResult = [&]() -> llvm::Optional<ExtValue> { 2392 llvm::SmallVector<mlir::Value> extents; 2393 llvm::SmallVector<mlir::Value> lengths; 2394 if (!caller.callerAllocateResult()) 2395 return {}; 2396 mlir::Type type = caller.getResultStorageType(); 2397 if (type.isa<fir::SequenceType>()) 2398 caller.walkResultExtents([&](const Fortran::lower::SomeExpr &e) { 2399 extents.emplace_back(lowerSpecExpr(e)); 2400 }); 2401 caller.walkResultLengths([&](const Fortran::lower::SomeExpr &e) { 2402 lengths.emplace_back(lowerSpecExpr(e)); 2403 }); 2404 2405 // Result length parameters should not be provided to box storage 2406 // allocation and save_results, but they are still useful information to 2407 // keep in the ExtendedValue if non-deferred. 2408 if (!type.isa<fir::BoxType>()) { 2409 if (fir::isa_char(fir::unwrapSequenceType(type)) && lengths.empty()) { 2410 // Calling an assumed length function. This is only possible if this 2411 // is a call to a character dummy procedure. 2412 if (!charFuncPointerLength) 2413 fir::emitFatalError(loc, "failed to retrieve character function " 2414 "length while calling it"); 2415 lengths.push_back(charFuncPointerLength); 2416 } 2417 resultLengths = lengths; 2418 } 2419 2420 if (!extents.empty() || !lengths.empty()) { 2421 auto *bldr = &converter.getFirOpBuilder(); 2422 auto stackSaveFn = fir::factory::getLlvmStackSave(builder); 2423 auto stackSaveSymbol = bldr->getSymbolRefAttr(stackSaveFn.getName()); 2424 mlir::Value sp = 2425 bldr->create<fir::CallOp>( 2426 loc, stackSaveFn.getFunctionType().getResults(), 2427 stackSaveSymbol, mlir::ValueRange{}) 2428 .getResult(0); 2429 stmtCtx.attachCleanup([bldr, loc, sp]() { 2430 auto stackRestoreFn = fir::factory::getLlvmStackRestore(*bldr); 2431 auto stackRestoreSymbol = 2432 bldr->getSymbolRefAttr(stackRestoreFn.getName()); 2433 bldr->create<fir::CallOp>( 2434 loc, stackRestoreFn.getFunctionType().getResults(), 2435 stackRestoreSymbol, mlir::ValueRange{sp}); 2436 }); 2437 } 2438 mlir::Value temp = 2439 builder.createTemporary(loc, type, ".result", extents, resultLengths); 2440 return toExtendedValue(loc, temp, extents, lengths); 2441 }(); 2442 2443 if (mustPopSymMap) 2444 symMap.popScope(); 2445 2446 // Place allocated result or prepare the fir.save_result arguments. 2447 mlir::Value arrayResultShape; 2448 if (allocatedResult) { 2449 if (std::optional<Fortran::lower::CallInterface< 2450 Fortran::lower::CallerInterface>::PassedEntity> 2451 resultArg = caller.getPassedResult()) { 2452 if (resultArg->passBy == PassBy::AddressAndLength) 2453 caller.placeAddressAndLengthInput(*resultArg, 2454 fir::getBase(*allocatedResult), 2455 fir::getLen(*allocatedResult)); 2456 else if (resultArg->passBy == PassBy::BaseAddress) 2457 caller.placeInput(*resultArg, fir::getBase(*allocatedResult)); 2458 else 2459 fir::emitFatalError( 2460 loc, "only expect character scalar result to be passed by ref"); 2461 } else { 2462 assert(caller.mustSaveResult()); 2463 arrayResultShape = allocatedResult->match( 2464 [&](const fir::CharArrayBoxValue &) { 2465 return builder.createShape(loc, *allocatedResult); 2466 }, 2467 [&](const fir::ArrayBoxValue &) { 2468 return builder.createShape(loc, *allocatedResult); 2469 }, 2470 [&](const auto &) { return mlir::Value{}; }); 2471 } 2472 } 2473 2474 // In older Fortran, procedure argument types are inferred. This may lead 2475 // different view of what the function signature is in different locations. 2476 // Casts are inserted as needed below to accommodate this. 2477 2478 // The mlir::func::FuncOp type prevails, unless it has a different number of 2479 // arguments which can happen in legal program if it was passed as a dummy 2480 // procedure argument earlier with no further type information. 2481 mlir::SymbolRefAttr funcSymbolAttr; 2482 bool addHostAssociations = false; 2483 if (!funcPointer) { 2484 mlir::FunctionType funcOpType = caller.getFuncOp().getFunctionType(); 2485 mlir::SymbolRefAttr symbolAttr = 2486 builder.getSymbolRefAttr(caller.getMangledName()); 2487 if (callSiteType.getNumResults() == funcOpType.getNumResults() && 2488 callSiteType.getNumInputs() + 1 == funcOpType.getNumInputs() && 2489 fir::anyFuncArgsHaveAttr(caller.getFuncOp(), 2490 fir::getHostAssocAttrName())) { 2491 // The number of arguments is off by one, and we're lowering a function 2492 // with host associations. Modify call to include host associations 2493 // argument by appending the value at the end of the operands. 2494 assert(funcOpType.getInput(findHostAssocTuplePos(caller.getFuncOp())) == 2495 converter.hostAssocTupleValue().getType()); 2496 addHostAssociations = true; 2497 } 2498 if (!addHostAssociations && 2499 (callSiteType.getNumResults() != funcOpType.getNumResults() || 2500 callSiteType.getNumInputs() != funcOpType.getNumInputs())) { 2501 // Deal with argument number mismatch by making a function pointer so 2502 // that function type cast can be inserted. Do not emit a warning here 2503 // because this can happen in legal program if the function is not 2504 // defined here and it was first passed as an argument without any more 2505 // information. 2506 funcPointer = 2507 builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr); 2508 } else if (callSiteType.getResults() != funcOpType.getResults()) { 2509 // Implicit interface result type mismatch are not standard Fortran, but 2510 // some compilers are not complaining about it. The front end is not 2511 // protecting lowering from this currently. Support this with a 2512 // discouraging warning. 2513 LLVM_DEBUG(mlir::emitWarning( 2514 loc, "a return type mismatch is not standard compliant and may " 2515 "lead to undefined behavior.")); 2516 // Cast the actual function to the current caller implicit type because 2517 // that is the behavior we would get if we could not see the definition. 2518 funcPointer = 2519 builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr); 2520 } else { 2521 funcSymbolAttr = symbolAttr; 2522 } 2523 } 2524 2525 mlir::FunctionType funcType = 2526 funcPointer ? callSiteType : caller.getFuncOp().getFunctionType(); 2527 llvm::SmallVector<mlir::Value> operands; 2528 // First operand of indirect call is the function pointer. Cast it to 2529 // required function type for the call to handle procedures that have a 2530 // compatible interface in Fortran, but that have different signatures in 2531 // FIR. 2532 if (funcPointer) { 2533 operands.push_back( 2534 funcPointer.getType().isa<fir::BoxProcType>() 2535 ? builder.create<fir::BoxAddrOp>(loc, funcType, funcPointer) 2536 : builder.createConvert(loc, funcType, funcPointer)); 2537 } 2538 2539 // Deal with potential mismatches in arguments types. Passing an array to a 2540 // scalar argument should for instance be tolerated here. 2541 bool callingImplicitInterface = caller.canBeCalledViaImplicitInterface(); 2542 for (auto [fst, snd] : 2543 llvm::zip(caller.getInputs(), funcType.getInputs())) { 2544 // When passing arguments to a procedure that can be called an implicit 2545 // interface, allow character actual arguments to be passed to dummy 2546 // arguments of any type and vice versa 2547 mlir::Value cast; 2548 auto *context = builder.getContext(); 2549 if (snd.isa<fir::BoxProcType>() && 2550 fst.getType().isa<mlir::FunctionType>()) { 2551 auto funcTy = mlir::FunctionType::get(context, llvm::None, llvm::None); 2552 auto boxProcTy = builder.getBoxProcType(funcTy); 2553 if (mlir::Value host = argumentHostAssocs(converter, fst)) { 2554 cast = builder.create<fir::EmboxProcOp>( 2555 loc, boxProcTy, llvm::ArrayRef<mlir::Value>{fst, host}); 2556 } else { 2557 cast = builder.create<fir::EmboxProcOp>(loc, boxProcTy, fst); 2558 } 2559 } else { 2560 cast = builder.convertWithSemantics(loc, snd, fst, 2561 callingImplicitInterface); 2562 } 2563 operands.push_back(cast); 2564 } 2565 2566 // Add host associations as necessary. 2567 if (addHostAssociations) 2568 operands.push_back(converter.hostAssocTupleValue()); 2569 2570 auto call = builder.create<fir::CallOp>(loc, funcType.getResults(), 2571 funcSymbolAttr, operands); 2572 2573 if (caller.mustSaveResult()) 2574 builder.create<fir::SaveResultOp>( 2575 loc, call.getResult(0), fir::getBase(allocatedResult.getValue()), 2576 arrayResultShape, resultLengths); 2577 2578 if (allocatedResult) { 2579 allocatedResult->match( 2580 [&](const fir::MutableBoxValue &box) { 2581 if (box.isAllocatable()) { 2582 // 9.7.3.2 point 4. Finalize allocatables. 2583 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder(); 2584 stmtCtx.attachCleanup([bldr, loc, box]() { 2585 fir::factory::genFinalization(*bldr, loc, box); 2586 }); 2587 } 2588 }, 2589 [](const auto &) {}); 2590 return *allocatedResult; 2591 } 2592 2593 if (!resultType) 2594 return mlir::Value{}; // subroutine call 2595 // For now, Fortran return values are implemented with a single MLIR 2596 // function return value. 2597 assert(call.getNumResults() == 1 && 2598 "Expected exactly one result in FUNCTION call"); 2599 return call.getResult(0); 2600 } 2601 2602 /// Like genExtAddr, but ensure the address returned is a temporary even if \p 2603 /// expr is variable inside parentheses. 2604 ExtValue genTempExtAddr(const Fortran::lower::SomeExpr &expr) { 2605 // In general, genExtAddr might not create a temp for variable inside 2606 // parentheses to avoid creating array temporary in sub-expressions. It only 2607 // ensures the sub-expression is not re-associated with other parts of the 2608 // expression. In the call semantics, there is a difference between expr and 2609 // variable (see R1524). For expressions, a variable storage must not be 2610 // argument associated since it could be modified inside the call, or the 2611 // variable could also be modified by other means during the call. 2612 if (!isParenthesizedVariable(expr)) 2613 return genExtAddr(expr); 2614 if (expr.Rank() > 0) 2615 return asArray(expr); 2616 mlir::Location loc = getLoc(); 2617 return genExtValue(expr).match( 2618 [&](const fir::CharBoxValue &boxChar) -> ExtValue { 2619 return fir::factory::CharacterExprHelper{builder, loc}.createTempFrom( 2620 boxChar); 2621 }, 2622 [&](const fir::UnboxedValue &v) -> ExtValue { 2623 mlir::Type type = v.getType(); 2624 mlir::Value value = v; 2625 if (fir::isa_ref_type(type)) 2626 value = builder.create<fir::LoadOp>(loc, value); 2627 mlir::Value temp = builder.createTemporary(loc, value.getType()); 2628 builder.create<fir::StoreOp>(loc, value, temp); 2629 return temp; 2630 }, 2631 [&](const fir::BoxValue &x) -> ExtValue { 2632 // Derived type scalar that may be polymorphic. 2633 assert(!x.hasRank() && x.isDerived()); 2634 if (x.isDerivedWithLenParameters()) 2635 fir::emitFatalError( 2636 loc, "making temps for derived type with length parameters"); 2637 // TODO: polymorphic aspects should be kept but for now the temp 2638 // created always has the declared type. 2639 mlir::Value var = 2640 fir::getBase(fir::factory::readBoxValue(builder, loc, x)); 2641 auto value = builder.create<fir::LoadOp>(loc, var); 2642 mlir::Value temp = builder.createTemporary(loc, value.getType()); 2643 builder.create<fir::StoreOp>(loc, value, temp); 2644 return temp; 2645 }, 2646 [&](const auto &) -> ExtValue { 2647 fir::emitFatalError(loc, "expr is not a scalar value"); 2648 }); 2649 } 2650 2651 /// Helper structure to track potential copy-in of non contiguous variable 2652 /// argument into a contiguous temp. It is used to deallocate the temp that 2653 /// may have been created as well as to the copy-out from the temp to the 2654 /// variable after the call. 2655 struct CopyOutPair { 2656 ExtValue var; 2657 ExtValue temp; 2658 // Flag to indicate if the argument may have been modified by the 2659 // callee, in which case it must be copied-out to the variable. 2660 bool argMayBeModifiedByCall; 2661 // Optional boolean value that, if present and false, prevents 2662 // the copy-out and temp deallocation. 2663 llvm::Optional<mlir::Value> restrictCopyAndFreeAtRuntime; 2664 }; 2665 using CopyOutPairs = llvm::SmallVector<CopyOutPair, 4>; 2666 2667 /// Helper to read any fir::BoxValue into other fir::ExtendedValue categories 2668 /// not based on fir.box. 2669 /// This will lose any non contiguous stride information and dynamic type and 2670 /// should only be called if \p exv is known to be contiguous or if its base 2671 /// address will be replaced by a contiguous one. If \p exv is not a 2672 /// fir::BoxValue, this is a no-op. 2673 ExtValue readIfBoxValue(const ExtValue &exv) { 2674 if (const auto *box = exv.getBoxOf<fir::BoxValue>()) 2675 return fir::factory::readBoxValue(builder, getLoc(), *box); 2676 return exv; 2677 } 2678 2679 /// Generate a contiguous temp to pass \p actualArg as argument \p arg. The 2680 /// creation of the temp and copy-in can be made conditional at runtime by 2681 /// providing a runtime boolean flag \p restrictCopyAtRuntime (in which case 2682 /// the temp and copy will only be made if the value is true at runtime). 2683 ExtValue genCopyIn(const ExtValue &actualArg, 2684 const Fortran::lower::CallerInterface::PassedEntity &arg, 2685 CopyOutPairs ©OutPairs, 2686 llvm::Optional<mlir::Value> restrictCopyAtRuntime) { 2687 if (!restrictCopyAtRuntime) { 2688 ExtValue temp = genArrayTempFromMold(actualArg, ".copyinout"); 2689 if (arg.mayBeReadByCall()) 2690 genArrayCopy(temp, actualArg); 2691 copyOutPairs.emplace_back(CopyOutPair{ 2692 actualArg, temp, arg.mayBeModifiedByCall(), restrictCopyAtRuntime}); 2693 return temp; 2694 } 2695 // Otherwise, need to be careful to only copy-in if allowed at runtime. 2696 mlir::Location loc = getLoc(); 2697 auto addrType = fir::HeapType::get( 2698 fir::unwrapPassByRefType(fir::getBase(actualArg).getType())); 2699 mlir::Value addr = 2700 builder 2701 .genIfOp(loc, {addrType}, *restrictCopyAtRuntime, 2702 /*withElseRegion=*/true) 2703 .genThen([&]() { 2704 auto temp = genArrayTempFromMold(actualArg, ".copyinout"); 2705 if (arg.mayBeReadByCall()) 2706 genArrayCopy(temp, actualArg); 2707 builder.create<fir::ResultOp>(loc, fir::getBase(temp)); 2708 }) 2709 .genElse([&]() { 2710 auto nullPtr = builder.createNullConstant(loc, addrType); 2711 builder.create<fir::ResultOp>(loc, nullPtr); 2712 }) 2713 .getResults()[0]; 2714 // Associate the temp address with actualArg lengths and extents. 2715 fir::ExtendedValue temp = fir::substBase(readIfBoxValue(actualArg), addr); 2716 copyOutPairs.emplace_back(CopyOutPair{ 2717 actualArg, temp, arg.mayBeModifiedByCall(), restrictCopyAtRuntime}); 2718 return temp; 2719 } 2720 2721 /// Generate copy-out if needed and free the temporary for an argument that 2722 /// has been copied-in into a contiguous temp. 2723 void genCopyOut(const CopyOutPair ©OutPair) { 2724 mlir::Location loc = getLoc(); 2725 if (!copyOutPair.restrictCopyAndFreeAtRuntime) { 2726 if (copyOutPair.argMayBeModifiedByCall) 2727 genArrayCopy(copyOutPair.var, copyOutPair.temp); 2728 builder.create<fir::FreeMemOp>(loc, fir::getBase(copyOutPair.temp)); 2729 return; 2730 } 2731 builder.genIfThen(loc, *copyOutPair.restrictCopyAndFreeAtRuntime) 2732 .genThen([&]() { 2733 if (copyOutPair.argMayBeModifiedByCall) 2734 genArrayCopy(copyOutPair.var, copyOutPair.temp); 2735 builder.create<fir::FreeMemOp>(loc, fir::getBase(copyOutPair.temp)); 2736 }) 2737 .end(); 2738 } 2739 2740 /// Lower a designator to a variable that may be absent at runtime into an 2741 /// ExtendedValue where all the properties (base address, shape and length 2742 /// parameters) can be safely read (set to zero if not present). It also 2743 /// returns a boolean mlir::Value telling if the variable is present at 2744 /// runtime. 2745 /// This is useful to later be able to do conditional copy-in/copy-out 2746 /// or to retrieve the base address without having to deal with the case 2747 /// where the actual may be an absent fir.box. 2748 std::pair<ExtValue, mlir::Value> 2749 prepareActualThatMayBeAbsent(const Fortran::lower::SomeExpr &expr) { 2750 mlir::Location loc = getLoc(); 2751 if (Fortran::evaluate::IsAllocatableOrPointerObject( 2752 expr, converter.getFoldingContext())) { 2753 // Fortran 2018 15.5.2.12 point 1: If unallocated/disassociated, 2754 // it is as if the argument was absent. The main care here is to 2755 // not do a copy-in/copy-out because the temp address, even though 2756 // pointing to a null size storage, would not be a nullptr and 2757 // therefore the argument would not be considered absent on the 2758 // callee side. Note: if wholeSymbol is optional, it cannot be 2759 // absent as per 15.5.2.12 point 7. and 8. We rely on this to 2760 // un-conditionally read the allocatable/pointer descriptor here. 2761 fir::MutableBoxValue mutableBox = genMutableBoxValue(expr); 2762 mlir::Value isPresent = fir::factory::genIsAllocatedOrAssociatedTest( 2763 builder, loc, mutableBox); 2764 fir::ExtendedValue actualArg = 2765 fir::factory::genMutableBoxRead(builder, loc, mutableBox); 2766 return {actualArg, isPresent}; 2767 } 2768 // Absent descriptor cannot be read. To avoid any issue in 2769 // copy-in/copy-out, and when retrieving the address/length 2770 // create an descriptor pointing to a null address here if the 2771 // fir.box is absent. 2772 ExtValue actualArg = gen(expr); 2773 mlir::Value actualArgBase = fir::getBase(actualArg); 2774 mlir::Value isPresent = builder.create<fir::IsPresentOp>( 2775 loc, builder.getI1Type(), actualArgBase); 2776 if (!actualArgBase.getType().isa<fir::BoxType>()) 2777 return {actualArg, isPresent}; 2778 ExtValue safeToReadBox; 2779 return {safeToReadBox, isPresent}; 2780 } 2781 2782 /// Create a temp on the stack for scalar actual arguments that may be absent 2783 /// at runtime, but must be passed via a temp if they are presents. 2784 fir::ExtendedValue 2785 createScalarTempForArgThatMayBeAbsent(ExtValue actualArg, 2786 mlir::Value isPresent) { 2787 mlir::Location loc = getLoc(); 2788 mlir::Type type = fir::unwrapRefType(fir::getBase(actualArg).getType()); 2789 if (fir::isDerivedWithLenParameters(actualArg)) 2790 TODO(loc, "parametrized derived type optional scalar argument copy-in"); 2791 if (const fir::CharBoxValue *charBox = actualArg.getCharBox()) { 2792 mlir::Value len = charBox->getLen(); 2793 mlir::Value zero = builder.createIntegerConstant(loc, len.getType(), 0); 2794 len = builder.create<mlir::arith::SelectOp>(loc, isPresent, len, zero); 2795 mlir::Value temp = builder.createTemporary( 2796 loc, type, /*name=*/{}, 2797 /*shape=*/{}, mlir::ValueRange{len}, 2798 llvm::ArrayRef<mlir::NamedAttribute>{ 2799 Fortran::lower::getAdaptToByRefAttr(builder)}); 2800 return fir::CharBoxValue{temp, len}; 2801 } 2802 assert((fir::isa_trivial(type) || type.isa<fir::RecordType>()) && 2803 "must be simple scalar"); 2804 return builder.createTemporary( 2805 loc, type, 2806 llvm::ArrayRef<mlir::NamedAttribute>{ 2807 Fortran::lower::getAdaptToByRefAttr(builder)}); 2808 } 2809 2810 /// Lower an actual argument that must be passed via an address. 2811 /// This generates of the copy-in/copy-out if the actual is not contiguous, or 2812 /// the creation of the temp if the actual is a variable and \p byValue is 2813 /// true. It handles the cases where the actual may be absent, and all of the 2814 /// copying has to be conditional at runtime. 2815 ExtValue prepareActualToBaseAddressLike( 2816 const Fortran::lower::SomeExpr &expr, 2817 const Fortran::lower::CallerInterface::PassedEntity &arg, 2818 CopyOutPairs ©OutPairs, bool byValue) { 2819 mlir::Location loc = getLoc(); 2820 const bool isArray = expr.Rank() > 0; 2821 const bool actualArgIsVariable = Fortran::evaluate::IsVariable(expr); 2822 // It must be possible to modify VALUE arguments on the callee side, even 2823 // if the actual argument is a literal or named constant. Hence, the 2824 // address of static storage must not be passed in that case, and a copy 2825 // must be made even if this is not a variable. 2826 // Note: isArray should be used here, but genBoxArg already creates copies 2827 // for it, so do not duplicate the copy until genBoxArg behavior is changed. 2828 const bool isStaticConstantByValue = 2829 byValue && Fortran::evaluate::IsActuallyConstant(expr) && 2830 (isCharacterType(expr)); 2831 const bool variableNeedsCopy = 2832 actualArgIsVariable && 2833 (byValue || (isArray && !Fortran::evaluate::IsSimplyContiguous( 2834 expr, converter.getFoldingContext()))); 2835 const bool needsCopy = isStaticConstantByValue || variableNeedsCopy; 2836 auto argAddr = [&]() -> ExtValue { 2837 if (!actualArgIsVariable && !needsCopy) 2838 // Actual argument is not a variable. Make sure a variable address is 2839 // not passed. 2840 return genTempExtAddr(expr); 2841 ExtValue baseAddr; 2842 if (arg.isOptional() && Fortran::evaluate::MayBePassedAsAbsentOptional( 2843 expr, converter.getFoldingContext())) { 2844 auto [actualArgBind, isPresent] = prepareActualThatMayBeAbsent(expr); 2845 const ExtValue &actualArg = actualArgBind; 2846 if (!needsCopy) 2847 return actualArg; 2848 2849 if (isArray) 2850 return genCopyIn(actualArg, arg, copyOutPairs, 2851 isPresent /*, byValue*/); 2852 // Scalars, create a temp, and use it conditionally at runtime if 2853 // the argument is present. 2854 ExtValue temp = 2855 createScalarTempForArgThatMayBeAbsent(actualArg, isPresent); 2856 mlir::Type tempAddrTy = fir::getBase(temp).getType(); 2857 mlir::Value selectAddr = 2858 builder 2859 .genIfOp(loc, {tempAddrTy}, isPresent, 2860 /*withElseRegion=*/true) 2861 .genThen([&]() { 2862 fir::factory::genScalarAssignment(builder, loc, temp, 2863 actualArg); 2864 builder.create<fir::ResultOp>(loc, fir::getBase(temp)); 2865 }) 2866 .genElse([&]() { 2867 mlir::Value absent = 2868 builder.create<fir::AbsentOp>(loc, tempAddrTy); 2869 builder.create<fir::ResultOp>(loc, absent); 2870 }) 2871 .getResults()[0]; 2872 return fir::substBase(temp, selectAddr); 2873 } 2874 // Actual cannot be absent, the actual argument can safely be 2875 // copied-in/copied-out without any care if needed. 2876 if (isArray) { 2877 ExtValue box = genBoxArg(expr); 2878 if (needsCopy) 2879 return genCopyIn(box, arg, copyOutPairs, 2880 /*restrictCopyAtRuntime=*/llvm::None /*, byValue*/); 2881 // Contiguous: just use the box we created above! 2882 // This gets "unboxed" below, if needed. 2883 return box; 2884 } 2885 // Actual argument is a non-optional, non-pointer, non-allocatable 2886 // scalar. 2887 ExtValue actualArg = genExtAddr(expr); 2888 if (needsCopy) 2889 return createInMemoryScalarCopy(builder, loc, actualArg); 2890 return actualArg; 2891 }(); 2892 // Scalar and contiguous expressions may be lowered to a fir.box, 2893 // either to account for potential polymorphism, or because lowering 2894 // did not account for some contiguity hints. 2895 // Here, polymorphism does not matter (an entity of the declared type 2896 // is passed, not one of the dynamic type), and the expr is known to 2897 // be simply contiguous, so it is safe to unbox it and pass the 2898 // address without making a copy. 2899 return readIfBoxValue(argAddr); 2900 } 2901 2902 /// Lower a non-elemental procedure reference. 2903 ExtValue genRawProcedureRef(const Fortran::evaluate::ProcedureRef &procRef, 2904 llvm::Optional<mlir::Type> resultType) { 2905 mlir::Location loc = getLoc(); 2906 if (isElementalProcWithArrayArgs(procRef)) 2907 fir::emitFatalError(loc, "trying to lower elemental procedure with array " 2908 "arguments as normal procedure"); 2909 if (const Fortran::evaluate::SpecificIntrinsic *intrinsic = 2910 procRef.proc().GetSpecificIntrinsic()) 2911 return genIntrinsicRef(procRef, *intrinsic, resultType); 2912 2913 if (isStatementFunctionCall(procRef)) 2914 return genStmtFunctionRef(procRef); 2915 2916 Fortran::lower::CallerInterface caller(procRef, converter); 2917 using PassBy = Fortran::lower::CallerInterface::PassEntityBy; 2918 2919 llvm::SmallVector<fir::MutableBoxValue> mutableModifiedByCall; 2920 // List of <var, temp> where temp must be copied into var after the call. 2921 CopyOutPairs copyOutPairs; 2922 2923 mlir::FunctionType callSiteType = caller.genFunctionType(); 2924 2925 // Lower the actual arguments and map the lowered values to the dummy 2926 // arguments. 2927 for (const Fortran::lower::CallInterface< 2928 Fortran::lower::CallerInterface>::PassedEntity &arg : 2929 caller.getPassedArguments()) { 2930 const auto *actual = arg.entity; 2931 mlir::Type argTy = callSiteType.getInput(arg.firArgument); 2932 if (!actual) { 2933 // Optional dummy argument for which there is no actual argument. 2934 caller.placeInput(arg, builder.create<fir::AbsentOp>(loc, argTy)); 2935 continue; 2936 } 2937 const auto *expr = actual->UnwrapExpr(); 2938 if (!expr) 2939 TODO(loc, "assumed type actual argument lowering"); 2940 2941 if (arg.passBy == PassBy::Value) { 2942 ExtValue argVal = genval(*expr); 2943 if (!fir::isUnboxedValue(argVal)) 2944 fir::emitFatalError( 2945 loc, "internal error: passing non trivial value by value"); 2946 caller.placeInput(arg, fir::getBase(argVal)); 2947 continue; 2948 } 2949 2950 if (arg.passBy == PassBy::MutableBox) { 2951 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( 2952 *expr)) { 2953 // If expr is NULL(), the mutableBox created must be a deallocated 2954 // pointer with the dummy argument characteristics (see table 16.5 2955 // in Fortran 2018 standard). 2956 // No length parameters are set for the created box because any non 2957 // deferred type parameters of the dummy will be evaluated on the 2958 // callee side, and it is illegal to use NULL without a MOLD if any 2959 // dummy length parameters are assumed. 2960 mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy); 2961 assert(boxTy && boxTy.isa<fir::BoxType>() && 2962 "must be a fir.box type"); 2963 mlir::Value boxStorage = builder.createTemporary(loc, boxTy); 2964 mlir::Value nullBox = fir::factory::createUnallocatedBox( 2965 builder, loc, boxTy, /*nonDeferredParams=*/{}); 2966 builder.create<fir::StoreOp>(loc, nullBox, boxStorage); 2967 caller.placeInput(arg, boxStorage); 2968 continue; 2969 } 2970 if (fir::isPointerType(argTy) && 2971 !Fortran::evaluate::IsObjectPointer( 2972 *expr, converter.getFoldingContext())) { 2973 // Passing a non POINTER actual argument to a POINTER dummy argument. 2974 // Create a pointer of the dummy argument type and assign the actual 2975 // argument to it. 2976 mlir::Value irBox = 2977 builder.createTemporary(loc, fir::unwrapRefType(argTy)); 2978 // Non deferred parameters will be evaluated on the callee side. 2979 fir::MutableBoxValue pointer(irBox, 2980 /*nonDeferredParams=*/mlir::ValueRange{}, 2981 /*mutableProperties=*/{}); 2982 Fortran::lower::associateMutableBox(converter, loc, pointer, *expr, 2983 /*lbounds=*/llvm::None, stmtCtx); 2984 caller.placeInput(arg, irBox); 2985 continue; 2986 } 2987 // Passing a POINTER to a POINTER, or an ALLOCATABLE to an ALLOCATABLE. 2988 fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr); 2989 mlir::Value irBox = 2990 fir::factory::getMutableIRBox(builder, loc, mutableBox); 2991 caller.placeInput(arg, irBox); 2992 if (arg.mayBeModifiedByCall()) 2993 mutableModifiedByCall.emplace_back(std::move(mutableBox)); 2994 continue; 2995 } 2996 const bool actualArgIsVariable = Fortran::evaluate::IsVariable(*expr); 2997 if (arg.passBy == PassBy::BaseAddressValueAttribute) { 2998 mlir::Value temp; 2999 if (isArray(*expr)) { 3000 auto val = genBoxArg(*expr); 3001 if (!actualArgIsVariable) 3002 temp = getBase(val); 3003 else { 3004 ExtValue copy = genArrayTempFromMold(val, ".copy"); 3005 genArrayCopy(copy, val); 3006 temp = fir::getBase(copy); 3007 } 3008 } else { 3009 mlir::Value val = fir::getBase(genval(*expr)); 3010 temp = builder.createTemporary( 3011 loc, val.getType(), 3012 llvm::ArrayRef<mlir::NamedAttribute>{ 3013 Fortran::lower::getAdaptToByRefAttr(builder)}); 3014 builder.create<fir::StoreOp>(loc, val, temp); 3015 } 3016 caller.placeInput(arg, temp); 3017 continue; 3018 } 3019 if (arg.passBy == PassBy::BaseAddress || arg.passBy == PassBy::BoxChar) { 3020 const bool actualIsSimplyContiguous = 3021 !actualArgIsVariable || Fortran::evaluate::IsSimplyContiguous( 3022 *expr, converter.getFoldingContext()); 3023 auto argAddr = [&]() -> ExtValue { 3024 ExtValue baseAddr; 3025 if (actualArgIsVariable && arg.isOptional()) { 3026 if (Fortran::evaluate::IsAllocatableOrPointerObject( 3027 *expr, converter.getFoldingContext())) { 3028 // Fortran 2018 15.5.2.12 point 1: If unallocated/disassociated, 3029 // it is as if the argument was absent. The main care here is to 3030 // not do a copy-in/copy-out because the temp address, even though 3031 // pointing to a null size storage, would not be a nullptr and 3032 // therefore the argument would not be considered absent on the 3033 // callee side. Note: if wholeSymbol is optional, it cannot be 3034 // absent as per 15.5.2.12 point 7. and 8. We rely on this to 3035 // un-conditionally read the allocatable/pointer descriptor here. 3036 if (actualIsSimplyContiguous) 3037 return genBoxArg(*expr); 3038 fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr); 3039 mlir::Value isAssociated = 3040 fir::factory::genIsAllocatedOrAssociatedTest(builder, loc, 3041 mutableBox); 3042 fir::ExtendedValue actualExv = 3043 fir::factory::genMutableBoxRead(builder, loc, mutableBox); 3044 return genCopyIn(actualExv, arg, copyOutPairs, isAssociated); 3045 } 3046 if (const Fortran::semantics::Symbol *wholeSymbol = 3047 Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef( 3048 *expr)) 3049 if (Fortran::semantics::IsOptional(*wholeSymbol)) { 3050 ExtValue actualArg = gen(*expr); 3051 mlir::Value actualArgBase = fir::getBase(actualArg); 3052 if (!actualArgBase.getType().isa<fir::BoxType>()) 3053 return actualArg; 3054 // Do not read wholeSymbol descriptor that may be a nullptr in 3055 // case wholeSymbol is absent. 3056 // Absent descriptor cannot be read. To avoid any issue in 3057 // copy-in/copy-out, and when retrieving the address/length 3058 // create an descriptor pointing to a null address here if the 3059 // fir.box is absent. 3060 mlir::Value isPresent = builder.create<fir::IsPresentOp>( 3061 loc, builder.getI1Type(), actualArgBase); 3062 mlir::Type boxType = actualArgBase.getType(); 3063 mlir::Value emptyBox = fir::factory::createUnallocatedBox( 3064 builder, loc, boxType, llvm::None); 3065 auto safeToReadBox = builder.create<mlir::arith::SelectOp>( 3066 loc, isPresent, actualArgBase, emptyBox); 3067 fir::ExtendedValue safeToReadExv = 3068 fir::substBase(actualArg, safeToReadBox); 3069 if (actualIsSimplyContiguous) 3070 return safeToReadExv; 3071 return genCopyIn(safeToReadExv, arg, copyOutPairs, isPresent); 3072 } 3073 // Fall through: The actual argument can safely be 3074 // copied-in/copied-out without any care if needed. 3075 } 3076 if (actualArgIsVariable && expr->Rank() > 0) { 3077 ExtValue box = genBoxArg(*expr); 3078 if (!actualIsSimplyContiguous) 3079 return genCopyIn(box, arg, copyOutPairs, 3080 /*restrictCopyAtRuntime=*/llvm::None); 3081 // Contiguous: just use the box we created above! 3082 // This gets "unboxed" below, if needed. 3083 return box; 3084 } 3085 // Actual argument is a non optional/non pointer/non allocatable 3086 // scalar. 3087 if (actualArgIsVariable) 3088 return genExtAddr(*expr); 3089 // Actual argument is not a variable. Make sure a variable address is 3090 // not passed. 3091 return genTempExtAddr(*expr); 3092 }(); 3093 // Scalar and contiguous expressions may be lowered to a fir.box, 3094 // either to account for potential polymorphism, or because lowering 3095 // did not account for some contiguity hints. 3096 // Here, polymorphism does not matter (an entity of the declared type 3097 // is passed, not one of the dynamic type), and the expr is known to 3098 // be simply contiguous, so it is safe to unbox it and pass the 3099 // address without making a copy. 3100 argAddr = readIfBoxValue(argAddr); 3101 3102 if (arg.passBy == PassBy::BaseAddress) { 3103 caller.placeInput(arg, fir::getBase(argAddr)); 3104 } else { 3105 assert(arg.passBy == PassBy::BoxChar); 3106 auto helper = fir::factory::CharacterExprHelper{builder, loc}; 3107 auto boxChar = argAddr.match( 3108 [&](const fir::CharBoxValue &x) { return helper.createEmbox(x); }, 3109 [&](const fir::CharArrayBoxValue &x) { 3110 return helper.createEmbox(x); 3111 }, 3112 [&](const auto &x) -> mlir::Value { 3113 // Fortran allows an actual argument of a completely different 3114 // type to be passed to a procedure expecting a CHARACTER in the 3115 // dummy argument position. When this happens, the data pointer 3116 // argument is simply assumed to point to CHARACTER data and the 3117 // LEN argument used is garbage. Simulate this behavior by 3118 // free-casting the base address to be a !fir.char reference and 3119 // setting the LEN argument to undefined. What could go wrong? 3120 auto dataPtr = fir::getBase(x); 3121 assert(!dataPtr.getType().template isa<fir::BoxType>()); 3122 return builder.convertWithSemantics( 3123 loc, argTy, dataPtr, 3124 /*allowCharacterConversion=*/true); 3125 }); 3126 caller.placeInput(arg, boxChar); 3127 } 3128 } else if (arg.passBy == PassBy::Box) { 3129 // Before lowering to an address, handle the allocatable/pointer actual 3130 // argument to optional fir.box dummy. It is legal to pass 3131 // unallocated/disassociated entity to an optional. In this case, an 3132 // absent fir.box must be created instead of a fir.box with a null value 3133 // (Fortran 2018 15.5.2.12 point 1). 3134 if (arg.isOptional() && Fortran::evaluate::IsAllocatableOrPointerObject( 3135 *expr, converter.getFoldingContext())) { 3136 // Note that passing an absent allocatable to a non-allocatable 3137 // optional dummy argument is illegal (15.5.2.12 point 3 (8)). So 3138 // nothing has to be done to generate an absent argument in this case, 3139 // and it is OK to unconditionally read the mutable box here. 3140 fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr); 3141 mlir::Value isAllocated = 3142 fir::factory::genIsAllocatedOrAssociatedTest(builder, loc, 3143 mutableBox); 3144 auto absent = builder.create<fir::AbsentOp>(loc, argTy); 3145 /// For now, assume it is not OK to pass the allocatable/pointer 3146 /// descriptor to a non pointer/allocatable dummy. That is a strict 3147 /// interpretation of 18.3.6 point 4 that stipulates the descriptor 3148 /// has the dummy attributes in BIND(C) contexts. 3149 mlir::Value box = builder.createBox( 3150 loc, fir::factory::genMutableBoxRead(builder, loc, mutableBox)); 3151 // Need the box types to be exactly similar for the selectOp. 3152 mlir::Value convertedBox = builder.createConvert(loc, argTy, box); 3153 caller.placeInput(arg, builder.create<mlir::arith::SelectOp>( 3154 loc, isAllocated, convertedBox, absent)); 3155 } else { 3156 // Make sure a variable address is only passed if the expression is 3157 // actually a variable. 3158 mlir::Value box = 3159 actualArgIsVariable 3160 ? builder.createBox(loc, genBoxArg(*expr)) 3161 : builder.createBox(getLoc(), genTempExtAddr(*expr)); 3162 caller.placeInput(arg, box); 3163 } 3164 } else if (arg.passBy == PassBy::AddressAndLength) { 3165 ExtValue argRef = genExtAddr(*expr); 3166 caller.placeAddressAndLengthInput(arg, fir::getBase(argRef), 3167 fir::getLen(argRef)); 3168 } else if (arg.passBy == PassBy::CharProcTuple) { 3169 ExtValue argRef = genExtAddr(*expr); 3170 mlir::Value tuple = createBoxProcCharTuple( 3171 converter, argTy, fir::getBase(argRef), fir::getLen(argRef)); 3172 caller.placeInput(arg, tuple); 3173 } else { 3174 TODO(loc, "pass by value in non elemental function call"); 3175 } 3176 } 3177 3178 ExtValue result = genCallOpAndResult(caller, callSiteType, resultType); 3179 3180 // Sync pointers and allocatables that may have been modified during the 3181 // call. 3182 for (const auto &mutableBox : mutableModifiedByCall) 3183 fir::factory::syncMutableBoxFromIRBox(builder, loc, mutableBox); 3184 // Handle case where result was passed as argument 3185 3186 // Copy-out temps that were created for non contiguous variable arguments if 3187 // needed. 3188 for (const auto ©OutPair : copyOutPairs) 3189 genCopyOut(copyOutPair); 3190 3191 return result; 3192 } 3193 3194 template <typename A> 3195 ExtValue genval(const Fortran::evaluate::FunctionRef<A> &funcRef) { 3196 ExtValue result = genFunctionRef(funcRef); 3197 if (result.rank() == 0 && fir::isa_ref_type(fir::getBase(result).getType())) 3198 return genLoad(result); 3199 return result; 3200 } 3201 3202 ExtValue genval(const Fortran::evaluate::ProcedureRef &procRef) { 3203 llvm::Optional<mlir::Type> resTy; 3204 if (procRef.hasAlternateReturns()) 3205 resTy = builder.getIndexType(); 3206 return genProcedureRef(procRef, resTy); 3207 } 3208 3209 template <typename A> 3210 bool isScalar(const A &x) { 3211 return x.Rank() == 0; 3212 } 3213 3214 /// Helper to detect Transformational function reference. 3215 template <typename T> 3216 bool isTransformationalRef(const T &) { 3217 return false; 3218 } 3219 template <typename T> 3220 bool isTransformationalRef(const Fortran::evaluate::FunctionRef<T> &funcRef) { 3221 return !funcRef.IsElemental() && funcRef.Rank(); 3222 } 3223 template <typename T> 3224 bool isTransformationalRef(Fortran::evaluate::Expr<T> expr) { 3225 return std::visit([&](const auto &e) { return isTransformationalRef(e); }, 3226 expr.u); 3227 } 3228 3229 template <typename A> 3230 ExtValue asArray(const A &x) { 3231 return Fortran::lower::createSomeArrayTempValue(converter, toEvExpr(x), 3232 symMap, stmtCtx); 3233 } 3234 3235 /// Lower an array value as an argument. This argument can be passed as a box 3236 /// value, so it may be possible to avoid making a temporary. 3237 template <typename A> 3238 ExtValue asArrayArg(const Fortran::evaluate::Expr<A> &x) { 3239 return std::visit([&](const auto &e) { return asArrayArg(e, x); }, x.u); 3240 } 3241 template <typename A, typename B> 3242 ExtValue asArrayArg(const Fortran::evaluate::Expr<A> &x, const B &y) { 3243 return std::visit([&](const auto &e) { return asArrayArg(e, y); }, x.u); 3244 } 3245 template <typename A, typename B> 3246 ExtValue asArrayArg(const Fortran::evaluate::Designator<A> &, const B &x) { 3247 // Designator is being passed as an argument to a procedure. Lower the 3248 // expression to a boxed value. 3249 auto someExpr = toEvExpr(x); 3250 return Fortran::lower::createBoxValue(getLoc(), converter, someExpr, symMap, 3251 stmtCtx); 3252 } 3253 template <typename A, typename B> 3254 ExtValue asArrayArg(const A &, const B &x) { 3255 // If the expression to pass as an argument is not a designator, then create 3256 // an array temp. 3257 return asArray(x); 3258 } 3259 3260 template <typename A> 3261 ExtValue gen(const Fortran::evaluate::Expr<A> &x) { 3262 // Whole array symbols or components, and results of transformational 3263 // functions already have a storage and the scalar expression lowering path 3264 // is used to not create a new temporary storage. 3265 if (isScalar(x) || 3266 Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(x) || 3267 isTransformationalRef(x)) 3268 return std::visit([&](const auto &e) { return genref(e); }, x.u); 3269 if (useBoxArg) 3270 return asArrayArg(x); 3271 return asArray(x); 3272 } 3273 template <typename A> 3274 ExtValue genval(const Fortran::evaluate::Expr<A> &x) { 3275 if (isScalar(x) || Fortran::evaluate::UnwrapWholeSymbolDataRef(x) || 3276 inInitializer) 3277 return std::visit([&](const auto &e) { return genval(e); }, x.u); 3278 return asArray(x); 3279 } 3280 3281 template <int KIND> 3282 ExtValue genval(const Fortran::evaluate::Expr<Fortran::evaluate::Type< 3283 Fortran::common::TypeCategory::Logical, KIND>> &exp) { 3284 return std::visit([&](const auto &e) { return genval(e); }, exp.u); 3285 } 3286 3287 using RefSet = 3288 std::tuple<Fortran::evaluate::ComplexPart, Fortran::evaluate::Substring, 3289 Fortran::evaluate::DataRef, Fortran::evaluate::Component, 3290 Fortran::evaluate::ArrayRef, Fortran::evaluate::CoarrayRef, 3291 Fortran::semantics::SymbolRef>; 3292 template <typename A> 3293 static constexpr bool inRefSet = Fortran::common::HasMember<A, RefSet>; 3294 3295 template <typename A, typename = std::enable_if_t<inRefSet<A>>> 3296 ExtValue genref(const A &a) { 3297 return gen(a); 3298 } 3299 template <typename A> 3300 ExtValue genref(const A &a) { 3301 if (inInitializer) { 3302 // Initialization expressions can never allocate memory. 3303 return genval(a); 3304 } 3305 mlir::Type storageType = converter.genType(toEvExpr(a)); 3306 return placeScalarValueInMemory(builder, getLoc(), genval(a), storageType); 3307 } 3308 3309 template <typename A, template <typename> typename T, 3310 typename B = std::decay_t<T<A>>, 3311 std::enable_if_t< 3312 std::is_same_v<B, Fortran::evaluate::Expr<A>> || 3313 std::is_same_v<B, Fortran::evaluate::Designator<A>> || 3314 std::is_same_v<B, Fortran::evaluate::FunctionRef<A>>, 3315 bool> = true> 3316 ExtValue genref(const T<A> &x) { 3317 return gen(x); 3318 } 3319 3320 private: 3321 mlir::Location location; 3322 Fortran::lower::AbstractConverter &converter; 3323 fir::FirOpBuilder &builder; 3324 Fortran::lower::StatementContext &stmtCtx; 3325 Fortran::lower::SymMap &symMap; 3326 InitializerData *inInitializer = nullptr; 3327 bool useBoxArg = false; // expression lowered as argument 3328 }; 3329 } // namespace 3330 3331 // Helper for changing the semantics in a given context. Preserves the current 3332 // semantics which is resumed when the "push" goes out of scope. 3333 #define PushSemantics(PushVal) \ 3334 [[maybe_unused]] auto pushSemanticsLocalVariable##__LINE__ = \ 3335 Fortran::common::ScopedSet(semant, PushVal); 3336 3337 static bool isAdjustedArrayElementType(mlir::Type t) { 3338 return fir::isa_char(t) || fir::isa_derived(t) || t.isa<fir::SequenceType>(); 3339 } 3340 static bool elementTypeWasAdjusted(mlir::Type t) { 3341 if (auto ty = t.dyn_cast<fir::ReferenceType>()) 3342 return isAdjustedArrayElementType(ty.getEleTy()); 3343 return false; 3344 } 3345 static mlir::Type adjustedArrayElementType(mlir::Type t) { 3346 return isAdjustedArrayElementType(t) ? fir::ReferenceType::get(t) : t; 3347 } 3348 3349 /// Helper to generate calls to scalar user defined assignment procedures. 3350 static void genScalarUserDefinedAssignmentCall(fir::FirOpBuilder &builder, 3351 mlir::Location loc, 3352 mlir::func::FuncOp func, 3353 const fir::ExtendedValue &lhs, 3354 const fir::ExtendedValue &rhs) { 3355 auto prepareUserDefinedArg = 3356 [](fir::FirOpBuilder &builder, mlir::Location loc, 3357 const fir::ExtendedValue &value, mlir::Type argType) -> mlir::Value { 3358 if (argType.isa<fir::BoxCharType>()) { 3359 const fir::CharBoxValue *charBox = value.getCharBox(); 3360 assert(charBox && "argument type mismatch in elemental user assignment"); 3361 return fir::factory::CharacterExprHelper{builder, loc}.createEmbox( 3362 *charBox); 3363 } 3364 if (argType.isa<fir::BoxType>()) { 3365 mlir::Value box = builder.createBox(loc, value); 3366 return builder.createConvert(loc, argType, box); 3367 } 3368 // Simple pass by address. 3369 mlir::Type argBaseType = fir::unwrapRefType(argType); 3370 assert(!fir::hasDynamicSize(argBaseType)); 3371 mlir::Value from = fir::getBase(value); 3372 if (argBaseType != fir::unwrapRefType(from.getType())) { 3373 // With logicals, it is possible that from is i1 here. 3374 if (fir::isa_ref_type(from.getType())) 3375 from = builder.create<fir::LoadOp>(loc, from); 3376 from = builder.createConvert(loc, argBaseType, from); 3377 } 3378 if (!fir::isa_ref_type(from.getType())) { 3379 mlir::Value temp = builder.createTemporary(loc, argBaseType); 3380 builder.create<fir::StoreOp>(loc, from, temp); 3381 from = temp; 3382 } 3383 return builder.createConvert(loc, argType, from); 3384 }; 3385 assert(func.getNumArguments() == 2); 3386 mlir::Type lhsType = func.getFunctionType().getInput(0); 3387 mlir::Type rhsType = func.getFunctionType().getInput(1); 3388 mlir::Value lhsArg = prepareUserDefinedArg(builder, loc, lhs, lhsType); 3389 mlir::Value rhsArg = prepareUserDefinedArg(builder, loc, rhs, rhsType); 3390 builder.create<fir::CallOp>(loc, func, mlir::ValueRange{lhsArg, rhsArg}); 3391 } 3392 3393 /// Convert the result of a fir.array_modify to an ExtendedValue given the 3394 /// related fir.array_load. 3395 static fir::ExtendedValue arrayModifyToExv(fir::FirOpBuilder &builder, 3396 mlir::Location loc, 3397 fir::ArrayLoadOp load, 3398 mlir::Value elementAddr) { 3399 mlir::Type eleTy = fir::unwrapPassByRefType(elementAddr.getType()); 3400 if (fir::isa_char(eleTy)) { 3401 auto len = fir::factory::CharacterExprHelper{builder, loc}.getLength( 3402 load.getMemref()); 3403 if (!len) { 3404 assert(load.getTypeparams().size() == 1 && 3405 "length must be in array_load"); 3406 len = load.getTypeparams()[0]; 3407 } 3408 return fir::CharBoxValue{elementAddr, len}; 3409 } 3410 return elementAddr; 3411 } 3412 3413 //===----------------------------------------------------------------------===// 3414 // 3415 // Lowering of scalar expressions in an explicit iteration space context. 3416 // 3417 //===----------------------------------------------------------------------===// 3418 3419 // Shared code for creating a copy of a derived type element. This function is 3420 // called from a continuation. 3421 inline static fir::ArrayAmendOp 3422 createDerivedArrayAmend(mlir::Location loc, fir::ArrayLoadOp destLoad, 3423 fir::FirOpBuilder &builder, fir::ArrayAccessOp destAcc, 3424 const fir::ExtendedValue &elementExv, mlir::Type eleTy, 3425 mlir::Value innerArg) { 3426 if (destLoad.getTypeparams().empty()) { 3427 fir::factory::genRecordAssignment(builder, loc, destAcc, elementExv); 3428 } else { 3429 auto boxTy = fir::BoxType::get(eleTy); 3430 auto toBox = builder.create<fir::EmboxOp>(loc, boxTy, destAcc.getResult(), 3431 mlir::Value{}, mlir::Value{}, 3432 destLoad.getTypeparams()); 3433 auto fromBox = builder.create<fir::EmboxOp>( 3434 loc, boxTy, fir::getBase(elementExv), mlir::Value{}, mlir::Value{}, 3435 destLoad.getTypeparams()); 3436 fir::factory::genRecordAssignment(builder, loc, fir::BoxValue(toBox), 3437 fir::BoxValue(fromBox)); 3438 } 3439 return builder.create<fir::ArrayAmendOp>(loc, innerArg.getType(), innerArg, 3440 destAcc); 3441 } 3442 3443 inline static fir::ArrayAmendOp 3444 createCharArrayAmend(mlir::Location loc, fir::FirOpBuilder &builder, 3445 fir::ArrayAccessOp dstOp, mlir::Value &dstLen, 3446 const fir::ExtendedValue &srcExv, mlir::Value innerArg, 3447 llvm::ArrayRef<mlir::Value> bounds) { 3448 fir::CharBoxValue dstChar(dstOp, dstLen); 3449 fir::factory::CharacterExprHelper helper{builder, loc}; 3450 if (!bounds.empty()) { 3451 dstChar = helper.createSubstring(dstChar, bounds); 3452 fir::factory::genCharacterCopy(fir::getBase(srcExv), fir::getLen(srcExv), 3453 dstChar.getAddr(), dstChar.getLen(), builder, 3454 loc); 3455 // Update the LEN to the substring's LEN. 3456 dstLen = dstChar.getLen(); 3457 } 3458 // For a CHARACTER, we generate the element assignment loops inline. 3459 helper.createAssign(fir::ExtendedValue{dstChar}, srcExv); 3460 // Mark this array element as amended. 3461 mlir::Type ty = innerArg.getType(); 3462 auto amend = builder.create<fir::ArrayAmendOp>(loc, ty, innerArg, dstOp); 3463 return amend; 3464 } 3465 3466 /// Build an ExtendedValue from a fir.array<?x...?xT> without actually setting 3467 /// the actual extents and lengths. This is only to allow their propagation as 3468 /// ExtendedValue without triggering verifier failures when propagating 3469 /// character/arrays as unboxed values. Only the base of the resulting 3470 /// ExtendedValue should be used, it is undefined to use the length or extents 3471 /// of the extended value returned, 3472 inline static fir::ExtendedValue 3473 convertToArrayBoxValue(mlir::Location loc, fir::FirOpBuilder &builder, 3474 mlir::Value val, mlir::Value len) { 3475 mlir::Type ty = fir::unwrapRefType(val.getType()); 3476 mlir::IndexType idxTy = builder.getIndexType(); 3477 auto seqTy = ty.cast<fir::SequenceType>(); 3478 auto undef = builder.create<fir::UndefOp>(loc, idxTy); 3479 llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), undef); 3480 if (fir::isa_char(seqTy.getEleTy())) 3481 return fir::CharArrayBoxValue(val, len ? len : undef, extents); 3482 return fir::ArrayBoxValue(val, extents); 3483 } 3484 3485 //===----------------------------------------------------------------------===// 3486 // 3487 // Lowering of array expressions. 3488 // 3489 //===----------------------------------------------------------------------===// 3490 3491 namespace { 3492 class ArrayExprLowering { 3493 using ExtValue = fir::ExtendedValue; 3494 3495 /// Structure to keep track of lowered array operands in the 3496 /// array expression. Useful to later deduce the shape of the 3497 /// array expression. 3498 struct ArrayOperand { 3499 /// Array base (can be a fir.box). 3500 mlir::Value memref; 3501 /// ShapeOp, ShapeShiftOp or ShiftOp 3502 mlir::Value shape; 3503 /// SliceOp 3504 mlir::Value slice; 3505 /// Can this operand be absent ? 3506 bool mayBeAbsent = false; 3507 }; 3508 3509 using ImplicitSubscripts = Fortran::lower::details::ImplicitSubscripts; 3510 using PathComponent = Fortran::lower::PathComponent; 3511 3512 /// Active iteration space. 3513 using IterationSpace = Fortran::lower::IterationSpace; 3514 using IterSpace = const Fortran::lower::IterationSpace &; 3515 3516 /// Current continuation. Function that will generate IR for a single 3517 /// iteration of the pending iterative loop structure. 3518 using CC = Fortran::lower::GenerateElementalArrayFunc; 3519 3520 /// Projection continuation. Function that will project one iteration space 3521 /// into another. 3522 using PC = std::function<IterationSpace(IterSpace)>; 3523 using ArrayBaseTy = 3524 std::variant<std::monostate, const Fortran::evaluate::ArrayRef *, 3525 const Fortran::evaluate::DataRef *>; 3526 using ComponentPath = Fortran::lower::ComponentPath; 3527 3528 public: 3529 //===--------------------------------------------------------------------===// 3530 // Regular array assignment 3531 //===--------------------------------------------------------------------===// 3532 3533 /// Entry point for array assignments. Both the left-hand and right-hand sides 3534 /// can either be ExtendedValue or evaluate::Expr. 3535 template <typename TL, typename TR> 3536 static void lowerArrayAssignment(Fortran::lower::AbstractConverter &converter, 3537 Fortran::lower::SymMap &symMap, 3538 Fortran::lower::StatementContext &stmtCtx, 3539 const TL &lhs, const TR &rhs) { 3540 ArrayExprLowering ael(converter, stmtCtx, symMap, 3541 ConstituentSemantics::CopyInCopyOut); 3542 ael.lowerArrayAssignment(lhs, rhs); 3543 } 3544 3545 template <typename TL, typename TR> 3546 void lowerArrayAssignment(const TL &lhs, const TR &rhs) { 3547 mlir::Location loc = getLoc(); 3548 /// Here the target subspace is not necessarily contiguous. The ArrayUpdate 3549 /// continuation is implicitly returned in `ccStoreToDest` and the ArrayLoad 3550 /// in `destination`. 3551 PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut); 3552 ccStoreToDest = genarr(lhs); 3553 determineShapeOfDest(lhs); 3554 semant = ConstituentSemantics::RefTransparent; 3555 ExtValue exv = lowerArrayExpression(rhs); 3556 if (explicitSpaceIsActive()) { 3557 explicitSpace->finalizeContext(); 3558 builder.create<fir::ResultOp>(loc, fir::getBase(exv)); 3559 } else { 3560 builder.create<fir::ArrayMergeStoreOp>( 3561 loc, destination, fir::getBase(exv), destination.getMemref(), 3562 destination.getSlice(), destination.getTypeparams()); 3563 } 3564 } 3565 3566 //===--------------------------------------------------------------------===// 3567 // WHERE array assignment, FORALL assignment, and FORALL+WHERE array 3568 // assignment 3569 //===--------------------------------------------------------------------===// 3570 3571 /// Entry point for array assignment when the iteration space is explicitly 3572 /// defined (Fortran's FORALL) with or without masks, and/or the implied 3573 /// iteration space involves masks (Fortran's WHERE). Both contexts (explicit 3574 /// space and implicit space with masks) may be present. 3575 static void lowerAnyMaskedArrayAssignment( 3576 Fortran::lower::AbstractConverter &converter, 3577 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 3578 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 3579 Fortran::lower::ExplicitIterSpace &explicitSpace, 3580 Fortran::lower::ImplicitIterSpace &implicitSpace) { 3581 if (explicitSpace.isActive() && lhs.Rank() == 0) { 3582 // Scalar assignment expression in a FORALL context. 3583 ArrayExprLowering ael(converter, stmtCtx, symMap, 3584 ConstituentSemantics::RefTransparent, 3585 &explicitSpace, &implicitSpace); 3586 ael.lowerScalarAssignment(lhs, rhs); 3587 return; 3588 } 3589 // Array assignment expression in a FORALL and/or WHERE context. 3590 ArrayExprLowering ael(converter, stmtCtx, symMap, 3591 ConstituentSemantics::CopyInCopyOut, &explicitSpace, 3592 &implicitSpace); 3593 ael.lowerArrayAssignment(lhs, rhs); 3594 } 3595 3596 //===--------------------------------------------------------------------===// 3597 // Array assignment to array of pointer box values. 3598 //===--------------------------------------------------------------------===// 3599 3600 /// Entry point for assignment to pointer in an array of pointers. 3601 static void lowerArrayOfPointerAssignment( 3602 Fortran::lower::AbstractConverter &converter, 3603 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 3604 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 3605 Fortran::lower::ExplicitIterSpace &explicitSpace, 3606 Fortran::lower::ImplicitIterSpace &implicitSpace, 3607 const llvm::SmallVector<mlir::Value> &lbounds, 3608 llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds) { 3609 ArrayExprLowering ael(converter, stmtCtx, symMap, 3610 ConstituentSemantics::CopyInCopyOut, &explicitSpace, 3611 &implicitSpace); 3612 ael.lowerArrayOfPointerAssignment(lhs, rhs, lbounds, ubounds); 3613 } 3614 3615 /// Scalar pointer assignment in an explicit iteration space. 3616 /// 3617 /// Pointers may be bound to targets in a FORALL context. This is a scalar 3618 /// assignment in the sense there is never an implied iteration space, even if 3619 /// the pointer is to a target with non-zero rank. Since the pointer 3620 /// assignment must appear in a FORALL construct, correctness may require that 3621 /// the array of pointers follow copy-in/copy-out semantics. The pointer 3622 /// assignment may include a bounds-spec (lower bounds), a bounds-remapping 3623 /// (lower and upper bounds), or neither. 3624 void lowerArrayOfPointerAssignment( 3625 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 3626 const llvm::SmallVector<mlir::Value> &lbounds, 3627 llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds) { 3628 setPointerAssignmentBounds(lbounds, ubounds); 3629 if (rhs.Rank() == 0 || 3630 (Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(rhs) && 3631 Fortran::evaluate::IsAllocatableOrPointerObject( 3632 rhs, converter.getFoldingContext()))) { 3633 lowerScalarAssignment(lhs, rhs); 3634 return; 3635 } 3636 TODO(getLoc(), 3637 "auto boxing of a ranked expression on RHS for pointer assignment"); 3638 } 3639 3640 //===--------------------------------------------------------------------===// 3641 // Array assignment to allocatable array 3642 //===--------------------------------------------------------------------===// 3643 3644 /// Entry point for assignment to allocatable array. 3645 static void lowerAllocatableArrayAssignment( 3646 Fortran::lower::AbstractConverter &converter, 3647 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 3648 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 3649 Fortran::lower::ExplicitIterSpace &explicitSpace, 3650 Fortran::lower::ImplicitIterSpace &implicitSpace) { 3651 ArrayExprLowering ael(converter, stmtCtx, symMap, 3652 ConstituentSemantics::CopyInCopyOut, &explicitSpace, 3653 &implicitSpace); 3654 ael.lowerAllocatableArrayAssignment(lhs, rhs); 3655 } 3656 3657 /// Assignment to allocatable array. 3658 /// 3659 /// The semantics are reverse that of a "regular" array assignment. The rhs 3660 /// defines the iteration space of the computation and the lhs is 3661 /// resized/reallocated to fit if necessary. 3662 void lowerAllocatableArrayAssignment(const Fortran::lower::SomeExpr &lhs, 3663 const Fortran::lower::SomeExpr &rhs) { 3664 // With assignment to allocatable, we want to lower the rhs first and use 3665 // its shape to determine if we need to reallocate, etc. 3666 mlir::Location loc = getLoc(); 3667 // FIXME: If the lhs is in an explicit iteration space, the assignment may 3668 // be to an array of allocatable arrays rather than a single allocatable 3669 // array. 3670 fir::MutableBoxValue mutableBox = 3671 Fortran::lower::createMutableBox(loc, converter, lhs, symMap); 3672 mlir::Type resultTy = converter.genType(rhs); 3673 if (rhs.Rank() > 0) 3674 determineShapeOfDest(rhs); 3675 auto rhsCC = [&]() { 3676 PushSemantics(ConstituentSemantics::RefTransparent); 3677 return genarr(rhs); 3678 }(); 3679 3680 llvm::SmallVector<mlir::Value> lengthParams; 3681 // Currently no safe way to gather length from rhs (at least for 3682 // character, it cannot be taken from array_loads since it may be 3683 // changed by concatenations). 3684 if ((mutableBox.isCharacter() && !mutableBox.hasNonDeferredLenParams()) || 3685 mutableBox.isDerivedWithLenParameters()) 3686 TODO(loc, "gather rhs length parameters in assignment to allocatable"); 3687 3688 // The allocatable must take lower bounds from the expr if it is 3689 // reallocated and the right hand side is not a scalar. 3690 const bool takeLboundsIfRealloc = rhs.Rank() > 0; 3691 llvm::SmallVector<mlir::Value> lbounds; 3692 // When the reallocated LHS takes its lower bounds from the RHS, 3693 // they will be non default only if the RHS is a whole array 3694 // variable. Otherwise, lbounds is left empty and default lower bounds 3695 // will be used. 3696 if (takeLboundsIfRealloc && 3697 Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(rhs)) { 3698 assert(arrayOperands.size() == 1 && 3699 "lbounds can only come from one array"); 3700 auto lbs = fir::factory::getOrigins(arrayOperands[0].shape); 3701 lbounds.append(lbs.begin(), lbs.end()); 3702 } 3703 fir::factory::MutableBoxReallocation realloc = 3704 fir::factory::genReallocIfNeeded(builder, loc, mutableBox, destShape, 3705 lengthParams); 3706 // Create ArrayLoad for the mutable box and save it into `destination`. 3707 PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut); 3708 ccStoreToDest = genarr(realloc.newValue); 3709 // If the rhs is scalar, get shape from the allocatable ArrayLoad. 3710 if (destShape.empty()) 3711 destShape = getShape(destination); 3712 // Finish lowering the loop nest. 3713 assert(destination && "destination must have been set"); 3714 ExtValue exv = lowerArrayExpression(rhsCC, resultTy); 3715 if (explicitSpaceIsActive()) { 3716 explicitSpace->finalizeContext(); 3717 builder.create<fir::ResultOp>(loc, fir::getBase(exv)); 3718 } else { 3719 builder.create<fir::ArrayMergeStoreOp>( 3720 loc, destination, fir::getBase(exv), destination.getMemref(), 3721 destination.getSlice(), destination.getTypeparams()); 3722 } 3723 fir::factory::finalizeRealloc(builder, loc, mutableBox, lbounds, 3724 takeLboundsIfRealloc, realloc); 3725 } 3726 3727 /// Entry point for when an array expression appears in a context where the 3728 /// result must be boxed. (BoxValue semantics.) 3729 static ExtValue 3730 lowerBoxedArrayExpression(Fortran::lower::AbstractConverter &converter, 3731 Fortran::lower::SymMap &symMap, 3732 Fortran::lower::StatementContext &stmtCtx, 3733 const Fortran::lower::SomeExpr &expr) { 3734 ArrayExprLowering ael{converter, stmtCtx, symMap, 3735 ConstituentSemantics::BoxValue}; 3736 return ael.lowerBoxedArrayExpr(expr); 3737 } 3738 3739 ExtValue lowerBoxedArrayExpr(const Fortran::lower::SomeExpr &exp) { 3740 PushSemantics(ConstituentSemantics::BoxValue); 3741 return std::visit( 3742 [&](const auto &e) { 3743 auto f = genarr(e); 3744 ExtValue exv = f(IterationSpace{}); 3745 if (fir::getBase(exv).getType().template isa<fir::BoxType>()) 3746 return exv; 3747 fir::emitFatalError(getLoc(), "array must be emboxed"); 3748 }, 3749 exp.u); 3750 } 3751 3752 /// Entry point into lowering an expression with rank. This entry point is for 3753 /// lowering a rhs expression, for example. (RefTransparent semantics.) 3754 static ExtValue 3755 lowerNewArrayExpression(Fortran::lower::AbstractConverter &converter, 3756 Fortran::lower::SymMap &symMap, 3757 Fortran::lower::StatementContext &stmtCtx, 3758 const Fortran::lower::SomeExpr &expr) { 3759 ArrayExprLowering ael{converter, stmtCtx, symMap}; 3760 ael.determineShapeOfDest(expr); 3761 ExtValue loopRes = ael.lowerArrayExpression(expr); 3762 fir::ArrayLoadOp dest = ael.destination; 3763 mlir::Value tempRes = dest.getMemref(); 3764 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 3765 mlir::Location loc = converter.getCurrentLocation(); 3766 builder.create<fir::ArrayMergeStoreOp>(loc, dest, fir::getBase(loopRes), 3767 tempRes, dest.getSlice(), 3768 dest.getTypeparams()); 3769 3770 auto arrTy = 3771 fir::dyn_cast_ptrEleTy(tempRes.getType()).cast<fir::SequenceType>(); 3772 if (auto charTy = 3773 arrTy.getEleTy().template dyn_cast<fir::CharacterType>()) { 3774 if (fir::characterWithDynamicLen(charTy)) 3775 TODO(loc, "CHARACTER does not have constant LEN"); 3776 mlir::Value len = builder.createIntegerConstant( 3777 loc, builder.getCharacterLengthType(), charTy.getLen()); 3778 return fir::CharArrayBoxValue(tempRes, len, dest.getExtents()); 3779 } 3780 return fir::ArrayBoxValue(tempRes, dest.getExtents()); 3781 } 3782 3783 static void lowerLazyArrayExpression( 3784 Fortran::lower::AbstractConverter &converter, 3785 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 3786 const Fortran::lower::SomeExpr &expr, mlir::Value raggedHeader) { 3787 ArrayExprLowering ael(converter, stmtCtx, symMap); 3788 ael.lowerLazyArrayExpression(expr, raggedHeader); 3789 } 3790 3791 /// Lower the expression \p expr into a buffer that is created on demand. The 3792 /// variable containing the pointer to the buffer is \p var and the variable 3793 /// containing the shape of the buffer is \p shapeBuffer. 3794 void lowerLazyArrayExpression(const Fortran::lower::SomeExpr &expr, 3795 mlir::Value header) { 3796 mlir::Location loc = getLoc(); 3797 mlir::TupleType hdrTy = fir::factory::getRaggedArrayHeaderType(builder); 3798 mlir::IntegerType i32Ty = builder.getIntegerType(32); 3799 3800 // Once the loop extents have been computed, which may require being inside 3801 // some explicit loops, lazily allocate the expression on the heap. The 3802 // following continuation creates the buffer as needed. 3803 ccPrelude = [=](llvm::ArrayRef<mlir::Value> shape) { 3804 mlir::IntegerType i64Ty = builder.getIntegerType(64); 3805 mlir::Value byteSize = builder.createIntegerConstant(loc, i64Ty, 1); 3806 fir::runtime::genRaggedArrayAllocate( 3807 loc, builder, header, /*asHeaders=*/false, byteSize, shape); 3808 }; 3809 3810 // Create a dummy array_load before the loop. We're storing to a lazy 3811 // temporary, so there will be no conflict and no copy-in. TODO: skip this 3812 // as there isn't any necessity for it. 3813 ccLoadDest = [=](llvm::ArrayRef<mlir::Value> shape) -> fir::ArrayLoadOp { 3814 mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1); 3815 auto var = builder.create<fir::CoordinateOp>( 3816 loc, builder.getRefType(hdrTy.getType(1)), header, one); 3817 auto load = builder.create<fir::LoadOp>(loc, var); 3818 mlir::Type eleTy = 3819 fir::unwrapSequenceType(fir::unwrapRefType(load.getType())); 3820 auto seqTy = fir::SequenceType::get(eleTy, shape.size()); 3821 mlir::Value castTo = 3822 builder.createConvert(loc, fir::HeapType::get(seqTy), load); 3823 mlir::Value shapeOp = builder.genShape(loc, shape); 3824 return builder.create<fir::ArrayLoadOp>( 3825 loc, seqTy, castTo, shapeOp, /*slice=*/mlir::Value{}, llvm::None); 3826 }; 3827 // Custom lowering of the element store to deal with the extra indirection 3828 // to the lazy allocated buffer. 3829 ccStoreToDest = [=](IterSpace iters) { 3830 mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1); 3831 auto var = builder.create<fir::CoordinateOp>( 3832 loc, builder.getRefType(hdrTy.getType(1)), header, one); 3833 auto load = builder.create<fir::LoadOp>(loc, var); 3834 mlir::Type eleTy = 3835 fir::unwrapSequenceType(fir::unwrapRefType(load.getType())); 3836 auto seqTy = fir::SequenceType::get(eleTy, iters.iterVec().size()); 3837 auto toTy = fir::HeapType::get(seqTy); 3838 mlir::Value castTo = builder.createConvert(loc, toTy, load); 3839 mlir::Value shape = builder.genShape(loc, genIterationShape()); 3840 llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices( 3841 loc, builder, castTo.getType(), shape, iters.iterVec()); 3842 auto eleAddr = builder.create<fir::ArrayCoorOp>( 3843 loc, builder.getRefType(eleTy), castTo, shape, 3844 /*slice=*/mlir::Value{}, indices, destination.getTypeparams()); 3845 mlir::Value eleVal = 3846 builder.createConvert(loc, eleTy, iters.getElement()); 3847 builder.create<fir::StoreOp>(loc, eleVal, eleAddr); 3848 return iters.innerArgument(); 3849 }; 3850 3851 // Lower the array expression now. Clean-up any temps that may have 3852 // been generated when lowering `expr` right after the lowered value 3853 // was stored to the ragged array temporary. The local temps will not 3854 // be needed afterwards. 3855 stmtCtx.pushScope(); 3856 [[maybe_unused]] ExtValue loopRes = lowerArrayExpression(expr); 3857 stmtCtx.finalize(/*popScope=*/true); 3858 assert(fir::getBase(loopRes)); 3859 } 3860 3861 static void 3862 lowerElementalUserAssignment(Fortran::lower::AbstractConverter &converter, 3863 Fortran::lower::SymMap &symMap, 3864 Fortran::lower::StatementContext &stmtCtx, 3865 Fortran::lower::ExplicitIterSpace &explicitSpace, 3866 Fortran::lower::ImplicitIterSpace &implicitSpace, 3867 const Fortran::evaluate::ProcedureRef &procRef) { 3868 ArrayExprLowering ael(converter, stmtCtx, symMap, 3869 ConstituentSemantics::CustomCopyInCopyOut, 3870 &explicitSpace, &implicitSpace); 3871 assert(procRef.arguments().size() == 2); 3872 const auto *lhs = procRef.arguments()[0].value().UnwrapExpr(); 3873 const auto *rhs = procRef.arguments()[1].value().UnwrapExpr(); 3874 assert(lhs && rhs && 3875 "user defined assignment arguments must be expressions"); 3876 mlir::func::FuncOp func = 3877 Fortran::lower::CallerInterface(procRef, converter).getFuncOp(); 3878 ael.lowerElementalUserAssignment(func, *lhs, *rhs); 3879 } 3880 3881 void lowerElementalUserAssignment(mlir::func::FuncOp userAssignment, 3882 const Fortran::lower::SomeExpr &lhs, 3883 const Fortran::lower::SomeExpr &rhs) { 3884 mlir::Location loc = getLoc(); 3885 PushSemantics(ConstituentSemantics::CustomCopyInCopyOut); 3886 auto genArrayModify = genarr(lhs); 3887 ccStoreToDest = [=](IterSpace iters) -> ExtValue { 3888 auto modifiedArray = genArrayModify(iters); 3889 auto arrayModify = mlir::dyn_cast_or_null<fir::ArrayModifyOp>( 3890 fir::getBase(modifiedArray).getDefiningOp()); 3891 assert(arrayModify && "must be created by ArrayModifyOp"); 3892 fir::ExtendedValue lhs = 3893 arrayModifyToExv(builder, loc, destination, arrayModify.getResult(0)); 3894 genScalarUserDefinedAssignmentCall(builder, loc, userAssignment, lhs, 3895 iters.elementExv()); 3896 return modifiedArray; 3897 }; 3898 determineShapeOfDest(lhs); 3899 semant = ConstituentSemantics::RefTransparent; 3900 auto exv = lowerArrayExpression(rhs); 3901 if (explicitSpaceIsActive()) { 3902 explicitSpace->finalizeContext(); 3903 builder.create<fir::ResultOp>(loc, fir::getBase(exv)); 3904 } else { 3905 builder.create<fir::ArrayMergeStoreOp>( 3906 loc, destination, fir::getBase(exv), destination.getMemref(), 3907 destination.getSlice(), destination.getTypeparams()); 3908 } 3909 } 3910 3911 /// Lower an elemental subroutine call with at least one array argument. 3912 /// An elemental subroutine is an exception and does not have copy-in/copy-out 3913 /// semantics. See 15.8.3. 3914 /// Do NOT use this for user defined assignments. 3915 static void 3916 lowerElementalSubroutine(Fortran::lower::AbstractConverter &converter, 3917 Fortran::lower::SymMap &symMap, 3918 Fortran::lower::StatementContext &stmtCtx, 3919 const Fortran::lower::SomeExpr &call) { 3920 ArrayExprLowering ael(converter, stmtCtx, symMap, 3921 ConstituentSemantics::RefTransparent); 3922 ael.lowerElementalSubroutine(call); 3923 } 3924 3925 // TODO: See the comment in genarr(const Fortran::lower::Parentheses<T>&). 3926 // This is skipping generation of copy-in/copy-out code for analysis that is 3927 // required when arguments are in parentheses. 3928 void lowerElementalSubroutine(const Fortran::lower::SomeExpr &call) { 3929 auto f = genarr(call); 3930 llvm::SmallVector<mlir::Value> shape = genIterationShape(); 3931 auto [iterSpace, insPt] = genImplicitLoops(shape, /*innerArg=*/{}); 3932 f(iterSpace); 3933 finalizeElementCtx(); 3934 builder.restoreInsertionPoint(insPt); 3935 } 3936 3937 ExtValue lowerScalarAssignment(const Fortran::lower::SomeExpr &lhs, 3938 const Fortran::lower::SomeExpr &rhs) { 3939 PushSemantics(ConstituentSemantics::RefTransparent); 3940 // 1) Lower the rhs expression with array_fetch op(s). 3941 IterationSpace iters; 3942 iters.setElement(genarr(rhs)(iters)); 3943 // 2) Lower the lhs expression to an array_update. 3944 semant = ConstituentSemantics::ProjectedCopyInCopyOut; 3945 auto lexv = genarr(lhs)(iters); 3946 // 3) Finalize the inner context. 3947 explicitSpace->finalizeContext(); 3948 // 4) Thread the array value updated forward. Note: the lhs might be 3949 // ill-formed (performing scalar assignment in an array context), 3950 // in which case there is no array to thread. 3951 auto createResult = [&](auto op) { 3952 mlir::Value oldInnerArg = op.getSequence(); 3953 std::size_t offset = explicitSpace->argPosition(oldInnerArg); 3954 explicitSpace->setInnerArg(offset, fir::getBase(lexv)); 3955 builder.create<fir::ResultOp>(getLoc(), fir::getBase(lexv)); 3956 }; 3957 llvm::TypeSwitch<mlir::Operation *, void>( 3958 fir::getBase(lexv).getDefiningOp()) 3959 .Case([&](fir::ArrayUpdateOp op) { createResult(op); }) 3960 .Case([&](fir::ArrayAmendOp op) { createResult(op); }) 3961 .Case([&](fir::ArrayModifyOp op) { createResult(op); }) 3962 .Default([&](mlir::Operation *) {}); 3963 return lexv; 3964 } 3965 3966 static ExtValue lowerScalarUserAssignment( 3967 Fortran::lower::AbstractConverter &converter, 3968 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 3969 Fortran::lower::ExplicitIterSpace &explicitIterSpace, 3970 mlir::func::FuncOp userAssignmentFunction, 3971 const Fortran::lower::SomeExpr &lhs, 3972 const Fortran::lower::SomeExpr &rhs) { 3973 Fortran::lower::ImplicitIterSpace implicit; 3974 ArrayExprLowering ael(converter, stmtCtx, symMap, 3975 ConstituentSemantics::RefTransparent, 3976 &explicitIterSpace, &implicit); 3977 return ael.lowerScalarUserAssignment(userAssignmentFunction, lhs, rhs); 3978 } 3979 3980 ExtValue lowerScalarUserAssignment(mlir::func::FuncOp userAssignment, 3981 const Fortran::lower::SomeExpr &lhs, 3982 const Fortran::lower::SomeExpr &rhs) { 3983 mlir::Location loc = getLoc(); 3984 if (rhs.Rank() > 0) 3985 TODO(loc, "user-defined elemental assigment from expression with rank"); 3986 // 1) Lower the rhs expression with array_fetch op(s). 3987 IterationSpace iters; 3988 iters.setElement(genarr(rhs)(iters)); 3989 fir::ExtendedValue elementalExv = iters.elementExv(); 3990 // 2) Lower the lhs expression to an array_modify. 3991 semant = ConstituentSemantics::CustomCopyInCopyOut; 3992 auto lexv = genarr(lhs)(iters); 3993 bool isIllFormedLHS = false; 3994 // 3) Insert the call 3995 if (auto modifyOp = mlir::dyn_cast<fir::ArrayModifyOp>( 3996 fir::getBase(lexv).getDefiningOp())) { 3997 mlir::Value oldInnerArg = modifyOp.getSequence(); 3998 std::size_t offset = explicitSpace->argPosition(oldInnerArg); 3999 explicitSpace->setInnerArg(offset, fir::getBase(lexv)); 4000 fir::ExtendedValue exv = arrayModifyToExv( 4001 builder, loc, *explicitSpace->getLhsLoad(0), modifyOp.getResult(0)); 4002 genScalarUserDefinedAssignmentCall(builder, loc, userAssignment, exv, 4003 elementalExv); 4004 } else { 4005 // LHS is ill formed, it is a scalar with no references to FORALL 4006 // subscripts, so there is actually no array assignment here. The user 4007 // code is probably bad, but still insert user assignment call since it 4008 // was not rejected by semantics (a warning was emitted). 4009 isIllFormedLHS = true; 4010 genScalarUserDefinedAssignmentCall(builder, getLoc(), userAssignment, 4011 lexv, elementalExv); 4012 } 4013 // 4) Finalize the inner context. 4014 explicitSpace->finalizeContext(); 4015 // 5). Thread the array value updated forward. 4016 if (!isIllFormedLHS) 4017 builder.create<fir::ResultOp>(getLoc(), fir::getBase(lexv)); 4018 return lexv; 4019 } 4020 4021 private: 4022 void determineShapeOfDest(const fir::ExtendedValue &lhs) { 4023 destShape = fir::factory::getExtents(getLoc(), builder, lhs); 4024 } 4025 4026 void determineShapeOfDest(const Fortran::lower::SomeExpr &lhs) { 4027 if (!destShape.empty()) 4028 return; 4029 if (explicitSpaceIsActive() && determineShapeWithSlice(lhs)) 4030 return; 4031 mlir::Type idxTy = builder.getIndexType(); 4032 mlir::Location loc = getLoc(); 4033 if (std::optional<Fortran::evaluate::ConstantSubscripts> constantShape = 4034 Fortran::evaluate::GetConstantExtents(converter.getFoldingContext(), 4035 lhs)) 4036 for (Fortran::common::ConstantSubscript extent : *constantShape) 4037 destShape.push_back(builder.createIntegerConstant(loc, idxTy, extent)); 4038 } 4039 4040 bool genShapeFromDataRef(const Fortran::semantics::Symbol &x) { 4041 return false; 4042 } 4043 bool genShapeFromDataRef(const Fortran::evaluate::CoarrayRef &) { 4044 TODO(getLoc(), "coarray ref"); 4045 return false; 4046 } 4047 bool genShapeFromDataRef(const Fortran::evaluate::Component &x) { 4048 return x.base().Rank() > 0 ? genShapeFromDataRef(x.base()) : false; 4049 } 4050 bool genShapeFromDataRef(const Fortran::evaluate::ArrayRef &x) { 4051 if (x.Rank() == 0) 4052 return false; 4053 if (x.base().Rank() > 0) 4054 if (genShapeFromDataRef(x.base())) 4055 return true; 4056 // x has rank and x.base did not produce a shape. 4057 ExtValue exv = x.base().IsSymbol() ? asScalarRef(getFirstSym(x.base())) 4058 : asScalarRef(x.base().GetComponent()); 4059 mlir::Location loc = getLoc(); 4060 mlir::IndexType idxTy = builder.getIndexType(); 4061 llvm::SmallVector<mlir::Value> definedShape = 4062 fir::factory::getExtents(loc, builder, exv); 4063 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1); 4064 for (auto ss : llvm::enumerate(x.subscript())) { 4065 std::visit(Fortran::common::visitors{ 4066 [&](const Fortran::evaluate::Triplet &trip) { 4067 // For a subscript of triple notation, we compute the 4068 // range of this dimension of the iteration space. 4069 auto lo = [&]() { 4070 if (auto optLo = trip.lower()) 4071 return fir::getBase(asScalar(*optLo)); 4072 return getLBound(exv, ss.index(), one); 4073 }(); 4074 auto hi = [&]() { 4075 if (auto optHi = trip.upper()) 4076 return fir::getBase(asScalar(*optHi)); 4077 return getUBound(exv, ss.index(), one); 4078 }(); 4079 auto step = builder.createConvert( 4080 loc, idxTy, fir::getBase(asScalar(trip.stride()))); 4081 auto extent = builder.genExtentFromTriplet(loc, lo, hi, 4082 step, idxTy); 4083 destShape.push_back(extent); 4084 }, 4085 [&](auto) {}}, 4086 ss.value().u); 4087 } 4088 return true; 4089 } 4090 bool genShapeFromDataRef(const Fortran::evaluate::NamedEntity &x) { 4091 if (x.IsSymbol()) 4092 return genShapeFromDataRef(getFirstSym(x)); 4093 return genShapeFromDataRef(x.GetComponent()); 4094 } 4095 bool genShapeFromDataRef(const Fortran::evaluate::DataRef &x) { 4096 return std::visit([&](const auto &v) { return genShapeFromDataRef(v); }, 4097 x.u); 4098 } 4099 4100 /// When in an explicit space, the ranked component must be evaluated to 4101 /// determine the actual number of iterations when slicing triples are 4102 /// present. Lower these expressions here. 4103 bool determineShapeWithSlice(const Fortran::lower::SomeExpr &lhs) { 4104 LLVM_DEBUG(Fortran::lower::DumpEvaluateExpr::dump( 4105 llvm::dbgs() << "determine shape of:\n", lhs)); 4106 // FIXME: We may not want to use ExtractDataRef here since it doesn't deal 4107 // with substrings, etc. 4108 std::optional<Fortran::evaluate::DataRef> dref = 4109 Fortran::evaluate::ExtractDataRef(lhs); 4110 return dref.has_value() ? genShapeFromDataRef(*dref) : false; 4111 } 4112 4113 /// CHARACTER and derived type elements are treated as memory references. The 4114 /// numeric types are treated as values. 4115 static mlir::Type adjustedArraySubtype(mlir::Type ty, 4116 mlir::ValueRange indices) { 4117 mlir::Type pathTy = fir::applyPathToType(ty, indices); 4118 assert(pathTy && "indices failed to apply to type"); 4119 return adjustedArrayElementType(pathTy); 4120 } 4121 4122 /// Lower rhs of an array expression. 4123 ExtValue lowerArrayExpression(const Fortran::lower::SomeExpr &exp) { 4124 mlir::Type resTy = converter.genType(exp); 4125 return std::visit( 4126 [&](const auto &e) { return lowerArrayExpression(genarr(e), resTy); }, 4127 exp.u); 4128 } 4129 ExtValue lowerArrayExpression(const ExtValue &exv) { 4130 assert(!explicitSpace); 4131 mlir::Type resTy = fir::unwrapPassByRefType(fir::getBase(exv).getType()); 4132 return lowerArrayExpression(genarr(exv), resTy); 4133 } 4134 4135 void populateBounds(llvm::SmallVectorImpl<mlir::Value> &bounds, 4136 const Fortran::evaluate::Substring *substring) { 4137 if (!substring) 4138 return; 4139 bounds.push_back(fir::getBase(asScalar(substring->lower()))); 4140 if (auto upper = substring->upper()) 4141 bounds.push_back(fir::getBase(asScalar(*upper))); 4142 } 4143 4144 /// Convert the original value, \p origVal, to type \p eleTy. When in a 4145 /// pointer assignment context, generate an appropriate `fir.rebox` for 4146 /// dealing with any bounds parameters on the pointer assignment. 4147 mlir::Value convertElementForUpdate(mlir::Location loc, mlir::Type eleTy, 4148 mlir::Value origVal) { 4149 mlir::Value val = builder.createConvert(loc, eleTy, origVal); 4150 if (isBoundsSpec()) { 4151 auto lbs = *lbounds; 4152 if (lbs.size() > 0) { 4153 // Rebox the value with user-specified shift. 4154 auto shiftTy = fir::ShiftType::get(eleTy.getContext(), lbs.size()); 4155 mlir::Value shiftOp = builder.create<fir::ShiftOp>(loc, shiftTy, lbs); 4156 val = builder.create<fir::ReboxOp>(loc, eleTy, val, shiftOp, 4157 mlir::Value{}); 4158 } 4159 } else if (isBoundsRemap()) { 4160 auto lbs = lbounds.getValue(); 4161 if (lbs.size() > 0) { 4162 // Rebox the value with user-specified shift and shape. 4163 auto shapeShiftArgs = flatZip(lbs, ubounds.getValue()); 4164 auto shapeTy = fir::ShapeShiftType::get(eleTy.getContext(), lbs.size()); 4165 mlir::Value shapeShift = 4166 builder.create<fir::ShapeShiftOp>(loc, shapeTy, shapeShiftArgs); 4167 val = builder.create<fir::ReboxOp>(loc, eleTy, val, shapeShift, 4168 mlir::Value{}); 4169 } 4170 } 4171 return val; 4172 } 4173 4174 /// Default store to destination implementation. 4175 /// This implements the default case, which is to assign the value in 4176 /// `iters.element` into the destination array, `iters.innerArgument`. Handles 4177 /// by value and by reference assignment. 4178 CC defaultStoreToDestination(const Fortran::evaluate::Substring *substring) { 4179 return [=](IterSpace iterSpace) -> ExtValue { 4180 mlir::Location loc = getLoc(); 4181 mlir::Value innerArg = iterSpace.innerArgument(); 4182 fir::ExtendedValue exv = iterSpace.elementExv(); 4183 mlir::Type arrTy = innerArg.getType(); 4184 mlir::Type eleTy = fir::applyPathToType(arrTy, iterSpace.iterVec()); 4185 if (isAdjustedArrayElementType(eleTy)) { 4186 // The elemental update is in the memref domain. Under this semantics, 4187 // we must always copy the computed new element from its location in 4188 // memory into the destination array. 4189 mlir::Type resRefTy = builder.getRefType(eleTy); 4190 // Get a reference to the array element to be amended. 4191 auto arrayOp = builder.create<fir::ArrayAccessOp>( 4192 loc, resRefTy, innerArg, iterSpace.iterVec(), 4193 destination.getTypeparams()); 4194 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 4195 llvm::SmallVector<mlir::Value> substringBounds; 4196 populateBounds(substringBounds, substring); 4197 mlir::Value dstLen = fir::factory::genLenOfCharacter( 4198 builder, loc, destination, iterSpace.iterVec(), substringBounds); 4199 fir::ArrayAmendOp amend = createCharArrayAmend( 4200 loc, builder, arrayOp, dstLen, exv, innerArg, substringBounds); 4201 return abstractArrayExtValue(amend, dstLen); 4202 } 4203 if (fir::isa_derived(eleTy)) { 4204 fir::ArrayAmendOp amend = createDerivedArrayAmend( 4205 loc, destination, builder, arrayOp, exv, eleTy, innerArg); 4206 return abstractArrayExtValue(amend /*FIXME: typeparams?*/); 4207 } 4208 assert(eleTy.isa<fir::SequenceType>() && "must be an array"); 4209 TODO(loc, "array (as element) assignment"); 4210 } 4211 // By value semantics. The element is being assigned by value. 4212 auto ele = convertElementForUpdate(loc, eleTy, fir::getBase(exv)); 4213 auto update = builder.create<fir::ArrayUpdateOp>( 4214 loc, arrTy, innerArg, ele, iterSpace.iterVec(), 4215 destination.getTypeparams()); 4216 return abstractArrayExtValue(update); 4217 }; 4218 } 4219 4220 /// For an elemental array expression. 4221 /// 1. Lower the scalars and array loads. 4222 /// 2. Create the iteration space. 4223 /// 3. Create the element-by-element computation in the loop. 4224 /// 4. Return the resulting array value. 4225 /// If no destination was set in the array context, a temporary of 4226 /// \p resultTy will be created to hold the evaluated expression. 4227 /// Otherwise, \p resultTy is ignored and the expression is evaluated 4228 /// in the destination. \p f is a continuation built from an 4229 /// evaluate::Expr or an ExtendedValue. 4230 ExtValue lowerArrayExpression(CC f, mlir::Type resultTy) { 4231 mlir::Location loc = getLoc(); 4232 auto [iterSpace, insPt] = genIterSpace(resultTy); 4233 auto exv = f(iterSpace); 4234 iterSpace.setElement(std::move(exv)); 4235 auto lambda = ccStoreToDest.hasValue() 4236 ? ccStoreToDest.getValue() 4237 : defaultStoreToDestination(/*substring=*/nullptr); 4238 mlir::Value updVal = fir::getBase(lambda(iterSpace)); 4239 finalizeElementCtx(); 4240 builder.create<fir::ResultOp>(loc, updVal); 4241 builder.restoreInsertionPoint(insPt); 4242 return abstractArrayExtValue(iterSpace.outerResult()); 4243 } 4244 4245 /// Compute the shape of a slice. 4246 llvm::SmallVector<mlir::Value> computeSliceShape(mlir::Value slice) { 4247 llvm::SmallVector<mlir::Value> slicedShape; 4248 auto slOp = mlir::cast<fir::SliceOp>(slice.getDefiningOp()); 4249 mlir::Operation::operand_range triples = slOp.getTriples(); 4250 mlir::IndexType idxTy = builder.getIndexType(); 4251 mlir::Location loc = getLoc(); 4252 for (unsigned i = 0, end = triples.size(); i < end; i += 3) { 4253 if (!mlir::isa_and_nonnull<fir::UndefOp>( 4254 triples[i + 1].getDefiningOp())) { 4255 // (..., lb:ub:step, ...) case: extent = max((ub-lb+step)/step, 0) 4256 // See Fortran 2018 9.5.3.3.2 section for more details. 4257 mlir::Value res = builder.genExtentFromTriplet( 4258 loc, triples[i], triples[i + 1], triples[i + 2], idxTy); 4259 slicedShape.emplace_back(res); 4260 } else { 4261 // do nothing. `..., i, ...` case, so dimension is dropped. 4262 } 4263 } 4264 return slicedShape; 4265 } 4266 4267 /// Get the shape from an ArrayOperand. The shape of the array is adjusted if 4268 /// the array was sliced. 4269 llvm::SmallVector<mlir::Value> getShape(ArrayOperand array) { 4270 if (array.slice) 4271 return computeSliceShape(array.slice); 4272 if (array.memref.getType().isa<fir::BoxType>()) 4273 return fir::factory::readExtents(builder, getLoc(), 4274 fir::BoxValue{array.memref}); 4275 return fir::factory::getExtents(array.shape); 4276 } 4277 4278 /// Get the shape from an ArrayLoad. 4279 llvm::SmallVector<mlir::Value> getShape(fir::ArrayLoadOp arrayLoad) { 4280 return getShape(ArrayOperand{arrayLoad.getMemref(), arrayLoad.getShape(), 4281 arrayLoad.getSlice()}); 4282 } 4283 4284 /// Returns the first array operand that may not be absent. If all 4285 /// array operands may be absent, return the first one. 4286 const ArrayOperand &getInducingShapeArrayOperand() const { 4287 assert(!arrayOperands.empty()); 4288 for (const ArrayOperand &op : arrayOperands) 4289 if (!op.mayBeAbsent) 4290 return op; 4291 // If all arrays operand appears in optional position, then none of them 4292 // is allowed to be absent as per 15.5.2.12 point 3. (6). Just pick the 4293 // first operands. 4294 // TODO: There is an opportunity to add a runtime check here that 4295 // this array is present as required. 4296 return arrayOperands[0]; 4297 } 4298 4299 /// Generate the shape of the iteration space over the array expression. The 4300 /// iteration space may be implicit, explicit, or both. If it is implied it is 4301 /// based on the destination and operand array loads, or an optional 4302 /// Fortran::evaluate::Shape from the front end. If the shape is explicit, 4303 /// this returns any implicit shape component, if it exists. 4304 llvm::SmallVector<mlir::Value> genIterationShape() { 4305 // Use the precomputed destination shape. 4306 if (!destShape.empty()) 4307 return destShape; 4308 // Otherwise, use the destination's shape. 4309 if (destination) 4310 return getShape(destination); 4311 // Otherwise, use the first ArrayLoad operand shape. 4312 if (!arrayOperands.empty()) 4313 return getShape(getInducingShapeArrayOperand()); 4314 fir::emitFatalError(getLoc(), 4315 "failed to compute the array expression shape"); 4316 } 4317 4318 bool explicitSpaceIsActive() const { 4319 return explicitSpace && explicitSpace->isActive(); 4320 } 4321 4322 bool implicitSpaceHasMasks() const { 4323 return implicitSpace && !implicitSpace->empty(); 4324 } 4325 4326 CC genMaskAccess(mlir::Value tmp, mlir::Value shape) { 4327 mlir::Location loc = getLoc(); 4328 return [=, builder = &converter.getFirOpBuilder()](IterSpace iters) { 4329 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(tmp.getType()); 4330 auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); 4331 mlir::Type eleRefTy = builder->getRefType(eleTy); 4332 mlir::IntegerType i1Ty = builder->getI1Type(); 4333 // Adjust indices for any shift of the origin of the array. 4334 llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices( 4335 loc, *builder, tmp.getType(), shape, iters.iterVec()); 4336 auto addr = 4337 builder->create<fir::ArrayCoorOp>(loc, eleRefTy, tmp, shape, 4338 /*slice=*/mlir::Value{}, indices, 4339 /*typeParams=*/llvm::None); 4340 auto load = builder->create<fir::LoadOp>(loc, addr); 4341 return builder->createConvert(loc, i1Ty, load); 4342 }; 4343 } 4344 4345 /// Construct the incremental instantiations of the ragged array structure. 4346 /// Rebind the lazy buffer variable, etc. as we go. 4347 template <bool withAllocation = false> 4348 mlir::Value prepareRaggedArrays(Fortran::lower::FrontEndExpr expr) { 4349 assert(explicitSpaceIsActive()); 4350 mlir::Location loc = getLoc(); 4351 mlir::TupleType raggedTy = fir::factory::getRaggedArrayHeaderType(builder); 4352 llvm::SmallVector<llvm::SmallVector<fir::DoLoopOp>> loopStack = 4353 explicitSpace->getLoopStack(); 4354 const std::size_t depth = loopStack.size(); 4355 mlir::IntegerType i64Ty = builder.getIntegerType(64); 4356 [[maybe_unused]] mlir::Value byteSize = 4357 builder.createIntegerConstant(loc, i64Ty, 1); 4358 mlir::Value header = implicitSpace->lookupMaskHeader(expr); 4359 for (std::remove_const_t<decltype(depth)> i = 0; i < depth; ++i) { 4360 auto insPt = builder.saveInsertionPoint(); 4361 if (i < depth - 1) 4362 builder.setInsertionPoint(loopStack[i + 1][0]); 4363 4364 // Compute and gather the extents. 4365 llvm::SmallVector<mlir::Value> extents; 4366 for (auto doLoop : loopStack[i]) 4367 extents.push_back(builder.genExtentFromTriplet( 4368 loc, doLoop.getLowerBound(), doLoop.getUpperBound(), 4369 doLoop.getStep(), i64Ty)); 4370 if constexpr (withAllocation) { 4371 fir::runtime::genRaggedArrayAllocate( 4372 loc, builder, header, /*asHeader=*/true, byteSize, extents); 4373 } 4374 4375 // Compute the dynamic position into the header. 4376 llvm::SmallVector<mlir::Value> offsets; 4377 for (auto doLoop : loopStack[i]) { 4378 auto m = builder.create<mlir::arith::SubIOp>( 4379 loc, doLoop.getInductionVar(), doLoop.getLowerBound()); 4380 auto n = builder.create<mlir::arith::DivSIOp>(loc, m, doLoop.getStep()); 4381 mlir::Value one = builder.createIntegerConstant(loc, n.getType(), 1); 4382 offsets.push_back(builder.create<mlir::arith::AddIOp>(loc, n, one)); 4383 } 4384 mlir::IntegerType i32Ty = builder.getIntegerType(32); 4385 mlir::Value uno = builder.createIntegerConstant(loc, i32Ty, 1); 4386 mlir::Type coorTy = builder.getRefType(raggedTy.getType(1)); 4387 auto hdOff = builder.create<fir::CoordinateOp>(loc, coorTy, header, uno); 4388 auto toTy = fir::SequenceType::get(raggedTy, offsets.size()); 4389 mlir::Type toRefTy = builder.getRefType(toTy); 4390 auto ldHdr = builder.create<fir::LoadOp>(loc, hdOff); 4391 mlir::Value hdArr = builder.createConvert(loc, toRefTy, ldHdr); 4392 auto shapeOp = builder.genShape(loc, extents); 4393 header = builder.create<fir::ArrayCoorOp>( 4394 loc, builder.getRefType(raggedTy), hdArr, shapeOp, 4395 /*slice=*/mlir::Value{}, offsets, 4396 /*typeparams=*/mlir::ValueRange{}); 4397 auto hdrVar = builder.create<fir::CoordinateOp>(loc, coorTy, header, uno); 4398 auto inVar = builder.create<fir::LoadOp>(loc, hdrVar); 4399 mlir::Value two = builder.createIntegerConstant(loc, i32Ty, 2); 4400 mlir::Type coorTy2 = builder.getRefType(raggedTy.getType(2)); 4401 auto hdrSh = builder.create<fir::CoordinateOp>(loc, coorTy2, header, two); 4402 auto shapePtr = builder.create<fir::LoadOp>(loc, hdrSh); 4403 // Replace the binding. 4404 implicitSpace->rebind(expr, genMaskAccess(inVar, shapePtr)); 4405 if (i < depth - 1) 4406 builder.restoreInsertionPoint(insPt); 4407 } 4408 return header; 4409 } 4410 4411 /// Lower mask expressions with implied iteration spaces from the variants of 4412 /// WHERE syntax. Since it is legal for mask expressions to have side-effects 4413 /// and modify values that will be used for the lhs, rhs, or both of 4414 /// subsequent assignments, the mask must be evaluated before the assignment 4415 /// is processed. 4416 /// Mask expressions are array expressions too. 4417 void genMasks() { 4418 // Lower the mask expressions, if any. 4419 if (implicitSpaceHasMasks()) { 4420 mlir::Location loc = getLoc(); 4421 // Mask expressions are array expressions too. 4422 for (const auto *e : implicitSpace->getExprs()) 4423 if (e && !implicitSpace->isLowered(e)) { 4424 if (mlir::Value var = implicitSpace->lookupMaskVariable(e)) { 4425 // Allocate the mask buffer lazily. 4426 assert(explicitSpaceIsActive()); 4427 mlir::Value header = 4428 prepareRaggedArrays</*withAllocations=*/true>(e); 4429 Fortran::lower::createLazyArrayTempValue(converter, *e, header, 4430 symMap, stmtCtx); 4431 // Close the explicit loops. 4432 builder.create<fir::ResultOp>(loc, explicitSpace->getInnerArgs()); 4433 builder.setInsertionPointAfter(explicitSpace->getOuterLoop()); 4434 // Open a new copy of the explicit loop nest. 4435 explicitSpace->genLoopNest(); 4436 continue; 4437 } 4438 fir::ExtendedValue tmp = Fortran::lower::createSomeArrayTempValue( 4439 converter, *e, symMap, stmtCtx); 4440 mlir::Value shape = builder.createShape(loc, tmp); 4441 implicitSpace->bind(e, genMaskAccess(fir::getBase(tmp), shape)); 4442 } 4443 4444 // Set buffer from the header. 4445 for (const auto *e : implicitSpace->getExprs()) { 4446 if (!e) 4447 continue; 4448 if (implicitSpace->lookupMaskVariable(e)) { 4449 // Index into the ragged buffer to retrieve cached results. 4450 const int rank = e->Rank(); 4451 assert(destShape.empty() || 4452 static_cast<std::size_t>(rank) == destShape.size()); 4453 mlir::Value header = prepareRaggedArrays(e); 4454 mlir::TupleType raggedTy = 4455 fir::factory::getRaggedArrayHeaderType(builder); 4456 mlir::IntegerType i32Ty = builder.getIntegerType(32); 4457 mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1); 4458 auto coor1 = builder.create<fir::CoordinateOp>( 4459 loc, builder.getRefType(raggedTy.getType(1)), header, one); 4460 auto db = builder.create<fir::LoadOp>(loc, coor1); 4461 mlir::Type eleTy = 4462 fir::unwrapSequenceType(fir::unwrapRefType(db.getType())); 4463 mlir::Type buffTy = 4464 builder.getRefType(fir::SequenceType::get(eleTy, rank)); 4465 // Address of ragged buffer data. 4466 mlir::Value buff = builder.createConvert(loc, buffTy, db); 4467 4468 mlir::Value two = builder.createIntegerConstant(loc, i32Ty, 2); 4469 auto coor2 = builder.create<fir::CoordinateOp>( 4470 loc, builder.getRefType(raggedTy.getType(2)), header, two); 4471 auto shBuff = builder.create<fir::LoadOp>(loc, coor2); 4472 mlir::IntegerType i64Ty = builder.getIntegerType(64); 4473 mlir::IndexType idxTy = builder.getIndexType(); 4474 llvm::SmallVector<mlir::Value> extents; 4475 for (std::remove_const_t<decltype(rank)> i = 0; i < rank; ++i) { 4476 mlir::Value off = builder.createIntegerConstant(loc, i32Ty, i); 4477 auto coor = builder.create<fir::CoordinateOp>( 4478 loc, builder.getRefType(i64Ty), shBuff, off); 4479 auto ldExt = builder.create<fir::LoadOp>(loc, coor); 4480 extents.push_back(builder.createConvert(loc, idxTy, ldExt)); 4481 } 4482 if (destShape.empty()) 4483 destShape = extents; 4484 // Construct shape of buffer. 4485 mlir::Value shapeOp = builder.genShape(loc, extents); 4486 4487 // Replace binding with the local result. 4488 implicitSpace->rebind(e, genMaskAccess(buff, shapeOp)); 4489 } 4490 } 4491 } 4492 } 4493 4494 // FIXME: should take multiple inner arguments. 4495 std::pair<IterationSpace, mlir::OpBuilder::InsertPoint> 4496 genImplicitLoops(mlir::ValueRange shape, mlir::Value innerArg) { 4497 mlir::Location loc = getLoc(); 4498 mlir::IndexType idxTy = builder.getIndexType(); 4499 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1); 4500 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0); 4501 llvm::SmallVector<mlir::Value> loopUppers; 4502 4503 // Convert any implied shape to closed interval form. The fir.do_loop will 4504 // run from 0 to `extent - 1` inclusive. 4505 for (auto extent : shape) 4506 loopUppers.push_back( 4507 builder.create<mlir::arith::SubIOp>(loc, extent, one)); 4508 4509 // Iteration space is created with outermost columns, innermost rows 4510 llvm::SmallVector<fir::DoLoopOp> loops; 4511 4512 const std::size_t loopDepth = loopUppers.size(); 4513 llvm::SmallVector<mlir::Value> ivars; 4514 4515 for (auto i : llvm::enumerate(llvm::reverse(loopUppers))) { 4516 if (i.index() > 0) { 4517 assert(!loops.empty()); 4518 builder.setInsertionPointToStart(loops.back().getBody()); 4519 } 4520 fir::DoLoopOp loop; 4521 if (innerArg) { 4522 loop = builder.create<fir::DoLoopOp>( 4523 loc, zero, i.value(), one, isUnordered(), 4524 /*finalCount=*/false, mlir::ValueRange{innerArg}); 4525 innerArg = loop.getRegionIterArgs().front(); 4526 if (explicitSpaceIsActive()) 4527 explicitSpace->setInnerArg(0, innerArg); 4528 } else { 4529 loop = builder.create<fir::DoLoopOp>(loc, zero, i.value(), one, 4530 isUnordered(), 4531 /*finalCount=*/false); 4532 } 4533 ivars.push_back(loop.getInductionVar()); 4534 loops.push_back(loop); 4535 } 4536 4537 if (innerArg) 4538 for (std::remove_const_t<decltype(loopDepth)> i = 0; i + 1 < loopDepth; 4539 ++i) { 4540 builder.setInsertionPointToEnd(loops[i].getBody()); 4541 builder.create<fir::ResultOp>(loc, loops[i + 1].getResult(0)); 4542 } 4543 4544 // Move insertion point to the start of the innermost loop in the nest. 4545 builder.setInsertionPointToStart(loops.back().getBody()); 4546 // Set `afterLoopNest` to just after the entire loop nest. 4547 auto currPt = builder.saveInsertionPoint(); 4548 builder.setInsertionPointAfter(loops[0]); 4549 auto afterLoopNest = builder.saveInsertionPoint(); 4550 builder.restoreInsertionPoint(currPt); 4551 4552 // Put the implicit loop variables in row to column order to match FIR's 4553 // Ops. (The loops were constructed from outermost column to innermost 4554 // row.) 4555 mlir::Value outerRes = loops[0].getResult(0); 4556 return {IterationSpace(innerArg, outerRes, llvm::reverse(ivars)), 4557 afterLoopNest}; 4558 } 4559 4560 /// Build the iteration space into which the array expression will be lowered. 4561 /// The resultType is used to create a temporary, if needed. 4562 std::pair<IterationSpace, mlir::OpBuilder::InsertPoint> 4563 genIterSpace(mlir::Type resultType) { 4564 mlir::Location loc = getLoc(); 4565 llvm::SmallVector<mlir::Value> shape = genIterationShape(); 4566 if (!destination) { 4567 // Allocate storage for the result if it is not already provided. 4568 destination = createAndLoadSomeArrayTemp(resultType, shape); 4569 } 4570 4571 // Generate the lazy mask allocation, if one was given. 4572 if (ccPrelude.hasValue()) 4573 ccPrelude.getValue()(shape); 4574 4575 // Now handle the implicit loops. 4576 mlir::Value inner = explicitSpaceIsActive() 4577 ? explicitSpace->getInnerArgs().front() 4578 : destination.getResult(); 4579 auto [iters, afterLoopNest] = genImplicitLoops(shape, inner); 4580 mlir::Value innerArg = iters.innerArgument(); 4581 4582 // Generate the mask conditional structure, if there are masks. Unlike the 4583 // explicit masks, which are interleaved, these mask expression appear in 4584 // the innermost loop. 4585 if (implicitSpaceHasMasks()) { 4586 // Recover the cached condition from the mask buffer. 4587 auto genCond = [&](Fortran::lower::FrontEndExpr e, IterSpace iters) { 4588 return implicitSpace->getBoundClosure(e)(iters); 4589 }; 4590 4591 // Handle the negated conditions in topological order of the WHERE 4592 // clauses. See 10.2.3.2p4 as to why this control structure is produced. 4593 for (llvm::SmallVector<Fortran::lower::FrontEndExpr> maskExprs : 4594 implicitSpace->getMasks()) { 4595 const std::size_t size = maskExprs.size() - 1; 4596 auto genFalseBlock = [&](const auto *e, auto &&cond) { 4597 auto ifOp = builder.create<fir::IfOp>( 4598 loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond), 4599 /*withElseRegion=*/true); 4600 builder.create<fir::ResultOp>(loc, ifOp.getResult(0)); 4601 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 4602 builder.create<fir::ResultOp>(loc, innerArg); 4603 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 4604 }; 4605 auto genTrueBlock = [&](const auto *e, auto &&cond) { 4606 auto ifOp = builder.create<fir::IfOp>( 4607 loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond), 4608 /*withElseRegion=*/true); 4609 builder.create<fir::ResultOp>(loc, ifOp.getResult(0)); 4610 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 4611 builder.create<fir::ResultOp>(loc, innerArg); 4612 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 4613 }; 4614 for (std::remove_const_t<decltype(size)> i = 0; i < size; ++i) 4615 if (const auto *e = maskExprs[i]) 4616 genFalseBlock(e, genCond(e, iters)); 4617 4618 // The last condition is either non-negated or unconditionally negated. 4619 if (const auto *e = maskExprs[size]) 4620 genTrueBlock(e, genCond(e, iters)); 4621 } 4622 } 4623 4624 // We're ready to lower the body (an assignment statement) for this context 4625 // of loop nests at this point. 4626 return {iters, afterLoopNest}; 4627 } 4628 4629 fir::ArrayLoadOp 4630 createAndLoadSomeArrayTemp(mlir::Type type, 4631 llvm::ArrayRef<mlir::Value> shape) { 4632 if (ccLoadDest.hasValue()) 4633 return ccLoadDest.getValue()(shape); 4634 auto seqTy = type.dyn_cast<fir::SequenceType>(); 4635 assert(seqTy && "must be an array"); 4636 mlir::Location loc = getLoc(); 4637 // TODO: Need to thread the length parameters here. For character, they may 4638 // differ from the operands length (e.g concatenation). So the array loads 4639 // type parameters are not enough. 4640 if (auto charTy = seqTy.getEleTy().dyn_cast<fir::CharacterType>()) 4641 if (charTy.hasDynamicLen()) 4642 TODO(loc, "character array expression temp with dynamic length"); 4643 if (auto recTy = seqTy.getEleTy().dyn_cast<fir::RecordType>()) 4644 if (recTy.getNumLenParams() > 0) 4645 TODO(loc, "derived type array expression temp with length parameters"); 4646 mlir::Value temp = seqTy.hasConstantShape() 4647 ? builder.create<fir::AllocMemOp>(loc, type) 4648 : builder.create<fir::AllocMemOp>( 4649 loc, type, ".array.expr", llvm::None, shape); 4650 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder(); 4651 stmtCtx.attachCleanup( 4652 [bldr, loc, temp]() { bldr->create<fir::FreeMemOp>(loc, temp); }); 4653 mlir::Value shapeOp = genShapeOp(shape); 4654 return builder.create<fir::ArrayLoadOp>(loc, seqTy, temp, shapeOp, 4655 /*slice=*/mlir::Value{}, 4656 llvm::None); 4657 } 4658 4659 static fir::ShapeOp genShapeOp(mlir::Location loc, fir::FirOpBuilder &builder, 4660 llvm::ArrayRef<mlir::Value> shape) { 4661 mlir::IndexType idxTy = builder.getIndexType(); 4662 llvm::SmallVector<mlir::Value> idxShape; 4663 for (auto s : shape) 4664 idxShape.push_back(builder.createConvert(loc, idxTy, s)); 4665 auto shapeTy = fir::ShapeType::get(builder.getContext(), idxShape.size()); 4666 return builder.create<fir::ShapeOp>(loc, shapeTy, idxShape); 4667 } 4668 4669 fir::ShapeOp genShapeOp(llvm::ArrayRef<mlir::Value> shape) { 4670 return genShapeOp(getLoc(), builder, shape); 4671 } 4672 4673 //===--------------------------------------------------------------------===// 4674 // Expression traversal and lowering. 4675 //===--------------------------------------------------------------------===// 4676 4677 /// Lower the expression, \p x, in a scalar context. 4678 template <typename A> 4679 ExtValue asScalar(const A &x) { 4680 return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.genval(x); 4681 } 4682 4683 /// Lower the expression, \p x, in a scalar context. If this is an explicit 4684 /// space, the expression may be scalar and refer to an array. We want to 4685 /// raise the array access to array operations in FIR to analyze potential 4686 /// conflicts even when the result is a scalar element. 4687 template <typename A> 4688 ExtValue asScalarArray(const A &x) { 4689 return explicitSpaceIsActive() && !isPointerAssignment() 4690 ? genarr(x)(IterationSpace{}) 4691 : asScalar(x); 4692 } 4693 4694 /// Lower the expression in a scalar context to a memory reference. 4695 template <typename A> 4696 ExtValue asScalarRef(const A &x) { 4697 return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.gen(x); 4698 } 4699 4700 /// Lower an expression without dereferencing any indirection that may be 4701 /// a nullptr (because this is an absent optional or unallocated/disassociated 4702 /// descriptor). The returned expression cannot be addressed directly, it is 4703 /// meant to inquire about its status before addressing the related entity. 4704 template <typename A> 4705 ExtValue asInquired(const A &x) { 4706 return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx} 4707 .lowerIntrinsicArgumentAsInquired(x); 4708 } 4709 4710 /// Some temporaries are allocated on an element-by-element basis during the 4711 /// array expression evaluation. Collect the cleanups here so the resources 4712 /// can be freed before the next loop iteration, avoiding memory leaks. etc. 4713 Fortran::lower::StatementContext &getElementCtx() { 4714 if (!elementCtx) { 4715 stmtCtx.pushScope(); 4716 elementCtx = true; 4717 } 4718 return stmtCtx; 4719 } 4720 4721 /// If there were temporaries created for this element evaluation, finalize 4722 /// and deallocate the resources now. This should be done just prior the the 4723 /// fir::ResultOp at the end of the innermost loop. 4724 void finalizeElementCtx() { 4725 if (elementCtx) { 4726 stmtCtx.finalize(/*popScope=*/true); 4727 elementCtx = false; 4728 } 4729 } 4730 4731 /// Lower an elemental function array argument. This ensures array 4732 /// sub-expressions that are not variables and must be passed by address 4733 /// are lowered by value and placed in memory. 4734 template <typename A> 4735 CC genElementalArgument(const A &x) { 4736 // Ensure the returned element is in memory if this is what was requested. 4737 if ((semant == ConstituentSemantics::RefOpaque || 4738 semant == ConstituentSemantics::DataAddr || 4739 semant == ConstituentSemantics::ByValueArg)) { 4740 if (!Fortran::evaluate::IsVariable(x)) { 4741 PushSemantics(ConstituentSemantics::DataValue); 4742 CC cc = genarr(x); 4743 mlir::Location loc = getLoc(); 4744 if (isParenthesizedVariable(x)) { 4745 // Parenthesised variables are lowered to a reference to the variable 4746 // storage. When passing it as an argument, a copy must be passed. 4747 return [=](IterSpace iters) -> ExtValue { 4748 return createInMemoryScalarCopy(builder, loc, cc(iters)); 4749 }; 4750 } 4751 mlir::Type storageType = 4752 fir::unwrapSequenceType(converter.genType(toEvExpr(x))); 4753 return [=](IterSpace iters) -> ExtValue { 4754 return placeScalarValueInMemory(builder, loc, cc(iters), storageType); 4755 }; 4756 } 4757 } 4758 return genarr(x); 4759 } 4760 4761 // A procedure reference to a Fortran elemental intrinsic procedure. 4762 CC genElementalIntrinsicProcRef( 4763 const Fortran::evaluate::ProcedureRef &procRef, 4764 llvm::Optional<mlir::Type> retTy, 4765 const Fortran::evaluate::SpecificIntrinsic &intrinsic) { 4766 llvm::SmallVector<CC> operands; 4767 llvm::StringRef name = intrinsic.name; 4768 const Fortran::lower::IntrinsicArgumentLoweringRules *argLowering = 4769 Fortran::lower::getIntrinsicArgumentLowering(name); 4770 mlir::Location loc = getLoc(); 4771 if (Fortran::lower::intrinsicRequiresCustomOptionalHandling( 4772 procRef, intrinsic, converter)) { 4773 using CcPairT = std::pair<CC, llvm::Optional<mlir::Value>>; 4774 llvm::SmallVector<CcPairT> operands; 4775 auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) { 4776 if (expr.Rank() == 0) { 4777 ExtValue optionalArg = this->asInquired(expr); 4778 mlir::Value isPresent = 4779 genActualIsPresentTest(builder, loc, optionalArg); 4780 operands.emplace_back( 4781 [=](IterSpace iters) -> ExtValue { 4782 return genLoad(builder, loc, optionalArg); 4783 }, 4784 isPresent); 4785 } else { 4786 auto [cc, isPresent, _] = this->genOptionalArrayFetch(expr); 4787 operands.emplace_back(cc, isPresent); 4788 } 4789 }; 4790 auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr) { 4791 PushSemantics(ConstituentSemantics::RefTransparent); 4792 operands.emplace_back(genElementalArgument(expr), llvm::None); 4793 }; 4794 Fortran::lower::prepareCustomIntrinsicArgument( 4795 procRef, intrinsic, retTy, prepareOptionalArg, prepareOtherArg, 4796 converter); 4797 4798 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder(); 4799 llvm::StringRef name = intrinsic.name; 4800 return [=](IterSpace iters) -> ExtValue { 4801 auto getArgument = [&](std::size_t i) -> ExtValue { 4802 return operands[i].first(iters); 4803 }; 4804 auto isPresent = [&](std::size_t i) -> llvm::Optional<mlir::Value> { 4805 return operands[i].second; 4806 }; 4807 return Fortran::lower::lowerCustomIntrinsic( 4808 *bldr, loc, name, retTy, isPresent, getArgument, operands.size(), 4809 getElementCtx()); 4810 }; 4811 } 4812 /// Otherwise, pre-lower arguments and use intrinsic lowering utility. 4813 for (const auto &[arg, dummy] : 4814 llvm::zip(procRef.arguments(), 4815 intrinsic.characteristics.value().dummyArguments)) { 4816 const auto *expr = 4817 Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg); 4818 if (!expr) { 4819 // Absent optional. 4820 operands.emplace_back([=](IterSpace) { return mlir::Value{}; }); 4821 } else if (!argLowering) { 4822 // No argument lowering instruction, lower by value. 4823 PushSemantics(ConstituentSemantics::RefTransparent); 4824 operands.emplace_back(genElementalArgument(*expr)); 4825 } else { 4826 // Ad-hoc argument lowering handling. 4827 Fortran::lower::ArgLoweringRule argRules = 4828 Fortran::lower::lowerIntrinsicArgumentAs(getLoc(), *argLowering, 4829 dummy.name); 4830 if (argRules.handleDynamicOptional && 4831 Fortran::evaluate::MayBePassedAsAbsentOptional( 4832 *expr, converter.getFoldingContext())) { 4833 // Currently, there is not elemental intrinsic that requires lowering 4834 // a potentially absent argument to something else than a value (apart 4835 // from character MAX/MIN that are handled elsewhere.) 4836 if (argRules.lowerAs != Fortran::lower::LowerIntrinsicArgAs::Value) 4837 TODO(loc, "lowering non trivial optional elemental intrinsic array " 4838 "argument"); 4839 PushSemantics(ConstituentSemantics::RefTransparent); 4840 operands.emplace_back(genarrForwardOptionalArgumentToCall(*expr)); 4841 continue; 4842 } 4843 switch (argRules.lowerAs) { 4844 case Fortran::lower::LowerIntrinsicArgAs::Value: { 4845 PushSemantics(ConstituentSemantics::RefTransparent); 4846 operands.emplace_back(genElementalArgument(*expr)); 4847 } break; 4848 case Fortran::lower::LowerIntrinsicArgAs::Addr: { 4849 // Note: assume does not have Fortran VALUE attribute semantics. 4850 PushSemantics(ConstituentSemantics::RefOpaque); 4851 operands.emplace_back(genElementalArgument(*expr)); 4852 } break; 4853 case Fortran::lower::LowerIntrinsicArgAs::Box: { 4854 PushSemantics(ConstituentSemantics::RefOpaque); 4855 auto lambda = genElementalArgument(*expr); 4856 operands.emplace_back([=](IterSpace iters) { 4857 return builder.createBox(loc, lambda(iters)); 4858 }); 4859 } break; 4860 case Fortran::lower::LowerIntrinsicArgAs::Inquired: 4861 TODO(loc, "intrinsic function with inquired argument"); 4862 break; 4863 } 4864 } 4865 } 4866 4867 // Let the intrinsic library lower the intrinsic procedure call 4868 return [=](IterSpace iters) { 4869 llvm::SmallVector<ExtValue> args; 4870 for (const auto &cc : operands) 4871 args.push_back(cc(iters)); 4872 return Fortran::lower::genIntrinsicCall(builder, loc, name, retTy, args, 4873 getElementCtx()); 4874 }; 4875 } 4876 4877 /// Lower a procedure reference to a user-defined elemental procedure. 4878 CC genElementalUserDefinedProcRef( 4879 const Fortran::evaluate::ProcedureRef &procRef, 4880 llvm::Optional<mlir::Type> retTy) { 4881 using PassBy = Fortran::lower::CallerInterface::PassEntityBy; 4882 4883 // 10.1.4 p5. Impure elemental procedures must be called in element order. 4884 if (const Fortran::semantics::Symbol *procSym = procRef.proc().GetSymbol()) 4885 if (!Fortran::semantics::IsPureProcedure(*procSym)) 4886 setUnordered(false); 4887 4888 Fortran::lower::CallerInterface caller(procRef, converter); 4889 llvm::SmallVector<CC> operands; 4890 operands.reserve(caller.getPassedArguments().size()); 4891 mlir::Location loc = getLoc(); 4892 mlir::FunctionType callSiteType = caller.genFunctionType(); 4893 for (const Fortran::lower::CallInterface< 4894 Fortran::lower::CallerInterface>::PassedEntity &arg : 4895 caller.getPassedArguments()) { 4896 // 15.8.3 p1. Elemental procedure with intent(out)/intent(inout) 4897 // arguments must be called in element order. 4898 if (arg.mayBeModifiedByCall()) 4899 setUnordered(false); 4900 const auto *actual = arg.entity; 4901 mlir::Type argTy = callSiteType.getInput(arg.firArgument); 4902 if (!actual) { 4903 // Optional dummy argument for which there is no actual argument. 4904 auto absent = builder.create<fir::AbsentOp>(loc, argTy); 4905 operands.emplace_back([=](IterSpace) { return absent; }); 4906 continue; 4907 } 4908 const auto *expr = actual->UnwrapExpr(); 4909 if (!expr) 4910 TODO(loc, "assumed type actual argument lowering"); 4911 4912 LLVM_DEBUG(expr->AsFortran(llvm::dbgs() 4913 << "argument: " << arg.firArgument << " = [") 4914 << "]\n"); 4915 if (arg.isOptional() && Fortran::evaluate::MayBePassedAsAbsentOptional( 4916 *expr, converter.getFoldingContext())) 4917 TODO(loc, 4918 "passing dynamically optional argument to elemental procedures"); 4919 switch (arg.passBy) { 4920 case PassBy::Value: { 4921 // True pass-by-value semantics. 4922 PushSemantics(ConstituentSemantics::RefTransparent); 4923 operands.emplace_back(genElementalArgument(*expr)); 4924 } break; 4925 case PassBy::BaseAddressValueAttribute: { 4926 // VALUE attribute or pass-by-reference to a copy semantics. (byval*) 4927 if (isArray(*expr)) { 4928 PushSemantics(ConstituentSemantics::ByValueArg); 4929 operands.emplace_back(genElementalArgument(*expr)); 4930 } else { 4931 // Store scalar value in a temp to fulfill VALUE attribute. 4932 mlir::Value val = fir::getBase(asScalar(*expr)); 4933 mlir::Value temp = builder.createTemporary( 4934 loc, val.getType(), 4935 llvm::ArrayRef<mlir::NamedAttribute>{ 4936 Fortran::lower::getAdaptToByRefAttr(builder)}); 4937 builder.create<fir::StoreOp>(loc, val, temp); 4938 operands.emplace_back( 4939 [=](IterSpace iters) -> ExtValue { return temp; }); 4940 } 4941 } break; 4942 case PassBy::BaseAddress: { 4943 if (isArray(*expr)) { 4944 PushSemantics(ConstituentSemantics::RefOpaque); 4945 operands.emplace_back(genElementalArgument(*expr)); 4946 } else { 4947 ExtValue exv = asScalarRef(*expr); 4948 operands.emplace_back([=](IterSpace iters) { return exv; }); 4949 } 4950 } break; 4951 case PassBy::CharBoxValueAttribute: { 4952 if (isArray(*expr)) { 4953 PushSemantics(ConstituentSemantics::DataValue); 4954 auto lambda = genElementalArgument(*expr); 4955 operands.emplace_back([=](IterSpace iters) { 4956 return fir::factory::CharacterExprHelper{builder, loc} 4957 .createTempFrom(lambda(iters)); 4958 }); 4959 } else { 4960 fir::factory::CharacterExprHelper helper(builder, loc); 4961 fir::CharBoxValue argVal = helper.createTempFrom(asScalarRef(*expr)); 4962 operands.emplace_back( 4963 [=](IterSpace iters) -> ExtValue { return argVal; }); 4964 } 4965 } break; 4966 case PassBy::BoxChar: { 4967 PushSemantics(ConstituentSemantics::RefOpaque); 4968 operands.emplace_back(genElementalArgument(*expr)); 4969 } break; 4970 case PassBy::AddressAndLength: 4971 // PassBy::AddressAndLength is only used for character results. Results 4972 // are not handled here. 4973 fir::emitFatalError( 4974 loc, "unexpected PassBy::AddressAndLength in elemental call"); 4975 break; 4976 case PassBy::CharProcTuple: { 4977 ExtValue argRef = asScalarRef(*expr); 4978 mlir::Value tuple = createBoxProcCharTuple( 4979 converter, argTy, fir::getBase(argRef), fir::getLen(argRef)); 4980 operands.emplace_back( 4981 [=](IterSpace iters) -> ExtValue { return tuple; }); 4982 } break; 4983 case PassBy::Box: 4984 case PassBy::MutableBox: 4985 // See C15100 and C15101 4986 fir::emitFatalError(loc, "cannot be POINTER, ALLOCATABLE"); 4987 } 4988 } 4989 4990 if (caller.getIfIndirectCallSymbol()) 4991 fir::emitFatalError(loc, "cannot be indirect call"); 4992 4993 // The lambda is mutable so that `caller` copy can be modified inside it. 4994 return 4995 [=, caller = std::move(caller)](IterSpace iters) mutable -> ExtValue { 4996 for (const auto &[cc, argIface] : 4997 llvm::zip(operands, caller.getPassedArguments())) { 4998 auto exv = cc(iters); 4999 auto arg = exv.match( 5000 [&](const fir::CharBoxValue &cb) -> mlir::Value { 5001 return fir::factory::CharacterExprHelper{builder, loc} 5002 .createEmbox(cb); 5003 }, 5004 [&](const auto &) { return fir::getBase(exv); }); 5005 caller.placeInput(argIface, arg); 5006 } 5007 return ScalarExprLowering{loc, converter, symMap, getElementCtx()} 5008 .genCallOpAndResult(caller, callSiteType, retTy); 5009 }; 5010 } 5011 5012 /// Generate a procedure reference. This code is shared for both functions and 5013 /// subroutines, the difference being reflected by `retTy`. 5014 CC genProcRef(const Fortran::evaluate::ProcedureRef &procRef, 5015 llvm::Optional<mlir::Type> retTy) { 5016 mlir::Location loc = getLoc(); 5017 if (procRef.IsElemental()) { 5018 if (const Fortran::evaluate::SpecificIntrinsic *intrin = 5019 procRef.proc().GetSpecificIntrinsic()) { 5020 // All elemental intrinsic functions are pure and cannot modify their 5021 // arguments. The only elemental subroutine, MVBITS has an Intent(inout) 5022 // argument. So for this last one, loops must be in element order 5023 // according to 15.8.3 p1. 5024 if (!retTy) 5025 setUnordered(false); 5026 5027 // Elemental intrinsic call. 5028 // The intrinsic procedure is called once per element of the array. 5029 return genElementalIntrinsicProcRef(procRef, retTy, *intrin); 5030 } 5031 if (ScalarExprLowering::isStatementFunctionCall(procRef)) 5032 fir::emitFatalError(loc, "statement function cannot be elemental"); 5033 5034 // Elemental call. 5035 // The procedure is called once per element of the array argument(s). 5036 return genElementalUserDefinedProcRef(procRef, retTy); 5037 } 5038 5039 // Transformational call. 5040 // The procedure is called once and produces a value of rank > 0. 5041 if (const Fortran::evaluate::SpecificIntrinsic *intrinsic = 5042 procRef.proc().GetSpecificIntrinsic()) { 5043 if (explicitSpaceIsActive() && procRef.Rank() == 0) { 5044 // Elide any implicit loop iters. 5045 return [=, &procRef](IterSpace) { 5046 return ScalarExprLowering{loc, converter, symMap, stmtCtx} 5047 .genIntrinsicRef(procRef, *intrinsic, retTy); 5048 }; 5049 } 5050 return genarr( 5051 ScalarExprLowering{loc, converter, symMap, stmtCtx}.genIntrinsicRef( 5052 procRef, *intrinsic, retTy)); 5053 } 5054 5055 if (explicitSpaceIsActive() && procRef.Rank() == 0) { 5056 // Elide any implicit loop iters. 5057 return [=, &procRef](IterSpace) { 5058 return ScalarExprLowering{loc, converter, symMap, stmtCtx} 5059 .genProcedureRef(procRef, retTy); 5060 }; 5061 } 5062 // In the default case, the call can be hoisted out of the loop nest. Apply 5063 // the iterations to the result, which may be an array value. 5064 return genarr( 5065 ScalarExprLowering{loc, converter, symMap, stmtCtx}.genProcedureRef( 5066 procRef, retTy)); 5067 } 5068 5069 CC genarr(const Fortran::evaluate::ProcedureDesignator &) { 5070 TODO(getLoc(), "procedure designator"); 5071 } 5072 CC genarr(const Fortran::evaluate::ProcedureRef &x) { 5073 if (x.hasAlternateReturns()) 5074 fir::emitFatalError(getLoc(), 5075 "array procedure reference with alt-return"); 5076 return genProcRef(x, llvm::None); 5077 } 5078 template <typename A> 5079 CC genScalarAndForwardValue(const A &x) { 5080 ExtValue result = asScalar(x); 5081 return [=](IterSpace) { return result; }; 5082 } 5083 template <typename A, typename = std::enable_if_t<Fortran::common::HasMember< 5084 A, Fortran::evaluate::TypelessExpression>>> 5085 CC genarr(const A &x) { 5086 return genScalarAndForwardValue(x); 5087 } 5088 5089 template <typename A> 5090 CC genarr(const Fortran::evaluate::Expr<A> &x) { 5091 LLVM_DEBUG(Fortran::lower::DumpEvaluateExpr::dump(llvm::dbgs(), x)); 5092 if (isArray(x) || (explicitSpaceIsActive() && isLeftHandSide()) || 5093 isElementalProcWithArrayArgs(x)) 5094 return std::visit([&](const auto &e) { return genarr(e); }, x.u); 5095 if (explicitSpaceIsActive()) { 5096 assert(!isArray(x) && !isLeftHandSide()); 5097 auto cc = std::visit([&](const auto &e) { return genarr(e); }, x.u); 5098 auto result = cc(IterationSpace{}); 5099 return [=](IterSpace) { return result; }; 5100 } 5101 return genScalarAndForwardValue(x); 5102 } 5103 5104 // Converting a value of memory bound type requires creating a temp and 5105 // copying the value. 5106 static ExtValue convertAdjustedType(fir::FirOpBuilder &builder, 5107 mlir::Location loc, mlir::Type toType, 5108 const ExtValue &exv) { 5109 return exv.match( 5110 [&](const fir::CharBoxValue &cb) -> ExtValue { 5111 mlir::Value len = cb.getLen(); 5112 auto mem = 5113 builder.create<fir::AllocaOp>(loc, toType, mlir::ValueRange{len}); 5114 fir::CharBoxValue result(mem, len); 5115 fir::factory::CharacterExprHelper{builder, loc}.createAssign( 5116 ExtValue{result}, exv); 5117 return result; 5118 }, 5119 [&](const auto &) -> ExtValue { 5120 fir::emitFatalError(loc, "convert on adjusted extended value"); 5121 }); 5122 } 5123 template <Fortran::common::TypeCategory TC1, int KIND, 5124 Fortran::common::TypeCategory TC2> 5125 CC genarr(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>, 5126 TC2> &x) { 5127 mlir::Location loc = getLoc(); 5128 auto lambda = genarr(x.left()); 5129 mlir::Type ty = converter.genType(TC1, KIND); 5130 return [=](IterSpace iters) -> ExtValue { 5131 auto exv = lambda(iters); 5132 mlir::Value val = fir::getBase(exv); 5133 auto valTy = val.getType(); 5134 if (elementTypeWasAdjusted(valTy) && 5135 !(fir::isa_ref_type(valTy) && fir::isa_integer(ty))) 5136 return convertAdjustedType(builder, loc, ty, exv); 5137 return builder.createConvert(loc, ty, val); 5138 }; 5139 } 5140 5141 template <int KIND> 5142 CC genarr(const Fortran::evaluate::ComplexComponent<KIND> &x) { 5143 mlir::Location loc = getLoc(); 5144 auto lambda = genarr(x.left()); 5145 bool isImagPart = x.isImaginaryPart; 5146 return [=](IterSpace iters) -> ExtValue { 5147 mlir::Value lhs = fir::getBase(lambda(iters)); 5148 return fir::factory::Complex{builder, loc}.extractComplexPart(lhs, 5149 isImagPart); 5150 }; 5151 } 5152 5153 template <typename T> 5154 CC genarr(const Fortran::evaluate::Parentheses<T> &x) { 5155 mlir::Location loc = getLoc(); 5156 if (isReferentiallyOpaque()) { 5157 // Context is a call argument in, for example, an elemental procedure 5158 // call. TODO: all array arguments should use array_load, array_access, 5159 // array_amend, and INTENT(OUT), INTENT(INOUT) arguments should have 5160 // array_merge_store ops. 5161 TODO(loc, "parentheses on argument in elemental call"); 5162 } 5163 auto f = genarr(x.left()); 5164 return [=](IterSpace iters) -> ExtValue { 5165 auto val = f(iters); 5166 mlir::Value base = fir::getBase(val); 5167 auto newBase = 5168 builder.create<fir::NoReassocOp>(loc, base.getType(), base); 5169 return fir::substBase(val, newBase); 5170 }; 5171 } 5172 template <int KIND> 5173 CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type< 5174 Fortran::common::TypeCategory::Integer, KIND>> &x) { 5175 mlir::Location loc = getLoc(); 5176 auto f = genarr(x.left()); 5177 return [=](IterSpace iters) -> ExtValue { 5178 mlir::Value val = fir::getBase(f(iters)); 5179 mlir::Type ty = 5180 converter.genType(Fortran::common::TypeCategory::Integer, KIND); 5181 mlir::Value zero = builder.createIntegerConstant(loc, ty, 0); 5182 return builder.create<mlir::arith::SubIOp>(loc, zero, val); 5183 }; 5184 } 5185 template <int KIND> 5186 CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type< 5187 Fortran::common::TypeCategory::Real, KIND>> &x) { 5188 mlir::Location loc = getLoc(); 5189 auto f = genarr(x.left()); 5190 return [=](IterSpace iters) -> ExtValue { 5191 return builder.create<mlir::arith::NegFOp>(loc, fir::getBase(f(iters))); 5192 }; 5193 } 5194 template <int KIND> 5195 CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type< 5196 Fortran::common::TypeCategory::Complex, KIND>> &x) { 5197 mlir::Location loc = getLoc(); 5198 auto f = genarr(x.left()); 5199 return [=](IterSpace iters) -> ExtValue { 5200 return builder.create<fir::NegcOp>(loc, fir::getBase(f(iters))); 5201 }; 5202 } 5203 5204 //===--------------------------------------------------------------------===// 5205 // Binary elemental ops 5206 //===--------------------------------------------------------------------===// 5207 5208 template <typename OP, typename A> 5209 CC createBinaryOp(const A &evEx) { 5210 mlir::Location loc = getLoc(); 5211 auto lambda = genarr(evEx.left()); 5212 auto rf = genarr(evEx.right()); 5213 return [=](IterSpace iters) -> ExtValue { 5214 mlir::Value left = fir::getBase(lambda(iters)); 5215 mlir::Value right = fir::getBase(rf(iters)); 5216 return builder.create<OP>(loc, left, right); 5217 }; 5218 } 5219 5220 #undef GENBIN 5221 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp) \ 5222 template <int KIND> \ 5223 CC genarr(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \ 5224 Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) { \ 5225 return createBinaryOp<GenBinFirOp>(x); \ 5226 } 5227 5228 GENBIN(Add, Integer, mlir::arith::AddIOp) 5229 GENBIN(Add, Real, mlir::arith::AddFOp) 5230 GENBIN(Add, Complex, fir::AddcOp) 5231 GENBIN(Subtract, Integer, mlir::arith::SubIOp) 5232 GENBIN(Subtract, Real, mlir::arith::SubFOp) 5233 GENBIN(Subtract, Complex, fir::SubcOp) 5234 GENBIN(Multiply, Integer, mlir::arith::MulIOp) 5235 GENBIN(Multiply, Real, mlir::arith::MulFOp) 5236 GENBIN(Multiply, Complex, fir::MulcOp) 5237 GENBIN(Divide, Integer, mlir::arith::DivSIOp) 5238 GENBIN(Divide, Real, mlir::arith::DivFOp) 5239 GENBIN(Divide, Complex, fir::DivcOp) 5240 5241 template <Fortran::common::TypeCategory TC, int KIND> 5242 CC genarr( 5243 const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &x) { 5244 mlir::Location loc = getLoc(); 5245 mlir::Type ty = converter.genType(TC, KIND); 5246 auto lf = genarr(x.left()); 5247 auto rf = genarr(x.right()); 5248 return [=](IterSpace iters) -> ExtValue { 5249 mlir::Value lhs = fir::getBase(lf(iters)); 5250 mlir::Value rhs = fir::getBase(rf(iters)); 5251 return Fortran::lower::genPow(builder, loc, ty, lhs, rhs); 5252 }; 5253 } 5254 template <Fortran::common::TypeCategory TC, int KIND> 5255 CC genarr( 5256 const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>> &x) { 5257 mlir::Location loc = getLoc(); 5258 auto lf = genarr(x.left()); 5259 auto rf = genarr(x.right()); 5260 switch (x.ordering) { 5261 case Fortran::evaluate::Ordering::Greater: 5262 return [=](IterSpace iters) -> ExtValue { 5263 mlir::Value lhs = fir::getBase(lf(iters)); 5264 mlir::Value rhs = fir::getBase(rf(iters)); 5265 return Fortran::lower::genMax(builder, loc, 5266 llvm::ArrayRef<mlir::Value>{lhs, rhs}); 5267 }; 5268 case Fortran::evaluate::Ordering::Less: 5269 return [=](IterSpace iters) -> ExtValue { 5270 mlir::Value lhs = fir::getBase(lf(iters)); 5271 mlir::Value rhs = fir::getBase(rf(iters)); 5272 return Fortran::lower::genMin(builder, loc, 5273 llvm::ArrayRef<mlir::Value>{lhs, rhs}); 5274 }; 5275 case Fortran::evaluate::Ordering::Equal: 5276 llvm_unreachable("Equal is not a valid ordering in this context"); 5277 } 5278 llvm_unreachable("unknown ordering"); 5279 } 5280 template <Fortran::common::TypeCategory TC, int KIND> 5281 CC genarr( 5282 const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>> 5283 &x) { 5284 mlir::Location loc = getLoc(); 5285 auto ty = converter.genType(TC, KIND); 5286 auto lf = genarr(x.left()); 5287 auto rf = genarr(x.right()); 5288 return [=](IterSpace iters) { 5289 mlir::Value lhs = fir::getBase(lf(iters)); 5290 mlir::Value rhs = fir::getBase(rf(iters)); 5291 return Fortran::lower::genPow(builder, loc, ty, lhs, rhs); 5292 }; 5293 } 5294 template <int KIND> 5295 CC genarr(const Fortran::evaluate::ComplexConstructor<KIND> &x) { 5296 mlir::Location loc = getLoc(); 5297 auto lf = genarr(x.left()); 5298 auto rf = genarr(x.right()); 5299 return [=](IterSpace iters) -> ExtValue { 5300 mlir::Value lhs = fir::getBase(lf(iters)); 5301 mlir::Value rhs = fir::getBase(rf(iters)); 5302 return fir::factory::Complex{builder, loc}.createComplex(KIND, lhs, rhs); 5303 }; 5304 } 5305 5306 /// Fortran's concatenation operator `//`. 5307 template <int KIND> 5308 CC genarr(const Fortran::evaluate::Concat<KIND> &x) { 5309 mlir::Location loc = getLoc(); 5310 auto lf = genarr(x.left()); 5311 auto rf = genarr(x.right()); 5312 return [=](IterSpace iters) -> ExtValue { 5313 auto lhs = lf(iters); 5314 auto rhs = rf(iters); 5315 const fir::CharBoxValue *lchr = lhs.getCharBox(); 5316 const fir::CharBoxValue *rchr = rhs.getCharBox(); 5317 if (lchr && rchr) { 5318 return fir::factory::CharacterExprHelper{builder, loc} 5319 .createConcatenate(*lchr, *rchr); 5320 } 5321 TODO(loc, "concat on unexpected extended values"); 5322 return mlir::Value{}; 5323 }; 5324 } 5325 5326 template <int KIND> 5327 CC genarr(const Fortran::evaluate::SetLength<KIND> &x) { 5328 auto lf = genarr(x.left()); 5329 mlir::Value rhs = fir::getBase(asScalar(x.right())); 5330 return [=](IterSpace iters) -> ExtValue { 5331 mlir::Value lhs = fir::getBase(lf(iters)); 5332 return fir::CharBoxValue{lhs, rhs}; 5333 }; 5334 } 5335 5336 template <typename A> 5337 CC genarr(const Fortran::evaluate::Constant<A> &x) { 5338 if (x.Rank() == 0) 5339 return genScalarAndForwardValue(x); 5340 mlir::Location loc = getLoc(); 5341 mlir::IndexType idxTy = builder.getIndexType(); 5342 mlir::Type arrTy = converter.genType(toEvExpr(x)); 5343 std::string globalName = Fortran::lower::mangle::mangleArrayLiteral(x); 5344 fir::GlobalOp global = builder.getNamedGlobal(globalName); 5345 if (!global) { 5346 mlir::Type symTy = arrTy; 5347 mlir::Type eleTy = symTy.cast<fir::SequenceType>().getEleTy(); 5348 // If we have a rank-1 array of integer, real, or logical, then we can 5349 // create a global array with the dense attribute. 5350 // 5351 // The mlir tensor type can only handle integer, real, or logical. It 5352 // does not currently support nested structures which is required for 5353 // complex. 5354 // 5355 // Also, we currently handle just rank-1 since tensor type assumes 5356 // row major array ordering. We will need to reorder the dimensions 5357 // in the tensor type to support Fortran's column major array ordering. 5358 // How to create this tensor type is to be determined. 5359 if (x.Rank() == 1 && 5360 eleTy.isa<fir::LogicalType, mlir::IntegerType, mlir::FloatType>()) 5361 global = Fortran::lower::createDenseGlobal( 5362 loc, arrTy, globalName, builder.createInternalLinkage(), true, 5363 toEvExpr(x), converter); 5364 // Note: If call to createDenseGlobal() returns 0, then call 5365 // createGlobalConstant() below. 5366 if (!global) 5367 global = builder.createGlobalConstant( 5368 loc, arrTy, globalName, 5369 [&](fir::FirOpBuilder &builder) { 5370 Fortran::lower::StatementContext stmtCtx( 5371 /*cleanupProhibited=*/true); 5372 fir::ExtendedValue result = 5373 Fortran::lower::createSomeInitializerExpression( 5374 loc, converter, toEvExpr(x), symMap, stmtCtx); 5375 mlir::Value castTo = 5376 builder.createConvert(loc, arrTy, fir::getBase(result)); 5377 builder.create<fir::HasValueOp>(loc, castTo); 5378 }, 5379 builder.createInternalLinkage()); 5380 } 5381 auto addr = builder.create<fir::AddrOfOp>(getLoc(), global.resultType(), 5382 global.getSymbol()); 5383 auto seqTy = global.getType().cast<fir::SequenceType>(); 5384 llvm::SmallVector<mlir::Value> extents; 5385 for (auto extent : seqTy.getShape()) 5386 extents.push_back(builder.createIntegerConstant(loc, idxTy, extent)); 5387 if (auto charTy = seqTy.getEleTy().dyn_cast<fir::CharacterType>()) { 5388 mlir::Value len = builder.createIntegerConstant(loc, builder.getI64Type(), 5389 charTy.getLen()); 5390 return genarr(fir::CharArrayBoxValue{addr, len, extents}); 5391 } 5392 return genarr(fir::ArrayBoxValue{addr, extents}); 5393 } 5394 5395 //===--------------------------------------------------------------------===// 5396 // A vector subscript expression may be wrapped with a cast to INTEGER*8. 5397 // Get rid of it here so the vector can be loaded. Add it back when 5398 // generating the elemental evaluation (inside the loop nest). 5399 5400 static Fortran::lower::SomeExpr 5401 ignoreEvConvert(const Fortran::evaluate::Expr<Fortran::evaluate::Type< 5402 Fortran::common::TypeCategory::Integer, 8>> &x) { 5403 return std::visit([&](const auto &v) { return ignoreEvConvert(v); }, x.u); 5404 } 5405 template <Fortran::common::TypeCategory FROM> 5406 static Fortran::lower::SomeExpr ignoreEvConvert( 5407 const Fortran::evaluate::Convert< 5408 Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, 8>, 5409 FROM> &x) { 5410 return toEvExpr(x.left()); 5411 } 5412 template <typename A> 5413 static Fortran::lower::SomeExpr ignoreEvConvert(const A &x) { 5414 return toEvExpr(x); 5415 } 5416 5417 //===--------------------------------------------------------------------===// 5418 // Get the `Se::Symbol*` for the subscript expression, `x`. This symbol can 5419 // be used to determine the lbound, ubound of the vector. 5420 5421 template <typename A> 5422 static const Fortran::semantics::Symbol * 5423 extractSubscriptSymbol(const Fortran::evaluate::Expr<A> &x) { 5424 return std::visit([&](const auto &v) { return extractSubscriptSymbol(v); }, 5425 x.u); 5426 } 5427 template <typename A> 5428 static const Fortran::semantics::Symbol * 5429 extractSubscriptSymbol(const Fortran::evaluate::Designator<A> &x) { 5430 return Fortran::evaluate::UnwrapWholeSymbolDataRef(x); 5431 } 5432 template <typename A> 5433 static const Fortran::semantics::Symbol *extractSubscriptSymbol(const A &x) { 5434 return nullptr; 5435 } 5436 5437 //===--------------------------------------------------------------------===// 5438 5439 /// Get the declared lower bound value of the array `x` in dimension `dim`. 5440 /// The argument `one` must be an ssa-value for the constant 1. 5441 mlir::Value getLBound(const ExtValue &x, unsigned dim, mlir::Value one) { 5442 return fir::factory::readLowerBound(builder, getLoc(), x, dim, one); 5443 } 5444 5445 /// Get the declared upper bound value of the array `x` in dimension `dim`. 5446 /// The argument `one` must be an ssa-value for the constant 1. 5447 mlir::Value getUBound(const ExtValue &x, unsigned dim, mlir::Value one) { 5448 mlir::Location loc = getLoc(); 5449 mlir::Value lb = getLBound(x, dim, one); 5450 mlir::Value extent = fir::factory::readExtent(builder, loc, x, dim); 5451 auto add = builder.create<mlir::arith::AddIOp>(loc, lb, extent); 5452 return builder.create<mlir::arith::SubIOp>(loc, add, one); 5453 } 5454 5455 /// Return the extent of the boxed array `x` in dimesion `dim`. 5456 mlir::Value getExtent(const ExtValue &x, unsigned dim) { 5457 return fir::factory::readExtent(builder, getLoc(), x, dim); 5458 } 5459 5460 template <typename A> 5461 ExtValue genArrayBase(const A &base) { 5462 ScalarExprLowering sel{getLoc(), converter, symMap, stmtCtx}; 5463 return base.IsSymbol() ? sel.gen(getFirstSym(base)) 5464 : sel.gen(base.GetComponent()); 5465 } 5466 5467 template <typename A> 5468 bool hasEvArrayRef(const A &x) { 5469 struct HasEvArrayRefHelper 5470 : public Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper> { 5471 HasEvArrayRefHelper() 5472 : Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper>(*this) {} 5473 using Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper>::operator(); 5474 bool operator()(const Fortran::evaluate::ArrayRef &) const { 5475 return true; 5476 } 5477 } helper; 5478 return helper(x); 5479 } 5480 5481 CC genVectorSubscriptArrayFetch(const Fortran::lower::SomeExpr &expr, 5482 std::size_t dim) { 5483 PushSemantics(ConstituentSemantics::RefTransparent); 5484 auto saved = Fortran::common::ScopedSet(explicitSpace, nullptr); 5485 llvm::SmallVector<mlir::Value> savedDestShape = destShape; 5486 destShape.clear(); 5487 auto result = genarr(expr); 5488 if (destShape.empty()) 5489 TODO(getLoc(), "expected vector to have an extent"); 5490 assert(destShape.size() == 1 && "vector has rank > 1"); 5491 if (destShape[0] != savedDestShape[dim]) { 5492 // Not the same, so choose the smaller value. 5493 mlir::Location loc = getLoc(); 5494 auto cmp = builder.create<mlir::arith::CmpIOp>( 5495 loc, mlir::arith::CmpIPredicate::sgt, destShape[0], 5496 savedDestShape[dim]); 5497 auto sel = builder.create<mlir::arith::SelectOp>( 5498 loc, cmp, savedDestShape[dim], destShape[0]); 5499 savedDestShape[dim] = sel; 5500 destShape = savedDestShape; 5501 } 5502 return result; 5503 } 5504 5505 /// Generate an access by vector subscript using the index in the iteration 5506 /// vector at `dim`. 5507 mlir::Value genAccessByVector(mlir::Location loc, CC genArrFetch, 5508 IterSpace iters, std::size_t dim) { 5509 IterationSpace vecIters(iters, 5510 llvm::ArrayRef<mlir::Value>{iters.iterValue(dim)}); 5511 fir::ExtendedValue fetch = genArrFetch(vecIters); 5512 mlir::IndexType idxTy = builder.getIndexType(); 5513 return builder.createConvert(loc, idxTy, fir::getBase(fetch)); 5514 } 5515 5516 /// When we have an array reference, the expressions specified in each 5517 /// dimension may be slice operations (e.g. `i:j:k`), vectors, or simple 5518 /// (loop-invarianet) scalar expressions. This returns the base entity, the 5519 /// resulting type, and a continuation to adjust the default iteration space. 5520 void genSliceIndices(ComponentPath &cmptData, const ExtValue &arrayExv, 5521 const Fortran::evaluate::ArrayRef &x, bool atBase) { 5522 mlir::Location loc = getLoc(); 5523 mlir::IndexType idxTy = builder.getIndexType(); 5524 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1); 5525 llvm::SmallVector<mlir::Value> &trips = cmptData.trips; 5526 LLVM_DEBUG(llvm::dbgs() << "array: " << arrayExv << '\n'); 5527 auto &pc = cmptData.pc; 5528 const bool useTripsForSlice = !explicitSpaceIsActive(); 5529 const bool createDestShape = destShape.empty(); 5530 bool useSlice = false; 5531 std::size_t shapeIndex = 0; 5532 for (auto sub : llvm::enumerate(x.subscript())) { 5533 const std::size_t subsIndex = sub.index(); 5534 std::visit( 5535 Fortran::common::visitors{ 5536 [&](const Fortran::evaluate::Triplet &t) { 5537 mlir::Value lowerBound; 5538 if (auto optLo = t.lower()) 5539 lowerBound = fir::getBase(asScalar(*optLo)); 5540 else 5541 lowerBound = getLBound(arrayExv, subsIndex, one); 5542 lowerBound = builder.createConvert(loc, idxTy, lowerBound); 5543 mlir::Value stride = fir::getBase(asScalar(t.stride())); 5544 stride = builder.createConvert(loc, idxTy, stride); 5545 if (useTripsForSlice || createDestShape) { 5546 // Generate a slice operation for the triplet. The first and 5547 // second position of the triplet may be omitted, and the 5548 // declared lbound and/or ubound expression values, 5549 // respectively, should be used instead. 5550 trips.push_back(lowerBound); 5551 mlir::Value upperBound; 5552 if (auto optUp = t.upper()) 5553 upperBound = fir::getBase(asScalar(*optUp)); 5554 else 5555 upperBound = getUBound(arrayExv, subsIndex, one); 5556 upperBound = builder.createConvert(loc, idxTy, upperBound); 5557 trips.push_back(upperBound); 5558 trips.push_back(stride); 5559 if (createDestShape) { 5560 auto extent = builder.genExtentFromTriplet( 5561 loc, lowerBound, upperBound, stride, idxTy); 5562 destShape.push_back(extent); 5563 } 5564 useSlice = true; 5565 } 5566 if (!useTripsForSlice) { 5567 auto currentPC = pc; 5568 pc = [=](IterSpace iters) { 5569 IterationSpace newIters = currentPC(iters); 5570 mlir::Value impliedIter = newIters.iterValue(subsIndex); 5571 // FIXME: must use the lower bound of this component. 5572 auto arrLowerBound = 5573 atBase ? getLBound(arrayExv, subsIndex, one) : one; 5574 auto initial = builder.create<mlir::arith::SubIOp>( 5575 loc, lowerBound, arrLowerBound); 5576 auto prod = builder.create<mlir::arith::MulIOp>( 5577 loc, impliedIter, stride); 5578 auto result = 5579 builder.create<mlir::arith::AddIOp>(loc, initial, prod); 5580 newIters.setIndexValue(subsIndex, result); 5581 return newIters; 5582 }; 5583 } 5584 shapeIndex++; 5585 }, 5586 [&](const Fortran::evaluate::IndirectSubscriptIntegerExpr &ie) { 5587 const auto &e = ie.value(); // dereference 5588 if (isArray(e)) { 5589 // This is a vector subscript. Use the index values as read 5590 // from a vector to determine the temporary array value. 5591 // Note: 9.5.3.3.3(3) specifies undefined behavior for 5592 // multiple updates to any specific array element through a 5593 // vector subscript with replicated values. 5594 assert(!isBoxValue() && 5595 "fir.box cannot be created with vector subscripts"); 5596 auto arrExpr = ignoreEvConvert(e); 5597 if (createDestShape) 5598 destShape.push_back(fir::factory::getExtentAtDimension( 5599 loc, builder, arrayExv, subsIndex)); 5600 auto genArrFetch = 5601 genVectorSubscriptArrayFetch(arrExpr, shapeIndex); 5602 auto currentPC = pc; 5603 pc = [=](IterSpace iters) { 5604 IterationSpace newIters = currentPC(iters); 5605 auto val = genAccessByVector(loc, genArrFetch, newIters, 5606 subsIndex); 5607 // Value read from vector subscript array and normalized 5608 // using the base array's lower bound value. 5609 mlir::Value lb = fir::factory::readLowerBound( 5610 builder, loc, arrayExv, subsIndex, one); 5611 auto origin = builder.create<mlir::arith::SubIOp>( 5612 loc, idxTy, val, lb); 5613 newIters.setIndexValue(subsIndex, origin); 5614 return newIters; 5615 }; 5616 if (useTripsForSlice) { 5617 LLVM_ATTRIBUTE_UNUSED auto vectorSubscriptShape = 5618 getShape(arrayOperands.back()); 5619 auto undef = builder.create<fir::UndefOp>(loc, idxTy); 5620 trips.push_back(undef); 5621 trips.push_back(undef); 5622 trips.push_back(undef); 5623 } 5624 shapeIndex++; 5625 } else { 5626 // This is a regular scalar subscript. 5627 if (useTripsForSlice) { 5628 // A regular scalar index, which does not yield an array 5629 // section. Use a degenerate slice operation 5630 // `(e:undef:undef)` in this dimension as a placeholder. 5631 // This does not necessarily change the rank of the original 5632 // array, so the iteration space must also be extended to 5633 // include this expression in this dimension to adjust to 5634 // the array's declared rank. 5635 mlir::Value v = fir::getBase(asScalar(e)); 5636 trips.push_back(v); 5637 auto undef = builder.create<fir::UndefOp>(loc, idxTy); 5638 trips.push_back(undef); 5639 trips.push_back(undef); 5640 auto currentPC = pc; 5641 // Cast `e` to index type. 5642 mlir::Value iv = builder.createConvert(loc, idxTy, v); 5643 // Normalize `e` by subtracting the declared lbound. 5644 mlir::Value lb = fir::factory::readLowerBound( 5645 builder, loc, arrayExv, subsIndex, one); 5646 mlir::Value ivAdj = 5647 builder.create<mlir::arith::SubIOp>(loc, idxTy, iv, lb); 5648 // Add lbound adjusted value of `e` to the iteration vector 5649 // (except when creating a box because the iteration vector 5650 // is empty). 5651 if (!isBoxValue()) 5652 pc = [=](IterSpace iters) { 5653 IterationSpace newIters = currentPC(iters); 5654 newIters.insertIndexValue(subsIndex, ivAdj); 5655 return newIters; 5656 }; 5657 } else { 5658 auto currentPC = pc; 5659 mlir::Value newValue = fir::getBase(asScalarArray(e)); 5660 mlir::Value result = 5661 builder.createConvert(loc, idxTy, newValue); 5662 mlir::Value lb = fir::factory::readLowerBound( 5663 builder, loc, arrayExv, subsIndex, one); 5664 result = builder.create<mlir::arith::SubIOp>(loc, idxTy, 5665 result, lb); 5666 pc = [=](IterSpace iters) { 5667 IterationSpace newIters = currentPC(iters); 5668 newIters.insertIndexValue(subsIndex, result); 5669 return newIters; 5670 }; 5671 } 5672 } 5673 }}, 5674 sub.value().u); 5675 } 5676 if (!useSlice) 5677 trips.clear(); 5678 } 5679 5680 static mlir::Type unwrapBoxEleTy(mlir::Type ty) { 5681 if (auto boxTy = ty.dyn_cast<fir::BoxType>()) 5682 return fir::unwrapRefType(boxTy.getEleTy()); 5683 return ty; 5684 } 5685 5686 llvm::SmallVector<mlir::Value> getShape(mlir::Type ty) { 5687 llvm::SmallVector<mlir::Value> result; 5688 ty = unwrapBoxEleTy(ty); 5689 mlir::Location loc = getLoc(); 5690 mlir::IndexType idxTy = builder.getIndexType(); 5691 for (auto extent : ty.cast<fir::SequenceType>().getShape()) { 5692 auto v = extent == fir::SequenceType::getUnknownExtent() 5693 ? builder.create<fir::UndefOp>(loc, idxTy).getResult() 5694 : builder.createIntegerConstant(loc, idxTy, extent); 5695 result.push_back(v); 5696 } 5697 return result; 5698 } 5699 5700 CC genarr(const Fortran::semantics::SymbolRef &sym, 5701 ComponentPath &components) { 5702 return genarr(sym.get(), components); 5703 } 5704 5705 ExtValue abstractArrayExtValue(mlir::Value val, mlir::Value len = {}) { 5706 return convertToArrayBoxValue(getLoc(), builder, val, len); 5707 } 5708 5709 CC genarr(const ExtValue &extMemref) { 5710 ComponentPath dummy(/*isImplicit=*/true); 5711 return genarr(extMemref, dummy); 5712 } 5713 5714 /// Base case of generating an array reference, 5715 CC genarr(const ExtValue &extMemref, ComponentPath &components) { 5716 mlir::Location loc = getLoc(); 5717 mlir::Value memref = fir::getBase(extMemref); 5718 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(memref.getType()); 5719 assert(arrTy.isa<fir::SequenceType>() && "memory ref must be an array"); 5720 mlir::Value shape = builder.createShape(loc, extMemref); 5721 mlir::Value slice; 5722 if (components.isSlice()) { 5723 if (isBoxValue() && components.substring) { 5724 // Append the substring operator to emboxing Op as it will become an 5725 // interior adjustment (add offset, adjust LEN) to the CHARACTER value 5726 // being referenced in the descriptor. 5727 llvm::SmallVector<mlir::Value> substringBounds; 5728 populateBounds(substringBounds, components.substring); 5729 // Convert to (offset, size) 5730 mlir::Type iTy = substringBounds[0].getType(); 5731 if (substringBounds.size() != 2) { 5732 fir::CharacterType charTy = 5733 fir::factory::CharacterExprHelper::getCharType(arrTy); 5734 if (charTy.hasConstantLen()) { 5735 mlir::IndexType idxTy = builder.getIndexType(); 5736 fir::CharacterType::LenType charLen = charTy.getLen(); 5737 mlir::Value lenValue = 5738 builder.createIntegerConstant(loc, idxTy, charLen); 5739 substringBounds.push_back(lenValue); 5740 } else { 5741 llvm::SmallVector<mlir::Value> typeparams = 5742 fir::getTypeParams(extMemref); 5743 substringBounds.push_back(typeparams.back()); 5744 } 5745 } 5746 // Convert the lower bound to 0-based substring. 5747 mlir::Value one = 5748 builder.createIntegerConstant(loc, substringBounds[0].getType(), 1); 5749 substringBounds[0] = 5750 builder.create<mlir::arith::SubIOp>(loc, substringBounds[0], one); 5751 // Convert the upper bound to a length. 5752 mlir::Value cast = builder.createConvert(loc, iTy, substringBounds[1]); 5753 mlir::Value zero = builder.createIntegerConstant(loc, iTy, 0); 5754 auto size = 5755 builder.create<mlir::arith::SubIOp>(loc, cast, substringBounds[0]); 5756 auto cmp = builder.create<mlir::arith::CmpIOp>( 5757 loc, mlir::arith::CmpIPredicate::sgt, size, zero); 5758 // size = MAX(upper - (lower - 1), 0) 5759 substringBounds[1] = 5760 builder.create<mlir::arith::SelectOp>(loc, cmp, size, zero); 5761 slice = builder.create<fir::SliceOp>(loc, components.trips, 5762 components.suffixComponents, 5763 substringBounds); 5764 } else { 5765 slice = builder.createSlice(loc, extMemref, components.trips, 5766 components.suffixComponents); 5767 } 5768 if (components.hasComponents()) { 5769 auto seqTy = arrTy.cast<fir::SequenceType>(); 5770 mlir::Type eleTy = 5771 fir::applyPathToType(seqTy.getEleTy(), components.suffixComponents); 5772 if (!eleTy) 5773 fir::emitFatalError(loc, "slicing path is ill-formed"); 5774 if (auto realTy = eleTy.dyn_cast<fir::RealType>()) 5775 eleTy = Fortran::lower::convertReal(realTy.getContext(), 5776 realTy.getFKind()); 5777 5778 // create the type of the projected array. 5779 arrTy = fir::SequenceType::get(seqTy.getShape(), eleTy); 5780 LLVM_DEBUG(llvm::dbgs() 5781 << "type of array projection from component slicing: " 5782 << eleTy << ", " << arrTy << '\n'); 5783 } 5784 } 5785 arrayOperands.push_back(ArrayOperand{memref, shape, slice}); 5786 if (destShape.empty()) 5787 destShape = getShape(arrayOperands.back()); 5788 if (isBoxValue()) { 5789 // Semantics are a reference to a boxed array. 5790 // This case just requires that an embox operation be created to box the 5791 // value. The value of the box is forwarded in the continuation. 5792 mlir::Type reduceTy = reduceRank(arrTy, slice); 5793 auto boxTy = fir::BoxType::get(reduceTy); 5794 if (components.substring) { 5795 // Adjust char length to substring size. 5796 fir::CharacterType charTy = 5797 fir::factory::CharacterExprHelper::getCharType(reduceTy); 5798 auto seqTy = reduceTy.cast<fir::SequenceType>(); 5799 // TODO: Use a constant for fir.char LEN if we can compute it. 5800 boxTy = fir::BoxType::get( 5801 fir::SequenceType::get(fir::CharacterType::getUnknownLen( 5802 builder.getContext(), charTy.getFKind()), 5803 seqTy.getDimension())); 5804 } 5805 mlir::Value embox = 5806 memref.getType().isa<fir::BoxType>() 5807 ? builder.create<fir::ReboxOp>(loc, boxTy, memref, shape, slice) 5808 .getResult() 5809 : builder 5810 .create<fir::EmboxOp>(loc, boxTy, memref, shape, slice, 5811 fir::getTypeParams(extMemref)) 5812 .getResult(); 5813 return [=](IterSpace) -> ExtValue { return fir::BoxValue(embox); }; 5814 } 5815 auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy(); 5816 if (isReferentiallyOpaque()) { 5817 // Semantics are an opaque reference to an array. 5818 // This case forwards a continuation that will generate the address 5819 // arithmetic to the array element. This does not have copy-in/copy-out 5820 // semantics. No attempt to copy the array value will be made during the 5821 // interpretation of the Fortran statement. 5822 mlir::Type refEleTy = builder.getRefType(eleTy); 5823 return [=](IterSpace iters) -> ExtValue { 5824 // ArrayCoorOp does not expect zero based indices. 5825 llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices( 5826 loc, builder, memref.getType(), shape, iters.iterVec()); 5827 mlir::Value coor = builder.create<fir::ArrayCoorOp>( 5828 loc, refEleTy, memref, shape, slice, indices, 5829 fir::getTypeParams(extMemref)); 5830 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 5831 llvm::SmallVector<mlir::Value> substringBounds; 5832 populateBounds(substringBounds, components.substring); 5833 if (!substringBounds.empty()) { 5834 mlir::Value dstLen = fir::factory::genLenOfCharacter( 5835 builder, loc, arrTy.cast<fir::SequenceType>(), memref, 5836 fir::getTypeParams(extMemref), iters.iterVec(), 5837 substringBounds); 5838 fir::CharBoxValue dstChar(coor, dstLen); 5839 return fir::factory::CharacterExprHelper{builder, loc} 5840 .createSubstring(dstChar, substringBounds); 5841 } 5842 } 5843 return fir::factory::arraySectionElementToExtendedValue( 5844 builder, loc, extMemref, coor, slice); 5845 }; 5846 } 5847 auto arrLoad = builder.create<fir::ArrayLoadOp>( 5848 loc, arrTy, memref, shape, slice, fir::getTypeParams(extMemref)); 5849 mlir::Value arrLd = arrLoad.getResult(); 5850 if (isProjectedCopyInCopyOut()) { 5851 // Semantics are projected copy-in copy-out. 5852 // The backing store of the destination of an array expression may be 5853 // partially modified. These updates are recorded in FIR by forwarding a 5854 // continuation that generates an `array_update` Op. The destination is 5855 // always loaded at the beginning of the statement and merged at the 5856 // end. 5857 destination = arrLoad; 5858 auto lambda = ccStoreToDest.hasValue() 5859 ? ccStoreToDest.getValue() 5860 : defaultStoreToDestination(components.substring); 5861 return [=](IterSpace iters) -> ExtValue { return lambda(iters); }; 5862 } 5863 if (isCustomCopyInCopyOut()) { 5864 // Create an array_modify to get the LHS element address and indicate 5865 // the assignment, the actual assignment must be implemented in 5866 // ccStoreToDest. 5867 destination = arrLoad; 5868 return [=](IterSpace iters) -> ExtValue { 5869 mlir::Value innerArg = iters.innerArgument(); 5870 mlir::Type resTy = innerArg.getType(); 5871 mlir::Type eleTy = fir::applyPathToType(resTy, iters.iterVec()); 5872 mlir::Type refEleTy = 5873 fir::isa_ref_type(eleTy) ? eleTy : builder.getRefType(eleTy); 5874 auto arrModify = builder.create<fir::ArrayModifyOp>( 5875 loc, mlir::TypeRange{refEleTy, resTy}, innerArg, iters.iterVec(), 5876 destination.getTypeparams()); 5877 return abstractArrayExtValue(arrModify.getResult(1)); 5878 }; 5879 } 5880 if (isCopyInCopyOut()) { 5881 // Semantics are copy-in copy-out. 5882 // The continuation simply forwards the result of the `array_load` Op, 5883 // which is the value of the array as it was when loaded. All data 5884 // references with rank > 0 in an array expression typically have 5885 // copy-in copy-out semantics. 5886 return [=](IterSpace) -> ExtValue { return arrLd; }; 5887 } 5888 mlir::Operation::operand_range arrLdTypeParams = arrLoad.getTypeparams(); 5889 if (isValueAttribute()) { 5890 // Semantics are value attribute. 5891 // Here the continuation will `array_fetch` a value from an array and 5892 // then store that value in a temporary. One can thus imitate pass by 5893 // value even when the call is pass by reference. 5894 return [=](IterSpace iters) -> ExtValue { 5895 mlir::Value base; 5896 mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec()); 5897 if (isAdjustedArrayElementType(eleTy)) { 5898 mlir::Type eleRefTy = builder.getRefType(eleTy); 5899 base = builder.create<fir::ArrayAccessOp>( 5900 loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams); 5901 } else { 5902 base = builder.create<fir::ArrayFetchOp>( 5903 loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams); 5904 } 5905 mlir::Value temp = builder.createTemporary( 5906 loc, base.getType(), 5907 llvm::ArrayRef<mlir::NamedAttribute>{ 5908 Fortran::lower::getAdaptToByRefAttr(builder)}); 5909 builder.create<fir::StoreOp>(loc, base, temp); 5910 return fir::factory::arraySectionElementToExtendedValue( 5911 builder, loc, extMemref, temp, slice); 5912 }; 5913 } 5914 // In the default case, the array reference forwards an `array_fetch` or 5915 // `array_access` Op in the continuation. 5916 return [=](IterSpace iters) -> ExtValue { 5917 mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec()); 5918 if (isAdjustedArrayElementType(eleTy)) { 5919 mlir::Type eleRefTy = builder.getRefType(eleTy); 5920 mlir::Value arrayOp = builder.create<fir::ArrayAccessOp>( 5921 loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams); 5922 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 5923 llvm::SmallVector<mlir::Value> substringBounds; 5924 populateBounds(substringBounds, components.substring); 5925 if (!substringBounds.empty()) { 5926 mlir::Value dstLen = fir::factory::genLenOfCharacter( 5927 builder, loc, arrLoad, iters.iterVec(), substringBounds); 5928 fir::CharBoxValue dstChar(arrayOp, dstLen); 5929 return fir::factory::CharacterExprHelper{builder, loc} 5930 .createSubstring(dstChar, substringBounds); 5931 } 5932 } 5933 return fir::factory::arraySectionElementToExtendedValue( 5934 builder, loc, extMemref, arrayOp, slice); 5935 } 5936 auto arrFetch = builder.create<fir::ArrayFetchOp>( 5937 loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams); 5938 return fir::factory::arraySectionElementToExtendedValue( 5939 builder, loc, extMemref, arrFetch, slice); 5940 }; 5941 } 5942 5943 /// Given an optional fir.box, returns an fir.box that is the original one if 5944 /// it is present and it otherwise an unallocated box. 5945 /// Absent fir.box are implemented as a null pointer descriptor. Generated 5946 /// code may need to unconditionally read a fir.box that can be absent. 5947 /// This helper allows creating a fir.box that can be read in all cases 5948 /// outside of a fir.if (isPresent) region. However, the usages of the value 5949 /// read from such box should still only be done in a fir.if(isPresent). 5950 static fir::ExtendedValue 5951 absentBoxToUnalllocatedBox(fir::FirOpBuilder &builder, mlir::Location loc, 5952 const fir::ExtendedValue &exv, 5953 mlir::Value isPresent) { 5954 mlir::Value box = fir::getBase(exv); 5955 mlir::Type boxType = box.getType(); 5956 assert(boxType.isa<fir::BoxType>() && "argument must be a fir.box"); 5957 mlir::Value emptyBox = 5958 fir::factory::createUnallocatedBox(builder, loc, boxType, llvm::None); 5959 auto safeToReadBox = 5960 builder.create<mlir::arith::SelectOp>(loc, isPresent, box, emptyBox); 5961 return fir::substBase(exv, safeToReadBox); 5962 } 5963 5964 std::tuple<CC, mlir::Value, mlir::Type> 5965 genOptionalArrayFetch(const Fortran::lower::SomeExpr &expr) { 5966 assert(expr.Rank() > 0 && "expr must be an array"); 5967 mlir::Location loc = getLoc(); 5968 ExtValue optionalArg = asInquired(expr); 5969 mlir::Value isPresent = genActualIsPresentTest(builder, loc, optionalArg); 5970 // Generate an array load and access to an array that may be an absent 5971 // optional or an unallocated optional. 5972 mlir::Value base = getBase(optionalArg); 5973 const bool hasOptionalAttr = 5974 fir::valueHasFirAttribute(base, fir::getOptionalAttrName()); 5975 mlir::Type baseType = fir::unwrapRefType(base.getType()); 5976 const bool isBox = baseType.isa<fir::BoxType>(); 5977 const bool isAllocOrPtr = Fortran::evaluate::IsAllocatableOrPointerObject( 5978 expr, converter.getFoldingContext()); 5979 mlir::Type arrType = fir::unwrapPassByRefType(baseType); 5980 mlir::Type eleType = fir::unwrapSequenceType(arrType); 5981 ExtValue exv = optionalArg; 5982 if (hasOptionalAttr && isBox && !isAllocOrPtr) { 5983 // Elemental argument cannot be allocatable or pointers (C15100). 5984 // Hence, per 15.5.2.12 3 (8) and (9), the provided Allocatable and 5985 // Pointer optional arrays cannot be absent. The only kind of entities 5986 // that can get here are optional assumed shape and polymorphic entities. 5987 exv = absentBoxToUnalllocatedBox(builder, loc, exv, isPresent); 5988 } 5989 // All the properties can be read from any fir.box but the read values may 5990 // be undefined and should only be used inside a fir.if (canBeRead) region. 5991 if (const auto *mutableBox = exv.getBoxOf<fir::MutableBoxValue>()) 5992 exv = fir::factory::genMutableBoxRead(builder, loc, *mutableBox); 5993 5994 mlir::Value memref = fir::getBase(exv); 5995 mlir::Value shape = builder.createShape(loc, exv); 5996 mlir::Value noSlice; 5997 auto arrLoad = builder.create<fir::ArrayLoadOp>( 5998 loc, arrType, memref, shape, noSlice, fir::getTypeParams(exv)); 5999 mlir::Operation::operand_range arrLdTypeParams = arrLoad.getTypeparams(); 6000 mlir::Value arrLd = arrLoad.getResult(); 6001 // Mark the load to tell later passes it is unsafe to use this array_load 6002 // shape unconditionally. 6003 arrLoad->setAttr(fir::getOptionalAttrName(), builder.getUnitAttr()); 6004 6005 // Place the array as optional on the arrayOperands stack so that its 6006 // shape will only be used as a fallback to induce the implicit loop nest 6007 // (that is if there is no non optional array arguments). 6008 arrayOperands.push_back( 6009 ArrayOperand{memref, shape, noSlice, /*mayBeAbsent=*/true}); 6010 6011 // By value semantics. 6012 auto cc = [=](IterSpace iters) -> ExtValue { 6013 auto arrFetch = builder.create<fir::ArrayFetchOp>( 6014 loc, eleType, arrLd, iters.iterVec(), arrLdTypeParams); 6015 return fir::factory::arraySectionElementToExtendedValue( 6016 builder, loc, exv, arrFetch, noSlice); 6017 }; 6018 return {cc, isPresent, eleType}; 6019 } 6020 6021 /// Generate a continuation to pass \p expr to an OPTIONAL argument of an 6022 /// elemental procedure. This is meant to handle the cases where \p expr might 6023 /// be dynamically absent (i.e. when it is a POINTER, an ALLOCATABLE or an 6024 /// OPTIONAL variable). If p\ expr is guaranteed to be present genarr() can 6025 /// directly be called instead. 6026 CC genarrForwardOptionalArgumentToCall(const Fortran::lower::SomeExpr &expr) { 6027 mlir::Location loc = getLoc(); 6028 // Only by-value numerical and logical so far. 6029 if (semant != ConstituentSemantics::RefTransparent) 6030 TODO(loc, "optional arguments in user defined elemental procedures"); 6031 6032 // Handle scalar argument case (the if-then-else is generated outside of the 6033 // implicit loop nest). 6034 if (expr.Rank() == 0) { 6035 ExtValue optionalArg = asInquired(expr); 6036 mlir::Value isPresent = genActualIsPresentTest(builder, loc, optionalArg); 6037 mlir::Value elementValue = 6038 fir::getBase(genOptionalValue(builder, loc, optionalArg, isPresent)); 6039 return [=](IterSpace iters) -> ExtValue { return elementValue; }; 6040 } 6041 6042 CC cc; 6043 mlir::Value isPresent; 6044 mlir::Type eleType; 6045 std::tie(cc, isPresent, eleType) = genOptionalArrayFetch(expr); 6046 return [=](IterSpace iters) -> ExtValue { 6047 mlir::Value elementValue = 6048 builder 6049 .genIfOp(loc, {eleType}, isPresent, 6050 /*withElseRegion=*/true) 6051 .genThen([&]() { 6052 builder.create<fir::ResultOp>(loc, fir::getBase(cc(iters))); 6053 }) 6054 .genElse([&]() { 6055 mlir::Value zero = 6056 fir::factory::createZeroValue(builder, loc, eleType); 6057 builder.create<fir::ResultOp>(loc, zero); 6058 }) 6059 .getResults()[0]; 6060 return elementValue; 6061 }; 6062 } 6063 6064 /// Reduce the rank of a array to be boxed based on the slice's operands. 6065 static mlir::Type reduceRank(mlir::Type arrTy, mlir::Value slice) { 6066 if (slice) { 6067 auto slOp = mlir::dyn_cast<fir::SliceOp>(slice.getDefiningOp()); 6068 assert(slOp && "expected slice op"); 6069 auto seqTy = arrTy.dyn_cast<fir::SequenceType>(); 6070 assert(seqTy && "expected array type"); 6071 mlir::Operation::operand_range triples = slOp.getTriples(); 6072 fir::SequenceType::Shape shape; 6073 // reduce the rank for each invariant dimension 6074 for (unsigned i = 1, end = triples.size(); i < end; i += 3) 6075 if (!mlir::isa_and_nonnull<fir::UndefOp>(triples[i].getDefiningOp())) 6076 shape.push_back(fir::SequenceType::getUnknownExtent()); 6077 return fir::SequenceType::get(shape, seqTy.getEleTy()); 6078 } 6079 // not sliced, so no change in rank 6080 return arrTy; 6081 } 6082 6083 /// Example: <code>array%RE</code> 6084 CC genarr(const Fortran::evaluate::ComplexPart &x, 6085 ComponentPath &components) { 6086 components.reversePath.push_back(&x); 6087 return genarr(x.complex(), components); 6088 } 6089 6090 template <typename A> 6091 CC genSlicePath(const A &x, ComponentPath &components) { 6092 return genarr(x, components); 6093 } 6094 6095 CC genarr(const Fortran::evaluate::StaticDataObject::Pointer &, 6096 ComponentPath &components) { 6097 fir::emitFatalError(getLoc(), "substring of static array object"); 6098 } 6099 6100 /// Substrings (see 9.4.1) 6101 CC genarr(const Fortran::evaluate::Substring &x, ComponentPath &components) { 6102 components.substring = &x; 6103 return std::visit([&](const auto &v) { return genarr(v, components); }, 6104 x.parent()); 6105 } 6106 6107 template <typename T> 6108 CC genarr(const Fortran::evaluate::FunctionRef<T> &funRef) { 6109 // Note that it's possible that the function being called returns either an 6110 // array or a scalar. In the first case, use the element type of the array. 6111 return genProcRef( 6112 funRef, fir::unwrapSequenceType(converter.genType(toEvExpr(funRef)))); 6113 } 6114 6115 //===--------------------------------------------------------------------===// 6116 // Array construction 6117 //===--------------------------------------------------------------------===// 6118 6119 /// Target agnostic computation of the size of an element in the array. 6120 /// Returns the size in bytes with type `index` or a null Value if the element 6121 /// size is not constant. 6122 mlir::Value computeElementSize(const ExtValue &exv, mlir::Type eleTy, 6123 mlir::Type resTy) { 6124 mlir::Location loc = getLoc(); 6125 mlir::IndexType idxTy = builder.getIndexType(); 6126 mlir::Value multiplier = builder.createIntegerConstant(loc, idxTy, 1); 6127 if (fir::hasDynamicSize(eleTy)) { 6128 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 6129 // Array of char with dynamic length parameter. Downcast to an array 6130 // of singleton char, and scale by the len type parameter from 6131 // `exv`. 6132 exv.match( 6133 [&](const fir::CharBoxValue &cb) { multiplier = cb.getLen(); }, 6134 [&](const fir::CharArrayBoxValue &cb) { multiplier = cb.getLen(); }, 6135 [&](const fir::BoxValue &box) { 6136 multiplier = fir::factory::CharacterExprHelper(builder, loc) 6137 .readLengthFromBox(box.getAddr()); 6138 }, 6139 [&](const fir::MutableBoxValue &box) { 6140 multiplier = fir::factory::CharacterExprHelper(builder, loc) 6141 .readLengthFromBox(box.getAddr()); 6142 }, 6143 [&](const auto &) { 6144 fir::emitFatalError(loc, 6145 "array constructor element has unknown size"); 6146 }); 6147 fir::CharacterType newEleTy = fir::CharacterType::getSingleton( 6148 eleTy.getContext(), charTy.getFKind()); 6149 if (auto seqTy = resTy.dyn_cast<fir::SequenceType>()) { 6150 assert(eleTy == seqTy.getEleTy()); 6151 resTy = fir::SequenceType::get(seqTy.getShape(), newEleTy); 6152 } 6153 eleTy = newEleTy; 6154 } else { 6155 TODO(loc, "dynamic sized type"); 6156 } 6157 } 6158 mlir::Type eleRefTy = builder.getRefType(eleTy); 6159 mlir::Type resRefTy = builder.getRefType(resTy); 6160 mlir::Value nullPtr = builder.createNullConstant(loc, resRefTy); 6161 auto offset = builder.create<fir::CoordinateOp>( 6162 loc, eleRefTy, nullPtr, mlir::ValueRange{multiplier}); 6163 return builder.createConvert(loc, idxTy, offset); 6164 } 6165 6166 /// Get the function signature of the LLVM memcpy intrinsic. 6167 mlir::FunctionType memcpyType() { 6168 return fir::factory::getLlvmMemcpy(builder).getFunctionType(); 6169 } 6170 6171 /// Create a call to the LLVM memcpy intrinsic. 6172 void createCallMemcpy(llvm::ArrayRef<mlir::Value> args) { 6173 mlir::Location loc = getLoc(); 6174 mlir::func::FuncOp memcpyFunc = fir::factory::getLlvmMemcpy(builder); 6175 mlir::SymbolRefAttr funcSymAttr = 6176 builder.getSymbolRefAttr(memcpyFunc.getName()); 6177 mlir::FunctionType funcTy = memcpyFunc.getFunctionType(); 6178 builder.create<fir::CallOp>(loc, funcTy.getResults(), funcSymAttr, args); 6179 } 6180 6181 // Construct code to check for a buffer overrun and realloc the buffer when 6182 // space is depleted. This is done between each item in the ac-value-list. 6183 mlir::Value growBuffer(mlir::Value mem, mlir::Value needed, 6184 mlir::Value bufferSize, mlir::Value buffSize, 6185 mlir::Value eleSz) { 6186 mlir::Location loc = getLoc(); 6187 mlir::func::FuncOp reallocFunc = fir::factory::getRealloc(builder); 6188 auto cond = builder.create<mlir::arith::CmpIOp>( 6189 loc, mlir::arith::CmpIPredicate::sle, bufferSize, needed); 6190 auto ifOp = builder.create<fir::IfOp>(loc, mem.getType(), cond, 6191 /*withElseRegion=*/true); 6192 auto insPt = builder.saveInsertionPoint(); 6193 builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); 6194 // Not enough space, resize the buffer. 6195 mlir::IndexType idxTy = builder.getIndexType(); 6196 mlir::Value two = builder.createIntegerConstant(loc, idxTy, 2); 6197 auto newSz = builder.create<mlir::arith::MulIOp>(loc, needed, two); 6198 builder.create<fir::StoreOp>(loc, newSz, buffSize); 6199 mlir::Value byteSz = builder.create<mlir::arith::MulIOp>(loc, newSz, eleSz); 6200 mlir::SymbolRefAttr funcSymAttr = 6201 builder.getSymbolRefAttr(reallocFunc.getName()); 6202 mlir::FunctionType funcTy = reallocFunc.getFunctionType(); 6203 auto newMem = builder.create<fir::CallOp>( 6204 loc, funcTy.getResults(), funcSymAttr, 6205 llvm::ArrayRef<mlir::Value>{ 6206 builder.createConvert(loc, funcTy.getInputs()[0], mem), 6207 builder.createConvert(loc, funcTy.getInputs()[1], byteSz)}); 6208 mlir::Value castNewMem = 6209 builder.createConvert(loc, mem.getType(), newMem.getResult(0)); 6210 builder.create<fir::ResultOp>(loc, castNewMem); 6211 builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); 6212 // Otherwise, just forward the buffer. 6213 builder.create<fir::ResultOp>(loc, mem); 6214 builder.restoreInsertionPoint(insPt); 6215 return ifOp.getResult(0); 6216 } 6217 6218 /// Copy the next value (or vector of values) into the array being 6219 /// constructed. 6220 mlir::Value copyNextArrayCtorSection(const ExtValue &exv, mlir::Value buffPos, 6221 mlir::Value buffSize, mlir::Value mem, 6222 mlir::Value eleSz, mlir::Type eleTy, 6223 mlir::Type eleRefTy, mlir::Type resTy) { 6224 mlir::Location loc = getLoc(); 6225 auto off = builder.create<fir::LoadOp>(loc, buffPos); 6226 auto limit = builder.create<fir::LoadOp>(loc, buffSize); 6227 mlir::IndexType idxTy = builder.getIndexType(); 6228 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1); 6229 6230 if (fir::isRecordWithAllocatableMember(eleTy)) 6231 TODO(loc, "deep copy on allocatable members"); 6232 6233 if (!eleSz) { 6234 // Compute the element size at runtime. 6235 assert(fir::hasDynamicSize(eleTy)); 6236 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 6237 auto charBytes = 6238 builder.getKindMap().getCharacterBitsize(charTy.getFKind()) / 8; 6239 mlir::Value bytes = 6240 builder.createIntegerConstant(loc, idxTy, charBytes); 6241 mlir::Value length = fir::getLen(exv); 6242 if (!length) 6243 fir::emitFatalError(loc, "result is not boxed character"); 6244 eleSz = builder.create<mlir::arith::MulIOp>(loc, bytes, length); 6245 } else { 6246 TODO(loc, "PDT size"); 6247 // Will call the PDT's size function with the type parameters. 6248 } 6249 } 6250 6251 // Compute the coordinate using `fir.coordinate_of`, or, if the type has 6252 // dynamic size, generating the pointer arithmetic. 6253 auto computeCoordinate = [&](mlir::Value buff, mlir::Value off) { 6254 mlir::Type refTy = eleRefTy; 6255 if (fir::hasDynamicSize(eleTy)) { 6256 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 6257 // Scale a simple pointer using dynamic length and offset values. 6258 auto chTy = fir::CharacterType::getSingleton(charTy.getContext(), 6259 charTy.getFKind()); 6260 refTy = builder.getRefType(chTy); 6261 mlir::Type toTy = builder.getRefType(builder.getVarLenSeqTy(chTy)); 6262 buff = builder.createConvert(loc, toTy, buff); 6263 off = builder.create<mlir::arith::MulIOp>(loc, off, eleSz); 6264 } else { 6265 TODO(loc, "PDT offset"); 6266 } 6267 } 6268 auto coor = builder.create<fir::CoordinateOp>(loc, refTy, buff, 6269 mlir::ValueRange{off}); 6270 return builder.createConvert(loc, eleRefTy, coor); 6271 }; 6272 6273 // Lambda to lower an abstract array box value. 6274 auto doAbstractArray = [&](const auto &v) { 6275 // Compute the array size. 6276 mlir::Value arrSz = one; 6277 for (auto ext : v.getExtents()) 6278 arrSz = builder.create<mlir::arith::MulIOp>(loc, arrSz, ext); 6279 6280 // Grow the buffer as needed. 6281 auto endOff = builder.create<mlir::arith::AddIOp>(loc, off, arrSz); 6282 mem = growBuffer(mem, endOff, limit, buffSize, eleSz); 6283 6284 // Copy the elements to the buffer. 6285 mlir::Value byteSz = 6286 builder.create<mlir::arith::MulIOp>(loc, arrSz, eleSz); 6287 auto buff = builder.createConvert(loc, fir::HeapType::get(resTy), mem); 6288 mlir::Value buffi = computeCoordinate(buff, off); 6289 llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments( 6290 builder, loc, memcpyType(), buffi, v.getAddr(), byteSz, 6291 /*volatile=*/builder.createBool(loc, false)); 6292 createCallMemcpy(args); 6293 6294 // Save the incremented buffer position. 6295 builder.create<fir::StoreOp>(loc, endOff, buffPos); 6296 }; 6297 6298 // Copy a trivial scalar value into the buffer. 6299 auto doTrivialScalar = [&](const ExtValue &v, mlir::Value len = {}) { 6300 // Increment the buffer position. 6301 auto plusOne = builder.create<mlir::arith::AddIOp>(loc, off, one); 6302 6303 // Grow the buffer as needed. 6304 mem = growBuffer(mem, plusOne, limit, buffSize, eleSz); 6305 6306 // Store the element in the buffer. 6307 mlir::Value buff = 6308 builder.createConvert(loc, fir::HeapType::get(resTy), mem); 6309 auto buffi = builder.create<fir::CoordinateOp>(loc, eleRefTy, buff, 6310 mlir::ValueRange{off}); 6311 fir::factory::genScalarAssignment( 6312 builder, loc, 6313 [&]() -> ExtValue { 6314 if (len) 6315 return fir::CharBoxValue(buffi, len); 6316 return buffi; 6317 }(), 6318 v); 6319 builder.create<fir::StoreOp>(loc, plusOne, buffPos); 6320 }; 6321 6322 // Copy the value. 6323 exv.match( 6324 [&](mlir::Value) { doTrivialScalar(exv); }, 6325 [&](const fir::CharBoxValue &v) { 6326 auto buffer = v.getBuffer(); 6327 if (fir::isa_char(buffer.getType())) { 6328 doTrivialScalar(exv, eleSz); 6329 } else { 6330 // Increment the buffer position. 6331 auto plusOne = builder.create<mlir::arith::AddIOp>(loc, off, one); 6332 6333 // Grow the buffer as needed. 6334 mem = growBuffer(mem, plusOne, limit, buffSize, eleSz); 6335 6336 // Store the element in the buffer. 6337 mlir::Value buff = 6338 builder.createConvert(loc, fir::HeapType::get(resTy), mem); 6339 mlir::Value buffi = computeCoordinate(buff, off); 6340 llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments( 6341 builder, loc, memcpyType(), buffi, v.getAddr(), eleSz, 6342 /*volatile=*/builder.createBool(loc, false)); 6343 createCallMemcpy(args); 6344 6345 builder.create<fir::StoreOp>(loc, plusOne, buffPos); 6346 } 6347 }, 6348 [&](const fir::ArrayBoxValue &v) { doAbstractArray(v); }, 6349 [&](const fir::CharArrayBoxValue &v) { doAbstractArray(v); }, 6350 [&](const auto &) { 6351 TODO(loc, "unhandled array constructor expression"); 6352 }); 6353 return mem; 6354 } 6355 6356 // Lower the expr cases in an ac-value-list. 6357 template <typename A> 6358 std::pair<ExtValue, bool> 6359 genArrayCtorInitializer(const Fortran::evaluate::Expr<A> &x, mlir::Type, 6360 mlir::Value, mlir::Value, mlir::Value, 6361 Fortran::lower::StatementContext &stmtCtx) { 6362 if (isArray(x)) 6363 return {lowerNewArrayExpression(converter, symMap, stmtCtx, toEvExpr(x)), 6364 /*needCopy=*/true}; 6365 return {asScalar(x), /*needCopy=*/true}; 6366 } 6367 6368 // Lower an ac-implied-do in an ac-value-list. 6369 template <typename A> 6370 std::pair<ExtValue, bool> 6371 genArrayCtorInitializer(const Fortran::evaluate::ImpliedDo<A> &x, 6372 mlir::Type resTy, mlir::Value mem, 6373 mlir::Value buffPos, mlir::Value buffSize, 6374 Fortran::lower::StatementContext &) { 6375 mlir::Location loc = getLoc(); 6376 mlir::IndexType idxTy = builder.getIndexType(); 6377 mlir::Value lo = 6378 builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.lower()))); 6379 mlir::Value up = 6380 builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.upper()))); 6381 mlir::Value step = 6382 builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.stride()))); 6383 auto seqTy = resTy.template cast<fir::SequenceType>(); 6384 mlir::Type eleTy = fir::unwrapSequenceType(seqTy); 6385 auto loop = 6386 builder.create<fir::DoLoopOp>(loc, lo, up, step, /*unordered=*/false, 6387 /*finalCount=*/false, mem); 6388 // create a new binding for x.name(), to ac-do-variable, to the iteration 6389 // value. 6390 symMap.pushImpliedDoBinding(toStringRef(x.name()), loop.getInductionVar()); 6391 auto insPt = builder.saveInsertionPoint(); 6392 builder.setInsertionPointToStart(loop.getBody()); 6393 // Thread mem inside the loop via loop argument. 6394 mem = loop.getRegionIterArgs()[0]; 6395 6396 mlir::Type eleRefTy = builder.getRefType(eleTy); 6397 6398 // Any temps created in the loop body must be freed inside the loop body. 6399 stmtCtx.pushScope(); 6400 llvm::Optional<mlir::Value> charLen; 6401 for (const Fortran::evaluate::ArrayConstructorValue<A> &acv : x.values()) { 6402 auto [exv, copyNeeded] = std::visit( 6403 [&](const auto &v) { 6404 return genArrayCtorInitializer(v, resTy, mem, buffPos, buffSize, 6405 stmtCtx); 6406 }, 6407 acv.u); 6408 mlir::Value eleSz = computeElementSize(exv, eleTy, resTy); 6409 mem = copyNeeded ? copyNextArrayCtorSection(exv, buffPos, buffSize, mem, 6410 eleSz, eleTy, eleRefTy, resTy) 6411 : fir::getBase(exv); 6412 if (fir::isa_char(seqTy.getEleTy()) && !charLen) { 6413 charLen = builder.createTemporary(loc, builder.getI64Type()); 6414 mlir::Value castLen = 6415 builder.createConvert(loc, builder.getI64Type(), fir::getLen(exv)); 6416 builder.create<fir::StoreOp>(loc, castLen, *charLen); 6417 } 6418 } 6419 stmtCtx.finalize(/*popScope=*/true); 6420 6421 builder.create<fir::ResultOp>(loc, mem); 6422 builder.restoreInsertionPoint(insPt); 6423 mem = loop.getResult(0); 6424 symMap.popImpliedDoBinding(); 6425 llvm::SmallVector<mlir::Value> extents = { 6426 builder.create<fir::LoadOp>(loc, buffPos).getResult()}; 6427 6428 // Convert to extended value. 6429 if (fir::isa_char(seqTy.getEleTy())) { 6430 auto len = builder.create<fir::LoadOp>(loc, *charLen); 6431 return {fir::CharArrayBoxValue{mem, len, extents}, /*needCopy=*/false}; 6432 } 6433 return {fir::ArrayBoxValue{mem, extents}, /*needCopy=*/false}; 6434 } 6435 6436 // To simplify the handling and interaction between the various cases, array 6437 // constructors are always lowered to the incremental construction code 6438 // pattern, even if the extent of the array value is constant. After the 6439 // MemToReg pass and constant folding, the optimizer should be able to 6440 // determine that all the buffer overrun tests are false when the 6441 // incremental construction wasn't actually required. 6442 template <typename A> 6443 CC genarr(const Fortran::evaluate::ArrayConstructor<A> &x) { 6444 mlir::Location loc = getLoc(); 6445 auto evExpr = toEvExpr(x); 6446 mlir::Type resTy = translateSomeExprToFIRType(converter, evExpr); 6447 mlir::IndexType idxTy = builder.getIndexType(); 6448 auto seqTy = resTy.template cast<fir::SequenceType>(); 6449 mlir::Type eleTy = fir::unwrapSequenceType(resTy); 6450 mlir::Value buffSize = builder.createTemporary(loc, idxTy, ".buff.size"); 6451 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0); 6452 mlir::Value buffPos = builder.createTemporary(loc, idxTy, ".buff.pos"); 6453 builder.create<fir::StoreOp>(loc, zero, buffPos); 6454 // Allocate space for the array to be constructed. 6455 mlir::Value mem; 6456 if (fir::hasDynamicSize(resTy)) { 6457 if (fir::hasDynamicSize(eleTy)) { 6458 // The size of each element may depend on a general expression. Defer 6459 // creating the buffer until after the expression is evaluated. 6460 mem = builder.createNullConstant(loc, builder.getRefType(eleTy)); 6461 builder.create<fir::StoreOp>(loc, zero, buffSize); 6462 } else { 6463 mlir::Value initBuffSz = 6464 builder.createIntegerConstant(loc, idxTy, clInitialBufferSize); 6465 mem = builder.create<fir::AllocMemOp>( 6466 loc, eleTy, /*typeparams=*/llvm::None, initBuffSz); 6467 builder.create<fir::StoreOp>(loc, initBuffSz, buffSize); 6468 } 6469 } else { 6470 mem = builder.create<fir::AllocMemOp>(loc, resTy); 6471 int64_t buffSz = 1; 6472 for (auto extent : seqTy.getShape()) 6473 buffSz *= extent; 6474 mlir::Value initBuffSz = 6475 builder.createIntegerConstant(loc, idxTy, buffSz); 6476 builder.create<fir::StoreOp>(loc, initBuffSz, buffSize); 6477 } 6478 // Compute size of element 6479 mlir::Type eleRefTy = builder.getRefType(eleTy); 6480 6481 // Populate the buffer with the elements, growing as necessary. 6482 llvm::Optional<mlir::Value> charLen; 6483 for (const auto &expr : x) { 6484 auto [exv, copyNeeded] = std::visit( 6485 [&](const auto &e) { 6486 return genArrayCtorInitializer(e, resTy, mem, buffPos, buffSize, 6487 stmtCtx); 6488 }, 6489 expr.u); 6490 mlir::Value eleSz = computeElementSize(exv, eleTy, resTy); 6491 mem = copyNeeded ? copyNextArrayCtorSection(exv, buffPos, buffSize, mem, 6492 eleSz, eleTy, eleRefTy, resTy) 6493 : fir::getBase(exv); 6494 if (fir::isa_char(seqTy.getEleTy()) && !charLen) { 6495 charLen = builder.createTemporary(loc, builder.getI64Type()); 6496 mlir::Value castLen = 6497 builder.createConvert(loc, builder.getI64Type(), fir::getLen(exv)); 6498 builder.create<fir::StoreOp>(loc, castLen, *charLen); 6499 } 6500 } 6501 mem = builder.createConvert(loc, fir::HeapType::get(resTy), mem); 6502 llvm::SmallVector<mlir::Value> extents = { 6503 builder.create<fir::LoadOp>(loc, buffPos)}; 6504 6505 // Cleanup the temporary. 6506 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder(); 6507 stmtCtx.attachCleanup( 6508 [bldr, loc, mem]() { bldr->create<fir::FreeMemOp>(loc, mem); }); 6509 6510 // Return the continuation. 6511 if (fir::isa_char(seqTy.getEleTy())) { 6512 if (charLen.hasValue()) { 6513 auto len = builder.create<fir::LoadOp>(loc, charLen.getValue()); 6514 return genarr(fir::CharArrayBoxValue{mem, len, extents}); 6515 } 6516 return genarr(fir::CharArrayBoxValue{mem, zero, extents}); 6517 } 6518 return genarr(fir::ArrayBoxValue{mem, extents}); 6519 } 6520 6521 CC genarr(const Fortran::evaluate::ImpliedDoIndex &) { 6522 fir::emitFatalError(getLoc(), "implied do index cannot have rank > 0"); 6523 } 6524 CC genarr(const Fortran::evaluate::TypeParamInquiry &x) { 6525 TODO(getLoc(), "array expr type parameter inquiry"); 6526 return [](IterSpace iters) -> ExtValue { return mlir::Value{}; }; 6527 } 6528 CC genarr(const Fortran::evaluate::DescriptorInquiry &x) { 6529 TODO(getLoc(), "array expr descriptor inquiry"); 6530 return [](IterSpace iters) -> ExtValue { return mlir::Value{}; }; 6531 } 6532 CC genarr(const Fortran::evaluate::StructureConstructor &x) { 6533 TODO(getLoc(), "structure constructor"); 6534 return [](IterSpace iters) -> ExtValue { return mlir::Value{}; }; 6535 } 6536 6537 //===--------------------------------------------------------------------===// 6538 // LOCICAL operators (.NOT., .AND., .EQV., etc.) 6539 //===--------------------------------------------------------------------===// 6540 6541 template <int KIND> 6542 CC genarr(const Fortran::evaluate::Not<KIND> &x) { 6543 mlir::Location loc = getLoc(); 6544 mlir::IntegerType i1Ty = builder.getI1Type(); 6545 auto lambda = genarr(x.left()); 6546 mlir::Value truth = builder.createBool(loc, true); 6547 return [=](IterSpace iters) -> ExtValue { 6548 mlir::Value logical = fir::getBase(lambda(iters)); 6549 mlir::Value val = builder.createConvert(loc, i1Ty, logical); 6550 return builder.create<mlir::arith::XOrIOp>(loc, val, truth); 6551 }; 6552 } 6553 template <typename OP, typename A> 6554 CC createBinaryBoolOp(const A &x) { 6555 mlir::Location loc = getLoc(); 6556 mlir::IntegerType i1Ty = builder.getI1Type(); 6557 auto lf = genarr(x.left()); 6558 auto rf = genarr(x.right()); 6559 return [=](IterSpace iters) -> ExtValue { 6560 mlir::Value left = fir::getBase(lf(iters)); 6561 mlir::Value right = fir::getBase(rf(iters)); 6562 mlir::Value lhs = builder.createConvert(loc, i1Ty, left); 6563 mlir::Value rhs = builder.createConvert(loc, i1Ty, right); 6564 return builder.create<OP>(loc, lhs, rhs); 6565 }; 6566 } 6567 template <typename OP, typename A> 6568 CC createCompareBoolOp(mlir::arith::CmpIPredicate pred, const A &x) { 6569 mlir::Location loc = getLoc(); 6570 mlir::IntegerType i1Ty = builder.getI1Type(); 6571 auto lf = genarr(x.left()); 6572 auto rf = genarr(x.right()); 6573 return [=](IterSpace iters) -> ExtValue { 6574 mlir::Value left = fir::getBase(lf(iters)); 6575 mlir::Value right = fir::getBase(rf(iters)); 6576 mlir::Value lhs = builder.createConvert(loc, i1Ty, left); 6577 mlir::Value rhs = builder.createConvert(loc, i1Ty, right); 6578 return builder.create<OP>(loc, pred, lhs, rhs); 6579 }; 6580 } 6581 template <int KIND> 6582 CC genarr(const Fortran::evaluate::LogicalOperation<KIND> &x) { 6583 switch (x.logicalOperator) { 6584 case Fortran::evaluate::LogicalOperator::And: 6585 return createBinaryBoolOp<mlir::arith::AndIOp>(x); 6586 case Fortran::evaluate::LogicalOperator::Or: 6587 return createBinaryBoolOp<mlir::arith::OrIOp>(x); 6588 case Fortran::evaluate::LogicalOperator::Eqv: 6589 return createCompareBoolOp<mlir::arith::CmpIOp>( 6590 mlir::arith::CmpIPredicate::eq, x); 6591 case Fortran::evaluate::LogicalOperator::Neqv: 6592 return createCompareBoolOp<mlir::arith::CmpIOp>( 6593 mlir::arith::CmpIPredicate::ne, x); 6594 case Fortran::evaluate::LogicalOperator::Not: 6595 llvm_unreachable(".NOT. handled elsewhere"); 6596 } 6597 llvm_unreachable("unhandled case"); 6598 } 6599 6600 //===--------------------------------------------------------------------===// 6601 // Relational operators (<, <=, ==, etc.) 6602 //===--------------------------------------------------------------------===// 6603 6604 template <typename OP, typename PRED, typename A> 6605 CC createCompareOp(PRED pred, const A &x) { 6606 mlir::Location loc = getLoc(); 6607 auto lf = genarr(x.left()); 6608 auto rf = genarr(x.right()); 6609 return [=](IterSpace iters) -> ExtValue { 6610 mlir::Value lhs = fir::getBase(lf(iters)); 6611 mlir::Value rhs = fir::getBase(rf(iters)); 6612 return builder.create<OP>(loc, pred, lhs, rhs); 6613 }; 6614 } 6615 template <typename A> 6616 CC createCompareCharOp(mlir::arith::CmpIPredicate pred, const A &x) { 6617 mlir::Location loc = getLoc(); 6618 auto lf = genarr(x.left()); 6619 auto rf = genarr(x.right()); 6620 return [=](IterSpace iters) -> ExtValue { 6621 auto lhs = lf(iters); 6622 auto rhs = rf(iters); 6623 return fir::runtime::genCharCompare(builder, loc, pred, lhs, rhs); 6624 }; 6625 } 6626 template <int KIND> 6627 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 6628 Fortran::common::TypeCategory::Integer, KIND>> &x) { 6629 return createCompareOp<mlir::arith::CmpIOp>(translateRelational(x.opr), x); 6630 } 6631 template <int KIND> 6632 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 6633 Fortran::common::TypeCategory::Character, KIND>> &x) { 6634 return createCompareCharOp(translateRelational(x.opr), x); 6635 } 6636 template <int KIND> 6637 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 6638 Fortran::common::TypeCategory::Real, KIND>> &x) { 6639 return createCompareOp<mlir::arith::CmpFOp>(translateFloatRelational(x.opr), 6640 x); 6641 } 6642 template <int KIND> 6643 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type< 6644 Fortran::common::TypeCategory::Complex, KIND>> &x) { 6645 return createCompareOp<fir::CmpcOp>(translateFloatRelational(x.opr), x); 6646 } 6647 CC genarr( 6648 const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &r) { 6649 return std::visit([&](const auto &x) { return genarr(x); }, r.u); 6650 } 6651 6652 template <typename A> 6653 CC genarr(const Fortran::evaluate::Designator<A> &des) { 6654 ComponentPath components(des.Rank() > 0); 6655 return std::visit([&](const auto &x) { return genarr(x, components); }, 6656 des.u); 6657 } 6658 6659 /// Is the path component rank > 0? 6660 static bool ranked(const PathComponent &x) { 6661 return std::visit(Fortran::common::visitors{ 6662 [](const ImplicitSubscripts &) { return false; }, 6663 [](const auto *v) { return v->Rank() > 0; }}, 6664 x); 6665 } 6666 6667 void extendComponent(Fortran::lower::ComponentPath &component, 6668 mlir::Type coorTy, mlir::ValueRange vals) { 6669 auto *bldr = &converter.getFirOpBuilder(); 6670 llvm::SmallVector<mlir::Value> offsets(vals.begin(), vals.end()); 6671 auto currentFunc = component.getExtendCoorRef(); 6672 auto loc = getLoc(); 6673 auto newCoorRef = [bldr, coorTy, offsets, currentFunc, 6674 loc](mlir::Value val) -> mlir::Value { 6675 return bldr->create<fir::CoordinateOp>(loc, bldr->getRefType(coorTy), 6676 currentFunc(val), offsets); 6677 }; 6678 component.extendCoorRef = newCoorRef; 6679 } 6680 6681 //===-------------------------------------------------------------------===// 6682 // Array data references in an explicit iteration space. 6683 // 6684 // Use the base array that was loaded before the loop nest. 6685 //===-------------------------------------------------------------------===// 6686 6687 /// Lower the path (`revPath`, in reverse) to be appended to an array_fetch or 6688 /// array_update op. \p ty is the initial type of the array 6689 /// (reference). Returns the type of the element after application of the 6690 /// path in \p components. 6691 /// 6692 /// TODO: This needs to deal with array's with initial bounds other than 1. 6693 /// TODO: Thread type parameters correctly. 6694 mlir::Type lowerPath(const ExtValue &arrayExv, ComponentPath &components) { 6695 mlir::Location loc = getLoc(); 6696 mlir::Type ty = fir::getBase(arrayExv).getType(); 6697 auto &revPath = components.reversePath; 6698 ty = fir::unwrapPassByRefType(ty); 6699 bool prefix = true; 6700 bool deref = false; 6701 auto addComponentList = [&](mlir::Type ty, mlir::ValueRange vals) { 6702 if (deref) { 6703 extendComponent(components, ty, vals); 6704 } else if (prefix) { 6705 for (auto v : vals) 6706 components.prefixComponents.push_back(v); 6707 } else { 6708 for (auto v : vals) 6709 components.suffixComponents.push_back(v); 6710 } 6711 }; 6712 mlir::IndexType idxTy = builder.getIndexType(); 6713 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1); 6714 bool atBase = true; 6715 auto saveSemant = semant; 6716 if (isProjectedCopyInCopyOut()) 6717 semant = ConstituentSemantics::RefTransparent; 6718 unsigned index = 0; 6719 for (const auto &v : llvm::reverse(revPath)) { 6720 std::visit( 6721 Fortran::common::visitors{ 6722 [&](const ImplicitSubscripts &) { 6723 prefix = false; 6724 ty = fir::unwrapSequenceType(ty); 6725 }, 6726 [&](const Fortran::evaluate::ComplexPart *x) { 6727 assert(!prefix && "complex part must be at end"); 6728 mlir::Value offset = builder.createIntegerConstant( 6729 loc, builder.getI32Type(), 6730 x->part() == Fortran::evaluate::ComplexPart::Part::RE ? 0 6731 : 1); 6732 components.suffixComponents.push_back(offset); 6733 ty = fir::applyPathToType(ty, mlir::ValueRange{offset}); 6734 }, 6735 [&](const Fortran::evaluate::ArrayRef *x) { 6736 if (Fortran::lower::isRankedArrayAccess(*x)) { 6737 genSliceIndices(components, arrayExv, *x, atBase); 6738 ty = fir::unwrapSeqOrBoxedSeqType(ty); 6739 } else { 6740 // Array access where the expressions are scalar and cannot 6741 // depend upon the implied iteration space. 6742 unsigned ssIndex = 0u; 6743 llvm::SmallVector<mlir::Value> componentsToAdd; 6744 for (const auto &ss : x->subscript()) { 6745 std::visit( 6746 Fortran::common::visitors{ 6747 [&](const Fortran::evaluate:: 6748 IndirectSubscriptIntegerExpr &ie) { 6749 const auto &e = ie.value(); 6750 if (isArray(e)) 6751 fir::emitFatalError( 6752 loc, 6753 "multiple components along single path " 6754 "generating array subexpressions"); 6755 // Lower scalar index expression, append it to 6756 // subs. 6757 mlir::Value subscriptVal = 6758 fir::getBase(asScalarArray(e)); 6759 // arrayExv is the base array. It needs to reflect 6760 // the current array component instead. 6761 // FIXME: must use lower bound of this component, 6762 // not just the constant 1. 6763 mlir::Value lb = 6764 atBase ? fir::factory::readLowerBound( 6765 builder, loc, arrayExv, ssIndex, 6766 one) 6767 : one; 6768 mlir::Value val = builder.createConvert( 6769 loc, idxTy, subscriptVal); 6770 mlir::Value ivAdj = 6771 builder.create<mlir::arith::SubIOp>( 6772 loc, idxTy, val, lb); 6773 componentsToAdd.push_back( 6774 builder.createConvert(loc, idxTy, ivAdj)); 6775 }, 6776 [&](const auto &) { 6777 fir::emitFatalError( 6778 loc, "multiple components along single path " 6779 "generating array subexpressions"); 6780 }}, 6781 ss.u); 6782 ssIndex++; 6783 } 6784 ty = fir::unwrapSeqOrBoxedSeqType(ty); 6785 addComponentList(ty, componentsToAdd); 6786 } 6787 }, 6788 [&](const Fortran::evaluate::Component *x) { 6789 auto fieldTy = fir::FieldType::get(builder.getContext()); 6790 llvm::StringRef name = toStringRef(getLastSym(*x).name()); 6791 if (auto recTy = ty.dyn_cast<fir::RecordType>()) { 6792 ty = recTy.getType(name); 6793 auto fld = builder.create<fir::FieldIndexOp>( 6794 loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv)); 6795 addComponentList(ty, {fld}); 6796 if (index != revPath.size() - 1 || !isPointerAssignment()) { 6797 // Need an intermediate dereference if the boxed value 6798 // appears in the middle of the component path or if it is 6799 // on the right and this is not a pointer assignment. 6800 if (auto boxTy = ty.dyn_cast<fir::BoxType>()) { 6801 auto currentFunc = components.getExtendCoorRef(); 6802 auto loc = getLoc(); 6803 auto *bldr = &converter.getFirOpBuilder(); 6804 auto newCoorRef = [=](mlir::Value val) -> mlir::Value { 6805 return bldr->create<fir::LoadOp>(loc, currentFunc(val)); 6806 }; 6807 components.extendCoorRef = newCoorRef; 6808 deref = true; 6809 } 6810 } 6811 } else if (auto boxTy = ty.dyn_cast<fir::BoxType>()) { 6812 ty = fir::unwrapRefType(boxTy.getEleTy()); 6813 auto recTy = ty.cast<fir::RecordType>(); 6814 ty = recTy.getType(name); 6815 auto fld = builder.create<fir::FieldIndexOp>( 6816 loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv)); 6817 extendComponent(components, ty, {fld}); 6818 } else { 6819 TODO(loc, "other component type"); 6820 } 6821 }}, 6822 v); 6823 atBase = false; 6824 ++index; 6825 } 6826 semant = saveSemant; 6827 ty = fir::unwrapSequenceType(ty); 6828 components.applied = true; 6829 return ty; 6830 } 6831 6832 llvm::SmallVector<mlir::Value> genSubstringBounds(ComponentPath &components) { 6833 llvm::SmallVector<mlir::Value> result; 6834 if (components.substring) 6835 populateBounds(result, components.substring); 6836 return result; 6837 } 6838 6839 CC applyPathToArrayLoad(fir::ArrayLoadOp load, ComponentPath &components) { 6840 mlir::Location loc = getLoc(); 6841 auto revPath = components.reversePath; 6842 fir::ExtendedValue arrayExv = 6843 arrayLoadExtValue(builder, loc, load, {}, load); 6844 mlir::Type eleTy = lowerPath(arrayExv, components); 6845 auto currentPC = components.pc; 6846 auto pc = [=, prefix = components.prefixComponents, 6847 suffix = components.suffixComponents](IterSpace iters) { 6848 // Add path prefix and suffix. 6849 return IterationSpace(currentPC(iters), prefix, suffix); 6850 }; 6851 components.resetPC(); 6852 llvm::SmallVector<mlir::Value> substringBounds = 6853 genSubstringBounds(components); 6854 if (isProjectedCopyInCopyOut()) { 6855 destination = load; 6856 auto lambda = [=, esp = this->explicitSpace](IterSpace iters) mutable { 6857 mlir::Value innerArg = esp->findArgumentOfLoad(load); 6858 if (isAdjustedArrayElementType(eleTy)) { 6859 mlir::Type eleRefTy = builder.getRefType(eleTy); 6860 auto arrayOp = builder.create<fir::ArrayAccessOp>( 6861 loc, eleRefTy, innerArg, iters.iterVec(), load.getTypeparams()); 6862 if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 6863 mlir::Value dstLen = fir::factory::genLenOfCharacter( 6864 builder, loc, load, iters.iterVec(), substringBounds); 6865 fir::ArrayAmendOp amend = createCharArrayAmend( 6866 loc, builder, arrayOp, dstLen, iters.elementExv(), innerArg, 6867 substringBounds); 6868 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), amend, 6869 dstLen); 6870 } 6871 if (fir::isa_derived(eleTy)) { 6872 fir::ArrayAmendOp amend = 6873 createDerivedArrayAmend(loc, load, builder, arrayOp, 6874 iters.elementExv(), eleTy, innerArg); 6875 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), 6876 amend); 6877 } 6878 assert(eleTy.isa<fir::SequenceType>()); 6879 TODO(loc, "array (as element) assignment"); 6880 } 6881 if (components.hasExtendCoorRef()) { 6882 auto eleBoxTy = 6883 fir::applyPathToType(innerArg.getType(), iters.iterVec()); 6884 assert(eleBoxTy && eleBoxTy.isa<fir::BoxType>()); 6885 auto arrayOp = builder.create<fir::ArrayAccessOp>( 6886 loc, builder.getRefType(eleBoxTy), innerArg, iters.iterVec(), 6887 fir::factory::getTypeParams(loc, builder, load)); 6888 mlir::Value addr = components.getExtendCoorRef()(arrayOp); 6889 components.resetExtendCoorRef(); 6890 // When the lhs is a boxed value and the context is not a pointer 6891 // assignment, then insert the dereference of the box before any 6892 // conversion and store. 6893 if (!isPointerAssignment()) { 6894 if (auto boxTy = eleTy.dyn_cast<fir::BoxType>()) { 6895 eleTy = boxTy.getEleTy(); 6896 if (!(eleTy.isa<fir::PointerType>() || 6897 eleTy.isa<fir::HeapType>())) 6898 eleTy = builder.getRefType(eleTy); 6899 addr = builder.create<fir::BoxAddrOp>(loc, eleTy, addr); 6900 eleTy = fir::unwrapRefType(eleTy); 6901 } 6902 } 6903 auto ele = convertElementForUpdate(loc, eleTy, iters.getElement()); 6904 builder.create<fir::StoreOp>(loc, ele, addr); 6905 auto amend = builder.create<fir::ArrayAmendOp>( 6906 loc, innerArg.getType(), innerArg, arrayOp); 6907 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), amend); 6908 } 6909 auto ele = convertElementForUpdate(loc, eleTy, iters.getElement()); 6910 auto update = builder.create<fir::ArrayUpdateOp>( 6911 loc, innerArg.getType(), innerArg, ele, iters.iterVec(), 6912 fir::factory::getTypeParams(loc, builder, load)); 6913 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), update); 6914 }; 6915 return [=](IterSpace iters) mutable { return lambda(pc(iters)); }; 6916 } 6917 if (isCustomCopyInCopyOut()) { 6918 // Create an array_modify to get the LHS element address and indicate 6919 // the assignment, and create the call to the user defined assignment. 6920 destination = load; 6921 auto lambda = [=](IterSpace iters) mutable { 6922 mlir::Value innerArg = explicitSpace->findArgumentOfLoad(load); 6923 mlir::Type refEleTy = 6924 fir::isa_ref_type(eleTy) ? eleTy : builder.getRefType(eleTy); 6925 auto arrModify = builder.create<fir::ArrayModifyOp>( 6926 loc, mlir::TypeRange{refEleTy, innerArg.getType()}, innerArg, 6927 iters.iterVec(), load.getTypeparams()); 6928 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), 6929 arrModify.getResult(1)); 6930 }; 6931 return [=](IterSpace iters) mutable { return lambda(pc(iters)); }; 6932 } 6933 auto lambda = [=, semant = this->semant](IterSpace iters) mutable { 6934 if (semant == ConstituentSemantics::RefOpaque || 6935 isAdjustedArrayElementType(eleTy)) { 6936 mlir::Type resTy = builder.getRefType(eleTy); 6937 // Use array element reference semantics. 6938 auto access = builder.create<fir::ArrayAccessOp>( 6939 loc, resTy, load, iters.iterVec(), load.getTypeparams()); 6940 mlir::Value newBase = access; 6941 if (fir::isa_char(eleTy)) { 6942 mlir::Value dstLen = fir::factory::genLenOfCharacter( 6943 builder, loc, load, iters.iterVec(), substringBounds); 6944 if (!substringBounds.empty()) { 6945 fir::CharBoxValue charDst{access, dstLen}; 6946 fir::factory::CharacterExprHelper helper{builder, loc}; 6947 charDst = helper.createSubstring(charDst, substringBounds); 6948 newBase = charDst.getAddr(); 6949 } 6950 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), newBase, 6951 dstLen); 6952 } 6953 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), newBase); 6954 } 6955 if (components.hasExtendCoorRef()) { 6956 auto eleBoxTy = fir::applyPathToType(load.getType(), iters.iterVec()); 6957 assert(eleBoxTy && eleBoxTy.isa<fir::BoxType>()); 6958 auto access = builder.create<fir::ArrayAccessOp>( 6959 loc, builder.getRefType(eleBoxTy), load, iters.iterVec(), 6960 fir::factory::getTypeParams(loc, builder, load)); 6961 mlir::Value addr = components.getExtendCoorRef()(access); 6962 components.resetExtendCoorRef(); 6963 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), addr); 6964 } 6965 if (isPointerAssignment()) { 6966 auto eleTy = fir::applyPathToType(load.getType(), iters.iterVec()); 6967 if (!eleTy.isa<fir::BoxType>()) { 6968 // Rhs is a regular expression that will need to be boxed before 6969 // assigning to the boxed variable. 6970 auto typeParams = fir::factory::getTypeParams(loc, builder, load); 6971 auto access = builder.create<fir::ArrayAccessOp>( 6972 loc, builder.getRefType(eleTy), load, iters.iterVec(), 6973 typeParams); 6974 auto addr = components.getExtendCoorRef()(access); 6975 components.resetExtendCoorRef(); 6976 auto ptrEleTy = fir::PointerType::get(eleTy); 6977 auto ptrAddr = builder.createConvert(loc, ptrEleTy, addr); 6978 auto boxTy = fir::BoxType::get(ptrEleTy); 6979 // FIXME: The typeparams to the load may be different than those of 6980 // the subobject. 6981 if (components.hasExtendCoorRef()) 6982 TODO(loc, "need to adjust typeparameter(s) to reflect the final " 6983 "component"); 6984 mlir::Value embox = 6985 builder.create<fir::EmboxOp>(loc, boxTy, ptrAddr, 6986 /*shape=*/mlir::Value{}, 6987 /*slice=*/mlir::Value{}, typeParams); 6988 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), embox); 6989 } 6990 } 6991 auto fetch = builder.create<fir::ArrayFetchOp>( 6992 loc, eleTy, load, iters.iterVec(), load.getTypeparams()); 6993 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), fetch); 6994 }; 6995 return [=](IterSpace iters) mutable { return lambda(pc(iters)); }; 6996 } 6997 6998 template <typename A> 6999 CC genImplicitArrayAccess(const A &x, ComponentPath &components) { 7000 components.reversePath.push_back(ImplicitSubscripts{}); 7001 ExtValue exv = asScalarRef(x); 7002 lowerPath(exv, components); 7003 auto lambda = genarr(exv, components); 7004 return [=](IterSpace iters) { return lambda(components.pc(iters)); }; 7005 } 7006 CC genImplicitArrayAccess(const Fortran::evaluate::NamedEntity &x, 7007 ComponentPath &components) { 7008 if (x.IsSymbol()) 7009 return genImplicitArrayAccess(getFirstSym(x), components); 7010 return genImplicitArrayAccess(x.GetComponent(), components); 7011 } 7012 7013 template <typename A> 7014 CC genAsScalar(const A &x) { 7015 mlir::Location loc = getLoc(); 7016 if (isProjectedCopyInCopyOut()) { 7017 return [=, &x, builder = &converter.getFirOpBuilder()]( 7018 IterSpace iters) -> ExtValue { 7019 ExtValue exv = asScalarRef(x); 7020 mlir::Value val = fir::getBase(exv); 7021 mlir::Type eleTy = fir::unwrapRefType(val.getType()); 7022 if (isAdjustedArrayElementType(eleTy)) { 7023 if (fir::isa_char(eleTy)) { 7024 fir::factory::CharacterExprHelper{*builder, loc}.createAssign( 7025 exv, iters.elementExv()); 7026 } else if (fir::isa_derived(eleTy)) { 7027 TODO(loc, "assignment of derived type"); 7028 } else { 7029 fir::emitFatalError(loc, "array type not expected in scalar"); 7030 } 7031 } else { 7032 builder->create<fir::StoreOp>(loc, iters.getElement(), val); 7033 } 7034 return exv; 7035 }; 7036 } 7037 return [=, &x](IterSpace) { return asScalar(x); }; 7038 } 7039 7040 bool tailIsPointerInPointerAssignment(const Fortran::semantics::Symbol &x, 7041 ComponentPath &components) { 7042 return isPointerAssignment() && Fortran::semantics::IsPointer(x) && 7043 !components.hasComponents(); 7044 } 7045 bool tailIsPointerInPointerAssignment(const Fortran::evaluate::Component &x, 7046 ComponentPath &components) { 7047 return tailIsPointerInPointerAssignment(getLastSym(x), components); 7048 } 7049 7050 CC genarr(const Fortran::semantics::Symbol &x, ComponentPath &components) { 7051 if (explicitSpaceIsActive()) { 7052 if (x.Rank() > 0 && !tailIsPointerInPointerAssignment(x, components)) 7053 components.reversePath.push_back(ImplicitSubscripts{}); 7054 if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x)) 7055 return applyPathToArrayLoad(load, components); 7056 } else { 7057 return genImplicitArrayAccess(x, components); 7058 } 7059 if (pathIsEmpty(components)) 7060 return genAsScalar(x); 7061 mlir::Location loc = getLoc(); 7062 return [=](IterSpace) -> ExtValue { 7063 fir::emitFatalError(loc, "reached symbol with path"); 7064 }; 7065 } 7066 7067 /// Lower a component path with or without rank. 7068 /// Example: <code>array%baz%qux%waldo</code> 7069 CC genarr(const Fortran::evaluate::Component &x, ComponentPath &components) { 7070 if (explicitSpaceIsActive()) { 7071 if (x.base().Rank() == 0 && x.Rank() > 0 && 7072 !tailIsPointerInPointerAssignment(x, components)) 7073 components.reversePath.push_back(ImplicitSubscripts{}); 7074 if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x)) 7075 return applyPathToArrayLoad(load, components); 7076 } else { 7077 if (x.base().Rank() == 0) 7078 return genImplicitArrayAccess(x, components); 7079 } 7080 bool atEnd = pathIsEmpty(components); 7081 if (!getLastSym(x).test(Fortran::semantics::Symbol::Flag::ParentComp)) 7082 // Skip parent components; their components are placed directly in the 7083 // object. 7084 components.reversePath.push_back(&x); 7085 auto result = genarr(x.base(), components); 7086 if (components.applied) 7087 return result; 7088 if (atEnd) 7089 return genAsScalar(x); 7090 mlir::Location loc = getLoc(); 7091 return [=](IterSpace) -> ExtValue { 7092 fir::emitFatalError(loc, "reached component with path"); 7093 }; 7094 } 7095 7096 /// Array reference with subscripts. If this has rank > 0, this is a form 7097 /// of an array section (slice). 7098 /// 7099 /// There are two "slicing" primitives that may be applied on a dimension by 7100 /// dimension basis: (1) triple notation and (2) vector addressing. Since 7101 /// dimensions can be selectively sliced, some dimensions may contain 7102 /// regular scalar expressions and those dimensions do not participate in 7103 /// the array expression evaluation. 7104 CC genarr(const Fortran::evaluate::ArrayRef &x, ComponentPath &components) { 7105 if (explicitSpaceIsActive()) { 7106 if (Fortran::lower::isRankedArrayAccess(x)) 7107 components.reversePath.push_back(ImplicitSubscripts{}); 7108 if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x)) { 7109 components.reversePath.push_back(&x); 7110 return applyPathToArrayLoad(load, components); 7111 } 7112 } else { 7113 if (Fortran::lower::isRankedArrayAccess(x)) { 7114 components.reversePath.push_back(&x); 7115 return genImplicitArrayAccess(x.base(), components); 7116 } 7117 } 7118 bool atEnd = pathIsEmpty(components); 7119 components.reversePath.push_back(&x); 7120 auto result = genarr(x.base(), components); 7121 if (components.applied) 7122 return result; 7123 mlir::Location loc = getLoc(); 7124 if (atEnd) { 7125 if (x.Rank() == 0) 7126 return genAsScalar(x); 7127 fir::emitFatalError(loc, "expected scalar"); 7128 } 7129 return [=](IterSpace) -> ExtValue { 7130 fir::emitFatalError(loc, "reached arrayref with path"); 7131 }; 7132 } 7133 7134 CC genarr(const Fortran::evaluate::CoarrayRef &x, ComponentPath &components) { 7135 TODO(getLoc(), "coarray reference"); 7136 } 7137 7138 CC genarr(const Fortran::evaluate::NamedEntity &x, 7139 ComponentPath &components) { 7140 return x.IsSymbol() ? genarr(getFirstSym(x), components) 7141 : genarr(x.GetComponent(), components); 7142 } 7143 7144 CC genarr(const Fortran::evaluate::DataRef &x, ComponentPath &components) { 7145 return std::visit([&](const auto &v) { return genarr(v, components); }, 7146 x.u); 7147 } 7148 7149 bool pathIsEmpty(const ComponentPath &components) { 7150 return components.reversePath.empty(); 7151 } 7152 7153 explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter, 7154 Fortran::lower::StatementContext &stmtCtx, 7155 Fortran::lower::SymMap &symMap) 7156 : converter{converter}, builder{converter.getFirOpBuilder()}, 7157 stmtCtx{stmtCtx}, symMap{symMap} {} 7158 7159 explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter, 7160 Fortran::lower::StatementContext &stmtCtx, 7161 Fortran::lower::SymMap &symMap, 7162 ConstituentSemantics sem) 7163 : converter{converter}, builder{converter.getFirOpBuilder()}, 7164 stmtCtx{stmtCtx}, symMap{symMap}, semant{sem} {} 7165 7166 explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter, 7167 Fortran::lower::StatementContext &stmtCtx, 7168 Fortran::lower::SymMap &symMap, 7169 ConstituentSemantics sem, 7170 Fortran::lower::ExplicitIterSpace *expSpace, 7171 Fortran::lower::ImplicitIterSpace *impSpace) 7172 : converter{converter}, builder{converter.getFirOpBuilder()}, 7173 stmtCtx{stmtCtx}, symMap{symMap}, 7174 explicitSpace(expSpace->isActive() ? expSpace : nullptr), 7175 implicitSpace(impSpace->empty() ? nullptr : impSpace), semant{sem} { 7176 // Generate any mask expressions, as necessary. This is the compute step 7177 // that creates the effective masks. See 10.2.3.2 in particular. 7178 genMasks(); 7179 } 7180 7181 mlir::Location getLoc() { return converter.getCurrentLocation(); } 7182 7183 /// Array appears in a lhs context such that it is assigned after the rhs is 7184 /// fully evaluated. 7185 inline bool isCopyInCopyOut() { 7186 return semant == ConstituentSemantics::CopyInCopyOut; 7187 } 7188 7189 /// Array appears in a lhs (or temp) context such that a projected, 7190 /// discontiguous subspace of the array is assigned after the rhs is fully 7191 /// evaluated. That is, the rhs array value is merged into a section of the 7192 /// lhs array. 7193 inline bool isProjectedCopyInCopyOut() { 7194 return semant == ConstituentSemantics::ProjectedCopyInCopyOut; 7195 } 7196 7197 // ???: Do we still need this? 7198 inline bool isCustomCopyInCopyOut() { 7199 return semant == ConstituentSemantics::CustomCopyInCopyOut; 7200 } 7201 7202 /// Are we lowering in a left-hand side context? 7203 inline bool isLeftHandSide() { 7204 return isCopyInCopyOut() || isProjectedCopyInCopyOut() || 7205 isCustomCopyInCopyOut(); 7206 } 7207 7208 /// Array appears in a context where it must be boxed. 7209 inline bool isBoxValue() { return semant == ConstituentSemantics::BoxValue; } 7210 7211 /// Array appears in a context where differences in the memory reference can 7212 /// be observable in the computational results. For example, an array 7213 /// element is passed to an impure procedure. 7214 inline bool isReferentiallyOpaque() { 7215 return semant == ConstituentSemantics::RefOpaque; 7216 } 7217 7218 /// Array appears in a context where it is passed as a VALUE argument. 7219 inline bool isValueAttribute() { 7220 return semant == ConstituentSemantics::ByValueArg; 7221 } 7222 7223 /// Can the loops over the expression be unordered? 7224 inline bool isUnordered() const { return unordered; } 7225 7226 void setUnordered(bool b) { unordered = b; } 7227 7228 inline bool isPointerAssignment() const { return lbounds.hasValue(); } 7229 7230 inline bool isBoundsSpec() const { 7231 return isPointerAssignment() && !ubounds.hasValue(); 7232 } 7233 7234 inline bool isBoundsRemap() const { 7235 return isPointerAssignment() && ubounds.hasValue(); 7236 } 7237 7238 void setPointerAssignmentBounds( 7239 const llvm::SmallVector<mlir::Value> &lbs, 7240 llvm::Optional<llvm::SmallVector<mlir::Value>> ubs) { 7241 lbounds = lbs; 7242 ubounds = ubs; 7243 } 7244 7245 Fortran::lower::AbstractConverter &converter; 7246 fir::FirOpBuilder &builder; 7247 Fortran::lower::StatementContext &stmtCtx; 7248 bool elementCtx = false; 7249 Fortran::lower::SymMap &symMap; 7250 /// The continuation to generate code to update the destination. 7251 llvm::Optional<CC> ccStoreToDest; 7252 llvm::Optional<std::function<void(llvm::ArrayRef<mlir::Value>)>> ccPrelude; 7253 llvm::Optional<std::function<fir::ArrayLoadOp(llvm::ArrayRef<mlir::Value>)>> 7254 ccLoadDest; 7255 /// The destination is the loaded array into which the results will be 7256 /// merged. 7257 fir::ArrayLoadOp destination; 7258 /// The shape of the destination. 7259 llvm::SmallVector<mlir::Value> destShape; 7260 /// List of arrays in the expression that have been loaded. 7261 llvm::SmallVector<ArrayOperand> arrayOperands; 7262 /// If there is a user-defined iteration space, explicitShape will hold the 7263 /// information from the front end. 7264 Fortran::lower::ExplicitIterSpace *explicitSpace = nullptr; 7265 Fortran::lower::ImplicitIterSpace *implicitSpace = nullptr; 7266 ConstituentSemantics semant = ConstituentSemantics::RefTransparent; 7267 /// `lbounds`, `ubounds` are used in POINTER value assignments, which may only 7268 /// occur in an explicit iteration space. 7269 llvm::Optional<llvm::SmallVector<mlir::Value>> lbounds; 7270 llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds; 7271 // Can the array expression be evaluated in any order? 7272 // Will be set to false if any of the expression parts prevent this. 7273 bool unordered = true; 7274 }; 7275 } // namespace 7276 7277 fir::ExtendedValue Fortran::lower::createSomeExtendedExpression( 7278 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 7279 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap, 7280 Fortran::lower::StatementContext &stmtCtx) { 7281 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n'); 7282 return ScalarExprLowering{loc, converter, symMap, stmtCtx}.genval(expr); 7283 } 7284 7285 fir::GlobalOp Fortran::lower::createDenseGlobal( 7286 mlir::Location loc, mlir::Type symTy, llvm::StringRef globalName, 7287 mlir::StringAttr linkage, bool isConst, 7288 const Fortran::lower::SomeExpr &expr, 7289 Fortran::lower::AbstractConverter &converter) { 7290 7291 Fortran::lower::StatementContext stmtCtx(/*prohibited=*/true); 7292 Fortran::lower::SymMap emptyMap; 7293 InitializerData initData(/*genRawVals=*/true); 7294 ScalarExprLowering sel(loc, converter, emptyMap, stmtCtx, 7295 /*initializer=*/&initData); 7296 sel.genval(expr); 7297 7298 size_t sz = initData.rawVals.size(); 7299 llvm::ArrayRef<mlir::Attribute> ar = {initData.rawVals.data(), sz}; 7300 7301 mlir::RankedTensorType tensorTy; 7302 auto &builder = converter.getFirOpBuilder(); 7303 mlir::Type iTy = initData.rawType; 7304 if (!iTy) 7305 return 0; // array extent is probably 0 in this case, so just return 0. 7306 tensorTy = mlir::RankedTensorType::get(sz, iTy); 7307 auto init = mlir::DenseElementsAttr::get(tensorTy, ar); 7308 return builder.createGlobal(loc, symTy, globalName, linkage, init, isConst); 7309 } 7310 7311 fir::ExtendedValue Fortran::lower::createSomeInitializerExpression( 7312 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 7313 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap, 7314 Fortran::lower::StatementContext &stmtCtx) { 7315 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n'); 7316 InitializerData initData; // needed for initializations 7317 return ScalarExprLowering{loc, converter, symMap, stmtCtx, 7318 /*initializer=*/&initData} 7319 .genval(expr); 7320 } 7321 7322 fir::ExtendedValue Fortran::lower::createSomeExtendedAddress( 7323 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 7324 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap, 7325 Fortran::lower::StatementContext &stmtCtx) { 7326 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n'); 7327 return ScalarExprLowering(loc, converter, symMap, stmtCtx).gen(expr); 7328 } 7329 7330 fir::ExtendedValue Fortran::lower::createInitializerAddress( 7331 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 7332 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap, 7333 Fortran::lower::StatementContext &stmtCtx) { 7334 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n'); 7335 InitializerData init; 7336 return ScalarExprLowering(loc, converter, symMap, stmtCtx, &init).gen(expr); 7337 } 7338 7339 void Fortran::lower::createSomeArrayAssignment( 7340 Fortran::lower::AbstractConverter &converter, 7341 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 7342 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 7343 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "onto array: ") << '\n'; 7344 rhs.AsFortran(llvm::dbgs() << "assign expression: ") << '\n';); 7345 ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs); 7346 } 7347 7348 void Fortran::lower::createSomeArrayAssignment( 7349 Fortran::lower::AbstractConverter &converter, const fir::ExtendedValue &lhs, 7350 const Fortran::lower::SomeExpr &rhs, Fortran::lower::SymMap &symMap, 7351 Fortran::lower::StatementContext &stmtCtx) { 7352 LLVM_DEBUG(llvm::dbgs() << "onto array: " << lhs << '\n'; 7353 rhs.AsFortran(llvm::dbgs() << "assign expression: ") << '\n';); 7354 ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs); 7355 } 7356 void Fortran::lower::createSomeArrayAssignment( 7357 Fortran::lower::AbstractConverter &converter, const fir::ExtendedValue &lhs, 7358 const fir::ExtendedValue &rhs, Fortran::lower::SymMap &symMap, 7359 Fortran::lower::StatementContext &stmtCtx) { 7360 LLVM_DEBUG(llvm::dbgs() << "onto array: " << lhs << '\n'; 7361 llvm::dbgs() << "assign expression: " << rhs << '\n';); 7362 ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs); 7363 } 7364 7365 void Fortran::lower::createAnyMaskedArrayAssignment( 7366 Fortran::lower::AbstractConverter &converter, 7367 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 7368 Fortran::lower::ExplicitIterSpace &explicitSpace, 7369 Fortran::lower::ImplicitIterSpace &implicitSpace, 7370 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 7371 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "onto array: ") << '\n'; 7372 rhs.AsFortran(llvm::dbgs() << "assign expression: ") 7373 << " given the explicit iteration space:\n" 7374 << explicitSpace << "\n and implied mask conditions:\n" 7375 << implicitSpace << '\n';); 7376 ArrayExprLowering::lowerAnyMaskedArrayAssignment( 7377 converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace); 7378 } 7379 7380 void Fortran::lower::createAllocatableArrayAssignment( 7381 Fortran::lower::AbstractConverter &converter, 7382 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 7383 Fortran::lower::ExplicitIterSpace &explicitSpace, 7384 Fortran::lower::ImplicitIterSpace &implicitSpace, 7385 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 7386 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "defining array: ") << '\n'; 7387 rhs.AsFortran(llvm::dbgs() << "assign expression: ") 7388 << " given the explicit iteration space:\n" 7389 << explicitSpace << "\n and implied mask conditions:\n" 7390 << implicitSpace << '\n';); 7391 ArrayExprLowering::lowerAllocatableArrayAssignment( 7392 converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace); 7393 } 7394 7395 void Fortran::lower::createArrayOfPointerAssignment( 7396 Fortran::lower::AbstractConverter &converter, 7397 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs, 7398 Fortran::lower::ExplicitIterSpace &explicitSpace, 7399 Fortran::lower::ImplicitIterSpace &implicitSpace, 7400 const llvm::SmallVector<mlir::Value> &lbounds, 7401 llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds, 7402 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 7403 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "defining pointer: ") << '\n'; 7404 rhs.AsFortran(llvm::dbgs() << "assign expression: ") 7405 << " given the explicit iteration space:\n" 7406 << explicitSpace << "\n and implied mask conditions:\n" 7407 << implicitSpace << '\n';); 7408 assert(explicitSpace.isActive() && "must be in FORALL construct"); 7409 ArrayExprLowering::lowerArrayOfPointerAssignment( 7410 converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace, 7411 lbounds, ubounds); 7412 } 7413 7414 fir::ExtendedValue Fortran::lower::createSomeArrayTempValue( 7415 Fortran::lower::AbstractConverter &converter, 7416 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap, 7417 Fortran::lower::StatementContext &stmtCtx) { 7418 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "array value: ") << '\n'); 7419 return ArrayExprLowering::lowerNewArrayExpression(converter, symMap, stmtCtx, 7420 expr); 7421 } 7422 7423 void Fortran::lower::createLazyArrayTempValue( 7424 Fortran::lower::AbstractConverter &converter, 7425 const Fortran::lower::SomeExpr &expr, mlir::Value raggedHeader, 7426 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 7427 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "array value: ") << '\n'); 7428 ArrayExprLowering::lowerLazyArrayExpression(converter, symMap, stmtCtx, expr, 7429 raggedHeader); 7430 } 7431 7432 fir::ExtendedValue 7433 Fortran::lower::createSomeArrayBox(Fortran::lower::AbstractConverter &converter, 7434 const Fortran::lower::SomeExpr &expr, 7435 Fortran::lower::SymMap &symMap, 7436 Fortran::lower::StatementContext &stmtCtx) { 7437 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "box designator: ") << '\n'); 7438 return ArrayExprLowering::lowerBoxedArrayExpression(converter, symMap, 7439 stmtCtx, expr); 7440 } 7441 7442 fir::MutableBoxValue Fortran::lower::createMutableBox( 7443 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 7444 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap) { 7445 // MutableBox lowering StatementContext does not need to be propagated 7446 // to the caller because the result value is a variable, not a temporary 7447 // expression. The StatementContext clean-up can occur before using the 7448 // resulting MutableBoxValue. Variables of all other types are handled in the 7449 // bridge. 7450 Fortran::lower::StatementContext dummyStmtCtx; 7451 return ScalarExprLowering{loc, converter, symMap, dummyStmtCtx} 7452 .genMutableBoxValue(expr); 7453 } 7454 7455 fir::ExtendedValue Fortran::lower::createBoxValue( 7456 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 7457 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap, 7458 Fortran::lower::StatementContext &stmtCtx) { 7459 if (expr.Rank() > 0 && Fortran::evaluate::IsVariable(expr) && 7460 !Fortran::evaluate::HasVectorSubscript(expr)) 7461 return Fortran::lower::createSomeArrayBox(converter, expr, symMap, stmtCtx); 7462 fir::ExtendedValue addr = Fortran::lower::createSomeExtendedAddress( 7463 loc, converter, expr, symMap, stmtCtx); 7464 return fir::BoxValue(converter.getFirOpBuilder().createBox(loc, addr)); 7465 } 7466 7467 mlir::Value Fortran::lower::createSubroutineCall( 7468 AbstractConverter &converter, const evaluate::ProcedureRef &call, 7469 ExplicitIterSpace &explicitIterSpace, ImplicitIterSpace &implicitIterSpace, 7470 SymMap &symMap, StatementContext &stmtCtx, bool isUserDefAssignment) { 7471 mlir::Location loc = converter.getCurrentLocation(); 7472 7473 if (isUserDefAssignment) { 7474 assert(call.arguments().size() == 2); 7475 const auto *lhs = call.arguments()[0].value().UnwrapExpr(); 7476 const auto *rhs = call.arguments()[1].value().UnwrapExpr(); 7477 assert(lhs && rhs && 7478 "user defined assignment arguments must be expressions"); 7479 if (call.IsElemental() && lhs->Rank() > 0) { 7480 // Elemental user defined assignment has special requirements to deal with 7481 // LHS/RHS overlaps. See 10.2.1.5 p2. 7482 ArrayExprLowering::lowerElementalUserAssignment( 7483 converter, symMap, stmtCtx, explicitIterSpace, implicitIterSpace, 7484 call); 7485 } else if (explicitIterSpace.isActive() && lhs->Rank() == 0) { 7486 // Scalar defined assignment (elemental or not) in a FORALL context. 7487 mlir::func::FuncOp func = 7488 Fortran::lower::CallerInterface(call, converter).getFuncOp(); 7489 ArrayExprLowering::lowerScalarUserAssignment( 7490 converter, symMap, stmtCtx, explicitIterSpace, func, *lhs, *rhs); 7491 } else if (explicitIterSpace.isActive()) { 7492 // TODO: need to array fetch/modify sub-arrays? 7493 TODO(loc, "non elemental user defined array assignment inside FORALL"); 7494 } else { 7495 if (!implicitIterSpace.empty()) 7496 fir::emitFatalError( 7497 loc, 7498 "C1032: user defined assignment inside WHERE must be elemental"); 7499 // Non elemental user defined assignment outside of FORALL and WHERE. 7500 // FIXME: The non elemental user defined assignment case with array 7501 // arguments must be take into account potential overlap. So far the front 7502 // end does not add parentheses around the RHS argument in the call as it 7503 // should according to 15.4.3.4.3 p2. 7504 Fortran::lower::createSomeExtendedExpression( 7505 loc, converter, toEvExpr(call), symMap, stmtCtx); 7506 } 7507 return {}; 7508 } 7509 7510 assert(implicitIterSpace.empty() && !explicitIterSpace.isActive() && 7511 "subroutine calls are not allowed inside WHERE and FORALL"); 7512 7513 if (isElementalProcWithArrayArgs(call)) { 7514 ArrayExprLowering::lowerElementalSubroutine(converter, symMap, stmtCtx, 7515 toEvExpr(call)); 7516 return {}; 7517 } 7518 // Simple subroutine call, with potential alternate return. 7519 auto res = Fortran::lower::createSomeExtendedExpression( 7520 loc, converter, toEvExpr(call), symMap, stmtCtx); 7521 return fir::getBase(res); 7522 } 7523 7524 template <typename A> 7525 fir::ArrayLoadOp genArrayLoad(mlir::Location loc, 7526 Fortran::lower::AbstractConverter &converter, 7527 fir::FirOpBuilder &builder, const A *x, 7528 Fortran::lower::SymMap &symMap, 7529 Fortran::lower::StatementContext &stmtCtx) { 7530 auto exv = ScalarExprLowering{loc, converter, symMap, stmtCtx}.gen(*x); 7531 mlir::Value addr = fir::getBase(exv); 7532 mlir::Value shapeOp = builder.createShape(loc, exv); 7533 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType()); 7534 return builder.create<fir::ArrayLoadOp>(loc, arrTy, addr, shapeOp, 7535 /*slice=*/mlir::Value{}, 7536 fir::getTypeParams(exv)); 7537 } 7538 template <> 7539 fir::ArrayLoadOp 7540 genArrayLoad(mlir::Location loc, Fortran::lower::AbstractConverter &converter, 7541 fir::FirOpBuilder &builder, const Fortran::evaluate::ArrayRef *x, 7542 Fortran::lower::SymMap &symMap, 7543 Fortran::lower::StatementContext &stmtCtx) { 7544 if (x->base().IsSymbol()) 7545 return genArrayLoad(loc, converter, builder, &getLastSym(x->base()), symMap, 7546 stmtCtx); 7547 return genArrayLoad(loc, converter, builder, &x->base().GetComponent(), 7548 symMap, stmtCtx); 7549 } 7550 7551 void Fortran::lower::createArrayLoads( 7552 Fortran::lower::AbstractConverter &converter, 7553 Fortran::lower::ExplicitIterSpace &esp, Fortran::lower::SymMap &symMap) { 7554 std::size_t counter = esp.getCounter(); 7555 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 7556 mlir::Location loc = converter.getCurrentLocation(); 7557 Fortran::lower::StatementContext &stmtCtx = esp.stmtContext(); 7558 // Gen the fir.array_load ops. 7559 auto genLoad = [&](const auto *x) -> fir::ArrayLoadOp { 7560 return genArrayLoad(loc, converter, builder, x, symMap, stmtCtx); 7561 }; 7562 if (esp.lhsBases[counter].hasValue()) { 7563 auto &base = esp.lhsBases[counter].getValue(); 7564 auto load = std::visit(genLoad, base); 7565 esp.initialArgs.push_back(load); 7566 esp.resetInnerArgs(); 7567 esp.bindLoad(base, load); 7568 } 7569 for (const auto &base : esp.rhsBases[counter]) 7570 esp.bindLoad(base, std::visit(genLoad, base)); 7571 } 7572 7573 void Fortran::lower::createArrayMergeStores( 7574 Fortran::lower::AbstractConverter &converter, 7575 Fortran::lower::ExplicitIterSpace &esp) { 7576 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 7577 mlir::Location loc = converter.getCurrentLocation(); 7578 builder.setInsertionPointAfter(esp.getOuterLoop()); 7579 // Gen the fir.array_merge_store ops for all LHS arrays. 7580 for (auto i : llvm::enumerate(esp.getOuterLoop().getResults())) 7581 if (llvm::Optional<fir::ArrayLoadOp> ldOpt = esp.getLhsLoad(i.index())) { 7582 fir::ArrayLoadOp load = ldOpt.getValue(); 7583 builder.create<fir::ArrayMergeStoreOp>(loc, load, i.value(), 7584 load.getMemref(), load.getSlice(), 7585 load.getTypeparams()); 7586 } 7587 if (esp.loopCleanup.hasValue()) { 7588 esp.loopCleanup.getValue()(builder); 7589 esp.loopCleanup = llvm::None; 7590 } 7591 esp.initialArgs.clear(); 7592 esp.innerArgs.clear(); 7593 esp.outerLoop = llvm::None; 7594 esp.resetBindings(); 7595 esp.incrementCounter(); 7596 } 7597