Docs/Advanced

SIMD vectors

Vector types for data-parallel math.

On this page

Normally, adding two arrays of four numbers takes four separate additions in a loop. SIMD (Single Instruction, Multiple Data) packs several numbers side by side into one fixed-size value — called a vector — so the CPU can add, multiply, or compare all of them in a single instruction.

Each slot inside a vector is called a lane. For example, an i32x4 holds four i32 values in four lanes: [1, 2, 3, 4]. Adding two i32x4 vectors adds each lane independently at the same time:

Text
  [  1,  2,  3,  4 ]
+ [ 10, 20, 30, 40 ]
= [ 11, 22, 33, 44 ]

SIMD shines in tight loops that do the same work on many numbers or bytes — such as scanning text, processing pixels or audio, checksums, and numeric math. The compiler emits hardware SIMD instructions where the target CPU supports them and falls back to regular instructions where it doesn't.

Vector types#

A vector type name is <element type>x<lane count>, and its total size is between 64 and 512 bits:

Type Lanes Total size Typical use
u8x16 16 bytes 128 bits Scanning text, parsing, byte transforms
i32x4, f32x4 4 ints or floats 128 bits Math, geometry, pixels (works everywhere by default)
i64x2, f64x2 2 64-bit numbers 128 bits Double-precision math
u8x32, f32x8 32 bytes / 8 floats 256 bits Wider throughput on CPUs with AVX2
i64x8, f32x16 8 / 16 lanes 512 bits Wider throughput on CPUs with AVX-512

Other combinations such as i16x8 or u32x8 work the same way. 128-bit vectors are supported on every 64-bit x86-64 and ARM64 CPU out of the box; see CPU features for using wider vectors safely.

Standard operators work lane by lane — lane 0 with lane 0, lane 1 with lane 1, and so on:

  • +, -, and * on any vector; / on float vectors
  • &, |, ^, and ~ on integer vectors; << and >> by a constant shift count
  • == and != check whether every lane matches and return a single bool

Create, load, and store vectors#

Because a vector is a fixed-size pack of lanes, you usually get data into and out of it in three ways:

  • $load[T](view, offset) copies one vector's worth of adjacent elements starting at index offset from an Array, String, or slice. $store(view, offset, v) writes the lanes back out. Both are bounds-checked and do not require special memory alignment.
  • $splat[T](x) creates a vector where every lane contains the same value x — for example, $splat[i32x4](10) produces [10, 10, 10, 10]. This is how you add or multiply every lane by a constant.
  • $extract(v, i) reads a single lane as a normal scalar, $insert(v, i, x) returns a new vector with lane i replaced, and $reduce_add(v) collapses all lanes into one total.
Valk
fn main() {
    let values = Array[i32]{ 1, 2, 3, 4 }

    let a = $load[i32x4](values, 0)  // [1, 2, 3, 4]
    let b = $splat[i32x4](10)        // [10, 10, 10, 10]
    let c = a * b + a                // [11, 22, 33, 44]

    println($extract(c, 3))          // 44
    println($reduce_add(c))          // 110 (11 + 22 + 33 + 44)

    let changed = $insert(a, 0, 9)   // [9, 2, 3, 4]
    $store(values, 0, changed)
    println(values[0])               // 9
}

Compare and select without branches#

In normal code you branch with if, but inside a vector some lanes may satisfy a condition while others do not. SIMD handles this without branches in two steps:

  1. Compare two vectors lane by lane with $eq, $ne, $lt, $gt, $lte, or $gte. The result is a mask: an integer vector with all bits set (true) in the lanes that matched and 0 (false) in the rest.
  2. Act on the mask in one of two ways: - $select(mask, if_true, if_false) acts like a per-lane ternary (mask ? if_true : if_false), picking each lane from if_true where the mask is set and from if_false where it isn't. - $mask_bits(mask) packs one bit per lane into a regular uint (bit 0 is lane 0, bit 1 is lane 1, and so on). You can test bits != 0 to see if any lane matched, or call $count_ones(bits) to count how many lanes matched.
Valk
fn main() {
    let a = $load[i32x4](Array[i32]{ 1, 2, 3, 4 }, 0) // [1, 2, 3, 4]
    let limit = $splat[i32x4](2)                      // [2, 2, 2, 2]

    let big = $gt(a, limit)                           // [false, false, true, true]
    println($mask_bits(big))                          // 12 (binary 1100: lanes 2 and 3)

    // Clamp every lane to at most 2: pick `limit` where `big` is true, else keep `a`
    let capped = $select(big, limit, a)               // [1, 2, 2, 2]
    println($reduce_max(capped))                      // 2
}

Example: process a slice in chunks#

Most real SIMD loops follow the same two-part structure:

  1. A vector loop that processes a full chunk at a time (here 16 bytes per iteration with u8x16).
  2. A plain scalar tail loop that handles the remaining 0–15 elements at the end when the input length isn't a multiple of the vector width.
