1 //===-- AffinePromotion.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This transformation is a prototype that promote FIR loops operations
10 // to affine dialect operations.
11 // It is not part of the production pipeline and would need more work in order
12 // to be used in production.
13 // More information can be found in this presentation:
14 // https://slides.com/rajanwalia/deck
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "PassDetail.h"
19 #include "flang/Optimizer/Dialect/FIRDialect.h"
20 #include "flang/Optimizer/Dialect/FIROps.h"
21 #include "flang/Optimizer/Dialect/FIRType.h"
22 #include "flang/Optimizer/Transforms/Passes.h"
23 #include "mlir/Dialect/Affine/IR/AffineOps.h"
24 #include "mlir/Dialect/SCF/SCF.h"
25 #include "mlir/Dialect/StandardOps/IR/Ops.h"
26 #include "mlir/IR/BuiltinAttributes.h"
27 #include "mlir/IR/IntegerSet.h"
28 #include "mlir/IR/Visitors.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/Support/Debug.h"
33 
34 #define DEBUG_TYPE "flang-affine-promotion"
35 
36 using namespace fir;
37 
38 namespace {
39 struct AffineLoopAnalysis;
40 struct AffineIfAnalysis;
41 
42 /// Stores analysis objects for all loops and if operations inside a function
43 /// these analysis are used twice, first for marking operations for rewrite and
44 /// second when doing rewrite.
45 struct AffineFunctionAnalysis {
46   explicit AffineFunctionAnalysis(mlir::FuncOp funcOp) {
47     for (fir::DoLoopOp op : funcOp.getOps<fir::DoLoopOp>())
48       loopAnalysisMap.try_emplace(op, op, *this);
49   }
50 
51   AffineLoopAnalysis getChildLoopAnalysis(fir::DoLoopOp op) const;
52 
53   AffineIfAnalysis getChildIfAnalysis(fir::IfOp op) const;
54 
55   llvm::DenseMap<mlir::Operation *, AffineLoopAnalysis> loopAnalysisMap;
56   llvm::DenseMap<mlir::Operation *, AffineIfAnalysis> ifAnalysisMap;
57 };
58 } // namespace
59 
60 static bool analyzeCoordinate(mlir::Value coordinate, mlir::Operation *op) {
61   if (auto blockArg = coordinate.dyn_cast<mlir::BlockArgument>()) {
62     if (isa<fir::DoLoopOp>(blockArg.getOwner()->getParentOp()))
63       return true;
64     LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: array coordinate is not a "
65                                "loop induction variable (owner not loopOp)\n";
66                op->dump());
67     return false;
68   }
69   LLVM_DEBUG(
70       llvm::dbgs() << "AffineLoopAnalysis: array coordinate is not a loop "
71                       "induction variable (not a block argument)\n";
72       op->dump(); coordinate.getDefiningOp()->dump());
73   return false;
74 }
75 
76 namespace {
77 struct AffineLoopAnalysis {
78   AffineLoopAnalysis() = default;
79 
80   explicit AffineLoopAnalysis(fir::DoLoopOp op, AffineFunctionAnalysis &afa)
81       : legality(analyzeLoop(op, afa)) {}
82 
83   bool canPromoteToAffine() { return legality; }
84 
85 private:
86   bool analyzeBody(fir::DoLoopOp loopOperation,
87                    AffineFunctionAnalysis &functionAnalysis) {
88     for (auto loopOp : loopOperation.getOps<fir::DoLoopOp>()) {
89       auto analysis = functionAnalysis.loopAnalysisMap
90                           .try_emplace(loopOp, loopOp, functionAnalysis)
91                           .first->getSecond();
92       if (!analysis.canPromoteToAffine())
93         return false;
94     }
95     for (auto ifOp : loopOperation.getOps<fir::IfOp>())
96       functionAnalysis.ifAnalysisMap.try_emplace(ifOp, ifOp, functionAnalysis);
97     return true;
98   }
99 
100   bool analyzeLoop(fir::DoLoopOp loopOperation,
101                    AffineFunctionAnalysis &functionAnalysis) {
102     LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: \n"; loopOperation.dump(););
103     return analyzeMemoryAccess(loopOperation) &&
104            analyzeBody(loopOperation, functionAnalysis);
105   }
106 
107   bool analyzeReference(mlir::Value memref, mlir::Operation *op) {
108     if (auto acoOp = memref.getDefiningOp<ArrayCoorOp>()) {
109       if (acoOp.memref().getType().isa<fir::BoxType>()) {
110         // TODO: Look if and how fir.box can be promoted to affine.
111         LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: cannot promote loop, "
112                                    "array memory operation uses fir.box\n";
113                    op->dump(); acoOp.dump(););
114         return false;
115       }
116       bool canPromote = true;
117       for (auto coordinate : acoOp.indices())
118         canPromote = canPromote && analyzeCoordinate(coordinate, op);
119       return canPromote;
120     }
121     if (auto coOp = memref.getDefiningOp<CoordinateOp>()) {
122       LLVM_DEBUG(llvm::dbgs()
123                      << "AffineLoopAnalysis: cannot promote loop, "
124                         "array memory operation uses non ArrayCoorOp\n";
125                  op->dump(); coOp.dump(););
126 
127       return false;
128     }
129     LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: unknown type of memory "
130                                "reference for array load\n";
131                op->dump(););
132     return false;
133   }
134 
135   bool analyzeMemoryAccess(fir::DoLoopOp loopOperation) {
136     for (auto loadOp : loopOperation.getOps<fir::LoadOp>())
137       if (!analyzeReference(loadOp.memref(), loadOp))
138         return false;
139     for (auto storeOp : loopOperation.getOps<fir::StoreOp>())
140       if (!analyzeReference(storeOp.memref(), storeOp))
141         return false;
142     return true;
143   }
144 
145   bool legality{};
146 };
147 } // namespace
148 
149 AffineLoopAnalysis
150 AffineFunctionAnalysis::getChildLoopAnalysis(fir::DoLoopOp op) const {
151   auto it = loopAnalysisMap.find_as(op);
152   if (it == loopAnalysisMap.end()) {
153     LLVM_DEBUG(llvm::dbgs() << "AffineFunctionAnalysis: not computed for:\n";
154                op.dump(););
155     op.emitError("error in fetching loop analysis in AffineFunctionAnalysis\n");
156     return {};
157   }
158   return it->getSecond();
159 }
160 
161 namespace {
162 /// Calculates arguments for creating an IntegerSet. symCount, dimCount are the
163 /// final number of symbols and dimensions of the affine map. Integer set if
164 /// possible is in Optional IntegerSet.
165 struct AffineIfCondition {
166   using MaybeAffineExpr = llvm::Optional<mlir::AffineExpr>;
167 
168   explicit AffineIfCondition(mlir::Value fc) : firCondition(fc) {
169     if (auto condDef = firCondition.getDefiningOp<mlir::arith::CmpIOp>())
170       fromCmpIOp(condDef);
171   }
172 
173   bool hasIntegerSet() const { return integerSet.hasValue(); }
174 
175   mlir::IntegerSet getIntegerSet() const {
176     assert(hasIntegerSet() && "integer set is missing");
177     return integerSet.getValue();
178   }
179 
180   mlir::ValueRange getAffineArgs() const { return affineArgs; }
181 
182 private:
183   MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, mlir::Value lhs,
184                                  mlir::Value rhs) {
185     return affineBinaryOp(kind, toAffineExpr(lhs), toAffineExpr(rhs));
186   }
187 
188   MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, MaybeAffineExpr lhs,
189                                  MaybeAffineExpr rhs) {
190     if (lhs.hasValue() && rhs.hasValue())
191       return mlir::getAffineBinaryOpExpr(kind, lhs.getValue(), rhs.getValue());
192     return {};
193   }
194 
195   MaybeAffineExpr toAffineExpr(MaybeAffineExpr e) { return e; }
196 
197   MaybeAffineExpr toAffineExpr(int64_t value) {
198     return {mlir::getAffineConstantExpr(value, firCondition.getContext())};
199   }
200 
201   /// Returns an AffineExpr if it is a result of operations that can be done
202   /// in an affine expression, this includes -, +, *, rem, constant.
203   /// block arguments of a loopOp or forOp are used as dimensions
204   MaybeAffineExpr toAffineExpr(mlir::Value value) {
205     if (auto op = value.getDefiningOp<mlir::arith::SubIOp>())
206       return affineBinaryOp(
207           mlir::AffineExprKind::Add, toAffineExpr(op.getLhs()),
208           affineBinaryOp(mlir::AffineExprKind::Mul, toAffineExpr(op.getRhs()),
209                          toAffineExpr(-1)));
210     if (auto op = value.getDefiningOp<mlir::arith::AddIOp>())
211       return affineBinaryOp(mlir::AffineExprKind::Add, op.getLhs(),
212                             op.getRhs());
213     if (auto op = value.getDefiningOp<mlir::arith::MulIOp>())
214       return affineBinaryOp(mlir::AffineExprKind::Mul, op.getLhs(),
215                             op.getRhs());
216     if (auto op = value.getDefiningOp<mlir::arith::RemUIOp>())
217       return affineBinaryOp(mlir::AffineExprKind::Mod, op.getLhs(),
218                             op.getRhs());
219     if (auto op = value.getDefiningOp<mlir::arith::ConstantOp>())
220       if (auto intConstant = op.getValue().dyn_cast<IntegerAttr>())
221         return toAffineExpr(intConstant.getInt());
222     if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) {
223       affineArgs.push_back(value);
224       if (isa<fir::DoLoopOp>(blockArg.getOwner()->getParentOp()) ||
225           isa<mlir::AffineForOp>(blockArg.getOwner()->getParentOp()))
226         return {mlir::getAffineDimExpr(dimCount++, value.getContext())};
227       return {mlir::getAffineSymbolExpr(symCount++, value.getContext())};
228     }
229     return {};
230   }
231 
232   void fromCmpIOp(mlir::arith::CmpIOp cmpOp) {
233     auto lhsAffine = toAffineExpr(cmpOp.getLhs());
234     auto rhsAffine = toAffineExpr(cmpOp.getRhs());
235     if (!lhsAffine.hasValue() || !rhsAffine.hasValue())
236       return;
237     auto constraintPair = constraint(
238         cmpOp.getPredicate(), rhsAffine.getValue() - lhsAffine.getValue());
239     if (!constraintPair)
240       return;
241     integerSet = mlir::IntegerSet::get(dimCount, symCount,
242                                        {constraintPair.getValue().first},
243                                        {constraintPair.getValue().second});
244     return;
245   }
246 
247   llvm::Optional<std::pair<AffineExpr, bool>>
248   constraint(mlir::arith::CmpIPredicate predicate, mlir::AffineExpr basic) {
249     switch (predicate) {
250     case mlir::arith::CmpIPredicate::slt:
251       return {std::make_pair(basic - 1, false)};
252     case mlir::arith::CmpIPredicate::sle:
253       return {std::make_pair(basic, false)};
254     case mlir::arith::CmpIPredicate::sgt:
255       return {std::make_pair(1 - basic, false)};
256     case mlir::arith::CmpIPredicate::sge:
257       return {std::make_pair(0 - basic, false)};
258     case mlir::arith::CmpIPredicate::eq:
259       return {std::make_pair(basic, true)};
260     default:
261       return {};
262     }
263   }
264 
265   llvm::SmallVector<mlir::Value> affineArgs;
266   llvm::Optional<mlir::IntegerSet> integerSet;
267   mlir::Value firCondition;
268   unsigned symCount{0u};
269   unsigned dimCount{0u};
270 };
271 } // namespace
272 
273 namespace {
274 /// Analysis for affine promotion of fir.if
275 struct AffineIfAnalysis {
276   AffineIfAnalysis() = default;
277 
278   explicit AffineIfAnalysis(fir::IfOp op, AffineFunctionAnalysis &afa)
279       : legality(analyzeIf(op, afa)) {}
280 
281   bool canPromoteToAffine() { return legality; }
282 
283 private:
284   bool analyzeIf(fir::IfOp op, AffineFunctionAnalysis &afa) {
285     if (op.getNumResults() == 0)
286       return true;
287     LLVM_DEBUG(llvm::dbgs()
288                    << "AffineIfAnalysis: not promoting as op has results\n";);
289     return false;
290   }
291 
292   bool legality{};
293 };
294 } // namespace
295 
296 AffineIfAnalysis
297 AffineFunctionAnalysis::getChildIfAnalysis(fir::IfOp op) const {
298   auto it = ifAnalysisMap.find_as(op);
299   if (it == ifAnalysisMap.end()) {
300     LLVM_DEBUG(llvm::dbgs() << "AffineFunctionAnalysis: not computed for:\n";
301                op.dump(););
302     op.emitError("error in fetching if analysis in AffineFunctionAnalysis\n");
303     return {};
304   }
305   return it->getSecond();
306 }
307 
308 /// AffineMap rewriting fir.array_coor operation to affine apply,
309 /// %dim = fir.gendim %lowerBound, %upperBound, %stride
310 /// %a = fir.array_coor %arr(%dim) %i
311 /// returning affineMap = affine_map<(i)[lb, ub, st] -> (i*st - lb)>
312 static mlir::AffineMap createArrayIndexAffineMap(unsigned dimensions,
313                                                  MLIRContext *context) {
314   auto index = mlir::getAffineConstantExpr(0, context);
315   auto accuExtent = mlir::getAffineConstantExpr(1, context);
316   for (unsigned i = 0; i < dimensions; ++i) {
317     mlir::AffineExpr idx = mlir::getAffineDimExpr(i, context),
318                      lowerBound = mlir::getAffineSymbolExpr(i * 3, context),
319                      currentExtent =
320                          mlir::getAffineSymbolExpr(i * 3 + 1, context),
321                      stride = mlir::getAffineSymbolExpr(i * 3 + 2, context),
322                      currentPart = (idx * stride - lowerBound) * accuExtent;
323     index = currentPart + index;
324     accuExtent = accuExtent * currentExtent;
325   }
326   return mlir::AffineMap::get(dimensions, dimensions * 3, index);
327 }
328 
329 static Optional<int64_t> constantIntegerLike(const mlir::Value value) {
330   if (auto definition = value.getDefiningOp<mlir::arith::ConstantOp>())
331     if (auto stepAttr = definition.getValue().dyn_cast<IntegerAttr>())
332       return stepAttr.getInt();
333   return {};
334 }
335 
336 static mlir::Type coordinateArrayElement(fir::ArrayCoorOp op) {
337   if (auto refType = op.memref().getType().dyn_cast_or_null<ReferenceType>()) {
338     if (auto seqType = refType.getEleTy().dyn_cast_or_null<SequenceType>()) {
339       return seqType.getEleTy();
340     }
341   }
342   op.emitError(
343       "AffineLoopConversion: array type in coordinate operation not valid\n");
344   return mlir::Type();
345 }
346 
347 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::ShapeOp shape,
348                               SmallVectorImpl<mlir::Value> &indexArgs,
349                               mlir::PatternRewriter &rewriter) {
350   auto one = rewriter.create<mlir::arith::ConstantOp>(
351       acoOp.getLoc(), rewriter.getIndexType(), rewriter.getIndexAttr(1));
352   auto extents = shape.extents();
353   for (auto i = extents.begin(); i < extents.end(); i++) {
354     indexArgs.push_back(one);
355     indexArgs.push_back(*i);
356     indexArgs.push_back(one);
357   }
358 }
359 
360 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::ShapeShiftOp shape,
361                               SmallVectorImpl<mlir::Value> &indexArgs,
362                               mlir::PatternRewriter &rewriter) {
363   auto one = rewriter.create<mlir::arith::ConstantOp>(
364       acoOp.getLoc(), rewriter.getIndexType(), rewriter.getIndexAttr(1));
365   auto extents = shape.pairs();
366   for (auto i = extents.begin(); i < extents.end();) {
367     indexArgs.push_back(*i++);
368     indexArgs.push_back(*i++);
369     indexArgs.push_back(one);
370   }
371 }
372 
373 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::SliceOp slice,
374                               SmallVectorImpl<mlir::Value> &indexArgs,
375                               mlir::PatternRewriter &rewriter) {
376   auto extents = slice.triples();
377   for (auto i = extents.begin(); i < extents.end();) {
378     indexArgs.push_back(*i++);
379     indexArgs.push_back(*i++);
380     indexArgs.push_back(*i++);
381   }
382 }
383 
384 static void populateIndexArgs(fir::ArrayCoorOp acoOp,
385                               SmallVectorImpl<mlir::Value> &indexArgs,
386                               mlir::PatternRewriter &rewriter) {
387   if (auto shape = acoOp.shape().getDefiningOp<ShapeOp>())
388     return populateIndexArgs(acoOp, shape, indexArgs, rewriter);
389   if (auto shapeShift = acoOp.shape().getDefiningOp<ShapeShiftOp>())
390     return populateIndexArgs(acoOp, shapeShift, indexArgs, rewriter);
391   if (auto slice = acoOp.shape().getDefiningOp<SliceOp>())
392     return populateIndexArgs(acoOp, slice, indexArgs, rewriter);
393   return;
394 }
395 
396 /// Returns affine.apply and fir.convert from array_coor and gendims
397 static std::pair<mlir::AffineApplyOp, fir::ConvertOp>
398 createAffineOps(mlir::Value arrayRef, mlir::PatternRewriter &rewriter) {
399   auto acoOp = arrayRef.getDefiningOp<ArrayCoorOp>();
400   auto affineMap =
401       createArrayIndexAffineMap(acoOp.indices().size(), acoOp.getContext());
402   SmallVector<mlir::Value> indexArgs;
403   indexArgs.append(acoOp.indices().begin(), acoOp.indices().end());
404 
405   populateIndexArgs(acoOp, indexArgs, rewriter);
406 
407   auto affineApply = rewriter.create<mlir::AffineApplyOp>(acoOp.getLoc(),
408                                                           affineMap, indexArgs);
409   auto arrayElementType = coordinateArrayElement(acoOp);
410   auto newType = mlir::MemRefType::get({-1}, arrayElementType);
411   auto arrayConvert =
412       rewriter.create<fir::ConvertOp>(acoOp.getLoc(), newType, acoOp.memref());
413   return std::make_pair(affineApply, arrayConvert);
414 }
415 
416 static void rewriteLoad(fir::LoadOp loadOp, mlir::PatternRewriter &rewriter) {
417   rewriter.setInsertionPoint(loadOp);
418   auto affineOps = createAffineOps(loadOp.memref(), rewriter);
419   rewriter.replaceOpWithNewOp<mlir::AffineLoadOp>(
420       loadOp, affineOps.second.getResult(), affineOps.first.getResult());
421 }
422 
423 static void rewriteStore(fir::StoreOp storeOp,
424                          mlir::PatternRewriter &rewriter) {
425   rewriter.setInsertionPoint(storeOp);
426   auto affineOps = createAffineOps(storeOp.memref(), rewriter);
427   rewriter.replaceOpWithNewOp<mlir::AffineStoreOp>(storeOp, storeOp.value(),
428                                                    affineOps.second.getResult(),
429                                                    affineOps.first.getResult());
430 }
431 
432 static void rewriteMemoryOps(Block *block, mlir::PatternRewriter &rewriter) {
433   for (auto &bodyOp : block->getOperations()) {
434     if (isa<fir::LoadOp>(bodyOp))
435       rewriteLoad(cast<fir::LoadOp>(bodyOp), rewriter);
436     if (isa<fir::StoreOp>(bodyOp))
437       rewriteStore(cast<fir::StoreOp>(bodyOp), rewriter);
438   }
439 }
440 
441 namespace {
442 /// Convert `fir.do_loop` to `affine.for`, creates fir.convert for arrays to
443 /// memref, rewrites array_coor to affine.apply with affine_map. Rewrites fir
444 /// loads and stores to affine.
445 class AffineLoopConversion : public mlir::OpRewritePattern<fir::DoLoopOp> {
446 public:
447   using OpRewritePattern::OpRewritePattern;
448   AffineLoopConversion(mlir::MLIRContext *context, AffineFunctionAnalysis &afa)
449       : OpRewritePattern(context), functionAnalysis(afa) {}
450 
451   mlir::LogicalResult
452   matchAndRewrite(fir::DoLoopOp loop,
453                   mlir::PatternRewriter &rewriter) const override {
454     LLVM_DEBUG(llvm::dbgs() << "AffineLoopConversion: rewriting loop:\n";
455                loop.dump(););
456     LLVM_ATTRIBUTE_UNUSED auto loopAnalysis =
457         functionAnalysis.getChildLoopAnalysis(loop);
458     auto &loopOps = loop.getBody()->getOperations();
459     auto loopAndIndex = createAffineFor(loop, rewriter);
460     auto affineFor = loopAndIndex.first;
461     auto inductionVar = loopAndIndex.second;
462 
463     rewriter.startRootUpdate(affineFor.getOperation());
464     affineFor.getBody()->getOperations().splice(
465         std::prev(affineFor.getBody()->end()), loopOps, loopOps.begin(),
466         std::prev(loopOps.end()));
467     rewriter.finalizeRootUpdate(affineFor.getOperation());
468 
469     rewriter.startRootUpdate(loop.getOperation());
470     loop.getInductionVar().replaceAllUsesWith(inductionVar);
471     rewriter.finalizeRootUpdate(loop.getOperation());
472 
473     rewriteMemoryOps(affineFor.getBody(), rewriter);
474 
475     LLVM_DEBUG(llvm::dbgs() << "AffineLoopConversion: loop rewriten to:\n";
476                affineFor.dump(););
477     rewriter.replaceOp(loop, affineFor.getOperation()->getResults());
478     return success();
479   }
480 
481 private:
482   std::pair<mlir::AffineForOp, mlir::Value>
483   createAffineFor(fir::DoLoopOp op, mlir::PatternRewriter &rewriter) const {
484     if (auto constantStep = constantIntegerLike(op.step()))
485       if (constantStep.getValue() > 0)
486         return positiveConstantStep(op, constantStep.getValue(), rewriter);
487     return genericBounds(op, rewriter);
488   }
489 
490   // when step for the loop is positive compile time constant
491   std::pair<mlir::AffineForOp, mlir::Value>
492   positiveConstantStep(fir::DoLoopOp op, int64_t step,
493                        mlir::PatternRewriter &rewriter) const {
494     auto affineFor = rewriter.create<mlir::AffineForOp>(
495         op.getLoc(), ValueRange(op.lowerBound()),
496         mlir::AffineMap::get(0, 1,
497                              mlir::getAffineSymbolExpr(0, op.getContext())),
498         ValueRange(op.upperBound()),
499         mlir::AffineMap::get(0, 1,
500                              1 + mlir::getAffineSymbolExpr(0, op.getContext())),
501         step);
502     return std::make_pair(affineFor, affineFor.getInductionVar());
503   }
504 
505   std::pair<mlir::AffineForOp, mlir::Value>
506   genericBounds(fir::DoLoopOp op, mlir::PatternRewriter &rewriter) const {
507     auto lowerBound = mlir::getAffineSymbolExpr(0, op.getContext());
508     auto upperBound = mlir::getAffineSymbolExpr(1, op.getContext());
509     auto step = mlir::getAffineSymbolExpr(2, op.getContext());
510     mlir::AffineMap upperBoundMap = mlir::AffineMap::get(
511         0, 3, (upperBound - lowerBound + step).floorDiv(step));
512     auto genericUpperBound = rewriter.create<mlir::AffineApplyOp>(
513         op.getLoc(), upperBoundMap,
514         ValueRange({op.lowerBound(), op.upperBound(), op.step()}));
515     auto actualIndexMap = mlir::AffineMap::get(
516         1, 2,
517         (lowerBound + mlir::getAffineDimExpr(0, op.getContext())) *
518             mlir::getAffineSymbolExpr(1, op.getContext()));
519 
520     auto affineFor = rewriter.create<mlir::AffineForOp>(
521         op.getLoc(), ValueRange(),
522         AffineMap::getConstantMap(0, op.getContext()),
523         genericUpperBound.getResult(),
524         mlir::AffineMap::get(0, 1,
525                              1 + mlir::getAffineSymbolExpr(0, op.getContext())),
526         1);
527     rewriter.setInsertionPointToStart(affineFor.getBody());
528     auto actualIndex = rewriter.create<mlir::AffineApplyOp>(
529         op.getLoc(), actualIndexMap,
530         ValueRange({affineFor.getInductionVar(), op.lowerBound(), op.step()}));
531     return std::make_pair(affineFor, actualIndex.getResult());
532   }
533 
534   AffineFunctionAnalysis &functionAnalysis;
535 };
536 
537 /// Convert `fir.if` to `affine.if`.
538 class AffineIfConversion : public mlir::OpRewritePattern<fir::IfOp> {
539 public:
540   using OpRewritePattern::OpRewritePattern;
541   AffineIfConversion(mlir::MLIRContext *context, AffineFunctionAnalysis &afa)
542       : OpRewritePattern(context) {}
543   mlir::LogicalResult
544   matchAndRewrite(fir::IfOp op,
545                   mlir::PatternRewriter &rewriter) const override {
546     LLVM_DEBUG(llvm::dbgs() << "AffineIfConversion: rewriting if:\n";
547                op.dump(););
548     auto &ifOps = op.thenRegion().front().getOperations();
549     auto affineCondition = AffineIfCondition(op.condition());
550     if (!affineCondition.hasIntegerSet()) {
551       LLVM_DEBUG(
552           llvm::dbgs()
553               << "AffineIfConversion: couldn't calculate affine condition\n";);
554       return failure();
555     }
556     auto affineIf = rewriter.create<mlir::AffineIfOp>(
557         op.getLoc(), affineCondition.getIntegerSet(),
558         affineCondition.getAffineArgs(), !op.elseRegion().empty());
559     rewriter.startRootUpdate(affineIf);
560     affineIf.getThenBlock()->getOperations().splice(
561         std::prev(affineIf.getThenBlock()->end()), ifOps, ifOps.begin(),
562         std::prev(ifOps.end()));
563     if (!op.elseRegion().empty()) {
564       auto &otherOps = op.elseRegion().front().getOperations();
565       affineIf.getElseBlock()->getOperations().splice(
566           std::prev(affineIf.getElseBlock()->end()), otherOps, otherOps.begin(),
567           std::prev(otherOps.end()));
568     }
569     rewriter.finalizeRootUpdate(affineIf);
570     rewriteMemoryOps(affineIf.getBody(), rewriter);
571 
572     LLVM_DEBUG(llvm::dbgs() << "AffineIfConversion: if converted to:\n";
573                affineIf.dump(););
574     rewriter.replaceOp(op, affineIf.getOperation()->getResults());
575     return success();
576   }
577 };
578 
579 /// Promote fir.do_loop and fir.if to affine.for and affine.if, in the cases
580 /// where such a promotion is possible.
581 class AffineDialectPromotion
582     : public AffineDialectPromotionBase<AffineDialectPromotion> {
583 public:
584   void runOnFunction() override {
585 
586     auto *context = &getContext();
587     auto function = getFunction();
588     markAllAnalysesPreserved();
589     auto functionAnalysis = AffineFunctionAnalysis(function);
590     mlir::OwningRewritePatternList patterns(context);
591     patterns.insert<AffineIfConversion>(context, functionAnalysis);
592     patterns.insert<AffineLoopConversion>(context, functionAnalysis);
593     mlir::ConversionTarget target = *context;
594     target.addLegalDialect<
595         mlir::AffineDialect, FIROpsDialect, mlir::scf::SCFDialect,
596         mlir::arith::ArithmeticDialect, mlir::StandardOpsDialect>();
597     target.addDynamicallyLegalOp<IfOp>([&functionAnalysis](fir::IfOp op) {
598       return !(functionAnalysis.getChildIfAnalysis(op).canPromoteToAffine());
599     });
600     target.addDynamicallyLegalOp<DoLoopOp>([&functionAnalysis](
601                                                fir::DoLoopOp op) {
602       return !(functionAnalysis.getChildLoopAnalysis(op).canPromoteToAffine());
603     });
604 
605     LLVM_DEBUG(llvm::dbgs()
606                    << "AffineDialectPromotion: running promotion on: \n";
607                function.print(llvm::dbgs()););
608     // apply the patterns
609     if (mlir::failed(mlir::applyPartialConversion(function, target,
610                                                   std::move(patterns)))) {
611       mlir::emitError(mlir::UnknownLoc::get(context),
612                       "error in converting to affine dialect\n");
613       signalPassFailure();
614     }
615   }
616 };
617 } // namespace
618 
619 /// Convert FIR loop constructs to the Affine dialect
620 std::unique_ptr<mlir::Pass> fir::createPromoteToAffinePass() {
621   return std::make_unique<AffineDialectPromotion>();
622 }
623