1 //===- Sparsification.cpp - Implementation of sparsification --------------===// 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 converting sparse tensor types to actual sparse code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodegenUtils.h" 14 #include "mlir/Dialect/Affine/IR/AffineOps.h" 15 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 16 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" 17 #include "mlir/Dialect/Bufferization/IR/Bufferization.h" 18 #include "mlir/Dialect/Linalg/IR/Linalg.h" 19 #include "mlir/Dialect/Linalg/Utils/Utils.h" 20 #include "mlir/Dialect/MemRef/IR/MemRef.h" 21 #include "mlir/Dialect/SCF/SCF.h" 22 #include "mlir/Dialect/SCF/Transforms.h" 23 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" 24 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h" 25 #include "mlir/Dialect/SparseTensor/Utils/Merger.h" 26 #include "mlir/Dialect/Vector/IR/VectorOps.h" 27 #include "mlir/IR/Matchers.h" 28 #include "mlir/IR/TensorEncoding.h" 29 #include "llvm/ADT/SmallBitVector.h" 30 31 using namespace mlir; 32 using namespace mlir::sparse_tensor; 33 34 //===----------------------------------------------------------------------===// 35 // Declarations of data structures. 36 //===----------------------------------------------------------------------===// 37 38 namespace { 39 40 // Iteration graph sorting. 41 enum SortMask { kSparseOnly = 0x0, kIncludeDense = 0x1, kIncludeUndef = 0x2 }; 42 43 // Reduction kinds. 44 enum Reduction { kNoReduc, kSum, kProduct, kAnd, kOr, kXor }; 45 46 // Code generation. 47 struct CodeGen { 48 CodeGen(SparsificationOptions o, unsigned numTensors, unsigned numLoops, 49 OpOperand *op, unsigned nest) 50 : options(o), loops(numLoops), sizes(numLoops), buffers(numTensors), 51 pointers(numTensors, std::vector<Value>(numLoops)), 52 indices(numTensors, std::vector<Value>(numLoops)), 53 highs(numTensors, std::vector<Value>(numLoops)), 54 pidxs(numTensors, std::vector<Value>(numLoops)), 55 idxs(numTensors, std::vector<Value>(numLoops)), redExp(-1u), redVal(), 56 redKind(kNoReduc), sparseOut(op), outerParNest(nest), lexIdx(), 57 expValues(), expFilled(), expAdded(), expCount(), curVecLength(1), 58 curVecMask() {} 59 /// Sparsification options. 60 SparsificationOptions options; 61 /// Universal dense indices and upper bounds (by index). The loops array 62 /// is updated with the value of the universal dense index in the current 63 /// loop. The sizes array is set once with the inferred dimension sizes. 64 std::vector<Value> loops; 65 std::vector<Value> sizes; 66 /// Buffers for storing dense and sparse numerical values (by tensor). 67 /// This array is set once during bufferization of all tensors. 68 std::vector<Value> buffers; 69 /// Sparse storage schemes (1-D): pointers and indices (by tensor and index). 70 /// This array is set once during bufferization of all sparse tensors. 71 std::vector<std::vector<Value>> pointers; 72 std::vector<std::vector<Value>> indices; 73 /// Sparse iteration information (by tensor and index). These arrays 74 /// are updated to remain current within the current loop. 75 std::vector<std::vector<Value>> highs; 76 std::vector<std::vector<Value>> pidxs; 77 std::vector<std::vector<Value>> idxs; 78 /// Current reduction, updated during code generation. When indices of a 79 /// reduction are exhausted, all inner loops can use a scalarized reduction. 80 unsigned redExp; 81 Value redVal; 82 Reduction redKind; 83 // Sparse tensor as output. Implemented either through direct injective 84 // insertion in lexicographic index order (where indices are updated 85 // in the temporary array `lexIdx`) or through access pattern expansion 86 // in the innermost loop nest (`expValues` through `expCount`). 87 OpOperand *sparseOut; 88 unsigned outerParNest; 89 Value lexIdx; 90 Value expValues; 91 Value expFilled; 92 Value expAdded; 93 Value expCount; 94 // Current vector length and mask. 95 unsigned curVecLength; 96 Value curVecMask; 97 }; 98 99 } // namespace 100 101 //===----------------------------------------------------------------------===// 102 // Sparse compiler analysis methods. 103 //===----------------------------------------------------------------------===// 104 105 /// Helper method to apply dimension ordering permutation. 106 static unsigned perm(const SparseTensorEncodingAttr &enc, unsigned d) { 107 if (enc) { 108 auto order = enc.getDimOrdering(); 109 if (order) { 110 assert(order.isPermutation()); 111 return order.getDimPosition(d); 112 } 113 } 114 return d; 115 } 116 117 /// Helper method to translate dim level type to internal representation. 118 static Dim toDim(const SparseTensorEncodingAttr &enc, unsigned d) { 119 if (enc) { 120 SparseTensorEncodingAttr::DimLevelType tp = enc.getDimLevelType()[d]; 121 if (tp == SparseTensorEncodingAttr::DimLevelType::Compressed) 122 return Dim::kSparse; 123 if (tp == SparseTensorEncodingAttr::DimLevelType::Singleton) 124 return Dim::kSingle; 125 } 126 return Dim::kDense; 127 } 128 129 /// Helper method to inspect affine expressions. Rejects cases where the 130 /// same index is used more than once. Also rejects affine expressions 131 /// that are not a direct index for annotated tensors. 132 // TODO: accept more affine cases for sparse tensors 133 static bool findAffine(Merger &merger, unsigned tensor, AffineExpr a, Dim dim, 134 bool isDense) { 135 switch (a.getKind()) { 136 case AffineExprKind::DimId: { 137 unsigned idx = a.cast<AffineDimExpr>().getPosition(); 138 if (!merger.isDim(tensor, idx, Dim::kUndef)) 139 return false; // used more than once 140 merger.setDim(tensor, idx, dim); 141 return true; 142 } 143 case AffineExprKind::Add: 144 case AffineExprKind::Mul: { 145 if (!isDense) 146 return false; 147 auto binOp = a.cast<AffineBinaryOpExpr>(); 148 return findAffine(merger, tensor, binOp.getLHS(), dim, isDense) && 149 findAffine(merger, tensor, binOp.getRHS(), dim, isDense); 150 } 151 case AffineExprKind::Constant: 152 return isDense; 153 default: 154 return false; 155 } 156 } 157 158 /// Helper method to inspect sparse encodings in the tensor types. 159 /// Fills the per-dimension sparsity information for all tensors. 160 /// Returns true if the sparse annotations and affine subscript 161 /// expressions of all tensors are admissable. Returns false if 162 /// no annotations are found or inadmissable constructs occur. 163 static bool findSparseAnnotations(Merger &merger, linalg::GenericOp op) { 164 bool annotated = false; 165 for (OpOperand *t : op.getInputAndOutputOperands()) { 166 auto map = op.getTiedIndexingMap(t); 167 auto enc = getSparseTensorEncoding(t->get().getType()); 168 if (enc) 169 annotated = true; 170 assert(map.getNumResults() == op.getRank(t)); 171 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 172 unsigned tensor = t->getOperandNumber(); 173 AffineExpr a = map.getResult(perm(enc, d)); 174 if (!findAffine(merger, tensor, a, toDim(enc, d), !enc)) 175 return false; // inadmissable affine expression 176 } 177 } 178 return annotated; 179 } 180 181 /// A DFS helper to compute a topological sort. Note that recursion is 182 /// bounded by the number of implicit loops, which is always small. 183 /// Returns false when a cycle is detected. 184 static bool topSortDFS(unsigned i, std::vector<unsigned> &visit, 185 std::vector<unsigned> &topSort, 186 std::vector<std::vector<bool>> &adjM) { 187 if (visit[i] != 0) 188 return visit[i] != 1; // 1 denotes cycle! 189 visit[i] = 1; 190 for (unsigned j = 0, e = visit.size(); j < e; j++) 191 if (adjM[i][j]) 192 if (!topSortDFS(j, visit, topSort, adjM)) 193 return false; 194 visit[i] = 2; 195 topSort.push_back(i); 196 return true; 197 } 198 199 /// Helper method to add all constraints from the indices in one affine 200 /// expression before all indices in the other affine expression. For 201 /// example i0+i1 < i2+i3+1 yields i0<i2, i0<i3, i1<i2, and i1<i3. 202 static void addAffineOrderings(std::vector<std::vector<bool>> &adjM, 203 AffineExpr a, AffineExpr b, unsigned fidx) { 204 switch (a.getKind()) { 205 case AffineExprKind::DimId: { 206 unsigned idx = a.cast<AffineDimExpr>().getPosition(); 207 if (b) 208 addAffineOrderings(adjM, b, AffineExpr(), idx); 209 else 210 adjM[fidx][idx] = true; 211 break; 212 } 213 case AffineExprKind::Add: 214 case AffineExprKind::Mul: { 215 auto binOp = a.cast<AffineBinaryOpExpr>(); 216 addAffineOrderings(adjM, binOp.getLHS(), b, fidx); 217 addAffineOrderings(adjM, binOp.getRHS(), b, fidx); 218 break; 219 } 220 default: 221 break; 222 } 223 } 224 225 /// Computes a topologically sorted iteration graph for the linalg operation. 226 /// Ensures all tensors are visited in natural index order. This is essential 227 /// for sparse storage formats since these only support access along fixed 228 /// dimensions. Even for dense storage formats, however, the natural index 229 /// order yields innermost unit-stride access with better spatial locality. 230 static bool computeIterationGraph(Merger &merger, linalg::GenericOp op, 231 std::vector<unsigned> &topSort, 232 unsigned mask) { 233 // Set up an n x n from/to adjacency matrix of the iteration graph 234 // for the implicit loop indices i_0 .. i_n-1. 235 unsigned n = op.getNumLoops(); 236 std::vector<std::vector<bool>> adjM(n, std::vector<bool>(n, false)); 237 238 // Iterate over the indexing maps of every tensor in the tensor expression. 239 for (OpOperand *t : op.getInputAndOutputOperands()) { 240 auto map = op.getTiedIndexingMap(t); 241 auto enc = getSparseTensorEncoding(t->get().getType()); 242 assert(map.getNumDims() == n); 243 // Skip dense tensor constraints when not requested. 244 if (!(mask & SortMask::kIncludeDense) && !enc) 245 continue; 246 // Each tensor expression and optional dimension ordering (row-major 247 // by default) puts an ordering constraint on the loop indices. For 248 // example, the tensor expresion A_ijk forces the ordering i < j < k 249 // on the loop indices if no explicit dimension ordering is given. 250 for (unsigned d = 1, rank = map.getNumResults(); d < rank; d++) { 251 AffineExpr f = map.getResult(perm(enc, d - 1)); 252 AffineExpr t = map.getResult(perm(enc, d)); 253 addAffineOrderings(adjM, f, t, 0); 254 } 255 // Push unrelated loops into sparse iteration space, so these 256 // will be skipped more often. 257 if (mask & SortMask::kIncludeUndef) { 258 unsigned tensor = t->getOperandNumber(); 259 for (unsigned i = 0; i < n; i++) 260 if (merger.isDim(tensor, i, Dim::kSparse)) 261 for (unsigned j = 0; j < n; j++) 262 if (merger.isDim(tensor, j, Dim::kUndef)) 263 adjM[i][j] = true; 264 } 265 } 266 267 // Topologically sort the iteration graph to determine loop order. 268 // Report failure for a cyclic iteration graph. 269 topSort.clear(); 270 topSort.reserve(n); 271 std::vector<unsigned> visit(n, 0); 272 for (unsigned i = 0; i < n; i++) 273 if (visit[i] == 0) 274 if (!topSortDFS(i, visit, topSort, adjM)) 275 return false; // cycle! 276 std::reverse(std::begin(topSort), std::end(topSort)); 277 return true; 278 } 279 280 /// Returns true if tensor has an in-place annotation. 281 static bool isInPlace(Value val) { 282 if (auto arg = val.dyn_cast<BlockArgument>()) 283 if (auto funcOp = dyn_cast<FuncOp>(arg.getOwner()->getParentOp())) 284 if (auto attr = funcOp.getArgAttrOfType<BoolAttr>( 285 arg.getArgNumber(), 286 bufferization::BufferizableOpInterface::kInplaceableAttrName)) 287 return attr.getValue(); 288 return false; 289 } 290 291 /// Returns true if tensor materializes uninitialized into the computation. 292 static bool isMaterializing(Value val) { 293 return val.getDefiningOp<linalg::InitTensorOp>() || 294 val.getDefiningOp<InitOp>(); 295 } 296 297 /// Returns true when the tensor expression is admissable for codegen. 298 /// Since all sparse input tensors are admissable, we just need to check 299 /// whether the out tensor in the tensor expression codegen is admissable. 300 /// Sets `sparseOut` to the tensor and `outerParNest` to the outer injective 301 /// nesting depth when a "truly dynamic" sparse tensor output occurs. 302 static bool isAdmissableTensorExp(Merger &merger, linalg::GenericOp op, 303 std::vector<unsigned> &topSort, unsigned exp, 304 OpOperand **sparseOut, 305 unsigned &outerParNest) { 306 OpOperand *lhs = op.getOutputOperand(0); 307 unsigned tensor = lhs->getOperandNumber(); 308 auto enc = getSparseTensorEncoding(lhs->get().getType()); 309 // An non-annotated output tensor is assumed dense, and becomes a random 310 // access n-dim memref. Admissable since insertions cannot occur. 311 if (!enc) 312 return true; 313 // An all-dense annotated "sparse" output tensor becomes a linearized random 314 // access 1-dim memref. Also admissable since insertions cannot occur. 315 bool allDense = true; 316 auto iteratorTypes = op.iterator_types().getValue(); 317 unsigned numLoops = iteratorTypes.size(); 318 for (unsigned i = 0; i < numLoops; i++) 319 if (merger.isDim(tensor, i, Dim::kSparse)) { 320 allDense = false; 321 break; 322 } 323 if (allDense) 324 return true; 325 // A tensor expression with a sparse output tensor that changes its values 326 // but not its nonzero structure, an operation called "simply dynamic" in 327 // [Bik96,Ch9], is also admissable without special codegen, provided 328 // the tensor's underlying sparse storage scheme can be modified in place. 329 if (merger.isSingleCondition(tensor, exp) && isInPlace(lhs->get())) 330 return true; 331 // Accept "truly dynamic" if the output tensor materializes uninitialized 332 // into the computation and insertions occur in lexicographic index order. 333 if (isMaterializing(lhs->get())) { 334 unsigned nest = 0; 335 for (unsigned i = 0; i < numLoops; i++) { 336 if (isReductionIterator(iteratorTypes[topSort[i]])) 337 break; // terminate at first reduction 338 nest++; 339 } 340 // Determine admissable dynamic insertion situations: 341 // (1) fully injective, since there are no reductions, 342 // (2) admissable 1-d expansion in innermost dimension. 343 if (nest >= op.getRank(lhs) - 1) { 344 *sparseOut = lhs; 345 outerParNest = nest; 346 return true; 347 } 348 } 349 return false; 350 } 351 352 //===----------------------------------------------------------------------===// 353 // Sparse compiler synthesis methods (reductions). 354 //===----------------------------------------------------------------------===// 355 356 /// Maps reduction kind to vector::CombiningKind. 357 static vector::CombiningKind getCombiningKind(Reduction kind) { 358 switch (kind) { 359 case kNoReduc: 360 break; 361 case kSum: 362 return vector::CombiningKind::ADD; 363 case kProduct: 364 return vector::CombiningKind::MUL; 365 case kAnd: 366 return vector::CombiningKind::AND; 367 case kOr: 368 return vector::CombiningKind::OR; 369 case kXor: 370 return vector::CombiningKind::XOR; 371 } 372 llvm_unreachable("unknown reduction kind"); 373 } 374 375 /// Maps operation to reduction. 376 static Reduction getReduction(Kind kind) { 377 switch (kind) { 378 case Kind::kAddF: 379 case Kind::kAddI: 380 case Kind::kSubF: 381 case Kind::kSubI: 382 return kSum; 383 case Kind::kMulF: 384 case Kind::kMulI: 385 return kProduct; 386 case Kind::kAndI: 387 return kAnd; 388 case Kind::kOrI: 389 return kOr; 390 case Kind::kXorI: 391 return kXor; 392 default: 393 llvm_unreachable("unexpected reduction operator"); 394 } 395 } 396 397 /// Generates an initial value for a vector reduction, following the scheme 398 /// given in Chapter 5 of "The Software Vectorization Handbook", where the 399 /// initial scalar value is correctly embedded in the vector reduction value, 400 /// and a straightforward horizontal reduction will complete the operation. 401 static Value genVectorReducInit(CodeGen &codegen, PatternRewriter &rewriter, 402 Location loc, VectorType vtp) { 403 Value r = codegen.redVal; 404 switch (codegen.redKind) { 405 case kNoReduc: 406 break; 407 case kSum: 408 case kXor: 409 // Initialize reduction vector to: | 0 | .. | 0 | r | 410 return rewriter.create<vector::InsertElementOp>( 411 loc, r, constantZero(rewriter, loc, vtp), 412 constantIndex(rewriter, loc, 0)); 413 case kProduct: 414 // Initialize reduction vector to: | 1 | .. | 1 | r | 415 return rewriter.create<vector::InsertElementOp>( 416 loc, r, constantOne(rewriter, loc, vtp), 417 constantIndex(rewriter, loc, 0)); 418 case kAnd: 419 case kOr: 420 // Initialize reduction vector to: | r | .. | r | r | 421 return rewriter.create<vector::BroadcastOp>(loc, vtp, r); 422 } 423 llvm_unreachable("unknown reduction kind"); 424 } 425 426 /// Generates final value for a vector reduction. 427 static Value genVectorReducEnd(CodeGen &codegen, PatternRewriter &rewriter, 428 Location loc, VectorType vtp) { 429 vector::CombiningKind kind = getCombiningKind(codegen.redKind); 430 return rewriter.create<vector::ReductionOp>(loc, kind, codegen.redVal); 431 } 432 433 /// Updates scalarized reduction value. 434 static void updateReduc(Merger &merger, CodeGen &codegen, Value reduc) { 435 assert(codegen.redKind != kNoReduc); 436 codegen.redVal = merger.exp(codegen.redExp).val = reduc; 437 } 438 439 //===----------------------------------------------------------------------===// 440 // Sparse compiler synthesis methods (statements and expressions). 441 //===----------------------------------------------------------------------===// 442 443 /// Generates buffer for the output tensor. Note that all sparse kernels 444 /// assume that when all elements are written to (viz. x(i) = y(i) * z(i)), 445 /// the output buffer is already initialized to all zeroes and only nonzeroes 446 /// values are computed and written out. For updates (viz. x(i) += y(i) * z(i)), 447 /// only nonzeroes values are used for the updates and no assumption on the 448 /// original contents of the output buffer is necessary.. 449 static Value genOutputBuffer(CodeGen &codegen, PatternRewriter &rewriter, 450 linalg::GenericOp op, MemRefType denseTp, 451 ArrayRef<Value> args) { 452 Location loc = op.getLoc(); 453 Value tensor = op.getOutputOperand(0)->get(); 454 // The output tensor simply could materialize from the buffer that will 455 // be generated for the tensor present in the outs() clause. This has 456 // the major advantage that the sparse kernel only updates the nonzero 457 // positions for the output tensor. 458 if (isInPlace(tensor)) 459 return rewriter.create<bufferization::ToMemrefOp>(loc, denseTp, tensor); 460 // By default, a new buffer is allocated which is initialized to the 461 // tensor defined in the outs() clause. This is always correct but 462 // introduces a dense initialization component that may negatively 463 // impact the running complexity of the sparse kernel. If the tensor 464 // materializes into the computation, we need to preserve the zero 465 // initialization assumption of all sparse output buffers. 466 Value alloc = rewriter.create<memref::AllocOp>(loc, denseTp, args); 467 if (isMaterializing(tensor)) { 468 Value zero = constantZero(rewriter, loc, denseTp.getElementType()); 469 rewriter.create<linalg::FillOp>(loc, zero, alloc); 470 } else { 471 Value init = 472 rewriter.create<bufferization::ToMemrefOp>(loc, denseTp, tensor); 473 rewriter.create<memref::CopyOp>(loc, init, alloc); 474 } 475 return alloc; 476 } 477 478 /// Local bufferization of all dense and sparse data structures. 479 /// This code enables testing the first prototype sparse compiler. 480 // TODO: replace this with a proliferated bufferization strategy 481 static void genBuffers(Merger &merger, CodeGen &codegen, 482 PatternRewriter &rewriter, linalg::GenericOp op) { 483 Location loc = op.getLoc(); 484 assert(op.getNumInputsAndOutputs() == op.getNumInputs() + 1); 485 // For every tensor, find lower and upper bound on dimensions, set the 486 // same bounds on loop indices, and obtain dense or sparse buffer(s). 487 SmallVector<Value, 4> args; 488 for (OpOperand *t : op.getInputAndOutputOperands()) { 489 unsigned tensor = t->getOperandNumber(); 490 auto shape = op.getShape(t); 491 auto map = op.getTiedIndexingMap(t); 492 auto enc = getSparseTensorEncoding(t->get().getType()); 493 // Scan all dimensions of current tensor. 494 args.clear(); 495 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 496 AffineExpr a = map.getResult(perm(enc, d)); 497 if (a.getKind() != AffineExprKind::DimId) 498 continue; // compound 499 unsigned idx = a.cast<AffineDimExpr>().getPosition(); 500 // Handle sparse storage schemes. 501 if (merger.isDim(tensor, idx, Dim::kSparse)) { 502 auto dynShape = {ShapedType::kDynamicSize}; 503 auto ptrTp = 504 MemRefType::get(dynShape, getPointerOverheadType(rewriter, enc)); 505 auto indTp = 506 MemRefType::get(dynShape, getIndexOverheadType(rewriter, enc)); 507 Value dim = constantIndex(rewriter, loc, d); 508 // Generate sparse primitives to obtains pointer and indices. 509 codegen.pointers[tensor][idx] = 510 rewriter.create<ToPointersOp>(loc, ptrTp, t->get(), dim); 511 codegen.indices[tensor][idx] = 512 rewriter.create<ToIndicesOp>(loc, indTp, t->get(), dim); 513 } 514 // Find upper bound in current dimension. 515 unsigned p = perm(enc, d); 516 Value up = linalg::createOrFoldDimOp(rewriter, loc, t->get(), p); 517 if (ShapedType::isDynamic(shape[p])) 518 args.push_back(up); 519 assert(codegen.highs[tensor][idx] == nullptr); 520 codegen.sizes[idx] = codegen.highs[tensor][idx] = up; 521 } 522 // Perform the required bufferization. Dense inputs materialize 523 // from the input tensors. Dense outputs need special handling. 524 // Sparse inputs use sparse primitives to obtain the values. 525 // We also accept in-place all-dense annotated "sparse" outputs. 526 Type elementType = getElementTypeOrSelf(t->get().getType()); 527 if (!enc) { 528 // Non-annotated dense tensors. 529 auto denseTp = MemRefType::get(shape, elementType); 530 if (tensor < op.getNumInputs()) 531 codegen.buffers[tensor] = 532 rewriter.create<bufferization::ToMemrefOp>(loc, denseTp, t->get()); 533 else 534 codegen.buffers[tensor] = 535 genOutputBuffer(codegen, rewriter, op, denseTp, args); 536 } else if (t == codegen.sparseOut) { 537 // True sparse output needs a lexIdx array. 538 Value rank = constantIndex(rewriter, loc, op.getRank(t)); 539 auto dynShape = {ShapedType::kDynamicSize}; 540 auto memTp = MemRefType::get(dynShape, rewriter.getIndexType()); 541 codegen.lexIdx = rewriter.create<memref::AllocaOp>(loc, memTp, rank); 542 } else { 543 // Annotated sparse tensors. 544 auto dynShape = {ShapedType::kDynamicSize}; 545 auto sparseTp = MemRefType::get(dynShape, elementType); 546 codegen.buffers[tensor] = 547 rewriter.create<ToValuesOp>(loc, sparseTp, t->get()); 548 } 549 } 550 } 551 552 /// Constructs vector type. 553 static VectorType vectorType(CodeGen &codegen, Type etp) { 554 return VectorType::get(codegen.curVecLength, etp); 555 } 556 557 /// Constructs vector type from pointer. 558 static VectorType vectorType(CodeGen &codegen, Value ptr) { 559 return vectorType(codegen, ptr.getType().cast<MemRefType>().getElementType()); 560 } 561 562 /// Constructs vector iteration mask. 563 static Value genVectorMask(CodeGen &codegen, PatternRewriter &rewriter, 564 Value iv, Value lo, Value hi, Value step) { 565 Location loc = iv.getLoc(); 566 VectorType mtp = vectorType(codegen, rewriter.getI1Type()); 567 // Special case if the vector length evenly divides the trip count (for 568 // example, "for i = 0, 128, 16"). A constant all-true mask is generated 569 // so that all subsequent masked memory operations are immediately folded 570 // into unconditional memory operations. 571 IntegerAttr loInt, hiInt, stepInt; 572 if (matchPattern(lo, m_Constant(&loInt)) && 573 matchPattern(hi, m_Constant(&hiInt)) && 574 matchPattern(step, m_Constant(&stepInt))) { 575 if (((hiInt.getInt() - loInt.getInt()) % stepInt.getInt()) == 0) 576 return rewriter.create<vector::BroadcastOp>( 577 loc, mtp, constantI1(rewriter, loc, true)); 578 } 579 // Otherwise, generate a vector mask that avoids overrunning the upperbound 580 // during vector execution. Here we rely on subsequent loop optimizations to 581 // avoid executing the mask in all iterations, for example, by splitting the 582 // loop into an unconditional vector loop and a scalar cleanup loop. 583 auto minMap = AffineMap::get( 584 /*dimCount=*/2, /*symbolCount=*/1, 585 {rewriter.getAffineSymbolExpr(0), 586 rewriter.getAffineDimExpr(0) - rewriter.getAffineDimExpr(1)}, 587 rewriter.getContext()); 588 Value end = 589 rewriter.createOrFold<AffineMinOp>(loc, minMap, ValueRange{hi, iv, step}); 590 return rewriter.create<vector::CreateMaskOp>(loc, mtp, end); 591 } 592 593 /// Generates a vectorized load lhs = a[ind[lo:hi]] or lhs = a[lo:hi]. 594 static Value genVectorLoad(CodeGen &codegen, PatternRewriter &rewriter, 595 Value ptr, ArrayRef<Value> args) { 596 Location loc = ptr.getLoc(); 597 VectorType vtp = vectorType(codegen, ptr); 598 Value pass = constantZero(rewriter, loc, vtp); 599 if (args.back().getType().isa<VectorType>()) { 600 SmallVector<Value, 4> scalarArgs(args.begin(), args.end()); 601 Value indexVec = args.back(); 602 scalarArgs.back() = constantIndex(rewriter, loc, 0); 603 return rewriter.create<vector::GatherOp>( 604 loc, vtp, ptr, scalarArgs, indexVec, codegen.curVecMask, pass); 605 } 606 return rewriter.create<vector::MaskedLoadOp>(loc, vtp, ptr, args, 607 codegen.curVecMask, pass); 608 } 609 610 /// Generates a vectorized store a[ind[lo:hi]] = rhs or a[lo:hi] = rhs. 611 static void genVectorStore(CodeGen &codegen, PatternRewriter &rewriter, 612 Value rhs, Value ptr, ArrayRef<Value> args) { 613 Location loc = ptr.getLoc(); 614 if (args.back().getType().isa<VectorType>()) { 615 SmallVector<Value, 4> scalarArgs(args.begin(), args.end()); 616 Value indexVec = args.back(); 617 scalarArgs.back() = constantIndex(rewriter, loc, 0); 618 rewriter.create<vector::ScatterOp>(loc, ptr, scalarArgs, indexVec, 619 codegen.curVecMask, rhs); 620 return; 621 } 622 rewriter.create<vector::MaskedStoreOp>(loc, ptr, args, codegen.curVecMask, 623 rhs); 624 } 625 626 /// Generates a vectorized invariant. Here we rely on subsequent loop 627 /// optimizations to hoist the invariant broadcast out of the vector loop. 628 static Value genVectorInvariantValue(CodeGen &codegen, 629 PatternRewriter &rewriter, Value val) { 630 VectorType vtp = vectorType(codegen, val.getType()); 631 return rewriter.create<vector::BroadcastOp>(val.getLoc(), vtp, val); 632 } 633 634 /// Generates an affine expression. 635 // 636 // TODO: generalize for sparse tensor subscripts 637 // 638 static Value genAffine(CodeGen &codegen, PatternRewriter &rewriter, 639 AffineExpr a, Location loc) { 640 switch (a.getKind()) { 641 case AffineExprKind::DimId: { 642 unsigned idx = a.cast<AffineDimExpr>().getPosition(); 643 return codegen.loops[idx]; // universal dense index 644 } 645 case AffineExprKind::Add: { 646 auto binOp = a.cast<AffineBinaryOpExpr>(); 647 return rewriter.create<arith::AddIOp>( 648 loc, genAffine(codegen, rewriter, binOp.getLHS(), loc), 649 genAffine(codegen, rewriter, binOp.getRHS(), loc)); 650 } 651 case AffineExprKind::Mul: { 652 auto binOp = a.cast<AffineBinaryOpExpr>(); 653 return rewriter.create<arith::MulIOp>( 654 loc, genAffine(codegen, rewriter, binOp.getLHS(), loc), 655 genAffine(codegen, rewriter, binOp.getRHS(), loc)); 656 } 657 case AffineExprKind::Constant: { 658 int64_t c = a.cast<AffineConstantExpr>().getValue(); 659 return constantIndex(rewriter, loc, c); 660 } 661 default: 662 llvm_unreachable("unexpected affine subscript"); 663 } 664 } 665 666 /// Generates index for load/store on sparse tensor. 667 static Value genIndex(CodeGen &codegen, linalg::GenericOp op, OpOperand *t) { 668 auto map = op.getTiedIndexingMap(t); 669 auto enc = getSparseTensorEncoding(t->get().getType()); 670 AffineExpr a = map.getResult(perm(enc, map.getNumResults() - 1)); 671 assert(a.getKind() == AffineExprKind::DimId); 672 unsigned idx = a.cast<AffineDimExpr>().getPosition(); 673 return codegen.loops[idx]; 674 } 675 676 /// Generates subscript for load/store on a dense or sparse tensor. 677 static Value genSubscript(CodeGen &codegen, PatternRewriter &rewriter, 678 linalg::GenericOp op, OpOperand *t, 679 SmallVector<Value, 4> &args) { 680 unsigned tensor = t->getOperandNumber(); 681 auto map = op.getTiedIndexingMap(t); 682 auto enc = getSparseTensorEncoding(t->get().getType()); 683 unsigned rank = map.getNumResults(); 684 if (enc) { 685 // Note that currently, all sparse subscripts are simple. 686 // TODO: accept affine too? 687 AffineExpr a = map.getResult(perm(enc, rank - 1)); 688 assert(a.getKind() == AffineExprKind::DimId); 689 unsigned idx = a.cast<AffineDimExpr>().getPosition(); 690 assert(codegen.pidxs[tensor][idx] != nullptr); 691 args.push_back(codegen.pidxs[tensor][idx]); // position index 692 } else { 693 for (unsigned d = 0; d < rank; d++) { 694 AffineExpr a = map.getResult(perm(enc, d)); 695 args.push_back(genAffine(codegen, rewriter, a, op.getLoc())); 696 } 697 } 698 return codegen.buffers[tensor]; 699 } 700 701 /// Generates insertion code to implement dynamic tensor load. 702 static Value genInsertionLoad(CodeGen &codegen, PatternRewriter &rewriter, 703 linalg::GenericOp op, OpOperand *t) { 704 Location loc = op.getLoc(); 705 // Direct lexicographic index order, tensor loads as zero. 706 if (!codegen.expValues) { 707 Type tp = getElementTypeOrSelf(t->get().getType()); 708 return constantZero(rewriter, loc, tp); 709 } 710 // Load from expanded access pattern. 711 Value index = genIndex(codegen, op, t); 712 return rewriter.create<memref::LoadOp>(loc, codegen.expValues, index); 713 } 714 715 /// Generates insertion code to implement dynamic tensor store. 716 static void genInsertionStore(CodeGen &codegen, PatternRewriter &rewriter, 717 linalg::GenericOp op, OpOperand *t, Value rhs) { 718 Location loc = op.getLoc(); 719 // Direct insertion in lexicographic index order. 720 if (!codegen.expValues) { 721 rewriter.create<LexInsertOp>(loc, t->get(), codegen.lexIdx, rhs); 722 return; 723 } 724 // Generates insertion code along expanded access pattern. 725 // if (!expFilled[i]) then 726 // expFilled[i] = true 727 // expAdded[inserts++] = i 728 // endif 729 // values[i] = rhs 730 Value index = genIndex(codegen, op, t); 731 Value fval = constantI1(rewriter, loc, false); 732 Value tval = constantI1(rewriter, loc, true); 733 // If statement. 734 Value filled = rewriter.create<memref::LoadOp>(loc, codegen.expFilled, index); 735 Value cond = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, 736 filled, fval); 737 scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, rewriter.getIndexType(), 738 cond, /*else=*/true); 739 // True branch. 740 rewriter.setInsertionPointToStart(&ifOp.getThenRegion().front()); 741 rewriter.create<memref::StoreOp>(loc, tval, codegen.expFilled, index); 742 rewriter.create<memref::StoreOp>(loc, index, codegen.expAdded, 743 codegen.expCount); 744 Value one = constantIndex(rewriter, loc, 1); 745 Value add = rewriter.create<arith::AddIOp>(loc, codegen.expCount, one); 746 rewriter.create<scf::YieldOp>(loc, add); 747 // False branch. 748 rewriter.setInsertionPointToStart(&ifOp.getElseRegion().front()); 749 rewriter.create<scf::YieldOp>(loc, codegen.expCount); 750 rewriter.setInsertionPointAfter(ifOp); 751 // Value assignment. 752 codegen.expCount = ifOp.getResult(0); 753 rewriter.create<memref::StoreOp>(loc, rhs, codegen.expValues, index); 754 } 755 756 /// Generates a load on a dense or sparse tensor. 757 static Value genTensorLoad(Merger &merger, CodeGen &codegen, 758 PatternRewriter &rewriter, linalg::GenericOp op, 759 unsigned exp) { 760 // Test if the load was hoisted to a higher loop nest. 761 Value val = merger.exp(exp).val; 762 if (val) { 763 if (codegen.curVecLength > 1 && !val.getType().isa<VectorType>()) 764 return genVectorInvariantValue(codegen, rewriter, val); 765 return val; 766 } 767 // Load during insertion. 768 OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor]; 769 if (t == codegen.sparseOut) 770 return genInsertionLoad(codegen, rewriter, op, t); 771 // Actual load. 772 SmallVector<Value, 4> args; 773 Value ptr = genSubscript(codegen, rewriter, op, t, args); 774 if (codegen.curVecLength > 1) 775 return genVectorLoad(codegen, rewriter, ptr, args); 776 return rewriter.create<memref::LoadOp>(op.getLoc(), ptr, args); 777 } 778 779 /// Generates a store on a dense or sparse tensor. 780 static void genTensorStore(Merger &merger, CodeGen &codegen, 781 PatternRewriter &rewriter, linalg::GenericOp op, 782 Value rhs) { 783 Location loc = op.getLoc(); 784 // Test if this is a scalarized reduction. 785 if (codegen.redVal) { 786 if (codegen.curVecLength > 1) 787 rhs = rewriter.create<arith::SelectOp>(loc, codegen.curVecMask, rhs, 788 codegen.redVal); 789 updateReduc(merger, codegen, rhs); 790 return; 791 } 792 // Store during insertion. 793 OpOperand *t = op.getOutputOperand(0); 794 if (t == codegen.sparseOut) { 795 genInsertionStore(codegen, rewriter, op, t, rhs); 796 return; 797 } 798 // Actual store. 799 SmallVector<Value, 4> args; 800 Value ptr = genSubscript(codegen, rewriter, op, t, args); 801 if (codegen.curVecLength > 1) 802 genVectorStore(codegen, rewriter, rhs, ptr, args); 803 else 804 rewriter.create<memref::StoreOp>(loc, rhs, ptr, args); 805 } 806 807 /// Generates a pointer/index load from the sparse storage scheme. Narrower 808 /// data types need to be zero extended before casting the value into the 809 /// index type used for looping and indexing. 810 static Value genLoad(CodeGen &codegen, PatternRewriter &rewriter, Location loc, 811 Value ptr, Value s) { 812 // See https://llvm.org/docs/GetElementPtr.html for some background on 813 // the complications described below. 814 if (codegen.curVecLength > 1) { 815 // Since the index vector is used in a subsequent gather/scatter operations, 816 // which effectively defines an unsigned pointer + signed index, we must 817 // zero extend the vector to an index width. For 8-bit and 16-bit values, 818 // an 32-bit index width suffices. For 32-bit values, zero extending the 819 // elements into 64-bit loses some performance since the 32-bit indexed 820 // gather/scatter is more efficient than the 64-bit index variant (if the 821 // negative 32-bit index space is unused, the enableSIMDIndex32 flag can 822 // preserve this performance). For 64-bit values, there is no good way 823 // to state that the indices are unsigned, with creates the potential of 824 // incorrect address calculations in the unlikely case we need such 825 // extremely large offsets. 826 Type etp = ptr.getType().cast<MemRefType>().getElementType(); 827 Value vload = genVectorLoad(codegen, rewriter, ptr, {s}); 828 if (!etp.isa<IndexType>()) { 829 if (etp.getIntOrFloatBitWidth() < 32) 830 vload = rewriter.create<arith::ExtUIOp>( 831 loc, vectorType(codegen, rewriter.getI32Type()), vload); 832 else if (etp.getIntOrFloatBitWidth() < 64 && 833 !codegen.options.enableSIMDIndex32) 834 vload = rewriter.create<arith::ExtUIOp>( 835 loc, vectorType(codegen, rewriter.getI64Type()), vload); 836 } 837 return vload; 838 } 839 // For the scalar case, we simply zero extend narrower indices into 64-bit 840 // values before casting to index without a performance penalty. Here too, 841 // however, indices that already are 64-bit, in theory, cannot express the 842 // full range as explained above. 843 Value load = rewriter.create<memref::LoadOp>(loc, ptr, s); 844 if (!load.getType().isa<IndexType>()) { 845 if (load.getType().getIntOrFloatBitWidth() < 64) 846 load = rewriter.create<arith::ExtUIOp>(loc, rewriter.getI64Type(), load); 847 load = 848 rewriter.create<arith::IndexCastOp>(loc, rewriter.getIndexType(), load); 849 } 850 return load; 851 } 852 853 /// Generates an invariant value. 854 static Value genInvariantValue(Merger &merger, CodeGen &codegen, 855 PatternRewriter &rewriter, unsigned exp) { 856 Value val = merger.exp(exp).val; 857 if (codegen.curVecLength > 1) 858 return genVectorInvariantValue(codegen, rewriter, val); 859 return val; 860 } 861 862 /// Generates an address computation "sz * p + i". 863 static Value genAddress(CodeGen &codegen, PatternRewriter &rewriter, 864 Location loc, Value size, Value p, Value i) { 865 Value mul = rewriter.create<arith::MulIOp>(loc, size, p); 866 if (auto vtp = i.getType().dyn_cast<VectorType>()) { 867 Value inv = 868 rewriter.create<arith::IndexCastOp>(loc, vtp.getElementType(), mul); 869 mul = genVectorInvariantValue(codegen, rewriter, inv); 870 } 871 return rewriter.create<arith::AddIOp>(loc, mul, i); 872 } 873 874 /// Recursively generates tensor expression. 875 static Value genExp(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 876 linalg::GenericOp op, unsigned exp) { 877 Location loc = op.getLoc(); 878 if (exp == -1u) 879 return Value(); 880 if (merger.exp(exp).kind == Kind::kTensor) 881 return genTensorLoad(merger, codegen, rewriter, op, exp); 882 if (merger.exp(exp).kind == Kind::kInvariant) 883 return genInvariantValue(merger, codegen, rewriter, exp); 884 Value v0 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e0); 885 Value v1 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e1); 886 return merger.buildExp(rewriter, loc, exp, v0, v1); 887 } 888 889 /// Determines if affine expression is invariant. 890 static bool isInvariantAffine(const CodeGen &codegen, AffineExpr a, 891 unsigned ldx, bool &atLevel) { 892 switch (a.getKind()) { 893 case AffineExprKind::DimId: { 894 unsigned idx = a.cast<AffineDimExpr>().getPosition(); 895 if (idx == ldx) 896 atLevel = true; 897 return codegen.loops[idx] != nullptr; // no longer in play? 898 } 899 case AffineExprKind::Add: 900 case AffineExprKind::Mul: { 901 auto binOp = a.cast<AffineBinaryOpExpr>(); 902 return isInvariantAffine(codegen, binOp.getLHS(), ldx, atLevel) && 903 isInvariantAffine(codegen, binOp.getRHS(), ldx, atLevel); 904 } 905 default: 906 return true; 907 } 908 } 909 910 /// Hoists loop invariant tensor loads for which indices have been exhausted. 911 static void genInvariants(Merger &merger, CodeGen &codegen, 912 PatternRewriter &rewriter, linalg::GenericOp op, 913 unsigned exp, unsigned ldx, bool atStart, 914 Kind last = Kind::kTensor) { 915 if (exp == -1u) 916 return; 917 if (merger.exp(exp).kind == Kind::kTensor) { 918 // Inspect tensor indices. 919 bool atLevel = ldx == -1u; 920 OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor]; 921 auto map = op.getTiedIndexingMap(t); 922 auto enc = getSparseTensorEncoding(t->get().getType()); 923 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 924 AffineExpr a = map.getResult(perm(enc, d)); 925 if (!isInvariantAffine(codegen, a, ldx, atLevel)) 926 return; // still in play 927 } 928 // All exhausted at this level (atLevel denotes exactly at this level). 929 if (!atLevel) 930 return; 931 OpOperand *lhs = op.getOutputOperand(0); 932 if (lhs == t) { 933 // Start or end a scalarized reduction 934 if (atStart) { 935 Value load = genTensorLoad(merger, codegen, rewriter, op, exp); 936 codegen.redKind = getReduction(last); 937 codegen.redExp = exp; 938 updateReduc(merger, codegen, load); 939 } else { 940 Value redVal = codegen.redVal; 941 updateReduc(merger, codegen, Value()); 942 codegen.redExp = -1u; 943 codegen.redKind = kNoReduc; 944 genTensorStore(merger, codegen, rewriter, op, redVal); 945 } 946 } else { 947 // Start or end loop invariant hoisting of a tensor load. 948 merger.exp(exp).val = 949 atStart ? genTensorLoad(merger, codegen, rewriter, op, exp) : Value(); 950 } 951 } else if (merger.exp(exp).kind != Kind::kInvariant) { 952 // Traverse into the binary operations. Note that we only hoist 953 // tensor loads, since subsequent MLIR/LLVM passes know how to 954 // deal with all other kinds of derived loop invariants. 955 Kind last = merger.exp(exp).kind; 956 unsigned e0 = merger.exp(exp).children.e0; 957 unsigned e1 = merger.exp(exp).children.e1; 958 genInvariants(merger, codegen, rewriter, op, e0, ldx, atStart, last); 959 genInvariants(merger, codegen, rewriter, op, e1, ldx, atStart, last); 960 } 961 } 962 963 /// Generates an expanded access pattern in innermost dimension. 964 static void genExpansion(Merger &merger, CodeGen &codegen, 965 PatternRewriter &rewriter, linalg::GenericOp op, 966 unsigned at, bool atStart) { 967 OpOperand *lhs = codegen.sparseOut; 968 if (!lhs || codegen.outerParNest != op.getRank(lhs) - 1 || 969 at != codegen.outerParNest) 970 return; // not needed at this level 971 // Generate start or end of an expanded access pattern. 972 Value tensor = lhs->get(); 973 Location loc = op.getLoc(); 974 if (atStart) { 975 auto dynShape = {ShapedType::kDynamicSize}; 976 Type etp = tensor.getType().cast<ShapedType>().getElementType(); 977 Type t1 = MemRefType::get(dynShape, etp); 978 Type t2 = MemRefType::get(dynShape, rewriter.getI1Type()); 979 Type t3 = MemRefType::get(dynShape, rewriter.getIndexType()); 980 Type t4 = rewriter.getIndexType(); 981 auto res = 982 rewriter.create<ExpandOp>(loc, TypeRange({t1, t2, t3, t4}), tensor); 983 assert(res.getNumResults() == 4); 984 assert(!codegen.expValues); 985 codegen.expValues = res.getResult(0); 986 codegen.expFilled = res.getResult(1); 987 codegen.expAdded = res.getResult(2); 988 codegen.expCount = res.getResult(3); 989 } else { 990 assert(codegen.expValues); 991 rewriter.create<CompressOp>(loc, tensor, codegen.lexIdx, codegen.expValues, 992 codegen.expFilled, codegen.expAdded, 993 codegen.expCount); 994 codegen.expValues = codegen.expFilled = codegen.expAdded = 995 codegen.expCount = Value(); 996 } 997 } 998 999 /// Generates initialization code for the subsequent loop sequence at 1000 /// current index level. Returns true if the loop sequence needs to 1001 /// maintain the universal index. 1002 static bool genInit(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 1003 linalg::GenericOp op, std::vector<unsigned> &topSort, 1004 unsigned at, BitVector &inits) { 1005 bool needsUniv = false; 1006 Location loc = op.getLoc(); 1007 unsigned idx = topSort[at]; 1008 1009 // Initialize sparse positions. 1010 for (unsigned b = 0, be = inits.size(); b < be; b++) { 1011 if (inits[b]) { 1012 unsigned tensor = merger.tensor(b); 1013 assert(idx == merger.index(b)); 1014 if (merger.isDim(b, Dim::kSparse)) { 1015 // Initialize sparse index. 1016 unsigned pat = at; 1017 for (; pat != 0; pat--) { 1018 if (codegen.pidxs[tensor][topSort[pat - 1]]) 1019 break; 1020 } 1021 Value ptr = codegen.pointers[tensor][idx]; 1022 Value one = constantIndex(rewriter, loc, 1); 1023 Value p0 = (pat == 0) ? constantIndex(rewriter, loc, 0) 1024 : codegen.pidxs[tensor][topSort[pat - 1]]; 1025 codegen.pidxs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p0); 1026 Value p1 = rewriter.create<arith::AddIOp>(loc, p0, one); 1027 codegen.highs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p1); 1028 } else { 1029 // Dense index still in play. 1030 needsUniv = true; 1031 } 1032 } 1033 } 1034 1035 // Initialize the universal dense index. 1036 codegen.loops[idx] = constantIndex(rewriter, loc, 0); 1037 return needsUniv; 1038 } 1039 1040 /// Returns vectorization strategy. Any implicit inner loop in the Linalg 1041 /// operation is a candidate. Whether it is actually converted to SIMD code 1042 /// depends on the requested strategy. 1043 static bool isVectorFor(CodeGen &codegen, bool isInner, bool isSparse) { 1044 switch (codegen.options.vectorizationStrategy) { 1045 case SparseVectorizationStrategy::kNone: 1046 return false; 1047 case SparseVectorizationStrategy::kDenseInnerLoop: 1048 return isInner && !isSparse; 1049 case SparseVectorizationStrategy::kAnyStorageInnerLoop: 1050 return isInner; 1051 } 1052 llvm_unreachable("unexpected vectorization strategy"); 1053 } 1054 1055 /// Returns parallelization strategy. Any implicit loop in the Linalg operation 1056 /// that is marked "parallel" is a candidate. Whether it is actually converted 1057 /// to a parallel operation depends on the requested strategy. 1058 static bool isParallelFor(CodeGen &codegen, bool isOuter, bool isReduction, 1059 bool isSparse, bool isVector) { 1060 switch (codegen.options.parallelizationStrategy) { 1061 case SparseParallelizationStrategy::kNone: 1062 return false; 1063 case SparseParallelizationStrategy::kDenseOuterLoop: 1064 return isOuter && !isSparse && !isReduction && !isVector; 1065 case SparseParallelizationStrategy::kAnyStorageOuterLoop: 1066 return isOuter && !isReduction && !isVector; 1067 case SparseParallelizationStrategy::kDenseAnyLoop: 1068 return !isSparse && !isReduction && !isVector; 1069 case SparseParallelizationStrategy::kAnyStorageAnyLoop: 1070 return !isReduction && !isVector; 1071 } 1072 llvm_unreachable("unexpected parallelization strategy"); 1073 } 1074 1075 /// Checks unit stride for dense tensors. The iteration graph may have ignored 1076 /// dense access patterns in order to avoid cycles (sparse access patterns are 1077 /// always placed innermost), but that means dense access has become strided. 1078 /// This prevents effective vectorization. 1079 static bool denseUnitStrides(Merger &merger, linalg::GenericOp op, 1080 unsigned idx) { 1081 for (OpOperand *t : op.getInputAndOutputOperands()) { 1082 if (!getSparseTensorEncoding(t->get().getType())) { 1083 auto map = op.getTiedIndexingMap(t); 1084 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 1085 AffineExpr a = map.getResult(d); 1086 // Report non-unit stride if innermost index appears at an outer 1087 // dimension (true non-unit stride) or if the innermost index appears 1088 // in a compound subscript in the innermost dimension. Even if the 1089 // latter is unit stride, it does not play well with scatter/gather. 1090 // TODO: accept unit stride affine innermost like a[i,j+k+1]? 1091 if (a.isFunctionOfDim(idx) && 1092 ((d != rank - 1) || (a.getKind() != AffineExprKind::DimId))) 1093 return false; 1094 } 1095 } 1096 } 1097 return true; 1098 } 1099 1100 /// Generates a for-loop on a single index. 1101 static Operation *genFor(Merger &merger, CodeGen &codegen, 1102 PatternRewriter &rewriter, linalg::GenericOp op, 1103 bool isOuter, bool isInner, unsigned idx, 1104 BitVector &indices) { 1105 unsigned fb = indices.find_first(); 1106 unsigned tensor = merger.tensor(fb); 1107 assert(idx == merger.index(fb)); 1108 auto iteratorTypes = op.iterator_types().getValue(); 1109 bool isReduction = isReductionIterator(iteratorTypes[idx]); 1110 bool isSparse = merger.isDim(fb, Dim::kSparse); 1111 bool isVector = !codegen.sparseOut && 1112 isVectorFor(codegen, isInner, isSparse) && 1113 denseUnitStrides(merger, op, idx); 1114 bool isParallel = 1115 !codegen.sparseOut && 1116 isParallelFor(codegen, isOuter, isReduction, isSparse, isVector); 1117 1118 // Prepare vector length. 1119 if (isVector) 1120 codegen.curVecLength = codegen.options.vectorLength; 1121 1122 // Loop bounds and increment. 1123 Location loc = op.getLoc(); 1124 Value lo = isSparse ? codegen.pidxs[tensor][idx] : codegen.loops[idx]; 1125 Value hi = isSparse ? codegen.highs[tensor][idx] : codegen.sizes[idx]; 1126 Value step = constantIndex(rewriter, loc, codegen.curVecLength); 1127 1128 // Emit a parallel loop. 1129 if (isParallel) { 1130 assert(!isVector); 1131 scf::ParallelOp parOp = rewriter.create<scf::ParallelOp>(loc, lo, hi, step); 1132 if (isSparse) 1133 codegen.pidxs[tensor][idx] = parOp.getInductionVars()[0]; 1134 else 1135 codegen.loops[idx] = parOp.getInductionVars()[0]; 1136 rewriter.setInsertionPointToStart(parOp.getBody()); 1137 return parOp; 1138 } 1139 1140 // Emit a sequential or vector loop. 1141 SmallVector<Value, 4> operands; 1142 if (codegen.redVal) { 1143 // In a vector loop, bring reduction into SIMD form, if not already. 1144 if (isVector && !codegen.redVal.getType().isa<VectorType>()) { 1145 VectorType vtp = vectorType(codegen, codegen.redVal.getType()); 1146 Value vred = genVectorReducInit(codegen, rewriter, loc, vtp); 1147 updateReduc(merger, codegen, vred); 1148 } 1149 operands.push_back(codegen.redVal); 1150 } 1151 if (codegen.expValues) 1152 operands.push_back(codegen.expCount); 1153 scf::ForOp forOp = rewriter.create<scf::ForOp>(loc, lo, hi, step, operands); 1154 if (codegen.redVal) 1155 updateReduc(merger, codegen, forOp.getRegionIterArgs().front()); 1156 if (codegen.expValues) 1157 codegen.expCount = forOp.getRegionIterArgs().back(); 1158 // Assign induction variable to sparse or dense index. 1159 Value iv = forOp.getInductionVar(); 1160 if (isSparse) 1161 codegen.pidxs[tensor][idx] = iv; 1162 else 1163 codegen.loops[idx] = iv; 1164 rewriter.setInsertionPointToStart(forOp.getBody()); 1165 // Share vector iteration mask between all subsequent loads/stores. 1166 if (isVector) 1167 codegen.curVecMask = genVectorMask(codegen, rewriter, iv, lo, hi, step); 1168 return forOp; 1169 } 1170 1171 /// Emit a while-loop for co-iteration over multiple indices. 1172 static Operation *genWhile(Merger &merger, CodeGen &codegen, 1173 PatternRewriter &rewriter, linalg::GenericOp op, 1174 unsigned idx, bool needsUniv, 1175 BitVector &indices) { 1176 SmallVector<Type, 4> types; 1177 SmallVector<Value, 4> operands; 1178 // Construct the while-loop with a parameter for each index. 1179 Type indexType = rewriter.getIndexType(); 1180 for (unsigned b = 0, be = indices.size(); b < be; b++) { 1181 if (indices[b] && merger.isDim(b, Dim::kSparse)) { 1182 unsigned tensor = merger.tensor(b); 1183 assert(idx == merger.index(b)); 1184 types.push_back(indexType); 1185 operands.push_back(codegen.pidxs[tensor][idx]); 1186 } 1187 } 1188 if (codegen.redVal) { 1189 types.push_back(codegen.redVal.getType()); 1190 operands.push_back(codegen.redVal); 1191 } 1192 if (codegen.expValues) { 1193 types.push_back(indexType); 1194 operands.push_back(codegen.expCount); 1195 } 1196 if (needsUniv) { 1197 types.push_back(indexType); 1198 operands.push_back(codegen.loops[idx]); 1199 } 1200 assert(types.size() == operands.size()); 1201 Location loc = op.getLoc(); 1202 scf::WhileOp whileOp = rewriter.create<scf::WhileOp>(loc, types, operands); 1203 1204 SmallVector<Location> locs(types.size(), loc); 1205 Block *before = rewriter.createBlock(&whileOp.getBefore(), {}, types, locs); 1206 Block *after = rewriter.createBlock(&whileOp.getAfter(), {}, types, locs); 1207 1208 // Build the "before" region, which effectively consists 1209 // of a conjunction of "i < upper" tests on all induction. 1210 rewriter.setInsertionPointToStart(&whileOp.getBefore().front()); 1211 Value cond; 1212 unsigned o = 0; 1213 for (unsigned b = 0, be = indices.size(); b < be; b++) { 1214 if (indices[b] && merger.isDim(b, Dim::kSparse)) { 1215 unsigned tensor = merger.tensor(b); 1216 assert(idx == merger.index(b)); 1217 Value op1 = before->getArgument(o); 1218 Value op2 = codegen.highs[tensor][idx]; 1219 Value opc = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, 1220 op1, op2); 1221 cond = cond ? rewriter.create<arith::AndIOp>(loc, cond, opc) : opc; 1222 codegen.pidxs[tensor][idx] = after->getArgument(o++); 1223 } 1224 } 1225 if (codegen.redVal) 1226 updateReduc(merger, codegen, after->getArgument(o++)); 1227 if (codegen.expValues) 1228 codegen.expCount = after->getArgument(o++); 1229 if (needsUniv) 1230 codegen.loops[idx] = after->getArgument(o++); 1231 assert(o == operands.size()); 1232 rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments()); 1233 rewriter.setInsertionPointToStart(&whileOp.getAfter().front()); 1234 return whileOp; 1235 } 1236 1237 /// Generates a for-loop or a while-loop, depending on whether it implements 1238 /// singleton iteration or co-iteration over the given conjunction. 1239 static Operation *genLoop(Merger &merger, CodeGen &codegen, 1240 PatternRewriter &rewriter, linalg::GenericOp op, 1241 std::vector<unsigned> &topSort, unsigned at, 1242 bool needsUniv, BitVector &indices) { 1243 unsigned idx = topSort[at]; 1244 if (indices.count() == 1) { 1245 bool isOuter = at == 0; 1246 bool isInner = at == topSort.size() - 1; 1247 return genFor(merger, codegen, rewriter, op, isOuter, isInner, idx, 1248 indices); 1249 } 1250 return genWhile(merger, codegen, rewriter, op, idx, needsUniv, indices); 1251 } 1252 1253 /// Generates the local variables for this loop, consisting of the sparse 1254 /// indices, restored universal dense index, and dense positions. 1255 static void genLocals(Merger &merger, CodeGen &codegen, 1256 PatternRewriter &rewriter, linalg::GenericOp op, 1257 std::vector<unsigned> &topSort, unsigned at, 1258 bool needsUniv, BitVector &locals) { 1259 Location loc = op.getLoc(); 1260 unsigned idx = topSort[at]; 1261 1262 // Initialize sparse indices. 1263 Value min; 1264 for (unsigned b = 0, be = locals.size(); b < be; b++) { 1265 if (locals[b] && merger.isDim(b, Dim::kSparse)) { 1266 unsigned tensor = merger.tensor(b); 1267 assert(idx == merger.index(b)); 1268 Value ptr = codegen.indices[tensor][idx]; 1269 Value s = codegen.pidxs[tensor][idx]; 1270 Value load = genLoad(codegen, rewriter, loc, ptr, s); 1271 codegen.idxs[tensor][idx] = load; 1272 if (!needsUniv) { 1273 if (min) { 1274 Value cmp = rewriter.create<arith::CmpIOp>( 1275 loc, arith::CmpIPredicate::ult, load, min); 1276 min = rewriter.create<arith::SelectOp>(loc, cmp, load, min); 1277 } else { 1278 min = load; 1279 } 1280 } 1281 } 1282 } 1283 1284 // Merge dense universal index over minimum. 1285 if (min) { 1286 assert(!needsUniv); 1287 codegen.loops[idx] = min; 1288 } 1289 1290 // Initialize dense positions. Note that we generate dense indices of the 1291 // output tensor unconditionally, since they may not appear in the lattice, 1292 // but may be needed for linearized codegen. 1293 for (unsigned b = 0, be = locals.size(); b < be; b++) { 1294 if ((locals[b] || merger.isOutTensor(b, idx)) && 1295 merger.isDim(b, Dim::kDense)) { 1296 unsigned tensor = merger.tensor(b); 1297 assert(idx == merger.index(b)); 1298 unsigned pat = at; 1299 for (; pat != 0; pat--) 1300 if (codegen.pidxs[tensor][topSort[pat - 1]]) 1301 break; 1302 Value p = (pat == 0) ? constantIndex(rewriter, loc, 0) 1303 : codegen.pidxs[tensor][topSort[pat - 1]]; 1304 codegen.pidxs[tensor][idx] = genAddress( 1305 codegen, rewriter, loc, codegen.sizes[idx], p, codegen.loops[idx]); 1306 } 1307 } 1308 1309 // Move the insertion indices in lexicographic index order. During access 1310 // pattern expansion, we can skip setting the innermost dimension. 1311 if (codegen.sparseOut && !codegen.expValues) { 1312 Value pos = constantIndex(rewriter, loc, at); 1313 rewriter.create<memref::StoreOp>(loc, codegen.loops[idx], codegen.lexIdx, 1314 pos); 1315 } 1316 } 1317 1318 /// Generates the induction structure for a while-loop. 1319 static void genWhileInduction(Merger &merger, CodeGen &codegen, 1320 PatternRewriter &rewriter, linalg::GenericOp op, 1321 unsigned idx, bool needsUniv, 1322 BitVector &induction, 1323 scf::WhileOp whileOp) { 1324 Location loc = op.getLoc(); 1325 // Finalize each else branch of all if statements. 1326 if (codegen.redVal || codegen.expValues) { 1327 while (auto ifOp = dyn_cast_or_null<scf::IfOp>( 1328 rewriter.getInsertionBlock()->getParentOp())) { 1329 unsigned y = 0; 1330 SmallVector<Value, 4> yields; 1331 if (codegen.redVal) { 1332 yields.push_back(codegen.redVal); 1333 updateReduc(merger, codegen, ifOp.getResult(y++)); 1334 } 1335 if (codegen.expValues) { 1336 yields.push_back(codegen.expCount); 1337 codegen.expCount = ifOp->getResult(y++); 1338 } 1339 assert(y == yields.size()); 1340 rewriter.create<scf::YieldOp>(loc, yields); 1341 rewriter.setInsertionPointAfter(ifOp); 1342 } 1343 } 1344 rewriter.setInsertionPointToEnd(&whileOp.getAfter().front()); 1345 // Finalize the induction. Note that the induction could be performed 1346 // in the individual if-branches to avoid re-evaluating the conditions. 1347 // However, that would result in a rather elaborate forest of yield 1348 // instructions during code generation. Moreover, performing the induction 1349 // after the if-statements more closely resembles code generated by TACO. 1350 unsigned o = 0; 1351 SmallVector<Value, 4> operands; 1352 Value one = constantIndex(rewriter, loc, 1); 1353 for (unsigned b = 0, be = induction.size(); b < be; b++) { 1354 if (induction[b] && merger.isDim(b, Dim::kSparse)) { 1355 unsigned tensor = merger.tensor(b); 1356 assert(idx == merger.index(b)); 1357 Value op1 = codegen.idxs[tensor][idx]; 1358 Value op2 = codegen.loops[idx]; 1359 Value op3 = codegen.pidxs[tensor][idx]; 1360 Value cmp = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, 1361 op1, op2); 1362 Value add = rewriter.create<arith::AddIOp>(loc, op3, one); 1363 operands.push_back(rewriter.create<arith::SelectOp>(loc, cmp, add, op3)); 1364 codegen.pidxs[tensor][idx] = whileOp->getResult(o++); 1365 } 1366 } 1367 if (codegen.redVal) { 1368 operands.push_back(codegen.redVal); 1369 updateReduc(merger, codegen, whileOp->getResult(o++)); 1370 } 1371 if (codegen.expValues) { 1372 operands.push_back(codegen.expCount); 1373 codegen.expCount = whileOp->getResult(o++); 1374 } 1375 if (needsUniv) { 1376 operands.push_back( 1377 rewriter.create<arith::AddIOp>(loc, codegen.loops[idx], one)); 1378 codegen.loops[idx] = whileOp->getResult(o++); 1379 } 1380 assert(o == operands.size()); 1381 rewriter.create<scf::YieldOp>(loc, operands); 1382 rewriter.setInsertionPointAfter(whileOp); 1383 } 1384 1385 /// Generates the induction structure for a for-loop. 1386 static void genForInduction(Merger &merger, CodeGen &codegen, 1387 PatternRewriter &rewriter, linalg::GenericOp op, 1388 Operation *loop) { 1389 Location loc = op.getLoc(); 1390 unsigned o = 0; 1391 SmallVector<Value, 4> operands; 1392 if (codegen.redVal) { 1393 operands.push_back(codegen.redVal); 1394 updateReduc(merger, codegen, loop->getResult(o++)); 1395 } 1396 if (codegen.expValues) { 1397 operands.push_back(codegen.expCount); 1398 codegen.expCount = loop->getResult(o++); 1399 } 1400 assert(o == operands.size()); 1401 if (o > 0) 1402 rewriter.create<scf::YieldOp>(loc, operands); 1403 rewriter.setInsertionPointAfter(loop); 1404 } 1405 1406 /// Generates a single if-statement within a while-loop. 1407 static scf::IfOp genIf(Merger &merger, CodeGen &codegen, 1408 PatternRewriter &rewriter, linalg::GenericOp op, 1409 unsigned idx, BitVector &conditions) { 1410 Location loc = op.getLoc(); 1411 SmallVector<Type, 4> types; 1412 Value cond; 1413 for (unsigned b = 0, be = conditions.size(); b < be; b++) { 1414 if (conditions[b]) { 1415 unsigned tensor = merger.tensor(b); 1416 assert(idx == merger.index(b)); 1417 Value clause; 1418 if (merger.isDim(b, Dim::kSparse)) { 1419 Value op1 = codegen.idxs[tensor][idx]; 1420 Value op2 = codegen.loops[idx]; 1421 clause = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, 1422 op1, op2); 1423 } else { 1424 clause = constantI1(rewriter, loc, true); 1425 } 1426 cond = cond ? rewriter.create<arith::AndIOp>(loc, cond, clause) : clause; 1427 } 1428 } 1429 if (codegen.redVal) 1430 types.push_back(codegen.redVal.getType()); 1431 if (codegen.expValues) 1432 types.push_back(rewriter.getIndexType()); 1433 scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, types, cond, /*else=*/true); 1434 rewriter.setInsertionPointToStart(&ifOp.getThenRegion().front()); 1435 return ifOp; 1436 } 1437 1438 /// Generates end of true branch of if-statement within a while-loop. 1439 static void endIf(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 1440 linalg::GenericOp op, scf::IfOp ifOp, Operation *loop, 1441 Value redInput, Value cntInput) { 1442 SmallVector<Value, 4> operands; 1443 if (codegen.redVal) { 1444 operands.push_back(codegen.redVal); 1445 updateReduc(merger, codegen, redInput); 1446 } 1447 if (codegen.expValues) { 1448 operands.push_back(codegen.expCount); 1449 codegen.expCount = cntInput; 1450 } 1451 if (!operands.empty()) 1452 rewriter.create<scf::YieldOp>(op.getLoc(), operands); 1453 rewriter.setInsertionPointToStart(&ifOp.getElseRegion().front()); 1454 } 1455 1456 //===----------------------------------------------------------------------===// 1457 // Sparse compiler synthesis methods (loop sequence). 1458 //===----------------------------------------------------------------------===// 1459 1460 /// Starts a loop sequence at given level. Returns true if 1461 /// the universal loop index must be maintained at this level. 1462 static bool startLoopSeq(Merger &merger, CodeGen &codegen, 1463 PatternRewriter &rewriter, linalg::GenericOp op, 1464 std::vector<unsigned> &topSort, unsigned exp, 1465 unsigned at, unsigned idx, unsigned ldx, 1466 unsigned lts) { 1467 assert(codegen.curVecLength == 1); 1468 assert(!codegen.loops[idx]); 1469 // Emit invariants at this loop sequence level. 1470 genInvariants(merger, codegen, rewriter, op, exp, ldx, /*atStart=*/true); 1471 // Emit access pattern expansion for sparse tensor output. 1472 genExpansion(merger, codegen, rewriter, op, at, /*atStart=*/true); 1473 // Emit further intitialization at this loop sequence level. 1474 unsigned l0 = merger.set(lts)[0]; 1475 bool needsUniv = 1476 genInit(merger, codegen, rewriter, op, topSort, at, merger.lat(l0).bits); 1477 // Maintain the universal index only if it is actually 1478 // consumed by a subsequent lattice point. 1479 if (needsUniv) { 1480 unsigned lsize = merger.set(lts).size(); 1481 for (unsigned i = 1; i < lsize; i++) { 1482 unsigned li = merger.set(lts)[i]; 1483 if (!merger.hasAnyDimOf(merger.lat(li).simple, Dim::kSparse)) 1484 return true; 1485 } 1486 } 1487 return false; 1488 } 1489 1490 /// Starts a single loop in current sequence. 1491 static Operation *startLoop(Merger &merger, CodeGen &codegen, 1492 PatternRewriter &rewriter, linalg::GenericOp op, 1493 std::vector<unsigned> &topSort, unsigned at, 1494 unsigned li, bool needsUniv) { 1495 assert(codegen.curVecLength == 1); 1496 // Emit the for/while-loop control. 1497 Operation *loop = genLoop(merger, codegen, rewriter, op, topSort, at, 1498 needsUniv, merger.lat(li).simple); 1499 // Emit the locals for this loop. 1500 genLocals(merger, codegen, rewriter, op, topSort, at, needsUniv, 1501 merger.lat(li).bits); 1502 return loop; 1503 } 1504 1505 /// Ends a single loop in current sequence. Returns new values for needsUniv. 1506 static bool endLoop(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 1507 linalg::GenericOp op, Operation *loop, unsigned idx, 1508 unsigned li, bool needsUniv) { 1509 codegen.curVecLength = 1; 1510 // End a while-loop. 1511 if (auto whileOp = dyn_cast<scf::WhileOp>(loop)) { 1512 genWhileInduction(merger, codegen, rewriter, op, idx, needsUniv, 1513 merger.lat(li).bits, whileOp); 1514 return needsUniv; 1515 } 1516 // End a for-loop. 1517 genForInduction(merger, codegen, rewriter, op, loop); 1518 return false; 1519 } 1520 1521 /// Ends a loop sequence at given level. 1522 static void endLoopSeq(Merger &merger, CodeGen &codegen, 1523 PatternRewriter &rewriter, linalg::GenericOp op, 1524 unsigned exp, unsigned at, unsigned idx, unsigned ldx) { 1525 assert(codegen.curVecLength == 1); 1526 codegen.loops[idx] = Value(); 1527 // Bring a pending reduction back from SIMD form when sequence ends. 1528 if (codegen.redVal) 1529 if (auto vtp = codegen.redVal.getType().dyn_cast<VectorType>()) 1530 updateReduc(merger, codegen, 1531 genVectorReducEnd(codegen, rewriter, op.getLoc(), vtp)); 1532 // Unmark bookkeeping of invariants and loop index. 1533 genInvariants(merger, codegen, rewriter, op, exp, ldx, /*atStart=*/false); 1534 // Finalize access pattern expansion for sparse tensor output. 1535 genExpansion(merger, codegen, rewriter, op, at, /*atStart=*/false); 1536 } 1537 1538 /// Recursively generates code while computing iteration lattices in order 1539 /// to manage the complexity of implementing co-iteration over unions 1540 /// and intersections of sparse iterations spaces. 1541 static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 1542 linalg::GenericOp op, std::vector<unsigned> &topSort, 1543 unsigned exp, unsigned at) { 1544 // At each leaf, assign remaining tensor (sub)expression to output tensor. 1545 if (at == topSort.size()) { 1546 Value rhs = genExp(merger, codegen, rewriter, op, exp); 1547 genTensorStore(merger, codegen, rewriter, op, rhs); 1548 return; 1549 } 1550 1551 // Construct iteration lattices for current loop index, with L0 at top. 1552 unsigned idx = topSort[at]; 1553 unsigned ldx = at == 0 ? -1u : topSort[at - 1]; 1554 unsigned lts = merger.optimizeSet(merger.buildLattices(exp, idx)); 1555 1556 // Start a loop sequence. 1557 bool needsUniv = startLoopSeq(merger, codegen, rewriter, op, topSort, exp, at, 1558 idx, ldx, lts); 1559 1560 // Emit a loop for every lattice point L0 >= Li in this loop sequence. 1561 unsigned lsize = merger.set(lts).size(); 1562 for (unsigned i = 0; i < lsize; i++) { 1563 // Start a loop. 1564 unsigned li = merger.set(lts)[i]; 1565 Operation *loop = 1566 startLoop(merger, codegen, rewriter, op, topSort, at, li, needsUniv); 1567 1568 // Visit all lattices points with Li >= Lj to generate the 1569 // loop-body, possibly with if statements for coiteration. 1570 Value redInput = codegen.redVal; 1571 Value cntInput = codegen.expCount; 1572 bool isWhile = dyn_cast<scf::WhileOp>(loop) != nullptr; 1573 for (unsigned j = 0; j < lsize; j++) { 1574 unsigned lj = merger.set(lts)[j]; 1575 unsigned ej = merger.lat(lj).exp; 1576 if (li == lj || merger.latGT(li, lj)) { 1577 // Recurse into body of each branch. 1578 if (isWhile) { 1579 scf::IfOp ifOp = 1580 genIf(merger, codegen, rewriter, op, idx, merger.lat(lj).simple); 1581 genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1); 1582 endIf(merger, codegen, rewriter, op, ifOp, loop, redInput, cntInput); 1583 } else { 1584 genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1); 1585 } 1586 } 1587 } 1588 1589 // End a loop. 1590 needsUniv = 1591 endLoop(merger, codegen, rewriter, op, loop, idx, li, needsUniv); 1592 } 1593 1594 // End a loop sequence. 1595 endLoopSeq(merger, codegen, rewriter, op, exp, at, idx, ldx); 1596 } 1597 1598 /// Converts the result computed by the sparse kernel into the required form. 1599 static void genResult(Merger &merger, CodeGen &codegen, 1600 PatternRewriter &rewriter, linalg::GenericOp op) { 1601 OpOperand *lhs = op.getOutputOperand(0); 1602 Type resType = lhs->get().getType(); 1603 if (getSparseTensorEncoding(resType)) { 1604 // The sparse tensor rematerializes from the original sparse tensor's 1605 // underlying sparse storage format. 1606 rewriter.replaceOpWithNewOp<LoadOp>(op, resType, lhs->get(), 1607 codegen.sparseOut == lhs); 1608 } else { 1609 // To rematerialize an non-annotated tensor, simply load it 1610 // from the bufferized value. 1611 Value val = codegen.buffers.back(); // value array 1612 rewriter.replaceOpWithNewOp<bufferization::ToTensorOp>(op, resType, val); 1613 } 1614 } 1615 1616 //===----------------------------------------------------------------------===// 1617 // Sparse compiler rewriting methods. 1618 //===----------------------------------------------------------------------===// 1619 1620 namespace { 1621 1622 /// Sparse rewriting rule for generic Lingalg operation. 1623 struct GenericOpSparsifier : public OpRewritePattern<linalg::GenericOp> { 1624 public: 1625 GenericOpSparsifier(MLIRContext *context, SparsificationOptions o) 1626 : OpRewritePattern<linalg::GenericOp>(context), options(o) {} 1627 1628 LogicalResult matchAndRewrite(linalg::GenericOp op, 1629 PatternRewriter &rewriter) const override { 1630 // Detects sparse annotations and translate the per-dimension sparsity 1631 // information for all tensors to loop indices in the kernel. 1632 assert(op.getNumOutputs() == 1); 1633 unsigned numTensors = op.getNumInputsAndOutputs(); 1634 unsigned numLoops = op.iterator_types().getValue().size(); 1635 Merger merger(numTensors, numLoops); 1636 if (!findSparseAnnotations(merger, op)) 1637 return failure(); 1638 1639 // Computes a topologically sorted iteration graph to ensure 1640 // tensors are visited in natural index order. Fails on cycles. 1641 // This assumes that higher-level passes have already put the 1642 // tensors in each tensor expression in a feasible order. 1643 std::vector<unsigned> topSort; 1644 if (!computeIterationGraph(merger, op, topSort, 1645 SortMask::kIncludeUndef | 1646 SortMask::kIncludeDense) && 1647 !computeIterationGraph(merger, op, topSort, SortMask::kIncludeUndef) && 1648 !computeIterationGraph(merger, op, topSort, SortMask::kIncludeDense) && 1649 !computeIterationGraph(merger, op, topSort, SortMask::kSparseOnly)) 1650 return failure(); 1651 1652 // Builds the tensor expression for the Linalg operation in SSA form. 1653 Optional<unsigned> optExp = merger.buildTensorExpFromLinalg(op); 1654 if (!optExp.hasValue()) 1655 return failure(); 1656 unsigned exp = optExp.getValue(); 1657 1658 // Rejects an inadmissable tensor expression. 1659 OpOperand *sparseOut = nullptr; 1660 unsigned outerParNest = 0; 1661 if (!isAdmissableTensorExp(merger, op, topSort, exp, &sparseOut, 1662 outerParNest)) 1663 return failure(); 1664 1665 // Recursively generates code. 1666 merger.setHasSparseOut(sparseOut != nullptr); 1667 CodeGen codegen(options, numTensors, numLoops, sparseOut, outerParNest); 1668 genBuffers(merger, codegen, rewriter, op); 1669 genStmt(merger, codegen, rewriter, op, topSort, exp, 0); 1670 genResult(merger, codegen, rewriter, op); 1671 return success(); 1672 } 1673 1674 private: 1675 /// Options to control sparse code generation. 1676 SparsificationOptions options; 1677 }; 1678 1679 } // namespace 1680 1681 /// Populates the given patterns list with rewriting rules required for 1682 /// the sparsification of linear algebra operations. 1683 void mlir::populateSparsificationPatterns( 1684 RewritePatternSet &patterns, const SparsificationOptions &options) { 1685 patterns.add<GenericOpSparsifier>(patterns.getContext(), options); 1686 } 1687