forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtyped_compiler.rs
More file actions
2038 lines (1875 loc) · 73.8 KB
/
Copy pathtyped_compiler.rs
File metadata and controls
2038 lines (1875 loc) · 73.8 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
//! Type-directed JIT compilation with guard stripping.
//!
//! When the typechecker knows a register holds an `Int` or `Float`, the JIT
//! can skip NaN-tag manipulation and emit direct CLIF instructions (`iadd`,
//! `fadd`, etc.) instead of calling runtime helpers. This eliminates ~30% of
//! runtime overhead in numeric loops.
//!
//! # Architecture
//!
//! - `TypeMetadata`: Maps register indices to known static types.
//! - `KnownType`: Enum representing Int, Float, Bool, or Unknown.
//! - Typed emission functions: Emit direct CLIF when operand types are known,
//! fall back to runtime helper calls otherwise.
//! - `compile_bytecode_region_typed()`: Main entry point that accepts optional
//! `TypeMetadata` and routes each opcode to typed or untyped emission.
//!
//! # NaN Tag Layout (from vm.rs)
//!
//! ```text
//! TAG_INT = 0x7FFB_0000_0000_0000 (quiet NaN + int tag)
//! TAG_BOOL = 0x7FFA_0000_0000_0000 (true=1, false=0)
//! PAYLOAD_MASK = 0x0000_FFFF_FFFF_FFFF
//! SIGN_BIT = 0x0000_8000_0000_0000
//! SIGN_EXT = 0xFFFF_0000_0000_0000
//! ```
use cranelift::codegen::ir::FuncRef;
use cranelift::prelude::*;
use cranelift_frontend::FunctionBuilder;
use cranelift_jit::JITModule;
use cranelift_module::{Linkage, Module};
use std::collections::HashMap;
use crate::bytecode::{CodeModule, Constant, Instruction, OpCode};
use crate::jit::compiler::{emit_arr_load, CompileError};
use crate::jit::JitSession;
// ---------------------------------------------------------------------------
// NaN-tag constants and CLIF helpers — single source in `cranelift_utils`
// ---------------------------------------------------------------------------
use crate::cranelift_utils::{
emit_sext48, emit_tag_bool, emit_tag_int, PAYLOAD_MASK_I64, TAG_BOOL_I64, TAG_INT_I64,
TAG_NIL_I64,
};
pub use crate::type_metadata::{KnownType, TypeMetadata};
// Bytecode-level type inference
// ---------------------------------------------------------------------------
/// Infer register types at `pc` via a conservative forward dataflow over the
/// enclosing function's bytecode.
///
/// This is the bridge between the compiler frontend and the JIT tiering
/// path: the MIR pipeline allocates each typed local to a fixed register, so
/// the type of a register at a given pc can be recovered statically from the
/// instruction stream itself (constants, arithmetic results, moves). The
/// analysis is a *must* analysis — a register is only marked `Int`/`Float`/
/// `Bool` when every static path to `pc` proves it — so wrong metadata is
/// impossible by construction; missing precision simply yields `Unknown`,
/// which makes the typed compiler fall back to the same runtime helper calls
/// as the scalar compiler.
///
/// Rules:
/// - Anchors (function entries, behavior offsets, effect-handler bodies, the
/// module entry point) start with all registers `Unknown`: function
/// arguments arrive in r0..r15 with statically unknowable types.
/// - Modeled opcodes propagate the result type their interpreter semantics
/// guarantee unconditionally (e.g. `IAdd` always writes a tagged int,
/// comparisons always write a tagged bool; `IDiv`/`IMod`/`FDiv` can yield
/// nil, so their destination becomes `Unknown`).
/// - Any unmodeled opcode conservatively clobbers ALL registers — soundness
/// over precision.
/// - Functions containing effect opcodes (`Handle`/`Perform`/`Resume`/
/// `Unwind`) yield empty metadata: `Resume` restores a captured
/// continuation whose target pc is not statically known, so no fact about
/// registers is reliable there.
pub fn infer_reg_types(module: &CodeModule, pc: usize) -> TypeMetadata {
let mut meta = TypeMetadata::new();
let instructions = &module.instructions;
if pc >= instructions.len() {
return meta;
}
// Candidate function-entry anchors. The enclosing function starts at the
// greatest anchor at or below `pc`; the next anchor above it bounds the
// analysis window.
let mut anchors: Vec<usize> = Vec::with_capacity(module.function_table.len() + 2);
anchors.push(0);
anchors.extend(module.function_table.iter().copied());
anchors.extend(module.behaviors.iter().map(|b| b.code_offset));
for table in &module.handler_tables {
anchors.extend(table.bindings.iter().map(|b| b.handler_offset));
}
if let Some(entry) = module.entry_point {
anchors.push(entry);
}
anchors.retain(|&a| a < instructions.len());
anchors.sort_unstable();
anchors.dedup();
let start = anchors
.iter()
.copied()
.rev()
.find(|&a| a <= pc)
.unwrap_or(0);
let end = anchors
.iter()
.copied()
.find(|&a| a > start)
.unwrap_or(instructions.len());
// Cap the window: enormous functions would make the fixpoint expensive,
// and hot JIT regions are capped at 500 instructions anyway.
const MAX_ANALYSIS_WINDOW: usize = 2000;
if end - start > MAX_ANALYSIS_WINDOW {
return meta;
}
// Soundness guard: effect opcodes transfer control dynamically.
for instr in &instructions[start..end] {
if matches!(
instr.opcode,
OpCode::Handle
| OpCode::Perform
| OpCode::PerformDirect
| OpCode::Resume
| OpCode::Unwind
) {
return meta;
}
}
// Forward dataflow. `states[i]` is the register-type state *before*
// `instructions[start + i]`; `None` marks a not-yet-reached pc (the top
// of the meet lattice, so the first incoming state is adopted as-is —
// this is what lets loop-carried types survive the back-edge merge).
let n = end - start;
let mut states: Vec<Option<[KnownType; 256]>> = vec![None; n];
let mut queue: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
let mut in_queue: Vec<bool> = vec![false; n];
states[0] = Some([KnownType::Unknown; 256]);
queue.push_back(start);
in_queue[0] = true;
while let Some(at) = queue.pop_front() {
in_queue[at - start] = false;
let instr = instructions[at];
let mut next = states[at - start].unwrap_or([KnownType::Unknown; 256]);
apply_type_transfer(&instr, module, &mut next);
let push_succ = |succ: usize,
states: &mut Vec<Option<[KnownType; 256]>>,
queue: &mut std::collections::VecDeque<usize>,
in_queue: &mut Vec<bool>,
next: &[KnownType; 256]| {
let slot = &mut states[succ - start];
let changed = match slot {
None => {
*slot = Some(*next);
true
}
Some(cur) => {
let mut changed = false;
for (c, &nv) in cur.iter_mut().zip(next.iter()) {
// Meet: keep a known type only when both predecessors
// agree. `Unknown` is absorbing and never counts as a
// change, so the fixpoint always terminates.
if *c != nv && *c != KnownType::Unknown {
*c = KnownType::Unknown;
changed = true;
}
}
changed
}
};
if changed && !in_queue[succ - start] {
queue.push_back(succ);
in_queue[succ - start] = true;
}
};
let in_window = |target: usize| target >= start && target < end;
match instr.opcode {
OpCode::Jmp => {
let target = (at as i64 + instr.simm16() as i64) as usize;
if in_window(target) {
push_succ(target, &mut states, &mut queue, &mut in_queue, &next);
}
}
OpCode::JmpT | OpCode::JmpF => {
let target = (at as i64 + instr.offset16() as i64) as usize;
if in_window(target) {
push_succ(target, &mut states, &mut queue, &mut in_queue, &next);
}
if at + 1 < end {
push_succ(at + 1, &mut states, &mut queue, &mut in_queue, &next);
}
}
OpCode::Halt | OpCode::Ret | OpCode::RetVal => {}
_ => {
if at + 1 < end {
push_succ(at + 1, &mut states, &mut queue, &mut in_queue, &next);
}
}
}
}
if let Some(state) = &states[pc - start] {
for (reg, &ty) in state.iter().enumerate() {
if ty != KnownType::Unknown {
meta.set_type(reg, ty);
}
}
}
meta
}
/// Apply one instruction's register-write effect to a type state.
///
/// Only opcodes whose result type is guaranteed by the interpreter's
/// semantics propagate a known type; everything else conservatively
/// clobbers the whole register file to `Unknown`.
fn apply_type_transfer(instr: &Instruction, module: &CodeModule, state: &mut [KnownType; 256]) {
let op1 = instr.op1 as usize;
let op2 = instr.op2 as usize;
let op3 = instr.op3 as usize;
match instr.opcode {
// No register writes.
OpCode::Nop
| OpCode::Halt
| OpCode::DbgPrint
| OpCode::Jmp
| OpCode::JmpT
| OpCode::JmpF
| OpCode::Ret
| OpCode::RetVal => {}
OpCode::Const0 | OpCode::Const1 | OpCode::Const2 | OpCode::ConstM1 => {
state[op1] = KnownType::Int;
}
OpCode::ConstU => {
state[op3] = match module.constants.get(instr.imm16() as usize) {
Some(Constant::Int(_)) => KnownType::Int,
Some(Constant::Float(_)) => KnownType::Float,
Some(Constant::Bool(_)) => KnownType::Bool,
_ => KnownType::Unknown,
};
}
// Register copies (Load/Store are plain copies in this pipeline).
OpCode::Load | OpCode::Store | OpCode::Move | OpCode::Dup => {
state[op2] = state[op1];
}
OpCode::Swap => {
state.swap(op1, op2);
}
// Integer results are unconditional: the interpreter and the JIT
// helpers tag any operand payload as an int.
OpCode::IAdd
| OpCode::ISub
| OpCode::IMul
| OpCode::Xor
| OpCode::Shl
| OpCode::Shr
| OpCode::BitAnd
| OpCode::BitOr => {
state[op3] = KnownType::Int;
}
// Division/remainder by zero yields nil in the interpreter.
OpCode::IDiv | OpCode::IMod => {
state[op3] = KnownType::Unknown;
}
OpCode::INeg => {
state[op2] = KnownType::Int;
}
OpCode::IInc | OpCode::IDec => {
state[op1] = KnownType::Int;
}
// Drop writes nil into its register after releasing the reference
// (it is never JIT-compiled — regions stop before it — but the
// type analysis must not let it clobber the whole register file).
OpCode::Drop => {
state[op1] = KnownType::Unknown;
}
// FDiv is excluded: the interpreter yields nil on a zero divisor.
OpCode::FAdd | OpCode::FSub | OpCode::FMul | OpCode::FNeg => {
state[op3] = KnownType::Float;
}
OpCode::ICmpEq
| OpCode::ICmpLt
| OpCode::ICmpGt
| OpCode::ICmpLe
| OpCode::ICmpGe
| OpCode::FCmpEq
| OpCode::FCmpLt
| OpCode::FCmpGt => {
state[op3] = KnownType::Bool;
}
OpCode::Not => {
state[op2] = KnownType::Bool;
}
OpCode::And | OpCode::Or => {
state[op3] = KnownType::Bool;
}
OpCode::IToF => {
state[op2] = KnownType::Float;
}
OpCode::FToI => {
state[op2] = KnownType::Int;
}
// ArrLoad result is Unknown (array elements have runtime-only types).
OpCode::ArrLoad => {
state[op3] = KnownType::Unknown;
}
// ArrStore writes to memory, not registers — no type transfer.
OpCode::ArrStore => {}
// Unmodeled opcode: conservatively clobber everything.
_ => {
state.fill(KnownType::Unknown);
}
}
}
// ---------------------------------------------------------------------------
// CLIF Helpers (shared with compiler.rs)
// ---------------------------------------------------------------------------
/// Load a value from the register file at the given index.
/// `regs_ptr` is a pointer to the start of the 256-element u64 array.
pub(crate) fn load_reg(builder: &mut FunctionBuilder, regs_ptr: Value, idx: usize) -> Value {
let offset = (idx * 8) as i32;
let addr = if offset == 0 {
regs_ptr
} else {
let offset_val = builder.ins().iconst(types::I64, offset as i64);
builder.ins().iadd(regs_ptr, offset_val)
};
builder.ins().load(types::I64, MemFlags::new(), addr, 0)
}
/// Store a value into the register file at the given index.
pub(crate) fn store_reg(builder: &mut FunctionBuilder, regs_ptr: Value, idx: usize, val: Value) {
let offset = (idx * 8) as i32;
let addr = if offset == 0 {
regs_ptr
} else {
let offset_val = builder.ins().iconst(types::I64, offset as i64);
builder.ins().iadd(regs_ptr, offset_val)
};
builder.ins().store(MemFlags::new(), val, addr, 0);
}
fn make_bin_sig<M: Module>(module: &M) -> Signature {
let mut sig = module.make_signature();
sig.params.push(AbiParam::new(types::I64));
sig.params.push(AbiParam::new(types::I64));
sig.returns.push(AbiParam::new(types::I64));
sig
}
fn make_unary_sig<M: Module>(module: &M) -> Signature {
let mut sig = module.make_signature();
sig.params.push(AbiParam::new(types::I64));
sig.returns.push(AbiParam::new(types::I64));
sig
}
/// Bitcast an i64 (raw float bits) to f64 for direct float operations.
fn emit_bitcast_i64_to_f64(builder: &mut FunctionBuilder, bits: Value) -> Value {
builder.ins().bitcast(types::F64, MemFlags::new(), bits)
}
/// Bitcast an f64 back to i64 for storage in registers.
fn emit_bitcast_f64_to_i64(builder: &mut FunctionBuilder, val: Value) -> Value {
builder.ins().bitcast(types::I64, MemFlags::new(), val)
}
/// Emit a constant integer load into a register (NaN-tagged).
pub(crate) fn emit_const(builder: &mut FunctionBuilder, regs_ptr: Value, dst: usize, value: i64) {
let tag = builder.ins().iconst(types::I64, TAG_INT_I64);
let masked = value & PAYLOAD_MASK_I64;
let val_part = builder.ins().iconst(types::I64, masked);
let tagged = builder.ins().bor(tag, val_part);
store_reg(builder, regs_ptr, dst, tagged);
}
// ---------------------------------------------------------------------------
// Runtime Helper Registration
// ---------------------------------------------------------------------------
/// Register all runtime helper functions with the JIT module.
/// Returns a map from helper name → FuncRef.
/// Single source of truth: `RuntimeHelper::ALL` from `helpers.rs`.
fn register_runtime_helpers<M: Module>(
module: &mut M,
builder: &mut FunctionBuilder,
) -> HashMap<&'static str, FuncRef> {
use crate::jit::helpers::{HelperSig, RuntimeHelper};
let mut helpers = HashMap::new();
for (helper, name) in RuntimeHelper::ALL {
let sig = match helper.sig() {
HelperSig::Bin => make_bin_sig(module),
HelperSig::Unary => make_unary_sig(module),
_ => continue, // reg3/reg4 not used by typed_compiler
};
let func_id = module
.declare_function(name, Linkage::Import, &sig)
.expect("failed to declare runtime helper");
let func_ref = module.declare_func_in_func(func_id, builder.func);
helpers.insert(*name, func_ref);
}
helpers
}
// ---------------------------------------------------------------------------
// Typed Binary Operation Emission
// ---------------------------------------------------------------------------
/// Emit an integer binary operation with direct CLIF (no runtime call).
///
/// Only called when both operands are known to be `Int`. The sequence is:
/// 1. Load raw NaN-tagged values from registers
/// 2. Sign-extend payloads inline (`emit_sext48`)
/// 3. Perform the CLIF integer operation
/// 4. Re-tag the result as a NaN-tagged integer
/// 5. Store back to the destination register
fn emit_typed_ibinop(
builder: &mut FunctionBuilder,
regs_ptr: Value,
op1: usize,
op2: usize,
dst: usize,
op: TypedIntOp,
) {
let a_raw = load_reg(builder, regs_ptr, op1);
let b_raw = load_reg(builder, regs_ptr, op2);
let a = emit_sext48(builder, a_raw);
let b = emit_sext48(builder, b_raw);
let result = match op {
TypedIntOp::Add => builder.ins().iadd(a, b),
TypedIntOp::Sub => builder.ins().isub(a, b),
TypedIntOp::Mul => builder.ins().imul(a, b),
};
let tagged = emit_tag_int(builder, result);
store_reg(builder, regs_ptr, dst, tagged);
}
/// Emit a float binary operation with direct CLIF (no runtime call).
///
/// Only called when both operands are known to be `Float`. Floats are stored
/// as raw f64 bit patterns in registers, so no NaN-tag extraction is needed.
/// The sequence is:
/// 1. Load raw i64 values from registers
/// 2. Bitcast to f64
/// 3. Perform the CLIF float operation
/// 4. Bitcast result back to i64
/// 5. Store back (already a proper NaN-tagged float)
fn emit_typed_fbinop(
builder: &mut FunctionBuilder,
regs_ptr: Value,
op1: usize,
op2: usize,
dst: usize,
op: TypedFloatOp,
) {
let a_bits = load_reg(builder, regs_ptr, op1);
let b_bits = load_reg(builder, regs_ptr, op2);
let a = emit_bitcast_i64_to_f64(builder, a_bits);
let b = emit_bitcast_i64_to_f64(builder, b_bits);
let result = match op {
TypedFloatOp::Add => builder.ins().fadd(a, b),
TypedFloatOp::Sub => builder.ins().fsub(a, b),
TypedFloatOp::Mul => builder.ins().fmul(a, b),
};
let result_bits = emit_bitcast_f64_to_i64(builder, result);
store_reg(builder, regs_ptr, dst, result_bits);
}
/// CLIF integer binary operations supported by the typed compiler.
///
/// Division and remainder are deliberately absent: direct `sdiv`/`srem`
/// trap on a zero divisor, but the interpreter and the `nulang_idiv`/
/// `nulang_imod` runtime helpers yield nil — so those always go through
/// the helpers to keep typed code behaviorally identical to scalar code.
#[derive(Debug, Clone, Copy)]
enum TypedIntOp {
Add,
Sub,
Mul,
}
/// CLIF float binary operations supported by the typed compiler.
///
/// Division is deliberately absent: direct `fdiv` produces inf/NaN on a
/// zero divisor, but the interpreter and the `nulang_fdiv` runtime helper
/// yield nil — so FDiv always goes through the helper, exactly like
/// IDiv/IMod above.
#[derive(Debug, Clone, Copy)]
enum TypedFloatOp {
Add,
Sub,
Mul,
}
// ---------------------------------------------------------------------------
// Typed Comparison Emission
// ---------------------------------------------------------------------------
/// Emit a typed integer comparison with direct CLIF.
///
/// Both operands are known Int. Extracts payloads, sign-extends, compares,
/// and stores a NaN-tagged boolean result.
fn emit_typed_icmp(
builder: &mut FunctionBuilder,
regs_ptr: Value,
op1: usize,
op2: usize,
dst: usize,
cc: IntCC,
) {
let a_raw = load_reg(builder, regs_ptr, op1);
let b_raw = load_reg(builder, regs_ptr, op2);
let a = emit_sext48(builder, a_raw);
let b = emit_sext48(builder, b_raw);
let cond = builder.ins().icmp(cc, a, b);
let tagged_bool = emit_tag_bool(builder, cond);
store_reg(builder, regs_ptr, dst, tagged_bool);
}
/// Emit a typed float comparison with direct CLIF.
///
/// Both operands are known Float. Bitcasts to f64, compares, and stores
/// a NaN-tagged boolean result.
fn emit_typed_fcmp(
builder: &mut FunctionBuilder,
regs_ptr: Value,
op1: usize,
op2: usize,
dst: usize,
cc: FloatCC,
) {
let a_bits = load_reg(builder, regs_ptr, op1);
let b_bits = load_reg(builder, regs_ptr, op2);
let a = emit_bitcast_i64_to_f64(builder, a_bits);
let b = emit_bitcast_i64_to_f64(builder, b_bits);
let cond = builder.ins().fcmp(cc, a, b);
let tagged_bool = emit_tag_bool(builder, cond);
store_reg(builder, regs_ptr, dst, tagged_bool);
}
// ---------------------------------------------------------------------------
// Typed Unary Operation Emission
// ---------------------------------------------------------------------------
/// Emit a typed integer unary operation with direct CLIF.
fn emit_typed_iunary(
builder: &mut FunctionBuilder,
regs_ptr: Value,
src: usize,
dst: usize,
op: TypedIntUnaryOp,
) {
let raw = load_reg(builder, regs_ptr, src);
let val = emit_sext48(builder, raw);
let result = match op {
TypedIntUnaryOp::Neg => builder.ins().ineg(val),
TypedIntUnaryOp::Inc => {
let one = builder.ins().iconst(types::I64, 1);
builder.ins().iadd(val, one)
}
TypedIntUnaryOp::Dec => {
let one = builder.ins().iconst(types::I64, 1);
builder.ins().isub(val, one)
}
};
let tagged = emit_tag_int(builder, result);
store_reg(builder, regs_ptr, dst, tagged);
}
#[derive(Debug, Clone, Copy)]
enum TypedIntUnaryOp {
Neg,
Inc,
Dec,
}
// ---------------------------------------------------------------------------
// Typed Logic Emission
// ---------------------------------------------------------------------------
/// Emit typed logic operations (And, Or) with direct CLIF.
///
/// For `Bool`-typed operands, compare against the tagged false value.
/// Falls back to runtime helper for unknown types.
fn emit_typed_logic(
builder: &mut FunctionBuilder,
regs_ptr: Value,
op1: usize,
op2: usize,
dst: usize,
op: TypedLogicOp,
_helpers: &HashMap<&str, FuncRef>,
meta: &TypeMetadata,
) {
// Only optimize when both operands are known Bool
if meta.both_known(op1, op2, KnownType::Bool) {
let a_raw = load_reg(builder, regs_ptr, op1);
let b_raw = load_reg(builder, regs_ptr, op2);
// Check truthy: compare against tagged false, nil, and tagged 0.
let false_val = builder.ins().iconst(types::I64, TAG_BOOL_I64 | 0);
let nil_val = builder.ins().iconst(types::I64, TAG_NIL_I64);
let zero_int = builder.ins().iconst(types::I64, TAG_INT_I64); // tagged 0
let a_is_false = builder.ins().icmp(IntCC::Equal, a_raw, false_val);
let a_is_nil = builder.ins().icmp(IntCC::Equal, a_raw, nil_val);
let a_is_zero = builder.ins().icmp(IntCC::Equal, a_raw, zero_int);
let a_falsy_part = builder.ins().bor(a_is_false, a_is_nil);
let a_not_falsy = builder.ins().bor(a_falsy_part, a_is_zero);
let zero_const = builder.ins().iconst(types::I64, 0);
let a_truthy = builder.ins().icmp(IntCC::Equal, a_not_falsy, zero_const);
let b_is_false = builder.ins().icmp(IntCC::Equal, b_raw, false_val);
let b_is_nil = builder.ins().icmp(IntCC::Equal, b_raw, nil_val);
let b_is_zero = builder.ins().icmp(IntCC::Equal, b_raw, zero_int);
let b_falsy_part = builder.ins().bor(b_is_false, b_is_nil);
let b_not_falsy = builder.ins().bor(b_falsy_part, b_is_zero);
let b_truthy = builder.ins().icmp(IntCC::Equal, b_not_falsy, zero_const);
let result_cond = match op {
TypedLogicOp::And => builder.ins().band(a_truthy, b_truthy),
TypedLogicOp::Or => builder.ins().bor(a_truthy, b_truthy),
};
let tagged_bool = emit_tag_bool(builder, result_cond);
store_reg(builder, regs_ptr, dst, tagged_bool);
} else {
// Fall back to runtime helper
let helper_name = match op {
TypedLogicOp::And => "nulang_and",
TypedLogicOp::Or => "nulang_or",
};
emit_binop_runtime(builder, _helpers, regs_ptr, op1, op2, dst, helper_name);
}
}
#[derive(Debug, Clone, Copy)]
enum TypedLogicOp {
And,
Or,
}
// ---------------------------------------------------------------------------
// Typed Conversion Emission
// ---------------------------------------------------------------------------
/// Emit typed int-to-float conversion with direct CLIF.
fn emit_typed_itof(builder: &mut FunctionBuilder, regs_ptr: Value, src: usize, dst: usize) {
let raw = load_reg(builder, regs_ptr, src);
let val = emit_sext48(builder, raw);
let float_val = builder.ins().fcvt_from_sint(types::F64, val);
let bits = emit_bitcast_f64_to_i64(builder, float_val);
store_reg(builder, regs_ptr, dst, bits);
}
/// Emit typed float-to-int conversion with direct CLIF.
fn emit_typed_ftoi(builder: &mut FunctionBuilder, regs_ptr: Value, src: usize, dst: usize) {
let bits = load_reg(builder, regs_ptr, src);
let float_val = emit_bitcast_i64_to_f64(builder, bits);
let int_val = builder.ins().fcvt_to_sint_sat(types::I64, float_val);
let tagged = emit_tag_int(builder, int_val);
store_reg(builder, regs_ptr, dst, tagged);
}
// ---------------------------------------------------------------------------
// Runtime Fallback (untyped)
// ---------------------------------------------------------------------------
/// Emit a binary operation via a runtime helper call.
fn emit_binop_runtime(
builder: &mut FunctionBuilder,
helpers: &HashMap<&str, FuncRef>,
regs_ptr: Value,
op1: usize,
op2: usize,
dst: usize,
helper_name: &str,
) {
let a = load_reg(builder, regs_ptr, op1);
let b = load_reg(builder, regs_ptr, op2);
let func_ref = *helpers.get(helper_name).unwrap();
let call = builder.ins().call(func_ref, &[a, b]);
let result = builder.inst_results(call)[0];
store_reg(builder, regs_ptr, dst, result);
}
/// Emit a unary operation via a runtime helper call.
fn emit_unary_runtime(
builder: &mut FunctionBuilder,
helpers: &HashMap<&str, FuncRef>,
regs_ptr: Value,
src: usize,
dst: usize,
helper_name: &str,
) {
let a = load_reg(builder, regs_ptr, src);
let func_ref = *helpers.get(helper_name).unwrap();
let call = builder.ins().call(func_ref, &[a]);
let result = builder.inst_results(call)[0];
store_reg(builder, regs_ptr, dst, result);
}
// ---------------------------------------------------------------------------
// Main Compilation Entry Point (typed)
// ---------------------------------------------------------------------------
/// Opcodes the typed compiler knows how to emit.
///
/// This is deliberately a subset of `compiler::is_opcode_compilable`: the
/// typed compiler's catch-all arm jumps to the return block, so an
/// unsupported opcode in the middle of a region would silently drop the
/// remaining instructions. Callers must pre-check regions with this
/// function (as `compile_bytecode_region_typed` does) and fall back to the
/// scalar compiler for anything outside the set.
pub fn is_opcode_supported_typed(op: OpCode) -> bool {
matches!(
op,
OpCode::Nop
| OpCode::Halt
| OpCode::Const0
| OpCode::Const1
| OpCode::Const2
| OpCode::ConstM1
| OpCode::ConstU
| OpCode::Load
| OpCode::Store
| OpCode::Move
| OpCode::Swap
| OpCode::Dup
| OpCode::IAdd
| OpCode::ISub
| OpCode::IMul
| OpCode::IDiv
| OpCode::IMod
| OpCode::INeg
| OpCode::IInc
| OpCode::IDec
| OpCode::FAdd
| OpCode::FSub
| OpCode::FMul
| OpCode::FDiv
| OpCode::ICmpEq
| OpCode::ICmpLt
| OpCode::ICmpGt
| OpCode::ICmpLe
| OpCode::ICmpGe
| OpCode::FCmpEq
| OpCode::FCmpLt
| OpCode::FCmpGt
| OpCode::Not
| OpCode::And
| OpCode::Or
| OpCode::Jmp
| OpCode::JmpT
| OpCode::JmpF
| OpCode::IToF
| OpCode::FToI
| OpCode::DbgPrint
| OpCode::Ret
| OpCode::RetVal
)
}
/// Compile a bytecode region to native code with optional type-directed
/// optimization (type guard stripping).
///
/// When `type_metadata` is `Some`, the compiler emits direct CLIF instructions
/// for operations where operand types are statically known (Int, Float, Bool),
/// bypassing NaN-tag-aware runtime helpers. When `None` or when a register's
/// type is `Unknown`, it falls back to the same runtime helper calls as the
/// untyped compiler.
///
/// # Arguments
/// - `module`: The Cranelift JIT module
/// - `builder_context`: Reusable function builder context
/// - `ctx`: Reusable codegen context
/// - `func_name`: Unique name for the compiled function
/// - `start_offset`: Bytecode offset where compilation starts
/// - `num_instrs`: Number of instructions to compile
/// - `instructions`: Full instruction array (indexed by offset)
/// - `type_metadata`: Optional static type information for registers
///
/// # Returns
/// A raw function pointer to the compiled code, or an error if compilation fails.
pub fn compile_bytecode_region_typed(
module: &mut JITModule,
builder_context: &mut FunctionBuilderContext,
ctx: &mut codegen::Context,
func_name: &str,
start_offset: usize,
num_instrs: usize,
instructions: &[Instruction],
type_metadata: Option<&TypeMetadata>,
) -> Result<*const u8, CompileError> {
let end_offset = (start_offset + num_instrs).min(instructions.len());
// Reject regions containing opcodes this compiler does not model: the
// catch-all arm below terminates at the return block, which would drop
// the rest of the region. Callers fall back to the scalar compiler.
// This check must run before the FunctionBuilder is created so an
// early return leaves the reusable contexts clean.
for instr in &instructions[start_offset..end_offset] {
if !is_opcode_supported_typed(instr.opcode) {
return Err(CompileError::UnsupportedOpcode(format!(
"{:?}",
instr.opcode
)));
}
}
// Clear the codegen context
ctx.clear();
// Build the function signature: fn(regs: *mut u64, constants: *const u64)
let pointer_type = module.isa().pointer_type();
ctx.func.signature.params.push(AbiParam::new(pointer_type));
ctx.func.signature.params.push(AbiParam::new(pointer_type));
// Create the function builder
let mut builder = FunctionBuilder::new(&mut ctx.func, builder_context);
// Create the entry block
let entry_block = builder.create_block();
builder.append_block_params_for_function_params(entry_block);
builder.switch_to_block(entry_block);
builder.seal_block(entry_block);
// Extract parameters
let regs_ptr = builder.block_params(entry_block)[0];
let consts_ptr = builder.block_params(entry_block)[1];
// Register runtime helpers (always needed for fallback)
let helpers = register_runtime_helpers(module, &mut builder);
// Create blocks for each instruction offset
let mut blocks: HashMap<usize, Block> = HashMap::new();
for i in start_offset..end_offset {
blocks.insert(i, builder.create_block());
}
let return_block = builder.create_block();
// Inject JIT safepoint: decrement counter, yield if exhausted.
// Pointer is never null (initialized to a VM-owned dummy).
let safepoint_ptr_addr = JitSession::safepoint_ptr_addr();
let ptr_addr = builder.ins().iconst(types::I64, safepoint_ptr_addr);
let counter_ptr = builder.ins().load(types::I64, MemFlags::new(), ptr_addr, 0);
let counter = builder
.ins()
.load(types::I64, MemFlags::new(), counter_ptr, 0);
let one = builder.ins().iconst(types::I64, 1);
let new_counter = builder.ins().isub(counter, one);
builder
.ins()
.store(MemFlags::new(), new_counter, counter_ptr, 0);
let zero = builder.ins().iconst(types::I64, 0);
let exhausted = builder
.ins()
.icmp(IntCC::SignedLessThanOrEqual, new_counter, zero);
let yield_block = builder.create_block();
if let Some(&first_block) = blocks.get(&start_offset) {
builder
.ins()
.brif(exhausted, yield_block, &[], first_block, &[]);
} else {
builder
.ins()
.brif(exhausted, yield_block, &[], return_block, &[]);
}
// Yield block: store 0 to JIT_YIELD_PC, then return.
builder.switch_to_block(yield_block);
let yield_pc_addr = JitSession::yield_pc_addr();
let yield_pc_ptr = builder.ins().iconst(types::I64, yield_pc_addr);
let zero = builder.ins().iconst(types::I64, 0);
builder.ins().store(MemFlags::new(), zero, yield_pc_ptr, 0);
builder.ins().jump(return_block, &[]);
// Seal all new blocks.
builder.seal_block(yield_block);
// Mutable copy of type metadata so we can propagate result types
let mut meta = type_metadata.map(|m| m.clone()).unwrap_or_default();
// Compile each instruction
for pc in start_offset..end_offset {
let instr = instructions[pc];
let block = *blocks.get(&pc).unwrap();
builder.switch_to_block(block);
match instr.opcode {
// -- Special --
OpCode::Nop => {}
OpCode::Halt => {
builder.ins().jump(return_block, &[]);
}
OpCode::Const0 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, 0);
}
OpCode::Const1 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, 1);
}
OpCode::Const2 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, 2);
}
OpCode::ConstM1 => {
emit_const(&mut builder, regs_ptr, instr.op1 as usize, -1);
}
OpCode::ConstU => {
let idx = instr.imm16() as usize;
let offset = (idx * 8) as i32;
let addr = if offset == 0 {
consts_ptr
} else {
let off = builder.ins().iconst(types::I64, offset as i64);
builder.ins().iadd(consts_ptr, off)
};
let val = builder.ins().load(types::I64, MemFlags::new(), addr, 0);
// Destination is op3, matching the interpreter and the scalar
// compiler (op1/op2 hold the 16-bit constant index).
store_reg(&mut builder, regs_ptr, instr.op3 as usize, val);
meta.set_type(instr.op3 as usize, KnownType::Unknown);
}
// -- Register --
// Load/Store are plain register copies in this pipeline, exactly
// like Move/Dup (mirroring the scalar compiler).
OpCode::Load | OpCode::Store | OpCode::Move | OpCode::Dup => {
let val = load_reg(&mut builder, regs_ptr, instr.op1 as usize);
store_reg(&mut builder, regs_ptr, instr.op2 as usize, val);
meta.propagate_result(instr.op2 as usize, instr.op1 as usize);
}
OpCode::Swap => {
let v1 = load_reg(&mut builder, regs_ptr, instr.op1 as usize);
let v2 = load_reg(&mut builder, regs_ptr, instr.op2 as usize);
store_reg(&mut builder, regs_ptr, instr.op1 as usize, v2);
store_reg(&mut builder, regs_ptr, instr.op2 as usize, v1);
let ty1 = meta.get_type(instr.op1 as usize);
let ty2 = meta.get_type(instr.op2 as usize);
meta.set_type(instr.op1 as usize, ty2);
meta.set_type(instr.op2 as usize, ty1);
}
// -- Integer Arithmetic (typed when both operands known Int) --
OpCode::IAdd => {
let dst = instr.op3 as usize;
if meta.both_known(instr.op1 as usize, instr.op2 as usize, KnownType::Int) {
emit_typed_ibinop(
&mut builder,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
dst,
TypedIntOp::Add,
);
} else {
emit_binop_runtime(
&mut builder,
&helpers,
regs_ptr,
instr.op1 as usize,
instr.op2 as usize,
dst,
"nulang_iadd",
);
}
// Both branches always produce an Int-tagged result; the
// destination's type must not stay stale after a fallback.
meta.set_type(dst, KnownType::Int);
}
OpCode::ISub => {