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