Making array indexing cheaper in purple gardens VM and JIT

Tags:

Welcome to yet another blog article about a single topic hijacked into a dev log kind of situation with some detours and some microbenchmarks, have fun :)

Sooooooo: Arrays must be indexable, the index has to adhere to being 0<=i<|a|; where || is the length of the array a. Checking this is regarded as a bounds check (wikipedia -Bounds checking)

The obligatory gardening example

Lets consider the following purple-garden snippet:

GARDEN
1import "io"
2fn at(xs:Array<Int> i:Int) Int {
3    // just here to stop inlining :)
4    io.println(i)
5    xs.[i]
6}
7io.println(at([1 2 3] 1))

Disregarding the io.println calls and the seemingly unnecessary indirection of indexing via at 1, we can inspect the resulting intermedite representation of at:

LLVM
 1// at
 2fn f1(%v0:Array<Int>, %v1:Int) -> Int {
 3    b0(%v0, %v1):
 4        ; just here to stop inlining
 5        %v2:Void = Sys io.println_int(%v1)
 6
 7        ; load first word of array, which is its length
 8        %v3:Int = Load %v0+0
 9
10        ; assert idx > -1
11        %v5:Bool = IGt %v1, -1
12        %v6:Void = Assert(InBounds) %v5
13
14        ; assert len > idx
15        %v7:Bool = ILt %v1, %v3
16        %v8:Void = Assert(InBounds) %v7
17
18        ; calculate offset by type size (8)
19        %v10:Int = IMul %v1, 8
20        ; add offset to arr ptr
21        %v11:Ptr = IAdd %v0, %v10
22        ; fetch arrayptr+offset+1 (skipping length word)
23        %v12:Int = Load %v11+8
24        ret %v12
25}

Rethinking the approach

The attentive reader will have realised this produces 8 instructions per index, which for the bytecode backend, where dispatch dominates, is very costly, even more so than in the x86 backend, where it still isnt free though.

Simplifying two bounds checks into one by knowing 2complement

TL;DR - I know math 🤓 - Info

Two cases, assuming i and len are i64 values and len is nonnegative:

  • A: negative index:
$$ \begin{aligned} i < 0 &\implies i \bmod 2^{64} \geq 2^{63} \\ 0 \leq len &\implies len < 2^{63} \\ &\implies \textrm{cast}_{u64}(i) > \textrm{cast}_{u64}(len) \end{aligned} $$
  • B: nonnegative index:
$$ \begin{aligned} i \geq 0 &\implies \textrm{cast}_{u64}(i) = i \\ &\implies \textrm{cast}_{u64}(i) < \textrm{cast}_{u64}(len) \Leftrightarrow i < len \end{aligned} $$

Thus, combined:

$$ \begin{aligned} -1 < i < len &\Leftrightarrow \textrm{cast}_{u64}(i) < \textrm{cast}_{u64}(len) \end{aligned} $$

For the sake of explaining the simplification, I will not show this with 32 bit integers, but rather with 8 bit. In general, fixed width integers are represented with the two complements method, meaning you have a numeric value assigned to each bit, for instance 12 is formed by setting the bits for 4 and 8, but not for 1 and 2, in a table it would be:

twos complement2^72^62^52^42^32^22^12^0
decimal1286432168421
-
1200001100

Which is the sum of its set bits value in the twos complement table, which is 8+4, thus 12. However this is only valid for unsigned 8 bit integers, representing 0<=x<=255 (256) different values. For signed integers the most significant bit has a negative weight, while all others are the same numbers we are “adding” to this starting point. So -12 would be first msb set, so -128 as a base, whereas then the bits for 64, 32 and 4 are set so we arrive at -12 (-128+64+32+16+4=-12):

twos complement-(2^7)2^62^52^42^32^22^12^0
decimal-1286432168421
-
-1211110100

However, a simple cast in the sense of -12 as u8 results not in 12, but in the unsigned interpretation of -12’s bits, specifically seeing 0b11110100, which results in 128+64+32+16+4=244.

