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/Func/IR/FuncOps.h" 25 #include "mlir/Dialect/SCF/IR/SCF.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 using namespace mlir; 38 39 namespace { 40 struct AffineLoopAnalysis; 41 struct AffineIfAnalysis; 42 43 /// Stores analysis objects for all loops and if operations inside a function 44 /// these analysis are used twice, first for marking operations for rewrite and 45 /// second when doing rewrite. 46 struct AffineFunctionAnalysis { 47 explicit AffineFunctionAnalysis(mlir::func::FuncOp funcOp) { 48 for (fir::DoLoopOp op : funcOp.getOps<fir::DoLoopOp>()) 49 loopAnalysisMap.try_emplace(op, op, *this); 50 } 51 52 AffineLoopAnalysis getChildLoopAnalysis(fir::DoLoopOp op) const; 53 54 AffineIfAnalysis getChildIfAnalysis(fir::IfOp op) const; 55 56 llvm::DenseMap<mlir::Operation *, AffineLoopAnalysis> loopAnalysisMap; 57 llvm::DenseMap<mlir::Operation *, AffineIfAnalysis> ifAnalysisMap; 58 }; 59 } // namespace 60 61 static bool analyzeCoordinate(mlir::Value coordinate, mlir::Operation *op) { 62 if (auto blockArg = coordinate.dyn_cast<mlir::BlockArgument>()) { 63 if (isa<fir::DoLoopOp>(blockArg.getOwner()->getParentOp())) 64 return true; 65 LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: array coordinate is not a " 66 "loop induction variable (owner not loopOp)\n"; 67 op->dump()); 68 return false; 69 } 70 LLVM_DEBUG( 71 llvm::dbgs() << "AffineLoopAnalysis: array coordinate is not a loop " 72 "induction variable (not a block argument)\n"; 73 op->dump(); coordinate.getDefiningOp()->dump()); 74 return false; 75 } 76 77 namespace { 78 struct AffineLoopAnalysis { 79 AffineLoopAnalysis() = default; 80 81 explicit AffineLoopAnalysis(fir::DoLoopOp op, AffineFunctionAnalysis &afa) 82 : legality(analyzeLoop(op, afa)) {} 83 84 bool canPromoteToAffine() { return legality; } 85 86 private: 87 bool analyzeBody(fir::DoLoopOp loopOperation, 88 AffineFunctionAnalysis &functionAnalysis) { 89 for (auto loopOp : loopOperation.getOps<fir::DoLoopOp>()) { 90 auto analysis = functionAnalysis.loopAnalysisMap 91 .try_emplace(loopOp, loopOp, functionAnalysis) 92 .first->getSecond(); 93 if (!analysis.canPromoteToAffine()) 94 return false; 95 } 96 for (auto ifOp : loopOperation.getOps<fir::IfOp>()) 97 functionAnalysis.ifAnalysisMap.try_emplace(ifOp, ifOp, functionAnalysis); 98 return true; 99 } 100 101 bool analyzeLoop(fir::DoLoopOp loopOperation, 102 AffineFunctionAnalysis &functionAnalysis) { 103 LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: \n"; loopOperation.dump();); 104 return analyzeMemoryAccess(loopOperation) && 105 analyzeBody(loopOperation, functionAnalysis); 106 } 107 108 bool analyzeReference(mlir::Value memref, mlir::Operation *op) { 109 if (auto acoOp = memref.getDefiningOp<ArrayCoorOp>()) { 110 if (acoOp.getMemref().getType().isa<fir::BoxType>()) { 111 // TODO: Look if and how fir.box can be promoted to affine. 112 LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: cannot promote loop, " 113 "array memory operation uses fir.box\n"; 114 op->dump(); acoOp.dump();); 115 return false; 116 } 117 bool canPromote = true; 118 for (auto coordinate : acoOp.getIndices()) 119 canPromote = canPromote && analyzeCoordinate(coordinate, op); 120 return canPromote; 121 } 122 if (auto coOp = memref.getDefiningOp<CoordinateOp>()) { 123 LLVM_DEBUG(llvm::dbgs() 124 << "AffineLoopAnalysis: cannot promote loop, " 125 "array memory operation uses non ArrayCoorOp\n"; 126 op->dump(); coOp.dump();); 127 128 return false; 129 } 130 LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: unknown type of memory " 131 "reference for array load\n"; 132 op->dump();); 133 return false; 134 } 135 136 bool analyzeMemoryAccess(fir::DoLoopOp loopOperation) { 137 for (auto loadOp : loopOperation.getOps<fir::LoadOp>()) 138 if (!analyzeReference(loadOp.getMemref(), loadOp)) 139 return false; 140 for (auto storeOp : loopOperation.getOps<fir::StoreOp>()) 141 if (!analyzeReference(storeOp.getMemref(), storeOp)) 142 return false; 143 return true; 144 } 145 146 bool legality{}; 147 }; 148 } // namespace 149 150 AffineLoopAnalysis 151 AffineFunctionAnalysis::getChildLoopAnalysis(fir::DoLoopOp op) const { 152 auto it = loopAnalysisMap.find_as(op); 153 if (it == loopAnalysisMap.end()) { 154 LLVM_DEBUG(llvm::dbgs() << "AffineFunctionAnalysis: not computed for:\n"; 155 op.dump();); 156 op.emitError("error in fetching loop analysis in AffineFunctionAnalysis\n"); 157 return {}; 158 } 159 return it->getSecond(); 160 } 161 162 namespace { 163 /// Calculates arguments for creating an IntegerSet. symCount, dimCount are the 164 /// final number of symbols and dimensions of the affine map. Integer set if 165 /// possible is in Optional IntegerSet. 166 struct AffineIfCondition { 167 using MaybeAffineExpr = llvm::Optional<mlir::AffineExpr>; 168 169 explicit AffineIfCondition(mlir::Value fc) : firCondition(fc) { 170 if (auto condDef = firCondition.getDefiningOp<mlir::arith::CmpIOp>()) 171 fromCmpIOp(condDef); 172 } 173 174 bool hasIntegerSet() const { return integerSet.has_value(); } 175 176 mlir::IntegerSet getIntegerSet() const { 177 assert(hasIntegerSet() && "integer set is missing"); 178 return integerSet.getValue(); 179 } 180 181 mlir::ValueRange getAffineArgs() const { return affineArgs; } 182 183 private: 184 MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, mlir::Value lhs, 185 mlir::Value rhs) { 186 return affineBinaryOp(kind, toAffineExpr(lhs), toAffineExpr(rhs)); 187 } 188 189 MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, MaybeAffineExpr lhs, 190 MaybeAffineExpr rhs) { 191 if (lhs && rhs) 192 return mlir::getAffineBinaryOpExpr(kind, *lhs, *rhs); 193 return {}; 194 } 195 196 MaybeAffineExpr toAffineExpr(MaybeAffineExpr e) { return e; } 197 198 MaybeAffineExpr toAffineExpr(int64_t value) { 199 return {mlir::getAffineConstantExpr(value, firCondition.getContext())}; 200 } 201 202 /// Returns an AffineExpr if it is a result of operations that can be done 203 /// in an affine expression, this includes -, +, *, rem, constant. 204 /// block arguments of a loopOp or forOp are used as dimensions 205 MaybeAffineExpr toAffineExpr(mlir::Value value) { 206 if (auto op = value.getDefiningOp<mlir::arith::SubIOp>()) 207 return affineBinaryOp( 208 mlir::AffineExprKind::Add, toAffineExpr(op.getLhs()), 209 affineBinaryOp(mlir::AffineExprKind::Mul, toAffineExpr(op.getRhs()), 210 toAffineExpr(-1))); 211 if (auto op = value.getDefiningOp<mlir::arith::AddIOp>()) 212 return affineBinaryOp(mlir::AffineExprKind::Add, op.getLhs(), 213 op.getRhs()); 214 if (auto op = value.getDefiningOp<mlir::arith::MulIOp>()) 215 return affineBinaryOp(mlir::AffineExprKind::Mul, op.getLhs(), 216 op.getRhs()); 217 if (auto op = value.getDefiningOp<mlir::arith::RemUIOp>()) 218 return affineBinaryOp(mlir::AffineExprKind::Mod, op.getLhs(), 219 op.getRhs()); 220 if (auto op = value.getDefiningOp<mlir::arith::ConstantOp>()) 221 if (auto intConstant = op.getValue().dyn_cast<IntegerAttr>()) 222 return toAffineExpr(intConstant.getInt()); 223 if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) { 224 affineArgs.push_back(value); 225 if (isa<fir::DoLoopOp>(blockArg.getOwner()->getParentOp()) || 226 isa<mlir::AffineForOp>(blockArg.getOwner()->getParentOp())) 227 return {mlir::getAffineDimExpr(dimCount++, value.getContext())}; 228 return {mlir::getAffineSymbolExpr(symCount++, value.getContext())}; 229 } 230 return {}; 231 } 232 233 void fromCmpIOp(mlir::arith::CmpIOp cmpOp) { 234 auto lhsAffine = toAffineExpr(cmpOp.getLhs()); 235 auto rhsAffine = toAffineExpr(cmpOp.getRhs()); 236 if (!lhsAffine || !rhsAffine) 237 return; 238 auto constraintPair = constraint( 239 cmpOp.getPredicate(), rhsAffine.getValue() - lhsAffine.getValue()); 240 if (!constraintPair) 241 return; 242 integerSet = mlir::IntegerSet::get(dimCount, symCount, 243 {constraintPair.getValue().first}, 244 {constraintPair.getValue().second}); 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 = 338 op.getMemref().getType().dyn_cast_or_null<ReferenceType>()) { 339 if (auto seqType = refType.getEleTy().dyn_cast_or_null<SequenceType>()) { 340 return seqType.getEleTy(); 341 } 342 } 343 op.emitError( 344 "AffineLoopConversion: array type in coordinate operation not valid\n"); 345 return mlir::Type(); 346 } 347 348 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::ShapeOp shape, 349 SmallVectorImpl<mlir::Value> &indexArgs, 350 mlir::PatternRewriter &rewriter) { 351 auto one = rewriter.create<mlir::arith::ConstantOp>( 352 acoOp.getLoc(), rewriter.getIndexType(), rewriter.getIndexAttr(1)); 353 auto extents = shape.getExtents(); 354 for (auto i = extents.begin(); i < extents.end(); i++) { 355 indexArgs.push_back(one); 356 indexArgs.push_back(*i); 357 indexArgs.push_back(one); 358 } 359 } 360 361 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::ShapeShiftOp shape, 362 SmallVectorImpl<mlir::Value> &indexArgs, 363 mlir::PatternRewriter &rewriter) { 364 auto one = rewriter.create<mlir::arith::ConstantOp>( 365 acoOp.getLoc(), rewriter.getIndexType(), rewriter.getIndexAttr(1)); 366 auto extents = shape.getPairs(); 367 for (auto i = extents.begin(); i < extents.end();) { 368 indexArgs.push_back(*i++); 369 indexArgs.push_back(*i++); 370 indexArgs.push_back(one); 371 } 372 } 373 374 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::SliceOp slice, 375 SmallVectorImpl<mlir::Value> &indexArgs, 376 mlir::PatternRewriter &rewriter) { 377 auto extents = slice.getTriples(); 378 for (auto i = extents.begin(); i < extents.end();) { 379 indexArgs.push_back(*i++); 380 indexArgs.push_back(*i++); 381 indexArgs.push_back(*i++); 382 } 383 } 384 385 static void populateIndexArgs(fir::ArrayCoorOp acoOp, 386 SmallVectorImpl<mlir::Value> &indexArgs, 387 mlir::PatternRewriter &rewriter) { 388 if (auto shape = acoOp.getShape().getDefiningOp<ShapeOp>()) 389 return populateIndexArgs(acoOp, shape, indexArgs, rewriter); 390 if (auto shapeShift = acoOp.getShape().getDefiningOp<ShapeShiftOp>()) 391 return populateIndexArgs(acoOp, shapeShift, indexArgs, rewriter); 392 if (auto slice = acoOp.getShape().getDefiningOp<SliceOp>()) 393 return populateIndexArgs(acoOp, slice, indexArgs, rewriter); 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.getIndices().size(), acoOp.getContext()); 402 SmallVector<mlir::Value> indexArgs; 403 indexArgs.append(acoOp.getIndices().begin(), acoOp.getIndices().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 = rewriter.create<fir::ConvertOp>(acoOp.getLoc(), newType, 412 acoOp.getMemref()); 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.getMemref(), 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.getMemref(), rewriter); 427 rewriter.replaceOpWithNewOp<mlir::AffineStoreOp>(storeOp, storeOp.getValue(), 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.getStep())) 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.getLowerBound()), 496 mlir::AffineMap::get(0, 1, 497 mlir::getAffineSymbolExpr(0, op.getContext())), 498 ValueRange(op.getUpperBound()), 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.getLowerBound(), op.getUpperBound(), op.getStep()})); 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( 531 {affineFor.getInductionVar(), op.getLowerBound(), op.getStep()})); 532 return std::make_pair(affineFor, actualIndex.getResult()); 533 } 534 535 AffineFunctionAnalysis &functionAnalysis; 536 }; 537 538 /// Convert `fir.if` to `affine.if`. 539 class AffineIfConversion : public mlir::OpRewritePattern<fir::IfOp> { 540 public: 541 using OpRewritePattern::OpRewritePattern; 542 AffineIfConversion(mlir::MLIRContext *context, AffineFunctionAnalysis &afa) 543 : OpRewritePattern(context) {} 544 mlir::LogicalResult 545 matchAndRewrite(fir::IfOp op, 546 mlir::PatternRewriter &rewriter) const override { 547 LLVM_DEBUG(llvm::dbgs() << "AffineIfConversion: rewriting if:\n"; 548 op.dump();); 549 auto &ifOps = op.getThenRegion().front().getOperations(); 550 auto affineCondition = AffineIfCondition(op.getCondition()); 551 if (!affineCondition.hasIntegerSet()) { 552 LLVM_DEBUG( 553 llvm::dbgs() 554 << "AffineIfConversion: couldn't calculate affine condition\n";); 555 return failure(); 556 } 557 auto affineIf = rewriter.create<mlir::AffineIfOp>( 558 op.getLoc(), affineCondition.getIntegerSet(), 559 affineCondition.getAffineArgs(), !op.getElseRegion().empty()); 560 rewriter.startRootUpdate(affineIf); 561 affineIf.getThenBlock()->getOperations().splice( 562 std::prev(affineIf.getThenBlock()->end()), ifOps, ifOps.begin(), 563 std::prev(ifOps.end())); 564 if (!op.getElseRegion().empty()) { 565 auto &otherOps = op.getElseRegion().front().getOperations(); 566 affineIf.getElseBlock()->getOperations().splice( 567 std::prev(affineIf.getElseBlock()->end()), otherOps, otherOps.begin(), 568 std::prev(otherOps.end())); 569 } 570 rewriter.finalizeRootUpdate(affineIf); 571 rewriteMemoryOps(affineIf.getBody(), rewriter); 572 573 LLVM_DEBUG(llvm::dbgs() << "AffineIfConversion: if converted to:\n"; 574 affineIf.dump();); 575 rewriter.replaceOp(op, affineIf.getOperation()->getResults()); 576 return success(); 577 } 578 }; 579 580 /// Promote fir.do_loop and fir.if to affine.for and affine.if, in the cases 581 /// where such a promotion is possible. 582 class AffineDialectPromotion 583 : public AffineDialectPromotionBase<AffineDialectPromotion> { 584 public: 585 void runOnOperation() override { 586 587 auto *context = &getContext(); 588 auto function = getOperation(); 589 markAllAnalysesPreserved(); 590 auto functionAnalysis = AffineFunctionAnalysis(function); 591 mlir::RewritePatternSet patterns(context); 592 patterns.insert<AffineIfConversion>(context, functionAnalysis); 593 patterns.insert<AffineLoopConversion>(context, functionAnalysis); 594 mlir::ConversionTarget target = *context; 595 target.addLegalDialect< 596 mlir::AffineDialect, FIROpsDialect, mlir::scf::SCFDialect, 597 mlir::arith::ArithmeticDialect, mlir::func::FuncDialect>(); 598 target.addDynamicallyLegalOp<IfOp>([&functionAnalysis](fir::IfOp op) { 599 return !(functionAnalysis.getChildIfAnalysis(op).canPromoteToAffine()); 600 }); 601 target.addDynamicallyLegalOp<DoLoopOp>([&functionAnalysis]( 602 fir::DoLoopOp op) { 603 return !(functionAnalysis.getChildLoopAnalysis(op).canPromoteToAffine()); 604 }); 605 606 LLVM_DEBUG(llvm::dbgs() 607 << "AffineDialectPromotion: running promotion on: \n"; 608 function.print(llvm::dbgs());); 609 // apply the patterns 610 if (mlir::failed(mlir::applyPartialConversion(function, target, 611 std::move(patterns)))) { 612 mlir::emitError(mlir::UnknownLoc::get(context), 613 "error in converting to affine dialect\n"); 614 signalPassFailure(); 615 } 616 } 617 }; 618 } // namespace 619 620 /// Convert FIR loop constructs to the Affine dialect 621 std::unique_ptr<mlir::Pass> fir::createPromoteToAffinePass() { 622 return std::make_unique<AffineDialectPromotion>(); 623 } 624