vile / scheme / integer_tail_kernel.v
68 lines · 63 sloc · 2.4 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3// These types select checked arithmetic at compilation. No marker value or
4// procedure is created at runtime.
5struct IntegerTailAdd {}
6struct IntegerTailSubtract {}
7struct IntegerTailMultiply {}
8
9struct IntegerTailKernelState {
10mut:
11 left i64
12 right i64
13 steps int
14 advanced bool
15}
16
17@[inline]
18fn integer_tail_typed_update[T](a i64, b i64) ?i64 {
19 $if T is IntegerTailAdd {
20 return small_add(a, b)
21 } $else $if T is IntegerTailSubtract {
22 return small_subtract(a, b)
23 } $else $if T is IntegerTailMultiply {
24 return small_multiply(a, b)
25 } $else {
26 return none
27 }
28}
29
30// The caller owns all six operands and this scalar state for the complete
31// call. Neither pointer escapes. Keep parameters/charges in locals through
32// the recurrence and commit only complete simultaneous updates.
33@[direct_array_access; noinline]
34fn integer_tail_kernel[A, B](mut state IntegerTailKernelState, condition Primitive,
35 operands &[6]IntegerTailOperand, on_true bool, max_steps int) {
36 mut left, mut right := state.left, state.right
37 mut steps := state.steps
38 mut advanced := false
39 cost := 19
40 for integer_tail_condition(condition, unsafe { operands[0].get(left, right) },
41 unsafe { operands[1].get(left, right) }) == on_true {
42 if steps > max_int - cost || (max_steps > 0 && max_steps - steps < cost) { break }
43 next_left := integer_tail_typed_update[A](unsafe { operands[2].get(left, right) },
44 unsafe { operands[3].get(left, right) }) or { break }
45 next_right := integer_tail_typed_update[B](unsafe { operands[4].get(left, right) },
46 unsafe { operands[5].get(left, right) }) or { break }
47 left, right = next_left, next_right
48 steps += cost
49 advanced = true
50 }
51 state.left = left
52 state.right = right
53 state.steps = steps
54 state.advanced = advanced
55}
56
57// The two operation choices happen once per entry, outside all recurrence
58// iterations. The admission guard has already limited both to these modes.
59@[inline]
60fn integer_tail_choose_right[A](right_op Primitive, mut state IntegerTailKernelState,
61 condition Primitive, operands &[6]IntegerTailOperand, on_true bool, max_steps int) {
62 match right_op {
63 .add { integer_tail_kernel[A, IntegerTailAdd](mut state, condition, operands, on_true, max_steps) }
64 .subtract { integer_tail_kernel[A, IntegerTailSubtract](mut state, condition, operands, on_true, max_steps) }
65 .multiply { integer_tail_kernel[A, IntegerTailMultiply](mut state, condition, operands, on_true, max_steps) }
66 else {}
67 }
68}
69