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" 21*9f151b78SEugene Zhulenev #include "mlir/IR/Matchers.h" 22c30ab6c2SEugene Zhulenev #include "mlir/IR/PatternMatch.h" 23c30ab6c2SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 2486ad0af8SEugene Zhulenev #include "mlir/Transforms/RegionUtils.h" 25c30ab6c2SEugene Zhulenev 26c30ab6c2SEugene Zhulenev using namespace mlir; 27c30ab6c2SEugene Zhulenev using namespace mlir::async; 28c30ab6c2SEugene Zhulenev 29c30ab6c2SEugene Zhulenev #define DEBUG_TYPE "async-parallel-for" 30c30ab6c2SEugene Zhulenev 31c30ab6c2SEugene Zhulenev namespace { 32c30ab6c2SEugene Zhulenev 33c30ab6c2SEugene Zhulenev // Rewrite scf.parallel operation into multiple concurrent async.execute 34c30ab6c2SEugene Zhulenev // operations over non overlapping subranges of the original loop. 35c30ab6c2SEugene Zhulenev // 36c30ab6c2SEugene Zhulenev // Example: 37c30ab6c2SEugene Zhulenev // 3886ad0af8SEugene Zhulenev // scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) { 39c30ab6c2SEugene Zhulenev // "do_some_compute"(%i, %j): () -> () 40c30ab6c2SEugene Zhulenev // } 41c30ab6c2SEugene Zhulenev // 42c30ab6c2SEugene Zhulenev // Converted to: 43c30ab6c2SEugene Zhulenev // 4486ad0af8SEugene Zhulenev // // Parallel compute function that executes the parallel body region for 4586ad0af8SEugene Zhulenev // // a subset of the parallel iteration space defined by the one-dimensional 4686ad0af8SEugene Zhulenev // // compute block index. 4786ad0af8SEugene Zhulenev // func parallel_compute_function(%block_index : index, %block_size : index, 4886ad0af8SEugene Zhulenev // <parallel operation properties>, ...) { 4986ad0af8SEugene Zhulenev // // Compute multi-dimensional loop bounds for %block_index. 5086ad0af8SEugene Zhulenev // %block_lbi, %block_lbj = ... 5186ad0af8SEugene Zhulenev // %block_ubi, %block_ubj = ... 52c30ab6c2SEugene Zhulenev // 5386ad0af8SEugene Zhulenev // // Clone parallel operation body into the scf.for loop nest. 5486ad0af8SEugene Zhulenev // scf.for %i = %blockLbi to %blockUbi { 5586ad0af8SEugene Zhulenev // scf.for %j = block_lbj to %block_ubj { 56c30ab6c2SEugene Zhulenev // "do_some_compute"(%i, %j): () -> () 57c30ab6c2SEugene Zhulenev // } 58c30ab6c2SEugene Zhulenev // } 59c30ab6c2SEugene Zhulenev // } 60c30ab6c2SEugene Zhulenev // 6186ad0af8SEugene Zhulenev // And a dispatch function depending on the `asyncDispatch` option. 6286ad0af8SEugene Zhulenev // 6386ad0af8SEugene Zhulenev // When async dispatch is on: (pseudocode) 6486ad0af8SEugene Zhulenev // 6586ad0af8SEugene Zhulenev // %block_size = ... compute parallel compute block size 6686ad0af8SEugene Zhulenev // %block_count = ... compute the number of compute blocks 6786ad0af8SEugene Zhulenev // 6886ad0af8SEugene Zhulenev // func @async_dispatch(%block_start : index, %block_end : index, ...) { 6986ad0af8SEugene Zhulenev // // Keep splitting block range until we reached a range of size 1. 7086ad0af8SEugene Zhulenev // while (%block_end - %block_start > 1) { 7186ad0af8SEugene Zhulenev // %mid_index = block_start + (block_end - block_start) / 2; 7286ad0af8SEugene Zhulenev // async.execute { call @async_dispatch(%mid_index, %block_end); } 7386ad0af8SEugene Zhulenev // %block_end = %mid_index 74c30ab6c2SEugene Zhulenev // } 75c30ab6c2SEugene Zhulenev // 7686ad0af8SEugene Zhulenev // // Call parallel compute function for a single block. 7786ad0af8SEugene Zhulenev // call @parallel_compute_fn(%block_start, %block_size, ...); 7886ad0af8SEugene Zhulenev // } 79c30ab6c2SEugene Zhulenev // 8086ad0af8SEugene Zhulenev // // Launch async dispatch for [0, block_count) range. 8186ad0af8SEugene Zhulenev // call @async_dispatch(%c0, %block_count); 82c30ab6c2SEugene Zhulenev // 8386ad0af8SEugene Zhulenev // When async dispatch is off: 84c30ab6c2SEugene Zhulenev // 8586ad0af8SEugene Zhulenev // %block_size = ... compute parallel compute block size 8686ad0af8SEugene Zhulenev // %block_count = ... compute the number of compute blocks 8786ad0af8SEugene Zhulenev // 8886ad0af8SEugene Zhulenev // scf.for %block_index = %c0 to %block_count { 8986ad0af8SEugene Zhulenev // call @parallel_compute_fn(%block_index, %block_size, ...) 9086ad0af8SEugene Zhulenev // } 9186ad0af8SEugene Zhulenev // 9286ad0af8SEugene Zhulenev struct AsyncParallelForPass 9386ad0af8SEugene Zhulenev : public AsyncParallelForBase<AsyncParallelForPass> { 9486ad0af8SEugene Zhulenev AsyncParallelForPass() = default; 9534a164c9SEugene Zhulenev 9634a164c9SEugene Zhulenev AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads, 9755dfab39Sbakhtiyar int32_t minTaskSize) { 9834a164c9SEugene Zhulenev this->asyncDispatch = asyncDispatch; 9934a164c9SEugene Zhulenev this->numWorkerThreads = numWorkerThreads; 10055dfab39Sbakhtiyar this->minTaskSize = minTaskSize; 10134a164c9SEugene Zhulenev } 10234a164c9SEugene Zhulenev 10386ad0af8SEugene Zhulenev void runOnOperation() override; 10486ad0af8SEugene Zhulenev }; 10586ad0af8SEugene Zhulenev 106c30ab6c2SEugene Zhulenev struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> { 107c30ab6c2SEugene Zhulenev public: 10886ad0af8SEugene Zhulenev AsyncParallelForRewrite(MLIRContext *ctx, bool asyncDispatch, 10955dfab39Sbakhtiyar int32_t numWorkerThreads, int32_t minTaskSize) 11086ad0af8SEugene Zhulenev : OpRewritePattern(ctx), asyncDispatch(asyncDispatch), 11155dfab39Sbakhtiyar numWorkerThreads(numWorkerThreads), minTaskSize(minTaskSize) {} 112c30ab6c2SEugene Zhulenev 113c30ab6c2SEugene Zhulenev LogicalResult matchAndRewrite(scf::ParallelOp op, 114c30ab6c2SEugene Zhulenev PatternRewriter &rewriter) const override; 115c30ab6c2SEugene Zhulenev 116c30ab6c2SEugene Zhulenev private: 11786ad0af8SEugene Zhulenev bool asyncDispatch; 11886ad0af8SEugene Zhulenev int32_t numWorkerThreads; 11955dfab39Sbakhtiyar int32_t minTaskSize; 120c30ab6c2SEugene Zhulenev }; 121c30ab6c2SEugene Zhulenev 12286ad0af8SEugene Zhulenev struct ParallelComputeFunctionType { 12386ad0af8SEugene Zhulenev FunctionType type; 124*9f151b78SEugene Zhulenev SmallVector<Value> captures; 125*9f151b78SEugene Zhulenev }; 126*9f151b78SEugene Zhulenev 127*9f151b78SEugene Zhulenev // Helper struct to parse parallel compute function argument list. 128*9f151b78SEugene Zhulenev struct ParallelComputeFunctionArgs { 129*9f151b78SEugene Zhulenev BlockArgument blockIndex(); 130*9f151b78SEugene Zhulenev BlockArgument blockSize(); 131*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> tripCounts(); 132*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> lowerBounds(); 133*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> upperBounds(); 134*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> steps(); 135*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> captures(); 136*9f151b78SEugene Zhulenev 137*9f151b78SEugene Zhulenev unsigned numLoops; 138*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> args; 139*9f151b78SEugene Zhulenev }; 140*9f151b78SEugene Zhulenev 141*9f151b78SEugene Zhulenev struct ParallelComputeFunctionBounds { 142*9f151b78SEugene Zhulenev SmallVector<IntegerAttr> tripCounts; 143*9f151b78SEugene Zhulenev SmallVector<IntegerAttr> lowerBounds; 144*9f151b78SEugene Zhulenev SmallVector<IntegerAttr> upperBounds; 145*9f151b78SEugene Zhulenev SmallVector<IntegerAttr> steps; 14686ad0af8SEugene Zhulenev }; 14786ad0af8SEugene Zhulenev 14886ad0af8SEugene Zhulenev struct ParallelComputeFunction { 149*9f151b78SEugene Zhulenev unsigned numLoops; 15086ad0af8SEugene Zhulenev FuncOp func; 15186ad0af8SEugene Zhulenev llvm::SmallVector<Value> captures; 152c30ab6c2SEugene Zhulenev }; 153c30ab6c2SEugene Zhulenev 154c30ab6c2SEugene Zhulenev } // namespace 155c30ab6c2SEugene Zhulenev 156*9f151b78SEugene Zhulenev BlockArgument ParallelComputeFunctionArgs::blockIndex() { return args[0]; } 157*9f151b78SEugene Zhulenev BlockArgument ParallelComputeFunctionArgs::blockSize() { return args[1]; } 158*9f151b78SEugene Zhulenev 159*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::tripCounts() { 160*9f151b78SEugene Zhulenev return args.drop_front(2).take_front(numLoops); 161*9f151b78SEugene Zhulenev } 162*9f151b78SEugene Zhulenev 163*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::lowerBounds() { 164*9f151b78SEugene Zhulenev return args.drop_front(2 + 1 * numLoops).take_front(numLoops); 165*9f151b78SEugene Zhulenev } 166*9f151b78SEugene Zhulenev 167*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::upperBounds() { 168*9f151b78SEugene Zhulenev return args.drop_front(2 + 2 * numLoops).take_front(numLoops); 169*9f151b78SEugene Zhulenev } 170*9f151b78SEugene Zhulenev 171*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::steps() { 172*9f151b78SEugene Zhulenev return args.drop_front(2 + 3 * numLoops).take_front(numLoops); 173*9f151b78SEugene Zhulenev } 174*9f151b78SEugene Zhulenev 175*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> ParallelComputeFunctionArgs::captures() { 176*9f151b78SEugene Zhulenev return args.drop_front(2 + 4 * numLoops); 177*9f151b78SEugene Zhulenev } 178*9f151b78SEugene Zhulenev 179*9f151b78SEugene Zhulenev template <typename ValueRange> 180*9f151b78SEugene Zhulenev static SmallVector<IntegerAttr> integerConstants(ValueRange values) { 181*9f151b78SEugene Zhulenev SmallVector<IntegerAttr> attrs(values.size()); 182*9f151b78SEugene Zhulenev for (unsigned i = 0; i < values.size(); ++i) 183*9f151b78SEugene Zhulenev matchPattern(values[i], m_Constant(&attrs[i])); 184*9f151b78SEugene Zhulenev return attrs; 185*9f151b78SEugene Zhulenev } 186*9f151b78SEugene Zhulenev 18786ad0af8SEugene Zhulenev // Converts one-dimensional iteration index in the [0, tripCount) interval 18886ad0af8SEugene Zhulenev // into multidimensional iteration coordinate. 18986ad0af8SEugene Zhulenev static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index, 19034a164c9SEugene Zhulenev ArrayRef<Value> tripCounts) { 19186ad0af8SEugene Zhulenev SmallVector<Value> coords(tripCounts.size()); 19286ad0af8SEugene Zhulenev assert(!tripCounts.empty() && "tripCounts must be not empty"); 19386ad0af8SEugene Zhulenev 19486ad0af8SEugene Zhulenev for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) { 195a54f4eaeSMogball coords[i] = b.create<arith::RemSIOp>(index, tripCounts[i]); 196a54f4eaeSMogball index = b.create<arith::DivSIOp>(index, tripCounts[i]); 19786ad0af8SEugene Zhulenev } 19886ad0af8SEugene Zhulenev 19986ad0af8SEugene Zhulenev return coords; 20086ad0af8SEugene Zhulenev } 20186ad0af8SEugene Zhulenev 20286ad0af8SEugene Zhulenev // Returns a function type and implicit captures for a parallel compute 20386ad0af8SEugene Zhulenev // function. We'll need a list of implicit captures to setup block and value 20486ad0af8SEugene Zhulenev // mapping when we'll clone the body of the parallel operation. 20586ad0af8SEugene Zhulenev static ParallelComputeFunctionType 20686ad0af8SEugene Zhulenev getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) { 20786ad0af8SEugene Zhulenev // Values implicitly captured by the parallel operation. 20886ad0af8SEugene Zhulenev llvm::SetVector<Value> captures; 20986ad0af8SEugene Zhulenev getUsedValuesDefinedAbove(op.region(), op.region(), captures); 21086ad0af8SEugene Zhulenev 211*9f151b78SEugene Zhulenev SmallVector<Type> inputs; 21286ad0af8SEugene Zhulenev inputs.reserve(2 + 4 * op.getNumLoops() + captures.size()); 21386ad0af8SEugene Zhulenev 21486ad0af8SEugene Zhulenev Type indexTy = rewriter.getIndexType(); 21586ad0af8SEugene Zhulenev 21686ad0af8SEugene Zhulenev // One-dimensional iteration space defined by the block index and size. 21786ad0af8SEugene Zhulenev inputs.push_back(indexTy); // blockIndex 21886ad0af8SEugene Zhulenev inputs.push_back(indexTy); // blockSize 21986ad0af8SEugene Zhulenev 22086ad0af8SEugene Zhulenev // Multi-dimensional parallel iteration space defined by the loop trip counts. 22186ad0af8SEugene Zhulenev for (unsigned i = 0; i < op.getNumLoops(); ++i) 22286ad0af8SEugene Zhulenev inputs.push_back(indexTy); // loop tripCount 22386ad0af8SEugene Zhulenev 224*9f151b78SEugene Zhulenev // Parallel operation lower bound, upper bound and step. Lower bound, upper 225*9f151b78SEugene Zhulenev // bound and step passed as contiguous arguments: 226*9f151b78SEugene Zhulenev // call @compute(%lb0, %lb1, ..., %ub0, %ub1, ..., %step0, %step1, ...) 22786ad0af8SEugene Zhulenev for (unsigned i = 0; i < op.getNumLoops(); ++i) { 22886ad0af8SEugene Zhulenev inputs.push_back(indexTy); // lower bound 22986ad0af8SEugene Zhulenev inputs.push_back(indexTy); // upper bound 23086ad0af8SEugene Zhulenev inputs.push_back(indexTy); // step 23186ad0af8SEugene Zhulenev } 23286ad0af8SEugene Zhulenev 23386ad0af8SEugene Zhulenev // Types of the implicit captures. 23486ad0af8SEugene Zhulenev for (Value capture : captures) 23586ad0af8SEugene Zhulenev inputs.push_back(capture.getType()); 23686ad0af8SEugene Zhulenev 23786ad0af8SEugene Zhulenev // Convert captures to vector for later convenience. 23886ad0af8SEugene Zhulenev SmallVector<Value> capturesVector(captures.begin(), captures.end()); 23986ad0af8SEugene Zhulenev return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector}; 24086ad0af8SEugene Zhulenev } 24186ad0af8SEugene Zhulenev 24286ad0af8SEugene Zhulenev // Create a parallel compute fuction from the parallel operation. 24386ad0af8SEugene Zhulenev static ParallelComputeFunction 244*9f151b78SEugene Zhulenev createParallelComputeFunction(scf::ParallelOp op, 245*9f151b78SEugene Zhulenev ParallelComputeFunctionBounds bounds, 246*9f151b78SEugene Zhulenev PatternRewriter &rewriter) { 24786ad0af8SEugene Zhulenev OpBuilder::InsertionGuard guard(rewriter); 24886ad0af8SEugene Zhulenev ImplicitLocOpBuilder b(op.getLoc(), rewriter); 24986ad0af8SEugene Zhulenev 25086ad0af8SEugene Zhulenev ModuleOp module = op->getParentOfType<ModuleOp>(); 25186ad0af8SEugene Zhulenev 25286ad0af8SEugene Zhulenev ParallelComputeFunctionType computeFuncType = 25386ad0af8SEugene Zhulenev getParallelComputeFunctionType(op, rewriter); 25486ad0af8SEugene Zhulenev 25586ad0af8SEugene Zhulenev FunctionType type = computeFuncType.type; 25686ad0af8SEugene Zhulenev FuncOp func = FuncOp::create(op.getLoc(), "parallel_compute_fn", type); 25786ad0af8SEugene Zhulenev func.setPrivate(); 25886ad0af8SEugene Zhulenev 25986ad0af8SEugene Zhulenev // Insert function into the module symbol table and assign it unique name. 26086ad0af8SEugene Zhulenev SymbolTable symbolTable(module); 26186ad0af8SEugene Zhulenev symbolTable.insert(func); 26286ad0af8SEugene Zhulenev rewriter.getListener()->notifyOperationInserted(func); 26386ad0af8SEugene Zhulenev 26486ad0af8SEugene Zhulenev // Create function entry block. 26586ad0af8SEugene Zhulenev Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 26686ad0af8SEugene Zhulenev b.setInsertionPointToEnd(block); 26786ad0af8SEugene Zhulenev 268*9f151b78SEugene Zhulenev ParallelComputeFunctionArgs args = {op.getNumLoops(), func.getArguments()}; 26986ad0af8SEugene Zhulenev 27086ad0af8SEugene Zhulenev // Block iteration position defined by the block index and size. 271*9f151b78SEugene Zhulenev BlockArgument blockIndex = args.blockIndex(); 272*9f151b78SEugene Zhulenev BlockArgument blockSize = args.blockSize(); 27386ad0af8SEugene Zhulenev 27486ad0af8SEugene Zhulenev // Constants used below. 275a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 276a54f4eaeSMogball Value c1 = b.create<arith::ConstantIndexOp>(1); 27786ad0af8SEugene Zhulenev 278*9f151b78SEugene Zhulenev // Materialize known constants as constant operation in the function body. 279*9f151b78SEugene Zhulenev auto values = [&](ArrayRef<BlockArgument> args, ArrayRef<IntegerAttr> attrs) { 280*9f151b78SEugene Zhulenev return llvm::to_vector( 281*9f151b78SEugene Zhulenev llvm::map_range(llvm::zip(args, attrs), [&](auto tuple) -> Value { 282*9f151b78SEugene Zhulenev if (IntegerAttr attr = std::get<1>(tuple)) 283*9f151b78SEugene Zhulenev return b.create<ConstantOp>(attr); 284*9f151b78SEugene Zhulenev return std::get<0>(tuple); 285*9f151b78SEugene Zhulenev })); 286*9f151b78SEugene Zhulenev }; 287*9f151b78SEugene Zhulenev 28886ad0af8SEugene Zhulenev // Multi-dimensional parallel iteration space defined by the loop trip counts. 289*9f151b78SEugene Zhulenev auto tripCounts = values(args.tripCounts(), bounds.tripCounts); 290*9f151b78SEugene Zhulenev 291*9f151b78SEugene Zhulenev // Parallel operation lower bound and step. 292*9f151b78SEugene Zhulenev auto lowerBounds = values(args.lowerBounds(), bounds.lowerBounds); 293*9f151b78SEugene Zhulenev auto steps = values(args.steps(), bounds.steps); 294*9f151b78SEugene Zhulenev 295*9f151b78SEugene Zhulenev // Remaining arguments are implicit captures of the parallel operation. 296*9f151b78SEugene Zhulenev ArrayRef<BlockArgument> captures = args.captures(); 29786ad0af8SEugene Zhulenev 29886ad0af8SEugene Zhulenev // Compute a product of trip counts to get the size of the flattened 29986ad0af8SEugene Zhulenev // one-dimensional iteration space. 30086ad0af8SEugene Zhulenev Value tripCount = tripCounts[0]; 30186ad0af8SEugene Zhulenev for (unsigned i = 1; i < tripCounts.size(); ++i) 302a54f4eaeSMogball tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 30386ad0af8SEugene Zhulenev 30486ad0af8SEugene Zhulenev // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]: 30586ad0af8SEugene Zhulenev // blockFirstIndex = blockIndex * blockSize 306a54f4eaeSMogball Value blockFirstIndex = b.create<arith::MulIOp>(blockIndex, blockSize); 30786ad0af8SEugene Zhulenev 30886ad0af8SEugene Zhulenev // The last one-dimensional index in the block defined by the `blockIndex`: 30968a7c001SEugene Zhulenev // blockLastIndex = min(blockFirstIndex + blockSize, tripCount) - 1 310a54f4eaeSMogball Value blockEnd0 = b.create<arith::AddIOp>(blockFirstIndex, blockSize); 3117bd87a03Sbakhtiyar Value blockEnd1 = b.create<arith::MinSIOp>(blockEnd0, tripCount); 3127bd87a03Sbakhtiyar Value blockLastIndex = b.create<arith::SubIOp>(blockEnd1, c1); 31386ad0af8SEugene Zhulenev 31486ad0af8SEugene Zhulenev // Convert one-dimensional indices to multi-dimensional coordinates. 31586ad0af8SEugene Zhulenev auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts); 31686ad0af8SEugene Zhulenev auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts); 31786ad0af8SEugene Zhulenev 31834a164c9SEugene Zhulenev // Compute loops upper bounds derived from the block last coordinates: 31986ad0af8SEugene Zhulenev // blockEndCoord[i] = blockLastCoord[i] + 1 32086ad0af8SEugene Zhulenev // 32186ad0af8SEugene Zhulenev // Block first and last coordinates can be the same along the outer compute 32234a164c9SEugene Zhulenev // dimension when inner compute dimension contains multiple blocks. 32386ad0af8SEugene Zhulenev SmallVector<Value> blockEndCoord(op.getNumLoops()); 32486ad0af8SEugene Zhulenev for (size_t i = 0; i < blockLastCoord.size(); ++i) 325a54f4eaeSMogball blockEndCoord[i] = b.create<arith::AddIOp>(blockLastCoord[i], c1); 32686ad0af8SEugene Zhulenev 32786ad0af8SEugene Zhulenev // Construct a loop nest out of scf.for operations that will iterate over 32886ad0af8SEugene Zhulenev // all coordinates in [blockFirstCoord, blockLastCoord] range. 32986ad0af8SEugene Zhulenev using LoopBodyBuilder = 33086ad0af8SEugene Zhulenev std::function<void(OpBuilder &, Location, Value, ValueRange)>; 33186ad0af8SEugene Zhulenev using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>; 33286ad0af8SEugene Zhulenev 33386ad0af8SEugene Zhulenev // Parallel region induction variables computed from the multi-dimensional 33486ad0af8SEugene Zhulenev // iteration coordinate using parallel operation bounds and step: 33586ad0af8SEugene Zhulenev // 33686ad0af8SEugene Zhulenev // computeBlockInductionVars[loopIdx] = 33768a7c001SEugene Zhulenev // lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopIdx] 33886ad0af8SEugene Zhulenev SmallVector<Value> computeBlockInductionVars(op.getNumLoops()); 33986ad0af8SEugene Zhulenev 34086ad0af8SEugene Zhulenev // We need to know if we are in the first or last iteration of the 34186ad0af8SEugene Zhulenev // multi-dimensional loop for each loop in the nest, so we can decide what 34286ad0af8SEugene Zhulenev // loop bounds should we use for the nested loops: bounds defined by compute 34386ad0af8SEugene Zhulenev // block interval, or bounds defined by the parallel operation. 34486ad0af8SEugene Zhulenev // 34586ad0af8SEugene Zhulenev // Example: 2d parallel operation 34686ad0af8SEugene Zhulenev // i j 34786ad0af8SEugene Zhulenev // loop sizes: [50, 50] 34886ad0af8SEugene Zhulenev // first coord: [25, 25] 34986ad0af8SEugene Zhulenev // last coord: [30, 30] 35086ad0af8SEugene Zhulenev // 35186ad0af8SEugene Zhulenev // If `i` is equal to 25 then iteration over `j` should start at 25, when `i` 35286ad0af8SEugene Zhulenev // is between 25 and 30 it should start at 0. The upper bound for `j` should 35386ad0af8SEugene Zhulenev // be 50, except when `i` is equal to 30, then it should also be 30. 35486ad0af8SEugene Zhulenev // 35586ad0af8SEugene Zhulenev // Value at ith position specifies if all loops in [0, i) range of the loop 35686ad0af8SEugene Zhulenev // nest are in the first/last iteration. 35786ad0af8SEugene Zhulenev SmallVector<Value> isBlockFirstCoord(op.getNumLoops()); 35886ad0af8SEugene Zhulenev SmallVector<Value> isBlockLastCoord(op.getNumLoops()); 35986ad0af8SEugene Zhulenev 36086ad0af8SEugene Zhulenev // Builds inner loop nest inside async.execute operation that does all the 36186ad0af8SEugene Zhulenev // work concurrently. 36286ad0af8SEugene Zhulenev LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder { 36386ad0af8SEugene Zhulenev return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv, 36486ad0af8SEugene Zhulenev ValueRange args) { 36586ad0af8SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 36686ad0af8SEugene Zhulenev 36786ad0af8SEugene Zhulenev // Compute induction variable for `loopIdx`. 368a54f4eaeSMogball computeBlockInductionVars[loopIdx] = nb.create<arith::AddIOp>( 369*9f151b78SEugene Zhulenev lowerBounds[loopIdx], nb.create<arith::MulIOp>(iv, steps[loopIdx])); 37086ad0af8SEugene Zhulenev 37186ad0af8SEugene Zhulenev // Check if we are inside first or last iteration of the loop. 372a54f4eaeSMogball isBlockFirstCoord[loopIdx] = nb.create<arith::CmpIOp>( 373a54f4eaeSMogball arith::CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]); 374a54f4eaeSMogball isBlockLastCoord[loopIdx] = nb.create<arith::CmpIOp>( 375a54f4eaeSMogball arith::CmpIPredicate::eq, iv, blockLastCoord[loopIdx]); 37686ad0af8SEugene Zhulenev 37734a164c9SEugene Zhulenev // Check if the previous loop is in its first or last iteration. 37886ad0af8SEugene Zhulenev if (loopIdx > 0) { 379a54f4eaeSMogball isBlockFirstCoord[loopIdx] = nb.create<arith::AndIOp>( 38086ad0af8SEugene Zhulenev isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]); 381a54f4eaeSMogball isBlockLastCoord[loopIdx] = nb.create<arith::AndIOp>( 38286ad0af8SEugene Zhulenev isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]); 38386ad0af8SEugene Zhulenev } 38486ad0af8SEugene Zhulenev 38586ad0af8SEugene Zhulenev // Keep building loop nest. 38686ad0af8SEugene Zhulenev if (loopIdx < op.getNumLoops() - 1) { 38768a7c001SEugene Zhulenev // Select nested loop lower/upper bounds depending on our position in 38886ad0af8SEugene Zhulenev // the multi-dimensional iteration space. 38986ad0af8SEugene Zhulenev auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx], 39086ad0af8SEugene Zhulenev blockFirstCoord[loopIdx + 1], c0); 39186ad0af8SEugene Zhulenev 39286ad0af8SEugene Zhulenev auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx], 39386ad0af8SEugene Zhulenev blockEndCoord[loopIdx + 1], 39486ad0af8SEugene Zhulenev tripCounts[loopIdx + 1]); 39586ad0af8SEugene Zhulenev 39686ad0af8SEugene Zhulenev nb.create<scf::ForOp>(lb, ub, c1, ValueRange(), 39786ad0af8SEugene Zhulenev workLoopBuilder(loopIdx + 1)); 39886ad0af8SEugene Zhulenev nb.create<scf::YieldOp>(loc); 39986ad0af8SEugene Zhulenev return; 40086ad0af8SEugene Zhulenev } 40186ad0af8SEugene Zhulenev 40286ad0af8SEugene Zhulenev // Copy the body of the parallel op into the inner-most loop. 40386ad0af8SEugene Zhulenev BlockAndValueMapping mapping; 40486ad0af8SEugene Zhulenev mapping.map(op.getInductionVars(), computeBlockInductionVars); 40586ad0af8SEugene Zhulenev mapping.map(computeFuncType.captures, captures); 40686ad0af8SEugene Zhulenev 40786ad0af8SEugene Zhulenev for (auto &bodyOp : op.getLoopBody().getOps()) 40886ad0af8SEugene Zhulenev nb.clone(bodyOp, mapping); 40986ad0af8SEugene Zhulenev }; 41086ad0af8SEugene Zhulenev }; 41186ad0af8SEugene Zhulenev 41286ad0af8SEugene Zhulenev b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(), 41386ad0af8SEugene Zhulenev workLoopBuilder(0)); 41486ad0af8SEugene Zhulenev b.create<ReturnOp>(ValueRange()); 41586ad0af8SEugene Zhulenev 416*9f151b78SEugene Zhulenev return {op.getNumLoops(), func, std::move(computeFuncType.captures)}; 41786ad0af8SEugene Zhulenev } 41886ad0af8SEugene Zhulenev 41986ad0af8SEugene Zhulenev // Creates recursive async dispatch function for the given parallel compute 42086ad0af8SEugene Zhulenev // function. Dispatch function keeps splitting block range into halves until it 42186ad0af8SEugene Zhulenev // reaches a single block, and then excecutes it inline. 42286ad0af8SEugene Zhulenev // 42386ad0af8SEugene Zhulenev // Function pseudocode (mix of C++ and MLIR): 42486ad0af8SEugene Zhulenev // 42586ad0af8SEugene Zhulenev // func @async_dispatch(%block_start : index, %block_end : index, ...) { 42686ad0af8SEugene Zhulenev // 42786ad0af8SEugene Zhulenev // // Keep splitting block range until we reached a range of size 1. 42886ad0af8SEugene Zhulenev // while (%block_end - %block_start > 1) { 42986ad0af8SEugene Zhulenev // %mid_index = block_start + (block_end - block_start) / 2; 43086ad0af8SEugene Zhulenev // async.execute { call @async_dispatch(%mid_index, %block_end); } 43186ad0af8SEugene Zhulenev // %block_end = %mid_index 43286ad0af8SEugene Zhulenev // } 43386ad0af8SEugene Zhulenev // 43486ad0af8SEugene Zhulenev // // Call parallel compute function for a single block. 43586ad0af8SEugene Zhulenev // call @parallel_compute_fn(%block_start, %block_size, ...); 43686ad0af8SEugene Zhulenev // } 43786ad0af8SEugene Zhulenev // 43886ad0af8SEugene Zhulenev static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc, 43986ad0af8SEugene Zhulenev PatternRewriter &rewriter) { 44086ad0af8SEugene Zhulenev OpBuilder::InsertionGuard guard(rewriter); 44186ad0af8SEugene Zhulenev Location loc = computeFunc.func.getLoc(); 44286ad0af8SEugene Zhulenev ImplicitLocOpBuilder b(loc, rewriter); 44386ad0af8SEugene Zhulenev 44486ad0af8SEugene Zhulenev ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>(); 44586ad0af8SEugene Zhulenev 44686ad0af8SEugene Zhulenev ArrayRef<Type> computeFuncInputTypes = 44786ad0af8SEugene Zhulenev computeFunc.func.type().cast<FunctionType>().getInputs(); 44886ad0af8SEugene Zhulenev 44986ad0af8SEugene Zhulenev // Compared to the parallel compute function async dispatch function takes 45086ad0af8SEugene Zhulenev // additional !async.group argument. Also instead of a single `blockIndex` it 45186ad0af8SEugene Zhulenev // takes `blockStart` and `blockEnd` arguments to define the range of 45286ad0af8SEugene Zhulenev // dispatched blocks. 45386ad0af8SEugene Zhulenev SmallVector<Type> inputTypes; 45486ad0af8SEugene Zhulenev inputTypes.push_back(async::GroupType::get(rewriter.getContext())); 45586ad0af8SEugene Zhulenev inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument 45686ad0af8SEugene Zhulenev inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end()); 45786ad0af8SEugene Zhulenev 45886ad0af8SEugene Zhulenev FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange()); 45986ad0af8SEugene Zhulenev FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type); 46086ad0af8SEugene Zhulenev func.setPrivate(); 46186ad0af8SEugene Zhulenev 46286ad0af8SEugene Zhulenev // Insert function into the module symbol table and assign it unique name. 46386ad0af8SEugene Zhulenev SymbolTable symbolTable(module); 46486ad0af8SEugene Zhulenev symbolTable.insert(func); 46586ad0af8SEugene Zhulenev rewriter.getListener()->notifyOperationInserted(func); 46686ad0af8SEugene Zhulenev 46786ad0af8SEugene Zhulenev // Create function entry block. 46886ad0af8SEugene Zhulenev Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 46986ad0af8SEugene Zhulenev b.setInsertionPointToEnd(block); 47086ad0af8SEugene Zhulenev 47186ad0af8SEugene Zhulenev Type indexTy = b.getIndexType(); 472a54f4eaeSMogball Value c1 = b.create<arith::ConstantIndexOp>(1); 473a54f4eaeSMogball Value c2 = b.create<arith::ConstantIndexOp>(2); 47486ad0af8SEugene Zhulenev 47586ad0af8SEugene Zhulenev // Get the async group that will track async dispatch completion. 47686ad0af8SEugene Zhulenev Value group = block->getArgument(0); 47786ad0af8SEugene Zhulenev 47886ad0af8SEugene Zhulenev // Get the block iteration range: [blockStart, blockEnd) 47986ad0af8SEugene Zhulenev Value blockStart = block->getArgument(1); 48086ad0af8SEugene Zhulenev Value blockEnd = block->getArgument(2); 48186ad0af8SEugene Zhulenev 48286ad0af8SEugene Zhulenev // Create a work splitting while loop for the [blockStart, blockEnd) range. 48386ad0af8SEugene Zhulenev SmallVector<Type> types = {indexTy, indexTy}; 48486ad0af8SEugene Zhulenev SmallVector<Value> operands = {blockStart, blockEnd}; 48586ad0af8SEugene Zhulenev 48686ad0af8SEugene Zhulenev // Create a recursive dispatch loop. 48786ad0af8SEugene Zhulenev scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands); 48886ad0af8SEugene Zhulenev Block *before = b.createBlock(&whileOp.before(), {}, types); 48986ad0af8SEugene Zhulenev Block *after = b.createBlock(&whileOp.after(), {}, types); 49086ad0af8SEugene Zhulenev 49186ad0af8SEugene Zhulenev // Setup dispatch loop condition block: decide if we need to go into the 49286ad0af8SEugene Zhulenev // `after` block and launch one more async dispatch. 49386ad0af8SEugene Zhulenev { 49486ad0af8SEugene Zhulenev b.setInsertionPointToEnd(before); 49586ad0af8SEugene Zhulenev Value start = before->getArgument(0); 49686ad0af8SEugene Zhulenev Value end = before->getArgument(1); 497a54f4eaeSMogball Value distance = b.create<arith::SubIOp>(end, start); 498a54f4eaeSMogball Value dispatch = 499a54f4eaeSMogball b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, distance, c1); 50086ad0af8SEugene Zhulenev b.create<scf::ConditionOp>(dispatch, before->getArguments()); 50186ad0af8SEugene Zhulenev } 50286ad0af8SEugene Zhulenev 50386ad0af8SEugene Zhulenev // Setup the async dispatch loop body: recursively call dispatch function 50434a164c9SEugene Zhulenev // for the seconds half of the original range and go to the next iteration. 50586ad0af8SEugene Zhulenev { 50686ad0af8SEugene Zhulenev b.setInsertionPointToEnd(after); 50786ad0af8SEugene Zhulenev Value start = after->getArgument(0); 50886ad0af8SEugene Zhulenev Value end = after->getArgument(1); 509a54f4eaeSMogball Value distance = b.create<arith::SubIOp>(end, start); 510a54f4eaeSMogball Value halfDistance = b.create<arith::DivSIOp>(distance, c2); 511a54f4eaeSMogball Value midIndex = b.create<arith::AddIOp>(start, halfDistance); 51286ad0af8SEugene Zhulenev 51386ad0af8SEugene Zhulenev // Call parallel compute function inside the async.execute region. 51486ad0af8SEugene Zhulenev auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 51586ad0af8SEugene Zhulenev Location executeLoc, ValueRange executeArgs) { 51686ad0af8SEugene Zhulenev // Update the original `blockStart` and `blockEnd` with new range. 51786ad0af8SEugene Zhulenev SmallVector<Value> operands{block->getArguments().begin(), 51886ad0af8SEugene Zhulenev block->getArguments().end()}; 51986ad0af8SEugene Zhulenev operands[1] = midIndex; 52086ad0af8SEugene Zhulenev operands[2] = end; 52186ad0af8SEugene Zhulenev 52286ad0af8SEugene Zhulenev executeBuilder.create<CallOp>(executeLoc, func.sym_name(), 52386ad0af8SEugene Zhulenev func.getCallableResults(), operands); 52486ad0af8SEugene Zhulenev executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 52586ad0af8SEugene Zhulenev }; 52686ad0af8SEugene Zhulenev 52786ad0af8SEugene Zhulenev // Create async.execute operation to dispatch half of the block range. 52886ad0af8SEugene Zhulenev auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 52986ad0af8SEugene Zhulenev executeBodyBuilder); 53086ad0af8SEugene Zhulenev b.create<AddToGroupOp>(indexTy, execute.token(), group); 53134a164c9SEugene Zhulenev b.create<scf::YieldOp>(ValueRange({start, midIndex})); 53286ad0af8SEugene Zhulenev } 53386ad0af8SEugene Zhulenev 53486ad0af8SEugene Zhulenev // After dispatching async operations to process the tail of the block range 53586ad0af8SEugene Zhulenev // call the parallel compute function for the first block of the range. 53686ad0af8SEugene Zhulenev b.setInsertionPointAfter(whileOp); 53786ad0af8SEugene Zhulenev 53886ad0af8SEugene Zhulenev // Drop async dispatch specific arguments: async group, block start and end. 53986ad0af8SEugene Zhulenev auto forwardedInputs = block->getArguments().drop_front(3); 54086ad0af8SEugene Zhulenev SmallVector<Value> computeFuncOperands = {blockStart}; 54186ad0af8SEugene Zhulenev computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end()); 54286ad0af8SEugene Zhulenev 54386ad0af8SEugene Zhulenev b.create<CallOp>(computeFunc.func.sym_name(), 54486ad0af8SEugene Zhulenev computeFunc.func.getCallableResults(), computeFuncOperands); 54586ad0af8SEugene Zhulenev b.create<ReturnOp>(ValueRange()); 54686ad0af8SEugene Zhulenev 54786ad0af8SEugene Zhulenev return func; 54886ad0af8SEugene Zhulenev } 54986ad0af8SEugene Zhulenev 55086ad0af8SEugene Zhulenev // Launch async dispatch of the parallel compute function. 55186ad0af8SEugene Zhulenev static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 55286ad0af8SEugene Zhulenev ParallelComputeFunction ¶llelComputeFunction, 55386ad0af8SEugene Zhulenev scf::ParallelOp op, Value blockSize, 55486ad0af8SEugene Zhulenev Value blockCount, 55586ad0af8SEugene Zhulenev const SmallVector<Value> &tripCounts) { 55686ad0af8SEugene Zhulenev MLIRContext *ctx = op->getContext(); 55786ad0af8SEugene Zhulenev 55886ad0af8SEugene Zhulenev // Add one more level of indirection to dispatch parallel compute functions 55986ad0af8SEugene Zhulenev // using async operations and recursive work splitting. 56086ad0af8SEugene Zhulenev FuncOp asyncDispatchFunction = 56186ad0af8SEugene Zhulenev createAsyncDispatchFunction(parallelComputeFunction, rewriter); 56286ad0af8SEugene Zhulenev 563a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 564a54f4eaeSMogball Value c1 = b.create<arith::ConstantIndexOp>(1); 56586ad0af8SEugene Zhulenev 566a8f819c6SEugene Zhulenev // Appends operands shared by async dispatch and parallel compute functions to 567a8f819c6SEugene Zhulenev // the given operands vector. 568a8f819c6SEugene Zhulenev auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) { 569a8f819c6SEugene Zhulenev operands.append(tripCounts); 570a8f819c6SEugene Zhulenev operands.append(op.lowerBound().begin(), op.lowerBound().end()); 571a8f819c6SEugene Zhulenev operands.append(op.upperBound().begin(), op.upperBound().end()); 572a8f819c6SEugene Zhulenev operands.append(op.step().begin(), op.step().end()); 573a8f819c6SEugene Zhulenev operands.append(parallelComputeFunction.captures); 574a8f819c6SEugene Zhulenev }; 575a8f819c6SEugene Zhulenev 576a8f819c6SEugene Zhulenev // Check if the block size is one, in this case we can skip the async dispatch 577a8f819c6SEugene Zhulenev // completely. If this will be known statically, then canonicalization will 578a8f819c6SEugene Zhulenev // erase async group operations. 579a54f4eaeSMogball Value isSingleBlock = 580a54f4eaeSMogball b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1); 581a8f819c6SEugene Zhulenev 582a8f819c6SEugene Zhulenev auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 583a8f819c6SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 584a8f819c6SEugene Zhulenev 585a8f819c6SEugene Zhulenev // Call parallel compute function for the single block. 586a8f819c6SEugene Zhulenev SmallVector<Value> operands = {c0, blockSize}; 587a8f819c6SEugene Zhulenev appendBlockComputeOperands(operands); 588a8f819c6SEugene Zhulenev 589a8f819c6SEugene Zhulenev nb.create<CallOp>(parallelComputeFunction.func.sym_name(), 590a8f819c6SEugene Zhulenev parallelComputeFunction.func.getCallableResults(), 591a8f819c6SEugene Zhulenev operands); 592a8f819c6SEugene Zhulenev nb.create<scf::YieldOp>(); 593a8f819c6SEugene Zhulenev }; 594a8f819c6SEugene Zhulenev 595a8f819c6SEugene Zhulenev auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 596bdde9595Sbakhtiyar // Create an async.group to wait on all async tokens from the concurrent 597bdde9595Sbakhtiyar // execution of multiple parallel compute function. First block will be 598bdde9595Sbakhtiyar // executed synchronously in the caller thread. 599a54f4eaeSMogball Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 600bdde9595Sbakhtiyar Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 601bdde9595Sbakhtiyar 602a8f819c6SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 60386ad0af8SEugene Zhulenev 60486ad0af8SEugene Zhulenev // Launch async dispatch function for [0, blockCount) range. 605a8f819c6SEugene Zhulenev SmallVector<Value> operands = {group, c0, blockCount, blockSize}; 606a8f819c6SEugene Zhulenev appendBlockComputeOperands(operands); 607a8f819c6SEugene Zhulenev 608a8f819c6SEugene Zhulenev nb.create<CallOp>(asyncDispatchFunction.sym_name(), 609a8f819c6SEugene Zhulenev asyncDispatchFunction.getCallableResults(), operands); 610bdde9595Sbakhtiyar 611bdde9595Sbakhtiyar // Wait for the completion of all parallel compute operations. 612bdde9595Sbakhtiyar b.create<AwaitAllOp>(group); 613bdde9595Sbakhtiyar 614a8f819c6SEugene Zhulenev nb.create<scf::YieldOp>(); 615a8f819c6SEugene Zhulenev }; 616a8f819c6SEugene Zhulenev 617a8f819c6SEugene Zhulenev // Dispatch either single block compute function, or launch async dispatch. 618a8f819c6SEugene Zhulenev b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch); 61986ad0af8SEugene Zhulenev } 62086ad0af8SEugene Zhulenev 62186ad0af8SEugene Zhulenev // Dispatch parallel compute functions by submitting all async compute tasks 62286ad0af8SEugene Zhulenev // from a simple for loop in the caller thread. 62386ad0af8SEugene Zhulenev static void 62455dfab39Sbakhtiyar doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 62586ad0af8SEugene Zhulenev ParallelComputeFunction ¶llelComputeFunction, 62686ad0af8SEugene Zhulenev scf::ParallelOp op, Value blockSize, Value blockCount, 62786ad0af8SEugene Zhulenev const SmallVector<Value> &tripCounts) { 62886ad0af8SEugene Zhulenev MLIRContext *ctx = op->getContext(); 62986ad0af8SEugene Zhulenev 63086ad0af8SEugene Zhulenev FuncOp compute = parallelComputeFunction.func; 63186ad0af8SEugene Zhulenev 632a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 633a54f4eaeSMogball Value c1 = b.create<arith::ConstantIndexOp>(1); 63486ad0af8SEugene Zhulenev 63586ad0af8SEugene Zhulenev // Create an async.group to wait on all async tokens from the concurrent 63686ad0af8SEugene Zhulenev // execution of multiple parallel compute function. First block will be 63786ad0af8SEugene Zhulenev // executed synchronously in the caller thread. 638a54f4eaeSMogball Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 63986ad0af8SEugene Zhulenev Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 64086ad0af8SEugene Zhulenev 64186ad0af8SEugene Zhulenev // Call parallel compute function for all blocks. 64286ad0af8SEugene Zhulenev using LoopBodyBuilder = 64386ad0af8SEugene Zhulenev std::function<void(OpBuilder &, Location, Value, ValueRange)>; 64486ad0af8SEugene Zhulenev 64586ad0af8SEugene Zhulenev // Returns parallel compute function operands to process the given block. 64686ad0af8SEugene Zhulenev auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> { 64786ad0af8SEugene Zhulenev SmallVector<Value> computeFuncOperands = {blockIndex, blockSize}; 64886ad0af8SEugene Zhulenev computeFuncOperands.append(tripCounts); 64986ad0af8SEugene Zhulenev computeFuncOperands.append(op.lowerBound().begin(), op.lowerBound().end()); 65086ad0af8SEugene Zhulenev computeFuncOperands.append(op.upperBound().begin(), op.upperBound().end()); 65186ad0af8SEugene Zhulenev computeFuncOperands.append(op.step().begin(), op.step().end()); 65286ad0af8SEugene Zhulenev computeFuncOperands.append(parallelComputeFunction.captures); 65386ad0af8SEugene Zhulenev return computeFuncOperands; 65486ad0af8SEugene Zhulenev }; 65586ad0af8SEugene Zhulenev 65686ad0af8SEugene Zhulenev // Induction variable is the index of the block: [0, blockCount). 65786ad0af8SEugene Zhulenev LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc, 65886ad0af8SEugene Zhulenev Value iv, ValueRange args) { 65986ad0af8SEugene Zhulenev ImplicitLocOpBuilder nb(loc, loopBuilder); 66086ad0af8SEugene Zhulenev 66186ad0af8SEugene Zhulenev // Call parallel compute function inside the async.execute region. 66286ad0af8SEugene Zhulenev auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 66386ad0af8SEugene Zhulenev Location executeLoc, ValueRange executeArgs) { 66486ad0af8SEugene Zhulenev executeBuilder.create<CallOp>(executeLoc, compute.sym_name(), 66586ad0af8SEugene Zhulenev compute.getCallableResults(), 66686ad0af8SEugene Zhulenev computeFuncOperands(iv)); 66786ad0af8SEugene Zhulenev executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 66886ad0af8SEugene Zhulenev }; 66986ad0af8SEugene Zhulenev 67086ad0af8SEugene Zhulenev // Create async.execute operation to launch parallel computate function. 67186ad0af8SEugene Zhulenev auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 67286ad0af8SEugene Zhulenev executeBodyBuilder); 67386ad0af8SEugene Zhulenev nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group); 67486ad0af8SEugene Zhulenev nb.create<scf::YieldOp>(); 67586ad0af8SEugene Zhulenev }; 67686ad0af8SEugene Zhulenev 67786ad0af8SEugene Zhulenev // Iterate over all compute blocks and launch parallel compute operations. 67886ad0af8SEugene Zhulenev b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder); 67986ad0af8SEugene Zhulenev 68086ad0af8SEugene Zhulenev // Call parallel compute function for the first block in the caller thread. 68186ad0af8SEugene Zhulenev b.create<CallOp>(compute.sym_name(), compute.getCallableResults(), 68286ad0af8SEugene Zhulenev computeFuncOperands(c0)); 68386ad0af8SEugene Zhulenev 68486ad0af8SEugene Zhulenev // Wait for the completion of all async compute operations. 68586ad0af8SEugene Zhulenev b.create<AwaitAllOp>(group); 68686ad0af8SEugene Zhulenev } 68786ad0af8SEugene Zhulenev 688c30ab6c2SEugene Zhulenev LogicalResult 689c30ab6c2SEugene Zhulenev AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op, 690c30ab6c2SEugene Zhulenev PatternRewriter &rewriter) const { 691c30ab6c2SEugene Zhulenev // We do not currently support rewrite for parallel op with reductions. 692c30ab6c2SEugene Zhulenev if (op.getNumReductions() != 0) 693c30ab6c2SEugene Zhulenev return failure(); 694c30ab6c2SEugene Zhulenev 69586ad0af8SEugene Zhulenev ImplicitLocOpBuilder b(op.getLoc(), rewriter); 696c30ab6c2SEugene Zhulenev 697*9f151b78SEugene Zhulenev // Make sure that all constants will be inside the parallel operation body to 698*9f151b78SEugene Zhulenev // reduce the number of parallel compute function arguments. 699*9f151b78SEugene Zhulenev cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter); 700*9f151b78SEugene Zhulenev 701c30ab6c2SEugene Zhulenev // Compute trip count for each loop induction variable: 70286ad0af8SEugene Zhulenev // tripCount = ceil_div(upperBound - lowerBound, step); 70386ad0af8SEugene Zhulenev SmallVector<Value> tripCounts(op.getNumLoops()); 704c30ab6c2SEugene Zhulenev for (size_t i = 0; i < op.getNumLoops(); ++i) { 705c30ab6c2SEugene Zhulenev auto lb = op.lowerBound()[i]; 706c30ab6c2SEugene Zhulenev auto ub = op.upperBound()[i]; 707c30ab6c2SEugene Zhulenev auto step = op.step()[i]; 708*9f151b78SEugene Zhulenev auto range = b.createOrFold<arith::SubIOp>(ub, lb); 709*9f151b78SEugene Zhulenev tripCounts[i] = b.createOrFold<arith::CeilDivSIOp>(range, step); 710c30ab6c2SEugene Zhulenev } 711c30ab6c2SEugene Zhulenev 71286ad0af8SEugene Zhulenev // Compute a product of trip counts to get the 1-dimensional iteration space 71386ad0af8SEugene Zhulenev // for the scf.parallel operation. 71486ad0af8SEugene Zhulenev Value tripCount = tripCounts[0]; 71586ad0af8SEugene Zhulenev for (size_t i = 1; i < tripCounts.size(); ++i) 716a54f4eaeSMogball tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 717c30ab6c2SEugene Zhulenev 7186c1f6558SEugene Zhulenev // Short circuit no-op parallel loops (zero iterations) that can arise from 7196c1f6558SEugene Zhulenev // the memrefs with dynamic dimension(s) equal to zero. 720a54f4eaeSMogball Value c0 = b.create<arith::ConstantIndexOp>(0); 721a54f4eaeSMogball Value isZeroIterations = 722a54f4eaeSMogball b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0); 7236c1f6558SEugene Zhulenev 7246c1f6558SEugene Zhulenev // Do absolutely nothing if the trip count is zero. 7256c1f6558SEugene Zhulenev auto noOp = [&](OpBuilder &nestedBuilder, Location loc) { 7266c1f6558SEugene Zhulenev nestedBuilder.create<scf::YieldOp>(loc); 7276c1f6558SEugene Zhulenev }; 7286c1f6558SEugene Zhulenev 7296c1f6558SEugene Zhulenev // Compute the parallel block size and dispatch concurrent tasks computing 7306c1f6558SEugene Zhulenev // results for each block. 7316c1f6558SEugene Zhulenev auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) { 7326c1f6558SEugene Zhulenev ImplicitLocOpBuilder nb(loc, nestedBuilder); 7336c1f6558SEugene Zhulenev 734c1194c2eSEugene Zhulenev // With large number of threads the value of creating many compute blocks 735c1194c2eSEugene Zhulenev // is reduced because the problem typically becomes memory bound. For small 736c1194c2eSEugene Zhulenev // number of threads it helps with stragglers. 737c1194c2eSEugene Zhulenev float overshardingFactor = numWorkerThreads <= 4 ? 8.0 738c1194c2eSEugene Zhulenev : numWorkerThreads <= 8 ? 4.0 739c1194c2eSEugene Zhulenev : numWorkerThreads <= 16 ? 2.0 740c1194c2eSEugene Zhulenev : numWorkerThreads <= 32 ? 1.0 741c1194c2eSEugene Zhulenev : numWorkerThreads <= 64 ? 0.8 742c1194c2eSEugene Zhulenev : 0.6; 743c1194c2eSEugene Zhulenev 74486ad0af8SEugene Zhulenev // Do not overload worker threads with too many compute blocks. 745a54f4eaeSMogball Value maxComputeBlocks = b.create<arith::ConstantIndexOp>( 746c1194c2eSEugene Zhulenev std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor))); 747c30ab6c2SEugene Zhulenev 74886ad0af8SEugene Zhulenev // Target block size from the pass parameters. 749a54f4eaeSMogball Value minTaskSizeCst = b.create<arith::ConstantIndexOp>(minTaskSize); 750c30ab6c2SEugene Zhulenev 75186ad0af8SEugene Zhulenev // Compute parallel block size from the parallel problem size: 75286ad0af8SEugene Zhulenev // blockSize = min(tripCount, 75334a164c9SEugene Zhulenev // max(ceil_div(tripCount, maxComputeBlocks), 75455dfab39Sbakhtiyar // ceil_div(minTaskSize, bodySize))) 7557bd87a03Sbakhtiyar Value bs0 = b.create<arith::CeilDivSIOp>(tripCount, maxComputeBlocks); 7567bd87a03Sbakhtiyar Value bs1 = b.create<arith::MaxSIOp>(bs0, minTaskSizeCst); 7577bd87a03Sbakhtiyar Value blockSize = b.create<arith::MinSIOp>(tripCount, bs1); 758a54f4eaeSMogball Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize); 75986ad0af8SEugene Zhulenev 760*9f151b78SEugene Zhulenev // Collect statically known constants defining the loop nest in the parallel 761*9f151b78SEugene Zhulenev // compute function. LLVM can't always push constants across the non-trivial 762*9f151b78SEugene Zhulenev // async dispatch call graph, by providing these values explicitly we can 763*9f151b78SEugene Zhulenev // choose to build more efficient loop nest, and rely on a better constant 764*9f151b78SEugene Zhulenev // folding, loop unrolling and vectorization. 765*9f151b78SEugene Zhulenev ParallelComputeFunctionBounds staticBounds = { 766*9f151b78SEugene Zhulenev integerConstants(tripCounts), 767*9f151b78SEugene Zhulenev integerConstants(op.lowerBound()), 768*9f151b78SEugene Zhulenev integerConstants(op.upperBound()), 769*9f151b78SEugene Zhulenev integerConstants(op.step()), 770*9f151b78SEugene Zhulenev }; 771*9f151b78SEugene Zhulenev 77286ad0af8SEugene Zhulenev // Create a parallel compute function that takes a block id and computes the 77386ad0af8SEugene Zhulenev // parallel operation body for a subset of iteration space. 77486ad0af8SEugene Zhulenev ParallelComputeFunction parallelComputeFunction = 775*9f151b78SEugene Zhulenev createParallelComputeFunction(op, staticBounds, rewriter); 77686ad0af8SEugene Zhulenev 7776c1f6558SEugene Zhulenev // Dispatch parallel compute function using async recursive work splitting, 7786c1f6558SEugene Zhulenev // or by submitting compute task sequentially from a caller thread. 77986ad0af8SEugene Zhulenev if (asyncDispatch) { 78086ad0af8SEugene Zhulenev doAsyncDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 78186ad0af8SEugene Zhulenev blockCount, tripCounts); 78286ad0af8SEugene Zhulenev } else { 78355dfab39Sbakhtiyar doSequentialDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 78486ad0af8SEugene Zhulenev blockCount, tripCounts); 785c30ab6c2SEugene Zhulenev } 786c30ab6c2SEugene Zhulenev 7876c1f6558SEugene Zhulenev nb.create<scf::YieldOp>(); 7886c1f6558SEugene Zhulenev }; 7896c1f6558SEugene Zhulenev 7906c1f6558SEugene Zhulenev // Replace the `scf.parallel` operation with the parallel compute function. 7916c1f6558SEugene Zhulenev b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch); 7926c1f6558SEugene Zhulenev 79334a164c9SEugene Zhulenev // Parallel operation was replaced with a block iteration loop. 794c30ab6c2SEugene Zhulenev rewriter.eraseOp(op); 795c30ab6c2SEugene Zhulenev 796c30ab6c2SEugene Zhulenev return success(); 797c30ab6c2SEugene Zhulenev } 798c30ab6c2SEugene Zhulenev 7998a316b00SEugene Zhulenev void AsyncParallelForPass::runOnOperation() { 800c30ab6c2SEugene Zhulenev MLIRContext *ctx = &getContext(); 801c30ab6c2SEugene Zhulenev 802dc4e913bSChris Lattner RewritePatternSet patterns(ctx); 80386ad0af8SEugene Zhulenev patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads, 80455dfab39Sbakhtiyar minTaskSize); 805c30ab6c2SEugene Zhulenev 8068a316b00SEugene Zhulenev if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) 807c30ab6c2SEugene Zhulenev signalPassFailure(); 808c30ab6c2SEugene Zhulenev } 809c30ab6c2SEugene Zhulenev 8108a316b00SEugene Zhulenev std::unique_ptr<Pass> mlir::createAsyncParallelForPass() { 811c30ab6c2SEugene Zhulenev return std::make_unique<AsyncParallelForPass>(); 812c30ab6c2SEugene Zhulenev } 81334a164c9SEugene Zhulenev 81455dfab39Sbakhtiyar std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch, 81555dfab39Sbakhtiyar int32_t numWorkerThreads, 81655dfab39Sbakhtiyar int32_t minTaskSize) { 81734a164c9SEugene Zhulenev return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads, 81855dfab39Sbakhtiyar minTaskSize); 81934a164c9SEugene Zhulenev } 820