In summary: casting a negative signed integer to its equal bit sized unsigned counterpart produces very large numbers, thus satisfing our requirement to make the bound check in a single comparison.

This behaviour we can exploit to merge the two comparisons in both the bytecode and the x86 jitted output from:

RUST
1-1 < i && i < len

To

RUST
1(i as u64) < (len as u64)

Info

My quick verification to make sure:

RUST
 1fn main() {
 2    let len = 2;
 3    std::env::args()
 4        .filter_map(|n| n.parse::<i64>().ok())
 5        .for_each(|i| {
 6            let base = -1 < i && i < len;
 7            let opt = (i as u64) < (len as u64);
 8            assert_eq!(base, opt);
 9        });
10}
SHELL
1cargo run 12 15 1 0 -1000

In the Immediate representation

Thus, let me introduce the Index ir instruction, merging the bounds check, offset calculation and offset usage a single instruction:

LLVM
1// at
2fn f1(%v0:Array<Int>, %v1:Int) -> Int {
3        b0(%v0, %v1):
4                %v2:Void = Sys io.println_int(%v1)
5                %v3:Ptr<Int> = Index %v0, %v1
6                %v4:Int = Load %v3+0
7                ret %v4
8}

In the bytecode virtual machine

Previously, the ir lowered to bytecode instructions:

ASM
 100000000 <at>:
 2    ; removed prologue
 3
 4    ; fetch r0+0 (array length) into r2
 5  0005:    b8 00 00 00    load r2, r0, #0          ; 4: xs.[i]
 6    ; check r1 (idx) > -1 into r3
 7  0006:    d0 08 ff ff    igt_imm r3, r1, #-1
 8    ; trap if !r3
 9  0007:    fb 08 00 00    assert r3, InBounds
10    ; check r1 < r2 (idx < arrlen) into r2
11  0008:    8c 08 02 00    ilt r2, r1, r2
12    ; trap if !r2
13  0009:    bb 08 00 00    assert r2, InBounds
14    ; r1 mul 8 (idx*type size) into r1
15  000a:    45 08 08 00    imul_imm r1, r1, #8
16    ; r0+r1 (arr+offset) into r0
17  000b:    00 00 01 00    iadd r0, r0, r1
18    ; fetch value from r0
19  000c:    38 00 08 00    load r0, r0, #8
20    ; removed epilogue

Now its two instructions, meaning we reduced our instruction count by 6, cutting the dispatch cost by a lot 🤓:

ASM
100000000 <at>:
2    ; removed prologue
3
4    ; idx r0 with r1 with typesize 8 into r0 (arr[idx])
5  0005:    3a 00 01 01    idx r0, r0, r1, #8       ; 4: xs.[i]
6    ; fetch value from r0
7  0006:    38 00 00 00    load r0, r0, #0
8    ; removed epilogue

Being sidetracked: Dispatch here, dispatch there

Btw, purple garden uses the become proposal for tailcalling op code handlers, meaning instead of jumping back to the loop head, decoding the op code and then jumping to the handler. Instead, become decodes the op and the jmp location and then jumps to it, making dispatch less costly due to less indirection while jumping from opcode handler to opcode handler, see the following setup:

