1 //===- SparseTensorConversion.cpp - Sparse tensor primitives conversion ---===//
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 // Convert sparse tensor primitives to calls into a runtime support library.
10 // Note that this is a current implementation choice to keep the conversion
11 // simple. In principle, these primitives could also be converted to actual
12 // elaborate IR code that implements the primitives on the selected sparse
13 // tensor storage schemes.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CodegenUtils.h"
18 
19 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
20 #include "mlir/Dialect/Func/IR/FuncOps.h"
21 #include "mlir/Dialect/LLVMIR/LLVMDialect.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/SparseTensor/IR/SparseTensor.h"
26 #include "mlir/Dialect/SparseTensor/Transforms/Passes.h"
27 #include "mlir/Dialect/Tensor/IR/Tensor.h"
28 #include "mlir/ExecutionEngine/SparseTensorUtils.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 
31 using namespace mlir;
32 using namespace mlir::sparse_tensor;
33 
34 namespace {
35 
36 /// Shorthand aliases for the `emitCInterface` argument to `getFunc()`,
37 /// `createFuncCall()`, and `replaceOpWithFuncCall()`.
38 enum class EmitCInterface : bool { Off = false, On = true };
39 
40 //===----------------------------------------------------------------------===//
41 // Helper methods.
42 //===----------------------------------------------------------------------===//
43 
44 /// Returns the equivalent of `void*` for opaque arguments to the
45 /// execution engine.
46 static Type getOpaquePointerType(OpBuilder &builder) {
47   return LLVM::LLVMPointerType::get(builder.getI8Type());
48 }
49 
50 /// Returns a function reference (first hit also inserts into module). Sets
51 /// the "_emit_c_interface" on the function declaration when requested,
52 /// so that LLVM lowering generates a wrapper function that takes care
53 /// of ABI complications with passing in and returning MemRefs to C functions.
54 static FlatSymbolRefAttr getFunc(Operation *op, StringRef name,
55                                  TypeRange resultType, ValueRange operands,
56                                  EmitCInterface emitCInterface) {
57   MLIRContext *context = op->getContext();
58   auto module = op->getParentOfType<ModuleOp>();
59   auto result = SymbolRefAttr::get(context, name);
60   auto func = module.lookupSymbol<func::FuncOp>(result.getAttr());
61   if (!func) {
62     OpBuilder moduleBuilder(module.getBodyRegion());
63     func = moduleBuilder.create<func::FuncOp>(
64         op->getLoc(), name,
65         FunctionType::get(context, operands.getTypes(), resultType));
66     func.setPrivate();
67     if (static_cast<bool>(emitCInterface))
68       func->setAttr(LLVM::LLVMDialect::getEmitCWrapperAttrName(),
69                     UnitAttr::get(context));
70   }
71   return result;
72 }
73 
74 /// Creates a `CallOp` to the function reference returned by `getFunc()`.
75 static func::CallOp createFuncCall(OpBuilder &builder, Operation *op,
76                                    StringRef name, TypeRange resultType,
77                                    ValueRange operands,
78                                    EmitCInterface emitCInterface) {
79   auto fn = getFunc(op, name, resultType, operands, emitCInterface);
80   return builder.create<func::CallOp>(op->getLoc(), resultType, fn, operands);
81 }
82 
83 /// Replaces the `op` with  a `CallOp` to the function reference returned
84 /// by `getFunc()`.
85 static func::CallOp replaceOpWithFuncCall(RewriterBase &rewriter, Operation *op,
86                                           StringRef name, TypeRange resultType,
87                                           ValueRange operands,
88                                           EmitCInterface emitCInterface) {
89   auto fn = getFunc(op, name, resultType, operands, emitCInterface);
90   return rewriter.replaceOpWithNewOp<func::CallOp>(op, resultType, fn,
91                                                    operands);
92 }
93 
94 /// Generates dimension size call.
95 static Value genDimSizeCall(OpBuilder &builder, Operation *op,
96                             SparseTensorEncodingAttr &enc, Value src,
97                             int64_t idx) {
98   // Permute the index according to an optional dimension ordering.
99   if (AffineMap p = enc.getDimOrdering())
100     idx = p.getPermutedPosition(idx);
101   // Generate the call.
102   StringRef name = "sparseDimSize";
103   SmallVector<Value, 2> params{src, constantIndex(builder, op->getLoc(), idx)};
104   Type iTp = builder.getIndexType();
105   return createFuncCall(builder, op, name, iTp, params, EmitCInterface::Off)
106       .getResult(0);
107 }
108 
109 /// Generates a call into the "swiss army knife" method of the sparse runtime
110 /// support library for materializing sparse tensors into the computation.
111 static Value genNewCall(OpBuilder &builder, Operation *op,
112                         ArrayRef<Value> params) {
113   StringRef name = "newSparseTensor";
114   Type pTp = getOpaquePointerType(builder);
115   return createFuncCall(builder, op, name, pTp, params, EmitCInterface::On)
116       .getResult(0);
117 }
118 
119 /// Populates given sizes array from type.
120 static void sizesFromType(OpBuilder &builder, SmallVector<Value, 4> &sizes,
121                           Location loc, ShapedType stp) {
122   auto shape = stp.getShape();
123   for (unsigned i = 0, rank = stp.getRank(); i < rank; i++) {
124     uint64_t s = shape[i] == ShapedType::kDynamicSize ? 0 : shape[i];
125     sizes.push_back(constantIndex(builder, loc, s));
126   }
127 }
128 
129 /// Populates given sizes array from source.
130 static void sizesFromSrc(OpBuilder &builder, SmallVector<Value, 4> &sizes,
131                          Location loc, Value src) {
132   unsigned rank = src.getType().cast<ShapedType>().getRank();
133   for (unsigned i = 0; i < rank; i++)
134     sizes.push_back(linalg::createOrFoldDimOp(builder, loc, src, i));
135 }
136 
137 /// Populates given sizes array from type (for static sizes) and from
138 /// an already converted into opague pointer source (for dynamic sizes).
139 static void sizesFromPtr(OpBuilder &builder, SmallVector<Value, 4> &sizes,
140                          Operation *op, SparseTensorEncodingAttr &enc,
141                          ShapedType stp, Value src) {
142   Location loc = op->getLoc();
143   auto shape = stp.getShape();
144   for (unsigned i = 0, rank = stp.getRank(); i < rank; i++)
145     if (shape[i] == ShapedType::kDynamicSize)
146       sizes.push_back(genDimSizeCall(builder, op, enc, src, i));
147     else
148       sizes.push_back(constantIndex(builder, loc, shape[i]));
149 }
150 
151 /// Generates an uninitialized temporary buffer of the given size and
152 /// type, but returns it as type `memref<? x $tp>` (rather than as type
153 /// `memref<$sz x $tp>`).
154 static Value genAlloca(OpBuilder &builder, Location loc, Value sz, Type tp) {
155   auto memTp = MemRefType::get({ShapedType::kDynamicSize}, tp);
156   return builder.create<memref::AllocaOp>(loc, memTp, ValueRange{sz});
157 }
158 
159 /// Generates an uninitialized buffer of the given size and type,
160 /// but returns it as type `memref<? x $tp>` (rather than as type
161 /// `memref<$sz x $tp>`). Unlike temporary buffers on the stack,
162 /// this buffer must be explicitly deallocated by client.
163 static Value genAlloc(RewriterBase &rewriter, Location loc, Value sz, Type tp) {
164   auto memTp = MemRefType::get({ShapedType::kDynamicSize}, tp);
165   return rewriter.create<memref::AllocOp>(loc, memTp, ValueRange{sz});
166 }
167 
168 /// Generates an uninitialized temporary buffer of the given size and
169 /// type, but returns it as type `memref<? x $tp>` (rather than as type
170 /// `memref<$sz x $tp>`).
171 static Value genAlloca(OpBuilder &builder, Location loc, unsigned sz, Type tp) {
172   return genAlloca(builder, loc, constantIndex(builder, loc, sz), tp);
173 }
174 
175 /// Generates an uninitialized temporary buffer with room for one value
176 /// of the given type, and returns the `memref<$tp>`.
177 static Value genAllocaScalar(OpBuilder &builder, Location loc, Type tp) {
178   return builder.create<memref::AllocaOp>(loc, MemRefType::get({}, tp));
179 }
180 
181 /// Generates a temporary buffer of the given type and given contents.
182 static Value genBuffer(OpBuilder &builder, Location loc, ValueRange values) {
183   unsigned sz = values.size();
184   assert(sz >= 1);
185   Value buffer = genAlloca(builder, loc, sz, values[0].getType());
186   for (unsigned i = 0; i < sz; i++) {
187     Value idx = constantIndex(builder, loc, i);
188     builder.create<memref::StoreOp>(loc, values[i], buffer, idx);
189   }
190   return buffer;
191 }
192 
193 /// Populates parameters required to call the "swiss army knife" method of the
194 /// sparse runtime support library for materializing sparse tensors into the
195 /// computation.
196 static void newParams(OpBuilder &builder, SmallVector<Value, 8> &params,
197                       Operation *op, ShapedType stp,
198                       SparseTensorEncodingAttr &enc, Action action,
199                       ValueRange szs, Value ptr = Value()) {
200   Location loc = op->getLoc();
201   ArrayRef<SparseTensorEncodingAttr::DimLevelType> dlt = enc.getDimLevelType();
202   unsigned sz = dlt.size();
203   // Sparsity annotations.
204   SmallVector<Value, 4> attrs;
205   for (unsigned i = 0; i < sz; i++)
206     attrs.push_back(constantDimLevelTypeEncoding(builder, loc, dlt[i]));
207   params.push_back(genBuffer(builder, loc, attrs));
208   // Dimension sizes array of the enveloping tensor. Useful for either
209   // verification of external data, or for construction of internal data.
210   params.push_back(genBuffer(builder, loc, szs));
211   // Dimension order permutation array. This is the "identity" permutation by
212   // default, or otherwise the "reverse" permutation of a given ordering, so
213   // that indices can be mapped quickly to the right position.
214   SmallVector<Value, 4> rev(sz);
215   if (AffineMap p = enc.getDimOrdering()) {
216     for (unsigned i = 0; i < sz; i++)
217       rev[p.getDimPosition(i)] = constantIndex(builder, loc, i);
218   } else {
219     for (unsigned i = 0; i < sz; i++)
220       rev[i] = constantIndex(builder, loc, i);
221   }
222   params.push_back(genBuffer(builder, loc, rev));
223   // Secondary and primary types encoding.
224   Type elemTp = stp.getElementType();
225   params.push_back(constantPointerTypeEncoding(builder, loc, enc));
226   params.push_back(constantIndexTypeEncoding(builder, loc, enc));
227   params.push_back(constantPrimaryTypeEncoding(builder, loc, elemTp));
228   // User action.
229   params.push_back(constantAction(builder, loc, action));
230   // Payload pointer.
231   if (!ptr)
232     ptr = builder.create<LLVM::NullOp>(loc, getOpaquePointerType(builder));
233   params.push_back(ptr);
234 }
235 
236 /// Generates the code to read the value from tensor[ivs], and conditionally
237 /// stores the indices ivs to the memory in ind. The generated code looks like
238 /// the following and the insertion point after this routine is inside the
239 /// if-then branch behind the assignment to ind. This is to ensure that the
240 /// addEltX call generated after is inside the if-then branch.
241 ///    if (tensor[ivs]!=0) {
242 ///      ind = ivs
243 static Value genIndexAndValueForDense(OpBuilder &builder, Location loc,
244                                       Value tensor, Value ind, ValueRange ivs) {
245   Value val = builder.create<tensor::ExtractOp>(loc, tensor, ivs);
246   Value cond = genIsNonzero(builder, loc, val);
247   scf::IfOp ifOp = builder.create<scf::IfOp>(loc, cond, /*else*/ false);
248   builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
249   unsigned i = 0;
250   for (auto iv : ivs) {
251     Value idx = constantIndex(builder, loc, i++);
252     builder.create<memref::StoreOp>(loc, iv, ind, idx);
253   }
254   return val;
255 }
256 
257 /// Generates a call to release/delete a `SparseTensorCOO`.
258 static void genDelCOOCall(OpBuilder &builder, Operation *op, Type elemTp,
259                           Value coo) {
260   SmallString<21> name{"delSparseTensorCOO", primaryTypeFunctionSuffix(elemTp)};
261   TypeRange noTp;
262   createFuncCall(builder, op, name, noTp, coo, EmitCInterface::Off);
263 }
264 
265 /// Generates a call that adds one element to a coordinate scheme.
266 /// In particular, this generates code like the following:
267 ///   val = a[i1,..,ik];
268 ///   if val != 0
269 ///     t->add(&val, [i1,..,ik], [p1,..,pk]);
270 static void genAddEltCall(OpBuilder &builder, Operation *op, Type eltType,
271                           Value ptr, Value valPtr, Value ind, Value perm) {
272   SmallString<9> name{"addElt", primaryTypeFunctionSuffix(eltType)};
273   SmallVector<Value, 4> params{ptr, valPtr, ind, perm};
274   Type pTp = getOpaquePointerType(builder);
275   createFuncCall(builder, op, name, pTp, params, EmitCInterface::On);
276 }
277 
278 /// Generates a call to `iter->getNext()`.  If there is a next element,
279 /// then it is copied into the out-parameters `ind` and `elemPtr`,
280 /// and the return value is true.  If there isn't a next element, then
281 /// the memory for `iter` is freed and the return value is false.
282 static Value genGetNextCall(OpBuilder &builder, Operation *op, Value iter,
283                             Value ind, Value elemPtr) {
284   Type elemTp = elemPtr.getType().cast<ShapedType>().getElementType();
285   SmallString<10> name{"getNext", primaryTypeFunctionSuffix(elemTp)};
286   SmallVector<Value, 3> params{iter, ind, elemPtr};
287   Type i1 = builder.getI1Type();
288   return createFuncCall(builder, op, name, i1, params, EmitCInterface::On)
289       .getResult(0);
290 }
291 
292 /// If the tensor is a sparse constant, generates and returns the pair of
293 /// the constants for the indices and the values.
294 static Optional<std::pair<Value, Value>>
295 genSplitSparseConstant(OpBuilder &builder, Location loc, Value tensor) {
296   if (auto constOp = tensor.getDefiningOp<arith::ConstantOp>()) {
297     if (auto attr = constOp.getValue().dyn_cast<SparseElementsAttr>()) {
298       DenseElementsAttr indicesAttr = attr.getIndices();
299       Value indices = builder.create<arith::ConstantOp>(loc, indicesAttr);
300       DenseElementsAttr valuesAttr = attr.getValues();
301       Value values = builder.create<arith::ConstantOp>(loc, valuesAttr);
302       return std::make_pair(indices, values);
303     }
304   }
305   return {};
306 }
307 
308 /// Generates the code to copy the index at indices[ivs] to ind, and return
309 /// the value at value[ivs].
310 static Value genIndexAndValueForSparse(OpBuilder &builder, Location loc,
311                                        Value indices, Value values, Value ind,
312                                        ValueRange ivs, unsigned rank) {
313   for (unsigned i = 0; i < rank; i++) {
314     Value idx = constantIndex(builder, loc, i);
315     Value val = builder.create<tensor::ExtractOp>(loc, indices,
316                                                   ValueRange{ivs[0], idx});
317     val = builder.create<arith::IndexCastOp>(loc, builder.getIndexType(), val);
318     builder.create<memref::StoreOp>(loc, val, ind, idx);
319   }
320   return builder.create<tensor::ExtractOp>(loc, values, ivs[0]);
321 }
322 
323 /// Generates code to allocate a tensor of the given type, and zero
324 /// initialize it.  If the tensor type has any dynamic sizes, then the
325 /// `sizes` parameter should be as filled by sizesFromPtr(); that way
326 /// we can reuse the genDimSizeCall() results generated by sizesFromPtr().
327 static Value allocDenseTensor(OpBuilder &builder, Location loc,
328                               RankedTensorType tensorTp, ValueRange sizes) {
329   Type elemTp = tensorTp.getElementType();
330   auto shape = tensorTp.getShape();
331   auto memTp = MemRefType::get(shape, elemTp);
332   SmallVector<Value> dynamicSizes;
333   for (unsigned i = 0, rank = tensorTp.getRank(); i < rank; i++) {
334     if (shape[i] == ShapedType::kDynamicSize)
335       dynamicSizes.push_back(sizes[i]);
336   }
337   Value mem = builder.create<memref::AllocOp>(loc, memTp, dynamicSizes);
338   Value zero = constantZero(builder, loc, elemTp);
339   builder.create<linalg::FillOp>(loc, ValueRange{zero}, ValueRange{mem});
340   return mem;
341 }
342 
343 /// Inserts the element returned by genGetNextCall(_, ind, elemPtr) into
344 /// the tensor created by allocDenseTensor().  The `rank` is the rank
345 /// of the `tensor` and the length of `ind`.
346 static void insertScalarIntoDenseTensor(OpBuilder &builder, Location loc,
347                                         Value elemPtr, Value tensor,
348                                         unsigned rank, Value ind) {
349   SmallVector<Value, 4> ivs;
350   ivs.reserve(rank);
351   for (unsigned i = 0; i < rank; i++) {
352     Value idx = constantIndex(builder, loc, i);
353     ivs.push_back(builder.create<memref::LoadOp>(loc, ind, idx));
354   }
355   Value elemV = builder.create<memref::LoadOp>(loc, elemPtr);
356   builder.create<memref::StoreOp>(loc, elemV, tensor, ivs);
357 }
358 
359 /// Determine if the runtime library supports direct conversion to the
360 /// given target `dimTypes`.
361 static bool canUseDirectConversion(
362     ArrayRef<SparseTensorEncodingAttr::DimLevelType> dimTypes) {
363   bool alreadyCompressed = false;
364   for (uint64_t rank = dimTypes.size(), r = 0; r < rank; r++) {
365     switch (dimTypes[r]) {
366     case SparseTensorEncodingAttr::DimLevelType::Compressed:
367       if (alreadyCompressed)
368         return false; // Multiple compressed dimensions not yet supported.
369       alreadyCompressed = true;
370       break;
371     case SparseTensorEncodingAttr::DimLevelType::Dense:
372       if (alreadyCompressed)
373         return false; // Dense after Compressed not yet supported.
374       break;
375     case SparseTensorEncodingAttr::DimLevelType::Singleton:
376       // Although Singleton isn't generally supported yet, the direct
377       // conversion method doesn't have any particular problems with
378       // singleton after compressed.
379       break;
380     }
381   }
382   return true;
383 }
384 
385 //===----------------------------------------------------------------------===//
386 // Conversion rules.
387 //===----------------------------------------------------------------------===//
388 
389 /// Sparse conversion rule for returns.
390 class SparseReturnConverter : public OpConversionPattern<func::ReturnOp> {
391 public:
392   using OpConversionPattern::OpConversionPattern;
393   LogicalResult
394   matchAndRewrite(func::ReturnOp op, OpAdaptor adaptor,
395                   ConversionPatternRewriter &rewriter) const override {
396     rewriter.replaceOpWithNewOp<func::ReturnOp>(op, adaptor.getOperands());
397     return success();
398   }
399 };
400 
401 /// Sparse conversion rule for dimension accesses.
402 class SparseTensorToDimSizeConverter
403     : public OpConversionPattern<tensor::DimOp> {
404 public:
405   using OpConversionPattern::OpConversionPattern;
406   LogicalResult
407   matchAndRewrite(tensor::DimOp op, OpAdaptor adaptor,
408                   ConversionPatternRewriter &rewriter) const override {
409     // Only rewrite annotated DimOp with constant index.
410     auto enc = getSparseTensorEncoding(op.getSource().getType());
411     if (!enc)
412       return failure();
413     Optional<int64_t> index = op.getConstantIndex();
414     if (!index.hasValue())
415       return failure();
416     // Generate the call.
417     Value src = adaptor.getOperands()[0];
418     int64_t idx = index.getValue();
419     rewriter.replaceOp(op, genDimSizeCall(rewriter, op, enc, src, idx));
420     return success();
421   }
422 };
423 
424 /// Sparse conversion rule for trivial tensor casts.
425 class SparseCastConverter : public OpConversionPattern<tensor::CastOp> {
426   using OpConversionPattern::OpConversionPattern;
427   LogicalResult
428   matchAndRewrite(tensor::CastOp op, OpAdaptor adaptor,
429                   ConversionPatternRewriter &rewriter) const override {
430     // Only rewrite identically annotated source/dest.
431     auto encDst = getSparseTensorEncoding(op.getType());
432     auto encSrc = getSparseTensorEncoding(op.getSource().getType());
433     if (!encDst || encDst != encSrc)
434       return failure();
435     rewriter.replaceOp(op, adaptor.getOperands());
436     return success();
437   }
438 };
439 
440 /// Sparse conversion rule for the new operator.
441 class SparseTensorNewConverter : public OpConversionPattern<NewOp> {
442   using OpConversionPattern::OpConversionPattern;
443   LogicalResult
444   matchAndRewrite(NewOp op, OpAdaptor adaptor,
445                   ConversionPatternRewriter &rewriter) const override {
446     Type resType = op.getType();
447     auto enc = getSparseTensorEncoding(resType);
448     if (!enc)
449       return failure();
450     // Generate the call to construct tensor from ptr. The sizes are
451     // inferred from the result type of the new operator.
452     SmallVector<Value, 4> sizes;
453     SmallVector<Value, 8> params;
454     ShapedType stp = resType.cast<ShapedType>();
455     sizesFromType(rewriter, sizes, op.getLoc(), stp);
456     Value ptr = adaptor.getOperands()[0];
457     newParams(rewriter, params, op, stp, enc, Action::kFromFile, sizes, ptr);
458     rewriter.replaceOp(op, genNewCall(rewriter, op, params));
459     return success();
460   }
461 };
462 
463 /// Sparse conversion rule for the alloc operator.
464 class SparseTensorAllocConverter
465     : public OpConversionPattern<bufferization::AllocTensorOp> {
466   using OpConversionPattern::OpConversionPattern;
467   LogicalResult
468   matchAndRewrite(bufferization::AllocTensorOp op, OpAdaptor adaptor,
469                   ConversionPatternRewriter &rewriter) const override {
470     RankedTensorType resType = op.getType();
471     auto enc = getSparseTensorEncoding(resType);
472     if (!enc)
473       return failure();
474     // Gather all dimension sizes as SSA values.
475     SmallVector<Value> sizes;
476     unsigned int operandCtr = 0;
477     for (int64_t i = 0; i < resType.getRank(); ++i) {
478       if (resType.isDynamicDim(i)) {
479         sizes.push_back(adaptor.getOperands()[operandCtr++]);
480       } else {
481         sizes.push_back(rewriter.create<arith::ConstantIndexOp>(
482             op.getLoc(), op.getStaticSize(i)));
483       }
484     }
485     // Generate the call to construct empty tensor. The sizes are
486     // explicitly defined by the arguments to the alloc operator.
487     SmallVector<Value, 8> params;
488     ShapedType stp = resType.cast<ShapedType>();
489     newParams(rewriter, params, op, stp, enc, Action::kEmpty, sizes);
490     rewriter.replaceOp(op, genNewCall(rewriter, op, params));
491     return success();
492   }
493 };
494 
495 /// Sparse conversion rule for the convert operator.
496 class SparseTensorConvertConverter : public OpConversionPattern<ConvertOp> {
497   /// Options to control sparse code generation.
498   SparseTensorConversionOptions options;
499 
500 public:
501   using OpConversionPattern::OpConversionPattern;
502   SparseTensorConvertConverter(MLIRContext *context,
503                                SparseTensorConversionOptions o)
504       : OpConversionPattern<ConvertOp>(context), options(o) {}
505   SparseTensorConvertConverter(TypeConverter &typeConv, MLIRContext *context,
506                                SparseTensorConversionOptions o)
507       : OpConversionPattern<ConvertOp>(typeConv, context), options(o) {}
508 
509   LogicalResult
510   matchAndRewrite(ConvertOp op, OpAdaptor adaptor,
511                   ConversionPatternRewriter &rewriter) const override {
512     Location loc = op->getLoc();
513     Type resType = op.getType();
514     Type srcType = op.getSource().getType();
515     auto encDst = getSparseTensorEncoding(resType);
516     auto encSrc = getSparseTensorEncoding(srcType);
517     Value src = adaptor.getOperands()[0];
518     if (encDst && encSrc) {
519       // This is a sparse => sparse conversion, which is handled as follows:
520       //   t = src->toCOO();         ; src to COO in dst order
521       //   dst = newSparseTensor(t)
522       // Using the coordinate scheme as an intermediate does not always
523       // yield the fastest conversion but avoids the need for a full
524       // O(N^2) conversion matrix.
525       if (encDst == encSrc) {
526         rewriter.replaceOp(op, adaptor.getOperands()); // hidden nop cast
527         return success();
528       }
529       SmallVector<Value, 4> sizes;
530       SmallVector<Value, 8> params;
531       ShapedType stp = srcType.cast<ShapedType>();
532       sizesFromPtr(rewriter, sizes, op, encSrc, stp, src);
533       bool useDirectConversion;
534       switch (options.sparseToSparseStrategy) {
535       case SparseToSparseConversionStrategy::kViaCOO:
536         useDirectConversion = false;
537         break;
538       case SparseToSparseConversionStrategy::kDirect:
539         useDirectConversion = true;
540         assert(canUseDirectConversion(encDst.getDimLevelType()) &&
541                "Unsupported target for direct sparse-to-sparse conversion");
542         break;
543       case SparseToSparseConversionStrategy::kAuto:
544         useDirectConversion = canUseDirectConversion(encDst.getDimLevelType());
545         break;
546       }
547       if (useDirectConversion) {
548         newParams(rewriter, params, op, stp, encDst, Action::kSparseToSparse,
549                   sizes, src);
550         rewriter.replaceOp(op, genNewCall(rewriter, op, params));
551       } else { // use via-COO conversion.
552         // Set up encoding with right mix of src and dst so that the two
553         // method calls can share most parameters, while still providing
554         // the correct sparsity information to either of them.
555         auto enc = SparseTensorEncodingAttr::get(
556             op->getContext(), encDst.getDimLevelType(), encDst.getDimOrdering(),
557             encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
558         newParams(rewriter, params, op, stp, enc, Action::kToCOO, sizes, src);
559         Value coo = genNewCall(rewriter, op, params);
560         params[3] = constantPointerTypeEncoding(rewriter, loc, encDst);
561         params[4] = constantIndexTypeEncoding(rewriter, loc, encDst);
562         params[6] = constantAction(rewriter, loc, Action::kFromCOO);
563         params[7] = coo;
564         Value dst = genNewCall(rewriter, op, params);
565         genDelCOOCall(rewriter, op, stp.getElementType(), coo);
566         rewriter.replaceOp(op, dst);
567       }
568       return success();
569     }
570     if (!encDst && encSrc) {
571       // This is sparse => dense conversion, which is handled as follows:
572       //   dst = new Tensor(0);
573       //   iter = src->toCOO();
574       //   iter->startIterator();
575       //   while (elem = iter->getNext()) {
576       //     dst[elem.indices] = elem.value;
577       //   }
578       RankedTensorType dstTensorTp = resType.cast<RankedTensorType>();
579       RankedTensorType srcTensorTp = srcType.cast<RankedTensorType>();
580       unsigned rank = dstTensorTp.getRank();
581       Type elemTp = dstTensorTp.getElementType();
582       // Fabricate a no-permutation encoding for newParams().
583       // The pointer/index types must be those of `src`.
584       // The dimLevelTypes aren't actually used by Action::kToIterator.
585       encDst = SparseTensorEncodingAttr::get(
586           op->getContext(),
587           SmallVector<SparseTensorEncodingAttr::DimLevelType>(
588               rank, SparseTensorEncodingAttr::DimLevelType::Dense),
589           AffineMap(), encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
590       SmallVector<Value, 4> sizes;
591       SmallVector<Value, 8> params;
592       sizesFromPtr(rewriter, sizes, op, encSrc, srcTensorTp, src);
593       newParams(rewriter, params, op, dstTensorTp, encDst, Action::kToIterator,
594                 sizes, src);
595       Value iter = genNewCall(rewriter, op, params);
596       Value ind = genAlloca(rewriter, loc, rank, rewriter.getIndexType());
597       Value elemPtr = genAllocaScalar(rewriter, loc, elemTp);
598       Value dst = allocDenseTensor(rewriter, loc, dstTensorTp, sizes);
599       SmallVector<Value> noArgs;
600       SmallVector<Type> noTypes;
601       auto whileOp = rewriter.create<scf::WhileOp>(loc, noTypes, noArgs);
602       Block *before = rewriter.createBlock(&whileOp.getBefore(), {}, noTypes);
603       rewriter.setInsertionPointToEnd(before);
604       Value cond = genGetNextCall(rewriter, op, iter, ind, elemPtr);
605       rewriter.create<scf::ConditionOp>(loc, cond, before->getArguments());
606       Block *after = rewriter.createBlock(&whileOp.getAfter(), {}, noTypes);
607       rewriter.setInsertionPointToStart(after);
608       insertScalarIntoDenseTensor(rewriter, loc, elemPtr, dst, rank, ind);
609       rewriter.create<scf::YieldOp>(loc);
610       rewriter.setInsertionPointAfter(whileOp);
611       genDelCOOCall(rewriter, op, elemTp, iter);
612       rewriter.replaceOpWithNewOp<bufferization::ToTensorOp>(op, resType, dst);
613       return success();
614     }
615     if (!encDst && !encSrc) {
616       // dense => dense
617       return failure();
618     }
619     // This is a dense => sparse conversion or a sparse constant in COO =>
620     // sparse conversion, which is handled as follows:
621     //   t = newSparseCOO()
622     //   ...code to fill the COO tensor t...
623     //   s = newSparseTensor(t)
624     //
625     // To fill the COO tensor from a dense tensor:
626     //   for i1 in dim1
627     //    ..
628     //     for ik in dimk
629     //       val = a[i1,..,ik]
630     //       if val != 0
631     //         t->add(val, [i1,..,ik], [p1,..,pk])
632     //
633     // To fill the COO tensor from a sparse constant in COO format:
634     //   for i in range(NNZ)
635     //     val = values[i]
636     //     [i1,..,ik] = indices[i]
637     //     t->add(val, [i1,..,ik], [p1,..,pk])
638     //
639     // Note that the dense tensor traversal code is actually implemented
640     // using MLIR IR to avoid having to expose too much low-level
641     // memref traversal details to the runtime support library.
642     // Also note that the code below only generates the "new" ops and
643     // the loop-nest per se; whereas the entire body of the innermost
644     // loop is generated by genAddElt().
645     ShapedType stp = resType.cast<ShapedType>();
646     unsigned rank = stp.getRank();
647     SmallVector<Value, 4> sizes;
648     SmallVector<Value, 8> params;
649     sizesFromSrc(rewriter, sizes, loc, src);
650     newParams(rewriter, params, op, stp, encDst, Action::kEmptyCOO, sizes);
651     Value coo = genNewCall(rewriter, op, params);
652     Value ind = genAlloca(rewriter, loc, rank, rewriter.getIndexType());
653     Value perm = params[2];
654     SmallVector<Value> lo;
655     SmallVector<Value> hi;
656     SmallVector<Value> st;
657     Value zero = constantIndex(rewriter, loc, 0);
658     Value one = constantIndex(rewriter, loc, 1);
659     auto indicesValues = genSplitSparseConstant(rewriter, loc, src);
660     bool isCOOConstant = indicesValues.hasValue();
661     Value indices;
662     Value values;
663     if (isCOOConstant) {
664       indices = indicesValues->first;
665       values = indicesValues->second;
666       lo.push_back(zero);
667       hi.push_back(linalg::createOrFoldDimOp(rewriter, loc, values, 0));
668       st.push_back(one);
669     } else {
670       for (unsigned i = 0; i < rank; i++) {
671         lo.push_back(zero);
672         hi.push_back(linalg::createOrFoldDimOp(rewriter, loc, src, i));
673         st.push_back(one);
674       }
675     }
676     Type eltType = stp.getElementType();
677     Value elemPtr = genAllocaScalar(rewriter, loc, eltType);
678     scf::buildLoopNest(
679         rewriter, op.getLoc(), lo, hi, st, {},
680         [&](OpBuilder &builder, Location loc, ValueRange ivs,
681             ValueRange args) -> scf::ValueVector {
682           Value val;
683           if (isCOOConstant)
684             val = genIndexAndValueForSparse(rewriter, loc, indices, values, ind,
685                                             ivs, rank);
686           else
687             val = genIndexAndValueForDense(rewriter, loc, src, ind, ivs);
688           builder.create<memref::StoreOp>(loc, val, elemPtr);
689           genAddEltCall(rewriter, op, eltType, coo, elemPtr, ind, perm);
690           return {};
691         });
692     // Final call to construct sparse tensor storage.
693     params[6] = constantAction(rewriter, loc, Action::kFromCOO);
694     params[7] = coo;
695     Value dst = genNewCall(rewriter, op, params);
696     genDelCOOCall(rewriter, op, eltType, coo);
697     rewriter.replaceOp(op, dst);
698     return success();
699   }
700 };
701 
702 /// Sparse conversion rule for the release operator.
703 class SparseTensorReleaseConverter : public OpConversionPattern<ReleaseOp> {
704 public:
705   using OpConversionPattern::OpConversionPattern;
706   LogicalResult
707   matchAndRewrite(ReleaseOp op, OpAdaptor adaptor,
708                   ConversionPatternRewriter &rewriter) const override {
709     StringRef name = "delSparseTensor";
710     TypeRange noTp;
711     createFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
712                    EmitCInterface::Off);
713     rewriter.eraseOp(op);
714     return success();
715   }
716 };
717 
718 /// Sparse conversion rule for pointer accesses.
719 class SparseTensorToPointersConverter
720     : public OpConversionPattern<ToPointersOp> {
721 public:
722   using OpConversionPattern::OpConversionPattern;
723   LogicalResult
724   matchAndRewrite(ToPointersOp op, OpAdaptor adaptor,
725                   ConversionPatternRewriter &rewriter) const override {
726     Type resType = op.getType();
727     Type ptrType = resType.cast<ShapedType>().getElementType();
728     SmallString<16> name{"sparsePointers", overheadTypeFunctionSuffix(ptrType)};
729     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
730                           EmitCInterface::On);
731     return success();
732   }
733 };
734 
735 /// Sparse conversion rule for index accesses.
736 class SparseTensorToIndicesConverter : public OpConversionPattern<ToIndicesOp> {
737 public:
738   using OpConversionPattern::OpConversionPattern;
739   LogicalResult
740   matchAndRewrite(ToIndicesOp op, OpAdaptor adaptor,
741                   ConversionPatternRewriter &rewriter) const override {
742     Type resType = op.getType();
743     Type indType = resType.cast<ShapedType>().getElementType();
744     SmallString<15> name{"sparseIndices", overheadTypeFunctionSuffix(indType)};
745     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
746                           EmitCInterface::On);
747     return success();
748   }
749 };
750 
751 /// Sparse conversion rule for value accesses.
752 class SparseTensorToValuesConverter : public OpConversionPattern<ToValuesOp> {
753 public:
754   using OpConversionPattern::OpConversionPattern;
755   LogicalResult
756   matchAndRewrite(ToValuesOp op, OpAdaptor adaptor,
757                   ConversionPatternRewriter &rewriter) const override {
758     Type resType = op.getType();
759     Type eltType = resType.cast<ShapedType>().getElementType();
760     SmallString<15> name{"sparseValues", primaryTypeFunctionSuffix(eltType)};
761     replaceOpWithFuncCall(rewriter, op, name, resType, adaptor.getOperands(),
762                           EmitCInterface::On);
763     return success();
764   }
765 };
766 
767 /// Sparse conversion rule for tensor rematerialization.
768 class SparseTensorLoadConverter : public OpConversionPattern<LoadOp> {
769 public:
770   using OpConversionPattern::OpConversionPattern;
771   LogicalResult
772   matchAndRewrite(LoadOp op, OpAdaptor adaptor,
773                   ConversionPatternRewriter &rewriter) const override {
774     if (op.getHasInserts()) {
775       // Finalize any pending insertions.
776       StringRef name = "endInsert";
777       TypeRange noTp;
778       createFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
779                      EmitCInterface::Off);
780     }
781     rewriter.replaceOp(op, adaptor.getOperands());
782     return success();
783   }
784 };
785 
786 /// Sparse conversion rule for inserting in lexicographic index order.
787 class SparseTensorLexInsertConverter : public OpConversionPattern<LexInsertOp> {
788 public:
789   using OpConversionPattern::OpConversionPattern;
790   LogicalResult
791   matchAndRewrite(LexInsertOp op, OpAdaptor adaptor,
792                   ConversionPatternRewriter &rewriter) const override {
793     Type elemTp = op.getTensor().getType().cast<ShapedType>().getElementType();
794     SmallString<12> name{"lexInsert", primaryTypeFunctionSuffix(elemTp)};
795     TypeRange noTp;
796     replaceOpWithFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
797                           EmitCInterface::On);
798     return success();
799   }
800 };
801 
802 class SparseTensorExpandConverter : public OpConversionPattern<ExpandOp> {
803 public:
804   using OpConversionPattern::OpConversionPattern;
805   LogicalResult
806   matchAndRewrite(ExpandOp op, OpAdaptor adaptor,
807                   ConversionPatternRewriter &rewriter) const override {
808     Location loc = op->getLoc();
809     ShapedType srcType = op.getTensor().getType().cast<ShapedType>();
810     Type eltType = srcType.getElementType();
811     Type boolType = rewriter.getIntegerType(1);
812     Type idxType = rewriter.getIndexType();
813     // All initialization should be done on entry of the loop nest.
814     rewriter.setInsertionPointAfter(op.getTensor().getDefiningOp());
815     // Determine the size for access expansion.
816     auto enc = getSparseTensorEncoding(srcType);
817     Value src = adaptor.getOperands()[0];
818     Value sz = genDimSizeCall(rewriter, op, enc, src, srcType.getRank() - 1);
819     // Allocate temporary buffers for values, filled-switch, and indices.
820     // We do not use stack buffers for this, since the expanded size may
821     // be rather large (as it envelops a single expanded dense dimension).
822     Value values = genAlloc(rewriter, loc, sz, eltType);
823     Value filled = genAlloc(rewriter, loc, sz, boolType);
824     Value indices = genAlloc(rewriter, loc, sz, idxType);
825     Value zero = constantZero(rewriter, loc, idxType);
826     // Reset the values/filled-switch to all-zero/false. Note that this
827     // introduces an O(N) operation into the computation, but this reset
828     // operation is amortized over the innermost loops for the access
829     // pattern expansion. As noted in the operation doc, we would like
830     // to amortize this setup cost even between kernels.
831     rewriter.create<linalg::FillOp>(
832         loc, ValueRange{constantZero(rewriter, loc, eltType)},
833         ValueRange{values});
834     rewriter.create<linalg::FillOp>(
835         loc, ValueRange{constantZero(rewriter, loc, boolType)},
836         ValueRange{filled});
837     // Replace expansion op with these buffers and initial index.
838     assert(op.getNumResults() == 4);
839     rewriter.replaceOp(op, {values, filled, indices, zero});
840     return success();
841   }
842 };
843 
844 class SparseTensorCompressConverter : public OpConversionPattern<CompressOp> {
845 public:
846   using OpConversionPattern::OpConversionPattern;
847   LogicalResult
848   matchAndRewrite(CompressOp op, OpAdaptor adaptor,
849                   ConversionPatternRewriter &rewriter) const override {
850     Location loc = op->getLoc();
851     // Note that this method call resets the values/filled-switch back to
852     // all-zero/false by only iterating over the set elements, so the
853     // complexity remains proportional to the sparsity of the expanded
854     // access pattern.
855     Type elemTp = op.getTensor().getType().cast<ShapedType>().getElementType();
856     SmallString<12> name{"expInsert", primaryTypeFunctionSuffix(elemTp)};
857     TypeRange noTp;
858     replaceOpWithFuncCall(rewriter, op, name, noTp, adaptor.getOperands(),
859                           EmitCInterface::On);
860     // Deallocate the buffers on exit of the loop nest.
861     Operation *parent = op;
862     for (; isa<scf::ForOp>(parent->getParentOp()) ||
863            isa<scf::WhileOp>(parent->getParentOp()) ||
864            isa<scf::ParallelOp>(parent->getParentOp()) ||
865            isa<scf::IfOp>(parent->getParentOp());
866          parent = parent->getParentOp())
867       ;
868     rewriter.setInsertionPointAfter(parent);
869     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[2]);
870     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[3]);
871     rewriter.create<memref::DeallocOp>(loc, adaptor.getOperands()[4]);
872     return success();
873   }
874 };
875 
876 class SparseTensorOutConverter : public OpConversionPattern<OutOp> {
877 public:
878   using OpConversionPattern::OpConversionPattern;
879   LogicalResult
880   matchAndRewrite(OutOp op, OpAdaptor adaptor,
881                   ConversionPatternRewriter &rewriter) const override {
882     Location loc = op->getLoc();
883     ShapedType srcType = op.getTensor().getType().cast<ShapedType>();
884     // Convert to default permuted COO.
885     Value src = adaptor.getOperands()[0];
886     auto encSrc = getSparseTensorEncoding(srcType);
887     SmallVector<Value, 4> sizes;
888     SmallVector<Value, 8> params;
889     sizesFromPtr(rewriter, sizes, op, encSrc, srcType, src);
890     auto enc = SparseTensorEncodingAttr::get(
891         op->getContext(), encSrc.getDimLevelType(), AffineMap(),
892         encSrc.getPointerBitWidth(), encSrc.getIndexBitWidth());
893     newParams(rewriter, params, op, srcType, enc, Action::kToCOO, sizes, src);
894     Value coo = genNewCall(rewriter, op, params);
895     // Then output the tensor to external file with indices in the externally
896     // visible lexicographic index order. A sort is required if the source was
897     // not in that order yet (note that the sort can be dropped altogether if
898     // external format does not care about the order at all, but here we assume
899     // it does).
900     bool sort =
901         encSrc.getDimOrdering() && !encSrc.getDimOrdering().isIdentity();
902     params.clear();
903     params.push_back(coo);
904     params.push_back(adaptor.getOperands()[1]);
905     params.push_back(constantI1(rewriter, loc, sort));
906     Type eltType = srcType.getElementType();
907     SmallString<18> name{"outSparseTensor", primaryTypeFunctionSuffix(eltType)};
908     TypeRange noTp;
909     createFuncCall(rewriter, op, name, noTp, params, EmitCInterface::Off);
910     genDelCOOCall(rewriter, op, eltType, coo);
911     rewriter.eraseOp(op);
912     return success();
913   }
914 };
915 
916 } // namespace
917 
918 //===----------------------------------------------------------------------===//
919 // Public method for populating conversion rules.
920 //===----------------------------------------------------------------------===//
921 
922 /// Populates the given patterns list with conversion rules required for
923 /// the sparsification of linear algebra operations.
924 void mlir::populateSparseTensorConversionPatterns(
925     TypeConverter &typeConverter, RewritePatternSet &patterns,
926     const SparseTensorConversionOptions &options) {
927   patterns.add<SparseReturnConverter, SparseTensorToDimSizeConverter,
928                SparseCastConverter, SparseTensorNewConverter,
929                SparseTensorAllocConverter, SparseTensorReleaseConverter,
930                SparseTensorToPointersConverter, SparseTensorToIndicesConverter,
931                SparseTensorToValuesConverter, SparseTensorLoadConverter,
932                SparseTensorLexInsertConverter, SparseTensorExpandConverter,
933                SparseTensorCompressConverter, SparseTensorOutConverter>(
934       typeConverter, patterns.getContext());
935   patterns.add<SparseTensorConvertConverter>(typeConverter,
936                                              patterns.getContext(), options);
937 }
938