polycomp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ir.rs CHANGED
@@ -18,6 +18,7 @@ pub enum BuiltinId {
18
18
  Print,
19
19
  Println,
20
20
  Printf,
21
+ Sprintf,
21
22
  Len,
22
23
  Str,
23
24
  Int,
@@ -28,6 +29,12 @@ pub enum BuiltinId {
28
29
  Max,
29
30
  Sqrt,
30
31
  Pow,
32
+ Floor,
33
+ Ceil,
34
+ Round,
35
+ Sin,
36
+ Cos,
37
+ Log,
31
38
  Push,
32
39
  Pop,
33
40
  TypeOf,
@@ -37,6 +44,19 @@ pub enum BuiltinId {
37
44
  BufLen,
38
45
  ClockMs,
39
46
  Assert,
47
+ Range,
48
+ RegexNew,
49
+ RegexTest,
50
+ RegexMatch,
51
+ RegexFindAll,
52
+ RegexReplace,
53
+ RegexSplit,
54
+ StrContains,
55
+ StrSplit,
56
+ StrTrim,
57
+ StrUpper,
58
+ StrLower,
59
+ StrReplace,
40
60
  }
41
61
 
42
62
  impl BuiltinId {
@@ -45,8 +65,9 @@ impl BuiltinId {
45
65
  "print" => Some(BuiltinId::Print),
46
66
  "println" => Some(BuiltinId::Println),
47
67
  "printf" => Some(BuiltinId::Printf),
68
+ "sprintf" => Some(BuiltinId::Sprintf),
48
69
  "len" => Some(BuiltinId::Len),
49
- "str" | "String" => Some(BuiltinId::Str),
70
+ "str" | "String" | "to_string" => Some(BuiltinId::Str),
50
71
  "int" => Some(BuiltinId::Int),
51
72
  "float" => Some(BuiltinId::Float),
52
73
  "bool" => Some(BuiltinId::Bool),
@@ -55,6 +76,12 @@ impl BuiltinId {
55
76
  "max" => Some(BuiltinId::Max),
56
77
  "sqrt" => Some(BuiltinId::Sqrt),
57
78
  "pow" => Some(BuiltinId::Pow),
79
+ "floor" => Some(BuiltinId::Floor),
80
+ "ceil" => Some(BuiltinId::Ceil),
81
+ "round" => Some(BuiltinId::Round),
82
+ "sin" => Some(BuiltinId::Sin),
83
+ "cos" => Some(BuiltinId::Cos),
84
+ "log" => Some(BuiltinId::Log),
58
85
  "push" | "append" => Some(BuiltinId::Push),
59
86
  "pop" => Some(BuiltinId::Pop),
60
87
  "typeof" | "type" => Some(BuiltinId::TypeOf),
@@ -64,6 +91,8 @@ impl BuiltinId {
64
91
  "buf_len" => Some(BuiltinId::BufLen),
65
92
  "clock_ms" => Some(BuiltinId::ClockMs),
66
93
  "assert" => Some(BuiltinId::Assert),
94
+ "range" => Some(BuiltinId::Range),
95
+ "RegExp" => Some(BuiltinId::RegexNew),
67
96
  _ => None,
68
97
  }
69
98
  }
@@ -107,6 +136,7 @@ pub enum Constant {
107
136
  Int(i64),
108
137
  Float(f64),
109
138
  String(String),
139
+ Regex { pattern: String, flags: String },
110
140
  }
111
141
 
112
142
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -117,6 +147,7 @@ pub enum IrBinOp {
117
147
  Div,
118
148
  FloorDiv,
119
149
  Mod,
150
+ Pow,
120
151
  Eq,
121
152
  Ne,
122
153
  Lt,
@@ -172,12 +203,10 @@ pub enum IrInstruction {
172
203
  BinOp(IrBinOp, Register, Register, Register),
173
204
  UnaryOp(IrUnaryOp, Register, Register),
174
205
 
175
- /// Demand-driven, lazy cross-language call site.
176
- /// The target module is only parsed & target function only lowered when executed.
177
206
  CallLazy(Register, CallSiteId, Vec<Register>),
178
- /// Fast direct call once resolved/known (e.g., self-recursion or resolved target).
179
207
  CallFn(Register, FnId, Vec<Register>),
180
208
  CallIndirect(Register, Register, Vec<Register>),
209
+ CallMethod(Register, Register, String, Vec<Register>),
181
210
  CallBuiltin(Register, BuiltinId, Vec<Register>),
182
211
  ResolveFn(Register, CallSiteId),
183
212
  LoadFnRef(Register, FnId),
@@ -186,6 +215,10 @@ pub enum IrInstruction {
186
215
  BranchIf(Register, BasicBlockId, BasicBlockId),
187
216
  Jump(BasicBlockId),
188
217
 
218
+ TryBegin(BasicBlockId, Register),
219
+ TryEnd,
220
+ Throw(Register),
221
+
189
222
  CreateArray(Register, Vec<Register>),
190
223
  GetIndex(Register, Register, Register),
191
224
  SetIndex(Register, Register, Register),
package/src/jit.rs CHANGED
@@ -48,20 +48,24 @@ impl JitAbiVal {
48
48
  tag: ABI_TAG_STR,
49
49
  payload: u64::from(h.0),
50
50
  },
51
- Value::Array(h) => Self {
51
+ Value::Regex(h) => Self {
52
52
  tag: 5,
53
53
  payload: u64::from(h.0),
54
54
  },
55
- Value::Object(h) => Self {
55
+ Value::Array(h) => Self {
56
56
  tag: 6,
57
57
  payload: u64::from(h.0),
58
58
  },
59
- Value::RawBuffer(h) => Self {
59
+ Value::Object(h) => Self {
60
60
  tag: 7,
61
61
  payload: u64::from(h.0),
62
62
  },
63
- Value::FunctionRef(id) => Self {
63
+ Value::RawBuffer(h) => Self {
64
64
  tag: 8,
65
+ payload: u64::from(h.0),
66
+ },
67
+ Value::FunctionRef(id) => Self {
68
+ tag: 9,
65
69
  payload: u64::from(id.0),
66
70
  },
67
71
  }
@@ -73,10 +77,11 @@ impl JitAbiVal {
73
77
  ABI_TAG_INT => Value::Int(self.payload as i64),
74
78
  ABI_TAG_FLOAT => Value::Float(f64::from_bits(self.payload)),
75
79
  ABI_TAG_STR => Value::Str(crate::runtime::StrHandle(self.payload as u32)),
76
- 5 => Value::Array(crate::runtime::ArrHandle(self.payload as u32)),
77
- 6 => Value::Object(crate::runtime::ObjHandle(self.payload as u32)),
78
- 7 => Value::RawBuffer(crate::runtime::BufHandle(self.payload as u32)),
79
- 8 => Value::FunctionRef(FnId(self.payload as u32)),
80
+ 5 => Value::Regex(crate::runtime::RegHandle(self.payload as u32)),
81
+ 6 => Value::Array(crate::runtime::ArrHandle(self.payload as u32)),
82
+ 7 => Value::Object(crate::runtime::ObjHandle(self.payload as u32)),
83
+ 8 => Value::RawBuffer(crate::runtime::BufHandle(self.payload as u32)),
84
+ 9 => Value::FunctionRef(FnId(self.payload as u32)),
80
85
  _ => Value::Nil,
81
86
  }
82
87
  }
@@ -122,7 +127,7 @@ pub fn is_jit_eligible(func: &IrFunction) -> bool {
122
127
  if !func.register_types[dst.0].is_jit_primitive() {
123
128
  return false;
124
129
  }
125
- if matches!(c, Constant::Nil) {
130
+ if matches!(c, Constant::Nil | Constant::Regex { .. }) {
126
131
  return false;
127
132
  }
128
133
  }
@@ -131,8 +136,14 @@ pub fn is_jit_eligible(func: &IrFunction) -> bool {
131
136
  return false;
132
137
  }
133
138
  }
134
- IrInstruction::UnaryOp(_, dst, src) => {
135
- if !is_numeric_or_bool(func, *dst) || !is_numeric_or_bool(func, *src) {
139
+ IrInstruction::UnaryOp(op, dst, src) => {
140
+ if *op == IrUnaryOp::BitsToF64 {
141
+ if func.register_types[src.0] != IrType::I64
142
+ || func.register_types[dst.0] != IrType::F64
143
+ {
144
+ return false;
145
+ }
146
+ } else if !is_numeric_or_bool(func, *dst) || !is_numeric_or_bool(func, *src) {
136
147
  return false;
137
148
  }
138
149
  }
@@ -174,7 +185,11 @@ pub fn is_jit_eligible(func: &IrFunction) -> bool {
174
185
  }
175
186
  }
176
187
  IrInstruction::Jump(_) => {}
177
- IrInstruction::CreateArray(..)
188
+ IrInstruction::TryBegin(..)
189
+ | IrInstruction::TryEnd
190
+ | IrInstruction::Throw(..)
191
+ | IrInstruction::CallMethod(..)
192
+ | IrInstruction::CreateArray(..)
178
193
  | IrInstruction::GetIndex(..)
179
194
  | IrInstruction::SetIndex(..)
180
195
  | IrInstruction::CreateObject(..)
@@ -256,12 +271,12 @@ impl JitEngine {
256
271
  let ptr_ty = module.target_config().pointer_type();
257
272
 
258
273
  let mut sig_call = module.make_signature();
259
- sig_call.params.push(AbiParam::new(ptr_ty)); // rt_ctx
260
- sig_call.params.push(AbiParam::new(types::I32)); // id
261
- sig_call.params.push(AbiParam::new(ptr_ty)); // args_ptr
262
- sig_call.params.push(AbiParam::new(ptr_ty)); // args_len
263
- sig_call.params.push(AbiParam::new(ptr_ty)); // out_ptr
264
- sig_call.returns.push(AbiParam::new(types::I8)); // status
274
+ sig_call.params.push(AbiParam::new(ptr_ty));
275
+ sig_call.params.push(AbiParam::new(types::I32));
276
+ sig_call.params.push(AbiParam::new(ptr_ty));
277
+ sig_call.params.push(AbiParam::new(ptr_ty));
278
+ sig_call.params.push(AbiParam::new(ptr_ty));
279
+ sig_call.returns.push(AbiParam::new(types::I8));
265
280
 
266
281
  let rt_call_site_id = module
267
282
  .declare_function("polycomp_rt_call_site", Linkage::Import, &sig_call)
@@ -315,10 +330,10 @@ impl JitEngine {
315
330
 
316
331
  let ptr_ty = self.module.target_config().pointer_type();
317
332
  let target_cfg = self.module.target_config();
318
- // Build native impl signature: (rt_ctx: ptr, status_out: ptr, p0, p1, ...) -> ret?
333
+
319
334
  let mut impl_sig = self.module.make_signature();
320
- impl_sig.params.push(AbiParam::new(ptr_ty)); // rt_ctx
321
- impl_sig.params.push(AbiParam::new(ptr_ty)); // status_out: *mut u8
335
+ impl_sig.params.push(AbiParam::new(ptr_ty));
336
+ impl_sig.params.push(AbiParam::new(ptr_ty));
322
337
  let param_types: Vec<IrType> = func.params.iter().map(|(_, t)| *t).collect();
323
338
  for &pty in &param_types {
324
339
  impl_sig.params.push(AbiParam::new(ir_to_cl_type(pty)));
@@ -335,7 +350,6 @@ impl JitEngine {
335
350
  .declare_function(&impl_name, Linkage::Local, &impl_sig)
336
351
  .map_err(|e| PolyError::msg("E0604", format!("JIT declare error: {e}")))?;
337
352
 
338
- // Pre-intern all string constants in the function
339
353
  let mut str_ids: FxHashMap<String, u32> = FxHashMap::default();
340
354
  for bb in &func.blocks {
341
355
  for instr in &bb.instructions {
@@ -372,7 +386,6 @@ impl JitEngine {
372
386
  let cl_blocks: Vec<_> = (0..func.blocks.len()).map(|_| fb.create_block()).collect();
373
387
  let trap_block = fb.create_block();
374
388
 
375
- // Declare SSA Variables for every IR register with primitive type
376
389
  let mut vars: Vec<Option<Variable>> = Vec::with_capacity(func.register_types.len());
377
390
  for &rty in &func.register_types {
378
391
  if rty.is_jit_primitive() && rty != IrType::Void {
@@ -387,7 +400,6 @@ impl JitEngine {
387
400
  let status_ptr_val = fb.block_params(prolog)[1];
388
401
  let entry_params: Vec<_> = fb.block_params(prolog)[2..].to_vec();
389
402
 
390
- // Zero-init all vars so SSA construction is guaranteed valid on all CFG paths
391
403
  for (idx, var_opt) in vars.iter().enumerate() {
392
404
  if let Some(var) = var_opt {
393
405
  let zero = match func.register_types[idx] {
@@ -404,7 +416,6 @@ impl JitEngine {
404
416
  }
405
417
  }
406
418
 
407
- // Compute max call args for scratch stack slots
408
419
  let max_args = func
409
420
  .blocks
410
421
  .iter()
@@ -460,7 +471,7 @@ impl JitEngine {
460
471
  let h = str_ids[s];
461
472
  fb.ins().iconst(types::I64, i64::from(h))
462
473
  }
463
- Constant::Nil => fb.ins().iconst(types::I64, 0),
474
+ _ => fb.ins().iconst(types::I64, 0),
464
475
  };
465
476
  fb.def_var(var, v);
466
477
  }
@@ -506,7 +517,7 @@ impl JitEngine {
506
517
  IrUnaryOp::BitNot => {
507
518
  let iv = coerce_cl_val(&mut fb, v, st, IrType::I64);
508
519
  fb.ins().bnot(iv)
509
- },
520
+ }
510
521
  IrUnaryOp::BitsToF64 => {
511
522
  let iv = coerce_cl_val(&mut fb, v, st, IrType::I64);
512
523
  fb.ins().bitcast(types::F64, MemFlagsData::new(), iv)
@@ -569,12 +580,28 @@ impl JitEngine {
569
580
  (fb.ins().floor(q), IrType::F64)
570
581
  }
571
582
  IrBinOp::Mod => {
572
- // x - floor(x / y) * y
573
583
  let q = fb.ins().fdiv(lf, rf);
574
584
  let trunc = fb.ins().trunc(q);
575
585
  let prod = fb.ins().fmul(trunc, rf);
576
586
  (fb.ins().fsub(lf, prod), IrType::F64)
577
587
  }
588
+ IrBinOp::Pow => {
589
+ emit_rt_abi_call(
590
+ &mut fb,
591
+ call_builtin_ref,
592
+ rt_ctx_val,
593
+ BuiltinId::Pow as u32,
594
+ &[*l, *r],
595
+ func,
596
+ &vars,
597
+ args_slot,
598
+ out_slot,
599
+ ptr_ty,
600
+ *dst,
601
+ trap_block,
602
+ );
603
+ continue;
604
+ }
578
605
  IrBinOp::Eq => (
579
606
  fb.ins().fcmp(FloatCC::Equal, lf, rf),
580
607
  IrType::Bool,
@@ -608,8 +635,24 @@ impl JitEngine {
608
635
  IrBinOp::Add => (fb.ins().iadd(li, ri), IrType::I64),
609
636
  IrBinOp::Sub => (fb.ins().isub(li, ri), IrType::I64),
610
637
  IrBinOp::Mul => (fb.ins().imul(li, ri), IrType::I64),
638
+ IrBinOp::Pow => {
639
+ emit_rt_abi_call(
640
+ &mut fb,
641
+ call_builtin_ref,
642
+ rt_ctx_val,
643
+ BuiltinId::Pow as u32,
644
+ &[*l, *r],
645
+ func,
646
+ &vars,
647
+ args_slot,
648
+ out_slot,
649
+ ptr_ty,
650
+ *dst,
651
+ trap_block,
652
+ );
653
+ continue;
654
+ }
611
655
  IrBinOp::Div | IrBinOp::FloorDiv | IrBinOp::Mod => {
612
- // Guard against integer division by zero
613
656
  let zero_chk =
614
657
  fb.ins().icmp_imm_s(IntCC::Equal, ri, 0);
615
658
  let ok_bb = fb.create_block();
@@ -633,7 +676,6 @@ impl JitEngine {
633
676
  } else if *op == IrBinOp::Mod {
634
677
  (fb.ins().srem(li, ri), IrType::I64)
635
678
  } else {
636
- // Python floor division
637
679
  let q = fb.ins().sdiv(li, ri);
638
680
  let rem = fb.ins().srem(li, ri);
639
681
  let rem_nz =
@@ -696,7 +738,6 @@ impl JitEngine {
696
738
  }
697
739
  IrInstruction::CallFn(dst, target_id, args) => {
698
740
  if *target_id == func.id && args.len() == func.params.len() {
699
- // Fast direct native self-recursion with zero boxing!
700
741
  let mut call_args = vec![rt_ctx_val, status_ptr_val];
701
742
  for (i, a) in args.iter().enumerate() {
702
743
  let av = fb.use_var(vars[a.0].unwrap());
@@ -714,7 +755,12 @@ impl JitEngine {
714
755
  let call_inst = fb.ins().call(self_ref, &call_args);
715
756
  let call_res = fb.inst_results(call_inst).first().copied();
716
757
 
717
- let st = fb.ins().load(types::I8, MemFlagsData::new(), status_ptr_val, 0);
758
+ let st = fb.ins().load(
759
+ types::I8,
760
+ MemFlagsData::new(),
761
+ status_ptr_val,
762
+ 0,
763
+ );
718
764
  let failed = fb.ins().icmp_imm_s(IntCC::NotEqual, st, 0);
719
765
  let ok_bb = fb.create_block();
720
766
  fb.ins().brif(
@@ -828,12 +874,11 @@ impl JitEngine {
828
874
  .map_err(|e| PolyError::msg("E0605", format!("JIT define impl error: {e}")))?;
829
875
  self.module.clear_context(&mut ctx);
830
876
 
831
- // Build uniform trampoline: extern "C" fn(rt_ctx, args_ptr, out_ptr) -> u8
832
877
  let mut tramp_sig = self.module.make_signature();
833
- tramp_sig.params.push(AbiParam::new(ptr_ty)); // rt_ctx
834
- tramp_sig.params.push(AbiParam::new(ptr_ty)); // args_ptr: *const u64
835
- tramp_sig.params.push(AbiParam::new(ptr_ty)); // out_ptr: *mut u64
836
- tramp_sig.returns.push(AbiParam::new(types::I8)); // status
878
+ tramp_sig.params.push(AbiParam::new(ptr_ty));
879
+ tramp_sig.params.push(AbiParam::new(ptr_ty));
880
+ tramp_sig.params.push(AbiParam::new(ptr_ty));
881
+ tramp_sig.returns.push(AbiParam::new(types::I8));
837
882
 
838
883
  let tramp_name = format!("__poly_tramp_{}", func.id.0);
839
884
  let tramp_func_id = self
@@ -864,13 +909,20 @@ impl JitEngine {
864
909
  for (i, &pty) in param_types.iter().enumerate() {
865
910
  let offset = (i * 8) as i32;
866
911
  let arg_val = match pty {
867
- IrType::F64 => fb.ins().load(types::F64, MemFlagsData::new(), args_ptr, offset),
912
+ IrType::F64 => {
913
+ fb.ins()
914
+ .load(types::F64, MemFlagsData::new(), args_ptr, offset)
915
+ }
868
916
  IrType::Bool => {
869
917
  let raw =
870
- fb.ins().load(types::I64, MemFlagsData::new(), args_ptr, offset);
918
+ fb.ins()
919
+ .load(types::I64, MemFlagsData::new(), args_ptr, offset);
871
920
  fb.ins().icmp_imm_s(IntCC::NotEqual, raw, 0)
872
921
  }
873
- _ => fb.ins().load(types::I64, MemFlagsData::new(), args_ptr, offset),
922
+ _ => {
923
+ fb.ins()
924
+ .load(types::I64, MemFlagsData::new(), args_ptr, offset)
925
+ }
874
926
  };
875
927
  call_args.push(arg_val);
876
928
  }
@@ -1028,6 +1080,7 @@ fn unary_out_ty(op: IrUnaryOp, src: IrType) -> IrType {
1028
1080
  match op {
1029
1081
  IrUnaryOp::Not => IrType::Bool,
1030
1082
  IrUnaryOp::BitNot => IrType::I64,
1083
+ IrUnaryOp::BitsToF64 => IrType::F64,
1031
1084
  IrUnaryOp::Neg => {
1032
1085
  if src == IrType::F64 {
1033
1086
  IrType::F64
@@ -1035,7 +1088,6 @@ fn unary_out_ty(op: IrUnaryOp, src: IrType) -> IrType {
1035
1088
  IrType::I64
1036
1089
  }
1037
1090
  }
1038
- IrUnaryOp::BitsToF64 => IrType::F64,
1039
1091
  }
1040
1092
  }
1041
1093
 
@@ -1096,4 +1148,4 @@ fn emit_return_zero(fb: &mut FunctionBuilder<'_>, ret_ty: IrType) {
1096
1148
  fb.ins().return_(&[z]);
1097
1149
  }
1098
1150
  }
1099
- }
1151
+ }