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>
248a91bc7bSHarrietAkot #include <cctype>
258a91bc7bSHarrietAkot #include <cinttypes>
268a91bc7bSHarrietAkot #include <cstdio>
278a91bc7bSHarrietAkot #include <cstdlib>
288a91bc7bSHarrietAkot #include <cstring>
29efa15f41SAart Bik #include <fstream>
30efa15f41SAart Bik #include <iostream>
314d0a18d0Swren romano #include <limits>
328a91bc7bSHarrietAkot #include <numeric>
338a91bc7bSHarrietAkot #include <vector>
348a91bc7bSHarrietAkot 
358a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
368a91bc7bSHarrietAkot //
378a91bc7bSHarrietAkot // Internal support for storing and reading sparse tensors.
388a91bc7bSHarrietAkot //
398a91bc7bSHarrietAkot // The following memory-resident sparse storage schemes are supported:
408a91bc7bSHarrietAkot //
418a91bc7bSHarrietAkot // (a) A coordinate scheme for temporarily storing and lexicographically
428a91bc7bSHarrietAkot //     sorting a sparse tensor by index (SparseTensorCOO).
438a91bc7bSHarrietAkot //
448a91bc7bSHarrietAkot // (b) A "one-size-fits-all" sparse tensor storage scheme defined by
458a91bc7bSHarrietAkot //     per-dimension sparse/dense annnotations together with a dimension
468a91bc7bSHarrietAkot //     ordering used by MLIR compiler-generated code (SparseTensorStorage).
478a91bc7bSHarrietAkot //
488a91bc7bSHarrietAkot // The following external formats are supported:
498a91bc7bSHarrietAkot //
508a91bc7bSHarrietAkot // (1) Matrix Market Exchange (MME): *.mtx
518a91bc7bSHarrietAkot //     https://math.nist.gov/MatrixMarket/formats.html
528a91bc7bSHarrietAkot //
538a91bc7bSHarrietAkot // (2) Formidable Repository of Open Sparse Tensors and Tools (FROSTT): *.tns
548a91bc7bSHarrietAkot //     http://frostt.io/tensors/file-formats.html
558a91bc7bSHarrietAkot //
568a91bc7bSHarrietAkot // Two public APIs are supported:
578a91bc7bSHarrietAkot //
588a91bc7bSHarrietAkot // (I) Methods operating on MLIR buffers (memrefs) to interact with sparse
598a91bc7bSHarrietAkot //     tensors. These methods should be used exclusively by MLIR
608a91bc7bSHarrietAkot //     compiler-generated code.
618a91bc7bSHarrietAkot //
628a91bc7bSHarrietAkot // (II) Methods that accept C-style data structures to interact with sparse
638a91bc7bSHarrietAkot //      tensors. These methods can be used by any external runtime that wants
648a91bc7bSHarrietAkot //      to interact with MLIR compiler-generated code.
658a91bc7bSHarrietAkot //
668a91bc7bSHarrietAkot // In both cases (I) and (II), the SparseTensorStorage format is externally
678a91bc7bSHarrietAkot // only visible as an opaque pointer.
688a91bc7bSHarrietAkot //
698a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
708a91bc7bSHarrietAkot 
718a91bc7bSHarrietAkot namespace {
728a91bc7bSHarrietAkot 
7303fe15ceSAart Bik static constexpr int kColWidth = 1025;
7403fe15ceSAart Bik 
7572ec2f76Swren romano /// A version of `operator*` on `uint64_t` which checks for overflows.
7672ec2f76Swren romano static inline uint64_t checkedMul(uint64_t lhs, uint64_t rhs) {
7772ec2f76Swren romano   assert((lhs == 0 || rhs <= std::numeric_limits<uint64_t>::max() / lhs) &&
7872ec2f76Swren romano          "Integer overflow");
7972ec2f76Swren romano   return lhs * rhs;
8072ec2f76Swren romano }
8172ec2f76Swren romano 
828a91bc7bSHarrietAkot /// A sparse tensor element in coordinate scheme (value and indices).
838a91bc7bSHarrietAkot /// For example, a rank-1 vector element would look like
848a91bc7bSHarrietAkot ///   ({i}, a[i])
858a91bc7bSHarrietAkot /// and a rank-5 tensor element like
868a91bc7bSHarrietAkot ///   ({i,j,k,l,m}, a[i,j,k,l,m])
878a91bc7bSHarrietAkot template <typename V>
888a91bc7bSHarrietAkot struct Element {
898a91bc7bSHarrietAkot   Element(const std::vector<uint64_t> &ind, V val) : indices(ind), value(val){};
908a91bc7bSHarrietAkot   std::vector<uint64_t> indices;
918a91bc7bSHarrietAkot   V value;
92110295ebSwren romano   /// Returns true if indices of e1 < indices of e2.
93110295ebSwren romano   static bool lexOrder(const Element<V> &e1, const Element<V> &e2) {
94110295ebSwren romano     uint64_t rank = e1.indices.size();
95110295ebSwren romano     assert(rank == e2.indices.size());
96110295ebSwren romano     for (uint64_t r = 0; r < rank; r++) {
97110295ebSwren romano       if (e1.indices[r] == e2.indices[r])
98110295ebSwren romano         continue;
99110295ebSwren romano       return e1.indices[r] < e2.indices[r];
100110295ebSwren romano     }
101110295ebSwren romano     return false;
102110295ebSwren romano   }
1038a91bc7bSHarrietAkot };
1048a91bc7bSHarrietAkot 
1058a91bc7bSHarrietAkot /// A memory-resident sparse tensor in coordinate scheme (collection of
1068a91bc7bSHarrietAkot /// elements). This data structure is used to read a sparse tensor from
1078a91bc7bSHarrietAkot /// any external format into memory and sort the elements lexicographically
1088a91bc7bSHarrietAkot /// by indices before passing it back to the client (most packed storage
1098a91bc7bSHarrietAkot /// formats require the elements to appear in lexicographic index order).
1108a91bc7bSHarrietAkot template <typename V>
1118a91bc7bSHarrietAkot struct SparseTensorCOO {
1128a91bc7bSHarrietAkot public:
1138a91bc7bSHarrietAkot   SparseTensorCOO(const std::vector<uint64_t> &szs, uint64_t capacity)
114*db6796dfSMehdi Amini       : sizes(szs) {
1158a91bc7bSHarrietAkot     if (capacity)
1168a91bc7bSHarrietAkot       elements.reserve(capacity);
1178a91bc7bSHarrietAkot   }
1188a91bc7bSHarrietAkot   /// Adds element as indices and value.
1198a91bc7bSHarrietAkot   void add(const std::vector<uint64_t> &ind, V val) {
1208a91bc7bSHarrietAkot     assert(!iteratorLocked && "Attempt to add() after startIterator()");
1218a91bc7bSHarrietAkot     uint64_t rank = getRank();
1228a91bc7bSHarrietAkot     assert(rank == ind.size());
1238a91bc7bSHarrietAkot     for (uint64_t r = 0; r < rank; r++)
1248a91bc7bSHarrietAkot       assert(ind[r] < sizes[r]); // within bounds
1258a91bc7bSHarrietAkot     elements.emplace_back(ind, val);
1268a91bc7bSHarrietAkot   }
1278a91bc7bSHarrietAkot   /// Sorts elements lexicographically by index.
1288a91bc7bSHarrietAkot   void sort() {
1298a91bc7bSHarrietAkot     assert(!iteratorLocked && "Attempt to sort() after startIterator()");
130cf358253Swren romano     // TODO: we may want to cache an `isSorted` bit, to avoid
131cf358253Swren romano     // unnecessary/redundant sorting.
132110295ebSwren romano     std::sort(elements.begin(), elements.end(), Element<V>::lexOrder);
1338a91bc7bSHarrietAkot   }
1348a91bc7bSHarrietAkot   /// Returns rank.
1358a91bc7bSHarrietAkot   uint64_t getRank() const { return sizes.size(); }
1368a91bc7bSHarrietAkot   /// Getter for sizes array.
1378a91bc7bSHarrietAkot   const std::vector<uint64_t> &getSizes() const { return sizes; }
1388a91bc7bSHarrietAkot   /// Getter for elements array.
1398a91bc7bSHarrietAkot   const std::vector<Element<V>> &getElements() const { return elements; }
1408a91bc7bSHarrietAkot 
1418a91bc7bSHarrietAkot   /// Switch into iterator mode.
1428a91bc7bSHarrietAkot   void startIterator() {
1438a91bc7bSHarrietAkot     iteratorLocked = true;
1448a91bc7bSHarrietAkot     iteratorPos = 0;
1458a91bc7bSHarrietAkot   }
1468a91bc7bSHarrietAkot   /// Get the next element.
1478a91bc7bSHarrietAkot   const Element<V> *getNext() {
1488a91bc7bSHarrietAkot     assert(iteratorLocked && "Attempt to getNext() before startIterator()");
1498a91bc7bSHarrietAkot     if (iteratorPos < elements.size())
1508a91bc7bSHarrietAkot       return &(elements[iteratorPos++]);
1518a91bc7bSHarrietAkot     iteratorLocked = false;
1528a91bc7bSHarrietAkot     return nullptr;
1538a91bc7bSHarrietAkot   }
1548a91bc7bSHarrietAkot 
1558a91bc7bSHarrietAkot   /// Factory method. Permutes the original dimensions according to
1568a91bc7bSHarrietAkot   /// the given ordering and expects subsequent add() calls to honor
1578a91bc7bSHarrietAkot   /// that same ordering for the given indices. The result is a
1588a91bc7bSHarrietAkot   /// fully permuted coordinate scheme.
1598d8b566fSwren romano   ///
1608d8b566fSwren romano   /// Precondition: `sizes` and `perm` must be valid for `rank`.
1618a91bc7bSHarrietAkot   static SparseTensorCOO<V> *newSparseTensorCOO(uint64_t rank,
1628a91bc7bSHarrietAkot                                                 const uint64_t *sizes,
1638a91bc7bSHarrietAkot                                                 const uint64_t *perm,
1648a91bc7bSHarrietAkot                                                 uint64_t capacity = 0) {
1658a91bc7bSHarrietAkot     std::vector<uint64_t> permsz(rank);
166d83a7068Swren romano     for (uint64_t r = 0; r < rank; r++) {
167d83a7068Swren romano       assert(sizes[r] > 0 && "Dimension size zero has trivial storage");
1688a91bc7bSHarrietAkot       permsz[perm[r]] = sizes[r];
169d83a7068Swren romano     }
1708a91bc7bSHarrietAkot     return new SparseTensorCOO<V>(permsz, capacity);
1718a91bc7bSHarrietAkot   }
1728a91bc7bSHarrietAkot 
1738a91bc7bSHarrietAkot private:
1748a91bc7bSHarrietAkot   const std::vector<uint64_t> sizes; // per-dimension sizes
1758a91bc7bSHarrietAkot   std::vector<Element<V>> elements;
176*db6796dfSMehdi Amini   bool iteratorLocked = false;
177*db6796dfSMehdi Amini   unsigned iteratorPos = 0;
1788a91bc7bSHarrietAkot };
1798a91bc7bSHarrietAkot 
1808d8b566fSwren romano /// Abstract base class for `SparseTensorStorage<P,I,V>`.  This class
1818d8b566fSwren romano /// takes responsibility for all the `<P,I,V>`-independent aspects
1828d8b566fSwren romano /// of the tensor (e.g., shape, sparsity, permutation).  In addition,
1838d8b566fSwren romano /// we use function overloading to implement "partial" method
1848d8b566fSwren romano /// specialization, which the C-API relies on to catch type errors
1858d8b566fSwren romano /// arising from our use of opaque pointers.
1868a91bc7bSHarrietAkot class SparseTensorStorageBase {
1878a91bc7bSHarrietAkot public:
1888d8b566fSwren romano   /// Constructs a new storage object.  The `perm` maps the tensor's
1898d8b566fSwren romano   /// semantic-ordering of dimensions to this object's storage-order.
1908d8b566fSwren romano   /// The `szs` and `sparsity` arrays are already in storage-order.
1918d8b566fSwren romano   ///
1928d8b566fSwren romano   /// Precondition: `perm` and `sparsity` must be valid for `szs.size()`.
1938d8b566fSwren romano   SparseTensorStorageBase(const std::vector<uint64_t> &szs,
1948d8b566fSwren romano                           const uint64_t *perm, const DimLevelType *sparsity)
1958d8b566fSwren romano       : dimSizes(szs), rev(getRank()),
1968d8b566fSwren romano         dimTypes(sparsity, sparsity + getRank()) {
1978d8b566fSwren romano     const uint64_t rank = getRank();
1988d8b566fSwren romano     // Validate parameters.
1998d8b566fSwren romano     assert(rank > 0 && "Trivial shape is unsupported");
2008d8b566fSwren romano     for (uint64_t r = 0; r < rank; r++) {
2018d8b566fSwren romano       assert(dimSizes[r] > 0 && "Dimension size zero has trivial storage");
2028d8b566fSwren romano       assert((dimTypes[r] == DimLevelType::kDense ||
2038d8b566fSwren romano               dimTypes[r] == DimLevelType::kCompressed) &&
2048d8b566fSwren romano              "Unsupported DimLevelType");
2058d8b566fSwren romano     }
2068d8b566fSwren romano     // Construct the "reverse" (i.e., inverse) permutation.
2078d8b566fSwren romano     for (uint64_t r = 0; r < rank; r++)
2088d8b566fSwren romano       rev[perm[r]] = r;
2098d8b566fSwren romano   }
2108d8b566fSwren romano 
2118d8b566fSwren romano   virtual ~SparseTensorStorageBase() = default;
2128d8b566fSwren romano 
2138d8b566fSwren romano   /// Get the rank of the tensor.
2148d8b566fSwren romano   uint64_t getRank() const { return dimSizes.size(); }
2158d8b566fSwren romano 
2168d8b566fSwren romano   /// Getter for the dimension-sizes array, in storage-order.
2178d8b566fSwren romano   const std::vector<uint64_t> &getDimSizes() const { return dimSizes; }
2188d8b566fSwren romano 
2198d8b566fSwren romano   /// Safely lookup the size of the given (storage-order) dimension.
2208d8b566fSwren romano   uint64_t getDimSize(uint64_t d) const {
2218d8b566fSwren romano     assert(d < getRank());
2228d8b566fSwren romano     return dimSizes[d];
2238d8b566fSwren romano   }
2248d8b566fSwren romano 
2258d8b566fSwren romano   /// Getter for the "reverse" permutation, which maps this object's
2268d8b566fSwren romano   /// storage-order to the tensor's semantic-order.
2278d8b566fSwren romano   const std::vector<uint64_t> &getRev() const { return rev; }
2288d8b566fSwren romano 
2298d8b566fSwren romano   /// Getter for the dimension-types array, in storage-order.
2308d8b566fSwren romano   const std::vector<DimLevelType> &getDimTypes() const { return dimTypes; }
2318d8b566fSwren romano 
2328d8b566fSwren romano   /// Safely check if the (storage-order) dimension uses compressed storage.
2338d8b566fSwren romano   bool isCompressedDim(uint64_t d) const {
2348d8b566fSwren romano     assert(d < getRank());
2358d8b566fSwren romano     return (dimTypes[d] == DimLevelType::kCompressed);
2368d8b566fSwren romano   }
2378a91bc7bSHarrietAkot 
2384f2ec7f9SAart Bik   /// Overhead storage.
2398a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint64_t> **, uint64_t) { fatal("p64"); }
2408a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint32_t> **, uint64_t) { fatal("p32"); }
2418a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint16_t> **, uint64_t) { fatal("p16"); }
2428a91bc7bSHarrietAkot   virtual void getPointers(std::vector<uint8_t> **, uint64_t) { fatal("p8"); }
2438a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint64_t> **, uint64_t) { fatal("i64"); }
2448a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint32_t> **, uint64_t) { fatal("i32"); }
2458a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint16_t> **, uint64_t) { fatal("i16"); }
2468a91bc7bSHarrietAkot   virtual void getIndices(std::vector<uint8_t> **, uint64_t) { fatal("i8"); }
2478a91bc7bSHarrietAkot 
2484f2ec7f9SAart Bik   /// Primary storage.
2498a91bc7bSHarrietAkot   virtual void getValues(std::vector<double> **) { fatal("valf64"); }
2508a91bc7bSHarrietAkot   virtual void getValues(std::vector<float> **) { fatal("valf32"); }
2518a91bc7bSHarrietAkot   virtual void getValues(std::vector<int64_t> **) { fatal("vali64"); }
2528a91bc7bSHarrietAkot   virtual void getValues(std::vector<int32_t> **) { fatal("vali32"); }
2538a91bc7bSHarrietAkot   virtual void getValues(std::vector<int16_t> **) { fatal("vali16"); }
2548a91bc7bSHarrietAkot   virtual void getValues(std::vector<int8_t> **) { fatal("vali8"); }
2558a91bc7bSHarrietAkot 
2564f2ec7f9SAart Bik   /// Element-wise insertion in lexicographic index order.
257c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, double) { fatal("insf64"); }
258c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, float) { fatal("insf32"); }
259c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int64_t) { fatal("insi64"); }
260c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int32_t) { fatal("insi32"); }
261c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int16_t) { fatal("ins16"); }
262c03fd1e6Swren romano   virtual void lexInsert(const uint64_t *, int8_t) { fatal("insi8"); }
2634f2ec7f9SAart Bik 
2644f2ec7f9SAart Bik   /// Expanded insertion.
2654f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, double *, bool *, uint64_t *, uint64_t) {
2664f2ec7f9SAart Bik     fatal("expf64");
2674f2ec7f9SAart Bik   }
2684f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, float *, bool *, uint64_t *, uint64_t) {
2694f2ec7f9SAart Bik     fatal("expf32");
2704f2ec7f9SAart Bik   }
2714f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int64_t *, bool *, uint64_t *, uint64_t) {
2724f2ec7f9SAart Bik     fatal("expi64");
2734f2ec7f9SAart Bik   }
2744f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int32_t *, bool *, uint64_t *, uint64_t) {
2754f2ec7f9SAart Bik     fatal("expi32");
2764f2ec7f9SAart Bik   }
2774f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int16_t *, bool *, uint64_t *, uint64_t) {
2784f2ec7f9SAart Bik     fatal("expi16");
2794f2ec7f9SAart Bik   }
2804f2ec7f9SAart Bik   virtual void expInsert(uint64_t *, int8_t *, bool *, uint64_t *, uint64_t) {
2814f2ec7f9SAart Bik     fatal("expi8");
2824f2ec7f9SAart Bik   }
2834f2ec7f9SAart Bik 
2844f2ec7f9SAart Bik   /// Finishes insertion.
285f66e5769SAart Bik   virtual void endInsert() = 0;
286f66e5769SAart Bik 
2878a91bc7bSHarrietAkot private:
28846bdacaaSwren romano   static void fatal(const char *tp) {
2898a91bc7bSHarrietAkot     fprintf(stderr, "unsupported %s\n", tp);
2908a91bc7bSHarrietAkot     exit(1);
2918a91bc7bSHarrietAkot   }
2928d8b566fSwren romano 
2938d8b566fSwren romano   const std::vector<uint64_t> dimSizes;
2948d8b566fSwren romano   std::vector<uint64_t> rev;
2958d8b566fSwren romano   const std::vector<DimLevelType> dimTypes;
2968a91bc7bSHarrietAkot };
2978a91bc7bSHarrietAkot 
2988a91bc7bSHarrietAkot /// A memory-resident sparse tensor using a storage scheme based on
2998a91bc7bSHarrietAkot /// per-dimension sparse/dense annotations. This data structure provides a
3008a91bc7bSHarrietAkot /// bufferized form of a sparse tensor type. In contrast to generating setup
3018a91bc7bSHarrietAkot /// methods for each differently annotated sparse tensor, this method provides
3028a91bc7bSHarrietAkot /// a convenient "one-size-fits-all" solution that simply takes an input tensor
3038a91bc7bSHarrietAkot /// and annotations to implement all required setup in a general manner.
3048a91bc7bSHarrietAkot template <typename P, typename I, typename V>
3058a91bc7bSHarrietAkot class SparseTensorStorage : public SparseTensorStorageBase {
3068a91bc7bSHarrietAkot public:
3078a91bc7bSHarrietAkot   /// Constructs a sparse tensor storage scheme with the given dimensions,
3088a91bc7bSHarrietAkot   /// permutation, and per-dimension dense/sparse annotations, using
3098a91bc7bSHarrietAkot   /// the coordinate scheme tensor for the initial contents if provided.
3108d8b566fSwren romano   ///
3118d8b566fSwren romano   /// Precondition: `perm` and `sparsity` must be valid for `szs.size()`.
3128a91bc7bSHarrietAkot   SparseTensorStorage(const std::vector<uint64_t> &szs, const uint64_t *perm,
313f66e5769SAart Bik                       const DimLevelType *sparsity,
3148d8b566fSwren romano                       SparseTensorCOO<V> *coo = nullptr)
3158d8b566fSwren romano       : SparseTensorStorageBase(szs, perm, sparsity), pointers(getRank()),
3168d8b566fSwren romano         indices(getRank()), idx(getRank()) {
3178a91bc7bSHarrietAkot     // Provide hints on capacity of pointers and indices.
318175b9af4SAart Bik     // TODO: needs much fine-tuning based on actual sparsity; currently
319175b9af4SAart Bik     //       we reserve pointer/index space based on all previous dense
320175b9af4SAart Bik     //       dimensions, which works well up to first sparse dim; but
321175b9af4SAart Bik     //       we should really use nnz and dense/sparse distribution.
322f66e5769SAart Bik     bool allDense = true;
323f66e5769SAart Bik     uint64_t sz = 1;
3248d8b566fSwren romano     for (uint64_t r = 0, rank = getRank(); r < rank; r++) {
3258d8b566fSwren romano       if (isCompressedDim(r)) {
3268d8b566fSwren romano         // TODO: Take a parameter between 1 and `sizes[r]`, and multiply
3278d8b566fSwren romano         // `sz` by that before reserving. (For now we just use 1.)
328f66e5769SAart Bik         pointers[r].reserve(sz + 1);
3298d8b566fSwren romano         pointers[r].push_back(0);
330f66e5769SAart Bik         indices[r].reserve(sz);
331f66e5769SAart Bik         sz = 1;
332f66e5769SAart Bik         allDense = false;
3338d8b566fSwren romano       } else { // Dense dimension.
3348d8b566fSwren romano         sz = checkedMul(sz, getDimSizes()[r]);
3358a91bc7bSHarrietAkot       }
3368a91bc7bSHarrietAkot     }
3378a91bc7bSHarrietAkot     // Then assign contents from coordinate scheme tensor if provided.
3388d8b566fSwren romano     if (coo) {
3394d0a18d0Swren romano       // Ensure both preconditions of `fromCOO`.
3408d8b566fSwren romano       assert(coo->getSizes() == getDimSizes() && "Tensor size mismatch");
3418d8b566fSwren romano       coo->sort();
3424d0a18d0Swren romano       // Now actually insert the `elements`.
3438d8b566fSwren romano       const std::vector<Element<V>> &elements = coo->getElements();
344ceda1ae9Swren romano       uint64_t nnz = elements.size();
3458a91bc7bSHarrietAkot       values.reserve(nnz);
346ceda1ae9Swren romano       fromCOO(elements, 0, nnz, 0);
3471ce77b56SAart Bik     } else if (allDense) {
348f66e5769SAart Bik       values.resize(sz, 0);
3498a91bc7bSHarrietAkot     }
3508a91bc7bSHarrietAkot   }
3518a91bc7bSHarrietAkot 
3520ae2e958SMehdi Amini   ~SparseTensorStorage() override = default;
3538a91bc7bSHarrietAkot 
354f66e5769SAart Bik   /// Partially specialize these getter methods based on template types.
3558a91bc7bSHarrietAkot   void getPointers(std::vector<P> **out, uint64_t d) override {
3568a91bc7bSHarrietAkot     assert(d < getRank());
3578a91bc7bSHarrietAkot     *out = &pointers[d];
3588a91bc7bSHarrietAkot   }
3598a91bc7bSHarrietAkot   void getIndices(std::vector<I> **out, uint64_t d) override {
3608a91bc7bSHarrietAkot     assert(d < getRank());
3618a91bc7bSHarrietAkot     *out = &indices[d];
3628a91bc7bSHarrietAkot   }
3638a91bc7bSHarrietAkot   void getValues(std::vector<V> **out) override { *out = &values; }
3648a91bc7bSHarrietAkot 
36503fe15ceSAart Bik   /// Partially specialize lexicographical insertions based on template types.
366c03fd1e6Swren romano   void lexInsert(const uint64_t *cursor, V val) override {
3671ce77b56SAart Bik     // First, wrap up pending insertion path.
3681ce77b56SAart Bik     uint64_t diff = 0;
3691ce77b56SAart Bik     uint64_t top = 0;
3701ce77b56SAart Bik     if (!values.empty()) {
3711ce77b56SAart Bik       diff = lexDiff(cursor);
3721ce77b56SAart Bik       endPath(diff + 1);
3731ce77b56SAart Bik       top = idx[diff] + 1;
3741ce77b56SAart Bik     }
3751ce77b56SAart Bik     // Then continue with insertion path.
3761ce77b56SAart Bik     insPath(cursor, diff, top, val);
377f66e5769SAart Bik   }
378f66e5769SAart Bik 
3794f2ec7f9SAart Bik   /// Partially specialize expanded insertions based on template types.
3804f2ec7f9SAart Bik   /// Note that this method resets the values/filled-switch array back
3814f2ec7f9SAart Bik   /// to all-zero/false while only iterating over the nonzero elements.
3824f2ec7f9SAart Bik   void expInsert(uint64_t *cursor, V *values, bool *filled, uint64_t *added,
3834f2ec7f9SAart Bik                  uint64_t count) override {
3844f2ec7f9SAart Bik     if (count == 0)
3854f2ec7f9SAart Bik       return;
3864f2ec7f9SAart Bik     // Sort.
3874f2ec7f9SAart Bik     std::sort(added, added + count);
3884f2ec7f9SAart Bik     // Restore insertion path for first insert.
3893bf2ba3bSwren romano     const uint64_t lastDim = getRank() - 1;
3904f2ec7f9SAart Bik     uint64_t index = added[0];
3913bf2ba3bSwren romano     cursor[lastDim] = index;
3924f2ec7f9SAart Bik     lexInsert(cursor, values[index]);
3934f2ec7f9SAart Bik     assert(filled[index]);
3944f2ec7f9SAart Bik     values[index] = 0;
3954f2ec7f9SAart Bik     filled[index] = false;
3964f2ec7f9SAart Bik     // Subsequent insertions are quick.
3974f2ec7f9SAart Bik     for (uint64_t i = 1; i < count; i++) {
3984f2ec7f9SAart Bik       assert(index < added[i] && "non-lexicographic insertion");
3994f2ec7f9SAart Bik       index = added[i];
4003bf2ba3bSwren romano       cursor[lastDim] = index;
4013bf2ba3bSwren romano       insPath(cursor, lastDim, added[i - 1] + 1, values[index]);
4024f2ec7f9SAart Bik       assert(filled[index]);
4033bf2ba3bSwren romano       values[index] = 0;
4044f2ec7f9SAart Bik       filled[index] = false;
4054f2ec7f9SAart Bik     }
4064f2ec7f9SAart Bik   }
4074f2ec7f9SAart Bik 
408f66e5769SAart Bik   /// Finalizes lexicographic insertions.
4091ce77b56SAart Bik   void endInsert() override {
4101ce77b56SAart Bik     if (values.empty())
41172ec2f76Swren romano       finalizeSegment(0);
4121ce77b56SAart Bik     else
4131ce77b56SAart Bik       endPath(0);
4141ce77b56SAart Bik   }
415f66e5769SAart Bik 
4168a91bc7bSHarrietAkot   /// Returns this sparse tensor storage scheme as a new memory-resident
4178a91bc7bSHarrietAkot   /// sparse tensor in coordinate scheme with the given dimension order.
4188d8b566fSwren romano   ///
4198d8b566fSwren romano   /// Precondition: `perm` must be valid for `getRank()`.
4208a91bc7bSHarrietAkot   SparseTensorCOO<V> *toCOO(const uint64_t *perm) {
4218a91bc7bSHarrietAkot     // Restore original order of the dimension sizes and allocate coordinate
4228a91bc7bSHarrietAkot     // scheme with desired new ordering specified in perm.
4238d8b566fSwren romano     const uint64_t rank = getRank();
4248d8b566fSwren romano     const auto &rev = getRev();
4258d8b566fSwren romano     const auto &sizes = getDimSizes();
4268a91bc7bSHarrietAkot     std::vector<uint64_t> orgsz(rank);
4278a91bc7bSHarrietAkot     for (uint64_t r = 0; r < rank; r++)
4288a91bc7bSHarrietAkot       orgsz[rev[r]] = sizes[r];
4298d8b566fSwren romano     SparseTensorCOO<V> *coo = SparseTensorCOO<V>::newSparseTensorCOO(
4308a91bc7bSHarrietAkot         rank, orgsz.data(), perm, values.size());
4318a91bc7bSHarrietAkot     // Populate coordinate scheme restored from old ordering and changed with
4328a91bc7bSHarrietAkot     // new ordering. Rather than applying both reorderings during the recursion,
4338a91bc7bSHarrietAkot     // we compute the combine permutation in advance.
4348a91bc7bSHarrietAkot     std::vector<uint64_t> reord(rank);
4358a91bc7bSHarrietAkot     for (uint64_t r = 0; r < rank; r++)
4368a91bc7bSHarrietAkot       reord[r] = perm[rev[r]];
4378d8b566fSwren romano     toCOO(*coo, reord, 0, 0);
4388d8b566fSwren romano     // TODO: This assertion assumes there are no stored zeros,
4398d8b566fSwren romano     // or if there are then that we don't filter them out.
4408d8b566fSwren romano     // Cf., <https://github.com/llvm/llvm-project/issues/54179>
4418d8b566fSwren romano     assert(coo->getElements().size() == values.size());
4428d8b566fSwren romano     return coo;
4438a91bc7bSHarrietAkot   }
4448a91bc7bSHarrietAkot 
4458a91bc7bSHarrietAkot   /// Factory method. Constructs a sparse tensor storage scheme with the given
4468a91bc7bSHarrietAkot   /// dimensions, permutation, and per-dimension dense/sparse annotations,
4478a91bc7bSHarrietAkot   /// using the coordinate scheme tensor for the initial contents if provided.
4488a91bc7bSHarrietAkot   /// In the latter case, the coordinate scheme must respect the same
4498a91bc7bSHarrietAkot   /// permutation as is desired for the new sparse tensor storage.
4508d8b566fSwren romano   ///
4518d8b566fSwren romano   /// Precondition: `shape`, `perm`, and `sparsity` must be valid for `rank`.
4528a91bc7bSHarrietAkot   static SparseTensorStorage<P, I, V> *
453d83a7068Swren romano   newSparseTensor(uint64_t rank, const uint64_t *shape, const uint64_t *perm,
4548d8b566fSwren romano                   const DimLevelType *sparsity, SparseTensorCOO<V> *coo) {
4558a91bc7bSHarrietAkot     SparseTensorStorage<P, I, V> *n = nullptr;
4568d8b566fSwren romano     if (coo) {
4578d8b566fSwren romano       assert(coo->getRank() == rank && "Tensor rank mismatch");
4588d8b566fSwren romano       const auto &coosz = coo->getSizes();
4598a91bc7bSHarrietAkot       for (uint64_t r = 0; r < rank; r++)
4608d8b566fSwren romano         assert(shape[r] == 0 || shape[r] == coosz[perm[r]]);
4618d8b566fSwren romano       n = new SparseTensorStorage<P, I, V>(coosz, perm, sparsity, coo);
4628a91bc7bSHarrietAkot     } else {
4638a91bc7bSHarrietAkot       std::vector<uint64_t> permsz(rank);
464d83a7068Swren romano       for (uint64_t r = 0; r < rank; r++) {
465d83a7068Swren romano         assert(shape[r] > 0 && "Dimension size zero has trivial storage");
466d83a7068Swren romano         permsz[perm[r]] = shape[r];
467d83a7068Swren romano       }
468f66e5769SAart Bik       n = new SparseTensorStorage<P, I, V>(permsz, perm, sparsity);
4698a91bc7bSHarrietAkot     }
4708a91bc7bSHarrietAkot     return n;
4718a91bc7bSHarrietAkot   }
4728a91bc7bSHarrietAkot 
4738a91bc7bSHarrietAkot private:
47472ec2f76Swren romano   /// Appends an arbitrary new position to `pointers[d]`.  This method
47572ec2f76Swren romano   /// checks that `pos` is representable in the `P` type; however, it
47672ec2f76Swren romano   /// does not check that `pos` is semantically valid (i.e., larger than
47772ec2f76Swren romano   /// the previous position and smaller than `indices[d].capacity()`).
4788d8b566fSwren romano   void appendPointer(uint64_t d, uint64_t pos, uint64_t count = 1) {
47972ec2f76Swren romano     assert(isCompressedDim(d));
48072ec2f76Swren romano     assert(pos <= std::numeric_limits<P>::max() &&
4814d0a18d0Swren romano            "Pointer value is too large for the P-type");
48272ec2f76Swren romano     pointers[d].insert(pointers[d].end(), count, static_cast<P>(pos));
4834d0a18d0Swren romano   }
4844d0a18d0Swren romano 
48572ec2f76Swren romano   /// Appends index `i` to dimension `d`, in the semantically general
48672ec2f76Swren romano   /// sense.  For non-dense dimensions, that means appending to the
48772ec2f76Swren romano   /// `indices[d]` array, checking that `i` is representable in the `I`
48872ec2f76Swren romano   /// type; however, we do not verify other semantic requirements (e.g.,
48972ec2f76Swren romano   /// that `i` is in bounds for `sizes[d]`, and not previously occurring
49072ec2f76Swren romano   /// in the same segment).  For dense dimensions, this method instead
49172ec2f76Swren romano   /// appends the appropriate number of zeros to the `values` array,
49272ec2f76Swren romano   /// where `full` is the number of "entries" already written to `values`
49372ec2f76Swren romano   /// for this segment (aka one after the highest index previously appended).
49472ec2f76Swren romano   void appendIndex(uint64_t d, uint64_t full, uint64_t i) {
49572ec2f76Swren romano     if (isCompressedDim(d)) {
4964d0a18d0Swren romano       assert(i <= std::numeric_limits<I>::max() &&
4974d0a18d0Swren romano              "Index value is too large for the I-type");
49872ec2f76Swren romano       indices[d].push_back(static_cast<I>(i));
49972ec2f76Swren romano     } else { // Dense dimension.
50072ec2f76Swren romano       assert(i >= full && "Index was already filled");
50172ec2f76Swren romano       if (i == full)
50272ec2f76Swren romano         return; // Short-circuit, since it'll be a nop.
50372ec2f76Swren romano       if (d + 1 == getRank())
50472ec2f76Swren romano         values.insert(values.end(), i - full, 0);
50572ec2f76Swren romano       else
50672ec2f76Swren romano         finalizeSegment(d + 1, 0, i - full);
50772ec2f76Swren romano     }
5084d0a18d0Swren romano   }
5094d0a18d0Swren romano 
5108a91bc7bSHarrietAkot   /// Initializes sparse tensor storage scheme from a memory-resident sparse
5118a91bc7bSHarrietAkot   /// tensor in coordinate scheme. This method prepares the pointers and
5128a91bc7bSHarrietAkot   /// indices arrays under the given per-dimension dense/sparse annotations.
5134d0a18d0Swren romano   ///
5144d0a18d0Swren romano   /// Preconditions:
5154d0a18d0Swren romano   /// (1) the `elements` must be lexicographically sorted.
5164d0a18d0Swren romano   /// (2) the indices of every element are valid for `sizes` (equal rank
5174d0a18d0Swren romano   ///     and pointwise less-than).
518ceda1ae9Swren romano   void fromCOO(const std::vector<Element<V>> &elements, uint64_t lo,
519ceda1ae9Swren romano                uint64_t hi, uint64_t d) {
5208a91bc7bSHarrietAkot     // Once dimensions are exhausted, insert the numerical values.
521c4017f9dSwren romano     assert(d <= getRank() && hi <= elements.size());
5228a91bc7bSHarrietAkot     if (d == getRank()) {
523c4017f9dSwren romano       assert(lo < hi);
5241ce77b56SAart Bik       values.push_back(elements[lo].value);
5258a91bc7bSHarrietAkot       return;
5268a91bc7bSHarrietAkot     }
5278a91bc7bSHarrietAkot     // Visit all elements in this interval.
5288a91bc7bSHarrietAkot     uint64_t full = 0;
529c4017f9dSwren romano     while (lo < hi) { // If `hi` is unchanged, then `lo < elements.size()`.
5308a91bc7bSHarrietAkot       // Find segment in interval with same index elements in this dimension.
531f66e5769SAart Bik       uint64_t i = elements[lo].indices[d];
5328a91bc7bSHarrietAkot       uint64_t seg = lo + 1;
533f66e5769SAart Bik       while (seg < hi && elements[seg].indices[d] == i)
5348a91bc7bSHarrietAkot         seg++;
5358a91bc7bSHarrietAkot       // Handle segment in interval for sparse or dense dimension.
53672ec2f76Swren romano       appendIndex(d, full, i);
53772ec2f76Swren romano       full = i + 1;
538ceda1ae9Swren romano       fromCOO(elements, lo, seg, d + 1);
5398a91bc7bSHarrietAkot       // And move on to next segment in interval.
5408a91bc7bSHarrietAkot       lo = seg;
5418a91bc7bSHarrietAkot     }
5428a91bc7bSHarrietAkot     // Finalize the sparse pointer structure at this dimension.
54372ec2f76Swren romano     finalizeSegment(d, full);
5448a91bc7bSHarrietAkot   }
5458a91bc7bSHarrietAkot 
5468a91bc7bSHarrietAkot   /// Stores the sparse tensor storage scheme into a memory-resident sparse
5478a91bc7bSHarrietAkot   /// tensor in coordinate scheme.
548ceda1ae9Swren romano   void toCOO(SparseTensorCOO<V> &tensor, std::vector<uint64_t> &reord,
549f66e5769SAart Bik              uint64_t pos, uint64_t d) {
5508a91bc7bSHarrietAkot     assert(d <= getRank());
5518a91bc7bSHarrietAkot     if (d == getRank()) {
5528a91bc7bSHarrietAkot       assert(pos < values.size());
553ceda1ae9Swren romano       tensor.add(idx, values[pos]);
5541ce77b56SAart Bik     } else if (isCompressedDim(d)) {
5558a91bc7bSHarrietAkot       // Sparse dimension.
5568a91bc7bSHarrietAkot       for (uint64_t ii = pointers[d][pos]; ii < pointers[d][pos + 1]; ii++) {
5578a91bc7bSHarrietAkot         idx[reord[d]] = indices[d][ii];
558f66e5769SAart Bik         toCOO(tensor, reord, ii, d + 1);
5598a91bc7bSHarrietAkot       }
5601ce77b56SAart Bik     } else {
5611ce77b56SAart Bik       // Dense dimension.
5628d8b566fSwren romano       const uint64_t sz = getDimSizes()[d];
5638d8b566fSwren romano       const uint64_t off = pos * sz;
5648d8b566fSwren romano       for (uint64_t i = 0; i < sz; i++) {
5651ce77b56SAart Bik         idx[reord[d]] = i;
5661ce77b56SAart Bik         toCOO(tensor, reord, off + i, d + 1);
5678a91bc7bSHarrietAkot       }
5688a91bc7bSHarrietAkot     }
5691ce77b56SAart Bik   }
5701ce77b56SAart Bik 
57172ec2f76Swren romano   /// Finalize the sparse pointer structure at this dimension.
57272ec2f76Swren romano   void finalizeSegment(uint64_t d, uint64_t full = 0, uint64_t count = 1) {
57372ec2f76Swren romano     if (count == 0)
57472ec2f76Swren romano       return; // Short-circuit, since it'll be a nop.
57572ec2f76Swren romano     if (isCompressedDim(d)) {
57672ec2f76Swren romano       appendPointer(d, indices[d].size(), count);
57772ec2f76Swren romano     } else { // Dense dimension.
5788d8b566fSwren romano       const uint64_t sz = getDimSizes()[d];
57972ec2f76Swren romano       assert(sz >= full && "Segment is overfull");
5808d8b566fSwren romano       count = checkedMul(count, sz - full);
58172ec2f76Swren romano       // For dense storage we must enumerate all the remaining coordinates
58272ec2f76Swren romano       // in this dimension (i.e., coordinates after the last non-zero
58372ec2f76Swren romano       // element), and either fill in their zero values or else recurse
58472ec2f76Swren romano       // to finalize some deeper dimension.
58572ec2f76Swren romano       if (d + 1 == getRank())
58672ec2f76Swren romano         values.insert(values.end(), count, 0);
58772ec2f76Swren romano       else
58872ec2f76Swren romano         finalizeSegment(d + 1, 0, count);
5891ce77b56SAart Bik     }
5901ce77b56SAart Bik   }
5911ce77b56SAart Bik 
5921ce77b56SAart Bik   /// Wraps up a single insertion path, inner to outer.
5931ce77b56SAart Bik   void endPath(uint64_t diff) {
5941ce77b56SAart Bik     uint64_t rank = getRank();
5951ce77b56SAart Bik     assert(diff <= rank);
5961ce77b56SAart Bik     for (uint64_t i = 0; i < rank - diff; i++) {
59772ec2f76Swren romano       const uint64_t d = rank - i - 1;
59872ec2f76Swren romano       finalizeSegment(d, idx[d] + 1);
5991ce77b56SAart Bik     }
6001ce77b56SAart Bik   }
6011ce77b56SAart Bik 
6021ce77b56SAart Bik   /// Continues a single insertion path, outer to inner.
603c03fd1e6Swren romano   void insPath(const uint64_t *cursor, uint64_t diff, uint64_t top, V val) {
6041ce77b56SAart Bik     uint64_t rank = getRank();
6051ce77b56SAart Bik     assert(diff < rank);
6061ce77b56SAart Bik     for (uint64_t d = diff; d < rank; d++) {
6071ce77b56SAart Bik       uint64_t i = cursor[d];
60872ec2f76Swren romano       appendIndex(d, top, i);
6091ce77b56SAart Bik       top = 0;
6101ce77b56SAart Bik       idx[d] = i;
6111ce77b56SAart Bik     }
6121ce77b56SAart Bik     values.push_back(val);
6131ce77b56SAart Bik   }
6141ce77b56SAart Bik 
6151ce77b56SAart Bik   /// Finds the lexicographic differing dimension.
61646bdacaaSwren romano   uint64_t lexDiff(const uint64_t *cursor) const {
6171ce77b56SAart Bik     for (uint64_t r = 0, rank = getRank(); r < rank; r++)
6181ce77b56SAart Bik       if (cursor[r] > idx[r])
6191ce77b56SAart Bik         return r;
6201ce77b56SAart Bik       else
6211ce77b56SAart Bik         assert(cursor[r] == idx[r] && "non-lexicographic insertion");
6221ce77b56SAart Bik     assert(0 && "duplication insertion");
6231ce77b56SAart Bik     return -1u;
6241ce77b56SAart Bik   }
6251ce77b56SAart Bik 
6268a91bc7bSHarrietAkot private:
6278a91bc7bSHarrietAkot   std::vector<std::vector<P>> pointers;
6288a91bc7bSHarrietAkot   std::vector<std::vector<I>> indices;
6298a91bc7bSHarrietAkot   std::vector<V> values;
6308d8b566fSwren romano   std::vector<uint64_t> idx; // index cursor for lexicographic insertion.
6318a91bc7bSHarrietAkot };
6328a91bc7bSHarrietAkot 
6338a91bc7bSHarrietAkot /// Helper to convert string to lower case.
6348a91bc7bSHarrietAkot static char *toLower(char *token) {
6358a91bc7bSHarrietAkot   for (char *c = token; *c; c++)
6368a91bc7bSHarrietAkot     *c = tolower(*c);
6378a91bc7bSHarrietAkot   return token;
6388a91bc7bSHarrietAkot }
6398a91bc7bSHarrietAkot 
6408a91bc7bSHarrietAkot /// Read the MME header of a general sparse matrix of type real.
64103fe15ceSAart Bik static void readMMEHeader(FILE *file, char *filename, char *line,
642bb56c2b3SMehdi Amini                           uint64_t *idata, bool *isSymmetric) {
6438a91bc7bSHarrietAkot   char header[64];
6448a91bc7bSHarrietAkot   char object[64];
6458a91bc7bSHarrietAkot   char format[64];
6468a91bc7bSHarrietAkot   char field[64];
6478a91bc7bSHarrietAkot   char symmetry[64];
6488a91bc7bSHarrietAkot   // Read header line.
6498a91bc7bSHarrietAkot   if (fscanf(file, "%63s %63s %63s %63s %63s\n", header, object, format, field,
6508a91bc7bSHarrietAkot              symmetry) != 5) {
65103fe15ceSAart Bik     fprintf(stderr, "Corrupt header in %s\n", filename);
6528a91bc7bSHarrietAkot     exit(1);
6538a91bc7bSHarrietAkot   }
654bb56c2b3SMehdi Amini   *isSymmetric = (strcmp(toLower(symmetry), "symmetric") == 0);
6558a91bc7bSHarrietAkot   // Make sure this is a general sparse matrix.
6568a91bc7bSHarrietAkot   if (strcmp(toLower(header), "%%matrixmarket") ||
6578a91bc7bSHarrietAkot       strcmp(toLower(object), "matrix") ||
6588a91bc7bSHarrietAkot       strcmp(toLower(format), "coordinate") || strcmp(toLower(field), "real") ||
659bb56c2b3SMehdi Amini       (strcmp(toLower(symmetry), "general") && !(*isSymmetric))) {
6608a91bc7bSHarrietAkot     fprintf(stderr,
66103fe15ceSAart Bik             "Cannot find a general sparse matrix with type real in %s\n",
66203fe15ceSAart Bik             filename);
6638a91bc7bSHarrietAkot     exit(1);
6648a91bc7bSHarrietAkot   }
6658a91bc7bSHarrietAkot   // Skip comments.
666e5639b3fSMehdi Amini   while (true) {
66703fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
66803fe15ceSAart Bik       fprintf(stderr, "Cannot find data in %s\n", filename);
6698a91bc7bSHarrietAkot       exit(1);
6708a91bc7bSHarrietAkot     }
6718a91bc7bSHarrietAkot     if (line[0] != '%')
6728a91bc7bSHarrietAkot       break;
6738a91bc7bSHarrietAkot   }
6748a91bc7bSHarrietAkot   // Next line contains M N NNZ.
6758a91bc7bSHarrietAkot   idata[0] = 2; // rank
6768a91bc7bSHarrietAkot   if (sscanf(line, "%" PRIu64 "%" PRIu64 "%" PRIu64 "\n", idata + 2, idata + 3,
6778a91bc7bSHarrietAkot              idata + 1) != 3) {
67803fe15ceSAart Bik     fprintf(stderr, "Cannot find size in %s\n", filename);
6798a91bc7bSHarrietAkot     exit(1);
6808a91bc7bSHarrietAkot   }
6818a91bc7bSHarrietAkot }
6828a91bc7bSHarrietAkot 
6838a91bc7bSHarrietAkot /// Read the "extended" FROSTT header. Although not part of the documented
6848a91bc7bSHarrietAkot /// format, we assume that the file starts with optional comments followed
6858a91bc7bSHarrietAkot /// by two lines that define the rank, the number of nonzeros, and the
6868a91bc7bSHarrietAkot /// dimensions sizes (one per rank) of the sparse tensor.
68703fe15ceSAart Bik static void readExtFROSTTHeader(FILE *file, char *filename, char *line,
68803fe15ceSAart Bik                                 uint64_t *idata) {
6898a91bc7bSHarrietAkot   // Skip comments.
690e5639b3fSMehdi Amini   while (true) {
69103fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
69203fe15ceSAart Bik       fprintf(stderr, "Cannot find data in %s\n", filename);
6938a91bc7bSHarrietAkot       exit(1);
6948a91bc7bSHarrietAkot     }
6958a91bc7bSHarrietAkot     if (line[0] != '#')
6968a91bc7bSHarrietAkot       break;
6978a91bc7bSHarrietAkot   }
6988a91bc7bSHarrietAkot   // Next line contains RANK and NNZ.
6998a91bc7bSHarrietAkot   if (sscanf(line, "%" PRIu64 "%" PRIu64 "\n", idata, idata + 1) != 2) {
70003fe15ceSAart Bik     fprintf(stderr, "Cannot find metadata in %s\n", filename);
7018a91bc7bSHarrietAkot     exit(1);
7028a91bc7bSHarrietAkot   }
7038a91bc7bSHarrietAkot   // Followed by a line with the dimension sizes (one per rank).
7048a91bc7bSHarrietAkot   for (uint64_t r = 0; r < idata[0]; r++) {
7058a91bc7bSHarrietAkot     if (fscanf(file, "%" PRIu64, idata + 2 + r) != 1) {
70603fe15ceSAart Bik       fprintf(stderr, "Cannot find dimension size %s\n", filename);
7078a91bc7bSHarrietAkot       exit(1);
7088a91bc7bSHarrietAkot     }
7098a91bc7bSHarrietAkot   }
71003fe15ceSAart Bik   fgets(line, kColWidth, file); // end of line
7118a91bc7bSHarrietAkot }
7128a91bc7bSHarrietAkot 
7138a91bc7bSHarrietAkot /// Reads a sparse tensor with the given filename into a memory-resident
7148a91bc7bSHarrietAkot /// sparse tensor in coordinate scheme.
7158a91bc7bSHarrietAkot template <typename V>
7168a91bc7bSHarrietAkot static SparseTensorCOO<V> *openSparseTensorCOO(char *filename, uint64_t rank,
717d83a7068Swren romano                                                const uint64_t *shape,
7188a91bc7bSHarrietAkot                                                const uint64_t *perm) {
7198a91bc7bSHarrietAkot   // Open the file.
7208a91bc7bSHarrietAkot   FILE *file = fopen(filename, "r");
7218a91bc7bSHarrietAkot   if (!file) {
7223734c078Swren romano     assert(filename && "Received nullptr for filename");
7233734c078Swren romano     fprintf(stderr, "Cannot find file %s\n", filename);
7248a91bc7bSHarrietAkot     exit(1);
7258a91bc7bSHarrietAkot   }
7268a91bc7bSHarrietAkot   // Perform some file format dependent set up.
72703fe15ceSAart Bik   char line[kColWidth];
7288a91bc7bSHarrietAkot   uint64_t idata[512];
729bb56c2b3SMehdi Amini   bool isSymmetric = false;
7308a91bc7bSHarrietAkot   if (strstr(filename, ".mtx")) {
731bb56c2b3SMehdi Amini     readMMEHeader(file, filename, line, idata, &isSymmetric);
7328a91bc7bSHarrietAkot   } else if (strstr(filename, ".tns")) {
73303fe15ceSAart Bik     readExtFROSTTHeader(file, filename, line, idata);
7348a91bc7bSHarrietAkot   } else {
7358a91bc7bSHarrietAkot     fprintf(stderr, "Unknown format %s\n", filename);
7368a91bc7bSHarrietAkot     exit(1);
7378a91bc7bSHarrietAkot   }
7388a91bc7bSHarrietAkot   // Prepare sparse tensor object with per-dimension sizes
7398a91bc7bSHarrietAkot   // and the number of nonzeros as initial capacity.
7408a91bc7bSHarrietAkot   assert(rank == idata[0] && "rank mismatch");
7418a91bc7bSHarrietAkot   uint64_t nnz = idata[1];
7428a91bc7bSHarrietAkot   for (uint64_t r = 0; r < rank; r++)
743d83a7068Swren romano     assert((shape[r] == 0 || shape[r] == idata[2 + r]) &&
7448a91bc7bSHarrietAkot            "dimension size mismatch");
7458a91bc7bSHarrietAkot   SparseTensorCOO<V> *tensor =
7468a91bc7bSHarrietAkot       SparseTensorCOO<V>::newSparseTensorCOO(rank, idata + 2, perm, nnz);
7478a91bc7bSHarrietAkot   //  Read all nonzero elements.
7488a91bc7bSHarrietAkot   std::vector<uint64_t> indices(rank);
7498a91bc7bSHarrietAkot   for (uint64_t k = 0; k < nnz; k++) {
75003fe15ceSAart Bik     if (!fgets(line, kColWidth, file)) {
75103fe15ceSAart Bik       fprintf(stderr, "Cannot find next line of data in %s\n", filename);
7528a91bc7bSHarrietAkot       exit(1);
7538a91bc7bSHarrietAkot     }
75403fe15ceSAart Bik     char *linePtr = line;
75503fe15ceSAart Bik     for (uint64_t r = 0; r < rank; r++) {
75603fe15ceSAart Bik       uint64_t idx = strtoul(linePtr, &linePtr, 10);
7578a91bc7bSHarrietAkot       // Add 0-based index.
7588a91bc7bSHarrietAkot       indices[perm[r]] = idx - 1;
7598a91bc7bSHarrietAkot     }
7608a91bc7bSHarrietAkot     // The external formats always store the numerical values with the type
7618a91bc7bSHarrietAkot     // double, but we cast these values to the sparse tensor object type.
76203fe15ceSAart Bik     double value = strtod(linePtr, &linePtr);
7638a91bc7bSHarrietAkot     tensor->add(indices, value);
76402710413SBixia Zheng     // We currently chose to deal with symmetric matrices by fully constructing
76502710413SBixia Zheng     // them. In the future, we may want to make symmetry implicit for storage
76602710413SBixia Zheng     // reasons.
767bb56c2b3SMehdi Amini     if (isSymmetric && indices[0] != indices[1])
76802710413SBixia Zheng       tensor->add({indices[1], indices[0]}, value);
7698a91bc7bSHarrietAkot   }
7708a91bc7bSHarrietAkot   // Close the file and return tensor.
7718a91bc7bSHarrietAkot   fclose(file);
7728a91bc7bSHarrietAkot   return tensor;
7738a91bc7bSHarrietAkot }
7748a91bc7bSHarrietAkot 
775efa15f41SAart Bik /// Writes the sparse tensor to extended FROSTT format.
776efa15f41SAart Bik template <typename V>
77746bdacaaSwren romano static void outSparseTensor(void *tensor, void *dest, bool sort) {
7786438783fSAart Bik   assert(tensor && dest);
7796438783fSAart Bik   auto coo = static_cast<SparseTensorCOO<V> *>(tensor);
7806438783fSAart Bik   if (sort)
7816438783fSAart Bik     coo->sort();
7826438783fSAart Bik   char *filename = static_cast<char *>(dest);
7836438783fSAart Bik   auto &sizes = coo->getSizes();
7846438783fSAart Bik   auto &elements = coo->getElements();
7856438783fSAart Bik   uint64_t rank = coo->getRank();
786efa15f41SAart Bik   uint64_t nnz = elements.size();
787efa15f41SAart Bik   std::fstream file;
788efa15f41SAart Bik   file.open(filename, std::ios_base::out | std::ios_base::trunc);
789efa15f41SAart Bik   assert(file.is_open());
790efa15f41SAart Bik   file << "; extended FROSTT format\n" << rank << " " << nnz << std::endl;
791efa15f41SAart Bik   for (uint64_t r = 0; r < rank - 1; r++)
792efa15f41SAart Bik     file << sizes[r] << " ";
793efa15f41SAart Bik   file << sizes[rank - 1] << std::endl;
794efa15f41SAart Bik   for (uint64_t i = 0; i < nnz; i++) {
795efa15f41SAart Bik     auto &idx = elements[i].indices;
796efa15f41SAart Bik     for (uint64_t r = 0; r < rank; r++)
797efa15f41SAart Bik       file << (idx[r] + 1) << " ";
798efa15f41SAart Bik     file << elements[i].value << std::endl;
799efa15f41SAart Bik   }
800efa15f41SAart Bik   file.flush();
801efa15f41SAart Bik   file.close();
802efa15f41SAart Bik   assert(file.good());
8036438783fSAart Bik }
8046438783fSAart Bik 
8056438783fSAart Bik /// Initializes sparse tensor from an external COO-flavored format.
8066438783fSAart Bik template <typename V>
80746bdacaaSwren romano static SparseTensorStorage<uint64_t, uint64_t, V> *
8086438783fSAart Bik toMLIRSparseTensor(uint64_t rank, uint64_t nse, uint64_t *shape, V *values,
80920eaa88fSBixia Zheng                    uint64_t *indices, uint64_t *perm, uint8_t *sparse) {
81020eaa88fSBixia Zheng   const DimLevelType *sparsity = (DimLevelType *)(sparse);
81120eaa88fSBixia Zheng #ifndef NDEBUG
81220eaa88fSBixia Zheng   // Verify that perm is a permutation of 0..(rank-1).
81320eaa88fSBixia Zheng   std::vector<uint64_t> order(perm, perm + rank);
81420eaa88fSBixia Zheng   std::sort(order.begin(), order.end());
8151e47888dSAart Bik   for (uint64_t i = 0; i < rank; ++i) {
81620eaa88fSBixia Zheng     if (i != order[i]) {
817988d4b0dSAart Bik       fprintf(stderr, "Not a permutation of 0..%" PRIu64 "\n", rank);
81820eaa88fSBixia Zheng       exit(1);
81920eaa88fSBixia Zheng     }
82020eaa88fSBixia Zheng   }
82120eaa88fSBixia Zheng 
82220eaa88fSBixia Zheng   // Verify that the sparsity values are supported.
8231e47888dSAart Bik   for (uint64_t i = 0; i < rank; ++i) {
82420eaa88fSBixia Zheng     if (sparsity[i] != DimLevelType::kDense &&
82520eaa88fSBixia Zheng         sparsity[i] != DimLevelType::kCompressed) {
82620eaa88fSBixia Zheng       fprintf(stderr, "Unsupported sparsity value %d\n",
82720eaa88fSBixia Zheng               static_cast<int>(sparsity[i]));
82820eaa88fSBixia Zheng       exit(1);
82920eaa88fSBixia Zheng     }
83020eaa88fSBixia Zheng   }
83120eaa88fSBixia Zheng #endif
83220eaa88fSBixia Zheng 
8336438783fSAart Bik   // Convert external format to internal COO.
83463bdcaf9Swren romano   auto *coo = SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm, nse);
8356438783fSAart Bik   std::vector<uint64_t> idx(rank);
8366438783fSAart Bik   for (uint64_t i = 0, base = 0; i < nse; i++) {
8376438783fSAart Bik     for (uint64_t r = 0; r < rank; r++)
838d8b229a1SAart Bik       idx[perm[r]] = indices[base + r];
83963bdcaf9Swren romano     coo->add(idx, values[i]);
8406438783fSAart Bik     base += rank;
8416438783fSAart Bik   }
8426438783fSAart Bik   // Return sparse tensor storage format as opaque pointer.
84363bdcaf9Swren romano   auto *tensor = SparseTensorStorage<uint64_t, uint64_t, V>::newSparseTensor(
84463bdcaf9Swren romano       rank, shape, perm, sparsity, coo);
84563bdcaf9Swren romano   delete coo;
84663bdcaf9Swren romano   return tensor;
8476438783fSAart Bik }
8486438783fSAart Bik 
8496438783fSAart Bik /// Converts a sparse tensor to an external COO-flavored format.
8506438783fSAart Bik template <typename V>
85146bdacaaSwren romano static void fromMLIRSparseTensor(void *tensor, uint64_t *pRank, uint64_t *pNse,
85246bdacaaSwren romano                                  uint64_t **pShape, V **pValues,
85346bdacaaSwren romano                                  uint64_t **pIndices) {
8546438783fSAart Bik   auto sparseTensor =
8556438783fSAart Bik       static_cast<SparseTensorStorage<uint64_t, uint64_t, V> *>(tensor);
8566438783fSAart Bik   uint64_t rank = sparseTensor->getRank();
8576438783fSAart Bik   std::vector<uint64_t> perm(rank);
8586438783fSAart Bik   std::iota(perm.begin(), perm.end(), 0);
8596438783fSAart Bik   SparseTensorCOO<V> *coo = sparseTensor->toCOO(perm.data());
8606438783fSAart Bik 
8616438783fSAart Bik   const std::vector<Element<V>> &elements = coo->getElements();
8626438783fSAart Bik   uint64_t nse = elements.size();
8636438783fSAart Bik 
8646438783fSAart Bik   uint64_t *shape = new uint64_t[rank];
8656438783fSAart Bik   for (uint64_t i = 0; i < rank; i++)
8666438783fSAart Bik     shape[i] = coo->getSizes()[i];
8676438783fSAart Bik 
8686438783fSAart Bik   V *values = new V[nse];
8696438783fSAart Bik   uint64_t *indices = new uint64_t[rank * nse];
8706438783fSAart Bik 
8716438783fSAart Bik   for (uint64_t i = 0, base = 0; i < nse; i++) {
8726438783fSAart Bik     values[i] = elements[i].value;
8736438783fSAart Bik     for (uint64_t j = 0; j < rank; j++)
8746438783fSAart Bik       indices[base + j] = elements[i].indices[j];
8756438783fSAart Bik     base += rank;
8766438783fSAart Bik   }
8776438783fSAart Bik 
8786438783fSAart Bik   delete coo;
8796438783fSAart Bik   *pRank = rank;
8806438783fSAart Bik   *pNse = nse;
8816438783fSAart Bik   *pShape = shape;
8826438783fSAart Bik   *pValues = values;
8836438783fSAart Bik   *pIndices = indices;
884efa15f41SAart Bik }
885efa15f41SAart Bik 
886be0a7e9fSMehdi Amini } // namespace
8878a91bc7bSHarrietAkot 
8888a91bc7bSHarrietAkot extern "C" {
8898a91bc7bSHarrietAkot 
8908a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
8918a91bc7bSHarrietAkot //
8928a91bc7bSHarrietAkot // Public API with methods that operate on MLIR buffers (memrefs) to interact
8938a91bc7bSHarrietAkot // with sparse tensors, which are only visible as opaque pointers externally.
8948a91bc7bSHarrietAkot // These methods should be used exclusively by MLIR compiler-generated code.
8958a91bc7bSHarrietAkot //
8968a91bc7bSHarrietAkot // Some macro magic is used to generate implementations for all required type
8978a91bc7bSHarrietAkot // combinations that can be called from MLIR compiler-generated code.
8988a91bc7bSHarrietAkot //
8998a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
9008a91bc7bSHarrietAkot 
9018a91bc7bSHarrietAkot #define CASE(p, i, v, P, I, V)                                                 \
9028a91bc7bSHarrietAkot   if (ptrTp == (p) && indTp == (i) && valTp == (v)) {                          \
90363bdcaf9Swren romano     SparseTensorCOO<V> *coo = nullptr;                                         \
904845561ecSwren romano     if (action <= Action::kFromCOO) {                                          \
905845561ecSwren romano       if (action == Action::kFromFile) {                                       \
9068a91bc7bSHarrietAkot         char *filename = static_cast<char *>(ptr);                             \
90763bdcaf9Swren romano         coo = openSparseTensorCOO<V>(filename, rank, shape, perm);             \
908845561ecSwren romano       } else if (action == Action::kFromCOO) {                                 \
90963bdcaf9Swren romano         coo = static_cast<SparseTensorCOO<V> *>(ptr);                          \
9108a91bc7bSHarrietAkot       } else {                                                                 \
911845561ecSwren romano         assert(action == Action::kEmpty);                                      \
9128a91bc7bSHarrietAkot       }                                                                        \
91363bdcaf9Swren romano       auto *tensor = SparseTensorStorage<P, I, V>::newSparseTensor(            \
91463bdcaf9Swren romano           rank, shape, perm, sparsity, coo);                                   \
91563bdcaf9Swren romano       if (action == Action::kFromFile)                                         \
91663bdcaf9Swren romano         delete coo;                                                            \
91763bdcaf9Swren romano       return tensor;                                                           \
918bb56c2b3SMehdi Amini     }                                                                          \
919bb56c2b3SMehdi Amini     if (action == Action::kEmptyCOO)                                           \
920d83a7068Swren romano       return SparseTensorCOO<V>::newSparseTensorCOO(rank, shape, perm);        \
92163bdcaf9Swren romano     coo = static_cast<SparseTensorStorage<P, I, V> *>(ptr)->toCOO(perm);       \
922845561ecSwren romano     if (action == Action::kToIterator) {                                       \
92363bdcaf9Swren romano       coo->startIterator();                                                    \
9248a91bc7bSHarrietAkot     } else {                                                                   \
925845561ecSwren romano       assert(action == Action::kToCOO);                                        \
9268a91bc7bSHarrietAkot     }                                                                          \
92763bdcaf9Swren romano     return coo;                                                                \
9288a91bc7bSHarrietAkot   }
9298a91bc7bSHarrietAkot 
930845561ecSwren romano #define CASE_SECSAME(p, v, P, V) CASE(p, p, v, P, P, V)
931845561ecSwren romano 
9328a91bc7bSHarrietAkot #define IMPL_SPARSEVALUES(NAME, TYPE, LIB)                                     \
9338a91bc7bSHarrietAkot   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor) {    \
9344f2ec7f9SAart Bik     assert(ref &&tensor);                                                      \
9358a91bc7bSHarrietAkot     std::vector<TYPE> *v;                                                      \
9368a91bc7bSHarrietAkot     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v);                   \
9378a91bc7bSHarrietAkot     ref->basePtr = ref->data = v->data();                                      \
9388a91bc7bSHarrietAkot     ref->offset = 0;                                                           \
9398a91bc7bSHarrietAkot     ref->sizes[0] = v->size();                                                 \
9408a91bc7bSHarrietAkot     ref->strides[0] = 1;                                                       \
9418a91bc7bSHarrietAkot   }
9428a91bc7bSHarrietAkot 
9438a91bc7bSHarrietAkot #define IMPL_GETOVERHEAD(NAME, TYPE, LIB)                                      \
9448a91bc7bSHarrietAkot   void _mlir_ciface_##NAME(StridedMemRefType<TYPE, 1> *ref, void *tensor,      \
945d2215e79SRainer Orth                            index_type d) {                                     \
9464f2ec7f9SAart Bik     assert(ref &&tensor);                                                      \
9478a91bc7bSHarrietAkot     std::vector<TYPE> *v;                                                      \
9488a91bc7bSHarrietAkot     static_cast<SparseTensorStorageBase *>(tensor)->LIB(&v, d);                \
9498a91bc7bSHarrietAkot     ref->basePtr = ref->data = v->data();                                      \
9508a91bc7bSHarrietAkot     ref->offset = 0;                                                           \
9518a91bc7bSHarrietAkot     ref->sizes[0] = v->size();                                                 \
9528a91bc7bSHarrietAkot     ref->strides[0] = 1;                                                       \
9538a91bc7bSHarrietAkot   }
9548a91bc7bSHarrietAkot 
9558a91bc7bSHarrietAkot #define IMPL_ADDELT(NAME, TYPE)                                                \
9568a91bc7bSHarrietAkot   void *_mlir_ciface_##NAME(void *tensor, TYPE value,                          \
957d2215e79SRainer Orth                             StridedMemRefType<index_type, 1> *iref,            \
958d2215e79SRainer Orth                             StridedMemRefType<index_type, 1> *pref) {          \
9594f2ec7f9SAart Bik     assert(tensor &&iref &&pref);                                              \
9608a91bc7bSHarrietAkot     assert(iref->strides[0] == 1 && pref->strides[0] == 1);                    \
9618a91bc7bSHarrietAkot     assert(iref->sizes[0] == pref->sizes[0]);                                  \
962d2215e79SRainer Orth     const index_type *indx = iref->data + iref->offset;                        \
963d2215e79SRainer Orth     const index_type *perm = pref->data + pref->offset;                        \
9648a91bc7bSHarrietAkot     uint64_t isize = iref->sizes[0];                                           \
965d2215e79SRainer Orth     std::vector<index_type> indices(isize);                                    \
9668a91bc7bSHarrietAkot     for (uint64_t r = 0; r < isize; r++)                                       \
9678a91bc7bSHarrietAkot       indices[perm[r]] = indx[r];                                              \
9688a91bc7bSHarrietAkot     static_cast<SparseTensorCOO<TYPE> *>(tensor)->add(indices, value);         \
9698a91bc7bSHarrietAkot     return tensor;                                                             \
9708a91bc7bSHarrietAkot   }
9718a91bc7bSHarrietAkot 
9728a91bc7bSHarrietAkot #define IMPL_GETNEXT(NAME, V)                                                  \
973d2215e79SRainer Orth   bool _mlir_ciface_##NAME(void *tensor,                                       \
974d2215e79SRainer Orth                            StridedMemRefType<index_type, 1> *iref,             \
9758a91bc7bSHarrietAkot                            StridedMemRefType<V, 0> *vref) {                    \
9764f2ec7f9SAart Bik     assert(tensor &&iref &&vref);                                              \
9778a91bc7bSHarrietAkot     assert(iref->strides[0] == 1);                                             \
978d2215e79SRainer Orth     index_type *indx = iref->data + iref->offset;                              \
979c9f2beffSMehdi Amini     V *value = vref->data + vref->offset;                                      \
9808a91bc7bSHarrietAkot     const uint64_t isize = iref->sizes[0];                                     \
9818a91bc7bSHarrietAkot     auto iter = static_cast<SparseTensorCOO<V> *>(tensor);                     \
9828a91bc7bSHarrietAkot     const Element<V> *elem = iter->getNext();                                  \
98363bdcaf9Swren romano     if (elem == nullptr)                                                       \
9848a91bc7bSHarrietAkot       return false;                                                            \
9858a91bc7bSHarrietAkot     for (uint64_t r = 0; r < isize; r++)                                       \
9868a91bc7bSHarrietAkot       indx[r] = elem->indices[r];                                              \
9878a91bc7bSHarrietAkot     *value = elem->value;                                                      \
9888a91bc7bSHarrietAkot     return true;                                                               \
9898a91bc7bSHarrietAkot   }
9908a91bc7bSHarrietAkot 
991f66e5769SAart Bik #define IMPL_LEXINSERT(NAME, V)                                                \
992d2215e79SRainer Orth   void _mlir_ciface_##NAME(void *tensor,                                       \
993d2215e79SRainer Orth                            StridedMemRefType<index_type, 1> *cref, V val) {    \
9944f2ec7f9SAart Bik     assert(tensor &&cref);                                                     \
995f66e5769SAart Bik     assert(cref->strides[0] == 1);                                             \
996d2215e79SRainer Orth     index_type *cursor = cref->data + cref->offset;                            \
997f66e5769SAart Bik     assert(cursor);                                                            \
998f66e5769SAart Bik     static_cast<SparseTensorStorageBase *>(tensor)->lexInsert(cursor, val);    \
999f66e5769SAart Bik   }
1000f66e5769SAart Bik 
10014f2ec7f9SAart Bik #define IMPL_EXPINSERT(NAME, V)                                                \
10024f2ec7f9SAart Bik   void _mlir_ciface_##NAME(                                                    \
1003d2215e79SRainer Orth       void *tensor, StridedMemRefType<index_type, 1> *cref,                    \
10044f2ec7f9SAart Bik       StridedMemRefType<V, 1> *vref, StridedMemRefType<bool, 1> *fref,         \
1005d2215e79SRainer Orth       StridedMemRefType<index_type, 1> *aref, index_type count) {              \
10064f2ec7f9SAart Bik     assert(tensor &&cref &&vref &&fref &&aref);                                \
10074f2ec7f9SAart Bik     assert(cref->strides[0] == 1);                                             \
10084f2ec7f9SAart Bik     assert(vref->strides[0] == 1);                                             \
10094f2ec7f9SAart Bik     assert(fref->strides[0] == 1);                                             \
10104f2ec7f9SAart Bik     assert(aref->strides[0] == 1);                                             \
10114f2ec7f9SAart Bik     assert(vref->sizes[0] == fref->sizes[0]);                                  \
1012d2215e79SRainer Orth     index_type *cursor = cref->data + cref->offset;                            \
1013c9f2beffSMehdi Amini     V *values = vref->data + vref->offset;                                     \
10144f2ec7f9SAart Bik     bool *filled = fref->data + fref->offset;                                  \
1015d2215e79SRainer Orth     index_type *added = aref->data + aref->offset;                             \
10164f2ec7f9SAart Bik     static_cast<SparseTensorStorageBase *>(tensor)->expInsert(                 \
10174f2ec7f9SAart Bik         cursor, values, filled, added, count);                                 \
10184f2ec7f9SAart Bik   }
10194f2ec7f9SAart Bik 
1020d2215e79SRainer Orth // Assume index_type is in fact uint64_t, so that _mlir_ciface_newSparseTensor
1021bc04a470Swren romano // can safely rewrite kIndex to kU64.  We make this assertion to guarantee
1022bc04a470Swren romano // that this file cannot get out of sync with its header.
1023d2215e79SRainer Orth static_assert(std::is_same<index_type, uint64_t>::value,
1024d2215e79SRainer Orth               "Expected index_type == uint64_t");
1025bc04a470Swren romano 
10268a91bc7bSHarrietAkot /// Constructs a new sparse tensor. This is the "swiss army knife"
10278a91bc7bSHarrietAkot /// method for materializing sparse tensors into the computation.
10288a91bc7bSHarrietAkot ///
1029845561ecSwren romano /// Action:
10308a91bc7bSHarrietAkot /// kEmpty = returns empty storage to fill later
10318a91bc7bSHarrietAkot /// kFromFile = returns storage, where ptr contains filename to read
10328a91bc7bSHarrietAkot /// kFromCOO = returns storage, where ptr contains coordinate scheme to assign
10338a91bc7bSHarrietAkot /// kEmptyCOO = returns empty coordinate scheme to fill and use with kFromCOO
10348a91bc7bSHarrietAkot /// kToCOO = returns coordinate scheme from storage in ptr to use with kFromCOO
1035845561ecSwren romano /// kToIterator = returns iterator from storage in ptr (call getNext() to use)
10368a91bc7bSHarrietAkot void *
1037845561ecSwren romano _mlir_ciface_newSparseTensor(StridedMemRefType<DimLevelType, 1> *aref, // NOLINT
1038d2215e79SRainer Orth                              StridedMemRefType<index_type, 1> *sref,
1039d2215e79SRainer Orth                              StridedMemRefType<index_type, 1> *pref,
1040845561ecSwren romano                              OverheadType ptrTp, OverheadType indTp,
1041845561ecSwren romano                              PrimaryType valTp, Action action, void *ptr) {
10428a91bc7bSHarrietAkot   assert(aref && sref && pref);
10438a91bc7bSHarrietAkot   assert(aref->strides[0] == 1 && sref->strides[0] == 1 &&
10448a91bc7bSHarrietAkot          pref->strides[0] == 1);
10458a91bc7bSHarrietAkot   assert(aref->sizes[0] == sref->sizes[0] && sref->sizes[0] == pref->sizes[0]);
1046845561ecSwren romano   const DimLevelType *sparsity = aref->data + aref->offset;
1047d83a7068Swren romano   const index_type *shape = sref->data + sref->offset;
1048d2215e79SRainer Orth   const index_type *perm = pref->data + pref->offset;
10498a91bc7bSHarrietAkot   uint64_t rank = aref->sizes[0];
10508a91bc7bSHarrietAkot 
1051bc04a470Swren romano   // Rewrite kIndex to kU64, to avoid introducing a bunch of new cases.
1052bc04a470Swren romano   // This is safe because of the static_assert above.
1053bc04a470Swren romano   if (ptrTp == OverheadType::kIndex)
1054bc04a470Swren romano     ptrTp = OverheadType::kU64;
1055bc04a470Swren romano   if (indTp == OverheadType::kIndex)
1056bc04a470Swren romano     indTp = OverheadType::kU64;
1057bc04a470Swren romano 
10588a91bc7bSHarrietAkot   // Double matrices with all combinations of overhead storage.
1059845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF64, uint64_t,
1060845561ecSwren romano        uint64_t, double);
1061845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF64, uint64_t,
1062845561ecSwren romano        uint32_t, double);
1063845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF64, uint64_t,
1064845561ecSwren romano        uint16_t, double);
1065845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF64, uint64_t,
1066845561ecSwren romano        uint8_t, double);
1067845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF64, uint32_t,
1068845561ecSwren romano        uint64_t, double);
1069845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF64, uint32_t,
1070845561ecSwren romano        uint32_t, double);
1071845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF64, uint32_t,
1072845561ecSwren romano        uint16_t, double);
1073845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF64, uint32_t,
1074845561ecSwren romano        uint8_t, double);
1075845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF64, uint16_t,
1076845561ecSwren romano        uint64_t, double);
1077845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF64, uint16_t,
1078845561ecSwren romano        uint32_t, double);
1079845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF64, uint16_t,
1080845561ecSwren romano        uint16_t, double);
1081845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF64, uint16_t,
1082845561ecSwren romano        uint8_t, double);
1083845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF64, uint8_t,
1084845561ecSwren romano        uint64_t, double);
1085845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF64, uint8_t,
1086845561ecSwren romano        uint32_t, double);
1087845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF64, uint8_t,
1088845561ecSwren romano        uint16_t, double);
1089845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF64, uint8_t,
1090845561ecSwren romano        uint8_t, double);
10918a91bc7bSHarrietAkot 
10928a91bc7bSHarrietAkot   // Float matrices with all combinations of overhead storage.
1093845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU64, PrimaryType::kF32, uint64_t,
1094845561ecSwren romano        uint64_t, float);
1095845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU32, PrimaryType::kF32, uint64_t,
1096845561ecSwren romano        uint32_t, float);
1097845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU16, PrimaryType::kF32, uint64_t,
1098845561ecSwren romano        uint16_t, float);
1099845561ecSwren romano   CASE(OverheadType::kU64, OverheadType::kU8, PrimaryType::kF32, uint64_t,
1100845561ecSwren romano        uint8_t, float);
1101845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU64, PrimaryType::kF32, uint32_t,
1102845561ecSwren romano        uint64_t, float);
1103845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU32, PrimaryType::kF32, uint32_t,
1104845561ecSwren romano        uint32_t, float);
1105845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU16, PrimaryType::kF32, uint32_t,
1106845561ecSwren romano        uint16_t, float);
1107845561ecSwren romano   CASE(OverheadType::kU32, OverheadType::kU8, PrimaryType::kF32, uint32_t,
1108845561ecSwren romano        uint8_t, float);
1109845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU64, PrimaryType::kF32, uint16_t,
1110845561ecSwren romano        uint64_t, float);
1111845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU32, PrimaryType::kF32, uint16_t,
1112845561ecSwren romano        uint32_t, float);
1113845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU16, PrimaryType::kF32, uint16_t,
1114845561ecSwren romano        uint16_t, float);
1115845561ecSwren romano   CASE(OverheadType::kU16, OverheadType::kU8, PrimaryType::kF32, uint16_t,
1116845561ecSwren romano        uint8_t, float);
1117845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU64, PrimaryType::kF32, uint8_t,
1118845561ecSwren romano        uint64_t, float);
1119845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU32, PrimaryType::kF32, uint8_t,
1120845561ecSwren romano        uint32_t, float);
1121845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU16, PrimaryType::kF32, uint8_t,
1122845561ecSwren romano        uint16_t, float);
1123845561ecSwren romano   CASE(OverheadType::kU8, OverheadType::kU8, PrimaryType::kF32, uint8_t,
1124845561ecSwren romano        uint8_t, float);
11258a91bc7bSHarrietAkot 
1126845561ecSwren romano   // Integral matrices with both overheads of the same type.
1127845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI64, uint64_t, int64_t);
1128845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI32, uint64_t, int32_t);
1129845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI16, uint64_t, int16_t);
1130845561ecSwren romano   CASE_SECSAME(OverheadType::kU64, PrimaryType::kI8, uint64_t, int8_t);
1131845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI32, uint32_t, int32_t);
1132845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI16, uint32_t, int16_t);
1133845561ecSwren romano   CASE_SECSAME(OverheadType::kU32, PrimaryType::kI8, uint32_t, int8_t);
1134845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI32, uint16_t, int32_t);
1135845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI16, uint16_t, int16_t);
1136845561ecSwren romano   CASE_SECSAME(OverheadType::kU16, PrimaryType::kI8, uint16_t, int8_t);
1137845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI32, uint8_t, int32_t);
1138845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI16, uint8_t, int16_t);
1139845561ecSwren romano   CASE_SECSAME(OverheadType::kU8, PrimaryType::kI8, uint8_t, int8_t);
11408a91bc7bSHarrietAkot 
11418a91bc7bSHarrietAkot   // Unsupported case (add above if needed).
11428a91bc7bSHarrietAkot   fputs("unsupported combination of types\n", stderr);
11438a91bc7bSHarrietAkot   exit(1);
11448a91bc7bSHarrietAkot }
11458a91bc7bSHarrietAkot 
11468a91bc7bSHarrietAkot /// Methods that provide direct access to pointers.
1147d2215e79SRainer Orth IMPL_GETOVERHEAD(sparsePointers, index_type, getPointers)
11488a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers64, uint64_t, getPointers)
11498a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers32, uint32_t, getPointers)
11508a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers16, uint16_t, getPointers)
11518a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparsePointers8, uint8_t, getPointers)
11528a91bc7bSHarrietAkot 
11538a91bc7bSHarrietAkot /// Methods that provide direct access to indices.
1154d2215e79SRainer Orth IMPL_GETOVERHEAD(sparseIndices, index_type, getIndices)
11558a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices64, uint64_t, getIndices)
11568a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices32, uint32_t, getIndices)
11578a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices16, uint16_t, getIndices)
11588a91bc7bSHarrietAkot IMPL_GETOVERHEAD(sparseIndices8, uint8_t, getIndices)
11598a91bc7bSHarrietAkot 
11608a91bc7bSHarrietAkot /// Methods that provide direct access to values.
11618a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesF64, double, getValues)
11628a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesF32, float, getValues)
11638a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI64, int64_t, getValues)
11648a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI32, int32_t, getValues)
11658a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI16, int16_t, getValues)
11668a91bc7bSHarrietAkot IMPL_SPARSEVALUES(sparseValuesI8, int8_t, getValues)
11678a91bc7bSHarrietAkot 
11688a91bc7bSHarrietAkot /// Helper to add value to coordinate scheme, one per value type.
11698a91bc7bSHarrietAkot IMPL_ADDELT(addEltF64, double)
11708a91bc7bSHarrietAkot IMPL_ADDELT(addEltF32, float)
11718a91bc7bSHarrietAkot IMPL_ADDELT(addEltI64, int64_t)
11728a91bc7bSHarrietAkot IMPL_ADDELT(addEltI32, int32_t)
11738a91bc7bSHarrietAkot IMPL_ADDELT(addEltI16, int16_t)
11748a91bc7bSHarrietAkot IMPL_ADDELT(addEltI8, int8_t)
11758a91bc7bSHarrietAkot 
11768a91bc7bSHarrietAkot /// Helper to enumerate elements of coordinate scheme, one per value type.
11778a91bc7bSHarrietAkot IMPL_GETNEXT(getNextF64, double)
11788a91bc7bSHarrietAkot IMPL_GETNEXT(getNextF32, float)
11798a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI64, int64_t)
11808a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI32, int32_t)
11818a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI16, int16_t)
11828a91bc7bSHarrietAkot IMPL_GETNEXT(getNextI8, int8_t)
11838a91bc7bSHarrietAkot 
11846438783fSAart Bik /// Insert elements in lexicographical index order, one per value type.
1185f66e5769SAart Bik IMPL_LEXINSERT(lexInsertF64, double)
1186f66e5769SAart Bik IMPL_LEXINSERT(lexInsertF32, float)
1187f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI64, int64_t)
1188f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI32, int32_t)
1189f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI16, int16_t)
1190f66e5769SAart Bik IMPL_LEXINSERT(lexInsertI8, int8_t)
1191f66e5769SAart Bik 
11926438783fSAart Bik /// Insert using expansion, one per value type.
11934f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertF64, double)
11944f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertF32, float)
11954f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI64, int64_t)
11964f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI32, int32_t)
11974f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI16, int16_t)
11984f2ec7f9SAart Bik IMPL_EXPINSERT(expInsertI8, int8_t)
11994f2ec7f9SAart Bik 
12008a91bc7bSHarrietAkot #undef CASE
12018a91bc7bSHarrietAkot #undef IMPL_SPARSEVALUES
12028a91bc7bSHarrietAkot #undef IMPL_GETOVERHEAD
12038a91bc7bSHarrietAkot #undef IMPL_ADDELT
12048a91bc7bSHarrietAkot #undef IMPL_GETNEXT
12054f2ec7f9SAart Bik #undef IMPL_LEXINSERT
12064f2ec7f9SAart Bik #undef IMPL_EXPINSERT
12076438783fSAart Bik 
12086438783fSAart Bik /// Output a sparse tensor, one per value type.
12096438783fSAart Bik void outSparseTensorF64(void *tensor, void *dest, bool sort) {
12106438783fSAart Bik   return outSparseTensor<double>(tensor, dest, sort);
12116438783fSAart Bik }
12126438783fSAart Bik void outSparseTensorF32(void *tensor, void *dest, bool sort) {
12136438783fSAart Bik   return outSparseTensor<float>(tensor, dest, sort);
12146438783fSAart Bik }
12156438783fSAart Bik void outSparseTensorI64(void *tensor, void *dest, bool sort) {
12166438783fSAart Bik   return outSparseTensor<int64_t>(tensor, dest, sort);
12176438783fSAart Bik }
12186438783fSAart Bik void outSparseTensorI32(void *tensor, void *dest, bool sort) {
12196438783fSAart Bik   return outSparseTensor<int32_t>(tensor, dest, sort);
12206438783fSAart Bik }
12216438783fSAart Bik void outSparseTensorI16(void *tensor, void *dest, bool sort) {
12226438783fSAart Bik   return outSparseTensor<int16_t>(tensor, dest, sort);
12236438783fSAart Bik }
12246438783fSAart Bik void outSparseTensorI8(void *tensor, void *dest, bool sort) {
12256438783fSAart Bik   return outSparseTensor<int8_t>(tensor, dest, sort);
12266438783fSAart Bik }
12278a91bc7bSHarrietAkot 
12288a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
12298a91bc7bSHarrietAkot //
12308a91bc7bSHarrietAkot // Public API with methods that accept C-style data structures to interact
12318a91bc7bSHarrietAkot // with sparse tensors, which are only visible as opaque pointers externally.
12328a91bc7bSHarrietAkot // These methods can be used both by MLIR compiler-generated code as well as by
12338a91bc7bSHarrietAkot // an external runtime that wants to interact with MLIR compiler-generated code.
12348a91bc7bSHarrietAkot //
12358a91bc7bSHarrietAkot //===----------------------------------------------------------------------===//
12368a91bc7bSHarrietAkot 
12378a91bc7bSHarrietAkot /// Helper method to read a sparse tensor filename from the environment,
12388a91bc7bSHarrietAkot /// defined with the naming convention ${TENSOR0}, ${TENSOR1}, etc.
1239d2215e79SRainer Orth char *getTensorFilename(index_type id) {
12408a91bc7bSHarrietAkot   char var[80];
12418a91bc7bSHarrietAkot   sprintf(var, "TENSOR%" PRIu64, id);
12428a91bc7bSHarrietAkot   char *env = getenv(var);
12433734c078Swren romano   if (!env) {
12443734c078Swren romano     fprintf(stderr, "Environment variable %s is not set\n", var);
12453734c078Swren romano     exit(1);
12463734c078Swren romano   }
12478a91bc7bSHarrietAkot   return env;
12488a91bc7bSHarrietAkot }
12498a91bc7bSHarrietAkot 
12508a91bc7bSHarrietAkot /// Returns size of sparse tensor in given dimension.
1251d2215e79SRainer Orth index_type sparseDimSize(void *tensor, index_type d) {
12528a91bc7bSHarrietAkot   return static_cast<SparseTensorStorageBase *>(tensor)->getDimSize(d);
12538a91bc7bSHarrietAkot }
12548a91bc7bSHarrietAkot 
1255f66e5769SAart Bik /// Finalizes lexicographic insertions.
1256f66e5769SAart Bik void endInsert(void *tensor) {
1257f66e5769SAart Bik   return static_cast<SparseTensorStorageBase *>(tensor)->endInsert();
1258f66e5769SAart Bik }
1259f66e5769SAart Bik 
12608a91bc7bSHarrietAkot /// Releases sparse tensor storage.
12618a91bc7bSHarrietAkot void delSparseTensor(void *tensor) {
12628a91bc7bSHarrietAkot   delete static_cast<SparseTensorStorageBase *>(tensor);
12638a91bc7bSHarrietAkot }
12648a91bc7bSHarrietAkot 
126563bdcaf9Swren romano /// Releases sparse tensor coordinate scheme.
126663bdcaf9Swren romano #define IMPL_DELCOO(VNAME, V)                                                  \
126763bdcaf9Swren romano   void delSparseTensorCOO##VNAME(void *coo) {                                  \
126863bdcaf9Swren romano     delete static_cast<SparseTensorCOO<V> *>(coo);                             \
126963bdcaf9Swren romano   }
127063bdcaf9Swren romano IMPL_DELCOO(F64, double)
127163bdcaf9Swren romano IMPL_DELCOO(F32, float)
127263bdcaf9Swren romano IMPL_DELCOO(I64, int64_t)
127363bdcaf9Swren romano IMPL_DELCOO(I32, int32_t)
127463bdcaf9Swren romano IMPL_DELCOO(I16, int16_t)
127563bdcaf9Swren romano IMPL_DELCOO(I8, int8_t)
127663bdcaf9Swren romano #undef IMPL_DELCOO
127763bdcaf9Swren romano 
12788a91bc7bSHarrietAkot /// Initializes sparse tensor from a COO-flavored format expressed using C-style
12798a91bc7bSHarrietAkot /// data structures. The expected parameters are:
12808a91bc7bSHarrietAkot ///
12818a91bc7bSHarrietAkot ///   rank:    rank of tensor
12828a91bc7bSHarrietAkot ///   nse:     number of specified elements (usually the nonzeros)
12838a91bc7bSHarrietAkot ///   shape:   array with dimension size for each rank
12848a91bc7bSHarrietAkot ///   values:  a "nse" array with values for all specified elements
12858a91bc7bSHarrietAkot ///   indices: a flat "nse x rank" array with indices for all specified elements
128620eaa88fSBixia Zheng ///   perm:    the permutation of the dimensions in the storage
128720eaa88fSBixia Zheng ///   sparse:  the sparsity for the dimensions
12888a91bc7bSHarrietAkot ///
12898a91bc7bSHarrietAkot /// For example, the sparse matrix
12908a91bc7bSHarrietAkot ///     | 1.0 0.0 0.0 |
12918a91bc7bSHarrietAkot ///     | 0.0 5.0 3.0 |
12928a91bc7bSHarrietAkot /// can be passed as
12938a91bc7bSHarrietAkot ///      rank    = 2
12948a91bc7bSHarrietAkot ///      nse     = 3
12958a91bc7bSHarrietAkot ///      shape   = [2, 3]
12968a91bc7bSHarrietAkot ///      values  = [1.0, 5.0, 3.0]
12978a91bc7bSHarrietAkot ///      indices = [ 0, 0,  1, 1,  1, 2]
12988a91bc7bSHarrietAkot //
129920eaa88fSBixia Zheng // TODO: generalize beyond 64-bit indices.
13008a91bc7bSHarrietAkot //
13016438783fSAart Bik void *convertToMLIRSparseTensorF64(uint64_t rank, uint64_t nse, uint64_t *shape,
130220eaa88fSBixia Zheng                                    double *values, uint64_t *indices,
130320eaa88fSBixia Zheng                                    uint64_t *perm, uint8_t *sparse) {
130420eaa88fSBixia Zheng   return toMLIRSparseTensor<double>(rank, nse, shape, values, indices, perm,
130520eaa88fSBixia Zheng                                     sparse);
13068a91bc7bSHarrietAkot }
13076438783fSAart Bik void *convertToMLIRSparseTensorF32(uint64_t rank, uint64_t nse, uint64_t *shape,
130820eaa88fSBixia Zheng                                    float *values, uint64_t *indices,
130920eaa88fSBixia Zheng                                    uint64_t *perm, uint8_t *sparse) {
131020eaa88fSBixia Zheng   return toMLIRSparseTensor<float>(rank, nse, shape, values, indices, perm,
131120eaa88fSBixia Zheng                                    sparse);
13128a91bc7bSHarrietAkot }
13138a91bc7bSHarrietAkot 
13142f49e6b0SBixia Zheng /// Converts a sparse tensor to COO-flavored format expressed using C-style
13152f49e6b0SBixia Zheng /// data structures. The expected output parameters are pointers for these
13162f49e6b0SBixia Zheng /// values:
13172f49e6b0SBixia Zheng ///
13182f49e6b0SBixia Zheng ///   rank:    rank of tensor
13192f49e6b0SBixia Zheng ///   nse:     number of specified elements (usually the nonzeros)
13202f49e6b0SBixia Zheng ///   shape:   array with dimension size for each rank
13212f49e6b0SBixia Zheng ///   values:  a "nse" array with values for all specified elements
13222f49e6b0SBixia Zheng ///   indices: a flat "nse x rank" array with indices for all specified elements
13232f49e6b0SBixia Zheng ///
13242f49e6b0SBixia Zheng /// The input is a pointer to SparseTensorStorage<P, I, V>, typically returned
13252f49e6b0SBixia Zheng /// from convertToMLIRSparseTensor.
13262f49e6b0SBixia Zheng ///
13272f49e6b0SBixia Zheng //  TODO: Currently, values are copied from SparseTensorStorage to
13282f49e6b0SBixia Zheng //  SparseTensorCOO, then to the output. We may want to reduce the number of
13292f49e6b0SBixia Zheng //  copies.
13302f49e6b0SBixia Zheng //
13316438783fSAart Bik // TODO: generalize beyond 64-bit indices, no dim ordering, all dimensions
13326438783fSAart Bik // compressed
13332f49e6b0SBixia Zheng //
13346438783fSAart Bik void convertFromMLIRSparseTensorF64(void *tensor, uint64_t *pRank,
13356438783fSAart Bik                                     uint64_t *pNse, uint64_t **pShape,
13366438783fSAart Bik                                     double **pValues, uint64_t **pIndices) {
13376438783fSAart Bik   fromMLIRSparseTensor<double>(tensor, pRank, pNse, pShape, pValues, pIndices);
13382f49e6b0SBixia Zheng }
13396438783fSAart Bik void convertFromMLIRSparseTensorF32(void *tensor, uint64_t *pRank,
13406438783fSAart Bik                                     uint64_t *pNse, uint64_t **pShape,
13416438783fSAart Bik                                     float **pValues, uint64_t **pIndices) {
13426438783fSAart Bik   fromMLIRSparseTensor<float>(tensor, pRank, pNse, pShape, pValues, pIndices);
13432f49e6b0SBixia Zheng }
1344efa15f41SAart Bik 
13458a91bc7bSHarrietAkot } // extern "C"
13468a91bc7bSHarrietAkot 
13478a91bc7bSHarrietAkot #endif // MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
1348