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