RUST
 1type V = *mut Vm<'static>;
 2type Handler = unsafe fn(V, *const Packed, usize, Packed) -> usize;
 3struct Handlers<const B: bool>;
 4
 5impl<const B: bool> Handlers<B> {
 6    const TABLE: [Handler; 64] = {
 7        let mut table: [Handler; 64] = [halt::<B>; 64];
 8        let mut i = 0;
 9        while i < Tag::COUNT {
10            table[i] = Self::handler(unsafe { std::mem::transmute::<u8, Tag>(i as u8) });
11            i += 1;
12        }
13        table
14    };
15
16    const fn handler(tag: Tag) -> Handler {
17        match tag {
18            // [...]
19            Tag::Idx => rrri11::idx::<B>,
20            Tag::Nop => nop::<B>,
21        }
22    }
23}
24
25macro_rules! next {
26    ($vm:ident, $code:ident, $pc:expr) => {{
27        let pc = $pc;
28        let op = *$code.add(pc);
29        become (Handlers::<B>::TABLE[op.tag() as usize])($vm as V, $code, pc, op)
30    }};
31}
32
33pub(super) unsafe fn enter<const B: bool>(
34    vm: V,
35    code: *const Packed,
36    pc: usize,
37) -> Result<usize, Anomaly> {
38    unsafe {
39        let op = *code.add(pc);
40        let pc = (Handlers::<B>::TABLE[op.tag() as usize])(vm, code, pc, op);
41        (*vm).pending_trap.take().map_or(Ok(pc), Err)
42    }
43}

For instance, the NOP op handler is defined as:

RUST
1unsafe fn nop<const B: bool>(vm: V, code: *const Packed, pc: usize, _op: Packed) -> usize {
2    unsafe { next!(vm, code, pc.wrapping_add(1)) }
3}

Meaning the dispatch compiles to a solid 6 instructions:

NASM
1mov    ecx,DWORD PTR [rsi+rdx*4+0x4]   ; op = code[pc+1]
2inc    rdx                             ; pc += 1
3mov    eax,ecx
4and    eax,0x3f                        ; tag = op & 63
5lea    r8,[rip+TABLE]
6jmp    QWORD PTR [r8+rax*8]            ; become TABLE[tag](vm, code, pc, op)

Generating op codes

That aside, lets look at the Op code and its packed representation

Lets not get sidetracked as before again, but i use a macro to generate the rusty representation in the form of an enum and its tag, which must fit into 6 bits:

