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