0 | {--
 1 | Copyright (C) 2022  Joel Berkeley
 2 |
 3 | This program is free software: you can redistribute it and/or modify
 4 | it under the terms of the GNU Affero General Public License as published
 5 | by the Free Software Foundation, either version 3 of the License, or
 6 | (at your option) any later version.
 7 |
 8 | This program is distributed in the hope that it will be useful,
 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 | GNU Affero General Public License for more details.
12 |
13 | You should have received a copy of the GNU Affero General Public License
14 | along with this program.  If not, see <https://www.gnu.org/licenses/>.
15 | --}
16 | ||| For internal spidr use only.
17 | module Compiler.LiteralRW
18 |
19 | import Control.Monad.State
20 |
21 | import Compiler.MLIR.IR.MLIRContext
22 | import Compiler.MLIR.IR.Types
23 | import Compiler.MLIR.IR.BuiltinTypes
24 | import Compiler.MLIR.IR.BuiltinAttributes
25 | import Compiler.Array
26 | import Compiler.DType
27 | import Compiler.FFI
28 | import Literal
29 | import DType
30 | import Util
31 |
32 | export
33 | dtypeIsArrayType : (dtype : DType) -> ArrayType (idrisType dtype)
34 | dtypeIsArrayType PRED = %search
35 | dtypeIsArrayType S32  = %search
36 | dtypeIsArrayType S64  = %search
37 | dtypeIsArrayType U32  = %search
38 | dtypeIsArrayType U64  = %search
39 | dtypeIsArrayType F64  = %search
40 |
41 | export
42 | mkDenseElementsAttr :
43 |   HasIO io =>
44 |   MLIRContext ->
45 |   {shape : _} -> {dtype : _} ->
46 |   Literal shape (idrisType dtype) ->
47 |   io DenseElementsAttr
48 | mkDenseElementsAttr ctx lit = do
49 |   type <- RankedTensorType.get shape !(mlirType ctx dtype)
50 |   arr <- let at = dtypeIsArrayType dtype in fromList $ toList lit
51 |   case dtype of
52 |     PRED => DenseElementsAttr.ArrayRef.Bool.get type arr
53 |     S32  => DenseElementsAttr.ArrayRef.Int32.get type arr
54 |     S64  => DenseElementsAttr.ArrayRef.Int64.get type arr
55 |     U32  => DenseElementsAttr.ArrayRef.UInt32.get type arr
56 |     U64  => DenseElementsAttr.ArrayRef.UInt64.get type arr
57 |     F64  => DenseElementsAttr.ArrayRef.Double.get type arr
58 |
59 | export
60 | read : {shape : _} -> (dtype : DType) -> Array (idrisType dtype) -> Literal shape (idrisType dtype)
61 | read dtype arr =
62 |   let arrIndices = evalState Z $ traverse (\() => State.get <* modify S) (pure ())
63 |       at = dtypeIsArrayType dtype
64 |    in Array.get arr <$> arrIndices
65 |