1 //===- LoopPipelining.cpp - Code to perform loop software pipelining-------===//
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 loop software pipelining
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
15 #include "mlir/Dialect/SCF/SCF.h"
16 #include "mlir/Dialect/SCF/Transforms.h"
17 #include "mlir/Dialect/SCF/Utils.h"
18 #include "mlir/Dialect/StandardOps/IR/Ops.h"
19 #include "mlir/IR/BlockAndValueMapping.h"
20 #include "mlir/IR/PatternMatch.h"
21 #include "mlir/Support/MathExtras.h"
22 
23 using namespace mlir;
24 using namespace mlir::scf;
25 
26 namespace {
27 
28 /// Helper to keep internal information during pipelining transformation.
29 struct LoopPipelinerInternal {
30   /// Coarse liverange information for ops used across stages.
31   struct LiverangeInfo {
32     unsigned lastUseStage = 0;
33     unsigned defStage = 0;
34   };
35 
36 protected:
37   ForOp forOp;
38   unsigned maxStage = 0;
39   DenseMap<Operation *, unsigned> stages;
40   std::vector<Operation *> opOrder;
41   int64_t ub;
42   int64_t lb;
43   int64_t step;
44 
45   // When peeling the kernel we generate several version of each value for
46   // different stage of the prologue. This map tracks the mapping between
47   // original Values in the loop and the different versions
48   // peeled from the loop.
49   DenseMap<Value, llvm::SmallVector<Value>> valueMapping;
50 
51   /// Assign a value to `valueMapping`, this means `val` represents the version
52   /// `idx` of `key` in the epilogue.
53   void setValueMapping(Value key, Value el, int64_t idx);
54 
55 public:
56   /// Initalize the information for the given `op`, return true if it
57   /// satisfies the pre-condition to apply pipelining.
58   bool initializeLoopInfo(ForOp op, const PipeliningOption &options);
59   /// Emits the prologue, this creates `maxStage - 1` part which will contain
60   /// operations from stages [0; i], where i is the part index.
61   void emitPrologue(PatternRewriter &rewriter);
62   /// Gather liverange information for Values that are used in a different stage
63   /// than its definition.
64   llvm::MapVector<Value, LiverangeInfo> analyzeCrossStageValues();
65   scf::ForOp createKernelLoop(
66       const llvm::MapVector<Value, LiverangeInfo> &crossStageValues,
67       PatternRewriter &rewriter,
68       llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap);
69   /// Emits the pipelined kernel. This clones loop operations following user
70   /// order and remaps operands defined in a different stage as their use.
71   void createKernel(
72       scf::ForOp newForOp,
73       const llvm::MapVector<Value, LiverangeInfo> &crossStageValues,
74       const llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap,
75       PatternRewriter &rewriter);
76   /// Emits the epilogue, this creates `maxStage - 1` part which will contain
77   /// operations from stages [i; maxStage], where i is the part index.
78   llvm::SmallVector<Value> emitEpilogue(PatternRewriter &rewriter);
79 };
80 
81 bool LoopPipelinerInternal::initializeLoopInfo(
82     ForOp op, const PipeliningOption &options) {
83   forOp = op;
84   auto upperBoundCst =
85       forOp.getUpperBound().getDefiningOp<arith::ConstantIndexOp>();
86   auto lowerBoundCst =
87       forOp.getLowerBound().getDefiningOp<arith::ConstantIndexOp>();
88   auto stepCst = forOp.getStep().getDefiningOp<arith::ConstantIndexOp>();
89   if (!upperBoundCst || !lowerBoundCst || !stepCst)
90     return false;
91   ub = upperBoundCst.value();
92   lb = lowerBoundCst.value();
93   step = stepCst.value();
94   int64_t numIteration = ceilDiv(ub - lb, step);
95   std::vector<std::pair<Operation *, unsigned>> schedule;
96   options.getScheduleFn(forOp, schedule);
97   if (schedule.empty())
98     return false;
99 
100   opOrder.reserve(schedule.size());
101   for (auto &opSchedule : schedule) {
102     maxStage = std::max(maxStage, opSchedule.second);
103     stages[opSchedule.first] = opSchedule.second;
104     opOrder.push_back(opSchedule.first);
105   }
106   if (numIteration <= maxStage)
107     return false;
108 
109   // All operations need to have a stage.
110   if (forOp
111           .walk([this](Operation *op) {
112             if (op != forOp.getOperation() && !isa<scf::YieldOp>(op) &&
113                 stages.find(op) == stages.end())
114               return WalkResult::interrupt();
115             return WalkResult::advance();
116           })
117           .wasInterrupted())
118     return false;
119 
120   // Only support loop carried dependency with a distance of 1. This means the
121   // source of all the scf.yield operands needs to be defined by operations in
122   // the loop.
123   if (llvm::any_of(forOp.getBody()->getTerminator()->getOperands(),
124                    [this](Value operand) {
125                      Operation *def = operand.getDefiningOp();
126                      return !def || stages.find(def) == stages.end();
127                    }))
128     return false;
129   return true;
130 }
131 
132 void LoopPipelinerInternal::emitPrologue(PatternRewriter &rewriter) {
133   // Initialize the iteration argument to the loop initiale values.
134   for (BlockArgument &arg : forOp.getRegionIterArgs()) {
135     OpOperand &operand = forOp.getOpOperandForRegionIterArg(arg);
136     setValueMapping(arg, operand.get(), 0);
137   }
138   auto yield = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
139   for (int64_t i = 0; i < maxStage; i++) {
140     // special handling for induction variable as the increment is implicit.
141     Value iv = rewriter.create<arith::ConstantIndexOp>(forOp.getLoc(), lb + i);
142     setValueMapping(forOp.getInductionVar(), iv, i);
143     for (Operation *op : opOrder) {
144       if (stages[op] > i)
145         continue;
146       Operation *newOp = rewriter.clone(*op);
147       for (unsigned opIdx = 0; opIdx < op->getNumOperands(); opIdx++) {
148         auto it = valueMapping.find(op->getOperand(opIdx));
149         if (it != valueMapping.end())
150           newOp->setOperand(opIdx, it->second[i - stages[op]]);
151       }
152       for (unsigned destId : llvm::seq(unsigned(0), op->getNumResults())) {
153         setValueMapping(op->getResult(destId), newOp->getResult(destId),
154                         i - stages[op]);
155         // If the value is a loop carried dependency update the loop argument
156         // mapping.
157         for (OpOperand &operand : yield->getOpOperands()) {
158           if (operand.get() != op->getResult(destId))
159             continue;
160           setValueMapping(forOp.getRegionIterArgs()[operand.getOperandNumber()],
161                           newOp->getResult(destId), i - stages[op] + 1);
162         }
163       }
164     }
165   }
166 }
167 
168 llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
169 LoopPipelinerInternal::analyzeCrossStageValues() {
170   llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo> crossStageValues;
171   for (Operation *op : opOrder) {
172     unsigned stage = stages[op];
173     for (OpOperand &operand : op->getOpOperands()) {
174       Operation *def = operand.get().getDefiningOp();
175       if (!def)
176         continue;
177       auto defStage = stages.find(def);
178       if (defStage == stages.end() || defStage->second == stage)
179         continue;
180       assert(stage > defStage->second);
181       LiverangeInfo &info = crossStageValues[operand.get()];
182       info.defStage = defStage->second;
183       info.lastUseStage = std::max(info.lastUseStage, stage);
184     }
185   }
186   return crossStageValues;
187 }
188 
189 scf::ForOp LoopPipelinerInternal::createKernelLoop(
190     const llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
191         &crossStageValues,
192     PatternRewriter &rewriter,
193     llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap) {
194   // Creates the list of initial values associated to values used across
195   // stages. The initial values come from the prologue created above.
196   // Keep track of the kernel argument associated to each version of the
197   // values passed to the kernel.
198   llvm::SmallVector<Value> newLoopArg;
199   // For existing loop argument initialize them with the right version from the
200   // prologue.
201   for (auto retVal :
202        llvm::enumerate(forOp.getBody()->getTerminator()->getOperands())) {
203     Operation *def = retVal.value().getDefiningOp();
204     assert(def && "Only support loop carried dependencies of distance 1");
205     unsigned defStage = stages[def];
206     Value valueVersion = valueMapping[forOp.getRegionIterArgs()[retVal.index()]]
207                                      [maxStage - defStage];
208     assert(valueVersion);
209     newLoopArg.push_back(valueVersion);
210   }
211   for (auto escape : crossStageValues) {
212     LiverangeInfo &info = escape.second;
213     Value value = escape.first;
214     for (unsigned stageIdx = 0; stageIdx < info.lastUseStage - info.defStage;
215          stageIdx++) {
216       Value valueVersion =
217           valueMapping[value][maxStage - info.lastUseStage + stageIdx];
218       assert(valueVersion);
219       newLoopArg.push_back(valueVersion);
220       loopArgMap[std::make_pair(value, info.lastUseStage - info.defStage -
221                                            stageIdx)] = newLoopArg.size() - 1;
222     }
223   }
224 
225   // Create the new kernel loop. Since we need to peel `numStages - 1`
226   // iteration we change the upper bound to remove those iterations.
227   Value newUb = rewriter.create<arith::ConstantIndexOp>(forOp.getLoc(),
228                                                         ub - maxStage * step);
229   auto newForOp =
230       rewriter.create<scf::ForOp>(forOp.getLoc(), forOp.getLowerBound(), newUb,
231                                   forOp.getStep(), newLoopArg);
232   return newForOp;
233 }
234 
235 void LoopPipelinerInternal::createKernel(
236     scf::ForOp newForOp,
237     const llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
238         &crossStageValues,
239     const llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap,
240     PatternRewriter &rewriter) {
241   valueMapping.clear();
242 
243   // Create the kernel, we clone instruction based on the order given by
244   // user and remap operands coming from a previous stages.
245   rewriter.setInsertionPoint(newForOp.getBody(), newForOp.getBody()->begin());
246   BlockAndValueMapping mapping;
247   mapping.map(forOp.getInductionVar(), newForOp.getInductionVar());
248   for (auto arg : llvm::enumerate(forOp.getRegionIterArgs())) {
249     mapping.map(arg.value(), newForOp.getRegionIterArgs()[arg.index()]);
250   }
251   for (Operation *op : opOrder) {
252     int64_t useStage = stages[op];
253     auto *newOp = rewriter.clone(*op, mapping);
254     for (OpOperand &operand : op->getOpOperands()) {
255       // Special case for the induction variable uses. We replace it with a
256       // version incremented based on the stage where it is used.
257       if (operand.get() == forOp.getInductionVar()) {
258         rewriter.setInsertionPoint(newOp);
259         Value offset = rewriter.create<arith::ConstantIndexOp>(
260             forOp.getLoc(), (maxStage - stages[op]) * step);
261         Value iv = rewriter.create<arith::AddIOp>(
262             forOp.getLoc(), newForOp.getInductionVar(), offset);
263         newOp->setOperand(operand.getOperandNumber(), iv);
264         rewriter.setInsertionPointAfter(newOp);
265         continue;
266       }
267       auto arg = operand.get().dyn_cast<BlockArgument>();
268       if (arg && arg.getOwner() == forOp.getBody()) {
269         // If the value is a loop carried value coming from stage N + 1 remap,
270         // it will become a direct use.
271         Value ret = forOp.getBody()->getTerminator()->getOperand(
272             arg.getArgNumber() - 1);
273         Operation *dep = ret.getDefiningOp();
274         if (!dep)
275           continue;
276         auto stageDep = stages.find(dep);
277         if (stageDep == stages.end() || stageDep->second == useStage)
278           continue;
279         assert(stageDep->second == useStage + 1);
280         newOp->setOperand(operand.getOperandNumber(),
281                           mapping.lookupOrDefault(ret));
282         continue;
283       }
284       // For operands defined in a previous stage we need to remap it to use
285       // the correct region argument. We look for the right version of the
286       // Value based on the stage where it is used.
287       Operation *def = operand.get().getDefiningOp();
288       if (!def)
289         continue;
290       auto stageDef = stages.find(def);
291       if (stageDef == stages.end() || stageDef->second == useStage)
292         continue;
293       auto remap = loopArgMap.find(
294           std::make_pair(operand.get(), useStage - stageDef->second));
295       assert(remap != loopArgMap.end());
296       newOp->setOperand(operand.getOperandNumber(),
297                         newForOp.getRegionIterArgs()[remap->second]);
298     }
299   }
300 
301   // Collect the Values that need to be returned by the forOp. For each
302   // value we need to have `LastUseStage - DefStage` number of versions
303   // returned.
304   // We create a mapping between original values and the associated loop
305   // returned values that will be needed by the epilogue.
306   llvm::SmallVector<Value> yieldOperands;
307   for (Value retVal : forOp.getBody()->getTerminator()->getOperands()) {
308     yieldOperands.push_back(mapping.lookupOrDefault(retVal));
309   }
310   for (auto &it : crossStageValues) {
311     int64_t version = maxStage - it.second.lastUseStage + 1;
312     unsigned numVersionReturned = it.second.lastUseStage - it.second.defStage;
313     // add the original verstion to yield ops.
314     // If there is a liverange spanning across more than 2 stages we need to add
315     // extra arg.
316     for (unsigned i = 1; i < numVersionReturned; i++) {
317       setValueMapping(it.first, newForOp->getResult(yieldOperands.size()),
318                       version++);
319       yieldOperands.push_back(
320           newForOp.getBody()->getArguments()[yieldOperands.size() + 1 +
321                                              newForOp.getNumInductionVars()]);
322     }
323     setValueMapping(it.first, newForOp->getResult(yieldOperands.size()),
324                     version++);
325     yieldOperands.push_back(mapping.lookupOrDefault(it.first));
326   }
327   // Map the yield operand to the forOp returned value.
328   for (auto retVal :
329        llvm::enumerate(forOp.getBody()->getTerminator()->getOperands())) {
330     Operation *def = retVal.value().getDefiningOp();
331     assert(def && "Only support loop carried dependencies of distance 1");
332     unsigned defStage = stages[def];
333     setValueMapping(forOp.getRegionIterArgs()[retVal.index()],
334                     newForOp->getResult(retVal.index()),
335                     maxStage - defStage + 1);
336   }
337   rewriter.create<scf::YieldOp>(forOp.getLoc(), yieldOperands);
338 }
339 
340 llvm::SmallVector<Value>
341 LoopPipelinerInternal::emitEpilogue(PatternRewriter &rewriter) {
342   llvm::SmallVector<Value> returnValues(forOp->getNumResults());
343   // Emit different versions of the induction variable. They will be
344   // removed by dead code if not used.
345   for (int64_t i = 0; i < maxStage; i++) {
346     Value newlastIter = rewriter.create<arith::ConstantIndexOp>(
347         forOp.getLoc(), lb + step * ((((ub - 1) - lb) / step) - i));
348     setValueMapping(forOp.getInductionVar(), newlastIter, maxStage - i);
349   }
350   // Emit `maxStage - 1` epilogue part that includes operations fro stages
351   // [i; maxStage].
352   for (int64_t i = 1; i <= maxStage; i++) {
353     for (Operation *op : opOrder) {
354       if (stages[op] < i)
355         continue;
356       Operation *newOp = rewriter.clone(*op);
357       for (unsigned opIdx = 0; opIdx < op->getNumOperands(); opIdx++) {
358         auto it = valueMapping.find(op->getOperand(opIdx));
359         if (it != valueMapping.end()) {
360           Value v = it->second[maxStage - stages[op] + i];
361           assert(v);
362           newOp->setOperand(opIdx, v);
363         }
364       }
365       for (unsigned destId : llvm::seq(unsigned(0), op->getNumResults())) {
366         setValueMapping(op->getResult(destId), newOp->getResult(destId),
367                         maxStage - stages[op] + i);
368         // If the value is a loop carried dependency update the loop argument
369         // mapping and keep track of the last version to replace the original
370         // forOp uses.
371         for (OpOperand &operand :
372              forOp.getBody()->getTerminator()->getOpOperands()) {
373           if (operand.get() != op->getResult(destId))
374             continue;
375           unsigned version = maxStage - stages[op] + i + 1;
376           // If the version is greater than maxStage it means it maps to the
377           // original forOp returned value.
378           if (version > maxStage) {
379             returnValues[operand.getOperandNumber()] = newOp->getResult(destId);
380             continue;
381           }
382           setValueMapping(forOp.getRegionIterArgs()[operand.getOperandNumber()],
383                           newOp->getResult(destId), version);
384         }
385       }
386     }
387   }
388   return returnValues;
389 }
390 
391 void LoopPipelinerInternal::setValueMapping(Value key, Value el, int64_t idx) {
392   auto it = valueMapping.find(key);
393   // If the value is not in the map yet add a vector big enough to store all
394   // versions.
395   if (it == valueMapping.end())
396     it =
397         valueMapping
398             .insert(std::make_pair(key, llvm::SmallVector<Value>(maxStage + 1)))
399             .first;
400   it->second[idx] = el;
401 }
402 
403 /// Generate a pipelined version of the scf.for loop based on the schedule given
404 /// as option. This applies the mechanical transformation of changing the loop
405 /// and generating the prologue/epilogue for the pipelining and doesn't make any
406 /// decision regarding the schedule.
407 /// Based on the option the loop is split into several stages.
408 /// The transformation assumes that the scheduling given by user is valid.
409 /// For example if we break a loop into 3 stages named S0, S1, S2 we would
410 /// generate the following code with the number in parenthesis the iteration
411 /// index:
412 /// S0(0)                        // Prologue
413 /// S0(1) S1(0)                  // Prologue
414 /// scf.for %I = %C0 to %N - 2 {
415 ///  S0(I+2) S1(I+1) S2(I)       // Pipelined kernel
416 /// }
417 /// S1(N) S2(N-1)                // Epilogue
418 /// S2(N)                        // Epilogue
419 struct ForLoopPipelining : public OpRewritePattern<ForOp> {
420   ForLoopPipelining(const PipeliningOption &options, MLIRContext *context)
421       : OpRewritePattern<ForOp>(context), options(options) {}
422   LogicalResult matchAndRewrite(ForOp forOp,
423                                 PatternRewriter &rewriter) const override {
424 
425     LoopPipelinerInternal pipeliner;
426     if (!pipeliner.initializeLoopInfo(forOp, options))
427       return failure();
428 
429     // 1. Emit prologue.
430     pipeliner.emitPrologue(rewriter);
431 
432     // 2. Track values used across stages. When a value cross stages it will
433     // need to be passed as loop iteration arguments.
434     // We first collect the values that are used in a different stage than where
435     // they are defined.
436     llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
437         crossStageValues = pipeliner.analyzeCrossStageValues();
438 
439     // Mapping between original loop values used cross stage and the block
440     // arguments associated after pipelining. A Value may map to several
441     // arguments if its liverange spans across more than 2 stages.
442     llvm::DenseMap<std::pair<Value, unsigned>, unsigned> loopArgMap;
443     // 3. Create the new kernel loop and return the block arguments mapping.
444     ForOp newForOp =
445         pipeliner.createKernelLoop(crossStageValues, rewriter, loopArgMap);
446     // Create the kernel block, order ops based on user choice and remap
447     // operands.
448     pipeliner.createKernel(newForOp, crossStageValues, loopArgMap, rewriter);
449 
450     // 4. Emit the epilogue after the new forOp.
451     rewriter.setInsertionPointAfter(newForOp);
452     llvm::SmallVector<Value> returnValues = pipeliner.emitEpilogue(rewriter);
453 
454     // 5. Erase the original loop and replace the uses with the epilogue output.
455     if (forOp->getNumResults() > 0)
456       rewriter.replaceOp(forOp, returnValues);
457     else
458       rewriter.eraseOp(forOp);
459 
460     return success();
461   }
462 
463 protected:
464   PipeliningOption options;
465 };
466 
467 } // namespace
468 
469 void mlir::scf::populateSCFLoopPipeliningPatterns(
470     RewritePatternSet &patterns, const PipeliningOption &options) {
471   patterns.add<ForLoopPipelining>(options, patterns.getContext());
472 }
473