1//===- ForallToFor.cpp - scf.forall to scf.for loop conversion ------------===//
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// Transforms SCF.ForallOp's into SCF.ForOp's.
10//
11//===----------------------------------------------------------------------===//
12
13#include "mlir/Dialect/SCF/Transforms/Passes.h"
14
15#include "mlir/Dialect/SCF/IR/SCF.h"
16#include "mlir/Dialect/SCF/Transforms/Transforms.h"
17#include "mlir/IR/PatternMatch.h"
18
19namespace mlir {
20#define GEN_PASS_DEF_SCFFORALLTOFORLOOP
21#include "mlir/Dialect/SCF/Transforms/Passes.h.inc"
22} // namespace mlir
23
24using namespace mlir;
25using scf::LoopNest;
26
27LogicalResult
28mlir::scf::forallToForLoop(RewriterBase &rewriter, scf::ForallOp forallOp,
29 SmallVectorImpl<Operation *> *results) {
30 OpBuilder::InsertionGuard guard(rewriter);
31 rewriter.setInsertionPoint(forallOp);
32
33 if (!forallOp.getOutputs().empty()) {
34 forallOp.emitWarning()
35 << "skipping scf.forall with outputs, currently not supported";
36 return success();
37 }
38
39 Location loc = forallOp.getLoc();
40 SmallVector<Value> lbs = forallOp.getLowerBound(b&: rewriter);
41 SmallVector<Value> ubs = forallOp.getUpperBound(b&: rewriter);
42 SmallVector<Value> steps = forallOp.getStep(b&: rewriter);
43 LoopNest loopNest = scf::buildLoopNest(builder&: rewriter, loc, lbs, ubs, steps);
44
45 SmallVector<Value> ivs = llvm::map_to_vector(
46 C&: loopNest.loops, F: [](scf::ForOp loop) { return loop.getInductionVar(); });
47
48 Block *innermostBlock = loopNest.loops.back().getBody();
49 rewriter.eraseOp(op: forallOp.getBody()->getTerminator());
50 rewriter.inlineBlockBefore(source: forallOp.getBody(), dest: innermostBlock,
51 before: innermostBlock->getTerminator()->getIterator(),
52 argValues: ivs);
53 rewriter.eraseOp(op: forallOp);
54
55 if (results) {
56 llvm::move(Range&: loopNest.loops, Out: std::back_inserter(x&: *results));
57 }
58
59 return success();
60}
61
62namespace {
63struct ForallToForLoop : public impl::SCFForallToForLoopBase<ForallToForLoop> {
64 void runOnOperation() override {
65 Operation *parentOp = getOperation();
66 IRRewriter rewriter(parentOp->getContext());
67
68 parentOp->walk(callback: [&](scf::ForallOp forallOp) {
69 if (failed(Result: scf::forallToForLoop(rewriter, forallOp))) {
70 return signalPassFailure();
71 }
72 });
73 }
74};
75} // namespace
76
77std::unique_ptr<Pass> mlir::createForallToForLoopPass() {
78 return std::make_unique<ForallToForLoop>();
79}
80