1 //===- Utils.cpp - Utilities to support the Linalg dialect ----------------===// 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 utilities for the Linalg dialect. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/Linalg/Utils/Utils.h" 14 15 #include "mlir/Analysis/AffineStructures.h" 16 #include "mlir/Analysis/SliceAnalysis.h" 17 #include "mlir/Dialect/Affine/IR/AffineOps.h" 18 #include "mlir/Dialect/Affine/IR/AffineValueMap.h" 19 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 20 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 21 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h" 22 #include "mlir/Dialect/MemRef/IR/MemRef.h" 23 #include "mlir/Dialect/SCF/SCF.h" 24 #include "mlir/Dialect/StandardOps/IR/Ops.h" 25 #include "mlir/Dialect/StandardOps/Utils/Utils.h" 26 #include "mlir/Dialect/Tensor/IR/Tensor.h" 27 #include "mlir/Dialect/Utils/StaticValueUtils.h" 28 #include "mlir/IR/AffineExpr.h" 29 #include "mlir/IR/AffineExprVisitor.h" 30 #include "mlir/IR/AffineMap.h" 31 #include "mlir/IR/Matchers.h" 32 #include "mlir/IR/OpImplementation.h" 33 #include "mlir/Pass/Pass.h" 34 #include "mlir/Transforms/LoopUtils.h" 35 #include "llvm/ADT/TypeSwitch.h" 36 #include "llvm/Support/Debug.h" 37 38 #define DEBUG_TYPE "linalg-utils" 39 40 using namespace mlir; 41 using namespace mlir::linalg; 42 using namespace mlir::scf; 43 44 static bool isZero(Value v) { 45 if (auto cst = v.getDefiningOp<arith::ConstantIndexOp>()) 46 return cst.value() == 0; 47 return false; 48 } 49 50 namespace { 51 52 // Helper visitor to determine whether an AffineExpr is tiled. 53 // This is achieved by traversing every AffineDimExpr with position `pos` and 54 // checking whether the corresponding `tileSizes[pos]` is non-zero. 55 // This also enforces only positive coefficients occur in multiplications. 56 // 57 // Example: 58 // `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0] 59 // 60 struct TileCheck : public AffineExprVisitor<TileCheck> { 61 TileCheck(ValueRange tileSizes) : isTiled(false), tileSizes(tileSizes) {} 62 63 void visitDimExpr(AffineDimExpr expr) { 64 isTiled |= !isZero(tileSizes[expr.getPosition()]); 65 } 66 void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) { 67 visit(expr.getLHS()); 68 visit(expr.getRHS()); 69 if (expr.getKind() == mlir::AffineExprKind::Mul) 70 assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 && 71 "nonpositive multiplying coefficient"); 72 } 73 bool isTiled; 74 ValueRange tileSizes; 75 }; 76 77 } // namespace 78 79 static bool isTiled(AffineExpr expr, ValueRange tileSizes) { 80 if (!expr) 81 return false; 82 TileCheck t(tileSizes); 83 t.visit(expr); 84 return t.isTiled; 85 } 86 87 // Checks whether the `map varies with respect to a non-zero `tileSize`. 88 static bool isTiled(AffineMap map, ValueRange tileSizes) { 89 if (!map) 90 return false; 91 for (unsigned r = 0; r < map.getNumResults(); ++r) 92 if (isTiled(map.getResult(r), tileSizes)) 93 return true; 94 return false; 95 } 96 97 Optional<RegionMatcher::BinaryOpKind> 98 RegionMatcher::matchAsScalarBinaryOp(GenericOp op) { 99 auto ®ion = op.region(); 100 if (!llvm::hasSingleElement(region)) 101 return llvm::None; 102 103 Block &block = region.front(); 104 if (block.getNumArguments() != 2 || 105 !block.getArgument(0).getType().isSignlessIntOrFloat() || 106 !block.getArgument(1).getType().isSignlessIntOrFloat()) 107 return llvm::None; 108 109 auto &ops = block.getOperations(); 110 if (!llvm::hasSingleElement(block.without_terminator())) 111 return llvm::None; 112 113 using mlir::matchers::m_Val; 114 auto a = m_Val(block.getArgument(0)); 115 auto b = m_Val(block.getArgument(1)); 116 117 auto addPattern = m_Op<linalg::YieldOp>(m_Op<arith::AddIOp>(a, b)); 118 if (addPattern.match(&ops.back())) 119 return BinaryOpKind::IAdd; 120 121 return llvm::None; 122 } 123 124 /// Explicit instantiation of loop nest generator for different loop types. 125 template struct mlir::linalg::GenerateLoopNest<scf::ForOp>; 126 template struct mlir::linalg::GenerateLoopNest<scf::ParallelOp>; 127 template struct mlir::linalg::GenerateLoopNest<AffineForOp>; 128 template struct mlir::linalg::GenerateLoopNest<TiledLoopOp>; 129 130 /// Given a list of subview ranges, extract individual values for lower, upper 131 /// bounds and steps and put them into the corresponding vectors. 132 static void unpackRanges(ArrayRef<Range> ranges, SmallVectorImpl<Value> &lbs, 133 SmallVectorImpl<Value> &ubs, 134 SmallVectorImpl<Value> &steps) { 135 for (Range range : ranges) { 136 lbs.emplace_back(range.offset); 137 ubs.emplace_back(range.size); 138 steps.emplace_back(range.stride); 139 } 140 } 141 142 namespace mlir { 143 namespace linalg { 144 145 bool isPermutation(ArrayRef<int64_t> permutation) { 146 // Count the number of appearances for all indices. 147 SmallVector<int64_t> indexCounts(permutation.size(), 0); 148 for (auto index : permutation) { 149 // Exit if the index is out-of-range. 150 if (index < 0 || index >= static_cast<int64_t>(permutation.size())) 151 return false; 152 indexCounts[index]++; 153 } 154 // Return true if all indices appear once. 155 return count(indexCounts, 1) == static_cast<int64_t>(permutation.size()); 156 } 157 158 /// Helper function that creates a memref::DimOp or tensor::DimOp depending on 159 /// the type of `source`. 160 Value createOrFoldDimOp(OpBuilder &b, Location loc, Value source, int64_t dim) { 161 if (source.getType().isa<UnrankedMemRefType, MemRefType>()) 162 return b.createOrFold<memref::DimOp>(loc, source, dim); 163 if (source.getType().isa<UnrankedTensorType, RankedTensorType>()) 164 return b.createOrFold<tensor::DimOp>(loc, source, dim); 165 llvm_unreachable("Expected MemRefType or TensorType"); 166 } 167 168 /// Given an operation, retrieves the value of each dynamic dimension through 169 /// constructing the necessary DimOp operators. 170 SmallVector<Value, 4> getDynOperands(Location loc, Value val, OpBuilder &b) { 171 SmallVector<Value, 4> dynOperands; 172 auto shapedType = val.getType().cast<ShapedType>(); 173 for (auto dim : llvm::enumerate(shapedType.getShape())) { 174 if (dim.value() == ShapedType::kDynamicSize) 175 dynOperands.push_back(createOrFoldDimOp(b, loc, val, dim.index())); 176 } 177 return dynOperands; 178 } 179 180 void getUpperBoundForIndex(Value value, AffineMap &boundMap, 181 SmallVectorImpl<Value> &boundOperands) { 182 // Initialize `boundMap` and `boundOperands` to the identity returning 183 // `value`. This combination is the default result of the method if no 184 // simplification is possible. 185 assert(value.getType().isIndex() && "expect value to have index type"); 186 boundMap = AffineMap::getMultiDimIdentityMap(1, value.getContext()); 187 boundOperands.assign({value}); 188 canonicalizeMapAndOperands(&boundMap, &boundOperands); 189 190 // Continue only if there is an affine index computation to simplify. 191 Operation *definingOp = value.getDefiningOp(); 192 if (!definingOp || !isa<AffineApplyOp, AffineMinOp>(definingOp)) 193 return; 194 195 // Get the backward slice containing the affine index computation. 196 SetVector<Operation *> backwardSlice; 197 getBackwardSlice(definingOp, &backwardSlice, [](Operation *op) { 198 return isa<AffineApplyOp, AffineMinOp>(op); 199 }); 200 backwardSlice.insert(definingOp); 201 202 // Setup a system of affine constraints that describe the index computation. 203 FlatAffineValueConstraints constraints; 204 205 // Helper to find or create an identifier for the given value. 206 auto findOrCreateId = [&](Value value) { 207 if (!constraints.containsId(value)) { 208 constraints.appendDimId(value); 209 return true; 210 } 211 unsigned pos; 212 constraints.findId(value, &pos); 213 return pos < constraints.getNumDimIds(); 214 }; 215 // Helper to get the position for the given value. 216 auto getPosition = [&](Value value) { 217 unsigned pos; 218 bool exists = constraints.findId(value, &pos); 219 (void)exists; 220 assert(exists && "expect to find the identifier"); 221 return pos; 222 }; 223 224 // Add the affine operations in `backwardSlice` to the constraints. 225 for (Operation *op : llvm::reverse(backwardSlice)) { 226 // Add an identifier for all op results and operands. 227 if (!(llvm::all_of(op->getResults(), findOrCreateId) && 228 llvm::all_of(op->getOperands(), findOrCreateId))) 229 return; 230 // Add AffineApplyOps to the constraints. 231 if (auto applyOp = dyn_cast<AffineApplyOp>(op)) { 232 AffineValueMap valueMap(applyOp.getAffineMap(), applyOp.getOperands(), 233 applyOp.getResult()); 234 if (failed(constraints.composeMap(&valueMap))) 235 return; 236 continue; 237 } 238 // Add AffineMinOps to the constraints. 239 auto minOp = cast<AffineMinOp>(op); 240 AffineMap map = constraints.computeAlignedMap(minOp.getAffineMap(), 241 minOp.getOperands()); 242 if (failed(constraints.addBound(FlatAffineConstraints::UB, 243 getPosition(minOp.getResult()), map))) 244 return; 245 } 246 247 // Obtain an upper bound for the affine index computation by projecting out 248 // all temporary results and expressing the upper bound for `value` in terms 249 // of the terminals of the index computation. 250 SmallVector<AffineMap> lowerBounds(1), upperBounds(1); 251 constraints.getSliceBounds(getPosition(value), 1, value.getContext(), 252 &lowerBounds, &upperBounds); 253 254 // Verify `upperBounds[0]` is valid and has at least one result. 255 if (!upperBounds[0] || upperBounds[0].getNumResults() == 0) 256 return; 257 258 // Set `boundMap` and `boundOperands` to the computed upper bound. 259 boundMap = upperBounds[0]; 260 constraints.getAllValues(&boundOperands); 261 erase_value(boundOperands, value); 262 canonicalizeMapAndOperands(&boundMap, &boundOperands); 263 } 264 265 FailureOr<int64_t> getConstantUpperBoundForIndex(Value value) { 266 // Compute an upper bound for `value`. 267 AffineMap boundMap; 268 SmallVector<Value> boundOperands; 269 getUpperBoundForIndex(value, boundMap, boundOperands); 270 271 // Search the results of `boundMap` for constant upper bounds. 272 SmallVector<int64_t> constantBounds; 273 for (AffineExpr result : boundMap.getResults()) 274 if (auto constExpr = result.dyn_cast<AffineConstantExpr>()) 275 constantBounds.push_back(constExpr.getValue()); 276 277 // Return the minimal upper bound or failure if none is found. 278 if (constantBounds.empty()) 279 return failure(); 280 return *std::min_element(constantBounds.begin(), constantBounds.end()); 281 } 282 283 tensor::ExtractSliceOp makeComposedExtractSliceOp( 284 OpBuilder &b, Location loc, Value source, ArrayRef<OpFoldResult> offsets, 285 ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) { 286 assert(source && "expect source to be nonzero"); 287 288 // Do not fold if the producer is not an ExtractSliceOp. 289 auto producerOp = source.getDefiningOp<tensor::ExtractSliceOp>(); 290 if (!producerOp) 291 return b.create<tensor::ExtractSliceOp>(loc, source, offsets, sizes, 292 strides); 293 294 // Do not fold if the producer is rank reducing or if there are any non-unit 295 // strides. Supporting non-unit strides complicates the offset computation 296 // since the consumer offsets need to be multiplied by the producer strides. 297 // TODO: support non-unit strides once there are use cases. 298 SmallVector<OpFoldResult> allStrides = producerOp.getMixedStrides(); 299 allStrides.append(strides.begin(), strides.end()); 300 bool hasNonUnitStride = any_of(allStrides, [](OpFoldResult ofr) { 301 return getConstantIntValue(ofr) != static_cast<int64_t>(1); 302 }); 303 if (hasNonUnitStride || 304 producerOp.getSourceType().getRank() != 305 producerOp.getResult().getType().cast<ShapedType>().getRank()) 306 return b.create<tensor::ExtractSliceOp>(loc, source, offsets, sizes, 307 strides); 308 309 // Fold the producer by adding the offests and extracting the slice directly 310 // from the producer source tensor. 311 SmallVector<OpFoldResult> foldedOffsets(offsets.begin(), offsets.end()); 312 AffineExpr dim1, dim2; 313 bindDims(b.getContext(), dim1, dim2); 314 for (auto en : enumerate(producerOp.getMixedOffsets())) { 315 SmallVector<Value> offsetValues = { 316 getValueOrCreateConstantIndexOp(b, loc, foldedOffsets[en.index()]), 317 getValueOrCreateConstantIndexOp(b, loc, en.value())}; 318 foldedOffsets[en.index()] = 319 makeComposedAffineApply(b, loc, dim1 + dim2, offsetValues).getResult(); 320 } 321 return b.create<tensor::ExtractSliceOp>(loc, producerOp.source(), 322 foldedOffsets, sizes, strides); 323 } 324 325 /// Specialization to build an scf "for" nest. 326 template <> 327 void GenerateLoopNest<scf::ForOp>::doit( 328 OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp, 329 ArrayRef<Attribute> iteratorTypes, 330 function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange, 331 ValueRange)> 332 bodyBuilderFn, 333 Optional<LinalgLoopDistributionOptions> distributionOptions, 334 ArrayRef<StringRef> distributionTypes) { 335 SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands(); 336 // Create procInfo so it dominates loops, if appropriate. 337 SmallVector<ProcInfo, 4> procInfo; 338 SmallVector<DistributionMethod, 0> distributionMethod; 339 if (distributionOptions.hasValue()) { 340 // Collect loop ranges for parallel dimensions. 341 SmallVector<Range, 2> parallelLoopRanges; 342 for (auto iteratorType : enumerate(iteratorTypes)) 343 if (isParallelIterator(iteratorType.value())) 344 parallelLoopRanges.push_back(loopRanges[iteratorType.index()]); 345 346 // Get their distribution schemes. 347 distributionMethod = distributionOptions->distributionMethod; 348 if (distributionMethod.size() < parallelLoopRanges.size()) 349 parallelLoopRanges.resize(distributionMethod.size()); 350 procInfo = distributionOptions->procInfo(b, loc, parallelLoopRanges); 351 } 352 353 SmallVector<Value, 4> lbs, ubs, steps; 354 unpackRanges(loopRanges, lbs, ubs, steps); 355 LoopNest loopNest = mlir::scf::buildLoopNest( 356 b, loc, lbs, ubs, steps, iterArgInitValues, 357 [&](OpBuilder &b, Location loc, ValueRange ivs, ValueRange iterArgs) { 358 assert(iterArgs.size() == linalgOp.getOutputTensorOperands().size() && 359 "expect the number of output tensors and iter args to match"); 360 SmallVector<Value> operandValuesToUse = 361 linalgOp.getInputAndOutputOperands(); 362 if (!iterArgs.empty()) { 363 operandValuesToUse = linalgOp.getInputOperands(); 364 operandValuesToUse.append(iterArgs.begin(), iterArgs.end()); 365 } 366 return bodyBuilderFn(b, loc, ivs, operandValuesToUse); 367 }); 368 369 if (!distributionOptions || loopNest.loops.empty()) 370 return; 371 372 // Filter out scf.for loops that were created out of parallel dimensions. 373 SmallVector<scf::ForOp, 4> loops; 374 for (auto iteratorType : enumerate(iteratorTypes)) 375 if (isParallelIterator(iteratorType.value())) 376 loops.push_back(loopNest.loops[iteratorType.index()]); 377 378 // Distribute - only supports cyclic distribution for now. 379 for (auto it : llvm::zip(loops, procInfo, distributionMethod)) 380 if (std::get<2>(it) == DistributionMethod::Cyclic) 381 mapLoopToProcessorIds(std::get<0>(it), std::get<1>(it).procId, 382 std::get<1>(it).nprocs); 383 } 384 385 /// Specialization to build affine "for" nest. 386 template <> 387 void GenerateLoopNest<AffineForOp>::doit( 388 OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp, 389 ArrayRef<Attribute> iteratorTypes, 390 function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange, 391 ValueRange)> 392 bodyBuilderFn, 393 Optional<LinalgLoopDistributionOptions>, ArrayRef<StringRef>) { 394 SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands(); 395 assert(iterArgInitValues.empty() && "unexpected AffineForOp init values"); 396 SmallVector<Value, 4> lbs, ubs, steps; 397 unpackRanges(loopRanges, lbs, ubs, steps); 398 399 // Affine loops require constant steps. 400 SmallVector<int64_t, 4> constantSteps; 401 constantSteps.reserve(steps.size()); 402 for (Value v : steps) { 403 auto op = v.getDefiningOp<arith::ConstantIndexOp>(); 404 assert(op && "Affine loops require constant steps"); 405 constantSteps.push_back(op.value()); 406 } 407 408 mlir::buildAffineLoopNest(b, loc, lbs, ubs, constantSteps, 409 [&](OpBuilder &b, Location loc, ValueRange ivs) { 410 SmallVector<Value> operandValuesToUse = 411 linalgOp.getInputAndOutputOperands(); 412 bodyBuilderFn(b, loc, ivs, operandValuesToUse); 413 }); 414 } 415 416 /// Specialization to build an linalg.tiled_loop 417 template <> 418 void GenerateLoopNest<TiledLoopOp>::doit( 419 OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp, 420 ArrayRef<Attribute> iteratorTypes, 421 function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange, 422 ValueRange)> 423 bodyBuilderFn, 424 Optional<LinalgLoopDistributionOptions> distributionOptions, 425 ArrayRef<StringRef> distributionTypes) { 426 SmallVector<ProcInfo, 2> procInfo; 427 SmallVector<Value, 4> lbs, ubs, steps; 428 unpackRanges(loopRanges, lbs, ubs, steps); 429 430 auto wrappedBuilderFn = [&](OpBuilder &nestedBuilder, Location nestedLoc, 431 ValueRange ivs, ValueRange inputs, 432 ValueRange outputs) { 433 SmallVector<Value> operandValuesToUse = inputs; 434 operandValuesToUse.append(outputs.begin(), outputs.end()); 435 scf::ValueVector results = 436 bodyBuilderFn(nestedBuilder, nestedLoc, ivs, operandValuesToUse); 437 nestedBuilder.create<linalg::YieldOp>(nestedLoc, results); 438 }; 439 440 SmallVector<Value> inputOperands = linalgOp.getInputOperands(); 441 SmallVector<Value> outputOperands = linalgOp.getOutputOperands(); 442 auto tiledLoop = 443 b.create<TiledLoopOp>(loc, lbs, ubs, steps, inputOperands, outputOperands, 444 b.getArrayAttr(iteratorTypes), wrappedBuilderFn); 445 if (!distributionTypes.empty()) 446 tiledLoop.setDistributionTypes(b, distributionTypes); 447 } 448 449 /// Update the `lb`, `ub` and `step` to get per processor `lb`, `ub` and `step`. 450 void updateBoundsForCyclicDistribution(OpBuilder &b, Location loc, Value procId, 451 Value nprocs, Value &lb, Value &ub, 452 Value &step) { 453 AffineExpr d0, d1; 454 bindDims(b.getContext(), d0, d1); 455 AffineExpr s0 = getAffineSymbolExpr(0, b.getContext()); 456 lb = makeComposedAffineApply(b, loc, d0 + d1 * s0, {lb, procId, step}); 457 step = makeComposedAffineApply(b, loc, d0 * s0, {nprocs, step}); 458 } 459 460 /// Generates a loop nest consisting of scf.parallel and scf.for, depending 461 /// on the `iteratorTypes.` Consecutive parallel loops create a single 462 /// scf.parallel operation; each sequential loop creates a new scf.for 463 /// operation. The body of the innermost loop is populated by 464 /// `bodyBuilderFn` that accepts a range of induction variables for all 465 /// loops. `ivStorage` is used to store the partial list of induction 466 /// variables. 467 // TODO: this function can be made iterative instead. However, it 468 // will have at most as many recursive calls as nested loops, which rarely 469 // exceeds 10. 470 static void generateParallelLoopNest( 471 OpBuilder &b, Location loc, ValueRange lbs, ValueRange ubs, 472 ValueRange steps, ArrayRef<Attribute> iteratorTypes, 473 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn, 474 SmallVectorImpl<Value> &ivStorage, 475 ArrayRef<DistributionMethod> distributionMethod = {}) { 476 assert(lbs.size() == ubs.size()); 477 assert(lbs.size() == steps.size()); 478 assert(lbs.size() == iteratorTypes.size()); 479 480 // If there are no (more) loops to be generated, generate the body and be 481 // done with it. 482 if (iteratorTypes.empty()) { 483 bodyBuilderFn(b, loc, ivStorage); 484 return; 485 } 486 487 // Find the outermost parallel loops and drop their types from the list. 488 unsigned nLoops = iteratorTypes.size(); 489 unsigned nOuterPar = 490 nLoops - iteratorTypes.drop_while(isParallelIterator).size(); 491 492 // If there are no outer parallel loops, generate one sequential loop and 493 // recurse. Note that we wouldn't have dropped anything from `iteratorTypes` 494 // in this case. 495 if (nOuterPar == 0) { 496 LoopNest singleLoop = buildLoopNest( 497 b, loc, lbs.take_front(), ubs.take_front(), steps.take_front(), 498 [&](OpBuilder &b, Location loc, ValueRange ivs) { 499 ivStorage.append(ivs.begin(), ivs.end()); 500 generateParallelLoopNest(b, loc, lbs.drop_front(), ubs.drop_front(), 501 steps.drop_front(), 502 iteratorTypes.drop_front(), bodyBuilderFn, 503 ivStorage, distributionMethod); 504 }); 505 return; 506 } 507 if (distributionMethod.empty()) { 508 // Generate a single parallel loop-nest operation for all outermost 509 // parallel loops and recurse. 510 b.create<scf::ParallelOp>( 511 loc, lbs.take_front(nOuterPar), ubs.take_front(nOuterPar), 512 steps.take_front(nOuterPar), 513 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange localIvs) { 514 ivStorage.append(localIvs.begin(), localIvs.end()); 515 generateParallelLoopNest( 516 nestedBuilder, nestedLoc, lbs.drop_front(nOuterPar), 517 ubs.drop_front(nOuterPar), steps.drop_front(nOuterPar), 518 iteratorTypes.drop_front(nOuterPar), bodyBuilderFn, ivStorage, 519 (distributionMethod.size() < nOuterPar) 520 ? ArrayRef<DistributionMethod>() 521 : distributionMethod.drop_front(nOuterPar)); 522 }); 523 return; 524 } 525 526 // Process all consecutive similarly distributed loops simultaneously. 527 DistributionMethod methodToUse = distributionMethod[0]; 528 unsigned numProcessed = 1; 529 for (unsigned i = 1; i < nOuterPar && i < distributionMethod.size(); ++i) { 530 if (distributionMethod[i] != methodToUse) 531 break; 532 numProcessed++; 533 } 534 535 switch (methodToUse) { 536 case DistributionMethod::Cyclic: { 537 // Generate a single parallel loop-nest operation for all outermost 538 // parallel loops and recurse. 539 b.create<scf::ParallelOp>( 540 loc, lbs.take_front(numProcessed), ubs.take_front(numProcessed), 541 steps.take_front(numProcessed), 542 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange localIvs) { 543 ivStorage.append(localIvs.begin(), localIvs.end()); 544 generateParallelLoopNest( 545 nestedBuilder, nestedLoc, lbs.drop_front(numProcessed), 546 ubs.drop_front(numProcessed), steps.drop_front(numProcessed), 547 iteratorTypes.drop_front(numProcessed), bodyBuilderFn, ivStorage, 548 (distributionMethod.size() < numProcessed) 549 ? ArrayRef<DistributionMethod>() 550 : distributionMethod.drop_front(numProcessed)); 551 }); 552 return; 553 } 554 case DistributionMethod::CyclicNumProcsGeNumIters: { 555 // Check (for the processed loops) that the iteration is in-bounds. 556 ArithBuilder ab(b, loc); 557 Value cond = ab.slt(lbs[0], ubs[0]); 558 for (unsigned i = 1; i < numProcessed; ++i) 559 cond = ab._and(cond, ab.slt(lbs[i], ubs[i])); 560 ivStorage.append(lbs.begin(), std::next(lbs.begin(), numProcessed)); 561 b.create<scf::IfOp>(loc, cond, [&](OpBuilder &b, Location loc) { 562 generateParallelLoopNest( 563 b, loc, lbs.drop_front(numProcessed), ubs.drop_front(numProcessed), 564 steps.drop_front(numProcessed), 565 iteratorTypes.drop_front(numProcessed), bodyBuilderFn, ivStorage, 566 distributionMethod.drop_front(numProcessed)); 567 b.create<scf::YieldOp>(loc, ValueRange{}); 568 }); 569 return; 570 } 571 case DistributionMethod::CyclicNumProcsEqNumIters: 572 // No check/loops needed here. Set the `%iv` to be the `%lb` and proceed 573 // with inner loop generation. 574 ivStorage.append(lbs.begin(), std::next(lbs.begin(), numProcessed)); 575 generateParallelLoopNest( 576 b, loc, lbs.drop_front(numProcessed), ubs.drop_front(numProcessed), 577 steps.drop_front(numProcessed), iteratorTypes.drop_front(numProcessed), 578 bodyBuilderFn, ivStorage, distributionMethod.drop_front(numProcessed)); 579 return; 580 } 581 } 582 583 /// Specialization for generating a mix of parallel and sequential scf loops. 584 template <> 585 void GenerateLoopNest<scf::ParallelOp>::doit( 586 OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp, 587 ArrayRef<Attribute> iteratorTypes, 588 function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange, 589 ValueRange)> 590 bodyBuilderFn, 591 Optional<LinalgLoopDistributionOptions> distributionOptions, 592 ArrayRef<StringRef> distributionTypes) { 593 SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands(); 594 assert(iterArgInitValues.empty() && "unexpected ParallelOp init values"); 595 // This function may be passed more iterator types than ranges. 596 assert(iteratorTypes.size() >= loopRanges.size() && 597 "expected iterator type for all ranges"); 598 iteratorTypes = iteratorTypes.take_front(loopRanges.size()); 599 SmallVector<Value, 8> lbsStorage, ubsStorage, stepsStorage, ivs; 600 unsigned numLoops = iteratorTypes.size(); 601 ivs.reserve(numLoops); 602 lbsStorage.reserve(numLoops); 603 ubsStorage.reserve(numLoops); 604 stepsStorage.reserve(numLoops); 605 606 // Get the loop lb, ub, and step. 607 unpackRanges(loopRanges, lbsStorage, ubsStorage, stepsStorage); 608 609 // Modify the lb, ub, and step based on the distribution options. 610 SmallVector<DistributionMethod, 0> distributionMethod; 611 if (distributionOptions) { 612 auto &options = distributionOptions.getValue(); 613 distributionMethod.assign(distributionOptions->distributionMethod.begin(), 614 distributionOptions->distributionMethod.end()); 615 SmallVector<Range, 2> parallelLoopRanges; 616 for (auto iteratorType : enumerate(iteratorTypes)) { 617 if (isParallelIterator(iteratorType.value())) 618 parallelLoopRanges.push_back(loopRanges[iteratorType.index()]); 619 } 620 if (distributionMethod.size() < parallelLoopRanges.size()) 621 parallelLoopRanges.resize(distributionMethod.size()); 622 SmallVector<ProcInfo, 2> procInfo = 623 options.procInfo(b, loc, parallelLoopRanges); 624 unsigned index = 0; 625 for (auto iteratorType : enumerate(iteratorTypes)) { 626 if (index >= procInfo.size()) 627 break; 628 if (isParallelIterator(iteratorType.value())) { 629 unsigned i = iteratorType.index(); 630 updateBoundsForCyclicDistribution(b, loc, procInfo[index].procId, 631 procInfo[index].nprocs, lbsStorage[i], 632 ubsStorage[i], stepsStorage[i]); 633 index++; 634 } 635 } 636 } 637 ValueRange lbs(lbsStorage), ubs(ubsStorage), steps(stepsStorage); 638 generateParallelLoopNest( 639 b, loc, lbs, ubs, steps, iteratorTypes, 640 [&](OpBuilder &b, Location loc, ValueRange ivs) { 641 SmallVector<Value> operandValuesToUse = 642 linalgOp.getInputAndOutputOperands(); 643 bodyBuilderFn(b, loc, ivs, operandValuesToUse); 644 }, 645 ivs, distributionMethod); 646 647 assert(ivs.size() == iteratorTypes.size() && "did not generate enough loops"); 648 } 649 650 static Value fullyComposeAndAffineApply(OpBuilder &b, Location loc, 651 AffineExpr expr, ValueRange operands) { 652 AffineMap map = AffineMap::inferFromExprList({expr}).front(); 653 SmallVector<Value> normalizedOperands(operands.begin(), operands.end()); 654 mlir::fullyComposeAffineMapAndOperands(&map, &normalizedOperands); 655 canonicalizeMapAndOperands(&map, &normalizedOperands); 656 return b.createOrFold<AffineApplyOp>(loc, map, normalizedOperands); 657 } 658 659 Value makeTiledShape(OpBuilder &builder, Location loc, Value valueToTile, 660 ValueRange tileSizes, AffineMap map, ValueRange lbs, 661 ValueRange ubs, ValueRange subShapeSizes) { 662 auto shapedType = valueToTile.getType().dyn_cast<ShapedType>(); 663 assert(shapedType && "only shaped types can be tiled"); 664 ArrayRef<int64_t> shape = shapedType.getShape(); 665 int64_t rank = shapedType.getRank(); 666 667 // Construct a new subview / extract_slice for the tile. 668 SmallVector<OpFoldResult, 4> offsets, sizes, strides; 669 offsets.reserve(rank); 670 sizes.reserve(rank); 671 strides.reserve(rank); 672 for (unsigned r = 0; r < rank; ++r) { 673 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: for dim#" << r); 674 if (!isTiled(map.getSubMap({r}), tileSizes)) { 675 offsets.push_back(builder.getIndexAttr(0)); 676 Value dim = createOrFoldDimOp(builder, loc, valueToTile, r); 677 sizes.push_back(getAsOpFoldResult(dim)); 678 strides.push_back(builder.getIndexAttr(1)); 679 LLVM_DEBUG(llvm::dbgs() << ": not tiled: use size: " << dim << "\n"); 680 continue; 681 } 682 LLVM_DEBUG(llvm::dbgs() << ": tiled: figure out subsize...\n"); 683 684 // Tiling creates a new slice at the proper index, the slice step is 1 685 // (i.e. the op does not subsample, stepping occurs in the loop). 686 auto m = map.getSubMap({r}); 687 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: submap: " << m << "\n"); 688 auto offset = applyMapToValues(builder, loc, m, lbs).front(); 689 offsets.push_back(offset); 690 auto closedIntSize = 691 applyMapToValues(builder, loc, m, subShapeSizes).front(); 692 // Resulting size needs to be made half open interval again. 693 AffineExpr s0 = getAffineSymbolExpr(0, builder.getContext()); 694 Value size = 695 fullyComposeAndAffineApply(builder, loc, s0 + 1, closedIntSize); 696 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: raw size: " << size << "\n"); 697 698 // The size of the subview / extract_slice should be trimmed to avoid 699 // out-of-bounds accesses, unless: 700 // a. We statically know the subshape size divides the shape size evenly. 701 // b. The subshape size is 1. According to the way the loops are set up, 702 // tensors with "0" dimensions would never be constructed. 703 int64_t shapeSize = shape[r]; 704 auto sizeCst = size.getDefiningOp<arith::ConstantIndexOp>(); 705 auto hasTileSizeOne = sizeCst && sizeCst.value() == 1; 706 auto dividesEvenly = sizeCst && !ShapedType::isDynamic(shapeSize) && 707 ((shapeSize % sizeCst.value()) == 0); 708 if (!hasTileSizeOne && !dividesEvenly) { 709 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: shapeSize=" << shapeSize 710 << ", size: " << size 711 << ": make sure in bound with affine.min\n"); 712 713 AffineExpr dim0, dim1, dim2; 714 bindDims(builder.getContext(), dim0, dim1, dim2); 715 716 // Get the dimension size for this dimension. We need to first calculate 717 // the max index and then plus one. This is important because for 718 // convolution ops, we have its input window dimension's affine map of the 719 // form `(d0 * s0 + d1)`, where `d0`/`d1 is an output/filter window 720 // dimension and `s0` is stride. Directly use the dimension size of 721 // output/filer window dimensions will cause incorrect calculation. 722 AffineMap minusOneMap = 723 AffineMap::inferFromExprList({ArrayRef<AffineExpr>{dim0 - 1}}) 724 .front(); 725 AffineMap plusOneMap = 726 AffineMap::inferFromExprList({ArrayRef<AffineExpr>{dim0 + 1}}) 727 .front(); 728 auto maxIndices = llvm::to_vector<8>(llvm::map_range(ubs, [&](Value ub) { 729 return makeComposedAffineApply(builder, loc, minusOneMap, {ub}) 730 .getResult(); 731 })); 732 Value maxIndex = applyMapToValues(builder, loc, m, maxIndices).front(); 733 Value d = makeComposedAffineApply(builder, loc, plusOneMap, {maxIndex}); 734 735 // Compute min(size, dim - offset) to avoid out-of-bounds accesses. 736 AffineMap minMap = AffineMap::inferFromExprList( 737 {ArrayRef<AffineExpr>{dim0, dim1 - dim2}}) 738 .front(); 739 SmallVector<Value, 4> operands{size, d, offset}; 740 fullyComposeAffineMapAndOperands(&minMap, &operands); 741 canonicalizeMapAndOperands(&minMap, &operands); 742 size = builder.create<AffineMinOp>(loc, builder.getIndexType(), minMap, 743 operands); 744 } 745 746 sizes.push_back(size); 747 LLVM_DEBUG(llvm::dbgs() 748 << "makeTiledShape: new offset: " << offset << "\n"); 749 LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: new size: " << size << "\n"); 750 strides.push_back(builder.getIndexAttr(1)); 751 } 752 753 auto *sliceOp = TypeSwitch<ShapedType, Operation *>(shapedType) 754 .Case([&](MemRefType) { 755 return builder.create<memref::SubViewOp>( 756 loc, valueToTile, offsets, sizes, strides); 757 }) 758 .Case([&](RankedTensorType) { 759 return makeComposedExtractSliceOp( 760 builder, loc, valueToTile, offsets, sizes, strides); 761 }) 762 .Default([](ShapedType) -> Operation * { 763 llvm_unreachable("Unexpected shaped type"); 764 }); 765 return sliceOp->getResult(0); 766 } 767 768 SmallVector<Value> computeTileOffsets(OpBuilder &b, Location loc, 769 ValueRange ivs, ValueRange tileSizes) { 770 SmallVector<Value> offsets; 771 for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) { 772 LLVM_DEBUG(llvm::dbgs() << "makeTiledShapes: for loop#" << idx << "\n"); 773 bool isTiled = !isZero(tileSizes[idx]); 774 offsets.push_back( 775 isTiled ? ivs[idxIvs++] 776 : b.create<arith::ConstantIndexOp>(loc, 0).getResult()); 777 LLVM_DEBUG(llvm::dbgs() 778 << "computeTileOffsets: " << offsets.back() << "\n"); 779 } 780 return offsets; 781 } 782 783 SmallVector<Value> computeTileSizes(OpBuilder &b, Location loc, ValueRange ivs, 784 ValueRange tileSizes, 785 ArrayRef<Value> sizeBounds) { 786 SmallVector<Value> sizes; 787 for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx) { 788 bool isTiled = !isZero(tileSizes[idx]); 789 // Before composing, we need to make range a closed interval. 790 Value size = isTiled ? tileSizes[idx] : sizeBounds[idx]; 791 AffineExpr d0 = getAffineDimExpr(0, b.getContext()); 792 sizes.push_back(fullyComposeAndAffineApply(b, loc, d0 - 1, size)); 793 LLVM_DEBUG(llvm::dbgs() << "computeTileSizes: " << sizes.back() << "\n"); 794 } 795 return sizes; 796 } 797 798 SmallVector<Value, 4> makeTiledShapes(OpBuilder &b, Location loc, 799 LinalgOp linalgOp, 800 ArrayRef<Value> valuesToTile, 801 ValueRange ivs, ValueRange tileSizes, 802 ArrayRef<Value> sizeBounds) { 803 assert(ivs.size() == static_cast<size_t>(llvm::count_if( 804 llvm::make_range(tileSizes.begin(), tileSizes.end()), 805 [](Value v) { return !isZero(v); })) && 806 "expected as many ivs as non-zero sizes"); 807 808 // Construct (potentially temporary) mins and maxes on which to apply maps 809 // that define tile subshapes. 810 SmallVector<Value> lbs = computeTileOffsets(b, loc, ivs, tileSizes); 811 SmallVector<Value> subShapeSizes = 812 computeTileSizes(b, loc, ivs, tileSizes, sizeBounds); 813 814 assert(static_cast<int64_t>(valuesToTile.size()) == 815 linalgOp.getNumInputsAndOutputs() && 816 "expected one value to tile for every operand"); 817 SmallVector<Value, 4> tiledShapes; 818 tiledShapes.reserve(valuesToTile.size()); 819 for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) { 820 Value shapedOp = valuesToTile[opOperand->getOperandNumber()]; 821 LLVM_DEBUG(llvm::dbgs() << "makeTiledShapes: for operand " << shapedOp); 822 AffineMap map = linalgOp.getTiedIndexingMap(opOperand); 823 // Use `opOperand` as is if it is not tiled and not an output tensor. Having 824 // an extract/insert slice pair for all output tensors simplifies follow up 825 // transformations such as padding and bufferization since the 826 // extract/insert slice pairs make the accessed iteration argument 827 // subdomains explicit. 828 if (!isTiled(map, tileSizes) && !linalgOp.isOutputTensor(opOperand)) { 829 tiledShapes.push_back(shapedOp); 830 LLVM_DEBUG(llvm::dbgs() << ": not tiled: use shape: " 831 << opOperand->get().getType() << "\n"); 832 continue; 833 } 834 LLVM_DEBUG(llvm::dbgs() << ": tiled: figure out subshape...\n"); 835 836 tiledShapes.push_back(makeTiledShape(b, loc, shapedOp, tileSizes, map, lbs, 837 sizeBounds, subShapeSizes)); 838 } 839 840 return tiledShapes; 841 } 842 843 void addTileLoopIvsToIndexOpResults(OpBuilder &b, LinalgOp tiledOp, 844 ArrayRef<Value> ivs) { 845 if (tiledOp.hasIndexSemantics()) { 846 for (IndexOp indexOp : tiledOp.getBlock()->getOps<IndexOp>()) { 847 if (ivs[indexOp.dim()] == nullptr) 848 continue; 849 OpBuilder::InsertionGuard guard(b); 850 b.setInsertionPointAfter(indexOp); 851 AffineExpr index, offset; 852 bindDims(b.getContext(), index, offset); 853 AffineApplyOp applyOp = makeComposedAffineApply( 854 b, indexOp.getLoc(), index + offset, 855 ValueRange{indexOp.getResult(), ivs[indexOp.dim()]}); 856 indexOp.getResult().replaceAllUsesExcept(applyOp, applyOp); 857 } 858 } 859 } 860 861 } // namespace linalg 862 } // namespace mlir 863