Okay, let's break down how to use SIMD (Single Instruction, Multiple Data) instructions in x86 assembly using NASM syntax.
Important Clarification: i386 vs. SIMD
The original Intel 80386 (i386) processor did not have SIMD instructions. SIMD was introduced later with technologies like:
- MMX (MultiMedia eXtensions): Introduced with Pentium MMX. Uses 64-bit registers (
mm0-mm7) that alias the x87 FPU registers. Primarily for integers.
- SSE (Streaming SIMD Extensions): Introduced with Pentium III. Uses dedicated 128-bit registers (
xmm0-xmm7 in 32-bit mode, xmm0-xmm15 in 64-bit mode). Handles packed single-precision floating-point numbers and integers.
- SSE2: Introduced with Pentium 4 / AMD Athlon 64. Adds support for packed double-precision floating-point and more integer operations in XMM registers. SSE2 is widely available on almost all modern x86 CPUs (even 32-bit ones made in the last ~15-20 years).
- SSE3, SSSE3, SSE4.1, SSE4.2: Added more specialized instructions.
- AVX, AVX2 (Advanced Vector Extensions): Uses 256-bit registers (
ymm0-ymm15) extending XMM registers. Requires VEX encoding.
- AVX-512: Uses 512-bit registers (
zmm0-zmm31) extending YMM registers. Requires EVEX encoding.
When people ask about SIMD in "i386 assembly", they usually mean writing 32-bit x86 assembly (which can run on processors much newer than the original i386) that utilizes these later SIMD extensions. We'll focus primarily on SSE/SSE2 using XMM registers as they are the most common and practical starting point, avoiding the complexities of MMX/FPU state management.
Core Concept of SIMD
SIMD allows you to perform the same operation on multiple data elements simultaneously using a single instruction.
- Example: Instead of adding two arrays element by element using scalar instructions (one
add per element), you can load multiple elements (e.g., 4 floats) from each array into SIMD registers and perform a single SIMD add instruction that adds all 4 pairs at once.
Key Components for Using SSE/SSE2 in NASM (32-bit Mode)
-
Registers:
xmm0 through xmm7: Eight 128-bit registers. Each can hold:
- 4 single-precision (32-bit) floats (
float)
- 2 double-precision (64-bit) floats (
double) - SSE2
- 16 signed/unsigned bytes (8-bit) (
int8_t/uint8_t)
- 8 signed/unsigned words (16-bit) (
int16_t/uint16_t)
- 4 signed/unsigned doublewords (32-bit) (
int32_t/uint32_t)
- 2 signed/unsigned quadwords (64-bit) (
int64_t/uint64_t) - SSE2
-
Data Types (Instruction Suffixes):
PS: Packed Single-precision (float) - Operates on 4 floats in parallel.
PD: Packed Double-precision (double) - Operates on 2 doubles in parallel (SSE2).
SS: Scalar Single-precision (float) - Operates only on the lowest float.
SD: Scalar Double-precision (double) - Operates only on the lowest double (SSE2).
- Integer instructions often use
P (Packed) prefix and suffixes like B (Byte), W (Word), D (Doubleword), Q (Quadword) (e.g., PADDB, PADDW, PADDD, PADDQ).
-
Common SSE/SSE2 Instructions (NASM Syntax):
-
Data Movement:
movaps xmm0, [my_aligned_floats] : Move Aligned Packed Single-precision (requires 16-byte aligned memory).
movups xmm1, [my_unaligned_floats] : Move Unaligned Packed Single-precision (slower than movaps if data is aligned, but safer if unsure).
movapd xmm0, [my_aligned_doubles] : Move Aligned Packed Double-precision (SSE2, 16-byte aligned).
movupd xmm1, [my_unaligned_doubles] : Move Unaligned Packed Double-precision (SSE2).
movdqa xmm0, [my_aligned_integers] : Move Aligned Double Quadword (Integer data, SSE2, 16-byte aligned).
movdqu xmm1, [my_unaligned_integers] : Move Unaligned Double Quadword (Integer data, SSE2).
movaps [result_floats], xmm0 : Store register to memory (aligned).
movups [result_floats], xmm1 : Store register to memory (unaligned).
movaps xmm0, xmm1 : Move data between registers.
movd xmm0, eax : Move 32-bit integer from GPR to the low dword of XMM (zeroing upper bits).
movd eax, xmm0 : Move low 32-bit integer from XMM to GPR.
movq xmm0, mm0 : Move 64 bits between MMX and XMM (requires SSE2 if moving to XMM).
pxor xmm0, xmm0 : Common idiom to zero an XMM register.
-
Arithmetic (Packed):
addps xmm0, xmm1 : Add 4 floats in xmm1 to xmm0. (xmm0 = xmm0 + xmm1)
subps xmm0, xmm1 : Subtract 4 floats.
mulps xmm0, xmm1 : Multiply 4 floats.
divps xmm0, xmm1 : Divide 4 floats.
sqrtps xmm0, xmm1 : Square root of 4 floats in xmm1, result in xmm0.
addpd xmm0, xmm1 : Add 2 doubles (SSE2).
paddb xmm0, xmm1 : Add 16 bytes (with saturation or wrap-around depending on specific instruction variants).
paddw xmm0, xmm1 : Add 8 words.
paddd xmm0, xmm1 : Add 4 doublewords.
paddq xmm0, xmm1 : Add 2 quadwords (SSE2).
-
CPU Feature Detection:
- Crucial Step! Before using any SIMD instructions (MMX, SSE, SSE2, AVX etc.), you must check if the CPU supports them. Otherwise, your program will crash with an "Invalid Opcode" exception (
#UD).
- Use the
cpuid instruction. Check specific bits in edx and ecx after calling cpuid with eax=1.
eax=1 -> edx bit 23: MMX support
eax=1 -> edx bit 25: SSE support
eax=1 -> edx bit 26: SSE2 support
eax=1 -> ecx bit 0: SSE3 support
eax=1 -> ecx bit 9: SSSE3 support
eax=1 -> ecx bit 19: SSE4.1 support
eax=1 -> ecx bit 20: SSE4.2 support
eax=1 -> ecx bit 28: AVX support (also need OS support check)
- You typically do this once at program startup and branch to different code paths (SIMD vs. scalar) or exit if required features are missing.
-
Alignment:
- Many SIMD instructions that access memory have an "aligned" version (e.g.,
movaps) and an "unaligned" version (e.g., movups).
- Aligned versions require the memory address to be a multiple of the data size (usually 16 bytes for XMM). They are generally faster.
- Unaligned versions work with any memory address but might be slower, especially on older CPUs. On some very old CPUs, using an aligned instruction on unaligned data could even fault.
- Best Practice: Align your data structures to 16-byte boundaries whenever possible if you plan to use SIMD. NASM provides directives like
ALIGN 16.
Example: Adding Two Arrays of Floats (SSE)
Let's add arrayA and arrayB, storing the result in arrayC. Assume arrays have N elements, where N is a multiple of 4, and are 16-byte aligned.
section .data
; Assume these arrays are defined and populated elsewhere
; and are 16-byte aligned
; Example: arrayA dd 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
; arrayB dd 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, ...
; arrayC resd N ; Reserve space for N floats
; Let's assume N = 8 for this example
arrayA dd 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0
ALIGN 16
arrayB dd 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0
ALIGN 16
arrayC resd 8 ; Reserve 8 floats (32 bytes)
ALIGN 16
section .text
global _start ; Or your actual entry point
_start:
; --- CPU Feature Check (Simplified - MUST DO PROPERLY!) ---
; A real program would call cpuid here and check SSE support.
; We'll skip it for brevity, assuming SSE is available.
; --- Setup ---
mov esi, arrayA ; Pointer to source array A
mov edi, arrayB ; Pointer to source array B
mov edx, arrayC ; Pointer to destination array C
mov ecx, 8 ; Number of floats to process
shr ecx, 2 ; Number of 4-float chunks (iterations) = 8 / 4 = 2
; Check if count is zero
test ecx, ecx
jz .done ; If no chunks to process, skip
.loop:
; Load 4 floats (16 bytes) from arrayA into xmm0
movaps xmm0, [esi]
; Load 4 floats (16 bytes) from arrayB into xmm1
movaps xmm1, [edi]
; Add the packed floats: xmm0 = xmm0 + xmm1
addps xmm0, xmm1
; Store the 4 resulting floats from xmm0 into arrayC
movaps [edx], xmm0
; Advance pointers by 16 bytes (4 floats * 4 bytes/float)
add esi, 16
add edi, 16
add edx, 16
; Decrement loop counter and loop if not zero
dec ecx
jnz .loop
.done:
; --- Handle remaining elements if N wasn't a multiple of 4 ---
; (This example assumes N is a multiple of 4, so no remainder handling)
; --- Exit program (Linux example) ---
mov eax, 1 ; syscall number (sys_exit)
xor ebx, ebx ; exit code 0
int 0x80 ; invoke kernel
Explanation:
.data Section: Declares aligned arrays. ALIGN 16 ensures the following data starts on a 16-byte boundary.
- Pointers:
esi, edi, edx are loaded with the addresses of the arrays.
- Loop Counter:
ecx holds the total float count, then shr ecx, 2 divides it by 4 to get the number of loop iterations (since we process 4 floats per iteration).
.loop:
movaps xmm0, [esi]: Loads 16 bytes (4 floats) from the address in esi into xmm0. aps = Aligned Packed Single.
movaps xmm1, [edi]: Loads 4 floats from edi into xmm1.
addps xmm0, xmm1: Performs four additions simultaneously: xmm0[0]+=xmm1[0], xmm0[1]+=xmm1[1], xmm0[2]+=xmm1[2], xmm0[3]+=xmm1[3].
movaps [edx], xmm0: Stores the 16 bytes (4 results) from xmm0 to the address in edx.
add esi/edi/edx, 16: Moves pointers to the next chunk of 4 floats.
dec ecx / jnz .loop: Decrements the chunk counter and loops if more chunks remain.
- Remainder Handling: A real-world loop would need extra scalar code after the main SIMD loop to handle cases where the total number of elements is not perfectly divisible by the SIMD vector width (4 in this case).
- Exit: Standard Linux exit syscall.
Key Takeaways:
- SIMD requires specific CPU support (use
cpuid check).
- Use the dedicated XMM registers for SSE/SSE2 (preferred over MMX).
- Choose instructions based on data type (float
ps, double pd, integers p...b/w/d/q).
- Pay attention to memory alignment (
movaps vs movups). Align data when possible.
- Structure loops to process data in chunks matching the SIMD register width.
- Remember to handle remainders if the data size isn't a multiple of the chunk size.
- Consider compiler intrinsics in C/C++ as a higher-level, often easier alternative to raw assembly for accessing SIMD.