-
Notifications
You must be signed in to change notification settings - Fork 164
/
GenericC.hs
2145 lines (1906 loc) · 69.1 KB
/
GenericC.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TupleSections #-}
-- | C code generator framework.
module Futhark.CodeGen.Backends.GenericC
( compileProg,
CParts (..),
asLibrary,
asExecutable,
asServer,
-- * Pluggable compiler
Operations (..),
defaultOperations,
OpCompiler,
ErrorCompiler,
CallCompiler,
PointerQuals,
MemoryType,
WriteScalar,
writeScalarPointerWithQuals,
ReadScalar,
readScalarPointerWithQuals,
Allocate,
Deallocate,
Copy,
StaticArray,
-- * Monadic compiler interface
CompilerM,
CompilerState (compUserState, compNameSrc),
getUserState,
modifyUserState,
contextContents,
contextFinalInits,
runCompilerM,
inNewFunction,
cachingMemory,
blockScope,
compileFun,
compileCode,
compileExp,
compilePrimExp,
compileExpToName,
rawMem,
item,
items,
stm,
stms,
decl,
atInit,
headerDecl,
publicDef,
publicDef_,
profileReport,
onClear,
HeaderSection (..),
libDecl,
earlyDecl,
publicName,
contextType,
contextField,
memToCType,
cacheMem,
fatMemory,
rawMemCType,
cproduct,
fatMemType,
-- * Building Blocks
primTypeToCType,
intTypeToCType,
copyMemoryDefaultSpace,
)
where
import Control.Monad.Identity
import Control.Monad.Reader
import Control.Monad.State
import Data.Bifunctor (first)
import qualified Data.DList as DL
import Data.Loc
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.Text as T
import Futhark.CodeGen.Backends.GenericC.CLI (cliDefs)
import Futhark.CodeGen.Backends.GenericC.Options
import Futhark.CodeGen.Backends.GenericC.Server (serverDefs)
import Futhark.CodeGen.Backends.SimpleRep
import Futhark.CodeGen.ImpCode
import Futhark.CodeGen.RTS.C (halfH, lockH, timingH, utilH)
import Futhark.IR.Prop (isBuiltInFunction)
import Futhark.MonadFreshNames
import Futhark.Util.Pretty (prettyText)
import qualified Language.C.Quote.OpenCL as C
import qualified Language.C.Syntax as C
import NeatInterpolation (untrimming)
-- How public an array type definition sould be. Public types show up
-- in the generated API, while private types are used only to
-- implement the members of opaques.
data Publicness = Private | Public
deriving (Eq, Ord, Show)
type ArrayType = (Space, Signedness, PrimType, Int)
data CompilerState s = CompilerState
{ compArrayTypes :: M.Map ArrayType Publicness,
compOpaqueTypes :: M.Map String [ValueDesc],
compEarlyDecls :: DL.DList C.Definition,
compInit :: [C.Stm],
compNameSrc :: VNameSource,
compUserState :: s,
compHeaderDecls :: M.Map HeaderSection (DL.DList C.Definition),
compLibDecls :: DL.DList C.Definition,
compCtxFields :: DL.DList (C.Id, C.Type, Maybe C.Exp),
compProfileItems :: DL.DList C.BlockItem,
compClearItems :: DL.DList C.BlockItem,
compDeclaredMem :: [(VName, Space)],
compItems :: DL.DList C.BlockItem
}
newCompilerState :: VNameSource -> s -> CompilerState s
newCompilerState src s =
CompilerState
{ compArrayTypes = mempty,
compOpaqueTypes = mempty,
compEarlyDecls = mempty,
compInit = [],
compNameSrc = src,
compUserState = s,
compHeaderDecls = mempty,
compLibDecls = mempty,
compCtxFields = mempty,
compProfileItems = mempty,
compClearItems = mempty,
compDeclaredMem = mempty,
compItems = mempty
}
-- | In which part of the header file we put the declaration. This is
-- to ensure that the header file remains structured and readable.
data HeaderSection
= ArrayDecl String
| OpaqueDecl String
| EntryDecl
| MiscDecl
| InitDecl
deriving (Eq, Ord)
-- | A substitute expression compiler, tried before the main
-- compilation function.
type OpCompiler op s = op -> CompilerM op s ()
type ErrorCompiler op s = ErrorMsg Exp -> String -> CompilerM op s ()
-- | The address space qualifiers for a pointer of the given type with
-- the given annotation.
type PointerQuals op s = String -> CompilerM op s [C.TypeQual]
-- | The type of a memory block in the given memory space.
type MemoryType op s = SpaceId -> CompilerM op s C.Type
-- | Write a scalar to the given memory block with the given element
-- index and in the given memory space.
type WriteScalar op s =
C.Exp -> C.Exp -> C.Type -> SpaceId -> Volatility -> C.Exp -> CompilerM op s ()
-- | Read a scalar from the given memory block with the given element
-- index and in the given memory space.
type ReadScalar op s =
C.Exp -> C.Exp -> C.Type -> SpaceId -> Volatility -> CompilerM op s C.Exp
-- | Allocate a memory block of the given size and with the given tag
-- in the given memory space, saving a reference in the given variable
-- name.
type Allocate op s =
C.Exp ->
C.Exp ->
C.Exp ->
SpaceId ->
CompilerM op s ()
-- | De-allocate the given memory block with the given tag, which is
-- in the given memory space.
type Deallocate op s = C.Exp -> C.Exp -> SpaceId -> CompilerM op s ()
-- | Create a static array of values - initialised at load time.
type StaticArray op s = VName -> SpaceId -> PrimType -> ArrayContents -> CompilerM op s ()
-- | Copy from one memory block to another.
type Copy op s =
C.Exp ->
C.Exp ->
Space ->
C.Exp ->
C.Exp ->
Space ->
C.Exp ->
CompilerM op s ()
-- | Call a function.
type CallCompiler op s = [VName] -> Name -> [C.Exp] -> CompilerM op s ()
data Operations op s = Operations
{ opsWriteScalar :: WriteScalar op s,
opsReadScalar :: ReadScalar op s,
opsAllocate :: Allocate op s,
opsDeallocate :: Deallocate op s,
opsCopy :: Copy op s,
opsStaticArray :: StaticArray op s,
opsMemoryType :: MemoryType op s,
opsCompiler :: OpCompiler op s,
opsError :: ErrorCompiler op s,
opsCall :: CallCompiler op s,
-- | If true, use reference counting. Otherwise, bare
-- pointers.
opsFatMemory :: Bool,
-- | Code to bracket critical sections.
opsCritical :: ([C.BlockItem], [C.BlockItem])
}
errorMsgString :: ErrorMsg Exp -> CompilerM op s (String, [C.Exp])
errorMsgString (ErrorMsg parts) = do
let boolStr e = [C.cexp|($exp:e) ? "true" : "false"|]
asLongLong e = [C.cexp|(long long int)$exp:e|]
asDouble e = [C.cexp|(double)$exp:e|]
onPart (ErrorString s) = return ("%s", [C.cexp|$string:s|])
onPart (ErrorVal Bool x) = ("%s",) . boolStr <$> compileExp x
onPart (ErrorVal Unit _) = pure ("%s", [C.cexp|"()"|])
onPart (ErrorVal (IntType Int8) x) = ("%hhd",) <$> compileExp x
onPart (ErrorVal (IntType Int16) x) = ("%hd",) <$> compileExp x
onPart (ErrorVal (IntType Int32) x) = ("%d",) <$> compileExp x
onPart (ErrorVal (IntType Int64) x) = ("%lld",) . asLongLong <$> compileExp x
onPart (ErrorVal (FloatType Float16) x) = ("%f",) . asDouble <$> compileExp x
onPart (ErrorVal (FloatType Float32) x) = ("%f",) . asDouble <$> compileExp x
onPart (ErrorVal (FloatType Float64) x) = ("%f",) <$> compileExp x
(formatstrs, formatargs) <- unzip <$> mapM onPart parts
pure (mconcat formatstrs, formatargs)
defError :: ErrorCompiler op s
defError msg stacktrace = do
free_all_mem <- collect $ mapM_ (uncurry unRefMem) =<< gets compDeclaredMem
(formatstr, formatargs) <- errorMsgString msg
let formatstr' = "Error: " <> formatstr <> "\n\nBacktrace:\n%s"
items
[C.citems|ctx->error = msgprintf($string:formatstr', $args:formatargs, $string:stacktrace);
$items:free_all_mem
return 1;|]
defCall :: CallCompiler op s
defCall dests fname args = do
let out_args = [[C.cexp|&$id:d|] | d <- dests]
args'
| isBuiltInFunction fname = args
| otherwise = [C.cexp|ctx|] : out_args ++ args
case dests of
[dest]
| isBuiltInFunction fname ->
stm [C.cstm|$id:dest = $id:(funName fname)($args:args');|]
_ ->
item [C.citem|if ($id:(funName fname)($args:args') != 0) { err = 1; goto cleanup; }|]
-- | A set of operations that fail for every operation involving
-- non-default memory spaces. Uses plain pointers and @malloc@ for
-- memory management.
defaultOperations :: Operations op s
defaultOperations =
Operations
{ opsWriteScalar = defWriteScalar,
opsReadScalar = defReadScalar,
opsAllocate = defAllocate,
opsDeallocate = defDeallocate,
opsCopy = defCopy,
opsStaticArray = defStaticArray,
opsMemoryType = defMemoryType,
opsCompiler = defCompiler,
opsFatMemory = True,
opsError = defError,
opsCall = defCall,
opsCritical = mempty
}
where
defWriteScalar _ _ _ _ _ =
error "Cannot write to non-default memory space because I am dumb"
defReadScalar _ _ _ _ =
error "Cannot read from non-default memory space"
defAllocate _ _ _ =
error "Cannot allocate in non-default memory space"
defDeallocate _ _ =
error "Cannot deallocate in non-default memory space"
defCopy destmem destoffset DefaultSpace srcmem srcoffset DefaultSpace size =
copyMemoryDefaultSpace destmem destoffset srcmem srcoffset size
defCopy _ _ _ _ _ _ _ =
error "Cannot copy to or from non-default memory space"
defStaticArray _ _ _ _ =
error "Cannot create static array in non-default memory space"
defMemoryType _ =
error "Has no type for non-default memory space"
defCompiler _ =
error "The default compiler cannot compile extended operations"
data CompilerEnv op s = CompilerEnv
{ envOperations :: Operations op s,
-- | Mapping memory blocks to sizes. These memory blocks are CPU
-- memory that we know are used in particularly simple ways (no
-- reference counting necessary). To cut down on allocator
-- pressure, we keep these allocations around for a long time, and
-- record their sizes so we can reuse them if possible (and
-- realloc() when needed).
envCachedMem :: M.Map C.Exp VName
}
envOpCompiler :: CompilerEnv op s -> OpCompiler op s
envOpCompiler = opsCompiler . envOperations
envMemoryType :: CompilerEnv op s -> MemoryType op s
envMemoryType = opsMemoryType . envOperations
envReadScalar :: CompilerEnv op s -> ReadScalar op s
envReadScalar = opsReadScalar . envOperations
envWriteScalar :: CompilerEnv op s -> WriteScalar op s
envWriteScalar = opsWriteScalar . envOperations
envAllocate :: CompilerEnv op s -> Allocate op s
envAllocate = opsAllocate . envOperations
envDeallocate :: CompilerEnv op s -> Deallocate op s
envDeallocate = opsDeallocate . envOperations
envCopy :: CompilerEnv op s -> Copy op s
envCopy = opsCopy . envOperations
envStaticArray :: CompilerEnv op s -> StaticArray op s
envStaticArray = opsStaticArray . envOperations
envFatMemory :: CompilerEnv op s -> Bool
envFatMemory = opsFatMemory . envOperations
declsCode :: (HeaderSection -> Bool) -> CompilerState s -> T.Text
declsCode p =
T.unlines
. map prettyText
. concatMap (DL.toList . snd)
. filter (p . fst)
. M.toList
. compHeaderDecls
initDecls, arrayDecls, opaqueDecls, entryDecls, miscDecls :: CompilerState s -> T.Text
initDecls = declsCode (== InitDecl)
arrayDecls = declsCode isArrayDecl
where
isArrayDecl ArrayDecl {} = True
isArrayDecl _ = False
opaqueDecls = declsCode isOpaqueDecl
where
isOpaqueDecl OpaqueDecl {} = True
isOpaqueDecl _ = False
entryDecls = declsCode (== EntryDecl)
miscDecls = declsCode (== MiscDecl)
contextContents :: CompilerM op s ([C.FieldGroup], [C.Stm])
contextContents = do
(field_names, field_types, field_values) <- gets $ unzip3 . DL.toList . compCtxFields
let fields =
[ [C.csdecl|$ty:ty $id:name;|]
| (name, ty) <- zip field_names field_types
]
init_fields =
[ [C.cstm|ctx->$id:name = $exp:e;|]
| (name, Just e) <- zip field_names field_values
]
return (fields, init_fields)
contextFinalInits :: CompilerM op s [C.Stm]
contextFinalInits = gets compInit
newtype CompilerM op s a
= CompilerM (ReaderT (CompilerEnv op s) (State (CompilerState s)) a)
deriving
( Functor,
Applicative,
Monad,
MonadState (CompilerState s),
MonadReader (CompilerEnv op s)
)
instance MonadFreshNames (CompilerM op s) where
getNameSource = gets compNameSrc
putNameSource src = modify $ \s -> s {compNameSrc = src}
runCompilerM ::
Operations op s ->
VNameSource ->
s ->
CompilerM op s a ->
(a, CompilerState s)
runCompilerM ops src userstate (CompilerM m) =
runState
(runReaderT m (CompilerEnv ops mempty))
(newCompilerState src userstate)
getUserState :: CompilerM op s s
getUserState = gets compUserState
modifyUserState :: (s -> s) -> CompilerM op s ()
modifyUserState f = modify $ \compstate ->
compstate {compUserState = f $ compUserState compstate}
atInit :: C.Stm -> CompilerM op s ()
atInit x = modify $ \s ->
s {compInit = compInit s ++ [x]}
collect :: CompilerM op s () -> CompilerM op s [C.BlockItem]
collect m = snd <$> collect' m
collect' :: CompilerM op s a -> CompilerM op s (a, [C.BlockItem])
collect' m = do
old <- gets compItems
modify $ \s -> s {compItems = mempty}
x <- m
new <- gets compItems
modify $ \s -> s {compItems = old}
pure (x, DL.toList new)
-- | Used when we, inside an existing 'CompilerM' action, want to
-- generate code for a new function. Use this so that the compiler
-- understands that previously declared memory doesn't need to be
-- freed inside this action.
inNewFunction :: Bool -> CompilerM op s a -> CompilerM op s a
inNewFunction keep_cached m = do
old_mem <- gets compDeclaredMem
modify $ \s -> s {compDeclaredMem = mempty}
x <- local noCached m
modify $ \s -> s {compDeclaredMem = old_mem}
return x
where
noCached env
| keep_cached = env
| otherwise = env {envCachedMem = mempty}
item :: C.BlockItem -> CompilerM op s ()
item x = modify $ \s -> s {compItems = DL.snoc (compItems s) x}
items :: [C.BlockItem] -> CompilerM op s ()
items xs = modify $ \s -> s {compItems = DL.append (compItems s) (DL.fromList xs)}
fatMemory :: Space -> CompilerM op s Bool
fatMemory ScalarSpace {} = return False
fatMemory _ = asks envFatMemory
cacheMem :: C.ToExp a => a -> CompilerM op s (Maybe VName)
cacheMem a = asks $ M.lookup (C.toExp a noLoc) . envCachedMem
-- | Construct a publicly visible definition using the specified name
-- as the template. The first returned definition is put in the
-- header file, and the second is the implementation. Returns the public
-- name.
publicDef ::
String ->
HeaderSection ->
(String -> (C.Definition, C.Definition)) ->
CompilerM op s String
publicDef s h f = do
s' <- publicName s
let (pub, priv) = f s'
headerDecl h pub
earlyDecl priv
return s'
-- | As 'publicDef', but ignores the public name.
publicDef_ ::
String ->
HeaderSection ->
(String -> (C.Definition, C.Definition)) ->
CompilerM op s ()
publicDef_ s h f = void $ publicDef s h f
headerDecl :: HeaderSection -> C.Definition -> CompilerM op s ()
headerDecl sec def = modify $ \s ->
s
{ compHeaderDecls =
M.unionWith
(<>)
(compHeaderDecls s)
(M.singleton sec (DL.singleton def))
}
libDecl :: C.Definition -> CompilerM op s ()
libDecl def = modify $ \s ->
s {compLibDecls = compLibDecls s <> DL.singleton def}
earlyDecl :: C.Definition -> CompilerM op s ()
earlyDecl def = modify $ \s ->
s {compEarlyDecls = compEarlyDecls s <> DL.singleton def}
contextField :: C.Id -> C.Type -> Maybe C.Exp -> CompilerM op s ()
contextField name ty initial = modify $ \s ->
s {compCtxFields = compCtxFields s <> DL.singleton (name, ty, initial)}
profileReport :: C.BlockItem -> CompilerM op s ()
profileReport x = modify $ \s ->
s {compProfileItems = compProfileItems s <> DL.singleton x}
onClear :: C.BlockItem -> CompilerM op s ()
onClear x = modify $ \s ->
s {compClearItems = compClearItems s <> DL.singleton x}
stm :: C.Stm -> CompilerM op s ()
stm s = item [C.citem|$stm:s|]
stms :: [C.Stm] -> CompilerM op s ()
stms = mapM_ stm
decl :: C.InitGroup -> CompilerM op s ()
decl x = item [C.citem|$decl:x;|]
-- | Public names must have a consitent prefix.
publicName :: String -> CompilerM op s String
publicName s = return $ "futhark_" ++ s
-- | The generated code must define a struct with this name.
contextType :: CompilerM op s C.Type
contextType = do
name <- publicName "context"
return [C.cty|struct $id:name|]
memToCType :: VName -> Space -> CompilerM op s C.Type
memToCType v space = do
refcount <- fatMemory space
cached <- isJust <$> cacheMem v
if refcount && not cached
then return $ fatMemType space
else rawMemCType space
rawMemCType :: Space -> CompilerM op s C.Type
rawMemCType DefaultSpace = return defaultMemBlockType
rawMemCType (Space sid) = join $ asks envMemoryType <*> pure sid
rawMemCType (ScalarSpace [] t) =
return [C.cty|$ty:(primTypeToCType t)[1]|]
rawMemCType (ScalarSpace ds t) =
return [C.cty|$ty:(primTypeToCType t)[$exp:(cproduct ds')]|]
where
ds' = map (`C.toExp` noLoc) ds
fatMemType :: Space -> C.Type
fatMemType space =
[C.cty|struct $id:name|]
where
name = case space of
Space sid -> "memblock_" ++ sid
_ -> "memblock"
fatMemSet :: Space -> String
fatMemSet (Space sid) = "memblock_set_" ++ sid
fatMemSet _ = "memblock_set"
fatMemAlloc :: Space -> String
fatMemAlloc (Space sid) = "memblock_alloc_" ++ sid
fatMemAlloc _ = "memblock_alloc"
fatMemUnRef :: Space -> String
fatMemUnRef (Space sid) = "memblock_unref_" ++ sid
fatMemUnRef _ = "memblock_unref"
rawMem :: VName -> CompilerM op s C.Exp
rawMem v = rawMem' <$> fat <*> pure v
where
fat = asks ((&&) . envFatMemory) <*> (isNothing <$> cacheMem v)
rawMem' :: C.ToExp a => Bool -> a -> C.Exp
rawMem' True e = [C.cexp|$exp:e.mem|]
rawMem' False e = [C.cexp|$exp:e|]
allocRawMem ::
(C.ToExp a, C.ToExp b, C.ToExp c) =>
a ->
b ->
Space ->
c ->
CompilerM op s ()
allocRawMem dest size space desc = case space of
Space sid ->
join $
asks envAllocate <*> pure [C.cexp|$exp:dest|]
<*> pure [C.cexp|$exp:size|]
<*> pure [C.cexp|$exp:desc|]
<*> pure sid
_ ->
stm [C.cstm|$exp:dest = (unsigned char*) malloc((size_t)$exp:size);|]
freeRawMem ::
(C.ToExp a, C.ToExp b) =>
a ->
Space ->
b ->
CompilerM op s ()
freeRawMem mem space desc =
case space of
Space sid -> do
free_mem <- asks envDeallocate
free_mem [C.cexp|$exp:mem|] [C.cexp|$exp:desc|] sid
_ -> item [C.citem|free($exp:mem);|]
defineMemorySpace :: Space -> CompilerM op s (C.Definition, [C.Definition], C.BlockItem)
defineMemorySpace space = do
rm <- rawMemCType space
let structdef =
[C.cedecl|struct $id:sname { int *references;
$ty:rm mem;
typename int64_t size;
const char *desc; };|]
contextField peakname [C.cty|typename int64_t|] $ Just [C.cexp|0|]
contextField usagename [C.cty|typename int64_t|] $ Just [C.cexp|0|]
-- Unreferencing a memory block consists of decreasing its reference
-- count and freeing the corresponding memory if the count reaches
-- zero.
free <- collect $ freeRawMem [C.cexp|block->mem|] space [C.cexp|desc|]
ctx_ty <- contextType
let unrefdef =
[C.cedecl|static int $id:(fatMemUnRef space) ($ty:ctx_ty *ctx, $ty:mty *block, const char *desc) {
if (block->references != NULL) {
*(block->references) -= 1;
if (ctx->detail_memory) {
fprintf(ctx->log, "Unreferencing block %s (allocated as %s) in %s: %d references remaining.\n",
desc, block->desc, $string:spacedesc, *(block->references));
}
if (*(block->references) == 0) {
ctx->$id:usagename -= block->size;
$items:free
free(block->references);
if (ctx->detail_memory) {
fprintf(ctx->log, "%lld bytes freed (now allocated: %lld bytes)\n",
(long long) block->size, (long long) ctx->$id:usagename);
}
}
block->references = NULL;
}
return 0;
}|]
-- When allocating a memory block we initialise the reference count to 1.
alloc <-
collect $
allocRawMem [C.cexp|block->mem|] [C.cexp|size|] space [C.cexp|desc|]
let allocdef =
[C.cedecl|static int $id:(fatMemAlloc space) ($ty:ctx_ty *ctx, $ty:mty *block, typename int64_t size, const char *desc) {
if (size < 0) {
futhark_panic(1, "Negative allocation of %lld bytes attempted for %s in %s.\n",
(long long)size, desc, $string:spacedesc, ctx->$id:usagename);
}
int ret = $id:(fatMemUnRef space)(ctx, block, desc);
ctx->$id:usagename += size;
if (ctx->detail_memory) {
fprintf(ctx->log, "Allocating %lld bytes for %s in %s (then allocated: %lld bytes)",
(long long) size,
desc, $string:spacedesc,
(long long) ctx->$id:usagename);
}
if (ctx->$id:usagename > ctx->$id:peakname) {
ctx->$id:peakname = ctx->$id:usagename;
if (ctx->detail_memory) {
fprintf(ctx->log, " (new peak).\n");
}
} else if (ctx->detail_memory) {
fprintf(ctx->log, ".\n");
}
$items:alloc
block->references = (int*) malloc(sizeof(int));
*(block->references) = 1;
block->size = size;
block->desc = desc;
return ret;
}|]
-- Memory setting - unreference the destination and increase the
-- count of the source by one.
let setdef =
[C.cedecl|static int $id:(fatMemSet space) ($ty:ctx_ty *ctx, $ty:mty *lhs, $ty:mty *rhs, const char *lhs_desc) {
int ret = $id:(fatMemUnRef space)(ctx, lhs, lhs_desc);
if (rhs->references != NULL) {
(*(rhs->references))++;
}
*lhs = *rhs;
return ret;
}
|]
onClear [C.citem|ctx->$id:peakname = 0;|]
let peakmsg = "Peak memory usage for " ++ spacedesc ++ ": %lld bytes.\n"
return
( structdef,
[unrefdef, allocdef, setdef],
-- Do not report memory usage for DefaultSpace (CPU memory),
-- because it would not be accurate anyway. This whole
-- tracking probably needs to be rethought.
if space == DefaultSpace
then [C.citem|{}|]
else [C.citem|str_builder(&builder, $string:peakmsg, (long long) ctx->$id:peakname);|]
)
where
mty = fatMemType space
(peakname, usagename, sname, spacedesc) = case space of
Space sid ->
( C.toIdent ("peak_mem_usage_" ++ sid) noLoc,
C.toIdent ("cur_mem_usage_" ++ sid) noLoc,
C.toIdent ("memblock_" ++ sid) noLoc,
"space '" ++ sid ++ "'"
)
_ ->
( "peak_mem_usage_default",
"cur_mem_usage_default",
"memblock",
"default space"
)
declMem :: VName -> Space -> CompilerM op s ()
declMem name space = do
cached <- isJust <$> cacheMem name
unless cached $ do
ty <- memToCType name space
decl [C.cdecl|$ty:ty $id:name;|]
resetMem name space
modify $ \s -> s {compDeclaredMem = (name, space) : compDeclaredMem s}
resetMem :: C.ToExp a => a -> Space -> CompilerM op s ()
resetMem mem space = do
refcount <- fatMemory space
cached <- isJust <$> cacheMem mem
if cached
then stm [C.cstm|$exp:mem = NULL;|]
else
when refcount $
stm [C.cstm|$exp:mem.references = NULL;|]
setMem :: (C.ToExp a, C.ToExp b) => a -> b -> Space -> CompilerM op s ()
setMem dest src space = do
refcount <- fatMemory space
let src_s = pretty $ C.toExp src noLoc
if refcount
then
stm
[C.cstm|if ($id:(fatMemSet space)(ctx, &$exp:dest, &$exp:src,
$string:src_s) != 0) {
return 1;
}|]
else case space of
ScalarSpace ds _ -> do
i' <- newVName "i"
let i = C.toIdent i'
it = primTypeToCType $ IntType Int32
ds' = map (`C.toExp` noLoc) ds
bound = cproduct ds'
stm
[C.cstm|for ($ty:it $id:i = 0; $id:i < $exp:bound; $id:i++) {
$exp:dest[$id:i] = $exp:src[$id:i];
}|]
_ -> stm [C.cstm|$exp:dest = $exp:src;|]
unRefMem :: C.ToExp a => a -> Space -> CompilerM op s ()
unRefMem mem space = do
refcount <- fatMemory space
cached <- isJust <$> cacheMem mem
let mem_s = pretty $ C.toExp mem noLoc
when (refcount && not cached) $
stm
[C.cstm|if ($id:(fatMemUnRef space)(ctx, &$exp:mem, $string:mem_s) != 0) {
return 1;
}|]
allocMem ::
(C.ToExp a, C.ToExp b) =>
a ->
b ->
Space ->
C.Stm ->
CompilerM op s ()
allocMem mem size space on_failure = do
refcount <- fatMemory space
let mem_s = pretty $ C.toExp mem noLoc
if refcount
then
stm
[C.cstm|if ($id:(fatMemAlloc space)(ctx, &$exp:mem, $exp:size,
$string:mem_s)) {
$stm:on_failure
}|]
else do
freeRawMem mem space mem_s
allocRawMem mem size space [C.cexp|desc|]
copyMemoryDefaultSpace ::
C.Exp ->
C.Exp ->
C.Exp ->
C.Exp ->
C.Exp ->
CompilerM op s ()
copyMemoryDefaultSpace destmem destidx srcmem srcidx nbytes =
stm
[C.cstm|if ($exp:nbytes > 0) {
memmove($exp:destmem + $exp:destidx,
$exp:srcmem + $exp:srcidx,
$exp:nbytes);
}|]
--- Entry points.
criticalSection :: Operations op s -> [C.BlockItem] -> [C.BlockItem]
criticalSection ops x =
[C.citems|lock_lock(&ctx->lock);
$items:(fst (opsCritical ops))
$items:x
$items:(snd (opsCritical ops))
lock_unlock(&ctx->lock);
|]
arrayLibraryFunctions ::
Publicness ->
Space ->
PrimType ->
Signedness ->
Int ->
CompilerM op s [C.Definition]
arrayLibraryFunctions pub space pt signed rank = do
let pt' = primAPIType signed pt
name = arrayName pt signed rank
arr_name = "futhark_" ++ name
array_type = [C.cty|struct $id:arr_name|]
new_array <- publicName $ "new_" ++ name
new_raw_array <- publicName $ "new_raw_" ++ name
free_array <- publicName $ "free_" ++ name
values_array <- publicName $ "values_" ++ name
values_raw_array <- publicName $ "values_raw_" ++ name
shape_array <- publicName $ "shape_" ++ name
let shape_names = ["dim" ++ show i | i <- [0 .. rank -1]]
shape_params = [[C.cparam|typename int64_t $id:k|] | k <- shape_names]
arr_size = cproduct [[C.cexp|$id:k|] | k <- shape_names]
arr_size_array = cproduct [[C.cexp|arr->shape[$int:i]|] | i <- [0 .. rank -1]]
copy <- asks envCopy
memty <- rawMemCType space
let prepare_new = do
resetMem [C.cexp|arr->mem|] space
allocMem
[C.cexp|arr->mem|]
[C.cexp|$exp:arr_size * $int:(primByteSize pt::Int)|]
space
[C.cstm|return NULL;|]
forM_ [0 .. rank -1] $ \i ->
let dim_s = "dim" ++ show i
in stm [C.cstm|arr->shape[$int:i] = $id:dim_s;|]
new_body <- collect $ do
prepare_new
copy
[C.cexp|arr->mem.mem|]
[C.cexp|0|]
space
[C.cexp|data|]
[C.cexp|0|]
DefaultSpace
[C.cexp|((size_t)$exp:arr_size) * $int:(primByteSize pt::Int)|]
new_raw_body <- collect $ do
prepare_new
copy
[C.cexp|arr->mem.mem|]
[C.cexp|0|]
space
[C.cexp|data|]
[C.cexp|offset|]
space
[C.cexp|((size_t)$exp:arr_size) * $int:(primByteSize pt::Int)|]
free_body <- collect $ unRefMem [C.cexp|arr->mem|] space
values_body <-
collect $
copy
[C.cexp|data|]
[C.cexp|0|]
DefaultSpace
[C.cexp|arr->mem.mem|]
[C.cexp|0|]
space
[C.cexp|((size_t)$exp:arr_size_array) * $int:(primByteSize pt::Int)|]
ctx_ty <- contextType
ops <- asks envOperations
let proto = case pub of
Public -> headerDecl (ArrayDecl name)
Private -> libDecl
proto
[C.cedecl|struct $id:arr_name;|]
proto
[C.cedecl|$ty:array_type* $id:new_array($ty:ctx_ty *ctx, const $ty:pt' *data, $params:shape_params);|]
proto
[C.cedecl|$ty:array_type* $id:new_raw_array($ty:ctx_ty *ctx, const $ty:memty data, typename int64_t offset, $params:shape_params);|]
proto
[C.cedecl|int $id:free_array($ty:ctx_ty *ctx, $ty:array_type *arr);|]
proto
[C.cedecl|int $id:values_array($ty:ctx_ty *ctx, $ty:array_type *arr, $ty:pt' *data);|]
proto
[C.cedecl|$ty:memty $id:values_raw_array($ty:ctx_ty *ctx, $ty:array_type *arr);|]
proto
[C.cedecl|const typename int64_t* $id:shape_array($ty:ctx_ty *ctx, $ty:array_type *arr);|]
return
[C.cunit|
$ty:array_type* $id:new_array($ty:ctx_ty *ctx, const $ty:pt' *data, $params:shape_params) {
$ty:array_type* bad = NULL;
$ty:array_type *arr = ($ty:array_type*) malloc(sizeof($ty:array_type));
if (arr == NULL) {
return bad;
}
$items:(criticalSection ops new_body)
return arr;
}
$ty:array_type* $id:new_raw_array($ty:ctx_ty *ctx, const $ty:memty data, typename int64_t offset,
$params:shape_params) {
$ty:array_type* bad = NULL;
$ty:array_type *arr = ($ty:array_type*) malloc(sizeof($ty:array_type));
if (arr == NULL) {
return bad;
}
$items:(criticalSection ops new_raw_body)
return arr;
}
int $id:free_array($ty:ctx_ty *ctx, $ty:array_type *arr) {
$items:(criticalSection ops free_body)
free(arr);
return 0;
}
int $id:values_array($ty:ctx_ty *ctx, $ty:array_type *arr, $ty:pt' *data) {
$items:(criticalSection ops values_body)
return 0;
}
$ty:memty $id:values_raw_array($ty:ctx_ty *ctx, $ty:array_type *arr) {
(void)ctx;
return arr->mem.mem;
}
const typename int64_t* $id:shape_array($ty:ctx_ty *ctx, $ty:array_type *arr) {
(void)ctx;
return arr->shape;
}
|]
opaqueLibraryFunctions ::
String ->
[ValueDesc] ->
CompilerM op s [C.Definition]
opaqueLibraryFunctions desc vds = do
name <- publicName $ opaqueName desc vds
free_opaque <- publicName $ "free_" ++ opaqueName desc vds
store_opaque <- publicName $ "store_" ++ opaqueName desc vds
restore_opaque <- publicName $ "restore_" ++ opaqueName desc vds
let opaque_type = [C.cty|struct $id:name|]
freeComponent _ ScalarValue {} =
return ()
freeComponent i (ArrayValue _ _ pt signed shape) = do
let rank = length shape
field = tupleField i
free_array <- publicName $ "free_" ++ arrayName pt signed rank
-- Protect against NULL here, because we also want to use this
-- to free partially loaded opaques.
stm
[C.cstm|if (obj->$id:field != NULL && (tmp = $id:free_array(ctx, obj->$id:field)) != 0) {
ret = tmp;
}|]
storeComponent i (ScalarValue pt sign _) =
let field = tupleField i
in ( storageSize pt 0 [C.cexp|NULL|],
storeValueHeader sign pt 0 [C.cexp|NULL|] [C.cexp|out|]
++ [C.cstms|memcpy(out, &obj->$id:field, sizeof(obj->$id:field));
out += sizeof(obj->$id:field);|]