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