forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.rs
More file actions
5080 lines (4884 loc) · 220 KB
/
Copy pathcodegen.rs
File metadata and controls
5080 lines (4884 loc) · 220 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
//! AOT code generation: MIR → Cranelift CLIF.
//!
//! Compiles whole MIR functions to native code with unboxed parameter and
//! return types when type metadata is available. Falls back to NaN-tagged
//! runtime helpers when types are unknown.
//!
//! # Calling convention
//!
//! Compiled functions follow the C ABI:
//! ```c
//! uint64_t nulang_fn_N(uint64_t arg0, uint64_t arg1, ...);
//! ```
//! All arguments and return values are `u64` (NaN-tagged when type is
//! unknown, raw bits when unboxed). The AOT runtime trampoline handles
//! boxing/unboxing at function boundaries.
use cranelift::codegen::ir::{BlockArg, FuncRef};
use cranelift::prelude::*;
use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
use cranelift_jit::JITModule;
use cranelift_module::{Linkage, Module};
use std::collections::{HashMap, HashSet};
use crate::mir;
use crate::type_metadata::{CapabilityMetadata, KnownType, TypeMetadata};
// Reuse NaN-tag constants and CLIF helpers from `cranelift_utils`.
use crate::cranelift_utils::{emit_sext48, emit_tag_bool, emit_tag_int, TAG_BOOL_I64, TAG_NIL_I64};
// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------
/// Errors that can occur during AOT compilation.
#[derive(Debug)]
pub enum AotCompileError {
/// A MIR construct that isn't yet supported by the AOT backend.
Unsupported(String),
/// Internal compiler error.
Internal(String),
/// Cranelift compilation failure.
Cranelift(String),
}
impl std::fmt::Display for AotCompileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AotCompileError::Unsupported(msg) => write!(f, "AOT unsupported: {}", msg),
AotCompileError::Internal(msg) => write!(f, "AOT internal error: {}", msg),
AotCompileError::Cranelift(msg) => write!(f, "AOT cranelift error: {}", msg),
}
}
}
impl std::error::Error for AotCompileError {}
pub type AotResult<T> = Result<T, AotCompileError>;
// CLIF helpers imported from `cranelift_utils` (above).
// ---------------------------------------------------------------------------
// Compilation context
// ---------------------------------------------------------------------------
/// State maintained during compilation of one MIR module.
pub struct AotContext<'a> {
/// The Cranelift JIT module.
pub module: &'a mut JITModule,
/// Reusable function builder context.
pub builder_context: &'a mut FunctionBuilderContext,
/// Cranelift codegen context (holds the current function being compiled).
pub codegen_ctx: codegen::Context,
/// Runtime helpers registered with the JIT module.
pub helpers: HashMap<&'static str, FuncRef>,
/// FuncIds of already-compiled functions, indexed by MIR function index.
pub func_ids: Vec<cranelift_module::FuncId>,
/// Capability metadata for each register.
pub cap_metadata: CapabilityMetadata,
/// Compilation mode: boxed (NaN-tagged) or unboxed (raw i64 for Int).
pub mode: CompileMode,
/// Module-wide field name → slot index mapping for records.
pub field_map: HashMap<String, u8>,
/// Module constant pool (for String constant resolution).
pub constants: Vec<crate::bytecode::Constant>,
/// Module foreign-function declarations, indexed by `RValue::FFICall.idx`.
pub foreign_functions: Vec<mir::ForeignFunction>,
}
impl<'a> AotContext<'a> {
pub fn new(module: &'a mut JITModule, builder_context: &'a mut FunctionBuilderContext) -> Self {
let codegen_ctx = module.make_context();
AotContext {
module,
builder_context,
codegen_ctx,
helpers: HashMap::new(),
func_ids: Vec::new(),
cap_metadata: CapabilityMetadata::new(),
mode: CompileMode::Boxed,
field_map: HashMap::new(),
constants: Vec::new(),
foreign_functions: Vec::new(),
}
}
}
// ---------------------------------------------------------------------------
// SSA construction helpers
// ---------------------------------------------------------------------------
/// Edges from blocks containing a `perform` with a statically-resolved,
/// *resuming* handler to that handler's body block. These are not reflected
/// in any terminator — the handler body is entered via effect dispatch — but
/// the AOT backend compiles them as intra-function jumps (a resuming effect is
/// just control flow within the same native function). Without these edges the
/// handler body blocks would be unreachable in the successor graph and never
/// compiled.
fn effect_handler_edges(func: &mir::Function) -> Vec<(mir::BlockId, mir::BlockId)> {
let mut edges = Vec::new();
for block in &func.blocks {
for stmt in &block.stmts {
if let mir::Stmt::Assign {
op:
mir::RValue::Perform {
resolved_handler: Some(href),
..
},
..
} = stmt
{
if let Some(body) = func
.handler_tables
.get(href.table_index as usize)
.and_then(|t| t.bindings.get(href.binding_index as usize))
.map(|b| b.body)
{
edges.push((block.id, body));
}
}
}
}
edges
}
/// Compute block predecessors from terminators.
fn compute_predecessors(func: &mir::Function) -> HashMap<mir::BlockId, Vec<mir::BlockId>> {
let mut preds: HashMap<mir::BlockId, Vec<mir::BlockId>> = HashMap::new();
for block in &func.blocks {
match &block.terminator {
mir::Terminator::Jump(target) => {
preds.entry(*target).or_default().push(block.id);
}
mir::Terminator::Branch { then_, else_, .. } => {
preds.entry(*then_).or_default().push(block.id);
preds.entry(*else_).or_default().push(block.id);
}
_ => {}
}
}
for (src, dst) in effect_handler_edges(func) {
// Multiple performs from the same block are the same predecessor;
// dedup so live-in analysis doesn't over-approximate (which would
// pull post-perform locals into a handler body's block params).
let v = preds.entry(dst).or_default();
if !v.contains(&src) {
v.push(src);
}
}
preds
}
/// Compute successors of each block for topological traversal.
fn compute_successors(func: &mir::Function) -> HashMap<mir::BlockId, Vec<mir::BlockId>> {
let mut succs = compute_normal_successors(func);
for (src, dst) in effect_handler_edges(func) {
succs.entry(src).or_default().push(dst);
}
succs
}
/// Compute successors over NORMAL control flow only (Jump/Branch), excluding
/// the effect-handler edges. Used for continuation-liveness: a handler body is
/// not a normal flow successor, so its effect params must not count as live
/// into the perform block.
fn compute_normal_successors(func: &mir::Function) -> HashMap<mir::BlockId, Vec<mir::BlockId>> {
let mut succs: HashMap<mir::BlockId, Vec<mir::BlockId>> = HashMap::new();
for block in &func.blocks {
let targets = match &block.terminator {
mir::Terminator::Jump(target) => vec![*target],
mir::Terminator::Branch { then_, else_, .. } => vec![*then_, *else_],
_ => vec![],
};
succs.insert(block.id, targets);
}
succs
}
/// Compute reverse post-order (topological order) starting from the entry block.
fn reverse_postorder(func: &mir::Function) -> Vec<mir::BlockId> {
let succs = compute_successors(func);
let mut order = Vec::new();
let mut visited = HashSet::new();
// Recursive post-order DFS from entry.
fn dfs(
node: mir::BlockId,
succs: &HashMap<mir::BlockId, Vec<mir::BlockId>>,
visited: &mut HashSet<mir::BlockId>,
order: &mut Vec<mir::BlockId>,
) {
if !visited.insert(node) {
return;
}
if let Some(children) = succs.get(&node) {
for &child in children {
dfs(child, succs, visited, order);
}
}
order.push(node);
}
dfs(func.entry, &succs, &mut visited, &mut order);
order.reverse();
order
}
/// Count how many resuming `perform`s target each resuming handler body block.
/// When a resuming handler is invoked more than once, the handler body needs a
/// continuation-index block param so its `Terminator::Resume` can dispatch back
/// to the right perform site's continuation.
fn resuming_perform_count(func: &mir::Function) -> HashMap<mir::BlockId, usize> {
let mut out: HashMap<mir::BlockId, usize> = HashMap::new();
for block in &func.blocks {
for stmt in &block.stmts {
if let mir::Stmt::Assign {
op:
mir::RValue::Perform {
resolved_handler: Some(href),
..
},
..
} = stmt
{
if let Some(binding) = func
.handler_tables
.get(href.table_index as usize)
.and_then(|t| t.bindings.get(href.binding_index as usize))
{
if binding.resume {
*out.entry(binding.body).or_insert(0) += 1;
}
}
}
}
}
out
}
/// A resuming `perform` site within a MIR function.
struct ResumingSite {
/// The resuming handler body block.
body: mir::BlockId,
/// The block containing the perform.
block: mir::BlockId,
/// Statement index of the perform within `block`.
idx: usize,
/// The perform's destination register.
dst: u32,
}
/// Enumerate every resuming `perform` site (those whose handler binding has
/// `resume == true`).
fn resuming_sites(func: &mir::Function) -> Vec<ResumingSite> {
let local_base = mir::FunctionBuilder::LOCAL_BASE as u32;
let mut out = Vec::new();
for block in &func.blocks {
for (idx, stmt) in block.stmts.iter().enumerate() {
if let mir::Stmt::Assign {
dst,
op:
mir::RValue::Perform {
resolved_handler: Some(href),
..
},
..
} = stmt
{
if let Some(binding) = func
.handler_tables
.get(href.table_index as usize)
.and_then(|t| t.bindings.get(href.binding_index as usize))
{
if binding.resume {
out.push(ResumingSite {
body: binding.body,
block: block.id,
idx,
dst: local_base + dst.0,
});
}
}
}
}
}
out
}
/// For each resuming `perform` site (block, stmt index), the set of registers
/// live at the point the perform's continuation begins — i.e. the values the
/// post-perform code (or the block's successors) read that are NOT redefined
/// after the perform. Computed by a backward liveness walk per block starting
/// from each block's live-out set.
fn continuation_live_ins(
func: &mir::Function,
sites: &[ResumingSite],
) -> HashMap<(mir::BlockId, usize), HashSet<u32>> {
let local_base = mir::FunctionBuilder::LOCAL_BASE as u32;
// NORMAL successors only — the handler body is not a real flow successor,
// so its effect params must not be treated as live into the perform block.
let succs = compute_normal_successors(func);
let live_ins = compute_live_ins(func, local_base, &succs);
let live_out = |b: mir::BlockId| -> HashSet<u32> {
let mut out = HashSet::new();
if let Some(ss) = succs.get(&b) {
for s in ss {
if let Some(si) = live_ins.get(s) {
out.extend(si.iter().copied());
}
}
}
out
};
// Which (block, idx) are sites.
let site_set: HashSet<(mir::BlockId, usize)> =
sites.iter().map(|s| (s.block, s.idx)).collect();
let mut out: HashMap<(mir::BlockId, usize), HashSet<u32>> = HashMap::new();
for block in &func.blocks {
let mut live = live_out(block.id);
for i in (0..block.stmts.len()).rev() {
let stmt = &block.stmts[i];
let key = (block.id, i);
if site_set.contains(&key) {
// Record the continuation live-in (before this stmt's def).
out.insert(key, live.clone());
}
// Backward transfer: live = (live - defs) ∪ uses.
let mut defs: Vec<u32> = Vec::new();
let mut uses: Vec<u32> = Vec::new();
match stmt {
mir::Stmt::Assign { dst, op } => {
defs.push(local_base + dst.0);
uses.extend(stmt_rvalue_uses(op).iter().map(|l| local_base + l.0));
}
mir::Stmt::StoreFieldNamed { obj, src, .. } => {
uses.push(local_base + obj.0);
uses.push(local_base + src.0);
}
mir::Stmt::ArrayStore { arr, idx, src } => {
uses.push(local_base + arr.0);
uses.push(local_base + idx.0);
uses.push(local_base + src.0);
}
mir::Stmt::StateSet { src, .. } => {
uses.push(local_base + src.0);
}
mir::Stmt::Emit { args, .. } => {
uses.extend(args.iter().map(|a| local_base + a.0));
}
_ => {}
}
for d in &defs {
live.remove(d);
}
for u in uses {
live.insert(u);
}
}
}
out
}
/// Threaded-slot analysis for multi-site resuming handlers. Returns:
/// - per-body uniform threaded width;
/// - per-site "extra" threaded values (the continuation live-ins, minus the
/// perform's own dst and the same-block prior results).
///
/// A resuming perform's continuation is a new CLIF block that is a successor
/// of the (possibly shared) handler body, so it is NOT dominated by the
/// perform's block and can only read what the handler's `Resume` dispatch
/// forwards to it. Besides the resume value (dst) and same-block prior
/// results, the continuation may read any value live at its entry — which can
/// include cross-block values (e.g. a mutable accumulator assigned in an
/// earlier block's perform and read after a later perform). Those must be
/// threaded through the handler too. The width is the max over sites of
/// (same-block priors + extras), and every site supplies its own set padded
/// to that width.
fn resuming_threading(
func: &mir::Function,
) -> (HashMap<mir::BlockId, usize>, HashMap<(mir::BlockId, usize), Vec<u32>>) {
let sites = resuming_sites(func);
let cont_live = continuation_live_ins(func, &sites);
// Same-block prior results per site: perform dsts earlier in the same block.
let mut per_site_priors: HashMap<(mir::BlockId, usize), Vec<u32>> = HashMap::new();
for site in &sites {
let priors: Vec<u32> = sites
.iter()
.filter(|s| s.block == site.block && s.idx < site.idx)
.map(|s| s.dst)
.collect();
per_site_priors.insert((site.block, site.idx), priors);
}
// Extras per site = continuation live-ins minus dst minus same-block priors.
let mut site_extras: HashMap<(mir::BlockId, usize), Vec<u32>> = HashMap::new();
for site in &sites {
let key = (site.block, site.idx);
let priors: HashSet<u32> = per_site_priors.get(&key).cloned().unwrap_or_default().into_iter().collect();
let mut extras: Vec<u32> = cont_live
.get(&key)
.cloned()
.unwrap_or_default()
.into_iter()
.filter(|&r| r != site.dst && !priors.contains(&r))
.collect();
extras.sort_unstable();
site_extras.insert(key, extras);
}
// Width per body = max over sites of (priors.len() + extras.len()).
let mut width: HashMap<mir::BlockId, usize> = HashMap::new();
for site in &sites {
let key = (site.block, site.idx);
let n = per_site_priors.get(&key).map(|p| p.len()).unwrap_or(0)
+ site_extras.get(&key).map(|e| e.len()).unwrap_or(0);
width
.entry(site.body)
.and_modify(|x| *x = (*x).max(n))
.or_insert(n);
}
(width, site_extras)
}
/// Collect the MIR locals a statement's RValue reads (as registers).
fn stmt_rvalue_uses(op: &mir::RValue) -> Vec<mir::LocalId> {
let mut out = Vec::new();
match op {
mir::RValue::Load(l) => out.push(*l),
mir::RValue::LoadFieldNamed { obj, .. } => out.push(*obj),
mir::RValue::LoadFieldPos { obj, .. } => out.push(*obj),
mir::RValue::ArrayLoad { arr, idx } => {
out.push(*arr);
out.push(*idx);
}
mir::RValue::ArrayLen(a) => out.push(*a),
mir::RValue::ArrayLit(items) => out.extend_from_slice(items),
mir::RValue::Unary(_, l) => out.push(*l),
mir::RValue::Binary(_, a, b) => {
out.push(*a);
out.push(*b);
}
mir::RValue::StringEq(a, b) | mir::RValue::StrConcat(a, b) => {
out.push(*a);
out.push(*b);
}
mir::RValue::Call { args, .. }
| mir::RValue::FFICall { args, .. }
| mir::RValue::PerformAsync { args, .. } => out.extend_from_slice(args),
mir::RValue::Perform { args, .. } => out.extend_from_slice(args),
mir::RValue::Closure { captures, .. } => out.extend_from_slice(captures),
mir::RValue::Tuple(items) => out.extend_from_slice(items),
mir::RValue::Record(fields) => {
for (_, v) in fields {
out.push(*v);
}
}
mir::RValue::RecordUpdate { base, overrides } => {
out.push(*base);
for (_, v) in overrides {
out.push(*v);
}
}
mir::RValue::SignalWait { .. }
| mir::RValue::Receive
| mir::RValue::ReceiveMatch { .. }
| mir::RValue::ReceiveCommit
| mir::RValue::SelfRef
| mir::RValue::StateGet { .. } => {}
mir::RValue::ReceiveWait { timeout, .. } => out.push(*timeout),
mir::RValue::Migrate { actor, node } => {
out.push(*actor);
out.push(*node);
}
mir::RValue::CapabilityCheck { val } => out.push(*val),
mir::RValue::Spawn {
init, target_node, ..
} => {
if let Some(n) = target_node {
out.push(*n);
}
for (_, rv) in init {
out.extend(stmt_rvalue_uses(rv));
}
}
mir::RValue::Send {
actor, args, ..
}
| mir::RValue::Ask {
actor, args, ..
} => {
out.push(*actor);
out.extend_from_slice(args);
}
mir::RValue::Resume(l) => out.push(*l),
mir::RValue::Const(_) => {}
}
out
}
/// Per-block live-in sets (registers) over the normal + handler CFG, used by
/// the cross-block resuming-perform guard. A register is live-in to a block if
/// it may be read on some path from that block's entry before being redefined.
fn compute_live_ins(
func: &mir::Function,
local_base: u32,
succs: &HashMap<mir::BlockId, Vec<mir::BlockId>>,
) -> HashMap<mir::BlockId, HashSet<u32>> {
// `gen[block]` = locals used before their first definition in the block
// (a value used only AFTER being defined in the same block is not live-in).
// `kill[block]` = locals defined in the block. Backward fixpoint:
// live_in(block) = gen ∪ (live_out − kill), live_out = ∪ live_in(succ).
let mut gen: HashMap<mir::BlockId, HashSet<u32>> = HashMap::new();
let mut kill: HashMap<mir::BlockId, HashSet<u32>> = HashMap::new();
for block in &func.blocks {
let mut g = HashSet::new();
let mut k = HashSet::new();
// Assign statements: uses first (gen, unless already defined this
// block), then the def (kill).
let stmt_uses = |g: &mut HashSet<u32>, k: &HashSet<u32>, op: &mir::RValue| {
for l in stmt_rvalue_uses(op) {
let reg = local_base + l.0;
if !k.contains(®) {
g.insert(reg);
}
}
};
for stmt in &block.stmts {
match stmt {
mir::Stmt::Assign { dst, op } => {
stmt_uses(&mut g, &k, op);
k.insert(local_base + dst.0);
}
mir::Stmt::StoreFieldNamed { obj, src, .. } => {
for l in [*obj, *src] {
let reg = local_base + l.0;
if !k.contains(®) {
g.insert(reg);
}
}
}
mir::Stmt::ArrayStore { arr, idx, src } => {
for l in [*arr, *idx, *src] {
let reg = local_base + l.0;
if !k.contains(®) {
g.insert(reg);
}
}
}
mir::Stmt::StateSet { src, .. } => {
let reg = local_base + src.0;
if !k.contains(®) {
g.insert(reg);
}
}
mir::Stmt::Emit { args, .. } => {
for a in args {
let reg = local_base + a.0;
if !k.contains(®) {
g.insert(reg);
}
}
}
_ => {}
}
}
// Terminator uses (after all defs). A terminator operand that was
// defined earlier in this block is NOT a live-in (gen) — it is killed.
let term_uses = |g: &mut HashSet<u32>, k: &HashSet<u32>, id: mir::LocalId| {
let reg = local_base + id.0;
if !k.contains(®) {
g.insert(reg);
}
};
match &block.terminator {
mir::Terminator::Return(Some(l)) => term_uses(&mut g, &k, *l),
mir::Terminator::Branch { cond, .. } => term_uses(&mut g, &k, *cond),
mir::Terminator::Resume(id) => term_uses(&mut g, &k, *id),
_ => {}
}
gen.insert(block.id, g);
kill.insert(block.id, k);
}
let mut live_in: HashMap<mir::BlockId, HashSet<u32>> = HashMap::new();
loop {
let mut changed = false;
for block in &func.blocks {
let mut out: HashSet<u32> = HashSet::new();
if let Some(ss) = succs.get(&block.id) {
for s in ss {
if let Some(si) = live_in.get(s) {
out.extend(si.iter().copied());
}
}
}
let g = gen.get(&block.id).cloned().unwrap_or_default();
let k = kill.get(&block.id).cloned().unwrap_or_default();
let mut inn = g;
for v in out {
if !k.contains(&v) {
inn.insert(v);
}
}
if live_in.get(&block.id).map(|s| s != &inn).unwrap_or(true) {
live_in.insert(block.id, inn);
changed = true;
}
}
if !changed {
break;
}
}
live_in
}
/// Map each effect-handler body block (resuming OR abortive) to its declared
/// effect parameters (MIR locals). A `perform` passes its args into these as
/// block params, so the handler body can read them like a callee reads
/// parameters.
fn effect_handler_body_params(func: &mir::Function) -> HashMap<mir::BlockId, Vec<mir::LocalId>> {
let mut out: HashMap<mir::BlockId, Vec<mir::LocalId>> = HashMap::new();
for table in &func.handler_tables {
for binding in &table.bindings {
out.insert(binding.body, binding.params.clone());
}
}
out
}
/// For each block, collect the set of register indices that are:
/// - Last assigned in at least one predecessor, AND
/// - The block has >1 predecessor.
///
/// These locals need CLIF block parameters for proper SSA merging.
///
/// Effect-handler body blocks are EXCLUDED: they are reached by `perform`
/// jumps (not normal control-flow merges), read only their declared effect
/// params (already block params) plus outer locals that flow through the
/// shared `local_vals` (dominance-scoped), and must not inherit a perform
/// block's post-perform locals — most importantly the perform result
/// destination, which flows BACK through the continuation, not into the
/// handler body.
fn compute_liveins(
func: &mir::Function,
preds: &HashMap<mir::BlockId, Vec<mir::BlockId>>,
local_base: u32,
handler_body_params: &HashMap<mir::BlockId, Vec<mir::LocalId>>,
) -> HashMap<mir::BlockId, Vec<u32>> {
// First, for each block, find which locals are last-assigned in that block.
let mut block_defs: HashMap<mir::BlockId, HashSet<u32>> = HashMap::new();
for block in &func.blocks {
let mut defs = HashSet::new();
for stmt in &block.stmts {
if let mir::Stmt::Assign { dst, .. } = stmt {
defs.insert(local_base + dst.0);
}
}
block_defs.insert(block.id, defs);
}
// Live-in sets (proper gen/kill liveness) for phi placement.
let full_succs = compute_successors(func);
let live_ins = compute_live_ins(func, local_base, &full_succs);
// For each block with >1 predecessor, compute locals that need a CLIF block
// param so the merge can read the right SSA value on every incoming path.
let mut liveins: HashMap<mir::BlockId, Vec<u32>> = HashMap::new();
for block in &func.blocks {
if handler_body_params.contains_key(&block.id) {
continue;
}
let pids = match preds.get(&block.id) {
Some(p) if p.len() > 1 => p,
_ => continue,
};
// (1) Locals defined in ALL predecessors (the historical heuristic;
// kept as a safe superset — dead members are harmless).
let mut merged: HashSet<u32> = block_defs.get(&pids[0]).cloned().unwrap_or_default();
for pid in &pids[1..] {
if let Some(defs) = block_defs.get(pid) {
merged = merged.intersection(defs).copied().collect();
} else {
merged.clear();
break;
}
}
// (2) Locals live into the merge AND defined in at least one predecessor
// get DIFFERENT reaching definitions from different paths (a branch
// assigns the variable on one path, another path carries the prior
// value), so they must be merged as a block param. Without this, a
// value assigned in one branch and read after the join is referenced
// from a non-dominating block → CLIF verifier error.
if let Some(li) = live_ins.get(&block.id) {
for &v in li {
let defined_in_pred = pids
.iter()
.any(|pid| block_defs.get(pid).map(|d| d.contains(&v)).unwrap_or(false));
if defined_in_pred {
merged.insert(v);
}
}
}
if !merged.is_empty() {
let mut sorted: Vec<u32> = merged.into_iter().collect();
sorted.sort();
liveins.insert(block.id, sorted);
}
}
liveins
}
/// Like `compile_terminator` but passes block-param values for merged locals.
fn compile_terminator_with_params(
builder: &mut FunctionBuilder,
term: &mir::Terminator,
block_map: &HashMap<mir::BlockId, cranelift::prelude::Block>,
block_params: &HashMap<mir::BlockId, Vec<u32>>,
local_vals: &HashMap<u32, Value>,
_mode: CompileMode,
current_block: mir::BlockId,
handler_continuations: &HashMap<mir::BlockId, Vec<(cranelift::prelude::Block, u32)>>,
) -> AotResult<()> {
match term {
mir::Terminator::Return(val) => {
if let Some(id) = val {
let reg = mir::FunctionBuilder::LOCAL_BASE + id.0;
let v = *local_vals.get(®).ok_or_else(|| {
AotCompileError::Internal("return value uninitialized".into())
})?;
builder.ins().return_(&[v]);
} else {
let nil = builder
.ins()
.iconst(types::I64, 0x7FF8_0000_0000_0000u64 as i64);
builder.ins().return_(&[nil]);
}
Ok(())
}
mir::Terminator::Jump(target) => {
let clif_block = *block_map
.get(target)
.ok_or_else(|| AotCompileError::Internal("jump to unknown block".into()))?;
let args = block_param_args(block_params, target, local_vals);
builder.ins().jump(clif_block, &args);
Ok(())
}
mir::Terminator::Branch { cond, then_, else_ } => {
let cond_reg = mir::FunctionBuilder::LOCAL_BASE + cond.0;
let cond_val = *local_vals
.get(&cond_reg)
.ok_or_else(|| AotCompileError::Internal("branch cond uninitialized".into()))?;
let then_block = *block_map
.get(then_)
.ok_or_else(|| AotCompileError::Internal("branch then unknown".into()))?;
let else_block = *block_map
.get(else_)
.ok_or_else(|| AotCompileError::Internal("branch else unknown".into()))?;
let false_val = builder.ins().iconst(types::I64, TAG_BOOL_I64);
let is_true = builder.ins().icmp(IntCC::NotEqual, cond_val, false_val);
let then_args = block_param_args(block_params, then_, local_vals);
let else_args = block_param_args(block_params, else_, local_vals);
builder
.ins()
.brif(is_true, then_block, &then_args, else_block, &else_args);
Ok(())
}
mir::Terminator::Resume(id) => {
// Resuming handler body: restore the continuation by jumping back
// to the block that follows the originating `perform`, passing the
// resume value into the perform's destination local.
let conts = handler_continuations.get(¤t_block).ok_or_else(|| {
AotCompileError::Internal(
"Terminator::Resume in a block with no captured continuation".into(),
)
})?;
let reg = mir::FunctionBuilder::LOCAL_BASE + id.0;
let v = *local_vals
.get(®)
.ok_or_else(|| AotCompileError::Internal("resume value uninitialized".into()))?;
if conts.len() == 1 {
// Single continuation: pass the resume value plus any threaded
// slots the continuation carries (continuation live-ins / prior
// results). No continuation-index param exists for a single
// site, so threaded slots start at block_params.len().
let idx_pos = block_params.get(¤t_block).map(|p| p.len()).unwrap_or(0);
let cur = builder.current_block().ok_or_else(|| {
AotCompileError::Internal("Resume outside a block".into())
})?;
let hparams = builder.block_params(cur);
let mut args: Vec<BlockArg> = vec![BlockArg::from(v)];
args.extend(hparams[idx_pos..].iter().copied().map(BlockArg::from));
builder.ins().jump(conts[0].0, &args);
return Ok(());
}
// Multiple perform sites share this handler body. Dispatch on the
// continuation-index block param (position = block_params.len())
// to the matching continuation. Each continuation receives the
// resume value plus the FULL uniform-width threaded slot set. The
// values present are those supplied by whichever perform site
// entered this invocation; each continuation binds only the
// same-block prior slots it actually has, so the excess (cross-block
// or padded) slots are ignored by all continuations.
let idx_pos = block_params.get(¤t_block).map(|p| p.len()).unwrap_or(0);
let cur = builder.current_block().ok_or_else(|| {
AotCompileError::Internal("Resume outside a block".into())
})?;
let hparams = builder.block_params(cur);
let mut idx_val = hparams[idx_pos];
let mut resume_val = v;
// Threaded prior perform results, ordered as in the perform sites.
let mut threaded: Vec<Value> = hparams[idx_pos + 1..].to_vec();
for (i, (cont, _dst)) in conts.iter().enumerate() {
let idx_const = builder.ins().iconst(types::I64, i as i64);
let eq = builder.ins().icmp(IntCC::Equal, idx_val, idx_const);
let mut args: Vec<BlockArg> = vec![BlockArg::from(resume_val)];
args.extend(threaded.iter().copied().map(BlockArg::from));
if i == conts.len() - 1 {
// Last case: unconditional.
builder.ins().jump(*cont, &args);
} else {
// Fall-through chain. The next link can't read this block's
// SSA values, so carry the dispatch index, resume value,
// and threaded results as the next block's params.
let next = builder.create_block();
for _ in 0..(2 + threaded.len()) {
builder.append_block_param(next, types::I64);
}
let mut else_args: Vec<BlockArg> =
vec![BlockArg::from(idx_val), BlockArg::from(resume_val)];
else_args.extend(threaded.iter().copied().map(BlockArg::from));
builder.ins().brif(eq, *cont, &args, next, &else_args);
builder.switch_to_block(next);
let nparams = builder.block_params(next);
idx_val = nparams[0];
resume_val = nparams[1];
threaded = nparams[2..].to_vec();
}
}
Ok(())
}
mir::Terminator::Unterminated => Err(AotCompileError::Internal(
"reached Unterminated terminator in codegen — this is a compiler bug".into(),
)),
}
}
/// Build the argument list for a jump/branch to `target`: one Value per
/// block parameter, taken from the current `local_vals`.
fn block_param_args(
block_params: &HashMap<mir::BlockId, Vec<u32>>,
target: &mir::BlockId,
local_vals: &HashMap<u32, Value>,
) -> Vec<BlockArg> {
if let Some(params) = block_params.get(target) {
params
.iter()
.map(|reg| {
let val = *local_vals.get(reg).expect("block param local missing");
BlockArg::from(val)
})
.collect()
} else {
vec![]
}
}
// ---------------------------------------------------------------------------
// Main entry point: compile a MIR function to a native function pointer
// ---------------------------------------------------------------------------
/// Whether to emit NaN-tagged (boxed) or raw (unboxed) integer values.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CompileMode {
/// NaN-tagged i64 — the default, interoperable representation.
Boxed,
/// Raw i64 for Int types — faster, but requires type knowledge at call sites.
Unboxed,
}
/// Check whether a function is eligible for unboxed compilation:
/// all params are `KnownType::Int` and the return type is Int or void.
pub fn is_all_int(func: &mir::Function) -> bool {
// Functions with handled effects (resuming or abortive) must stay boxed.
// The perform-result and handler-param locals carry Unknown type metadata,
// so operations on them fall back to the NaN-tagged runtime helpers
// (`nulang_iadd` etc.) — which misread raw (unboxed) operands as floats.
// Boxed operands are properly tagged, so the helpers compute correctly.
if !effect_handler_edges(func).is_empty() {
return false;
}
// FFICall crosses into the runtime with boxed argument values; an unboxed
// (raw) Int argument would be misread by the FFI marshaller. Functions
// that call foreign functions must stay boxed.
for block in &func.blocks {
for stmt in &block.stmts {
if matches!(stmt, mir::Stmt::Assign { op: mir::RValue::FFICall { .. }, .. }) {
return false;
}
}
}
// PerformAsync routes boxed argument values to the runtime's async-effect
// dispatcher; an unboxed (raw) Int argument would be misread there.
for block in &func.blocks {
for stmt in &block.stmts {
if matches!(stmt, mir::Stmt::Assign { op: mir::RValue::PerformAsync { .. }, .. }) {
return false;
}
}
}
// SignalWait delivers a boxed signal value (unit/nil); an unboxed function
// would misread it if used as a raw int.
for block in &func.blocks {
for stmt in &block.stmts {
if matches!(stmt, mir::Stmt::Assign { op: mir::RValue::SignalWait { .. }, .. }) {
return false;
}
}
}
// Migrate delivers a boxed unit value; an unboxed function would misread
// it if used as a raw int.
for block in &func.blocks {
for stmt in &block.stmts {
if matches!(stmt, mir::Stmt::Assign { op: mir::RValue::Migrate { .. }, .. }) {
return false;
}
}
}
// Nil-producing / heap-object operations must stay boxed. An unboxed
// function tags its raw result, so a nil (div-by-zero, out-of-bounds
// array access) would be re-tagged as int 0, and heap objects hold tagged
// values the unboxed raw int path would corrupt.
for block in &func.blocks {
for stmt in &block.stmts {
let nil_or_object = match stmt {
mir::Stmt::Assign { op, .. } => matches!(
op,
mir::RValue::Binary(
crate::ast::BinOp::Div | crate::ast::BinOp::Mod,
..
) | mir::RValue::ArrayLit(_)
| mir::RValue::ArrayLoad { .. }
| mir::RValue::ArrayLen(_)
| mir::RValue::Record(_)
| mir::RValue::Tuple(_)
| mir::RValue::RecordUpdate { .. }
| mir::RValue::LoadFieldNamed { .. }
| mir::RValue::LoadFieldPos { .. }
),
mir::Stmt::StoreFieldNamed { .. } | mir::Stmt::ArrayStore { .. } => true,
_ => false,
};
if nil_or_object {
return false;
}
}
}
// Captured closures allocate a closure object holding boxed capture values
// and dispatch through a runtime helper; the capture slots must be tagged.
for block in &func.blocks {
for stmt in &block.stmts {
if matches!(
stmt,
mir::Stmt::Assign {
op: mir::RValue::Closure { captures, .. },
..
} if !captures.is_empty()
) {
return false;
}
}
}
// Lifted closure functions receive captured values as trailing boxed
// params; an unboxed variant would misread them as raw ints.
if !func.captures.is_empty() {
return false;
}
// A call through a closure value whose target is not statically known
// (a parameter, a recursive-closure const binding, or a captured closure)
// dispatches through the runtime helper with boxed arguments; an unboxed
// caller would pass raw Ints the helper misreads. Only direct calls to
// statically-known uncaptured closures stay unboxed.
let mut direct_closure_locals: HashSet<u32> = HashSet::new();
for block in &func.blocks {
for stmt in &block.stmts {
if let mir::Stmt::Assign {