-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValues.lean
More file actions
4184 lines (3968 loc) · 189 KB
/
Copy pathValues.lean
File metadata and controls
4184 lines (3968 loc) · 189 KB
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
import Lean
import LeanExe.Extract.Types
import LeanExe.IR.Core
import LeanExe.Runtime
open Lean
namespace LeanExe.Extract.Core
def lookupBinding (locals : List Binding) (index : Nat) : Except String Binding :=
match locals[index]? with
| some binding => .ok binding
| none => .error s!"unbound de Bruijn variable: {index}"
def structuralBelowProjection (below : StructuralBelow) (index : Nat) :
Except String StructuralBelow :=
match below, index with
| .pair left _, 0 => .ok left
| .pair _ right, 1 => .ok right
| _, _ => .error "unsupported structural recursion below projection"
partial def structuralBelowFromExpr?
(locals : List Binding)
(expr : Expr) :
Except String (Option StructuralBelow) := do
match expr.consumeMData with
| .bvar index =>
match ← lookupBinding locals index with
| .structuralRec functionName arg => .ok (some (.call functionName arg []))
| .structuralBelow below => .ok (some below)
| _ => .ok none
| .proj ``PProd index body =>
match ← structuralBelowFromExpr? locals body with
| some below => .ok (some (← structuralBelowProjection below index))
| none => .ok none
| _ => .ok none
def structuralRecProjection?
(locals : List Binding)
(expr : Expr) :
Except String (Option (Name × ExtractedValue × List ExtractedValue)) := do
match ← structuralBelowFromExpr? locals expr with
| some (.call functionName arg capturedArgs) => .ok (some (functionName, arg, capturedArgs))
| some _ => .error "unsupported structural recursion projection"
| none => .ok none
def primitiveArgPair? (args : List Expr) : Option (Expr × Expr) :=
match args.reverse with
| right :: left :: _ => some (left, right)
| _ => none
def primitiveResultType? (env : Environment) (args : List Expr) : Option Ty :=
match args with
| _leftType :: _rightType :: resultType :: _ => typeAtom? env resultType
| _ => none
def primitiveReceiverType? (env : Environment) (args : List Expr) : Option Ty :=
match args with
| ty :: _ => typeAtom? env ty
| _ => none
def primitiveStringReceiver? (args : List Expr) : Bool :=
match args with
| ty :: _ => isStringType ty
| _ => false
def primitiveStringResult? (args : List Expr) : Bool :=
match args with
| _leftTy :: _rightTy :: resultTy :: _ => isStringType resultTy
| _ => false
def runtimeStatPrimitive? (name : Name) : Option LeanExe.IR.RuntimeStat :=
if name == ``LeanExe.Runtime.allocCount then
some .allocs
else if name == ``LeanExe.Runtime.retainCount then
some .retains
else if name == ``LeanExe.Runtime.releaseCount then
some .releases
else if name == ``LeanExe.Runtime.freeCount then
some .frees
else
none
partial def compileTimeString?
(ctx : Context)
(locals : List Binding)
(fuel : Nat)
(expr : Expr) : Option String :=
match fuel with
| 0 => none
| fuel + 1 =>
match expr.consumeMData with
| .lit (.strVal value) => some value
| .bvar index =>
match lookupBinding locals index with
| .ok (.thunk savedLocals inlineStack value) => compileTimeString? { ctx with inlineStack } savedLocals fuel value
| _ => none
| .letE _ type value body _ =>
if containsBVar 0 body then
if isStringType type then
compileTimeString? ctx (.thunk locals ctx.inlineStack value :: locals) fuel body
else
none
else
compileTimeString? ctx (.recursor :: locals) fuel body
| .mdata _ body => compileTimeString? ctx locals fuel body
| .const name _ =>
match ctx.env.find? name with
| some info =>
if isStringType info.type then
match info.value? with
| some value => compileTimeString? ctx [] fuel value
| none => none
else
none
| none => none
| _ =>
match appFnArgs expr with
| (.const ``String.append _, [left, right]) =>
match compileTimeString? ctx locals fuel left,
compileTimeString? ctx locals fuel right with
| some leftValue, some rightValue => some (leftValue ++ rightValue)
| _, _ => none
| (.const ``HAppend.hAppend _, args) =>
if primitiveStringResult? args then
match primitiveArgPair? args with
| some (left, right) =>
match compileTimeString? ctx locals fuel left,
compileTimeString? ctx locals fuel right with
| some leftValue, some rightValue => some (leftValue ++ rightValue)
| _, _ => none
| none => none
else
none
| (.const ``Append.append _, args) =>
if primitiveStringReceiver? args then
match primitiveArgPair? args with
| some (left, right) =>
match compileTimeString? ctx locals fuel left,
compileTimeString? ctx locals fuel right with
| some leftValue, some rightValue => some (leftValue ++ rightValue)
| _, _ => none
| none => none
else
none
| (.const ``id _, args) =>
match args.reverse with
| value :: _ => compileTimeString? ctx locals fuel value
| _ => none
| _ => none
def asciiStringExprBytesFrom
(ctx : Context)
(locals : List Binding)
(expr : Expr)
(unsupportedMessage nonAsciiMessage : String) :
Except String (List UInt8) :=
match compileTimeString? ctx locals 256 expr with
| some value =>
match asciiStringBytes? value with
| some bytes => .ok bytes
| none => .error nonAsciiMessage
| none => .error unsupportedMessage
def boolExpr (cond : IRCond) : IRExpr :=
.ite cond (.u64 1) (.u64 0)
def boolCond (expr : IRExpr) : IRCond :=
.not (.eqU64 expr (.u64 0))
def constLocal? (slot : Nat) : List (Nat × Nat) → Option Nat
| [] => none
| (candidate, value) :: rest =>
if candidate == slot then some value else constLocal? slot rest
def removeConstLocal (slot : Nat) (locals : List (Nat × Nat)) : List (Nat × Nat) :=
locals.filter fun item => item.fst != slot
def removeConstLocals (slots : List Nat) (locals : List (Nat × Nat)) : List (Nat × Nat) :=
slots.foldl (fun acc slot => removeConstLocal slot acc) locals
mutual
partial def exprConstFrom? (locals : List (Nat × Nat)) : IRExpr → Option Nat
| .u64 value => some value
| .local slot => constLocal? slot locals
| .ite cond thenValue elseValue =>
match condConstFrom? locals cond with
| some true => exprConstFrom? locals thenValue
| some false => exprConstFrom? locals elseValue
| none =>
match exprConstFrom? locals thenValue, exprConstFrom? locals elseValue with
| some thenConst, some elseConst =>
if thenConst == elseConst then some thenConst else none
| _, _ => none
| .letE slot value body =>
let nextLocals :=
match exprConstFrom? locals value with
| some valueConst => (slot, valueConst) :: removeConstLocal slot locals
| none => removeConstLocal slot locals
exprConstFrom? nextLocals body
| .letCall slots _ _ body =>
exprConstFrom? (removeConstLocals slots locals) body
| _ => none
partial def condConstFrom? (locals : List (Nat × Nat)) : IRCond → Option Bool
| .true => some true
| .false => some false
| .eqU64 left right => do
some ((← exprConstFrom? locals left) == (← exprConstFrom? locals right))
| .ltU64 left right => do
some ((← exprConstFrom? locals left) < (← exprConstFrom? locals right))
| .leU64 left right => do
some ((← exprConstFrom? locals left) <= (← exprConstFrom? locals right))
| .not cond => condConstFrom? locals cond |>.map Bool.not
| .and left right =>
match condConstFrom? locals left, condConstFrom? locals right with
| some false, _ => some false
| _, some false => some false
| some true, some true => some true
| _, _ => none
| .or left right =>
match condConstFrom? locals left, condConstFrom? locals right with
| some true, _ => some true
| _, some true => some true
| some false, some false => some false
| _, _ => none
end
def exprConst? (expr : IRExpr) : Option Nat :=
exprConstFrom? [] expr
def condConst? (cond : IRCond) : Option Bool :=
condConstFrom? [] cond
mutual
partial def exprContainsFoldMultiSlot : IRExpr → Bool
| .arrayFoldMultiSlot .. => true
| .byteArrayFoldMultiSlot .. => true
| .rangeFoldMultiSlot .. => true
| .loopFoldMultiSlot .. => true
| .ite cond thenValue elseValue =>
condContainsFoldMultiSlot cond ||
exprContainsFoldMultiSlot thenValue ||
exprContainsFoldMultiSlot elseValue
| .letE _ value body =>
exprContainsFoldMultiSlot value || exprContainsFoldMultiSlot body
| .letCall _ _ args body =>
exprListContainsFoldMultiSlot args || exprContainsFoldMultiSlot body
| .letLets lets body =>
localLetsContainFoldMultiSlot lets || exprContainsFoldMultiSlot body
| _ => false
partial def condContainsFoldMultiSlot : IRCond → Bool
| .eqU64 left right
| .ltU64 left right
| .leU64 left right =>
exprContainsFoldMultiSlot left || exprContainsFoldMultiSlot right
| .not cond => condContainsFoldMultiSlot cond
| .and left right
| .or left right =>
condContainsFoldMultiSlot left || condContainsFoldMultiSlot right
| .true
| .false => false
partial def exprListContainsFoldMultiSlot : List IRExpr → Bool
| [] => false
| expr :: rest => exprContainsFoldMultiSlot expr || exprListContainsFoldMultiSlot rest
partial def localLetContainsFoldMultiSlot : LeanExe.IR.LocalLet → Bool
| .expr _ expr => exprContainsFoldMultiSlot expr
| .slots _ values => exprListContainsFoldMultiSlot values
| .call _ _ args => exprListContainsFoldMultiSlot args
| .branch cond thenLets elseLets =>
condContainsFoldMultiSlot cond ||
localLetsContainFoldMultiSlot thenLets ||
localLetsContainFoldMultiSlot elseLets
partial def localLetsContainFoldMultiSlot : List LeanExe.IR.LocalLet → Bool
| [] => false
| localLet :: rest =>
localLetContainsFoldMultiSlot localLet || localLetsContainFoldMultiSlot rest
partial def valueContainsFoldMultiSlot : ExtractedValue → Bool
| .scalar expr => exprContainsFoldMultiSlot expr
| .array owner ptr => exprContainsFoldMultiSlot owner || exprContainsFoldMultiSlot ptr
| .byteArray owner ptr len =>
exprContainsFoldMultiSlot owner ||
exprContainsFoldMultiSlot ptr ||
exprContainsFoldMultiSlot len
| .product left right =>
valueContainsFoldMultiSlot left || valueContainsFoldMultiSlot right
| .sum tag left right =>
exprContainsFoldMultiSlot tag ||
valueContainsFoldMultiSlot left ||
valueContainsFoldMultiSlot right
| .struct _ fields => valuesContainFoldMultiSlot fields
| .variant _ tag ctors =>
exprContainsFoldMultiSlot tag || ctorValuesContainFoldMultiSlot ctors
| .recursiveVariant _ tag ctors =>
exprContainsFoldMultiSlot tag ||
ctors.any (fun fields => fields.any fun field => valueContainsFoldMultiSlot field.snd)
| .heapVariant _ ptr => exprContainsFoldMultiSlot ptr
| .ite cond thenValue elseValue =>
condContainsFoldMultiSlot cond ||
valueContainsFoldMultiSlot thenValue ||
valueContainsFoldMultiSlot elseValue
| .letE _ expr body =>
exprContainsFoldMultiSlot expr || valueContainsFoldMultiSlot body
| .letCall _ _ args body =>
exprListContainsFoldMultiSlot args || valueContainsFoldMultiSlot body
| .letLocal lets body =>
localLetsContainFoldMultiSlot lets || valueContainsFoldMultiSlot body
partial def valuesContainFoldMultiSlot : List ExtractedValue → Bool
| [] => false
| value :: rest => valueContainsFoldMultiSlot value || valuesContainFoldMultiSlot rest
partial def ctorValuesContainFoldMultiSlot : List (List ExtractedValue) → Bool
| [] => false
| fields :: rest => valuesContainFoldMultiSlot fields || ctorValuesContainFoldMultiSlot rest
end
def irConstNat? : IRExpr → Option Nat
| .u64 value => some value
| _ => none
def u8WrapExpr (expr : IRExpr) : IRExpr :=
.u64Bin .bitAnd expr (.u64 255)
def u8ShiftAmountExpr (expr : IRExpr) : IRExpr :=
.u64Bin .bitAnd expr (.u64 7)
def u32WrapExpr (expr : IRExpr) : IRExpr :=
.u64Bin .bitAnd expr (.u64 (2 ^ 32 - 1))
def u32ShiftAmountExpr (expr : IRExpr) : IRExpr :=
.u64Bin .bitAnd expr (.u64 31)
partial def supportedEqType : Ty → Bool
| .unit => true
| .bool => true
| .u8 => true
| .u32 => true
| .u64 => true
| .nat => true
| .byteArray => true
| .array item => supportedEqType item && (arrayElementSlots? item |>.isSome)
| .product left right => supportedEqType left && supportedEqType right
| .sum left right => supportedEqType left && supportedEqType right
| .struct _ _ fields => fields.all supportedEqType
| .variant _ _ ctors => ctors.all (fun fields => fields.all supportedEqType)
| _ => false
def addLiveSlot (live : List Nat) (slot : Nat) : List Nat :=
if live.contains slot then live else slot :: live
def addLiveSlots (live slots : List Nat) : List Nat :=
slots.foldl addLiveSlot live
def exprIsRelease : IRExpr → Bool
| .release _ => true
| _ => false
def removeLiveSlot (live : List Nat) (slot : Nat) : List Nat :=
live.filter fun candidate => candidate != slot
def removeLiveSlots (live slots : List Nat) : List Nat :=
slots.foldl removeLiveSlot live
def anyLiveSlot (live slots : List Nat) : Bool :=
slots.any fun slot => live.contains slot
def slotsFrom (start width : Nat) : List Nat :=
(List.range width).map fun offset => start + offset
/-- Conservative allowlist of expressions that construct a fresh array the
evaluator owns. Used to release a fold's bound source array after the loop;
anything unrecognized keeps the previous leak rather than risking a double
release. -/
partial def exprBuildsFreshArray : IRExpr → Bool
| .arrayLiteralSlots .. => true
| .byteArrayGenerate32Ptr .. => true
| .byteArrayPushPtr .. => true
| .byteArrayAppendPtr .. => true
| .byteArraySetPtr .. => true
| .byteArrayFromArrayPtr .. => true
| .byteArrayCopySlicePtr .. => true
| .heapAllocSlots .. => true
| .arrayAllocSlots .. => true
| .arrayReplicateSlots .. => true
| .arraySetSlots .. => true
| .arrayPushSlots .. => true
| .arrayAppendSlots .. => true
| .arrayExtractSlots .. => true
| .arrayMapSlots .. => true
| .arrayFilterSlots .. => true
| .arrayInsertIfInBoundsSlots .. => true
| .arrayEraseIfInBoundsSlots .. => true
| .arraySwapIfInBoundsSlots .. => true
| .arrayReverseSlots .. => true
| .letE _ _ body => exprBuildsFreshArray body
| .letCall _ _ _ body => exprBuildsFreshArray body
| .letLets _ body => exprBuildsFreshArray body
| _ => false
def arrayFoldMultiSlotAssign? (targets : List Nat) (values : List IRExpr) :
Option IRStmt :=
match values with
| .arrayFoldMultiSlot sourceWidth resultWidth reverse array start stop initValues accStart itemStart
bodyValues bodyLets bodyDone releaseOffsets _ :: _ =>
if values.length == resultWidth && targets.length == resultWidth then
let expected : List IRExpr :=
(List.range resultWidth).map fun offset =>
.arrayFoldMultiSlot sourceWidth resultWidth reverse array start stop initValues accStart
itemStart bodyValues bodyLets bodyDone releaseOffsets offset
if values == expected then
some <|
.arrayFoldMultiSlotAssign sourceWidth resultWidth reverse array start stop initValues
accStart itemStart bodyValues bodyLets bodyDone releaseOffsets targets
else
none
else
none
| .letE bindSlot bound
(.arrayFoldMultiSlot sourceWidth resultWidth reverse array start stop initValues accStart
itemStart bodyValues bodyLets bodyDone releaseOffsets _) :: _ =>
if values.length == resultWidth && targets.length == resultWidth then
let expected : List IRExpr :=
(List.range resultWidth).map fun offset =>
.letE bindSlot bound
(.arrayFoldMultiSlot sourceWidth resultWidth reverse array start stop initValues
accStart itemStart bodyValues bodyLets bodyDone releaseOffsets offset)
if values == expected then
let foldStmt :=
.arrayFoldMultiSlotAssign sourceWidth resultWidth reverse array start stop initValues
accStart itemStart bodyValues bodyLets bodyDone releaseOffsets targets
let foldStmt :=
if exprBuildsFreshArray bound then
.seq foldStmt (.release (.local bindSlot))
else
foldStmt
some (.seq (.assign bindSlot bound) foldStmt)
else
none
else
none
| _ => none
/-- The binder prefix a value-let wrapper puts in front of a fold: plain
lets and call lets, peeled so the fold underneath can convert to its
statement form with the binders hoisted in front of it. -/
partial def stripValueLetWrapper (expr : IRExpr) :
List (Sum (Nat × IRExpr) (List Nat × Nat × List IRExpr)) × IRExpr :=
match expr with
| .letE slot value body =>
let rest := stripValueLetWrapper body
(Sum.inl (slot, value) :: rest.fst, rest.snd)
| .letCall slots index args body =>
let rest := stripValueLetWrapper body
(Sum.inr (slots, index, args) :: rest.fst, rest.snd)
| other => ([], other)
def rewrapValueLetWrapper
(binds : List (Sum (Nat × IRExpr) (List Nat × Nat × List IRExpr)))
(core : IRExpr) : IRExpr :=
binds.foldr
(fun bind acc =>
match bind with
| Sum.inl (slot, value) => .letE slot value acc
| Sum.inr (slots, index, args) => .letCall slots index args acc)
core
def byteArrayFoldMultiSlotAssign? (targets : List Nat) (values : List IRExpr) :
Option IRStmt :=
match values with
| first :: _ =>
let stripped := stripValueLetWrapper first
match stripped.snd with
| .byteArrayFoldMultiSlot resultWidth ptr len start stop initValues accStart byteSlot
bodyValues bodyLets bodyDone releaseOffsets _ =>
if values.length == resultWidth && targets.length == resultWidth then
let expected : List IRExpr :=
(List.range resultWidth).map fun offset =>
rewrapValueLetWrapper stripped.fst
(.byteArrayFoldMultiSlot resultWidth ptr len start stop initValues accStart
byteSlot bodyValues bodyLets bodyDone releaseOffsets offset)
if values == expected then
let bindStmts : List IRStmt :=
stripped.fst.map fun bind =>
match bind with
| Sum.inl (slot, value) => .assign slot value
| Sum.inr (slots, index, args) => .call slots index args
let foldStmt : IRStmt :=
.byteArrayFoldMultiSlotAssign resultWidth ptr len start stop initValues accStart
byteSlot bodyValues bodyLets bodyDone releaseOffsets targets
let freshSlots :=
stripped.fst.filterMap fun bind =>
match bind with
| Sum.inl (slot, value) =>
if exprBuildsFreshArray value then some slot else none
| Sum.inr _ => none
some <|
freshSlots.foldl
(fun current slot => .seq current (.release (.local slot)))
(LeanExe.IR.seqList (bindStmts ++ [foldStmt]))
else
none
else
none
| _ => none
| _ => none
def rangeFoldMultiSlotAssign? (targets : List Nat) (values : List IRExpr) :
Option IRStmt :=
match values with
| .rangeFoldMultiSlot resultWidth start stop step initValues accStart itemSlot
bodyValues bodyLets bodyDone releaseOffsets _ :: _ =>
if values.length == resultWidth && targets.length == resultWidth then
let expected : List IRExpr :=
(List.range resultWidth).map fun offset =>
.rangeFoldMultiSlot resultWidth start stop step initValues accStart itemSlot bodyValues
bodyLets bodyDone releaseOffsets offset
if values == expected then
some <|
.rangeFoldMultiSlotAssign resultWidth start stop step initValues accStart itemSlot
bodyValues bodyLets bodyDone releaseOffsets targets
else
none
else
none
| _ => none
def loopFoldMultiSlotAssign? (targets : List Nat) (values : List IRExpr) :
Option IRStmt :=
match values with
| .loopFoldMultiSlot resultWidth initValues accStart bodyValues bodyLets bodyDone
releaseOffsets _ :: _ =>
if values.length == resultWidth && targets.length == resultWidth then
let expected : List IRExpr :=
(List.range resultWidth).map fun offset =>
.loopFoldMultiSlot resultWidth initValues accStart bodyValues bodyLets bodyDone
releaseOffsets offset
if values == expected then
some <|
.loopFoldMultiSlotAssign resultWidth initValues accStart bodyValues bodyLets bodyDone
releaseOffsets targets
else
none
else
none
| _ => none
def foldMultiSlotAssign? (targets : List Nat) (values : List IRExpr) : Option IRStmt :=
match arrayFoldMultiSlotAssign? targets values with
| some stmt => some stmt
| none =>
match byteArrayFoldMultiSlotAssign? targets values with
| some stmt => some stmt
| none =>
match rangeFoldMultiSlotAssign? targets values with
| some stmt => some stmt
| none => loopFoldMultiSlotAssign? targets values
mutual
partial def tyReleaseOwnerSlotOffsetsAt (base : Nat) : Ty → List Nat
| .array item =>
if supportedArrayElementType item then [base] else []
| .byteArray => [base]
| .recVariant _ _ => [base]
| .product left right =>
addLiveSlots
(tyReleaseOwnerSlotOffsetsAt base left)
(tyReleaseOwnerSlotOffsetsAt (base + internalSlots left) right)
| .sum left right =>
addLiveSlots
(tyReleaseOwnerSlotOffsetsAt (base + 1) left)
(tyReleaseOwnerSlotOffsetsAt (base + 1 + internalSlots left) right)
| .struct _ _ fields => tyListReleaseOwnerSlotOffsetsAt base fields
| .variant _ _ ctors => tyCtorListReleaseOwnerSlotOffsetsAt (base + 1) ctors
| _ => []
partial def tyListReleaseOwnerSlotOffsetsAt (base : Nat) : List Ty → List Nat
| [] => []
| ty :: rest =>
addLiveSlots
(tyReleaseOwnerSlotOffsetsAt base ty)
(tyListReleaseOwnerSlotOffsetsAt (base + internalSlots ty) rest)
partial def tyCtorListReleaseOwnerSlotOffsetsAt (base : Nat) : List (List Ty) → List Nat
| [] => []
| fields :: rest =>
let width := fields.foldl (fun total ty => total + internalSlots ty) 0
addLiveSlots
(tyListReleaseOwnerSlotOffsetsAt base fields)
(tyCtorListReleaseOwnerSlotOffsetsAt (base + width) rest)
end
def tyReleaseOwnerSlotOffsets (ty : Ty) : List Nat :=
tyReleaseOwnerSlotOffsetsAt 0 ty
mutual
partial def tyNonrecursiveReleaseOwnerSlotOffsetsAt (base : Nat) : Ty → List Nat
| .array item =>
if supportedArrayElementType item then [base] else []
| .byteArray => [base]
| .recVariant _ _ => []
| .product left right =>
addLiveSlots
(tyNonrecursiveReleaseOwnerSlotOffsetsAt base left)
(tyNonrecursiveReleaseOwnerSlotOffsetsAt (base + internalSlots left) right)
| .sum left right =>
addLiveSlots
(tyNonrecursiveReleaseOwnerSlotOffsetsAt (base + 1) left)
(tyNonrecursiveReleaseOwnerSlotOffsetsAt (base + 1 + internalSlots left) right)
| .struct _ _ fields => tyListNonrecursiveReleaseOwnerSlotOffsetsAt base fields
| .variant _ _ ctors => tyCtorListNonrecursiveReleaseOwnerSlotOffsetsAt (base + 1) ctors
| _ => []
partial def tyListNonrecursiveReleaseOwnerSlotOffsetsAt (base : Nat) : List Ty → List Nat
| [] => []
| ty :: rest =>
addLiveSlots
(tyNonrecursiveReleaseOwnerSlotOffsetsAt base ty)
(tyListNonrecursiveReleaseOwnerSlotOffsetsAt (base + internalSlots ty) rest)
partial def tyCtorListNonrecursiveReleaseOwnerSlotOffsetsAt
(base : Nat) :
List (List Ty) → List Nat
| [] => []
| fields :: rest =>
let width := fields.foldl (fun total ty => total + internalSlots ty) 0
addLiveSlots
(tyListNonrecursiveReleaseOwnerSlotOffsetsAt base fields)
(tyCtorListNonrecursiveReleaseOwnerSlotOffsetsAt (base + width) rest)
end
def tyNonrecursiveReleaseOwnerSlotOffsets (ty : Ty) : List Nat :=
tyNonrecursiveReleaseOwnerSlotOffsetsAt 0 ty
partial def tyContainsHeapPointer : Ty → Bool
| .byteArray => true
| .array _ => true
| .recVariant _ _ => true
| .product left right => tyContainsHeapPointer left || tyContainsHeapPointer right
| .sum left right => tyContainsHeapPointer left || tyContainsHeapPointer right
| .struct _ _ fields => fields.any tyContainsHeapPointer
| .variant _ _ ctors => ctors.any fun ctor => ctor.any tyContainsHeapPointer
| .unit => false
| .bool => false
| .u8 => false
| .u32 => false
| .u64 => false
| .nat => false
def slotsAtOffsets (slots offsets : List Nat) : List Nat :=
offsets.filterMap fun offset => slots[offset]?
def summarizedCallResultOwnerSlots
(summaries : Array (List Nat))
(index : Nat)
(slots : List Nat) :
List Nat :=
match summaries[index]? with
| some offsets => slotsAtOffsets slots offsets
| none => []
def functionNameAtIndex? (ctx : Context) (index : Nat) : Option Name :=
if h : index < ctx.names.size then
some ctx.names[index]
else
none
def callResultReleaseOwnerSlots (ctx : Context) (index : Nat) (slots : List Nat) : List Nat :=
match ctx.freshResultOwnerOffsets[index]? with
| some _ => summarizedCallResultOwnerSlots ctx.freshResultOwnerOffsets index slots
| none =>
match functionNameAtIndex? ctx index with
| some name =>
match functionSignature? ctx name with
| some sig =>
if sig.params.any tyContainsHeapPointer then
[]
else
slotsAtOffsets slots (tyReleaseOwnerSlotOffsets sig.result)
| none => []
| none => []
def callResultNonrecursiveReleaseOwnerSlots
(ctx : Context)
(index : Nat)
(slots : List Nat) :
List Nat :=
match functionNameAtIndex? ctx index with
| some name =>
match functionSignature? ctx name with
| some sig =>
let nonrecursiveSlots :=
slotsAtOffsets slots (tyNonrecursiveReleaseOwnerSlotOffsets sig.result)
(callResultReleaseOwnerSlots ctx index slots).filter fun slot =>
nonrecursiveSlots.contains slot
| none => []
| none => []
def callResultMayAliasParamOwners (ctx : Context) (index : Nat) : Bool :=
match functionNameAtIndex? ctx index with
| some name =>
match functionSignature? ctx name with
| some sig =>
if sig.params.any tyContainsHeapPointer then
let freshOffsets :=
match ctx.freshResultOwnerOffsets[index]? with
| some offsets => offsets
| none => []
(tyReleaseOwnerSlotOffsets sig.result).any fun offset =>
!freshOffsets.contains offset
else
false
| none => false
| none => false
mutual
partial def exprUsedSlots : IRExpr → List Nat
| .local index => [index]
| .trap => []
| .u64 _ => []
| .f64SqrtBits value => exprUsedSlots value
| .floatUnary _ value => exprUsedSlots value
| .u64Bin _ left right =>
addLiveSlots (exprUsedSlots left) (exprUsedSlots right)
| .ite cond thenValue elseValue =>
addLiveSlots (addLiveSlots (condUsedSlots cond) (exprUsedSlots thenValue))
(exprUsedSlots elseValue)
| .letE slot value body =>
let bodyLive := exprUsedSlots body
if bodyLive.contains slot || exprIsRelease value then
addLiveSlots (removeLiveSlot bodyLive slot) (exprUsedSlots value)
else
bodyLive
| .letCall slots _ args body =>
let bodyLive := exprUsedSlots body
if anyLiveSlot bodyLive slots then
addLiveSlots (removeLiveSlots bodyLive slots) (exprListUsedSlots args)
else
bodyLive
| .letLets lets body =>
(pruneLocalLetsWithLive lets (exprUsedSlots body)).snd
| .runtimeStat _ => []
| .release ptr => exprUsedSlots ptr
| .arrayAllocSlots _ _ cells => exprUsedSlots cells
| .heapAllocSlots _ _ values => exprListUsedSlots values
| .heapLoadSlot ptr _ => exprUsedSlots ptr
| .arrayReplicateSlots _ _ _ cells values =>
addLiveSlots (exprUsedSlots cells) (exprListUsedSlots values)
| .arrayLiteralSlots _ _ elements =>
elements.foldl
(fun acc element => addLiveSlots acc (exprListUsedSlots element.snd))
[]
| .arraySize array => exprUsedSlots array
| .arrayGetSlot _ _ array index =>
addLiveSlots (exprUsedSlots array) (exprUsedSlots index)
| .arraySetSlots _ _ _ array index values =>
addLiveSlots (addLiveSlots (exprUsedSlots array) (exprUsedSlots index))
(exprListUsedSlots values)
| .arrayPushSlots _ _ _ array values =>
addLiveSlots (exprUsedSlots array) (exprListUsedSlots values)
| .arrayPopSlots _ _ array => exprUsedSlots array
| .arrayAppendSlots _ _ left right =>
addLiveSlots (exprUsedSlots left) (exprUsedSlots right)
| .arrayExtractSlots _ _ array start stop =>
addLiveSlots (addLiveSlots (exprUsedSlots array) (exprUsedSlots start))
(exprUsedSlots stop)
| .arrayMapSlots sourceWidth _ _ _ array itemStart bodyValues bodyLets =>
let bodyLive := removeLiveSlots
(pruneLocalLetsWithLive bodyLets (exprListUsedSlots bodyValues)).snd
(slotsFrom itemStart sourceWidth)
addLiveSlots (exprUsedSlots array) bodyLive
| .arrayFoldMultiSlot sourceWidth resultWidth _reverse array start stop initValues accStart
itemStart bodyValues bodyLets bodyDone _releaseOffsets _ =>
let bodyLive := addLiveSlots (exprListUsedSlots bodyValues) (exprUsedSlots bodyDone)
let bodyFree := removeLiveSlots
(removeLiveSlots (pruneLocalLetsWithLive bodyLets bodyLive).snd
(slotsFrom accStart resultWidth))
(slotsFrom itemStart sourceWidth)
addLiveSlots
(addLiveSlots
(addLiveSlots (exprUsedSlots array) (exprUsedSlots start))
(exprUsedSlots stop))
(addLiveSlots (exprListUsedSlots initValues) bodyFree)
| .arrayFindIdxSlots sourceWidth array itemStart predicate _ =>
let predicateFree := removeLiveSlots (exprUsedSlots predicate)
(slotsFrom itemStart sourceWidth)
addLiveSlots (exprUsedSlots array) predicateFree
| .arrayFindSlot sourceWidth array itemStart predicate _ =>
let predicateFree := removeLiveSlots (exprUsedSlots predicate)
(slotsFrom itemStart sourceWidth)
addLiveSlots (exprUsedSlots array) predicateFree
| .arrayEqSlots width left right leftStart rightStart predicate =>
let predicateFree :=
removeLiveSlots
(removeLiveSlots (exprUsedSlots predicate) (slotsFrom leftStart width))
(slotsFrom rightStart width)
addLiveSlots (addLiveSlots (exprUsedSlots left) (exprUsedSlots right))
predicateFree
| .arrayAnySlots sourceWidth array start stop itemStart predicate _ =>
let predicateFree := removeLiveSlots (exprUsedSlots predicate)
(slotsFrom itemStart sourceWidth)
addLiveSlots
(addLiveSlots
(addLiveSlots (exprUsedSlots array) (exprUsedSlots start))
(exprUsedSlots stop))
predicateFree
| .arrayFilterSlots sourceWidth _ array start stop itemStart predicate =>
let predicateFree := removeLiveSlots (exprUsedSlots predicate)
(slotsFrom itemStart sourceWidth)
addLiveSlots
(addLiveSlots
(addLiveSlots (exprUsedSlots array) (exprUsedSlots start))
(exprUsedSlots stop))
predicateFree
| .arrayInsertIfInBoundsSlots _ _ _ array index values =>
addLiveSlots (addLiveSlots (exprUsedSlots array) (exprUsedSlots index))
(exprListUsedSlots values)
| .arrayEraseIfInBoundsSlots _ _ array index =>
addLiveSlots (exprUsedSlots array) (exprUsedSlots index)
| .arraySwapIfInBoundsSlots _ _ array left right =>
addLiveSlots (addLiveSlots (exprUsedSlots array) (exprUsedSlots left))
(exprUsedSlots right)
| .arrayReverseSlots _ _ array => exprUsedSlots array
| .byteArrayGet ptr len index =>
addLiveSlots (addLiveSlots (exprUsedSlots ptr) (exprUsedSlots len))
(exprUsedSlots index)
| .byteArrayLoad32 ptr len index =>
addLiveSlots (addLiveSlots (exprUsedSlots ptr) (exprUsedSlots len))
(exprUsedSlots index)
| .byteArrayGenerate32Ptr len indexSlot body =>
addLiveSlots (exprUsedSlots len) (removeLiveSlot (exprUsedSlots body) indexSlot)
| .byteArrayPushPtr ptr len value =>
addLiveSlots (addLiveSlots (exprUsedSlots ptr) (exprUsedSlots len))
(exprUsedSlots value)
| .byteArrayAppendPtr leftPtr leftLen rightPtr rightLen =>
addLiveSlots
(addLiveSlots (addLiveSlots (exprUsedSlots leftPtr) (exprUsedSlots leftLen))
(exprUsedSlots rightPtr))
(exprUsedSlots rightLen)
| .byteArraySetPtr ptr len index value =>
addLiveSlots
(addLiveSlots (addLiveSlots (exprUsedSlots ptr) (exprUsedSlots len))
(exprUsedSlots index))
(exprUsedSlots value)
| .byteArrayFromArrayPtr array => exprUsedSlots array
| .byteArrayCopySlicePtr srcPtr srcLen srcOff destPtr destLen destOff copyLen =>
addLiveSlots
(addLiveSlots
(addLiveSlots
(addLiveSlots
(addLiveSlots
(addLiveSlots (exprUsedSlots srcPtr) (exprUsedSlots srcLen))
(exprUsedSlots srcOff))
(exprUsedSlots destPtr))
(exprUsedSlots destLen))
(exprUsedSlots destOff))
(exprUsedSlots copyLen)
| .byteArrayEq leftPtr leftLen rightPtr rightLen =>
addLiveSlots
(addLiveSlots (addLiveSlots (exprUsedSlots leftPtr) (exprUsedSlots leftLen))
(exprUsedSlots rightPtr))
(exprUsedSlots rightLen)
| .byteArrayFindIdx ptr len start byteSlot predicate _ =>
addLiveSlots
(addLiveSlots (addLiveSlots (exprUsedSlots ptr) (exprUsedSlots len))
(exprUsedSlots start))
(removeLiveSlot (exprUsedSlots predicate) byteSlot)
| .byteArrayFoldMultiSlot resultWidth ptr len start stop initValues accStart byteSlot
bodyValues bodyLets bodyDone _releaseOffsets _ =>
let bodyLive := addLiveSlots (exprListUsedSlots bodyValues) (exprUsedSlots bodyDone)
let bodyFree := removeLiveSlot
(removeLiveSlots (pruneLocalLetsWithLive bodyLets bodyLive).snd
(slotsFrom accStart resultWidth))
byteSlot
addLiveSlots
(addLiveSlots
(addLiveSlots
(addLiveSlots (exprUsedSlots ptr) (exprUsedSlots len))
(exprUsedSlots start))
(exprUsedSlots stop))
(addLiveSlots (exprListUsedSlots initValues) bodyFree)
| .rangeFoldMultiSlot resultWidth start stop step initValues accStart itemSlot
bodyValues bodyLets bodyDone _releaseOffsets _ =>
let bodyLive := addLiveSlots (exprListUsedSlots bodyValues) (exprUsedSlots bodyDone)
let bodyFree := removeLiveSlot
(removeLiveSlots (pruneLocalLetsWithLive bodyLets bodyLive).snd
(slotsFrom accStart resultWidth))
itemSlot
addLiveSlots
(addLiveSlots
(addLiveSlots (exprUsedSlots start) (exprUsedSlots stop))
(exprUsedSlots step))
(addLiveSlots (exprListUsedSlots initValues) bodyFree)
| .loopFoldMultiSlot resultWidth initValues accStart bodyValues bodyLets bodyDone
_releaseOffsets _ =>
let bodyLive := addLiveSlots (exprListUsedSlots bodyValues) (exprUsedSlots bodyDone)
let bodyFree :=
removeLiveSlots (pruneLocalLetsWithLive bodyLets bodyLive).snd
(slotsFrom accStart resultWidth)
addLiveSlots (exprListUsedSlots initValues) bodyFree
| .heapLinearPredicate ptr _ fieldSlotCount _ fieldStart predicate _ _ =>
addLiveSlots (exprUsedSlots ptr)
(removeLiveSlots (exprUsedSlots predicate) (slotsFrom fieldStart fieldSlotCount))
| .call _ args => exprListUsedSlots args
partial def condUsedSlots : IRCond → List Nat
| .true => []
| .false => []
| .eqU64 left right =>
addLiveSlots (exprUsedSlots left) (exprUsedSlots right)
| .ltU64 left right =>
addLiveSlots (exprUsedSlots left) (exprUsedSlots right)
| .leU64 left right =>
addLiveSlots (exprUsedSlots left) (exprUsedSlots right)
| .not cond => condUsedSlots cond
| .and left right =>
addLiveSlots (condUsedSlots left) (condUsedSlots right)
| .or left right =>
addLiveSlots (condUsedSlots left) (condUsedSlots right)
partial def exprListUsedSlots (exprs : List IRExpr) : List Nat :=
exprs.foldl (fun live expr => addLiveSlots live (exprUsedSlots expr)) []
partial def valueUsedSlots : ExtractedValue → List Nat
| .scalar expr => exprUsedSlots expr
| .array owner ptr => addLiveSlots (exprUsedSlots owner) (exprUsedSlots ptr)
| .byteArray owner ptr len =>
addLiveSlots (exprUsedSlots owner) (addLiveSlots (exprUsedSlots ptr) (exprUsedSlots len))
| .product left right =>
addLiveSlots (valueUsedSlots left) (valueUsedSlots right)
| .sum tag left right =>
addLiveSlots (addLiveSlots (exprUsedSlots tag) (valueUsedSlots left))
(valueUsedSlots right)
| .struct _ fields =>
fields.foldl (fun live field => addLiveSlots live (valueUsedSlots field)) []
| .variant _ tag ctors =>
ctors.foldl
(fun live fields =>
fields.foldl (fun acc field => addLiveSlots acc (valueUsedSlots field)) live)
(exprUsedSlots tag)
| .recursiveVariant _ tag ctors =>
ctors.foldl
(fun live fields =>
fields.foldl (fun acc field => addLiveSlots acc (valueUsedSlots field.snd)) live)
(exprUsedSlots tag)
| .heapVariant _ ptr => exprUsedSlots ptr
| .ite cond thenValue elseValue =>
addLiveSlots (addLiveSlots (condUsedSlots cond) (valueUsedSlots thenValue))
(valueUsedSlots elseValue)
| .letE slot value body =>
let bodyLive := valueUsedSlots body
if bodyLive.contains slot || exprIsRelease value then
addLiveSlots (removeLiveSlot bodyLive slot) (exprUsedSlots value)
else
bodyLive
| .letCall slots _ args body =>
let bodyLive := valueUsedSlots body
if anyLiveSlot bodyLive slots then
addLiveSlots (removeLiveSlots bodyLive slots) (exprListUsedSlots args)
else
bodyLive
| .letLocal lets body =>
(pruneLocalLetsWithLive lets (valueUsedSlots body)).snd
partial def pruneLocalLetWithLive (localLet : LeanExe.IR.LocalLet) (liveAfter : List Nat) :
Option LeanExe.IR.LocalLet × List Nat :=
match localLet with
| .expr slot value =>
if liveAfter.contains slot || exprIsRelease value then
(some (.expr slot value), addLiveSlots (removeLiveSlot liveAfter slot)
(exprUsedSlots value))
else
(none, liveAfter)
| .call slots index args =>
if anyLiveSlot liveAfter slots then
(some (.call slots index args), addLiveSlots (removeLiveSlots liveAfter slots)
(exprListUsedSlots args))
else
(none, liveAfter)
| .slots slots values =>
match foldMultiSlotAssign? slots values with
| some _ =>
if anyLiveSlot liveAfter slots then
(some (.slots slots values),
addLiveSlots (removeLiveSlots liveAfter slots) (exprListUsedSlots values))
else
(none, liveAfter)
| none =>
let kept := (slots.zip values).filter fun item => liveAfter.contains item.fst
if kept.isEmpty then
(none, liveAfter)
else
let keptSlots := kept.map Prod.fst
let keptValues := kept.map Prod.snd
(some (.slots keptSlots keptValues),