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/Arithmetic/IR/Arithmetic.h" 15 #include "mlir/Dialect/Async/IR/Async.h" 16 #include "mlir/Dialect/Async/Passes.h" 17 #include "mlir/Dialect/Async/Transforms.h" 18 #include "mlir/Dialect/SCF/SCF.h" 19 #include "mlir/Dialect/StandardOps/IR/Ops.h" 20 #include "mlir/IR/BlockAndValueMapping.h" 21 #include "mlir/IR/ImplicitLocOpBuilder.h" 22 #include "mlir/IR/Matchers.h" 23 #include "mlir/IR/PatternMatch.h" 24 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 25 #include "mlir/Transforms/RegionUtils.h" 26 27 using namespace mlir; 28 using namespace mlir::async; 29 30 #define DEBUG_TYPE "async-parallel-for" 31 32 namespace { 33 34 // Rewrite scf.parallel operation into multiple concurrent async.execute 35 // operations over non overlapping subranges of the original loop. 36 // 37 // Example: 38 // 39 // scf.parallel (%i, %j) = (%lbi, %lbj) to (%ubi, %ubj) step (%si, %sj) { 40 // "do_some_compute"(%i, %j): () -> () 41 // } 42 // 43 // Converted to: 44 // 45 // // Parallel compute function that executes the parallel body region for 46 // // a subset of the parallel iteration space defined by the one-dimensional 47 // // compute block index. 48 // func parallel_compute_function(%block_index : index, %block_size : index, 49 // <parallel operation properties>, ...) { 50 // // Compute multi-dimensional loop bounds for %block_index. 51 // %block_lbi, %block_lbj = ... 52 // %block_ubi, %block_ubj = ... 53 // 54 // // Clone parallel operation body into the scf.for loop nest. 55 // scf.for %i = %blockLbi to %blockUbi { 56 // scf.for %j = block_lbj to %block_ubj { 57 // "do_some_compute"(%i, %j): () -> () 58 // } 59 // } 60 // } 61 // 62 // And a dispatch function depending on the `asyncDispatch` option. 63 // 64 // When async dispatch is on: (pseudocode) 65 // 66 // %block_size = ... compute parallel compute block size 67 // %block_count = ... compute the number of compute blocks 68 // 69 // func @async_dispatch(%block_start : index, %block_end : index, ...) { 70 // // Keep splitting block range until we reached a range of size 1. 71 // while (%block_end - %block_start > 1) { 72 // %mid_index = block_start + (block_end - block_start) / 2; 73 // async.execute { call @async_dispatch(%mid_index, %block_end); } 74 // %block_end = %mid_index 75 // } 76 // 77 // // Call parallel compute function for a single block. 78 // call @parallel_compute_fn(%block_start, %block_size, ...); 79 // } 80 // 81 // // Launch async dispatch for [0, block_count) range. 82 // call @async_dispatch(%c0, %block_count); 83 // 84 // When async dispatch is off: 85 // 86 // %block_size = ... compute parallel compute block size 87 // %block_count = ... compute the number of compute blocks 88 // 89 // scf.for %block_index = %c0 to %block_count { 90 // call @parallel_compute_fn(%block_index, %block_size, ...) 91 // } 92 // 93 struct AsyncParallelForPass 94 : public AsyncParallelForBase<AsyncParallelForPass> { 95 AsyncParallelForPass() = default; 96 97 AsyncParallelForPass(bool asyncDispatch, int32_t numWorkerThreads, 98 int32_t minTaskSize) { 99 this->asyncDispatch = asyncDispatch; 100 this->numWorkerThreads = numWorkerThreads; 101 this->minTaskSize = minTaskSize; 102 } 103 104 void runOnOperation() override; 105 }; 106 107 struct AsyncParallelForRewrite : public OpRewritePattern<scf::ParallelOp> { 108 public: 109 AsyncParallelForRewrite( 110 MLIRContext *ctx, bool asyncDispatch, int32_t numWorkerThreads, 111 AsyncMinTaskSizeComputationFunction computeMinTaskSize) 112 : OpRewritePattern(ctx), asyncDispatch(asyncDispatch), 113 numWorkerThreads(numWorkerThreads), 114 computeMinTaskSize(computeMinTaskSize) {} 115 116 LogicalResult matchAndRewrite(scf::ParallelOp op, 117 PatternRewriter &rewriter) const override; 118 119 private: 120 bool asyncDispatch; 121 int32_t numWorkerThreads; 122 AsyncMinTaskSizeComputationFunction computeMinTaskSize; 123 }; 124 125 struct ParallelComputeFunctionType { 126 FunctionType type; 127 SmallVector<Value> captures; 128 }; 129 130 // Helper struct to parse parallel compute function argument list. 131 struct ParallelComputeFunctionArgs { 132 BlockArgument blockIndex(); 133 BlockArgument blockSize(); 134 ArrayRef<BlockArgument> tripCounts(); 135 ArrayRef<BlockArgument> lowerBounds(); 136 ArrayRef<BlockArgument> upperBounds(); 137 ArrayRef<BlockArgument> steps(); 138 ArrayRef<BlockArgument> captures(); 139 140 unsigned numLoops; 141 ArrayRef<BlockArgument> args; 142 }; 143 144 struct ParallelComputeFunctionBounds { 145 SmallVector<IntegerAttr> tripCounts; 146 SmallVector<IntegerAttr> lowerBounds; 147 SmallVector<IntegerAttr> upperBounds; 148 SmallVector<IntegerAttr> steps; 149 }; 150 151 struct ParallelComputeFunction { 152 unsigned numLoops; 153 FuncOp func; 154 llvm::SmallVector<Value> captures; 155 }; 156 157 } // namespace 158 159 BlockArgument ParallelComputeFunctionArgs::blockIndex() { return args[0]; } 160 BlockArgument ParallelComputeFunctionArgs::blockSize() { return args[1]; } 161 162 ArrayRef<BlockArgument> ParallelComputeFunctionArgs::tripCounts() { 163 return args.drop_front(2).take_front(numLoops); 164 } 165 166 ArrayRef<BlockArgument> ParallelComputeFunctionArgs::lowerBounds() { 167 return args.drop_front(2 + 1 * numLoops).take_front(numLoops); 168 } 169 170 ArrayRef<BlockArgument> ParallelComputeFunctionArgs::upperBounds() { 171 return args.drop_front(2 + 2 * numLoops).take_front(numLoops); 172 } 173 174 ArrayRef<BlockArgument> ParallelComputeFunctionArgs::steps() { 175 return args.drop_front(2 + 3 * numLoops).take_front(numLoops); 176 } 177 178 ArrayRef<BlockArgument> ParallelComputeFunctionArgs::captures() { 179 return args.drop_front(2 + 4 * numLoops); 180 } 181 182 template <typename ValueRange> 183 static SmallVector<IntegerAttr> integerConstants(ValueRange values) { 184 SmallVector<IntegerAttr> attrs(values.size()); 185 for (unsigned i = 0; i < values.size(); ++i) 186 matchPattern(values[i], m_Constant(&attrs[i])); 187 return attrs; 188 } 189 190 // Converts one-dimensional iteration index in the [0, tripCount) interval 191 // into multidimensional iteration coordinate. 192 static SmallVector<Value> delinearize(ImplicitLocOpBuilder &b, Value index, 193 ArrayRef<Value> tripCounts) { 194 SmallVector<Value> coords(tripCounts.size()); 195 assert(!tripCounts.empty() && "tripCounts must be not empty"); 196 197 for (ssize_t i = tripCounts.size() - 1; i >= 0; --i) { 198 coords[i] = b.create<arith::RemSIOp>(index, tripCounts[i]); 199 index = b.create<arith::DivSIOp>(index, tripCounts[i]); 200 } 201 202 return coords; 203 } 204 205 // Returns a function type and implicit captures for a parallel compute 206 // function. We'll need a list of implicit captures to setup block and value 207 // mapping when we'll clone the body of the parallel operation. 208 static ParallelComputeFunctionType 209 getParallelComputeFunctionType(scf::ParallelOp op, PatternRewriter &rewriter) { 210 // Values implicitly captured by the parallel operation. 211 llvm::SetVector<Value> captures; 212 getUsedValuesDefinedAbove(op.getRegion(), op.getRegion(), captures); 213 214 SmallVector<Type> inputs; 215 inputs.reserve(2 + 4 * op.getNumLoops() + captures.size()); 216 217 Type indexTy = rewriter.getIndexType(); 218 219 // One-dimensional iteration space defined by the block index and size. 220 inputs.push_back(indexTy); // blockIndex 221 inputs.push_back(indexTy); // blockSize 222 223 // Multi-dimensional parallel iteration space defined by the loop trip counts. 224 for (unsigned i = 0; i < op.getNumLoops(); ++i) 225 inputs.push_back(indexTy); // loop tripCount 226 227 // Parallel operation lower bound, upper bound and step. Lower bound, upper 228 // bound and step passed as contiguous arguments: 229 // call @compute(%lb0, %lb1, ..., %ub0, %ub1, ..., %step0, %step1, ...) 230 for (unsigned i = 0; i < op.getNumLoops(); ++i) { 231 inputs.push_back(indexTy); // lower bound 232 inputs.push_back(indexTy); // upper bound 233 inputs.push_back(indexTy); // step 234 } 235 236 // Types of the implicit captures. 237 for (Value capture : captures) 238 inputs.push_back(capture.getType()); 239 240 // Convert captures to vector for later convenience. 241 SmallVector<Value> capturesVector(captures.begin(), captures.end()); 242 return {rewriter.getFunctionType(inputs, TypeRange()), capturesVector}; 243 } 244 245 // Create a parallel compute fuction from the parallel operation. 246 static ParallelComputeFunction createParallelComputeFunction( 247 scf::ParallelOp op, ParallelComputeFunctionBounds bounds, 248 unsigned numBlockAlignedInnerLoops, PatternRewriter &rewriter) { 249 OpBuilder::InsertionGuard guard(rewriter); 250 ImplicitLocOpBuilder b(op.getLoc(), rewriter); 251 252 ModuleOp module = op->getParentOfType<ModuleOp>(); 253 254 ParallelComputeFunctionType computeFuncType = 255 getParallelComputeFunctionType(op, rewriter); 256 257 FunctionType type = computeFuncType.type; 258 FuncOp func = FuncOp::create(op.getLoc(), 259 numBlockAlignedInnerLoops > 0 260 ? "parallel_compute_fn_with_aligned_loops" 261 : "parallel_compute_fn", 262 type); 263 func.setPrivate(); 264 265 // Insert function into the module symbol table and assign it unique name. 266 SymbolTable symbolTable(module); 267 symbolTable.insert(func); 268 rewriter.getListener()->notifyOperationInserted(func); 269 270 // Create function entry block. 271 Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 272 b.setInsertionPointToEnd(block); 273 274 ParallelComputeFunctionArgs args = {op.getNumLoops(), func.getArguments()}; 275 276 // Block iteration position defined by the block index and size. 277 BlockArgument blockIndex = args.blockIndex(); 278 BlockArgument blockSize = args.blockSize(); 279 280 // Constants used below. 281 Value c0 = b.create<arith::ConstantIndexOp>(0); 282 Value c1 = b.create<arith::ConstantIndexOp>(1); 283 284 // Materialize known constants as constant operation in the function body. 285 auto values = [&](ArrayRef<BlockArgument> args, ArrayRef<IntegerAttr> attrs) { 286 return llvm::to_vector( 287 llvm::map_range(llvm::zip(args, attrs), [&](auto tuple) -> Value { 288 if (IntegerAttr attr = std::get<1>(tuple)) 289 return b.create<ConstantOp>(attr); 290 return std::get<0>(tuple); 291 })); 292 }; 293 294 // Multi-dimensional parallel iteration space defined by the loop trip counts. 295 auto tripCounts = values(args.tripCounts(), bounds.tripCounts); 296 297 // Parallel operation lower bound and step. 298 auto lowerBounds = values(args.lowerBounds(), bounds.lowerBounds); 299 auto steps = values(args.steps(), bounds.steps); 300 301 // Remaining arguments are implicit captures of the parallel operation. 302 ArrayRef<BlockArgument> captures = args.captures(); 303 304 // Compute a product of trip counts to get the size of the flattened 305 // one-dimensional iteration space. 306 Value tripCount = tripCounts[0]; 307 for (unsigned i = 1; i < tripCounts.size(); ++i) 308 tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 309 310 // Find one-dimensional iteration bounds: [blockFirstIndex, blockLastIndex]: 311 // blockFirstIndex = blockIndex * blockSize 312 Value blockFirstIndex = b.create<arith::MulIOp>(blockIndex, blockSize); 313 314 // The last one-dimensional index in the block defined by the `blockIndex`: 315 // blockLastIndex = min(blockFirstIndex + blockSize, tripCount) - 1 316 Value blockEnd0 = b.create<arith::AddIOp>(blockFirstIndex, blockSize); 317 Value blockEnd1 = b.create<arith::MinSIOp>(blockEnd0, tripCount); 318 Value blockLastIndex = b.create<arith::SubIOp>(blockEnd1, c1); 319 320 // Convert one-dimensional indices to multi-dimensional coordinates. 321 auto blockFirstCoord = delinearize(b, blockFirstIndex, tripCounts); 322 auto blockLastCoord = delinearize(b, blockLastIndex, tripCounts); 323 324 // Compute loops upper bounds derived from the block last coordinates: 325 // blockEndCoord[i] = blockLastCoord[i] + 1 326 // 327 // Block first and last coordinates can be the same along the outer compute 328 // dimension when inner compute dimension contains multiple blocks. 329 SmallVector<Value> blockEndCoord(op.getNumLoops()); 330 for (size_t i = 0; i < blockLastCoord.size(); ++i) 331 blockEndCoord[i] = b.create<arith::AddIOp>(blockLastCoord[i], c1); 332 333 // Construct a loop nest out of scf.for operations that will iterate over 334 // all coordinates in [blockFirstCoord, blockLastCoord] range. 335 using LoopBodyBuilder = 336 std::function<void(OpBuilder &, Location, Value, ValueRange)>; 337 using LoopNestBuilder = std::function<LoopBodyBuilder(size_t loopIdx)>; 338 339 // Parallel region induction variables computed from the multi-dimensional 340 // iteration coordinate using parallel operation bounds and step: 341 // 342 // computeBlockInductionVars[loopIdx] = 343 // lowerBound[loopIdx] + blockCoord[loopIdx] * step[loopIdx] 344 SmallVector<Value> computeBlockInductionVars(op.getNumLoops()); 345 346 // We need to know if we are in the first or last iteration of the 347 // multi-dimensional loop for each loop in the nest, so we can decide what 348 // loop bounds should we use for the nested loops: bounds defined by compute 349 // block interval, or bounds defined by the parallel operation. 350 // 351 // Example: 2d parallel operation 352 // i j 353 // loop sizes: [50, 50] 354 // first coord: [25, 25] 355 // last coord: [30, 30] 356 // 357 // If `i` is equal to 25 then iteration over `j` should start at 25, when `i` 358 // is between 25 and 30 it should start at 0. The upper bound for `j` should 359 // be 50, except when `i` is equal to 30, then it should also be 30. 360 // 361 // Value at ith position specifies if all loops in [0, i) range of the loop 362 // nest are in the first/last iteration. 363 SmallVector<Value> isBlockFirstCoord(op.getNumLoops()); 364 SmallVector<Value> isBlockLastCoord(op.getNumLoops()); 365 366 // Builds inner loop nest inside async.execute operation that does all the 367 // work concurrently. 368 LoopNestBuilder workLoopBuilder = [&](size_t loopIdx) -> LoopBodyBuilder { 369 return [&, loopIdx](OpBuilder &nestedBuilder, Location loc, Value iv, 370 ValueRange args) { 371 ImplicitLocOpBuilder nb(loc, nestedBuilder); 372 373 // Compute induction variable for `loopIdx`. 374 computeBlockInductionVars[loopIdx] = nb.create<arith::AddIOp>( 375 lowerBounds[loopIdx], nb.create<arith::MulIOp>(iv, steps[loopIdx])); 376 377 // Check if we are inside first or last iteration of the loop. 378 isBlockFirstCoord[loopIdx] = nb.create<arith::CmpIOp>( 379 arith::CmpIPredicate::eq, iv, blockFirstCoord[loopIdx]); 380 isBlockLastCoord[loopIdx] = nb.create<arith::CmpIOp>( 381 arith::CmpIPredicate::eq, iv, blockLastCoord[loopIdx]); 382 383 // Check if the previous loop is in its first or last iteration. 384 if (loopIdx > 0) { 385 isBlockFirstCoord[loopIdx] = nb.create<arith::AndIOp>( 386 isBlockFirstCoord[loopIdx], isBlockFirstCoord[loopIdx - 1]); 387 isBlockLastCoord[loopIdx] = nb.create<arith::AndIOp>( 388 isBlockLastCoord[loopIdx], isBlockLastCoord[loopIdx - 1]); 389 } 390 391 // Keep building loop nest. 392 if (loopIdx < op.getNumLoops() - 1) { 393 if (loopIdx + 1 >= op.getNumLoops() - numBlockAlignedInnerLoops) { 394 // For block aligned loops we always iterate starting from 0 up to 395 // the loop trip counts. 396 nb.create<scf::ForOp>(c0, tripCounts[loopIdx + 1], c1, ValueRange(), 397 workLoopBuilder(loopIdx + 1)); 398 399 } else { 400 // Select nested loop lower/upper bounds depending on our position in 401 // the multi-dimensional iteration space. 402 auto lb = nb.create<SelectOp>(isBlockFirstCoord[loopIdx], 403 blockFirstCoord[loopIdx + 1], c0); 404 405 auto ub = nb.create<SelectOp>(isBlockLastCoord[loopIdx], 406 blockEndCoord[loopIdx + 1], 407 tripCounts[loopIdx + 1]); 408 409 nb.create<scf::ForOp>(lb, ub, c1, ValueRange(), 410 workLoopBuilder(loopIdx + 1)); 411 } 412 413 nb.create<scf::YieldOp>(loc); 414 return; 415 } 416 417 // Copy the body of the parallel op into the inner-most loop. 418 BlockAndValueMapping mapping; 419 mapping.map(op.getInductionVars(), computeBlockInductionVars); 420 mapping.map(computeFuncType.captures, captures); 421 422 for (auto &bodyOp : op.getLoopBody().getOps()) 423 nb.clone(bodyOp, mapping); 424 }; 425 }; 426 427 b.create<scf::ForOp>(blockFirstCoord[0], blockEndCoord[0], c1, ValueRange(), 428 workLoopBuilder(0)); 429 b.create<ReturnOp>(ValueRange()); 430 431 return {op.getNumLoops(), func, std::move(computeFuncType.captures)}; 432 } 433 434 // Creates recursive async dispatch function for the given parallel compute 435 // function. Dispatch function keeps splitting block range into halves until it 436 // reaches a single block, and then excecutes it inline. 437 // 438 // Function pseudocode (mix of C++ and MLIR): 439 // 440 // func @async_dispatch(%block_start : index, %block_end : index, ...) { 441 // 442 // // Keep splitting block range until we reached a range of size 1. 443 // while (%block_end - %block_start > 1) { 444 // %mid_index = block_start + (block_end - block_start) / 2; 445 // async.execute { call @async_dispatch(%mid_index, %block_end); } 446 // %block_end = %mid_index 447 // } 448 // 449 // // Call parallel compute function for a single block. 450 // call @parallel_compute_fn(%block_start, %block_size, ...); 451 // } 452 // 453 static FuncOp createAsyncDispatchFunction(ParallelComputeFunction &computeFunc, 454 PatternRewriter &rewriter) { 455 OpBuilder::InsertionGuard guard(rewriter); 456 Location loc = computeFunc.func.getLoc(); 457 ImplicitLocOpBuilder b(loc, rewriter); 458 459 ModuleOp module = computeFunc.func->getParentOfType<ModuleOp>(); 460 461 ArrayRef<Type> computeFuncInputTypes = 462 computeFunc.func.type().cast<FunctionType>().getInputs(); 463 464 // Compared to the parallel compute function async dispatch function takes 465 // additional !async.group argument. Also instead of a single `blockIndex` it 466 // takes `blockStart` and `blockEnd` arguments to define the range of 467 // dispatched blocks. 468 SmallVector<Type> inputTypes; 469 inputTypes.push_back(async::GroupType::get(rewriter.getContext())); 470 inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument 471 inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end()); 472 473 FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange()); 474 FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type); 475 func.setPrivate(); 476 477 // Insert function into the module symbol table and assign it unique name. 478 SymbolTable symbolTable(module); 479 symbolTable.insert(func); 480 rewriter.getListener()->notifyOperationInserted(func); 481 482 // Create function entry block. 483 Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs()); 484 b.setInsertionPointToEnd(block); 485 486 Type indexTy = b.getIndexType(); 487 Value c1 = b.create<arith::ConstantIndexOp>(1); 488 Value c2 = b.create<arith::ConstantIndexOp>(2); 489 490 // Get the async group that will track async dispatch completion. 491 Value group = block->getArgument(0); 492 493 // Get the block iteration range: [blockStart, blockEnd) 494 Value blockStart = block->getArgument(1); 495 Value blockEnd = block->getArgument(2); 496 497 // Create a work splitting while loop for the [blockStart, blockEnd) range. 498 SmallVector<Type> types = {indexTy, indexTy}; 499 SmallVector<Value> operands = {blockStart, blockEnd}; 500 501 // Create a recursive dispatch loop. 502 scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands); 503 Block *before = b.createBlock(&whileOp.getBefore(), {}, types); 504 Block *after = b.createBlock(&whileOp.getAfter(), {}, types); 505 506 // Setup dispatch loop condition block: decide if we need to go into the 507 // `after` block and launch one more async dispatch. 508 { 509 b.setInsertionPointToEnd(before); 510 Value start = before->getArgument(0); 511 Value end = before->getArgument(1); 512 Value distance = b.create<arith::SubIOp>(end, start); 513 Value dispatch = 514 b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, distance, c1); 515 b.create<scf::ConditionOp>(dispatch, before->getArguments()); 516 } 517 518 // Setup the async dispatch loop body: recursively call dispatch function 519 // for the seconds half of the original range and go to the next iteration. 520 { 521 b.setInsertionPointToEnd(after); 522 Value start = after->getArgument(0); 523 Value end = after->getArgument(1); 524 Value distance = b.create<arith::SubIOp>(end, start); 525 Value halfDistance = b.create<arith::DivSIOp>(distance, c2); 526 Value midIndex = b.create<arith::AddIOp>(start, halfDistance); 527 528 // Call parallel compute function inside the async.execute region. 529 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 530 Location executeLoc, ValueRange executeArgs) { 531 // Update the original `blockStart` and `blockEnd` with new range. 532 SmallVector<Value> operands{block->getArguments().begin(), 533 block->getArguments().end()}; 534 operands[1] = midIndex; 535 operands[2] = end; 536 537 executeBuilder.create<CallOp>(executeLoc, func.sym_name(), 538 func.getCallableResults(), operands); 539 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 540 }; 541 542 // Create async.execute operation to dispatch half of the block range. 543 auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 544 executeBodyBuilder); 545 b.create<AddToGroupOp>(indexTy, execute.token(), group); 546 b.create<scf::YieldOp>(ValueRange({start, midIndex})); 547 } 548 549 // After dispatching async operations to process the tail of the block range 550 // call the parallel compute function for the first block of the range. 551 b.setInsertionPointAfter(whileOp); 552 553 // Drop async dispatch specific arguments: async group, block start and end. 554 auto forwardedInputs = block->getArguments().drop_front(3); 555 SmallVector<Value> computeFuncOperands = {blockStart}; 556 computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end()); 557 558 b.create<CallOp>(computeFunc.func.sym_name(), 559 computeFunc.func.getCallableResults(), computeFuncOperands); 560 b.create<ReturnOp>(ValueRange()); 561 562 return func; 563 } 564 565 // Launch async dispatch of the parallel compute function. 566 static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 567 ParallelComputeFunction ¶llelComputeFunction, 568 scf::ParallelOp op, Value blockSize, 569 Value blockCount, 570 const SmallVector<Value> &tripCounts) { 571 MLIRContext *ctx = op->getContext(); 572 573 // Add one more level of indirection to dispatch parallel compute functions 574 // using async operations and recursive work splitting. 575 FuncOp asyncDispatchFunction = 576 createAsyncDispatchFunction(parallelComputeFunction, rewriter); 577 578 Value c0 = b.create<arith::ConstantIndexOp>(0); 579 Value c1 = b.create<arith::ConstantIndexOp>(1); 580 581 // Appends operands shared by async dispatch and parallel compute functions to 582 // the given operands vector. 583 auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) { 584 operands.append(tripCounts); 585 operands.append(op.getLowerBound().begin(), op.getLowerBound().end()); 586 operands.append(op.getUpperBound().begin(), op.getUpperBound().end()); 587 operands.append(op.getStep().begin(), op.getStep().end()); 588 operands.append(parallelComputeFunction.captures); 589 }; 590 591 // Check if the block size is one, in this case we can skip the async dispatch 592 // completely. If this will be known statically, then canonicalization will 593 // erase async group operations. 594 Value isSingleBlock = 595 b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1); 596 597 auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 598 ImplicitLocOpBuilder nb(loc, nestedBuilder); 599 600 // Call parallel compute function for the single block. 601 SmallVector<Value> operands = {c0, blockSize}; 602 appendBlockComputeOperands(operands); 603 604 nb.create<CallOp>(parallelComputeFunction.func.sym_name(), 605 parallelComputeFunction.func.getCallableResults(), 606 operands); 607 nb.create<scf::YieldOp>(); 608 }; 609 610 auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 611 // Create an async.group to wait on all async tokens from the concurrent 612 // execution of multiple parallel compute function. First block will be 613 // executed synchronously in the caller thread. 614 Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 615 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 616 617 ImplicitLocOpBuilder nb(loc, nestedBuilder); 618 619 // Launch async dispatch function for [0, blockCount) range. 620 SmallVector<Value> operands = {group, c0, blockCount, blockSize}; 621 appendBlockComputeOperands(operands); 622 623 nb.create<CallOp>(asyncDispatchFunction.sym_name(), 624 asyncDispatchFunction.getCallableResults(), operands); 625 626 // Wait for the completion of all parallel compute operations. 627 b.create<AwaitAllOp>(group); 628 629 nb.create<scf::YieldOp>(); 630 }; 631 632 // Dispatch either single block compute function, or launch async dispatch. 633 b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch); 634 } 635 636 // Dispatch parallel compute functions by submitting all async compute tasks 637 // from a simple for loop in the caller thread. 638 static void 639 doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 640 ParallelComputeFunction ¶llelComputeFunction, 641 scf::ParallelOp op, Value blockSize, Value blockCount, 642 const SmallVector<Value> &tripCounts) { 643 MLIRContext *ctx = op->getContext(); 644 645 FuncOp compute = parallelComputeFunction.func; 646 647 Value c0 = b.create<arith::ConstantIndexOp>(0); 648 Value c1 = b.create<arith::ConstantIndexOp>(1); 649 650 // Create an async.group to wait on all async tokens from the concurrent 651 // execution of multiple parallel compute function. First block will be 652 // executed synchronously in the caller thread. 653 Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 654 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 655 656 // Call parallel compute function for all blocks. 657 using LoopBodyBuilder = 658 std::function<void(OpBuilder &, Location, Value, ValueRange)>; 659 660 // Returns parallel compute function operands to process the given block. 661 auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> { 662 SmallVector<Value> computeFuncOperands = {blockIndex, blockSize}; 663 computeFuncOperands.append(tripCounts); 664 computeFuncOperands.append(op.getLowerBound().begin(), 665 op.getLowerBound().end()); 666 computeFuncOperands.append(op.getUpperBound().begin(), 667 op.getUpperBound().end()); 668 computeFuncOperands.append(op.getStep().begin(), op.getStep().end()); 669 computeFuncOperands.append(parallelComputeFunction.captures); 670 return computeFuncOperands; 671 }; 672 673 // Induction variable is the index of the block: [0, blockCount). 674 LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc, 675 Value iv, ValueRange args) { 676 ImplicitLocOpBuilder nb(loc, loopBuilder); 677 678 // Call parallel compute function inside the async.execute region. 679 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 680 Location executeLoc, ValueRange executeArgs) { 681 executeBuilder.create<CallOp>(executeLoc, compute.sym_name(), 682 compute.getCallableResults(), 683 computeFuncOperands(iv)); 684 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 685 }; 686 687 // Create async.execute operation to launch parallel computate function. 688 auto execute = nb.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 689 executeBodyBuilder); 690 nb.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group); 691 nb.create<scf::YieldOp>(); 692 }; 693 694 // Iterate over all compute blocks and launch parallel compute operations. 695 b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder); 696 697 // Call parallel compute function for the first block in the caller thread. 698 b.create<CallOp>(compute.sym_name(), compute.getCallableResults(), 699 computeFuncOperands(c0)); 700 701 // Wait for the completion of all async compute operations. 702 b.create<AwaitAllOp>(group); 703 } 704 705 LogicalResult 706 AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op, 707 PatternRewriter &rewriter) const { 708 // We do not currently support rewrite for parallel op with reductions. 709 if (op.getNumReductions() != 0) 710 return failure(); 711 712 ImplicitLocOpBuilder b(op.getLoc(), rewriter); 713 714 // Computing minTaskSize emits IR and can be implemented as executing a cost 715 // model on the body of the scf.parallel. Thus it needs to be computed before 716 // the body of the scf.parallel has been manipulated. 717 Value minTaskSize = computeMinTaskSize(b, op); 718 719 // Make sure that all constants will be inside the parallel operation body to 720 // reduce the number of parallel compute function arguments. 721 cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter); 722 723 // Compute trip count for each loop induction variable: 724 // tripCount = ceil_div(upperBound - lowerBound, step); 725 SmallVector<Value> tripCounts(op.getNumLoops()); 726 for (size_t i = 0; i < op.getNumLoops(); ++i) { 727 auto lb = op.getLowerBound()[i]; 728 auto ub = op.getUpperBound()[i]; 729 auto step = op.getStep()[i]; 730 auto range = b.createOrFold<arith::SubIOp>(ub, lb); 731 tripCounts[i] = b.createOrFold<arith::CeilDivSIOp>(range, step); 732 } 733 734 // Compute a product of trip counts to get the 1-dimensional iteration space 735 // for the scf.parallel operation. 736 Value tripCount = tripCounts[0]; 737 for (size_t i = 1; i < tripCounts.size(); ++i) 738 tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 739 740 // Short circuit no-op parallel loops (zero iterations) that can arise from 741 // the memrefs with dynamic dimension(s) equal to zero. 742 Value c0 = b.create<arith::ConstantIndexOp>(0); 743 Value isZeroIterations = 744 b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0); 745 746 // Do absolutely nothing if the trip count is zero. 747 auto noOp = [&](OpBuilder &nestedBuilder, Location loc) { 748 nestedBuilder.create<scf::YieldOp>(loc); 749 }; 750 751 // Compute the parallel block size and dispatch concurrent tasks computing 752 // results for each block. 753 auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) { 754 ImplicitLocOpBuilder nb(loc, nestedBuilder); 755 756 // Collect statically known constants defining the loop nest in the parallel 757 // compute function. LLVM can't always push constants across the non-trivial 758 // async dispatch call graph, by providing these values explicitly we can 759 // choose to build more efficient loop nest, and rely on a better constant 760 // folding, loop unrolling and vectorization. 761 ParallelComputeFunctionBounds staticBounds = { 762 integerConstants(tripCounts), 763 integerConstants(op.getLowerBound()), 764 integerConstants(op.getUpperBound()), 765 integerConstants(op.getStep()), 766 }; 767 768 // Find how many inner iteration dimensions are statically known, and their 769 // product is smaller than the `512`. We align the parallel compute block 770 // size by the product of statically known dimensions, so that we can 771 // guarantee that the inner loops executes from 0 to the loop trip counts 772 // and we can elide dynamic loop boundaries, and give LLVM an opportunity to 773 // unroll the loops. The constant `512` is arbitrary, it should depend on 774 // how many iterations LLVM will typically decide to unroll. 775 static constexpr int64_t maxIterations = 512; 776 777 // The number of inner loops with statically known number of iterations less 778 // than the `maxIterations` value. 779 int numUnrollableLoops = 0; 780 781 auto getInt = [](IntegerAttr attr) { return attr ? attr.getInt() : 0; }; 782 783 SmallVector<int64_t> numIterations(op.getNumLoops()); 784 numIterations.back() = getInt(staticBounds.tripCounts.back()); 785 786 for (int i = op.getNumLoops() - 2; i >= 0; --i) { 787 int64_t tripCount = getInt(staticBounds.tripCounts[i]); 788 int64_t innerIterations = numIterations[i + 1]; 789 numIterations[i] = tripCount * innerIterations; 790 791 // Update the number of inner loops that we can potentially unroll. 792 if (innerIterations > 0 && innerIterations <= maxIterations) 793 numUnrollableLoops++; 794 } 795 796 // With large number of threads the value of creating many compute blocks 797 // is reduced because the problem typically becomes memory bound. For small 798 // number of threads it helps with stragglers. 799 float overshardingFactor = numWorkerThreads <= 4 ? 8.0 800 : numWorkerThreads <= 8 ? 4.0 801 : numWorkerThreads <= 16 ? 2.0 802 : numWorkerThreads <= 32 ? 1.0 803 : numWorkerThreads <= 64 ? 0.8 804 : 0.6; 805 806 // Do not overload worker threads with too many compute blocks. 807 Value maxComputeBlocks = b.create<arith::ConstantIndexOp>( 808 std::max(1, static_cast<int>(numWorkerThreads * overshardingFactor))); 809 810 // Compute parallel block size from the parallel problem size: 811 // blockSize = min(tripCount, 812 // max(ceil_div(tripCount, maxComputeBlocks), 813 // minTaskSize)) 814 Value bs0 = b.create<arith::CeilDivSIOp>(tripCount, maxComputeBlocks); 815 Value bs1 = b.create<arith::MaxSIOp>(bs0, minTaskSize); 816 Value blockSize = b.create<arith::MinSIOp>(tripCount, bs1); 817 818 ParallelComputeFunction notUnrollableParallelComputeFunction = 819 createParallelComputeFunction(op, staticBounds, 0, rewriter); 820 821 // Dispatch parallel compute function using async recursive work splitting, 822 // or by submitting compute task sequentially from a caller thread. 823 auto doDispatch = asyncDispatch ? doAsyncDispatch : doSequentialDispatch; 824 825 // Create a parallel compute function that takes a block id and computes 826 // the parallel operation body for a subset of iteration space. 827 828 // Compute the number of parallel compute blocks. 829 Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize); 830 831 // Unroll when numUnrollableLoops > 0 && blockSize >= maxIterations. 832 bool staticShouldUnroll = numUnrollableLoops > 0; 833 auto dispatchNotUnrollable = [&](OpBuilder &nestedBuilder, Location loc) { 834 ImplicitLocOpBuilder nb(loc, nestedBuilder); 835 doDispatch(b, rewriter, notUnrollableParallelComputeFunction, op, 836 blockSize, blockCount, tripCounts); 837 nb.create<scf::YieldOp>(); 838 }; 839 840 if (staticShouldUnroll) { 841 Value dynamicShouldUnroll = b.create<arith::CmpIOp>( 842 arith::CmpIPredicate::sge, blockSize, 843 b.create<arith::ConstantIndexOp>(maxIterations)); 844 845 ParallelComputeFunction unrollableParallelComputeFunction = 846 createParallelComputeFunction(op, staticBounds, numUnrollableLoops, 847 rewriter); 848 849 auto dispatchUnrollable = [&](OpBuilder &nestedBuilder, Location loc) { 850 ImplicitLocOpBuilder nb(loc, nestedBuilder); 851 // Align the block size to be a multiple of the statically known 852 // number of iterations in the inner loops. 853 Value numIters = nb.create<arith::ConstantIndexOp>( 854 numIterations[op.getNumLoops() - numUnrollableLoops]); 855 Value alignedBlockSize = nb.create<arith::MulIOp>( 856 nb.create<arith::CeilDivSIOp>(blockSize, numIters), numIters); 857 doDispatch(b, rewriter, unrollableParallelComputeFunction, op, 858 alignedBlockSize, blockCount, tripCounts); 859 nb.create<scf::YieldOp>(); 860 }; 861 862 b.create<scf::IfOp>(TypeRange(), dynamicShouldUnroll, dispatchUnrollable, 863 dispatchNotUnrollable); 864 nb.create<scf::YieldOp>(); 865 } else { 866 dispatchNotUnrollable(nb, loc); 867 } 868 }; 869 870 // Replace the `scf.parallel` operation with the parallel compute function. 871 b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch); 872 873 // Parallel operation was replaced with a block iteration loop. 874 rewriter.eraseOp(op); 875 876 return success(); 877 } 878 879 void AsyncParallelForPass::runOnOperation() { 880 MLIRContext *ctx = &getContext(); 881 882 RewritePatternSet patterns(ctx); 883 populateAsyncParallelForPatterns( 884 patterns, asyncDispatch, numWorkerThreads, 885 [&](ImplicitLocOpBuilder builder, scf::ParallelOp op) { 886 return builder.create<arith::ConstantIndexOp>(minTaskSize); 887 }); 888 if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) 889 signalPassFailure(); 890 } 891 892 std::unique_ptr<Pass> mlir::createAsyncParallelForPass() { 893 return std::make_unique<AsyncParallelForPass>(); 894 } 895 896 std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch, 897 int32_t numWorkerThreads, 898 int32_t minTaskSize) { 899 return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads, 900 minTaskSize); 901 } 902 903 void mlir::async::populateAsyncParallelForPatterns( 904 RewritePatternSet &patterns, bool asyncDispatch, int32_t numWorkerThreads, 905 AsyncMinTaskSizeComputationFunction computeMinTaskSize) { 906 MLIRContext *ctx = patterns.getContext(); 907 patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads, 908 computeMinTaskSize); 909 } 910