forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstructions.rs
More file actions
1485 lines (1346 loc) · 62.7 KB
/
Copy pathinstructions.rs
File metadata and controls
1485 lines (1346 loc) · 62.7 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
// spell-checker: disable
use super::{JitCompileError, JitSig, JitType};
use alloc::collections::BTreeSet;
use cranelift::codegen::ir::FuncRef;
use cranelift::prelude::*;
use num_traits::cast::ToPrimitive;
use rustpython_compiler_core::bytecode::{
self, BinaryOperator, BorrowedConstant, CodeObject, ComparisonOperator, Instruction,
IntrinsicFunction1, Label, OpArg, OpArgState, oparg,
};
use std::collections::HashMap;
#[repr(u16)]
enum CustomTrapCode {
/// Raised when shifting by a negative number
NegativeShiftCount = 1,
}
#[derive(Clone)]
struct Local {
var: Variable,
ty: JitType,
}
#[derive(Debug)]
enum JitValue {
Int(Value),
Float(Value),
Bool(Value),
None,
Null,
Tuple(Vec<Self>),
FuncRef(FuncRef),
}
impl JitValue {
fn from_type_and_value(ty: JitType, val: Value) -> Self {
match ty {
JitType::Int => Self::Int(val),
JitType::Float => Self::Float(val),
JitType::Bool => Self::Bool(val),
}
}
fn to_jit_type(&self) -> Option<JitType> {
match self {
Self::Int(_) => Some(JitType::Int),
Self::Float(_) => Some(JitType::Float),
Self::Bool(_) => Some(JitType::Bool),
Self::None | Self::Null | Self::Tuple(_) | Self::FuncRef(_) => None,
}
}
fn into_value(self) -> Option<Value> {
match self {
Self::Int(val) | Self::Float(val) | Self::Bool(val) => Some(val),
Self::None | Self::Null | Self::Tuple(_) | Self::FuncRef(_) => None,
}
}
}
#[derive(Clone)]
struct DDValue {
hi: Value,
lo: Value,
}
pub(crate) struct FunctionCompiler<'a, 'b> {
builder: &'a mut FunctionBuilder<'b>,
stack: Vec<JitValue>,
variables: Box<[Option<Local>]>,
label_to_block: HashMap<Label, Block>,
pub(crate) sig: JitSig,
}
impl<'a, 'b> FunctionCompiler<'a, 'b> {
pub(crate) fn new(
builder: &'a mut FunctionBuilder<'b>,
num_variables: usize,
arg_types: &[JitType],
ret_type: Option<JitType>,
entry_block: Block,
) -> Self {
let mut compiler = Self {
builder,
stack: Vec::new(),
variables: vec![None; num_variables].into_boxed_slice(),
label_to_block: HashMap::new(),
sig: JitSig {
args: arg_types.to_vec(),
ret: ret_type,
},
};
let params = compiler.builder.func.dfg.block_params(entry_block).to_vec();
for (i, (ty, val)) in arg_types.iter().zip(params).enumerate() {
compiler
.store_variable(
(i as u32).into(),
JitValue::from_type_and_value(ty.clone(), val),
)
.unwrap();
}
compiler
}
fn pop_multiple(&mut self, count: usize) -> Vec<JitValue> {
let stack_len = self.stack.len();
self.stack.drain(stack_len - count..).collect()
}
fn store_variable(&mut self, idx: oparg::VarNum, val: JitValue) -> Result<(), JitCompileError> {
#[expect(clippy::mut_mut, reason = "This seems like a false positive")]
let builder = &mut self.builder;
let ty = val.to_jit_type().ok_or(JitCompileError::NotSupported)?;
let local = self.variables[idx].get_or_insert_with(|| {
let var = builder.declare_var(ty.to_cranelift());
Local {
var,
ty: ty.clone(),
}
});
if ty != local.ty {
Err(JitCompileError::NotSupported)
} else {
self.builder.def_var(local.var, val.into_value().unwrap());
Ok(())
}
}
fn boolean_val(&mut self, val: JitValue) -> Result<Value, JitCompileError> {
match val {
JitValue::Float(val) => {
let zero = self.builder.ins().f64const(0.0);
let val = self.builder.ins().fcmp(FloatCC::NotEqual, val, zero);
Ok(val)
}
JitValue::Int(val) => {
let zero = self.builder.ins().iconst(types::I64, 0);
let val = self.builder.ins().icmp(IntCC::NotEqual, val, zero);
Ok(val)
}
JitValue::Bool(val) => Ok(val),
JitValue::None => Ok(self.builder.ins().iconst(types::I8, 0)),
JitValue::Null | JitValue::Tuple(_) | JitValue::FuncRef(_) => {
Err(JitCompileError::NotSupported)
}
}
}
fn get_or_create_block(&mut self, label: Label) -> Block {
#[expect(clippy::mut_mut, reason = "This seems like a false positive")]
let builder = &mut self.builder;
*self
.label_to_block
.entry(label)
.or_insert_with(|| builder.create_block())
}
fn jump_target_forward(offset: u32, caches: u32, arg: OpArg) -> Result<Label, JitCompileError> {
let after = offset
.checked_add(1)
.and_then(|i| i.checked_add(caches))
.ok_or(JitCompileError::BadBytecode)?;
let target = after
.checked_add(u32::from(arg))
.ok_or(JitCompileError::BadBytecode)?;
Ok(Label::from_u32(target))
}
fn jump_target_backward(
offset: u32,
caches: u32,
arg: OpArg,
) -> Result<Label, JitCompileError> {
let after = offset
.checked_add(1)
.and_then(|i| i.checked_add(caches))
.ok_or(JitCompileError::BadBytecode)?;
let target = after
.checked_sub(u32::from(arg))
.ok_or(JitCompileError::BadBytecode)?;
Ok(Label::from_u32(target))
}
fn instruction_target(
offset: u32,
instruction: Instruction,
arg: OpArg,
) -> Result<Option<Label>, JitCompileError> {
let caches = instruction.cache_entries() as u32;
let target = match instruction {
Instruction::JumpForward { .. } => {
Some(Self::jump_target_forward(offset, caches, arg)?)
}
Instruction::JumpBackward { .. } | Instruction::JumpBackwardNoInterrupt { .. } => {
Some(Self::jump_target_backward(offset, caches, arg)?)
}
Instruction::PopJumpIfFalse { .. }
| Instruction::PopJumpIfTrue { .. }
| Instruction::PopJumpIfNone { .. }
| Instruction::PopJumpIfNotNone { .. }
| Instruction::ForIter { .. }
| Instruction::Send { .. } => Some(Self::jump_target_forward(offset, caches, arg)?),
_ => None,
};
Ok(target)
}
pub(crate) fn compile<C: bytecode::Constant>(
&mut self,
func_ref: FuncRef,
bytecode: &CodeObject<C>,
) -> Result<(), JitCompileError> {
// JIT should consume a stable instruction stream: de-specialized opcodes
// with zeroed CACHE entries, not runtime-mutated quickened code.
let clean_instructions: bytecode::CodeUnits = bytecode
.instructions
.original_bytes()
.as_slice()
.try_into()
.map_err(|_| JitCompileError::BadBytecode)?;
let mut label_targets = BTreeSet::new();
let mut target_arg_state = OpArgState::default();
for (offset, &raw_instr) in clean_instructions.iter().enumerate() {
let (instruction, arg) = target_arg_state.get(raw_instr);
if let Some(target) = Self::instruction_target(offset as u32, instruction, arg)? {
label_targets.insert(target);
}
}
let mut arg_state = OpArgState::default();
// Track whether we have "returned" in the current block
let mut in_unreachable_code = false;
for (offset, &raw_instr) in clean_instructions.iter().enumerate() {
let label = Label::from_u32(offset as u32);
let (instruction, arg) = arg_state.get(raw_instr);
// If this is a label that some earlier jump can target,
// treat it as the start of a new reachable block:
if label_targets.contains(&label) {
// Create or get the block for this label:
let target_block = self.get_or_create_block(label);
// If the current block isn't terminated, add a fallthrough jump
if let Some(cur) = self.builder.current_block()
&& cur != target_block
{
// Check if the block needs a terminator by examining the last instruction
let needs_terminator = match self.builder.func.layout.last_inst(cur) {
None => true, // Empty block needs terminator
Some(inst) => {
// Check if the last instruction is a terminator
!self.builder.func.dfg.insts[inst].opcode().is_terminator()
}
};
if needs_terminator {
self.builder.ins().jump(target_block, &[]);
}
}
// Switch to the target block
if self.builder.current_block() != Some(target_block) {
self.builder.switch_to_block(target_block);
}
// We are definitely reachable again at this label
in_unreachable_code = false;
}
// If we're in unreachable code, skip this instruction unless the label re-entered above.
if in_unreachable_code {
continue;
}
// Actually compile this instruction:
self.add_instruction(func_ref, bytecode, offset as u32, instruction, arg)?;
// If that was an unconditional branch or return, mark future instructions unreachable
match instruction {
Instruction::ReturnValue
| Instruction::JumpBackward { .. }
| Instruction::JumpBackwardNoInterrupt { .. }
| Instruction::JumpForward { .. } => {
in_unreachable_code = true;
}
_ => {}
}
}
// After processing, if the current block is unterminated, insert a trap
if let Some(cur) = self.builder.current_block() {
let needs_terminator = match self.builder.func.layout.last_inst(cur) {
None => true,
Some(inst) => !self.builder.func.dfg.insts[inst].opcode().is_terminator(),
};
if needs_terminator {
self.builder.ins().trap(TrapCode::user(0).unwrap());
}
}
Ok(())
}
fn prepare_const<C: bytecode::Constant>(
&mut self,
constant: BorrowedConstant<'_, C>,
) -> Result<JitValue, JitCompileError> {
let value = match constant {
BorrowedConstant::Integer { value } => {
let val = self.builder.ins().iconst(
types::I64,
value.to_i64().ok_or(JitCompileError::NotSupported)?,
);
JitValue::Int(val)
}
BorrowedConstant::Float { value } => {
let val = self.builder.ins().f64const(value);
JitValue::Float(val)
}
BorrowedConstant::Boolean { value } => {
let val = self.builder.ins().iconst(types::I8, value as i64);
JitValue::Bool(val)
}
BorrowedConstant::None => JitValue::None,
_ => return Err(JitCompileError::NotSupported),
};
Ok(value)
}
fn return_value(&mut self, val: JitValue) -> Result<(), JitCompileError> {
if let Some(ref ty) = self.sig.ret {
// If the signature has a return type, enforce it
if val.to_jit_type().as_ref() != Some(ty) {
return Err(JitCompileError::NotSupported);
}
} else {
// First time we see a return, define it in the signature
let ty = val.to_jit_type().ok_or(JitCompileError::NotSupported)?;
self.sig.ret = Some(ty.clone());
self.builder
.func
.signature
.returns
.push(AbiParam::new(ty.to_cranelift()));
}
// If this is e.g. an Int, Float, or Bool we have a Cranelift `Value`.
// If we have JitValue::None or .Tuple(...) but can't handle that, error out (or handle differently).
let cr_val = val.into_value().ok_or(JitCompileError::NotSupported)?;
self.builder.ins().return_(&[cr_val]);
Ok(())
}
pub(crate) fn add_instruction<C: bytecode::Constant>(
&mut self,
func_ref: FuncRef,
bytecode: &CodeObject<C>,
offset: u32,
instruction: Instruction,
arg: OpArg,
) -> Result<(), JitCompileError> {
match instruction {
Instruction::BinaryOp { op } => {
let op = op.get(arg);
// the rhs is popped off first
let b = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a_type = a.to_jit_type();
let b_type = b.to_jit_type();
let val = match (op, a, b) {
(
BinaryOperator::Add | BinaryOperator::InplaceAdd,
JitValue::Int(a),
JitValue::Int(b),
) => {
let (out, carry) = self.builder.ins().sadd_overflow(a, b);
self.builder.ins().trapnz(carry, TrapCode::INTEGER_OVERFLOW);
JitValue::Int(out)
}
(
BinaryOperator::Subtract | BinaryOperator::InplaceSubtract,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.compile_sub(a, b)),
(
BinaryOperator::FloorDivide | BinaryOperator::InplaceFloorDivide,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().sdiv(a, b)),
(
BinaryOperator::TrueDivide | BinaryOperator::InplaceTrueDivide,
JitValue::Int(a),
JitValue::Int(b),
) => {
// Check if b == 0, If so trap with a division by zero error
self.builder
.ins()
.trapz(b, TrapCode::INTEGER_DIVISION_BY_ZERO);
// Else convert to float and divide
let a_float = self.builder.ins().fcvt_from_sint(types::F64, a);
let b_float = self.builder.ins().fcvt_from_sint(types::F64, b);
JitValue::Float(self.builder.ins().fdiv(a_float, b_float))
}
(
BinaryOperator::Multiply | BinaryOperator::InplaceMultiply,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().imul(a, b)),
(
BinaryOperator::Remainder | BinaryOperator::InplaceRemainder,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().srem(a, b)),
(
BinaryOperator::Power | BinaryOperator::InplacePower,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.compile_ipow(a, b)),
(
BinaryOperator::Lshift | BinaryOperator::Rshift,
JitValue::Int(a),
JitValue::Int(b),
) => {
// Shifts throw an exception if we have a negative shift count
// Remove all bits except the sign bit, and trap if its 1 (i.e. negative).
let sign = self.builder.ins().ushr_imm(b, 63);
self.builder.ins().trapnz(
sign,
TrapCode::user(CustomTrapCode::NegativeShiftCount as u8).unwrap(),
);
let out =
if matches!(op, BinaryOperator::Lshift | BinaryOperator::InplaceLshift)
{
self.builder.ins().ishl(a, b)
} else {
self.builder.ins().sshr(a, b)
};
JitValue::Int(out)
}
(
BinaryOperator::And | BinaryOperator::InplaceAnd,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().band(a, b)),
(
BinaryOperator::Or | BinaryOperator::InplaceOr,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().bor(a, b)),
(
BinaryOperator::Xor | BinaryOperator::InplaceXor,
JitValue::Int(a),
JitValue::Int(b),
) => JitValue::Int(self.builder.ins().bxor(a, b)),
// Floats
(
BinaryOperator::Add | BinaryOperator::InplaceAdd,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fadd(a, b)),
(
BinaryOperator::Subtract | BinaryOperator::InplaceSubtract,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fsub(a, b)),
(
BinaryOperator::Multiply | BinaryOperator::InplaceMultiply,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fmul(a, b)),
(
BinaryOperator::TrueDivide | BinaryOperator::InplaceTrueDivide,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.builder.ins().fdiv(a, b)),
(
BinaryOperator::Power | BinaryOperator::InplacePower,
JitValue::Float(a),
JitValue::Float(b),
) => JitValue::Float(self.compile_fpow(a, b)),
// Floats and Integers
(_, JitValue::Int(a), JitValue::Float(b))
| (_, JitValue::Float(a), JitValue::Int(b)) => {
let operand_one = match a_type.unwrap() {
JitType::Int => self.builder.ins().fcvt_from_sint(types::F64, a),
_ => a,
};
let operand_two = match b_type.unwrap() {
JitType::Int => self.builder.ins().fcvt_from_sint(types::F64, b),
_ => b,
};
match op {
BinaryOperator::Add | BinaryOperator::InplaceAdd => {
JitValue::Float(self.builder.ins().fadd(operand_one, operand_two))
}
BinaryOperator::Subtract | BinaryOperator::InplaceSubtract => {
JitValue::Float(self.builder.ins().fsub(operand_one, operand_two))
}
BinaryOperator::Multiply | BinaryOperator::InplaceMultiply => {
JitValue::Float(self.builder.ins().fmul(operand_one, operand_two))
}
BinaryOperator::TrueDivide | BinaryOperator::InplaceTrueDivide => {
JitValue::Float(self.builder.ins().fdiv(operand_one, operand_two))
}
BinaryOperator::Power | BinaryOperator::InplacePower => {
JitValue::Float(self.compile_fpow(operand_one, operand_two))
}
_ => return Err(JitCompileError::NotSupported),
}
}
_ => return Err(JitCompileError::NotSupported),
};
self.stack.push(val);
Ok(())
}
Instruction::BuildTuple { count } => {
let elements = self.pop_multiple(count.get(arg) as usize);
self.stack.push(JitValue::Tuple(elements));
Ok(())
}
Instruction::Call { argc } => {
let nargs = argc.get(arg);
let mut args = Vec::new();
for _ in 0..nargs {
let arg = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
args.push(arg.into_value().unwrap());
}
// Pop self_or_null (should be Null for JIT-compiled recursive calls)
let self_or_null = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
if !matches!(self_or_null, JitValue::Null) {
return Err(JitCompileError::NotSupported);
}
match self.stack.pop().ok_or(JitCompileError::BadBytecode)? {
JitValue::FuncRef(reference) => {
let call = self.builder.ins().call(reference, &args);
let returns = self.builder.inst_results(call);
self.stack.push(JitValue::Int(returns[0]));
Ok(())
}
_ => Err(JitCompileError::BadBytecode),
}
}
Instruction::PushNull => {
self.stack.push(JitValue::Null);
Ok(())
}
Instruction::CallIntrinsic1 { func } => {
match func.get(arg) {
IntrinsicFunction1::UnaryPositive => {
match self.stack.pop().ok_or(JitCompileError::BadBytecode)? {
JitValue::Int(val) => {
// Nothing to do
self.stack.push(JitValue::Int(val));
Ok(())
}
_ => Err(JitCompileError::NotSupported),
}
}
_ => Err(JitCompileError::NotSupported),
}
}
Instruction::CompareOp { opname } => {
let op = opname.get(arg);
// the rhs is popped off first
let b = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let a_type: Option<JitType> = a.to_jit_type();
let b_type: Option<JitType> = b.to_jit_type();
match (a, b) {
(
JitValue::Int(a) | JitValue::Bool(a),
JitValue::Int(b) | JitValue::Bool(b),
) => {
let operand_one = match a_type.unwrap() {
JitType::Bool => self.builder.ins().uextend(types::I64, a),
_ => a,
};
let operand_two = match b_type.unwrap() {
JitType::Bool => self.builder.ins().uextend(types::I64, b),
_ => b,
};
let cond = match op {
ComparisonOperator::Equal => IntCC::Equal,
ComparisonOperator::NotEqual => IntCC::NotEqual,
ComparisonOperator::Less => IntCC::SignedLessThan,
ComparisonOperator::LessOrEqual => IntCC::SignedLessThanOrEqual,
ComparisonOperator::Greater => IntCC::SignedGreaterThan,
ComparisonOperator::GreaterOrEqual => IntCC::SignedGreaterThanOrEqual,
};
let val = self.builder.ins().icmp(cond, operand_one, operand_two);
self.stack.push(JitValue::Bool(val));
Ok(())
}
(JitValue::Float(a), JitValue::Float(b)) => {
let cond = match op {
ComparisonOperator::Equal => FloatCC::Equal,
ComparisonOperator::NotEqual => FloatCC::NotEqual,
ComparisonOperator::Less => FloatCC::LessThan,
ComparisonOperator::LessOrEqual => FloatCC::LessThanOrEqual,
ComparisonOperator::Greater => FloatCC::GreaterThan,
ComparisonOperator::GreaterOrEqual => FloatCC::GreaterThanOrEqual,
};
let val = self.builder.ins().fcmp(cond, a, b);
self.stack.push(JitValue::Bool(val));
Ok(())
}
_ => Err(JitCompileError::NotSupported),
}
}
Instruction::ExtendedArg
| Instruction::Cache
| Instruction::MakeCell { .. }
| Instruction::CopyFreeVars { .. } => Ok(()),
Instruction::JumpBackward { .. }
| Instruction::JumpBackwardNoInterrupt { .. }
| Instruction::JumpForward { .. } => {
let target = Self::instruction_target(offset, instruction, arg)?
.ok_or(JitCompileError::BadBytecode)?;
let target_block = self.get_or_create_block(target);
self.builder.ins().jump(target_block, &[]);
Ok(())
}
Instruction::LoadConst { consti } => {
let val =
self.prepare_const(bytecode.constants[consti.get(arg)].borrow_constant())?;
self.stack.push(val);
Ok(())
}
Instruction::LoadSmallInt { i } => {
let small_int = i.get(arg) as i64;
let val = self.builder.ins().iconst(types::I64, small_int);
self.stack.push(JitValue::Int(val));
Ok(())
}
Instruction::LoadFast { var_num } | Instruction::LoadFastBorrow { var_num } => {
let local = self.variables[var_num.get(arg)]
.as_ref()
.ok_or(JitCompileError::BadBytecode)?;
self.stack.push(JitValue::from_type_and_value(
local.ty.clone(),
self.builder.use_var(local.var),
));
Ok(())
}
Instruction::LoadFastLoadFast { var_nums }
| Instruction::LoadFastBorrowLoadFastBorrow { var_nums } => {
let oparg = var_nums.get(arg);
let (idx1, idx2) = oparg.indexes();
for idx in [idx1, idx2] {
let local = self.variables[idx]
.as_ref()
.ok_or(JitCompileError::BadBytecode)?;
self.stack.push(JitValue::from_type_and_value(
local.ty.clone(),
self.builder.use_var(local.var),
));
}
Ok(())
}
Instruction::LoadGlobal { namei } => {
let oparg = namei.get(arg);
let name = &bytecode.names[(oparg >> 1) as usize];
if name.as_ref() != bytecode.obj_name.as_ref() {
Err(JitCompileError::NotSupported)
} else {
self.stack.push(JitValue::FuncRef(func_ref));
if (oparg & 1) != 0 {
self.stack.push(JitValue::Null);
}
Ok(())
}
}
Instruction::Nop | Instruction::NotTaken => Ok(()),
Instruction::PopJumpIfFalse { .. } => {
let cond = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let val = self.boolean_val(cond)?;
let then_label = Self::instruction_target(offset, instruction, arg)?
.ok_or(JitCompileError::BadBytecode)?;
let then_block = self.get_or_create_block(then_label);
let else_block = self.builder.create_block();
self.builder
.ins()
.brif(val, else_block, &[], then_block, &[]);
self.builder.switch_to_block(else_block);
Ok(())
}
Instruction::PopJumpIfTrue { .. } => {
let cond = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let val = self.boolean_val(cond)?;
let then_label = Self::instruction_target(offset, instruction, arg)?
.ok_or(JitCompileError::BadBytecode)?;
let then_block = self.get_or_create_block(then_label);
let else_block = self.builder.create_block();
self.builder
.ins()
.brif(val, then_block, &[], else_block, &[]);
self.builder.switch_to_block(else_block);
Ok(())
}
Instruction::PopTop => {
self.stack.pop();
Ok(())
}
Instruction::Resume { .. } => {
// TODO: Implement the resume instruction
Ok(())
}
Instruction::ReturnValue => {
let val = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
self.return_value(val)
}
Instruction::StoreFast { var_num } => {
let val = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
self.store_variable(var_num.get(arg), val)
}
Instruction::StoreFastLoadFast { var_nums } => {
let oparg = var_nums.get(arg);
let (store_idx, load_idx) = oparg.indexes();
let val = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
self.store_variable(store_idx, val)?;
let local = self.variables[load_idx]
.as_ref()
.ok_or(JitCompileError::BadBytecode)?;
self.stack.push(JitValue::from_type_and_value(
local.ty.clone(),
self.builder.use_var(local.var),
));
Ok(())
}
Instruction::StoreFastStoreFast { var_nums } => {
let oparg = var_nums.get(arg);
let (idx1, idx2) = oparg.indexes();
let val1 = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
self.store_variable(idx1, val1)?;
let val2 = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
self.store_variable(idx2, val2)
}
Instruction::Swap { i: index } => {
let len = self.stack.len();
let i = len - 1;
let j = len - 1 - index.get(arg) as usize;
self.stack.swap(i, j);
Ok(())
}
Instruction::ToBool => {
let a = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let value = self.boolean_val(a)?;
self.stack.push(JitValue::Bool(value));
Ok(())
}
Instruction::UnaryNot => {
let boolean = match self.stack.pop().ok_or(JitCompileError::BadBytecode)? {
JitValue::Bool(val) => val,
_ => return Err(JitCompileError::BadBytecode),
};
let not_boolean = self.builder.ins().bxor_imm(boolean, 1);
self.stack.push(JitValue::Bool(not_boolean));
Ok(())
}
Instruction::UnaryNegative => {
match self.stack.pop().ok_or(JitCompileError::BadBytecode)? {
JitValue::Int(val) => {
// Compile minus as 0 - val.
let zero = self.builder.ins().iconst(types::I64, 0);
let out = self.compile_sub(zero, val);
self.stack.push(JitValue::Int(out));
Ok(())
}
_ => Err(JitCompileError::NotSupported),
}
}
Instruction::UnpackSequence { count } => {
let val = self.stack.pop().ok_or(JitCompileError::BadBytecode)?;
let elements = match val {
JitValue::Tuple(elements) => elements,
_ => return Err(JitCompileError::NotSupported),
};
if elements.len() != count.get(arg) as usize {
return Err(JitCompileError::NotSupported);
}
self.stack.extend(elements.into_iter().rev());
Ok(())
}
_ => Err(JitCompileError::NotSupported),
}
}
fn compile_sub(&mut self, a: Value, b: Value) -> Value {
let (out, carry) = self.builder.ins().ssub_overflow(a, b);
self.builder.ins().trapnz(carry, TrapCode::INTEGER_OVERFLOW);
out
}
/// Creates a double–double (DDValue) from a regular f64 constant.
/// The high part is set to x and the low part is set to 0.0.
fn dd_from_f64(&mut self, x: f64) -> DDValue {
DDValue {
hi: self.builder.ins().f64const(x),
lo: self.builder.ins().f64const(0.0),
}
}
/// Creates a DDValue from a Value (assumed to represent an f64).
/// This function initializes the high part with x and the low part to 0.0.
fn dd_from_value(&mut self, x: Value) -> DDValue {
DDValue {
hi: x,
lo: self.builder.ins().f64const(0.0),
}
}
/// Creates a DDValue from two f64 parts.
/// The 'hi' parameter sets the high part and 'lo' sets the low part.
fn dd_from_parts(&mut self, hi: f64, lo: f64) -> DDValue {
DDValue {
hi: self.builder.ins().f64const(hi),
lo: self.builder.ins().f64const(lo),
}
}
/// Converts a DDValue back to a single f64 value by adding the high and low parts.
fn dd_to_f64(&mut self, dd: DDValue) -> Value {
self.builder.ins().fadd(dd.hi, dd.lo)
}
/// Computes the negation of a DDValue.
/// It subtracts both the high and low parts from zero.
fn dd_neg(&mut self, dd: DDValue) -> DDValue {
let zero = self.builder.ins().f64const(0.0);
DDValue {
hi: self.builder.ins().fsub(zero, dd.hi),
lo: self.builder.ins().fsub(zero, dd.lo),
}
}
/// Adds two DDValue numbers using error-free transformations to maintain extra precision.
/// It carefully adds the high parts, computes the rounding error, adds the low parts along with the error,
/// and then normalizes the result.
fn dd_add(&mut self, a: DDValue, b: DDValue) -> DDValue {
// Compute the sum of the high parts.
let s = self.builder.ins().fadd(a.hi, b.hi);
// Compute t = s - a.hi to capture part of the rounding error.
let t = self.builder.ins().fsub(s, a.hi);
// Compute the error e from the high part additions.
let s_minus_t = self.builder.ins().fsub(s, t);
let part1 = self.builder.ins().fsub(a.hi, s_minus_t);
let part2 = self.builder.ins().fsub(b.hi, t);
let e = self.builder.ins().fadd(part1, part2);
// Sum the low parts along with the error.
let lo = self.builder.ins().fadd(a.lo, b.lo);
let lo_sum = self.builder.ins().fadd(lo, e);
// Renormalize: add the low sum to s and compute a new low component.
let hi_new = self.builder.ins().fadd(s, lo_sum);
let hi_new_minus_s = self.builder.ins().fsub(hi_new, s);
let lo_new = self.builder.ins().fsub(lo_sum, hi_new_minus_s);
DDValue {
hi: hi_new,
lo: lo_new,
}
}
/// Subtracts DDValue b from DDValue a by negating b and then using the addition function.
fn dd_sub(&mut self, a: DDValue, b: DDValue) -> DDValue {
let neg_b = self.dd_neg(b);
self.dd_add(a, neg_b)
}
/// Multiplies two DDValue numbers using double–double arithmetic.
/// It calculates the high product, uses a fused multiply–add (FMA) to capture rounding error,
/// computes the cross products, and then normalizes the result.
fn dd_mul(&mut self, a: DDValue, b: DDValue) -> DDValue {
// p = a.hi * b.hi (primary product)
let p = self.builder.ins().fmul(a.hi, b.hi);
// err = fma(a.hi, b.hi, -p) recovers the rounding error.
let zero = self.builder.ins().f64const(0.0);
let neg_p = self.builder.ins().fsub(zero, p);
let err = self.builder.ins().fma(a.hi, b.hi, neg_p);
// Compute cross terms: a.hi*b.lo + a.lo*b.hi.
let a_hi_b_lo = self.builder.ins().fmul(a.hi, b.lo);
let a_lo_b_hi = self.builder.ins().fmul(a.lo, b.hi);
let cross = self.builder.ins().fadd(a_hi_b_lo, a_lo_b_hi);
// Sum p and the cross terms.
let s = self.builder.ins().fadd(p, cross);
// Isolate rounding error from the addition.
let t = self.builder.ins().fsub(s, p);
let s_minus_t = self.builder.ins().fsub(s, t);
let part1 = self.builder.ins().fsub(p, s_minus_t);
let part2 = self.builder.ins().fsub(cross, t);
let e = self.builder.ins().fadd(part1, part2);
// Include the error from the low parts multiplication.
let a_lo_b_lo = self.builder.ins().fmul(a.lo, b.lo);
let err_plus_e = self.builder.ins().fadd(err, e);
let lo_sum = self.builder.ins().fadd(err_plus_e, a_lo_b_lo);
// Renormalize the sum.
let hi_new = self.builder.ins().fadd(s, lo_sum);
let hi_new_minus_s = self.builder.ins().fsub(hi_new, s);
let lo_new = self.builder.ins().fsub(lo_sum, hi_new_minus_s);
DDValue {
hi: hi_new,
lo: lo_new,
}
}
/// Multiplies a DDValue by a regular f64 (Value) using similar techniques as dd_mul.
/// It multiplies both the high and low parts by b, computes the rounding error,
/// and then renormalizes the result.
fn dd_mul_f64(&mut self, a: DDValue, b: Value) -> DDValue {
// p = a.hi * b (primary product)
let p = self.builder.ins().fmul(a.hi, b);
// Compute the rounding error using fma.
let zero = self.builder.ins().f64const(0.0);
let neg_p = self.builder.ins().fsub(zero, p);
let err = self.builder.ins().fma(a.hi, b, neg_p);
// Multiply the low part.
let cross = self.builder.ins().fmul(a.lo, b);
// Sum the primary product and the low multiplication.
let s = self.builder.ins().fadd(p, cross);
// Capture rounding error from addition.
let t = self.builder.ins().fsub(s, p);
let s_minus_t = self.builder.ins().fsub(s, t);
let part1 = self.builder.ins().fsub(p, s_minus_t);
let part2 = self.builder.ins().fsub(cross, t);
let e = self.builder.ins().fadd(part1, part2);
// Combine the error components.
let lo_sum = self.builder.ins().fadd(err, e);
// Renormalize to form the final double–double number.
let hi_new = self.builder.ins().fadd(s, lo_sum);
let hi_new_minus_s = self.builder.ins().fsub(hi_new, s);
let lo_new = self.builder.ins().fsub(lo_sum, hi_new_minus_s);
DDValue {
hi: hi_new,
lo: lo_new,
}
}
/// Scales a DDValue by multiplying both its high and low parts by the given factor.
fn dd_scale(&mut self, dd: DDValue, factor: Value) -> DDValue {
DDValue {
hi: self.builder.ins().fmul(dd.hi, factor),
lo: self.builder.ins().fmul(dd.lo, factor),
}
}
/// Approximates ln(1+f) using its Taylor series expansion in double–double arithmetic.
/// It computes the series ∑ (-1)^(i-1) * f^i / i from i = 1 to 1000 for high precision.
fn dd_ln_1p_series(&mut self, f: Value) -> DDValue {
// Convert f to a DDValue and initialize the sum and term.
let f_dd = self.dd_from_value(f);
let mut sum = f_dd.clone();
let mut term = f_dd;
// Alternating sign starts at -1 for the second term.
let mut sign = -1.0_f64;
let range = 1000;
// Loop over terms from i = 2 to 1000.
for i in 2..=range {
// Compute f^i by multiplying the previous term by f.
term = self.dd_mul_f64(term, f);
// Divide the term by i.
let inv_i = 1.0 / (i as f64);
let c_inv_i = self.builder.ins().f64const(inv_i);
let term_div = self.dd_mul_f64(term.clone(), c_inv_i);
// Multiply by the alternating sign.
let dd_sign = self.dd_from_f64(sign);
let to_add = self.dd_mul(dd_sign, term_div);
// Add the term to the cumulative sum.
sum = self.dd_add(sum, to_add);
// Flip the sign for the next term.
sign = -sign;
}
sum
}