1 //===- ConvertArrayConstructor.cpp -- Array Constructor ---------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "flang/Lower/ConvertArrayConstructor.h" 10 #include "flang/Evaluate/expression.h" 11 #include "flang/Lower/AbstractConverter.h" 12 #include "flang/Lower/ConvertExprToHLFIR.h" 13 #include "flang/Lower/ConvertType.h" 14 #include "flang/Lower/StatementContext.h" 15 #include "flang/Lower/SymbolMap.h" 16 #include "flang/Optimizer/Builder/HLFIRTools.h" 17 #include "flang/Optimizer/Builder/Runtime/ArrayConstructor.h" 18 #include "flang/Optimizer/Builder/Runtime/RTBuilder.h" 19 #include "flang/Optimizer/Builder/TemporaryStorage.h" 20 #include "flang/Optimizer/Builder/Todo.h" 21 #include "flang/Optimizer/HLFIR/HLFIROps.h" 22 23 // Array constructors are lowered with three different strategies. 24 // All strategies are not possible with all array constructors. 25 // 26 // - Strategy 1: runtime approach (RuntimeTempStrategy). 27 // This strategy works will all array constructors, but will create more 28 // complex code that is harder to optimize. An allocatable temp is created, 29 // it may be unallocated if the array constructor length parameters or extent 30 // could not be computed. Then, the runtime is called to push lowered 31 // ac-value (array constructor elements) into the allocatable. The runtime 32 // will allocate or reallocate as needed while values are being pushed. 33 // In the end, the allocatable contain a temporary with all the array 34 // constructor evaluated elements. 35 // 36 // - Strategy 2: inlined temporary approach (InlinedTempStrategyImpl) 37 // This strategy can only be used if the array constructor extent and length 38 // parameters can be pre-computed without evaluating any ac-value, and if all 39 // of the ac-value are scalars (at least for now). 40 // A temporary is allocated inline in one go, and an index pointing at the 41 // current ac-value position in the array constructor element sequence is 42 // maintained and used to store ac-value as they are being lowered. 43 // 44 // - Strategy 3: "function of the indices" approach (AsElementalStrategy) 45 // This strategy can only be used if the array constructor extent and length 46 // parameters can be pre-computed and, if the array constructor is of the 47 // form "[(scalar_expr, ac-implied-do-control)]". In this case, it is lowered 48 // into an hlfir.elemental without creating any temporary in lowering. This 49 // form should maximize the chance of array temporary elision when assigning 50 // the array constructor, potentially reshaped, to an array variable. 51 // 52 // The array constructor lowering looks like: 53 // ``` 54 // strategy = selectArrayCtorLoweringStrategy(array-ctor-expr); 55 // for (ac-value : array-ctor-expr) 56 // if (ac-value is expression) { 57 // strategy.pushValue(ac-value); 58 // } else if (ac-value is implied-do) { 59 // strategy.startImpliedDo(lower, upper, stride); 60 // strategy.startImpliedDoScope(); 61 // // lower nested values 62 // ... 63 // strategy.endImpliedDoScope(); 64 // } 65 // result = strategy.finishArrayCtorLowering(); 66 // ``` 67 68 //===----------------------------------------------------------------------===// 69 // Definition of the lowering strategies. Each lowering strategy is defined 70 // as a class that implements "pushValue", "startImpliedDo" and 71 // "finishArrayCtorLowering". A strategy may optionally override 72 // "startImpliedDoScope" and "endImpliedDoScope" virtual methods 73 // of its base class StrategyBase. 74 //===----------------------------------------------------------------------===// 75 76 namespace { 77 /// Class provides common implementation of scope push/pop methods 78 /// that update StatementContext scopes and SymMap bindings. 79 /// They might be overridden by the lowering strategies, e.g. 80 /// see AsElementalStrategy. 81 class StrategyBase { 82 public: 83 StrategyBase(Fortran::lower::StatementContext &stmtCtx, 84 Fortran::lower::SymMap &symMap) 85 : stmtCtx{stmtCtx}, symMap{symMap} {}; 86 virtual ~StrategyBase() = default; 87 88 virtual void startImpliedDoScope(llvm::StringRef doName, 89 mlir::Value indexValue) { 90 symMap.pushImpliedDoBinding(doName, indexValue); 91 stmtCtx.pushScope(); 92 } 93 94 virtual void endImpliedDoScope() { 95 stmtCtx.finalizeAndPop(); 96 symMap.popImpliedDoBinding(); 97 } 98 99 protected: 100 Fortran::lower::StatementContext &stmtCtx; 101 Fortran::lower::SymMap &symMap; 102 }; 103 104 /// Class that implements the "inlined temp strategy" to lower array 105 /// constructors. It must be provided a boolean to indicate if the array 106 /// constructor has any implied-do-loop. 107 template <bool hasLoops> 108 class InlinedTempStrategyImpl : public StrategyBase, 109 public fir::factory::HomogeneousScalarStack { 110 /// Name that will be given to the temporary allocation and hlfir.declare in 111 /// the IR. 112 static constexpr char tempName[] = ".tmp.arrayctor"; 113 114 public: 115 /// Start lowering an array constructor according to the inline strategy. 116 /// The temporary is created right away. 117 InlinedTempStrategyImpl(mlir::Location loc, fir::FirOpBuilder &builder, 118 Fortran::lower::StatementContext &stmtCtx, 119 Fortran::lower::SymMap &symMap, 120 fir::SequenceType declaredType, mlir::Value extent, 121 llvm::ArrayRef<mlir::Value> lengths) 122 : StrategyBase{stmtCtx, symMap}, 123 fir::factory::HomogeneousScalarStack{ 124 loc, builder, declaredType, 125 extent, lengths, /*allocateOnHeap=*/true, 126 hasLoops, tempName} {} 127 128 /// Push a lowered ac-value into the current insertion point and 129 /// increment the insertion point. 130 using fir::factory::HomogeneousScalarStack::pushValue; 131 132 /// Start a fir.do_loop with the control from an implied-do and return 133 /// the loop induction variable that is the ac-do-variable value. 134 /// Only usable if the counter is able to track the position through loops. 135 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 136 mlir::Value lower, mlir::Value upper, 137 mlir::Value stride) { 138 if constexpr (!hasLoops) 139 fir::emitFatalError(loc, "array constructor lowering is inconsistent"); 140 auto loop = builder.create<fir::DoLoopOp>(loc, lower, upper, stride, 141 /*unordered=*/false, 142 /*finalCount=*/false); 143 builder.setInsertionPointToStart(loop.getBody()); 144 return loop.getInductionVar(); 145 } 146 147 /// Move the temporary to an hlfir.expr value (array constructors are not 148 /// variables and cannot be further modified). 149 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 150 fir::FirOpBuilder &builder) { 151 return moveStackAsArrayExpr(loc, builder); 152 } 153 }; 154 155 /// Semantic analysis expression rewrites unroll implied do loop with 156 /// compile time constant bounds (even if huge). So using a minimalistic 157 /// counter greatly reduces the generated IR for simple but big array 158 /// constructors [(i,i=1,constant-expr)] that are expected to be quite 159 /// common. 160 using LooplessInlinedTempStrategy = InlinedTempStrategyImpl</*hasLoops=*/false>; 161 /// A generic memory based counter that can deal with all cases of 162 /// "inlined temp strategy". The counter value is stored in a temp 163 /// from which it is loaded, incremented, and stored every time an 164 /// ac-value is pushed. 165 using InlinedTempStrategy = InlinedTempStrategyImpl</*hasLoops=*/true>; 166 167 /// Class that implements the "as function of the indices" lowering strategy. 168 /// It will lower [(scalar_expr(i), i=l,u,s)] to: 169 /// ``` 170 /// %extent = max((%u-%l+1)/%s, 0) 171 /// %shape = fir.shape %extent 172 /// %elem = hlfir.elemental %shape { 173 /// ^bb0(%pos:index): 174 /// %i = %l+(%i-1)*%s 175 /// %value = scalar_expr(%i) 176 /// hlfir.yield_element %value 177 /// } 178 /// ``` 179 /// That way, no temporary is created in lowering, and if the array constructor 180 /// is part of a more complex elemental expression, or an assignment, it will be 181 /// trivial to "inline" it in the expression or assignment loops if allowed by 182 /// alias analysis. 183 /// This lowering is however only possible for the form of array constructors as 184 /// in the illustration above. It could be extended to deeper independent 185 /// implied-do nest and wrapped in an hlfir.reshape to a rank 1 array. But this 186 /// op does not exist yet, so this is left for the future if it appears 187 /// profitable. 188 class AsElementalStrategy : public StrategyBase { 189 public: 190 /// The constructor only gathers the operands to create the hlfir.elemental. 191 AsElementalStrategy(mlir::Location loc, fir::FirOpBuilder &builder, 192 Fortran::lower::StatementContext &stmtCtx, 193 Fortran::lower::SymMap &symMap, 194 fir::SequenceType declaredType, mlir::Value extent, 195 llvm::ArrayRef<mlir::Value> lengths) 196 : StrategyBase{stmtCtx, symMap}, shape{builder.genShape(loc, {extent})}, 197 lengthParams{lengths.begin(), lengths.end()}, 198 exprType{getExprType(declaredType)} {} 199 200 static hlfir::ExprType getExprType(fir::SequenceType declaredType) { 201 // Note: 7.8 point 4: the dynamic type of an array constructor is its static 202 // type, it is not polymorphic. 203 return hlfir::ExprType::get(declaredType.getContext(), 204 declaredType.getShape(), 205 declaredType.getEleTy(), 206 /*isPolymorphic=*/false); 207 } 208 209 /// Create the hlfir.elemental and compute the ac-implied-do-index value 210 /// given the lower bound and stride (compute "%i" in the illustration above). 211 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 212 mlir::Value lower, mlir::Value upper, 213 mlir::Value stride) { 214 assert(!elementalOp && "expected only one implied-do"); 215 mlir::Value one = 216 builder.createIntegerConstant(loc, builder.getIndexType(), 1); 217 elementalOp = 218 builder.create<hlfir::ElementalOp>(loc, exprType, shape, lengthParams, 219 /*isUnordered=*/true); 220 builder.setInsertionPointToStart(elementalOp.getBody()); 221 // implied-do-index = lower+((i-1)*stride) 222 mlir::Value diff = builder.create<mlir::arith::SubIOp>( 223 loc, elementalOp.getIndices()[0], one); 224 mlir::Value mul = builder.create<mlir::arith::MulIOp>(loc, diff, stride); 225 mlir::Value add = builder.create<mlir::arith::AddIOp>(loc, lower, mul); 226 return add; 227 } 228 229 /// Create the elemental hlfir.yield_element with the scalar ac-value. 230 void pushValue(mlir::Location loc, fir::FirOpBuilder &builder, 231 hlfir::Entity value) { 232 assert(value.isScalar() && "cannot use hlfir.elemental with array values"); 233 assert(elementalOp && "array constructor must contain an outer implied-do"); 234 mlir::Value elementResult = value; 235 if (fir::isa_trivial(elementResult.getType())) 236 elementResult = 237 builder.createConvert(loc, exprType.getElementType(), elementResult); 238 239 // The clean-ups associated with the implied-do body operations 240 // must be initiated before the YieldElementOp, so we have to pop the scope 241 // right now. 242 stmtCtx.finalizeAndPop(); 243 244 builder.create<hlfir::YieldElementOp>(loc, elementResult); 245 } 246 247 // Override the default, because the context scope must be popped in 248 // pushValue(). 249 virtual void endImpliedDoScope() override { symMap.popImpliedDoBinding(); } 250 251 /// Return the created hlfir.elemental. 252 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 253 fir::FirOpBuilder &builder) { 254 return hlfir::Entity{elementalOp}; 255 } 256 257 private: 258 mlir::Value shape; 259 llvm::SmallVector<mlir::Value> lengthParams; 260 hlfir::ExprType exprType; 261 hlfir::ElementalOp elementalOp{}; 262 }; 263 264 /// Class that implements the "runtime temp strategy" to lower array 265 /// constructors. 266 class RuntimeTempStrategy : public StrategyBase { 267 /// Name that will be given to the temporary allocation and hlfir.declare in 268 /// the IR. 269 static constexpr char tempName[] = ".tmp.arrayctor"; 270 271 public: 272 /// Start lowering an array constructor according to the runtime strategy. 273 /// The temporary is only created if the extents and length parameters are 274 /// already known. Otherwise, the handling of the allocation (and 275 /// reallocation) is left up to the runtime. 276 /// \p extent is the pre-computed extent of the array constructor, if it could 277 /// be pre-computed. It is std::nullopt otherwise. 278 /// \p lengths are the pre-computed length parameters of the array 279 /// constructor, if they could be precomputed. \p missingLengthParameters is 280 /// set to true if the length parameters could not be precomputed. 281 RuntimeTempStrategy(mlir::Location loc, fir::FirOpBuilder &builder, 282 Fortran::lower::StatementContext &stmtCtx, 283 Fortran::lower::SymMap &symMap, 284 fir::SequenceType declaredType, 285 std::optional<mlir::Value> extent, 286 llvm::ArrayRef<mlir::Value> lengths, 287 bool missingLengthParameters) 288 : StrategyBase{stmtCtx, symMap}, 289 arrayConstructorElementType{declaredType.getEleTy()} { 290 mlir::Type heapType = fir::HeapType::get(declaredType); 291 mlir::Type boxType = fir::BoxType::get(heapType); 292 allocatableTemp = builder.createTemporary(loc, boxType, tempName); 293 mlir::Value initialBoxValue; 294 if (extent && !missingLengthParameters) { 295 llvm::SmallVector<mlir::Value, 1> extents{*extent}; 296 mlir::Value tempStorage = builder.createHeapTemporary( 297 loc, declaredType, tempName, extents, lengths); 298 mlir::Value shape = builder.genShape(loc, extents); 299 declare = builder.create<hlfir::DeclareOp>( 300 loc, tempStorage, tempName, shape, lengths, 301 fir::FortranVariableFlagsAttr{}); 302 initialBoxValue = 303 builder.createBox(loc, boxType, declare->getOriginalBase(), shape, 304 /*slice=*/mlir::Value{}, lengths, /*tdesc=*/{}); 305 } else { 306 // The runtime will have to do the initial allocation. 307 // The declare operation cannot be emitted in this case since the final 308 // array constructor has not yet been allocated. Instead, the resulting 309 // temporary variable will be extracted from the allocatable descriptor 310 // after all the API calls. 311 // Prepare the initial state of the allocatable descriptor with a 312 // deallocated status and all the available knowledge about the extent 313 // and length parameters. 314 llvm::SmallVector<mlir::Value> emboxLengths(lengths.begin(), 315 lengths.end()); 316 if (!extent) 317 extent = builder.createIntegerConstant(loc, builder.getIndexType(), 0); 318 if (missingLengthParameters) { 319 if (declaredType.getEleTy().isa<fir::CharacterType>()) 320 emboxLengths.push_back(builder.createIntegerConstant( 321 loc, builder.getCharacterLengthType(), 0)); 322 else 323 TODO(loc, 324 "parametrized derived type array constructor without type-spec"); 325 } 326 mlir::Value nullAddr = builder.createNullConstant(loc, heapType); 327 mlir::Value shape = builder.genShape(loc, {*extent}); 328 initialBoxValue = builder.createBox(loc, boxType, nullAddr, shape, 329 /*slice=*/mlir::Value{}, emboxLengths, 330 /*tdesc=*/{}); 331 } 332 builder.create<fir::StoreOp>(loc, initialBoxValue, allocatableTemp); 333 arrayConstructorVector = fir::runtime::genInitArrayConstructorVector( 334 loc, builder, allocatableTemp, 335 builder.createBool(loc, missingLengthParameters)); 336 } 337 338 bool useSimplePushRuntime(hlfir::Entity value) { 339 return value.isScalar() && 340 !arrayConstructorElementType.isa<fir::CharacterType>() && 341 !fir::isRecordWithAllocatableMember(arrayConstructorElementType) && 342 !fir::isRecordWithTypeParameters(arrayConstructorElementType); 343 } 344 345 /// Push a lowered ac-value into the array constructor vector using 346 /// the runtime API. 347 void pushValue(mlir::Location loc, fir::FirOpBuilder &builder, 348 hlfir::Entity value) { 349 if (useSimplePushRuntime(value)) { 350 auto [addrExv, cleanUp] = hlfir::convertToAddress( 351 loc, builder, value, arrayConstructorElementType); 352 mlir::Value addr = fir::getBase(addrExv); 353 if (addr.getType().isa<fir::BaseBoxType>()) 354 addr = builder.create<fir::BoxAddrOp>(loc, addr); 355 fir::runtime::genPushArrayConstructorSimpleScalar( 356 loc, builder, arrayConstructorVector, addr); 357 if (cleanUp) 358 (*cleanUp)(); 359 return; 360 } 361 auto [boxExv, cleanUp] = 362 hlfir::convertToBox(loc, builder, value, arrayConstructorElementType); 363 fir::runtime::genPushArrayConstructorValue( 364 loc, builder, arrayConstructorVector, fir::getBase(boxExv)); 365 if (cleanUp) 366 (*cleanUp)(); 367 } 368 369 /// Start a fir.do_loop with the control from an implied-do and return 370 /// the loop induction variable that is the ac-do-variable value. 371 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 372 mlir::Value lower, mlir::Value upper, 373 mlir::Value stride) { 374 auto loop = builder.create<fir::DoLoopOp>(loc, lower, upper, stride, 375 /*unordered=*/false, 376 /*finalCount=*/false); 377 builder.setInsertionPointToStart(loop.getBody()); 378 return loop.getInductionVar(); 379 } 380 381 /// Move the temporary to an hlfir.expr value (array constructors are not 382 /// variables and cannot be further modified). 383 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 384 fir::FirOpBuilder &builder) { 385 // Temp is created using createHeapTemporary, or allocated on the heap 386 // by the runtime. 387 mlir::Value mustFree = builder.createBool(loc, true); 388 mlir::Value temp; 389 if (declare) 390 temp = declare->getBase(); 391 else 392 temp = hlfir::derefPointersAndAllocatables( 393 loc, builder, hlfir::Entity{allocatableTemp}); 394 auto hlfirExpr = builder.create<hlfir::AsExprOp>(loc, temp, mustFree); 395 return hlfir::Entity{hlfirExpr}; 396 } 397 398 private: 399 /// Element type of the array constructor being built. 400 mlir::Type arrayConstructorElementType; 401 /// Allocatable descriptor for the storage of the array constructor being 402 /// built. 403 mlir::Value allocatableTemp; 404 /// Structure that allows the runtime API to maintain the status of 405 /// of the array constructor being built between two API calls. 406 mlir::Value arrayConstructorVector; 407 /// DeclareOp for the array constructor storage, if it was possible to 408 /// allocate it before any API calls. 409 std::optional<hlfir::DeclareOp> declare; 410 }; 411 412 /// Wrapper class that dispatch to the selected array constructor lowering 413 /// strategy and does nothing else. 414 class ArrayCtorLoweringStrategy { 415 public: 416 template <typename A> 417 ArrayCtorLoweringStrategy(A &&impl) : implVariant{std::forward<A>(impl)} {} 418 419 void pushValue(mlir::Location loc, fir::FirOpBuilder &builder, 420 hlfir::Entity value) { 421 return std::visit( 422 [&](auto &impl) { return impl.pushValue(loc, builder, value); }, 423 implVariant); 424 } 425 426 mlir::Value startImpliedDo(mlir::Location loc, fir::FirOpBuilder &builder, 427 mlir::Value lower, mlir::Value upper, 428 mlir::Value stride) { 429 return std::visit( 430 [&](auto &impl) { 431 return impl.startImpliedDo(loc, builder, lower, upper, stride); 432 }, 433 implVariant); 434 } 435 436 hlfir::Entity finishArrayCtorLowering(mlir::Location loc, 437 fir::FirOpBuilder &builder) { 438 return std::visit( 439 [&](auto &impl) { return impl.finishArrayCtorLowering(loc, builder); }, 440 implVariant); 441 } 442 443 void startImpliedDoScope(llvm::StringRef doName, mlir::Value indexValue) { 444 std::visit( 445 [&](auto &impl) { 446 return impl.startImpliedDoScope(doName, indexValue); 447 }, 448 implVariant); 449 } 450 451 void endImpliedDoScope() { 452 std::visit([&](auto &impl) { return impl.endImpliedDoScope(); }, 453 implVariant); 454 } 455 456 private: 457 std::variant<InlinedTempStrategy, LooplessInlinedTempStrategy, 458 AsElementalStrategy, RuntimeTempStrategy> 459 implVariant; 460 }; 461 } // namespace 462 463 //===----------------------------------------------------------------------===// 464 // Definition of selectArrayCtorLoweringStrategy and its helpers. 465 // This is the code that analyses the evaluate::ArrayConstructor<T>, 466 // pre-lowers the array constructor extent and length parameters if it can, 467 // and chooses the lowering strategy. 468 //===----------------------------------------------------------------------===// 469 470 /// Helper to lower a scalar extent expression (like implied-do bounds). 471 static mlir::Value lowerExtentExpr(mlir::Location loc, 472 Fortran::lower::AbstractConverter &converter, 473 Fortran::lower::SymMap &symMap, 474 Fortran::lower::StatementContext &stmtCtx, 475 const Fortran::evaluate::ExtentExpr &expr) { 476 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 477 mlir::IndexType idxTy = builder.getIndexType(); 478 hlfir::Entity value = Fortran::lower::convertExprToHLFIR( 479 loc, converter, toEvExpr(expr), symMap, stmtCtx); 480 value = hlfir::loadTrivialScalar(loc, builder, value); 481 return builder.createConvert(loc, idxTy, value); 482 } 483 484 namespace { 485 /// Helper class to lower the array constructor type and its length parameters. 486 /// The length parameters, if any, are only lowered if this does not require 487 /// evaluating an ac-value. 488 template <typename T> 489 struct LengthAndTypeCollector { 490 static mlir::Type collect(mlir::Location, 491 Fortran::lower::AbstractConverter &converter, 492 const Fortran::evaluate::ArrayConstructor<T> &, 493 Fortran::lower::SymMap &, 494 Fortran::lower::StatementContext &, 495 mlir::SmallVectorImpl<mlir::Value> &) { 496 // Numerical and Logical types. 497 return Fortran::lower::getFIRType(&converter.getMLIRContext(), T::category, 498 T::kind, /*lenParams*/ {}); 499 } 500 }; 501 502 template <> 503 struct LengthAndTypeCollector<Fortran::evaluate::SomeDerived> { 504 static mlir::Type collect( 505 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 506 const Fortran::evaluate::ArrayConstructor<Fortran::evaluate::SomeDerived> 507 &arrayCtorExpr, 508 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 509 mlir::SmallVectorImpl<mlir::Value> &lengths) { 510 // Array constructors cannot be unlimited polymorphic (C7113), so there must 511 // be a derived type spec available. 512 return Fortran::lower::translateDerivedTypeToFIRType( 513 converter, arrayCtorExpr.result().derivedTypeSpec()); 514 } 515 }; 516 517 template <int Kind> 518 using Character = 519 Fortran::evaluate::Type<Fortran::common::TypeCategory::Character, Kind>; 520 template <int Kind> 521 struct LengthAndTypeCollector<Character<Kind>> { 522 static mlir::Type collect( 523 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 524 const Fortran::evaluate::ArrayConstructor<Character<Kind>> &arrayCtorExpr, 525 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 526 mlir::SmallVectorImpl<mlir::Value> &lengths) { 527 llvm::SmallVector<Fortran::lower::LenParameterTy> typeLengths; 528 if (const Fortran::evaluate::ExtentExpr *lenExpr = arrayCtorExpr.LEN()) { 529 lengths.push_back( 530 lowerExtentExpr(loc, converter, symMap, stmtCtx, *lenExpr)); 531 if (std::optional<std::int64_t> cstLen = 532 Fortran::evaluate::ToInt64(*lenExpr)) 533 typeLengths.push_back(*cstLen); 534 } 535 return Fortran::lower::getFIRType(&converter.getMLIRContext(), 536 Fortran::common::TypeCategory::Character, 537 Kind, typeLengths); 538 } 539 }; 540 } // namespace 541 542 /// Does the array constructor have length parameters that 543 /// LengthAndTypeCollector::collect could not lower because this requires 544 /// lowering an ac-value and must be delayed? 545 static bool missingLengthParameters(mlir::Type elementType, 546 llvm::ArrayRef<mlir::Value> lengths) { 547 return (elementType.isa<fir::CharacterType>() || 548 fir::isRecordWithTypeParameters(elementType)) && 549 lengths.empty(); 550 } 551 552 namespace { 553 /// Structure that analyses the ac-value and implied-do of 554 /// evaluate::ArrayConstructor before they are lowered. It does not generate any 555 /// IR. The result of this analysis pass is used to select the lowering 556 /// strategy. 557 struct ArrayCtorAnalysis { 558 template <typename T> 559 ArrayCtorAnalysis( 560 Fortran::evaluate::FoldingContext &, 561 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr); 562 563 // Can the array constructor easily be rewritten into an hlfir.elemental ? 564 bool isSingleImpliedDoWithOneScalarPureExpr() const { 565 return !anyArrayExpr && isPerfectLoopNest && 566 innerNumberOfExprIfPrefectNest == 1 && depthIfPerfectLoopNest == 1 && 567 innerExprIsPureIfPerfectNest; 568 } 569 570 bool anyImpliedDo = false; 571 bool anyArrayExpr = false; 572 bool isPerfectLoopNest = true; 573 bool innerExprIsPureIfPerfectNest = false; 574 std::int64_t innerNumberOfExprIfPrefectNest = 0; 575 std::int64_t depthIfPerfectLoopNest = 0; 576 }; 577 } // namespace 578 579 template <typename T> 580 ArrayCtorAnalysis::ArrayCtorAnalysis( 581 Fortran::evaluate::FoldingContext &foldingContext, 582 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr) { 583 llvm::SmallVector<const Fortran::evaluate::ArrayConstructorValues<T> *> 584 arrayValueListStack{&arrayCtorExpr}; 585 // Loop through the ac-value-list(s) of the array constructor. 586 while (!arrayValueListStack.empty()) { 587 std::int64_t localNumberOfImpliedDo = 0; 588 std::int64_t localNumberOfExpr = 0; 589 // Loop though the ac-value of an ac-value list, and add any nested 590 // ac-value-list of ac-implied-do to the stack. 591 const Fortran::evaluate::ArrayConstructorValues<T> *currentArrayValueList = 592 arrayValueListStack.pop_back_val(); 593 for (const Fortran::evaluate::ArrayConstructorValue<T> &acValue : 594 *currentArrayValueList) 595 std::visit(Fortran::common::visitors{ 596 [&](const Fortran::evaluate::ImpliedDo<T> &impledDo) { 597 arrayValueListStack.push_back(&impledDo.values()); 598 localNumberOfImpliedDo++; 599 }, 600 [&](const Fortran::evaluate::Expr<T> &expr) { 601 localNumberOfExpr++; 602 anyArrayExpr = anyArrayExpr || expr.Rank() > 0; 603 }}, 604 acValue.u); 605 anyImpliedDo = anyImpliedDo || localNumberOfImpliedDo > 0; 606 607 if (localNumberOfImpliedDo == 0) { 608 // Leaf ac-value-list in the array constructor ac-value tree. 609 if (isPerfectLoopNest) { 610 // This this the only leaf of the array-constructor (the array 611 // constructor is a nest of single implied-do with a list of expression 612 // in the last deeper implied do). e.g: "[((i+j, i=1,n)j=1,m)]". 613 innerNumberOfExprIfPrefectNest = localNumberOfExpr; 614 if (localNumberOfExpr == 1) 615 innerExprIsPureIfPerfectNest = !Fortran::evaluate::FindImpureCall( 616 foldingContext, toEvExpr(std::get<Fortran::evaluate::Expr<T>>( 617 currentArrayValueList->begin()->u))); 618 } 619 } else if (localNumberOfImpliedDo == 1 && localNumberOfExpr == 0) { 620 // Perfect implied-do nest new level. 621 ++depthIfPerfectLoopNest; 622 } else { 623 // More than one implied-do, or at least one implied-do and an expr 624 // at that level. This will not form a perfect nest. Examples: 625 // "[a, (i, i=1,n)]" or "[(i, i=1,n), (j, j=1,m)]". 626 isPerfectLoopNest = false; 627 } 628 } 629 } 630 631 /// Does \p expr contain no calls to user function? 632 static bool isCallFreeExpr(const Fortran::evaluate::ExtentExpr &expr) { 633 for (const Fortran::semantics::Symbol &symbol : 634 Fortran::evaluate::CollectSymbols(expr)) 635 if (Fortran::semantics::IsProcedure(symbol)) 636 return false; 637 return true; 638 } 639 640 /// Core function that pre-lowers the extent and length parameters of 641 /// array constructors if it can, runs the ac-value analysis and 642 /// select the lowering strategy accordingly. 643 template <typename T> 644 static ArrayCtorLoweringStrategy selectArrayCtorLoweringStrategy( 645 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 646 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr, 647 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 648 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 649 mlir::Type idxType = builder.getIndexType(); 650 // Try to gather the array constructor extent. 651 mlir::Value extent; 652 fir::SequenceType::Extent typeExtent = fir::SequenceType::getUnknownExtent(); 653 auto shapeExpr = Fortran::evaluate::GetContextFreeShape( 654 converter.getFoldingContext(), arrayCtorExpr); 655 if (shapeExpr && shapeExpr->size() == 1 && (*shapeExpr)[0]) { 656 const Fortran::evaluate::ExtentExpr &extentExpr = *(*shapeExpr)[0]; 657 if (auto constantExtent = Fortran::evaluate::ToInt64(extentExpr)) { 658 typeExtent = *constantExtent; 659 extent = builder.createIntegerConstant(loc, idxType, typeExtent); 660 } else if (isCallFreeExpr(extentExpr)) { 661 // The expression built by expression analysis for the array constructor 662 // extent does not contain procedure symbols. It is side effect free. 663 // This could be relaxed to allow pure procedure, but some care must 664 // be taken to not bring in "unmapped" symbols from callee scopes. 665 extent = lowerExtentExpr(loc, converter, symMap, stmtCtx, extentExpr); 666 } 667 // Otherwise, the temporary will have to be built step by step with 668 // reallocation and the extent will only be known at the end of the array 669 // constructor evaluation. 670 } 671 // Convert the array constructor type and try to gather its length parameter 672 // values, if any. 673 mlir::SmallVector<mlir::Value> lengths; 674 mlir::Type elementType = LengthAndTypeCollector<T>::collect( 675 loc, converter, arrayCtorExpr, symMap, stmtCtx, lengths); 676 // Run an analysis of the array constructor ac-value. 677 ArrayCtorAnalysis analysis(converter.getFoldingContext(), arrayCtorExpr); 678 bool needToEvaluateOneExprToGetLengthParameters = 679 missingLengthParameters(elementType, lengths); 680 auto declaredType = fir::SequenceType::get({typeExtent}, elementType); 681 682 // Based on what was gathered and the result of the analysis, select and 683 // instantiate the right lowering strategy for the array constructor. 684 if (!extent || needToEvaluateOneExprToGetLengthParameters || 685 analysis.anyArrayExpr || declaredType.getEleTy().isa<fir::RecordType>()) 686 return RuntimeTempStrategy( 687 loc, builder, stmtCtx, symMap, declaredType, 688 extent ? std::optional<mlir::Value>(extent) : std::nullopt, lengths, 689 needToEvaluateOneExprToGetLengthParameters); 690 // Note: the generated hlfir.elemental is always unordered, thus, 691 // AsElementalStrategy can only be used for array constructors without 692 // impure ac-value expressions. If/when this changes, make sure 693 // the 'unordered' attribute is set accordingly for the hlfir.elemental. 694 if (analysis.isSingleImpliedDoWithOneScalarPureExpr()) 695 return AsElementalStrategy(loc, builder, stmtCtx, symMap, declaredType, 696 extent, lengths); 697 698 if (analysis.anyImpliedDo) 699 return InlinedTempStrategy(loc, builder, stmtCtx, symMap, declaredType, 700 extent, lengths); 701 702 return LooplessInlinedTempStrategy(loc, builder, stmtCtx, symMap, 703 declaredType, extent, lengths); 704 } 705 706 /// Lower an ac-value expression \p expr and forward it to the selected 707 /// lowering strategy \p arrayBuilder, 708 template <typename T> 709 static void genAcValue(mlir::Location loc, 710 Fortran::lower::AbstractConverter &converter, 711 const Fortran::evaluate::Expr<T> &expr, 712 Fortran::lower::SymMap &symMap, 713 Fortran::lower::StatementContext &stmtCtx, 714 ArrayCtorLoweringStrategy &arrayBuilder) { 715 // TODO: get rid of the toEvExpr indirection. 716 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 717 hlfir::Entity value = Fortran::lower::convertExprToHLFIR( 718 loc, converter, toEvExpr(expr), symMap, stmtCtx); 719 value = hlfir::loadTrivialScalar(loc, builder, value); 720 arrayBuilder.pushValue(loc, builder, value); 721 } 722 723 /// Lowers an ac-value implied-do \p impledDo according to the selected 724 /// lowering strategy \p arrayBuilder. 725 template <typename T> 726 static void genAcValue(mlir::Location loc, 727 Fortran::lower::AbstractConverter &converter, 728 const Fortran::evaluate::ImpliedDo<T> &impledDo, 729 Fortran::lower::SymMap &symMap, 730 Fortran::lower::StatementContext &stmtCtx, 731 ArrayCtorLoweringStrategy &arrayBuilder) { 732 auto lowerIndex = 733 [&](const Fortran::evaluate::ExtentExpr expr) -> mlir::Value { 734 return lowerExtentExpr(loc, converter, symMap, stmtCtx, expr); 735 }; 736 mlir::Value lower = lowerIndex(impledDo.lower()); 737 mlir::Value upper = lowerIndex(impledDo.upper()); 738 mlir::Value stride = lowerIndex(impledDo.stride()); 739 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 740 mlir::OpBuilder::InsertPoint insertPt = builder.saveInsertionPoint(); 741 mlir::Value impliedDoIndexValue = 742 arrayBuilder.startImpliedDo(loc, builder, lower, upper, stride); 743 arrayBuilder.startImpliedDoScope(toStringRef(impledDo.name()), 744 impliedDoIndexValue); 745 746 for (const auto &acValue : impledDo.values()) 747 std::visit( 748 [&](const auto &x) { 749 genAcValue(loc, converter, x, symMap, stmtCtx, arrayBuilder); 750 }, 751 acValue.u); 752 753 arrayBuilder.endImpliedDoScope(); 754 builder.restoreInsertionPoint(insertPt); 755 } 756 757 /// Entry point for evaluate::ArrayConstructor lowering. 758 template <typename T> 759 hlfir::EntityWithAttributes Fortran::lower::ArrayConstructorBuilder<T>::gen( 760 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 761 const Fortran::evaluate::ArrayConstructor<T> &arrayCtorExpr, 762 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) { 763 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 764 // Select the lowering strategy given the array constructor. 765 auto arrayBuilder = selectArrayCtorLoweringStrategy( 766 loc, converter, arrayCtorExpr, symMap, stmtCtx); 767 // Run the array lowering strategy through the ac-values. 768 for (const auto &acValue : arrayCtorExpr) 769 std::visit( 770 [&](const auto &x) { 771 genAcValue(loc, converter, x, symMap, stmtCtx, arrayBuilder); 772 }, 773 acValue.u); 774 hlfir::Entity hlfirExpr = arrayBuilder.finishArrayCtorLowering(loc, builder); 775 // Insert the clean-up for the created hlfir.expr. 776 fir::FirOpBuilder *bldr = &builder; 777 stmtCtx.attachCleanup( 778 [=]() { bldr->create<hlfir::DestroyOp>(loc, hlfirExpr); }); 779 return hlfir::EntityWithAttributes{hlfirExpr}; 780 } 781 782 using namespace Fortran::evaluate; 783 using namespace Fortran::common; 784 FOR_EACH_SPECIFIC_TYPE(template class Fortran::lower::ArrayConstructorBuilder, ) 785