doublestores an approximation,x87computes in 80 bits, andSSE2holds numbers in flatxmmregisters—and every single one of those facts changes your result.
In C99, 0.1 + 0.2 does not equal 0.3, and printf("%.17g", ...) prints two different numbers. That isn’t a compiler bug or “sloppy hardware precision”—it’s a direct consequence of the binary storage format. In this lesson, I break down the IEEE 754 standard, the eight-slot x87 stack, and the flat SSE2 registers.
Mental Model: Three Fields and Two Access Models
| What it looks like in C99 | What happens in hardware |
|---|---|
double is just a number |
The value is split into sign, exponent, and mantissa |
0.1 is stored exactly |
0.1 is an infinite repeating fraction in binary and gets rounded |
x87 is an ordinary register file |
Eight slots with a TOP pointer; fld decrements the top pointer |
SSE2 also works like a stack |
xmm registers are flat: addsd names two registers and writes the result directly |
NaN equals itself |
QNaN compares unequal to everything, including itself |
IEEE 754: Sign, Exponent, and Mantissa
A double occupies 64 bits divided into three fields: 1 sign bit, 11 biased-exponent bits, and 52 fractional mantissa bits.
| Field | double |
float |
|---|---|---|
| Sign | 1 bit | 1 bit |
| Exponent | 11 bits | 8 bits |
| Fractional mantissa | 52 bits | 23 bits |
The numeric value is reconstructed as:
- sign bit: 0 for positive, 1 for negative.
- fractional part of the mantissa; the leading
1before the binary point is implicit. - biased exponent from the exponent field.
- bias: 1023 for
double, 127 forfloat.
The leading 1 before the binary point isn’t stored because every normalized binary number starts with 1—giving one extra bit of precision for free. The two exceptions are the extreme exponent values: e = 0 (zero and subnormal numbers without the implicit leading one) and all-ones e (Inf and NaN, such as 0x7ff8000000000000).
The fractional field m encodes the sum , so becomes the repeating binary fraction , and equals . The diagram below shows the field boundaries and bit widths:
double 0.1 = 0x3fb999999999999a
fields: s = 1 bit | e = 11 bits (0x3fb) | m = 52 bits (0x999999999999a ≈ 0.6)
bits: 0 | 0111 1111 011 | 1001 1001 1001 ... 1010
float 0.1 = 0x3dcccccd
fields: s = 1 bit | e = 8 bits (0x7b) | m = 23 bits (0x4ccccd ≈ 0.6)
bits: 0 | 0111 1011 | 100 1100 1100 1100 1100 1101
The 9-bit s+e header splits the third hex digit 'c' of 0x3dcccccd across
the exponent (1 bit) and the mantissa (3 bits).The float_sse.c testbed prints the raw bits of both 0.1 representations:
double 0.1: 0x3fb999999999999a— sign0, exponent0x3fb(1019 - 1023 = -4), fractional mantissa0x999999999999a(); with the implicit leading1, the significand is .float 0.1: 0x3dcccccd— sign0, exponent0x7b(123 - 127 = -4), fractional mantissa0x4ccccd(, significand ); hex digits shift by one bit because of the 9-bit header.
Both store the same mathematical number , just with different mantissa widths. In binary, 0.1 is the infinite repeating fraction 0.0001100110011..., so the register holds the nearest representable value, not the exact decimal.
Adding two rounded values produces a third rounded value:
0.1 + 0.2 = 0.30000000000000004(0x3fd3333333333334) — the sum of two already-rounded approximations.0.3 = 0.29999999999999999(0x3fd3333333333333) — an independent approximation rounded on its own.equal: false— the bit patterns differ by one least-significant bit, so==returns false.
The x87 Stack: Eight Slots and a Ninth fld
x87 computes in an 80-bit extended format: 1 sign bit, 15 exponent bits, and 64 mantissa bits. There are eight physical registers, and TOP tracks the current top st0. fld decrements TOP and pushes a value; fstp reads the top and increments TOP.
On x86-64, GCC and Clang always emit flat SSE2 instructions on xmm registers for float and double, leaving the 80-bit x87 stack mainly for long double and legacy code.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; x87_overflow.asm — eight x87 slots and a ninth fld.
default rel
%define SYS_EXIT 60
%define EXIT_OK 42
section .rodata
values: dd 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0
section .text
global _start
; ------------------------------------------------------------------------------
; _start — loads eight values, then issues a ninth fld on a full stack.
; Input: none
; Output: does not return; exits with 42 when x87 exceptions are masked
; Clobbers: rax, rbx, rcx, rdi, r11, x87 stack, flags
; ------------------------------------------------------------------------------
_start:
lea rbx, [values]
mov ecx, 8
.loop:
fld dword [rbx]
add rbx, 4
dec ecx
jnz .loop
after_fld8:
fld dword [rbx]
after_fld9:
; syscall: exit(EXIT_OK)
mov edi, EXIT_OK
mov eax, SYS_EXIT
syscall
section .note.GNU-stack noalloc noexec nowrite progbitsobjdump shows the exact machine instructions:
0000000000401000 <_start>:
401000: 48 8d 1d f9 0f 00 00 lea rbx,[rip+0xff9] # 402000 <values>
401007: b9 08 00 00 00 mov ecx,0x8
000000000040100c <_start.loop>:
40100c: d9 03 fld DWORD PTR [rbx]
40100e: 48 83 c3 04 add rbx,0x4
401012: ff c9 dec ecx
401014: 75 f6 jne 40100c <_start.loop>
0000000000401016 <after_fld8>:
401016: d9 03 fld DWORD PTR [rbx]
0000000000401018 <after_fld9>:
401018: bf 2a 00 00 00 mov edi,0x2a
40101d: b8 3c 00 00 00 mov eax,0x3c
401022: 0f 05 syscalllea rbx, [values]loads the array address;default relmakes it RIP-relative.fld dword [rbx]loads a 32-bitfloatand widens it to 80 bits on the top of the stack.add rbx, 4advances the pointer to the next element.dec ecxandjnerepeat the load exactly eight times.after_fld8pauses right before the ninthfld; that ninthfldimmediately follows.mov edi, 0x2areturns exit status42provided the exception is masked.
In GDB at after_fld8, the stack is completely full:
(gdb) break after_fld8
Breakpoint 1 at 0x401016: file x87_overflow.asm, line 33.
(gdb) run
Starting program: .../lessons/16-float-x87-sse2/build/x87_overflow
Breakpoint 1, after_fld8 () at x87_overflow.asm:33
33 fld dword [rbx]
(gdb) info float
R7: Valid 0x3fff8000000000000000 +1
R6: Valid 0x40008000000000000000 +2
R5: Valid 0x4000c000000000000000 +3
R4: Valid 0x40018000000000000000 +4
R3: Valid 0x4001a000000000000000 +5
R2: Valid 0x4001c000000000000000 +6
R1: Valid 0x4001e000000000000000 +7
=>R0: Valid 0x40028000000000000000 +8
Status Word: 0x0000
TOP: 0
Control Word: 0x037f IM DM ZM OM UM PM
PC: Extended Precision (64-bits)
RC: Round to nearest
Tag Word: 0x0000
Instruction Pointer: 0x00:0x00000000
Operand Pointer: 0x00:0x00000000
Opcode: 0x0000A single nexti executes the ninth fld, changing the state:
(gdb) nexti
after_fld9 () at x87_overflow.asm:37
37 mov edi, EXIT_OK
(gdb) info float
=>R7: Special 0xffffc000000000000000 Real Indefinite (QNaN)
R6: Valid 0x40008000000000000000 +2
R5: Valid 0x4000c000000000000000 +3
R4: Valid 0x40018000000000000000 +4
R3: Valid 0x4001a000000000000000 +5
R2: Valid 0x4001c000000000000000 +6
R1: Valid 0x4001e000000000000000 +7
R0: Valid 0x40028000000000000000 +8
Status Word: 0x3a41 IE SF C1
TOP: 7
Control Word: 0x037f IM DM ZM OM UM PM
PC: Extended Precision (64-bits)
RC: Round to nearest
Tag Word: 0x8000
Instruction Pointer: 0x00:0x00000000
Operand Pointer: 0x00:0x00000000
Opcode: 0x0000TOP: 0meansst0is physical slotR0holding+8; the remaining slots run fromR7throughR1.- After the ninth
fld,TOPwraps to7, andR7turnsSpecialwithReal Indefinite (QNaN):9.0never appears in any slot.
x87 ring: every fld decrements TOP by 1 (mod 8)
Start (empty): TOP=0
fld #1..#8 (+1..+8): R7(+1) -> R6(+2) -> ... -> R0(+8), TOP=0 (stack full)
fld #9 (+9): TOP=7 lands on occupied R7 (Tag=Valid)
──► Stack Fault (IE, SF, C1) ──► R7 = QNaNStatus Word and Control Word list the flags and masks. Control Word is the control word; the abbreviations in both lines mean:
| Flag | Meaning | Meaning here |
|---|---|---|
IE |
Invalid Operation | invalid operation raised |
SF |
Stack Fault | x87 stack overflow or underflow raised |
C1 |
condition / stack overflow flag | 1 — stack overflowed |
IM–PM |
exception masks: Invalid, Denormal, Zero-divide, Overflow, Underflow, Precision | all six are 1, so no trap/signal is raised |
PC |
Precision Control | Extended Precision (64-bits) — 64-bit mantissa |
RC |
Rounding Control | Round to nearest — round to nearest, ties to even |
Status Word 0x3a41setsIE,SF, andC1;C1 = 1signals stack overflow.Control Word 0x037fmasks all six exceptions, so instead of raising a signal the CPU writesQNaNat the top and keeps running.PC: Extended Precision (64-bits)selects 64-bit mantissa precision;RC: Round to nearestselects round-to-nearest-even.
QNaN is the quiet “not a number” marker that x87 writes on a masked stack overflow.
SSE2: Flat xmm Registers and a Single addsd
SSE2 has no top-of-stack pointer. Each xmm register is a flat 128-bit register addressed directly by number. The scalar addsd instruction adds the low 64 bits of two registers and leaves the sum in the destination.
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */
/* float_sse.c — C99 testbed: binary fractions, comparisons, and quiet NaN. */
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static uint64_t double_bits(double value)
{
uint64_t bits = 0;
memcpy(&bits, &value, sizeof(bits));
return bits;
}
static uint32_t float_bits(float value)
{
uint32_t bits = 0;
memcpy(&bits, &value, sizeof(bits));
return bits;
}
double test_add(double a, double b)
{
return a + b;
}
int test_equal(double a, double b)
{
return a == b;
}
int main(void)
{
volatile double a = 0.1;
volatile double b = 0.2;
volatile double c = 0.3;
double sum = test_add(a, b);
uint64_t qnan_bits = UINT64_C(0x7ff8000000000000);
double qnan = 0.0;
memcpy(&qnan, &qnan_bits, sizeof(qnan));
printf("0.1 + 0.2 = %.17g\n", sum);
printf("0.3 = %.17g\n", c);
printf("equal: %s\n", test_equal(sum, c) ? "true" : "false");
printf("double 0.1: 0x%016" PRIx64 "\n", double_bits(0.1));
printf("float 0.1: 0x%08" PRIx32 "\n", float_bits(0.1f));
printf("qnan: 0x%016" PRIx64 ", qnan == qnan: %s\n", double_bits(qnan),
qnan == qnan ? "true" : "false");
return 0;
}Running the testbed prints the exact bit patterns and comparison outcomes:
0.1 + 0.2 = 0.30000000000000004
0.3 = 0.29999999999999999
equal: false
double 0.1: 0x3fb999999999999a
float 0.1: 0x3dcccccd
qnan: 0x7ff8000000000000, qnan == qnan: falseCompiling with -O2 -S -masm=intel reduces both functions to two short sequences:
test_add:
addsd xmm0, xmm1
ret
test_equal:
xor eax, eax
ucomisd xmm0, xmm1
mov edx, 0
setnp al
cmovne eax, edx
retaddsd xmm0, xmm1adds the lowdoublelanes ofxmm0andxmm1, returning the sum inxmm0.ucomisd xmm0, xmm1compares twodoubles and setsZF,PF, andCF.xor eax, eaxzeros all ofeaxbeforehand (beforeucomisd), becausesetnp alwrites only the low byte without clearing upper bits, and runningxorlater would clobber the flags.mov edx, 0sits afterucomisdsafely becausemovdoes not touchRFLAGS.setnp alrejects thePF = 1unordered case so comparing againstQNaNnever evaluates to equal.cmovne eax, edxmoves0fromedxintoeaxwhenZF = 0(ordinary inequality), leaving1ineaxonly when bothZF = 1andPF = 0—true equality withoutNaN.
| Case | ucomisd flags |
setnp al |
cmovne eax, edx |
Final eax |
|---|---|---|---|---|
a == b |
ZF=1, PF=0, CF=0 |
al = 1 |
not taken | 1 |
a != b |
ZF=0, PF=0, CF=0/1 |
al = 1 |
copies 0 from edx |
0 |
NaN |
ZF=1, PF=1, CF=1 |
al = 0 |
not taken | 0 |
In GDB, you can inspect a 128-bit xmm register as two double lanes:
Breakpoint 1, test_add (a=0.10000000000000001, b=0.20000000000000001)
at float_sse.c:30
30 return a + b;
(gdb) print $xmm0.v2_double
$1 = {0.10000000000000001, 0}
(gdb) print $xmm1.v2_double
$2 = {0.20000000000000001, 0}
(gdb) nexti 3
(gdb) print $xmm0.v2_double
$3 = {0.30000000000000004, 0}v2_doubleviews a 128-bitxmmregister as twodoubles; the second lane stays0because scalar instructions only touch the low 64 bits.- On entry
xmm0holdsaandxmm1holdsb; afteraddsd,xmm0holds0.30000000000000004. 0x7ff8000000000000inqnanhas sign0, all 11 exponent bits set to1, and the top mantissa bit set to1; that’s whyQNaNisn’t equal even to itself.
The suffix after the dot in the register name tells GDB how to slice the 128 bits of an xmm register:
| View | Layout | Prints |
|---|---|---|
.v2_double |
2 × 64-bit | two doubles |
.v4_float |
4 × 32-bit | four floats |
.v2_int64 |
2 × 64-bit | two int64_ts |
.v4_int32 |
4 × 32-bit | four int32_ts |
.v8_int16 |
8 × 16-bit | eight int16_ts |
.v16_int8 |
16 × 8-bit | sixteen int8_ts |
v2_double above is just one view; the integer and float views come in handy when inspecting packed SIMD registers.
AVX extends this same flat model to wider registers while x87 remains a separate legacy stack. More on that in lesson 21.
Common Pitfalls
-
"
0.1 + 0.2should equal0.3."
Fact: the testbed prints0.30000000000000004and0.29999999999999999, and==returnsfalse.
Cause:0.1,0.2, and0.3have no finite binary representation; each rounds independently.
Fix: compare with a tolerance (fabs(a - b) < eps), or represent money and exact quantities in integer units. -
“A ninth
fldsimply evicts the oldest value.”
Fact: after the ninthfld,TOP = 7,R7holdsReal Indefinite (QNaN), andR0still holds+8;9.0is nowhere on the stack.
Cause: pushing onto a fullx87stack raises a stack fault and, when masked, writesQNaNto the top instead of rotating the ring.
Fix: keepx87stack depth at most eight and spill intermediates to memory withfstp. -
"
floatanddoublestore the exact same value."
Fact:0.1encodes as0x3fb999999999999aindoubleand0x3dcccccdinfloat.
Cause:floathas only 23 mantissa bits vs. 52 indouble, producing a coarser rounding.
Fix: default todoublefor computation and reservefloatfor memory-bound arrays or wire formats. -
“Checking
jeafterucomisdis enough to test equality.”
Fact:qnan == qnanreturnsfalse, and the compiler emitssetnpalongsideucomisd.
Cause: on unordered (NaN) operands,ucomisdsetsZF = PF = CF = 1; checkingZFalone cannot distinguishNaNfrom equality.
Fix: checkPF(jp/setnp) before deciding equality, or pairucomisdwith bothseteandsetnp.
Floating-point ABI cheat sheet. The full System V ABI rules live in lesson 18, but the core rule is simple: integer/pointer arguments go in rdi, rsi, rdx, …, floating-point parameters (float/double) go in xmm0–xmm7, and a floating-point return value comes back in xmm0.
Lab
Goal. Implement asm_double_sum(const double *values, size_t count) in NASM to sum a double array using scalar SSE2 instructions.
Contract and requirements.
- Inputs: pointer to the array and element count; an empty array returns
+0.0. - Output:
doublesum inxmm0. - Called from a C99 test harness compiled with
-std=c99 -D_POSIX_C_SOURCE=200809L -Wall -Wextra -Werror -pedantic. - Use
SSE2only; neitherx87norAVXis needed. - Any
NaNin the input must propagate to the return value rather than being ignored.
Verification criteria.
make -C lessons/16-float-x87-sse2 build testpasses.{1.5, 2.5}returns4.0, an empty array returns+0.0, and{0.1, 0.2}produces bits0x3fd3333333333334.objdump -d -M intelshowsaddsdand nofld/fstp.- Running under
-fsanitize=address,undefinedreports zero errors.
Hints, expected output, and walkthrough
Initialize the accumulator to +0.0 with pxor xmm0, xmm0 so it clears the register cleanly without depending on prior contents. Then loop over the array, loading each double into the accumulator with addsd, advancing the pointer by 8 bytes, and decrementing the counter until zero.
For an empty array, the loop executes zero times and returns +0.0. For {0.1, 0.2}, adding left to right matches float_sse.c, producing the exact bits 0x3fd3333333333334 (0.30000000000000004).
addsd propagates QNaN naturally: if any input element is NaN, the result becomes NaN with no extra check required.
Testbed sources, Makefile, and automated tests for this lesson: lessons/16-float-x87-sse2.
Summary
IEEE 754encodes a floating-point number as sign, biased exponent, and fractional mantissa.doubleuses 64 bits,floatuses 32 bits, andx87uses an 80-bit extended format.flddecrementsTOPand pushes onto the eight-slotx87stack.- A ninth
fldwith masked exceptions leavesQNaNon top and setsIE,SF, andC1. SSE2uses flatxmmregisters:addsdanducomisdaddress registers by number without a stack pointer.QNaNis not equal to itself, sodoubleequality requires checkingPFin addition toZF.
xmm registers, yet our assembly object files have been built mostly in isolation. In lesson 17, I unpack global, extern, weak, PLT, and GOT: how the linker stitches modules together and resolves external shared libraries.