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"
14*a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
15c30ab6c2SEugene Zhulenev #include "mlir/Dialect/Async/IR/Async.h"
16c30ab6c2SEugene Zhulenev #include "mlir/Dialect/Async/Passes.h"
17c30ab6c2SEugene Zhulenev #include "mlir/Dialect/SCF/SCF.h"
18c30ab6c2SEugene Zhulenev #include "mlir/Dialect/StandardOps/IR/Ops.h"
19c30ab6c2SEugene Zhulenev #include "mlir/IR/BlockAndValueMapping.h"
2086ad0af8SEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h"
21c30ab6c2SEugene Zhulenev #include "mlir/IR/PatternMatch.h"
22c30ab6c2SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
2386ad0af8SEugene Zhulenev #include "mlir/Transforms/RegionUtils.h"
24c30ab6c2SEugene Zhulenev 
25c30ab6c2SEugene Zhulenev using namespace mlir;
26c30ab6c2SEugene Zhulenev using namespace mlir::async;
27c30ab6c2SEugene Zhulenev 
28c30ab6c2SEugene Zhulenev #define DEBUG_TYPE "async-parallel-for"
29c30ab6c2SEugene Zhulenev 
30c30ab6c2SEugene Zhulenev namespace {
31c30ab6c2SEugene Zhulenev 
32c30ab6c2SEugene Zhulenev // Rewrite scf.parallel operation into multiple concurrent async.execute
33c30ab6c2SEugene Zhulenev // operations over non overlapping subranges of the original loop.
34c30ab6c2SEugene Zhulenev //
35c30ab6c2SEugene Zhulenev // Example:
36c30ab6c2SEugene Zhulenev //
3786ad0af8SEugene Zhulenev //   scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) {
38c30ab6c2SEugene Zhulenev //     "do_some_compute"(%i, %j): () -> ()
39c30ab6c2SEugene Zhulenev //   }
40c30ab6c2SEugene Zhulenev //
41c30ab6c2SEugene Zhulenev // Converted to:
42c30ab6c2SEugene Zhulenev //
4386ad0af8SEugene Zhulenev //   // Parallel compute function that executes the parallel body region for
4486ad0af8SEugene Zhulenev //   // a subset of the parallel iteration space defined by the one-dimensional
4586ad0af8SEugene Zhulenev //   // compute block index.
4686ad0af8SEugene Zhulenev //   func parallel_compute_function(%block_index : index, %block_size : index,
4786ad0af8SEugene Zhulenev //                                  <parallel operation properties>, ...) {
4886ad0af8SEugene Zhulenev //     // Compute multi-dimensional loop bounds for %block_index.
4986ad0af8SEugene Zhulenev //     %block_lbi, %block_lbj = ...
5086ad0af8SEugene Zhulenev //     %block_ubi, %block_ubj = ...
51c30ab6c2SEugene Zhulenev //
5286ad0af8SEugene Zhulenev //     // Clone parallel operation body into the scf.for loop nest.
5386ad0af8SEugene Zhulenev //     scf.for %i = %blockLbi to %blockUbi {
5486ad0af8SEugene Zhulenev //       scf.for %j = block_lbj to %block_ubj {
55c30ab6c2SEugene Zhulenev //         "do_some_compute"(%i, %j): () -> ()
56c30ab6c2SEugene Zhulenev //       }
57c30ab6c2SEugene Zhulenev //     }
58c30ab6c2SEugene Zhulenev //   }
59c30ab6c2SEugene Zhulenev //
6086ad0af8SEugene Zhulenev // And a dispatch function depending on the `asyncDispatch` option.
6186ad0af8SEugene Zhulenev //
6286ad0af8SEugene Zhulenev // When async dispatch is on: (pseudocode)
6386ad0af8SEugene Zhulenev //
6486ad0af8SEugene Zhulenev //   %block_size = ... compute parallel compute block size
6586ad0af8SEugene Zhulenev //   %block_count = ... compute the number of compute blocks
6686ad0af8SEugene Zhulenev //
6786ad0af8SEugene Zhulenev //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
6886ad0af8SEugene Zhulenev //     // Keep splitting block range until we reached a range of size 1.
6986ad0af8SEugene Zhulenev //     while (%block_end - %block_start > 1) {
7086ad0af8SEugene Zhulenev //       %mid_index = block_start + (block_end - block_start) / 2;
7186ad0af8SEugene Zhulenev //       async.execute { call @async_dispatch(%mid_index, %block_end); }
7286ad0af8SEugene Zhulenev //       %block_end = %mid_index
73c30ab6c2SEugene Zhulenev //     }
74c30ab6c2SEugene Zhulenev //
7586ad0af8SEugene Zhulenev //     // Call parallel compute function for a single block.
7686ad0af8SEugene Zhulenev //     call @parallel_compute_fn(%block_start, %block_size, ...);
7786ad0af8SEugene Zhulenev //   }
78c30ab6c2SEugene Zhulenev //
7986ad0af8SEugene Zhulenev //   // Launch async dispatch for [0, block_count) range.
8086ad0af8SEugene Zhulenev //   call @async_dispatch(%c0, %block_count);
81c30ab6c2SEugene Zhulenev //
8286ad0af8SEugene Zhulenev // When async dispatch is off:
83c30ab6c2SEugene Zhulenev //
8486ad0af8SEugene Zhulenev //   %block_size = ... compute parallel compute block size
8586ad0af8SEugene Zhulenev //   %block_count = ... compute the number of compute blocks
8686ad0af8SEugene Zhulenev //
8786ad0af8SEugene Zhulenev //   scf.for %block_index = %c0 to %block_count {
8886ad0af8SEugene Zhulenev //      call @parallel_compute_fn(%block_index, %block_size, ...)
8986ad0af8SEugene Zhulenev //   }
9086ad0af8SEugene Zhulenev //
9186ad0af8SEugene Zhulenev struct AsyncParallelForPass
9286ad0af8SEugene Zhulenev     : public AsyncParallelForBase<AsyncParallelForPass> {
9386ad0af8SEugene Zhulenev   AsyncParallelForPass() = default;
9434a164c9SEugene Zhulenev 
9534a164c9SEugene Zhulenev   AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads,
9655dfab39Sbakhtiyar                        int32_t minTaskSize) {
9734a164c9SEugene Zhulenev     this->asyncDispatch = asyncDispatch;
9834a164c9SEugene Zhulenev     this->numWorkerThreads = numWorkerThreads;
9955dfab39Sbakhtiyar     this->minTaskSize = minTaskSize;
10034a164c9SEugene Zhulenev   }
10134a164c9SEugene Zhulenev 
10286ad0af8SEugene Zhulenev   void runOnOperation() override;
10386ad0af8SEugene Zhulenev };
10486ad0af8SEugene Zhulenev 
105c30ab6c2SEugene Zhulenev struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> {
106c30ab6c2SEugene Zhulenev public:
10786ad0af8SEugene Zhulenev   AsyncParallelForRewrite(MLIRContext *ctx, bool asyncDispatch,
10855dfab39Sbakhtiyar                           int32_t numWorkerThreads, int32_t minTaskSize)
10986ad0af8SEugene Zhulenev       : OpRewritePattern(ctx), asyncDispatch(asyncDispatch),
11055dfab39Sbakhtiyar         numWorkerThreads(numWorkerThreads), minTaskSize(minTaskSize) {}
111c30ab6c2SEugene Zhulenev 
112c30ab6c2SEugene Zhulenev   LogicalResult matchAndRewrite(scf::ParallelOp op,
113c30ab6c2SEugene Zhulenev                                 PatternRewriter &rewriter) const override;
114c30ab6c2SEugene Zhulenev 
115c30ab6c2SEugene Zhulenev private:
11686ad0af8SEugene Zhulenev   bool asyncDispatch;
11786ad0af8SEugene Zhulenev   int32_t numWorkerThreads;
11855dfab39Sbakhtiyar   int32_t minTaskSize;
119c30ab6c2SEugene Zhulenev };
120c30ab6c2SEugene Zhulenev 
12186ad0af8SEugene Zhulenev struct ParallelComputeFunctionType {
12286ad0af8SEugene Zhulenev   FunctionType type;
12386ad0af8SEugene Zhulenev   llvm::SmallVector<Value> captures;
12486ad0af8SEugene Zhulenev };
12586ad0af8SEugene Zhulenev 
12686ad0af8SEugene Zhulenev struct ParallelComputeFunction {
12786ad0af8SEugene Zhulenev   FuncOp func;
12886ad0af8SEugene Zhulenev   llvm::SmallVector<Value> captures;
129c30ab6c2SEugene Zhulenev };
130c30ab6c2SEugene Zhulenev 
131c30ab6c2SEugene Zhulenev } // namespace
132c30ab6c2SEugene Zhulenev 
13386ad0af8SEugene Zhulenev // Converts one-dimensional iteration index in the [0, tripCount) interval
13486ad0af8SEugene Zhulenev // into multidimensional iteration coordinate.
13586ad0af8SEugene Zhulenev static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index,
13634a164c9SEugene Zhulenev                                       ArrayRef<Value> tripCounts) {
13786ad0af8SEugene Zhulenev   SmallVector<Value> coords(tripCounts.size());
13886ad0af8SEugene Zhulenev   assert(!tripCounts.empty() && "tripCounts must be not empty");
13986ad0af8SEugene Zhulenev 
14086ad0af8SEugene Zhulenev   for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) {
141*a54f4eaeSMogball     coords[i] = b.create<arith::RemSIOp>(index, tripCounts[i]);
142*a54f4eaeSMogball     index = b.create<arith::DivSIOp>(index, tripCounts[i]);
14386ad0af8SEugene Zhulenev   }
14486ad0af8SEugene Zhulenev 
14586ad0af8SEugene Zhulenev   return coords;
14686ad0af8SEugene Zhulenev }
14786ad0af8SEugene Zhulenev 
14886ad0af8SEugene Zhulenev // Returns a function type and implicit captures for a parallel compute
14986ad0af8SEugene Zhulenev // function. We'll need a list of implicit captures to setup block and value
15086ad0af8SEugene Zhulenev // mapping when we'll clone the body of the parallel operation.
15186ad0af8SEugene Zhulenev static ParallelComputeFunctionType
15286ad0af8SEugene Zhulenev getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) {
15386ad0af8SEugene Zhulenev   // Values implicitly captured by the parallel operation.
15486ad0af8SEugene Zhulenev   llvm::SetVector<Value> captures;
15586ad0af8SEugene Zhulenev   getUsedValuesDefinedAbove(op.region(), op.region(), captures);
15686ad0af8SEugene Zhulenev 
15786ad0af8SEugene Zhulenev   llvm::SmallVector<Type> inputs;
15886ad0af8SEugene Zhulenev   inputs.reserve(2 + 4 * op.getNumLoops() + captures.size());
15986ad0af8SEugene Zhulenev 
16086ad0af8SEugene Zhulenev   Type indexTy = rewriter.getIndexType();
16186ad0af8SEugene Zhulenev 
16286ad0af8SEugene Zhulenev   // One-dimensional iteration space defined by the block index and size.
16386ad0af8SEugene Zhulenev   inputs.push_back(indexTy); // blockIndex
16486ad0af8SEugene Zhulenev   inputs.push_back(indexTy); // blockSize
16586ad0af8SEugene Zhulenev 
16686ad0af8SEugene Zhulenev   // Multi-dimensional parallel iteration space defined by the loop trip counts.
16786ad0af8SEugene Zhulenev   for (unsigned i = 0; i < op.getNumLoops(); ++i)
16886ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // loop tripCount
16986ad0af8SEugene Zhulenev 
17086ad0af8SEugene Zhulenev   // Parallel operation lower bound, upper bound and step.
17186ad0af8SEugene Zhulenev   for (unsigned i = 0; i < op.getNumLoops(); ++i) {
17286ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // lower bound
17386ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // upper bound
17486ad0af8SEugene Zhulenev     inputs.push_back(indexTy); // step
17586ad0af8SEugene Zhulenev   }
17686ad0af8SEugene Zhulenev 
17786ad0af8SEugene Zhulenev   // Types of the implicit captures.
17886ad0af8SEugene Zhulenev   for (Value capture : captures)
17986ad0af8SEugene Zhulenev     inputs.push_back(capture.getType());
18086ad0af8SEugene Zhulenev 
18186ad0af8SEugene Zhulenev   // Convert captures to vector for later convenience.
18286ad0af8SEugene Zhulenev   SmallVector<Value> capturesVector(captures.begin(), captures.end());
18386ad0af8SEugene Zhulenev   return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector};
18486ad0af8SEugene Zhulenev }
18586ad0af8SEugene Zhulenev 
18686ad0af8SEugene Zhulenev // Create a parallel compute fuction from the parallel operation.
18786ad0af8SEugene Zhulenev static ParallelComputeFunction
18886ad0af8SEugene Zhulenev createParallelComputeFunction(scf::ParallelOp op, PatternRewriter &rewriter) {
18986ad0af8SEugene Zhulenev   OpBuilder::InsertionGuard guard(rewriter);
19086ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
19186ad0af8SEugene Zhulenev 
19286ad0af8SEugene Zhulenev   ModuleOp module = op->getParentOfType<ModuleOp>();
19386ad0af8SEugene Zhulenev 
194b537c5b4SEugene Zhulenev   // Make sure that all constants will be inside the parallel operation body to
195b537c5b4SEugene Zhulenev   // reduce the number of parallel compute function arguments.
196b537c5b4SEugene Zhulenev   cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter);
197b537c5b4SEugene Zhulenev 
19886ad0af8SEugene Zhulenev   ParallelComputeFunctionType computeFuncType =
19986ad0af8SEugene Zhulenev       getParallelComputeFunctionType(op, rewriter);
20086ad0af8SEugene Zhulenev 
20186ad0af8SEugene Zhulenev   FunctionType type = computeFuncType.type;
20286ad0af8SEugene Zhulenev   FuncOp func = FuncOp::create(op.getLoc(), "parallel_compute_fn", type);
20386ad0af8SEugene Zhulenev   func.setPrivate();
20486ad0af8SEugene Zhulenev 
20586ad0af8SEugene Zhulenev   // Insert function into the module symbol table and assign it unique name.
20686ad0af8SEugene Zhulenev   SymbolTable symbolTable(module);
20786ad0af8SEugene Zhulenev   symbolTable.insert(func);
20886ad0af8SEugene Zhulenev   rewriter.getListener()->notifyOperationInserted(func);
20986ad0af8SEugene Zhulenev 
21086ad0af8SEugene Zhulenev   // Create function entry block.
21186ad0af8SEugene Zhulenev   Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs());
21286ad0af8SEugene Zhulenev   b.setInsertionPointToEnd(block);
21386ad0af8SEugene Zhulenev 
21486ad0af8SEugene Zhulenev   unsigned offset = 0; // argument offset for arguments decoding
21586ad0af8SEugene Zhulenev 
21634a164c9SEugene Zhulenev   // Returns `numArguments` arguments starting from `offset` and updates offset
21734a164c9SEugene Zhulenev   // by moving forward to the next argument.
21834a164c9SEugene Zhulenev   auto getArguments = [&](unsigned numArguments) -> ArrayRef<Value> {
21934a164c9SEugene Zhulenev     auto args = block->getArguments();
22034a164c9SEugene Zhulenev     auto slice = args.drop_front(offset).take_front(numArguments);
22134a164c9SEugene Zhulenev     offset += numArguments;
22234a164c9SEugene Zhulenev     return {slice.begin(), slice.end()};
22386ad0af8SEugene Zhulenev   };
22486ad0af8SEugene Zhulenev 
22586ad0af8SEugene Zhulenev   // Block iteration position defined by the block index and size.
22686ad0af8SEugene Zhulenev   Value blockIndex = block->getArgument(offset++);
22786ad0af8SEugene Zhulenev   Value blockSize = block->getArgument(offset++);
22886ad0af8SEugene Zhulenev 
22986ad0af8SEugene Zhulenev   // Constants used below.
230*a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
231*a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
23286ad0af8SEugene Zhulenev 
23386ad0af8SEugene Zhulenev   // Multi-dimensional parallel iteration space defined by the loop trip counts.
23434a164c9SEugene Zhulenev   ArrayRef<Value> tripCounts = getArguments(op.getNumLoops());
23586ad0af8SEugene Zhulenev 
23686ad0af8SEugene Zhulenev   // Compute a product of trip counts to get the size of the flattened
23786ad0af8SEugene Zhulenev   // one-dimensional iteration space.
23886ad0af8SEugene Zhulenev   Value tripCount = tripCounts[0];
23986ad0af8SEugene Zhulenev   for (unsigned i = 1; i < tripCounts.size(); ++i)
240*a54f4eaeSMogball     tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]);
24186ad0af8SEugene Zhulenev 
24234a164c9SEugene Zhulenev   // Parallel operation lower bound and step.
24334a164c9SEugene Zhulenev   ArrayRef<Value> lowerBound = getArguments(op.getNumLoops());
24434a164c9SEugene Zhulenev   offset += op.getNumLoops(); // skip upper bound arguments
24534a164c9SEugene Zhulenev   ArrayRef<Value> step = getArguments(op.getNumLoops());
24686ad0af8SEugene Zhulenev 
24786ad0af8SEugene Zhulenev   // Remaining arguments are implicit captures of the parallel operation.
24834a164c9SEugene Zhulenev   ArrayRef<Value> captures = getArguments(block->getNumArguments() - offset);
24986ad0af8SEugene Zhulenev 
25086ad0af8SEugene Zhulenev   // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]:
25186ad0af8SEugene Zhulenev   //   blockFirstIndex = blockIndex * blockSize
252*a54f4eaeSMogball   Value blockFirstIndex = b.create<arith::MulIOp>(blockIndex, blockSize);
25386ad0af8SEugene Zhulenev 
25486ad0af8SEugene Zhulenev   // The last one-dimensional index in the block defined by the `blockIndex`:
25534a164c9SEugene Zhulenev   //   blockLastIndex = max(blockFirstIndex + blockSize, tripCount) - 1
256*a54f4eaeSMogball   Value blockEnd0 = b.create<arith::AddIOp>(blockFirstIndex, blockSize);
257*a54f4eaeSMogball   Value blockEnd1 =
258*a54f4eaeSMogball       b.create<arith::CmpIOp>(arith::CmpIPredicate::sge, blockEnd0, tripCount);
25934a164c9SEugene Zhulenev   Value blockEnd2 = b.create<SelectOp>(blockEnd1, tripCount, blockEnd0);
260*a54f4eaeSMogball   Value blockLastIndex = b.create<arith::SubIOp>(blockEnd2, c1);
26186ad0af8SEugene Zhulenev 
26286ad0af8SEugene Zhulenev   // Convert one-dimensional indices to multi-dimensional coordinates.
26386ad0af8SEugene Zhulenev   auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts);
26486ad0af8SEugene Zhulenev   auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts);
26586ad0af8SEugene Zhulenev 
26634a164c9SEugene Zhulenev   // Compute loops upper bounds derived from the block last coordinates:
26786ad0af8SEugene Zhulenev   //   blockEndCoord[i] = blockLastCoord[i] + 1
26886ad0af8SEugene Zhulenev   //
26986ad0af8SEugene Zhulenev   // Block first and last coordinates can be the same along the outer compute
27034a164c9SEugene Zhulenev   // dimension when inner compute dimension contains multiple blocks.
27186ad0af8SEugene Zhulenev   SmallVector<Value> blockEndCoord(op.getNumLoops());
27286ad0af8SEugene Zhulenev   for (size_t i = 0; i < blockLastCoord.size(); ++i)
273*a54f4eaeSMogball     blockEndCoord[i] = b.create<arith::AddIOp>(blockLastCoord[i], c1);
27486ad0af8SEugene Zhulenev 
27586ad0af8SEugene Zhulenev   // Construct a loop nest out of scf.for operations that will iterate over
27686ad0af8SEugene Zhulenev   // all coordinates in [blockFirstCoord, blockLastCoord] range.
27786ad0af8SEugene Zhulenev   using LoopBodyBuilder =
27886ad0af8SEugene Zhulenev       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
27986ad0af8SEugene Zhulenev   using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>;
28086ad0af8SEugene Zhulenev 
28186ad0af8SEugene Zhulenev   // Parallel region induction variables computed from the multi-dimensional
28286ad0af8SEugene Zhulenev   // iteration coordinate using parallel operation bounds and step:
28386ad0af8SEugene Zhulenev   //
28486ad0af8SEugene Zhulenev   //   computeBlockInductionVars[loopIdx] =
28586ad0af8SEugene Zhulenev   //       lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopDdx]
28686ad0af8SEugene Zhulenev   SmallVector<Value> computeBlockInductionVars(op.getNumLoops());
28786ad0af8SEugene Zhulenev 
28886ad0af8SEugene Zhulenev   // We need to know if we are in the first or last iteration of the
28986ad0af8SEugene Zhulenev   // multi-dimensional loop for each loop in the nest, so we can decide what
29086ad0af8SEugene Zhulenev   // loop bounds should we use for the nested loops: bounds defined by compute
29186ad0af8SEugene Zhulenev   // block interval, or bounds defined by the parallel operation.
29286ad0af8SEugene Zhulenev   //
29386ad0af8SEugene Zhulenev   // Example: 2d parallel operation
29486ad0af8SEugene Zhulenev   //                   i   j
29586ad0af8SEugene Zhulenev   //   loop sizes:   [50, 50]
29686ad0af8SEugene Zhulenev   //   first coord:  [25, 25]
29786ad0af8SEugene Zhulenev   //   last coord:   [30, 30]
29886ad0af8SEugene Zhulenev   //
29986ad0af8SEugene Zhulenev   // If `i` is equal to 25 then iteration over `j` should start at 25, when `i`
30086ad0af8SEugene Zhulenev   // is between 25 and 30 it should start at 0. The upper bound for `j` should
30186ad0af8SEugene Zhulenev   // be 50, except when `i` is equal to 30, then it should also be 30.
30286ad0af8SEugene Zhulenev   //
30386ad0af8SEugene Zhulenev   // Value at ith position specifies if all loops in [0, i) range of the loop
30486ad0af8SEugene Zhulenev   // nest are in the first/last iteration.
30586ad0af8SEugene Zhulenev   SmallVector<Value> isBlockFirstCoord(op.getNumLoops());
30686ad0af8SEugene Zhulenev   SmallVector<Value> isBlockLastCoord(op.getNumLoops());
30786ad0af8SEugene Zhulenev 
30886ad0af8SEugene Zhulenev   // Builds inner loop nest inside async.execute operation that does all the
30986ad0af8SEugene Zhulenev   // work concurrently.
31086ad0af8SEugene Zhulenev   LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder {
31186ad0af8SEugene Zhulenev     return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv,
31286ad0af8SEugene Zhulenev                         ValueRange args) {
31386ad0af8SEugene Zhulenev       ImplicitLocOpBuilder nb(loc, nestedBuilder);
31486ad0af8SEugene Zhulenev 
31586ad0af8SEugene Zhulenev       // Compute induction variable for `loopIdx`.
316*a54f4eaeSMogball       computeBlockInductionVars[loopIdx] = nb.create<arith::AddIOp>(
317*a54f4eaeSMogball           lowerBound[loopIdx], nb.create<arith::MulIOp>(iv, step[loopIdx]));
31886ad0af8SEugene Zhulenev 
31986ad0af8SEugene Zhulenev       // Check if we are inside first or last iteration of the loop.
320*a54f4eaeSMogball       isBlockFirstCoord[loopIdx] = nb.create<arith::CmpIOp>(
321*a54f4eaeSMogball           arith::CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]);
322*a54f4eaeSMogball       isBlockLastCoord[loopIdx] = nb.create<arith::CmpIOp>(
323*a54f4eaeSMogball           arith::CmpIPredicate::eq, iv, blockLastCoord[loopIdx]);
32486ad0af8SEugene Zhulenev 
32534a164c9SEugene Zhulenev       // Check if the previous loop is in its first or last iteration.
32686ad0af8SEugene Zhulenev       if (loopIdx > 0) {
327*a54f4eaeSMogball         isBlockFirstCoord[loopIdx] = nb.create<arith::AndIOp>(
32886ad0af8SEugene Zhulenev             isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]);
329*a54f4eaeSMogball         isBlockLastCoord[loopIdx] = nb.create<arith::AndIOp>(
33086ad0af8SEugene Zhulenev             isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]);
33186ad0af8SEugene Zhulenev       }
33286ad0af8SEugene Zhulenev 
33386ad0af8SEugene Zhulenev       // Keep building loop nest.
33486ad0af8SEugene Zhulenev       if (loopIdx < op.getNumLoops() - 1) {
33586ad0af8SEugene Zhulenev         // Select nested loop lower/upper bounds depending on out position in
33686ad0af8SEugene Zhulenev         // the multi-dimensional iteration space.
33786ad0af8SEugene Zhulenev         auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx],
33886ad0af8SEugene Zhulenev                                       blockFirstCoord[loopIdx + 1], c0);
33986ad0af8SEugene Zhulenev 
34086ad0af8SEugene Zhulenev         auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx],
34186ad0af8SEugene Zhulenev                                       blockEndCoord[loopIdx + 1],
34286ad0af8SEugene Zhulenev                                       tripCounts[loopIdx + 1]);
34386ad0af8SEugene Zhulenev 
34486ad0af8SEugene Zhulenev         nb.create<scf::ForOp>(lb, ub, c1, ValueRange(),
34586ad0af8SEugene Zhulenev                               workLoopBuilder(loopIdx + 1));
34686ad0af8SEugene Zhulenev         nb.create<scf::YieldOp>(loc);
34786ad0af8SEugene Zhulenev         return;
34886ad0af8SEugene Zhulenev       }
34986ad0af8SEugene Zhulenev 
35086ad0af8SEugene Zhulenev       // Copy the body of the parallel op into the inner-most loop.
35186ad0af8SEugene Zhulenev       BlockAndValueMapping mapping;
35286ad0af8SEugene Zhulenev       mapping.map(op.getInductionVars(), computeBlockInductionVars);
35386ad0af8SEugene Zhulenev       mapping.map(computeFuncType.captures, captures);
35486ad0af8SEugene Zhulenev 
35586ad0af8SEugene Zhulenev       for (auto &bodyOp : op.getLoopBody().getOps())
35686ad0af8SEugene Zhulenev         nb.clone(bodyOp, mapping);
35786ad0af8SEugene Zhulenev     };
35886ad0af8SEugene Zhulenev   };
35986ad0af8SEugene Zhulenev 
36086ad0af8SEugene Zhulenev   b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(),
36186ad0af8SEugene Zhulenev                        workLoopBuilder(0));
36286ad0af8SEugene Zhulenev   b.create<ReturnOp>(ValueRange());
36386ad0af8SEugene Zhulenev 
36486ad0af8SEugene Zhulenev   return {func, std::move(computeFuncType.captures)};
36586ad0af8SEugene Zhulenev }
36686ad0af8SEugene Zhulenev 
36786ad0af8SEugene Zhulenev // Creates recursive async dispatch function for the given parallel compute
36886ad0af8SEugene Zhulenev // function. Dispatch function keeps splitting block range into halves until it
36986ad0af8SEugene Zhulenev // reaches a single block, and then excecutes it inline.
37086ad0af8SEugene Zhulenev //
37186ad0af8SEugene Zhulenev // Function pseudocode (mix of C++ and MLIR):
37286ad0af8SEugene Zhulenev //
37386ad0af8SEugene Zhulenev //   func @async_dispatch(%block_start : index, %block_end : index, ...) {
37486ad0af8SEugene Zhulenev //
37586ad0af8SEugene Zhulenev //     // Keep splitting block range until we reached a range of size 1.
37686ad0af8SEugene Zhulenev //     while (%block_end - %block_start > 1) {
37786ad0af8SEugene Zhulenev //       %mid_index = block_start + (block_end - block_start) / 2;
37886ad0af8SEugene Zhulenev //       async.execute { call @async_dispatch(%mid_index, %block_end); }
37986ad0af8SEugene Zhulenev //       %block_end = %mid_index
38086ad0af8SEugene Zhulenev //     }
38186ad0af8SEugene Zhulenev //
38286ad0af8SEugene Zhulenev //     // Call parallel compute function for a single block.
38386ad0af8SEugene Zhulenev //     call @parallel_compute_fn(%block_start, %block_size, ...);
38486ad0af8SEugene Zhulenev //   }
38586ad0af8SEugene Zhulenev //
38686ad0af8SEugene Zhulenev static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc,
38786ad0af8SEugene Zhulenev                                           PatternRewriter &rewriter) {
38886ad0af8SEugene Zhulenev   OpBuilder::InsertionGuard guard(rewriter);
38986ad0af8SEugene Zhulenev   Location loc = computeFunc.func.getLoc();
39086ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(loc, rewriter);
39186ad0af8SEugene Zhulenev 
39286ad0af8SEugene Zhulenev   ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>();
39386ad0af8SEugene Zhulenev 
39486ad0af8SEugene Zhulenev   ArrayRef<Type> computeFuncInputTypes =
39586ad0af8SEugene Zhulenev       computeFunc.func.type().cast<FunctionType>().getInputs();
39686ad0af8SEugene Zhulenev 
39786ad0af8SEugene Zhulenev   // Compared to the parallel compute function async dispatch function takes
39886ad0af8SEugene Zhulenev   // additional !async.group argument. Also instead of a single `blockIndex` it
39986ad0af8SEugene Zhulenev   // takes `blockStart` and `blockEnd` arguments to define the range of
40086ad0af8SEugene Zhulenev   // dispatched blocks.
40186ad0af8SEugene Zhulenev   SmallVector<Type> inputTypes;
40286ad0af8SEugene Zhulenev   inputTypes.push_back(async::GroupType::get(rewriter.getContext()));
40386ad0af8SEugene Zhulenev   inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument
40486ad0af8SEugene Zhulenev   inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end());
40586ad0af8SEugene Zhulenev 
40686ad0af8SEugene Zhulenev   FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange());
40786ad0af8SEugene Zhulenev   FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type);
40886ad0af8SEugene Zhulenev   func.setPrivate();
40986ad0af8SEugene Zhulenev 
41086ad0af8SEugene Zhulenev   // Insert function into the module symbol table and assign it unique name.
41186ad0af8SEugene Zhulenev   SymbolTable symbolTable(module);
41286ad0af8SEugene Zhulenev   symbolTable.insert(func);
41386ad0af8SEugene Zhulenev   rewriter.getListener()->notifyOperationInserted(func);
41486ad0af8SEugene Zhulenev 
41586ad0af8SEugene Zhulenev   // Create function entry block.
41686ad0af8SEugene Zhulenev   Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs());
41786ad0af8SEugene Zhulenev   b.setInsertionPointToEnd(block);
41886ad0af8SEugene Zhulenev 
41986ad0af8SEugene Zhulenev   Type indexTy = b.getIndexType();
420*a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
421*a54f4eaeSMogball   Value c2 = b.create<arith::ConstantIndexOp>(2);
42286ad0af8SEugene Zhulenev 
42386ad0af8SEugene Zhulenev   // Get the async group that will track async dispatch completion.
42486ad0af8SEugene Zhulenev   Value group = block->getArgument(0);
42586ad0af8SEugene Zhulenev 
42686ad0af8SEugene Zhulenev   // Get the block iteration range: [blockStart, blockEnd)
42786ad0af8SEugene Zhulenev   Value blockStart = block->getArgument(1);
42886ad0af8SEugene Zhulenev   Value blockEnd = block->getArgument(2);
42986ad0af8SEugene Zhulenev 
43086ad0af8SEugene Zhulenev   // Create a work splitting while loop for the [blockStart, blockEnd) range.
43186ad0af8SEugene Zhulenev   SmallVector<Type> types = {indexTy, indexTy};
43286ad0af8SEugene Zhulenev   SmallVector<Value> operands = {blockStart, blockEnd};
43386ad0af8SEugene Zhulenev 
43486ad0af8SEugene Zhulenev   // Create a recursive dispatch loop.
43586ad0af8SEugene Zhulenev   scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands);
43686ad0af8SEugene Zhulenev   Block *before = b.createBlock(&whileOp.before(), {}, types);
43786ad0af8SEugene Zhulenev   Block *after = b.createBlock(&whileOp.after(), {}, types);
43886ad0af8SEugene Zhulenev 
43986ad0af8SEugene Zhulenev   // Setup dispatch loop condition block: decide if we need to go into the
44086ad0af8SEugene Zhulenev   // `after` block and launch one more async dispatch.
44186ad0af8SEugene Zhulenev   {
44286ad0af8SEugene Zhulenev     b.setInsertionPointToEnd(before);
44386ad0af8SEugene Zhulenev     Value start = before->getArgument(0);
44486ad0af8SEugene Zhulenev     Value end = before->getArgument(1);
445*a54f4eaeSMogball     Value distance = b.create<arith::SubIOp>(end, start);
446*a54f4eaeSMogball     Value dispatch =
447*a54f4eaeSMogball         b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, distance, c1);
44886ad0af8SEugene Zhulenev     b.create<scf::ConditionOp>(dispatch, before->getArguments());
44986ad0af8SEugene Zhulenev   }
45086ad0af8SEugene Zhulenev 
45186ad0af8SEugene Zhulenev   // Setup the async dispatch loop body: recursively call dispatch function
45234a164c9SEugene Zhulenev   // for the seconds half of the original range and go to the next iteration.
45386ad0af8SEugene Zhulenev   {
45486ad0af8SEugene Zhulenev     b.setInsertionPointToEnd(after);
45586ad0af8SEugene Zhulenev     Value start = after->getArgument(0);
45686ad0af8SEugene Zhulenev     Value end = after->getArgument(1);
457*a54f4eaeSMogball     Value distance = b.create<arith::SubIOp>(end, start);
458*a54f4eaeSMogball     Value halfDistance = b.create<arith::DivSIOp>(distance, c2);
459*a54f4eaeSMogball     Value midIndex = b.create<arith::AddIOp>(start, halfDistance);
46086ad0af8SEugene Zhulenev 
46186ad0af8SEugene Zhulenev     // Call parallel compute function inside the async.execute region.
46286ad0af8SEugene Zhulenev     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
46386ad0af8SEugene Zhulenev                                   Location executeLoc, ValueRange executeArgs) {
46486ad0af8SEugene Zhulenev       // Update the original `blockStart` and `blockEnd` with new range.
46586ad0af8SEugene Zhulenev       SmallVector<Value> operands{block->getArguments().begin(),
46686ad0af8SEugene Zhulenev                                   block->getArguments().end()};
46786ad0af8SEugene Zhulenev       operands[1] = midIndex;
46886ad0af8SEugene Zhulenev       operands[2] = end;
46986ad0af8SEugene Zhulenev 
47086ad0af8SEugene Zhulenev       executeBuilder.create<CallOp>(executeLoc, func.sym_name(),
47186ad0af8SEugene Zhulenev                                     func.getCallableResults(), operands);
47286ad0af8SEugene Zhulenev       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
47386ad0af8SEugene Zhulenev     };
47486ad0af8SEugene Zhulenev 
47586ad0af8SEugene Zhulenev     // Create async.execute operation to dispatch half of the block range.
47686ad0af8SEugene Zhulenev     auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
47786ad0af8SEugene Zhulenev                                        executeBodyBuilder);
47886ad0af8SEugene Zhulenev     b.create<AddToGroupOp>(indexTy, execute.token(), group);
47934a164c9SEugene Zhulenev     b.create<scf::YieldOp>(ValueRange({start, midIndex}));
48086ad0af8SEugene Zhulenev   }
48186ad0af8SEugene Zhulenev 
48286ad0af8SEugene Zhulenev   // After dispatching async operations to process the tail of the block range
48386ad0af8SEugene Zhulenev   // call the parallel compute function for the first block of the range.
48486ad0af8SEugene Zhulenev   b.setInsertionPointAfter(whileOp);
48586ad0af8SEugene Zhulenev 
48686ad0af8SEugene Zhulenev   // Drop async dispatch specific arguments: async group, block start and end.
48786ad0af8SEugene Zhulenev   auto forwardedInputs = block->getArguments().drop_front(3);
48886ad0af8SEugene Zhulenev   SmallVector<Value> computeFuncOperands = {blockStart};
48986ad0af8SEugene Zhulenev   computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end());
49086ad0af8SEugene Zhulenev 
49186ad0af8SEugene Zhulenev   b.create<CallOp>(computeFunc.func.sym_name(),
49286ad0af8SEugene Zhulenev                    computeFunc.func.getCallableResults(), computeFuncOperands);
49386ad0af8SEugene Zhulenev   b.create<ReturnOp>(ValueRange());
49486ad0af8SEugene Zhulenev 
49586ad0af8SEugene Zhulenev   return func;
49686ad0af8SEugene Zhulenev }
49786ad0af8SEugene Zhulenev 
49886ad0af8SEugene Zhulenev // Launch async dispatch of the parallel compute function.
49986ad0af8SEugene Zhulenev static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
50086ad0af8SEugene Zhulenev                             ParallelComputeFunction &parallelComputeFunction,
50186ad0af8SEugene Zhulenev                             scf::ParallelOp op, Value blockSize,
50286ad0af8SEugene Zhulenev                             Value blockCount,
50386ad0af8SEugene Zhulenev                             const SmallVector<Value> &tripCounts) {
50486ad0af8SEugene Zhulenev   MLIRContext *ctx = op->getContext();
50586ad0af8SEugene Zhulenev 
50686ad0af8SEugene Zhulenev   // Add one more level of indirection to dispatch parallel compute functions
50786ad0af8SEugene Zhulenev   // using async operations and recursive work splitting.
50886ad0af8SEugene Zhulenev   FuncOp asyncDispatchFunction =
50986ad0af8SEugene Zhulenev       createAsyncDispatchFunction(parallelComputeFunction, rewriter);
51086ad0af8SEugene Zhulenev 
511*a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
512*a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
51386ad0af8SEugene Zhulenev 
514a8f819c6SEugene Zhulenev   // Appends operands shared by async dispatch and parallel compute functions to
515a8f819c6SEugene Zhulenev   // the given operands vector.
516a8f819c6SEugene Zhulenev   auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) {
517a8f819c6SEugene Zhulenev     operands.append(tripCounts);
518a8f819c6SEugene Zhulenev     operands.append(op.lowerBound().begin(), op.lowerBound().end());
519a8f819c6SEugene Zhulenev     operands.append(op.upperBound().begin(), op.upperBound().end());
520a8f819c6SEugene Zhulenev     operands.append(op.step().begin(), op.step().end());
521a8f819c6SEugene Zhulenev     operands.append(parallelComputeFunction.captures);
522a8f819c6SEugene Zhulenev   };
523a8f819c6SEugene Zhulenev 
524a8f819c6SEugene Zhulenev   // Check if the block size is one, in this case we can skip the async dispatch
525a8f819c6SEugene Zhulenev   // completely. If this will be known statically, then canonicalization will
526a8f819c6SEugene Zhulenev   // erase async group operations.
527*a54f4eaeSMogball   Value isSingleBlock =
528*a54f4eaeSMogball       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1);
529a8f819c6SEugene Zhulenev 
530a8f819c6SEugene Zhulenev   auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
531a8f819c6SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, nestedBuilder);
532a8f819c6SEugene Zhulenev 
533a8f819c6SEugene Zhulenev     // Call parallel compute function for the single block.
534a8f819c6SEugene Zhulenev     SmallVector<Value> operands = {c0, blockSize};
535a8f819c6SEugene Zhulenev     appendBlockComputeOperands(operands);
536a8f819c6SEugene Zhulenev 
537a8f819c6SEugene Zhulenev     nb.create<CallOp>(parallelComputeFunction.func.sym_name(),
538a8f819c6SEugene Zhulenev                       parallelComputeFunction.func.getCallableResults(),
539a8f819c6SEugene Zhulenev                       operands);
540a8f819c6SEugene Zhulenev     nb.create<scf::YieldOp>();
541a8f819c6SEugene Zhulenev   };
542a8f819c6SEugene Zhulenev 
543a8f819c6SEugene Zhulenev   auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) {
544bdde9595Sbakhtiyar     // Create an async.group to wait on all async tokens from the concurrent
545bdde9595Sbakhtiyar     // execution of multiple parallel compute function. First block will be
546bdde9595Sbakhtiyar     // executed synchronously in the caller thread.
547*a54f4eaeSMogball     Value groupSize = b.create<arith::SubIOp>(blockCount, c1);
548bdde9595Sbakhtiyar     Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
549bdde9595Sbakhtiyar 
550a8f819c6SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, nestedBuilder);
55186ad0af8SEugene Zhulenev 
55286ad0af8SEugene Zhulenev     // Launch async dispatch function for [0, blockCount) range.
553a8f819c6SEugene Zhulenev     SmallVector<Value> operands = {group, c0, blockCount, blockSize};
554a8f819c6SEugene Zhulenev     appendBlockComputeOperands(operands);
555a8f819c6SEugene Zhulenev 
556a8f819c6SEugene Zhulenev     nb.create<CallOp>(asyncDispatchFunction.sym_name(),
557a8f819c6SEugene Zhulenev                       asyncDispatchFunction.getCallableResults(), operands);
558bdde9595Sbakhtiyar 
559bdde9595Sbakhtiyar     // Wait for the completion of all parallel compute operations.
560bdde9595Sbakhtiyar     b.create<AwaitAllOp>(group);
561bdde9595Sbakhtiyar 
562a8f819c6SEugene Zhulenev     nb.create<scf::YieldOp>();
563a8f819c6SEugene Zhulenev   };
564a8f819c6SEugene Zhulenev 
565a8f819c6SEugene Zhulenev   // Dispatch either single block compute function, or launch async dispatch.
566a8f819c6SEugene Zhulenev   b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch);
56786ad0af8SEugene Zhulenev }
56886ad0af8SEugene Zhulenev 
56986ad0af8SEugene Zhulenev // Dispatch parallel compute functions by submitting all async compute tasks
57086ad0af8SEugene Zhulenev // from a simple for loop in the caller thread.
57186ad0af8SEugene Zhulenev static void
57255dfab39Sbakhtiyar doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter,
57386ad0af8SEugene Zhulenev                      ParallelComputeFunction &parallelComputeFunction,
57486ad0af8SEugene Zhulenev                      scf::ParallelOp op, Value blockSize, Value blockCount,
57586ad0af8SEugene Zhulenev                      const SmallVector<Value> &tripCounts) {
57686ad0af8SEugene Zhulenev   MLIRContext *ctx = op->getContext();
57786ad0af8SEugene Zhulenev 
57886ad0af8SEugene Zhulenev   FuncOp compute = parallelComputeFunction.func;
57986ad0af8SEugene Zhulenev 
580*a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
581*a54f4eaeSMogball   Value c1 = b.create<arith::ConstantIndexOp>(1);
58286ad0af8SEugene Zhulenev 
58386ad0af8SEugene Zhulenev   // Create an async.group to wait on all async tokens from the concurrent
58486ad0af8SEugene Zhulenev   // execution of multiple parallel compute function. First block will be
58586ad0af8SEugene Zhulenev   // executed synchronously in the caller thread.
586*a54f4eaeSMogball   Value groupSize = b.create<arith::SubIOp>(blockCount, c1);
58786ad0af8SEugene Zhulenev   Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize);
58886ad0af8SEugene Zhulenev 
58986ad0af8SEugene Zhulenev   // Call parallel compute function for all blocks.
59086ad0af8SEugene Zhulenev   using LoopBodyBuilder =
59186ad0af8SEugene Zhulenev       std::function<void(OpBuilder &, Location, Value, ValueRange)>;
59286ad0af8SEugene Zhulenev 
59386ad0af8SEugene Zhulenev   // Returns parallel compute function operands to process the given block.
59486ad0af8SEugene Zhulenev   auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> {
59586ad0af8SEugene Zhulenev     SmallVector<Value> computeFuncOperands = {blockIndex, blockSize};
59686ad0af8SEugene Zhulenev     computeFuncOperands.append(tripCounts);
59786ad0af8SEugene Zhulenev     computeFuncOperands.append(op.lowerBound().begin(), op.lowerBound().end());
59886ad0af8SEugene Zhulenev     computeFuncOperands.append(op.upperBound().begin(), op.upperBound().end());
59986ad0af8SEugene Zhulenev     computeFuncOperands.append(op.step().begin(), op.step().end());
60086ad0af8SEugene Zhulenev     computeFuncOperands.append(parallelComputeFunction.captures);
60186ad0af8SEugene Zhulenev     return computeFuncOperands;
60286ad0af8SEugene Zhulenev   };
60386ad0af8SEugene Zhulenev 
60486ad0af8SEugene Zhulenev   // Induction variable is the index of the block: [0, blockCount).
60586ad0af8SEugene Zhulenev   LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc,
60686ad0af8SEugene Zhulenev                                     Value iv, ValueRange args) {
60786ad0af8SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, loopBuilder);
60886ad0af8SEugene Zhulenev 
60986ad0af8SEugene Zhulenev     // Call parallel compute function inside the async.execute region.
61086ad0af8SEugene Zhulenev     auto executeBodyBuilder = [&](OpBuilder &executeBuilder,
61186ad0af8SEugene Zhulenev                                   Location executeLoc, ValueRange executeArgs) {
61286ad0af8SEugene Zhulenev       executeBuilder.create<CallOp>(executeLoc, compute.sym_name(),
61386ad0af8SEugene Zhulenev                                     compute.getCallableResults(),
61486ad0af8SEugene Zhulenev                                     computeFuncOperands(iv));
61586ad0af8SEugene Zhulenev       executeBuilder.create<async::YieldOp>(executeLoc, ValueRange());
61686ad0af8SEugene Zhulenev     };
61786ad0af8SEugene Zhulenev 
61886ad0af8SEugene Zhulenev     // Create async.execute operation to launch parallel computate function.
61986ad0af8SEugene Zhulenev     auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(),
62086ad0af8SEugene Zhulenev                                         executeBodyBuilder);
62186ad0af8SEugene Zhulenev     nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group);
62286ad0af8SEugene Zhulenev     nb.create<scf::YieldOp>();
62386ad0af8SEugene Zhulenev   };
62486ad0af8SEugene Zhulenev 
62586ad0af8SEugene Zhulenev   // Iterate over all compute blocks and launch parallel compute operations.
62686ad0af8SEugene Zhulenev   b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder);
62786ad0af8SEugene Zhulenev 
62886ad0af8SEugene Zhulenev   // Call parallel compute function for the first block in the caller thread.
62986ad0af8SEugene Zhulenev   b.create<CallOp>(compute.sym_name(), compute.getCallableResults(),
63086ad0af8SEugene Zhulenev                    computeFuncOperands(c0));
63186ad0af8SEugene Zhulenev 
63286ad0af8SEugene Zhulenev   // Wait for the completion of all async compute operations.
63386ad0af8SEugene Zhulenev   b.create<AwaitAllOp>(group);
63486ad0af8SEugene Zhulenev }
63586ad0af8SEugene Zhulenev 
636c30ab6c2SEugene Zhulenev LogicalResult
637c30ab6c2SEugene Zhulenev AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op,
638c30ab6c2SEugene Zhulenev                                          PatternRewriter &rewriter) const {
639c30ab6c2SEugene Zhulenev   // We do not currently support rewrite for parallel op with reductions.
640c30ab6c2SEugene Zhulenev   if (op.getNumReductions() != 0)
641c30ab6c2SEugene Zhulenev     return failure();
642c30ab6c2SEugene Zhulenev 
64386ad0af8SEugene Zhulenev   ImplicitLocOpBuilder b(op.getLoc(), rewriter);
644c30ab6c2SEugene Zhulenev 
645c30ab6c2SEugene Zhulenev   // Compute trip count for each loop induction variable:
64686ad0af8SEugene Zhulenev   //   tripCount = ceil_div(upperBound - lowerBound, step);
64786ad0af8SEugene Zhulenev   SmallVector<Value> tripCounts(op.getNumLoops());
648c30ab6c2SEugene Zhulenev   for (size_t i = 0; i < op.getNumLoops(); ++i) {
649c30ab6c2SEugene Zhulenev     auto lb = op.lowerBound()[i];
650c30ab6c2SEugene Zhulenev     auto ub = op.upperBound()[i];
651c30ab6c2SEugene Zhulenev     auto step = op.step()[i];
652*a54f4eaeSMogball     auto range = b.create<arith::SubIOp>(ub, lb);
653*a54f4eaeSMogball     tripCounts[i] = b.create<arith::CeilDivSIOp>(range, step);
654c30ab6c2SEugene Zhulenev   }
655c30ab6c2SEugene Zhulenev 
65686ad0af8SEugene Zhulenev   // Compute a product of trip counts to get the 1-dimensional iteration space
65786ad0af8SEugene Zhulenev   // for the scf.parallel operation.
65886ad0af8SEugene Zhulenev   Value tripCount = tripCounts[0];
65986ad0af8SEugene Zhulenev   for (size_t i = 1; i < tripCounts.size(); ++i)
660*a54f4eaeSMogball     tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]);
661c30ab6c2SEugene Zhulenev 
6626c1f6558SEugene Zhulenev   // Short circuit no-op parallel loops (zero iterations) that can arise from
6636c1f6558SEugene Zhulenev   // the memrefs with dynamic dimension(s) equal to zero.
664*a54f4eaeSMogball   Value c0 = b.create<arith::ConstantIndexOp>(0);
665*a54f4eaeSMogball   Value isZeroIterations =
666*a54f4eaeSMogball       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0);
6676c1f6558SEugene Zhulenev 
6686c1f6558SEugene Zhulenev   // Do absolutely nothing if the trip count is zero.
6696c1f6558SEugene Zhulenev   auto noOp = [&](OpBuilder &nestedBuilder, Location loc) {
6706c1f6558SEugene Zhulenev     nestedBuilder.create<scf::YieldOp>(loc);
6716c1f6558SEugene Zhulenev   };
6726c1f6558SEugene Zhulenev 
6736c1f6558SEugene Zhulenev   // Compute the parallel block size and dispatch concurrent tasks computing
6746c1f6558SEugene Zhulenev   // results for each block.
6756c1f6558SEugene Zhulenev   auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) {
6766c1f6558SEugene Zhulenev     ImplicitLocOpBuilder nb(loc, nestedBuilder);
6776c1f6558SEugene Zhulenev 
678c1194c2eSEugene Zhulenev     // With large number of threads the value of creating many compute blocks
679c1194c2eSEugene Zhulenev     // is reduced because the problem typically becomes memory bound. For small
680c1194c2eSEugene Zhulenev     // number of threads it helps with stragglers.
681c1194c2eSEugene Zhulenev     float overshardingFactor = numWorkerThreads <= 4    ? 8.0
682c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 8  ? 4.0
683c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 16 ? 2.0
684c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 32 ? 1.0
685c1194c2eSEugene Zhulenev                                : numWorkerThreads <= 64 ? 0.8
686c1194c2eSEugene Zhulenev                                                         : 0.6;
687c1194c2eSEugene Zhulenev 
68886ad0af8SEugene Zhulenev     // Do not overload worker threads with too many compute blocks.
689*a54f4eaeSMogball     Value maxComputeBlocks = b.create<arith::ConstantIndexOp>(
690c1194c2eSEugene Zhulenev         std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor)));
691c30ab6c2SEugene Zhulenev 
69286ad0af8SEugene Zhulenev     // Target block size from the pass parameters.
693*a54f4eaeSMogball     Value minTaskSizeCst = b.create<arith::ConstantIndexOp>(minTaskSize);
694c30ab6c2SEugene Zhulenev 
69586ad0af8SEugene Zhulenev     // Compute parallel block size from the parallel problem size:
69686ad0af8SEugene Zhulenev     //   blockSize = min(tripCount,
69734a164c9SEugene Zhulenev     //                   max(ceil_div(tripCount, maxComputeBlocks),
69855dfab39Sbakhtiyar     //                       ceil_div(minTaskSize, bodySize)))
699*a54f4eaeSMogball     Value bs0 = b.create<arith::DivSIOp>(tripCount, maxComputeBlocks);
700*a54f4eaeSMogball     Value bs1 =
701*a54f4eaeSMogball         b.create<arith::CmpIOp>(arith::CmpIPredicate::sge, bs0, minTaskSizeCst);
70255dfab39Sbakhtiyar     Value bs2 = b.create<SelectOp>(bs1, bs0, minTaskSizeCst);
703*a54f4eaeSMogball     Value bs3 =
704*a54f4eaeSMogball         b.create<arith::CmpIOp>(arith::CmpIPredicate::sle, tripCount, bs2);
705c1194c2eSEugene Zhulenev     Value blockSize0 = b.create<SelectOp>(bs3, tripCount, bs2);
706*a54f4eaeSMogball     Value blockCount0 = b.create<arith::CeilDivSIOp>(tripCount, blockSize0);
707c1194c2eSEugene Zhulenev 
708c1194c2eSEugene Zhulenev     // Compute balanced block size for the estimated block count.
709*a54f4eaeSMogball     Value blockSize = b.create<arith::CeilDivSIOp>(tripCount, blockCount0);
710*a54f4eaeSMogball     Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize);
71186ad0af8SEugene Zhulenev 
71286ad0af8SEugene Zhulenev     // Create a parallel compute function that takes a block id and computes the
71386ad0af8SEugene Zhulenev     // parallel operation body for a subset of iteration space.
71486ad0af8SEugene Zhulenev     ParallelComputeFunction parallelComputeFunction =
71586ad0af8SEugene Zhulenev         createParallelComputeFunction(op, rewriter);
71686ad0af8SEugene Zhulenev 
7176c1f6558SEugene Zhulenev     // Dispatch parallel compute function using async recursive work splitting,
7186c1f6558SEugene Zhulenev     // or by submitting compute task sequentially from a caller thread.
71986ad0af8SEugene Zhulenev     if (asyncDispatch) {
72086ad0af8SEugene Zhulenev       doAsyncDispatch(b, rewriter, parallelComputeFunction, op, blockSize,
72186ad0af8SEugene Zhulenev                       blockCount, tripCounts);
72286ad0af8SEugene Zhulenev     } else {
72355dfab39Sbakhtiyar       doSequentialDispatch(b, rewriter, parallelComputeFunction, op, blockSize,
72486ad0af8SEugene Zhulenev                            blockCount, tripCounts);
725c30ab6c2SEugene Zhulenev     }
726c30ab6c2SEugene Zhulenev 
7276c1f6558SEugene Zhulenev     nb.create<scf::YieldOp>();
7286c1f6558SEugene Zhulenev   };
7296c1f6558SEugene Zhulenev 
7306c1f6558SEugene Zhulenev   // Replace the `scf.parallel` operation with the parallel compute function.
7316c1f6558SEugene Zhulenev   b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch);
7326c1f6558SEugene Zhulenev 
73334a164c9SEugene Zhulenev   // Parallel operation was replaced with a block iteration loop.
734c30ab6c2SEugene Zhulenev   rewriter.eraseOp(op);
735c30ab6c2SEugene Zhulenev 
736c30ab6c2SEugene Zhulenev   return success();
737c30ab6c2SEugene Zhulenev }
738c30ab6c2SEugene Zhulenev 
7398a316b00SEugene Zhulenev void AsyncParallelForPass::runOnOperation() {
740c30ab6c2SEugene Zhulenev   MLIRContext *ctx = &getContext();
741c30ab6c2SEugene Zhulenev 
742dc4e913bSChris Lattner   RewritePatternSet patterns(ctx);
74386ad0af8SEugene Zhulenev   patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads,
74455dfab39Sbakhtiyar                                         minTaskSize);
745c30ab6c2SEugene Zhulenev 
7468a316b00SEugene Zhulenev   if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns))))
747c30ab6c2SEugene Zhulenev     signalPassFailure();
748c30ab6c2SEugene Zhulenev }
749c30ab6c2SEugene Zhulenev 
7508a316b00SEugene Zhulenev std::unique_ptr<Pass> mlir::createAsyncParallelForPass() {
751c30ab6c2SEugene Zhulenev   return std::make_unique<AsyncParallelForPass>();
752c30ab6c2SEugene Zhulenev }
75334a164c9SEugene Zhulenev 
75455dfab39Sbakhtiyar std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch,
75555dfab39Sbakhtiyar                                                        int32_t numWorkerThreads,
75655dfab39Sbakhtiyar                                                        int32_t minTaskSize) {
75734a164c9SEugene Zhulenev   return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads,
75855dfab39Sbakhtiyar                                                 minTaskSize);
75934a164c9SEugene Zhulenev }
760