Valk
fn count_spaces(text: local &[u8]) uint {
    let spaces = $splat[u8x16](' ')           // 16 copies of ' '
    let total: uint = 0
    let i: uint = 0

    // Process 16 bytes at a time
    while i + 16 <= text.length {
        let chunk = $load[u8x16](text, i)     // load next 16 bytes
        let matches = $eq(chunk, spaces)      // mask: true where byte == ' '
        let bits = $mask_bits(matches)        // 16-bit integer, 1 bit per lane
        total += $count_ones(bits)            // count how many lanes matched
        i += 16
    }

    // Handle any remaining bytes (< 16)
    while i < text.length {
        if text[i] == ' ' : total++
        i++
    }
    return total
}

fn main() {
    println(count_spaces("a b c d e f g h i j k l m n o p q r")) // 17
}

Rearrange lanes with $shuffle#

$shuffle(a, b, i0, i1, ...) builds a new vector by picking lanes from a and b using constant indices. For two 4-lane vectors, indices 0..3 refer to lanes of a and 4..7 refer to lanes of b:

Valk
fn main() {
    let a = $load[i32x4](Array[i32]{ 10, 20, 30, 40 }, 0)
    let b = $load[i32x4](Array[i32]{ 50, 60, 70, 80 }, 0)

    let reversed = $shuffle(a, a, 3, 2, 1, 0)  // [40, 30, 20, 10]
    let mixed = $shuffle(a, b, 0, 4, 1, 5)     // [10, 50, 20, 60]

    println($extract(reversed, 0))             // 40
    println($extract(mixed, 1))                // 50
}

Builtins reference#

Where the vector type cannot be inferred from the arguments, write it in [...] (for example $splat[u8x16](0) or $load[f32x4](slice, 0)).

Builtin What it does
$splat[T](x) Create a vector of type T with every lane filled with x (e.g. [x, x, x, x])
$load[T](view, offset) Copy one vector of type T from view starting at element offset
$store(view, offset, v) Write all lanes of v into view starting at element offset
$extract(v, i) Read the single value at lane i
$insert(v, i, x) Return a copy of v with lane i replaced by x
$shuffle(a, b, i0, i1, ...) Build a vector from lanes at constant indices (0..n-1 from a, n..2n-1 from b)
$eq, $ne, $lt, $gt, $lte, $gte(a, b) Compare a and b lane by lane, returning a mask vector
$select(mask, a, b) Per-lane ternary: pick from a where mask is true, else from b
$mask_bits(mask) Pack one bit per mask lane into a uint (bit i is 1 if lane i is true)
$reduce_add, $reduce_min, $reduce_max(v) Collapse all lanes into a single scalar (sum, minimum, or maximum)
$reduce_and, $reduce_or, $reduce_xor(v) Combine all integer lanes into a single scalar with bitwise AND, OR, or XOR
$bitcast[T](v) Reinterpret the raw bytes of v as another vector type of the same total bit width
$lookup(table, indexes) Byte lookup table: each lane in indexes picks a byte from table (16 or 32 lanes; requires $target_ssse3 / $target_avx2 on x86-64)
$clmul(a, b) Carry-less multiply of two u64 values into a u64x2 (for CRC/GCM; x86-64 with $target_pclmul)

CPU features#

By default, the compiler targets a baseline CPU where 128-bit vectors work everywhere, while wider instructions such as AVX2 are not assumed. You have two ways to use newer CPU instructions:

  1. Target a specific CPU at compile time when you control the machine running the binary:
Terminal
valk build src -o app --release --cpu native     # optimize for this machine's CPU
valk build src -o app --release --cpu x86-64-v3  # target a named x86-64 feature level (includes AVX2)
  1. Dispatch at runtime when shipping one executable that should run everywhere and speed up on newer CPUs. Mark the fast function with a $target_* attribute and call it only after core.cpu_has confirms the feature:
Valk
use valk.core

fn sum_avx2(values: local &[f32]) f32 $target_avx2 {
    let acc = $splat[f32x8](0)        // 8 running sums in parallel
    let i: uint = 0
    while i + 8 <= values.length {
        acc = acc + $load[f32x8](values, i)
        i += 8
    }
    let total = $reduce_add(acc)      // combine the 8 partial sums into one
    while i < values.length {
        total += values[i]
        i++
    }
    return total
}

fn sum_plain(values: local &[f32]) f32 {
    let total: f32 = 0
    each values as v : total += v
    return total
}

fn sum(values: local &[f32]) f32 {
    if core.cpu_has(.avx2) : return sum_avx2(values)
    return sum_plain(values)
}

fn main() {
    let values = Array[f32]{ 1.5 x 20 }
    println(sum(values)) // 30
}

The available function attributes are $target_ssse3, $target_sse41, $target_avx, $target_avx2, and $target_pclmul (x86-64). A $target_* function cannot be marked $inline and cannot take or return a vector wider than 128 bits.