18a91bc7bSHarrietAkot //===- SparseTensorUtils.cpp - Sparse Tensor Utils for MLIR execution -----===//
28a91bc7bSHarrietAkot //
38a91bc7bSHarrietAkot // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
48a91bc7bSHarrietAkot // See https://llvm.org/LICENSE.txt for license information.
58a91bc7bSHarrietAkot // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68a91bc7bSHarrietAkot //
78a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
88a91bc7bSHarrietAkot //
98a91bc7bSHarrietAkot // This file implements a light-weight runtime support library that is useful
108a91bc7bSHarrietAkot // for sparse tensor manipulations. The functionality provided in this library
118a91bc7bSHarrietAkot // is meant to simplify benchmarking, testing, and debugging MLIR code that
128a91bc7bSHarrietAkot // operates on sparse tensors. The provided functionality is **not** part
138a91bc7bSHarrietAkot // of core MLIR, however.
148a91bc7bSHarrietAkot //
158a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
168a91bc7bSHarrietAkot 
17845561ecSwren romano #include "mlir/ExecutionEngine/SparseTensorUtils.h"
188a91bc7bSHarrietAkot #include "mlir/ExecutionEngine/CRunnerUtils.h"
198a91bc7bSHarrietAkot 
208a91bc7bSHarrietAkot #ifdef MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
218a91bc7bSHarrietAkot 
228a91bc7bSHarrietAkot #include <algorithm>
238a91bc7bSHarrietAkot #include <cassert>
24736c1b66SAart Bik #include <complex>
258a91bc7bSHarrietAkot #include <cctype>
268a91bc7bSHarrietAkot #include <cinttypes>
278a91bc7bSHarrietAkot #include <cstdio>
288a91bc7bSHarrietAkot #include <cstdlib>
298a91bc7bSHarrietAkot #include <cstring>
30efa15f41SAart Bik #include <fstream>
31753fe330Swren romano #include <functional>
32efa15f41SAart Bik #include <iostream>
334d0a18d0Swren romano #include <limits>
348a91bc7bSHarrietAkot #include <numeric>
358a91bc7bSHarrietAkot #include <vector>
368a91bc7bSHarrietAkot 
37736c1b66SAart Bik using complex64 = std::complex<double>;
38736c1b66SAart Bik using complex32 = std::complex<float>;
39736c1b66SAart Bik 
408a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
418a91bc7bSHarrietAkot //
428a91bc7bSHarrietAkot // Internal support for storing and reading sparse tensors.
438a91bc7bSHarrietAkot //
448a91bc7bSHarrietAkot // The following memory-resident sparse storage schemes are supported:
458a91bc7bSHarrietAkot //
468a91bc7bSHarrietAkot // (a) A coordinate scheme for temporarily storing and lexicographically
478a91bc7bSHarrietAkot //     sorting a sparse tensor by index (SparseTensorCOO).
488a91bc7bSHarrietAkot //
498a91bc7bSHarrietAkot // (b) A "one-size-fits-all" sparse tensor storage scheme defined by
508a91bc7bSHarrietAkot //     per-dimension sparse/dense annnotations together with a dimension
518a91bc7bSHarrietAkot //     ordering used by MLIR compiler-generated code (SparseTensorStorage).
528a91bc7bSHarrietAkot //
538a91bc7bSHarrietAkot // The following external formats are supported:
548a91bc7bSHarrietAkot //
558a91bc7bSHarrietAkot // (1) Matrix Market Exchange (MME): *.mtx
568a91bc7bSHarrietAkot //     https://math.nist.gov/MatrixMarket/formats.html
578a91bc7bSHarrietAkot //
588a91bc7bSHarrietAkot // (2) Formidable Repository of Open Sparse Tensors and Tools (FROSTT): *.tns
598a91bc7bSHarrietAkot //     http://frostt.io/tensors/file-formats.html
608a91bc7bSHarrietAkot //
618a91bc7bSHarrietAkot // Two public APIs are supported:
628a91bc7bSHarrietAkot //
638a91bc7bSHarrietAkot // (I) Methods operating on MLIR buffers (memrefs) to interact with sparse
648a91bc7bSHarrietAkot //     tensors. These methods should be used exclusively by MLIR
658a91bc7bSHarrietAkot //     compiler-generated code.
668a91bc7bSHarrietAkot //
678a91bc7bSHarrietAkot // (II) Methods that accept C-style data structures to interact with sparse
688a91bc7bSHarrietAkot //      tensors. These methods can be used by any external runtime that wants
698a91bc7bSHarrietAkot //      to interact with MLIR compiler-generated code.
708a91bc7bSHarrietAkot //
718a91bc7bSHarrietAkot // In both cases (I) and (II), the SparseTensorStorage format is externally
728a91bc7bSHarrietAkot // only visible as an opaque pointer.
738a91bc7bSHarrietAkot //
748a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
758a91bc7bSHarrietAkot 
768a91bc7bSHarrietAkot namespace {
778a91bc7bSHarrietAkot 
7803fe15ceSAart Bik static constexpr int kColWidth = 1025;
7903fe15ceSAart Bik 
8072ec2f76Swren romano /// A version of `operator*` on `uint64_t` which checks for overflows.
8172ec2f76Swren romano static inline uint64_t checkedMul(uint64_t lhs, uint64_t rhs) {
8272ec2f76Swren romano   assert((lhs == 0 || rhs <= std::numeric_limits<uint64_t>::max() / lhs) &&
8372ec2f76Swren romano          "Integer overflow");
8472ec2f76Swren romano   return lhs * rhs;
8572ec2f76Swren romano }
8672ec2f76Swren romano 
87*8cb33240Swren romano // TODO: adjust this so it can be used by `openSparseTensorCOO` too.
88*8cb33240Swren romano // That version doesn't have the permutation, and the `sizes` are
89*8cb33240Swren romano // a pointer/C-array rather than `std::vector`.
90*8cb33240Swren romano //
91*8cb33240Swren romano /// Asserts that the `sizes` (in target-order) under the `perm` (mapping
92*8cb33240Swren romano /// semantic-order to target-order) are a refinement of the desired `shape`
93*8cb33240Swren romano /// (in semantic-order).
94*8cb33240Swren romano ///
95*8cb33240Swren romano /// Precondition: `perm` and `shape` must be valid for `rank`.
96*8cb33240Swren romano static inline void
97*8cb33240Swren romano assertPermutedSizesMatchShape(const std::vector<uint64_t> &sizes, uint64_t rank,
98*8cb33240Swren romano                               const uint64_t *perm, const uint64_t *shape) {
99*8cb33240Swren romano   assert(perm && shape);
100*8cb33240Swren romano   assert(rank == sizes.size() && "Rank mismatch");
101*8cb33240Swren romano   for (uint64_t r = 0; r < rank; r++)
102*8cb33240Swren romano     assert((shape[r] == 0 || shape[r] == sizes[perm[r]]) &&
103*8cb33240Swren romano            "Dimension size mismatch");
104*8cb33240Swren romano }
105*8cb33240Swren romano 
1068a91bc7bSHarrietAkot /// A sparse tensor element in coordinate scheme (value and indices).
1078a91bc7bSHarrietAkot /// For example, a rank-1 vector element would look like
1088a91bc7bSHarrietAkot ///   ({i}, a[i])
1098a91bc7bSHarrietAkot /// and a rank-5 tensor element like
1108a91bc7bSHarrietAkot ///   ({i,j,k,l,m}, a[i,j,k,l,m])
111ccd047cbSAart Bik /// We use pointer to a shared index pool rather than e.g. a direct
112ccd047cbSAart Bik /// vector since that (1) reduces the per-element memory footprint, and
113ccd047cbSAart Bik /// (2) centralizes the memory reservation and (re)allocation to one place.
1148a91bc7bSHarrietAkot template <typename V>
1158a91bc7bSHarrietAkot struct Element {
116ccd047cbSAart Bik   Element(uint64_t *ind, V val) : indices(ind), value(val){};
117ccd047cbSAart Bik   uint64_t *indices; // pointer into shared index pool
1188a91bc7bSHarrietAkot   V value;
1198a91bc7bSHarrietAkot };
1208a91bc7bSHarrietAkot 
121753fe330Swren romano /// The type of callback functions which receive an element.  We avoid
122753fe330Swren romano /// packaging the coordinates and value together as an `Element` object
123753fe330Swren romano /// because this helps keep code somewhat cleaner.
124753fe330Swren romano template <typename V>
125753fe330Swren romano using ElementConsumer =
126753fe330Swren romano     const std::function<void(const std::vector<uint64_t> &, V)> &;
127753fe330Swren romano 
1288a91bc7bSHarrietAkot /// A memory-resident sparse tensor in coordinate scheme (collection of
1298a91bc7bSHarrietAkot /// elements). This data structure is used to read a sparse tensor from
1308a91bc7bSHarrietAkot /// any external format into memory and sort the elements lexicographically
1318a91bc7bSHarrietAkot /// by indices before passing it back to the client (most packed storage
1328a91bc7bSHarrietAkot /// formats require the elements to appear in lexicographic index order).
1338a91bc7bSHarrietAkot template <typename V>
1348a91bc7bSHarrietAkot struct SparseTensorCOO {
1358a91bc7bSHarrietAkot public:
1368a91bc7bSHarrietAkot   SparseTensorCOO(const std::vector<uint64_t> &szs, uint64_t capacity)
137db6796dfSMehdi Amini       : sizes(szs) {
138ccd047cbSAart Bik     if (capacity) {
1398a91bc7bSHarrietAkot       elements.reserve(capacity);
140ccd047cbSAart Bik       indices.reserve(capacity * getRank());
1418a91bc7bSHarrietAkot     }
142ccd047cbSAart Bik   }
143ccd047cbSAart Bik 
1448a91bc7bSHarrietAkot   /// Adds element as indices and value.
1458a91bc7bSHarrietAkot   void add(const std::vector<uint64_t> &ind, V val) {
1468a91bc7bSHarrietAkot     assert(!iteratorLocked && "Attempt to add() after startIterator()");
147ccd047cbSAart Bik     uint64_t *base = indices.data();
148ccd047cbSAart Bik     uint64_t size = indices.size();
1498a91bc7bSHarrietAkot     uint64_t rank = getRank();
1508a91bc7bSHarrietAkot     assert(rank == ind.size());
151ccd047cbSAart Bik     for (uint64_t r = 0; r < rank; r++) {
1528a91bc7bSHarrietAkot       assert(ind[r] < sizes[r]); // within bounds
153ccd047cbSAart Bik       indices.push_back(ind[r]);
1548a91bc7bSHarrietAkot     }
155ccd047cbSAart Bik     // This base only changes if indices were reallocated. In that case, we
156ccd047cbSAart Bik     // need to correct all previous pointers into the vector. Note that this
157ccd047cbSAart Bik     // only happens if we did not set the initial capacity right, and then only
158ccd047cbSAart Bik     // for every internal vector reallocation (which with the doubling rule
159ccd047cbSAart Bik     // should only incur an amortized linear overhead).
160298d2fa1SMehdi Amini     uint64_t *newBase = indices.data();
161298d2fa1SMehdi Amini     if (newBase != base) {
162ccd047cbSAart Bik       for (uint64_t i = 0, n = elements.size(); i < n; i++)
163298d2fa1SMehdi Amini         elements[i].indices = newBase + (elements[i].indices - base);
164298d2fa1SMehdi Amini       base = newBase;
165ccd047cbSAart Bik     }
166ccd047cbSAart Bik     // Add element as (pointer into shared index pool, value) pair.
167ccd047cbSAart Bik     elements.emplace_back(base + size, val);
168ccd047cbSAart Bik   }
169ccd047cbSAart Bik 
1708a91bc7bSHarrietAkot   /// Sorts elements lexicographically by index.
1718a91bc7bSHarrietAkot   void sort() {
1728a91bc7bSHarrietAkot     assert(!iteratorLocked && "Attempt to sort() after startIterator()");
173cf358253Swren romano     // TODO: we may want to cache an `isSorted` bit, to avoid
174cf358253Swren romano     // unnecessary/redundant sorting.
175ccd047cbSAart Bik     std::sort(elements.begin(), elements.end(),
176ccd047cbSAart Bik               [this](const Element<V> &e1, const Element<V> &e2) {
177ccd047cbSAart Bik                 uint64_t rank = getRank();
178ccd047cbSAart Bik                 for (uint64_t r = 0; r < rank; r++) {
179ccd047cbSAart Bik                   if (e1.indices[r] == e2.indices[r])
180ccd047cbSAart Bik                     continue;
181ccd047cbSAart Bik                   return e1.indices[r] < e2.indices[r];
1828a91bc7bSHarrietAkot                 }
183ccd047cbSAart Bik                 return false;
184ccd047cbSAart Bik               });
185ccd047cbSAart Bik   }
186ccd047cbSAart Bik 
1878a91bc7bSHarrietAkot   /// Returns rank.
1888a91bc7bSHarrietAkot   uint64_t getRank() const { return sizes.size(); }
189ccd047cbSAart Bik 
1908a91bc7bSHarrietAkot   /// Getter for sizes array.
1918a91bc7bSHarrietAkot   const std::vector<uint64_t> &getSizes() const { return sizes; }
192ccd047cbSAart Bik 
1938a91bc7bSHarrietAkot   /// Getter for elements array.
1948a91bc7bSHarrietAkot   const std::vector<Element<V>> &getElements() const { return elements; }
1958a91bc7bSHarrietAkot 
1968a91bc7bSHarrietAkot   /// Switch into iterator mode.
1978a91bc7bSHarrietAkot   void startIterator() {
1988a91bc7bSHarrietAkot     iteratorLocked = true;
1998a91bc7bSHarrietAkot     iteratorPos = 0;
2008a91bc7bSHarrietAkot   }
201ccd047cbSAart Bik 
2028a91bc7bSHarrietAkot   /// Get the next element.
2038a91bc7bSHarrietAkot   const Element<V> *getNext() {
2048a91bc7bSHarrietAkot     assert(iteratorLocked && "Attempt to getNext() before startIterator()");
2058a91bc7bSHarrietAkot     if (iteratorPos < elements.size())
2068a91bc7bSHarrietAkot       return &(elements[iteratorPos++]);
2078a91bc7bSHarrietAkot     iteratorLocked = false;
2088a91bc7bSHarrietAkot     return nullptr;
2098a91bc7bSHarrietAkot   }
2108a91bc7bSHarrietAkot 
2118a91bc7bSHarrietAkot   /// Factory method. Permutes the original dimensions according to
2128a91bc7bSHarrietAkot   /// the given ordering and expects subsequent add() calls to honor
2138a91bc7bSHarrietAkot   /// that same ordering for the given indices. The result is a
2148a91bc7bSHarrietAkot   /// fully permuted coordinate scheme.
2158d8b566fSwren romano   ///
2168d8b566fSwren romano   /// Precondition: `sizes` and `perm` must be valid for `rank`.
2178a91bc7bSHarrietAkot   static SparseTensorCOO<V> *newSparseTensorCOO(uint64_t rank,
2188a91bc7bSHarrietAkot                                                 const uint64_t *sizes,
2198a91bc7bSHarrietAkot                                                 const uint64_t *perm,
2208a91bc7bSHarrietAkot                                                 uint64_t capacity = 0) {
2218a91bc7bSHarrietAkot     std::vector<uint64_t> permsz(rank);
222d83a7068Swren romano     for (uint64_t r = 0; r < rank; r++) {
223d83a7068Swren romano       assert(sizes[r] > 0 && "Dimension size zero has trivial storage");
2248a91bc7bSHarrietAkot       permsz[perm[r]] = sizes[r];
225d83a7068Swren romano     }
2268a91bc7bSHarrietAkot     return new SparseTensorCOO<V>(permsz, capacity);
2278a91bc7bSHarrietAkot   }
2288a91bc7bSHarrietAkot 
2298a91bc7bSHarrietAkot private:
2308a91bc7bSHarrietAkot   const std::vector<uint64_t> sizes; // per-dimension sizes
231ccd047cbSAart Bik   std::vector<Element<V>> elements;  // all COO elements
232ccd047cbSAart Bik   std::vector<uint64_t> indices;     // shared index pool
233db6796dfSMehdi Amini   bool iteratorLocked = false;
234db6796dfSMehdi Amini   unsigned iteratorPos = 0;
2358a91bc7bSHarrietAkot };
2368a91bc7bSHarrietAkot 
237*8cb33240Swren romano // Forward.
238*8cb33240Swren romano template <typename V>
239*8cb33240Swren romano class SparseTensorEnumeratorBase;
240*8cb33240Swren romano 
2418d8b566fSwren romano /// Abstract base class for `SparseTensorStorage<P,I,V>`.  This class
2428d8b566fSwren romano /// takes responsibility for all the `<P,I,V>`-independent aspects
2438d8b566fSwren romano /// of the tensor (e.g., shape, sparsity, permutation).  In addition,
2448d8b566fSwren romano /// we use function overloading to implement "partial" method
2458d8b566fSwren romano /// specialization, which the C-API relies on to catch type errors
2468d8b566fSwren romano /// arising from our use of opaque pointers.
2478a91bc7bSHarrietAkot class SparseTensorStorageBase {
2488a91bc7bSHarrietAkot public:
2498d8b566fSwren romano   /// Constructs a new storage object.  The `perm` maps the tensor's
2508d8b566fSwren romano   /// semantic-ordering of dimensions to this object's storage-order.
2518d8b566fSwren romano   /// The `szs` and `sparsity` arrays are already in storage-order.
2528d8b566fSwren romano   ///
2538d8b566fSwren romano   /// Precondition: `perm` and `sparsity` must be valid for `szs.size()`.
2548d8b566fSwren romano   SparseTensorStorageBase(const std::vector<uint64_t> &szs,
2558d8b566fSwren romano                           const uint64_t *perm, const DimLevelType *sparsity)
2568d8b566fSwren romano       : dimSizes(szs), rev(getRank()),
2578d8b566fSwren romano         dimTypes(sparsity, sparsity + getRank()) {
258753fe330Swren romano     assert(perm && sparsity);
2598d8b566fSwren romano     const uint64_t rank = getRank();
2608d8b566fSwren romano     // Validate parameters.
2618d8b566fSwren romano     assert(rank > 0 && "Trivial shape is unsupported");
2628d8b566fSwren romano     for (uint64_t r = 0; r < rank; r++) {
2638d8b566fSwren romano       assert(dimSizes[r] > 0 && "Dimension size zero has trivial storage");
2648d8b566fSwren romano       assert((dimTypes[r] == DimLevelType::kDense ||
2658d8b566fSwren romano               dimTypes[r] == DimLevelType::kCompressed) &&
2668d8b566fSwren romano              "Unsupported DimLevelType");
2678d8b566fSwren romano     }
2688d8b566fSwren romano     // Construct the "reverse" (i.e., inverse) permutation.
2698d8b566fSwren romano     for (uint64_t r = 0; r < rank; r++)
2708d8b566fSwren romano       rev[perm[r]] = r;
2718d8b566fSwren romano   }
2728d8b566fSwren romano 
2738d8b566fSwren romano   virtual ~SparseTensorStorageBase() = default;
2748d8b566fSwren romano 
2758d8b566fSwren romano   /// Get the rank of the tensor.
2768d8b566fSwren romano   uint64_t getRank() const { return dimSizes.size(); }
2778d8b566fSwren romano 
2788d8b566fSwren romano   /// Getter for the dimension-sizes array, in storage-order.
2798d8b566fSwren romano   const std::vector<uint64_t> &getDimSizes() const { return dimSizes; }
2808d8b566fSwren romano 
2818d8b566fSwren romano   /// Safely lookup the size of the given (storage-order) dimension.
2828d8b566fSwren romano   uint64_t getDimSize(uint64_t d) const {
2838d8b566fSwren romano     assert(d < getRank());
2848d8b566fSwren romano     return dimSizes[d];
2858d8b566fSwren romano   }
2868d8b566fSwren romano 
2878d8b566fSwren romano   /// Getter for the "reverse" permutation, which maps this object's
2888d8b566fSwren romano   /// storage-order to the tensor's semantic-order.
2898d8b566fSwren romano   const std::vector<uint64_t> &getRev() const { return rev; }
2908d8b566fSwren romano 
2918d8b566fSwren romano   /// Getter for the dimension-types array, in storage-order.
2928d8b566fSwren romano   const std::vector<DimLevelType> &getDimTypes() const { return dimTypes; }
2938d8b566fSwren romano 
2948d8b566fSwren romano   /// Safely check if the (storage-order) dimension uses compressed storage.
2958d8b566fSwren romano   bool isCompressedDim(uint64_t d) const {
2968d8b566fSwren romano     assert(d < getRank());
2978d8b566fSwren romano     return (dimTypes[d] == DimLevelType::kCompressed);
2988d8b566fSwren romano   }
2998a91bc7bSHarrietAkot 
300*8cb33240Swren romano   /// Allocate a new enumerator.
301*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<double> **, uint64_t,
302*8cb33240Swren romano                              const uint64_t *) const {
303*8cb33240Swren romano     fatal("enumf64");
304*8cb33240Swren romano   }
305*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<float> **, uint64_t,
306*8cb33240Swren romano                              const uint64_t *) const {
307*8cb33240Swren romano     fatal("enumf32");
308*8cb33240Swren romano   }
309*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<int64_t> **, uint64_t,
310*8cb33240Swren romano                              const uint64_t *) const {
311*8cb33240Swren romano     fatal("enumi64");
312*8cb33240Swren romano   }
313*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<int32_t> **, uint64_t,
314*8cb33240Swren romano                              const uint64_t *) const {
315*8cb33240Swren romano     fatal("enumi32");
316*8cb33240Swren romano   }
317*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<int16_t> **, uint64_t,
318*8cb33240Swren romano                              const uint64_t *) const {
319*8cb33240Swren romano     fatal("enumi16");
320*8cb33240Swren romano   }
321*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<int8_t> **, uint64_t,
322*8cb33240Swren romano                              const uint64_t *) const {
323*8cb33240Swren romano     fatal("enumi8");
324*8cb33240Swren romano   }
325*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<complex64> **, uint64_t,
326*8cb33240Swren romano                              const uint64_t *) const {
327*8cb33240Swren romano     fatal("enumc64");
328*8cb33240Swren romano   }
329*8cb33240Swren romano   virtual void newEnumerator(SparseTensorEnumeratorBase<complex32> **, uint64_t,
330*8cb33240Swren romano                              const uint64_t *) const {
331*8cb33240Swren romano     fatal("enumc32");
332*8cb33240Swren romano   }
333*8cb33240Swren romano 
3344f2ec7f9SAart Bik   /// Overhead storage.
3358a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint64_t> **, uint64_t) { fatal("p64"); }
3368a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint32_t> **, uint64_t) { fatal("p32"); }
3378a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint16_t> **, uint64_t) { fatal("p16"); }
3388a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint8_t> **, uint64_t) { fatal("p8"); }
3398a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint64_t> **, uint64_t) { fatal("i64"); }
3408a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint32_t> **, uint64_t) { fatal("i32"); }
3418a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint16_t> **, uint64_t) { fatal("i16"); }
3428a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint8_t> **, uint64_t) { fatal("i8"); }
3438a91bc7bSHarrietAkot 
3444f2ec7f9SAart Bik   /// Primary storage.
3458a91bc7bSHarrietAkot   virtual void getValues(std::vector<double> **) { fatal("valf64"); }
3468a91bc7bSHarrietAkot   virtual void getValues(std::vector<float> **) { fatal("valf32"); }
3478a91bc7bSHarrietAkot   virtual void getValues(std::vector<int64_t> **) { fatal("vali64"); }
3488a91bc7bSHarrietAkot   virtual void getValues(std::vector<int32_t> **) { fatal("vali32"); }
3498a91bc7bSHarrietAkot   virtual void getValues(std::vector<int16_t> **) { fatal("vali16"); }
3508a91bc7bSHarrietAkot   virtual void getValues(std::vector<int8_t> **) { fatal("vali8"); }
351736c1b66SAart Bik   virtual void getValues(std::vector<complex64> **) { fatal("valc64"); }
352736c1b66SAart Bik   virtual void getValues(std::vector<complex32> **) { fatal("valc32"); }
3538a91bc7bSHarrietAkot 
3544f2ec7f9SAart Bik   /// Element-wise insertion in lexicographic index order.
355c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, double) { fatal("insf64"); }
356c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, float) { fatal("insf32"); }
357c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int64_t) { fatal("insi64"); }
358c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int32_t) { fatal("insi32"); }
359c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int16_t) { fatal("ins16"); }
360c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int8_t) { fatal("insi8"); }
361736c1b66SAart Bik   virtual void lexInsert(const uint64_t *, complex64) { fatal("insc64"); }
362736c1b66SAart Bik   virtual void lexInsert(const uint64_t *, complex32) { fatal("insc32"); }
3634f2ec7f9SAart Bik 
3644f2ec7f9SAart Bik   /// Expanded insertion.
3654f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, double *, bool *, uint64_t *, uint64_t) {
3664f2ec7f9SAart Bik     fatal("expf64");
3674f2ec7f9SAart Bik   }
3684f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, float *, bool *, uint64_t *, uint64_t) {
3694f2ec7f9SAart Bik     fatal("expf32");
3704f2ec7f9SAart Bik   }
3714f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int64_t *, bool *, uint64_t *, uint64_t) {
3724f2ec7f9SAart Bik     fatal("expi64");
3734f2ec7f9SAart Bik   }
3744f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int32_t *, bool *, uint64_t *, uint64_t) {
3754f2ec7f9SAart Bik     fatal("expi32");
3764f2ec7f9SAart Bik   }
3774f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int16_t *, bool *, uint64_t *, uint64_t) {
3784f2ec7f9SAart Bik     fatal("expi16");
3794f2ec7f9SAart Bik   }
3804f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int8_t *, bool *, uint64_t *, uint64_t) {
3814f2ec7f9SAart Bik     fatal("expi8");
3824f2ec7f9SAart Bik   }
383736c1b66SAart Bik   virtual void expInsert(uint64_t *, complex64 *, bool *, uint64_t *,
384736c1b66SAart Bik                          uint64_t) {
385736c1b66SAart Bik     fatal("expc64");
386736c1b66SAart Bik   }
387736c1b66SAart Bik   virtual void expInsert(uint64_t *, complex32 *, bool *, uint64_t *,
388736c1b66SAart Bik                          uint64_t) {
389736c1b66SAart Bik     fatal("expc32");
390736c1b66SAart Bik   }
3914f2ec7f9SAart Bik 
3924f2ec7f9SAart Bik   /// Finishes insertion.
393f66e5769SAart Bik   virtual void endInsert() = 0;
394f66e5769SAart Bik 
395753fe330Swren romano protected:
396753fe330Swren romano   // Since this class is virtual, we must disallow public copying in
397753fe330Swren romano   // order to avoid "slicing".  Since this class has data members,
398753fe330Swren romano   // that means making copying protected.
399753fe330Swren romano   // <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-copy-virtual>
400753fe330Swren romano   SparseTensorStorageBase(const SparseTensorStorageBase &) = default;
401753fe330Swren romano   // Copy-assignment would be implicitly deleted (because `dimSizes`
402753fe330Swren romano   // is const), so we explicitly delete it for clarity.
403753fe330Swren romano   SparseTensorStorageBase &operator=(const SparseTensorStorageBase &) = delete;
404753fe330Swren romano 
4058a91bc7bSHarrietAkot private:
40646bdacaaSwren romano   static void fatal(const char *tp) {
4078a91bc7bSHarrietAkot     fprintf(stderr, "unsupported %s\n", tp);
4088a91bc7bSHarrietAkot     exit(1);
4098a91bc7bSHarrietAkot   }
4108d8b566fSwren romano 
4118d8b566fSwren romano   const std::vector<uint64_t> dimSizes;
4128d8b566fSwren romano   std::vector<uint64_t> rev;
4138d8b566fSwren romano   const std::vector<DimLevelType> dimTypes;
4148a91bc7bSHarrietAkot };
4158a91bc7bSHarrietAkot 
416753fe330Swren romano // Forward.
417753fe330Swren romano template <typename P, typename I, typename V>
418753fe330Swren romano class SparseTensorEnumerator;
419753fe330Swren romano 
4208a91bc7bSHarrietAkot /// A memory-resident sparse tensor using a storage scheme based on
4218a91bc7bSHarrietAkot /// per-dimension sparse/dense annotations. This data structure provides a
4228a91bc7bSHarrietAkot /// bufferized form of a sparse tensor type. In contrast to generating setup
4238a91bc7bSHarrietAkot /// methods for each differently annotated sparse tensor, this method provides
4248a91bc7bSHarrietAkot /// a convenient "one-size-fits-all" solution that simply takes an input tensor
4258a91bc7bSHarrietAkot /// and annotations to implement all required setup in a general manner.
4268a91bc7bSHarrietAkot template <typename P, typename I, typename V>
4278a91bc7bSHarrietAkot class SparseTensorStorage : public SparseTensorStorageBase {
428*8cb33240Swren romano   /// Private constructor to share code between the other constructors.
429*8cb33240Swren romano   /// Beware that the object is not necessarily guaranteed to be in a
430*8cb33240Swren romano   /// valid state after this constructor alone; e.g., `isCompressedDim(d)`
431*8cb33240Swren romano   /// doesn't entail `!(pointers[d].empty())`.
432*8cb33240Swren romano   ///
433*8cb33240Swren romano   /// Precondition: `perm` and `sparsity` must be valid for `szs.size()`.
434*8cb33240Swren romano   SparseTensorStorage(const std::vector<uint64_t> &szs, const uint64_t *perm,
435*8cb33240Swren romano                       const DimLevelType *sparsity)
436*8cb33240Swren romano       : SparseTensorStorageBase(szs, perm, sparsity), pointers(getRank()),
437*8cb33240Swren romano         indices(getRank()), idx(getRank()) {}
438*8cb33240Swren romano 
4398a91bc7bSHarrietAkot public:
4408a91bc7bSHarrietAkot   /// Constructs a sparse tensor storage scheme with the given dimensions,
4418a91bc7bSHarrietAkot   /// permutation, and per-dimension dense/sparse annotations, using
4428a91bc7bSHarrietAkot   /// the coordinate scheme tensor for the initial contents if provided.
4438d8b566fSwren romano   ///
4448d8b566fSwren romano   /// Precondition: `perm` and `sparsity` must be valid for `szs.size()`.
4458a91bc7bSHarrietAkot   SparseTensorStorage(const std::vector<uint64_t> &szs, const uint64_t *perm,
446*8cb33240Swren romano                       const DimLevelType *sparsity, SparseTensorCOO<V> *coo)
447*8cb33240Swren romano       : SparseTensorStorage(szs, perm, sparsity) {
4488a91bc7bSHarrietAkot     // Provide hints on capacity of pointers and indices.
449175b9af4SAart Bik     // TODO: needs much fine-tuning based on actual sparsity; currently
450175b9af4SAart Bik     //       we reserve pointer/index space based on all previous dense
451175b9af4SAart Bik     //       dimensions, which works well up to first sparse dim; but
452175b9af4SAart Bik     //       we should really use nnz and dense/sparse distribution.
453f66e5769SAart Bik     bool allDense = true;
454f66e5769SAart Bik     uint64_t sz = 1;
4558d8b566fSwren romano     for (uint64_t r = 0, rank = getRank(); r < rank; r++) {
4568d8b566fSwren romano       if (isCompressedDim(r)) {
4578d8b566fSwren romano         // TODO: Take a parameter between 1 and `sizes[r]`, and multiply
4588d8b566fSwren romano         // `sz` by that before reserving. (For now we just use 1.)
459f66e5769SAart Bik         pointers[r].reserve(sz + 1);
4608d8b566fSwren romano         pointers[r].push_back(0);
461f66e5769SAart Bik         indices[r].reserve(sz);
462f66e5769SAart Bik         sz = 1;
463f66e5769SAart Bik         allDense = false;
4648d8b566fSwren romano       } else { // Dense dimension.
4658d8b566fSwren romano         sz = checkedMul(sz, getDimSizes()[r]);
4668a91bc7bSHarrietAkot       }
4678a91bc7bSHarrietAkot     }
4688a91bc7bSHarrietAkot     // Then assign contents from coordinate scheme tensor if provided.
4698d8b566fSwren romano     if (coo) {
4704d0a18d0Swren romano       // Ensure both preconditions of `fromCOO`.
4718d8b566fSwren romano       assert(coo->getSizes() == getDimSizes() && "Tensor size mismatch");
4728d8b566fSwren romano       coo->sort();
4734d0a18d0Swren romano       // Now actually insert the `elements`.
4748d8b566fSwren romano       const std::vector<Element<V>> &elements = coo->getElements();
475ceda1ae9Swren romano       uint64_t nnz = elements.size();
4768a91bc7bSHarrietAkot       values.reserve(nnz);
477ceda1ae9Swren romano       fromCOO(elements, 0, nnz, 0);
4781ce77b56SAart Bik     } else if (allDense) {
479f66e5769SAart Bik       values.resize(sz, 0);
4808a91bc7bSHarrietAkot     }
4818a91bc7bSHarrietAkot   }
4828a91bc7bSHarrietAkot 
483*8cb33240Swren romano   /// Constructs a sparse tensor storage scheme with the given dimensions,
484*8cb33240Swren romano   /// permutation, and per-dimension dense/sparse annotations, using
485*8cb33240Swren romano   /// the given sparse tensor for the initial contents.
486*8cb33240Swren romano   ///
487*8cb33240Swren romano   /// Preconditions:
488*8cb33240Swren romano   /// * `perm` and `sparsity` must be valid for `szs.size()`.
489*8cb33240Swren romano   /// * The `tensor` must have the same value type `V`.
490*8cb33240Swren romano   SparseTensorStorage(const std::vector<uint64_t> &szs, const uint64_t *perm,
491*8cb33240Swren romano                       const DimLevelType *sparsity,
492*8cb33240Swren romano                       const SparseTensorStorageBase &tensor);
493*8cb33240Swren romano 
4940ae2e958SMehdi Amini   ~SparseTensorStorage() override = default;
4958a91bc7bSHarrietAkot 
496f66e5769SAart Bik   /// Partially specialize these getter methods based on template types.
4978a91bc7bSHarrietAkot   void getPointers(std::vector<P> **out, uint64_t d) override {
4988a91bc7bSHarrietAkot     assert(d < getRank());
4998a91bc7bSHarrietAkot     *out = &pointers[d];
5008a91bc7bSHarrietAkot   }
5018a91bc7bSHarrietAkot   void getIndices(std::vector<I> **out, uint64_t d) override {
5028a91bc7bSHarrietAkot     assert(d < getRank());
5038a91bc7bSHarrietAkot     *out = &indices[d];
5048a91bc7bSHarrietAkot   }
5058a91bc7bSHarrietAkot   void getValues(std::vector<V> **out) override { *out = &values; }
5068a91bc7bSHarrietAkot 
50703fe15ceSAart Bik   /// Partially specialize lexicographical insertions based on template types.
508c03fd1e6Swren romano   void lexInsert(const uint64_t *cursor, V val) override {
5091ce77b56SAart Bik     // First, wrap up pending insertion path.
5101ce77b56SAart Bik     uint64_t diff = 0;
5111ce77b56SAart Bik     uint64_t top = 0;
5121ce77b56SAart Bik     if (!values.empty()) {
5131ce77b56SAart Bik       diff = lexDiff(cursor);
5141ce77b56SAart Bik       endPath(diff + 1);
5151ce77b56SAart Bik       top = idx[diff] + 1;
5161ce77b56SAart Bik     }
5171ce77b56SAart Bik     // Then continue with insertion path.
5181ce77b56SAart Bik     insPath(cursor, diff, top, val);
519f66e5769SAart Bik   }
520f66e5769SAart Bik 
5214f2ec7f9SAart Bik   /// Partially specialize expanded insertions based on template types.
5224f2ec7f9SAart Bik   /// Note that this method resets the values/filled-switch array back
5234f2ec7f9SAart Bik   /// to all-zero/false while only iterating over the nonzero elements.
5244f2ec7f9SAart Bik   void expInsert(uint64_t *cursor, V *values, bool *filled, uint64_t *added,
5254f2ec7f9SAart Bik                  uint64_t count) override {
5264f2ec7f9SAart Bik     if (count == 0)
5274f2ec7f9SAart Bik       return;
5284f2ec7f9SAart Bik     // Sort.
5294f2ec7f9SAart Bik     std::sort(added, added + count);
5304f2ec7f9SAart Bik     // Restore insertion path for first insert.
5313bf2ba3bSwren romano     const uint64_t lastDim = getRank() - 1;
5324f2ec7f9SAart Bik     uint64_t index = added[0];
5333bf2ba3bSwren romano     cursor[lastDim] = index;
5344f2ec7f9SAart Bik     lexInsert(cursor, values[index]);
5354f2ec7f9SAart Bik     assert(filled[index]);
5364f2ec7f9SAart Bik     values[index] = 0;
5374f2ec7f9SAart Bik     filled[index] = false;
5384f2ec7f9SAart Bik     // Subsequent insertions are quick.
5394f2ec7f9SAart Bik     for (uint64_t i = 1; i < count; i++) {
5404f2ec7f9SAart Bik       assert(index < added[i] && "non-lexicographic insertion");
5414f2ec7f9SAart Bik       index = added[i];
5423bf2ba3bSwren romano       cursor[lastDim] = index;
5433bf2ba3bSwren romano       insPath(cursor, lastDim, added[i - 1] + 1, values[index]);
5444f2ec7f9SAart Bik       assert(filled[index]);
5453bf2ba3bSwren romano       values[index] = 0;
5464f2ec7f9SAart Bik       filled[index] = false;
5474f2ec7f9SAart Bik     }
5484f2ec7f9SAart Bik   }
5494f2ec7f9SAart Bik 
550f66e5769SAart Bik   /// Finalizes lexicographic insertions.
5511ce77b56SAart Bik   void endInsert() override {
5521ce77b56SAart Bik     if (values.empty())
55372ec2f76Swren romano       finalizeSegment(0);
5541ce77b56SAart Bik     else
5551ce77b56SAart Bik       endPath(0);
5561ce77b56SAart Bik   }
557f66e5769SAart Bik 
558*8cb33240Swren romano   void newEnumerator(SparseTensorEnumeratorBase<V> **out, uint64_t rank,
559*8cb33240Swren romano                      const uint64_t *perm) const override {
560*8cb33240Swren romano     *out = new SparseTensorEnumerator<P, I, V>(*this, rank, perm);
561*8cb33240Swren romano   }
562*8cb33240Swren romano 
5638a91bc7bSHarrietAkot   /// Returns this sparse tensor storage scheme as a new memory-resident
5648a91bc7bSHarrietAkot   /// sparse tensor in coordinate scheme with the given dimension order.
5658d8b566fSwren romano   ///
5668d8b566fSwren romano   /// Precondition: `perm` must be valid for `getRank()`.
567753fe330Swren romano   SparseTensorCOO<V> *toCOO(const uint64_t *perm) const {
568*8cb33240Swren romano     SparseTensorEnumeratorBase<V> *enumerator;
569*8cb33240Swren romano     newEnumerator(&enumerator, getRank(), perm);
570753fe330Swren romano     SparseTensorCOO<V> *coo =
571*8cb33240Swren romano         new SparseTensorCOO<V>(enumerator->permutedSizes(), values.size());
572*8cb33240Swren romano     enumerator->forallElements([&coo](const std::vector<uint64_t> &ind, V val) {
573753fe330Swren romano       coo->add(ind, val);
574753fe330Swren romano     });
5758d8b566fSwren romano     // TODO: This assertion assumes there are no stored zeros,
5768d8b566fSwren romano     // or if there are then that we don't filter them out.
5778d8b566fSwren romano     // Cf., <https://github.com/llvm/llvm-project/issues/54179>
5788d8b566fSwren romano     assert(coo->getElements().size() == values.size());
579*8cb33240Swren romano     delete enumerator;
5808d8b566fSwren romano     return coo;
5818a91bc7bSHarrietAkot   }
5828a91bc7bSHarrietAkot 
5838a91bc7bSHarrietAkot   /// Factory method. Constructs a sparse tensor storage scheme with the given
5848a91bc7bSHarrietAkot   /// dimensions, permutation, and per-dimension dense/sparse annotations,
5858a91bc7bSHarrietAkot   /// using the coordinate scheme tensor for the initial contents if provided.
5868a91bc7bSHarrietAkot   /// In the latter case, the coordinate scheme must respect the same
5878a91bc7bSHarrietAkot   /// permutation as is desired for the new sparse tensor storage.
5888d8b566fSwren romano   ///
5898d8b566fSwren romano   /// Precondition: `shape`, `perm`, and `sparsity` must be valid for `rank`.
5908a91bc7bSHarrietAkot   static SparseTensorStorage<P, I, V> *
591d83a7068Swren romano   newSparseTensor(uint64_t rank, const uint64_t *shape, const uint64_t *perm,
5928d8b566fSwren romano                   const DimLevelType *sparsity, SparseTensorCOO<V> *coo) {
5938a91bc7bSHarrietAkot     SparseTensorStorage<P, I, V> *n = nullptr;
5948d8b566fSwren romano     if (coo) {
5958d8b566fSwren romano       const auto &coosz = coo->getSizes();
596*8cb33240Swren romano       assertPermutedSizesMatchShape(coosz, rank, perm, shape);
5978d8b566fSwren romano       n = new SparseTensorStorage<P, I, V>(coosz, perm, sparsity, coo);
5988a91bc7bSHarrietAkot     } else {
5998a91bc7bSHarrietAkot       std::vector<uint64_t> permsz(rank);
600d83a7068Swren romano       for (uint64_t r = 0; r < rank; r++) {
601d83a7068Swren romano         assert(shape[r] > 0 && "Dimension size zero has trivial storage");
602d83a7068Swren romano         permsz[perm[r]] = shape[r];
603d83a7068Swren romano       }
604*8cb33240Swren romano       // We pass the null `coo` to ensure we select the intended constructor.
605*8cb33240Swren romano       n = new SparseTensorStorage<P, I, V>(permsz, perm, sparsity, coo);
6068a91bc7bSHarrietAkot     }
6078a91bc7bSHarrietAkot     return n;
6088a91bc7bSHarrietAkot   }
6098a91bc7bSHarrietAkot 
610*8cb33240Swren romano   /// Factory method. Constructs a sparse tensor storage scheme with
611*8cb33240Swren romano   /// the given dimensions, permutation, and per-dimension dense/sparse
612*8cb33240Swren romano   /// annotations, using the sparse tensor for the initial contents.
613*8cb33240Swren romano   ///
614*8cb33240Swren romano   /// Preconditions:
615*8cb33240Swren romano   /// * `shape`, `perm`, and `sparsity` must be valid for `rank`.
616*8cb33240Swren romano   /// * The `tensor` must have the same value type `V`.
617*8cb33240Swren romano   static SparseTensorStorage<P, I, V> *
618*8cb33240Swren romano   newSparseTensor(uint64_t rank, const uint64_t *shape, const uint64_t *perm,
619*8cb33240Swren romano                   const DimLevelType *sparsity,
620*8cb33240Swren romano                   const SparseTensorStorageBase *source) {
621*8cb33240Swren romano     assert(source && "Got nullptr for source");
622*8cb33240Swren romano     SparseTensorEnumeratorBase<V> *enumerator;
623*8cb33240Swren romano     source->newEnumerator(&enumerator, rank, perm);
624*8cb33240Swren romano     const auto &permsz = enumerator->permutedSizes();
625*8cb33240Swren romano     assertPermutedSizesMatchShape(permsz, rank, perm, shape);
626*8cb33240Swren romano     auto *tensor =
627*8cb33240Swren romano         new SparseTensorStorage<P, I, V>(permsz, perm, sparsity, *source);
628*8cb33240Swren romano     delete enumerator;
629*8cb33240Swren romano     return tensor;
630*8cb33240Swren romano   }
631*8cb33240Swren romano 
6328a91bc7bSHarrietAkot private:
63372ec2f76Swren romano   /// Appends an arbitrary new position to `pointers[d]`.  This method
63472ec2f76Swren romano   /// checks that `pos` is representable in the `P` type; however, it
63572ec2f76Swren romano   /// does not check that `pos` is semantically valid (i.e., larger than
63672ec2f76Swren romano   /// the previous position and smaller than `indices[d].capacity()`).
6378d8b566fSwren romano   void appendPointer(uint64_t d, uint64_t pos, uint64_t count = 1) {
63872ec2f76Swren romano     assert(isCompressedDim(d));
63972ec2f76Swren romano     assert(pos <= std::numeric_limits<P>::max() &&
6404d0a18d0Swren romano            "Pointer value is too large for the P-type");
64172ec2f76Swren romano     pointers[d].insert(pointers[d].end(), count, static_cast<P>(pos));
6424d0a18d0Swren romano   }
6434d0a18d0Swren romano 
64472ec2f76Swren romano   /// Appends index `i` to dimension `d`, in the semantically general
64572ec2f76Swren romano   /// sense.  For non-dense dimensions, that means appending to the
64672ec2f76Swren romano   /// `indices[d]` array, checking that `i` is representable in the `I`
64772ec2f76Swren romano   /// type; however, we do not verify other semantic requirements (e.g.,
64872ec2f76Swren romano   /// that `i` is in bounds for `sizes[d]`, and not previously occurring
64972ec2f76Swren romano   /// in the same segment).  For dense dimensions, this method instead
65072ec2f76Swren romano   /// appends the appropriate number of zeros to the `values` array,
65172ec2f76Swren romano   /// where `full` is the number of "entries" already written to `values`
65272ec2f76Swren romano   /// for this segment (aka one after the highest index previously appended).
65372ec2f76Swren romano   void appendIndex(uint64_t d, uint64_t full, uint64_t i) {
65472ec2f76Swren romano     if (isCompressedDim(d)) {
6554d0a18d0Swren romano       assert(i <= std::numeric_limits<I>::max() &&
6564d0a18d0Swren romano              "Index value is too large for the I-type");
65772ec2f76Swren romano       indices[d].push_back(static_cast<I>(i));
65872ec2f76Swren romano     } else { // Dense dimension.
65972ec2f76Swren romano       assert(i >= full && "Index was already filled");
66072ec2f76Swren romano       if (i == full)
66172ec2f76Swren romano         return; // Short-circuit, since it'll be a nop.
66272ec2f76Swren romano       if (d + 1 == getRank())
66372ec2f76Swren romano         values.insert(values.end(), i - full, 0);
66472ec2f76Swren romano       else
66572ec2f76Swren romano         finalizeSegment(d + 1, 0, i - full);
66672ec2f76Swren romano     }
6674d0a18d0Swren romano   }
6684d0a18d0Swren romano 
669*8cb33240Swren romano   /// Writes the given coordinate to `indices[d][pos]`.  This method
670*8cb33240Swren romano   /// checks that `i` is representable in the `I` type; however, it
671*8cb33240Swren romano   /// does not check that `i` is semantically valid (i.e., in bounds
672*8cb33240Swren romano   /// for `sizes[d]` and not elsewhere occurring in the same segment).
673*8cb33240Swren romano   void writeIndex(uint64_t d, uint64_t pos, uint64_t i) {
674*8cb33240Swren romano     assert(isCompressedDim(d));
675*8cb33240Swren romano     // Subscript assignment to `std::vector` requires that the `pos`-th
676*8cb33240Swren romano     // entry has been initialized; thus we must be sure to check `size()`
677*8cb33240Swren romano     // here, instead of `capacity()` as would be ideal.
678*8cb33240Swren romano     assert(pos < indices[d].size() && "Index position is out of bounds");
679*8cb33240Swren romano     assert(i <= std::numeric_limits<I>::max() &&
680*8cb33240Swren romano            "Index value is too large for the I-type");
681*8cb33240Swren romano     indices[d][pos] = static_cast<I>(i);
682*8cb33240Swren romano   }
683*8cb33240Swren romano 
684*8cb33240Swren romano   /// Computes the assembled-size associated with the `d`-th dimension,
685*8cb33240Swren romano   /// given the assembled-size associated with the `(d-1)`-th dimension.
686*8cb33240Swren romano   /// "Assembled-sizes" correspond to the (nominal) sizes of overhead
687*8cb33240Swren romano   /// storage, as opposed to "dimension-sizes" which are the cardinality
688*8cb33240Swren romano   /// of coordinates for that dimension.
689*8cb33240Swren romano   ///
690*8cb33240Swren romano   /// Precondition: the `pointers[d]` array must be fully initialized
691*8cb33240Swren romano   /// before calling this method.
692*8cb33240Swren romano   uint64_t assembledSize(uint64_t parentSz, uint64_t d) const {
693*8cb33240Swren romano     if (isCompressedDim(d))
694*8cb33240Swren romano       return pointers[d][parentSz];
695*8cb33240Swren romano     // else if dense:
696*8cb33240Swren romano     return parentSz * getDimSizes()[d];
697*8cb33240Swren romano   }
698*8cb33240Swren romano 
6998a91bc7bSHarrietAkot   /// Initializes sparse tensor storage scheme from a memory-resident sparse
7008a91bc7bSHarrietAkot   /// tensor in coordinate scheme. This method prepares the pointers and
7018a91bc7bSHarrietAkot   /// indices arrays under the given per-dimension dense/sparse annotations.
7024d0a18d0Swren romano   ///
7034d0a18d0Swren romano   /// Preconditions:
7044d0a18d0Swren romano   /// (1) the `elements` must be lexicographically sorted.
7054d0a18d0Swren romano   /// (2) the indices of every element are valid for `sizes` (equal rank
7064d0a18d0Swren romano   ///     and pointwise less-than).
707ceda1ae9Swren romano   void fromCOO(const std::vector<Element<V>> &elements, uint64_t lo,
708ceda1ae9Swren romano                uint64_t hi, uint64_t d) {
709753fe330Swren romano     uint64_t rank = getRank();
710753fe330Swren romano     assert(d <= rank && hi <= elements.size());
7118a91bc7bSHarrietAkot     // Once dimensions are exhausted, insert the numerical values.
712753fe330Swren romano     if (d == rank) {
713c4017f9dSwren romano       assert(lo < hi);
7141ce77b56SAart Bik       values.push_back(elements[lo].value);
7158a91bc7bSHarrietAkot       return;
7168a91bc7bSHarrietAkot     }
7178a91bc7bSHarrietAkot     // Visit all elements in this interval.
7188a91bc7bSHarrietAkot     uint64_t full = 0;
719c4017f9dSwren romano     while (lo < hi) { // If `hi` is unchanged, then `lo < elements.size()`.
7208a91bc7bSHarrietAkot       // Find segment in interval with same index elements in this dimension.
721f66e5769SAart Bik       uint64_t i = elements[lo].indices[d];
7228a91bc7bSHarrietAkot       uint64_t seg = lo + 1;
723f66e5769SAart Bik       while (seg < hi && elements[seg].indices[d] == i)
7248a91bc7bSHarrietAkot         seg++;
7258a91bc7bSHarrietAkot       // Handle segment in interval for sparse or dense dimension.
72672ec2f76Swren romano       appendIndex(d, full, i);
72772ec2f76Swren romano       full = i + 1;
728ceda1ae9Swren romano       fromCOO(elements, lo, seg, d + 1);
7298a91bc7bSHarrietAkot       // And move on to next segment in interval.
7308a91bc7bSHarrietAkot       lo = seg;
7318a91bc7bSHarrietAkot     }
7328a91bc7bSHarrietAkot     // Finalize the sparse pointer structure at this dimension.
73372ec2f76Swren romano     finalizeSegment(d, full);
7348a91bc7bSHarrietAkot   }
7358a91bc7bSHarrietAkot 
73672ec2f76Swren romano   /// Finalize the sparse pointer structure at this dimension.
73772ec2f76Swren romano   void finalizeSegment(uint64_t d, uint64_t full = 0, uint64_t count = 1) {
73872ec2f76Swren romano     if (count == 0)
73972ec2f76Swren romano       return; // Short-circuit, since it'll be a nop.
74072ec2f76Swren romano     if (isCompressedDim(d)) {
74172ec2f76Swren romano       appendPointer(d, indices[d].size(), count);
74272ec2f76Swren romano     } else { // Dense dimension.
7438d8b566fSwren romano       const uint64_t sz = getDimSizes()[d];
74472ec2f76Swren romano       assert(sz >= full && "Segment is overfull");
7458d8b566fSwren romano       count = checkedMul(count, sz - full);
74672ec2f76Swren romano       // For dense storage we must enumerate all the remaining coordinates
74772ec2f76Swren romano       // in this dimension (i.e., coordinates after the last non-zero
74872ec2f76Swren romano       // element), and either fill in their zero values or else recurse
74972ec2f76Swren romano       // to finalize some deeper dimension.
75072ec2f76Swren romano       if (d + 1 == getRank())
75172ec2f76Swren romano         values.insert(values.end(), count, 0);
75272ec2f76Swren romano       else
75372ec2f76Swren romano         finalizeSegment(d + 1, 0, count);
7541ce77b56SAart Bik     }
7551ce77b56SAart Bik   }
7561ce77b56SAart Bik 
7571ce77b56SAart Bik   /// Wraps up a single insertion path, inner to outer.
7581ce77b56SAart Bik   void endPath(uint64_t diff) {
7591ce77b56SAart Bik     uint64_t rank = getRank();
7601ce77b56SAart Bik     assert(diff <= rank);
7611ce77b56SAart Bik     for (uint64_t i = 0; i < rank - diff; i++) {
76272ec2f76Swren romano       const uint64_t d = rank - i - 1;
76372ec2f76Swren romano       finalizeSegment(d, idx[d] + 1);
7641ce77b56SAart Bik     }
7651ce77b56SAart Bik   }
7661ce77b56SAart Bik 
7671ce77b56SAart Bik   /// Continues a single insertion path, outer to inner.
768c03fd1e6Swren romano   void insPath(const uint64_t *cursor, uint64_t diff, uint64_t top, V val) {
7691ce77b56SAart Bik     uint64_t rank = getRank();
7701ce77b56SAart Bik     assert(diff < rank);
7711ce77b56SAart Bik     for (uint64_t d = diff; d < rank; d++) {
7721ce77b56SAart Bik       uint64_t i = cursor[d];
77372ec2f76Swren romano       appendIndex(d, top, i);
7741ce77b56SAart Bik       top = 0;
7751ce77b56SAart Bik       idx[d] = i;
7761ce77b56SAart Bik     }
7771ce77b56SAart Bik     values.push_back(val);
7781ce77b56SAart Bik   }
7791ce77b56SAart Bik 
7801ce77b56SAart Bik   /// Finds the lexicographic differing dimension.
78146bdacaaSwren romano   uint64_t lexDiff(const uint64_t *cursor) const {
7821ce77b56SAart Bik     for (uint64_t r = 0, rank = getRank(); r < rank; r++)
7831ce77b56SAart Bik       if (cursor[r] > idx[r])
7841ce77b56SAart Bik         return r;
7851ce77b56SAart Bik       else
7861ce77b56SAart Bik         assert(cursor[r] == idx[r] && "non-lexicographic insertion");
7871ce77b56SAart Bik     assert(0 && "duplication insertion");
7881ce77b56SAart Bik     return -1u;
7891ce77b56SAart Bik   }
7901ce77b56SAart Bik 
791753fe330Swren romano   // Allow `SparseTensorEnumerator` to access the data-members (to avoid
792753fe330Swren romano   // the cost of virtual-function dispatch in inner loops), without
793753fe330Swren romano   // making them public to other client code.
794753fe330Swren romano   friend class SparseTensorEnumerator<P, I, V>;
795753fe330Swren romano 
7968a91bc7bSHarrietAkot   std::vector<std::vector<P>> pointers;
7978a91bc7bSHarrietAkot   std::vector<std::vector<I>> indices;
7988a91bc7bSHarrietAkot   std::vector<V> values;
7998d8b566fSwren romano   std::vector<uint64_t> idx; // index cursor for lexicographic insertion.
8008a91bc7bSHarrietAkot };
8018a91bc7bSHarrietAkot 
802753fe330Swren romano /// A (higher-order) function object for enumerating the elements of some
803753fe330Swren romano /// `SparseTensorStorage` under a permutation.  That is, the `forallElements`
804753fe330Swren romano /// method encapsulates the loop-nest for enumerating the elements of
805753fe330Swren romano /// the source tensor (in whatever order is best for the source tensor),
806753fe330Swren romano /// and applies a permutation to the coordinates/indices before handing
807753fe330Swren romano /// each element to the callback.  A single enumerator object can be
808753fe330Swren romano /// freely reused for several calls to `forallElements`, just so long
809753fe330Swren romano /// as each call is sequential with respect to one another.
810753fe330Swren romano ///
811753fe330Swren romano /// N.B., this class stores a reference to the `SparseTensorStorageBase`
812753fe330Swren romano /// passed to the constructor; thus, objects of this class must not
813753fe330Swren romano /// outlive the sparse tensor they depend on.
814753fe330Swren romano ///
815753fe330Swren romano /// Design Note: The reason we define this class instead of simply using
816753fe330Swren romano /// `SparseTensorEnumerator<P,I,V>` is because we need to hide/generalize
817753fe330Swren romano /// the `<P,I>` template parameters from MLIR client code (to simplify the
818753fe330Swren romano /// type parameters used for direct sparse-to-sparse conversion).  And the
819753fe330Swren romano /// reason we define the `SparseTensorEnumerator<P,I,V>` subclasses rather
820753fe330Swren romano /// than simply using this class, is to avoid the cost of virtual-method
821753fe330Swren romano /// dispatch within the loop-nest.
822753fe330Swren romano template <typename V>
823753fe330Swren romano class SparseTensorEnumeratorBase {
824753fe330Swren romano public:
825753fe330Swren romano   /// Constructs an enumerator with the given permutation for mapping
826753fe330Swren romano   /// the semantic-ordering of dimensions to the desired target-ordering.
827753fe330Swren romano   ///
828753fe330Swren romano   /// Preconditions:
829753fe330Swren romano   /// * the `tensor` must have the same `V` value type.
830753fe330Swren romano   /// * `perm` must be valid for `rank`.
831753fe330Swren romano   SparseTensorEnumeratorBase(const SparseTensorStorageBase &tensor,
832753fe330Swren romano                              uint64_t rank, const uint64_t *perm)
833753fe330Swren romano       : src(tensor), permsz(src.getRev().size()), reord(getRank()),
834753fe330Swren romano         cursor(getRank()) {
835753fe330Swren romano     assert(perm && "Received nullptr for permutation");
836753fe330Swren romano     assert(rank == getRank() && "Permutation rank mismatch");
837753fe330Swren romano     const auto &rev = src.getRev();        // source stg-order -> semantic-order
838753fe330Swren romano     const auto &sizes = src.getDimSizes(); // in source storage-order
839753fe330Swren romano     for (uint64_t s = 0; s < rank; s++) {  // `s` source storage-order
840753fe330Swren romano       uint64_t t = perm[rev[s]];           // `t` target-order
841753fe330Swren romano       reord[s] = t;
842753fe330Swren romano       permsz[t] = sizes[s];
843753fe330Swren romano     }
844753fe330Swren romano   }
845753fe330Swren romano 
846753fe330Swren romano   virtual ~SparseTensorEnumeratorBase() = default;
847753fe330Swren romano 
848753fe330Swren romano   // We disallow copying to help avoid leaking the `src` reference.
849753fe330Swren romano   // (In addition to avoiding the problem of slicing.)
850753fe330Swren romano   SparseTensorEnumeratorBase(const SparseTensorEnumeratorBase &) = delete;
851753fe330Swren romano   SparseTensorEnumeratorBase &
852753fe330Swren romano   operator=(const SparseTensorEnumeratorBase &) = delete;
853753fe330Swren romano 
854753fe330Swren romano   /// Returns the source/target tensor's rank.  (The source-rank and
855753fe330Swren romano   /// target-rank are always equal since we only support permutations.
856753fe330Swren romano   /// Though once we add support for other dimension mappings, this
857753fe330Swren romano   /// method will have to be split in two.)
858753fe330Swren romano   uint64_t getRank() const { return permsz.size(); }
859753fe330Swren romano 
860753fe330Swren romano   /// Returns the target tensor's dimension sizes.
861753fe330Swren romano   const std::vector<uint64_t> &permutedSizes() const { return permsz; }
862753fe330Swren romano 
863753fe330Swren romano   /// Enumerates all elements of the source tensor, permutes their
864753fe330Swren romano   /// indices, and passes the permuted element to the callback.
865753fe330Swren romano   /// The callback must not store the cursor reference directly,
866753fe330Swren romano   /// since this function reuses the storage.  Instead, the callback
867753fe330Swren romano   /// must copy it if they want to keep it.
868753fe330Swren romano   virtual void forallElements(ElementConsumer<V> yield) = 0;
869753fe330Swren romano 
870753fe330Swren romano protected:
871753fe330Swren romano   const SparseTensorStorageBase &src;
872753fe330Swren romano   std::vector<uint64_t> permsz; // in target order.
873753fe330Swren romano   std::vector<uint64_t> reord;  // source storage-order -> target order.
874753fe330Swren romano   std::vector<uint64_t> cursor; // in target order.
875753fe330Swren romano };
876753fe330Swren romano 
877753fe330Swren romano template <typename P, typename I, typename V>
878753fe330Swren romano class SparseTensorEnumerator final : public SparseTensorEnumeratorBase<V> {
879753fe330Swren romano   using Base = SparseTensorEnumeratorBase<V>;
880753fe330Swren romano 
881753fe330Swren romano public:
882753fe330Swren romano   /// Constructs an enumerator with the given permutation for mapping
883753fe330Swren romano   /// the semantic-ordering of dimensions to the desired target-ordering.
884753fe330Swren romano   ///
885753fe330Swren romano   /// Precondition: `perm` must be valid for `rank`.
886753fe330Swren romano   SparseTensorEnumerator(const SparseTensorStorage<P, I, V> &tensor,
887753fe330Swren romano                          uint64_t rank, const uint64_t *perm)
888753fe330Swren romano       : Base(tensor, rank, perm) {}
889753fe330Swren romano 
890753fe330Swren romano   ~SparseTensorEnumerator() final override = default;
891753fe330Swren romano 
892753fe330Swren romano   void forallElements(ElementConsumer<V> yield) final override {
893753fe330Swren romano     forallElements(yield, 0, 0);
894753fe330Swren romano   }
895753fe330Swren romano 
896753fe330Swren romano private:
897753fe330Swren romano   /// The recursive component of the public `forallElements`.
898753fe330Swren romano   void forallElements(ElementConsumer<V> yield, uint64_t parentPos,
899753fe330Swren romano                       uint64_t d) {
900753fe330Swren romano     // Recover the `<P,I,V>` type parameters of `src`.
901753fe330Swren romano     const auto &src =
902753fe330Swren romano         static_cast<const SparseTensorStorage<P, I, V> &>(this->src);
903753fe330Swren romano     if (d == Base::getRank()) {
904753fe330Swren romano       assert(parentPos < src.values.size() &&
905753fe330Swren romano              "Value position is out of bounds");
906753fe330Swren romano       // TODO: <https://github.com/llvm/llvm-project/issues/54179>
907753fe330Swren romano       yield(this->cursor, src.values[parentPos]);
908753fe330Swren romano     } else if (src.isCompressedDim(d)) {
909753fe330Swren romano       // Look up the bounds of the `d`-level segment determined by the
910753fe330Swren romano       // `d-1`-level position `parentPos`.
911753fe330Swren romano       const std::vector<P> &pointers_d = src.pointers[d];
912753fe330Swren romano       assert(parentPos + 1 < pointers_d.size() &&
913753fe330Swren romano              "Parent pointer position is out of bounds");
914753fe330Swren romano       const uint64_t pstart = static_cast<uint64_t>(pointers_d[parentPos]);
915753fe330Swren romano       const uint64_t pstop = static_cast<uint64_t>(pointers_d[parentPos + 1]);
916753fe330Swren romano       // Loop-invariant code for looking up the `d`-level coordinates/indices.
917753fe330Swren romano       const std::vector<I> &indices_d = src.indices[d];
918753fe330Swren romano       assert(pstop - 1 < indices_d.size() && "Index position is out of bounds");
919753fe330Swren romano       uint64_t &cursor_reord_d = this->cursor[this->reord[d]];
920753fe330Swren romano       for (uint64_t pos = pstart; pos < pstop; pos++) {
921753fe330Swren romano         cursor_reord_d = static_cast<uint64_t>(indices_d[pos]);
922753fe330Swren romano         forallElements(yield, pos, d + 1);
923753fe330Swren romano       }
924753fe330Swren romano     } else { // Dense dimension.
925753fe330Swren romano       const uint64_t sz = src.getDimSizes()[d];
926753fe330Swren romano       const uint64_t pstart = parentPos * sz;
927753fe330Swren romano       uint64_t &cursor_reord_d = this->cursor[this->reord[d]];
928753fe330Swren romano       for (uint64_t i = 0; i < sz; i++) {
929753fe330Swren romano         cursor_reord_d = i;
930753fe330Swren romano         forallElements(yield, pstart + i, d + 1);
931753fe330Swren romano       }
932753fe330Swren romano     }
933753fe330Swren romano   }
934753fe330Swren romano };
935753fe330Swren romano 
936*8cb33240Swren romano /// Statistics regarding the number of nonzero subtensors in
937*8cb33240Swren romano /// a source tensor, for direct sparse=>sparse conversion a la
938*8cb33240Swren romano /// <https://arxiv.org/abs/2001.02609>.
939*8cb33240Swren romano ///
940*8cb33240Swren romano /// N.B., this class stores references to the parameters passed to
941*8cb33240Swren romano /// the constructor; thus, objects of this class must not outlive
942*8cb33240Swren romano /// those parameters.
943*8cb33240Swren romano class SparseTensorNNZ {
944*8cb33240Swren romano public:
945*8cb33240Swren romano   /// Allocate the statistics structure for the desired sizes and
946*8cb33240Swren romano   /// sparsity (in the target tensor's storage-order).  This constructor
947*8cb33240Swren romano   /// does not actually populate the statistics, however; for that see
948*8cb33240Swren romano   /// `initialize`.
949*8cb33240Swren romano   ///
950*8cb33240Swren romano   /// Precondition: `szs` must not contain zeros.
951*8cb33240Swren romano   SparseTensorNNZ(const std::vector<uint64_t> &szs,
952*8cb33240Swren romano                   const std::vector<DimLevelType> &sparsity)
953*8cb33240Swren romano       : dimSizes(szs), dimTypes(sparsity), nnz(getRank()) {
954*8cb33240Swren romano     assert(dimSizes.size() == dimTypes.size() && "Rank mismatch");
955*8cb33240Swren romano     bool uncompressed = true;
956*8cb33240Swren romano     uint64_t sz = 1; // the product of all `dimSizes` strictly less than `r`.
957*8cb33240Swren romano     for (uint64_t rank = getRank(), r = 0; r < rank; r++) {
958*8cb33240Swren romano       switch (dimTypes[r]) {
959*8cb33240Swren romano       case DimLevelType::kCompressed:
960*8cb33240Swren romano         assert(uncompressed &&
961*8cb33240Swren romano                "Multiple compressed layers not currently supported");
962*8cb33240Swren romano         uncompressed = false;
963*8cb33240Swren romano         nnz[r].resize(sz, 0); // Both allocate and zero-initialize.
964*8cb33240Swren romano         break;
965*8cb33240Swren romano       case DimLevelType::kDense:
966*8cb33240Swren romano         assert(uncompressed &&
967*8cb33240Swren romano                "Dense after compressed not currently supported");
968*8cb33240Swren romano         break;
969*8cb33240Swren romano       case DimLevelType::kSingleton:
970*8cb33240Swren romano         // Singleton after Compressed causes no problems for allocating
971*8cb33240Swren romano         // `nnz` nor for the yieldPos loop.  This remains true even
972*8cb33240Swren romano         // when adding support for multiple compressed dimensions or
973*8cb33240Swren romano         // for dense-after-compressed.
974*8cb33240Swren romano         break;
975*8cb33240Swren romano       }
976*8cb33240Swren romano       sz = checkedMul(sz, dimSizes[r]);
977*8cb33240Swren romano     }
978*8cb33240Swren romano   }
979*8cb33240Swren romano 
980*8cb33240Swren romano   // We disallow copying to help avoid leaking the stored references.
981*8cb33240Swren romano   SparseTensorNNZ(const SparseTensorNNZ &) = delete;
982*8cb33240Swren romano   SparseTensorNNZ &operator=(const SparseTensorNNZ &) = delete;
983*8cb33240Swren romano 
984*8cb33240Swren romano   /// Returns the rank of the target tensor.
985*8cb33240Swren romano   uint64_t getRank() const { return dimSizes.size(); }
986*8cb33240Swren romano 
987*8cb33240Swren romano   /// Enumerate the source tensor to fill in the statistics.  The
988*8cb33240Swren romano   /// enumerator should already incorporate the permutation (from
989*8cb33240Swren romano   /// semantic-order to the target storage-order).
990*8cb33240Swren romano   template <typename V>
991*8cb33240Swren romano   void initialize(SparseTensorEnumeratorBase<V> &enumerator) {
992*8cb33240Swren romano     assert(enumerator.getRank() == getRank() && "Tensor rank mismatch");
993*8cb33240Swren romano     assert(enumerator.permutedSizes() == dimSizes && "Tensor size mismatch");
994*8cb33240Swren romano     enumerator.forallElements(
995*8cb33240Swren romano         [this](const std::vector<uint64_t> &ind, V) { add(ind); });
996*8cb33240Swren romano   }
997*8cb33240Swren romano 
998*8cb33240Swren romano   /// The type of callback functions which receive an nnz-statistic.
999*8cb33240Swren romano   using NNZConsumer = const std::function<void(uint64_t)> &;
1000*8cb33240Swren romano 
1001*8cb33240Swren romano   /// Lexicographically enumerates all indicies for dimensions strictly
1002*8cb33240Swren romano   /// less than `stopDim`, and passes their nnz statistic to the callback.
1003*8cb33240Swren romano   /// Since our use-case only requires the statistic not the coordinates
1004*8cb33240Swren romano   /// themselves, we do not bother to construct those coordinates.
1005*8cb33240Swren romano   void forallIndices(uint64_t stopDim, NNZConsumer yield) const {
1006*8cb33240Swren romano     assert(stopDim < getRank() && "Stopping-dimension is out of bounds");
1007*8cb33240Swren romano     assert(dimTypes[stopDim] == DimLevelType::kCompressed &&
1008*8cb33240Swren romano            "Cannot look up non-compressed dimensions");
1009*8cb33240Swren romano     forallIndices(yield, stopDim, 0, 0);
1010*8cb33240Swren romano   }
1011*8cb33240Swren romano 
1012*8cb33240Swren romano private:
1013*8cb33240Swren romano   /// Adds a new element (i.e., increment its statistics).  We use
1014*8cb33240Swren romano   /// a method rather than inlining into the lambda in `initialize`,
1015*8cb33240Swren romano   /// to avoid spurious templating over `V`.  And this method is private
1016*8cb33240Swren romano   /// to avoid needing to re-assert validity of `ind` (which is guaranteed
1017*8cb33240Swren romano   /// by `forallElements`).
1018*8cb33240Swren romano   void add(const std::vector<uint64_t> &ind) {
1019*8cb33240Swren romano     uint64_t parentPos = 0;
1020*8cb33240Swren romano     for (uint64_t rank = getRank(), r = 0; r < rank; r++) {
1021*8cb33240Swren romano       if (dimTypes[r] == DimLevelType::kCompressed)
1022*8cb33240Swren romano         nnz[r][parentPos]++;
1023*8cb33240Swren romano       parentPos = parentPos * dimSizes[r] + ind[r];
1024*8cb33240Swren romano     }
1025*8cb33240Swren romano   }
1026*8cb33240Swren romano 
1027*8cb33240Swren romano   /// Recursive component of the public `forallIndices`.
1028*8cb33240Swren romano   void forallIndices(NNZConsumer yield, uint64_t stopDim, uint64_t parentPos,
1029*8cb33240Swren romano                      uint64_t d) const {
1030*8cb33240Swren romano     assert(d <= stopDim);
1031*8cb33240Swren romano     if (d == stopDim) {
1032*8cb33240Swren romano       assert(parentPos < nnz[d].size() && "Cursor is out of range");
1033*8cb33240Swren romano       yield(nnz[d][parentPos]);
1034*8cb33240Swren romano     } else {
1035*8cb33240Swren romano       const uint64_t sz = dimSizes[d];
1036*8cb33240Swren romano       const uint64_t pstart = parentPos * sz;
1037*8cb33240Swren romano       for (uint64_t i = 0; i < sz; i++)
1038*8cb33240Swren romano         forallIndices(yield, stopDim, pstart + i, d + 1);
1039*8cb33240Swren romano     }
1040*8cb33240Swren romano   }
1041*8cb33240Swren romano 
1042*8cb33240Swren romano   // All of these are in the target storage-order.
1043*8cb33240Swren romano   const std::vector<uint64_t> &dimSizes;
1044*8cb33240Swren romano   const std::vector<DimLevelType> &dimTypes;
1045*8cb33240Swren romano   std::vector<std::vector<uint64_t>> nnz;
1046*8cb33240Swren romano };
1047*8cb33240Swren romano 
1048*8cb33240Swren romano template <typename P, typename I, typename V>
1049*8cb33240Swren romano SparseTensorStorage<P, I, V>::SparseTensorStorage(
1050*8cb33240Swren romano     const std::vector<uint64_t> &szs, const uint64_t *perm,
1051*8cb33240Swren romano     const DimLevelType *sparsity, const SparseTensorStorageBase &tensor)
1052*8cb33240Swren romano     : SparseTensorStorage(szs, perm, sparsity) {
1053*8cb33240Swren romano   SparseTensorEnumeratorBase<V> *enumerator;
1054*8cb33240Swren romano   tensor.newEnumerator(&enumerator, getRank(), perm);
1055*8cb33240Swren romano   {
1056*8cb33240Swren romano     // Initialize the statistics structure.
1057*8cb33240Swren romano     SparseTensorNNZ nnz(getDimSizes(), getDimTypes());
1058*8cb33240Swren romano     nnz.initialize(*enumerator);
1059*8cb33240Swren romano     // Initialize "pointers" overhead (and allocate "indices", "values").
1060*8cb33240Swren romano     uint64_t parentSz = 1; // assembled-size (not dimension-size) of `r-1`.
1061*8cb33240Swren romano     for (uint64_t rank = getRank(), r = 0; r < rank; r++) {
1062*8cb33240Swren romano       if (isCompressedDim(r)) {
1063*8cb33240Swren romano         pointers[r].reserve(parentSz + 1);
1064*8cb33240Swren romano         pointers[r].push_back(0);
1065*8cb33240Swren romano         uint64_t currentPos = 0;
1066*8cb33240Swren romano         nnz.forallIndices(r, [this, &currentPos, r](uint64_t n) {
1067*8cb33240Swren romano           currentPos += n;
1068*8cb33240Swren romano           appendPointer(r, currentPos);
1069*8cb33240Swren romano         });
1070*8cb33240Swren romano         assert(pointers[r].size() == parentSz + 1 &&
1071*8cb33240Swren romano                "Final pointers size doesn't match allocated size");
1072*8cb33240Swren romano         // That assertion entails `assembledSize(parentSz, r)`
1073*8cb33240Swren romano         // is now in a valid state.  That is, `pointers[r][parentSz]`
1074*8cb33240Swren romano         // equals the present value of `currentPos`, which is the
1075*8cb33240Swren romano         // correct assembled-size for `indices[r]`.
1076*8cb33240Swren romano       }
1077*8cb33240Swren romano       // Update assembled-size for the next iteration.
1078*8cb33240Swren romano       parentSz = assembledSize(parentSz, r);
1079*8cb33240Swren romano       // Ideally we need only `indices[r].reserve(parentSz)`, however
1080*8cb33240Swren romano       // the `std::vector` implementation forces us to initialize it too.
1081*8cb33240Swren romano       // That is, in the yieldPos loop we need random-access assignment
1082*8cb33240Swren romano       // to `indices[r]`; however, `std::vector`'s subscript-assignment
1083*8cb33240Swren romano       // only allows assigning to already-initialized positions.
1084*8cb33240Swren romano       if (isCompressedDim(r))
1085*8cb33240Swren romano         indices[r].resize(parentSz, 0);
1086*8cb33240Swren romano     }
1087*8cb33240Swren romano     values.resize(parentSz, 0); // Both allocate and zero-initialize.
1088*8cb33240Swren romano   }
1089*8cb33240Swren romano   // The yieldPos loop
1090*8cb33240Swren romano   enumerator->forallElements([this](const std::vector<uint64_t> &ind, V val) {
1091*8cb33240Swren romano     uint64_t parentSz = 1, parentPos = 0;
1092*8cb33240Swren romano     for (uint64_t rank = getRank(), r = 0; r < rank; r++) {
1093*8cb33240Swren romano       if (isCompressedDim(r)) {
1094*8cb33240Swren romano         // If `parentPos == parentSz` then it's valid as an array-lookup;
1095*8cb33240Swren romano         // however, it's semantically invalid here since that entry
1096*8cb33240Swren romano         // does not represent a segment of `indices[r]`.  Moreover, that
1097*8cb33240Swren romano         // entry must be immutable for `assembledSize` to remain valid.
1098*8cb33240Swren romano         assert(parentPos < parentSz && "Pointers position is out of bounds");
1099*8cb33240Swren romano         const uint64_t currentPos = pointers[r][parentPos];
1100*8cb33240Swren romano         // This increment won't overflow the `P` type, since it can't
1101*8cb33240Swren romano         // exceed the original value of `pointers[r][parentPos+1]`
1102*8cb33240Swren romano         // which was already verified to be within bounds for `P`
1103*8cb33240Swren romano         // when it was written to the array.
1104*8cb33240Swren romano         pointers[r][parentPos]++;
1105*8cb33240Swren romano         writeIndex(r, currentPos, ind[r]);
1106*8cb33240Swren romano         parentPos = currentPos;
1107*8cb33240Swren romano       } else { // Dense dimension.
1108*8cb33240Swren romano         parentPos = parentPos * getDimSizes()[r] + ind[r];
1109*8cb33240Swren romano       }
1110*8cb33240Swren romano       parentSz = assembledSize(parentSz, r);
1111*8cb33240Swren romano     }
1112*8cb33240Swren romano     assert(parentPos < values.size() && "Value position is out of bounds");
1113*8cb33240Swren romano     values[parentPos] = val;
1114*8cb33240Swren romano   });
1115*8cb33240Swren romano   // No longer need the enumerator, so we'll delete it ASAP.
1116*8cb33240Swren romano   delete enumerator;
1117*8cb33240Swren romano   // The finalizeYieldPos loop
1118*8cb33240Swren romano   for (uint64_t parentSz = 1, rank = getRank(), r = 0; r < rank; r++) {
1119*8cb33240Swren romano     if (isCompressedDim(r)) {
1120*8cb33240Swren romano       assert(parentSz == pointers[r].size() - 1 &&
1121*8cb33240Swren romano              "Actual pointers size doesn't match the expected size");
1122*8cb33240Swren romano       // Can't check all of them, but at least we can check the last one.
1123*8cb33240Swren romano       assert(pointers[r][parentSz - 1] == pointers[r][parentSz] &&
1124*8cb33240Swren romano              "Pointers got corrupted");
1125*8cb33240Swren romano       // TODO: optimize this by using `memmove` or similar.
1126*8cb33240Swren romano       for (uint64_t n = 0; n < parentSz; n++) {
1127*8cb33240Swren romano         const uint64_t parentPos = parentSz - n;
1128*8cb33240Swren romano         pointers[r][parentPos] = pointers[r][parentPos - 1];
1129*8cb33240Swren romano       }
1130*8cb33240Swren romano       pointers[r][0] = 0;
1131*8cb33240Swren romano     }
1132*8cb33240Swren romano     parentSz = assembledSize(parentSz, r);
1133*8cb33240Swren romano   }
1134*8cb33240Swren romano }
1135*8cb33240Swren romano 
11368a91bc7bSHarrietAkot /// Helper to convert string to lower case.
11378a91bc7bSHarrietAkot static char *toLower(char *token) {
11388a91bc7bSHarrietAkot   for (char *c = token; *c; c++)
11398a91bc7bSHarrietAkot     *c = tolower(*c);
11408a91bc7bSHarrietAkot   return token;
11418a91bc7bSHarrietAkot }
11428a91bc7bSHarrietAkot 
11438a91bc7bSHarrietAkot /// Read the MME header of a general sparse matrix of type real.
114403fe15ceSAart Bik static void readMMEHeader(FILE *file, char *filename, char *line,
114533e8ab8eSAart Bik                           uint64_t *idata, bool *isPattern, bool *isSymmetric) {
11468a91bc7bSHarrietAkot   char header[64];
11478a91bc7bSHarrietAkot   char object[64];
11488a91bc7bSHarrietAkot   char format[64];
11498a91bc7bSHarrietAkot   char field[64];
11508a91bc7bSHarrietAkot   char symmetry[64];
11518a91bc7bSHarrietAkot   // Read header line.
11528a91bc7bSHarrietAkot   if (fscanf(file, "%63s %63s %63s %63s %63s\n", header, object, format, field,
11538a91bc7bSHarrietAkot              symmetry) != 5) {
115403fe15ceSAart Bik     fprintf(stderr, "Corrupt header in %s\n", filename);
11558a91bc7bSHarrietAkot     exit(1);
11568a91bc7bSHarrietAkot   }
115733e8ab8eSAart Bik   // Set properties
115833e8ab8eSAart Bik   *isPattern = (strcmp(toLower(field), "pattern") == 0);
1159bb56c2b3SMehdi Amini   *isSymmetric = (strcmp(toLower(symmetry), "symmetric") == 0);
11608a91bc7bSHarrietAkot   // Make sure this is a general sparse matrix.
11618a91bc7bSHarrietAkot   if (strcmp(toLower(header), "%%matrixmarket") ||
11628a91bc7bSHarrietAkot       strcmp(toLower(object), "matrix") ||
116333e8ab8eSAart Bik       strcmp(toLower(format), "coordinate") ||
116433e8ab8eSAart Bik       (strcmp(toLower(field), "real") && !(*isPattern)) ||
1165bb56c2b3SMehdi Amini       (strcmp(toLower(symmetry), "general") && !(*isSymmetric))) {
116633e8ab8eSAart Bik     fprintf(stderr, "Cannot find a general sparse matrix in %s\n", filename);
11678a91bc7bSHarrietAkot     exit(1);
11688a91bc7bSHarrietAkot   }
11698a91bc7bSHarrietAkot   // Skip comments.
1170e5639b3fSMehdi Amini   while (true) {
117103fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
117203fe15ceSAart Bik       fprintf(stderr, "Cannot find data in %s\n", filename);
11738a91bc7bSHarrietAkot       exit(1);
11748a91bc7bSHarrietAkot     }
11758a91bc7bSHarrietAkot     if (line[0] != '%')
11768a91bc7bSHarrietAkot       break;
11778a91bc7bSHarrietAkot   }
11788a91bc7bSHarrietAkot   // Next line contains M N NNZ.
11798a91bc7bSHarrietAkot   idata[0] = 2; // rank
11808a91bc7bSHarrietAkot   if (sscanf(line, "%" PRIu64 "%" PRIu64 "%" PRIu64 "\n", idata + 2, idata + 3,
11818a91bc7bSHarrietAkot              idata + 1) != 3) {
118203fe15ceSAart Bik     fprintf(stderr, "Cannot find size in %s\n", filename);
11838a91bc7bSHarrietAkot     exit(1);
11848a91bc7bSHarrietAkot   }
11858a91bc7bSHarrietAkot }
11868a91bc7bSHarrietAkot 
11878a91bc7bSHarrietAkot /// Read the "extended" FROSTT header. Although not part of the documented
11888a91bc7bSHarrietAkot /// format, we assume that the file starts with optional comments followed
11898a91bc7bSHarrietAkot /// by two lines that define the rank, the number of nonzeros, and the
11908a91bc7bSHarrietAkot /// dimensions sizes (one per rank) of the sparse tensor.
119103fe15ceSAart Bik static void readExtFROSTTHeader(FILE *file, char *filename, char *line,
119203fe15ceSAart Bik                                 uint64_t *idata) {
11938a91bc7bSHarrietAkot   // Skip comments.
1194e5639b3fSMehdi Amini   while (true) {
119503fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
119603fe15ceSAart Bik       fprintf(stderr, "Cannot find data in %s\n", filename);
11978a91bc7bSHarrietAkot       exit(1);
11988a91bc7bSHarrietAkot     }
11998a91bc7bSHarrietAkot     if (line[0] != '#')
12008a91bc7bSHarrietAkot       break;
12018a91bc7bSHarrietAkot   }
12028a91bc7bSHarrietAkot   // Next line contains RANK and NNZ.
12038a91bc7bSHarrietAkot   if (sscanf(line, "%" PRIu64 "%" PRIu64 "\n", idata, idata + 1) != 2) {
120403fe15ceSAart Bik     fprintf(stderr, "Cannot find metadata in %s\n", filename);
12058a91bc7bSHarrietAkot     exit(1);
12068a91bc7bSHarrietAkot   }
12078a91bc7bSHarrietAkot   // Followed by a line with the dimension sizes (one per rank).
12088a91bc7bSHarrietAkot   for (uint64_t r = 0; r < idata[0]; r++) {
12098a91bc7bSHarrietAkot     if (fscanf(file, "%" PRIu64, idata + 2 + r) != 1) {
121003fe15ceSAart Bik       fprintf(stderr, "Cannot find dimension size %s\n", filename);
12118a91bc7bSHarrietAkot       exit(1);
12128a91bc7bSHarrietAkot     }
12138a91bc7bSHarrietAkot   }
121403fe15ceSAart Bik   fgets(line, kColWidth, file); // end of line
12158a91bc7bSHarrietAkot }
12168a91bc7bSHarrietAkot 
12178a91bc7bSHarrietAkot /// Reads a sparse tensor with the given filename into a memory-resident
12188a91bc7bSHarrietAkot /// sparse tensor in coordinate scheme.
12198a91bc7bSHarrietAkot template <typename V>
12208a91bc7bSHarrietAkot static SparseTensorCOO<V> *openSparseTensorCOO(char *filename, uint64_t rank,
1221d83a7068Swren romano                                                const uint64_t *shape,
12228a91bc7bSHarrietAkot                                                const uint64_t *perm) {
12238a91bc7bSHarrietAkot   // Open the file.
12248a91bc7bSHarrietAkot   FILE *file = fopen(filename, "r");
12258a91bc7bSHarrietAkot   if (!file) {
12263734c078Swren romano     assert(filename && "Received nullptr for filename");
12273734c078Swren romano     fprintf(stderr, "Cannot find file %s\n", filename);
12288a91bc7bSHarrietAkot     exit(1);
12298a91bc7bSHarrietAkot   }
12308a91bc7bSHarrietAkot   // Perform some file format dependent set up.
123103fe15ceSAart Bik   char line[kColWidth];
12328a91bc7bSHarrietAkot   uint64_t idata[512];
123333e8ab8eSAart Bik   bool isPattern = false;
1234bb56c2b3SMehdi Amini   bool isSymmetric = false;
12358a91bc7bSHarrietAkot   if (strstr(filename, ".mtx")) {
123633e8ab8eSAart Bik     readMMEHeader(file, filename, line, idata, &isPattern, &isSymmetric);
12378a91bc7bSHarrietAkot   } else if (strstr(filename, ".tns")) {
123803fe15ceSAart Bik     readExtFROSTTHeader(file, filename, line, idata);
12398a91bc7bSHarrietAkot   } else {
12408a91bc7bSHarrietAkot     fprintf(stderr, "Unknown format %s\n", filename);
12418a91bc7bSHarrietAkot     exit(1);
12428a91bc7bSHarrietAkot   }
12438a91bc7bSHarrietAkot   // Prepare sparse tensor object with per-dimension sizes
12448a91bc7bSHarrietAkot   // and the number of nonzeros as initial capacity.
12458a91bc7bSHarrietAkot   assert(rank == idata[0] && "rank mismatch");
12468a91bc7bSHarrietAkot   uint64_t nnz = idata[1];
12478a91bc7bSHarrietAkot   for (uint64_t r = 0; r < rank; r++)
1248d83a7068Swren romano     assert((shape[r] == 0 || shape[r] == idata[2 + r]) &&
12498a91bc7bSHarrietAkot            "dimension size mismatch");
12508a91bc7bSHarrietAkot   SparseTensorCOO<V> *tensor =
12518a91bc7bSHarrietAkot       SparseTensorCOO<V>::newSparseTensorCOO(rank, idata + 2, perm, nnz);
12528a91bc7bSHarrietAkot   // Read all nonzero elements.
12538a91bc7bSHarrietAkot   std::vector<uint64_t> indices(rank);
12548a91bc7bSHarrietAkot   for (uint64_t k = 0; k < nnz; k++) {
125503fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
125603fe15ceSAart Bik       fprintf(stderr, "Cannot find next line of data in %s\n", filename);
12578a91bc7bSHarrietAkot       exit(1);
12588a91bc7bSHarrietAkot     }
125903fe15ceSAart Bik     char *linePtr = line;
126003fe15ceSAart Bik     for (uint64_t r = 0; r < rank; r++) {
126103fe15ceSAart Bik       uint64_t idx = strtoul(linePtr, &linePtr, 10);
12628a91bc7bSHarrietAkot       // Add 0-based index.
12638a91bc7bSHarrietAkot       indices[perm[r]] = idx - 1;
12648a91bc7bSHarrietAkot     }
12658a91bc7bSHarrietAkot     // The external formats always store the numerical values with the type
12668a91bc7bSHarrietAkot     // double, but we cast these values to the sparse tensor object type.
126733e8ab8eSAart Bik     // For a pattern tensor, we arbitrarily pick the value 1 for all entries.
126833e8ab8eSAart Bik     double value = isPattern ? 1.0 : strtod(linePtr, &linePtr);
12698a91bc7bSHarrietAkot     tensor->add(indices, value);
127002710413SBixia Zheng     // We currently chose to deal with symmetric matrices by fully constructing
127102710413SBixia Zheng     // them. In the future, we may want to make symmetry implicit for storage
127202710413SBixia Zheng     // reasons.
1273bb56c2b3SMehdi Amini     if (isSymmetric && indices[0] != indices[1])
127402710413SBixia Zheng       tensor->add({indices[1], indices[0]}, value);
12758a91bc7bSHarrietAkot   }
12768a91bc7bSHarrietAkot   // Close the file and return tensor.
12778a91bc7bSHarrietAkot   fclose(file);
12788a91bc7bSHarrietAkot   return tensor;
12798a91bc7bSHarrietAkot }
12808a91bc7bSHarrietAkot 
1281efa15f41SAart Bik /// Writes the sparse tensor to extended FROSTT format.
1282efa15f41SAart Bik template <typename V>
128346bdacaaSwren romano static void outSparseTensor(void *tensor, void *dest, bool sort) {
12846438783fSAart Bik   assert(tensor && dest);
12856438783fSAart Bik   auto coo = static_cast<SparseTensorCOO<V> *>(tensor);
12866438783fSAart Bik   if (sort)
12876438783fSAart Bik     coo->sort();
12886438783fSAart Bik   char *filename = static_cast<char *>(dest);
12896438783fSAart Bik   auto &sizes = coo->getSizes();
12906438783fSAart Bik   auto &elements = coo->getElements();
12916438783fSAart Bik   uint64_t rank = coo->getRank();
1292efa15f41SAart Bik   uint64_t nnz = elements.size();
1293efa15f41SAart Bik   std::fstream file;
1294efa15f41SAart Bik   file.open(filename, std::ios_base::out | std::ios_base::trunc);
1295efa15f41SAart Bik   assert(file.is_open());
1296efa15f41SAart Bik   file << "; extended FROSTT format\n" << rank << " " << nnz << std::endl;
1297efa15f41SAart Bik   for (uint64_t r = 0; r < rank - 1; r++)
1298efa15f41SAart Bik     file << sizes[r] << " ";
1299efa15f41SAart Bik   file << sizes[rank - 1] << std::endl;
1300efa15f41SAart Bik   for (uint64_t i = 0; i < nnz; i++) {
1301efa15f41SAart Bik     auto &idx = elements[i].indices;
1302efa15f41SAart Bik     for (uint64_t r = 0; r < rank; r++)
1303efa15f41SAart Bik       file << (idx[r] + 1) << " ";
1304efa15f41SAart Bik     file << elements[i].value << std::endl;
1305efa15f41SAart Bik   }
1306efa15f41SAart Bik   file.flush();
1307efa15f41SAart Bik   file.close();
1308efa15f41SAart Bik   assert(file.good());
13096438783fSAart Bik }
13106438783fSAart Bik 
13116438783fSAart Bik /// Initializes sparse tensor from an external COO-flavored format.
13126438783fSAart Bik template <typename V>
131346bdacaaSwren romano static SparseTensorStorage<uint64_t, uint64_t, V> *
13146438783fSAart Bik toMLIRSparseTensor(uint64_t rank, uint64_t nse, uint64_t *shape, V *values,
131520eaa88fSBixia Zheng                    uint64_t *indices, uint64_t *perm, uint8_t *sparse) {
131620eaa88fSBixia Zheng   const DimLevelType *sparsity = (DimLevelType *)(sparse);
131720eaa88fSBixia Zheng #ifndef NDEBUG
131820eaa88fSBixia Zheng   // Verify that perm is a permutation of 0..(rank-1).
131920eaa88fSBixia Zheng   std::vector<uint64_t> order(perm, perm + rank);
132020eaa88fSBixia Zheng   std::sort(order.begin(), order.end());
13211e47888dSAart Bik   for (uint64_t i = 0; i < rank; ++i) {
132220eaa88fSBixia Zheng     if (i != order[i]) {
1323988d4b0dSAart Bik       fprintf(stderr, "Not a permutation of 0..%" PRIu64 "\n", rank);
132420eaa88fSBixia Zheng       exit(1);
132520eaa88fSBixia Zheng     }
132620eaa88fSBixia Zheng   }
132720eaa88fSBixia Zheng 
132820eaa88fSBixia Zheng   // Verify that the sparsity values are supported.
13291e47888dSAart Bik   for (uint64_t i = 0; i < rank; ++i) {
133020eaa88fSBixia Zheng     if (sparsity[i] != DimLevelType::kDense &&
133120eaa88fSBixia Zheng         sparsity[i] != DimLevelType::kCompressed) {
133220eaa88fSBixia Zheng       fprintf(stderr, "Unsupported sparsity value %d\n",
133320eaa88fSBixia Zheng               static_cast<int>(sparsity[i]));
133420eaa88fSBixia Zheng       exit(1);
133520eaa88fSBixia Zheng     }
133620eaa88fSBixia Zheng   }
133720eaa88fSBixia Zheng #endif
133820eaa88fSBixia Zheng 
13396438783fSAart Bik   // Convert external format to internal COO.
134063bdcaf9Swren romano   auto *coo = SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm, nse);
13416438783fSAart Bik   std::vector<uint64_t> idx(rank);
13426438783fSAart Bik   for (uint64_t i = 0, base = 0; i < nse; i++) {
13436438783fSAart Bik     for (uint64_t r = 0; r < rank; r++)
1344d8b229a1SAart Bik       idx[perm[r]] = indices[base + r];
134563bdcaf9Swren romano     coo->add(idx, values[i]);
13466438783fSAart Bik     base += rank;
13476438783fSAart Bik   }
13486438783fSAart Bik   // Return sparse tensor storage format as opaque pointer.
134963bdcaf9Swren romano   auto *tensor = SparseTensorStorage<uint64_t, uint64_t, V>::newSparseTensor(
135063bdcaf9Swren romano       rank, shape, perm, sparsity, coo);
135163bdcaf9Swren romano   delete coo;
135263bdcaf9Swren romano   return tensor;
13536438783fSAart Bik }
13546438783fSAart Bik 
13556438783fSAart Bik /// Converts a sparse tensor to an external COO-flavored format.
13566438783fSAart Bik template <typename V>
135746bdacaaSwren romano static void fromMLIRSparseTensor(void *tensor, uint64_t *pRank, uint64_t *pNse,
135846bdacaaSwren romano                                  uint64_t **pShape, V **pValues,
135946bdacaaSwren romano                                  uint64_t **pIndices) {
1360736c1b66SAart Bik   assert(tensor);
13616438783fSAart Bik   auto sparseTensor =
13626438783fSAart Bik       static_cast<SparseTensorStorage<uint64_t, uint64_t, V> *>(tensor);
13636438783fSAart Bik   uint64_t rank = sparseTensor->getRank();
13646438783fSAart Bik   std::vector<uint64_t> perm(rank);
13656438783fSAart Bik   std::iota(perm.begin(), perm.end(), 0);
13666438783fSAart Bik   SparseTensorCOO<V> *coo = sparseTensor->toCOO(perm.data());
13676438783fSAart Bik 
13686438783fSAart Bik   const std::vector<Element<V>> &elements = coo->getElements();
13696438783fSAart Bik   uint64_t nse = elements.size();
13706438783fSAart Bik 
13716438783fSAart Bik   uint64_t *shape = new uint64_t[rank];
13726438783fSAart Bik   for (uint64_t i = 0; i < rank; i++)
13736438783fSAart Bik     shape[i] = coo->getSizes()[i];
13746438783fSAart Bik 
13756438783fSAart Bik   V *values = new V[nse];
13766438783fSAart Bik   uint64_t *indices = new uint64_t[rank * nse];
13776438783fSAart Bik 
13786438783fSAart Bik   for (uint64_t i = 0, base = 0; i < nse; i++) {
13796438783fSAart Bik     values[i] = elements[i].value;
13806438783fSAart Bik     for (uint64_t j = 0; j < rank; j++)
13816438783fSAart Bik       indices[base + j] = elements[i].indices[j];
13826438783fSAart Bik     base += rank;
13836438783fSAart Bik   }
13846438783fSAart Bik 
13856438783fSAart Bik   delete coo;
13866438783fSAart Bik   *pRank = rank;
13876438783fSAart Bik   *pNse = nse;
13886438783fSAart Bik   *pShape = shape;
13896438783fSAart Bik   *pValues = values;
13906438783fSAart Bik   *pIndices = indices;
1391efa15f41SAart Bik }
1392efa15f41SAart Bik 
1393be0a7e9fSMehdi Amini } // namespace
13948a91bc7bSHarrietAkot 
13958a91bc7bSHarrietAkot extern "C" {
13968a91bc7bSHarrietAkot 
13978a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
13988a91bc7bSHarrietAkot //
13998a91bc7bSHarrietAkot // Public API with methods that operate on MLIR buffers (memrefs) to interact
14008a91bc7bSHarrietAkot // with sparse tensors, which are only visible as opaque pointers externally.
14018a91bc7bSHarrietAkot // These methods should be used exclusively by MLIR compiler-generated code.
14028a91bc7bSHarrietAkot //
14038a91bc7bSHarrietAkot // Some macro magic is used to generate implementations for all required type
14048a91bc7bSHarrietAkot // combinations that can be called from MLIR compiler-generated code.
14058a91bc7bSHarrietAkot //
14068a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
14078a91bc7bSHarrietAkot 
14088a91bc7bSHarrietAkot #define CASE(p, i, v, P, I, V)                                                 \
14098a91bc7bSHarrietAkot   if (ptrTp == (p) && indTp == (i) && valTp == (v)) {                          \
141063bdcaf9Swren romano     SparseTensorCOO<V> *coo = nullptr;                                         \
1411845561ecSwren romano     if (action <= Action::kFromCOO) {                                          \
1412845561ecSwren romano       if (action == Action::kFromFile) {                                       \
14138a91bc7bSHarrietAkot         char *filename = static_cast<char *>(ptr);                             \
141463bdcaf9Swren romano         coo = openSparseTensorCOO<V>(filename, rank, shape, perm);             \
1415845561ecSwren romano       } else if (action == Action::kFromCOO) {                                 \
141663bdcaf9Swren romano         coo = static_cast<SparseTensorCOO<V> *>(ptr);                          \
14178a91bc7bSHarrietAkot       } else {                                                                 \
1418845561ecSwren romano         assert(action == Action::kEmpty);                                      \
14198a91bc7bSHarrietAkot       }                                                                        \
142063bdcaf9Swren romano       auto *tensor = SparseTensorStorage<P, I, V>::newSparseTensor(            \
142163bdcaf9Swren romano           rank, shape, perm, sparsity, coo);                                   \
142263bdcaf9Swren romano       if (action == Action::kFromFile)                                         \
142363bdcaf9Swren romano         delete coo;                                                            \
142463bdcaf9Swren romano       return tensor;                                                           \
1425bb56c2b3SMehdi Amini     }                                                                          \
1426*8cb33240Swren romano     if (action == Action::kSparseToSparse) {                                   \
1427*8cb33240Swren romano       auto *tensor = static_cast<SparseTensorStorageBase *>(ptr);              \
1428*8cb33240Swren romano       return SparseTensorStorage<P, I, V>::newSparseTensor(rank, shape, perm,  \
1429*8cb33240Swren romano                                                            sparsity, tensor);  \
1430*8cb33240Swren romano     }                                                                          \
1431bb56c2b3SMehdi Amini     if (action == Action::kEmptyCOO)                                           \
1432d83a7068Swren romano       return SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm);        \
143363bdcaf9Swren romano     coo = static_cast<SparseTensorStorage<P, I, V> *>(ptr)->toCOO(perm);       \
1434845561ecSwren romano     if (action == Action::kToIterator) {                                       \
143563bdcaf9Swren romano       coo->startIterator();                                                    \
14368a91bc7bSHarrietAkot     } else {                                                                   \
1437845561ecSwren romano       assert(action == Action::kToCOO);                                        \
14388a91bc7bSHarrietAkot     }                                                                          \
143963bdcaf9Swren romano     return coo;                                                                \
14408a91bc7bSHarrietAkot   }
14418a91bc7bSHarrietAkot 
1442845561ecSwren romano #define CASE_SECSAME(p, v, P, V) CASE(p, p, v, P, P, V)
1443845561ecSwren romano 
14448a91bc7bSHarrietAkot #define IMPL_SPARSEVALUES(NAME, TYPE, LIB)                                     \
14458a91bc7bSHarrietAkot   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor) {    \
14464f2ec7f9SAart Bik     assert(ref &&tensor);                                                      \
14478a91bc7bSHarrietAkot     std::vector<TYPE> *v;                                                      \
14488a91bc7bSHarrietAkot     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v);                   \
14498a91bc7bSHarrietAkot     ref->basePtr = ref->data = v->data();                                      \
14508a91bc7bSHarrietAkot     ref->offset = 0;                                                           \
14518a91bc7bSHarrietAkot     ref->sizes[0] = v->size();                                                 \
14528a91bc7bSHarrietAkot     ref->strides[0] = 1;                                                       \
14538a91bc7bSHarrietAkot   }
14548a91bc7bSHarrietAkot 
14558a91bc7bSHarrietAkot #define IMPL_GETOVERHEAD(NAME, TYPE, LIB)                                      \
14568a91bc7bSHarrietAkot   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor,      \
1457d2215e79SRainer Orth                            index_type d) {                                     \
14584f2ec7f9SAart Bik     assert(ref &&tensor);                                                      \
14598a91bc7bSHarrietAkot     std::vector<TYPE> *v;                                                      \
14608a91bc7bSHarrietAkot     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v, d);                \
14618a91bc7bSHarrietAkot     ref->basePtr = ref->data = v->data();                                      \
14628a91bc7bSHarrietAkot     ref->offset = 0;                                                           \
14638a91bc7bSHarrietAkot     ref->sizes[0] = v->size();                                                 \
14648a91bc7bSHarrietAkot     ref->strides[0] = 1;                                                       \
14658a91bc7bSHarrietAkot   }
14668a91bc7bSHarrietAkot 
14678a91bc7bSHarrietAkot #define IMPL_ADDELT(NAME, TYPE)                                                \
14688a91bc7bSHarrietAkot   void *_mlir_ciface_##NAME(void *tensor, TYPE value,                          \
1469d2215e79SRainer Orth                             StridedMemRefType<index_type, 1> *iref,            \
1470d2215e79SRainer Orth                             StridedMemRefType<index_type, 1> *pref) {          \
14714f2ec7f9SAart Bik     assert(tensor &&iref &&pref);                                              \
14728a91bc7bSHarrietAkot     assert(iref->strides[0] == 1 && pref->strides[0] == 1);                    \
14738a91bc7bSHarrietAkot     assert(iref->sizes[0] == pref->sizes[0]);                                  \
1474d2215e79SRainer Orth     const index_type *indx = iref->data + iref->offset;                        \
1475d2215e79SRainer Orth     const index_type *perm = pref->data + pref->offset;                        \
14768a91bc7bSHarrietAkot     uint64_t isize = iref->sizes[0];                                           \
1477d2215e79SRainer Orth     std::vector<index_type> indices(isize);                                    \
14788a91bc7bSHarrietAkot     for (uint64_t r = 0; r < isize; r++)                                       \
14798a91bc7bSHarrietAkot       indices[perm[r]] = indx[r];                                              \
14808a91bc7bSHarrietAkot     static_cast<SparseTensorCOO<TYPE> *>(tensor)->add(indices, value);         \
14818a91bc7bSHarrietAkot     return tensor;                                                             \
14828a91bc7bSHarrietAkot   }
14838a91bc7bSHarrietAkot 
14848a91bc7bSHarrietAkot #define IMPL_GETNEXT(NAME, V)                                                  \
1485d2215e79SRainer Orth   bool _mlir_ciface_##NAME(void *tensor,                                       \
1486d2215e79SRainer Orth                            StridedMemRefType<index_type, 1> *iref,             \
14878a91bc7bSHarrietAkot                            StridedMemRefType<V, 0> *vref) {                    \
14884f2ec7f9SAart Bik     assert(tensor &&iref &&vref);                                              \
14898a91bc7bSHarrietAkot     assert(iref->strides[0] == 1);                                             \
1490d2215e79SRainer Orth     index_type *indx = iref->data + iref->offset;                              \
1491c9f2beffSMehdi Amini     V *value = vref->data + vref->offset;                                      \
14928a91bc7bSHarrietAkot     const uint64_t isize = iref->sizes[0];                                     \
14938a91bc7bSHarrietAkot     auto iter = static_cast<SparseTensorCOO<V> *>(tensor);                     \
14948a91bc7bSHarrietAkot     const Element<V> *elem = iter->getNext();                                  \
149563bdcaf9Swren romano     if (elem == nullptr)                                                       \
14968a91bc7bSHarrietAkot       return false;                                                            \
14978a91bc7bSHarrietAkot     for (uint64_t r = 0; r < isize; r++)                                       \
14988a91bc7bSHarrietAkot       indx[r] = elem->indices[r];                                              \
14998a91bc7bSHarrietAkot     *value = elem->value;                                                      \
15008a91bc7bSHarrietAkot     return true;                                                               \
15018a91bc7bSHarrietAkot   }
15028a91bc7bSHarrietAkot 
1503f66e5769SAart Bik #define IMPL_LEXINSERT(NAME, V)                                                \
1504d2215e79SRainer Orth   void _mlir_ciface_##NAME(void *tensor,                                       \
1505d2215e79SRainer Orth                            StridedMemRefType<index_type, 1> *cref, V val) {    \
15064f2ec7f9SAart Bik     assert(tensor &&cref);                                                     \
1507f66e5769SAart Bik     assert(cref->strides[0] == 1);                                             \
1508d2215e79SRainer Orth     index_type *cursor = cref->data + cref->offset;                            \
1509f66e5769SAart Bik     assert(cursor);                                                            \
1510f66e5769SAart Bik     static_cast<SparseTensorStorageBase *>(tensor)->lexInsert(cursor, val);    \
1511f66e5769SAart Bik   }
1512f66e5769SAart Bik 
15134f2ec7f9SAart Bik #define IMPL_EXPINSERT(NAME, V)                                                \
15144f2ec7f9SAart Bik   void _mlir_ciface_##NAME(                                                    \
1515d2215e79SRainer Orth       void *tensor, StridedMemRefType<index_type, 1> *cref,                    \
15164f2ec7f9SAart Bik       StridedMemRefType<V, 1> *vref, StridedMemRefType<bool, 1> *fref,         \
1517d2215e79SRainer Orth       StridedMemRefType<index_type, 1> *aref, index_type count) {              \
15184f2ec7f9SAart Bik     assert(tensor &&cref &&vref &&fref &&aref);                                \
15194f2ec7f9SAart Bik     assert(cref->strides[0] == 1);                                             \
15204f2ec7f9SAart Bik     assert(vref->strides[0] == 1);                                             \
15214f2ec7f9SAart Bik     assert(fref->strides[0] == 1);                                             \
15224f2ec7f9SAart Bik     assert(aref->strides[0] == 1);                                             \
15234f2ec7f9SAart Bik     assert(vref->sizes[0] == fref->sizes[0]);                                  \
1524d2215e79SRainer Orth     index_type *cursor = cref->data + cref->offset;                            \
1525c9f2beffSMehdi Amini     V *values = vref->data + vref->offset;                                     \
15264f2ec7f9SAart Bik     bool *filled = fref->data + fref->offset;                                  \
1527d2215e79SRainer Orth     index_type *added = aref->data + aref->offset;                             \
15284f2ec7f9SAart Bik     static_cast<SparseTensorStorageBase *>(tensor)->expInsert(                 \
15294f2ec7f9SAart Bik         cursor, values, filled, added, count);                                 \
15304f2ec7f9SAart Bik   }
15314f2ec7f9SAart Bik 
1532d2215e79SRainer Orth // Assume index_type is in fact uint64_t, so that _mlir_ciface_newSparseTensor
1533bc04a470Swren romano // can safely rewrite kIndex to kU64.  We make this assertion to guarantee
1534bc04a470Swren romano // that this file cannot get out of sync with its header.
1535d2215e79SRainer Orth static_assert(std::is_same<index_type, uint64_t>::value,
1536d2215e79SRainer Orth               "Expected index_type == uint64_t");
1537bc04a470Swren romano 
15388a91bc7bSHarrietAkot /// Constructs a new sparse tensor. This is the "swiss army knife"
15398a91bc7bSHarrietAkot /// method for materializing sparse tensors into the computation.
15408a91bc7bSHarrietAkot ///
1541845561ecSwren romano /// Action:
15428a91bc7bSHarrietAkot /// kEmpty = returns empty storage to fill later
15438a91bc7bSHarrietAkot /// kFromFile = returns storage, where ptr contains filename to read
15448a91bc7bSHarrietAkot /// kFromCOO = returns storage, where ptr contains coordinate scheme to assign
15458a91bc7bSHarrietAkot /// kEmptyCOO = returns empty coordinate scheme to fill and use with kFromCOO
15468a91bc7bSHarrietAkot /// kToCOO = returns coordinate scheme from storage in ptr to use with kFromCOO
1547845561ecSwren romano /// kToIterator = returns iterator from storage in ptr (call getNext() to use)
15488a91bc7bSHarrietAkot void *
1549845561ecSwren romano _mlir_ciface_newSparseTensor(StridedMemRefType<DimLevelType, 1> *aref, // NOLINT
1550d2215e79SRainer Orth                              StridedMemRefType<index_type, 1> *sref,
1551d2215e79SRainer Orth                              StridedMemRefType<index_type, 1> *pref,
1552845561ecSwren romano                              OverheadType ptrTp, OverheadType indTp,
1553845561ecSwren romano                              PrimaryType valTp, Action action, void *ptr) {
15548a91bc7bSHarrietAkot   assert(aref && sref && pref);
15558a91bc7bSHarrietAkot   assert(aref->strides[0] == 1 && sref->strides[0] == 1 &&
15568a91bc7bSHarrietAkot          pref->strides[0] == 1);
15578a91bc7bSHarrietAkot   assert(aref->sizes[0] == sref->sizes[0] && sref->sizes[0] == pref->sizes[0]);
1558845561ecSwren romano   const DimLevelType *sparsity = aref->data + aref->offset;
1559d83a7068Swren romano   const index_type *shape = sref->data + sref->offset;
1560d2215e79SRainer Orth   const index_type *perm = pref->data + pref->offset;
15618a91bc7bSHarrietAkot   uint64_t rank = aref->sizes[0];
15628a91bc7bSHarrietAkot 
1563bc04a470Swren romano   // Rewrite kIndex to kU64, to avoid introducing a bunch of new cases.
1564bc04a470Swren romano   // This is safe because of the static_assert above.
1565bc04a470Swren romano   if (ptrTp == OverheadType::kIndex)
1566bc04a470Swren romano     ptrTp = OverheadType::kU64;
1567bc04a470Swren romano   if (indTp == OverheadType::kIndex)
1568bc04a470Swren romano     indTp = OverheadType::kU64;
1569bc04a470Swren romano 
15708a91bc7bSHarrietAkot   // Double matrices with all combinations of overhead storage.
1571845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF64, uint64_t,
1572845561ecSwren romano        uint64_t, double);
1573845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF64, uint64_t,
1574845561ecSwren romano        uint32_t, double);
1575845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF64, uint64_t,
1576845561ecSwren romano        uint16_t, double);
1577845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF64, uint64_t,
1578845561ecSwren romano        uint8_t, double);
1579845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF64, uint32_t,
1580845561ecSwren romano        uint64_t, double);
1581845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF64, uint32_t,
1582845561ecSwren romano        uint32_t, double);
1583845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF64, uint32_t,
1584845561ecSwren romano        uint16_t, double);
1585845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF64, uint32_t,
1586845561ecSwren romano        uint8_t, double);
1587845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF64, uint16_t,
1588845561ecSwren romano        uint64_t, double);
1589845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF64, uint16_t,
1590845561ecSwren romano        uint32_t, double);
1591845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF64, uint16_t,
1592845561ecSwren romano        uint16_t, double);
1593845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF64, uint16_t,
1594845561ecSwren romano        uint8_t, double);
1595845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF64, uint8_t,
1596845561ecSwren romano        uint64_t, double);
1597845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF64, uint8_t,
1598845561ecSwren romano        uint32_t, double);
1599845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF64, uint8_t,
1600845561ecSwren romano        uint16_t, double);
1601845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF64, uint8_t,
1602845561ecSwren romano        uint8_t, double);
16038a91bc7bSHarrietAkot 
16048a91bc7bSHarrietAkot   // Float matrices with all combinations of overhead storage.
1605845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF32, uint64_t,
1606845561ecSwren romano        uint64_t, float);
1607845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF32, uint64_t,
1608845561ecSwren romano        uint32_t, float);
1609845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF32, uint64_t,
1610845561ecSwren romano        uint16_t, float);
1611845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF32, uint64_t,
1612845561ecSwren romano        uint8_t, float);
1613845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF32, uint32_t,
1614845561ecSwren romano        uint64_t, float);
1615845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF32, uint32_t,
1616845561ecSwren romano        uint32_t, float);
1617845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF32, uint32_t,
1618845561ecSwren romano        uint16_t, float);
1619845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF32, uint32_t,
1620845561ecSwren romano        uint8_t, float);
1621845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF32, uint16_t,
1622845561ecSwren romano        uint64_t, float);
1623845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF32, uint16_t,
1624845561ecSwren romano        uint32_t, float);
1625845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF32, uint16_t,
1626845561ecSwren romano        uint16_t, float);
1627845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF32, uint16_t,
1628845561ecSwren romano        uint8_t, float);
1629845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF32, uint8_t,
1630845561ecSwren romano        uint64_t, float);
1631845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF32, uint8_t,
1632845561ecSwren romano        uint32_t, float);
1633845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF32, uint8_t,
1634845561ecSwren romano        uint16_t, float);
1635845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF32, uint8_t,
1636845561ecSwren romano        uint8_t, float);
16378a91bc7bSHarrietAkot 
1638845561ecSwren romano   // Integral matrices with both overheads of the same type.
1639845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI64, uint64_t, int64_t);
1640845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI32, uint64_t, int32_t);
1641845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI16, uint64_t, int16_t);
1642845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI8, uint64_t, int8_t);
1643845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI32, uint32_t, int32_t);
1644845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI16, uint32_t, int16_t);
1645845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI8, uint32_t, int8_t);
1646845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI32, uint16_t, int32_t);
1647845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI16, uint16_t, int16_t);
1648845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI8, uint16_t, int8_t);
1649845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI32, uint8_t, int32_t);
1650845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI16, uint8_t, int16_t);
1651845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI8, uint8_t, int8_t);
16528a91bc7bSHarrietAkot 
1653736c1b66SAart Bik   // Complex matrices with wide overhead.
1654736c1b66SAart Bik   CASE_SECSAME(OverheadType::kU64, PrimaryType::kC64, uint64_t, complex64);
1655736c1b66SAart Bik   CASE_SECSAME(OverheadType::kU64, PrimaryType::kC32, uint64_t, complex32);
1656736c1b66SAart Bik 
16578a91bc7bSHarrietAkot   // Unsupported case (add above if needed).
16588a91bc7bSHarrietAkot   fputs("unsupported combination of types\n", stderr);
16598a91bc7bSHarrietAkot   exit(1);
16608a91bc7bSHarrietAkot }
16618a91bc7bSHarrietAkot 
16628a91bc7bSHarrietAkot /// Methods that provide direct access to pointers.
1663d2215e79SRainer Orth IMPL_GETOVERHEAD(sparsePointers, index_type, getPointers)
16648a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers64, uint64_t, getPointers)
16658a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers32, uint32_t, getPointers)
16668a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers16, uint16_t, getPointers)
16678a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers8, uint8_t, getPointers)
16688a91bc7bSHarrietAkot 
16698a91bc7bSHarrietAkot /// Methods that provide direct access to indices.
1670d2215e79SRainer Orth IMPL_GETOVERHEAD(sparseIndices, index_type, getIndices)
16718a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices64, uint64_t, getIndices)
16728a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices32, uint32_t, getIndices)
16738a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices16, uint16_t, getIndices)
16748a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices8, uint8_t, getIndices)
16758a91bc7bSHarrietAkot 
16768a91bc7bSHarrietAkot /// Methods that provide direct access to values.
16778a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesF64, double, getValues)
16788a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesF32, float, getValues)
16798a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI64, int64_t, getValues)
16808a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI32, int32_t, getValues)
16818a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI16, int16_t, getValues)
16828a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI8, int8_t, getValues)
1683736c1b66SAart Bik IMPL_SPARSEVALUES(sparseValuesC64, complex64, getValues)
1684736c1b66SAart Bik IMPL_SPARSEVALUES(sparseValuesC32, complex32, getValues)
16858a91bc7bSHarrietAkot 
16868a91bc7bSHarrietAkot /// Helper to add value to coordinate scheme, one per value type.
16878a91bc7bSHarrietAkot IMPL_ADDELT(addEltF64, double)
16888a91bc7bSHarrietAkot IMPL_ADDELT(addEltF32, float)
16898a91bc7bSHarrietAkot IMPL_ADDELT(addEltI64, int64_t)
16908a91bc7bSHarrietAkot IMPL_ADDELT(addEltI32, int32_t)
16918a91bc7bSHarrietAkot IMPL_ADDELT(addEltI16, int16_t)
16928a91bc7bSHarrietAkot IMPL_ADDELT(addEltI8, int8_t)
1693736c1b66SAart Bik IMPL_ADDELT(addEltC64, complex64)
1694736c1b66SAart Bik IMPL_ADDELT(addEltC32ABI, complex32)
1695736c1b66SAart Bik // Make prototype explicit to accept the !llvm.struct<(f32, f32)> without
1696736c1b66SAart Bik // any padding (which seem to happen for complex32 when passed as scalar;
1697736c1b66SAart Bik // all other cases, e.g. pointer to array, work as expected).
1698736c1b66SAart Bik // TODO: cleaner way to avoid ABI padding problem?
1699736c1b66SAart Bik void *_mlir_ciface_addEltC32(void *tensor, float r, float i,
1700736c1b66SAart Bik                              StridedMemRefType<index_type, 1> *iref,
1701736c1b66SAart Bik                              StridedMemRefType<index_type, 1> *pref) {
1702736c1b66SAart Bik   return _mlir_ciface_addEltC32ABI(tensor, complex32(r, i), iref, pref);
1703736c1b66SAart Bik }
17048a91bc7bSHarrietAkot 
17058a91bc7bSHarrietAkot /// Helper to enumerate elements of coordinate scheme, one per value type.
17068a91bc7bSHarrietAkot IMPL_GETNEXT(getNextF64, double)
17078a91bc7bSHarrietAkot IMPL_GETNEXT(getNextF32, float)
17088a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI64, int64_t)
17098a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI32, int32_t)
17108a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI16, int16_t)
17118a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI8, int8_t)
1712736c1b66SAart Bik IMPL_GETNEXT(getNextC64, complex64)
1713736c1b66SAart Bik IMPL_GETNEXT(getNextC32, complex32)
17148a91bc7bSHarrietAkot 
17156438783fSAart Bik /// Insert elements in lexicographical index order, one per value type.
1716f66e5769SAart Bik IMPL_LEXINSERT(lexInsertF64, double)
1717f66e5769SAart Bik IMPL_LEXINSERT(lexInsertF32, float)
1718f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI64, int64_t)
1719f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI32, int32_t)
1720f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI16, int16_t)
1721f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI8, int8_t)
1722736c1b66SAart Bik IMPL_LEXINSERT(lexInsertC64, complex64)
1723736c1b66SAart Bik IMPL_LEXINSERT(lexInsertC32ABI, complex32)
1724736c1b66SAart Bik // Make prototype explicit to accept the !llvm.struct<(f32, f32)> without
1725736c1b66SAart Bik // any padding (which seem to happen for complex32 when passed as scalar;
1726736c1b66SAart Bik // all other cases, e.g. pointer to array, work as expected).
1727736c1b66SAart Bik // TODO: cleaner way to avoid ABI padding problem?
1728736c1b66SAart Bik void _mlir_ciface_lexInsertC32(void *tensor,
1729736c1b66SAart Bik                                StridedMemRefType<index_type, 1> *cref, float r,
1730736c1b66SAart Bik                                float i) {
1731736c1b66SAart Bik   _mlir_ciface_lexInsertC32ABI(tensor, cref, complex32(r, i));
1732736c1b66SAart Bik }
1733f66e5769SAart Bik 
17346438783fSAart Bik /// Insert using expansion, one per value type.
17354f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertF64, double)
17364f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertF32, float)
17374f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI64, int64_t)
17384f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI32, int32_t)
17394f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI16, int16_t)
17404f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI8, int8_t)
1741736c1b66SAart Bik IMPL_EXPINSERT(expInsertC64, complex64)
1742736c1b66SAart Bik IMPL_EXPINSERT(expInsertC32, complex32)
17434f2ec7f9SAart Bik 
17448a91bc7bSHarrietAkot #undef CASE
17458a91bc7bSHarrietAkot #undef IMPL_SPARSEVALUES
17468a91bc7bSHarrietAkot #undef IMPL_GETOVERHEAD
17478a91bc7bSHarrietAkot #undef IMPL_ADDELT
17488a91bc7bSHarrietAkot #undef IMPL_GETNEXT
17494f2ec7f9SAart Bik #undef IMPL_LEXINSERT
17504f2ec7f9SAart Bik #undef IMPL_EXPINSERT
17516438783fSAart Bik 
17526438783fSAart Bik /// Output a sparse tensor, one per value type.
17536438783fSAart Bik void outSparseTensorF64(void *tensor, void *dest, bool sort) {
17546438783fSAart Bik   return outSparseTensor<double>(tensor, dest, sort);
17556438783fSAart Bik }
17566438783fSAart Bik void outSparseTensorF32(void *tensor, void *dest, bool sort) {
17576438783fSAart Bik   return outSparseTensor<float>(tensor, dest, sort);
17586438783fSAart Bik }
17596438783fSAart Bik void outSparseTensorI64(void *tensor, void *dest, bool sort) {
17606438783fSAart Bik   return outSparseTensor<int64_t>(tensor, dest, sort);
17616438783fSAart Bik }
17626438783fSAart Bik void outSparseTensorI32(void *tensor, void *dest, bool sort) {
17636438783fSAart Bik   return outSparseTensor<int32_t>(tensor, dest, sort);
17646438783fSAart Bik }
17656438783fSAart Bik void outSparseTensorI16(void *tensor, void *dest, bool sort) {
17666438783fSAart Bik   return outSparseTensor<int16_t>(tensor, dest, sort);
17676438783fSAart Bik }
17686438783fSAart Bik void outSparseTensorI8(void *tensor, void *dest, bool sort) {
17696438783fSAart Bik   return outSparseTensor<int8_t>(tensor, dest, sort);
17706438783fSAart Bik }
1771736c1b66SAart Bik void outSparseTensorC64(void *tensor, void *dest, bool sort) {
1772736c1b66SAart Bik   return outSparseTensor<complex64>(tensor, dest, sort);
1773736c1b66SAart Bik }
1774736c1b66SAart Bik void outSparseTensorC32(void *tensor, void *dest, bool sort) {
1775736c1b66SAart Bik   return outSparseTensor<complex32>(tensor, dest, sort);
1776736c1b66SAart Bik }
17778a91bc7bSHarrietAkot 
17788a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
17798a91bc7bSHarrietAkot //
17808a91bc7bSHarrietAkot // Public API with methods that accept C-style data structures to interact
17818a91bc7bSHarrietAkot // with sparse tensors, which are only visible as opaque pointers externally.
17828a91bc7bSHarrietAkot // These methods can be used both by MLIR compiler-generated code as well as by
17838a91bc7bSHarrietAkot // an external runtime that wants to interact with MLIR compiler-generated code.
17848a91bc7bSHarrietAkot //
17858a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
17868a91bc7bSHarrietAkot 
17878a91bc7bSHarrietAkot /// Helper method to read a sparse tensor filename from the environment,
17888a91bc7bSHarrietAkot /// defined with the naming convention ${TENSOR0}, ${TENSOR1}, etc.
1789d2215e79SRainer Orth char *getTensorFilename(index_type id) {
17908a91bc7bSHarrietAkot   char var[80];
17918a91bc7bSHarrietAkot   sprintf(var, "TENSOR%" PRIu64, id);
17928a91bc7bSHarrietAkot   char *env = getenv(var);
17933734c078Swren romano   if (!env) {
17943734c078Swren romano     fprintf(stderr, "Environment variable %s is not set\n", var);
17953734c078Swren romano     exit(1);
17963734c078Swren romano   }
17978a91bc7bSHarrietAkot   return env;
17988a91bc7bSHarrietAkot }
17998a91bc7bSHarrietAkot 
18008a91bc7bSHarrietAkot /// Returns size of sparse tensor in given dimension.
1801d2215e79SRainer Orth index_type sparseDimSize(void *tensor, index_type d) {
18028a91bc7bSHarrietAkot   return static_cast<SparseTensorStorageBase *>(tensor)->getDimSize(d);
18038a91bc7bSHarrietAkot }
18048a91bc7bSHarrietAkot 
1805f66e5769SAart Bik /// Finalizes lexicographic insertions.
1806f66e5769SAart Bik void endInsert(void *tensor) {
1807f66e5769SAart Bik   return static_cast<SparseTensorStorageBase *>(tensor)->endInsert();
1808f66e5769SAart Bik }
1809f66e5769SAart Bik 
18108a91bc7bSHarrietAkot /// Releases sparse tensor storage.
18118a91bc7bSHarrietAkot void delSparseTensor(void *tensor) {
18128a91bc7bSHarrietAkot   delete static_cast<SparseTensorStorageBase *>(tensor);
18138a91bc7bSHarrietAkot }
18148a91bc7bSHarrietAkot 
181563bdcaf9Swren romano /// Releases sparse tensor coordinate scheme.
181663bdcaf9Swren romano #define IMPL_DELCOO(VNAME, V)                                                  \
181763bdcaf9Swren romano   void delSparseTensorCOO##VNAME(void *coo) {                                  \
181863bdcaf9Swren romano     delete static_cast<SparseTensorCOO<V> *>(coo);                             \
181963bdcaf9Swren romano   }
182063bdcaf9Swren romano IMPL_DELCOO(F64, double)
182163bdcaf9Swren romano IMPL_DELCOO(F32, float)
182263bdcaf9Swren romano IMPL_DELCOO(I64, int64_t)
182363bdcaf9Swren romano IMPL_DELCOO(I32, int32_t)
182463bdcaf9Swren romano IMPL_DELCOO(I16, int16_t)
182563bdcaf9Swren romano IMPL_DELCOO(I8, int8_t)
1826736c1b66SAart Bik IMPL_DELCOO(C64, complex64)
1827736c1b66SAart Bik IMPL_DELCOO(C32, complex32)
182863bdcaf9Swren romano #undef IMPL_DELCOO
182963bdcaf9Swren romano 
18308a91bc7bSHarrietAkot /// Initializes sparse tensor from a COO-flavored format expressed using C-style
18318a91bc7bSHarrietAkot /// data structures. The expected parameters are:
18328a91bc7bSHarrietAkot ///
18338a91bc7bSHarrietAkot ///   rank:    rank of tensor
18348a91bc7bSHarrietAkot ///   nse:     number of specified elements (usually the nonzeros)
18358a91bc7bSHarrietAkot ///   shape:   array with dimension size for each rank
18368a91bc7bSHarrietAkot ///   values:  a "nse" array with values for all specified elements
18378a91bc7bSHarrietAkot ///   indices: a flat "nse x rank" array with indices for all specified elements
183820eaa88fSBixia Zheng ///   perm:    the permutation of the dimensions in the storage
183920eaa88fSBixia Zheng ///   sparse:  the sparsity for the dimensions
18408a91bc7bSHarrietAkot ///
18418a91bc7bSHarrietAkot /// For example, the sparse matrix
18428a91bc7bSHarrietAkot ///     | 1.0 0.0 0.0 |
18438a91bc7bSHarrietAkot ///     | 0.0 5.0 3.0 |
18448a91bc7bSHarrietAkot /// can be passed as
18458a91bc7bSHarrietAkot ///      rank    = 2
18468a91bc7bSHarrietAkot ///      nse     = 3
18478a91bc7bSHarrietAkot ///      shape   = [2, 3]
18488a91bc7bSHarrietAkot ///      values  = [1.0, 5.0, 3.0]
18498a91bc7bSHarrietAkot ///      indices = [ 0, 0,  1, 1,  1, 2]
18508a91bc7bSHarrietAkot //
185120eaa88fSBixia Zheng // TODO: generalize beyond 64-bit indices.
18528a91bc7bSHarrietAkot //
18536438783fSAart Bik void *convertToMLIRSparseTensorF64(uint64_t rank, uint64_t nse, uint64_t *shape,
185420eaa88fSBixia Zheng                                    double *values, uint64_t *indices,
185520eaa88fSBixia Zheng                                    uint64_t *perm, uint8_t *sparse) {
185620eaa88fSBixia Zheng   return toMLIRSparseTensor<double>(rank, nse, shape, values, indices, perm,
185720eaa88fSBixia Zheng                                     sparse);
18588a91bc7bSHarrietAkot }
18596438783fSAart Bik void *convertToMLIRSparseTensorF32(uint64_t rank, uint64_t nse, uint64_t *shape,
186020eaa88fSBixia Zheng                                    float *values, uint64_t *indices,
186120eaa88fSBixia Zheng                                    uint64_t *perm, uint8_t *sparse) {
186220eaa88fSBixia Zheng   return toMLIRSparseTensor<float>(rank, nse, shape, values, indices, perm,
186320eaa88fSBixia Zheng                                    sparse);
18648a91bc7bSHarrietAkot }
18651abcdc67SAart Bik void *convertToMLIRSparseTensorI64(uint64_t rank, uint64_t nse, uint64_t *shape,
18661abcdc67SAart Bik                                    int64_t *values, uint64_t *indices,
18671abcdc67SAart Bik                                    uint64_t *perm, uint8_t *sparse) {
18681abcdc67SAart Bik   return toMLIRSparseTensor<int64_t>(rank, nse, shape, values, indices, perm,
18691abcdc67SAart Bik                                      sparse);
18701abcdc67SAart Bik }
18711abcdc67SAart Bik void *convertToMLIRSparseTensorI32(uint64_t rank, uint64_t nse, uint64_t *shape,
18721abcdc67SAart Bik                                    int32_t *values, uint64_t *indices,
18731abcdc67SAart Bik                                    uint64_t *perm, uint8_t *sparse) {
18741abcdc67SAart Bik   return toMLIRSparseTensor<int32_t>(rank, nse, shape, values, indices, perm,
18751abcdc67SAart Bik                                      sparse);
18761abcdc67SAart Bik }
18771abcdc67SAart Bik void *convertToMLIRSparseTensorI16(uint64_t rank, uint64_t nse, uint64_t *shape,
18781abcdc67SAart Bik                                    int16_t *values, uint64_t *indices,
18791abcdc67SAart Bik                                    uint64_t *perm, uint8_t *sparse) {
18801abcdc67SAart Bik   return toMLIRSparseTensor<int16_t>(rank, nse, shape, values, indices, perm,
18811abcdc67SAart Bik                                      sparse);
18821abcdc67SAart Bik }
18831abcdc67SAart Bik void *convertToMLIRSparseTensorI8(uint64_t rank, uint64_t nse, uint64_t *shape,
18841abcdc67SAart Bik                                   int8_t *values, uint64_t *indices,
18851abcdc67SAart Bik                                   uint64_t *perm, uint8_t *sparse) {
18861abcdc67SAart Bik   return toMLIRSparseTensor<int8_t>(rank, nse, shape, values, indices, perm,
18871abcdc67SAart Bik                                     sparse);
18881abcdc67SAart Bik }
1889736c1b66SAart Bik void *convertToMLIRSparseTensorC64(uint64_t rank, uint64_t nse, uint64_t *shape,
1890736c1b66SAart Bik                                    complex64 *values, uint64_t *indices,
1891736c1b66SAart Bik                                    uint64_t *perm, uint8_t *sparse) {
1892736c1b66SAart Bik   return toMLIRSparseTensor<complex64>(rank, nse, shape, values, indices, perm,
1893736c1b66SAart Bik                                        sparse);
1894736c1b66SAart Bik }
1895736c1b66SAart Bik void *convertToMLIRSparseTensorC32(uint64_t rank, uint64_t nse, uint64_t *shape,
1896736c1b66SAart Bik                                    complex32 *values, uint64_t *indices,
1897736c1b66SAart Bik                                    uint64_t *perm, uint8_t *sparse) {
1898736c1b66SAart Bik   return toMLIRSparseTensor<complex32>(rank, nse, shape, values, indices, perm,
1899736c1b66SAart Bik                                        sparse);
1900736c1b66SAart Bik }
19018a91bc7bSHarrietAkot 
19022f49e6b0SBixia Zheng /// Converts a sparse tensor to COO-flavored format expressed using C-style
19032f49e6b0SBixia Zheng /// data structures. The expected output parameters are pointers for these
19042f49e6b0SBixia Zheng /// values:
19052f49e6b0SBixia Zheng ///
19062f49e6b0SBixia Zheng ///   rank:    rank of tensor
19072f49e6b0SBixia Zheng ///   nse:     number of specified elements (usually the nonzeros)
19082f49e6b0SBixia Zheng ///   shape:   array with dimension size for each rank
19092f49e6b0SBixia Zheng ///   values:  a "nse" array with values for all specified elements
19102f49e6b0SBixia Zheng ///   indices: a flat "nse x rank" array with indices for all specified elements
19112f49e6b0SBixia Zheng ///
19122f49e6b0SBixia Zheng /// The input is a pointer to SparseTensorStorage<P, I, V>, typically returned
19132f49e6b0SBixia Zheng /// from convertToMLIRSparseTensor.
19142f49e6b0SBixia Zheng ///
19152f49e6b0SBixia Zheng //  TODO: Currently, values are copied from SparseTensorStorage to
19162f49e6b0SBixia Zheng //  SparseTensorCOO, then to the output. We may want to reduce the number of
19172f49e6b0SBixia Zheng //  copies.
19182f49e6b0SBixia Zheng //
19196438783fSAart Bik // TODO: generalize beyond 64-bit indices, no dim ordering, all dimensions
19206438783fSAart Bik // compressed
19212f49e6b0SBixia Zheng //
19226438783fSAart Bik void convertFromMLIRSparseTensorF64(void *tensor, uint64_t *pRank,
19236438783fSAart Bik                                     uint64_t *pNse, uint64_t **pShape,
19246438783fSAart Bik                                     double **pValues, uint64_t **pIndices) {
19256438783fSAart Bik   fromMLIRSparseTensor<double>(tensor, pRank, pNse, pShape, pValues, pIndices);
19262f49e6b0SBixia Zheng }
19276438783fSAart Bik void convertFromMLIRSparseTensorF32(void *tensor, uint64_t *pRank,
19286438783fSAart Bik                                     uint64_t *pNse, uint64_t **pShape,
19296438783fSAart Bik                                     float **pValues, uint64_t **pIndices) {
19306438783fSAart Bik   fromMLIRSparseTensor<float>(tensor, pRank, pNse, pShape, pValues, pIndices);
19312f49e6b0SBixia Zheng }
19321abcdc67SAart Bik void convertFromMLIRSparseTensorI64(void *tensor, uint64_t *pRank,
19331abcdc67SAart Bik                                     uint64_t *pNse, uint64_t **pShape,
19341abcdc67SAart Bik                                     int64_t **pValues, uint64_t **pIndices) {
19351abcdc67SAart Bik   fromMLIRSparseTensor<int64_t>(tensor, pRank, pNse, pShape, pValues, pIndices);
19361abcdc67SAart Bik }
19371abcdc67SAart Bik void convertFromMLIRSparseTensorI32(void *tensor, uint64_t *pRank,
19381abcdc67SAart Bik                                     uint64_t *pNse, uint64_t **pShape,
19391abcdc67SAart Bik                                     int32_t **pValues, uint64_t **pIndices) {
19401abcdc67SAart Bik   fromMLIRSparseTensor<int32_t>(tensor, pRank, pNse, pShape, pValues, pIndices);
19411abcdc67SAart Bik }
19421abcdc67SAart Bik void convertFromMLIRSparseTensorI16(void *tensor, uint64_t *pRank,
19431abcdc67SAart Bik                                     uint64_t *pNse, uint64_t **pShape,
19441abcdc67SAart Bik                                     int16_t **pValues, uint64_t **pIndices) {
19451abcdc67SAart Bik   fromMLIRSparseTensor<int16_t>(tensor, pRank, pNse, pShape, pValues, pIndices);
19461abcdc67SAart Bik }
19471abcdc67SAart Bik void convertFromMLIRSparseTensorI8(void *tensor, uint64_t *pRank,
19481abcdc67SAart Bik                                    uint64_t *pNse, uint64_t **pShape,
19491abcdc67SAart Bik                                    int8_t **pValues, uint64_t **pIndices) {
19501abcdc67SAart Bik   fromMLIRSparseTensor<int8_t>(tensor, pRank, pNse, pShape, pValues, pIndices);
19511abcdc67SAart Bik }
1952736c1b66SAart Bik void convertFromMLIRSparseTensorC64(void *tensor, uint64_t *pRank,
1953736c1b66SAart Bik                                     uint64_t *pNse, uint64_t **pShape,
1954736c1b66SAart Bik                                     complex64 **pValues, uint64_t **pIndices) {
1955736c1b66SAart Bik   fromMLIRSparseTensor<complex64>(tensor, pRank, pNse, pShape, pValues,
1956736c1b66SAart Bik                                   pIndices);
1957736c1b66SAart Bik }
1958736c1b66SAart Bik void convertFromMLIRSparseTensorC32(void *tensor, uint64_t *pRank,
1959736c1b66SAart Bik                                     uint64_t *pNse, uint64_t **pShape,
1960736c1b66SAart Bik                                     complex32 **pValues, uint64_t **pIndices) {
1961736c1b66SAart Bik   fromMLIRSparseTensor<complex32>(tensor, pRank, pNse, pShape, pValues,
1962736c1b66SAart Bik                                   pIndices);
1963736c1b66SAart Bik }
1964efa15f41SAart Bik 
19658a91bc7bSHarrietAkot } // extern "C"
19668a91bc7bSHarrietAkot 
19678a91bc7bSHarrietAkot #endif // MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
1968