1 //===- LoopSpecialization.cpp - scf.parallel/SCR.for specialization -------===// 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 // Specializes parallel loops and for loops for easier unrolling and 10 // vectorization. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PassDetail.h" 15 #include "mlir/Analysis/AffineStructures.h" 16 #include "mlir/Dialect/Affine/IR/AffineOps.h" 17 #include "mlir/Dialect/SCF/Passes.h" 18 #include "mlir/Dialect/SCF/SCF.h" 19 #include "mlir/Dialect/SCF/Transforms.h" 20 #include "mlir/Dialect/StandardOps/IR/Ops.h" 21 #include "mlir/Dialect/Utils/StaticValueUtils.h" 22 #include "mlir/IR/AffineExpr.h" 23 #include "mlir/IR/BlockAndValueMapping.h" 24 #include "mlir/IR/PatternMatch.h" 25 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 26 #include "llvm/ADT/DenseMap.h" 27 28 using namespace mlir; 29 using scf::ForOp; 30 using scf::ParallelOp; 31 32 /// Rewrite a parallel loop with bounds defined by an affine.min with a constant 33 /// into 2 loops after checking if the bounds are equal to that constant. This 34 /// is beneficial if the loop will almost always have the constant bound and 35 /// that version can be fully unrolled and vectorized. 36 static void specializeParallelLoopForUnrolling(ParallelOp op) { 37 SmallVector<int64_t, 2> constantIndices; 38 constantIndices.reserve(op.upperBound().size()); 39 for (auto bound : op.upperBound()) { 40 auto minOp = bound.getDefiningOp<AffineMinOp>(); 41 if (!minOp) 42 return; 43 int64_t minConstant = std::numeric_limits<int64_t>::max(); 44 for (AffineExpr expr : minOp.map().getResults()) { 45 if (auto constantIndex = expr.dyn_cast<AffineConstantExpr>()) 46 minConstant = std::min(minConstant, constantIndex.getValue()); 47 } 48 if (minConstant == std::numeric_limits<int64_t>::max()) 49 return; 50 constantIndices.push_back(minConstant); 51 } 52 53 OpBuilder b(op); 54 BlockAndValueMapping map; 55 Value cond; 56 for (auto bound : llvm::zip(op.upperBound(), constantIndices)) { 57 Value constant = b.create<ConstantIndexOp>(op.getLoc(), std::get<1>(bound)); 58 Value cmp = b.create<CmpIOp>(op.getLoc(), CmpIPredicate::eq, 59 std::get<0>(bound), constant); 60 cond = cond ? b.create<AndOp>(op.getLoc(), cond, cmp) : cmp; 61 map.map(std::get<0>(bound), constant); 62 } 63 auto ifOp = b.create<scf::IfOp>(op.getLoc(), cond, /*withElseRegion=*/true); 64 ifOp.getThenBodyBuilder().clone(*op.getOperation(), map); 65 ifOp.getElseBodyBuilder().clone(*op.getOperation()); 66 op.erase(); 67 } 68 69 /// Rewrite a for loop with bounds defined by an affine.min with a constant into 70 /// 2 loops after checking if the bounds are equal to that constant. This is 71 /// beneficial if the loop will almost always have the constant bound and that 72 /// version can be fully unrolled and vectorized. 73 static void specializeForLoopForUnrolling(ForOp op) { 74 auto bound = op.upperBound(); 75 auto minOp = bound.getDefiningOp<AffineMinOp>(); 76 if (!minOp) 77 return; 78 int64_t minConstant = std::numeric_limits<int64_t>::max(); 79 for (AffineExpr expr : minOp.map().getResults()) { 80 if (auto constantIndex = expr.dyn_cast<AffineConstantExpr>()) 81 minConstant = std::min(minConstant, constantIndex.getValue()); 82 } 83 if (minConstant == std::numeric_limits<int64_t>::max()) 84 return; 85 86 OpBuilder b(op); 87 BlockAndValueMapping map; 88 Value constant = b.create<ConstantIndexOp>(op.getLoc(), minConstant); 89 Value cond = 90 b.create<CmpIOp>(op.getLoc(), CmpIPredicate::eq, bound, constant); 91 map.map(bound, constant); 92 auto ifOp = b.create<scf::IfOp>(op.getLoc(), cond, /*withElseRegion=*/true); 93 ifOp.getThenBodyBuilder().clone(*op.getOperation(), map); 94 ifOp.getElseBodyBuilder().clone(*op.getOperation()); 95 op.erase(); 96 } 97 98 /// Rewrite a for loop with bounds/step that potentially do not divide evenly 99 /// into a for loop where the step divides the iteration space evenly, followed 100 /// by an scf.if for the last (partial) iteration (if any). 101 /// 102 /// This function rewrites the given scf.for loop in-place and creates a new 103 /// scf.if operation for the last iteration. It replaces all uses of the 104 /// unpeeled loop with the results of the newly generated scf.if. 105 /// 106 /// The newly generated scf.if operation is returned via `ifOp`. The boundary 107 /// at which the loop is split (new upper bound) is returned via `splitBound`. 108 /// The return value indicates whether the loop was rewritten or not. 109 static LogicalResult peelForLoop(RewriterBase &b, ForOp forOp, scf::IfOp &ifOp, 110 Value &splitBound) { 111 RewriterBase::InsertionGuard guard(b); 112 auto lbInt = getConstantIntValue(forOp.lowerBound()); 113 auto ubInt = getConstantIntValue(forOp.upperBound()); 114 auto stepInt = getConstantIntValue(forOp.step()); 115 116 // No specialization necessary if step already divides upper bound evenly. 117 if (lbInt && ubInt && stepInt && (*ubInt - *lbInt) % *stepInt == 0) 118 return failure(); 119 // No specialization necessary if step size is 1. 120 if (stepInt == static_cast<int64_t>(1)) 121 return failure(); 122 123 auto loc = forOp.getLoc(); 124 AffineExpr sym0, sym1, sym2; 125 bindSymbols(b.getContext(), sym0, sym1, sym2); 126 // New upper bound: %ub - (%ub - %lb) mod %step 127 auto modMap = AffineMap::get(0, 3, {sym1 - ((sym1 - sym0) % sym2)}); 128 b.setInsertionPoint(forOp); 129 splitBound = b.createOrFold<AffineApplyOp>( 130 loc, modMap, 131 ValueRange{forOp.lowerBound(), forOp.upperBound(), forOp.step()}); 132 133 // Set new upper loop bound. 134 Value previousUb = forOp.upperBound(); 135 b.updateRootInPlace(forOp, 136 [&]() { forOp.upperBoundMutable().assign(splitBound); }); 137 b.setInsertionPointAfter(forOp); 138 139 // Do we need one more iteration? 140 Value hasMoreIter = 141 b.create<CmpIOp>(loc, CmpIPredicate::slt, splitBound, previousUb); 142 143 // Create IfOp for last iteration. 144 auto resultTypes = forOp.getResultTypes(); 145 ifOp = b.create<scf::IfOp>(loc, resultTypes, hasMoreIter, 146 /*withElseRegion=*/!resultTypes.empty()); 147 forOp.replaceAllUsesWith(ifOp->getResults()); 148 149 // Build then case. 150 BlockAndValueMapping bvm; 151 bvm.map(forOp.region().getArgument(0), splitBound); 152 for (auto it : llvm::zip(forOp.getRegionIterArgs(), forOp->getResults())) { 153 bvm.map(std::get<0>(it), std::get<1>(it)); 154 } 155 b.cloneRegionBefore(forOp.region(), ifOp.thenRegion(), 156 ifOp.thenRegion().begin(), bvm); 157 // Build else case. 158 if (!resultTypes.empty()) 159 ifOp.getElseBodyBuilder(b.getListener()) 160 .create<scf::YieldOp>(loc, forOp->getResults()); 161 162 return success(); 163 } 164 165 static void unpackOptionalValues(ArrayRef<Optional<Value>> source, 166 SmallVector<Value> &target) { 167 target = llvm::to_vector<4>(llvm::map_range(source, [](Optional<Value> val) { 168 return val.hasValue() ? *val : Value(); 169 })); 170 } 171 172 /// Bound an identifier `pos` in a given FlatAffineValueConstraints with 173 /// constraints drawn from an affine map. Before adding the constraint, the 174 /// dimensions/symbols of the affine map are aligned with `constraints`. 175 /// `operands` are the SSA Value operands used with the affine map. 176 /// Note: This function adds a new symbol column to the `constraints` for each 177 /// dimension/symbol that exists in the affine map but not in `constraints`. 178 static LogicalResult alignAndAddBound(FlatAffineValueConstraints &constraints, 179 FlatAffineConstraints::BoundType type, 180 unsigned pos, AffineMap map, 181 ValueRange operands) { 182 SmallVector<Value> dims, syms, newSyms; 183 unpackOptionalValues(constraints.getMaybeDimValues(), dims); 184 unpackOptionalValues(constraints.getMaybeSymbolValues(), syms); 185 186 AffineMap alignedMap = 187 alignAffineMapWithValues(map, operands, dims, syms, &newSyms); 188 for (unsigned i = syms.size(); i < newSyms.size(); ++i) 189 constraints.addSymbolId(constraints.getNumSymbolIds(), newSyms[i]); 190 return constraints.addBound(type, pos, alignedMap); 191 } 192 193 /// This function tries to canonicalize min/max operations by proving that their 194 /// value is bounded by the same lower and upper bound. In that case, the 195 /// operation can be folded away. 196 /// 197 /// Bounds are computed by FlatAffineValueConstraints. Invariants required for 198 /// finding/proving bounds should be supplied via `constraints`. 199 /// 200 /// 1. Add dimensions for `op` and `opBound` (lower or upper bound of `op`). 201 /// 2. Compute an upper bound of `op` (in case of `isMin`) or a lower bound (in 202 /// case of `!isMin`) and bind it to `opBound`. SSA values that are used in 203 /// `op` but are not part of `constraints`, are added as extra symbols. 204 /// 3. For each result of `op`: Add result as a dimension `r_i`. Prove that: 205 /// * If `isMin`: r_i >= opBound 206 /// * If `isMax`: r_i <= opBound 207 /// If this is the case, ub(op) == lb(op). 208 /// 4. Replace `op` with `opBound`. 209 /// 210 /// In summary, the following constraints are added throughout this function. 211 /// Note: `invar` are dimensions added by the caller to express the invariants. 212 /// (Showing only the case where `isMin`.) 213 /// 214 /// invar | op | opBound | r_i | extra syms... | const | eq/ineq 215 /// ------+-------+---------+-----+---------------+-------+------------------- 216 /// (various eq./ineq. constraining `invar`, added by the caller) 217 /// ... | 0 | 0 | 0 | 0 | ... | ... 218 /// ------+-------+---------+-----+---------------+-------+------------------- 219 /// (various ineq. constraining `op` in terms of `op` operands (`invar` and 220 /// extra `op` operands "extra syms" that are not in `invar`)). 221 /// ... | -1 | 0 | 0 | ... | ... | >= 0 222 /// ------+-------+---------+-----+---------------+-------+------------------- 223 /// (set `opBound` to `op` upper bound in terms of `invar` and "extra syms") 224 /// ... | 0 | -1 | 0 | ... | ... | = 0 225 /// ------+-------+---------+-----+---------------+-------+------------------- 226 /// (for each `op` map result r_i: set r_i to corresponding map result, 227 /// prove that r_i >= minOpUb via contradiction) 228 /// ... | 0 | 0 | -1 | ... | ... | = 0 229 /// 0 | 0 | 1 | -1 | 0 | -1 | >= 0 230 /// 231 static LogicalResult 232 canonicalizeMinMaxOp(RewriterBase &rewriter, Operation *op, AffineMap map, 233 ValueRange operands, bool isMin, 234 FlatAffineValueConstraints constraints) { 235 RewriterBase::InsertionGuard guard(rewriter); 236 unsigned numResults = map.getNumResults(); 237 238 // Add a few extra dimensions. 239 unsigned dimOp = constraints.addDimId(); // `op` 240 unsigned dimOpBound = constraints.addDimId(); // `op` lower/upper bound 241 unsigned resultDimStart = constraints.getNumDimIds(); 242 for (unsigned i = 0; i < numResults; ++i) 243 constraints.addDimId(); 244 245 // Add an inequality for each result expr_i of map: 246 // isMin: op <= expr_i, !isMin: op >= expr_i 247 auto boundType = 248 isMin ? FlatAffineConstraints::UB : FlatAffineConstraints::LB; 249 if (failed(alignAndAddBound(constraints, boundType, dimOp, map, operands))) 250 return failure(); 251 252 // Try to compute a lower/upper bound for op, expressed in terms of the other 253 // `dims` and extra symbols. 254 SmallVector<AffineMap> opLb(1), opUb(1); 255 constraints.getSliceBounds(dimOp, 1, rewriter.getContext(), &opLb, &opUb); 256 AffineMap boundMap = isMin ? opUb[0] : opLb[0]; 257 // TODO: `getSliceBounds` may return multiple bounds at the moment. This is 258 // a TODO of `getSliceBounds` and not handled here. 259 if (!boundMap || boundMap.getNumResults() != 1) 260 return failure(); // No or multiple bounds found. 261 262 // Add an equality: Set dimOpBound to computed bound. 263 // Add back dimension for op. (Was removed by `getSliceBounds`.) 264 AffineMap alignedBoundMap = boundMap.shiftDims(/*shift=*/1, /*offset=*/dimOp); 265 if (failed(constraints.addBound(FlatAffineConstraints::EQ, dimOpBound, 266 alignedBoundMap))) 267 return failure(); 268 269 // If the constraint system is empty, there is an inconsistency. (E.g., this 270 // can happen if loop lb > ub.) 271 if (constraints.isEmpty()) 272 return failure(); 273 274 // In the case of `isMin` (`!isMin` is inversed): 275 // Prove that each result of `map` has a lower bound that is equal to (or 276 // greater than) the upper bound of `op` (`dimOpBound`). In that case, `op` 277 // can be replaced with the bound. I.e., prove that for each result 278 // expr_i (represented by dimension r_i): 279 // 280 // r_i >= opBound 281 // 282 // To prove this inequality, add its negation to the constraint set and prove 283 // that the constraint set is empty. 284 for (unsigned i = resultDimStart; i < resultDimStart + numResults; ++i) { 285 FlatAffineValueConstraints newConstr(constraints); 286 287 // Add an equality: r_i = expr_i 288 // Note: These equalities could have been added earlier and used to express 289 // minOp <= expr_i. However, then we run the risk that `getSliceBounds` 290 // computes minOpUb in terms of r_i dims, which is not desired. 291 if (failed(alignAndAddBound(newConstr, FlatAffineConstraints::EQ, i, 292 map.getSubMap({i - resultDimStart}), operands))) 293 return failure(); 294 295 // If `isMin`: Add inequality: r_i < opBound 296 // equiv.: opBound - r_i - 1 >= 0 297 // If `!isMin`: Add inequality: r_i > opBound 298 // equiv.: -opBound + r_i - 1 >= 0 299 SmallVector<int64_t> ineq(newConstr.getNumCols(), 0); 300 ineq[dimOpBound] = isMin ? 1 : -1; 301 ineq[i] = isMin ? -1 : 1; 302 ineq[newConstr.getNumCols() - 1] = -1; 303 newConstr.addInequality(ineq); 304 if (!newConstr.isEmpty()) 305 return failure(); 306 } 307 308 // Lower and upper bound of `op` are equal. Replace `minOp` with its bound. 309 AffineMap newMap = alignedBoundMap; 310 SmallVector<Value> newOperands; 311 unpackOptionalValues(constraints.getMaybeDimAndSymbolValues(), newOperands); 312 mlir::canonicalizeMapAndOperands(&newMap, &newOperands); 313 rewriter.setInsertionPoint(op); 314 rewriter.replaceOpWithNewOp<AffineApplyOp>(op, newMap, newOperands); 315 return success(); 316 } 317 318 /// Try to simplify a min/max operation `op` after loop peeling. This function 319 /// can simplify min/max operations such as (ub is the previous upper bound of 320 /// the unpeeled loop): 321 /// ``` 322 /// #map = affine_map<(d0)[s0, s1] -> (s0, -d0 + s1)> 323 /// %r = affine.min #affine.min #map(%iv)[%step, %ub] 324 /// ``` 325 /// and rewrites them into (in the case the peeled loop): 326 /// ``` 327 /// %r = %step 328 /// ``` 329 /// min/max operations inside the generated scf.if operation are rewritten in 330 /// a similar way. 331 /// 332 /// This function builds up a set of constraints, capable of proving that: 333 /// * Inside the peeled loop: min(step, ub - iv) == step 334 /// * Inside the scf.if operation: min(step, ub - iv) == ub - iv 335 /// 336 /// Returns `success` if the given operation was replaced by a new operation; 337 /// `failure` otherwise. 338 /// 339 /// Note: `ub` is the previous upper bound of the loop (before peeling). 340 /// `insideLoop` must be true for min/max ops inside the loop and false for 341 /// affine.min ops inside the scf.for op. For an explanation of the other 342 /// parameters, see comment of `canonicalizeMinMaxOpInLoop`. 343 static LogicalResult rewritePeeledMinMaxOp(RewriterBase &rewriter, 344 Operation *op, AffineMap map, 345 ValueRange operands, bool isMin, 346 Value iv, Value ub, Value step, 347 bool insideLoop) { 348 FlatAffineValueConstraints constraints; 349 constraints.addDimId(0, iv); 350 constraints.addDimId(1, ub); 351 constraints.addDimId(2, step); 352 if (auto constUb = getConstantIntValue(ub)) 353 constraints.addBound(FlatAffineConstraints::EQ, 1, *constUb); 354 if (auto constStep = getConstantIntValue(step)) 355 constraints.addBound(FlatAffineConstraints::EQ, 2, *constStep); 356 357 // Add loop peeling invariant. This is the main piece of knowledge that 358 // enables AffineMinOp simplification. 359 if (insideLoop) { 360 // ub - iv >= step (equiv.: -iv + ub - step + 0 >= 0) 361 // Intuitively: Inside the peeled loop, every iteration is a "full" 362 // iteration, i.e., step divides the iteration space `ub - lb` evenly. 363 constraints.addInequality({-1, 1, -1, 0}); 364 } else { 365 // ub - iv < step (equiv.: iv + -ub + step - 1 >= 0) 366 // Intuitively: `iv` is the split bound here, i.e., the iteration variable 367 // value of the very last iteration (in the unpeeled loop). At that point, 368 // there are less than `step` elements remaining. (Otherwise, the peeled 369 // loop would run for at least one more iteration.) 370 constraints.addInequality({1, -1, 1, -1}); 371 } 372 373 return canonicalizeMinMaxOp(rewriter, op, map, operands, isMin, constraints); 374 } 375 376 template <typename OpTy, bool IsMin> 377 static void 378 rewriteAffineOpAfterPeeling(RewriterBase &rewriter, ForOp forOp, scf::IfOp ifOp, 379 Value iv, Value splitBound, Value ub, Value step) { 380 forOp.walk([&](OpTy affineOp) { 381 (void)rewritePeeledMinMaxOp(rewriter, affineOp, affineOp.getAffineMap(), 382 affineOp.operands(), IsMin, iv, ub, step, 383 /*insideLoop=*/true); 384 }); 385 ifOp.walk([&](OpTy affineOp) { 386 (void)rewritePeeledMinMaxOp(rewriter, affineOp, affineOp.getAffineMap(), 387 affineOp.operands(), IsMin, splitBound, ub, 388 step, /*insideLoop=*/false); 389 }); 390 } 391 392 LogicalResult mlir::scf::peelAndCanonicalizeForLoop(RewriterBase &rewriter, 393 ForOp forOp, 394 scf::IfOp &ifOp) { 395 Value ub = forOp.upperBound(); 396 Value splitBound; 397 if (failed(peelForLoop(rewriter, forOp, ifOp, splitBound))) 398 return failure(); 399 400 // Rewrite affine.min and affine.max ops. 401 Value iv = forOp.getInductionVar(), step = forOp.step(); 402 rewriteAffineOpAfterPeeling<AffineMinOp, /*IsMin=*/true>( 403 rewriter, forOp, ifOp, iv, splitBound, ub, step); 404 rewriteAffineOpAfterPeeling<AffineMaxOp, /*IsMin=*/false>( 405 rewriter, forOp, ifOp, iv, splitBound, ub, step); 406 407 return success(); 408 } 409 410 /// Canonicalize min/max operations in the context of for loops with a known 411 /// range. Call `canonicalizeMinMaxOp` and add the following constraints to 412 /// the constraint system (along with the missing dimensions): 413 /// 414 /// * iv >= lb 415 /// * iv < lb + step * ((ub - lb - 1) floorDiv step) + 1 416 /// 417 /// Note: Due to limitations of FlatAffineConstraints, only constant step sizes 418 /// are currently supported. 419 LogicalResult 420 mlir::scf::canonicalizeMinMaxOpInLoop(RewriterBase &rewriter, Operation *op, 421 AffineMap map, ValueRange operands, 422 bool isMin, LoopMatcherFn loopMatcher) { 423 FlatAffineValueConstraints constraints; 424 DenseSet<Value> allIvs; 425 426 // Find all iteration variables among `minOp`'s operands add constrain them. 427 for (Value operand : operands) { 428 // Skip duplicate ivs. 429 if (llvm::find(allIvs, operand) != allIvs.end()) 430 continue; 431 432 // If `operand` is an iteration variable: Find corresponding loop 433 // bounds and step. 434 Value iv = operand; 435 Value lb, ub, step; 436 if (failed(loopMatcher(operand, lb, ub, step))) 437 continue; 438 allIvs.insert(iv); 439 440 // FlatAffineConstraints does not support semi-affine expressions. 441 // Therefore, only constant step values are supported. 442 auto stepInt = getConstantIntValue(step); 443 if (!stepInt) 444 continue; 445 446 unsigned dimIv = constraints.addDimId(iv); 447 unsigned dimLb = constraints.addDimId(lb); 448 unsigned dimUb = constraints.addDimId(ub); 449 450 // If loop lower/upper bounds are constant: Add EQ constraint. 451 Optional<int64_t> lbInt = getConstantIntValue(lb); 452 Optional<int64_t> ubInt = getConstantIntValue(ub); 453 if (lbInt) 454 constraints.addBound(FlatAffineConstraints::EQ, dimLb, *lbInt); 455 if (ubInt) 456 constraints.addBound(FlatAffineConstraints::EQ, dimUb, *ubInt); 457 458 // iv >= lb (equiv.: iv - lb >= 0) 459 SmallVector<int64_t> ineqLb(constraints.getNumCols(), 0); 460 ineqLb[dimIv] = 1; 461 ineqLb[dimLb] = -1; 462 constraints.addInequality(ineqLb); 463 464 // iv < lb + step * ((ub - lb - 1) floorDiv step) + 1 465 AffineExpr exprLb = lbInt ? rewriter.getAffineConstantExpr(*lbInt) 466 : rewriter.getAffineDimExpr(dimLb); 467 AffineExpr exprUb = ubInt ? rewriter.getAffineConstantExpr(*ubInt) 468 : rewriter.getAffineDimExpr(dimUb); 469 AffineExpr ivUb = 470 exprLb + 1 + (*stepInt * ((exprUb - exprLb - 1).floorDiv(*stepInt))); 471 auto map = AffineMap::get( 472 /*dimCount=*/constraints.getNumDimIds(), 473 /*symbolCount=*/constraints.getNumSymbolIds(), /*result=*/ivUb); 474 475 if (failed(constraints.addBound(FlatAffineConstraints::UB, dimIv, map))) 476 return failure(); 477 } 478 479 return canonicalizeMinMaxOp(rewriter, op, map, operands, isMin, constraints); 480 } 481 482 static constexpr char kPeeledLoopLabel[] = "__peeled_loop__"; 483 static constexpr char kPartialIterationLabel[] = "__partial_iteration__"; 484 485 namespace { 486 struct ForLoopPeelingPattern : public OpRewritePattern<ForOp> { 487 ForLoopPeelingPattern(MLIRContext *ctx, bool skipPartial) 488 : OpRewritePattern<ForOp>(ctx), skipPartial(skipPartial) {} 489 490 LogicalResult matchAndRewrite(ForOp forOp, 491 PatternRewriter &rewriter) const override { 492 // Do not peel already peeled loops. 493 if (forOp->hasAttr(kPeeledLoopLabel)) 494 return failure(); 495 if (skipPartial) { 496 // No peeling of loops inside the partial iteration (scf.if) of another 497 // peeled loop. 498 Operation *op = forOp.getOperation(); 499 while ((op = op->getParentOfType<scf::IfOp>())) { 500 if (op->hasAttr(kPartialIterationLabel)) 501 return failure(); 502 } 503 } 504 // Apply loop peeling. 505 scf::IfOp ifOp; 506 if (failed(peelAndCanonicalizeForLoop(rewriter, forOp, ifOp))) 507 return failure(); 508 // Apply label, so that the same loop is not rewritten a second time. 509 rewriter.updateRootInPlace(forOp, [&]() { 510 forOp->setAttr(kPeeledLoopLabel, rewriter.getUnitAttr()); 511 }); 512 ifOp->setAttr(kPartialIterationLabel, rewriter.getUnitAttr()); 513 return success(); 514 } 515 516 /// If set to true, loops inside partial iterations of another peeled loop 517 /// are not peeled. This reduces the size of the generated code. Partial 518 /// iterations are not usually performance critical. 519 /// Note: Takes into account the entire chain of parent operations, not just 520 /// the direct parent. 521 bool skipPartial; 522 }; 523 524 /// Canonicalize AffineMinOp/AffineMaxOp operations in the context of scf.for 525 /// and scf.parallel loops with a known range. 526 template <typename OpTy, bool IsMin> 527 struct AffineOpSCFCanonicalizationPattern : public OpRewritePattern<OpTy> { 528 using OpRewritePattern<OpTy>::OpRewritePattern; 529 530 LogicalResult matchAndRewrite(OpTy op, 531 PatternRewriter &rewriter) const override { 532 auto loopMatcher = [](Value iv, Value &lb, Value &ub, Value &step) { 533 if (scf::ForOp forOp = scf::getForInductionVarOwner(iv)) { 534 lb = forOp.lowerBound(); 535 ub = forOp.upperBound(); 536 step = forOp.step(); 537 return success(); 538 } 539 if (scf::ParallelOp parOp = scf::getParallelForInductionVarOwner(iv)) { 540 for (unsigned idx = 0; idx < parOp.getNumLoops(); ++idx) { 541 if (parOp.getInductionVars()[idx] == iv) { 542 lb = parOp.lowerBound()[idx]; 543 ub = parOp.upperBound()[idx]; 544 step = parOp.step()[idx]; 545 return success(); 546 } 547 } 548 return failure(); 549 } 550 return failure(); 551 }; 552 553 return scf::canonicalizeMinMaxOpInLoop(rewriter, op, op.getAffineMap(), 554 op.operands(), IsMin, loopMatcher); 555 } 556 }; 557 } // namespace 558 559 namespace { 560 struct ParallelLoopSpecialization 561 : public SCFParallelLoopSpecializationBase<ParallelLoopSpecialization> { 562 void runOnFunction() override { 563 getFunction().walk( 564 [](ParallelOp op) { specializeParallelLoopForUnrolling(op); }); 565 } 566 }; 567 568 struct ForLoopSpecialization 569 : public SCFForLoopSpecializationBase<ForLoopSpecialization> { 570 void runOnFunction() override { 571 getFunction().walk([](ForOp op) { specializeForLoopForUnrolling(op); }); 572 } 573 }; 574 575 struct ForLoopPeeling : public SCFForLoopPeelingBase<ForLoopPeeling> { 576 void runOnFunction() override { 577 FuncOp funcOp = getFunction(); 578 MLIRContext *ctx = funcOp.getContext(); 579 RewritePatternSet patterns(ctx); 580 patterns.add<ForLoopPeelingPattern>(ctx, skipPartial); 581 (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); 582 583 // Drop the markers. 584 funcOp.walk([](Operation *op) { 585 op->removeAttr(kPeeledLoopLabel); 586 op->removeAttr(kPartialIterationLabel); 587 }); 588 } 589 }; 590 591 struct SCFAffineOpCanonicalization 592 : public SCFAffineOpCanonicalizationBase<SCFAffineOpCanonicalization> { 593 void runOnFunction() override { 594 FuncOp funcOp = getFunction(); 595 MLIRContext *ctx = funcOp.getContext(); 596 RewritePatternSet patterns(ctx); 597 scf::populateSCFLoopBodyCanonicalizationPatterns(patterns); 598 if (failed(applyPatternsAndFoldGreedily(funcOp, std::move(patterns)))) 599 signalPassFailure(); 600 } 601 }; 602 } // namespace 603 604 std::unique_ptr<Pass> mlir::createSCFAffineOpCanonicalizationPass() { 605 return std::make_unique<SCFAffineOpCanonicalization>(); 606 } 607 608 std::unique_ptr<Pass> mlir::createParallelLoopSpecializationPass() { 609 return std::make_unique<ParallelLoopSpecialization>(); 610 } 611 612 std::unique_ptr<Pass> mlir::createForLoopSpecializationPass() { 613 return std::make_unique<ForLoopSpecialization>(); 614 } 615 616 std::unique_ptr<Pass> mlir::createForLoopPeelingPass() { 617 return std::make_unique<ForLoopPeeling>(); 618 } 619 620 void mlir::scf::populateSCFLoopBodyCanonicalizationPatterns( 621 RewritePatternSet &patterns) { 622 MLIRContext *ctx = patterns.getContext(); 623 patterns 624 .insert<AffineOpSCFCanonicalizationPattern<AffineMinOp, /*IsMin=*/true>, 625 AffineOpSCFCanonicalizationPattern<AffineMaxOp, /*IsMin=*/false>>( 626 ctx); 627 } 628