1 //===- AsyncParallelFor.cpp - Implementation of Async Parallel For --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements scf.parallel to scf.for + async.execute conversion pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PassDetail.h" 14 #include "mlir/Dialect/Async/IR/Async.h" 15 #include "mlir/Dialect/Async/Passes.h" 16 #include "mlir/Dialect/SCF/SCF.h" 17 #include "mlir/Dialect/StandardOps/IR/Ops.h" 18 #include "mlir/IR/BlockAndValueMapping.h" 19 #include "mlir/IR/ImplicitLocOpBuilder.h" 20 #include "mlir/IR/PatternMatch.h" 21 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 22 #include "mlir/Transforms/RegionUtils.h" 23 24 using namespace mlir; 25 using namespace mlir::async; 26 27 #define DEBUG_TYPE "async-parallel-for" 28 29 namespace { 30 31 // Rewrite scf.parallel operation into multiple concurrent async.execute 32 // operations over non overlapping subranges of the original loop. 33 // 34 // Example: 35 // 36 // scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) { 37 // "do_some_compute"(%i, %j): () -> () 38 // } 39 // 40 // Converted to: 41 // 42 // // Parallel compute function that executes the parallel body region for 43 // // a subset of the parallel iteration space defined by the one-dimensional 44 // // compute block index. 45 // func parallel_compute_function(%block_index : index, %block_size : index, 46 // <parallel operation properties>, ...) { 47 // // Compute multi-dimensional loop bounds for %block_index. 48 // %block_lbi, %block_lbj = ... 49 // %block_ubi, %block_ubj = ... 50 // 51 // // Clone parallel operation body into the scf.for loop nest. 52 // scf.for %i = %blockLbi to %blockUbi { 53 // scf.for %j = block_lbj to %block_ubj { 54 // "do_some_compute"(%i, %j): () -> () 55 // } 56 // } 57 // } 58 // 59 // And a dispatch function depending on the `asyncDispatch` option. 60 // 61 // When async dispatch is on: (pseudocode) 62 // 63 // %block_size = ... compute parallel compute block size 64 // %block_count = ... compute the number of compute blocks 65 // 66 // func @async_dispatch(%block_start : index, %block_end : index, ...) { 67 // // Keep splitting block range until we reached a range of size 1. 68 // while (%block_end - %block_start > 1) { 69 // %mid_index = block_start + (block_end - block_start) / 2; 70 // async.execute { call @async_dispatch(%mid_index, %block_end); } 71 // %block_end = %mid_index 72 // } 73 // 74 // // Call parallel compute function for a single block. 75 // call @parallel_compute_fn(%block_start, %block_size, ...); 76 // } 77 // 78 // // Launch async dispatch for [0, block_count) range. 79 // call @async_dispatch(%c0, %block_count); 80 // 81 // When async dispatch is off: 82 // 83 // %block_size = ... compute parallel compute block size 84 // %block_count = ... compute the number of compute blocks 85 // 86 // scf.for %block_index = %c0 to %block_count { 87 // call @parallel_compute_fn(%block_index, %block_size, ...) 88 // } 89 // 90 struct AsyncParallelForPass 91 : public AsyncParallelForBase<AsyncParallelForPass> { 92 AsyncParallelForPass() = default; 93 94 AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads, 95 int32_t minTaskSize) { 96 this->asyncDispatch = asyncDispatch; 97 this->numWorkerThreads = numWorkerThreads; 98 this->minTaskSize = minTaskSize; 99 } 100 101 void runOnOperation() override; 102 }; 103 104 struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> { 105 public: 106 AsyncParallelForRewrite(MLIRContext *ctx, bool asyncDispatch, 107 int32_t numWorkerThreads, int32_t minTaskSize) 108 : OpRewritePattern(ctx), asyncDispatch(asyncDispatch), 109 numWorkerThreads(numWorkerThreads), minTaskSize(minTaskSize) {} 110 111 LogicalResult matchAndRewrite(scf::ParallelOp op, 112 PatternRewriter &rewriter) const override; 113 114 private: 115 bool asyncDispatch; 116 int32_t numWorkerThreads; 117 int32_t minTaskSize; 118 }; 119 120 struct ParallelComputeFunctionType { 121 FunctionType type; 122 llvm::SmallVector<Value> captures; 123 }; 124 125 struct ParallelComputeFunction { 126 FuncOp func; 127 llvm::SmallVector<Value> captures; 128 }; 129 130 } // namespace 131 132 // Converts one-dimensional iteration index in the [0, tripCount) interval 133 // into multidimensional iteration coordinate. 134 static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index, 135 ArrayRef<Value> tripCounts) { 136 SmallVector<Value> coords(tripCounts.size()); 137 assert(!tripCounts.empty() && "tripCounts must be not empty"); 138 139 for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) { 140 coords[i] = b.create<SignedRemIOp>(index, tripCounts[i]); 141 index = b.create<SignedDivIOp>(index, tripCounts[i]); 142 } 143 144 return coords; 145 } 146 147 // Returns a function type and implicit captures for a parallel compute 148 // function. We'll need a list of implicit captures to setup block and value 149 // mapping when we'll clone the body of the parallel operation. 150 static ParallelComputeFunctionType 151 getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) { 152 // Values implicitly captured by the parallel operation. 153 llvm::SetVector<Value> captures; 154 getUsedValuesDefinedAbove(op.region(), op.region(), captures); 155 156 llvm::SmallVector<Type> inputs; 157 inputs.reserve(2 + 4 * op.getNumLoops() + captures.size()); 158 159 Type indexTy = rewriter.getIndexType(); 160 161 // One-dimensional iteration space defined by the block index and size. 162 inputs.push_back(indexTy); // blockIndex 163 inputs.push_back(indexTy); // blockSize 164 165 // Multi-dimensional parallel iteration space defined by the loop trip counts. 166 for (unsigned i = 0; i < op.getNumLoops(); ++i) 167 inputs.push_back(indexTy); // loop tripCount 168 169 // Parallel operation lower bound, upper bound and step. 170 for (unsigned i = 0; i < op.getNumLoops(); ++i) { 171 inputs.push_back(indexTy); // lower bound 172 inputs.push_back(indexTy); // upper bound 173 inputs.push_back(indexTy); // step 174 } 175 176 // Types of the implicit captures. 177 for (Value capture : captures) 178 inputs.push_back(capture.getType()); 179 180 // Convert captures to vector for later convenience. 181 SmallVector<Value> capturesVector(captures.begin(), captures.end()); 182 return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector}; 183 } 184 185 // Create a parallel compute fuction from the parallel operation. 186 static ParallelComputeFunction 187 createParallelComputeFunction(scf::ParallelOp op, PatternRewriter &rewriter) { 188 OpBuilder::InsertionGuard guard(rewriter); 189 ImplicitLocOpBuilder b(op.getLoc(), rewriter); 190 191 ModuleOp module = op->getParentOfType<ModuleOp>(); 192 193 // Make sure that all constants will be inside the parallel operation body to 194 // reduce the number of parallel compute function arguments. 195 cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter); 196 197 ParallelComputeFunctionType computeFuncType = 198 getParallelComputeFunctionType(op, rewriter); 199 200 FunctionType type = computeFuncType.type; 201 FuncOp func = FuncOp::create(op.getLoc(), "parallel_compute_fn", type); 202 func.setPrivate(); 203 204 // Insert function into the module symbol table and assign it unique name. 205 SymbolTable symbolTable(module); 206 symbolTable.insert(func); 207 rewriter.getListener()->notifyOperationInserted(func); 208 209 // Create function entry block. 210 Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 211 b.setInsertionPointToEnd(block); 212 213 unsigned offset = 0; // argument offset for arguments decoding 214 215 // Returns `numArguments` arguments starting from `offset` and updates offset 216 // by moving forward to the next argument. 217 auto getArguments = [&](unsigned numArguments) -> ArrayRef<Value> { 218 auto args = block->getArguments(); 219 auto slice = args.drop_front(offset).take_front(numArguments); 220 offset += numArguments; 221 return {slice.begin(), slice.end()}; 222 }; 223 224 // Block iteration position defined by the block index and size. 225 Value blockIndex = block->getArgument(offset++); 226 Value blockSize = block->getArgument(offset++); 227 228 // Constants used below. 229 Value c0 = b.create<ConstantIndexOp>(0); 230 Value c1 = b.create<ConstantIndexOp>(1); 231 232 // Multi-dimensional parallel iteration space defined by the loop trip counts. 233 ArrayRef<Value> tripCounts = getArguments(op.getNumLoops()); 234 235 // Compute a product of trip counts to get the size of the flattened 236 // one-dimensional iteration space. 237 Value tripCount = tripCounts[0]; 238 for (unsigned i = 1; i < tripCounts.size(); ++i) 239 tripCount = b.create<MulIOp>(tripCount, tripCounts[i]); 240 241 // Parallel operation lower bound and step. 242 ArrayRef<Value> lowerBound = getArguments(op.getNumLoops()); 243 offset += op.getNumLoops(); // skip upper bound arguments 244 ArrayRef<Value> step = getArguments(op.getNumLoops()); 245 246 // Remaining arguments are implicit captures of the parallel operation. 247 ArrayRef<Value> captures = getArguments(block->getNumArguments() - offset); 248 249 // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]: 250 // blockFirstIndex = blockIndex * blockSize 251 Value blockFirstIndex = b.create<MulIOp>(blockIndex, blockSize); 252 253 // The last one-dimensional index in the block defined by the `blockIndex`: 254 // blockLastIndex = max(blockFirstIndex + blockSize, tripCount) - 1 255 Value blockEnd0 = b.create<AddIOp>(blockFirstIndex, blockSize); 256 Value blockEnd1 = b.create<CmpIOp>(CmpIPredicate::sge, blockEnd0, tripCount); 257 Value blockEnd2 = b.create<SelectOp>(blockEnd1, tripCount, blockEnd0); 258 Value blockLastIndex = b.create<SubIOp>(blockEnd2, c1); 259 260 // Convert one-dimensional indices to multi-dimensional coordinates. 261 auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts); 262 auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts); 263 264 // Compute loops upper bounds derived from the block last coordinates: 265 // blockEndCoord[i] = blockLastCoord[i] + 1 266 // 267 // Block first and last coordinates can be the same along the outer compute 268 // dimension when inner compute dimension contains multiple blocks. 269 SmallVector<Value> blockEndCoord(op.getNumLoops()); 270 for (size_t i = 0; i < blockLastCoord.size(); ++i) 271 blockEndCoord[i] = b.create<AddIOp>(blockLastCoord[i], c1); 272 273 // Construct a loop nest out of scf.for operations that will iterate over 274 // all coordinates in [blockFirstCoord, blockLastCoord] range. 275 using LoopBodyBuilder = 276 std::function<void(OpBuilder &, Location, Value, ValueRange)>; 277 using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>; 278 279 // Parallel region induction variables computed from the multi-dimensional 280 // iteration coordinate using parallel operation bounds and step: 281 // 282 // computeBlockInductionVars[loopIdx] = 283 // lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopDdx] 284 SmallVector<Value> computeBlockInductionVars(op.getNumLoops()); 285 286 // We need to know if we are in the first or last iteration of the 287 // multi-dimensional loop for each loop in the nest, so we can decide what 288 // loop bounds should we use for the nested loops: bounds defined by compute 289 // block interval, or bounds defined by the parallel operation. 290 // 291 // Example: 2d parallel operation 292 // i j 293 // loop sizes: [50, 50] 294 // first coord: [25, 25] 295 // last coord: [30, 30] 296 // 297 // If `i` is equal to 25 then iteration over `j` should start at 25, when `i` 298 // is between 25 and 30 it should start at 0. The upper bound for `j` should 299 // be 50, except when `i` is equal to 30, then it should also be 30. 300 // 301 // Value at ith position specifies if all loops in [0, i) range of the loop 302 // nest are in the first/last iteration. 303 SmallVector<Value> isBlockFirstCoord(op.getNumLoops()); 304 SmallVector<Value> isBlockLastCoord(op.getNumLoops()); 305 306 // Builds inner loop nest inside async.execute operation that does all the 307 // work concurrently. 308 LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder { 309 return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv, 310 ValueRange args) { 311 ImplicitLocOpBuilder nb(loc, nestedBuilder); 312 313 // Compute induction variable for `loopIdx`. 314 computeBlockInductionVars[loopIdx] = nb.create<AddIOp>( 315 lowerBound[loopIdx], nb.create<MulIOp>(iv, step[loopIdx])); 316 317 // Check if we are inside first or last iteration of the loop. 318 isBlockFirstCoord[loopIdx] = 319 nb.create<CmpIOp>(CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]); 320 isBlockLastCoord[loopIdx] = 321 nb.create<CmpIOp>(CmpIPredicate::eq, iv, blockLastCoord[loopIdx]); 322 323 // Check if the previous loop is in its first or last iteration. 324 if (loopIdx > 0) { 325 isBlockFirstCoord[loopIdx] = nb.create<AndOp>( 326 isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]); 327 isBlockLastCoord[loopIdx] = nb.create<AndOp>( 328 isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]); 329 } 330 331 // Keep building loop nest. 332 if (loopIdx < op.getNumLoops() - 1) { 333 // Select nested loop lower/upper bounds depending on out position in 334 // the multi-dimensional iteration space. 335 auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx], 336 blockFirstCoord[loopIdx + 1], c0); 337 338 auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx], 339 blockEndCoord[loopIdx + 1], 340 tripCounts[loopIdx + 1]); 341 342 nb.create<scf::ForOp>(lb, ub, c1, ValueRange(), 343 workLoopBuilder(loopIdx + 1)); 344 nb.create<scf::YieldOp>(loc); 345 return; 346 } 347 348 // Copy the body of the parallel op into the inner-most loop. 349 BlockAndValueMapping mapping; 350 mapping.map(op.getInductionVars(), computeBlockInductionVars); 351 mapping.map(computeFuncType.captures, captures); 352 353 for (auto &bodyOp : op.getLoopBody().getOps()) 354 nb.clone(bodyOp, mapping); 355 }; 356 }; 357 358 b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(), 359 workLoopBuilder(0)); 360 b.create<ReturnOp>(ValueRange()); 361 362 return {func, std::move(computeFuncType.captures)}; 363 } 364 365 // Creates recursive async dispatch function for the given parallel compute 366 // function. Dispatch function keeps splitting block range into halves until it 367 // reaches a single block, and then excecutes it inline. 368 // 369 // Function pseudocode (mix of C++ and MLIR): 370 // 371 // func @async_dispatch(%block_start : index, %block_end : index, ...) { 372 // 373 // // Keep splitting block range until we reached a range of size 1. 374 // while (%block_end - %block_start > 1) { 375 // %mid_index = block_start + (block_end - block_start) / 2; 376 // async.execute { call @async_dispatch(%mid_index, %block_end); } 377 // %block_end = %mid_index 378 // } 379 // 380 // // Call parallel compute function for a single block. 381 // call @parallel_compute_fn(%block_start, %block_size, ...); 382 // } 383 // 384 static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc, 385 PatternRewriter &rewriter) { 386 OpBuilder::InsertionGuard guard(rewriter); 387 Location loc = computeFunc.func.getLoc(); 388 ImplicitLocOpBuilder b(loc, rewriter); 389 390 ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>(); 391 392 ArrayRef<Type> computeFuncInputTypes = 393 computeFunc.func.type().cast<FunctionType>().getInputs(); 394 395 // Compared to the parallel compute function async dispatch function takes 396 // additional !async.group argument. Also instead of a single `blockIndex` it 397 // takes `blockStart` and `blockEnd` arguments to define the range of 398 // dispatched blocks. 399 SmallVector<Type> inputTypes; 400 inputTypes.push_back(async::GroupType::get(rewriter.getContext())); 401 inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument 402 inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end()); 403 404 FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange()); 405 FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type); 406 func.setPrivate(); 407 408 // Insert function into the module symbol table and assign it unique name. 409 SymbolTable symbolTable(module); 410 symbolTable.insert(func); 411 rewriter.getListener()->notifyOperationInserted(func); 412 413 // Create function entry block. 414 Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 415 b.setInsertionPointToEnd(block); 416 417 Type indexTy = b.getIndexType(); 418 Value c1 = b.create<ConstantIndexOp>(1); 419 Value c2 = b.create<ConstantIndexOp>(2); 420 421 // Get the async group that will track async dispatch completion. 422 Value group = block->getArgument(0); 423 424 // Get the block iteration range: [blockStart, blockEnd) 425 Value blockStart = block->getArgument(1); 426 Value blockEnd = block->getArgument(2); 427 428 // Create a work splitting while loop for the [blockStart, blockEnd) range. 429 SmallVector<Type> types = {indexTy, indexTy}; 430 SmallVector<Value> operands = {blockStart, blockEnd}; 431 432 // Create a recursive dispatch loop. 433 scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands); 434 Block *before = b.createBlock(&whileOp.before(), {}, types); 435 Block *after = b.createBlock(&whileOp.after(), {}, types); 436 437 // Setup dispatch loop condition block: decide if we need to go into the 438 // `after` block and launch one more async dispatch. 439 { 440 b.setInsertionPointToEnd(before); 441 Value start = before->getArgument(0); 442 Value end = before->getArgument(1); 443 Value distance = b.create<SubIOp>(end, start); 444 Value dispatch = b.create<CmpIOp>(CmpIPredicate::sgt, distance, c1); 445 b.create<scf::ConditionOp>(dispatch, before->getArguments()); 446 } 447 448 // Setup the async dispatch loop body: recursively call dispatch function 449 // for the seconds half of the original range and go to the next iteration. 450 { 451 b.setInsertionPointToEnd(after); 452 Value start = after->getArgument(0); 453 Value end = after->getArgument(1); 454 Value distance = b.create<SubIOp>(end, start); 455 Value halfDistance = b.create<SignedDivIOp>(distance, c2); 456 Value midIndex = b.create<AddIOp>(start, halfDistance); 457 458 // Call parallel compute function inside the async.execute region. 459 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 460 Location executeLoc, ValueRange executeArgs) { 461 // Update the original `blockStart` and `blockEnd` with new range. 462 SmallVector<Value> operands{block->getArguments().begin(), 463 block->getArguments().end()}; 464 operands[1] = midIndex; 465 operands[2] = end; 466 467 executeBuilder.create<CallOp>(executeLoc, func.sym_name(), 468 func.getCallableResults(), operands); 469 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 470 }; 471 472 // Create async.execute operation to dispatch half of the block range. 473 auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 474 executeBodyBuilder); 475 b.create<AddToGroupOp>(indexTy, execute.token(), group); 476 b.create<scf::YieldOp>(ValueRange({start, midIndex})); 477 } 478 479 // After dispatching async operations to process the tail of the block range 480 // call the parallel compute function for the first block of the range. 481 b.setInsertionPointAfter(whileOp); 482 483 // Drop async dispatch specific arguments: async group, block start and end. 484 auto forwardedInputs = block->getArguments().drop_front(3); 485 SmallVector<Value> computeFuncOperands = {blockStart}; 486 computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end()); 487 488 b.create<CallOp>(computeFunc.func.sym_name(), 489 computeFunc.func.getCallableResults(), computeFuncOperands); 490 b.create<ReturnOp>(ValueRange()); 491 492 return func; 493 } 494 495 // Launch async dispatch of the parallel compute function. 496 static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 497 ParallelComputeFunction ¶llelComputeFunction, 498 scf::ParallelOp op, Value blockSize, 499 Value blockCount, 500 const SmallVector<Value> &tripCounts) { 501 MLIRContext *ctx = op->getContext(); 502 503 // Add one more level of indirection to dispatch parallel compute functions 504 // using async operations and recursive work splitting. 505 FuncOp asyncDispatchFunction = 506 createAsyncDispatchFunction(parallelComputeFunction, rewriter); 507 508 Value c0 = b.create<ConstantIndexOp>(0); 509 Value c1 = b.create<ConstantIndexOp>(1); 510 511 // Appends operands shared by async dispatch and parallel compute functions to 512 // the given operands vector. 513 auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) { 514 operands.append(tripCounts); 515 operands.append(op.lowerBound().begin(), op.lowerBound().end()); 516 operands.append(op.upperBound().begin(), op.upperBound().end()); 517 operands.append(op.step().begin(), op.step().end()); 518 operands.append(parallelComputeFunction.captures); 519 }; 520 521 // Check if the block size is one, in this case we can skip the async dispatch 522 // completely. If this will be known statically, then canonicalization will 523 // erase async group operations. 524 Value isSingleBlock = b.create<CmpIOp>(CmpIPredicate::eq, blockCount, c1); 525 526 auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 527 ImplicitLocOpBuilder nb(loc, nestedBuilder); 528 529 // Call parallel compute function for the single block. 530 SmallVector<Value> operands = {c0, blockSize}; 531 appendBlockComputeOperands(operands); 532 533 nb.create<CallOp>(parallelComputeFunction.func.sym_name(), 534 parallelComputeFunction.func.getCallableResults(), 535 operands); 536 nb.create<scf::YieldOp>(); 537 }; 538 539 auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 540 // Create an async.group to wait on all async tokens from the concurrent 541 // execution of multiple parallel compute function. First block will be 542 // executed synchronously in the caller thread. 543 Value groupSize = b.create<SubIOp>(blockCount, c1); 544 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 545 546 ImplicitLocOpBuilder nb(loc, nestedBuilder); 547 548 // Launch async dispatch function for [0, blockCount) range. 549 SmallVector<Value> operands = {group, c0, blockCount, blockSize}; 550 appendBlockComputeOperands(operands); 551 552 nb.create<CallOp>(asyncDispatchFunction.sym_name(), 553 asyncDispatchFunction.getCallableResults(), operands); 554 555 // Wait for the completion of all parallel compute operations. 556 b.create<AwaitAllOp>(group); 557 558 nb.create<scf::YieldOp>(); 559 }; 560 561 // Dispatch either single block compute function, or launch async dispatch. 562 b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch); 563 } 564 565 // Dispatch parallel compute functions by submitting all async compute tasks 566 // from a simple for loop in the caller thread. 567 static void 568 doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 569 ParallelComputeFunction ¶llelComputeFunction, 570 scf::ParallelOp op, Value blockSize, Value blockCount, 571 const SmallVector<Value> &tripCounts) { 572 MLIRContext *ctx = op->getContext(); 573 574 FuncOp compute = parallelComputeFunction.func; 575 576 Value c0 = b.create<ConstantIndexOp>(0); 577 Value c1 = b.create<ConstantIndexOp>(1); 578 579 // Create an async.group to wait on all async tokens from the concurrent 580 // execution of multiple parallel compute function. First block will be 581 // executed synchronously in the caller thread. 582 Value groupSize = b.create<SubIOp>(blockCount, c1); 583 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 584 585 // Call parallel compute function for all blocks. 586 using LoopBodyBuilder = 587 std::function<void(OpBuilder &, Location, Value, ValueRange)>; 588 589 // Returns parallel compute function operands to process the given block. 590 auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> { 591 SmallVector<Value> computeFuncOperands = {blockIndex, blockSize}; 592 computeFuncOperands.append(tripCounts); 593 computeFuncOperands.append(op.lowerBound().begin(), op.lowerBound().end()); 594 computeFuncOperands.append(op.upperBound().begin(), op.upperBound().end()); 595 computeFuncOperands.append(op.step().begin(), op.step().end()); 596 computeFuncOperands.append(parallelComputeFunction.captures); 597 return computeFuncOperands; 598 }; 599 600 // Induction variable is the index of the block: [0, blockCount). 601 LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc, 602 Value iv, ValueRange args) { 603 ImplicitLocOpBuilder nb(loc, loopBuilder); 604 605 // Call parallel compute function inside the async.execute region. 606 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 607 Location executeLoc, ValueRange executeArgs) { 608 executeBuilder.create<CallOp>(executeLoc, compute.sym_name(), 609 compute.getCallableResults(), 610 computeFuncOperands(iv)); 611 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 612 }; 613 614 // Create async.execute operation to launch parallel computate function. 615 auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 616 executeBodyBuilder); 617 nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group); 618 nb.create<scf::YieldOp>(); 619 }; 620 621 // Iterate over all compute blocks and launch parallel compute operations. 622 b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder); 623 624 // Call parallel compute function for the first block in the caller thread. 625 b.create<CallOp>(compute.sym_name(), compute.getCallableResults(), 626 computeFuncOperands(c0)); 627 628 // Wait for the completion of all async compute operations. 629 b.create<AwaitAllOp>(group); 630 } 631 632 LogicalResult 633 AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op, 634 PatternRewriter &rewriter) const { 635 // We do not currently support rewrite for parallel op with reductions. 636 if (op.getNumReductions() != 0) 637 return failure(); 638 639 ImplicitLocOpBuilder b(op.getLoc(), rewriter); 640 641 // Compute trip count for each loop induction variable: 642 // tripCount = ceil_div(upperBound - lowerBound, step); 643 SmallVector<Value> tripCounts(op.getNumLoops()); 644 for (size_t i = 0; i < op.getNumLoops(); ++i) { 645 auto lb = op.lowerBound()[i]; 646 auto ub = op.upperBound()[i]; 647 auto step = op.step()[i]; 648 auto range = b.create<SubIOp>(ub, lb); 649 tripCounts[i] = b.create<SignedCeilDivIOp>(range, step); 650 } 651 652 // Compute a product of trip counts to get the 1-dimensional iteration space 653 // for the scf.parallel operation. 654 Value tripCount = tripCounts[0]; 655 for (size_t i = 1; i < tripCounts.size(); ++i) 656 tripCount = b.create<MulIOp>(tripCount, tripCounts[i]); 657 658 // Short circuit no-op parallel loops (zero iterations) that can arise from 659 // the memrefs with dynamic dimension(s) equal to zero. 660 Value c0 = b.create<ConstantIndexOp>(0); 661 Value isZeroIterations = b.create<CmpIOp>(CmpIPredicate::eq, tripCount, c0); 662 663 // Do absolutely nothing if the trip count is zero. 664 auto noOp = [&](OpBuilder &nestedBuilder, Location loc) { 665 nestedBuilder.create<scf::YieldOp>(loc); 666 }; 667 668 // Compute the parallel block size and dispatch concurrent tasks computing 669 // results for each block. 670 auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) { 671 ImplicitLocOpBuilder nb(loc, nestedBuilder); 672 673 // With large number of threads the value of creating many compute blocks 674 // is reduced because the problem typically becomes memory bound. For small 675 // number of threads it helps with stragglers. 676 float overshardingFactor = numWorkerThreads <= 4 ? 8.0 677 : numWorkerThreads <= 8 ? 4.0 678 : numWorkerThreads <= 16 ? 2.0 679 : numWorkerThreads <= 32 ? 1.0 680 : numWorkerThreads <= 64 ? 0.8 681 : 0.6; 682 683 // Do not overload worker threads with too many compute blocks. 684 Value maxComputeBlocks = b.create<ConstantIndexOp>( 685 std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor))); 686 687 // Target block size from the pass parameters. 688 Value minTaskSizeCst = b.create<ConstantIndexOp>(minTaskSize); 689 690 // Compute parallel block size from the parallel problem size: 691 // blockSize = min(tripCount, 692 // max(ceil_div(tripCount, maxComputeBlocks), 693 // ceil_div(minTaskSize, bodySize))) 694 Value bs0 = b.create<SignedCeilDivIOp>(tripCount, maxComputeBlocks); 695 Value bs1 = b.create<CmpIOp>(CmpIPredicate::sge, bs0, minTaskSizeCst); 696 Value bs2 = b.create<SelectOp>(bs1, bs0, minTaskSizeCst); 697 Value bs3 = b.create<CmpIOp>(CmpIPredicate::sle, tripCount, bs2); 698 Value blockSize0 = b.create<SelectOp>(bs3, tripCount, bs2); 699 Value blockCount0 = b.create<SignedCeilDivIOp>(tripCount, blockSize0); 700 701 // Compute balanced block size for the estimated block count. 702 Value blockSize = b.create<SignedCeilDivIOp>(tripCount, blockCount0); 703 Value blockCount = b.create<SignedCeilDivIOp>(tripCount, blockSize); 704 705 // Create a parallel compute function that takes a block id and computes the 706 // parallel operation body for a subset of iteration space. 707 ParallelComputeFunction parallelComputeFunction = 708 createParallelComputeFunction(op, rewriter); 709 710 // Dispatch parallel compute function using async recursive work splitting, 711 // or by submitting compute task sequentially from a caller thread. 712 if (asyncDispatch) { 713 doAsyncDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 714 blockCount, tripCounts); 715 } else { 716 doSequentialDispatch(b, rewriter, parallelComputeFunction, op, blockSize, 717 blockCount, tripCounts); 718 } 719 720 nb.create<scf::YieldOp>(); 721 }; 722 723 // Replace the `scf.parallel` operation with the parallel compute function. 724 b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch); 725 726 // Parallel operation was replaced with a block iteration loop. 727 rewriter.eraseOp(op); 728 729 return success(); 730 } 731 732 void AsyncParallelForPass::runOnOperation() { 733 MLIRContext *ctx = &getContext(); 734 735 RewritePatternSet patterns(ctx); 736 patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads, 737 minTaskSize); 738 739 if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) 740 signalPassFailure(); 741 } 742 743 std::unique_ptr<Pass> mlir::createAsyncParallelForPass() { 744 return std::make_unique<AsyncParallelForPass>(); 745 } 746 747 std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch, 748 int32_t numWorkerThreads, 749 int32_t minTaskSize) { 750 return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads, 751 minTaskSize); 752 } 753