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 "mlir/Dialect/Linalg/IR/LinalgOps.h" 14 #include "mlir/Dialect/Linalg/Utils/Utils.h" 15 #include "mlir/Dialect/MemRef/IR/MemRef.h" 16 #include "mlir/Dialect/SCF/SCF.h" 17 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" 18 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h" 19 #include "mlir/Dialect/SparseTensor/Utils/Merger.h" 20 #include "mlir/Dialect/StandardOps/IR/Ops.h" 21 #include "mlir/Dialect/Vector/VectorOps.h" 22 #include "mlir/IR/Matchers.h" 23 #include "mlir/IR/TensorEncoding.h" 24 #include "llvm/ADT/SmallBitVector.h" 25 26 using namespace mlir; 27 using namespace mlir::sparse_tensor; 28 29 namespace { 30 31 // Code generation. 32 struct CodeGen { 33 CodeGen(SparsificationOptions o, unsigned numTensors, unsigned numLoops) 34 : options(o), loops(numLoops), sizes(numLoops), buffers(numTensors), 35 pointers(numTensors, std::vector<Value>(numLoops)), 36 indices(numTensors, std::vector<Value>(numLoops)), 37 highs(numTensors, std::vector<Value>(numLoops)), 38 pidxs(numTensors, std::vector<Value>(numLoops)), 39 idxs(numTensors, std::vector<Value>(numLoops)), redExp(-1u), redVal(), 40 curVecLength(1), curVecMask() {} 41 /// Sparsification options. 42 SparsificationOptions options; 43 /// Universal dense indices and upper bounds (by index). The loops array 44 /// is updated with the value of the universal dense index in the current 45 /// loop. The sizes array is set once with the inferred dimension sizes. 46 std::vector<Value> loops; 47 std::vector<Value> sizes; 48 /// Buffers for storing dense and sparse numerical values (by tensor). 49 /// This array is set once during bufferization of all tensors. 50 std::vector<Value> buffers; 51 /// Sparse storage schemes (1-D): pointers and indices (by tensor and index). 52 /// This array is set once during bufferization of all sparse tensors. 53 std::vector<std::vector<Value>> pointers; 54 std::vector<std::vector<Value>> indices; 55 /// Sparse iteration information (by tensor and index). These arrays 56 /// are updated to remain current within the current loop. 57 std::vector<std::vector<Value>> highs; 58 std::vector<std::vector<Value>> pidxs; 59 std::vector<std::vector<Value>> idxs; 60 /// Current reduction, updated during code generation. When indices of a 61 /// reduction are exhausted, all inner loops can "scalarize" the reduction. 62 // TODO: currently only done for (a chain of) innermost for-loops, where it 63 // is most effective; we could generalize to more outer and while-loops. 64 unsigned redExp; 65 Value redVal; 66 // Current vector length and mask. 67 unsigned curVecLength; 68 Value curVecMask; 69 }; 70 71 } // namespace 72 73 // Helper method to apply dimension ordering permutation. 74 static unsigned perm(SparseTensorEncodingAttr &enc, unsigned d) { 75 if (enc) { 76 auto order = enc.getDimOrdering(); 77 if (order) { 78 assert(order.isPermutation()); 79 return order.getDimPosition(d); 80 } 81 } 82 return d; 83 } 84 85 // Helper method to translate dim level type to internal representation. 86 static Dim toDim(SparseTensorEncodingAttr &enc, unsigned d) { 87 if (enc) { 88 SparseTensorEncodingAttr::DimLevelType tp = enc.getDimLevelType()[d]; 89 if (tp == SparseTensorEncodingAttr::DimLevelType::Compressed) 90 return Dim::kSparse; 91 if (tp == SparseTensorEncodingAttr::DimLevelType::Singleton) 92 return Dim::kSingle; 93 } 94 return Dim::kDense; 95 } 96 97 /// Helper method to inspect sparse encodings in the tensor types. 98 /// Fills the per-dimension sparsity information for all tensors. 99 static bool findSparseAnnotations(Merger &merger, linalg::GenericOp op) { 100 bool annotated = false; 101 for (OpOperand *t : op.getInputAndOutputOperands()) { 102 auto map = op.getTiedIndexingMap(t); 103 if (!map.isProjectedPermutation()) 104 return false; 105 auto enc = getSparseTensorEncoding(t->get().getType()); 106 if (enc) 107 annotated = true; 108 assert(map.getNumResults() == op.getRank(t)); 109 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 110 unsigned idx = map.getDimPosition(perm(enc, d)); 111 merger.setDim(t->getOperandNumber(), idx, toDim(enc, d)); 112 } 113 } 114 return annotated; 115 } 116 117 /// A DFS helper to compute a topological sort. Note that recursion is 118 /// bounded by the number of implicit loops, which is always small. 119 /// Returns false when a cycle is detected. 120 static bool topSortDFS(unsigned i, std::vector<unsigned> &visit, 121 std::vector<unsigned> &topSort, 122 std::vector<std::vector<bool>> &adjM) { 123 if (visit[i] != 0) 124 return visit[i] != 1; // 1 denotes cycle! 125 visit[i] = 1; 126 for (unsigned j = 0, e = visit.size(); j < e; j++) 127 if (adjM[i][j]) 128 if (!topSortDFS(j, visit, topSort, adjM)) 129 return false; 130 visit[i] = 2; 131 topSort.push_back(i); 132 return true; 133 } 134 135 /// Computes a topologically sorted iteration graph for the linalg operation. 136 /// Ensures all tensors are visited in natural index order. This is essential 137 /// for sparse storage formats since these only support access along fixed 138 /// dimensions. Even for dense storage formats, however, the natural index 139 /// order yields innermost unit-stride access with better spatial locality. 140 static bool computeIterationGraph(Merger &merger, linalg::GenericOp op, 141 std::vector<unsigned> &topSort, 142 bool sparseOnly) { 143 // Set up an n x n from/to adjacency matrix of the iteration graph 144 // for the implicit loop indices i_0 .. i_n-1. 145 unsigned n = op.getNumLoops(); 146 std::vector<std::vector<bool>> adjM(n, std::vector<bool>(n, false)); 147 148 // Iterate over the indexing maps of every tensor in the tensor expression. 149 for (OpOperand *t : op.getInputAndOutputOperands()) { 150 auto map = op.getTiedIndexingMap(t); 151 auto enc = getSparseTensorEncoding(t->get().getType()); 152 assert(map.getNumDims() == n); 153 // Skip dense tensor constraints when sparse only is requested. 154 if (sparseOnly && !enc) 155 continue; 156 // Each tensor expression and optional dimension ordering (row-major 157 // by default) puts an ordering constraint on the loop indices. For 158 // example, the tensor expresion A_ijk forces the ordering i < j < k 159 // on the loop indices if no explicit dimension ordering is given. 160 for (unsigned d = 1, rank = map.getNumResults(); d < rank; d++) { 161 unsigned f = map.getDimPosition(perm(enc, d - 1)); 162 unsigned t = map.getDimPosition(perm(enc, d)); 163 adjM[f][t] = true; 164 } 165 } 166 167 // Topologically sort the iteration graph to determine loop order. 168 // Report failure for a cyclic iteration graph. 169 topSort.clear(); 170 topSort.reserve(n); 171 std::vector<unsigned> visit(n, 0); 172 for (unsigned i = 0; i < n; i++) 173 if (visit[i] == 0) 174 if (!topSortDFS(i, visit, topSort, adjM)) 175 return false; // cycle! 176 std::reverse(std::begin(topSort), std::end(topSort)); 177 return true; 178 } 179 180 /// Returns true when the tensor expression is admissable for codegen. 181 /// Since all sparse input tensors are admissable, we just need to check 182 /// whether the output tensor in the tensor expression codegen is admissable. 183 static bool isAdmissableTensorExp(Merger &merger, linalg::GenericOp op, 184 unsigned exp) { 185 OpOperand *lhs = op.getOutputOperand(0); 186 unsigned tensor = lhs->getOperandNumber(); 187 auto enc = getSparseTensorEncoding(lhs->get().getType()); 188 // An non-annotated output tensor is assumed dense, and becomes a random 189 // access n-dim memref. Admissable since inserstions cannot occur. 190 if (!enc) 191 return true; 192 // An all-dense annotated "sparse" output tensor becomes a linearized random 193 // access 1-dim memref. Also admissable since insertions cannot occur. 194 bool allDense = true; 195 unsigned numLoops = op.iterator_types().getValue().size(); 196 for (unsigned i = 0; i < numLoops; i++) 197 if (merger.isDim(tensor, i, Dim::kSparse)) { 198 allDense = false; 199 break; 200 } 201 if (allDense) 202 return true; 203 // A tensor expression with a sparse output tensor that changes its values 204 // but not its nonzero structure, an operation called "simply dynamic" in 205 // [Bik96,Ch9], is also admissable without special codegen. 206 if (merger.isConjunction(tensor, exp)) 207 return true; 208 // Reject for now since this requires changes to the nonzero structure. 209 // TODO: implement "workspaces" [Kjolstad2019] 210 return false; 211 } 212 213 /// Maps sparse integer option to actual integral storage type. 214 static Type genIntType(PatternRewriter &rewriter, unsigned width) { 215 if (width == 0) 216 return rewriter.getIndexType(); 217 return rewriter.getIntegerType(width); 218 } 219 220 /// Detects in-place annotation on tensor argument. 221 static bool getInPlace(Value val) { 222 if (auto arg = val.dyn_cast<BlockArgument>()) 223 if (auto funcOp = dyn_cast<FuncOp>(arg.getOwner()->getParentOp())) 224 if (auto attr = funcOp.getArgAttrOfType<BoolAttr>( 225 arg.getArgNumber(), linalg::LinalgDialect::kInplaceableAttrName)) 226 return attr.getValue(); 227 return false; 228 } 229 230 /// Generates buffer for the output tensor. 231 static Value genOutputBuffer(CodeGen &codegen, PatternRewriter &rewriter, 232 linalg::GenericOp op, MemRefType denseTp, 233 ArrayRef<Value> args) { 234 Location loc = op.getLoc(); 235 Value tensor = op.getOutputOperand(0)->get(); 236 // The output tensor simply could materialize from the buffer that will 237 // be generated for the tensor present in the outs() clause. This has 238 // the major advantage that the sparse kernel only updates the nonzero 239 // positions for the output tensor. 240 if (getInPlace(tensor)) 241 return rewriter.create<memref::BufferCastOp>(loc, denseTp, tensor); 242 // By default, a new buffer is allocated which is initialized to the 243 // tensor defined in the outs() clause. This is always correct but 244 // introduces a dense initialization component that may negatively 245 // impact the running complexity of the sparse kernel. 246 Value init = rewriter.create<memref::BufferCastOp>(loc, denseTp, tensor); 247 Value alloc = rewriter.create<memref::AllocOp>(loc, denseTp, args); 248 rewriter.create<memref::CopyOp>(loc, init, alloc); 249 return alloc; 250 } 251 252 /// Local bufferization of all dense and sparse data structures. 253 /// This code enables testing the first prototype sparse compiler. 254 // TODO: replace this with a proliferated bufferization strategy 255 static bool genBuffers(Merger &merger, CodeGen &codegen, 256 PatternRewriter &rewriter, linalg::GenericOp op) { 257 Location loc = op.getLoc(); 258 assert(op.getNumInputsAndOutputs() == op.getNumInputs() + 1); 259 // For every tensor, find lower and upper bound on dimensions, set the 260 // same bounds on loop indices, and obtain dense or sparse buffer(s). 261 SmallVector<Value, 4> args; 262 for (OpOperand *t : op.getInputAndOutputOperands()) { 263 unsigned tensor = t->getOperandNumber(); 264 auto shape = op.getShape(t); 265 auto map = op.getTiedIndexingMap(t); 266 auto enc = getSparseTensorEncoding(t->get().getType()); 267 // Scan all dimensions of current tensor. 268 args.clear(); 269 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 270 unsigned idx = map.getDimPosition(perm(enc, d)); 271 // Handle sparse storage schemes. 272 if (merger.isDim(tensor, idx, Dim::kSparse)) { 273 auto dynShape = {ShapedType::kDynamicSize}; 274 auto ptrTp = MemRefType::get( 275 dynShape, genIntType(rewriter, enc.getPointerBitWidth())); 276 auto indTp = MemRefType::get( 277 dynShape, genIntType(rewriter, enc.getIndexBitWidth())); 278 Value dim = rewriter.create<ConstantIndexOp>(loc, d); 279 // Generate sparse primitives to obtains pointer and indices. 280 codegen.pointers[tensor][idx] = 281 rewriter.create<ToPointersOp>(loc, ptrTp, t->get(), dim); 282 codegen.indices[tensor][idx] = 283 rewriter.create<ToIndicesOp>(loc, indTp, t->get(), dim); 284 } 285 // Find upper bound in current dimension. 286 unsigned p = perm(enc, d); 287 Value up = linalg::createOrFoldDimOp(rewriter, loc, t->get(), p); 288 if (shape[p] == MemRefType::kDynamicSize) 289 args.push_back(up); 290 assert(codegen.highs[tensor][idx] == nullptr); 291 codegen.sizes[idx] = codegen.highs[tensor][idx] = up; 292 } 293 // Perform the required bufferization. Dense inputs materialize 294 // from the input tensors. Dense outputs need special handling. 295 // Sparse inputs use sparse primitives to obtain the values. 296 // We also accept in-place all-dense annotated "sparse" outputs. 297 Type elementType = getElementTypeOrSelf(t->get().getType()); 298 if (!enc) { 299 // Non-annotated dense tensors. 300 auto denseTp = MemRefType::get(shape, elementType); 301 if (tensor < op.getNumInputs()) 302 codegen.buffers[tensor] = 303 rewriter.create<memref::BufferCastOp>(loc, denseTp, t->get()); 304 else 305 codegen.buffers[tensor] = 306 genOutputBuffer(codegen, rewriter, op, denseTp, args); 307 } else { 308 // Annotated sparse tensors. 309 if (tensor == op.getNumInputs() && !getInPlace(t->get())) 310 return false; // reject output if not in-place 311 auto dynShape = {ShapedType::kDynamicSize}; 312 auto sparseTp = MemRefType::get(dynShape, elementType); 313 codegen.buffers[tensor] = 314 rewriter.create<ToValuesOp>(loc, sparseTp, t->get()); 315 } 316 } 317 return true; 318 } 319 320 /// Constructs vector type. 321 static VectorType vectorType(CodeGen &codegen, Type etp) { 322 return VectorType::get(codegen.curVecLength, etp); 323 } 324 325 /// Constructs vector type from pointer. 326 static VectorType vectorType(CodeGen &codegen, Value ptr) { 327 return vectorType(codegen, ptr.getType().cast<MemRefType>().getElementType()); 328 } 329 330 /// Constructs vector iteration mask. 331 static Value genVectorMask(CodeGen &codegen, PatternRewriter &rewriter, 332 Value iv, Value lo, Value hi, Value step) { 333 Location loc = iv.getLoc(); 334 VectorType mtp = vectorType(codegen, rewriter.getIntegerType(1)); 335 // Special case if the vector length evenly divides the trip count (for 336 // example, "for i = 0, 128, 16"). A constant all-true mask is generated 337 // so that all subsequent masked memory operations are immediately folded 338 // into unconditional memory operations. 339 IntegerAttr loInt, hiInt, stepInt; 340 if (matchPattern(lo, m_Constant(&loInt)) && 341 matchPattern(hi, m_Constant(&hiInt)) && 342 matchPattern(step, m_Constant(&stepInt))) { 343 if (((hiInt.getInt() - loInt.getInt()) % stepInt.getInt()) == 0) 344 return rewriter.create<vector::BroadcastOp>( 345 loc, mtp, rewriter.create<ConstantIntOp>(loc, 1, 1)); 346 } 347 // Otherwise, generate a vector mask that avoids overrunning the upperbound 348 // during vector execution. Here we rely on subsequent loop optimizations to 349 // avoid executing the mask in all iterations, for example, by splitting the 350 // loop into an unconditional vector loop and a scalar cleanup loop. 351 Value end = rewriter.create<SubIOp>(loc, hi, iv); 352 return rewriter.create<vector::CreateMaskOp>(loc, mtp, end); 353 } 354 355 /// Generates a vectorized load lhs = a[ind[lo:hi]] or lhs = a[lo:hi]. 356 static Value genVectorLoad(CodeGen &codegen, PatternRewriter &rewriter, 357 Value ptr, ArrayRef<Value> args) { 358 Location loc = ptr.getLoc(); 359 VectorType vtp = vectorType(codegen, ptr); 360 Value pass = rewriter.create<ConstantOp>(loc, vtp, rewriter.getZeroAttr(vtp)); 361 if (args.back().getType().isa<VectorType>()) { 362 SmallVector<Value, 4> scalarArgs(args.begin(), args.end()); 363 Value indexVec = args.back(); 364 scalarArgs.back() = rewriter.create<ConstantIndexOp>(loc, 0); 365 return rewriter.create<vector::GatherOp>( 366 loc, vtp, ptr, scalarArgs, indexVec, codegen.curVecMask, pass); 367 } 368 return rewriter.create<vector::MaskedLoadOp>(loc, vtp, ptr, args, 369 codegen.curVecMask, pass); 370 } 371 372 /// Generates a vectorized store a[ind[lo:hi]] = rhs or a[lo:hi] = rhs. 373 static void genVectorStore(CodeGen &codegen, PatternRewriter &rewriter, 374 Value rhs, Value ptr, ArrayRef<Value> args) { 375 Location loc = ptr.getLoc(); 376 if (args.back().getType().isa<VectorType>()) { 377 SmallVector<Value, 4> scalarArgs(args.begin(), args.end()); 378 Value indexVec = args.back(); 379 scalarArgs.back() = rewriter.create<ConstantIndexOp>(loc, 0); 380 rewriter.create<vector::ScatterOp>(loc, ptr, scalarArgs, indexVec, 381 codegen.curVecMask, rhs); 382 return; 383 } 384 rewriter.create<vector::MaskedStoreOp>(loc, ptr, args, codegen.curVecMask, 385 rhs); 386 } 387 388 /// Generates a vectorized invariant. Here we rely on subsequent loop 389 /// optimizations to hoist the invariant broadcast out of the vector loop. 390 static Value genVectorInvariantValue(CodeGen &codegen, 391 PatternRewriter &rewriter, Value val) { 392 VectorType vtp = vectorType(codegen, val.getType()); 393 return rewriter.create<vector::BroadcastOp>(val.getLoc(), vtp, val); 394 } 395 396 /// Generates a load on a dense or sparse tensor. 397 static Value genTensorLoad(Merger &merger, CodeGen &codegen, 398 PatternRewriter &rewriter, linalg::GenericOp op, 399 unsigned exp) { 400 // Test if the load was hoisted to a higher loop nest. 401 Value val = merger.exp(exp).val; 402 if (val) { 403 if (codegen.curVecLength > 1 && !val.getType().isa<VectorType>()) 404 return genVectorInvariantValue(codegen, rewriter, val); 405 return val; 406 } 407 // Actual load. 408 SmallVector<Value, 4> args; 409 OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor]; 410 unsigned tensor = t->getOperandNumber(); 411 auto map = op.getTiedIndexingMap(t); 412 auto enc = getSparseTensorEncoding(t->get().getType()); 413 unsigned rank = map.getNumResults(); 414 if (enc) { 415 unsigned idx = map.getDimPosition(perm(enc, rank - 1)); 416 assert(codegen.pidxs[tensor][idx] != nullptr); 417 args.push_back(codegen.pidxs[tensor][idx]); // position index 418 } else { 419 for (unsigned d = 0; d < rank; d++) { 420 unsigned idx = map.getDimPosition(d); 421 args.push_back(codegen.loops[idx]); // universal dense index 422 } 423 } 424 Location loc = op.getLoc(); 425 Value ptr = codegen.buffers[tensor]; 426 if (codegen.curVecLength > 1) 427 return genVectorLoad(codegen, rewriter, ptr, args); 428 return rewriter.create<memref::LoadOp>(loc, ptr, args); 429 } 430 431 /// Generates a store on a dense or sparse tensor. 432 static void genTensorStore(Merger &merger, CodeGen &codegen, 433 PatternRewriter &rewriter, linalg::GenericOp op, 434 OpOperand *t, Value rhs) { 435 Location loc = op.getLoc(); 436 // Test if this is a scalarized reduction. 437 OpOperand *lhs = op.getOutputOperand(0); 438 if (lhs == t && codegen.redVal) { 439 if (codegen.curVecLength > 1) 440 rhs = rewriter.create<SelectOp>(loc, codegen.curVecMask, rhs, 441 codegen.redVal); 442 codegen.redVal = rhs; 443 return; 444 } 445 // Actual store. 446 SmallVector<Value, 4> args; 447 unsigned tensor = t->getOperandNumber(); 448 auto map = op.getTiedIndexingMap(t); 449 auto enc = getSparseTensorEncoding(t->get().getType()); 450 unsigned rank = map.getNumResults(); 451 if (enc) { 452 unsigned idx = map.getDimPosition(perm(enc, rank - 1)); 453 assert(codegen.pidxs[tensor][idx] != nullptr); 454 args.push_back(codegen.pidxs[tensor][idx]); // position index 455 } else { 456 for (unsigned d = 0; d < rank; d++) { 457 unsigned idx = map.getDimPosition(d); 458 args.push_back(codegen.loops[idx]); // universal dense index 459 } 460 } 461 Value ptr = codegen.buffers[tensor]; 462 if (codegen.curVecLength > 1) 463 genVectorStore(codegen, rewriter, rhs, ptr, args); 464 else 465 rewriter.create<memref::StoreOp>(loc, rhs, ptr, args); 466 } 467 468 /// Generates a pointer/index load from the sparse storage scheme. Narrower 469 /// data types need to be zero extended before casting the value into the 470 /// index type used for looping and indexing. 471 static Value genLoad(CodeGen &codegen, PatternRewriter &rewriter, Location loc, 472 Value ptr, Value s) { 473 // See https://llvm.org/docs/GetElementPtr.html for some background on 474 // the complications described below. 475 if (codegen.curVecLength > 1) { 476 // Since the index vector is used in a subsequent gather/scatter operations, 477 // which effectively defines an unsigned pointer + signed index, we must 478 // zero extend the vector to an index width. For 8-bit and 16-bit values, 479 // an 32-bit index width suffices. For 32-bit values, zero extending the 480 // elements into 64-bit loses some performance since the 32-bit indexed 481 // gather/scatter is more efficient than the 64-bit index variant (if the 482 // negative 32-bit index space is unused, the enableSIMDIndex32 flag can 483 // preserve this performance). For 64-bit values, there is no good way 484 // to state that the indices are unsigned, with creates the potential of 485 // incorrect address calculations in the unlikely case we need such 486 // extremely large offsets. 487 Type etp = ptr.getType().cast<MemRefType>().getElementType(); 488 Value vload = genVectorLoad(codegen, rewriter, ptr, {s}); 489 if (!etp.isa<IndexType>()) { 490 if (etp.getIntOrFloatBitWidth() < 32) 491 vload = rewriter.create<ZeroExtendIOp>( 492 loc, vload, vectorType(codegen, rewriter.getIntegerType(32))); 493 else if (etp.getIntOrFloatBitWidth() < 64 && 494 !codegen.options.enableSIMDIndex32) 495 vload = rewriter.create<ZeroExtendIOp>( 496 loc, vload, vectorType(codegen, rewriter.getIntegerType(64))); 497 } 498 return vload; 499 } 500 // For the scalar case, we simply zero extend narrower indices into 64-bit 501 // values before casting to index without a performance penalty. Here too, 502 // however, indices that already are 64-bit, in theory, cannot express the 503 // full range as explained above. 504 Value load = rewriter.create<memref::LoadOp>(loc, ptr, s); 505 if (!load.getType().isa<IndexType>()) { 506 if (load.getType().getIntOrFloatBitWidth() < 64) 507 load = rewriter.create<ZeroExtendIOp>(loc, load, 508 rewriter.getIntegerType(64)); 509 load = rewriter.create<IndexCastOp>(loc, load, rewriter.getIndexType()); 510 } 511 return load; 512 } 513 514 /// Generates an invariant value. 515 static Value genInvariantValue(Merger &merger, CodeGen &codegen, 516 PatternRewriter &rewriter, unsigned exp) { 517 Value val = merger.exp(exp).val; 518 if (codegen.curVecLength > 1) 519 return genVectorInvariantValue(codegen, rewriter, val); 520 return val; 521 } 522 523 /// Generates an address computation "sz * p + i". 524 static Value genAddress(CodeGen &codegen, PatternRewriter &rewriter, 525 Location loc, Value size, Value p, Value i) { 526 Value mul = rewriter.create<MulIOp>(loc, size, p); 527 if (auto vtp = i.getType().dyn_cast<VectorType>()) { 528 Value inv = rewriter.create<IndexCastOp>(loc, mul, vtp.getElementType()); 529 mul = genVectorInvariantValue(codegen, rewriter, inv); 530 } 531 return rewriter.create<AddIOp>(loc, mul, i); 532 } 533 534 /// Generates start of a reduction. 535 static Value genReductionStart(Merger &merger, CodeGen &codegen, 536 PatternRewriter &rewriter, 537 linalg::GenericOp op) { 538 if (codegen.redVal) 539 return codegen.redVal; // chained with previous for-loop 540 if (codegen.curVecLength > 1) { 541 // TODO: assumes + reductions for now 542 VectorType vtp = vectorType(codegen, codegen.buffers[codegen.redExp]); 543 return rewriter.create<ConstantOp>(op.getLoc(), vtp, 544 rewriter.getZeroAttr(vtp)); 545 } 546 return genTensorLoad(merger, codegen, rewriter, op, codegen.redExp); 547 } 548 549 /// Generates end of a reduction. 550 static void genReductionEnd(Merger &merger, CodeGen &codegen, 551 PatternRewriter &rewriter, linalg::GenericOp op) { 552 Value red = codegen.redVal; 553 if (!red) 554 return; 555 assert(codegen.curVecLength == 1); 556 codegen.redVal = merger.exp(codegen.redExp).val = Value(); // end chain 557 OpOperand *lhs = op.getOutputOperand(0); 558 if (auto vtp = red.getType().dyn_cast<VectorType>()) { 559 // TODO: assumes + reductions for now 560 StringAttr kind = rewriter.getStringAttr("add"); 561 Value ld = genTensorLoad(merger, codegen, rewriter, op, codegen.redExp); 562 // Integer reductions don't accept an accumulator. 563 if (vtp.getElementType().isa<IntegerType>()) { 564 red = rewriter.create<vector::ReductionOp>(op.getLoc(), ld.getType(), 565 kind, red, ValueRange{}); 566 red = rewriter.create<AddIOp>(op.getLoc(), red, ld); 567 } else { 568 red = rewriter.create<vector::ReductionOp>(op.getLoc(), ld.getType(), 569 kind, red, ld); 570 } 571 } 572 genTensorStore(merger, codegen, rewriter, op, lhs, red); 573 } 574 575 /// Recursively generates tensor expression. 576 static Value genExp(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 577 linalg::GenericOp op, unsigned exp) { 578 Location loc = op.getLoc(); 579 if (exp == -1u) 580 return Value(); 581 if (merger.exp(exp).kind == Kind::kTensor) 582 return genTensorLoad(merger, codegen, rewriter, op, exp); 583 if (merger.exp(exp).kind == Kind::kInvariant) 584 return genInvariantValue(merger, codegen, rewriter, exp); 585 Value v0 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e0); 586 Value v1 = genExp(merger, codegen, rewriter, op, merger.exp(exp).children.e1); 587 if (merger.exp(exp).kind == Kind::kNegI) { 588 // TODO: no negi in std, need to make zero explicit. 589 Type tp = op.getOutputTensorTypes()[0].getElementType(); 590 v1 = v0; 591 v0 = rewriter.create<ConstantOp>(loc, tp, rewriter.getZeroAttr(tp)); 592 if (codegen.curVecLength > 1) 593 v0 = genVectorInvariantValue(codegen, rewriter, v0); 594 } 595 return merger.buildExp(rewriter, loc, exp, v0, v1); 596 } 597 598 /// Hoists loop invariant tensor loads for which indices have been exhausted. 599 static void genInvariants(Merger &merger, CodeGen &codegen, 600 PatternRewriter &rewriter, linalg::GenericOp op, 601 unsigned exp, unsigned ldx, bool hoist) { 602 if (exp == -1u) 603 return; 604 if (merger.exp(exp).kind == Kind::kTensor) { 605 // Inspect tensor indices. 606 bool atLevel = ldx == -1u; 607 OpOperand *t = op.getInputAndOutputOperands()[merger.exp(exp).tensor]; 608 auto map = op.getTiedIndexingMap(t); 609 auto enc = getSparseTensorEncoding(t->get().getType()); 610 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 611 unsigned idx = map.getDimPosition(perm(enc, d)); 612 if (!codegen.loops[idx]) 613 return; // still in play 614 else if (idx == ldx) 615 atLevel = true; 616 } 617 // All exhausted at this level (atLevel denotes exactly at this level). 618 OpOperand *lhs = op.getOutputOperand(0); 619 if (lhs == t) { 620 codegen.redExp = hoist ? exp : -1u; 621 } else if (atLevel) { 622 merger.exp(exp).val = 623 hoist ? genTensorLoad(merger, codegen, rewriter, op, exp) : Value(); 624 } 625 } else if (merger.exp(exp).kind != Kind::kInvariant) { 626 // Traverse into the binary operations. Note that we only hoist 627 // tensor loads, since subsequent MLIR/LLVM passes know how to 628 // deal with all other kinds of derived loop invariants. 629 unsigned e0 = merger.exp(exp).children.e0; 630 unsigned e1 = merger.exp(exp).children.e1; 631 genInvariants(merger, codegen, rewriter, op, e0, ldx, hoist); 632 genInvariants(merger, codegen, rewriter, op, e1, ldx, hoist); 633 } 634 } 635 636 /// Generates initialization code for the subsequent loop sequence at 637 /// current index level. Returns true if the loop sequence needs to 638 /// maintain the universal index. 639 static bool genInit(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 640 linalg::GenericOp op, std::vector<unsigned> &topSort, 641 unsigned at, llvm::BitVector &inits) { 642 bool needsUniv = false; 643 Location loc = op.getLoc(); 644 unsigned idx = topSort[at]; 645 646 // Initialize sparse positions. 647 for (unsigned b = 0, be = inits.size(); b < be; b++) { 648 if (inits[b]) { 649 unsigned tensor = merger.tensor(b); 650 assert(idx == merger.index(b)); 651 if (merger.isDim(b, Dim::kSparse)) { 652 // Initialize sparse index. 653 unsigned pat = at; 654 for (; pat != 0; pat--) { 655 if (codegen.pidxs[tensor][topSort[pat - 1]]) 656 break; 657 } 658 Value ptr = codegen.pointers[tensor][idx]; 659 Value one = rewriter.create<ConstantIndexOp>(loc, 1); 660 Value p0 = (pat == 0) ? rewriter.create<ConstantIndexOp>(loc, 0) 661 : codegen.pidxs[tensor][topSort[pat - 1]]; 662 codegen.pidxs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p0); 663 Value p1 = rewriter.create<AddIOp>(loc, p0, one); 664 codegen.highs[tensor][idx] = genLoad(codegen, rewriter, loc, ptr, p1); 665 } else { 666 // Dense index still in play. 667 needsUniv = true; 668 } 669 } 670 } 671 672 // Initialize the universal dense index. 673 codegen.loops[idx] = rewriter.create<ConstantIndexOp>(loc, 0); 674 return needsUniv; 675 } 676 677 /// Returns vectorization strategy. Any implicit inner loop in the Linalg 678 /// operation is a candidate. Whether it is actually converted to SIMD code 679 /// depends on the requested strategy. 680 static bool isVectorFor(CodeGen &codegen, bool isInner, bool isSparse) { 681 switch (codegen.options.vectorizationStrategy) { 682 case SparseVectorizationStrategy::kNone: 683 return false; 684 case SparseVectorizationStrategy::kDenseInnerLoop: 685 return isInner && !isSparse; 686 case SparseVectorizationStrategy::kAnyStorageInnerLoop: 687 return isInner; 688 } 689 llvm_unreachable("unexpected vectorization strategy"); 690 } 691 692 /// Returns parallelization strategy. Any implicit loop in the Linalg operation 693 /// that is marked "parallel" is a candidate. Whether it is actually converted 694 /// to a parallel operation depends on the requested strategy. 695 static bool isParallelFor(CodeGen &codegen, bool isOuter, bool isReduction, 696 bool isSparse, bool isVector) { 697 switch (codegen.options.parallelizationStrategy) { 698 case SparseParallelizationStrategy::kNone: 699 return false; 700 case SparseParallelizationStrategy::kDenseOuterLoop: 701 return isOuter && !isSparse && !isReduction && !isVector; 702 case SparseParallelizationStrategy::kAnyStorageOuterLoop: 703 return isOuter && !isReduction && !isVector; 704 case SparseParallelizationStrategy::kDenseAnyLoop: 705 return !isSparse && !isReduction && !isVector; 706 case SparseParallelizationStrategy::kAnyStorageAnyLoop: 707 return !isReduction && !isVector; 708 } 709 llvm_unreachable("unexpected parallelization strategy"); 710 } 711 712 /// Checks unit strides for dense tensors. The iteration graph may have ignored 713 /// dense access patterns in order to avoid cycles (sparse access patterns are 714 /// always placed innermost), but that means dense access has become strided. 715 /// For now, we reject vectorization of such cases. 716 /// TODO: implement strided load/stores on dense arrays 717 static bool denseUnitStrides(Merger &merger, linalg::GenericOp op, 718 unsigned idx) { 719 for (OpOperand *t : op.getInputAndOutputOperands()) { 720 if (!getSparseTensorEncoding(t->get().getType())) { 721 auto map = op.getTiedIndexingMap(t); 722 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 723 if (map.getDimPosition(d) == idx && d != rank - 1) 724 return false; 725 } 726 } 727 } 728 return true; 729 } 730 731 /// Generates a for-loop on a single index. 732 static Operation *genFor(Merger &merger, CodeGen &codegen, 733 PatternRewriter &rewriter, linalg::GenericOp op, 734 bool isOuter, bool isInner, unsigned idx, 735 llvm::BitVector &indices) { 736 unsigned fb = indices.find_first(); 737 unsigned tensor = merger.tensor(fb); 738 assert(idx == merger.index(fb)); 739 auto iteratorTypes = op.iterator_types().getValue(); 740 bool isReduction = isReductionIterator(iteratorTypes[idx]); 741 bool isSparse = merger.isDim(fb, Dim::kSparse); 742 bool isVector = isVectorFor(codegen, isInner, isSparse) && 743 denseUnitStrides(merger, op, idx); 744 bool isParallel = 745 isParallelFor(codegen, isOuter, isReduction, isSparse, isVector); 746 747 // Prepare vector length. 748 if (isVector) 749 codegen.curVecLength = codegen.options.vectorLength; 750 751 // Loop bounds and increment. 752 Location loc = op.getLoc(); 753 Value lo = isSparse ? codegen.pidxs[tensor][idx] : codegen.loops[idx]; 754 Value hi = isSparse ? codegen.highs[tensor][idx] : codegen.sizes[idx]; 755 Value step = rewriter.create<ConstantIndexOp>(loc, codegen.curVecLength); 756 757 // Emit a parallel loop. 758 if (isParallel) { 759 assert(!isVector); 760 scf::ParallelOp parOp = rewriter.create<scf::ParallelOp>(loc, lo, hi, step); 761 if (isSparse) 762 codegen.pidxs[tensor][idx] = parOp.getInductionVars()[0]; 763 else 764 codegen.loops[idx] = parOp.getInductionVars()[0]; 765 rewriter.setInsertionPointToStart(parOp.getBody()); 766 return parOp; 767 } 768 769 // Emit a sequential loop, potentially with a scalarized reduction. 770 bool scalarRed = isInner && codegen.redExp != -1u; 771 SmallVector<Value, 4> operands; 772 if (scalarRed) { 773 Value load = genReductionStart(merger, codegen, rewriter, op); 774 operands.push_back(load); 775 } 776 scf::ForOp forOp = rewriter.create<scf::ForOp>(loc, lo, hi, step, operands); 777 if (scalarRed) { 778 codegen.redVal = merger.exp(codegen.redExp).val = 779 forOp.getRegionIterArgs().front(); 780 } 781 // Assign induction variable to sparse or dense index. 782 Value iv = forOp.getInductionVar(); 783 if (isSparse) 784 codegen.pidxs[tensor][idx] = iv; 785 else 786 codegen.loops[idx] = iv; 787 rewriter.setInsertionPointToStart(forOp.getBody()); 788 // Share vector iteration mask between all subsequent loads/stores. 789 if (isVector) 790 codegen.curVecMask = genVectorMask(codegen, rewriter, iv, lo, hi, step); 791 return forOp; 792 } 793 794 /// Emit a while-loop for co-iteration over multiple indices. 795 static Operation *genWhile(Merger &merger, CodeGen &codegen, 796 PatternRewriter &rewriter, linalg::GenericOp op, 797 unsigned idx, bool needsUniv, 798 llvm::BitVector &indices) { 799 SmallVector<Type, 4> types; 800 SmallVector<Value, 4> operands; 801 // Construct the while-loop with a parameter for each index. 802 Type indexType = rewriter.getIndexType(); 803 for (unsigned b = 0, be = indices.size(); b < be; b++) { 804 if (indices[b] && merger.isDim(b, Dim::kSparse)) { 805 unsigned tensor = merger.tensor(b); 806 assert(idx == merger.index(b)); 807 types.push_back(indexType); 808 assert(codegen.pidxs[tensor][idx].getType().isa<IndexType>() && 809 "type mismatch for sparse index"); 810 operands.push_back(codegen.pidxs[tensor][idx]); 811 } 812 } 813 if (needsUniv) { 814 types.push_back(indexType); 815 assert(codegen.loops[idx].getType().isa<IndexType>() && 816 "type mismatch for universal index"); 817 operands.push_back(codegen.loops[idx]); 818 } 819 Location loc = op.getLoc(); 820 scf::WhileOp whileOp = rewriter.create<scf::WhileOp>(loc, types, operands); 821 Block *before = rewriter.createBlock(&whileOp.before(), {}, types); 822 Block *after = rewriter.createBlock(&whileOp.after(), {}, types); 823 824 // Build the "before" region, which effectively consists 825 // of a conjunction of "i < upper" tests on all induction. 826 rewriter.setInsertionPointToStart(&whileOp.before().front()); 827 Value cond; 828 unsigned o = 0; 829 for (unsigned b = 0, be = indices.size(); b < be; b++) { 830 if (indices[b] && merger.isDim(b, Dim::kSparse)) { 831 unsigned tensor = merger.tensor(b); 832 assert(idx == merger.index(b)); 833 Value op1 = before->getArgument(o); 834 Value op2 = codegen.highs[tensor][idx]; 835 Value opc = rewriter.create<CmpIOp>(loc, CmpIPredicate::ult, op1, op2); 836 cond = cond ? rewriter.create<AndOp>(loc, cond, opc) : opc; 837 codegen.pidxs[tensor][idx] = after->getArgument(o++); 838 } 839 } 840 if (needsUniv) 841 codegen.loops[idx] = after->getArgument(o++); 842 assert(o == operands.size()); 843 rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments()); 844 rewriter.setInsertionPointToStart(&whileOp.after().front()); 845 return whileOp; 846 } 847 848 /// Generates a for-loop or a while-loop, depending on whether it implements 849 /// singleton iteration or co-iteration over the given conjunction. 850 static Operation *genLoop(Merger &merger, CodeGen &codegen, 851 PatternRewriter &rewriter, linalg::GenericOp op, 852 std::vector<unsigned> &topSort, unsigned at, 853 bool needsUniv, llvm::BitVector &indices) { 854 unsigned idx = topSort[at]; 855 if (indices.count() == 1) { 856 bool isOuter = at == 0; 857 bool isInner = at == topSort.size() - 1; 858 return genFor(merger, codegen, rewriter, op, isOuter, isInner, idx, 859 indices); 860 } 861 genReductionEnd(merger, codegen, rewriter, op); // cannot chain 862 return genWhile(merger, codegen, rewriter, op, idx, needsUniv, indices); 863 } 864 865 /// Generates the local variables for this loop, consisting of the sparse 866 /// indices, restored universal dense index, and dense positions. 867 static void genLocals(Merger &merger, CodeGen &codegen, 868 PatternRewriter &rewriter, linalg::GenericOp op, 869 std::vector<unsigned> &topSort, unsigned at, 870 bool needsUniv, llvm::BitVector &locals) { 871 Location loc = op.getLoc(); 872 unsigned idx = topSort[at]; 873 874 // Initialize sparse indices. 875 Value min; 876 for (unsigned b = 0, be = locals.size(); b < be; b++) { 877 if (locals[b] && merger.isDim(b, Dim::kSparse)) { 878 unsigned tensor = merger.tensor(b); 879 assert(idx == merger.index(b)); 880 Value ptr = codegen.indices[tensor][idx]; 881 Value s = codegen.pidxs[tensor][idx]; 882 Value load = genLoad(codegen, rewriter, loc, ptr, s); 883 codegen.idxs[tensor][idx] = load; 884 if (!needsUniv) { 885 if (min) { 886 Value cmp = 887 rewriter.create<CmpIOp>(loc, CmpIPredicate::ult, load, min); 888 min = rewriter.create<SelectOp>(loc, cmp, load, min); 889 } else { 890 min = load; 891 } 892 } 893 } 894 } 895 896 // Merge dense universal index over minimum. 897 if (min) { 898 assert(!needsUniv); 899 codegen.loops[idx] = min; 900 } 901 902 // Initialize dense positions. Note that we generate dense indices of the 903 // output tensor unconditionally, since they may not appear in the lattice, 904 // but may be needed for linearized codegen. 905 for (unsigned b = 0, be = locals.size(); b < be; b++) { 906 if ((locals[b] || merger.isOutTensor(b, idx)) && 907 merger.isDim(b, Dim::kDense)) { 908 unsigned tensor = merger.tensor(b); 909 assert(idx == merger.index(b)); 910 unsigned pat = at; 911 for (; pat != 0; pat--) 912 if (codegen.pidxs[tensor][topSort[pat - 1]]) 913 break; 914 Value p = (pat == 0) ? rewriter.create<ConstantIndexOp>(loc, 0) 915 : codegen.pidxs[tensor][topSort[pat - 1]]; 916 codegen.pidxs[tensor][idx] = genAddress( 917 codegen, rewriter, loc, codegen.sizes[idx], p, codegen.loops[idx]); 918 } 919 } 920 } 921 922 /// Generates the induction structure for a while-loop. 923 static void genWhileInduction(Merger &merger, CodeGen &codegen, 924 PatternRewriter &rewriter, linalg::GenericOp op, 925 unsigned idx, bool needsUniv, 926 llvm::BitVector &induction, ResultRange results) { 927 Location loc = op.getLoc(); 928 unsigned o = 0; 929 SmallVector<Value, 4> operands; 930 Value one = rewriter.create<ConstantIndexOp>(loc, 1); 931 for (unsigned b = 0, be = induction.size(); b < be; b++) { 932 if (induction[b] && merger.isDim(b, Dim::kSparse)) { 933 unsigned tensor = merger.tensor(b); 934 assert(idx == merger.index(b)); 935 Value op1 = codegen.idxs[tensor][idx]; 936 Value op2 = codegen.loops[idx]; 937 Value op3 = codegen.pidxs[tensor][idx]; 938 Value cmp = rewriter.create<CmpIOp>(loc, CmpIPredicate::eq, op1, op2); 939 Value add = rewriter.create<AddIOp>(loc, op3, one); 940 operands.push_back(rewriter.create<SelectOp>(loc, cmp, add, op3)); 941 codegen.pidxs[tensor][idx] = results[o++]; 942 } 943 } 944 if (needsUniv) { 945 operands.push_back(rewriter.create<AddIOp>(loc, codegen.loops[idx], one)); 946 codegen.loops[idx] = results[o++]; 947 } 948 assert(o == operands.size()); 949 rewriter.create<scf::YieldOp>(loc, operands); 950 } 951 952 /// Generates a single if-statement within a while-loop. 953 static scf::IfOp genIf(Merger &merger, CodeGen &codegen, 954 PatternRewriter &rewriter, linalg::GenericOp op, 955 unsigned idx, llvm::BitVector &conditions) { 956 Location loc = op.getLoc(); 957 Value cond; 958 for (unsigned b = 0, be = conditions.size(); b < be; b++) { 959 if (conditions[b]) { 960 unsigned tensor = merger.tensor(b); 961 assert(idx == merger.index(b)); 962 Value clause; 963 if (merger.isDim(b, Dim::kSparse)) { 964 Value op1 = codegen.idxs[tensor][idx]; 965 Value op2 = codegen.loops[idx]; 966 clause = rewriter.create<CmpIOp>(loc, CmpIPredicate::eq, op1, op2); 967 } else { 968 clause = rewriter.create<ConstantIntOp>(loc, 1, 1); // true 969 } 970 cond = cond ? rewriter.create<AndOp>(loc, cond, clause) : clause; 971 } 972 } 973 scf::IfOp ifOp = rewriter.create<scf::IfOp>(loc, cond, /*else*/ true); 974 rewriter.setInsertionPointToStart(&ifOp.thenRegion().front()); 975 return ifOp; 976 } 977 978 /// Recursively generates code while computing iteration lattices in order 979 /// to manage the complexity of implementing co-iteration over unions 980 /// and intersections of sparse iterations spaces. 981 static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter, 982 linalg::GenericOp op, std::vector<unsigned> &topSort, 983 unsigned exp, unsigned at) { 984 // At each leaf, assign remaining tensor (sub)expression to output tensor. 985 if (at == topSort.size()) { 986 OpOperand *lhs = op.getOutputOperand(0); 987 Value rhs = genExp(merger, codegen, rewriter, op, exp); 988 genTensorStore(merger, codegen, rewriter, op, lhs, rhs); 989 return; 990 } 991 assert(codegen.curVecLength == 1); 992 993 // Construct iteration lattices for current loop index, with L0 at top. 994 // Then emit initialization code for the loop sequence at this level. 995 // We maintain the universal dense index if dense indices are still 996 // in play for a non-singleton loop sequence. 997 Location loc = op.getLoc(); 998 unsigned idx = topSort[at]; 999 unsigned lts = merger.optimizeSet(merger.buildLattices(exp, idx)); 1000 unsigned lsize = merger.set(lts).size(); 1001 assert(lsize != 0); 1002 unsigned l0 = merger.set(lts)[0]; 1003 unsigned ldx = at == 0 ? -1u : topSort[at - 1]; 1004 genInvariants(merger, codegen, rewriter, op, exp, ldx, /*hoist=*/true); 1005 bool needsUniv = false; 1006 if (genInit(merger, codegen, rewriter, op, topSort, at, 1007 merger.lat(l0).bits)) { 1008 // Maintain the universal index only if it is actually 1009 // consumed by a subsequent lattice point. 1010 for (unsigned i = 1; i < lsize; i++) { 1011 unsigned li = merger.set(lts)[i]; 1012 if (!merger.hasAnyDimOf(merger.lat(li).simple, Dim::kSparse)) { 1013 needsUniv = true; 1014 break; 1015 } 1016 } 1017 } 1018 1019 // Emit a loop for every lattice point L0 >= Li. 1020 for (unsigned i = 0; i < lsize; i++) { 1021 unsigned li = merger.set(lts)[i]; 1022 1023 // Emit loop. 1024 codegen.curVecLength = 1; 1025 llvm::BitVector indices = merger.lat(li).simple; 1026 Operation *loop = 1027 genLoop(merger, codegen, rewriter, op, topSort, at, needsUniv, indices); 1028 genLocals(merger, codegen, rewriter, op, topSort, at, needsUniv, 1029 merger.lat(li).bits); 1030 1031 // Visit all lattices points with Li >= Lj to generate the 1032 // loop-body, possibly with if statements for coiteration. 1033 bool isWhile = dyn_cast<scf::WhileOp>(loop) != nullptr; 1034 for (unsigned j = 0; j < lsize; j++) { 1035 unsigned lj = merger.set(lts)[j]; 1036 unsigned ej = merger.lat(lj).exp; 1037 if (li == lj || merger.latGT(li, lj)) { 1038 // Recurse into body of each branch. 1039 if (isWhile) { 1040 scf::IfOp ifOp = 1041 genIf(merger, codegen, rewriter, op, idx, merger.lat(lj).simple); 1042 genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1); 1043 rewriter.setInsertionPointToStart(&ifOp.elseRegion().front()); 1044 } else { 1045 genStmt(merger, codegen, rewriter, op, topSort, ej, at + 1); 1046 } 1047 } 1048 } 1049 1050 // Wrap-up induction and restore insertion point. 1051 if (isWhile) { 1052 scf::WhileOp whileOp = cast<scf::WhileOp>(loop); 1053 rewriter.setInsertionPointToEnd(&whileOp.after().front()); 1054 genWhileInduction(merger, codegen, rewriter, op, idx, needsUniv, 1055 merger.lat(li).bits, whileOp.results()); 1056 } else { 1057 needsUniv = false; 1058 if (codegen.redVal) { 1059 rewriter.create<scf::YieldOp>(loc, codegen.redVal); 1060 codegen.redVal = loop->getResult(0); 1061 } 1062 } 1063 rewriter.setInsertionPointAfter(loop); 1064 } 1065 1066 // Wrap-up loop sequence. 1067 codegen.curVecLength = 1; 1068 genReductionEnd(merger, codegen, rewriter, op); 1069 genInvariants(merger, codegen, rewriter, op, exp, ldx, /*hoist=*/false); 1070 codegen.loops[idx] = Value(); 1071 } 1072 1073 /// Converts the result computed by the sparse kernel into the required form. 1074 static void genResult(Merger &merger, CodeGen &codegen, 1075 PatternRewriter &rewriter, linalg::GenericOp op) { 1076 Location loc = op.getLoc(); 1077 OpOperand *lhs = op.getOutputOperand(0); 1078 Type resType = lhs->get().getType(); 1079 unsigned tensor = lhs->getOperandNumber(); 1080 auto map = op.getTiedIndexingMap(lhs); 1081 auto enc = getSparseTensorEncoding(resType); 1082 Value result = codegen.buffers.back(); // value array 1083 if (enc) { 1084 // The sparse annotation unambigiously defines the arrays needed 1085 // to "reconstruct" the sparse tensor from the storage scheme 1086 // (even though lowering should never need this eventually). 1087 SmallVector<Value, 4> args; 1088 for (unsigned d = 0, rank = map.getNumResults(); d < rank; d++) { 1089 unsigned idx = map.getDimPosition(perm(enc, d)); 1090 if (merger.isDim(tensor, idx, Dim::kSparse)) { 1091 args.push_back(codegen.pointers[tensor][idx]); 1092 args.push_back(codegen.indices[tensor][idx]); 1093 } 1094 } 1095 args.push_back(result); 1096 result = rewriter.create<ToTensorOp>(loc, resType, args); 1097 } else { 1098 // To "reconstruct" an non-annotated tensor, sipmly load it 1099 // from the bufferized value. 1100 result = rewriter.create<memref::TensorLoadOp>(loc, resType, result); 1101 } 1102 rewriter.replaceOp(op, result); 1103 } 1104 1105 namespace { 1106 1107 /// Sparse rewriting rule for generic Lingalg operation. 1108 struct GenericOpSparsifier : public OpRewritePattern<linalg::GenericOp> { 1109 public: 1110 GenericOpSparsifier(MLIRContext *context, SparsificationOptions o) 1111 : OpRewritePattern<linalg::GenericOp>(context), options(o) {} 1112 1113 LogicalResult matchAndRewrite(linalg::GenericOp op, 1114 PatternRewriter &rewriter) const override { 1115 // Detects sparse annotations and translate the per-dimension sparsity 1116 // information for all tensors to loop indices in the kernel. 1117 assert(op.getNumOutputs() == 1); 1118 unsigned numTensors = op.getNumInputsAndOutputs(); 1119 unsigned numLoops = op.iterator_types().getValue().size(); 1120 Merger merger(numTensors, numLoops); 1121 if (!findSparseAnnotations(merger, op)) 1122 return failure(); 1123 1124 // Computes a topologically sorted iteration graph to ensure 1125 // tensors are visited in natural index order. Fails on cycles. 1126 // This assumes that higher-level passes have already put the 1127 // tensors in each tensor expression in a feasible order. 1128 std::vector<unsigned> topSort; 1129 if (!computeIterationGraph(merger, op, topSort, /*sparseOnly=*/false) && 1130 !computeIterationGraph(merger, op, topSort, /*sparseOnly=*/true)) 1131 return failure(); 1132 1133 // Builds the tensor expression for the Linalg operation in SSA form. 1134 Optional<unsigned> exp = merger.buildTensorExpFromLinalg(op); 1135 if (!exp.hasValue()) 1136 return failure(); 1137 1138 // Rejects an inadmissable tensor expression. 1139 if (!isAdmissableTensorExp(merger, op, exp.getValue())) 1140 return failure(); 1141 1142 // Recursively generates code. 1143 CodeGen codegen(options, numTensors, numLoops); 1144 if (!genBuffers(merger, codegen, rewriter, op)) 1145 return failure(); // could not bufferize 1146 genStmt(merger, codegen, rewriter, op, topSort, exp.getValue(), 0); 1147 genResult(merger, codegen, rewriter, op); 1148 return success(); 1149 } 1150 1151 private: 1152 /// Options to control sparse code generation. 1153 SparsificationOptions options; 1154 }; 1155 1156 } // namespace 1157 1158 /// Populates the given patterns list with rewriting rules required for 1159 /// the sparsification of linear algebra operations. 1160 void mlir::populateSparsificationPatterns( 1161 RewritePatternSet &patterns, const SparsificationOptions &options) { 1162 patterns.add<GenericOpSparsifier>(patterns.getContext(), options); 1163 } 1164