Skip to content
systemcoding.dev
Assembly

ARM SVE and SVE2: Vector-Length-Agnostic Assembly

Write one AArch64 SVE loop that runs unchanged on 128-bit and 512-bit hardware, using predicates, whilelt and incw instead of a fixed vector width.

7 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the Arm, RISC-V and AMD logos.

NEON code has the vector width baked into every instruction: a v0.4s register is 128 bits, and a loop that processes four floats per iteration stays that way on every chip. The Scalable Vector Extension (SVE) removes that constant. A Z register is somewhere between 128 and 2048 bits wide, in steps of 128, and the hardware designer picks the number. Your binary does not know which one it will run on, so the loop has to be written so that the answer never matters. This post shows how that works in AArch64 assembly, using SVE, which arrived as an optional extension in Armv8.2-A, and SVE2, which belongs to Armv9-A. The examples assume GNU as from binutils 2.42 and the +sve architecture extension, with encodings taken from the Arm Architecture Reference Manual for A-profile.

What changes compared with NEON

SVE adds two register files and one status register to the AArch64 programmer's model:

RegisterCountMeaning
z0 to z3132Scalable vector registers. The low 128 bits overlap v0 to v31
p0 to p1516Predicate registers, one bit per byte of a Z register
ffr1First-fault register, written by first-fault loads

The vector length (VL) is a property of the hardware and, on Linux, of the process. You do not read it from a constant; you ask for it. rdvl x0, #1 puts VL in bytes into x0. cntw x0 puts the number of 32-bit elements into x0, which is what a float loop wants. On a 128-bit implementation cntw returns 4, on a 512-bit one it returns 16, and the code that uses it cannot tell the difference.

Predicates carry the second idea. Almost every SVE instruction takes a governing predicate that says which lanes participate. A lane whose predicate bit is clear is not read, not written, and cannot fault. That is how the loop tail gets handled without a separate scalar cleanup loop.

The loop skeleton: whilelt, incw, b.first

Every vector-length-agnostic loop in assembly has the same four parts. A counter lives in a scalar register. whilelt builds a predicate that is true for lanes whose index is still below the limit. The body runs under that predicate. An inc instruction advances the counter by the number of elements in a vector.

whilelt p0.s, x3, x2 sets lane k of p0 to true when x3 + k < x2, comparing signed 64-bit values, for as many 32-bit lanes as the vector holds. It also sets the condition flags as if you had run ptest on the result: N is set when the first lane is active, Z when no lane is active, C when the last lane is not active. That is why the loop-back branch is b.first, which is an alias of b.mi. The loop continues while the first lane is still active, meaning there is at least one element left.

A complete saxpy loop

The function below computes y[i] += a * x[i] for single-precision floats. It follows the AAPCS64 calling convention: the float a arrives in s0, the pointers in x0 and x1, the count in x2.

saxpy_sve.Sasm
        .arch   armv8.2-a+sve
        .text
        .globl  saxpy_sve
        .type   saxpy_sve, %function
// void saxpy_sve(float a, const float *x, float *y, long n)
saxpy_sve:
        mov     x3, #0                  // element index
        dup     z2.s, z0.s[0]           // broadcast a into every lane
        whilelt p0.s, x3, x2            // p0 = lanes with index < n
