A single instruction can add eight numbers at once—but only if the CPU supports 256-bit registers and the operating system has enabled saving their state across context switches.
The scalar loop from lesson 20 hits a ceiling at one dependency per iteration. Vectorized code removes not just cycles inside an operation, but entire loop iterations: 32 bytes are loaded by one vmovdqu, compared by one vpcmpeqb, and collapsed into a bitmask by one vpmovmskb. On the Ryzen 7 7840H testbed, these instructions are available, and CPUID and XCR0 confirm that both the core and the OS are ready to execute them.
Mental Model: Width Instead of Cycles
| Intuition | What the testbed shows |
|---|---|
| AVX2 is a library or compiler intrinsics | The disassembly shows ordinary instructions: vpbroadcastb, vpcmpeqb, vpmovmskb |
Checking avx2 in /proc/cpuinfo is enough |
You also need the OSXSAVE bit, the AVX bit, and the right bits enabled in XCR0 |
| A 256-bit comparison returns an index | vpcmpeqb produces a byte mask, and tzcnt extracts the index from it |
vzeroupper is optional boilerplate |
Without it, transitioning to legacy SSE code incurs a penalty for dirty upper state |
Vector Width, VEX Encoding, and OS Support
The AVX2 instruction set is encoded with the VEX prefix rather than the legacy SSE prefix scheme.
In objdump, the boundary between the two VEX forms is immediately visible in the first byte:
0000000000000000 <asm_avx_sum8>:
0: c5 fe 6f 17 vmovdqu ymm2,YMMWORD PTR [rdi]
4: c4 e3 7d 39 d3 01 vextracti128 xmm3,ymm2,0x1
a: c5 e9 fe d3 vpaddd xmm2,xmm2,xmm3
e: c4 e2 69 02 d2 vphaddd xmm2,xmm2,xmm2
13: c4 e2 69 02 d2 vphaddd xmm2,xmm2,xmm2
18: c5 f9 7e d0 vmovd eax,xmm2
1c: c5 f8 77 vzeroupper
1f: c3 retc5starts a 2-byte VEX prefix: the compact form used when all operands fit in the low registers (ymm0–ymm7) and standard opcode maps;c4starts a 3-byte VEX prefix: needed for instructions likevextracti128andvphadddwhose opcode maps don’t fit in the 2-byte form;c5 fe 6floads 32 bytes, andc5 f8 77isvzeroupper, a standalone instruction with no operands;- the trailing
01byte invextracti128selects the upper 128-bit lane ofymm2(index 1).
The practical payoff in a disassembler: glancing at the first byte of an objdump line tells you immediately whether an instruction is AVX or legacy SSE without consulting an opcode manual. c5 marks a 2-byte VEX prefix, c4 a 3-byte VEX prefix, and the remaining bytes are the opcode and operands.
Before executing the first AVX2 instruction, a program must verify support from both the CPU and the OS. cpuid returns the processor’s capability bits: leaf 1 reports OSXSAVE and AVX, and leaf 7 reports AVX2. Meanwhile, XCR0 holds the bitmask of architectural state components the OS has enabled XSAVE to preserve; without bits 1 and 2 set, the kernel does not guarantee preserving xmm/ymm across context switches.
avx2: yes
xcr0: 0x2e7
fma: yes- In binary,
0x2e7is10 1110 0111: bits 0, 1, 2, 5, 6, 7, and 9 are set; - bits 1 and 2 enable AVX state, bits 5–7 enable AVX-512 state, and bit 9 enables
PKRU; - this core exposes more state bits than AVX2 requires: the extra bits don’t hurt, though they don’t guarantee AVX-512 runs at full speed either;
fma: yescomes from bit 12 of leaf 1 and is noted below as a sibling extension on the same die.
Summing Eight int32_t Values
The kernel receives a pointer to eight int32_t values—exactly one ymm register wide. Alignment is not required because it uses vmovdqu rather than vmovdqa.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; avx_kernels.asm — AVX2 eight-int32 sum and byte search kernels.
default rel
section .text
global asm_avx_sum8
global asm_avx_find_byte
; ------------------------------------------------------------------------------
; int32_t asm_avx_sum8(const int32_t *arr)
; Input: rdi = arr, exactly 8 int32_t elements
; Output: eax = sum of all eight elements
; Clobbers: rax, ymm2, ymm3, upper halves of ymm0–ymm15 (flags untouched)
; ------------------------------------------------------------------------------
asm_avx_sum8:
vmovdqu ymm2, [rdi]
vextracti128 xmm3, ymm2, 1
vpaddd xmm2, xmm2, xmm3
vphaddd xmm2, xmm2, xmm2
vphaddd xmm2, xmm2, xmm2
vmovd eax, xmm2
vzeroupper
ret
; ------------------------------------------------------------------------------
; int64_t asm_avx_find_byte(const uint8_t *buf, size_t len, uint8_t needle)
; Input: rdi = buf, rsi = len, edx = target byte
; Output: rax = index of first match, or -1
; Clobbers: rax, rcx, rdx, r8, ymm0, ymm1, upper halves of ymm0–ymm15, flags
; ------------------------------------------------------------------------------
asm_avx_find_byte:
xor eax, eax
vmovd xmm1, edx
vpbroadcastb ymm1, xmm1
mov rcx, rsi
and rcx, -32
jz .tail
.loop32:
vmovdqu ymm0, [rdi + rax]
vpcmpeqb ymm0, ymm0, ymm1
vpmovmskb r8d, ymm0
test r8d, r8d
jnz .hit
add rax, 32
cmp rax, rcx
jb .loop32
.tail:
cmp rax, rsi
jae .miss
.tail_loop:
cmp byte [rdi + rax], dl
je .done
inc rax
cmp rax, rsi
jb .tail_loop
.miss:
mov rax, -1
.done:
vzeroupper
ret
.hit:
tzcnt edx, r8d
add rax, rdx
jmp .done
section .note.GNU-stack noalloc noexec nowrite progbitsThe reduction chain consists of five steps:
vmovdqu ymm2, [rdi]loads all 32 bytes—eightint32_telements;vextracti128 xmm3, ymm2, 1extracts the upper 16 bytes into a separate register;vpaddd xmm2, xmm2, xmm3adds the two halves lane-by-lane, yielding four partial sums;- the first
vphadddadds adjacent pairs, and the second adds the remaining pair; vmovd eax, xmm2moves the finalint32_tinto the return register.
Collapsing a 256-bit register into a scalar takes a four-step ladder, and you can trace how many partial sums remain at each stage:
ymm2 : [ a0 a1 a2 a3 | a4 a5 a6 a7 ] 8 x int32_t
|
vextracti128 xmm3, ymm2, 1
|
xmm2 = [ a0 a1 a2 a3 ]
xmm3 = [ a4 a5 a6 a7 ]
|
vpaddd xmm2, xmm2, xmm3
|
xmm2 = [ a0+a4 a1+a5 a2+a6 a3+a7 ] 4 partial sums
|
vphaddd xmm2, xmm2, xmm2
|
xmm2 = [ a0+a4+a1+a5 a2+a6+a3+a7 ... ... ] 2 partial sums
|
vphaddd xmm2, xmm2, xmm2
|
xmm2 = [ sum(a0..a7) ... ... ... ] 1 total in the lowest lane
|
vmovd eax, xmm2vphaddd performs horizontal addition within each 128-bit lane, so the second vphaddd leaves the total in the lowest int32_t lane, where vmovd reads it out. The upper lanes after the second vphaddd just hold duplicate copies of the sum and don’t affect the result.
Stepping one instruction with ni (nexti, lesson 05) executes the load and pauses before the next instruction, letting GDB display the vector register as eight integers:
$ gdb -q --nx -batch -ex 'b asm_avx_sum8' -ex run -ex 'ni 1' \
-ex 'p $ymm2.v8_int32' ./build/avx_test
Breakpoint 1, asm_avx_sum8 () at avx_kernels.asm:18
18 vmovdqu ymm2, [rdi]
19 vextracti128 xmm3, ymm2, 1
$1 = {0, 3, 6, 9, 12, 15, 18, 21}$ymm2.v8_int32 is not program syntax—it’s a GDB view specifier meaning “display ymm2 as eight signed 32-bit integers.”
This uses the same suffix convention from lesson 16, scaled up to 256 bits: xmm splits into four int32_t lanes (.v4_int32), while ymm splits into eight (.v8_int32). The testbed fills the array with i * 3, so the sum is 84.
Byte Search: Comparison Yields a Mask, Not an Index
The second routine finds the first occurrence of a given byte. Here the key isn’t arithmetic, but converting a vector comparison result into a byte offset:
vpbroadcastb ymm1, xmm1replicates the target byte across all 32 byte lanes;vpcmpeqb ymm0, ymm0, ymm1sets each matching byte lane to0xFFand non-matching lanes to0x00;vpmovmskb r8d, ymm0packs the most significant bit of each of the 32 bytes into a 32-bit mask;tzcnt edx, r8dcounts trailing zeros to recover the index of the first set bit—i.e., the match offset.
1. vpbroadcastb: needle (dl) ──► ymm1 = [ b | b | ... | b ] (32 copies)
2. vmovdqu: [rdi + rax] ──► ymm0 = [ b0 | b1 | ... | b31 ]
3. vpcmpeqb: ymm0 = [ 00 | FF | ... | 00 ] (byte mask)
4. vpmovmskb: r8d = 32-bit MSB mask
5. tzcnt: edx = index of first set bit (0..31)Buffer lengths are rarely multiples of 32. and rcx, -32 rounds the length down to the largest whole-vector count, and any remaining bytes are scanned by the scalar .tail_loop. The testbed exercises a 1,000-byte buffer: the vector loop covers the first 992 bytes, and a match at index 997 must be caught in the tail.
sum8: 84 (ref 84)
find(0x5A): first 33
find tail: 997
find(0xFF): -1
find(len=0): -1
avx: okWhen the byte isn’t found, the function returns -1 via mov rax, -1 rather than mov eax, -1: writing to the 32-bit register would zero-extend to 4294967295, breaking the signed int64_t check.
Alongside AVX2, this CPU also enables FMA, whose CPUID bit appeared as fma: yes. The byte-search kernel doesn’t need it.
vzeroupper on Exit
The vzeroupper instruction sits right before every ret in both kernels, including the .miss and .hit paths. In the machine-code listing, it encodes as c5 f8 77.
The rule is simple: any function that touches ymm registers must execute vzeroupper before returning to code that might not be AVX-aware. Compilers emit it automatically; hand-written assembly has to include it explicitly.
ymm0 (256 bits): [ upper 128 bits — cleared by vzeroupper | lower 128 bits = xmm0 ]Terminal Verification
$ make test
21-simd-avx2: AVX2 sum/find kernels OK
$ ./build/avx_test
avx2: yes
xcr0: 0x2e7
fma: yes
sum8: 84 (ref 84)
find(0x5A): first 33
find tail: 997
find(0xFF): -1
find(len=0): -1
avx: okThe buffers are allocated with posix_memalign aligned to 32 bytes: C99 predates aligned_alloc, and malloc isn’t required to return 32-byte-aligned addresses. Even though these AVX2 kernels use unaligned vmovdqu, 32-byte alignment keeps loads from straddling cache-line boundaries and makes the buffers safe for vmovdqa. The CPUID and XCR0 check runs before the first AVX2 call, so on hardware without support the harness exits with status 77 instead of crashing with SIGILL.
Common Failure Modes
-
Assuming the
avx2flag in/proc/cpuinfois enough.
Symptom: The testbed printsavx2: yesonly after verifying bothOSXSAVEandxcr0: 0x2e7.
Cause: The CPU may support AVX2 in silicon, yet the OS might not save 256-bit register state across context switches.
Fix: Check bits 27 and 28 ofCPUIDleaf 1, then readxgetbvand verify(XCR0 & 0x6) == 0x6. -
Trying to allocate a 32-byte-aligned buffer with
aligned_alloc.
Symptom: Compilation fails under-std=c99becausealigned_allocdoes not exist in C99.
Cause:aligned_allocwas introduced in C11 and also requires the size to be a multiple of the alignment.
Fix: Useposix_memalign((void **)&ptr, 32, size)and check its return code. -
Expecting
vpmovmskbto return the match index directly.
Symptom: Aftervpcmpeqbandvpmovmskb,r8dholds a 32-bit bitmask; the index33only appears aftertzcnt.
Cause: A vector byte comparison produces one bit per byte, not an integer offset.
Fix: Runtzcnt/bsfon the mask and add it to the current vector base offset. -
Stopping the search after the last full 32-byte vector.
Symptom: On a1000-byte buffer, a match at index997is only found by the scalar tail.
Cause:and rcx, -32leaves eight trailing bytes untouched byvmovdqu.
Fix: Always follow the vector loop with a scalarcmp byteloop over the remaininglen % 32bytes. -
Thinking
vzeroupperis only needed before calling external functions.
Symptom: Both kernels executevzeroupperbeforeret(asm_avx_sum8right before returning, andasm_avx_find_byteat the shared.doneexit).
Cause: Returning hands control back to C99 code that may use legacy SSE instructions and expects clean upper halves.
Fix: Emitvzeroupperalong every exit path of any function that modifiesymmregisters.
Lab
Goal. Implement asm_avx_count_byte(const uint8_t *buf, size_t len, uint8_t needle) to count occurrences of a byte across the entire buffer, including the tail.
Contract.
- Inputs: buffer pointer, buffer length, and target byte.
- Output:
uint64_tinrax. - Do not modify memory; preserve all
callee-savedregisters. - The C99 test harness allocates buffers via 32-byte
posix_memalignand checks your count against a reference loop at lengths0, 1, 31, 32, 33, 1000, 4096.
Acceptance criteria.
make testpasses for all tested lengths.objdump -d -M intelshowsvpcmpeqbandvpmovmskb.- At length
1000, the count matches the reference, with none of the final eight bytes dropped. - The
make leakstarget reports zero violations.
Hints, expected output, and walkthrough
Inside the vector loop, the bitmask from vpmovmskb doesn’t need tzcnt—it needs a population count of set bits, so popcnt from lesson 20 fits right in. Handle the tail with the same scalar loop as asm_avx_find_byte, incrementing your counter on each matching byte instead of returning on the first hit.
Expected output when the contract passes across all lengths:
count: all lengths okIf your count at length 1000 is lower than the reference, the tail bytes after the last full vector were skipped. If it’s higher, a mask or tail boundary byte is being double-counted.
Testbed sources, Makefile, and automated tests for this lesson: lessons/21-simd-avx2.
Summary
- AVX2 processes 32 bytes per instruction, packing eight
int32_tvalues into eachymmregister. - Before running AVX2 code, check
CPUIDfeature bits,OSXSAVE, and theXCR0state mask. - The VEX prefix enables non-destructive three-operand syntax and zeroes the upper bits of the result.
vpcmpeqbyields a byte mask;vpmovmskb+tzcntturn that mask into an index.- Round buffer lengths down to whole vectors and handle trailing bytes with a scalar loop.
- Emit
vzeroupperon exit to prevent SSE transition penalties in calling code.
mmap, MAP_FAILED, the MMU and TLB, and an arena allocator that carves out a thousand blocks from a single syscall.