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