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