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 = 467 computeFunc.func.getFunctionType().getInputs(); 468 469 // Compared to the parallel compute function async dispatch function takes 470 // additional !async.group argument. Also instead of a single `blockIndex` it 471 // takes `blockStart` and `blockEnd` arguments to define the range of 472 // dispatched blocks. 473 SmallVector<Type> inputTypes; 474 inputTypes.push_back(async::GroupType::get(rewriter.getContext())); 475 inputTypes.push_back(rewriter.getIndexType()); // add blockStart argument 476 inputTypes.append(computeFuncInputTypes.begin(), computeFuncInputTypes.end()); 477 478 FunctionType type = rewriter.getFunctionType(inputTypes, TypeRange()); 479 FuncOp func = FuncOp::create(loc, "async_dispatch_fn", type); 480 func.setPrivate(); 481 482 // Insert function into the module symbol table and assign it unique name. 483 SymbolTable symbolTable(module); 484 symbolTable.insert(func); 485 rewriter.getListener()->notifyOperationInserted(func); 486 487 // Create function entry block. 488 Block *block = b.createBlock(&func.getBody(), func.begin(), type.getInputs(), 489 SmallVector<Location>(type.getNumInputs(), loc)); 490 b.setInsertionPointToEnd(block); 491 492 Type indexTy = b.getIndexType(); 493 Value c1 = b.create<arith::ConstantIndexOp>(1); 494 Value c2 = b.create<arith::ConstantIndexOp>(2); 495 496 // Get the async group that will track async dispatch completion. 497 Value group = block->getArgument(0); 498 499 // Get the block iteration range: [blockStart, blockEnd) 500 Value blockStart = block->getArgument(1); 501 Value blockEnd = block->getArgument(2); 502 503 // Create a work splitting while loop for the [blockStart, blockEnd) range. 504 SmallVector<Type> types = {indexTy, indexTy}; 505 SmallVector<Value> operands = {blockStart, blockEnd}; 506 SmallVector<Location> locations = {loc, loc}; 507 508 // Create a recursive dispatch loop. 509 scf::WhileOp whileOp = b.create<scf::WhileOp>(types, operands); 510 Block *before = b.createBlock(&whileOp.getBefore(), {}, types, locations); 511 Block *after = b.createBlock(&whileOp.getAfter(), {}, types, locations); 512 513 // Setup dispatch loop condition block: decide if we need to go into the 514 // `after` block and launch one more async dispatch. 515 { 516 b.setInsertionPointToEnd(before); 517 Value start = before->getArgument(0); 518 Value end = before->getArgument(1); 519 Value distance = b.create<arith::SubIOp>(end, start); 520 Value dispatch = 521 b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, distance, c1); 522 b.create<scf::ConditionOp>(dispatch, before->getArguments()); 523 } 524 525 // Setup the async dispatch loop body: recursively call dispatch function 526 // for the seconds half of the original range and go to the next iteration. 527 { 528 b.setInsertionPointToEnd(after); 529 Value start = after->getArgument(0); 530 Value end = after->getArgument(1); 531 Value distance = b.create<arith::SubIOp>(end, start); 532 Value halfDistance = b.create<arith::DivSIOp>(distance, c2); 533 Value midIndex = b.create<arith::AddIOp>(start, halfDistance); 534 535 // Call parallel compute function inside the async.execute region. 536 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 537 Location executeLoc, ValueRange executeArgs) { 538 // Update the original `blockStart` and `blockEnd` with new range. 539 SmallVector<Value> operands{block->getArguments().begin(), 540 block->getArguments().end()}; 541 operands[1] = midIndex; 542 operands[2] = end; 543 544 executeBuilder.create<func::CallOp>(executeLoc, func.getSymName(), 545 func.getCallableResults(), operands); 546 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 547 }; 548 549 // Create async.execute operation to dispatch half of the block range. 550 auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 551 executeBodyBuilder); 552 b.create<AddToGroupOp>(indexTy, execute.token(), group); 553 b.create<scf::YieldOp>(ValueRange({start, midIndex})); 554 } 555 556 // After dispatching async operations to process the tail of the block range 557 // call the parallel compute function for the first block of the range. 558 b.setInsertionPointAfter(whileOp); 559 560 // Drop async dispatch specific arguments: async group, block start and end. 561 auto forwardedInputs = block->getArguments().drop_front(3); 562 SmallVector<Value> computeFuncOperands = {blockStart}; 563 computeFuncOperands.append(forwardedInputs.begin(), forwardedInputs.end()); 564 565 b.create<func::CallOp>(computeFunc.func.getSymName(), 566 computeFunc.func.getCallableResults(), 567 computeFuncOperands); 568 b.create<func::ReturnOp>(ValueRange()); 569 570 return func; 571 } 572 573 // Launch async dispatch of the parallel compute function. 574 static void doAsyncDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 575 ParallelComputeFunction ¶llelComputeFunction, 576 scf::ParallelOp op, Value blockSize, 577 Value blockCount, 578 const SmallVector<Value> &tripCounts) { 579 MLIRContext *ctx = op->getContext(); 580 581 // Add one more level of indirection to dispatch parallel compute functions 582 // using async operations and recursive work splitting. 583 FuncOp asyncDispatchFunction = 584 createAsyncDispatchFunction(parallelComputeFunction, rewriter); 585 586 Value c0 = b.create<arith::ConstantIndexOp>(0); 587 Value c1 = b.create<arith::ConstantIndexOp>(1); 588 589 // Appends operands shared by async dispatch and parallel compute functions to 590 // the given operands vector. 591 auto appendBlockComputeOperands = [&](SmallVector<Value> &operands) { 592 operands.append(tripCounts); 593 operands.append(op.getLowerBound().begin(), op.getLowerBound().end()); 594 operands.append(op.getUpperBound().begin(), op.getUpperBound().end()); 595 operands.append(op.getStep().begin(), op.getStep().end()); 596 operands.append(parallelComputeFunction.captures); 597 }; 598 599 // Check if the block size is one, in this case we can skip the async dispatch 600 // completely. If this will be known statically, then canonicalization will 601 // erase async group operations. 602 Value isSingleBlock = 603 b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, blockCount, c1); 604 605 auto syncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 606 ImplicitLocOpBuilder b(loc, nestedBuilder); 607 608 // Call parallel compute function for the single block. 609 SmallVector<Value> operands = {c0, blockSize}; 610 appendBlockComputeOperands(operands); 611 612 b.create<func::CallOp>(parallelComputeFunction.func.getSymName(), 613 parallelComputeFunction.func.getCallableResults(), 614 operands); 615 b.create<scf::YieldOp>(); 616 }; 617 618 auto asyncDispatch = [&](OpBuilder &nestedBuilder, Location loc) { 619 ImplicitLocOpBuilder b(loc, nestedBuilder); 620 621 // Create an async.group to wait on all async tokens from the concurrent 622 // execution of multiple parallel compute function. First block will be 623 // executed synchronously in the caller thread. 624 Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 625 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 626 627 // Launch async dispatch function for [0, blockCount) range. 628 SmallVector<Value> operands = {group, c0, blockCount, blockSize}; 629 appendBlockComputeOperands(operands); 630 631 b.create<func::CallOp>(asyncDispatchFunction.getSymName(), 632 asyncDispatchFunction.getCallableResults(), 633 operands); 634 635 // Wait for the completion of all parallel compute operations. 636 b.create<AwaitAllOp>(group); 637 638 b.create<scf::YieldOp>(); 639 }; 640 641 // Dispatch either single block compute function, or launch async dispatch. 642 b.create<scf::IfOp>(TypeRange(), isSingleBlock, syncDispatch, asyncDispatch); 643 } 644 645 // Dispatch parallel compute functions by submitting all async compute tasks 646 // from a simple for loop in the caller thread. 647 static void 648 doSequentialDispatch(ImplicitLocOpBuilder &b, PatternRewriter &rewriter, 649 ParallelComputeFunction ¶llelComputeFunction, 650 scf::ParallelOp op, Value blockSize, Value blockCount, 651 const SmallVector<Value> &tripCounts) { 652 MLIRContext *ctx = op->getContext(); 653 654 FuncOp compute = parallelComputeFunction.func; 655 656 Value c0 = b.create<arith::ConstantIndexOp>(0); 657 Value c1 = b.create<arith::ConstantIndexOp>(1); 658 659 // Create an async.group to wait on all async tokens from the concurrent 660 // execution of multiple parallel compute function. First block will be 661 // executed synchronously in the caller thread. 662 Value groupSize = b.create<arith::SubIOp>(blockCount, c1); 663 Value group = b.create<CreateGroupOp>(GroupType::get(ctx), groupSize); 664 665 // Call parallel compute function for all blocks. 666 using LoopBodyBuilder = 667 std::function<void(OpBuilder &, Location, Value, ValueRange)>; 668 669 // Returns parallel compute function operands to process the given block. 670 auto computeFuncOperands = [&](Value blockIndex) -> SmallVector<Value> { 671 SmallVector<Value> computeFuncOperands = {blockIndex, blockSize}; 672 computeFuncOperands.append(tripCounts); 673 computeFuncOperands.append(op.getLowerBound().begin(), 674 op.getLowerBound().end()); 675 computeFuncOperands.append(op.getUpperBound().begin(), 676 op.getUpperBound().end()); 677 computeFuncOperands.append(op.getStep().begin(), op.getStep().end()); 678 computeFuncOperands.append(parallelComputeFunction.captures); 679 return computeFuncOperands; 680 }; 681 682 // Induction variable is the index of the block: [0, blockCount). 683 LoopBodyBuilder loopBuilder = [&](OpBuilder &loopBuilder, Location loc, 684 Value iv, ValueRange args) { 685 ImplicitLocOpBuilder b(loc, loopBuilder); 686 687 // Call parallel compute function inside the async.execute region. 688 auto executeBodyBuilder = [&](OpBuilder &executeBuilder, 689 Location executeLoc, ValueRange executeArgs) { 690 executeBuilder.create<func::CallOp>(executeLoc, compute.getSymName(), 691 compute.getCallableResults(), 692 computeFuncOperands(iv)); 693 executeBuilder.create<async::YieldOp>(executeLoc, ValueRange()); 694 }; 695 696 // Create async.execute operation to launch parallel computate function. 697 auto execute = b.create<ExecuteOp>(TypeRange(), ValueRange(), ValueRange(), 698 executeBodyBuilder); 699 b.create<AddToGroupOp>(rewriter.getIndexType(), execute.token(), group); 700 b.create<scf::YieldOp>(); 701 }; 702 703 // Iterate over all compute blocks and launch parallel compute operations. 704 b.create<scf::ForOp>(c1, blockCount, c1, ValueRange(), loopBuilder); 705 706 // Call parallel compute function for the first block in the caller thread. 707 b.create<func::CallOp>(compute.getSymName(), compute.getCallableResults(), 708 computeFuncOperands(c0)); 709 710 // Wait for the completion of all async compute operations. 711 b.create<AwaitAllOp>(group); 712 } 713 714 LogicalResult 715 AsyncParallelForRewrite::matchAndRewrite(scf::ParallelOp op, 716 PatternRewriter &rewriter) const { 717 // We do not currently support rewrite for parallel op with reductions. 718 if (op.getNumReductions() != 0) 719 return failure(); 720 721 ImplicitLocOpBuilder b(op.getLoc(), rewriter); 722 723 // Computing minTaskSize emits IR and can be implemented as executing a cost 724 // model on the body of the scf.parallel. Thus it needs to be computed before 725 // the body of the scf.parallel has been manipulated. 726 Value minTaskSize = computeMinTaskSize(b, op); 727 728 // Make sure that all constants will be inside the parallel operation body to 729 // reduce the number of parallel compute function arguments. 730 cloneConstantsIntoTheRegion(op.getLoopBody(), rewriter); 731 732 // Compute trip count for each loop induction variable: 733 // tripCount = ceil_div(upperBound - lowerBound, step); 734 SmallVector<Value> tripCounts(op.getNumLoops()); 735 for (size_t i = 0; i < op.getNumLoops(); ++i) { 736 auto lb = op.getLowerBound()[i]; 737 auto ub = op.getUpperBound()[i]; 738 auto step = op.getStep()[i]; 739 auto range = b.createOrFold<arith::SubIOp>(ub, lb); 740 tripCounts[i] = b.createOrFold<arith::CeilDivSIOp>(range, step); 741 } 742 743 // Compute a product of trip counts to get the 1-dimensional iteration space 744 // for the scf.parallel operation. 745 Value tripCount = tripCounts[0]; 746 for (size_t i = 1; i < tripCounts.size(); ++i) 747 tripCount = b.create<arith::MulIOp>(tripCount, tripCounts[i]); 748 749 // Short circuit no-op parallel loops (zero iterations) that can arise from 750 // the memrefs with dynamic dimension(s) equal to zero. 751 Value c0 = b.create<arith::ConstantIndexOp>(0); 752 Value isZeroIterations = 753 b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, tripCount, c0); 754 755 // Do absolutely nothing if the trip count is zero. 756 auto noOp = [&](OpBuilder &nestedBuilder, Location loc) { 757 nestedBuilder.create<scf::YieldOp>(loc); 758 }; 759 760 // Compute the parallel block size and dispatch concurrent tasks computing 761 // results for each block. 762 auto dispatch = [&](OpBuilder &nestedBuilder, Location loc) { 763 ImplicitLocOpBuilder b(loc, nestedBuilder); 764 765 // Collect statically known constants defining the loop nest in the parallel 766 // compute function. LLVM can't always push constants across the non-trivial 767 // async dispatch call graph, by providing these values explicitly we can 768 // choose to build more efficient loop nest, and rely on a better constant 769 // folding, loop unrolling and vectorization. 770 ParallelComputeFunctionBounds staticBounds = { 771 integerConstants(tripCounts), 772 integerConstants(op.getLowerBound()), 773 integerConstants(op.getUpperBound()), 774 integerConstants(op.getStep()), 775 }; 776 777 // Find how many inner iteration dimensions are statically known, and their 778 // product is smaller than the `512`. We align the parallel compute block 779 // size by the product of statically known dimensions, so that we can 780 // guarantee that the inner loops executes from 0 to the loop trip counts 781 // and we can elide dynamic loop boundaries, and give LLVM an opportunity to 782 // unroll the loops. The constant `512` is arbitrary, it should depend on 783 // how many iterations LLVM will typically decide to unroll. 784 static constexpr int64_t maxUnrollableIterations = 512; 785 786 // The number of inner loops with statically known number of iterations less 787 // than the `maxUnrollableIterations` value. 788 int numUnrollableLoops = 0; 789 790 auto getInt = [](IntegerAttr attr) { return attr ? attr.getInt() : 0; }; 791 792 SmallVector<int64_t> numIterations(op.getNumLoops()); 793 numIterations.back() = getInt(staticBounds.tripCounts.back()); 794 795 for (int i = op.getNumLoops() - 2; i >= 0; --i) { 796 int64_t tripCount = getInt(staticBounds.tripCounts[i]); 797 int64_t innerIterations = numIterations[i + 1]; 798 numIterations[i] = tripCount * innerIterations; 799 800 // Update the number of inner loops that we can potentially unroll. 801 if (innerIterations > 0 && innerIterations <= maxUnrollableIterations) 802 numUnrollableLoops++; 803 } 804 805 Value numWorkerThreadsVal; 806 if (numWorkerThreads >= 0) 807 numWorkerThreadsVal = b.create<arith::ConstantIndexOp>(numWorkerThreads); 808 else 809 numWorkerThreadsVal = b.create<async::RuntimeNumWorkerThreadsOp>(); 810 811 // With large number of threads the value of creating many compute blocks 812 // is reduced because the problem typically becomes memory bound. For this 813 // reason we scale the number of workers using an equivalent to the 814 // following logic: 815 // float overshardingFactor = numWorkerThreads <= 4 ? 8.0 816 // : numWorkerThreads <= 8 ? 4.0 817 // : numWorkerThreads <= 16 ? 2.0 818 // : numWorkerThreads <= 32 ? 1.0 819 // : numWorkerThreads <= 64 ? 0.8 820 // : 0.6; 821 822 // Pairs of non-inclusive lower end of the bracket and factor that the 823 // number of workers needs to be scaled with if it falls in that bucket. 824 const SmallVector<std::pair<int, float>> overshardingBrackets = { 825 {4, 4.0f}, {8, 2.0f}, {16, 1.0f}, {32, 0.8f}, {64, 0.6f}}; 826 const float initialOvershardingFactor = 8.0f; 827 828 Value scalingFactor = b.create<arith::ConstantFloatOp>( 829 llvm::APFloat(initialOvershardingFactor), b.getF32Type()); 830 for (const std::pair<int, float> &p : overshardingBrackets) { 831 Value bracketBegin = b.create<arith::ConstantIndexOp>(p.first); 832 Value inBracket = b.create<arith::CmpIOp>( 833 arith::CmpIPredicate::sgt, numWorkerThreadsVal, bracketBegin); 834 Value bracketScalingFactor = b.create<arith::ConstantFloatOp>( 835 llvm::APFloat(p.second), b.getF32Type()); 836 scalingFactor = b.create<arith::SelectOp>(inBracket, bracketScalingFactor, 837 scalingFactor); 838 } 839 Value numWorkersIndex = 840 b.create<arith::IndexCastOp>(b.getI32Type(), numWorkerThreadsVal); 841 Value numWorkersFloat = 842 b.create<arith::SIToFPOp>(b.getF32Type(), numWorkersIndex); 843 Value scaledNumWorkers = 844 b.create<arith::MulFOp>(scalingFactor, numWorkersFloat); 845 Value scaledNumInt = 846 b.create<arith::FPToSIOp>(b.getI32Type(), scaledNumWorkers); 847 Value scaledWorkers = 848 b.create<arith::IndexCastOp>(b.getIndexType(), scaledNumInt); 849 850 Value maxComputeBlocks = b.create<arith::MaxSIOp>( 851 b.create<arith::ConstantIndexOp>(1), scaledWorkers); 852 853 // Compute parallel block size from the parallel problem size: 854 // blockSize = min(tripCount, 855 // max(ceil_div(tripCount, maxComputeBlocks), 856 // minTaskSize)) 857 Value bs0 = b.create<arith::CeilDivSIOp>(tripCount, maxComputeBlocks); 858 Value bs1 = b.create<arith::MaxSIOp>(bs0, minTaskSize); 859 Value blockSize = b.create<arith::MinSIOp>(tripCount, bs1); 860 861 // Dispatch parallel compute function using async recursive work splitting, 862 // or by submitting compute task sequentially from a caller thread. 863 auto doDispatch = asyncDispatch ? doAsyncDispatch : doSequentialDispatch; 864 865 // Create a parallel compute function that takes a block id and computes 866 // the parallel operation body for a subset of iteration space. 867 868 // Compute the number of parallel compute blocks. 869 Value blockCount = b.create<arith::CeilDivSIOp>(tripCount, blockSize); 870 871 // Dispatch parallel compute function without hints to unroll inner loops. 872 auto dispatchDefault = [&](OpBuilder &nestedBuilder, Location loc) { 873 ParallelComputeFunction compute = 874 createParallelComputeFunction(op, staticBounds, 0, rewriter); 875 876 ImplicitLocOpBuilder b(loc, nestedBuilder); 877 doDispatch(b, rewriter, compute, op, blockSize, blockCount, tripCounts); 878 b.create<scf::YieldOp>(); 879 }; 880 881 // Dispatch parallel compute function with hints for unrolling inner loops. 882 auto dispatchBlockAligned = [&](OpBuilder &nestedBuilder, Location loc) { 883 ParallelComputeFunction compute = createParallelComputeFunction( 884 op, staticBounds, numUnrollableLoops, rewriter); 885 886 ImplicitLocOpBuilder b(loc, nestedBuilder); 887 // Align the block size to be a multiple of the statically known 888 // number of iterations in the inner loops. 889 Value numIters = b.create<arith::ConstantIndexOp>( 890 numIterations[op.getNumLoops() - numUnrollableLoops]); 891 Value alignedBlockSize = b.create<arith::MulIOp>( 892 b.create<arith::CeilDivSIOp>(blockSize, numIters), numIters); 893 doDispatch(b, rewriter, compute, op, alignedBlockSize, blockCount, 894 tripCounts); 895 b.create<scf::YieldOp>(); 896 }; 897 898 // Dispatch to block aligned compute function only if the computed block 899 // size is larger than the number of iterations in the unrollable inner 900 // loops, because otherwise it can reduce the available parallelism. 901 if (numUnrollableLoops > 0) { 902 Value numIters = b.create<arith::ConstantIndexOp>( 903 numIterations[op.getNumLoops() - numUnrollableLoops]); 904 Value useBlockAlignedComputeFn = b.create<arith::CmpIOp>( 905 arith::CmpIPredicate::sge, blockSize, numIters); 906 907 b.create<scf::IfOp>(TypeRange(), useBlockAlignedComputeFn, 908 dispatchBlockAligned, dispatchDefault); 909 b.create<scf::YieldOp>(); 910 } else { 911 dispatchDefault(b, loc); 912 } 913 }; 914 915 // Replace the `scf.parallel` operation with the parallel compute function. 916 b.create<scf::IfOp>(TypeRange(), isZeroIterations, noOp, dispatch); 917 918 // Parallel operation was replaced with a block iteration loop. 919 rewriter.eraseOp(op); 920 921 return success(); 922 } 923 924 void AsyncParallelForPass::runOnOperation() { 925 MLIRContext *ctx = &getContext(); 926 927 RewritePatternSet patterns(ctx); 928 populateAsyncParallelForPatterns( 929 patterns, asyncDispatch, numWorkerThreads, 930 [&](ImplicitLocOpBuilder builder, scf::ParallelOp op) { 931 return builder.create<arith::ConstantIndexOp>(minTaskSize); 932 }); 933 if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns)))) 934 signalPassFailure(); 935 } 936 937 std::unique_ptr<Pass> mlir::createAsyncParallelForPass() { 938 return std::make_unique<AsyncParallelForPass>(); 939 } 940 941 std::unique_ptr<Pass> mlir::createAsyncParallelForPass(bool asyncDispatch, 942 int32_t numWorkerThreads, 943 int32_t minTaskSize) { 944 return std::make_unique<AsyncParallelForPass>(asyncDispatch, numWorkerThreads, 945 minTaskSize); 946 } 947 948 void mlir::async::populateAsyncParallelForPatterns( 949 RewritePatternSet &patterns, bool asyncDispatch, int32_t numWorkerThreads, 950 const AsyncMinTaskSizeComputationFunction &computeMinTaskSize) { 951 MLIRContext *ctx = patterns.getContext(); 952 patterns.add<AsyncParallelForRewrite>(ctx, asyncDispatch, numWorkerThreads, 953 computeMinTaskSize); 954 } 955