1:
        ld1w    {z0.s}, p0/z, [x0, x3, lsl #2]   // x[i..], inactive lanes read as 0
        ld1w    {z1.s}, p0/z, [x1, x3, lsl #2]   // y[i..]
        fmla    z1.s, p0/m, z0.s, z2.s           // y += x * a, active lanes only
        st1w    {z1.s}, p0, [x1, x3, lsl #2]     // write back active lanes
        incw    x3                      // advance by lanes per vector
        whilelt p0.s, x3, x2            // next predicate, sets flags
        b.first 1b                      // loop while lane 0 is active
        ret
        .size   saxpy_sve, .-saxpy_sve

Read the loop line by line. The /z suffix on the loads means zeroing predication: an inactive lane is set to zero rather than left alone. The /m on fmla is merging predication: an inactive lane keeps the old value of the destination. The store has no suffix because stores do not produce a register result; inactive lanes do not write memory. Nothing here mentions a vector width. The lsl #2 scales the element index by four bytes, which is the size of the element and is independent of VL.

Registers z0, z1, z2 and p0 are argument or scratch registers in the procedure call standard, so the function can use them without saving anything. A routine that needs z8 to z15 has to preserve the low 64 bits of those, per the SVE section of the AAPCS64 document.

A C caller that exercises it:

main.cc
#include <stdio.h>

void saxpy_sve(float a, const float *x, float *y, long n);

int main(void)
{
    float x[5] = {1, 2, 3, 4, 5};
    float y[5] = {10, 10, 10, 10, 10};

    saxpy_sve(2.0f, x, y, 5);
    for (int i = 0; i < 5; i++)
        printf("%.0f ", y[i]);
    printf("\n");
    return 0;
}
Text
12 14 16 18 20 

The result is identical on a 128-bit core, where the loop runs twice (four lanes, then one), and on a 512-bit core, where it runs once with five active lanes out of sixteen. The program has no way to observe the difference, which is the point.

Building and checking for support

Assemble and link with a toolchain that accepts the extension. With GCC 14 on an AArch64 Linux host:

Shell
gcc -O2 -march=armv8.2-a+sve main.c saxpy_sve.S -o saxpy

The .arch armv8.2-a+sve directive at the top of the assembly file is what makes as accept the SVE mnemonics when the compiler driver passes a lower baseline. Without it you get errors such as "selected processor does not support ld1w {z0.s},p0/z,[x0,x3,lsl #2]".

Running it on a core without SVE ends in SIGILL. On Linux, test for it at run time with getauxval(AT_HWCAP) & HWCAP_SVE, and for SVE2 with getauxval(AT_HWCAP2) & HWCAP2_SVE2, both defined in <asm/hwcap.h>. The kernel documents the interface in Documentation/arch/arm64/sve.rst. That file also covers prctl(PR_SVE_SET_VL, ...), which lets a process request a smaller vector length than the hardware maximum; the kernel rounds to a length it supports. You almost never need it, but it is the tool for reproducing a bug that only appears at one VL.

What SVE2 adds

SVE was designed mainly with floating-point HPC loops in mind. SVE2 is the Armv9-A extension that brings the integer, fixed-point and bit-manipulation repertoire of NEON into the scalable model, so code such as codecs, cryptography and string processing can use it. Examples of what became available:

  • Non-widening and widening integer multiply-accumulate in the same predicated form, plus saturating variants such as sqrdmulh.

  • Bit permutation instructions (bdep, bext, bgrp) in the optional SVE2 bit-permute extension.

  • match and nmatch, which test each byte of a vector against a set of bytes, useful for tokenizers and delimiter scans.

  • histcnt and histseg, which count equal elements, a building block for histogram and run-length code.

  • Three-input logical operations such as eor3 and bcax.

All of them use the same predicate-and-VL idiom, so the skeleton above carries over. What you have to re-check per instruction is the element sizes it accepts, because several SVE2 forms exist only for certain widths.

First-fault loads for loops with unknown length

A strlen loop does not know its bound in advance, and a wide load that runs past the end of a string can touch an unmapped page. SVE has a dedicated answer. setffr clears the first-fault register to all true. A first-fault load such as ldff1b {z0.b}, p0/z, [x0] loads lanes in order and, if a lane would fault, stops there instead of trapping, clearing the corresponding ffr bits. rdffr p1.b then reads back which lanes actually loaded. The first lane is the exception: a fault on lane zero is still taken as a real fault, because no progress would otherwise be possible. A complete strlen also needs cmpeq to find the zero byte, brkb to build a mask of the bytes before it, and cntp to count them. That is a second post of its own, but the mechanism is what makes unbounded scans safe without a scalar prologue that aligns the pointer.

When not to write this in assembly

Do not hand-write SVE unless a profile shows the compiler's code is the limit. GCC and Clang vectorize simple loops for SVE with -march=armv8.2-a+sve or -mcpu= for a specific core, and ACLE intrinsics in <arm_sve.h> (svld1, svmla_x, svwhilelt_b32) give you control without giving up register allocation. Assembly earns its place in a runtime library function, in a loop the compiler cannot prove safe to vectorize, or when you need an instruction the intrinsics do not model cleanly.

Also avoid code that assumes VL is a power of two. The architecture only guarantees a multiple of 128 bits, so a vector of 384 bits is legal. Any code that shifts by log2(VL) is wrong on such hardware.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.