Debian Codegraph @

flang/lib/Optimizer/HLFIR/Transforms/LowerHLFIROrderedAssignments.cpp

raw
1 //===- LowerHLFIROrderedAssignments.cpp - Lower HLFIR ordered assignments -===//
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 // This file defines a pass to lower HLFIR ordered assignments.
9 // Ordered assignments are all the operations with the
10 // OrderedAssignmentTreeOpInterface that implements user defined assignments,
11 // assignment to vector subscripted entities, and assignments inside forall and
12 // where.
13 // The pass lowers these operations to regular hlfir.assign, loops and, if
14 // needed, introduces temporary storage to fulfill Fortran semantics.
15 //
16 // For each rewrite, an analysis builds an evaluation schedule, and then the
17 // new code is generated by following the evaluation schedule.
18 //===----------------------------------------------------------------------===//
19
20 #include "ScheduleOrderedAssignments.h"
21 #include "flang/Optimizer/Builder/FIRBuilder.h"
22 #include "flang/Optimizer/Builder/HLFIRTools.h"
23 #include "flang/Optimizer/Builder/TemporaryStorage.h"
24 #include "flang/Optimizer/Builder/Todo.h"
25 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
26 #include "flang/Optimizer/HLFIR/Passes.h"
27 #include "mlir/IR/Dominance.h"
28 #include "mlir/IR/IRMapping.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/TypeSwitch.h"
32 #include "llvm/Support/Debug.h"
33
34 namespace hlfir {
35 #define GEN_PASS_DEF_LOWERHLFIRORDEREDASSIGNMENTS
36 #include "flang/Optimizer/HLFIR/Passes.h.inc"
37 } // namespace hlfir
38
39 #define DEBUG_TYPE "flang-ordered-assignment"
40
41 // Test option only to test the scheduling part only (operations are erased
42 // without codegen). The only goal is to allow printing and testing the debug
43 // info.
44 static llvm::cl::opt<bool> dbgScheduleOnly(
45 "flang-dbg-order-assignment-schedule-only",
46 llvm::cl::desc("Only run ordered assignment scheduling with no codegen"),
47 llvm::cl::init(false));
48
49 namespace {
50
51 /// Structure that represents a masked expression being lowered. Masked
52 /// expressions are any expressions inside an hlfir.where. As described in
53 /// Fortran 2018 section 10.2.3.2, the evaluation of the elemental parts of such
54 /// expressions must be masked, while the evaluation of none elemental parts
55 /// must not be masked. This structure analyzes the region evaluating the
56 /// expression and allows splitting the generation of the none elemental part
57 /// from the elemental part.
58 struct MaskedArrayExpr {
59 MaskedArrayExpr(mlir::Location loc, mlir::Region &region,
60 bool isOuterMaskExpr);
61
62 /// Generate the none elemental part. Must be called outside of the
63 /// loops created for the WHERE construct.
64 void generateNoneElementalPart(fir::FirOpBuilder &builder,
65 mlir::IRMapping &mapper);
66
67 /// Methods below can only be called once generateNoneElementalPart has been
68 /// called.
69
70 /// Return the shape of the expression.
71 mlir::Value generateShape(fir::FirOpBuilder &builder,
72 mlir::IRMapping &mapper);
73 /// Return the value of an element value for this expression given the current
74 /// where loop indices.
75 mlir::Value generateElementalParts(fir::FirOpBuilder &builder,
76 mlir::ValueRange oneBasedIndices,
77 mlir::IRMapping &mapper);
78 /// Generate the cleanup for the none elemental parts, if any. This must be
79 /// called after the loops created for the WHERE construct.
80 void generateNoneElementalCleanupIfAny(fir::FirOpBuilder &builder,
81 mlir::IRMapping &mapper);
82
83 /// Helper to clone the clean-ups of the masked expr region terminator.
84 /// This is called outside of the loops for the initial mask, and inside
85 /// the loops for the other masked expressions.
86 mlir::Operation *generateMaskedExprCleanUps(fir::FirOpBuilder &builder,
87 mlir::IRMapping &mapper);
88
89 mlir::Location loc;
90 mlir::Region &region;
91 /// Set of operations that form the elemental parts of the
92 /// expression evaluation. These are the hlfir.elemental and
93 /// hlfir.elemental_addr that form the elemental tree producing
94 /// the expression value. hlfir.elemental that produce values
95 /// used inside transformational operations are not part of this set.
96 llvm::SmallSet<mlir::Operation *, 4> elementalParts{};
97 /// Was generateNoneElementalPart called?
98 bool noneElementalPartWasGenerated = false;
99 /// Is this expression the mask expression of the outer where statement?
100 /// It is special because its evaluation is not masked by anything yet.
101 bool isOuterMaskExpr = false;
102 };
103 } // namespace
104
105 namespace {
106 /// Structure that visits an ordered assignment tree and generates code for
107 /// it according to a schedule.
108 class OrderedAssignmentRewriter {
109 public:
110 OrderedAssignmentRewriter(fir::FirOpBuilder &builder,
111 hlfir::OrderedAssignmentTreeOpInterface root)
112 : builder{builder}, root{root} {}
113
114 /// Generate code for the current run of the schedule.
115 void lowerRun(hlfir::Run &run) {
116 currentRun = &run;
117 walk(root);
118 currentRun = nullptr;
119 assert(constructStack.empty() && "must exit constructs after a run");
120 mapper.clear();
121 savedInCurrentRunBeforeUse.clear();
122 }
123
124 /// After all run have been lowered, clean-up all the temporary
125 /// storage that were created (do not call final routines).
126 void cleanupSavedEntities() {
127 for (auto &temp : savedEntities)
128 temp.second.destroy(root.getLoc(), builder);
129 }
130
131 /// Lowered value for an expression, and the original hlfir.yield if any
132 /// clean-up needs to be cloned after usage.
133 using ValueAndCleanUp = std::pair<mlir::Value, std::optional<hlfir::YieldOp>>;
134
135 private:
136 /// Walk the part of an order assignment tree node that needs
137 /// to be evaluated in the current run.
138 void walk(hlfir::OrderedAssignmentTreeOpInterface node);
139
140 /// Generate code when entering a given ordered assignment node.
141 void pre(hlfir::ForallOp forallOp);
142 void pre(hlfir::ForallIndexOp);
143 void pre(hlfir::ForallMaskOp);
144 void pre(hlfir::WhereOp whereOp);
145 void pre(hlfir::ElseWhereOp elseWhereOp);
146 void pre(hlfir::RegionAssignOp);
147
148 /// Generate code when leaving a given ordered assignment node.
149 void post(hlfir::ForallOp);
150 void post(hlfir::ForallMaskOp);
151 void post(hlfir::WhereOp);
152 void post(hlfir::ElseWhereOp);
153 /// Enter (and maybe create) the fir.if else block of an ElseWhereOp,
154 /// but do not generate the elswhere mask or the new fir.if.
155 void enterElsewhere(hlfir::ElseWhereOp);
156
157 /// Are there any leaf region in the node that must be saved in the current
158 /// run?
159 bool mustSaveRegionIn(
160 hlfir::OrderedAssignmentTreeOpInterface node,
161 llvm::SmallVectorImpl<hlfir::SaveEntity> &saveEntities) const;
162 /// Should this node be evaluated in the current run? Saving a region in a
163 /// node does not imply the node needs to be evaluated.
164 bool
165 isRequiredInCurrentRun(hlfir::OrderedAssignmentTreeOpInterface node) const;
166
167 /// Generate a scalar value yielded by an ordered assignment tree region.
168 /// If the value was not saved in a previous run, this clone the region
169 /// code, except the final yield, at the current execution point.
170 /// If the value was saved in a previous run, this fetches the saved value
171 /// from the temporary storage and returns the value.
172 /// Inside Forall, the value will be hoisted outside of the forall loops if
173 /// it does not depend on the forall indices.
174 /// An optional type can be provided to get a value from a specific type
175 /// (the cast will be hoisted if the computation is hoisted).
176 mlir::Value generateYieldedScalarValue(
177 mlir::Region &region,
178 std::optional<mlir::Type> castToType = std::nullopt);
179
180 /// Generate an entity yielded by an ordered assignment tree region, and
181 /// optionally return the (uncloned) yield if there is any clean-up that
182 /// should be done after using the entity. Like, generateYieldedScalarValue,
183 /// this will return the saved value if the region was saved in a previous
184 /// run.
185 ValueAndCleanUp
186 generateYieldedEntity(mlir::Region &region,
187 std::optional<mlir::Type> castToType = std::nullopt);
188
189 struct LhsValueAndCleanUp {
190 mlir::Value lhs;
191 std::optional<hlfir::YieldOp> elementalCleanup;
192 mlir::Region *nonElementalCleanup = nullptr;
193 std::optional<hlfir::LoopNest> vectorSubscriptLoopNest;
194 std::optional<mlir::Value> vectorSubscriptShape;
195 };
196
197 /// Generate the left-hand side. If the left-hand side is vector
198 /// subscripted (hlfir.elemental_addr), this will create a loop nest
199 /// (unless it was already created by a WHERE mask) and return the
200 /// element address.
201 LhsValueAndCleanUp
202 generateYieldedLHS(mlir::Location loc, mlir::Region &lhsRegion,
203 std::optional<hlfir::Entity> loweredRhs = std::nullopt);
204
205 /// If \p maybeYield is present and has a clean-up, generate the clean-up
206 /// at the current insertion point (by cloning).
207 void generateCleanupIfAny(std::optional<hlfir::YieldOp> maybeYield);
208 void generateCleanupIfAny(mlir::Region *cleanupRegion);
209
210 /// Generate a masked entity. This can only be called when whereLoopNest was
211 /// set (When an hlfir.where is being visited).
212 /// This method returns the scalar element (that may have been previously
213 /// saved) for the current indices inside the where loop.
214 mlir::Value generateMaskedEntity(mlir::Location loc, mlir::Region &region) {
215 MaskedArrayExpr maskedExpr(loc, region, /*isOuterMaskExpr=*/!whereLoopNest);
216 return generateMaskedEntity(maskedExpr);
217 }
218 mlir::Value generateMaskedEntity(MaskedArrayExpr &maskedExpr);
219
220 /// Create a fir.if at the current position inside the where loop nest
221 /// given the element value of a mask.
222 void generateMaskIfOp(mlir::Value cdt);
223
224 /// Save a value for subsequent runs.
225 void generateSaveEntity(hlfir::SaveEntity savedEntity,
226 bool willUseSavedEntityInSameRun);
227 void saveLeftHandSide(hlfir::SaveEntity savedEntity,
228 hlfir::RegionAssignOp regionAssignOp);
229
230 /// Get a value if it was saved in this run or a previous run. Returns
231 /// nullopt if it has not been saved.
232 std::optional<ValueAndCleanUp> getIfSaved(mlir::Region &region);
233
234 /// Generate code before the loop nest for the current run, if any.
235 void doBeforeLoopNest(const std::function<void()> &callback) {
236 if (constructStack.empty()) {
237 callback();
238 return;
239 }
240 auto insertionPoint = builder.saveInsertionPoint();
241 builder.setInsertionPoint(constructStack[0]);
242 callback();
243 builder.restoreInsertionPoint(insertionPoint);
244 }
245
246 /// Can the current loop nest iteration number be computed? For simplicity,
247 /// this is true if and only if all the bounds and steps of the fir.do_loop
248 /// nest dominates the outer loop. The argument is filled with the current
249 /// loop nest on success.
250 bool currentLoopNestIterationNumberCanBeComputed(
251 llvm::SmallVectorImpl<fir::DoLoopOp> &loopNest);
252
253 template <typename T>
254 fir::factory::TemporaryStorage *insertSavedEntity(mlir::Region &region,
255 T &&temp) {
256 auto inserted =
257 savedEntities.insert(std::make_pair(&region, std::forward<T>(temp)));
258 assert(inserted.second && "temp must have been emplaced");
259 return &inserted.first->second;
260 }
261
262 fir::FirOpBuilder &builder;
263
264 /// Map containing the mapping between the original order assignment tree
265 /// operations and the operations that have been cloned in the current run.
266 /// It is reset between two runs.
267 mlir::IRMapping mapper;
268 /// Dominance info is used to determine if inner loop bounds are all computed
269 /// before outer loop for the current loop. It does not need to be reset
270 /// between runs.
271 mlir::DominanceInfo dominanceInfo;
272 /// Construct stack in the current run. This allows setting back the insertion
273 /// point correctly when leaving a node that requires a fir.do_loop or fir.if
274 /// operation.
275 llvm::SmallVector<mlir::Operation *> constructStack;
276 /// Current where loop nest, if any.
277 std::optional<hlfir::LoopNest> whereLoopNest;
278
279 /// Map of temporary storage to keep track of saved entity once the run
280 /// that saves them has been lowered. It is kept in-between runs.
281 /// llvm::MapVector is used to guarantee deterministic order
282 /// of iterating through savedEntities (e.g. for generating
283 /// destruction code for the temporary storages).
284 llvm::MapVector<mlir::Region *, fir::factory::TemporaryStorage> savedEntities;
285 /// Map holding the values that were saved in the current run and that also
286 /// need to be used (because their construct will be visited). It is reset
287 /// after each run. It avoids having to store and fetch in the temporary
288 /// during the same run, which would require the temporary to have different
289 /// fetching and storing counters.
290 llvm::DenseMap<mlir::Region *, ValueAndCleanUp> savedInCurrentRunBeforeUse;
291
292 /// Root of the order assignment tree being lowered.
293 hlfir::OrderedAssignmentTreeOpInterface root;
294 /// Pointer to the current run of the schedule being lowered.
295 hlfir::Run *currentRun = nullptr;
296
297 /// When allocating temporary storage inlined, indicate if the storage should
298 /// be heap or stack allocated. Temporary allocated with the runtime are heap
299 /// allocated by the runtime.
300 bool allocateOnHeap = true;
301 };
302 } // namespace
303
304 void OrderedAssignmentRewriter::walk(
305 hlfir::OrderedAssignmentTreeOpInterface node) {
306 bool mustVisit =
307 isRequiredInCurrentRun(node) || mlir::isa<hlfir::ForallIndexOp>(node);
308 llvm::SmallVector<hlfir::SaveEntity> saveEntities;
309 mlir::Operation *nodeOp = node.getOperation();
310 if (mustSaveRegionIn(node, saveEntities)) {
311 mlir::IRRewriter::InsertPoint insertionPoint;
312 if (auto elseWhereOp = mlir::dyn_cast<hlfir::ElseWhereOp>(nodeOp)) {
313 // ElseWhere mask to save must be evaluated inside the fir.if else
314 // for the previous where/elsewehere (its evaluation must be
315 // masked by the "pending control mask").
316 insertionPoint = builder.saveInsertionPoint();
317 enterElsewhere(elseWhereOp);
318 }
319 for (hlfir::SaveEntity saveEntity : saveEntities)
320 generateSaveEntity(saveEntity, mustVisit);
321 if (insertionPoint.isSet())
322 builder.restoreInsertionPoint(insertionPoint);
323 }
324 if (mustVisit) {
325 llvm::TypeSwitch<mlir::Operation *, void>(nodeOp)
326 .Case<hlfir::ForallOp, hlfir::ForallIndexOp, hlfir::ForallMaskOp,
327 hlfir::RegionAssignOp, hlfir::WhereOp, hlfir::ElseWhereOp>(
328 [&](auto concreteOp) { pre(concreteOp); })
329 .Default([](auto) {});
330 if (auto *body = node.getSubTreeRegion()) {
331 for (mlir::Operation &op : body->getOps())
332 if (auto subNode =
333 mlir::dyn_cast<hlfir::OrderedAssignmentTreeOpInterface>(op))
334 walk(subNode);
335 llvm::TypeSwitch<mlir::Operation *, void>(nodeOp)
336 .Case<hlfir::ForallOp, hlfir::ForallMaskOp, hlfir::WhereOp,
337 hlfir::ElseWhereOp>([&](auto concreteOp) { post(concreteOp); })
338 .Default([](auto) {});
339 }
340 }
341 }
342
343 void OrderedAssignmentRewriter::pre(hlfir::ForallOp forallOp) {
344 /// Create a fir.do_loop given the hlfir.forall control values.
345 mlir::Type idxTy = builder.getIndexType();
346 mlir::Location loc = forallOp.getLoc();
347 mlir::Value lb = generateYieldedScalarValue(forallOp.getLbRegion(), idxTy);
348 mlir::Value ub = generateYieldedScalarValue(forallOp.getUbRegion(), idxTy);
349 mlir::Value step;
350 if (forallOp.getStepRegion().empty()) {
351 auto insertionPoint = builder.saveInsertionPoint();
352 if (!constructStack.empty())
353 builder.setInsertionPoint(constructStack[0]);
354 step = builder.createIntegerConstant(loc, idxTy, 1);
355 if (!constructStack.empty())
356 builder.restoreInsertionPoint(insertionPoint);
357 } else {
358 step = generateYieldedScalarValue(forallOp.getStepRegion(), idxTy);
359 }
360 auto doLoop = builder.create<fir::DoLoopOp>(loc, lb, ub, step);
361 builder.setInsertionPointToStart(doLoop.getBody());
362 mlir::Value oldIndex = forallOp.getForallIndexValue();
363 mlir::Value newIndex =
364 builder.createConvert(loc, oldIndex.getType(), doLoop.getInductionVar());
365 mapper.map(oldIndex, newIndex);
366 constructStack.push_back(doLoop);
367 }
368
369 void OrderedAssignmentRewriter::post(hlfir::ForallOp) {
370 assert(!constructStack.empty() && "must contain a loop");
371 builder.setInsertionPointAfter(constructStack.pop_back_val());
372 }
373
374 void OrderedAssignmentRewriter::pre(hlfir::ForallIndexOp forallIndexOp) {
375 mlir::Location loc = forallIndexOp.getLoc();
376 mlir::Type intTy = fir::unwrapRefType(forallIndexOp.getType());
377 mlir::Value indexVar =
378 builder.createTemporary(loc, intTy, forallIndexOp.getName());
379 mlir::Value newVal = mapper.lookupOrDefault(forallIndexOp.getIndex());
380 builder.createStoreWithConvert(loc, newVal, indexVar);
381 mapper.map(forallIndexOp, indexVar);
382 }
383
384 void OrderedAssignmentRewriter::pre(hlfir::ForallMaskOp forallMaskOp) {
385 mlir::Location loc = forallMaskOp.getLoc();
386 mlir::Value mask = generateYieldedScalarValue(forallMaskOp.getMaskRegion(),
387 builder.getI1Type());
388 auto ifOp = builder.create<fir::IfOp>(loc, std::nullopt, mask, false);
389 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
390 constructStack.push_back(ifOp);
391 }
392
393 void OrderedAssignmentRewriter::post(hlfir::ForallMaskOp forallMaskOp) {
394 assert(!constructStack.empty() && "must contain an ifop");
395 builder.setInsertionPointAfter(constructStack.pop_back_val());
396 }
397
398 /// Convert an entity to the type of a given mold.
399 /// This is intended to help with cases where hlfir entity is a value while
400 /// it must be used as a variable or vice-versa. These mismatches may occur
401 /// between the type of user defined assignment block arguments and the actual
402 /// argument that was lowered for them. The actual may be an in-memory copy
403 /// while the block argument expects an hlfir.expr.
404 static hlfir::Entity
405 convertToMoldType(mlir::Location loc, fir::FirOpBuilder &builder,
406 hlfir::Entity input, hlfir::Entity mold,
407 llvm::SmallVectorImpl<hlfir::CleanupFunction> &cleanups) {
408 if (input.getType() == mold.getType())
409 return input;
410 fir::FirOpBuilder *b = &builder;
411 if (input.isVariable() && mold.isValue()) {
412 if (fir::isa_trivial(mold.getType())) {
413 // fir.ref<T> to T.
414 mlir::Value load = builder.create<fir::LoadOp>(loc, input);
415 return hlfir::Entity{builder.createConvert(loc, mold.getType(), load)};
416 }
417 // fir.ref<T> to hlfir.expr<T>.
418 mlir::Value asExpr = builder.create<hlfir::AsExprOp>(loc, input);
419 if (asExpr.getType() != mold.getType())
420 TODO(loc, "hlfir.expr conversion");
421 cleanups.emplace_back([=]() { b->create<hlfir::DestroyOp>(loc, asExpr); });
422 return hlfir::Entity{asExpr};
423 }
424 if (input.isValue() && mold.isVariable()) {
425 // T to fir.ref<T>, or hlfir.expr<T> to fir.ref<T>.
426 hlfir::AssociateOp associate = hlfir::genAssociateExpr(
427 loc, builder, input, mold.getFortranElementType(), ".tmp.val2ref");
428 cleanups.emplace_back(
429 [=]() { b->create<hlfir::EndAssociateOp>(loc, associate); });
430 return hlfir::Entity{associate.getBase()};
431 }
432 // Variable to Variable mismatch (e.g., fir.heap<T> vs fir.ref<T>), or value
433 // to Value mismatch (e.g. i1 vs fir.logical<4>).
434 if (mlir::isa<fir::BaseBoxType>(mold.getType()) &&
435 !mlir::isa<fir::BaseBoxType>(input.getType())) {
436 // An entity may have have been saved without descriptor while the original
437 // value had a descriptor (e.g., it was not contiguous).
438 auto emboxed = hlfir::convertToBox(loc, builder, input, mold.getType());
439 assert(!emboxed.second && "temp should already be in memory");
440 input = hlfir::Entity{fir::getBase(emboxed.first)};
441 }
442 return hlfir::Entity{builder.createConvert(loc, mold.getType(), input)};
443 }
444
445 void OrderedAssignmentRewriter::pre(hlfir::RegionAssignOp regionAssignOp) {
446 mlir::Location loc = regionAssignOp.getLoc();
447 std::optional<hlfir::LoopNest> elementalLoopNest;
448 auto [rhsValue, oldRhsYield] =
449 generateYieldedEntity(regionAssignOp.getRhsRegion());
450 hlfir::Entity rhsEntity{rhsValue};
451 LhsValueAndCleanUp loweredLhs =
452 generateYieldedLHS(loc, regionAssignOp.getLhsRegion(), rhsEntity);
453 hlfir::Entity lhsEntity{loweredLhs.lhs};
454 if (loweredLhs.vectorSubscriptLoopNest)
455 rhsEntity = hlfir::getElementAt(
456 loc, builder, rhsEntity,
457 loweredLhs.vectorSubscriptLoopNest->oneBasedIndices);
458 if (!regionAssignOp.getUserDefinedAssignment().empty()) {
459 hlfir::Entity userAssignLhs{regionAssignOp.getUserAssignmentLhs()};
460 hlfir::Entity userAssignRhs{regionAssignOp.getUserAssignmentRhs()};
461 std::optional<hlfir::LoopNest> elementalLoopNest;
462 if (lhsEntity.isArray() && userAssignLhs.isScalar()) {
463 // Elemental assignment with array argument (the RHS cannot be an array
464 // if the LHS is not).
465 mlir::Value shape = hlfir::genShape(loc, builder, lhsEntity);
466 elementalLoopNest = hlfir::genLoopNest(loc, builder, shape);
467 builder.setInsertionPointToStart(elementalLoopNest->innerLoop.getBody());
468 lhsEntity = hlfir::getElementAt(loc, builder, lhsEntity,
469 elementalLoopNest->oneBasedIndices);
470 rhsEntity = hlfir::getElementAt(loc, builder, rhsEntity,
471 elementalLoopNest->oneBasedIndices);
472 }
473
474 llvm::SmallVector<hlfir::CleanupFunction, 2> argConversionCleanups;
475 lhsEntity = convertToMoldType(loc, builder, lhsEntity, userAssignLhs,
476 argConversionCleanups);
477 rhsEntity = convertToMoldType(loc, builder, rhsEntity, userAssignRhs,
478 argConversionCleanups);
479 mapper.map(userAssignLhs, lhsEntity);
480 mapper.map(userAssignRhs, rhsEntity);
481 for (auto &op :
482 regionAssignOp.getUserDefinedAssignment().front().without_terminator())
483 (void)builder.clone(op, mapper);
484 for (auto &cleanupConversion : argConversionCleanups)
485 cleanupConversion();
486 if (elementalLoopNest)
487 builder.setInsertionPointAfter(elementalLoopNest->outerLoop);
488 } else {
489 // TODO: preserve allocatable assignment aspects for forall once
490 // they are conveyed in hlfir.region_assign.
491 builder.create<hlfir::AssignOp>(loc, rhsEntity, lhsEntity);
492 }
493 generateCleanupIfAny(loweredLhs.elementalCleanup);
494 if (loweredLhs.vectorSubscriptLoopNest)
495 builder.setInsertionPointAfter(
496 loweredLhs.vectorSubscriptLoopNest->outerLoop);
497 generateCleanupIfAny(oldRhsYield);
498 generateCleanupIfAny(loweredLhs.nonElementalCleanup);
499 }
500
501 void OrderedAssignmentRewriter::generateMaskIfOp(mlir::Value cdt) {
502 mlir::Location loc = cdt.getLoc();
503 cdt = hlfir::loadTrivialScalar(loc, builder, hlfir::Entity{cdt});
504 cdt = builder.createConvert(loc, builder.getI1Type(), cdt);
505 auto ifOp = builder.create<fir::IfOp>(cdt.getLoc(), std::nullopt, cdt,
506 /*withElseRegion=*/false);
507 constructStack.push_back(ifOp.getOperation());
508 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
509 }
510
511 void OrderedAssignmentRewriter::pre(hlfir::WhereOp whereOp) {
512 mlir::Location loc = whereOp.getLoc();
513 if (!whereLoopNest) {
514 // This is the top-level WHERE. Start a loop nest iterating on the shape of
515 // the where mask.
516 if (auto maybeSaved = getIfSaved(whereOp.getMaskRegion())) {
517 // Use the saved value to get the shape and condition element.
518 hlfir::Entity savedMask{maybeSaved->first};
519 mlir::Value shape = hlfir::genShape(loc, builder, savedMask);
520 whereLoopNest = hlfir::genLoopNest(loc, builder, shape);
521 constructStack.push_back(whereLoopNest->outerLoop.getOperation());
522 builder.setInsertionPointToStart(whereLoopNest->innerLoop.getBody());
523 mlir::Value cdt = hlfir::getElementAt(loc, builder, savedMask,
524 whereLoopNest->oneBasedIndices);
525 generateMaskIfOp(cdt);
526 if (maybeSaved->second) {
527 // If this is the same run as the one that saved the value, the clean-up
528 // was left-over to be done now.
529 auto insertionPoint = builder.saveInsertionPoint();
530 builder.setInsertionPointAfter(whereLoopNest->outerLoop);
531 generateCleanupIfAny(maybeSaved->second);
532 builder.restoreInsertionPoint(insertionPoint);
533 }
534 return;
535 }
536 // The mask was not evaluated yet or can be safely re-evaluated.
537 MaskedArrayExpr mask(loc, whereOp.getMaskRegion(),
538 /*isOuterMaskExpr=*/true);
539 mask.generateNoneElementalPart(builder, mapper);
540 mlir::Value shape = mask.generateShape(builder, mapper);
541 whereLoopNest = hlfir::genLoopNest(loc, builder, shape);
542 constructStack.push_back(whereLoopNest->outerLoop.getOperation());
543 builder.setInsertionPointToStart(whereLoopNest->innerLoop.getBody());
544 mlir::Value cdt = generateMaskedEntity(mask);
545 generateMaskIfOp(cdt);
546 return;
547 }
548 // Where Loops have been already created by a parent WHERE.
549 // Generate a fir.if with the value of the current element of the mask
550 // inside the loops. The case where the mask was saved is handled in the
551 // generateYieldedScalarValue call.
552 mlir::Value cdt = generateYieldedScalarValue(whereOp.getMaskRegion());
553 generateMaskIfOp(cdt);
554 }
555
556 void OrderedAssignmentRewriter::post(hlfir::WhereOp whereOp) {
557 assert(!constructStack.empty() && "must contain a fir.if");
558 builder.setInsertionPointAfter(constructStack.pop_back_val());
559 // If all where/elsewhere fir.if have been popped, this is the outer whereOp,
560 // and the where loop must be exited.
561 assert(!constructStack.empty() && "must contain a fir.do_loop or fir.if");
562 if (mlir::isa<fir::DoLoopOp>(constructStack.back())) {
563 builder.setInsertionPointAfter(constructStack.pop_back_val());
564 whereLoopNest.reset();
565 }
566 }
567
568 void OrderedAssignmentRewriter::enterElsewhere(hlfir::ElseWhereOp elseWhereOp) {
569 // Create an "else" region for the current where/elsewhere fir.if.
570 auto ifOp = mlir::dyn_cast<fir::IfOp>(constructStack.back());
571 assert(ifOp && "must be an if");
572 if (ifOp.getElseRegion().empty()) {
573 mlir::Location loc = elseWhereOp.getLoc();
574 builder.createBlock(&ifOp.getElseRegion());
575 auto end = builder.create<fir::ResultOp>(loc);
576 builder.setInsertionPoint(end);
577 } else {
578 builder.setInsertionPoint(&ifOp.getElseRegion().back().back());
579 }
580 }
581
582 void OrderedAssignmentRewriter::pre(hlfir::ElseWhereOp elseWhereOp) {
583 enterElsewhere(elseWhereOp);
584 if (elseWhereOp.getMaskRegion().empty())
585 return;
586 // Create new nested fir.if with elsewhere mask if any.
587 mlir::Value cdt = generateYieldedScalarValue(elseWhereOp.getMaskRegion());
588 generateMaskIfOp(cdt);
589 }
590
591 void OrderedAssignmentRewriter::post(hlfir::ElseWhereOp elseWhereOp) {
592 // Exit ifOp that was created for the elseWhereOp mask, if any.
593 if (elseWhereOp.getMaskRegion().empty())
594 return;
595 assert(!constructStack.empty() && "must contain a fir.if");
596 builder.setInsertionPointAfter(constructStack.pop_back_val());
597 }
598
599 /// Is this value a Forall index?
600 /// Forall index are block arguments of hlfir.forall body, or the result
601 /// of hlfir.forall_index.
602 static bool isForallIndex(mlir::Value value) {
603 if (auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(value)) {
604 if (mlir::Block *block = blockArg.getOwner())
605 return block->isEntryBlock() &&
606 mlir::isa_and_nonnull<hlfir::ForallOp>(block->getParentOp());
607 return false;
608 }
609 return value.getDefiningOp<hlfir::ForallIndexOp>();
610 }
611
612 static OrderedAssignmentRewriter::ValueAndCleanUp
613 castIfNeeded(mlir::Location loc, fir::FirOpBuilder &builder,
614 OrderedAssignmentRewriter::ValueAndCleanUp valueAndCleanUp,
615 std::optional<mlir::Type> castToType) {
616 if (!castToType.has_value())
617 return valueAndCleanUp;
618 mlir::Value cast =
619 builder.createConvert(loc, *castToType, valueAndCleanUp.first);
620 return {cast, valueAndCleanUp.second};
621 }
622
623 std::optional<OrderedAssignmentRewriter::ValueAndCleanUp>
624 OrderedAssignmentRewriter::getIfSaved(mlir::Region &region) {
625 mlir::Location loc = region.getParentOp()->getLoc();
626 // If the region was saved in the same run, use the value that was evaluated
627 // instead of fetching the temp, and do clean-up, if any, that were delayed.
628 // This is done to avoid requiring the temporary stack to have different
629 // fetching and storing counters, and also because it produces slightly better
630 // code.
631 if (auto savedInSameRun = savedInCurrentRunBeforeUse.find(&region);
632 savedInSameRun != savedInCurrentRunBeforeUse.end())
633 return savedInSameRun->second;
634 // If the region was saved in a previous run, fetch the saved value.
635 if (auto temp = savedEntities.find(&region); temp != savedEntities.end()) {
636 doBeforeLoopNest([&]() { temp->second.resetFetchPosition(loc, builder); });
637 return ValueAndCleanUp{temp->second.fetch(loc, builder), std::nullopt};
638 }
639 return std::nullopt;
640 }
641
642 static hlfir::YieldOp getYield(mlir::Region &region) {
643 auto yield = mlir::dyn_cast_or_null<hlfir::YieldOp>(
644 region.back().getOperations().back());
645 assert(yield && "region computing entities must end with a YieldOp");
646 return yield;
647 }
648
649 OrderedAssignmentRewriter::ValueAndCleanUp
650 OrderedAssignmentRewriter::generateYieldedEntity(
651 mlir::Region &region, std::optional<mlir::Type> castToType) {
652 mlir::Location loc = region.getParentOp()->getLoc();
653 if (auto maybeValueAndCleanUp = getIfSaved(region))
654 return castIfNeeded(loc, builder, *maybeValueAndCleanUp, castToType);
655 // Otherwise, evaluate the region now.
656
657 // Masked expression must not evaluate the elemental parts that are masked,
658 // they have custom code generation.
659 if (whereLoopNest.has_value()) {
660 mlir::Value maskedValue = generateMaskedEntity(loc, region);
661 return castIfNeeded(loc, builder, {maskedValue, std::nullopt}, castToType);
662 }
663
664 assert(region.hasOneBlock() && "region must contain one block");
665 auto oldYield = getYield(region);
666 mlir::Block::OpListType &ops = region.back().getOperations();
667
668 // Inside Forall, scalars that do not depend on forall indices can be hoisted
669 // here because their evaluation is required to only call pure procedures, and
670 // if they depend on a variable previously assigned to in a forall assignment,
671 // this assignment must have been scheduled in a previous run. Hoisting of
672 // scalars is done here to help creating simple temporary storage if needed.
673 // Inner forall bounds can often be hoisted, and this allows computing the
674 // total number of iterations to create temporary storages.
675 bool hoistComputation = false;
676 if (fir::isa_trivial(oldYield.getEntity().getType()) &&
677 !constructStack.empty()) {
678 hoistComputation = true;
679 for (mlir::Operation &op : ops)
680 if (llvm::any_of(op.getOperands(), [](mlir::Value value) {
681 return isForallIndex(value);
682 })) {
683 hoistComputation = false;
684 break;
685 }
686 }
687 auto insertionPoint = builder.saveInsertionPoint();
688 if (hoistComputation)
689 builder.setInsertionPoint(constructStack[0]);
690
691 // Clone all operations except the final hlfir.yield.
692 assert(!ops.empty() && "yield block cannot be empty");
693 auto end = ops.end();
694 for (auto opIt = ops.begin(); std::next(opIt) != end; ++opIt)
695 (void)builder.clone(*opIt, mapper);
696 // Get the value for the yielded entity, it may be the result of an operation
697 // that was cloned, or it may be the same as the previous value if the yield
698 // operand was created before the ordered assignment tree.
699 mlir::Value newEntity = mapper.lookupOrDefault(oldYield.getEntity());
700 if (castToType.has_value())
701 newEntity =
702 builder.createConvert(newEntity.getLoc(), *castToType, newEntity);
703
704 if (hoistComputation) {
705 // Hoisted trivial scalars clean-up can be done right away, the value is
706 // in registers.
707 generateCleanupIfAny(oldYield);
708 builder.restoreInsertionPoint(insertionPoint);
709 return {newEntity, std::nullopt};
710 }
711 if (oldYield.getCleanup().empty())
712 return {newEntity, std::nullopt};
713 return {newEntity, oldYield};
714 }
715
716 mlir::Value OrderedAssignmentRewriter::generateYieldedScalarValue(
717 mlir::Region &region, std::optional<mlir::Type> castToType) {
718 mlir::Location loc = region.getParentOp()->getLoc();
719 auto [value, maybeYield] = generateYieldedEntity(region, castToType);
720 value = hlfir::loadTrivialScalar(loc, builder, hlfir::Entity{value});
721 assert(fir::isa_trivial(value.getType()) && "not a trivial scalar value");
722 generateCleanupIfAny(maybeYield);
723 return value;
724 }
725
726 OrderedAssignmentRewriter::LhsValueAndCleanUp
727 OrderedAssignmentRewriter::generateYieldedLHS(
728 mlir::Location loc, mlir::Region &lhsRegion,
729 std::optional<hlfir::Entity> loweredRhs) {
730 LhsValueAndCleanUp loweredLhs;
731 hlfir::ElementalAddrOp elementalAddrLhs =
732 mlir::dyn_cast<hlfir::ElementalAddrOp>(lhsRegion.back().back());
733 if (auto temp = savedEntities.find(&lhsRegion); temp != savedEntities.end()) {
734 // The LHS address was computed and saved in a previous run. Fetch it.
735 doBeforeLoopNest([&]() { temp->second.resetFetchPosition(loc, builder); });
736 if (elementalAddrLhs && !whereLoopNest) {
737 // Vector subscripted designator address are saved element by element.
738 // If no "elemental" loops have been created yet, the shape of the
739 // RHS, if it is an array can be used, or the shape of the vector
740 // subscripted designator must be retrieved to generate the "elemental"
741 // loop nest.
742 if (loweredRhs && loweredRhs->isArray()) {
743 // The RHS shape can be used to create the elemental loops and avoid
744 // saving the LHS shape.
745 loweredLhs.vectorSubscriptShape =
746 hlfir::genShape(loc, builder, *loweredRhs);
747 } else {
748 // If the shape cannot be retrieved from the RHS, it must have been
749 // saved. Get it from the temporary.
750 auto &vectorTmp =
751 temp->second.cast<fir::factory::AnyVectorSubscriptStack>();
752 loweredLhs.vectorSubscriptShape = vectorTmp.fetchShape(loc, builder);
753 }
754 loweredLhs.vectorSubscriptLoopNest = hlfir::genLoopNest(
755 loc, builder, loweredLhs.vectorSubscriptShape.value());
756 builder.setInsertionPointToStart(
757 loweredLhs.vectorSubscriptLoopNest->innerLoop.getBody());
758 }
759 loweredLhs.lhs = temp->second.fetch(loc, builder);
760 return loweredLhs;
761 }
762 // The LHS has not yet been evaluated and saved. Evaluate it now.
763 if (elementalAddrLhs && !whereLoopNest) {
764 // This is a vector subscripted entity. The address of elements must
765 // be returned. If no "elemental" loops have been created for a WHERE,
766 // create them now based on the vector subscripted designator shape.
767 for (auto &op : lhsRegion.front().without_terminator())
768 (void)builder.clone(op, mapper);
769 loweredLhs.vectorSubscriptShape =
770 mapper.lookupOrDefault(elementalAddrLhs.getShape());
771 loweredLhs.vectorSubscriptLoopNest =
772 hlfir::genLoopNest(loc, builder, *loweredLhs.vectorSubscriptShape,
773 !elementalAddrLhs.isOrdered());
774 builder.setInsertionPointToStart(
775 loweredLhs.vectorSubscriptLoopNest->innerLoop.getBody());
776 mapper.map(elementalAddrLhs.getIndices(),
777 loweredLhs.vectorSubscriptLoopNest->oneBasedIndices);
778 for (auto &op : elementalAddrLhs.getBody().front().without_terminator())
779 (void)builder.clone(op, mapper);
780 loweredLhs.elementalCleanup = elementalAddrLhs.getYieldOp();
781 loweredLhs.lhs =
782 mapper.lookupOrDefault(loweredLhs.elementalCleanup->getEntity());
783 } else {
784 // This is a designator without vector subscripts. Generate it as
785 // it is done for other entities.
786 auto [lhs, yield] = generateYieldedEntity(lhsRegion);
787 loweredLhs.lhs = lhs;
788 if (yield && !yield->getCleanup().empty())
789 loweredLhs.nonElementalCleanup = &yield->getCleanup();
790 }
791 return loweredLhs;
792 }
793
794 mlir::Value
795 OrderedAssignmentRewriter::generateMaskedEntity(MaskedArrayExpr &maskedExpr) {
796 assert(whereLoopNest.has_value() && "must be inside WHERE loop nest");
797 auto insertionPoint = builder.saveInsertionPoint();
798 if (!maskedExpr.noneElementalPartWasGenerated) {
799 // Generate none elemental part before the where loops (but inside the
800 // current forall loops if any).
801 builder.setInsertionPoint(whereLoopNest->outerLoop);
802 maskedExpr.generateNoneElementalPart(builder, mapper);
803 }
804 // Generate the none elemental part cleanup after the where loops.
805 builder.setInsertionPointAfter(whereLoopNest->outerLoop);
806 maskedExpr.generateNoneElementalCleanupIfAny(builder, mapper);
807 // Generate the value of the current element for the masked expression
808 // at the current insertion point (inside the where loops, and any fir.if
809 // generated for previous masks).
810 builder.restoreInsertionPoint(insertionPoint);
811 mlir::Value scalar = maskedExpr.generateElementalParts(
812 builder, whereLoopNest->oneBasedIndices, mapper);
813 /// Generate cleanups for the elemental parts inside the loops (setting the
814 /// location so that the assignment will be generated before the cleanups).
815 if (!maskedExpr.isOuterMaskExpr)
816 if (mlir::Operation *firstCleanup =
817 maskedExpr.generateMaskedExprCleanUps(builder, mapper))
818 builder.setInsertionPoint(firstCleanup);
819 return scalar;
820 }
821
822 void OrderedAssignmentRewriter::generateCleanupIfAny(
823 std::optional<hlfir::YieldOp> maybeYield) {
824 if (maybeYield.has_value())
825 generateCleanupIfAny(&maybeYield->getCleanup());
826 }
827 void OrderedAssignmentRewriter::generateCleanupIfAny(
828 mlir::Region *cleanupRegion) {
829 if (cleanupRegion && !cleanupRegion->empty()) {
830 assert(cleanupRegion->hasOneBlock() && "region must contain one block");
831 for (auto &op : cleanupRegion->back().without_terminator())
832 builder.clone(op, mapper);
833 }
834 }
835
836 bool OrderedAssignmentRewriter::mustSaveRegionIn(
837 hlfir::OrderedAssignmentTreeOpInterface node,
838 llvm::SmallVectorImpl<hlfir::SaveEntity> &saveEntities) const {
839 for (auto &action : currentRun->actions)
840 if (hlfir::SaveEntity *savedEntity =
841 std::get_if<hlfir::SaveEntity>(&action))
842 if (node.getOperation() == savedEntity->yieldRegion->getParentOp())
843 saveEntities.push_back(*savedEntity);
844 return !saveEntities.empty();
845 }
846
847 bool OrderedAssignmentRewriter::isRequiredInCurrentRun(
848 hlfir::OrderedAssignmentTreeOpInterface node) const {
849 // hlfir.forall_index do not contain saved regions/assignments,
850 // but if their hlfir.forall parent was required, they are
851 // required (the forall indices needs to be mapped).
852 if (mlir::isa<hlfir::ForallIndexOp>(node))
853 return true;
854 for (auto &action : currentRun->actions)
855 if (hlfir::SaveEntity *savedEntity =
856 std::get_if<hlfir::SaveEntity>(&action)) {
857 // A SaveEntity action does not require evaluating the node that contains
858 // it, but it requires to evaluate all the parents of the nodes that
859 // contains it. For instance, an saving a bound in hlfir.forall B does not
860 // require creating the loops for B, but it requires creating the loops
861 // for any forall parent A of the forall B.
862 if (node->isProperAncestor(savedEntity->yieldRegion->getParentOp()))
863 return true;
864 } else {
865 auto assign = std::get<hlfir::RegionAssignOp>(action);
866 if (node->isAncestor(assign.getOperation()))
867 return true;
868 }
869 return false;
870 }
871
872 /// Is the apply using all the elemental indices in order?
873 static bool isInOrderApply(hlfir::ApplyOp apply,
874 hlfir::ElementalOpInterface elemental) {
875 mlir::Region::BlockArgListType elementalIndices = elemental.getIndices();
876 if (elementalIndices.size() != apply.getIndices().size())
877 return false;
878 for (auto [elementalIdx, applyIdx] :
879 llvm::zip(elementalIndices, apply.getIndices()))
880 if (elementalIdx != applyIdx)
881 return false;
882 return true;
883 }
884
885 /// Gather the tree of hlfir::ElementalOpInterface use-def, if any, starting
886 /// from \p elemental, which may be a nullptr.
887 static void
888 gatherElementalTree(hlfir::ElementalOpInterface elemental,
889 llvm::SmallPtrSetImpl<mlir::Operation *> &elementalOps,
890 bool isOutOfOrder) {
891 if (elemental) {
892 // Only inline an applied elemental that must be executed in order if the
893 // applying indices are in order. An hlfir::Elemental may have been created
894 // for a transformational like transpose, and Fortran 2018 standard
895 // section 10.2.3.2, point 10 imply that impure elemental sub-expression
896 // evaluations should not be masked if they are the arguments of
897 // transformational expressions.
898 if (isOutOfOrder && elemental.isOrdered())
899 return;
900 elementalOps.insert(elemental.getOperation());
901 for (mlir::Operation &op : elemental.getElementalRegion().getOps())
902 if (auto apply = mlir::dyn_cast<hlfir::ApplyOp>(op)) {
903 bool isUnorderedApply =
904 isOutOfOrder || !isInOrderApply(apply, elemental);
905 auto maybeElemental =
906 mlir::dyn_cast_or_null<hlfir::ElementalOpInterface>(
907 apply.getExpr().getDefiningOp());
908 gatherElementalTree(maybeElemental, elementalOps, isUnorderedApply);
909 }
910 }
911 }
912
913 MaskedArrayExpr::MaskedArrayExpr(mlir::Location loc, mlir::Region &region,
914 bool isOuterMaskExpr)
915 : loc{loc}, region{region}, isOuterMaskExpr{isOuterMaskExpr} {
916 mlir::Operation &terminator = region.back().back();
917 if (auto elementalAddr =
918 mlir::dyn_cast<hlfir::ElementalOpInterface>(terminator)) {
919 // Vector subscripted designator (hlfir.elemental_addr terminator).
920 gatherElementalTree(elementalAddr, elementalParts, /*isOutOfOrder=*/false);
921 return;
922 }
923 // Try if elemental expression.
924 mlir::Value entity = mlir::cast<hlfir::YieldOp>(terminator).getEntity();
925 auto maybeElemental = mlir::dyn_cast_or_null<hlfir::ElementalOpInterface>(
926 entity.getDefiningOp());
927 gatherElementalTree(maybeElemental, elementalParts, /*isOutOfOrder=*/false);
928 }
929
930 void MaskedArrayExpr::generateNoneElementalPart(fir::FirOpBuilder &builder,
931 mlir::IRMapping &mapper) {
932 assert(!noneElementalPartWasGenerated &&
933 "none elemental parts already generated");
934 if (isOuterMaskExpr) {
935 // The outer mask expression is actually not masked, it is dealt as
936 // such so that its elemental part, if any, can be inlined in the WHERE
937 // loops. But all of the operations outside of hlfir.elemental/
938 // hlfir.elemental_addr must be emitted now because their value may be
939 // required to deduce the mask shape and the WHERE loop bounds.
940 for (mlir::Operation &op : region.back().without_terminator())
941 if (!elementalParts.contains(&op))
942 (void)builder.clone(op, mapper);
943 } else {
944 // For actual masked expressions, Fortran requires elemental expressions,
945 // even the scalar ones that are not encoded with hlfir.elemental, to be
946 // evaluated only when the mask is true. Blindly hoisting all scalar SSA
947 // tree could be wrong if the scalar computation has side effects and
948 // would never have been evaluated (e.g. division by zero) if the mask
949 // is fully false. See F'2023 10.2.3.2 point 10.
950 // Clone only the bodies of all hlfir.exactly_once operations, which contain
951 // the evaluation of sub-expression tree whose root was a non elemental
952 // function call at the Fortran level (the call itself may have been inlined
953 // since). These must be evaluated only once as per F'2023 10.2.3.2 point 9.
954 for (mlir::Operation &op : region.back().without_terminator())
955 if (auto exactlyOnce = mlir::dyn_cast<hlfir::ExactlyOnceOp>(op)) {
956 for (mlir::Operation &subOp :
957 exactlyOnce.getBody().back().without_terminator())
958 (void)builder.clone(subOp, mapper);
959 mlir::Value oldYield = getYield(exactlyOnce.getBody()).getEntity();
960 auto newYield = mapper.lookupOrDefault(oldYield);
961 mapper.map(exactlyOnce.getResult(), newYield);
962 }
963 }
964 noneElementalPartWasGenerated = true;
965 }
966
967 mlir::Value MaskedArrayExpr::generateShape(fir::FirOpBuilder &builder,
968 mlir::IRMapping &mapper) {
969 assert(noneElementalPartWasGenerated &&
970 "non elemental part must have been generated");
971 mlir::Operation &terminator = region.back().back();
972 // If the operation that produced the yielded entity is elemental, it was not
973 // cloned, but it holds a shape argument that was cloned. Return the cloned
974 // shape.
975 if (auto elementalAddrOp = mlir::dyn_cast<hlfir::ElementalAddrOp>(terminator))
976 return mapper.lookupOrDefault(elementalAddrOp.getShape());
977 mlir::Value entity = mlir::cast<hlfir::YieldOp>(terminator).getEntity();
978 if (auto elemental = entity.getDefiningOp<hlfir::ElementalOp>())
979 return mapper.lookupOrDefault(elemental.getShape());
980 // Otherwise, the whole entity was cloned, and the shape can be generated
981 // from it.
982 hlfir::Entity clonedEntity{mapper.lookupOrDefault(entity)};
983 return hlfir::genShape(loc, builder, hlfir::Entity{clonedEntity});
984 }
985
986 mlir::Value
987 MaskedArrayExpr::generateElementalParts(fir::FirOpBuilder &builder,
988 mlir::ValueRange oneBasedIndices,
989 mlir::IRMapping &mapper) {
990 assert(noneElementalPartWasGenerated &&
991 "non elemental part must have been generated");
992 if (!isOuterMaskExpr) {
993 // Clone all operations that are not hlfir.exactly_once and that are not
994 // hlfir.elemental/hlfir.elemental_addr.
995 for (mlir::Operation &op : region.back().without_terminator())
996 if (!mlir::isa<hlfir::ExactlyOnceOp>(op) && !elementalParts.contains(&op))
997 (void)builder.clone(op, mapper);
998 // For the outer mask, this was already done outside of the loop.
999 }
1000 // Clone and "index" bodies of hlfir.elemental/hlfir.elemental_addr.
1001 mlir::Operation &terminator = region.back().back();
1002 hlfir::ElementalOpInterface elemental =
1003 mlir::dyn_cast<hlfir::ElementalAddrOp>(terminator);
1004 if (!elemental) {
1005 // If the terminator is not an hlfir.elemental_addr, try if the yielded
1006 // entity was produced by an hlfir.elemental.
1007 mlir::Value entity = mlir::cast<hlfir::YieldOp>(terminator).getEntity();
1008 elemental = entity.getDefiningOp<hlfir::ElementalOp>();
1009 if (!elemental) {
1010 // The yielded entity was not produced by an elemental operation,
1011 // get its clone in the non elemental part evaluation and address it.
1012 hlfir::Entity clonedEntity{mapper.lookupOrDefault(entity)};
1013 return hlfir::getElementAt(loc, builder, clonedEntity, oneBasedIndices);
1014 }
1015 }
1016
1017 auto mustRecursivelyInline =
1018 [&](hlfir::ElementalOp appliedElemental) -> bool {
1019 return elementalParts.contains(appliedElemental.getOperation());
1020 };
1021 return inlineElementalOp(loc, builder, elemental, oneBasedIndices, mapper,
1022 mustRecursivelyInline);
1023 }
1024
1025 mlir::Operation *
1026 MaskedArrayExpr::generateMaskedExprCleanUps(fir::FirOpBuilder &builder,
1027 mlir::IRMapping &mapper) {
1028 // Clone the clean-ups from the region itself, except for the destroy
1029 // of the hlfir.elemental that have been inlined.
1030 mlir::Operation &terminator = region.back().back();
1031 mlir::Region *cleanupRegion = nullptr;
1032 if (auto elementalAddr = mlir::dyn_cast<hlfir::ElementalAddrOp>(terminator)) {
1033 cleanupRegion = &elementalAddr.getCleanup();
1034 } else {
1035 auto yieldOp = mlir::cast<hlfir::YieldOp>(terminator);
1036 cleanupRegion = &yieldOp.getCleanup();
1037 }
1038 if (cleanupRegion->empty())
1039 return nullptr;
1040 mlir::Operation *firstNewCleanup = nullptr;
1041 for (mlir::Operation &op : cleanupRegion->front().without_terminator()) {
1042 if (auto destroy = mlir::dyn_cast<hlfir::DestroyOp>(op))
1043 if (elementalParts.contains(destroy.getExpr().getDefiningOp()))
1044 continue;
1045 mlir::Operation *cleanup = builder.clone(op, mapper);
1046 if (!firstNewCleanup)
1047 firstNewCleanup = cleanup;
1048 }
1049 return firstNewCleanup;
1050 }
1051
1052 void MaskedArrayExpr::generateNoneElementalCleanupIfAny(
1053 fir::FirOpBuilder &builder, mlir::IRMapping &mapper) {
1054 if (!isOuterMaskExpr) {
1055 // Clone clean-ups of hlfir.exactly_once operations (in reverse order
1056 // to properly deal with stack restores).
1057 for (mlir::Operation &op :
1058 llvm::reverse(region.back().without_terminator()))
1059 if (auto exactlyOnce = mlir::dyn_cast<hlfir::ExactlyOnceOp>(op)) {
1060 mlir::Region &cleanupRegion =
1061 getYield(exactlyOnce.getBody()).getCleanup();
1062 if (!cleanupRegion.empty())
1063 for (mlir::Operation &cleanupOp :
1064 cleanupRegion.front().without_terminator())
1065 (void)builder.clone(cleanupOp, mapper);
1066 }
1067 } else {
1068 // For the outer mask, the region clean-ups must be generated
1069 // outside of the loops since the mask non hlfir.elemental part
1070 // is generated before the loops.
1071 generateMaskedExprCleanUps(builder, mapper);
1072 }
1073 }
1074
1075 static hlfir::RegionAssignOp
1076 getAssignIfLeftHandSideRegion(mlir::Region &region) {
1077 auto assign = mlir::dyn_cast<hlfir::RegionAssignOp>(region.getParentOp());
1078 if (assign && (&assign.getLhsRegion() == &region))
1079 return assign;
1080 return nullptr;
1081 }
1082
1083 bool OrderedAssignmentRewriter::currentLoopNestIterationNumberCanBeComputed(
1084 llvm::SmallVectorImpl<fir::DoLoopOp> &loopNest) {
1085 if (constructStack.empty())
1086 return true;
1087 mlir::Operation *outerLoop = constructStack[0];
1088 mlir::Operation *currentConstruct = constructStack.back();
1089 // Loop through the loops until the outer construct is met, and test if the
1090 // loop operands dominate the outer construct.
1091 while (currentConstruct) {
1092 if (auto doLoop = mlir::dyn_cast<fir::DoLoopOp>(currentConstruct)) {
1093 if (llvm::any_of(doLoop->getOperands(), [&](mlir::Value value) {
1094 return !dominanceInfo.properlyDominates(value, outerLoop);
1095 })) {
1096 return false;
1097 }
1098 loopNest.push_back(doLoop);
1099 }
1100 if (currentConstruct == outerLoop)
1101 currentConstruct = nullptr;
1102 else
1103 currentConstruct = currentConstruct->getParentOp();
1104 }
1105 return true;
1106 }
1107
1108 static mlir::Value
1109 computeLoopNestIterationNumber(mlir::Location loc, fir::FirOpBuilder &builder,
1110 llvm::ArrayRef<fir::DoLoopOp> loopNest) {
1111 mlir::Value loopExtent;
1112 for (fir::DoLoopOp doLoop : loopNest) {
1113 mlir::Value extent = builder.genExtentFromTriplet(
1114 loc, doLoop.getLowerBound(), doLoop.getUpperBound(), doLoop.getStep(),
1115 builder.getIndexType());
1116 if (!loopExtent)
1117 loopExtent = extent;
1118 else
1119 loopExtent = builder.create<mlir::arith::MulIOp>(loc, loopExtent, extent);
1120 }
1121 assert(loopExtent && "loopNest must not be empty");
1122 return loopExtent;
1123 }
1124
1125 /// Return a name for temporary storage that indicates in which context
1126 /// the temporary storage was created.
1127 static llvm::StringRef
1128 getTempName(hlfir::OrderedAssignmentTreeOpInterface root) {
1129 if (mlir::isa<hlfir::ForallOp>(root.getOperation()))
1130 return ".tmp.forall";
1131 if (mlir::isa<hlfir::WhereOp>(root.getOperation()))
1132 return ".tmp.where";
1133 return ".tmp.assign";
1134 }
1135
1136 void OrderedAssignmentRewriter::generateSaveEntity(
1137 hlfir::SaveEntity savedEntity, bool willUseSavedEntityInSameRun) {
1138 mlir::Region &region = *savedEntity.yieldRegion;
1139
1140 if (hlfir::RegionAssignOp regionAssignOp =
1141 getAssignIfLeftHandSideRegion(region)) {
1142 // Need to save the address, not the values.
1143 assert(!willUseSavedEntityInSameRun &&
1144 "lhs cannot be used in the loop nest where it is saved");
1145 return saveLeftHandSide(savedEntity, regionAssignOp);
1146 }
1147
1148 mlir::Location loc = region.getParentOp()->getLoc();
1149 // Evaluate the region inside the loop nest (if any).
1150 auto [clonedValue, oldYield] = generateYieldedEntity(region);
1151 hlfir::Entity entity{clonedValue};
1152 entity = hlfir::loadTrivialScalar(loc, builder, entity);
1153 mlir::Type entityType = entity.getType();
1154
1155 llvm::StringRef tempName = getTempName(root);
1156 fir::factory::TemporaryStorage *temp = nullptr;
1157 if (constructStack.empty()) {
1158 // Value evaluated outside of any loops (this may be the first MASK of a
1159 // WHERE construct, or an LHS/RHS temp of hlfir.region_assign outside of
1160 // WHERE/FORALL).
1161 temp = insertSavedEntity(
1162 region, fir::factory::SimpleCopy(loc, builder, entity, tempName));
1163 } else {
1164 // Need to create a temporary for values computed inside loops.
1165 // Create temporary storage outside of the loop nest given the entity
1166 // type (and the loop context).
1167 llvm::SmallVector<fir::DoLoopOp> loopNest;
1168 bool loopShapeCanBePreComputed =
1169 currentLoopNestIterationNumberCanBeComputed(loopNest);
1170 doBeforeLoopNest([&] {
1171 /// For simple scalars inside loops whose total iteration number can be
1172 /// pre-computed, create a rank-1 array outside of the loops. It will be
1173 /// assigned/fetched inside the loops like a normal Fortran array given
1174 /// the iteration count.
1175 if (loopShapeCanBePreComputed && fir::isa_trivial(entityType)) {
1176 mlir::Value loopExtent =
1177 computeLoopNestIterationNumber(loc, builder, loopNest);
1178 auto sequenceType =
1179 mlir::cast<fir::SequenceType>(builder.getVarLenSeqTy(entityType));
1180 temp = insertSavedEntity(region,
1181 fir::factory::HomogeneousScalarStack{
1182 loc, builder, sequenceType, loopExtent,
1183 /*lenParams=*/{}, allocateOnHeap,
1184 /*stackThroughLoops=*/true, tempName});
1185
1186 } else {
1187 // If the number of iteration is not known, or if the values at each
1188 // iterations are values that may have different shape, type parameters
1189 // or dynamic type, use the runtime to create and manage a stack-like
1190 // temporary.
1191 temp = insertSavedEntity(
1192 region, fir::factory::AnyValueStack{loc, builder, entityType});
1193 }
1194 });
1195 // Inside the loop nest (and any fir.if if there are active masks), copy
1196 // the value to the temp and do clean-ups for the value if any.
1197 temp->pushValue(loc, builder, entity);
1198 }
1199
1200 // Delay the clean-up if the entity will be used in the same run (i.e., the
1201 // parent construct will be visited and needs to be lowered). When possible,
1202 // this is not done for hlfir.expr because this use would prevent the
1203 // hlfir.expr storage from being moved when creating the temporary in
1204 // bufferization, and that would lead to an extra copy.
1205 if (willUseSavedEntityInSameRun &&
1206 (!temp->canBeFetchedAfterPush() ||
1207 !mlir::isa<hlfir::ExprType>(entity.getType()))) {
1208 auto inserted =
1209 savedInCurrentRunBeforeUse.try_emplace(&region, entity, oldYield);
1210 assert(inserted.second && "entity must have been emplaced");
1211 (void)inserted;
1212 } else {
1213 if (constructStack.empty() &&
1214 mlir::isa<hlfir::RegionAssignOp>(region.getParentOp())) {
1215 // Here the clean-up code is inserted after the original
1216 // RegionAssignOp, so that the assignment code happens
1217 // before the cleanup. We do this only for standalone
1218 // operations, because the clean-up is handled specially
1219 // during lowering of the parent constructs if any
1220 // (e.g. see generateNoneElementalCleanupIfAny for
1221 // WhereOp).
1222 auto insertionPoint = builder.saveInsertionPoint();
1223 builder.setInsertionPointAfter(region.getParentOp());
1224 generateCleanupIfAny(oldYield);
1225 builder.restoreInsertionPoint(insertionPoint);
1226 } else {
1227 generateCleanupIfAny(oldYield);
1228 }
1229 }
1230 }
1231
1232 static bool rhsIsArray(hlfir::RegionAssignOp regionAssignOp) {
1233 auto yieldOp = mlir::dyn_cast<hlfir::YieldOp>(
1234 regionAssignOp.getRhsRegion().back().back());
1235 return yieldOp && hlfir::Entity{yieldOp.getEntity()}.isArray();
1236 }
1237
1238 void OrderedAssignmentRewriter::saveLeftHandSide(
1239 hlfir::SaveEntity savedEntity, hlfir::RegionAssignOp regionAssignOp) {
1240 mlir::Region &region = *savedEntity.yieldRegion;
1241 mlir::Location loc = region.getParentOp()->getLoc();
1242 LhsValueAndCleanUp loweredLhs = generateYieldedLHS(loc, region);
1243 fir::factory::TemporaryStorage *temp = nullptr;
1244 if (loweredLhs.vectorSubscriptLoopNest)
1245 constructStack.push_back(loweredLhs.vectorSubscriptLoopNest->outerLoop);
1246 if (loweredLhs.vectorSubscriptLoopNest && !rhsIsArray(regionAssignOp)) {
1247 // Vector subscripted entity for which the shape must also be saved on top
1248 // of the element addresses (e.g. the shape may change in each forall
1249 // iteration and is needed to create the elemental loops).
1250 mlir::Value shape = loweredLhs.vectorSubscriptShape.value();
1251 int rank = mlir::cast<fir::ShapeType>(shape.getType()).getRank();
1252 const bool shapeIsInvariant =
1253 constructStack.empty() ||
1254 dominanceInfo.properlyDominates(shape, constructStack[0]);
1255 doBeforeLoopNest([&] {
1256 // Outside of any forall/where/elemental loops, create a temporary that
1257 // will both be able to save the vector subscripted designator shape(s)
1258 // and element addresses.
1259 temp =
1260 insertSavedEntity(region, fir::factory::AnyVectorSubscriptStack{
1261 loc, builder, loweredLhs.lhs.getType(),
1262 shapeIsInvariant, rank});
1263 });
1264 // Save shape before the elemental loop nest created by the vector
1265 // subscripted LHS.
1266 auto &vectorTmp = temp->cast<fir::factory::AnyVectorSubscriptStack>();
1267 auto insertionPoint = builder.saveInsertionPoint();
1268 builder.setInsertionPoint(loweredLhs.vectorSubscriptLoopNest->outerLoop);
1269 vectorTmp.pushShape(loc, builder, shape);
1270 builder.restoreInsertionPoint(insertionPoint);
1271 } else {
1272 // Otherwise, only save the LHS address.
1273 // If the LHS address dominates the constructs, its SSA value can
1274 // simply be tracked and there is no need to save the address in memory.
1275 // Otherwise, the addresses are stored at each iteration in memory with
1276 // a descriptor stack.
1277 if (constructStack.empty() ||
1278 dominanceInfo.properlyDominates(loweredLhs.lhs, constructStack[0]))
1279 doBeforeLoopNest([&] {
1280 temp = insertSavedEntity(region, fir::factory::SSARegister{});
1281 });
1282 else
1283 doBeforeLoopNest([&] {
1284 temp = insertSavedEntity(
1285 region, fir::factory::AnyVariableStack{loc, builder,
1286 loweredLhs.lhs.getType()});
1287 });
1288 }
1289 temp->pushValue(loc, builder, loweredLhs.lhs);
1290 generateCleanupIfAny(loweredLhs.elementalCleanup);
1291 if (loweredLhs.vectorSubscriptLoopNest) {
1292 constructStack.pop_back();
1293 builder.setInsertionPointAfter(
1294 loweredLhs.vectorSubscriptLoopNest->outerLoop);
1295 }
1296 }
1297
1298 /// Lower an ordered assignment tree to fir.do_loop and hlfir.assign given
1299 /// a schedule.
1300 static void lower(hlfir::OrderedAssignmentTreeOpInterface root,
1301 mlir::PatternRewriter &rewriter, hlfir::Schedule &schedule) {
1302 auto module = root->getParentOfType<mlir::ModuleOp>();
1303 fir::FirOpBuilder builder(rewriter, module);
1304 OrderedAssignmentRewriter assignmentRewriter(builder, root);
1305 for (auto &run : schedule)
1306 assignmentRewriter.lowerRun(run);
1307 assignmentRewriter.cleanupSavedEntities();
1308 }
1309
1310 /// Shared rewrite entry point for all the ordered assignment tree root
1311 /// operations. It calls the scheduler and then apply the schedule.
1312 static llvm::LogicalResult rewrite(hlfir::OrderedAssignmentTreeOpInterface root,
1313 bool tryFusingAssignments,
1314 mlir::PatternRewriter &rewriter) {
1315 hlfir::Schedule schedule =
1316 hlfir::buildEvaluationSchedule(root, tryFusingAssignments);
1317
1318 LLVM_DEBUG(
1319 /// Debug option to print the scheduling debug info without doing
1320 /// any code generation. The operations are simply erased to avoid
1321 /// failing and calling the rewrite patterns on nested operations.
1322 /// The only purpose of this is to help testing scheduling without
1323 /// having to test generated code.
1324 if (dbgScheduleOnly) {
1325 rewriter.eraseOp(root);
1326 return mlir::success();
1327 });
1328 lower(root, rewriter, schedule);
1329 rewriter.eraseOp(root);
1330 return mlir::success();
1331 }
1332
1333 namespace {
1334
1335 class ForallOpConversion : public mlir::OpRewritePattern<hlfir::ForallOp> {
1336 public:
1337 explicit ForallOpConversion(mlir::MLIRContext *ctx, bool tryFusingAssignments)
1338 : OpRewritePattern{ctx}, tryFusingAssignments{tryFusingAssignments} {}
1339
1340 llvm::LogicalResult
1341 matchAndRewrite(hlfir::ForallOp forallOp,
1342 mlir::PatternRewriter &rewriter) const override {
1343 auto root = mlir::cast<hlfir::OrderedAssignmentTreeOpInterface>(
1344 forallOp.getOperation());
1345 if (mlir::failed(::rewrite(root, tryFusingAssignments, rewriter)))
1346 TODO(forallOp.getLoc(), "FORALL construct or statement in HLFIR");
1347 return mlir::success();
1348 }
1349 const bool tryFusingAssignments;
1350 };
1351
1352 class WhereOpConversion : public mlir::OpRewritePattern<hlfir::WhereOp> {
1353 public:
1354 explicit WhereOpConversion(mlir::MLIRContext *ctx, bool tryFusingAssignments)
1355 : OpRewritePattern{ctx}, tryFusingAssignments{tryFusingAssignments} {}
1356
1357 llvm::LogicalResult
1358 matchAndRewrite(hlfir::WhereOp whereOp,
1359 mlir::PatternRewriter &rewriter) const override {
1360 auto root = mlir::cast<hlfir::OrderedAssignmentTreeOpInterface>(
1361 whereOp.getOperation());
1362 return ::rewrite(root, tryFusingAssignments, rewriter);
1363 }
1364 const bool tryFusingAssignments;
1365 };
1366
1367 class RegionAssignConversion
1368 : public mlir::OpRewritePattern<hlfir::RegionAssignOp> {
1369 public:
1370 explicit RegionAssignConversion(mlir::MLIRContext *ctx)
1371 : OpRewritePattern{ctx} {}
1372
1373 llvm::LogicalResult
1374 matchAndRewrite(hlfir::RegionAssignOp regionAssignOp,
1375 mlir::PatternRewriter &rewriter) const override {
1376 auto root = mlir::cast<hlfir::OrderedAssignmentTreeOpInterface>(
1377 regionAssignOp.getOperation());
1378 return ::rewrite(root, /*tryFusingAssignments=*/false, rewriter);
1379 }
1380 };
1381
1382 class LowerHLFIROrderedAssignments
1383 : public hlfir::impl::LowerHLFIROrderedAssignmentsBase<
1384 LowerHLFIROrderedAssignments> {
1385 public:
1386 using LowerHLFIROrderedAssignmentsBase<
1387 LowerHLFIROrderedAssignments>::LowerHLFIROrderedAssignmentsBase;
1388
1389 void runOnOperation() override {
1390 // Running on a ModuleOp because this pass may generate FuncOp declaration
1391 // for runtime calls. This could be a FuncOp pass otherwise.
1392 auto module = this->getOperation();
1393 auto *context = &getContext();
1394 mlir::RewritePatternSet patterns(context);
1395 // Patterns are only defined for the OrderedAssignmentTreeOpInterface
1396 // operations that can be the root of ordered assignments. The other
1397 // operations will be taken care of while rewriting these trees (they
1398 // cannot exist outside of these operations given their verifiers/traits).
1399 patterns.insert<ForallOpConversion, WhereOpConversion>(
1400 context, this->tryFusingAssignments.getValue());
1401 patterns.insert<RegionAssignConversion>(context);
1402 mlir::ConversionTarget target(*context);
1403 target.markUnknownOpDynamicallyLegal([](mlir::Operation *op) {
1404 return !mlir::isa<hlfir::OrderedAssignmentTreeOpInterface>(op);
1405 });
1406 if (mlir::failed(mlir::applyPartialConversion(module, target,
1407 std::move(patterns)))) {
1408 mlir::emitError(mlir::UnknownLoc::get(context),
1409 "failure in HLFIR ordered assignments lowering pass");
1410 signalPassFailure();
1411 }
1412 }
1413 };
1414 } // namespace