1c30ab6c2SEugene Zhulenev //===- AsyncParallelFor.cpp - Implementation of Async Parallel For --------===//
2c30ab6c2SEugene Zhulenev //
3c30ab6c2SEugene Zhulenev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4c30ab6c2SEugene Zhulenev // See https://llvm.org/LICENSE.txt for license information.
5c30ab6c2SEugene Zhulenev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c30ab6c2SEugene Zhulenev //
7c30ab6c2SEugene Zhulenev //===----------------------------------------------------------------------===//
8c30ab6c2SEugene Zhulenev //
986ad0af8SEugene Zhulenev // This file implements scf.parallel to scf.for + async.execute conversion pass.
10c30ab6c2SEugene Zhulenev //
11c30ab6c2SEugene Zhulenev //===----------------------------------------------------------------------===//
12c30ab6c2SEugene Zhulenev 
13c30ab6c2SEugene Zhulenev #include "PassDetail.h"
14c30ab6c2SEugene Zhulenev #include "mlir/Dialect/Async/IR/Async.h"
15c30ab6c2SEugene Zhulenev #include "mlir/Dialect/Async/Passes.h"
16c30ab6c2SEugene Zhulenev #include "mlir/Dialect/SCF/SCF.h"
17c30ab6c2SEugene Zhulenev #include "mlir/Dialect/StandardOps/IR/Ops.h"
18c30ab6c2SEugene Zhulenev #include "mlir/IR/BlockAndValueMapping.h"
1986ad0af8SEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h"
20c30ab6c2SEugene Zhulenev #include "mlir/IR/PatternMatch.h"
21c30ab6c2SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
2286ad0af8SEugene Zhulenev #include "mlir/Transforms/RegionUtils.h"
23c30ab6c2SEugene Zhulenev 
24c30ab6c2SEugene Zhulenev using namespace mlir;
25c30ab6c2SEugene Zhulenev using namespace mlir::async;
26c30ab6c2SEugene Zhulenev 
27c30ab6c2SEugene Zhulenev #define DEBUG_TYPE "async-parallel-for"
28c30ab6c2SEugene Zhulenev 
29c30ab6c2SEugene Zhulenev namespace {
30c30ab6c2SEugene Zhulenev 
31c30ab6c2SEugene Zhulenev // Rewrite scf.parallel operation into multiple concurrent async.execute
32c30ab6c2SEugene Zhulenev // operations over non overlapping subranges of the original loop.
33c30ab6c2SEugene Zhulenev //
34c30ab6c2SEugene Zhulenev // Example:
35c30ab6c2SEugene Zhulenev //
3686ad0af8SEugene Zhulenev //   scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) {
37c30ab6c2SEugene Zhulenev //     "do_some_compute"(%i, %j): () -> ()
38c30ab6c2SEugene Zhulenev //   }
39c30ab6c2SEugene Zhulenev //
40c30ab6c2SEugene Zhulenev // Converted to:
41c30ab6c2SEugene Zhulenev //
4286ad0af8SEugene Zhulenev //   // Parallel compute function that executes the parallel body region for
4386ad0af8SEugene Zhulenev //   // a subset of the parallel iteration space defined by the one-dimensional
4486ad0af8SEugene Zhulenev //   // compute block index.
4586ad0af8SEugene Zhulenev //   func parallel_compute_function(%block_index : index, %block_size : index,
4686ad0af8SEugene Zhulenev //                                  <parallel operation properties>, ...) {
4786ad0af8SEugene Zhulenev //     // Compute multi-dimensional loop bounds for %block_index.
4886ad0af8SEugene Zhulenev //     %block_lbi, %block_lbj = ...
4986ad0af8SEugene Zhulenev //     %block_ubi, %block_ubj = ...
50c30ab6c2SEugene Zhulenev //
5186ad0af8SEugene Zhulenev //     // Clone parallel operation body into the scf.for loop nest.
5286ad0af8SEugene Zhulenev //     scf.for %i = %blockLbi to %blockUbi {
5386ad0af8SEugene Zhulenev //       scf.for %j = block_lbj to %block_ubj {
54c30ab6c2SEugene Zhulenev //         "do_some_compute"(%i, %j): () -> ()
55c30ab6c2SEugene Zhulenev //       }
56c30ab6c2SEugene Zhulenev //     }
57c30ab6c2SEugene Zhulenev //   }
58c30ab6c2SEugene Zhulenev //
5986ad0af8SEugene Zhulenev // And a dispatch function depending on the `asyncDispatch` option.
6086ad0af8SEugene Zhulenev //
6186ad0af8SEugene Zhulenev // When async dispatch is on: (pseudocode)
6286ad0af8SEugene Zhulenev //
6386ad0af8SEugene Zhulenev //   %block_size = ... compute parallel compute block size
6486ad0af8SEugene Zhulenev //   %block_count = ... compute the number of compute blocks
6586ad0af8SEugene Zhulenev //
6686ad0af8SEugene Zhulenev //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
6786ad0af8SEugene Zhulenev //     // Keep splitting block range until we reached a range of size 1.
6886ad0af8SEugene Zhulenev //     while (%block_end - %block_start > 1) {
6986ad0af8SEugene Zhulenev //       %mid_index = block_start + (block_end - block_start) / 2;
7086ad0af8SEugene Zhulenev //       async.execute { call @async_dispatch(%mid_index, %block_end); }
7186ad0af8SEugene Zhulenev //       %block_end = %mid_index
72c30ab6c2SEugene Zhulenev //     }
73c30ab6c2SEugene Zhulenev //
7486ad0af8SEugene Zhulenev //     // Call parallel compute function for a single block.
7586ad0af8SEugene Zhulenev //     call @parallel_compute_fn(%block_start, %block_size, ...);
7686ad0af8SEugene Zhulenev //   }
77c30ab6c2SEugene Zhulenev //
7886ad0af8SEugene Zhulenev //   // Launch async dispatch for [0, block_count) range.
7986ad0af8SEugene Zhulenev //   call @async_dispatch(%c0, %block_count);
80c30ab6c2SEugene Zhulenev //
8186ad0af8SEugene Zhulenev // When async dispatch is off:
82c30ab6c2SEugene Zhulenev //
8386ad0af8SEugene Zhulenev //   %block_size = ... compute parallel compute block size
8486ad0af8SEugene Zhulenev //   %block_count = ... compute the number of compute blocks
8586ad0af8SEugene Zhulenev //
8686ad0af8SEugene Zhulenev //   scf.for %block_index = %c0 to %block_count {
8786ad0af8SEugene Zhulenev //      call @parallel_compute_fn(%block_index, %block_size, ...)
8886ad0af8SEugene Zhulenev //   }
8986ad0af8SEugene Zhulenev //
9086ad0af8SEugene Zhulenev struct AsyncParallelForPass
9186ad0af8SEugene Zhulenev     : public AsyncParallelForBase<AsyncParallelForPass> {
9286ad0af8SEugene Zhulenev   AsyncParallelForPass() = default;
9334a164c9SEugene Zhulenev 
9434a164c9SEugene Zhulenev   AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads,
95*55dfab39Sbakhtiyar                        int32_t minTaskSize) {
9634a164c9SEugene Zhulenev     this->asyncDispatch = asyncDispatch;
9734a164c9SEugene Zhulenev     this->numWorkerThreads = numWorkerThreads;
98*55dfab39Sbakhtiyar     this->minTaskSize = minTaskSize;
9934a164c9SEugene Zhulenev   }
10034a164c9SEugene Zhulenev 
10186ad0af8SEugene Zhulenev   void runOnOperation() override;
10286ad0af8SEugene Zhulenev };
10386ad0af8SEugene Zhulenev 
104c30ab6c2SEugene Zhulenev struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> {
105c30ab6c2SEugene Zhulenev public:
10686ad0af8SEugene Zhulenev   AsyncParallelForRewrite(MLIRContext *ctx, bool asyncDispatch,
107*55dfab39Sbakhtiyar                           int32_t numWorkerThreads, int32_t minTaskSize)
10886ad0af8SEugene Zhulenev       : OpRewritePattern(ctx), asyncDispatch(asyncDispatch),
109*55dfab39Sbakhtiyar         numWorkerThreads(numWorkerThreads), minTaskSize(minTaskSize) {}
110c30ab6c2SEugene Zhulenev 
111c30ab6c2SEugene Zhulenev   LogicalResult matchAndRewrite(scf::ParallelOp op,
112c30ab6c2SEugene Zhulenev                                 PatternRewriter &rewriter) const override;
113c30ab6c2SEugene Zhulenev 
114c30ab6c2SEugene Zhulenev private:
11586ad0af8SEugene Zhulenev   bool asyncDispatch;
11686ad0af8SEugene Zhulenev   int32_t numWorkerThreads;
117*55dfab39Sbakhtiyar   int32_t minTaskSize;
118c30ab6c2SEugene Zhulenev };
119c30ab6c2SEugene Zhulenev 
12086ad0af8SEugene Zhulenev struct ParallelComputeFunctionType {
12186ad0af8SEugene Zhulenev   FunctionType type;
12286ad0af8SEugene Zhulenev   llvm::SmallVector<Value> captures;
12386ad0af8SEugene Zhulenev };
12486ad0af8SEugene Zhulenev 
12586ad0af8SEugene Zhulenev struct ParallelComputeFunction {
12686ad0af8SEugene Zhulenev   FuncOp func;
12786ad0af8SEugene Zhulenev   llvm::SmallVector<Value> captures;
128c30ab6c2SEugene Zhulenev };
129c30ab6c2SEugene Zhulenev 
130c30ab6c2SEugene Zhulenev } // namespace
131c30ab6c2SEugene Zhulenev 
13286ad0af8SEugene Zhulenev // Converts one-dimensional iteration index in the [0, tripCount) interval
13386ad0af8SEugene Zhulenev // into multidimensional iteration coordinate.
13486ad0af8SEugene Zhulenev static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index,
13534a164c9SEugene Zhulenev                                       ArrayRef<Value> tripCounts) {
13686ad0af8SEugene Zhulenev   SmallVector<Value> coords(tripCounts.size());
13786ad0af8SEugene Zhulenev   assert(!tripCounts.empty() && "tripCounts must be not empty");
13886ad0af8SEugene Zhulenev 
13986ad0af8SEugene Zhulenev   for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) {
14086ad0af8SEugene Zhulenev     coords[i] = b.create<SignedRemIOp>(index, tripCounts[i]);
14186ad0af8SEugene Zhulenev     index = b.create<SignedDivIOp>(index, tripCounts[i]);
14286ad0af8SEugene Zhulenev   }
14386ad0af8SEugene Zhulenev 
14486ad0af8SEugene Zhulenev   return coords;
14586ad0af8SEugene Zhulenev }
14686ad0af8SEugene Zhulenev 
14786ad0af8SEugene Zhulenev // Returns a function type and implicit captures for a parallel compute
14886ad0af8SEugene Zhulenev // function. We'll need a list of implicit captures to setup block and value
14986ad0af8SEugene Zhulenev // mapping when we'll clone the body of the parallel operation.
15086ad0af8SEugene Zhulenev static ParallelComputeFunctionType
15186ad0af8SEugene Zhulenev getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) {
15286ad0af8SEugene Zhulenev   // Values implicitly captured by the parallel operation.
15386ad0af8SEugene Zhulenev   llvm::SetVector<Value> captures;
15486ad0af8SEugene Zhulenev   getUsedValuesDefinedAbove(op.region(), op.region(), captures);
15586ad0af8SEugene Zhulenev 
15686ad0af8SEugene Zhulenev   llvm::SmallVector<Type> inputs;
15786ad0af8SEugene Zhulenev   inputs.reserve(2 + 4 * op.getNumLoops() + captures.size());
15886ad0af8SEugene Zhulenev 
15986ad0af8SEugene Zhulenev   Type indexTy = rewriter.getIndexType();
16086ad0af8SEugene Zhulenev 
16186ad0af8SEugene Zhulenev   // One-dimensional iteration space defined by the block index and size.
16286ad0af8SEugene Zhulenev   inputs.push_back(indexTy); // blockIndex
16386ad0af8SEugene Zhulenev   inputs.push_back(indexTy); // blockSize
16486ad0af8SEugene Zhulenev 
16586ad0af8SEugene Zhulenev   // Multi-dimensional parallel iteration space defined by the loop trip counts.
16686ad0af8SEugene Zhulenev   for (unsigned i = 0; i < op.getNumLoops(); ++i)
16786ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // loop tripCount
16886ad0af8SEugene Zhulenev 
16986ad0af8SEugene Zhulenev   // Parallel operation lower bound, upper bound and step.
17086ad0af8SEugene Zhulenev   for (unsigned i = 0; i < op.getNumLoops(); ++i) {
17186ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // lower bound
17286ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // upper bound
17386ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // step
17486ad0af8SEugene Zhulenev   }
17586ad0af8SEugene Zhulenev 
17686ad0af8SEugene Zhulenev   // Types of the implicit captures.
17786ad0af8SEugene Zhulenev   for (Value capture : captures)
17886ad0af8SEugene Zhulenev     inputs.push_back(capture.getType());
17986ad0af8SEugene Zhulenev 
18086ad0af8SEugene Zhulenev   // Convert captures to vector for later convenience.
18186ad0af8SEugene Zhulenev   SmallVector<Value> capturesVector(captures.begin(), captures.end());
18286ad0af8SEugene Zhulenev   return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector};
18386ad0af8SEugene Zhulenev }
18486ad0af8SEugene Zhulenev 
18586ad0af8SEugene Zhulenev // Create a parallel compute fuction from the parallel operation.
18686ad0af8SEugene Zhulenev static ParallelComputeFunction
18786ad0af8SEugene Zhulenev createParallelComputeFunction(scf::ParallelOp op, PatternRewriter &rewriter) {
18886ad0af8SEugene Zhulenev   OpBuilder::InsertionGuard guard(rewriter);
18986ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
19086ad0af8SEugene Zhulenev 
19186ad0af8SEugene Zhulenev   ModuleOp module = op->getParentOfType<ModuleOp>();
19286ad0af8SEugene Zhulenev 
193b537c5b4SEugene Zhulenev   // Make sure that all constants will be inside the parallel operation body to
194b537c5b4SEugene Zhulenev   // reduce the number of parallel compute function arguments.
195b537c5b4SEugene Zhulenev   cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter);
196b537c5b4SEugene Zhulenev 
19786ad0af8SEugene Zhulenev   ParallelComputeFunctionType computeFuncType =
19886ad0af8SEugene Zhulenev       getParallelComputeFunctionType(op, rewriter);
19986ad0af8SEugene Zhulenev 
20086ad0af8SEugene Zhulenev   FunctionType type = computeFuncType.type;
20186ad0af8SEugene Zhulenev   FuncOp func = FuncOp::create(op.getLoc(), "parallel_compute_fn", type);
20286ad0af8SEugene Zhulenev   func.setPrivate();
20386ad0af8SEugene Zhulenev 
20486ad0af8SEugene Zhulenev   // Insert function into the module symbol table and assign it unique name.
20586ad0af8SEugene Zhulenev   SymbolTable symbolTable(module);
20686ad0af8SEugene Zhulenev   symbolTable.insert(func);
20786ad0af8SEugene Zhulenev   rewriter.getListener()->notifyOperationInserted(func);
20886ad0af8SEugene Zhulenev 
20986ad0af8SEugene Zhulenev   // Create function entry block.
21086ad0af8SEugene Zhulenev   Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs());
21186ad0af8SEugene Zhulenev   b.setInsertionPointToEnd(block);
21286ad0af8SEugene Zhulenev 
21386ad0af8SEugene Zhulenev   unsigned offset = 0; // argument offset for arguments decoding
21486ad0af8SEugene Zhulenev 
21534a164c9SEugene Zhulenev   // Returns `numArguments` arguments starting from `offset` and updates offset
21634a164c9SEugene Zhulenev   // by moving forward to the next argument.
21734a164c9SEugene Zhulenev   auto getArguments = [&](unsigned numArguments) -> ArrayRef<Value> {
21834a164c9SEugene Zhulenev     auto args = block->getArguments();
21934a164c9SEugene Zhulenev     auto slice = args.drop_front(offset).take_front(numArguments);
22034a164c9SEugene Zhulenev     offset += numArguments;
22134a164c9SEugene Zhulenev     return {slice.begin(), slice.end()};
22286ad0af8SEugene Zhulenev   };
22386ad0af8SEugene Zhulenev 
22486ad0af8SEugene Zhulenev   // Block iteration position defined by the block index and size.
22586ad0af8SEugene Zhulenev   Value blockIndex = block->getArgument(offset++);
22686ad0af8SEugene Zhulenev   Value blockSize = block->getArgument(offset++);
22786ad0af8SEugene Zhulenev 
22886ad0af8SEugene Zhulenev   // Constants used below.
22934a164c9SEugene Zhulenev   Value c0 = b.create<ConstantIndexOp>(0);
23034a164c9SEugene Zhulenev   Value c1 = b.create<ConstantIndexOp>(1);
23186ad0af8SEugene Zhulenev 
23286ad0af8SEugene Zhulenev   // Multi-dimensional parallel iteration space defined by the loop trip counts.
23334a164c9SEugene Zhulenev   ArrayRef<Value> tripCounts = getArguments(op.getNumLoops());
23486ad0af8SEugene Zhulenev 
23586ad0af8SEugene Zhulenev   // Compute a product of trip counts to get the size of the flattened
23686ad0af8SEugene Zhulenev   // one-dimensional iteration space.
23786ad0af8SEugene Zhulenev   Value tripCount = tripCounts[0];
23886ad0af8SEugene Zhulenev   for (unsigned i = 1; i < tripCounts.size(); ++i)
23986ad0af8SEugene Zhulenev     tripCount = b.create<MulIOp>(tripCount, tripCounts[i]);
24086ad0af8SEugene Zhulenev 
24134a164c9SEugene Zhulenev   // Parallel operation lower bound and step.
24234a164c9SEugene Zhulenev   ArrayRef<Value> lowerBound = getArguments(op.getNumLoops());
24334a164c9SEugene Zhulenev   offset += op.getNumLoops(); // skip upper bound arguments
24434a164c9SEugene Zhulenev   ArrayRef<Value> step = getArguments(op.getNumLoops());
24586ad0af8SEugene Zhulenev 
24686ad0af8SEugene Zhulenev   // Remaining arguments are implicit captures of the parallel operation.
24734a164c9SEugene Zhulenev   ArrayRef<Value> captures = getArguments(block->getNumArguments() - offset);
24886ad0af8SEugene Zhulenev 
24986ad0af8SEugene Zhulenev   // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]:
25086ad0af8SEugene Zhulenev   //   blockFirstIndex = blockIndex * blockSize
25186ad0af8SEugene Zhulenev   Value blockFirstIndex = b.create<MulIOp>(blockIndex, blockSize);
25286ad0af8SEugene Zhulenev 
25386ad0af8SEugene Zhulenev   // The last one-dimensional index in the block defined by the `blockIndex`:
25434a164c9SEugene Zhulenev   //   blockLastIndex = max(blockFirstIndex + blockSize, tripCount) - 1
25534a164c9SEugene Zhulenev   Value blockEnd0 = b.create<AddIOp>(blockFirstIndex, blockSize);
25634a164c9SEugene Zhulenev   Value blockEnd1 = b.create<CmpIOp>(CmpIPredicate::sge, blockEnd0, tripCount);
25734a164c9SEugene Zhulenev   Value blockEnd2 = b.create<SelectOp>(blockEnd1, tripCount, blockEnd0);
25834a164c9SEugene Zhulenev   Value blockLastIndex = b.create<SubIOp>(blockEnd2, c1);
25986ad0af8SEugene Zhulenev 
26086ad0af8SEugene Zhulenev   // Convert one-dimensional indices to multi-dimensional coordinates.
26186ad0af8SEugene Zhulenev   auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts);
26286ad0af8SEugene Zhulenev   auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts);
26386ad0af8SEugene Zhulenev 
26434a164c9SEugene Zhulenev   // Compute loops upper bounds derived from the block last coordinates:
26586ad0af8SEugene Zhulenev   //   blockEndCoord[i] = blockLastCoord[i] + 1
26686ad0af8SEugene Zhulenev   //
26786ad0af8SEugene Zhulenev   // Block first and last coordinates can be the same along the outer compute
26834a164c9SEugene Zhulenev   // dimension when inner compute dimension contains multiple blocks.
26986ad0af8SEugene Zhulenev   SmallVector<Value> blockEndCoord(op.getNumLoops());
27086ad0af8SEugene Zhulenev   for (size_t i = 0; i < blockLastCoord.size(); ++i)
27186ad0af8SEugene Zhulenev     blockEndCoord[i] = b.create<AddIOp>(blockLastCoord[i], c1);
27286ad0af8SEugene Zhulenev 
27386ad0af8SEugene Zhulenev   // Construct a loop nest out of scf.for operations that will iterate over
27486ad0af8SEugene Zhulenev   // all coordinates in [blockFirstCoord, blockLastCoord] range.
27586ad0af8SEugene Zhulenev   using LoopBodyBuilder =
27686ad0af8SEugene Zhulenev       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
27786ad0af8SEugene Zhulenev   using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>;
27886ad0af8SEugene Zhulenev 
27986ad0af8SEugene Zhulenev   // Parallel region induction variables computed from the multi-dimensional
28086ad0af8SEugene Zhulenev   // iteration coordinate using parallel operation bounds and step:
28186ad0af8SEugene Zhulenev   //
28286ad0af8SEugene Zhulenev   //   computeBlockInductionVars[loopIdx] =
28386ad0af8SEugene Zhulenev   //       lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopDdx]
28486ad0af8SEugene Zhulenev   SmallVector<Value> computeBlockInductionVars(op.getNumLoops());
28586ad0af8SEugene Zhulenev 
28686ad0af8SEugene Zhulenev   // We need to know if we are in the first or last iteration of the
28786ad0af8SEugene Zhulenev   // multi-dimensional loop for each loop in the nest, so we can decide what
28886ad0af8SEugene Zhulenev   // loop bounds should we use for the nested loops: bounds defined by compute
28986ad0af8SEugene Zhulenev   // block interval, or bounds defined by the parallel operation.
29086ad0af8SEugene Zhulenev   //
29186ad0af8SEugene Zhulenev   // Example: 2d parallel operation
29286ad0af8SEugene Zhulenev   //                   i   j
29386ad0af8SEugene Zhulenev   //   loop sizes:   [50, 50]
29486ad0af8SEugene Zhulenev   //   first coord:  [25, 25]
29586ad0af8SEugene Zhulenev   //   last coord:   [30, 30]
29686ad0af8SEugene Zhulenev   //
29786ad0af8SEugene Zhulenev   // If `i` is equal to 25 then iteration over `j` should start at 25, when `i`
29886ad0af8SEugene Zhulenev   // is between 25 and 30 it should start at 0. The upper bound for `j` should
29986ad0af8SEugene Zhulenev   // be 50, except when `i` is equal to 30, then it should also be 30.
30086ad0af8SEugene Zhulenev   //
30186ad0af8SEugene Zhulenev   // Value at ith position specifies if all loops in [0, i) range of the loop
30286ad0af8SEugene Zhulenev   // nest are in the first/last iteration.
30386ad0af8SEugene Zhulenev   SmallVector<Value> isBlockFirstCoord(op.getNumLoops());
30486ad0af8SEugene Zhulenev   SmallVector<Value> isBlockLastCoord(op.getNumLoops());
30586ad0af8SEugene Zhulenev 
30686ad0af8SEugene Zhulenev   // Builds inner loop nest inside async.execute operation that does all the
30786ad0af8SEugene Zhulenev   // work concurrently.
30886ad0af8SEugene Zhulenev   LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder {
30986ad0af8SEugene Zhulenev     return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv,
31086ad0af8SEugene Zhulenev                         ValueRange args) {
31186ad0af8SEugene Zhulenev       ImplicitLocOpBuilder nb(loc, nestedBuilder);
31286ad0af8SEugene Zhulenev 
31386ad0af8SEugene Zhulenev       // Compute induction variable for `loopIdx`.
31486ad0af8SEugene Zhulenev       computeBlockInductionVars[loopIdx] = nb.create<AddIOp>(
31586ad0af8SEugene Zhulenev           lowerBound[loopIdx], nb.create<MulIOp>(iv, step[loopIdx]));
31686ad0af8SEugene Zhulenev 
31786ad0af8SEugene Zhulenev       // Check if we are inside first or last iteration of the loop.
31886ad0af8SEugene Zhulenev       isBlockFirstCoord[loopIdx] =
31986ad0af8SEugene Zhulenev           nb.create<CmpIOp>(CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]);
32086ad0af8SEugene Zhulenev       isBlockLastCoord[loopIdx] =
32186ad0af8SEugene Zhulenev           nb.create<CmpIOp>(CmpIPredicate::eq, iv, blockLastCoord[loopIdx]);
32286ad0af8SEugene Zhulenev 
32334a164c9SEugene Zhulenev       // Check if the previous loop is in its first or last iteration.
32486ad0af8SEugene Zhulenev       if (loopIdx > 0) {
32586ad0af8SEugene Zhulenev         isBlockFirstCoord[loopIdx] = nb.create<AndOp>(
32686ad0af8SEugene Zhulenev             isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]);
32786ad0af8SEugene Zhulenev         isBlockLastCoord[loopIdx] = nb.create<AndOp>(
32886ad0af8SEugene Zhulenev             isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]);
32986ad0af8SEugene Zhulenev       }
33086ad0af8SEugene Zhulenev 
33186ad0af8SEugene Zhulenev       // Keep building loop nest.
33286ad0af8SEugene Zhulenev       if (loopIdx < op.getNumLoops() - 1) {
33386ad0af8SEugene Zhulenev         // Select nested loop lower/upper bounds depending on out position in
33486ad0af8SEugene Zhulenev         // the multi-dimensional iteration space.
33586ad0af8SEugene Zhulenev         auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx],
33686ad0af8SEugene Zhulenev                                       blockFirstCoord[loopIdx + 1], c0);
33786ad0af8SEugene Zhulenev 
33886ad0af8SEugene Zhulenev         auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx],
33986ad0af8SEugene Zhulenev                                       blockEndCoord[loopIdx + 1],
34086ad0af8SEugene Zhulenev                                       tripCounts[loopIdx + 1]);
34186ad0af8SEugene Zhulenev 
34286ad0af8SEugene Zhulenev         nb.create<scf::ForOp>(lb, ub, c1, ValueRange(),
34386ad0af8SEugene Zhulenev                               workLoopBuilder(loopIdx + 1));
34486ad0af8SEugene Zhulenev         nb.create<scf::YieldOp>(loc);
34586ad0af8SEugene Zhulenev         return;
34686ad0af8SEugene Zhulenev       }
34786ad0af8SEugene Zhulenev 
34886ad0af8SEugene Zhulenev       // Copy the body of the parallel op into the inner-most loop.
34986ad0af8SEugene Zhulenev       BlockAndValueMapping mapping;
35086ad0af8SEugene Zhulenev       mapping.map(op.getInductionVars(), computeBlockInductionVars);
35186ad0af8SEugene Zhulenev       mapping.map(computeFuncType.captures, captures);
35286ad0af8SEugene Zhulenev 
35386ad0af8SEugene Zhulenev       for (auto &bodyOp : op.getLoopBody().getOps())
35486ad0af8SEugene Zhulenev         nb.clone(bodyOp, mapping);
35586ad0af8SEugene Zhulenev     };
35686ad0af8SEugene Zhulenev   };
35786ad0af8SEugene Zhulenev 
35886ad0af8SEugene Zhulenev   b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(),
35986ad0af8SEugene Zhulenev                        workLoopBuilder(0));
36086ad0af8SEugene Zhulenev   b.create<ReturnOp>(ValueRange());
36186ad0af8SEugene Zhulenev 
36286ad0af8SEugene Zhulenev   return {func, std::move(computeFuncType.captures)};
36386ad0af8SEugene Zhulenev }
36486ad0af8SEugene Zhulenev 
36586ad0af8SEugene Zhulenev // Creates recursive async dispatch function for the given parallel compute
36686ad0af8SEugene Zhulenev // function. Dispatch function keeps splitting block range into halves until it
36786ad0af8SEugene Zhulenev // reaches a single block, and then excecutes it inline.
36886ad0af8SEugene Zhulenev //
36986ad0af8SEugene Zhulenev // Function pseudocode (mix of C++ and MLIR):
37086ad0af8SEugene Zhulenev //
37186ad0af8SEugene Zhulenev //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
37286ad0af8SEugene Zhulenev //
37386ad0af8SEugene Zhulenev //     // Keep splitting block range until we reached a range of size 1.
37486ad0af8SEugene Zhulenev //     while (%block_end - %block_start > 1) {
37586ad0af8SEugene Zhulenev //       %mid_index = block_start + (block_end - block_start) / 2;
37686ad0af8SEugene Zhulenev //       async.execute { call @async_dispatch(%mid_index, %block_end); }
37786ad0af8SEugene Zhulenev //       %block_end = %mid_index
37886ad0af8SEugene Zhulenev //     }
37986ad0af8SEugene Zhulenev //
38086ad0af8SEugene Zhulenev //     // Call parallel compute function for a single block.
38186ad0af8SEugene Zhulenev //     call @parallel_compute_fn(%block_start, %block_size, ...);
38286ad0af8SEugene Zhulenev //   }
38386ad0af8SEugene Zhulenev //
38486ad0af8SEugene Zhulenev static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc,
38586ad0af8SEugene Zhulenev                                           PatternRewriter &rewriter) {
38686ad0af8SEugene Zhulenev   OpBuilder::InsertionGuard guard(rewriter);
38786ad0af8SEugene Zhulenev   Location loc = computeFunc.func.getLoc();
38886ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(loc, rewriter);
38986ad0af8SEugene Zhulenev 
39086ad0af8SEugene Zhulenev   ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>();
39186ad0af8SEugene Zhulenev 
39286ad0af8SEugene Zhulenev   ArrayRef<Type> computeFuncInputTypes =
39386ad0af8SEugene Zhulenev       computeFunc.func.type().cast<FunctionType>().getInputs();
39486ad0af8SEugene Zhulenev 
39586ad0af8SEugene Zhulenev   // Compared to the parallel compute function async dispatch function takes
39686ad0af8SEugene Zhulenev   // additional !async.group argument. Also instead of a single `blockIndex` it
39786ad0af8SEugene Zhulenev   // takes `blockStart` and `blockEnd` arguments to define the range of
39886ad0af8SEugene Zhulenev   // dispatched blocks.
39986ad0af8SEugene Zhulenev   SmallVector<Type> inputTypes;
40086ad0af8SEugene Zhulenev   inputTypes.push_back(async::GroupType::get(rewriter.getContext()));
40186ad0af8SEugene Zhulenev   inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument
40286ad0af8SEugene Zhulenev   inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end());
40386ad0af8SEugene Zhulenev 
40486ad0af8SEugene Zhulenev   FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange());
40586ad0af8SEugene Zhulenev   FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type);
40686ad0af8SEugene Zhulenev   func.setPrivate();
40786ad0af8SEugene Zhulenev 
40886ad0af8SEugene Zhulenev   // Insert function into the module symbol table and assign it unique name.
40986ad0af8SEugene Zhulenev   SymbolTable symbolTable(module);
41086ad0af8SEugene Zhulenev   symbolTable.insert(func);
41186ad0af8SEugene Zhulenev   rewriter.getListener()->notifyOperationInserted(func);
41286ad0af8SEugene Zhulenev 
41386ad0af8SEugene Zhulenev   // Create function entry block.
41486ad0af8SEugene Zhulenev   Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs());
41586ad0af8SEugene Zhulenev   b.setInsertionPointToEnd(block);
41686ad0af8SEugene Zhulenev 
41786ad0af8SEugene Zhulenev   Type indexTy = b.getIndexType();
41834a164c9SEugene Zhulenev   Value c1 = b.create<ConstantIndexOp>(1);
41934a164c9SEugene Zhulenev   Value c2 = b.create<ConstantIndexOp>(2);
42086ad0af8SEugene Zhulenev 
42186ad0af8SEugene Zhulenev   // Get the async group that will track async dispatch completion.
42286ad0af8SEugene Zhulenev   Value group = block->getArgument(0);
42386ad0af8SEugene Zhulenev 
42486ad0af8SEugene Zhulenev   // Get the block iteration range: [blockStart, blockEnd)
42586ad0af8SEugene Zhulenev   Value blockStart = block->getArgument(1);
42686ad0af8SEugene Zhulenev   Value blockEnd = block->getArgument(2);
42786ad0af8SEugene Zhulenev 
42886ad0af8SEugene Zhulenev   // Create a work splitting while loop for the [blockStart, blockEnd) range.
42986ad0af8SEugene Zhulenev   SmallVector<Type> types = {indexTy, indexTy};
43086ad0af8SEugene Zhulenev   SmallVector<Value> operands = {blockStart, blockEnd};
43186ad0af8SEugene Zhulenev 
43286ad0af8SEugene Zhulenev   // Create a recursive dispatch loop.
43386ad0af8SEugene Zhulenev   scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands);
43486ad0af8SEugene Zhulenev   Block *before = b.createBlock(&whileOp.before(), {}, types);
43586ad0af8SEugene Zhulenev   Block *after = b.createBlock(&whileOp.after(), {}, types);
43686ad0af8SEugene Zhulenev 
43786ad0af8SEugene Zhulenev   // Setup dispatch loop condition block: decide if we need to go into the
43886ad0af8SEugene Zhulenev   // `after` block and launch one more async dispatch.
43986ad0af8SEugene Zhulenev   {
44086ad0af8SEugene Zhulenev     b.setInsertionPointToEnd(before);
44186ad0af8SEugene Zhulenev     Value start = before->getArgument(0);
44286ad0af8SEugene Zhulenev     Value end = before->getArgument(1);
44386ad0af8SEugene Zhulenev     Value distance = b.create<SubIOp>(end, start);
44486ad0af8SEugene Zhulenev     Value dispatch = b.create<CmpIOp>(CmpIPredicate::sgt, distance, c1);
44586ad0af8SEugene Zhulenev     b.create<scf::ConditionOp>(dispatch, before->getArguments());
44686ad0af8SEugene Zhulenev   }
44786ad0af8SEugene Zhulenev 
44886ad0af8SEugene Zhulenev   // Setup the async dispatch loop body: recursively call dispatch function
44934a164c9SEugene Zhulenev   // for the seconds half of the original range and go to the next iteration.
45086ad0af8SEugene Zhulenev   {
45186ad0af8SEugene Zhulenev     b.setInsertionPointToEnd(after);
45286ad0af8SEugene Zhulenev     Value start = after->getArgument(0);
45386ad0af8SEugene Zhulenev     Value end = after->getArgument(1);
45486ad0af8SEugene Zhulenev     Value distance = b.create<SubIOp>(end, start);
45586ad0af8SEugene Zhulenev     Value halfDistance = b.create<SignedDivIOp>(distance, c2);
45634a164c9SEugene Zhulenev     Value midIndex = b.create<AddIOp>(start, halfDistance);
45786ad0af8SEugene Zhulenev 
45886ad0af8SEugene Zhulenev     // Call parallel compute function inside the async.execute region.
45986ad0af8SEugene Zhulenev     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
46086ad0af8SEugene Zhulenev                                   Location executeLoc, ValueRange executeArgs) {
46186ad0af8SEugene Zhulenev       // Update the original `blockStart` and `blockEnd` with new range.
46286ad0af8SEugene Zhulenev       SmallVector<Value> operands{block->getArguments().begin(),
46386ad0af8SEugene Zhulenev                                   block->getArguments().end()};
46486ad0af8SEugene Zhulenev       operands[1] = midIndex;
46586ad0af8SEugene Zhulenev       operands[2] = end;
46686ad0af8SEugene Zhulenev 
46786ad0af8SEugene Zhulenev       executeBuilder.create<CallOp>(executeLoc, func.sym_name(),
46886ad0af8SEugene Zhulenev                                     func.getCallableResults(), operands);
46986ad0af8SEugene Zhulenev       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
47086ad0af8SEugene Zhulenev     };
47186ad0af8SEugene Zhulenev 
47286ad0af8SEugene Zhulenev     // Create async.execute operation to dispatch half of the block range.
47386ad0af8SEugene Zhulenev     auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
47486ad0af8SEugene Zhulenev                                        executeBodyBuilder);
47586ad0af8SEugene Zhulenev     b.create<AddToGroupOp>(indexTy, execute.token(), group);
47634a164c9SEugene Zhulenev     b.create<scf::YieldOp>(ValueRange({start, midIndex}));
47786ad0af8SEugene Zhulenev   }
47886ad0af8SEugene Zhulenev 
47986ad0af8SEugene Zhulenev   // After dispatching async operations to process the tail of the block range
48086ad0af8SEugene Zhulenev   // call the parallel compute function for the first block of the range.
48186ad0af8SEugene Zhulenev   b.setInsertionPointAfter(whileOp);
48286ad0af8SEugene Zhulenev 
48386ad0af8SEugene Zhulenev   // Drop async dispatch specific arguments: async group, block start and end.
48486ad0af8SEugene Zhulenev   auto forwardedInputs = block->getArguments().drop_front(3);
48586ad0af8SEugene Zhulenev   SmallVector<Value> computeFuncOperands = {blockStart};
48686ad0af8SEugene Zhulenev   computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end());
48786ad0af8SEugene Zhulenev 
48886ad0af8SEugene Zhulenev   b.create<CallOp>(computeFunc.func.sym_name(),
48986ad0af8SEugene Zhulenev                    computeFunc.func.getCallableResults(), computeFuncOperands);
49086ad0af8SEugene Zhulenev   b.create<ReturnOp>(ValueRange());
49186ad0af8SEugene Zhulenev 
49286ad0af8SEugene Zhulenev   return func;
49386ad0af8SEugene Zhulenev }
49486ad0af8SEugene Zhulenev 
49586ad0af8SEugene Zhulenev // Launch async dispatch of the parallel compute function.
49686ad0af8SEugene Zhulenev static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
49786ad0af8SEugene Zhulenev                             ParallelComputeFunction &parallelComputeFunction,
49886ad0af8SEugene Zhulenev                             scf::ParallelOp op, Value blockSize,
49986ad0af8SEugene Zhulenev                             Value blockCount,
50086ad0af8SEugene Zhulenev                             const SmallVector<Value> &tripCounts) {
50186ad0af8SEugene Zhulenev   MLIRContext *ctx = op->getContext();
50286ad0af8SEugene Zhulenev 
50386ad0af8SEugene Zhulenev   // Add one more level of indirection to dispatch parallel compute functions
50486ad0af8SEugene Zhulenev   // using async operations and recursive work splitting.
50586ad0af8SEugene Zhulenev   FuncOp asyncDispatchFunction =
50686ad0af8SEugene Zhulenev       createAsyncDispatchFunction(parallelComputeFunction, rewriter);
50786ad0af8SEugene Zhulenev 
50834a164c9SEugene Zhulenev   Value c0 = b.create<ConstantIndexOp>(0);
50934a164c9SEugene Zhulenev   Value c1 = b.create<ConstantIndexOp>(1);
51086ad0af8SEugene Zhulenev 
51186ad0af8SEugene Zhulenev   // Create an async.group to wait on all async tokens from the concurrent
51286ad0af8SEugene Zhulenev   // execution of multiple parallel compute function. First block will be
51386ad0af8SEugene Zhulenev   // executed synchronously in the caller thread.
51486ad0af8SEugene Zhulenev   Value groupSize = b.create<SubIOp>(blockCount, c1);
51586ad0af8SEugene Zhulenev   Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
51686ad0af8SEugene Zhulenev 
517a8f819c6SEugene Zhulenev   // Appends operands shared by async dispatch and parallel compute functions to
518a8f819c6SEugene Zhulenev   // the given operands vector.
519a8f819c6SEugene Zhulenev   auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) {
520a8f819c6SEugene Zhulenev     operands.append(tripCounts);
521a8f819c6SEugene Zhulenev     operands.append(op.lowerBound().begin(), op.lowerBound().end());
522a8f819c6SEugene Zhulenev     operands.append(op.upperBound().begin(), op.upperBound().end());
523a8f819c6SEugene Zhulenev     operands.append(op.step().begin(), op.step().end());
524a8f819c6SEugene Zhulenev     operands.append(parallelComputeFunction.captures);
525a8f819c6SEugene Zhulenev   };
526a8f819c6SEugene Zhulenev 
527a8f819c6SEugene Zhulenev   // Check if the block size is one, in this case we can skip the async dispatch
528a8f819c6SEugene Zhulenev   // completely. If this will be known statically, then canonicalization will
529a8f819c6SEugene Zhulenev   // erase async group operations.
530a8f819c6SEugene Zhulenev   Value isSingleBlock = b.create<CmpIOp>(CmpIPredicate::eq, blockCount, c1);
531a8f819c6SEugene Zhulenev 
532a8f819c6SEugene Zhulenev   auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
533a8f819c6SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, nestedBuilder);
534a8f819c6SEugene Zhulenev 
535a8f819c6SEugene Zhulenev     // Call parallel compute function for the single block.
536a8f819c6SEugene Zhulenev     SmallVector<Value> operands = {c0, blockSize};
537a8f819c6SEugene Zhulenev     appendBlockComputeOperands(operands);
538a8f819c6SEugene Zhulenev 
539a8f819c6SEugene Zhulenev     nb.create<CallOp>(parallelComputeFunction.func.sym_name(),
540a8f819c6SEugene Zhulenev                       parallelComputeFunction.func.getCallableResults(),
541a8f819c6SEugene Zhulenev                       operands);
542a8f819c6SEugene Zhulenev     nb.create<scf::YieldOp>();
543a8f819c6SEugene Zhulenev   };
544a8f819c6SEugene Zhulenev 
545a8f819c6SEugene Zhulenev   auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
546a8f819c6SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, nestedBuilder);
54786ad0af8SEugene Zhulenev 
54886ad0af8SEugene Zhulenev     // Launch async dispatch function for [0, blockCount) range.
549a8f819c6SEugene Zhulenev     SmallVector<Value> operands = {group, c0, blockCount, blockSize};
550a8f819c6SEugene Zhulenev     appendBlockComputeOperands(operands);
551a8f819c6SEugene Zhulenev 
552a8f819c6SEugene Zhulenev     nb.create<CallOp>(asyncDispatchFunction.sym_name(),
553a8f819c6SEugene Zhulenev                       asyncDispatchFunction.getCallableResults(), operands);
554a8f819c6SEugene Zhulenev     nb.create<scf::YieldOp>();
555a8f819c6SEugene Zhulenev   };
556a8f819c6SEugene Zhulenev 
557a8f819c6SEugene Zhulenev   // Dispatch either single block compute function, or launch async dispatch.
558a8f819c6SEugene Zhulenev   b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch);
55986ad0af8SEugene Zhulenev 
56086ad0af8SEugene Zhulenev   // Wait for the completion of all parallel compute operations.
56186ad0af8SEugene Zhulenev   b.create<AwaitAllOp>(group);
56286ad0af8SEugene Zhulenev }
56386ad0af8SEugene Zhulenev 
56486ad0af8SEugene Zhulenev // Dispatch parallel compute functions by submitting all async compute tasks
56586ad0af8SEugene Zhulenev // from a simple for loop in the caller thread.
56686ad0af8SEugene Zhulenev static void
567*55dfab39Sbakhtiyar doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
56886ad0af8SEugene Zhulenev                      ParallelComputeFunction &parallelComputeFunction,
56986ad0af8SEugene Zhulenev                      scf::ParallelOp op, Value blockSize, Value blockCount,
57086ad0af8SEugene Zhulenev                      const SmallVector<Value> &tripCounts) {
57186ad0af8SEugene Zhulenev   MLIRContext *ctx = op->getContext();
57286ad0af8SEugene Zhulenev 
57386ad0af8SEugene Zhulenev   FuncOp compute = parallelComputeFunction.func;
57486ad0af8SEugene Zhulenev 
57534a164c9SEugene Zhulenev   Value c0 = b.create<ConstantIndexOp>(0);
57634a164c9SEugene Zhulenev   Value c1 = b.create<ConstantIndexOp>(1);
57786ad0af8SEugene Zhulenev 
57886ad0af8SEugene Zhulenev   // Create an async.group to wait on all async tokens from the concurrent
57986ad0af8SEugene Zhulenev   // execution of multiple parallel compute function. First block will be
58086ad0af8SEugene Zhulenev   // executed synchronously in the caller thread.
58186ad0af8SEugene Zhulenev   Value groupSize = b.create<SubIOp>(blockCount, c1);
58286ad0af8SEugene Zhulenev   Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
58386ad0af8SEugene Zhulenev 
58486ad0af8SEugene Zhulenev   // Call parallel compute function for all blocks.
58586ad0af8SEugene Zhulenev   using LoopBodyBuilder =
58686ad0af8SEugene Zhulenev       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
58786ad0af8SEugene Zhulenev 
58886ad0af8SEugene Zhulenev   // Returns parallel compute function operands to process the given block.
58986ad0af8SEugene Zhulenev   auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> {
59086ad0af8SEugene Zhulenev     SmallVector<Value> computeFuncOperands = {blockIndex, blockSize};
59186ad0af8SEugene Zhulenev     computeFuncOperands.append(tripCounts);
59286ad0af8SEugene Zhulenev     computeFuncOperands.append(op.lowerBound().begin(), op.lowerBound().end());
59386ad0af8SEugene Zhulenev     computeFuncOperands.append(op.upperBound().begin(), op.upperBound().end());
59486ad0af8SEugene Zhulenev     computeFuncOperands.append(op.step().begin(), op.step().end());
59586ad0af8SEugene Zhulenev     computeFuncOperands.append(parallelComputeFunction.captures);
59686ad0af8SEugene Zhulenev     return computeFuncOperands;
59786ad0af8SEugene Zhulenev   };
59886ad0af8SEugene Zhulenev 
59986ad0af8SEugene Zhulenev   // Induction variable is the index of the block: [0, blockCount).
60086ad0af8SEugene Zhulenev   LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc,
60186ad0af8SEugene Zhulenev                                     Value iv, ValueRange args) {
60286ad0af8SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, loopBuilder);
60386ad0af8SEugene Zhulenev 
60486ad0af8SEugene Zhulenev     // Call parallel compute function inside the async.execute region.
60586ad0af8SEugene Zhulenev     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
60686ad0af8SEugene Zhulenev                                   Location executeLoc, ValueRange executeArgs) {
60786ad0af8SEugene Zhulenev       executeBuilder.create<CallOp>(executeLoc, compute.sym_name(),
60886ad0af8SEugene Zhulenev                                     compute.getCallableResults(),
60986ad0af8SEugene Zhulenev                                     computeFuncOperands(iv));
61086ad0af8SEugene Zhulenev       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
61186ad0af8SEugene Zhulenev     };
61286ad0af8SEugene Zhulenev 
61386ad0af8SEugene Zhulenev     // Create async.execute operation to launch parallel computate function.
61486ad0af8SEugene Zhulenev     auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
61586ad0af8SEugene Zhulenev                                         executeBodyBuilder);
61686ad0af8SEugene Zhulenev     nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group);
61786ad0af8SEugene Zhulenev     nb.create<scf::YieldOp>();
61886ad0af8SEugene Zhulenev   };
61986ad0af8SEugene Zhulenev 
62086ad0af8SEugene Zhulenev   // Iterate over all compute blocks and launch parallel compute operations.
62186ad0af8SEugene Zhulenev   b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder);
62286ad0af8SEugene Zhulenev 
62386ad0af8SEugene Zhulenev   // Call parallel compute function for the first block in the caller thread.
62486ad0af8SEugene Zhulenev   b.create<CallOp>(compute.sym_name(), compute.getCallableResults(),
62586ad0af8SEugene Zhulenev                    computeFuncOperands(c0));
62686ad0af8SEugene Zhulenev 
62786ad0af8SEugene Zhulenev   // Wait for the completion of all async compute operations.
62886ad0af8SEugene Zhulenev   b.create<AwaitAllOp>(group);
62986ad0af8SEugene Zhulenev }
63086ad0af8SEugene Zhulenev 
631c30ab6c2SEugene Zhulenev LogicalResult
632c30ab6c2SEugene Zhulenev AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op,
633c30ab6c2SEugene Zhulenev                                          PatternRewriter &rewriter) const {
634c30ab6c2SEugene Zhulenev   // We do not currently support rewrite for parallel op with reductions.
635c30ab6c2SEugene Zhulenev   if (op.getNumReductions() != 0)
636c30ab6c2SEugene Zhulenev     return failure();
637c30ab6c2SEugene Zhulenev 
63886ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
639c30ab6c2SEugene Zhulenev 
640c30ab6c2SEugene Zhulenev   // Compute trip count for each loop induction variable:
64186ad0af8SEugene Zhulenev   //   tripCount = ceil_div(upperBound - lowerBound, step);
64286ad0af8SEugene Zhulenev   SmallVector<Value> tripCounts(op.getNumLoops());
643c30ab6c2SEugene Zhulenev   for (size_t i = 0; i < op.getNumLoops(); ++i) {
644c30ab6c2SEugene Zhulenev     auto lb = op.lowerBound()[i];
645c30ab6c2SEugene Zhulenev     auto ub = op.upperBound()[i];
646c30ab6c2SEugene Zhulenev     auto step = op.step()[i];
64786ad0af8SEugene Zhulenev     auto range = b.create<SubIOp>(ub, lb);
64886ad0af8SEugene Zhulenev     tripCounts[i] = b.create<SignedCeilDivIOp>(range, step);
649c30ab6c2SEugene Zhulenev   }
650c30ab6c2SEugene Zhulenev 
65186ad0af8SEugene Zhulenev   // Compute a product of trip counts to get the 1-dimensional iteration space
65286ad0af8SEugene Zhulenev   // for the scf.parallel operation.
65386ad0af8SEugene Zhulenev   Value tripCount = tripCounts[0];
65486ad0af8SEugene Zhulenev   for (size_t i = 1; i < tripCounts.size(); ++i)
65586ad0af8SEugene Zhulenev     tripCount = b.create<MulIOp>(tripCount, tripCounts[i]);
656c30ab6c2SEugene Zhulenev 
6576c1f6558SEugene Zhulenev   // Short circuit no-op parallel loops (zero iterations) that can arise from
6586c1f6558SEugene Zhulenev   // the memrefs with dynamic dimension(s) equal to zero.
6596c1f6558SEugene Zhulenev   Value c0 = b.create<ConstantIndexOp>(0);
6606c1f6558SEugene Zhulenev   Value isZeroIterations = b.create<CmpIOp>(CmpIPredicate::eq, tripCount, c0);
6616c1f6558SEugene Zhulenev 
6626c1f6558SEugene Zhulenev   // Do absolutely nothing if the trip count is zero.
6636c1f6558SEugene Zhulenev   auto noOp = [&](OpBuilder &nestedBuilder, Location loc) {
6646c1f6558SEugene Zhulenev     nestedBuilder.create<scf::YieldOp>(loc);
6656c1f6558SEugene Zhulenev   };
6666c1f6558SEugene Zhulenev 
6676c1f6558SEugene Zhulenev   // Compute the parallel block size and dispatch concurrent tasks computing
6686c1f6558SEugene Zhulenev   // results for each block.
6696c1f6558SEugene Zhulenev   auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) {
6706c1f6558SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, nestedBuilder);
6716c1f6558SEugene Zhulenev 
672c1194c2eSEugene Zhulenev     // With large number of threads the value of creating many compute blocks
673c1194c2eSEugene Zhulenev     // is reduced because the problem typically becomes memory bound. For small
674c1194c2eSEugene Zhulenev     // number of threads it helps with stragglers.
675c1194c2eSEugene Zhulenev     float overshardingFactor = numWorkerThreads <= 4    ? 8.0
676c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 8  ? 4.0
677c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 16 ? 2.0
678c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 32 ? 1.0
679c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 64 ? 0.8
680c1194c2eSEugene Zhulenev                                                         : 0.6;
681c1194c2eSEugene Zhulenev 
68286ad0af8SEugene Zhulenev     // Do not overload worker threads with too many compute blocks.
683c1194c2eSEugene Zhulenev     Value maxComputeBlocks = b.create<ConstantIndexOp>(
684c1194c2eSEugene Zhulenev         std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor)));
685c30ab6c2SEugene Zhulenev 
68686ad0af8SEugene Zhulenev     // Target block size from the pass parameters.
687*55dfab39Sbakhtiyar     Value minTaskSizeCst = b.create<ConstantIndexOp>(minTaskSize);
688c30ab6c2SEugene Zhulenev 
68986ad0af8SEugene Zhulenev     // Compute parallel block size from the parallel problem size:
69086ad0af8SEugene Zhulenev     //   blockSize = min(tripCount,
69134a164c9SEugene Zhulenev     //                   max(ceil_div(tripCount, maxComputeBlocks),
692*55dfab39Sbakhtiyar     //                       ceil_div(minTaskSize, bodySize)))
69386ad0af8SEugene Zhulenev     Value bs0 = b.create<SignedCeilDivIOp>(tripCount, maxComputeBlocks);
694*55dfab39Sbakhtiyar     Value bs1 = b.create<CmpIOp>(CmpIPredicate::sge, bs0, minTaskSizeCst);
695*55dfab39Sbakhtiyar     Value bs2 = b.create<SelectOp>(bs1, bs0, minTaskSizeCst);
69686ad0af8SEugene Zhulenev     Value bs3 = b.create<CmpIOp>(CmpIPredicate::sle, tripCount, bs2);
697c1194c2eSEugene Zhulenev     Value blockSize0 = b.create<SelectOp>(bs3, tripCount, bs2);
698c1194c2eSEugene Zhulenev     Value blockCount0 = b.create<SignedCeilDivIOp>(tripCount, blockSize0);
699c1194c2eSEugene Zhulenev 
700c1194c2eSEugene Zhulenev     // Compute balanced block size for the estimated block count.
701c1194c2eSEugene Zhulenev     Value blockSize = b.create<SignedCeilDivIOp>(tripCount, blockCount0);
70286ad0af8SEugene Zhulenev     Value blockCount = b.create<SignedCeilDivIOp>(tripCount, blockSize);
70386ad0af8SEugene Zhulenev 
70486ad0af8SEugene Zhulenev     // Create a parallel compute function that takes a block id and computes the
70586ad0af8SEugene Zhulenev     // parallel operation body for a subset of iteration space.
70686ad0af8SEugene Zhulenev     ParallelComputeFunction parallelComputeFunction =
70786ad0af8SEugene Zhulenev         createParallelComputeFunction(op, rewriter);
70886ad0af8SEugene Zhulenev 
7096c1f6558SEugene Zhulenev     // Dispatch parallel compute function using async recursive work splitting,
7106c1f6558SEugene Zhulenev     // or by submitting compute task sequentially from a caller thread.
71186ad0af8SEugene Zhulenev     if (asyncDispatch) {
71286ad0af8SEugene Zhulenev       doAsyncDispatch(b, rewriter, parallelComputeFunction, op, blockSize,
71386ad0af8SEugene Zhulenev                       blockCount, tripCounts);
71486ad0af8SEugene Zhulenev     } else {
715*55dfab39Sbakhtiyar       doSequentialDispatch(b, rewriter, parallelComputeFunction, op, blockSize,
71686ad0af8SEugene Zhulenev                            blockCount, tripCounts);
717c30ab6c2SEugene Zhulenev     }
718c30ab6c2SEugene Zhulenev 
7196c1f6558SEugene Zhulenev     nb.create<scf::YieldOp>();
7206c1f6558SEugene Zhulenev   };
7216c1f6558SEugene Zhulenev 
7226c1f6558SEugene Zhulenev   // Replace the `scf.parallel` operation with the parallel compute function.
7236c1f6558SEugene Zhulenev   b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch);
7246c1f6558SEugene Zhulenev 
72534a164c9SEugene Zhulenev   // Parallel operation was replaced with a block iteration loop.
726c30ab6c2SEugene Zhulenev   rewriter.eraseOp(op);
727c30ab6c2SEugene Zhulenev 
728c30ab6c2SEugene Zhulenev   return success();
729c30ab6c2SEugene Zhulenev }
730c30ab6c2SEugene Zhulenev 
7318a316b00SEugene Zhulenev void AsyncParallelForPass::runOnOperation() {
732c30ab6c2SEugene Zhulenev   MLIRContext *ctx = &getContext();
733c30ab6c2SEugene Zhulenev 
734dc4e913bSChris Lattner   RewritePatternSet patterns(ctx);
73586ad0af8SEugene Zhulenev   patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads,
736*55dfab39Sbakhtiyar                                         minTaskSize);
737c30ab6c2SEugene Zhulenev 
7388a316b00SEugene Zhulenev   if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns))))
739c30ab6c2SEugene Zhulenev     signalPassFailure();
740c30ab6c2SEugene Zhulenev }
741c30ab6c2SEugene Zhulenev 
7428a316b00SEugene Zhulenev std::unique_ptr<Pass> mlir::createAsyncParallelForPass() {
743c30ab6c2SEugene Zhulenev   return std::make_unique<AsyncParallelForPass>();
744c30ab6c2SEugene Zhulenev }
74534a164c9SEugene Zhulenev 
746*55dfab39Sbakhtiyar std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch,
747*55dfab39Sbakhtiyar                                                        int32_t numWorkerThreads,
748*55dfab39Sbakhtiyar                                                        int32_t minTaskSize) {
74934a164c9SEugene Zhulenev   return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads,
750*55dfab39Sbakhtiyar                                                 minTaskSize);
75134a164c9SEugene Zhulenev }
752