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