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" 14a54f4eaeSMogball #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) { 141a54f4eaeSMogball coords[i] = b.create<arith::RemSIOp>(index, tripCounts[i]); 142a54f4eaeSMogball 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. 230a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 231a54f4eaeSMogball 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) 240a54f4eaeSMogball 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 252a54f4eaeSMogball Value blockFirstIndex = b.create<arith::MulIOp>(blockIndex, blockSize); 25386ad0af8SEugene Zhulenev 25486ad0af8SEugene Zhulenev // The last one-dimensional index in the block defined by the `blockIndex`: 255a54f4eaeSMogball Value blockEnd0 = b.create<arith::AddIOp>(blockFirstIndex, blockSize); 256*7bd87a03Sbakhtiyar Value blockEnd1 = b.create<arith::MinSIOp>(blockEnd0, tripCount); 257*7bd87a03Sbakhtiyar Value blockLastIndex = b.create<arith::SubIOp>(blockEnd1, c1); 25886ad0af8SEugene Zhulenev 25986ad0af8SEugene Zhulenev // Convert one-dimensional indices to multi-dimensional coordinates. 26086ad0af8SEugene Zhulenev auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts); 26186ad0af8SEugene Zhulenev auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts); 26286ad0af8SEugene Zhulenev 26334a164c9SEugene Zhulenev // Compute loops upper bounds derived from the block last coordinates: 26486ad0af8SEugene Zhulenev // blockEndCoord[i] = blockLastCoord[i] + 1 26586ad0af8SEugene Zhulenev // 26686ad0af8SEugene Zhulenev // Block first and last coordinates can be the same along the outer compute 26734a164c9SEugene Zhulenev // dimension when inner compute dimension contains multiple blocks. 26886ad0af8SEugene Zhulenev SmallVector<Value> blockEndCoord(op.getNumLoops()); 26986ad0af8SEugene Zhulenev for (size_t i = 0; i < blockLastCoord.size(); ++i) 270a54f4eaeSMogball blockEndCoord[i] = b.create<arith::AddIOp>(blockLastCoord[i], c1); 27186ad0af8SEugene Zhulenev 27286ad0af8SEugene Zhulenev // Construct a loop nest out of scf.for operations that will iterate over 27386ad0af8SEugene Zhulenev // all coordinates in [blockFirstCoord, blockLastCoord] range. 27486ad0af8SEugene Zhulenev using LoopBodyBuilder = 27586ad0af8SEugene Zhulenev std::function<void(OpBuilder &, Location, Value, ValueRange)>; 27686ad0af8SEugene Zhulenev using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>; 27786ad0af8SEugene Zhulenev 27886ad0af8SEugene Zhulenev // Parallel region induction variables computed from the multi-dimensional 27986ad0af8SEugene Zhulenev // iteration coordinate using parallel operation bounds and step: 28086ad0af8SEugene Zhulenev // 28186ad0af8SEugene Zhulenev // computeBlockInductionVars[loopIdx] = 28286ad0af8SEugene Zhulenev // lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopDdx] 28386ad0af8SEugene Zhulenev SmallVector<Value> computeBlockInductionVars(op.getNumLoops()); 28486ad0af8SEugene Zhulenev 28586ad0af8SEugene Zhulenev // We need to know if we are in the first or last iteration of the 28686ad0af8SEugene Zhulenev // multi-dimensional loop for each loop in the nest, so we can decide what 28786ad0af8SEugene Zhulenev // loop bounds should we use for the nested loops: bounds defined by compute 28886ad0af8SEugene Zhulenev // block interval, or bounds defined by the parallel operation. 28986ad0af8SEugene Zhulenev // 29086ad0af8SEugene Zhulenev // Example: 2d parallel operation 29186ad0af8SEugene Zhulenev // i j 29286ad0af8SEugene Zhulenev // loop sizes: [50, 50] 29386ad0af8SEugene Zhulenev // first coord: [25, 25] 29486ad0af8SEugene Zhulenev // last coord: [30, 30] 29586ad0af8SEugene Zhulenev // 29686ad0af8SEugene Zhulenev // If `i` is equal to 25 then iteration over `j` should start at 25, when `i` 29786ad0af8SEugene Zhulenev // is between 25 and 30 it should start at 0. The upper bound for `j` should 29886ad0af8SEugene Zhulenev // be 50, except when `i` is equal to 30, then it should also be 30. 29986ad0af8SEugene Zhulenev // 30086ad0af8SEugene Zhulenev // Value at ith position specifies if all loops in [0, i) range of the loop 30186ad0af8SEugene Zhulenev // nest are in the first/last iteration. 30286ad0af8SEugene Zhulenev SmallVector<Value> isBlockFirstCoord(op.getNumLoops()); 30386ad0af8SEugene Zhulenev SmallVector<Value> isBlockLastCoord(op.getNumLoops()); 30486ad0af8SEugene Zhulenev 30586ad0af8SEugene Zhulenev // Builds inner loop nest inside async.execute operation that does all the 30686ad0af8SEugene Zhulenev // work concurrently. 30786ad0af8SEugene Zhulenev LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder { 30886ad0af8SEugene Zhulenev return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv, 30986ad0af8SEugene Zhulenev ValueRange args) { 31086ad0af8SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 31186ad0af8SEugene Zhulenev 31286ad0af8SEugene Zhulenev // Compute induction variable for `loopIdx`. 313a54f4eaeSMogball computeBlockInductionVars[loopIdx] = nb.create<arith::AddIOp>( 314a54f4eaeSMogball lowerBound[loopIdx], nb.create<arith::MulIOp>(iv, step[loopIdx])); 31586ad0af8SEugene Zhulenev 31686ad0af8SEugene Zhulenev // Check if we are inside first or last iteration of the loop. 317a54f4eaeSMogball isBlockFirstCoord[loopIdx] = nb.create<arith::CmpIOp>( 318a54f4eaeSMogball arith::CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]); 319a54f4eaeSMogball isBlockLastCoord[loopIdx] = nb.create<arith::CmpIOp>( 320a54f4eaeSMogball arith::CmpIPredicate::eq, iv, blockLastCoord[loopIdx]); 32186ad0af8SEugene Zhulenev 32234a164c9SEugene Zhulenev // Check if the previous loop is in its first or last iteration. 32386ad0af8SEugene Zhulenev if (loopIdx > 0) { 324a54f4eaeSMogball isBlockFirstCoord[loopIdx] = nb.create<arith::AndIOp>( 32586ad0af8SEugene Zhulenev isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]); 326a54f4eaeSMogball isBlockLastCoord[loopIdx] = nb.create<arith::AndIOp>( 32786ad0af8SEugene Zhulenev isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]); 32886ad0af8SEugene Zhulenev } 32986ad0af8SEugene Zhulenev 33086ad0af8SEugene Zhulenev // Keep building loop nest. 33186ad0af8SEugene Zhulenev if (loopIdx < op.getNumLoops() - 1) { 33286ad0af8SEugene Zhulenev // Select nested loop lower/upper bounds depending on out position in 33386ad0af8SEugene Zhulenev // the multi-dimensional iteration space. 33486ad0af8SEugene Zhulenev auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx], 33586ad0af8SEugene Zhulenev blockFirstCoord[loopIdx + 1], c0); 33686ad0af8SEugene Zhulenev 33786ad0af8SEugene Zhulenev auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx], 33886ad0af8SEugene Zhulenev blockEndCoord[loopIdx + 1], 33986ad0af8SEugene Zhulenev tripCounts[loopIdx + 1]); 34086ad0af8SEugene Zhulenev 34186ad0af8SEugene Zhulenev nb.create<scf::ForOp>(lb, ub, c1, ValueRange(), 34286ad0af8SEugene Zhulenev workLoopBuilder(loopIdx + 1)); 34386ad0af8SEugene Zhulenev nb.create<scf::YieldOp>(loc); 34486ad0af8SEugene Zhulenev return; 34586ad0af8SEugene Zhulenev } 34686ad0af8SEugene Zhulenev 34786ad0af8SEugene Zhulenev // Copy the body of the parallel op into the inner-most loop. 34886ad0af8SEugene Zhulenev BlockAndValueMapping mapping; 34986ad0af8SEugene Zhulenev mapping.map(op.getInductionVars(), computeBlockInductionVars); 35086ad0af8SEugene Zhulenev mapping.map(computeFuncType.captures, captures); 35186ad0af8SEugene Zhulenev 35286ad0af8SEugene Zhulenev for (auto &bodyOp : op.getLoopBody().getOps()) 35386ad0af8SEugene Zhulenev nb.clone(bodyOp, mapping); 35486ad0af8SEugene Zhulenev }; 35586ad0af8SEugene Zhulenev }; 35686ad0af8SEugene Zhulenev 35786ad0af8SEugene Zhulenev b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(), 35886ad0af8SEugene Zhulenev workLoopBuilder(0)); 35986ad0af8SEugene Zhulenev b.create<ReturnOp>(ValueRange()); 36086ad0af8SEugene Zhulenev 36186ad0af8SEugene Zhulenev return {func, std::move(computeFuncType.captures)}; 36286ad0af8SEugene Zhulenev } 36386ad0af8SEugene Zhulenev 36486ad0af8SEugene Zhulenev // Creates recursive async dispatch function for the given parallel compute 36586ad0af8SEugene Zhulenev // function. Dispatch function keeps splitting block range into halves until it 36686ad0af8SEugene Zhulenev // reaches a single block, and then excecutes it inline. 36786ad0af8SEugene Zhulenev // 36886ad0af8SEugene Zhulenev // Function pseudocode (mix of C++ and MLIR): 36986ad0af8SEugene Zhulenev // 37086ad0af8SEugene Zhulenev // func @async_dispatch(%block_start : index, %block_end : index, ...) { 37186ad0af8SEugene Zhulenev // 37286ad0af8SEugene Zhulenev // // Keep splitting block range until we reached a range of size 1. 37386ad0af8SEugene Zhulenev // while (%block_end - %block_start > 1) { 37486ad0af8SEugene Zhulenev // %mid_index = block_start + (block_end - block_start) / 2; 37586ad0af8SEugene Zhulenev // async.execute { call @async_dispatch(%mid_index, %block_end); } 37686ad0af8SEugene Zhulenev // %block_end = %mid_index 37786ad0af8SEugene Zhulenev // } 37886ad0af8SEugene Zhulenev // 37986ad0af8SEugene Zhulenev // // Call parallel compute function for a single block. 38086ad0af8SEugene Zhulenev // call @parallel_compute_fn(%block_start, %block_size, ...); 38186ad0af8SEugene Zhulenev // } 38286ad0af8SEugene Zhulenev // 38386ad0af8SEugene Zhulenev static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc, 38486ad0af8SEugene Zhulenev PatternRewriter &rewriter) { 38586ad0af8SEugene Zhulenev OpBuilder::InsertionGuard guard(rewriter); 38686ad0af8SEugene Zhulenev Location loc = computeFunc.func.getLoc(); 38786ad0af8SEugene Zhulenev ImplicitLocOpBuilder b(loc, rewriter); 38886ad0af8SEugene Zhulenev 38986ad0af8SEugene Zhulenev ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>(); 39086ad0af8SEugene Zhulenev 39186ad0af8SEugene Zhulenev ArrayRef<Type> computeFuncInputTypes = 39286ad0af8SEugene Zhulenev computeFunc.func.type().cast<FunctionType>().getInputs(); 39386ad0af8SEugene Zhulenev 39486ad0af8SEugene Zhulenev // Compared to the parallel compute function async dispatch function takes 39586ad0af8SEugene Zhulenev // additional !async.group argument. Also instead of a single `blockIndex` it 39686ad0af8SEugene Zhulenev // takes `blockStart` and `blockEnd` arguments to define the range of 39786ad0af8SEugene Zhulenev // dispatched blocks. 39886ad0af8SEugene Zhulenev SmallVector<Type> inputTypes; 39986ad0af8SEugene Zhulenev inputTypes.push_back(async::GroupType::get(rewriter.getContext())); 40086ad0af8SEugene Zhulenev inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument 40186ad0af8SEugene Zhulenev inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end()); 40286ad0af8SEugene Zhulenev 40386ad0af8SEugene Zhulenev FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange()); 40486ad0af8SEugene Zhulenev FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type); 40586ad0af8SEugene Zhulenev func.setPrivate(); 40686ad0af8SEugene Zhulenev 40786ad0af8SEugene Zhulenev // Insert function into the module symbol table and assign it unique name. 40886ad0af8SEugene Zhulenev SymbolTable symbolTable(module); 40986ad0af8SEugene Zhulenev symbolTable.insert(func); 41086ad0af8SEugene Zhulenev rewriter.getListener()->notifyOperationInserted(func); 41186ad0af8SEugene Zhulenev 41286ad0af8SEugene Zhulenev // Create function entry block. 41386ad0af8SEugene Zhulenev Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 41486ad0af8SEugene Zhulenev b.setInsertionPointToEnd(block); 41586ad0af8SEugene Zhulenev 41686ad0af8SEugene Zhulenev Type indexTy = b.getIndexType(); 417a54f4eaeSMogball Value c1 = b.create<arith::ConstantIndexOp>(1); 418a54f4eaeSMogball Value c2 = b.create<arith::ConstantIndexOp>(2); 41986ad0af8SEugene Zhulenev 42086ad0af8SEugene Zhulenev // Get the async group that will track async dispatch completion. 42186ad0af8SEugene Zhulenev Value group = block->getArgument(0); 42286ad0af8SEugene Zhulenev 42386ad0af8SEugene Zhulenev // Get the block iteration range: [blockStart, blockEnd) 42486ad0af8SEugene Zhulenev Value blockStart = block->getArgument(1); 42586ad0af8SEugene Zhulenev Value blockEnd = block->getArgument(2); 42686ad0af8SEugene Zhulenev 42786ad0af8SEugene Zhulenev // Create a work splitting while loop for the [blockStart, blockEnd) range. 42886ad0af8SEugene Zhulenev SmallVector<Type> types = {indexTy, indexTy}; 42986ad0af8SEugene Zhulenev SmallVector<Value> operands = {blockStart, blockEnd}; 43086ad0af8SEugene Zhulenev 43186ad0af8SEugene Zhulenev // Create a recursive dispatch loop. 43286ad0af8SEugene Zhulenev scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands); 43386ad0af8SEugene Zhulenev Block *before = b.createBlock(&whileOp.before(), {}, types); 43486ad0af8SEugene Zhulenev Block *after = b.createBlock(&whileOp.after(), {}, types); 43586ad0af8SEugene Zhulenev 43686ad0af8SEugene Zhulenev // Setup dispatch loop condition block: decide if we need to go into the 43786ad0af8SEugene Zhulenev // `after` block and launch one more async dispatch. 43886ad0af8SEugene Zhulenev { 43986ad0af8SEugene Zhulenev b.setInsertionPointToEnd(before); 44086ad0af8SEugene Zhulenev Value start = before->getArgument(0); 44186ad0af8SEugene Zhulenev Value end = before->getArgument(1); 442a54f4eaeSMogball Value distance = b.create<arith::SubIOp>(end, start); 443a54f4eaeSMogball Value dispatch = 444a54f4eaeSMogball b.create<arith::CmpIOp>(arith::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); 454a54f4eaeSMogball Value distance = b.create<arith::SubIOp>(end, start); 455a54f4eaeSMogball Value halfDistance = b.create<arith::DivSIOp>(distance, c2); 456a54f4eaeSMogball Value midIndex = b.create<arith::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 ¶llelComputeFunction, 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 508a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 509a54f4eaeSMogball Value c1 = b.create<arith::ConstantIndexOp>(1); 51086ad0af8SEugene Zhulenev 511a8f819c6SEugene Zhulenev // Appends operands shared by async dispatch and parallel compute functions to 512a8f819c6SEugene Zhulenev // the given operands vector. 513a8f819c6SEugene Zhulenev auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) { 514a8f819c6SEugene Zhulenev operands.append(tripCounts); 515a8f819c6SEugene Zhulenev operands.append(op.lowerBound().begin(), op.lowerBound().end()); 516a8f819c6SEugene Zhulenev operands.append(op.upperBound().begin(), op.upperBound().end()); 517a8f819c6SEugene Zhulenev operands.append(op.step().begin(), op.step().end()); 518a8f819c6SEugene Zhulenev operands.append(parallelComputeFunction.captures); 519a8f819c6SEugene Zhulenev }; 520a8f819c6SEugene Zhulenev 521a8f819c6SEugene Zhulenev // Check if the block size is one, in this case we can skip the async dispatch 522a8f819c6SEugene Zhulenev // completely. If this will be known statically, then canonicalization will 523a8f819c6SEugene Zhulenev // erase async group operations. 524a54f4eaeSMogball Value isSingleBlock = 525a54f4eaeSMogball b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1); 526a8f819c6SEugene Zhulenev 527a8f819c6SEugene Zhulenev auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 528a8f819c6SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 529a8f819c6SEugene Zhulenev 530a8f819c6SEugene Zhulenev // Call parallel compute function for the single block. 531a8f819c6SEugene Zhulenev SmallVector<Value> operands = {c0, blockSize}; 532a8f819c6SEugene Zhulenev appendBlockComputeOperands(operands); 533a8f819c6SEugene Zhulenev 534a8f819c6SEugene Zhulenev nb.create<CallOp>(parallelComputeFunction.func.sym_name(), 535a8f819c6SEugene Zhulenev parallelComputeFunction.func.getCallableResults(), 536a8f819c6SEugene Zhulenev operands); 537a8f819c6SEugene Zhulenev nb.create<scf::YieldOp>(); 538a8f819c6SEugene Zhulenev }; 539a8f819c6SEugene Zhulenev 540a8f819c6SEugene Zhulenev auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 541bdde9595Sbakhtiyar // Create an async.group to wait on all async tokens from the concurrent 542bdde9595Sbakhtiyar // execution of multiple parallel compute function. First block will be 543bdde9595Sbakhtiyar // executed synchronously in the caller thread. 544a54f4eaeSMogball Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 545bdde9595Sbakhtiyar Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 546bdde9595Sbakhtiyar 547a8f819c6SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 54886ad0af8SEugene Zhulenev 54986ad0af8SEugene Zhulenev // Launch async dispatch function for [0, blockCount) range. 550a8f819c6SEugene Zhulenev SmallVector<Value> operands = {group, c0, blockCount, blockSize}; 551a8f819c6SEugene Zhulenev appendBlockComputeOperands(operands); 552a8f819c6SEugene Zhulenev 553a8f819c6SEugene Zhulenev nb.create<CallOp>(asyncDispatchFunction.sym_name(), 554a8f819c6SEugene Zhulenev asyncDispatchFunction.getCallableResults(), operands); 555bdde9595Sbakhtiyar 556bdde9595Sbakhtiyar // Wait for the completion of all parallel compute operations. 557bdde9595Sbakhtiyar b.create<AwaitAllOp>(group); 558bdde9595Sbakhtiyar 559a8f819c6SEugene Zhulenev nb.create<scf::YieldOp>(); 560a8f819c6SEugene Zhulenev }; 561a8f819c6SEugene Zhulenev 562a8f819c6SEugene Zhulenev // Dispatch either single block compute function, or launch async dispatch. 563a8f819c6SEugene Zhulenev b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch); 56486ad0af8SEugene Zhulenev } 56586ad0af8SEugene Zhulenev 56686ad0af8SEugene Zhulenev // Dispatch parallel compute functions by submitting all async compute tasks 56786ad0af8SEugene Zhulenev // from a simple for loop in the caller thread. 56886ad0af8SEugene Zhulenev static void 56955dfab39Sbakhtiyar doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 57086ad0af8SEugene Zhulenev ParallelComputeFunction ¶llelComputeFunction, 57186ad0af8SEugene Zhulenev scf::ParallelOp op, Value blockSize, Value blockCount, 57286ad0af8SEugene Zhulenev const SmallVector<Value> &tripCounts) { 57386ad0af8SEugene Zhulenev MLIRContext *ctx = op->getContext(); 57486ad0af8SEugene Zhulenev 57586ad0af8SEugene Zhulenev FuncOp compute = parallelComputeFunction.func; 57686ad0af8SEugene Zhulenev 577a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 578a54f4eaeSMogball Value c1 = b.create<arith::ConstantIndexOp>(1); 57986ad0af8SEugene Zhulenev 58086ad0af8SEugene Zhulenev // Create an async.group to wait on all async tokens from the concurrent 58186ad0af8SEugene Zhulenev // execution of multiple parallel compute function. First block will be 58286ad0af8SEugene Zhulenev // executed synchronously in the caller thread. 583a54f4eaeSMogball Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 58486ad0af8SEugene Zhulenev Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 58586ad0af8SEugene Zhulenev 58686ad0af8SEugene Zhulenev // Call parallel compute function for all blocks. 58786ad0af8SEugene Zhulenev using LoopBodyBuilder = 58886ad0af8SEugene Zhulenev std::function<void(OpBuilder &, Location, Value, ValueRange)>; 58986ad0af8SEugene Zhulenev 59086ad0af8SEugene Zhulenev // Returns parallel compute function operands to process the given block. 59186ad0af8SEugene Zhulenev auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> { 59286ad0af8SEugene Zhulenev SmallVector<Value> computeFuncOperands = {blockIndex, blockSize}; 59386ad0af8SEugene Zhulenev computeFuncOperands.append(tripCounts); 59486ad0af8SEugene Zhulenev computeFuncOperands.append(op.lowerBound().begin(), op.lowerBound().end()); 59586ad0af8SEugene Zhulenev computeFuncOperands.append(op.upperBound().begin(), op.upperBound().end()); 59686ad0af8SEugene Zhulenev computeFuncOperands.append(op.step().begin(), op.step().end()); 59786ad0af8SEugene Zhulenev computeFuncOperands.append(parallelComputeFunction.captures); 59886ad0af8SEugene Zhulenev return computeFuncOperands; 59986ad0af8SEugene Zhulenev }; 60086ad0af8SEugene Zhulenev 60186ad0af8SEugene Zhulenev // Induction variable is the index of the block: [0, blockCount). 60286ad0af8SEugene Zhulenev LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc, 60386ad0af8SEugene Zhulenev Value iv, ValueRange args) { 60486ad0af8SEugene Zhulenev ImplicitLocOpBuilder nb(loc, loopBuilder); 60586ad0af8SEugene Zhulenev 60686ad0af8SEugene Zhulenev // Call parallel compute function inside the async.execute region. 60786ad0af8SEugene Zhulenev auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 60886ad0af8SEugene Zhulenev Location executeLoc, ValueRange executeArgs) { 60986ad0af8SEugene Zhulenev executeBuilder.create<CallOp>(executeLoc, compute.sym_name(), 61086ad0af8SEugene Zhulenev compute.getCallableResults(), 61186ad0af8SEugene Zhulenev computeFuncOperands(iv)); 61286ad0af8SEugene Zhulenev executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 61386ad0af8SEugene Zhulenev }; 61486ad0af8SEugene Zhulenev 61586ad0af8SEugene Zhulenev // Create async.execute operation to launch parallel computate function. 61686ad0af8SEugene Zhulenev auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 61786ad0af8SEugene Zhulenev executeBodyBuilder); 61886ad0af8SEugene Zhulenev nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group); 61986ad0af8SEugene Zhulenev nb.create<scf::YieldOp>(); 62086ad0af8SEugene Zhulenev }; 62186ad0af8SEugene Zhulenev 62286ad0af8SEugene Zhulenev // Iterate over all compute blocks and launch parallel compute operations. 62386ad0af8SEugene Zhulenev b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder); 62486ad0af8SEugene Zhulenev 62586ad0af8SEugene Zhulenev // Call parallel compute function for the first block in the caller thread. 62686ad0af8SEugene Zhulenev b.create<CallOp>(compute.sym_name(), compute.getCallableResults(), 62786ad0af8SEugene Zhulenev computeFuncOperands(c0)); 62886ad0af8SEugene Zhulenev 62986ad0af8SEugene Zhulenev // Wait for the completion of all async compute operations. 63086ad0af8SEugene Zhulenev b.create<AwaitAllOp>(group); 63186ad0af8SEugene Zhulenev } 63286ad0af8SEugene Zhulenev 633c30ab6c2SEugene Zhulenev LogicalResult 634c30ab6c2SEugene Zhulenev AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op, 635c30ab6c2SEugene Zhulenev PatternRewriter &rewriter) const { 636c30ab6c2SEugene Zhulenev // We do not currently support rewrite for parallel op with reductions. 637c30ab6c2SEugene Zhulenev if (op.getNumReductions() != 0) 638c30ab6c2SEugene Zhulenev return failure(); 639c30ab6c2SEugene Zhulenev 64086ad0af8SEugene Zhulenev ImplicitLocOpBuilder b(op.getLoc(), rewriter); 641c30ab6c2SEugene Zhulenev 642c30ab6c2SEugene Zhulenev // Compute trip count for each loop induction variable: 64386ad0af8SEugene Zhulenev // tripCount = ceil_div(upperBound - lowerBound, step); 64486ad0af8SEugene Zhulenev SmallVector<Value> tripCounts(op.getNumLoops()); 645c30ab6c2SEugene Zhulenev for (size_t i = 0; i < op.getNumLoops(); ++i) { 646c30ab6c2SEugene Zhulenev auto lb = op.lowerBound()[i]; 647c30ab6c2SEugene Zhulenev auto ub = op.upperBound()[i]; 648c30ab6c2SEugene Zhulenev auto step = op.step()[i]; 649a54f4eaeSMogball auto range = b.create<arith::SubIOp>(ub, lb); 650a54f4eaeSMogball tripCounts[i] = b.create<arith::CeilDivSIOp>(range, step); 651c30ab6c2SEugene Zhulenev } 652c30ab6c2SEugene Zhulenev 65386ad0af8SEugene Zhulenev // Compute a product of trip counts to get the 1-dimensional iteration space 65486ad0af8SEugene Zhulenev // for the scf.parallel operation. 65586ad0af8SEugene Zhulenev Value tripCount = tripCounts[0]; 65686ad0af8SEugene Zhulenev for (size_t i = 1; i < tripCounts.size(); ++i) 657a54f4eaeSMogball tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 658c30ab6c2SEugene Zhulenev 6596c1f6558SEugene Zhulenev // Short circuit no-op parallel loops (zero iterations) that can arise from 6606c1f6558SEugene Zhulenev // the memrefs with dynamic dimension(s) equal to zero. 661a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 662a54f4eaeSMogball Value isZeroIterations = 663a54f4eaeSMogball b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0); 6646c1f6558SEugene Zhulenev 6656c1f6558SEugene Zhulenev // Do absolutely nothing if the trip count is zero. 6666c1f6558SEugene Zhulenev auto noOp = [&](OpBuilder &nestedBuilder, Location loc) { 6676c1f6558SEugene Zhulenev nestedBuilder.create<scf::YieldOp>(loc); 6686c1f6558SEugene Zhulenev }; 6696c1f6558SEugene Zhulenev 6706c1f6558SEugene Zhulenev // Compute the parallel block size and dispatch concurrent tasks computing 6716c1f6558SEugene Zhulenev // results for each block. 6726c1f6558SEugene Zhulenev auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) { 6736c1f6558SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 6746c1f6558SEugene Zhulenev 675c1194c2eSEugene Zhulenev // With large number of threads the value of creating many compute blocks 676c1194c2eSEugene Zhulenev // is reduced because the problem typically becomes memory bound. For small 677c1194c2eSEugene Zhulenev // number of threads it helps with stragglers. 678c1194c2eSEugene Zhulenev float overshardingFactor = numWorkerThreads <= 4 ? 8.0 679c1194c2eSEugene Zhulenev : numWorkerThreads <= 8 ? 4.0 680c1194c2eSEugene Zhulenev : numWorkerThreads <= 16 ? 2.0 681c1194c2eSEugene Zhulenev : numWorkerThreads <= 32 ? 1.0 682c1194c2eSEugene Zhulenev : numWorkerThreads <= 64 ? 0.8 683c1194c2eSEugene Zhulenev : 0.6; 684c1194c2eSEugene Zhulenev 68586ad0af8SEugene Zhulenev // Do not overload worker threads with too many compute blocks. 686a54f4eaeSMogball Value maxComputeBlocks = b.create<arith::ConstantIndexOp>( 687c1194c2eSEugene Zhulenev std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor))); 688c30ab6c2SEugene Zhulenev 68986ad0af8SEugene Zhulenev // Target block size from the pass parameters. 690a54f4eaeSMogball Value minTaskSizeCst = b.create<arith::ConstantIndexOp>(minTaskSize); 691c30ab6c2SEugene Zhulenev 69286ad0af8SEugene Zhulenev // Compute parallel block size from the parallel problem size: 69386ad0af8SEugene Zhulenev // blockSize = min(tripCount, 69434a164c9SEugene Zhulenev // max(ceil_div(tripCount, maxComputeBlocks), 69555dfab39Sbakhtiyar // ceil_div(minTaskSize, bodySize))) 696*7bd87a03Sbakhtiyar Value bs0 = b.create<arith::CeilDivSIOp>(tripCount, maxComputeBlocks); 697*7bd87a03Sbakhtiyar Value bs1 = b.create<arith::MaxSIOp>(bs0, minTaskSizeCst); 698*7bd87a03Sbakhtiyar Value blockSize = b.create<arith::MinSIOp>(tripCount, bs1); 699a54f4eaeSMogball Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize); 70086ad0af8SEugene Zhulenev 70186ad0af8SEugene Zhulenev // Create a parallel compute function that takes a block id and computes the 70286ad0af8SEugene Zhulenev // parallel operation body for a subset of iteration space. 70386ad0af8SEugene Zhulenev ParallelComputeFunction parallelComputeFunction = 70486ad0af8SEugene Zhulenev createParallelComputeFunction(op, rewriter); 70586ad0af8SEugene Zhulenev 7066c1f6558SEugene Zhulenev // Dispatch parallel compute function using async recursive work splitting, 7076c1f6558SEugene Zhulenev // or by submitting compute task sequentially from a caller thread. 70886ad0af8SEugene Zhulenev if (asyncDispatch) { 70986ad0af8SEugene Zhulenev doAsyncDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 71086ad0af8SEugene Zhulenev blockCount, tripCounts); 71186ad0af8SEugene Zhulenev } else { 71255dfab39Sbakhtiyar doSequentialDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 71386ad0af8SEugene Zhulenev blockCount, tripCounts); 714c30ab6c2SEugene Zhulenev } 715c30ab6c2SEugene Zhulenev 7166c1f6558SEugene Zhulenev nb.create<scf::YieldOp>(); 7176c1f6558SEugene Zhulenev }; 7186c1f6558SEugene Zhulenev 7196c1f6558SEugene Zhulenev // Replace the `scf.parallel` operation with the parallel compute function. 7206c1f6558SEugene Zhulenev b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch); 7216c1f6558SEugene Zhulenev 72234a164c9SEugene Zhulenev // Parallel operation was replaced with a block iteration loop. 723c30ab6c2SEugene Zhulenev rewriter.eraseOp(op); 724c30ab6c2SEugene Zhulenev 725c30ab6c2SEugene Zhulenev return success(); 726c30ab6c2SEugene Zhulenev } 727c30ab6c2SEugene Zhulenev 7288a316b00SEugene Zhulenev void AsyncParallelForPass::runOnOperation() { 729c30ab6c2SEugene Zhulenev MLIRContext *ctx = &getContext(); 730c30ab6c2SEugene Zhulenev 731dc4e913bSChris Lattner RewritePatternSet patterns(ctx); 73286ad0af8SEugene Zhulenev patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads, 73355dfab39Sbakhtiyar minTaskSize); 734c30ab6c2SEugene Zhulenev 7358a316b00SEugene Zhulenev if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) 736c30ab6c2SEugene Zhulenev signalPassFailure(); 737c30ab6c2SEugene Zhulenev } 738c30ab6c2SEugene Zhulenev 7398a316b00SEugene Zhulenev std::unique_ptr<Pass> mlir::createAsyncParallelForPass() { 740c30ab6c2SEugene Zhulenev return std::make_unique<AsyncParallelForPass>(); 741c30ab6c2SEugene Zhulenev } 74234a164c9SEugene Zhulenev 74355dfab39Sbakhtiyar std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch, 74455dfab39Sbakhtiyar int32_t numWorkerThreads, 74555dfab39Sbakhtiyar int32_t minTaskSize) { 74634a164c9SEugene Zhulenev return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads, 74755dfab39Sbakhtiyar minTaskSize); 74834a164c9SEugene Zhulenev } 749