MLIR 24.0.0git
Utils.cpp
Go to the documentation of this file.
1//===- Utils.cpp ---- Misc utilities for loop transformation ----------===//
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 file implements miscellaneous loop transformation routines.
10//
11//===----------------------------------------------------------------------===//
12
20#include "mlir/IR/IRMapping.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/SmallVectorExtras.h"
29#include "llvm/Support/DebugLog.h"
30#include <cstdint>
31
32using namespace mlir;
33
34#define DEBUG_TYPE "scf-utils"
35
37 RewriterBase &rewriter, MutableArrayRef<scf::ForOp> loopNest,
38 ValueRange newIterOperands, const NewYieldValuesFn &newYieldValuesFn,
39 bool replaceIterOperandsUsesInLoop) {
40 if (loopNest.empty())
41 return {};
42 // This method is recursive (to make it more readable). Adding an
43 // assertion here to limit the recursion. (See
44 // https://discourse.llvm.org/t/rfc-update-to-mlir-developer-policy-on-recursion/62235)
45 assert(loopNest.size() <= 10 &&
46 "exceeded recursion limit when yielding value from loop nest");
47
48 // To yield a value from a perfectly nested loop nest, the following
49 // pattern needs to be created, i.e. starting with
50 //
51 // ```mlir
52 // scf.for .. {
53 // scf.for .. {
54 // scf.for .. {
55 // %value = ...
56 // }
57 // }
58 // }
59 // ```
60 //
61 // needs to be modified to
62 //
63 // ```mlir
64 // %0 = scf.for .. iter_args(%arg0 = %init) {
65 // %1 = scf.for .. iter_args(%arg1 = %arg0) {
66 // %2 = scf.for .. iter_args(%arg2 = %arg1) {
67 // %value = ...
68 // scf.yield %value
69 // }
70 // scf.yield %2
71 // }
72 // scf.yield %1
73 // }
74 // ```
75 //
76 // The inner most loop is handled using the `replaceWithAdditionalYields`
77 // that works on a single loop.
78 if (loopNest.size() == 1) {
79 auto innerMostLoop =
80 cast<scf::ForOp>(*loopNest.back().replaceWithAdditionalYields(
81 rewriter, newIterOperands, replaceIterOperandsUsesInLoop,
82 newYieldValuesFn));
83 return {innerMostLoop};
84 }
85 // The outer loops are modified by calling this method recursively
86 // - The return value of the inner loop is the value yielded by this loop.
87 // - The region iter args of this loop are the init_args for the inner loop.
88 SmallVector<scf::ForOp> newLoopNest;
90 [&](OpBuilder &innerBuilder, Location loc,
92 newLoopNest = replaceLoopNestWithNewYields(rewriter, loopNest.drop_front(),
93 innerNewBBArgs, newYieldValuesFn,
94 replaceIterOperandsUsesInLoop);
95 return llvm::map_to_vector(
96 newLoopNest.front().getResults().take_back(innerNewBBArgs.size()),
97 [](OpResult r) -> Value { return r; });
98 };
99 scf::ForOp outerMostLoop =
100 cast<scf::ForOp>(*loopNest.front().replaceWithAdditionalYields(
101 rewriter, newIterOperands, replaceIterOperandsUsesInLoop, fn));
102 newLoopNest.insert(newLoopNest.begin(), outerMostLoop);
103 return newLoopNest;
104}
105
106/// Outline a region with a single block into a new FuncOp.
107/// Assumes the FuncOp result types is the type of the yielded operands of the
108/// single block. This constraint makes it easy to determine the result.
109/// This method also clones the `arith::ConstantIndexOp` at the start of
110/// `outlinedFuncBody` to alloc simple canonicalizations. If `callOp` is
111/// provided, it will be set to point to the operation that calls the outlined
112/// function.
113// TODO: support more than single-block regions.
114// TODO: more flexible constant handling.
115FailureOr<func::FuncOp> mlir::outlineSingleBlockRegion(RewriterBase &rewriter,
116 Location loc,
117 Region &region,
118 StringRef funcName,
119 func::CallOp *callOp) {
120 assert(!funcName.empty() && "funcName cannot be empty");
121 if (!region.hasOneBlock())
122 return failure();
123
124 Block *originalBlock = &region.front();
125 Operation *originalTerminator = originalBlock->getTerminator();
126
127 // Outline before current function.
128 OpBuilder::InsertionGuard g(rewriter);
129 rewriter.setInsertionPoint(region.getParentOfType<FunctionOpInterface>());
130
131 SetVector<Value> captures;
132 getUsedValuesDefinedAbove(region, captures);
133
134 ValueRange outlinedValues(captures.getArrayRef());
135 SmallVector<Type> outlinedFuncArgTypes;
136 SmallVector<Location> outlinedFuncArgLocs;
137 // Region's arguments are exactly the first block's arguments as per
138 // Region::getArguments().
139 // Func's arguments are cat(regions's arguments, captures arguments).
140 for (BlockArgument arg : region.getArguments()) {
141 outlinedFuncArgTypes.push_back(arg.getType());
142 outlinedFuncArgLocs.push_back(arg.getLoc());
143 }
144 for (Value value : outlinedValues) {
145 outlinedFuncArgTypes.push_back(value.getType());
146 outlinedFuncArgLocs.push_back(value.getLoc());
147 }
148 FunctionType outlinedFuncType =
149 FunctionType::get(rewriter.getContext(), outlinedFuncArgTypes,
150 originalTerminator->getOperandTypes());
151 auto outlinedFunc =
152 func::FuncOp::create(rewriter, loc, funcName, outlinedFuncType);
153 Block *outlinedFuncBody = outlinedFunc.addEntryBlock();
154
155 // Merge blocks while replacing the original block operands.
156 // Warning: `mergeBlocks` erases the original block, reconstruct it later.
157 int64_t numOriginalBlockArguments = originalBlock->getNumArguments();
158 auto outlinedFuncBlockArgs = outlinedFuncBody->getArguments();
159 {
160 OpBuilder::InsertionGuard g(rewriter);
161 rewriter.setInsertionPointToEnd(outlinedFuncBody);
162 rewriter.mergeBlocks(
163 originalBlock, outlinedFuncBody,
164 outlinedFuncBlockArgs.take_front(numOriginalBlockArguments));
165 // Explicitly set up a new ReturnOp terminator.
166 rewriter.setInsertionPointToEnd(outlinedFuncBody);
167 func::ReturnOp::create(rewriter, loc, originalTerminator->getResultTypes(),
168 originalTerminator->getOperands());
169 }
170
171 // Reconstruct the block that was deleted and add a
172 // terminator(call_results).
173 Block *newBlock = rewriter.createBlock(
174 &region, region.begin(),
175 TypeRange{outlinedFuncArgTypes}.take_front(numOriginalBlockArguments),
176 ArrayRef<Location>(outlinedFuncArgLocs)
177 .take_front(numOriginalBlockArguments));
178 {
179 OpBuilder::InsertionGuard g(rewriter);
180 rewriter.setInsertionPointToEnd(newBlock);
181 SmallVector<Value> callValues;
182 llvm::append_range(callValues, newBlock->getArguments());
183 llvm::append_range(callValues, outlinedValues);
184 auto call = func::CallOp::create(rewriter, loc, outlinedFunc, callValues);
185 if (callOp)
186 *callOp = call;
187
188 // `originalTerminator` was moved to `outlinedFuncBody` and is still valid.
189 // Clone `originalTerminator` to take the callOp results then erase it from
190 // `outlinedFuncBody`.
191 IRMapping bvm;
192 bvm.map(originalTerminator->getOperands(), call->getResults());
193 rewriter.clone(*originalTerminator, bvm);
194 rewriter.eraseOp(originalTerminator);
195 }
196
197 // Lastly, explicit RAUW outlinedValues, only for uses within `outlinedFunc`.
198 // Clone the `arith::ConstantIndexOp` at the start of `outlinedFuncBody`.
199 for (auto it : llvm::zip(outlinedValues, outlinedFuncBlockArgs.take_back(
200 outlinedValues.size()))) {
201 Value orig = std::get<0>(it);
202 Value repl = std::get<1>(it);
203 {
204 OpBuilder::InsertionGuard g(rewriter);
205 rewriter.setInsertionPointToStart(outlinedFuncBody);
207 repl = rewriter.clone(*cst)->getResult(0);
208 }
209 }
210 orig.replaceUsesWithIf(repl, [&](OpOperand &opOperand) {
211 return outlinedFunc->isProperAncestor(opOperand.getOwner());
212 });
213 }
214
215 return outlinedFunc;
216}
217
218LogicalResult mlir::outlineIfOp(RewriterBase &b, scf::IfOp ifOp,
219 func::FuncOp *thenFn, StringRef thenFnName,
220 func::FuncOp *elseFn, StringRef elseFnName) {
221 IRRewriter rewriter(b);
222 Location loc = ifOp.getLoc();
223 FailureOr<func::FuncOp> outlinedFuncOpOrFailure;
224 if (thenFn && !ifOp.getThenRegion().empty()) {
225 outlinedFuncOpOrFailure = outlineSingleBlockRegion(
226 rewriter, loc, ifOp.getThenRegion(), thenFnName);
227 if (failed(outlinedFuncOpOrFailure))
228 return failure();
229 *thenFn = *outlinedFuncOpOrFailure;
230 }
231 if (elseFn && !ifOp.getElseRegion().empty()) {
232 outlinedFuncOpOrFailure = outlineSingleBlockRegion(
233 rewriter, loc, ifOp.getElseRegion(), elseFnName);
234 if (failed(outlinedFuncOpOrFailure))
235 return failure();
236 *elseFn = *outlinedFuncOpOrFailure;
237 }
238 return success();
239}
240
243 assert(rootOp != nullptr && "Root operation must not be a nullptr.");
244 bool rootEnclosesPloops = false;
245 for (Region &region : rootOp->getRegions()) {
246 for (Block &block : region.getBlocks()) {
247 for (Operation &op : block) {
248 bool enclosesPloops = getInnermostParallelLoops(&op, result);
249 rootEnclosesPloops |= enclosesPloops;
250 if (auto ploop = dyn_cast<scf::ParallelOp>(op)) {
251 rootEnclosesPloops = true;
252
253 // Collect parallel loop if it is an innermost one.
254 if (!enclosesPloops)
255 result.push_back(ploop);
256 }
257 }
258 }
259 }
260 return rootEnclosesPloops;
261}
262
263// Build the IR that performs ceil division of a positive value by a constant:
264// ceildiv(a, B) = divis(a + (B-1), B)
265// where divis is rounding-to-zero division.
266static Value ceilDivPositive(OpBuilder &builder, Location loc, Value dividend,
267 int64_t divisor) {
268 assert(divisor > 0 && "expected positive divisor");
269 assert(dividend.getType().isIntOrIndex() &&
270 "expected integer or index-typed value");
271
272 Value divisorMinusOneCst = arith::ConstantOp::create(
273 builder, loc, builder.getIntegerAttr(dividend.getType(), divisor - 1));
274 Value divisorCst = arith::ConstantOp::create(
275 builder, loc, builder.getIntegerAttr(dividend.getType(), divisor));
276 Value sum = arith::AddIOp::create(builder, loc, dividend, divisorMinusOneCst);
277 return arith::DivUIOp::create(builder, loc, sum, divisorCst);
278}
279
280// Build the IR that performs ceil division of a positive value by another
281// positive value:
282// ceildiv(a, b) = divis(a + (b - 1), b)
283// where divis is rounding-to-zero division.
284static Value ceilDivPositive(OpBuilder &builder, Location loc, Value dividend,
285 Value divisor) {
286 assert(dividend.getType().isIntOrIndex() &&
287 "expected integer or index-typed value");
288 Value cstOne = arith::ConstantOp::create(
289 builder, loc, builder.getOneAttr(dividend.getType()));
290 Value divisorMinusOne = arith::SubIOp::create(builder, loc, divisor, cstOne);
291 Value sum = arith::AddIOp::create(builder, loc, dividend, divisorMinusOne);
292 return arith::DivUIOp::create(builder, loc, sum, divisor);
293}
294
296 Block *loopBodyBlock, Value iv, uint64_t unrollFactor,
297 function_ref<Value(unsigned, Value, OpBuilder)> ivRemapFn,
298 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
299 ValueRange iterArgs, ValueRange yieldedValues, IRMapping *clonedToSrcOpsMap,
300 SmallVectorImpl<SmallVector<Value>> *unrolledYieldedValues) {
301
302 // Check if the op was cloned from another source op, and return it if found
303 // (or the same op if not found)
304 auto findOriginalSrcOp =
305 [](Operation *op, const IRMapping &clonedToSrcOpsMap) -> Operation * {
306 Operation *srcOp = op;
307 // If the source op derives from another op: traverse the chain to find the
308 // original source op
309 while (srcOp && clonedToSrcOpsMap.contains(srcOp))
310 srcOp = clonedToSrcOpsMap.lookup(srcOp);
311 return srcOp;
312 };
313
314 // Builder to insert unrolled bodies just before the terminator of the body of
315 // the loop.
316 auto builder = OpBuilder::atBlockTerminator(loopBodyBlock);
317
318 static const auto noopAnnotateFn = [](unsigned, Operation *, OpBuilder) {};
319 if (!annotateFn)
320 annotateFn = noopAnnotateFn;
321
322 // Keep a pointer to the last non-terminator operation in the original block
323 // so that we know what to clone (since we are doing this in-place).
324 Block::iterator srcBlockEnd = std::prev(loopBodyBlock->end(), 2);
325
326 // Unroll the contents of the loop body (append unrollFactor - 1 additional
327 // copies).
328 SmallVector<Value, 4> lastYielded(yieldedValues);
329
330 for (unsigned i = 1; i < unrollFactor; i++) {
331 // Prepare operand map.
332 IRMapping operandMap;
333 operandMap.map(iterArgs, lastYielded);
334
335 // If the induction variable is used, create a remapping to the value for
336 // this unrolled instance.
337 if (!iv.use_empty()) {
338 Value ivUnroll = ivRemapFn(i, iv, builder);
339 operandMap.map(iv, ivUnroll);
340 }
341
342 // Clone the original body of 'forOp'.
343 for (auto it = loopBodyBlock->begin(); it != std::next(srcBlockEnd); it++) {
344 Operation *srcOp = &(*it);
345 Operation *clonedOp = builder.clone(*srcOp, operandMap);
346 annotateFn(i, clonedOp, builder);
347 if (clonedToSrcOpsMap)
348 clonedToSrcOpsMap->map(clonedOp,
349 findOriginalSrcOp(srcOp, *clonedToSrcOpsMap));
350 }
351
352 // Update yielded values.
353 for (unsigned i = 0, e = lastYielded.size(); i < e; i++)
354 lastYielded[i] = operandMap.lookupOrDefault(yieldedValues[i]);
355 if (unrolledYieldedValues)
356 unrolledYieldedValues->emplace_back(lastYielded.begin(),
357 lastYielded.end());
358 }
359
360 // Make sure we annotate the Ops in the original body. We do this last so that
361 // any annotations are not copied into the cloned Ops above.
362 for (auto it = loopBodyBlock->begin(); it != std::next(srcBlockEnd); it++)
363 annotateFn(0, &*it, builder);
364
365 // Update operands of the yield statement.
366 loopBodyBlock->getTerminator()->setOperands(lastYielded);
367}
368
369/// Splits `forOp` into two consecutive loops at `splitPoint`.
370FailureOr<std::pair<scf::ForOp, scf::ForOp>>
371mlir::splitForOpAtPoint(RewriterBase &rewriter, scf::ForOp forOp,
372 Value splitPoint) {
373 if (splitPoint.getType() != forOp.getLowerBound().getType())
374 return failure();
375
376 // Reject statically known violations of the split preconditions.
377 bool isUnsigned = forOp.getUnsignedCmp();
378 Value lbVal = forOp.getLowerBound();
379 Value ubVal = forOp.getUpperBound();
380 Value stepVal = forOp.getStep();
381 auto checkSplitPoint = [&](auto getBound) -> LogicalResult {
382 auto lb = getBound(lbVal);
383 auto ub = getBound(ubVal);
384 auto step = getBound(stepVal);
385 auto split = getBound(splitPoint);
386 if ((lb && split && *lb > *split) || (split && ub && *split >= *ub) ||
387 (step && *step <= 0))
388 return failure();
389 if (lb && step && split && (*split - *lb) % *step != 0)
390 return failure();
391 return success();
392 };
393 if (failed(isUnsigned ? checkSplitPoint(getConstantUIntValue)
394 : checkSplitPoint(getConstantIntValue)))
395 return failure();
396
397 OpBuilder::InsertionGuard guard(rewriter);
398 rewriter.setInsertionPointAfter(forOp);
399 auto firstForOp = cast<scf::ForOp>(rewriter.clone(*forOp));
400 auto secondForOp = cast<scf::ForOp>(rewriter.clone(*forOp));
401 rewriter.modifyOpInPlace(firstForOp,
402 [&] { firstForOp.setUpperBound(splitPoint); });
403 rewriter.modifyOpInPlace(secondForOp,
404 [&] { secondForOp.setLowerBound(splitPoint); });
405
406 // Chain iter-args across the split:
407 // - `secondForOp` is initialized from `firstForOp`'s results.
408 // - Users of `forOp`'s results are redirected to `secondForOp`'s results,
409 // so downstream code observes the final carried values.
410 rewriter.modifyOpInPlace(secondForOp, [&] {
411 secondForOp->setOperands(secondForOp.getNumControlOperands(),
412 secondForOp.getInitArgs().size(),
413 firstForOp.getResults());
414 });
415 rewriter.replaceOp(forOp, secondForOp.getResults());
416
417 return std::pair<scf::ForOp, scf::ForOp>{firstForOp, secondForOp};
418}
419
420/// Unrolls 'forOp' by 'unrollFactor', returns the unrolled main loop and the
421/// epilogue loop, if the loop is unrolled.
422FailureOr<UnrolledLoopInfo> mlir::loopUnrollByFactor(
423 scf::ForOp forOp, uint64_t unrollFactor,
424 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
425 bool shouldPromoteIfSingleIteration) {
426 assert(unrollFactor > 0 && "expected positive unroll factor");
427
428 // Return if the loop body is empty.
429 if (llvm::hasSingleElement(forOp.getBody()->getOperations()))
430 return UnrolledLoopInfo{forOp, std::nullopt};
431
432 // Compute tripCount = ceilDiv((upperBound - lowerBound), step) and populate
433 // 'upperBoundUnrolled' and 'stepUnrolled' for static and dynamic cases.
434 OpBuilder boundsBuilder(forOp);
435 IRRewriter rewriter(forOp.getContext());
436 auto loc = forOp.getLoc();
437 Value step = forOp.getStep();
438 Value upperBoundUnrolled;
439 Value stepUnrolled;
440 bool generateEpilogueLoop = true;
441
442 std::optional<APInt> constTripCount = forOp.getStaticTripCount();
443 // A static trip count does not imply constant bounds: it is also known when
444 // the lower and the upper bound are the same value (zero iterations), when
445 // the lower bound is zero and the upper bound is the step (one iteration),
446 // and when the upper bound is a constant offset from a non-constant lower
447 // bound. The computation below reads all three bounds as constants, so fall
448 // back to the dynamic case unless they are.
449 if (constTripCount && !(getConstantAPIntValue(forOp.getLowerBound()) &&
450 getConstantAPIntValue(forOp.getUpperBound()) &&
452 constTripCount = std::nullopt;
453 if (constTripCount) {
454 // Constant loop bounds computation.
455 bool isUnsignedLoop = forOp.getUnsignedCmp();
456 // For unsigned loops, bounds must be zero-extended: narrow integer types
457 // (e.g. i1, i2, i3) may have bit patterns that are negative in a signed
458 // context (e.g., i1 value 1 has getSExtValue() == -1, getZExtValue() == 1).
459 // Zero-extension is only safe when the unsigned value fits in int64_t, i.e.
460 // the type's bitwidth is < 64. Bail out for 64-bit unsigned loops.
461 if (isUnsignedLoop) {
462 if (auto intTy = dyn_cast<IntegerType>(forOp.getUpperBound().getType()))
463 if (intTy.getWidth() >= 64)
464 return failure();
465 }
466 auto getLoopBound = [&](Value v) -> int64_t {
467 auto apInt = getConstantAPIntValue(v);
468 assert(apInt && "expected constant loop bound");
469 return isUnsignedLoop ? static_cast<int64_t>(apInt->first.getZExtValue())
470 : apInt->first.getSExtValue();
471 };
472 int64_t lbCst = getLoopBound(forOp.getLowerBound());
473 int64_t ubCst = getLoopBound(forOp.getUpperBound());
474 int64_t stepCst = getLoopBound(step);
475 if (unrollFactor == 1) {
476 if (shouldPromoteIfSingleIteration && constTripCount->isOne() &&
477 failed(forOp.promoteIfSingleIteration(rewriter)))
478 return failure();
479 return UnrolledLoopInfo{forOp, std::nullopt};
480 }
481
482 uint64_t tripCount = constTripCount->getZExtValue();
483 uint64_t tripCountEvenMultiple = tripCount - tripCount % unrollFactor;
484 int64_t upperBoundUnrolledCst = lbCst + tripCountEvenMultiple * stepCst;
485 int64_t stepUnrolledCst = stepCst * unrollFactor;
486
487 // Create constant for 'upperBoundUnrolled' and set epilogue loop flag.
488 generateEpilogueLoop = upperBoundUnrolledCst < ubCst;
489 if (generateEpilogueLoop)
490 upperBoundUnrolled = arith::ConstantOp::create(
491 boundsBuilder, loc,
492 boundsBuilder.getIntegerAttr(forOp.getUpperBound().getType(),
493 upperBoundUnrolledCst));
494 else
495 upperBoundUnrolled = forOp.getUpperBound();
496
497 // Create constant for 'stepUnrolled'. When the main loop has zero
498 // iterations (tripCountEvenMultiple == 0), keep the original step.
499 // stepCst * unrollFactor may produce a value that, when truncated to the
500 // bound type's bitwidth during IntegerAttr construction, wraps to zero; a
501 // zero step causes constantTripCount to return nullopt instead of 0, which
502 // prevents the zero-trip main loop from being elided.
503 bool mainLoopHasNoIter = (tripCountEvenMultiple == 0);
504 bool stepUnchanged = (stepCst == stepUnrolledCst);
505 stepUnrolled =
506 (mainLoopHasNoIter || stepUnchanged)
507 ? step
508 : arith::ConstantOp::create(boundsBuilder, loc,
509 boundsBuilder.getIntegerAttr(
510 step.getType(), stepUnrolledCst));
511 } else {
512 // Dynamic loop bounds computation.
513 // TODO: Add dynamic asserts for negative lb/ub/step, or
514 // consider using ceilDiv from AffineApplyExpander.
515 auto lowerBound = forOp.getLowerBound();
516 auto upperBound = forOp.getUpperBound();
517 Value diff =
518 arith::SubIOp::create(boundsBuilder, loc, upperBound, lowerBound);
519 Value zero = arith::ConstantOp::create(
520 boundsBuilder, loc, boundsBuilder.getZeroAttr(diff.getType()));
521 Value nonEmpty = arith::CmpIOp::create(boundsBuilder, loc,
522 forOp.getUnsignedCmp()
523 ? arith::CmpIPredicate::ult
524 : arith::CmpIPredicate::slt,
525 lowerBound, upperBound);
526 diff = arith::SelectOp::create(boundsBuilder, loc, nonEmpty, diff, zero);
527
528 Value tripCount = ceilDivPositive(boundsBuilder, loc, diff, step);
529 Value unrollFactorCst = arith::ConstantOp::create(
530 boundsBuilder, loc,
531 boundsBuilder.getIntegerAttr(tripCount.getType(), unrollFactor));
532 Value tripCountRem =
533 arith::RemSIOp::create(boundsBuilder, loc, tripCount, unrollFactorCst);
534 // Compute tripCountEvenMultiple = tripCount - (tripCount % unrollFactor)
535 Value tripCountEvenMultiple =
536 arith::SubIOp::create(boundsBuilder, loc, tripCount, tripCountRem);
537 // Compute upperBoundUnrolled = UpperBound + tripCountEvenMultiple * step
538 upperBoundUnrolled = arith::AddIOp::create(
539 boundsBuilder, loc, lowerBound,
540 arith::MulIOp::create(boundsBuilder, loc, tripCountEvenMultiple, step));
541 // Compute stepUnrolled = step * unrollFactor
542 stepUnrolled =
543 arith::MulIOp::create(boundsBuilder, loc, step, unrollFactorCst);
544 }
545
546 UnrolledLoopInfo resultLoops;
547
548 // Create epilogue clean up loop starting at 'upperBoundUnrolled'.
549 if (generateEpilogueLoop) {
550 auto splitLoops = splitForOpAtPoint(rewriter, forOp, upperBoundUnrolled);
551 if (failed(splitLoops))
552 return failure();
553 forOp = splitLoops->first;
554 scf::ForOp epilogueForOp = splitLoops->second;
555 if (!shouldPromoteIfSingleIteration ||
556 epilogueForOp.promoteIfSingleIteration(rewriter).failed())
557 resultLoops.epilogueLoopOp = epilogueForOp;
558 } else {
559 forOp.setUpperBound(upperBoundUnrolled);
560 }
561
562 // Create unrolled loop.
563 forOp.setStep(stepUnrolled);
564
565 auto iterArgs = ValueRange(forOp.getRegionIterArgs());
566 auto yieldedValues = forOp.getBody()->getTerminator()->getOperands();
567
569 forOp.getBody(), forOp.getInductionVar(), unrollFactor,
570 [&](unsigned i, Value iv, OpBuilder b) {
571 // iv' = iv + step * i;
572 auto stride = arith::MulIOp::create(
573 b, loc, step,
574 arith::ConstantOp::create(b, loc,
575 b.getIntegerAttr(iv.getType(), i)));
576 return arith::AddIOp::create(b, loc, iv, stride);
577 },
578 annotateFn, iterArgs, yieldedValues);
579 // Promote the loop body up if this has turned into a single iteration loop
580 // and `shouldPromoteIfSingleIteration` is true.
581 if (!shouldPromoteIfSingleIteration ||
582 forOp.promoteIfSingleIteration(rewriter).failed())
583 resultLoops.mainLoopOp = forOp;
584 return resultLoops;
585}
586
587/// Unrolls this loop completely.
588LogicalResult mlir::loopUnrollFull(scf::ForOp forOp) {
589 IRRewriter rewriter(forOp.getContext());
590 std::optional<APInt> mayBeConstantTripCount = forOp.getStaticTripCount();
591 if (!mayBeConstantTripCount.has_value())
592 return failure();
593 const APInt &tripCount = *mayBeConstantTripCount;
594 if (tripCount.isZero())
595 return success();
596 if (tripCount.isOne())
597 return forOp.promoteIfSingleIteration(rewriter);
598 return loopUnrollByFactor(forOp, tripCount.getZExtValue());
599}
600
601/// Check if bounds of all inner loops are defined outside of `forOp`
602/// and return false if not.
603static bool areInnerBoundsInvariant(scf::ForOp forOp) {
604 auto walkResult = forOp.walk([&](scf::ForOp innerForOp) {
605 if (!forOp.isDefinedOutsideOfLoop(innerForOp.getLowerBound()) ||
606 !forOp.isDefinedOutsideOfLoop(innerForOp.getUpperBound()) ||
607 !forOp.isDefinedOutsideOfLoop(innerForOp.getStep()))
608 return WalkResult::interrupt();
609
610 return WalkResult::advance();
611 });
612 return !walkResult.wasInterrupted();
613}
614
615/// Unrolls and jams this loop by the specified factor.
616LogicalResult mlir::loopUnrollJamByFactor(scf::ForOp forOp,
617 uint64_t unrollJamFactor) {
618 assert(unrollJamFactor > 0 && "unroll jam factor should be positive");
619
620 if (unrollJamFactor == 1)
621 return success();
622
623 // If any control operand of any inner loop of `forOp` is defined within
624 // `forOp`, no unroll jam.
625 if (!areInnerBoundsInvariant(forOp)) {
626 LDBG() << "failed to unroll and jam: inner bounds are not invariant";
627 return failure();
628 }
629
630 // Currently, for operations with results are not supported.
631 if (forOp->getNumResults() > 0) {
632 LDBG() << "failed to unroll and jam: unsupported loop with results";
633 return failure();
634 }
635
636 // Currently, only constant trip count that divided by the unroll factor is
637 // supported.
638 std::optional<APInt> tripCount = forOp.getStaticTripCount();
639 if (!tripCount.has_value()) {
640 // If the trip count is dynamic, do not unroll & jam.
641 LDBG() << "failed to unroll and jam: trip count could not be determined";
642 return failure();
643 }
644 uint64_t tripCountValue = tripCount->getZExtValue();
645 if (tripCountValue == 0)
646 return success();
647 if (unrollJamFactor > tripCountValue) {
648 LDBG() << "unroll and jam factor is greater than trip count, set factor to "
649 "trip "
650 "count";
651 unrollJamFactor = tripCountValue;
652 } else if (tripCountValue % unrollJamFactor != 0) {
653 LDBG() << "failed to unroll and jam: unsupported trip count that is not a "
654 "multiple of unroll jam factor";
655 return failure();
656 }
657
658 // Nothing in the loop body other than the terminator.
659 if (llvm::hasSingleElement(forOp.getBody()->getOperations()))
660 return success();
661
662 // Gather all sub-blocks to jam upon the loop being unrolled.
664 jbg.walk(forOp);
665 auto &subBlocks = jbg.subBlocks;
666
667 // Collect inner loops.
668 SmallVector<scf::ForOp> innerLoops;
669 forOp.walk([&](scf::ForOp innerForOp) { innerLoops.push_back(innerForOp); });
670
671 // `operandMaps[i - 1]` carries old->new operand mapping for the ith unrolled
672 // iteration. There are (`unrollJamFactor` - 1) iterations.
673 SmallVector<IRMapping> operandMaps(unrollJamFactor - 1);
674
675 // For any loop with iter_args, replace it with a new loop that has
676 // `unrollJamFactor` copies of its iterOperands, iter_args and yield
677 // operands.
678 SmallVector<scf::ForOp> newInnerLoops;
679 IRRewriter rewriter(forOp.getContext());
680 for (scf::ForOp oldForOp : innerLoops) {
681 SmallVector<Value> dupIterOperands, dupYieldOperands;
682 ValueRange oldIterOperands = oldForOp.getInits();
683 ValueRange oldIterArgs = oldForOp.getRegionIterArgs();
684 ValueRange oldYieldOperands =
685 cast<scf::YieldOp>(oldForOp.getBody()->getTerminator()).getOperands();
686 // Get additional iterOperands, iterArgs, and yield operands. We will
687 // fix iterOperands and yield operands after cloning of sub-blocks.
688 for (unsigned i = unrollJamFactor - 1; i >= 1; --i) {
689 dupIterOperands.append(oldIterOperands.begin(), oldIterOperands.end());
690 dupYieldOperands.append(oldYieldOperands.begin(), oldYieldOperands.end());
691 }
692 // Create a new loop with additional iterOperands, iter_args and yield
693 // operands. This new loop will take the loop body of the original loop.
694 bool forOpReplaced = oldForOp == forOp;
695 scf::ForOp newForOp =
696 cast<scf::ForOp>(*oldForOp.replaceWithAdditionalYields(
697 rewriter, dupIterOperands, /*replaceInitOperandUsesInLoop=*/false,
698 [&](OpBuilder &b, Location loc, ArrayRef<BlockArgument> newBbArgs) {
699 return dupYieldOperands;
700 }));
701 newInnerLoops.push_back(newForOp);
702 // `forOp` has been replaced with a new loop.
703 if (forOpReplaced)
704 forOp = newForOp;
705 // Update `operandMaps` for `newForOp` iterArgs and results.
706 ValueRange newIterArgs = newForOp.getRegionIterArgs();
707 unsigned oldNumIterArgs = oldIterArgs.size();
708 ValueRange newResults = newForOp.getResults();
709 unsigned oldNumResults = newResults.size() / unrollJamFactor;
710 assert(oldNumIterArgs == oldNumResults &&
711 "oldNumIterArgs must be the same as oldNumResults");
712 for (unsigned i = unrollJamFactor - 1; i >= 1; --i) {
713 for (unsigned j = 0; j < oldNumIterArgs; ++j) {
714 // `newForOp` has `unrollJamFactor` - 1 new sets of iterArgs and
715 // results. Update `operandMaps[i - 1]` to map old iterArgs and results
716 // to those in the `i`th new set.
717 operandMaps[i - 1].map(newIterArgs[j],
718 newIterArgs[i * oldNumIterArgs + j]);
719 operandMaps[i - 1].map(newResults[j],
720 newResults[i * oldNumResults + j]);
721 }
722 }
723 }
724
725 // Scale the step of loop being unroll-jammed by the unroll-jam factor.
726 rewriter.setInsertionPoint(forOp);
727 int64_t step = forOp.getConstantStep()->getSExtValue();
728 auto newStep = rewriter.createOrFold<arith::MulIOp>(
729 forOp.getLoc(), forOp.getStep(),
730 rewriter.createOrFold<arith::ConstantOp>(
731 forOp.getLoc(), rewriter.getIndexAttr(unrollJamFactor)));
732 forOp.setStep(newStep);
733 auto forOpIV = forOp.getInductionVar();
734
735 // Unroll and jam (appends unrollJamFactor - 1 additional copies).
736 for (unsigned i = unrollJamFactor - 1; i >= 1; --i) {
737 for (auto &subBlock : subBlocks) {
738 // Builder to insert unroll-jammed bodies. Insert right at the end of
739 // sub-block.
740 OpBuilder builder(subBlock.first->getBlock(), std::next(subBlock.second));
741
742 // If the induction variable is used, create a remapping to the value for
743 // this unrolled instance.
744 if (!forOpIV.use_empty()) {
745 // iv' = iv + i * step, i = 1 to unrollJamFactor-1.
746 auto ivTag = builder.createOrFold<arith::ConstantOp>(
747 forOp.getLoc(), builder.getIndexAttr(step * i));
748 auto ivUnroll =
749 builder.createOrFold<arith::AddIOp>(forOp.getLoc(), forOpIV, ivTag);
750 operandMaps[i - 1].map(forOpIV, ivUnroll);
751 }
752 // Clone the sub-block being unroll-jammed.
753 for (auto it = subBlock.first; it != std::next(subBlock.second); ++it)
754 builder.clone(*it, operandMaps[i - 1]);
755 }
756 // Fix iterOperands and yield op operands of newly created loops.
757 for (auto newForOp : newInnerLoops) {
758 unsigned oldNumIterOperands =
759 newForOp.getNumRegionIterArgs() / unrollJamFactor;
760 unsigned numControlOperands = newForOp.getNumControlOperands();
761 auto yieldOp = cast<scf::YieldOp>(newForOp.getBody()->getTerminator());
762 unsigned oldNumYieldOperands = yieldOp.getNumOperands() / unrollJamFactor;
763 assert(oldNumIterOperands == oldNumYieldOperands &&
764 "oldNumIterOperands must be the same as oldNumYieldOperands");
765 for (unsigned j = 0; j < oldNumIterOperands; ++j) {
766 // The `i`th duplication of an old iterOperand or yield op operand
767 // needs to be replaced with a mapped value from `operandMaps[i - 1]`
768 // if such mapped value exists.
769 newForOp.setOperand(numControlOperands + i * oldNumIterOperands + j,
770 operandMaps[i - 1].lookupOrDefault(
771 newForOp.getOperand(numControlOperands + j)));
772 yieldOp.setOperand(
773 i * oldNumYieldOperands + j,
774 operandMaps[i - 1].lookupOrDefault(yieldOp.getOperand(j)));
775 }
776 }
777 }
778
779 // Promote the loop body up if this has turned into a single iteration loop.
780 (void)forOp.promoteIfSingleIteration(rewriter);
781 return success();
782}
783
785 Location loc, OpFoldResult lb,
787 OpFoldResult step) {
788 Range normalizedLoopBounds;
789 normalizedLoopBounds.offset = rewriter.getIndexAttr(0);
790 normalizedLoopBounds.stride = rewriter.getIndexAttr(1);
791 AffineExpr s0, s1, s2;
792 bindSymbols(rewriter.getContext(), s0, s1, s2);
793 AffineExpr e = (s1 - s0).ceilDiv(s2);
794 normalizedLoopBounds.size =
795 affine::makeComposedFoldedAffineApply(rewriter, loc, e, {lb, ub, step});
796 return normalizedLoopBounds;
797}
798
801 OpFoldResult step) {
802 if (getType(lb).isIndex()) {
803 return emitNormalizedLoopBoundsForIndexType(rewriter, loc, lb, ub, step);
804 }
805 // For non-index types, generate `arith` instructions
806 // Check if the loop is already known to have a constant zero lower bound or
807 // a constant one step.
808 bool isZeroBased = false;
809 if (auto lbCst = getConstantIntValue(lb))
810 isZeroBased = lbCst.value() == 0;
811
812 bool isStepOne = false;
813 if (auto stepCst = getConstantIntValue(step))
814 isStepOne = stepCst.value() == 1;
815
816 Type rangeType = getType(lb);
817 assert(rangeType == getType(ub) && rangeType == getType(step) &&
818 "expected matching types");
819
820 // Compute the number of iterations the loop executes: ceildiv(ub - lb, step)
821 // assuming the step is strictly positive. Update the bounds and the step
822 // of the loop to go from 0 to the number of iterations, if necessary.
823 if (isZeroBased && isStepOne)
824 return {lb, ub, step};
825
826 OpFoldResult diff = ub;
827 if (!isZeroBased) {
828 diff = rewriter.createOrFold<arith::SubIOp>(
829 loc, getValueOrCreateConstantIntOp(rewriter, loc, ub),
830 getValueOrCreateConstantIntOp(rewriter, loc, lb));
831 }
832 OpFoldResult newUpperBound = diff;
833 if (!isStepOne) {
834 newUpperBound = rewriter.createOrFold<arith::CeilDivSIOp>(
835 loc, getValueOrCreateConstantIntOp(rewriter, loc, diff),
836 getValueOrCreateConstantIntOp(rewriter, loc, step));
837 }
838
839 OpFoldResult newLowerBound = rewriter.getZeroAttr(rangeType);
840 OpFoldResult newStep = rewriter.getOneAttr(rangeType);
841
842 return {newLowerBound, newUpperBound, newStep};
843}
844
846 Location loc,
847 Value normalizedIv,
848 OpFoldResult origLb,
849 OpFoldResult origStep) {
850 AffineExpr d0, s0, s1;
851 bindSymbols(rewriter.getContext(), s0, s1);
852 bindDims(rewriter.getContext(), d0);
853 AffineExpr e = d0 * s1 + s0;
855 rewriter, loc, e, ArrayRef<OpFoldResult>{normalizedIv, origLb, origStep});
856 Value denormalizedIvVal =
857 getValueOrCreateConstantIndexOp(rewriter, loc, denormalizedIv);
858 SmallPtrSet<Operation *, 1> preservedUses;
859 // If an `affine.apply` operation is generated for denormalization, the use
860 // of `origLb` in those ops must not be replaced. These arent not generated
861 // when `origLb == 0` and `origStep == 1`.
862 if (!isZeroInteger(origLb) || !isOneInteger(origStep)) {
863 if (Operation *preservedUse = denormalizedIvVal.getDefiningOp()) {
864 preservedUses.insert(preservedUse);
865 }
866 }
867 rewriter.replaceAllUsesExcept(normalizedIv, denormalizedIvVal, preservedUses);
868}
869
871 Value normalizedIv, OpFoldResult origLb,
872 OpFoldResult origStep) {
873 if (getType(origLb).isIndex()) {
874 return denormalizeInductionVariableForIndexType(rewriter, loc, normalizedIv,
875 origLb, origStep);
876 }
877 Value denormalizedIv;
879 bool isStepOne = isOneInteger(origStep);
880 bool isZeroBased = isZeroInteger(origLb);
881
882 Value scaled = normalizedIv;
883 if (!isStepOne) {
884 Value origStepValue =
885 getValueOrCreateConstantIntOp(rewriter, loc, origStep);
886 scaled = arith::MulIOp::create(rewriter, loc, normalizedIv, origStepValue);
887 preserve.insert(scaled.getDefiningOp());
888 }
889 denormalizedIv = scaled;
890 if (!isZeroBased) {
891 Value origLbValue = getValueOrCreateConstantIntOp(rewriter, loc, origLb);
892 denormalizedIv = arith::AddIOp::create(rewriter, loc, scaled, origLbValue);
893 preserve.insert(denormalizedIv.getDefiningOp());
894 }
895
896 rewriter.replaceAllUsesExcept(normalizedIv, denormalizedIv, preserve);
897}
898
900 ArrayRef<OpFoldResult> values) {
901 assert(!values.empty() && "unexecpted empty array");
902 AffineExpr s0, s1;
903 bindSymbols(rewriter.getContext(), s0, s1);
904 AffineExpr mul = s0 * s1;
905 OpFoldResult products = rewriter.getIndexAttr(1);
906 for (auto v : values) {
908 rewriter, loc, mul, ArrayRef<OpFoldResult>{products, v});
909 }
910 return products;
911}
912
913/// Helper function to multiply a sequence of values.
915 ArrayRef<Value> values) {
916 assert(!values.empty() && "unexpected empty list");
917 if (getType(values.front()).isIndex()) {
919 OpFoldResult product = getProductOfIndexes(rewriter, loc, ofrs);
920 return getValueOrCreateConstantIndexOp(rewriter, loc, product);
921 }
922 std::optional<Value> productOf;
923 for (auto v : values) {
924 auto vOne = getConstantIntValue(v);
925 if (vOne && vOne.value() == 1)
926 continue;
927 if (productOf)
928 productOf = arith::MulIOp::create(rewriter, loc, productOf.value(), v)
929 .getResult();
930 else
931 productOf = v;
932 }
933 if (!productOf) {
934 productOf = arith::ConstantOp::create(
935 rewriter, loc, rewriter.getOneAttr(getType(values.front())))
936 .getResult();
937 }
938 return productOf.value();
939}
940
941/// For each original loop, the value of the
942/// induction variable can be obtained by dividing the induction variable of
943/// the linearized loop by the total number of iterations of the loops nested
944/// in it modulo the number of iterations in this loop (remove the values
945/// related to the outer loops):
946/// iv_i = floordiv(iv_linear, product-of-loop-ranges-until-i) mod range_i.
947/// Compute these iteratively from the innermost loop by creating a "running
948/// quotient" of division by the range.
949static std::pair<SmallVector<Value>, SmallPtrSet<Operation *, 2>>
951 Value linearizedIv, ArrayRef<Value> ubs) {
952
953 if (linearizedIv.getType().isIndex()) {
954 Operation *delinearizedOp = affine::AffineDelinearizeIndexOp::create(
955 rewriter, loc, linearizedIv, ubs);
956 auto resultVals = llvm::map_to_vector(
957 delinearizedOp->getResults(), [](OpResult r) -> Value { return r; });
958 return {resultVals, SmallPtrSet<Operation *, 2>{delinearizedOp}};
959 }
960
961 SmallVector<Value> delinearizedIvs(ubs.size());
962 SmallPtrSet<Operation *, 2> preservedUsers;
963
964 llvm::BitVector isUbOne(ubs.size());
965 for (auto [index, ub] : llvm::enumerate(ubs)) {
966 auto ubCst = getConstantIntValue(ub);
967 if (ubCst && ubCst.value() == 1)
968 isUbOne.set(index);
969 }
970
971 // Prune the lead ubs that are all ones.
972 unsigned numLeadingOneUbs = 0;
973 for (auto [index, ub] : llvm::enumerate(ubs)) {
974 if (!isUbOne.test(index)) {
975 break;
976 }
977 delinearizedIvs[index] = arith::ConstantOp::create(
978 rewriter, loc, rewriter.getZeroAttr(ub.getType()));
979 numLeadingOneUbs++;
980 }
981
982 Value previous = linearizedIv;
983 for (unsigned i = numLeadingOneUbs, e = ubs.size(); i < e; ++i) {
984 unsigned idx = ubs.size() - (i - numLeadingOneUbs) - 1;
985 if (i != numLeadingOneUbs && !isUbOne.test(idx + 1)) {
986 previous = arith::DivSIOp::create(rewriter, loc, previous, ubs[idx + 1]);
987 preservedUsers.insert(previous.getDefiningOp());
988 }
989 Value iv = previous;
990 if (i != e - 1) {
991 if (!isUbOne.test(idx)) {
992 iv = arith::RemSIOp::create(rewriter, loc, previous, ubs[idx]);
993 preservedUsers.insert(iv.getDefiningOp());
994 } else {
995 iv = arith::ConstantOp::create(
996 rewriter, loc, rewriter.getZeroAttr(ubs[idx].getType()));
997 }
998 }
999 delinearizedIvs[idx] = iv;
1000 }
1001 return {delinearizedIvs, preservedUsers};
1002}
1003
1004LogicalResult mlir::coalesceLoops(RewriterBase &rewriter,
1006 if (loops.size() < 2)
1007 return failure();
1008
1009 scf::ForOp innermost = loops.back();
1010 scf::ForOp outermost = loops.front();
1011
1012 // Bail out if any loop has a known zero step, as normalization
1013 // would result in a division by zero.
1014 for (auto loop : loops) {
1015 if (auto step = getConstantIntValue(loop.getStep())) {
1016 if (step.value() == 0) {
1017 return failure();
1018 }
1019 }
1020 }
1021 // 1. Make sure all loops iterate from 0 to upperBound with step 1. This
1022 // allows the following code to assume upperBound is the number of iterations.
1023 for (auto loop : loops) {
1024 OpBuilder::InsertionGuard g(rewriter);
1025 rewriter.setInsertionPoint(outermost);
1026 Value lb = loop.getLowerBound();
1027 Value ub = loop.getUpperBound();
1028 Value step = loop.getStep();
1029 auto newLoopRange =
1030 emitNormalizedLoopBounds(rewriter, loop.getLoc(), lb, ub, step);
1031
1032 rewriter.modifyOpInPlace(loop, [&]() {
1033 loop.setLowerBound(getValueOrCreateConstantIntOp(rewriter, loop.getLoc(),
1034 newLoopRange.offset));
1035 loop.setUpperBound(getValueOrCreateConstantIntOp(rewriter, loop.getLoc(),
1036 newLoopRange.size));
1037 loop.setStep(getValueOrCreateConstantIntOp(rewriter, loop.getLoc(),
1038 newLoopRange.stride));
1039 });
1040 rewriter.setInsertionPointToStart(innermost.getBody());
1041 denormalizeInductionVariable(rewriter, loop.getLoc(),
1042 loop.getInductionVar(), lb, step);
1043 }
1044
1045 // 2. Emit code computing the upper bound of the coalesced loop as product
1046 // of the number of iterations of all loops.
1047 OpBuilder::InsertionGuard g(rewriter);
1048 rewriter.setInsertionPoint(outermost);
1049 Location loc = outermost.getLoc();
1050 SmallVector<Value> upperBounds = llvm::map_to_vector(
1051 loops, [](auto loop) { return loop.getUpperBound(); });
1052 Value upperBound = getProductOfIntsOrIndexes(rewriter, loc, upperBounds);
1053 outermost.setUpperBound(upperBound);
1054
1055 // Insert delinearization at the start of the outermost loop body.
1056 rewriter.setInsertionPointToStart(outermost.getBody());
1057 auto [delinearizeIvs, preservedUsers] = delinearizeInductionVariable(
1058 rewriter, loc, outermost.getInductionVar(), upperBounds);
1059 rewriter.replaceAllUsesExcept(outermost.getInductionVar(), delinearizeIvs[0],
1060 preservedUsers);
1061
1062 for (int i = loops.size() - 1; i > 0; --i) {
1063 auto outerLoop = loops[i - 1];
1064 auto innerLoop = loops[i];
1065
1066 Operation *innerTerminator = innerLoop.getBody()->getTerminator();
1067 auto yieldedVals = llvm::to_vector(innerTerminator->getOperands());
1068 assert(llvm::equal(outerLoop.getRegionIterArgs(), innerLoop.getInitArgs()));
1069 for (Value &yieldedVal : yieldedVals) {
1070 // The yielded value may be the induction variable of the inner loop,
1071 // which is about to be inlined and whose block argument is about to
1072 // be destroyed. Use its replacement value instead.
1073 if (yieldedVal == innerLoop.getInductionVar()) {
1074 yieldedVal = delinearizeIvs[i];
1075 continue;
1076 }
1077 // The yielded value may be an iteration argument of the inner loop
1078 // which is about to be inlined.
1079 auto iter = llvm::find(innerLoop.getRegionIterArgs(), yieldedVal);
1080 if (iter != innerLoop.getRegionIterArgs().end()) {
1081 unsigned iterArgIndex = iter - innerLoop.getRegionIterArgs().begin();
1082 // `outerLoop` iter args identical to the `innerLoop` init args.
1083 assert(iterArgIndex < innerLoop.getInitArgs().size());
1084 yieldedVal = innerLoop.getInitArgs()[iterArgIndex];
1085 }
1086 }
1087 rewriter.eraseOp(innerTerminator);
1088
1089 SmallVector<Value> innerBlockArgs;
1090 innerBlockArgs.push_back(delinearizeIvs[i]);
1091 llvm::append_range(innerBlockArgs, outerLoop.getRegionIterArgs());
1092 rewriter.inlineBlockBefore(innerLoop.getBody(), outerLoop.getBody(),
1093 Block::iterator(innerLoop), innerBlockArgs);
1094 rewriter.replaceOp(innerLoop, yieldedVals);
1095 }
1096 return success();
1097}
1098
1100 if (loops.empty()) {
1101 return failure();
1102 }
1103 IRRewriter rewriter(loops.front().getContext());
1104 return coalesceLoops(rewriter, loops);
1105}
1106
1107LogicalResult mlir::coalescePerfectlyNestedSCFForLoops(scf::ForOp op) {
1108 LogicalResult result(failure());
1110 getPerfectlyNestedLoops(loops, op);
1111
1112 // Look for a band of loops that can be coalesced, i.e. perfectly nested
1113 // loops with bounds defined above some loop.
1114
1115 // 1. For each loop, find above which parent loop its bounds operands are
1116 // defined.
1117 SmallVector<unsigned> operandsDefinedAbove(loops.size());
1118 for (unsigned i = 0, e = loops.size(); i < e; ++i) {
1119 operandsDefinedAbove[i] = i;
1120 for (unsigned j = 0; j < i; ++j) {
1121 SmallVector<Value> boundsOperands = {loops[i].getLowerBound(),
1122 loops[i].getUpperBound(),
1123 loops[i].getStep()};
1124 if (areValuesDefinedAbove(boundsOperands, loops[j].getRegion())) {
1125 operandsDefinedAbove[i] = j;
1126 break;
1127 }
1128 }
1129 }
1130
1131 // 2. For each inner loop check that the iter_args for the immediately outer
1132 // loop are the init for the immediately inner loop and that the yields of the
1133 // return of the inner loop is the yield for the immediately outer loop. Keep
1134 // track of where the chain starts from for each loop.
1135 SmallVector<unsigned> iterArgChainStart(loops.size());
1136 iterArgChainStart[0] = 0;
1137 for (unsigned i = 1, e = loops.size(); i < e; ++i) {
1138 // By default set the start of the chain to itself.
1139 iterArgChainStart[i] = i;
1140 auto outerloop = loops[i - 1];
1141 auto innerLoop = loops[i];
1142 if (outerloop.getNumRegionIterArgs() != innerLoop.getNumRegionIterArgs()) {
1143 continue;
1144 }
1145 if (!llvm::equal(outerloop.getRegionIterArgs(), innerLoop.getInitArgs())) {
1146 continue;
1147 }
1148 auto outerloopTerminator = outerloop.getBody()->getTerminator();
1149 if (!llvm::equal(outerloopTerminator->getOperands(),
1150 innerLoop.getResults())) {
1151 continue;
1152 }
1153 iterArgChainStart[i] = iterArgChainStart[i - 1];
1154 }
1155
1156 // 3. Identify bands of loops such that the operands of all of them are
1157 // defined above the first loop in the band. Traverse the nest bottom-up
1158 // so that modifications don't invalidate the inner loops.
1159 for (unsigned end = loops.size(); end > 0; --end) {
1160 unsigned start = 0;
1161 for (; start < end - 1; ++start) {
1162 auto maxPos =
1163 *std::max_element(std::next(operandsDefinedAbove.begin(), start),
1164 std::next(operandsDefinedAbove.begin(), end));
1165 if (maxPos > start)
1166 continue;
1167 if (iterArgChainStart[end - 1] > start)
1168 continue;
1169 auto band = llvm::MutableArrayRef(loops.data() + start, end - start);
1170 if (succeeded(coalesceLoops(band)))
1171 result = success();
1172 break;
1173 }
1174 // If a band was found and transformed, keep looking at the loops above
1175 // the outermost transformed loop.
1176 if (start != end - 1)
1177 end = start + 1;
1178 }
1179 return result;
1180}
1181
1183 RewriterBase &rewriter, scf::ParallelOp loops,
1184 ArrayRef<std::vector<unsigned>> combinedDimensions) {
1185 OpBuilder::InsertionGuard g(rewriter);
1186 rewriter.setInsertionPoint(loops);
1187 Location loc = loops.getLoc();
1188
1189 // Presort combined dimensions.
1190 auto sortedDimensions = llvm::to_vector<3>(combinedDimensions);
1191 for (auto &dims : sortedDimensions)
1192 llvm::sort(dims);
1193
1194 // Normalize ParallelOp's iteration pattern.
1195 SmallVector<Value, 3> normalizedUpperBounds;
1196 for (unsigned i = 0, e = loops.getNumLoops(); i < e; ++i) {
1197 OpBuilder::InsertionGuard g2(rewriter);
1198 rewriter.setInsertionPoint(loops);
1199 Value lb = loops.getLowerBound()[i];
1200 Value ub = loops.getUpperBound()[i];
1201 Value step = loops.getStep()[i];
1202 auto newLoopRange = emitNormalizedLoopBounds(rewriter, loc, lb, ub, step);
1203 normalizedUpperBounds.push_back(getValueOrCreateConstantIntOp(
1204 rewriter, loops.getLoc(), newLoopRange.size));
1205
1206 rewriter.setInsertionPointToStart(loops.getBody());
1207 denormalizeInductionVariable(rewriter, loc, loops.getInductionVars()[i], lb,
1208 step);
1209 }
1210
1211 // Combine iteration spaces.
1212 SmallVector<Value, 3> lowerBounds, upperBounds, steps;
1213 auto cst0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
1214 auto cst1 = arith::ConstantIndexOp::create(rewriter, loc, 1);
1215 for (auto &sortedDimension : sortedDimensions) {
1216 Value newUpperBound = arith::ConstantIndexOp::create(rewriter, loc, 1);
1217 for (auto idx : sortedDimension) {
1218 newUpperBound = arith::MulIOp::create(rewriter, loc, newUpperBound,
1219 normalizedUpperBounds[idx]);
1220 }
1221 lowerBounds.push_back(cst0);
1222 steps.push_back(cst1);
1223 upperBounds.push_back(newUpperBound);
1224 }
1225
1226 // Create new ParallelLoop with conversions to the original induction values.
1227 // The loop below uses divisions to get the relevant range of values in the
1228 // new induction value that represent each range of the original induction
1229 // value. The remainders then determine based on that range, which iteration
1230 // of the original induction value this represents. This is a normalized value
1231 // that is un-normalized already by the previous logic.
1232 SmallVector<Value> newIVs(loops.getNumLoops());
1233 auto newPloop = scf::ParallelOp::create(
1234 rewriter, loc, lowerBounds, upperBounds, steps, loops.getInitVals(),
1235 [&](OpBuilder &insideBuilder, Location, ValueRange ploopIVs, ValueRange) {
1236 for (unsigned i = 0, e = combinedDimensions.size(); i < e; ++i) {
1237 Value previous = ploopIVs[i];
1238 unsigned numberCombinedDimensions = combinedDimensions[i].size();
1239 // Iterate over all except the last induction value.
1240 for (unsigned j = numberCombinedDimensions - 1; j > 0; --j) {
1241 unsigned idx = combinedDimensions[i][j];
1242
1243 // Determine the current induction value's current loop iteration
1244 Value iv = arith::RemSIOp::create(insideBuilder, loc, previous,
1245 normalizedUpperBounds[idx]);
1246 newIVs[idx] = iv;
1247
1248 // Remove the effect of the current induction value to prepare for
1249 // the next value.
1250 previous = arith::DivSIOp::create(insideBuilder, loc, previous,
1251 normalizedUpperBounds[idx]);
1252 }
1253
1254 // The final induction value is just the remaining value.
1255 unsigned idx = combinedDimensions[i][0];
1256 newIVs[idx] = previous;
1257 }
1258 });
1259
1260 // The builder inserts an empty scf.reduce only when there are no reductions.
1261 // Drop that terminator and move the original one over with the body, so a
1262 // loop with reductions keeps its scf.reduce and its results.
1263 if (loops.getInitVals().empty())
1264 rewriter.eraseOp(newPloop.getBody()->getTerminator());
1265 rewriter.mergeBlocks(loops.getBody(), newPloop.getBody(), newIVs);
1266 // Replace uses of the results.
1267 rewriter.replaceOp(loops, newPloop);
1268 return newPloop;
1269}
1270
1271// Hoist the ops within `outer` that appear before `inner`.
1272// Such ops include the ops that have been introduced by parametric tiling.
1273// Ops that come from triangular loops (i.e. that belong to the program slice
1274// rooted at `outer`) and ops that have side effects cannot be hoisted.
1275// Return failure when any op fails to hoist.
1276static LogicalResult hoistOpsBetween(scf::ForOp outer, scf::ForOp inner) {
1277 SetVector<Operation *> forwardSlice;
1279 options.filter = [&inner](Operation *op) {
1280 return op != inner.getOperation();
1281 };
1282 getForwardSlice(outer.getInductionVar(), &forwardSlice, options);
1283 LogicalResult status = success();
1285 for (auto &op : outer.getBody()->without_terminator()) {
1286 // Stop when encountering the inner loop.
1287 if (&op == inner.getOperation())
1288 break;
1289 // Skip over non-hoistable ops.
1290 if (forwardSlice.count(&op) > 0) {
1291 status = failure();
1292 continue;
1293 }
1294 // Skip intermediate scf::ForOp, these are not considered a failure.
1295 if (isa<scf::ForOp>(op))
1296 continue;
1297 // Skip other ops with regions.
1298 if (op.getNumRegions() > 0) {
1299 status = failure();
1300 continue;
1301 }
1302 // Skip if op has side effects.
1303 // TODO: loads to immutable memory regions are ok.
1304 if (!isMemoryEffectFree(&op)) {
1305 status = failure();
1306 continue;
1307 }
1308 toHoist.push_back(&op);
1309 }
1310 auto *outerForOp = outer.getOperation();
1311 for (auto *op : toHoist)
1312 op->moveBefore(outerForOp);
1313 return status;
1314}
1315
1316// Traverse the interTile and intraTile loops and try to hoist ops such that
1317// bands of perfectly nested loops are isolated.
1318// Return failure if either perfect interTile or perfect intraTile bands cannot
1319// be formed.
1320static LogicalResult tryIsolateBands(const TileLoops &tileLoops) {
1321 LogicalResult status = success();
1322 const Loops &interTile = tileLoops.first;
1323 const Loops &intraTile = tileLoops.second;
1324 auto size = interTile.size();
1325 assert(size == intraTile.size());
1326 if (size <= 1)
1327 return success();
1328 for (unsigned s = 1; s < size; ++s)
1329 status = succeeded(status) ? hoistOpsBetween(intraTile[0], intraTile[s])
1330 : failure();
1331 for (unsigned s = 1; s < size; ++s)
1332 status = succeeded(status) ? hoistOpsBetween(interTile[0], interTile[s])
1333 : failure();
1334 return status;
1335}
1336
1337/// Collect perfectly nested loops starting from `rootForOps`. Loops are
1338/// perfectly nested if each loop is the first and only non-terminator operation
1339/// in the parent loop. Collect at most `maxLoops` loops and append them to
1340/// `forOps`.
1341template <typename T>
1343 SmallVectorImpl<T> &forOps, T rootForOp,
1344 unsigned maxLoops = std::numeric_limits<unsigned>::max()) {
1345 for (unsigned i = 0; i < maxLoops; ++i) {
1346 forOps.push_back(rootForOp);
1347 Block &body = rootForOp.getRegion().front();
1348 if (body.begin() != std::prev(body.end(), 2))
1349 return;
1350
1351 rootForOp = dyn_cast<T>(&body.front());
1352 if (!rootForOp)
1353 return;
1354 }
1355}
1356
1357static Loops stripmineSink(scf::ForOp forOp, Value factor,
1358 ArrayRef<scf::ForOp> targets) {
1359 auto originalStep = forOp.getStep();
1360 auto iv = forOp.getInductionVar();
1361 bool isUnsigned = forOp.getUnsignedCmp();
1362
1363 OpBuilder b(forOp);
1364 forOp.setStep(arith::MulIOp::create(b, forOp.getLoc(), originalStep, factor));
1365
1366 Loops innerLoops;
1367 for (auto t : targets) {
1368 // Save information for splicing ops out of t when done
1369 auto begin = t.getBody()->begin();
1370 auto nOps = t.getBody()->getOperations().size();
1371
1372 // Insert newForOp before the terminator of `t`.
1373 auto b = OpBuilder::atBlockTerminator((t.getBody()));
1374 Value stepped = arith::AddIOp::create(b, t.getLoc(), iv, forOp.getStep());
1375 Value ub;
1376 if (isUnsigned)
1377 ub =
1378 arith::MinUIOp::create(b, t.getLoc(), forOp.getUpperBound(), stepped);
1379 else
1380 ub =
1381 arith::MinSIOp::create(b, t.getLoc(), forOp.getUpperBound(), stepped);
1382
1383 // Splice [begin, begin + nOps - 1) into `newForOp` and replace uses.
1384 auto newForOp =
1385 scf::ForOp::create(b, t.getLoc(), iv, ub, originalStep,
1386 /*initArgs=*/t.getRegionIterArgs(),
1387 /*bodyBuilder=*/nullptr, /*unsignedCmp=*/isUnsigned);
1388 newForOp.getBody()->getOperations().splice(
1389 newForOp.getBody()->getOperations().begin(),
1390 t.getBody()->getOperations(), begin, std::next(begin, nOps - 1));
1391 replaceAllUsesInRegionWith(iv, newForOp.getInductionVar(),
1392 newForOp.getRegion());
1393
1394 // Thread the iter_args of `t` through `newForOp`.
1395 if (!t.getInitArgs().empty()) {
1396 Operation *yieldOp = t.getBody()->getTerminator();
1397 yieldOp->moveBefore(newForOp.getBody(), newForOp.getBody()->end());
1398 for (auto [oldArg, newArg] :
1399 llvm::zip_equal(t.getRegionIterArgs(), newForOp.getRegionIterArgs()))
1400 replaceAllUsesInRegionWith(oldArg, newArg, newForOp.getRegion());
1401 b.setInsertionPointToEnd(t.getBody());
1402 scf::YieldOp::create(b, t.getLoc(), newForOp.getResults());
1403 }
1404
1405 innerLoops.push_back(newForOp);
1406 }
1407
1408 return innerLoops;
1409}
1410
1412 ArrayRef<Value> sizes,
1413 ArrayRef<scf::ForOp> targets) {
1415 SmallVector<scf::ForOp, 8> currentTargets(targets);
1416 for (auto it : llvm::zip(forOps, sizes)) {
1417 auto step = stripmineSink(std::get<0>(it), std::get<1>(it), currentTargets);
1418 res.push_back(step);
1419 currentTargets = step;
1420 }
1421 return res;
1422}
1423
1425 scf::ForOp target) {
1427 for (auto loops : tile(forOps, sizes, ArrayRef<scf::ForOp>(target)))
1428 res.push_back(llvm::getSingleElement(loops));
1429 return res;
1430}
1431
1433 // Collect perfectly nested loops. If more size values provided than nested
1434 // loops available, truncate `sizes`.
1436 forOps.reserve(sizes.size());
1437 getPerfectlyNestedLoopsImpl(forOps, rootForOp, sizes.size());
1438 if (forOps.size() < sizes.size())
1439 sizes = sizes.take_front(forOps.size());
1440
1441 return ::tile(forOps, sizes, forOps.back());
1442}
1443
1445 scf::ForOp root) {
1446 getPerfectlyNestedLoopsImpl(nestedLoops, root);
1447}
1448
1450 ArrayRef<int64_t> sizes) {
1451 // Collect perfectly nested loops. If more size values provided than nested
1452 // loops available, truncate `sizes`.
1454 forOps.reserve(sizes.size());
1455 getPerfectlyNestedLoopsImpl(forOps, rootForOp, sizes.size());
1456 if (forOps.size() < sizes.size())
1457 sizes = sizes.take_front(forOps.size());
1458
1459 // Compute the tile sizes such that i-th outer loop executes size[i]
1460 // iterations. Given that the loop current executes
1461 // numIterations = ceildiv((upperBound - lowerBound), step)
1462 // iterations, we need to tile with size ceildiv(numIterations, size[i]).
1463 SmallVector<Value, 4> tileSizes;
1464 tileSizes.reserve(sizes.size());
1465 for (unsigned i = 0, e = sizes.size(); i < e; ++i) {
1466 assert(sizes[i] > 0 && "expected strictly positive size for strip-mining");
1467
1468 auto forOp = forOps[i];
1469 OpBuilder builder(forOp);
1470 auto loc = forOp.getLoc();
1471 Value diff = arith::SubIOp::create(builder, loc, forOp.getUpperBound(),
1472 forOp.getLowerBound());
1473 Value numIterations = ceilDivPositive(builder, loc, diff, forOp.getStep());
1474 Value iterationsPerBlock =
1475 ceilDivPositive(builder, loc, numIterations, sizes[i]);
1476 tileSizes.push_back(iterationsPerBlock);
1477 }
1478
1479 // Call parametric tiling with the given sizes.
1480 auto intraTile = tile(forOps, tileSizes, forOps.back());
1481 TileLoops tileLoops = std::make_pair(forOps, intraTile);
1482
1483 // TODO: for now we just ignore the result of band isolation.
1484 // In the future, mapping decisions may be impacted by the ability to
1485 // isolate perfectly nested bands.
1486 (void)tryIsolateBands(tileLoops);
1487
1488 return tileLoops;
1489}
1490
1492 scf::ForallOp source,
1493 RewriterBase &rewriter) {
1494 unsigned numTargetOuts = target.getNumResults();
1495 unsigned numSourceOuts = source.getNumResults();
1496
1497 // Create fused shared_outs.
1498 SmallVector<Value> fusedOuts;
1499 llvm::append_range(fusedOuts, target.getOutputs());
1500 llvm::append_range(fusedOuts, source.getOutputs());
1501
1502 // Create a new scf.forall op after the source loop.
1503 rewriter.setInsertionPointAfter(source);
1504 scf::ForallOp fusedLoop = scf::ForallOp::create(
1505 rewriter, source.getLoc(), source.getMixedLowerBound(),
1506 source.getMixedUpperBound(), source.getMixedStep(), fusedOuts,
1507 source.getMapping());
1508
1509 // Map control operands.
1510 IRMapping mapping;
1511 mapping.map(target.getInductionVars(), fusedLoop.getInductionVars());
1512 mapping.map(source.getInductionVars(), fusedLoop.getInductionVars());
1513
1514 // Map shared outs.
1515 mapping.map(target.getRegionIterArgs(),
1516 fusedLoop.getRegionIterArgs().take_front(numTargetOuts));
1517 mapping.map(source.getRegionIterArgs(),
1518 fusedLoop.getRegionIterArgs().take_back(numSourceOuts));
1519
1520 // Append everything except the terminator into the fused operation.
1521 rewriter.setInsertionPointToStart(fusedLoop.getBody());
1522 for (Operation &op : target.getBody()->without_terminator())
1523 rewriter.clone(op, mapping);
1524 for (Operation &op : source.getBody()->without_terminator())
1525 rewriter.clone(op, mapping);
1526
1527 // Fuse the old terminator in_parallel ops into the new one.
1528 scf::InParallelOp targetTerm = target.getTerminator();
1529 scf::InParallelOp sourceTerm = source.getTerminator();
1530 scf::InParallelOp fusedTerm = fusedLoop.getTerminator();
1531 rewriter.setInsertionPointToStart(fusedTerm.getBody());
1532 for (Operation &op : targetTerm.getYieldingOps())
1533 rewriter.clone(op, mapping);
1534 for (Operation &op : sourceTerm.getYieldingOps())
1535 rewriter.clone(op, mapping);
1536
1537 // Replace old loops by substituting their uses by results of the fused loop.
1538 rewriter.replaceOp(target, fusedLoop.getResults().take_front(numTargetOuts));
1539 rewriter.replaceOp(source, fusedLoop.getResults().take_back(numSourceOuts));
1540
1541 return fusedLoop;
1542}
1543
1545 scf::ForOp source,
1546 RewriterBase &rewriter) {
1547 assert(source.getUnsignedCmp() == target.getUnsignedCmp() &&
1548 "incompatible signedness");
1549 unsigned numTargetOuts = target.getNumResults();
1550 unsigned numSourceOuts = source.getNumResults();
1551
1552 // Create fused init_args, with target's init_args before source's init_args.
1553 SmallVector<Value> fusedInitArgs;
1554 llvm::append_range(fusedInitArgs, target.getInitArgs());
1555 llvm::append_range(fusedInitArgs, source.getInitArgs());
1556
1557 // Create a new scf.for op after the source loop (with scf.yield terminator
1558 // (without arguments) only in case its init_args is empty).
1559 rewriter.setInsertionPointAfter(source);
1560 scf::ForOp fusedLoop = scf::ForOp::create(
1561 rewriter, source.getLoc(), source.getLowerBound(), source.getUpperBound(),
1562 source.getStep(), fusedInitArgs, /*bodyBuilder=*/nullptr,
1563 source.getUnsignedCmp());
1564
1565 // Map original induction variables and operands to those of the fused loop.
1566 IRMapping mapping;
1567 mapping.map(target.getInductionVar(), fusedLoop.getInductionVar());
1568 mapping.map(target.getRegionIterArgs(),
1569 fusedLoop.getRegionIterArgs().take_front(numTargetOuts));
1570 mapping.map(source.getInductionVar(), fusedLoop.getInductionVar());
1571 mapping.map(source.getRegionIterArgs(),
1572 fusedLoop.getRegionIterArgs().take_back(numSourceOuts));
1573
1574 // Merge target's body into the new (fused) for loop and then source's body.
1575 rewriter.setInsertionPointToStart(fusedLoop.getBody());
1576 for (Operation &op : target.getBody()->without_terminator())
1577 rewriter.clone(op, mapping);
1578 for (Operation &op : source.getBody()->without_terminator())
1579 rewriter.clone(op, mapping);
1580
1581 // Build fused yield results by appropriately mapping original yield operands.
1582 SmallVector<Value> yieldResults;
1583 for (Value operand : target.getBody()->getTerminator()->getOperands())
1584 yieldResults.push_back(mapping.lookupOrDefault(operand));
1585 for (Value operand : source.getBody()->getTerminator()->getOperands())
1586 yieldResults.push_back(mapping.lookupOrDefault(operand));
1587 if (!yieldResults.empty())
1588 scf::YieldOp::create(rewriter, source.getLoc(), yieldResults);
1589
1590 // Replace old loops by substituting their uses by results of the fused loop.
1591 rewriter.replaceOp(target, fusedLoop.getResults().take_front(numTargetOuts));
1592 rewriter.replaceOp(source, fusedLoop.getResults().take_back(numSourceOuts));
1593
1594 return fusedLoop;
1595}
1596
1597FailureOr<scf::ForallOp> mlir::normalizeForallOp(RewriterBase &rewriter,
1598 scf::ForallOp forallOp) {
1599 SmallVector<OpFoldResult> lbs = forallOp.getMixedLowerBound();
1600 SmallVector<OpFoldResult> ubs = forallOp.getMixedUpperBound();
1601 SmallVector<OpFoldResult> steps = forallOp.getMixedStep();
1602
1603 if (forallOp.isNormalized())
1604 return forallOp;
1605
1606 OpBuilder::InsertionGuard g(rewriter);
1607 auto loc = forallOp.getLoc();
1608 rewriter.setInsertionPoint(forallOp);
1610 for (auto [lb, ub, step] : llvm::zip_equal(lbs, ubs, steps)) {
1611 Range normalizedLoopParams =
1612 emitNormalizedLoopBounds(rewriter, loc, lb, ub, step);
1613 newUbs.push_back(normalizedLoopParams.size);
1614 }
1615 (void)foldDynamicIndexList(newUbs);
1616
1617 // Use the normalized builder since the lower bounds are always 0 and the
1618 // steps are always 1.
1619 auto normalizedForallOp = scf::ForallOp::create(
1620 rewriter, loc, newUbs, forallOp.getOutputs(), forallOp.getMapping(),
1621 [](OpBuilder &, Location, ValueRange) {});
1622
1623 rewriter.inlineRegionBefore(forallOp.getBodyRegion(),
1624 normalizedForallOp.getBodyRegion(),
1625 normalizedForallOp.getBodyRegion().begin());
1626 // Remove the original empty block in the new loop.
1627 rewriter.eraseBlock(&normalizedForallOp.getBodyRegion().back());
1628
1629 rewriter.setInsertionPointToStart(normalizedForallOp.getBody());
1630 // Update the users of the original loop variables.
1631 for (auto [idx, iv] :
1632 llvm::enumerate(normalizedForallOp.getInductionVars())) {
1633 auto origLb = getValueOrCreateConstantIndexOp(rewriter, loc, lbs[idx]);
1634 auto origStep = getValueOrCreateConstantIndexOp(rewriter, loc, steps[idx]);
1635 denormalizeInductionVariable(rewriter, loc, iv, origLb, origStep);
1636 }
1637
1638 rewriter.replaceOp(forallOp, normalizedForallOp);
1639 return normalizedForallOp;
1640}
1641
1644 assert(!loops.empty() && "unexpected empty loop nest");
1645 if (loops.size() == 1)
1646 return isa_and_nonnull<scf::ForOp>(loops.front().getOperation());
1647 for (auto [outerLoop, innerLoop] :
1648 llvm::zip_equal(loops.drop_back(), loops.drop_front())) {
1649 auto outerFor = dyn_cast_or_null<scf::ForOp>(outerLoop.getOperation());
1650 auto innerFor = dyn_cast_or_null<scf::ForOp>(innerLoop.getOperation());
1651 if (!outerFor || !innerFor)
1652 return false;
1653 auto outerBBArgs = outerFor.getRegionIterArgs();
1654 auto innerIterArgs = innerFor.getInitArgs();
1655 if (outerBBArgs.size() != innerIterArgs.size())
1656 return false;
1657
1658 for (auto [outerBBArg, innerIterArg] :
1659 llvm::zip_equal(outerBBArgs, innerIterArgs)) {
1660 if (!llvm::hasSingleElement(outerBBArg.getUses()) ||
1661 innerIterArg != outerBBArg)
1662 return false;
1663 }
1664
1665 ValueRange outerYields =
1666 cast<scf::YieldOp>(outerFor.getBody()->getTerminator())->getOperands();
1667 ValueRange innerResults = innerFor.getResults();
1668 if (outerYields.size() != innerResults.size())
1669 return false;
1670 for (auto [outerYield, innerResult] :
1671 llvm::zip_equal(outerYields, innerResults)) {
1672 if (!llvm::hasSingleElement(innerResult.getUses()) ||
1673 outerYield != innerResult)
1674 return false;
1675 }
1676 }
1677 return true;
1678}
1679
1681mlir::getConstLoopBounds(mlir::LoopLikeOpInterface loopOp) {
1682 std::optional<SmallVector<OpFoldResult>> loBnds = loopOp.getLoopLowerBounds();
1683 std::optional<SmallVector<OpFoldResult>> upBnds = loopOp.getLoopUpperBounds();
1684 std::optional<SmallVector<OpFoldResult>> steps = loopOp.getLoopSteps();
1685 if (!loBnds || !upBnds || !steps)
1686 return {};
1688 for (auto [lb, ub, step] : llvm::zip(*loBnds, *upBnds, *steps)) {
1689 auto lbCst = getConstantIntValue(lb);
1690 auto ubCst = getConstantIntValue(ub);
1691 auto stepCst = getConstantIntValue(step);
1692 if (!lbCst || !ubCst || !stepCst)
1693 return {};
1694 loopRanges.emplace_back(*lbCst, *ubCst, *stepCst);
1695 }
1696 return loopRanges;
1697}
1698
1700mlir::getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp) {
1701 std::optional<SmallVector<OpFoldResult>> loBnds = loopOp.getLoopLowerBounds();
1702 std::optional<SmallVector<OpFoldResult>> upBnds = loopOp.getLoopUpperBounds();
1703 std::optional<SmallVector<OpFoldResult>> steps = loopOp.getLoopSteps();
1704 if (!loBnds || !upBnds || !steps)
1705 return {};
1707 for (auto [lb, ub, step] : llvm::zip(*loBnds, *upBnds, *steps)) {
1708 // TODO(#178506): Signedness is not handled correctly here.
1709 std::optional<llvm::APInt> numIter = constantTripCount(
1710 lb, ub, step, /*isSigned=*/true, scf::computeUbMinusLb);
1711 if (!numIter)
1712 return {};
1713 tripCounts.push_back(*numIter);
1714 }
1715 return tripCounts;
1716}
1717
1718/// Makes `reduceOp` reduce the values of all the copies of the unrolled loop
1719/// body, combining `unrolledReduced` into `reduced` with the reduction
1720/// functions, which reassociates them.
1722 RewriterBase &rewriter, scf::ReduceOp reduceOp, SmallVector<Value> reduced,
1723 ArrayRef<SmallVector<Value>> unrolledReduced) {
1724 OpBuilder::InsertionGuard guard(rewriter);
1725 rewriter.setInsertionPoint(reduceOp);
1726 for (auto [idx, reduction] : llvm::enumerate(reduceOp.getReductions())) {
1727 Block &reduceBlock = reduction.front();
1728 for (ArrayRef<Value> copyReduced : unrolledReduced) {
1729 IRMapping mapping;
1730 mapping.map(reduceBlock.getArgument(0), reduced[idx]);
1731 mapping.map(reduceBlock.getArgument(1), copyReduced[idx]);
1732 for (Operation &reduceBodyOp : reduceBlock.without_terminator())
1733 rewriter.clone(reduceBodyOp, mapping);
1734 reduced[idx] = mapping.lookupOrDefault(
1735 cast<scf::ReduceReturnOp>(reduceBlock.getTerminator()).getResult());
1736 }
1737 }
1738 rewriter.modifyOpInPlace(reduceOp, [&]() { reduceOp->setOperands(reduced); });
1739}
1740
1741FailureOr<scf::ParallelOp> mlir::parallelLoopUnrollByFactors(
1742 scf::ParallelOp op, ArrayRef<uint64_t> unrollFactors,
1743 RewriterBase &rewriter,
1744 function_ref<void(unsigned, Operation *, OpBuilder)> annotateFn,
1745 IRMapping *clonedToSrcOpsMap) {
1746 const unsigned numLoops = op.getNumLoops();
1747 assert(llvm::none_of(unrollFactors, [](uint64_t f) { return f == 0; }) &&
1748 "Expected positive unroll factors");
1749 assert((!unrollFactors.empty() && (unrollFactors.size() <= numLoops)) &&
1750 "Expected non-empty unroll factors of size <= to the number of loops");
1751
1752 // Bail out if no valid unroll factors were provided
1753 if (llvm::all_of(unrollFactors, [](uint64_t f) { return f == 1; }))
1754 return rewriter.notifyMatchFailure(
1755 op, "Unrolling not applied if all factors are 1");
1756
1757 // Return if the loop body is empty.
1758 if (llvm::hasSingleElement(op.getBody()->getOperations()))
1759 return rewriter.notifyMatchFailure(op, "Cannot unroll an empty loop body");
1760
1761 // If the provided unroll factors do not cover all the loop dims, they are
1762 // applied to the inner loop dimensions.
1763 const unsigned firstLoopDimIdx = numLoops - unrollFactors.size();
1764
1765 // Make sure that the unroll factors divide the iteration space evenly
1766 // TODO: Support unrolling loops with dynamic iteration spaces.
1768 if (tripCounts.empty())
1769 return rewriter.notifyMatchFailure(
1770 op, "Failed to compute constant trip counts for the loop. Note that "
1771 "dynamic loop sizes are not supported.");
1772
1773 for (unsigned dimIdx = firstLoopDimIdx; dimIdx < numLoops; dimIdx++) {
1774 const uint64_t unrollFactor = unrollFactors[dimIdx - firstLoopDimIdx];
1775 if (tripCounts[dimIdx].urem(unrollFactor) != 0)
1776 return rewriter.notifyMatchFailure(
1777 op, "Unroll factors don't divide the iteration space evenly");
1778 }
1779
1780 std::optional<SmallVector<OpFoldResult>> maybeFoldSteps = op.getLoopSteps();
1781 if (!maybeFoldSteps)
1782 return rewriter.notifyMatchFailure(op, "Failed to retrieve loop steps");
1784 for (auto step : *maybeFoldSteps)
1785 steps.push_back(static_cast<size_t>(*getConstantIntValue(step)));
1786
1787 // The unrolled iterations share the reduction functions, which therefore
1788 // cannot use values computed by an iteration.
1789 auto reduceOp = cast<scf::ReduceOp>(op.getBody()->getTerminator());
1790 SetVector<Value> usedByReductions;
1791 getUsedValuesDefinedAbove(reduceOp.getReductions(), usedByReductions);
1792 if (!llvm::all_of(usedByReductions, [&](Value value) {
1793 return op.isDefinedOutsideOfLoop(value);
1794 }))
1795 return rewriter.notifyMatchFailure(
1796 op, "Reduction functions using values defined in the loop are not "
1797 "supported");
1798
1799 for (unsigned dimIdx = firstLoopDimIdx; dimIdx < numLoops; dimIdx++) {
1800 const uint64_t unrollFactor = unrollFactors[dimIdx - firstLoopDimIdx];
1801 if (unrollFactor == 1)
1802 continue;
1803 const size_t origStep = steps[dimIdx];
1804 const int64_t newStep = origStep * unrollFactor;
1805
1806 ValueRange iterArgs = ValueRange(op.getRegionIterArgs());
1807 auto yieldedValues = op.getBody()->getTerminator()->getOperands();
1808 SmallVector<Value> reduced(yieldedValues);
1809 SmallVector<SmallVector<Value>> unrolledReduced;
1810
1812 op.getBody(), op.getInductionVars()[dimIdx], unrollFactor,
1813 [&](unsigned i, Value iv, OpBuilder b) {
1814 // iv' = iv + step * i;
1815 const AffineExpr expr = b.getAffineDimExpr(0) + (origStep * i);
1816 const auto map =
1817 b.getDimIdentityMap().dropResult(0).insertResult(expr, 0);
1818 return affine::AffineApplyOp::create(b, iv.getLoc(), map,
1819 ValueRange{iv});
1820 },
1821 /*annotateFn*/ annotateFn, iterArgs, yieldedValues, clonedToSrcOpsMap,
1822 &unrolledReduced);
1823
1824 // The terminator reduces a single value per reduction, while each copy of
1825 // the body computes its own.
1826 combineUnrolledAssociativeReductions(rewriter, reduceOp, std::move(reduced),
1827 unrolledReduced);
1828
1829 // Update loop step
1830 auto prevInsertPoint = rewriter.saveInsertionPoint();
1831 rewriter.setInsertionPoint(op);
1832 op.getStepMutable()[dimIdx].assign(
1833 arith::ConstantIndexOp::create(rewriter, op.getLoc(), newStep));
1834 rewriter.restoreInsertionPoint(prevInsertPoint);
1835 }
1836 return op;
1837}
return success()
static OpFoldResult getProductOfIndexes(RewriterBase &rewriter, Location loc, ArrayRef< OpFoldResult > values)
Definition Utils.cpp:899
static LogicalResult tryIsolateBands(const TileLoops &tileLoops)
Definition Utils.cpp:1320
static void getPerfectlyNestedLoopsImpl(SmallVectorImpl< T > &forOps, T rootForOp, unsigned maxLoops=std::numeric_limits< unsigned >::max())
Collect perfectly nested loops starting from rootForOps.
Definition Utils.cpp:1342
static LogicalResult hoistOpsBetween(scf::ForOp outer, scf::ForOp inner)
Definition Utils.cpp:1276
static Range emitNormalizedLoopBoundsForIndexType(RewriterBase &rewriter, Location loc, OpFoldResult lb, OpFoldResult ub, OpFoldResult step)
Definition Utils.cpp:784
static void combineUnrolledAssociativeReductions(RewriterBase &rewriter, scf::ReduceOp reduceOp, SmallVector< Value > reduced, ArrayRef< SmallVector< Value > > unrolledReduced)
Makes reduceOp reduce the values of all the copies of the unrolled loop body, combining unrolledReduc...
Definition Utils.cpp:1721
static Loops stripmineSink(scf::ForOp forOp, Value factor, ArrayRef< scf::ForOp > targets)
Definition Utils.cpp:1357
static Value ceilDivPositive(OpBuilder &builder, Location loc, Value dividend, int64_t divisor)
Definition Utils.cpp:266
static Value getProductOfIntsOrIndexes(RewriterBase &rewriter, Location loc, ArrayRef< Value > values)
Helper function to multiply a sequence of values.
Definition Utils.cpp:914
static std::pair< SmallVector< Value >, SmallPtrSet< Operation *, 2 > > delinearizeInductionVariable(RewriterBase &rewriter, Location loc, Value linearizedIv, ArrayRef< Value > ubs)
For each original loop, the value of the induction variable can be obtained by dividing the induction...
Definition Utils.cpp:950
static void denormalizeInductionVariableForIndexType(RewriterBase &rewriter, Location loc, Value normalizedIv, OpFoldResult origLb, OpFoldResult origStep)
Definition Utils.cpp:845
static bool areInnerBoundsInvariant(scf::ForOp forOp)
Check if bounds of all inner loops are defined outside of forOp and return false if not.
Definition Utils.cpp:603
static int64_t product(ArrayRef< int64_t > vals)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static llvm::ManagedStatic< PassManagerOptions > options
#define mul(a, b)
Base type for affine expression.
Definition AffineExpr.h:68
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
OpListType::iterator iterator
Definition Block.h:165
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
Operation & front()
Definition Block.h:178
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
BlockArgListType getArguments()
Definition Block.h:112
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Definition Block.h:222
iterator end()
Definition Block.h:169
iterator begin()
Definition Block.h:168
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
MLIRContext * getContext() const
Definition Builders.h:56
TypedAttr getOneAttr(Type type)
Definition Builders.cpp:351
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:65
auto lookup(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:72
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
bool contains(T from) const
Checks to see if a mapping for 'from' exists.
Definition IRMapping.h:51
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
InsertPoint saveInsertionPoint() const
Return a saved insertion point.
Definition Builders.h:388
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
static OpBuilder atBlockTerminator(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the block terminator.
Definition Builders.h:255
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
void restoreInsertionPoint(InsertPoint ip)
Restore the insert point to a previously saved point.
Definition Builders.h:393
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
This class represents a single result from folding an operation.
This class represents an operand of an operation.
Definition Value.h:256
This is a value defined by a result of an operation.
Definition Value.h:456
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
operand_type_range getOperandTypes()
Definition Operation.h:424
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
result_type_range getResultTypes()
Definition Operation.h:455
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
void setOperands(ValueRange operands)
Replace the current operands of this operation with the ones provided in 'operands'.
result_range getResults()
Definition Operation.h:442
Operation * clone(IRMapping &mapper, const CloneOptions &options=CloneOptions::all())
Create a deep copy of this operation, remapping any operands that use values outside of the operation...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
BlockArgListType getArguments()
Definition Region.h:94
iterator begin()
Definition Region.h:55
ParentT getParentOfType()
Find the first parent operation of the given type, or nullptr if there is no ancestor operation.
Definition Region.h:206
bool hasOneBlock()
Return true if this region has exactly one block.
Definition Region.h:68
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseBlock(Block *block)
This method erases all operations in a block.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void replaceAllUsesExcept(Value from, Value to, Operation *exceptedUser)
Find uses of from and replace them with to except if the user is exceptedUser.
virtual void inlineBlockBefore(Block *source, Block *dest, Block::iterator before, ValueRange argValues={})
Inline the operations of block 'source' into block 'dest' before the given position.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIndex() const
Definition Types.cpp:56
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition Types.cpp:114
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
Type getType() const
Return the type of this value.
Definition Value.h:105
bool replaceUsesWithIf(Value newValue, function_ref< bool(OpOperand &)> shouldReplace)
Replace all uses of 'this' value with 'newValue' if the given callback returns true.
Definition Value.cpp:91
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
Specialization of arith.constant op that returns an integer of index type.
Definition Arith.h:85
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
std::optional< llvm::APSInt > computeUbMinusLb(Value lb, Value ub, bool isSigned)
Helper function to compute the difference between two values.
Definition SCF.cpp:114
Include the generated interface declarations.
void getPerfectlyNestedLoops(SmallVectorImpl< scf::ForOp > &nestedLoops, scf::ForOp root)
Get perfectly nested sequence of loops starting at root of loop nest (the first op being another Affi...
Definition Utils.cpp:1444
bool isPerfectlyNestedForLoops(MutableArrayRef< LoopLikeOpInterface > loops)
Check if the provided loops are perfectly nested for-loops.
Definition Utils.cpp:1642
FailureOr< UnrolledLoopInfo > loopUnrollByFactor(scf::ForOp forOp, uint64_t unrollFactor, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn=nullptr, bool shouldPromoteIfSingleIteration=true)
Unrolls this for operation by the specified unroll factor.
Definition Utils.cpp:422
LogicalResult outlineIfOp(RewriterBase &b, scf::IfOp ifOp, func::FuncOp *thenFn, StringRef thenFnName, func::FuncOp *elseFn, StringRef elseFnName)
Outline the then and/or else regions of ifOp as follows:
Definition Utils.cpp:218
void replaceAllUsesInRegionWith(Value orig, Value replacement, Region &region)
Replace all uses of orig within the given region with replacement.
void generateUnrolledLoop(Block *loopBodyBlock, Value iv, uint64_t unrollFactor, function_ref< Value(unsigned, Value, OpBuilder)> ivRemapFn, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn, ValueRange iterArgs, ValueRange yieldedValues, IRMapping *clonedToSrcOpsMap=nullptr, SmallVectorImpl< SmallVector< Value > > *unrolledYieldedValues=nullptr)
Generate unrolled copies of an scf loop's 'loopBodyBlock', with 'iterArgs' and 'yieldedValues' as the...
Definition Utils.cpp:295
SmallVector< scf::ForOp > replaceLoopNestWithNewYields(RewriterBase &rewriter, MutableArrayRef< scf::ForOp > loopNest, ValueRange newIterOperands, const NewYieldValuesFn &newYieldValuesFn, bool replaceIterOperandsUsesInLoop=true)
Update a perfectly nested loop nest to yield new values from the innermost loop and propagating it up...
Definition Utils.cpp:36
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
std::function< SmallVector< Value >( OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
scf::ParallelOp collapseParallelLoops(RewriterBase &rewriter, scf::ParallelOp loops, ArrayRef< std::vector< unsigned > > combinedDimensions)
Take the ParallelLoop and for each set of dimension indices, combine them into a single dimension.
Definition Utils.cpp:1182
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
LogicalResult coalescePerfectlyNestedSCFForLoops(scf::ForOp op)
Walk an affine.for to find a band to coalesce.
Definition Utils.cpp:1107
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:313
Value getValueOrCreateConstantIntOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:105
LogicalResult loopUnrollFull(scf::ForOp forOp)
Unrolls this loop completely.
Definition Utils.cpp:588
llvm::SmallVector< llvm::APInt > getConstLoopTripCounts(mlir::LoopLikeOpInterface loopOp)
Get constant trip counts for each of the induction variables of the given loop operation.
Definition Utils.cpp:1700
std::pair< Loops, Loops > TileLoops
Definition Utils.h:171
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::SmallVector< std::tuple< int64_t, int64_t, int64_t > > getConstLoopBounds(mlir::LoopLikeOpInterface loopOp)
Get constant loop bounds and steps for each of the induction variables of the given loop operation,...
Definition Utils.cpp:1681
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
FailureOr< std::pair< scf::ForOp, scf::ForOp > > splitForOpAtPoint(RewriterBase &rewriter, scf::ForOp forOp, Value splitPoint)
Splits forOp into two consecutive loops at splitPoint: first: [lowerBound, splitPoint) second: [split...
Definition Utils.cpp:371
std::optional< std::pair< APInt, bool > > getConstantAPIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
SliceOptions ForwardSliceOptions
Loops tilePerfectlyNested(scf::ForOp rootForOp, ArrayRef< Value > sizes)
Tile a nest of scf::ForOp loops rooted at rootForOp with the given (parametric) sizes.
Definition Utils.cpp:1432
LogicalResult loopUnrollJamByFactor(scf::ForOp forOp, uint64_t unrollFactor)
Unrolls and jams this scf.for operation by the specified unroll factor.
Definition Utils.cpp:616
bool getInnermostParallelLoops(Operation *rootOp, SmallVectorImpl< scf::ParallelOp > &result)
Get a list of innermost parallel loops contained in rootOp.
Definition Utils.cpp:241
bool isZeroInteger(OpFoldResult v)
Return "true" if v is an integer value/attribute with constant value 0.
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
Definition AffineExpr.h:327
FailureOr< scf::ParallelOp > parallelLoopUnrollByFactors(scf::ParallelOp op, ArrayRef< uint64_t > unrollFactors, RewriterBase &rewriter, function_ref< void(unsigned, Operation *, OpBuilder)> annotateFn=nullptr, IRMapping *clonedToSrcOpsMap=nullptr)
Unroll this scf::Parallel loop by the specified unroll factors.
Definition Utils.cpp:1741
void getUsedValuesDefinedAbove(Region &region, Region &limit, SetVector< Value > &values)
Fill values with a list of values defined at the ancestors of the limit region and used within region...
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
Definition Utils.cpp:1411
FailureOr< func::FuncOp > outlineSingleBlockRegion(RewriterBase &rewriter, Location loc, Region &region, StringRef funcName, func::CallOp *callOp=nullptr)
Outline a region with a single block into a new FuncOp.
Definition Utils.cpp:115
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
bool areValuesDefinedAbove(Range values, Region &limit)
Check if all values in the provided range are defined above the limit region.
Definition RegionUtils.h:26
void denormalizeInductionVariable(RewriterBase &rewriter, Location loc, Value normalizedIv, OpFoldResult origLb, OpFoldResult origStep)
Get back the original induction variable values after loop normalization.
Definition Utils.cpp:870
std::optional< uint64_t > getConstantUIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer zero-extended to 64 bits.
scf::ForallOp fuseIndependentSiblingForallLoops(scf::ForallOp target, scf::ForallOp source, RewriterBase &rewriter)
Given two scf.forall loops, target and source, fuses target into source.
Definition Utils.cpp:1491
LogicalResult coalesceLoops(MutableArrayRef< scf::ForOp > loops)
Replace a perfect nest of "for" loops with a single linearized loop.
Definition Utils.cpp:1099
scf::ForOp fuseIndependentSiblingForLoops(scf::ForOp target, scf::ForOp source, RewriterBase &rewriter)
Given two scf.for loops, target and source, fuses target into source.
Definition Utils.cpp:1544
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
TileLoops extractFixedOuterLoops(scf::ForOp rootFOrOp, ArrayRef< int64_t > sizes)
Definition Utils.cpp:1449
Range emitNormalizedLoopBounds(RewriterBase &rewriter, Location loc, OpFoldResult lb, OpFoldResult ub, OpFoldResult step)
Materialize bounds and step of a zero-based and unit-step loop derived by normalizing the specified b...
Definition Utils.cpp:799
SmallVector< scf::ForOp, 8 > Loops
Tile a nest of standard for loops rooted at rootForOp by finding such parametric tile sizes that the ...
Definition Utils.h:170
bool isOneInteger(OpFoldResult v)
Return true if v is an IntegerAttr with value 1.
std::optional< APInt > constantTripCount(OpFoldResult lb, OpFoldResult ub, OpFoldResult step, bool isSigned, llvm::function_ref< std::optional< llvm::APSInt >(Value, Value, bool)> computeUbMinusLb)
Return the number of iterations for a loop with a lower bound lb, upper bound ub and step step,...
LogicalResult foldDynamicIndexList(SmallVectorImpl< OpFoldResult > &ofrs, bool onlyNonNegative=false, bool onlyNonZero=false)
Returns "success" when any of the elements in ofrs is a constant value.
FailureOr< scf::ForallOp > normalizeForallOp(RewriterBase &rewriter, scf::ForallOp forallOp)
Normalize an scf.forall operation.
Definition Utils.cpp:1597
void getForwardSlice(Operation *op, SetVector< Operation * > *forwardSlice, const ForwardSliceOptions &options={})
Fills forwardSlice with the computed forward slice (i.e.
void walk(Operation *op)
SmallVector< std::pair< Block::iterator, Block::iterator > > subBlocks
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
OpFoldResult stride
OpFoldResult size
OpFoldResult offset
std::optional< scf::ForOp > epilogueLoopOp
Definition Utils.h:111
std::optional< scf::ForOp > mainLoopOp
Definition Utils.h:110
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.