xref: /llvm-project/mlir/lib/Dialect/Affine/Transforms/LoopTiling.cpp (revision 430b47a17d2281bd566fc1aac19de80b99e6f0c6)
1 //===- LoopTiling.cpp --- Loop tiling pass ------------------------------*-===//
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 a pass to tile loop nests.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Analysis/AffineAnalysis.h"
15 #include "mlir/Analysis/AffineStructures.h"
16 #include "mlir/Analysis/LoopAnalysis.h"
17 #include "mlir/Analysis/Utils.h"
18 #include "mlir/Dialect/Affine/IR/AffineOps.h"
19 #include "mlir/Dialect/Affine/IR/AffineValueMap.h"
20 #include "mlir/Dialect/Affine/Passes.h"
21 #include "mlir/IR/BlockAndValueMapping.h"
22 #include "mlir/IR/Builders.h"
23 #include "mlir/Transforms/LoopUtils.h"
24 #include "mlir/Transforms/Utils.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 using namespace mlir;
28 
29 #define DEBUG_TYPE "affine-loop-tile"
30 
31 namespace {
32 
33 /// A pass to perform loop tiling on all suitable loop nests of a Function.
34 struct LoopTiling : public AffineLoopTilingBase<LoopTiling> {
35   LoopTiling() = default;
36   explicit LoopTiling(uint64_t cacheSizeBytes, bool avoidMaxMinBounds = true)
37       : avoidMaxMinBounds(avoidMaxMinBounds) {
38     this->cacheSizeInKiB = cacheSizeBytes / 1024;
39   }
40 
41   void runOnFunction() override;
42   void getTileSizes(ArrayRef<AffineForOp> band,
43                     SmallVectorImpl<unsigned> *tileSizes);
44 
45   // Default tile size if nothing is provided.
46   constexpr static unsigned kDefaultTileSize = 4;
47 
48   // If true, tile sizes are set to avoid max/min in bounds if possible.
49   bool avoidMaxMinBounds = true;
50 };
51 
52 } // end anonymous namespace
53 
54 /// Creates a pass to perform loop tiling on all suitable loop nests of a
55 /// Function.
56 std::unique_ptr<OperationPass<FuncOp>>
57 mlir::createLoopTilingPass(uint64_t cacheSizeBytes) {
58   return std::make_unique<LoopTiling>(cacheSizeBytes);
59 }
60 std::unique_ptr<OperationPass<FuncOp>> mlir::createLoopTilingPass() {
61   return std::make_unique<LoopTiling>();
62 }
63 
64 // Move the loop body of AffineForOp 'src' from 'src' into the specified
65 // location in destination's body, ignoring the terminator.
66 static inline void moveLoopBody(AffineForOp src, AffineForOp dest,
67                                 Block::iterator loc) {
68   auto &insts = src.getBody()->getOperations();
69   dest.getBody()->getOperations().splice(loc, insts, insts.begin(),
70                                          std::prev(insts.end()));
71 }
72 
73 // Move the loop body of AffineForOp 'src' from 'src' to the start of dest's
74 // body.
75 static inline void moveLoopBody(AffineForOp src, AffineForOp dest) {
76   moveLoopBody(src, dest, dest.getBody()->begin());
77 }
78 
79 /// Constructs and sets new loop bounds after tiling for the case of
80 /// hyper-rectangular index sets, where the bounds of one dimension do not
81 /// depend on other dimensions. Bounds of each dimension can thus be treated
82 /// independently, and deriving the new bounds is much simpler and faster
83 /// than for the case of tiling arbitrary polyhedral shapes.
84 static void
85 constructTiledIndexSetHyperRect(MutableArrayRef<AffineForOp> origLoops,
86                                 MutableArrayRef<AffineForOp> newLoops,
87                                 ArrayRef<unsigned> tileSizes) {
88   assert(!origLoops.empty());
89   assert(origLoops.size() == tileSizes.size());
90 
91   OpBuilder b(origLoops[0].getOperation());
92   unsigned width = origLoops.size();
93 
94   // Bounds for tile space loops.
95   for (unsigned i = 0; i < width; i++) {
96     OperandRange newLbOperands = origLoops[i].getLowerBoundOperands();
97     OperandRange newUbOperands = origLoops[i].getUpperBoundOperands();
98     newLoops[i].setLowerBound(newLbOperands, origLoops[i].getLowerBoundMap());
99     newLoops[i].setUpperBound(newUbOperands, origLoops[i].getUpperBoundMap());
100     newLoops[i].setStep(tileSizes[i]);
101   }
102   // Bounds for intra-tile loops.
103   for (unsigned i = 0; i < width; i++) {
104     int64_t largestDiv = getLargestDivisorOfTripCount(origLoops[i]);
105     auto mayBeConstantCount = getConstantTripCount(origLoops[i]);
106     // The lower bound is just the tile-space loop.
107     AffineMap lbMap = b.getDimIdentityMap();
108     newLoops[width + i].setLowerBound(
109         /*operands=*/newLoops[i].getInductionVar(), lbMap);
110 
111     // Set the upper bound.
112     if (mayBeConstantCount && mayBeConstantCount.getValue() < tileSizes[i]) {
113       // Trip count is less than the tile size: upper bound is lower bound +
114       // trip count.
115       auto ubMap = b.getSingleDimShiftAffineMap(mayBeConstantCount.getValue());
116       newLoops[width + i].setUpperBound(
117           /*operands=*/newLoops[i].getInductionVar(), ubMap);
118     } else if (largestDiv % tileSizes[i] != 0) {
119       // Intra-tile loop ii goes from i to min(i + tileSize, ub_i).
120       // Construct the upper bound map; the operands are the original operands
121       // with 'i' (tile-space loop) appended to it. The new upper bound map is
122       // the original one with an additional expression i + tileSize appended.
123 
124       // Add dim operands from original upper bound.
125       SmallVector<Value, 4> ubOperands;
126       auto ub = origLoops[i].getUpperBound();
127       ubOperands.reserve(ub.getNumOperands() + 1);
128       auto origUbMap = ub.getMap();
129       for (unsigned j = 0, e = origUbMap.getNumDims(); j < e; ++j)
130         ubOperands.push_back(ub.getOperand(j));
131 
132       // Add dim operand for new loop upper bound.
133       ubOperands.push_back(newLoops[i].getInductionVar());
134 
135       // Add symbol operands from original upper bound.
136       for (unsigned j = 0, e = origUbMap.getNumSymbols(); j < e; ++j)
137         ubOperands.push_back(ub.getOperand(origUbMap.getNumDims() + j));
138 
139       SmallVector<AffineExpr, 4> boundExprs;
140       boundExprs.reserve(1 + origUbMap.getNumResults());
141       auto dim = b.getAffineDimExpr(origUbMap.getNumDims());
142       // The new upper bound map is the original one with an additional
143       // expression i + tileSize appended.
144       boundExprs.push_back(dim + tileSizes[i]);
145       boundExprs.append(origUbMap.getResults().begin(),
146                         origUbMap.getResults().end());
147       auto ubMap =
148           AffineMap::get(origUbMap.getNumDims() + 1, origUbMap.getNumSymbols(),
149                          boundExprs, b.getContext());
150       newLoops[width + i].setUpperBound(/*operands=*/ubOperands, ubMap);
151     } else {
152       // No need of the min expression.
153       auto dim = b.getAffineDimExpr(0);
154       auto ubMap = AffineMap::get(1, 0, dim + tileSizes[i]);
155       newLoops[width + i].setUpperBound(newLoops[i].getInductionVar(), ubMap);
156     }
157   }
158 }
159 
160 /// This function checks whether hyper-rectangular loop tiling of the nest
161 /// represented by `origLoops` is valid. The validity condition is from Irigoin
162 /// and Triolet, which states that two tiles cannot depend on each other. We
163 /// simplify such condition to just checking whether there is any negative
164 /// dependence direction, since we have the prior knowledge that the tiling
165 /// results will be hyper-rectangles, which are scheduled in the
166 /// lexicographically increasing order on the vector of loop indices. This
167 /// function will return failure when any dependence component is negative along
168 /// any of `origLoops`.
169 static LogicalResult
170 checkTilingLegality(MutableArrayRef<mlir::AffineForOp> origLoops) {
171   assert(!origLoops.empty() && "no original loops provided");
172 
173   // We first find out all dependences we intend to check.
174   SmallVector<Operation *, 8> loadAndStoreOps;
175   origLoops[0].getOperation()->walk([&](Operation *op) {
176     if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op))
177       loadAndStoreOps.push_back(op);
178   });
179 
180   unsigned numOps = loadAndStoreOps.size();
181   unsigned numLoops = origLoops.size();
182   FlatAffineConstraints dependenceConstraints;
183   for (unsigned d = 1; d <= numLoops + 1; ++d) {
184     for (unsigned i = 0; i < numOps; ++i) {
185       Operation *srcOp = loadAndStoreOps[i];
186       MemRefAccess srcAccess(srcOp);
187       for (unsigned j = 0; j < numOps; ++j) {
188         Operation *dstOp = loadAndStoreOps[j];
189         MemRefAccess dstAccess(dstOp);
190 
191         SmallVector<DependenceComponent, 2> depComps;
192         dependenceConstraints.reset();
193         DependenceResult result = checkMemrefAccessDependence(
194             srcAccess, dstAccess, d, &dependenceConstraints, &depComps);
195 
196         // Skip if there is no dependence in this case.
197         if (!hasDependence(result))
198           continue;
199 
200         // Check whether there is any negative direction vector in the
201         // dependence components found above, which means that dependence is
202         // violated by the default hyper-rect tiling method.
203         LLVM_DEBUG(llvm::dbgs() << "Checking whether tiling legality violated "
204                                    "for dependence at depth: "
205                                 << Twine(d) << " between:\n";);
206         LLVM_DEBUG(srcAccess.opInst->dump(););
207         LLVM_DEBUG(dstAccess.opInst->dump(););
208         for (unsigned k = 0, e = depComps.size(); k < e; k++) {
209           DependenceComponent depComp = depComps[k];
210           if (depComp.lb.hasValue() && depComp.ub.hasValue() &&
211               depComp.lb.getValue() < depComp.ub.getValue() &&
212               depComp.ub.getValue() < 0) {
213             LLVM_DEBUG(llvm::dbgs()
214                        << "Dependence component lb = "
215                        << Twine(depComp.lb.getValue())
216                        << " ub = " << Twine(depComp.ub.getValue())
217                        << " is negative  at depth: " << Twine(d)
218                        << " and thus violates the legality rule.\n");
219             return failure();
220           }
221         }
222       }
223     }
224   }
225 
226   return success();
227 }
228 /// Tiles the specified band of perfectly nested loops creating tile-space loops
229 /// and intra-tile loops. A band is a contiguous set of loops.
230 //  TODO: handle non hyper-rectangular spaces.
231 LogicalResult
232 mlir::tilePerfectlyNested(MutableArrayRef<AffineForOp> input,
233                           ArrayRef<unsigned> tileSizes,
234                           SmallVectorImpl<AffineForOp> *tiledNest) {
235   // Check if the supplied for op's are all successively nested.
236   assert(!input.empty() && "no loops in input band");
237   assert(input.size() == tileSizes.size() && "Too few/many tile sizes");
238 
239   assert(isPerfectlyNested(input) && "input loops not perfectly nested");
240 
241   auto origLoops = input;
242 
243   // Perform tiling legality test.
244   if (failed(checkTilingLegality(origLoops)))
245     origLoops[0].emitRemark("tiled code is illegal due to dependences");
246 
247   AffineForOp rootAffineForOp = origLoops[0];
248   auto loc = rootAffineForOp.getLoc();
249   // Note that width is at least one since band isn't empty.
250   unsigned width = input.size();
251 
252   SmallVector<AffineForOp, 6> tiledLoops(2 * width);
253 
254   // The outermost among the loops as we add more..
255   auto *topLoop = rootAffineForOp.getOperation();
256   AffineForOp innermostPointLoop;
257 
258   // Add intra-tile (or point) loops.
259   for (unsigned i = 0; i < width; i++) {
260     OpBuilder b(topLoop);
261     // Loop bounds will be set later.
262     auto pointLoop = b.create<AffineForOp>(loc, 0, 0);
263     pointLoop.getBody()->getOperations().splice(
264         pointLoop.getBody()->begin(), topLoop->getBlock()->getOperations(),
265         topLoop);
266     tiledLoops[2 * width - 1 - i] = pointLoop;
267     topLoop = pointLoop.getOperation();
268     if (i == 0)
269       innermostPointLoop = pointLoop;
270   }
271 
272   // Add tile space loops;
273   for (unsigned i = width; i < 2 * width; i++) {
274     OpBuilder b(topLoop);
275     // Loop bounds will be set later.
276     auto tileSpaceLoop = b.create<AffineForOp>(loc, 0, 0);
277     tileSpaceLoop.getBody()->getOperations().splice(
278         tileSpaceLoop.getBody()->begin(), topLoop->getBlock()->getOperations(),
279         topLoop);
280     tiledLoops[2 * width - i - 1] = tileSpaceLoop;
281     topLoop = tileSpaceLoop.getOperation();
282   }
283 
284   // Move the loop body of the original nest to the new one.
285   moveLoopBody(origLoops.back(), innermostPointLoop);
286 
287   SmallVector<Value, 8> origLoopIVs;
288   extractForInductionVars(input, &origLoopIVs);
289 
290   FlatAffineConstraints cst;
291   SmallVector<Operation *, 8> ops;
292   ops.reserve(input.size());
293   for (AffineForOp forOp : input)
294     ops.push_back(forOp);
295   getIndexSet(ops, &cst);
296   if (!cst.isHyperRectangular(0, width)) {
297     rootAffineForOp.emitError("tiled code generation unimplemented for the "
298                               "non-hyperrectangular case");
299     return failure();
300   }
301 
302   constructTiledIndexSetHyperRect(origLoops, tiledLoops, tileSizes);
303 
304   // Replace original IVs with intra-tile loop IVs.
305   for (unsigned i = 0; i < width; i++)
306     origLoopIVs[i].replaceAllUsesWith(tiledLoops[i + width].getInductionVar());
307 
308   // Erase the old loop nest.
309   rootAffineForOp.erase();
310 
311   if (tiledNest)
312     *tiledNest = std::move(tiledLoops);
313 
314   return success();
315 }
316 
317 // Identify valid and profitable bands of loops to tile. This is currently just
318 // a temporary placeholder to test the mechanics of tiled code generation.
319 // Returns all maximal outermost perfect loop nests to tile.
320 static void getTileableBands(FuncOp f,
321                              std::vector<SmallVector<AffineForOp, 6>> *bands) {
322   // Get maximal perfect nest of 'affine.for' insts starting from root
323   // (inclusive).
324   auto getMaximalPerfectLoopNest = [&](AffineForOp root) {
325     SmallVector<AffineForOp, 6> band;
326     getPerfectlyNestedLoops(band, root);
327     bands->push_back(band);
328   };
329 
330   for (auto &block : f)
331     for (auto &op : block)
332       if (auto forOp = dyn_cast<AffineForOp>(op))
333         getMaximalPerfectLoopNest(forOp);
334 }
335 
336 /// Reduces each tile size to the largest divisor of the corresponding trip
337 /// count (if the trip count is known).
338 static void adjustToDivisorsOfTripCounts(ArrayRef<AffineForOp> band,
339                                          SmallVectorImpl<unsigned> *tileSizes) {
340   assert(band.size() == tileSizes->size() && "invalid tile size count");
341   for (unsigned i = 0, e = band.size(); i < e; i++) {
342     unsigned &tSizeAdjusted = (*tileSizes)[i];
343     auto mayConst = getConstantTripCount(band[i]);
344     if (!mayConst)
345       continue;
346     // Adjust the tile size to largest factor of the trip count less than
347     // tSize.
348     uint64_t constTripCount = mayConst.getValue();
349     if (constTripCount > 1 && tSizeAdjusted > constTripCount / 2)
350       tSizeAdjusted = constTripCount / 2;
351     while (constTripCount % tSizeAdjusted != 0)
352       tSizeAdjusted--;
353   }
354 }
355 
356 // Returns tile sizes to use. Checks CL options; if none are specified, sets it
357 // based on a simple model that looks at the memory footprint and determines
358 // tile sizes assuming identity accesses / 1:1 tile size proportional footprint
359 // along each of the dimensions being tiled.
360 // TODO: evolve this model. Tile size determination is a large area
361 // to play with in general.
362 void LoopTiling::getTileSizes(ArrayRef<AffineForOp> band,
363                               SmallVectorImpl<unsigned> *tileSizes) {
364   if (band.empty())
365     return;
366 
367   // Use command-line tileSize for all loops if specified.
368   if (tileSize) {
369     tileSizes->assign(band.size(), tileSize);
370     return;
371   }
372 
373   // Use tileSizes and fill them with default tile size if it's short.
374   if (!this->tileSizes.empty()) {
375     tileSizes->assign(this->tileSizes.begin(), this->tileSizes.end());
376     tileSizes->resize(band.size(), kDefaultTileSize);
377     return;
378   }
379   tileSizes->resize(band.size());
380 
381   // The first loop in the band.
382   auto rootForOp = band[0];
383   (void)rootForOp;
384 
385   // Obtain memory footprint and set tile sizes so that a tile fits in
386   // the cache size. This is an approximation with the assumption that the
387   // footprint increases with the tile size linearly in that dimension (i.e.,
388   // assumes one-to-one access function).
389   auto fp = getMemoryFootprintBytes(band[0], 0);
390   if (!fp) {
391     // Fill with default tile sizes if footprint is unknown.
392     std::fill(tileSizes->begin(), tileSizes->end(),
393               LoopTiling::kDefaultTileSize);
394     if (avoidMaxMinBounds)
395       adjustToDivisorsOfTripCounts(band, tileSizes);
396     LLVM_DEBUG(
397         rootForOp.emitWarning("memory footprint unknown: using default tile "
398                               "sizes adjusted to trip count divisors"));
399     return;
400   }
401 
402   // Check how many times larger the cache size is when compared to footprint.
403   uint64_t cacheSizeBytes = cacheSizeInKiB * 1024;
404   uint64_t excessFactor = llvm::divideCeil(fp.getValue(), cacheSizeBytes);
405   if (excessFactor <= 1) {
406     // No need of any tiling - set tile size to 1.
407     std::fill(tileSizes->begin(), tileSizes->end(), 1);
408     return;
409   }
410 
411   // Divide all loops equally in an attempt to reduce footprint.
412   // TODO: this is approximate. Ideally, obtain reuse factor /
413   // profitability along each dimension and weight tile sizes based on that as
414   // one possible approach. Or compute a polynomial in tile sizes and solve for
415   // it.
416 
417   // For an n-d tileable band, compute the n^th root of the excess.
418   unsigned tSize =
419       static_cast<unsigned>(floorl(std::pow(excessFactor, 1.0 / band.size())));
420   // We'll keep a running product to determine the last tile size better.
421   unsigned cumulProductOfTileSizes = 1;
422   for (unsigned i = 0, e = band.size(); i < e; i++) {
423     if (i < e - 1)
424       (*tileSizes)[i] = tSize;
425     else
426       // Set last tile size to cover the balance.
427       (*tileSizes)[i] = std::max(
428           1U, static_cast<unsigned>(excessFactor / cumulProductOfTileSizes));
429     cumulProductOfTileSizes *= (*tileSizes)[i];
430   }
431   if (avoidMaxMinBounds)
432     adjustToDivisorsOfTripCounts(band, tileSizes);
433 }
434 
435 void LoopTiling::runOnFunction() {
436   // Bands of loops to tile.
437   std::vector<SmallVector<AffineForOp, 6>> bands;
438   getTileableBands(getFunction(), &bands);
439 
440   // Tile each band.
441   for (auto &band : bands) {
442     // Set up tile sizes; fill missing tile sizes at the end with default tile
443     // size or tileSize if one was provided.
444     SmallVector<unsigned, 6> tileSizes;
445     getTileSizes(band, &tileSizes);
446     if (llvm::DebugFlag) {
447       auto diag = band[0].emitRemark("using tile sizes [");
448       for (auto tSize : tileSizes)
449         diag << tSize << ' ';
450       diag << "]\n";
451     }
452     SmallVector<AffineForOp, 6> tiledNest;
453     if (failed(tilePerfectlyNested(band, tileSizes, &tiledNest)))
454       return signalPassFailure();
455 
456     // Separate full and partial tiles.
457     if (separate) {
458       auto intraTileLoops =
459           MutableArrayRef<AffineForOp>(tiledNest).drop_front(band.size());
460       separateFullTiles(intraTileLoops);
461     }
462   }
463 }
464 
465 constexpr unsigned LoopTiling::kDefaultTileSize;
466