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/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 =
142         rewriter.create<arith::ConstantIndexOp>(forOp.getLoc(), lb + i * step);
143     setValueMapping(forOp.getInductionVar(), iv, i);
144     for (Operation *op : opOrder) {
145       if (stages[op] > i)
146         continue;
147       Operation *newOp = rewriter.clone(*op);
148       for (unsigned opIdx = 0; opIdx < op->getNumOperands(); opIdx++) {
149         auto it = valueMapping.find(op->getOperand(opIdx));
150         if (it != valueMapping.end())
151           newOp->setOperand(opIdx, it->second[i - stages[op]]);
152       }
153       for (unsigned destId : llvm::seq(unsigned(0), op->getNumResults())) {
154         setValueMapping(op->getResult(destId), newOp->getResult(destId),
155                         i - stages[op]);
156         // If the value is a loop carried dependency update the loop argument
157         // mapping.
158         for (OpOperand &operand : yield->getOpOperands()) {
159           if (operand.get() != op->getResult(destId))
160             continue;
161           setValueMapping(forOp.getRegionIterArgs()[operand.getOperandNumber()],
162                           newOp->getResult(destId), i - stages[op] + 1);
163         }
164       }
165     }
166   }
167 }
168 
169 llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
170 LoopPipelinerInternal::analyzeCrossStageValues() {
171   llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo> crossStageValues;
172   for (Operation *op : opOrder) {
173     unsigned stage = stages[op];
174     for (OpOperand &operand : op->getOpOperands()) {
175       Operation *def = operand.get().getDefiningOp();
176       if (!def)
177         continue;
178       auto defStage = stages.find(def);
179       if (defStage == stages.end() || defStage->second == stage)
180         continue;
181       assert(stage > defStage->second);
182       LiverangeInfo &info = crossStageValues[operand.get()];
183       info.defStage = defStage->second;
184       info.lastUseStage = std::max(info.lastUseStage, stage);
185     }
186   }
187   return crossStageValues;
188 }
189 
190 scf::ForOp LoopPipelinerInternal::createKernelLoop(
191     const llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
192         &crossStageValues,
193     PatternRewriter &rewriter,
194     llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap) {
195   // Creates the list of initial values associated to values used across
196   // stages. The initial values come from the prologue created above.
197   // Keep track of the kernel argument associated to each version of the
198   // values passed to the kernel.
199   llvm::SmallVector<Value> newLoopArg;
200   // For existing loop argument initialize them with the right version from the
201   // prologue.
202   for (const auto &retVal :
203        llvm::enumerate(forOp.getBody()->getTerminator()->getOperands())) {
204     Operation *def = retVal.value().getDefiningOp();
205     assert(def && "Only support loop carried dependencies of distance 1");
206     unsigned defStage = stages[def];
207     Value valueVersion = valueMapping[forOp.getRegionIterArgs()[retVal.index()]]
208                                      [maxStage - defStage];
209     assert(valueVersion);
210     newLoopArg.push_back(valueVersion);
211   }
212   for (auto escape : crossStageValues) {
213     LiverangeInfo &info = escape.second;
214     Value value = escape.first;
215     for (unsigned stageIdx = 0; stageIdx < info.lastUseStage - info.defStage;
216          stageIdx++) {
217       Value valueVersion =
218           valueMapping[value][maxStage - info.lastUseStage + stageIdx];
219       assert(valueVersion);
220       newLoopArg.push_back(valueVersion);
221       loopArgMap[std::make_pair(value, info.lastUseStage - info.defStage -
222                                            stageIdx)] = newLoopArg.size() - 1;
223     }
224   }
225 
226   // Create the new kernel loop. Since we need to peel `numStages - 1`
227   // iteration we change the upper bound to remove those iterations.
228   Value newUb = rewriter.create<arith::ConstantIndexOp>(forOp.getLoc(),
229                                                         ub - maxStage * step);
230   auto newForOp =
231       rewriter.create<scf::ForOp>(forOp.getLoc(), forOp.getLowerBound(), newUb,
232                                   forOp.getStep(), newLoopArg);
233   return newForOp;
234 }
235 
236 void LoopPipelinerInternal::createKernel(
237     scf::ForOp newForOp,
238     const llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
239         &crossStageValues,
240     const llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap,
241     PatternRewriter &rewriter) {
242   valueMapping.clear();
243 
244   // Create the kernel, we clone instruction based on the order given by
245   // user and remap operands coming from a previous stages.
246   rewriter.setInsertionPoint(newForOp.getBody(), newForOp.getBody()->begin());
247   BlockAndValueMapping mapping;
248   mapping.map(forOp.getInductionVar(), newForOp.getInductionVar());
249   for (const auto &arg : llvm::enumerate(forOp.getRegionIterArgs())) {
250     mapping.map(arg.value(), newForOp.getRegionIterArgs()[arg.index()]);
251   }
252   for (Operation *op : opOrder) {
253     int64_t useStage = stages[op];
254     auto *newOp = rewriter.clone(*op, mapping);
255     for (OpOperand &operand : op->getOpOperands()) {
256       // Special case for the induction variable uses. We replace it with a
257       // version incremented based on the stage where it is used.
258       if (operand.get() == forOp.getInductionVar()) {
259         rewriter.setInsertionPoint(newOp);
260         Value offset = rewriter.create<arith::ConstantIndexOp>(
261             forOp.getLoc(), (maxStage - stages[op]) * step);
262         Value iv = rewriter.create<arith::AddIOp>(
263             forOp.getLoc(), newForOp.getInductionVar(), offset);
264         newOp->setOperand(operand.getOperandNumber(), iv);
265         rewriter.setInsertionPointAfter(newOp);
266         continue;
267       }
268       auto arg = operand.get().dyn_cast<BlockArgument>();
269       if (arg && arg.getOwner() == forOp.getBody()) {
270         // If the value is a loop carried value coming from stage N + 1 remap,
271         // it will become a direct use.
272         Value ret = forOp.getBody()->getTerminator()->getOperand(
273             arg.getArgNumber() - 1);
274         Operation *dep = ret.getDefiningOp();
275         if (!dep)
276           continue;
277         auto stageDep = stages.find(dep);
278         if (stageDep == stages.end() || stageDep->second == useStage)
279           continue;
280         assert(stageDep->second == useStage + 1);
281         newOp->setOperand(operand.getOperandNumber(),
282                           mapping.lookupOrDefault(ret));
283         continue;
284       }
285       // For operands defined in a previous stage we need to remap it to use
286       // the correct region argument. We look for the right version of the
287       // Value based on the stage where it is used.
288       Operation *def = operand.get().getDefiningOp();
289       if (!def)
290         continue;
291       auto stageDef = stages.find(def);
292       if (stageDef == stages.end() || stageDef->second == useStage)
293         continue;
294       auto remap = loopArgMap.find(
295           std::make_pair(operand.get(), useStage - stageDef->second));
296       assert(remap != loopArgMap.end());
297       newOp->setOperand(operand.getOperandNumber(),
298                         newForOp.getRegionIterArgs()[remap->second]);
299     }
300   }
301 
302   // Collect the Values that need to be returned by the forOp. For each
303   // value we need to have `LastUseStage - DefStage` number of versions
304   // returned.
305   // We create a mapping between original values and the associated loop
306   // returned values that will be needed by the epilogue.
307   llvm::SmallVector<Value> yieldOperands;
308   for (Value retVal : forOp.getBody()->getTerminator()->getOperands()) {
309     yieldOperands.push_back(mapping.lookupOrDefault(retVal));
310   }
311   for (auto &it : crossStageValues) {
312     int64_t version = maxStage - it.second.lastUseStage + 1;
313     unsigned numVersionReturned = it.second.lastUseStage - it.second.defStage;
314     // add the original verstion to yield ops.
315     // If there is a liverange spanning across more than 2 stages we need to add
316     // extra arg.
317     for (unsigned i = 1; i < numVersionReturned; i++) {
318       setValueMapping(it.first, newForOp->getResult(yieldOperands.size()),
319                       version++);
320       yieldOperands.push_back(
321           newForOp.getBody()->getArguments()[yieldOperands.size() + 1 +
322                                              newForOp.getNumInductionVars()]);
323     }
324     setValueMapping(it.first, newForOp->getResult(yieldOperands.size()),
325                     version++);
326     yieldOperands.push_back(mapping.lookupOrDefault(it.first));
327   }
328   // Map the yield operand to the forOp returned value.
329   for (const auto &retVal :
330        llvm::enumerate(forOp.getBody()->getTerminator()->getOperands())) {
331     Operation *def = retVal.value().getDefiningOp();
332     assert(def && "Only support loop carried dependencies of distance 1");
333     unsigned defStage = stages[def];
334     setValueMapping(forOp.getRegionIterArgs()[retVal.index()],
335                     newForOp->getResult(retVal.index()),
336                     maxStage - defStage + 1);
337   }
338   rewriter.create<scf::YieldOp>(forOp.getLoc(), yieldOperands);
339 }
340 
341 llvm::SmallVector<Value>
342 LoopPipelinerInternal::emitEpilogue(PatternRewriter &rewriter) {
343   llvm::SmallVector<Value> returnValues(forOp->getNumResults());
344   // Emit different versions of the induction variable. They will be
345   // removed by dead code if not used.
346   for (int64_t i = 0; i < maxStage; i++) {
347     Value newlastIter = rewriter.create<arith::ConstantIndexOp>(
348         forOp.getLoc(), lb + step * ((((ub - 1) - lb) / step) - i));
349     setValueMapping(forOp.getInductionVar(), newlastIter, maxStage - i);
350   }
351   // Emit `maxStage - 1` epilogue part that includes operations fro stages
352   // [i; maxStage].
353   for (int64_t i = 1; i <= maxStage; i++) {
354     for (Operation *op : opOrder) {
355       if (stages[op] < i)
356         continue;
357       Operation *newOp = rewriter.clone(*op);
358       for (unsigned opIdx = 0; opIdx < op->getNumOperands(); opIdx++) {
359         auto it = valueMapping.find(op->getOperand(opIdx));
360         if (it != valueMapping.end()) {
361           Value v = it->second[maxStage - stages[op] + i];
362           assert(v);
363           newOp->setOperand(opIdx, v);
364         }
365       }
366       for (unsigned destId : llvm::seq(unsigned(0), op->getNumResults())) {
367         setValueMapping(op->getResult(destId), newOp->getResult(destId),
368                         maxStage - stages[op] + i);
369         // If the value is a loop carried dependency update the loop argument
370         // mapping and keep track of the last version to replace the original
371         // forOp uses.
372         for (OpOperand &operand :
373              forOp.getBody()->getTerminator()->getOpOperands()) {
374           if (operand.get() != op->getResult(destId))
375             continue;
376           unsigned version = maxStage - stages[op] + i + 1;
377           // If the version is greater than maxStage it means it maps to the
378           // original forOp returned value.
379           if (version > maxStage) {
380             returnValues[operand.getOperandNumber()] = newOp->getResult(destId);
381             continue;
382           }
383           setValueMapping(forOp.getRegionIterArgs()[operand.getOperandNumber()],
384                           newOp->getResult(destId), version);
385         }
386       }
387     }
388   }
389   return returnValues;
390 }
391 
392 void LoopPipelinerInternal::setValueMapping(Value key, Value el, int64_t idx) {
393   auto it = valueMapping.find(key);
394   // If the value is not in the map yet add a vector big enough to store all
395   // versions.
396   if (it == valueMapping.end())
397     it =
398         valueMapping
399             .insert(std::make_pair(key, llvm::SmallVector<Value>(maxStage + 1)))
400             .first;
401   it->second[idx] = el;
402 }
403 
404 /// Generate a pipelined version of the scf.for loop based on the schedule given
405 /// as option. This applies the mechanical transformation of changing the loop
406 /// and generating the prologue/epilogue for the pipelining and doesn't make any
407 /// decision regarding the schedule.
408 /// Based on the option the loop is split into several stages.
409 /// The transformation assumes that the scheduling given by user is valid.
410 /// For example if we break a loop into 3 stages named S0, S1, S2 we would
411 /// generate the following code with the number in parenthesis the iteration
412 /// index:
413 /// S0(0)                        // Prologue
414 /// S0(1) S1(0)                  // Prologue
415 /// scf.for %I = %C0 to %N - 2 {
416 ///  S0(I+2) S1(I+1) S2(I)       // Pipelined kernel
417 /// }
418 /// S1(N) S2(N-1)                // Epilogue
419 /// S2(N)                        // Epilogue
420 struct ForLoopPipelining : public OpRewritePattern<ForOp> {
421   ForLoopPipelining(const PipeliningOption &options, MLIRContext *context)
422       : OpRewritePattern<ForOp>(context), options(options) {}
423   LogicalResult matchAndRewrite(ForOp forOp,
424                                 PatternRewriter &rewriter) const override {
425 
426     LoopPipelinerInternal pipeliner;
427     if (!pipeliner.initializeLoopInfo(forOp, options))
428       return failure();
429 
430     // 1. Emit prologue.
431     pipeliner.emitPrologue(rewriter);
432 
433     // 2. Track values used across stages. When a value cross stages it will
434     // need to be passed as loop iteration arguments.
435     // We first collect the values that are used in a different stage than where
436     // they are defined.
437     llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
438         crossStageValues = pipeliner.analyzeCrossStageValues();
439 
440     // Mapping between original loop values used cross stage and the block
441     // arguments associated after pipelining. A Value may map to several
442     // arguments if its liverange spans across more than 2 stages.
443     llvm::DenseMap<std::pair<Value, unsigned>, unsigned> loopArgMap;
444     // 3. Create the new kernel loop and return the block arguments mapping.
445     ForOp newForOp =
446         pipeliner.createKernelLoop(crossStageValues, rewriter, loopArgMap);
447     // Create the kernel block, order ops based on user choice and remap
448     // operands.
449     pipeliner.createKernel(newForOp, crossStageValues, loopArgMap, rewriter);
450 
451     // 4. Emit the epilogue after the new forOp.
452     rewriter.setInsertionPointAfter(newForOp);
453     llvm::SmallVector<Value> returnValues = pipeliner.emitEpilogue(rewriter);
454 
455     // 5. Erase the original loop and replace the uses with the epilogue output.
456     if (forOp->getNumResults() > 0)
457       rewriter.replaceOp(forOp, returnValues);
458     else
459       rewriter.eraseOp(forOp);
460 
461     return success();
462   }
463 
464 protected:
465   PipeliningOption options;
466 };
467 
468 } // namespace
469 
470 void mlir::scf::populateSCFLoopPipeliningPatterns(
471     RewritePatternSet &patterns, const PipeliningOption &options) {
472   patterns.add<ForLoopPipelining>(options, patterns.getContext());
473 }
474