Why use std.ArrayListAligned?

I’m struggling to understand when specifying a non-natural alignment with std.ArrayListAligned would be useful.

I’m not looking for a general explanation of memory alignment, because I’m pretty sure I understand the basic concept and why the compiler has to care about it. But I’d love a practical example where the programmer having control over alignment via std.ArrayListAligned is necessary.

I’m also confused about why a programmer might need to specify alignment when reading from a file, such as via readFileAllocOptions(). I believe somewhere down the call stack the alignment value you pass is used to initialize a std.ArrayListAligned… but that just gets back to my first question.

Hoping someone with more low-level programming experience could enlighten me. Thank you!

3 Likes

Example for readFileAllocOptions: I have some files that are just a list of f32’s. To be able to cast []u8 to []f32 the byte buffer needs to be aligned to f32’s alignment.

Bit more complicated example for std.ArrayListAligned: I have items of the form of a header struct { key_len: u32, value_len: u32 } followed by key_len u8s and value_len u8s. I always have the headers aligned to a Header alignment, so I can cast &items[header_idx] to type *Header. This needs the ArrayList buffer to be aligned to Headers alignment, too.

(ASCII-graphic for some visualization, the bytes: HHHHkkkvvvv?HHHHkkvvv???HHHH… with H headers, k keys, v values, and ? as skipped bytes for alignment for H.)

Thinking of it more, I guess my approach is: whenever you have mixed types in an array (like my Header and u8s), I find it easier to operate on []u8 (via ArrayListAligned(u8, max_alignment)) and do the pointer casting myself.

5 Likes

The natural alignment is the address boundary that matches the element data type T’s size in ArrayListAligned(T, alignment). Sometimes you want to control the alignment of the array itself rather than relying on the natural alignment of element T. E.g. ArrayListAligned(u16, .@"64") aligns the array itself to 64-byte while the natural alignment of u16 is 2-byte. This runs faster on machines with 64-byte cache line. A short array of less than 64 bytes won’t be placed across two cache lines and causing additional memory fetch.

2 Likes

You need it for SIMD on some architectures.

I mostly program for the ESP32-S3, which is a 32-bit microcontroller based on the XTensa architecture. It’s intended for IoT, so it has interfaces for audio, screens and cameras.

Audio and video can be pretty demanding, so to increase performance (without increasing the clock frequency) they extended the base instruction set with:

  • 128-bit vector instructions
  • 128-bit registers
  • 128-bit Load/Store unit and memory bus

This means you can use EE.VADDS.S8.LD.INCP to simultaneously add 16x 8-bit values and load a new set of 16 values from memory, all in a single clock cycle.

There’s a catch, though: the Load/Store unit only works with 128-bit aligned memory addresses So you need to make sure that your source(s) and destination all have the same alignment or it won’t work.

3 Likes

I found this example helpful, thank you.

I tested out loading u16s from disk with readFileAllocOptions() just to see what it would look like. Indeed, you have to specify an alignment of 2 in the call to readFileAllocOptions() (even though it returns a slice of u8s) otherwise the subsequent call to std.mem.bytesAsSlice() won’t compile.

const std = @import("std");
const Io = std.Io;

// Read file containing little-endian u16s.
// nums.dat has the contents:
// 0x01 0x00 0x02 0x00 0x03 0x00 0x04 0x00
pub fn main(init: std.process.Init) !void {
    const cwd = Io.Dir.cwd();

    const data: []align(2) u8 = try cwd.readFileAllocOptions(
        init.io,
        "nums.dat",
        init.arena.allocator(),
        .limited(9),
        .of(u16),
        null,
    );
    const nums: []u16 = std.mem.bytesAsSlice(u16, data);
    std.debug.print("{any}\n", .{nums});
}

On my machine this writes out:

$ zig run main.zig
{ 1, 2, 3, 4 }

This is the compiler error you get if you specify .of(u8) instead of .of(u16) in the call to readFileAllocOptions():

$ zig run main.zig
main.zig:18:45: error: expected type '[]u16', found '[]align(1) u16'
    const nums: []u16 = std.mem.bytesAsSlice(u16, data);
                        ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~
main.zig:18:45: note: pointer alignment '1' cannot cast into pointer alignment '2'

I was confused about why Zig gives you this option to specify the alignment of data loaded from a file when I’d never seen that in another language before. But it seems like Zig does this so you can do the kind of byte-reinterpretation/casting done here with bytesAsSlice() more intentionally and safely. (At least, that’s one reason.)

Some related discussion on the documentation for fftw:

No need for fftw_malloc in zig :D.