RUST
 1macro_rules! ops {
 2    (
 3        // match a single definition
 4        $(
 5            // meta tags like doc comments, which are just #[doc]
 6            $(#[$meta:meta])*
 7
 8            // definition and tag name
 9            $name:ident
10
11            // body delimited with {}, matches field containers, is optional via ? to support Halt
12            // and Nop (bodyless variants)
13            $({ $($body:tt)* })?
14        ),*
15        $(,)?
16    ) => {
17        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18        pub enum Op {
19             $( $(#[$meta])* $name $({ $($body)* })? ),*
20        }
21
22        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
23        #[repr(u8)]
24        pub enum Tag {
25            $($name),*
26        }
27
28        impl Tag {
29            pub const COUNT: usize = [$(Tag::$name),*].len();
30        }
31
32        /// static assertion since tag is 6 bits, meaning 2^6=64 op codes can be represented
33        const _: () = assert!(Tag::COUNT <= 64);
34
35        impl Op {
36            pub const fn tag(&self) -> Tag {
37                match self {
38                    $(Self::$name {..} => Tag::$name),*
39                }
40            }
41        }
42    }
43}

So that macro is used to generate the opcode, lets look at IAdd, Idx and Nop, just so you get the gist:

RUST
 1ops! {
 2     IAdd {
 3        dst: u8,
 4        lhs: u8,
 5        rhs: u8,
 6    },
 7    // [...]
 8
 9    /// `r[dst] = r[target] + 8 + r[idx] * stride`, the address of element idx.
10    /// Traps with [`crate::Anomaly::IndexOutOfBounds`] unless `0 <= r[idx] < len`,
11    /// len being the array's first word of an array
12    Idx {
13        dst: u8,
14        target: u8,
15        idx: u8,
16        /// distance between elements of array,
17        /// so addr = arr + 8 + idx * stride
18        stride: u16,
19    },
20
21    // [...]
22    Nop,
23}

Being sidetracked v2: Packing and unpacking op codes

Since every opcode is a fixed length (32bits), i decided to make the tag 6 bits, fitting 2^6 (64) op code variants or kinds. Every register I made 5 bits, since the purple garden virtual machine has 32 registers. So something like IAdd is the op class rrr, since it uses three registers, meaning i pack it using a macro helper:

RUST
 1/// encode different ops into the new packed format, operator classes are the prefix of the macro
 2/// invocation
 3///
 4/// Every opcode starts with tag6 at 0..5
 5///
 6/// r        := r5
 7/// rr       := r5 r5
 8/// rrr      := r5 r5 r5
 9/// rrri11   := r5 r5 r5 imm11
10/// rri16    := dst5 lhs5 imm16
11/// ri21     := dst5 imm21
12/// ru21     := r5 idx21
13/// t16      := target16
14/// u26      := func26
15/// rt16     := cond5 target16
16/// rrt16    := lhs5 rhs5 target16
17/// ri5t16   := lhs5 imm5 target16
18/// rru16    := r5 r5 offset16
19/// rk1u20   := subject5 kind1 table20
20/// rrk1u15  := dst5 subject5 kind1 table15
21/// rk2u3u16 := dst5 kind2 align_log(2)3 size16
22/// u5u16    := argc5 idx16
23/// u16k1    := idx16 returns_double1
24macro_rules! encode_packed {
25    // [...]
26    (rrr,$r1:expr,$r2:expr,$r3:expr) => {
27        ($r1 as u32) << 6 | ($r2 as u32) << 11 | ($r3 as u32) << 16
28    };
29    // [...]
30}

And unpack it using a method on the Packed structure:

RUST
 1#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 2#[repr(transparent)]
 3pub struct Packed(u32);
 4
 5impl Packed {
 6    /// [0..5]
 7    #[inline(always)]
 8    pub fn tag(&self) -> super::Tag {
 9        let tag_raw = (self.0 & 0b0011_1111) as u8;
10        unsafe { std::mem::transmute::<u8, super::Tag>(tag_raw) }
11    }
12
13    #[inline(always)]
14    pub fn to_le_bytes(self) -> [u8; 4] {
15        self.0.to_le_bytes()
16    }
17
18    /// `width` bits starting at bit `at`
19    #[inline(always)]
20    fn bits(self, at: u32, width: u32) -> u32 {
21        (self.0 >> at) & ((1 << width) - 1)
22    }
23
24    #[inline(always)]
25    pub fn r(self) -> u8 {
26        self.bits(6, 5) as u8
27    }
28
29    #[inline(always)]
30    pub fn rr(self) -> (u8, u8) {
31        (self.r(), self.bits(11, 5) as u8)
32    }
33
34    #[inline(always)]
35    pub fn rrr(self) -> (u8, u8, u8) {
36        let (r1, r2) = self.rr();
37        (r1, r2, self.bits(16, 5) as u8)
38    }
39}

So put together the easiest case (IAdd) is encoded:

RUST
 1impl super::Op {
 2    pub fn encode(self) -> Packed {
 3        Packed(
 4            self.tag() as u32
 5                | match self {
 6                    // none
 7                    crate::op::Op::Ret
 8                    | crate::op::Op::Halt
 9                    | crate::op::Op::Nop => 0,
10                    // rrr
11                    crate::op::Op::IAdd { dst, lhs, rhs } => encode_packed!(rrr, dst, lhs, rhs),
12
13                    // [...] all the other classes
14                },
15        )
16    }
17}

And decoded:

RUST
 1pub(super) unsafe fn i_add<const B: bool>(
 2    vm: V,
 3    code: *const Packed,
 4    pc: usize,
 5    op: Packed,
 6) -> usize {
 7    unsafe {
 8        let (dst, lhs, rhs) = op.rrr();
 9        let l = r!(vm, lhs).as_int();
10        let r = r!(vm, rhs).as_int();
11        r_mut!(vm, dst) = Value::from(l + r);
12        next!(vm, code, pc.wrapping_add(1))
13    }
14}

Now: the idx instruction

Previously we saw how the rust enum representing the idx opcode is laid out, now the packed version, same as before we have a macro for packing and a method for unpacking. Contrary to IAdd, Idx’s class is rrri11, since it needs three registers and a 11 bit immediate value:

RUST
 1macro_rules! encode_packed {
 2    // [...]
 3    (rrr,$r1:expr,$r2:expr,$r3:expr) => {
 4        ($r1 as u32) << 6 | ($r2 as u32) << 11 | ($r3 as u32) << 16
 5    };
 6    (rrri11,$r1:expr,$r2:expr,$r3:expr,$imm:expr) => {
 7        encode_packed!(rrr, $r1, $r2, $r3) | ($imm as u32) << 21
 8    };
 9    // [...]
10}

It is decoded or unpacked with a method of the same name on Packed:

RUST
 1impl Packed {
 2    // [...]
 3
 4    /// `width` bits starting at bit `at`
 5    #[inline(always)]
 6    fn bits(self, at: u32, width: u32) -> u32 {
 7        (self.0 >> at) & ((1 << width) - 1)
 8    }
 9
10    #[inline(always)]
11    pub fn r(self) -> u8 {
12        self.bits(6, 5) as u8
13    }
14
15    #[inline(always)]
16    pub fn rr(self) -> (u8, u8) {
17        (self.r(), self.bits(11, 5) as u8)
18    }
19
20    #[inline(always)]
21    pub fn rrr(self) -> (u8, u8, u8) {
22        let (r1, r2) = self.rr();
23        (r1, r2, self.bits(16, 5) as u8)
24    }
25
26    #[inline(always)]
27    pub fn rrri11(self) -> (u8, u8, u8, u16) {
28        let (r1, r2, r3) = self.rrr();
29        (r1, r2, r3, (self.0 >> 21) as u16)
30    }
31}

Thus encoding via:

RUST
1// rrri11
2crate::op::Op::Idx {
3    dst,
4    target,
5    idx,
6    stride,
7} => encode_packed!(rrri11, dst, target, idx, stride),

Meaning we decode and execute in the handler:

RUST
 1use super::*;
 2
 3pub(super) unsafe fn idx<const B: bool>(
 4    vm: V,
 5    code: *const Packed,
 6    pc: usize,
 7    op: Packed,
 8) -> usize {
 9    unsafe {
10        // decode op content
11        let (dst, target, idx, stride) = op.rrri11();
12        // fetch numeric idx from rIDX as int
13        // could be just 5 or something
14        let idx = r!(vm, idx).as_int();
15        // fetch rTARGET as a ptr, for instance an array
16        let ptr = r!(vm, target).as_ptr::<u8>();
17
18        // idx has to uphold 0<=idx<len(src),
19        // where len(src) is ptr+0, see memory layout
20        // of arrays
21        trap_if!(
22            vm,
23            idx as u64 >= *(ptr as *const u64),
24            Anomaly::IndexOutOfBounds { pc }
25        );
26
27        let offset = 8 + idx as usize * stride as usize;
28        // equiv to c like:
29        //      reg[dst] = *(Value)(arr+8+idx*stride)
30        // where stride is the size of the elements type
31        // and 8 is the skip over the first word of the ptr,
32        // which is the length of an array
33        r_mut!(vm, dst) = Value::from_ptr(ptr.add(offset));
34        next!(vm, code, pc.wrapping_add(1))
35    }
36}

Visualising with both vm registers and memory, assuming we are executing:

GARDEN
1let arr = [161 187]
2# focusing on:
3let idx2 = arr.[1]

Eqiv to loading the idx into r1, while the array reference is in r0:

ASM
100000000 <entry>:
2    ; removed array creation
3  0007:    5c 08 00 00    load_imm r1, #1
4  0008:    3a 00 01 01    idx r0, r0, r1, #8
TEXT
 1+------------ Vm -----------+
 2|     | u64 | u64 | u64 |   |
 3|   r | r0  | r1  | r2  |   |
 4+-------^-----^-------------+
 5        |     |
 6        |     idx (Int)
 7        |
 8       target (&Array<Int>)
 9              |
10              _
11---------- Vm Heap -----------
12              |
13              +-------+
14                      |
15                      v
16        +----------- Arr -------------+
17        | component: len  |pos0 |pos1 |
18        | layout:    [2]  [161] [187] |
19        +-----------------------------+

In the x86 jit backend

Whereas previously this required a bucketload of instructions:

Btw thank samuelscheit for the x86 assembly annotations, he was buggering me how no one understands this without comments :)

NASM
 10000000000000000 <jit_at>:
 2    ; removed prologue
 3
 4    ; rsi=r0 (arr ptr), rdx=r1 (idx), rbx=vm ptr
 5
 6    ; fetch rsi+0 (array length) into r8
 7  29:   4c 8b 46 00             mov    0x0(%rsi),%r8
 8    ; compare rdx (idx) with -1
 9  2d:   48 81 fa ff ff ff ff    cmp    $0xffffffffffffffff,%rdx
10    ; zero r9, mov instead of xor, so xor doesnt clobber cmp flag(s)
11  34:   49 c7 c1 00 00 00 00    mov    $0x0,%r9
12    ; r9b=1 if idx > -1
13  3b:   41 0f 9f c1             setg   %r9b
14    ; check r9 != 0
15  3f:   4d 85 c9                test   %r9,%r9
16    ; if idx > -1, jmp over trap, continue at 61
17  42:   0f 85 19 00 00 00       jne    61 <jit_at+0x61>
18    ; vm as first arg
19  48:   48 89 df                mov    %rbx,%rdi
20    ; anomaly kind as second arg (to communicate trap is InBounds kind)
21  4b:   48 be 01 00 00 00 00    movabs $0x1,%rsi
22  52:   00 00 00
23    ; absolute addr of jit_trap_assert in rax
24  55:   48 b8 00 00 00 00 00    movabs $0x0,%rax
25  5c:   00 00 00
26                        57: R_X86_64_64 jit_trap_assert
27  5f:   ff d0                   call   *%rax
28    ; compare rdx (idx) with r8 (array length)
29  61:   4c 39 c2                cmp    %r8,%rdx
30    ; zero r8, flag preserving
31  64:   49 c7 c0 00 00 00 00    mov    $0x0,%r8
32    ; r8b=1 if idx < len
33  6b:   41 0f 9c c0             setl   %r8b
34    ; check r8 != 0
35  6f:   4d 85 c0                test   %r8,%r8
36    ; if idx < len, skip over trap, continue at 91
37  72:   0f 85 19 00 00 00       jne    91 <jit_at+0x91>
38    ; same trap setup and call as above
39  78:   48 89 df                mov    %rbx,%rdi
40  7b:   48 be 01 00 00 00 00    movabs $0x1,%rsi
41  82:   00 00 00
42  85:   48 b8 00 00 00 00 00    movabs $0x0,%rax
43  8c:   00 00 00
44                        87: R_X86_64_64 jit_trap_assert
45  8f:   ff d0                   call   *%rax
46    ; rdx mul 8 (idx*type size) into r8
47  91:   4c 69 c2 08 00 00 00    imul   $0x8,%rdx,%r8
48    ; rsi+r8 (arr+offset) into rsi
49  98:   4c 01 c6                add    %r8,%rsi
50    ; fetch value from rsi+8 (skipping the length) into rsi
51  9b:   48 8b 76 08             mov    0x8(%rsi),%rsi
52    ; removed epilogue

We now instead lower the Index instruction to:

NASM
 10000000000000000 <jit_at>:
 2    ; removed prologue
 3    ; rsi=r0 (arr ptr), rdx=r1 (idx), rbx=vm ptr
 4
 5    ; compare rdx (idx) with rsi+0 (array len)
 6  29:   48 3b 56 00             cmp    0x0(%rsi),%rdx
 7    ; unsigned idx < len holds, skip trap, continue at 4c
 8    ; (jb is the unsigned below, so a negative idx is huge
 9    ; and fails the check, as i explained in the 2complements section)
10  2d:   0f 82 19 00 00 00       jb     4c <jit_at+0x4c>
11    ; vm ptr as first arg
12  33:   48 89 df                mov    %rbx,%rdi
13    ; anomaly kind as second arg
14  36:   48 be 01 00 00 00 00    movabs $0x1,%rsi
15  3d:   00 00 00
16    ; absolute addr of jit_trap_assert in rax
17  40:   48 b8 00 00 00 00 00    movabs $0x0,%rax
18  47:   00 00 00
19                        42: R_X86_64_64 jit_trap_assert
20    ; trap
21  4a:   ff d0                   call   *%rax
22    ; rsi+rdx*8+8 (arr+idx*type size+length skip) into rsi,
23    ; (this merges the offset computation in a single instruction, aitn that
24    ; nice)
25  4c:   48 8d 74 d6 08          lea    0x8(%rsi,%rdx,8),%rsi
26    ; fetch value from rsi
27  51:   48 8b 76 00             mov    0x0(%rsi),%rsi
28    ; removed epilogue

Benchmark(s)

Our example is a pretty uncomplicated heavy array indexing focused benchmark, which is, ofc a microbenchmark:

GARDEN
 1# Sums an array literal in a tight recursive loop.
 2# Every xs.[i] produces bounds check, showing indexing costs
 3import "testing"
 4
 5#! acc plus xs.[j] for j in [i, 32).
 6fn sweep(xs:Array<Int> i:Int acc:Int) Int {
 7    match {
 8        i == 32 { acc }
 9        { sweep(xs i + 1 acc + xs.[i]) }
10    }
11}
12
13#! Sum of k sweeps
14fn rounds(xs:Array<Int> k:Int acc:Int) Int {
15    match {
16        k == 0 { acc }
17        { rounds(xs k - 1 acc + sweep(xs 0 0)) }
18    }
19}
20
21#! b blocks of 2000 rounds
22fn blocks(xs:Array<Int> b:Int acc:Int) Int {
23    match {
24        b == 0 { acc }
25        { blocks(xs b - 1 acc + rounds(xs 2000 0)) }
26    }
27}
28
29let xs = [11 48 85 21 58 95 31 68 4 41 78 14 51 88 24 61 98 34 71 7 44 81 17 54 91 27 64 0 37 74 10 47]
30testing.assert(blocks(xs 100 0) == 306800000)

And all numbers were computed on:

SHELL
1$ inxi
2CPU: 8-core AMD Ryzen 7 3700X (-MT MCP-)
3speed/min/max: 4047/2200/4979 MHz
4Kernel: 7.2.14-arch1-1 x86_64 Up: 1d 5h 18m
5Mem: 21.27/31.26 GiB (68.0%) Storage: 2.27 TiB (38.6% used)
6Procs: 506 Shell: fish inxi: 3.3.41

Results for Interpreter and Jit

Interpreter (--no-jit)BeforeAfterChange
Wall time95.6 ms59.9 ms−37.4% (1.6x)
Instructions1,374,124,846836,515,352−39.1%
Cycles381,011,434234,946,985−38.3%
Branches112,984,47468,182,320−39.7%
Branch misses212,833212,0730
IPC3.613.56−0.05
JITBeforeAfterChange
Wall time11.5 ms7.9 ms−31.0% (1.4x)
Instructions140,113,69776,103,420−45.7%
Cycles42,189,25127,802,005−34.1%
Branches26,983,19020,581,065−23.7%
Branch misses211,863211,7470
IPC3.322.74−0.58

  1. i added, so the preexisting optimisation passes dont fuse the whole thing into a single load of the imm value at the idx of the arr:

    LLVM
    1// entry
    2fn f0() -> Void {
    3    b0():
    4        %v2:Int = 1
    5        %v16:Void = Sys io.println_int(%v2)
    6        ret %v16
    7}
     ↩︎