forked from roc-lang/roc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreset_reuse.rs
More file actions
1397 lines (1247 loc) · 57.5 KB
/
reset_reuse.rs
File metadata and controls
1397 lines (1247 loc) · 57.5 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
// This program was written by Jelle Teeuwissen within a final
// thesis project of the Computing Science master program at Utrecht
// University under supervision of Wouter Swierstra (w.s.swierstra@uu.nl).
// Implementation based of Reference Counting with Frame Limited Reuse
// https://www.microsoft.com/en-us/research/uploads/prod/2021/11/flreuse-tr.pdf
use std::hash::Hash;
use crate::ir::{
BranchInfo, Expr, JoinPointId, ModifyRc, Param, Proc, ProcLayout, ReuseToken, Stmt,
UpdateModeId, UpdateModeIds,
};
use crate::layout::{InLayout, LayoutInterner, LayoutRepr, STLayoutInterner, UnionLayout};
use bumpalo::Bump;
use bumpalo::collections::vec::Vec;
use bumpalo::collections::CollectIn;
use roc_collections::{MutMap, MutSet};
use roc_module::low_level::LowLevel;
use roc_module::symbol::{IdentIds, ModuleId, Symbol};
use roc_target::Target;
/**
Insert reset and reuse operations into the IR.
To allow for the reuse of memory allocation when said memory is no longer used.
*/
pub fn insert_reset_reuse_operations<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i STLayoutInterner<'a>,
home: ModuleId,
target: Target,
ident_ids: &'i mut IdentIds,
update_mode_ids: &'i mut UpdateModeIds,
procs: &mut MutMap<(Symbol, ProcLayout<'a>), Proc<'a>>,
) {
let mut global_layouts = SymbolLayout::default();
for (symbol, _layout) in procs.keys() {
global_layouts.insert(*symbol, LayoutOption::GloballyDefined);
}
for proc in procs.values_mut() {
let new_proc = insert_reset_reuse_operations_proc(
arena,
layout_interner,
target,
home,
ident_ids,
update_mode_ids,
global_layouts.clone(),
proc.clone(),
);
*proc = new_proc;
}
}
fn insert_reset_reuse_operations_proc<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i STLayoutInterner<'a>,
target: Target,
home: ModuleId,
ident_ids: &'i mut IdentIds,
update_mode_ids: &'i mut UpdateModeIds,
mut symbol_layout: SymbolLayout<'a>,
mut proc: Proc<'a>,
) -> Proc<'a> {
for (layout, symbol) in proc.args {
symbol_layout.insert(*symbol, LayoutOption::Layout(layout));
}
let mut env = ReuseEnvironment {
target,
symbol_tags: MutMap::default(),
non_unique_symbols: MutSet::default(),
reuse_tokens: MutMap::default(),
symbol_layouts: symbol_layout,
joinpoint_reuse_tokens: MutMap::default(),
jump_reuse_tokens: MutMap::default(),
};
let new_body = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
&mut env,
arena.alloc(proc.body),
);
// All reuse tokens either have to be used by reuse or not be inserted at all at the reset (and removed from the environment).
debug_assert!(env.reuse_tokens.is_empty());
proc.body = new_body.clone();
proc
}
fn insert_reset_reuse_operations_stmt<'a, 'i>(
arena: &'a Bump,
layout_interner: &'i STLayoutInterner<'a>,
home: ModuleId,
ident_ids: &'i mut IdentIds,
update_mode_ids: &'i mut UpdateModeIds,
environment: &mut ReuseEnvironment<'a>,
stmt: &'a Stmt<'a>,
) -> &'a Stmt<'a> {
match stmt {
Stmt::Let(_, _, _, _) => {
// Collect all the subsequent let bindings (including the current one).
// To prevent the stack from overflowing when there are many let bindings.
let mut triples = vec![];
let mut current_stmt = stmt;
while let Stmt::Let(binding, expr, layout, next_stmt) = current_stmt {
triples.push((binding, expr, layout));
current_stmt = next_stmt
}
debug_assert!(
!triples.is_empty(),
"Expected at least one let binding in the vector"
);
debug_assert!(
!matches!(current_stmt, Stmt::Let(_, _, _, _)),
"All let bindings should be in the vector"
);
// Update the triplets with reuse operations. Making sure to update the environment before the next let binding.
let mut new_triplets = vec![];
for (binding, expr, layout) in triples {
let new_expr = match expr {
Expr::Tag {
tag_layout,
tag_id,
arguments,
reuse,
} => {
debug_assert!(reuse.is_none());
// The value of the tag is currently only used in the case of nullable recursive unions.
// But for completeness we add every kind of union to the layout_tags.
environment.add_symbol_tag(*binding, *tag_id);
// Check if the tag id for this layout can be reused at all.
match can_reuse_union_layout_tag(*tag_layout, Option::Some(*tag_id)) {
// The tag is reusable.
Reuse::Reusable(union_layout) => {
// See if we have a token.
match environment.pop_reuse_token(&get_reuse_layout_info(
layout_interner,
union_layout,
)) {
// We have a reuse token for this layout, use it.
Some(TokenWithInLayout {
token: mut reuse_token,
inlayout: layout_info,
}) => {
if layout_info == layout {
// The reuse token layout is the same, we can use it without casting.
(
None,
Expr::Tag {
tag_layout: *tag_layout,
tag_id: *tag_id,
arguments,
reuse: Some(reuse_token),
},
)
} else {
// The reuse token has a different layout from the tag, we need to pointercast it before.
let new_symbol =
Symbol::new(home, ident_ids.gen_unique());
let ptr_cast = move |new_let| {
arena.alloc(Stmt::Let(
new_symbol,
create_ptr_cast(arena, reuse_token.symbol),
*layout,
new_let,
))
};
// we now want to reuse the cast pointer
reuse_token.symbol = new_symbol;
(
Some(ptr_cast),
Expr::Tag {
tag_layout: *tag_layout,
tag_id: *tag_id,
arguments,
reuse: Some(reuse_token),
},
)
}
}
// We have no reuse token available, keep the old expression with a fresh allocation.
None => (None, expr.clone()),
}
}
// We cannot reuse this tag id because it's a null pointer.
Reuse::Nonreusable => (None, expr.clone()),
}
}
_ => (None, expr.clone()),
};
environment.add_symbol_layout(*binding, layout);
new_triplets.push((binding, new_expr, layout))
}
let new_continuation = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
environment,
current_stmt,
);
new_triplets.into_iter().rev().fold(
new_continuation,
|new_continuation, (binding, (opt_ptr_cast, new_expr), layout)| {
let new_let =
arena.alloc(Stmt::Let(*binding, new_expr, *layout, new_continuation));
// if the layout for the reuse does not match that of the reset, use PtrCast to convert the layout.
match opt_ptr_cast {
Some(ptr_cast) => ptr_cast(new_let),
None => new_let,
}
},
)
}
Stmt::Switch {
cond_symbol,
cond_layout,
branches,
default_branch,
ret_layout,
} => {
macro_rules! update_env_with_constructor {
($branch_env:expr, $info:expr) => {{
match $info {
BranchInfo::Constructor {
scrutinee,
tag_id: tag,
..
} => {
$branch_env.add_symbol_tag(*scrutinee, *tag);
}
BranchInfo::Unique {
scrutinee,
unique: false,
} => {
$branch_env.non_unique_symbols.insert(*scrutinee);
}
BranchInfo::None
| BranchInfo::List { .. }
| BranchInfo::Unique { unique: true, .. } => {}
}
}};
}
let new_branches = branches
.iter()
.map(|(tag_id, info, branch)| {
let mut branch_env = environment.clone();
update_env_with_constructor!(branch_env, info);
let new_branch = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
&mut branch_env,
branch,
);
(*tag_id, info.clone(), new_branch, branch_env)
})
.collect_in::<Vec<_>>(arena);
let new_default_branch = {
let (info, branch) = default_branch;
let mut branch_env = environment.clone();
update_env_with_constructor!(branch_env, info);
let new_branch = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
&mut branch_env,
branch,
);
(info.clone(), new_branch, branch_env)
};
// First we determine the minimum of reuse tokens available for each layout.
let layout_min_reuse_tokens = {
let branch_envs = {
let mut branch_environments =
Vec::with_capacity_in(new_branches.len() + 1, arena);
for (_, _, _, branch_env) in new_branches.iter() {
branch_environments.push(branch_env);
}
branch_environments.push(&new_default_branch.2);
branch_environments
};
let layout_min_reuse_tokens =
environment.reuse_tokens.keys().copied().map(|layout| {
let min_reuse_tokens = branch_envs
.iter()
.map(|branch_environment| {
branch_environment
.reuse_tokens
.get(&layout)
.map_or(0, |tokens| tokens.len())
})
.min()
.expect("There should be at least one branch");
(layout, min_reuse_tokens)
});
layout_min_reuse_tokens.collect::<MutMap<_, _>>()
};
// Then we drop any unused reuse tokens in branches where the minimum is not reached.
let msg =
"All layouts in the environment should be in the layout_min_reuse_tokens map.";
let newer_branches = Vec::from_iter_in(
new_branches
.iter()
.map(|(label, info, branch, branch_env)| {
let unused_tokens = branch_env
.reuse_tokens
.iter()
.flat_map(|(layout, reuse_tokens)| {
let min_reuse_tokens =
layout_min_reuse_tokens.get(layout).expect(msg);
&reuse_tokens[*min_reuse_tokens..]
})
.map(|token_with_layout| token_with_layout.token);
let newer_branch = drop_unused_reuse_tokens(arena, unused_tokens, branch);
(*label, info.clone(), newer_branch.clone())
}),
arena,
)
.into_bump_slice();
let newer_default_branch = {
// let (info, branch, branch_env) = new_default_branch;
let unused_tokens= new_default_branch.2.reuse_tokens.iter().flat_map(|(layout, reuse_tokens) |{
let min_reuse_tokens = layout_min_reuse_tokens.get(layout).expect("All layouts in the environment should be in the layout_min_reuse_tokens map.");
&reuse_tokens[*min_reuse_tokens..]
}).map(|token_with_layout|{token_with_layout.token});
let newer_branch =
drop_unused_reuse_tokens(arena, unused_tokens, new_default_branch.1);
(new_default_branch.0, newer_branch)
};
// And finally we update the current environment to reflect the correct number of reuse tokens.
for (layout, reuse_tokens) in environment.reuse_tokens.iter_mut() {
let min_reuse_tokens = layout_min_reuse_tokens.get(layout).expect(
"All layouts in the environment should be in the layout_min_reuse_tokens map.",
);
reuse_tokens.truncate(*min_reuse_tokens)
}
// And remove any layouts that are no longer used.
environment
.reuse_tokens
.retain(|_, reuse_tokens| !reuse_tokens.is_empty());
// Propagate jump reuse tokens upwards.
environment.propagate_jump_reuse_tokens(
new_branches
.into_iter()
.map(|(_, _, _, branch_env)| branch_env)
.chain([new_default_branch.2]),
);
arena.alloc(Stmt::Switch {
cond_symbol: *cond_symbol,
cond_layout: *cond_layout,
branches: newer_branches,
default_branch: newer_default_branch,
ret_layout: *ret_layout,
})
}
Stmt::Refcounting(rc, continuation) => {
enum SymbolIsUnique {
Never,
Always(Symbol),
MustCheck(Symbol),
}
let can_reuse = match rc {
ModifyRc::Dec(symbol) | ModifyRc::DecRef(symbol) => {
// can only reuse if the symbol is (potentially) unique
if environment.non_unique_symbols.contains(symbol) {
SymbolIsUnique::Never
} else {
SymbolIsUnique::MustCheck(*symbol)
}
}
ModifyRc::Free(symbol) => {
// a free'd symbol is guaranteed to be unique
SymbolIsUnique::Always(*symbol)
}
ModifyRc::Inc(_, _) => {
// an incremented symbol is never unique
SymbolIsUnique::Never
}
};
enum ResetOperation {
Reset,
ResetRef,
ClearTagId,
Nothing,
}
let reuse_pair = match can_reuse {
SymbolIsUnique::MustCheck(symbol) | SymbolIsUnique::Always(symbol) => {
// Get the layout of the symbol from where it is defined.
let layout_option = environment.get_symbol_layout(symbol);
// If the symbol is defined in the current proc, we can use the layout from the environment.
match layout_option {
LayoutOption::Layout(layout) => {
match symbol_layout_reusability(
layout_interner,
environment,
&symbol,
layout,
) {
Reuse::Reusable(union_layout) => {
let (reuse_symbol, reset_op) = match rc {
ModifyRc::Dec(_) => (
Symbol::new(home, ident_ids.gen_unique()),
ResetOperation::Reset,
),
ModifyRc::DecRef(_) => (
Symbol::new(home, ident_ids.gen_unique()),
ResetOperation::ResetRef,
),
ModifyRc::Free(_) => {
if union_layout
.stores_tag_id_in_pointer(environment.target)
{
(
Symbol::new(home, ident_ids.gen_unique()),
ResetOperation::ClearTagId,
)
} else {
(symbol, ResetOperation::Nothing)
}
}
_ => unreachable!(),
};
let reuse_token = ReuseToken {
symbol: reuse_symbol,
update_mode: update_mode_ids.next_id(),
// for now, always overwrite the tag ID just to be sure
update_tag_id: true,
};
let owned_layout = **layout;
environment.push_reuse_token(
arena,
get_reuse_layout_info(layout_interner, union_layout),
reuse_token,
layout,
);
Some((
owned_layout,
union_layout,
symbol,
reuse_token,
reset_op,
))
}
Reuse::Nonreusable => None,
}
}
_ => None,
}
}
SymbolIsUnique::Never => {
// We don't need to do anything for an inc or symbols known to be non-unique.
None
}
};
let new_continuation = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
environment,
continuation,
);
// If we inserted a reuse token, we need to insert a reset reuse operation if the reuse token is consumed.
if let Some((layout, union_layout, symbol, reuse_token, reset_op)) = reuse_pair {
let stack_reuse_token = environment
.peek_reuse_token(&get_reuse_layout_info(layout_interner, union_layout));
match stack_reuse_token {
Some(token_with_layout) if token_with_layout.token == reuse_token => {
// The token we inserted is still on the stack, so we don't need to insert a reset operation.
// We do need to remove the token from the environment. To prevent errors higher in the tree.
let _ = environment
.pop_reuse_token(&get_reuse_layout_info(layout_interner, union_layout));
}
_ => {
// The token we inserted is no longer on the stack, it must have been consumed.
// So we need to insert a reset operation.
match reset_op {
ResetOperation::Reset => {
// a dec will be replaced by a reset.
let reset_expr = Expr::Reset {
symbol,
update_mode: reuse_token.update_mode,
};
return arena.alloc(Stmt::Let(
reuse_token.symbol,
reset_expr,
layout,
new_continuation,
));
}
ResetOperation::ResetRef => {
// a decref will be replaced by a resetref.
let reset_expr = Expr::ResetRef {
symbol,
update_mode: reuse_token.update_mode,
};
return arena.alloc(Stmt::Let(
reuse_token.symbol,
reset_expr,
layout,
new_continuation,
));
}
ResetOperation::ClearTagId => {
let reset_expr = Expr::Call(crate::ir::Call {
call_type: crate::ir::CallType::LowLevel {
op: LowLevel::PtrClearTagId,
update_mode: update_mode_ids.next_id(),
},
arguments: arena.alloc([symbol]),
});
return arena.alloc(Stmt::Let(
reuse_token.symbol,
reset_expr,
layout,
new_continuation,
));
}
ResetOperation::Nothing => {
// the reuse token is already in a valid state
return new_continuation;
}
}
}
}
}
// TODO update jump join points for the returned environment.
arena.alloc(Stmt::Refcounting(*rc, new_continuation))
}
Stmt::Ret(_) => {
// The return statement just doesn't consume any tokens. Dropping these tokens will be handled before.
stmt
}
Stmt::Expect {
condition,
region,
lookups,
variables,
remainder,
} => {
let new_remainder = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
environment,
remainder,
);
arena.alloc(Stmt::Expect {
condition: *condition,
region: *region,
lookups,
variables,
remainder: new_remainder,
})
}
Stmt::Dbg {
source_location,
source,
symbol,
variable,
remainder,
} => {
let new_remainder = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
environment,
remainder,
);
arena.alloc(Stmt::Dbg {
source_location,
source,
symbol: *symbol,
variable: *variable,
remainder: new_remainder,
})
}
Stmt::Join {
id: joinpoint_id,
parameters,
body,
remainder,
} => {
// First we evaluate the remainder, to see what reuse tokens are available at each jump. We generate code as if no reuse tokens are used.
// Then we evaluate the body, to see what reuse tokens are consumed by the body.
// - If no reuse tokens are consumed (or when there were no available in the previous step), we stop here and return the first pass symbols.
// Then we evaluate the body and remainder again, given the consumed reuse tokens. And we update the joinpoint parameters.
let (first_pass_remainder_environment, first_pass_remainder) = {
let mut first_pass_environment = environment.clone();
first_pass_environment.add_joinpoint_reuse_tokens(
*joinpoint_id,
JoinPointReuseTokens::RemainderFirst,
);
let first_pass_remainder = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
&mut first_pass_environment,
remainder,
);
first_pass_environment.remove_joinpoint_reuse_tokens(*joinpoint_id);
(first_pass_environment, first_pass_remainder)
};
let max_reuse_tokens =
match first_pass_remainder_environment.get_jump_reuse_tokens(*joinpoint_id) {
Some(all_reuse_maps) => {
let all_token_layouts = all_reuse_maps
.iter()
.flat_map(|reuse_map| reuse_map.keys())
// PERF: replace this collect with an unique iterator. To make sure every layout is only used once.
.collect::<MutSet<_>>()
.into_iter();
let reuse_layouts_max_tokens = all_token_layouts.map(|token_layout| {
// We get the tokens from the jump with the most tokens for this token layout.
// So we have an inlayout for each token. And can cast when needed.
let max_token_inlayouts = all_reuse_maps
.iter()
.filter_map(|reuse_map| reuse_map.get(token_layout))
.max_by_key(|tokens| tokens.len())
.expect("all layouts should be in at least one of the reuse maps");
(token_layout, max_token_inlayouts)
});
Vec::from_iter_in(reuse_layouts_max_tokens, arena)
}
// Normally the remainder should always have jumps and this would not be None,
// But for testing this might not be the case, so default to no available reuse tokens.
None => Vec::new_in(arena),
};
let (first_pass_body_environment, first_pass_body, used_reuse_tokens) = {
// For each possibly available reuse token, create a reuse token to add to the join point environment.
let max_reuse_token_symbols = max_reuse_tokens
.iter()
.copied()
.map(|(token_layout, tokens)| {
(
*token_layout,
Vec::from_iter_in(
tokens.iter().map(|token| TokenWithInLayout {
token: ReuseToken {
symbol: Symbol::new(home, ident_ids.gen_unique()),
update_mode: update_mode_ids.next_id(),
// for now, always overwrite the tag ID just to be sure
update_tag_id: true,
},
inlayout: token.inlayout,
}),
arena,
),
)
})
.collect::<ReuseTokens>();
// Create a new environment for the body. With everything but the jump reuse tokens. As those should be given by the jump.
let mut first_pass_body_environment = ReuseEnvironment {
target: environment.target,
symbol_tags: environment.symbol_tags.clone(),
non_unique_symbols: environment.non_unique_symbols.clone(),
reuse_tokens: max_reuse_token_symbols.clone(),
symbol_layouts: environment.symbol_layouts.clone(),
joinpoint_reuse_tokens: environment.joinpoint_reuse_tokens.clone(),
jump_reuse_tokens: environment.jump_reuse_tokens.clone(),
};
// Add the parameters to the body environment as well.
for param in parameters.iter() {
first_pass_body_environment.add_symbol_layout(param.symbol, ¶m.layout);
}
// Add a entry so that the body knows any jumps to this join point is recursive.
first_pass_body_environment
.add_joinpoint_reuse_tokens(*joinpoint_id, JoinPointReuseTokens::BodyFirst);
let first_pass_body = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
&mut first_pass_body_environment,
body,
);
first_pass_body_environment.remove_joinpoint_reuse_tokens(*joinpoint_id);
let used_reuse_tokens = {
max_reuse_token_symbols
.iter()
.filter_map(|(layout, reuse_tokens)| {
match first_pass_body_environment.reuse_tokens.get(layout) {
Some(remaining_tokens) => {
// There are tokens left, remove those from the bottom of the stack and return the consumed ones.
let mut consumed_reuse_tokens = reuse_tokens
.iter()
.skip(remaining_tokens.len())
.copied()
.peekable();
#[allow(clippy::manual_map)]
match consumed_reuse_tokens.peek() {
// If there are no consumed tokens, remove the layout from the map.
None => None,
// Otherwise return the layout and the consumed tokens.
Some(_) => Some((
*layout,
Vec::from_iter_in(consumed_reuse_tokens, arena),
)),
}
}
None => {
// All tokens were consumed. Meaning all of them should be passed from the jump. Keep tokens as is.
Some((*layout, reuse_tokens.clone()))
}
}
})
.collect::<ReuseTokens>()
};
(
first_pass_body_environment,
first_pass_body,
used_reuse_tokens,
)
};
// In the evaluation of the body and remainder we assumed no reuse tokens to be used.
// So if there indeed are no reuse tokens used, we can just return the body and remainder as is.
if used_reuse_tokens.is_empty() {
// We evaluated the first pass using a cloned environment to be able to do a second pass with the same environment.
// But if we don't need a second environment, we override the passed env with the first pass env.
*environment = first_pass_remainder_environment.clone();
// Propagate jump reuse tokens upwards.
environment
.propagate_jump_reuse_tokens(std::iter::once(first_pass_body_environment));
return arena.alloc(Stmt::Join {
id: *joinpoint_id,
parameters,
body: first_pass_body,
remainder: first_pass_remainder,
});
}
let layouts_for_reuse = Vec::from_iter_in(
used_reuse_tokens.iter().flat_map(|(layout, tokens)| {
tokens.iter().map(|token| (token.inlayout, *layout))
}),
arena,
);
let second_pass_remainder = {
environment.add_joinpoint_reuse_tokens(
*joinpoint_id,
JoinPointReuseTokens::RemainderSecond(layouts_for_reuse.clone()),
);
let second_pass_remainder = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
environment,
remainder,
);
environment.remove_joinpoint_reuse_tokens(*joinpoint_id);
second_pass_remainder
};
let extended_parameters = {
let layouts_for_reuse_with_token = Vec::from_iter_in(
used_reuse_tokens
.iter()
.flat_map(|(layout, tokens)| tokens.iter().map(|token| (*layout, *token))),
arena,
);
let token_params =
layouts_for_reuse_with_token
.into_iter()
.map(|(_reuse_layout, token)| Param {
symbol: token.token.symbol,
layout: *token.inlayout,
});
// Add the reuse tokens to the join arguments to match the expected arguments of the jump.
let extended_parameters =
Vec::from_iter_in(parameters.iter().copied().chain(token_params), arena)
.into_bump_slice();
extended_parameters
};
if first_pass_body_environment
.get_jump_reuse_tokens(*joinpoint_id)
.is_none()
{
// The body has no jumps to this join point. So we can just return the body and remainder as is.
// As there are no jumps to update.
// Propagate jump reuse tokens upwards.
environment
.propagate_jump_reuse_tokens(std::iter::once(first_pass_body_environment));
return arena.alloc(Stmt::Join {
id: *joinpoint_id,
parameters: extended_parameters,
body: first_pass_body,
remainder: second_pass_remainder,
});
}
let (second_pass_body_environment, second_pass_body) = {
// Create a new environment for the body. With everything but the jump reuse tokens. As those should be given by the jump.
let mut body_environment = ReuseEnvironment {
target: environment.target,
symbol_tags: environment.symbol_tags.clone(),
non_unique_symbols: environment.non_unique_symbols.clone(),
reuse_tokens: used_reuse_tokens.clone(),
symbol_layouts: environment.symbol_layouts.clone(),
joinpoint_reuse_tokens: environment.joinpoint_reuse_tokens.clone(),
jump_reuse_tokens: environment.jump_reuse_tokens.clone(),
};
// Add the parameters to the body environment as well.
for param in parameters.iter() {
body_environment.add_symbol_layout(param.symbol, ¶m.layout);
}
// Add a entry so that the body knows any jumps to this join point is recursive.
body_environment.add_joinpoint_reuse_tokens(
*joinpoint_id,
JoinPointReuseTokens::BodySecond(layouts_for_reuse),
);
let second_pass_body = insert_reset_reuse_operations_stmt(
arena,
layout_interner,
home,
ident_ids,
update_mode_ids,
&mut body_environment,
body,
);
body_environment.remove_joinpoint_reuse_tokens(*joinpoint_id);
(body_environment, second_pass_body)
};
environment.propagate_jump_reuse_tokens(std::iter::once(second_pass_body_environment));
arena.alloc(Stmt::Join {
id: *joinpoint_id,
parameters: extended_parameters,
body: second_pass_body,
remainder: second_pass_remainder,
})
}
Stmt::Jump(id, arguments) => {
// TODO make sure that the reuse tokens that are provided by most jumps are the tokens that are used in most paths.
let joinpoint_tokens = environment.get_joinpoint_reuse_tokens(*id);
match joinpoint_tokens {
JoinPointReuseTokens::RemainderFirst | JoinPointReuseTokens::BodyFirst => {
// For both the first pass of the continuation and the body, act as if there are no tokens to reuse.
environment.add_jump_reuse_tokens(*id, environment.reuse_tokens.clone());
arena.alloc(Stmt::Jump(*id, arguments))
}
JoinPointReuseTokens::RemainderSecond(token_layouts) => {
// If there are no tokens to reuse, we can just jump.
if token_layouts.is_empty() {
return arena.alloc(Stmt::Jump(*id, arguments));
}
let token_layouts_clone = token_layouts.clone();
let mut reuse_tokens_to_cast = Vec::new_in(arena);
let mut void_pointer_layout_symbols = Vec::new_in(arena);
// See what tokens we can get from the env, if none are available, use a void pointer.
// We process the tokens in reverse order, so that when we consume the tokens we last added,
// we consume the tokens that are most likely not to be null.
let tokens = token_layouts_clone
.iter()
.rev()
.map(|(param_layout, token_layout)| {
match environment.pop_reuse_token(token_layout) {
Some(reuse_token) => {
if reuse_token.inlayout != *param_layout {
let new_symbol = Symbol::new(home, ident_ids.gen_unique());
reuse_tokens_to_cast.push((
*param_layout,
reuse_token.token.symbol,
new_symbol,
));
new_symbol
} else {
reuse_token.token.symbol
}
}
None => match void_pointer_layout_symbols
.iter()
.find(|(layout, _)| layout == param_layout)
{
Some(existing_symbol) => existing_symbol.1,
None => {
let new_symbol = Symbol::new(home, ident_ids.gen_unique());
void_pointer_layout_symbols
.push((*param_layout, new_symbol));
new_symbol
}
},
}