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