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