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