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