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