TExcelTAD
Home › x86-64 Assembly › Reading Compiler Output

Reading Compiler Output

One of the most practical uses of assembly knowledge is reading what a compiler produced. It answers questions like "did my loop get vectorized?", "why is this function slow?" or "what does this undefined behaviour actually do?". The tool of choice is Compiler Explorer (godbolt.org) — the same service that runs the playgrounds on this site — or locally:

bash
gcc -O2 -S -masm=intel -fno-asynchronous-unwind-tables file.c -o file.s
objdump -d -M intel --no-show-raw-insn ./program

-masm=intel gives you the familiar syntax, and the -fno-asynchronous-unwind-tables flag removes the .cfi_ directives that clutter the listing.

A simple function

c
long add_scaled(long a, long b) {
    return a + b * 4;
}
nasm
; gcc -O2
add_scaled:
        lea     rax, [rdi+rsi*4]
        ret

Everything you learned is here: a arrives in rdi, b in rsi, the result goes in rax, and the arithmetic is a single lea. No stack frame, no saved registers.

Optimization levels change everything

At -O0 (the default!), GCC stores every variable on the stack so that a debugger can inspect it; the code is long and slow. Compare:

nasm
; gcc -O0
add_scaled:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-8], rdi
        mov     QWORD PTR [rbp-16], rsi
        mov     rax, QWORD PTR [rbp-16]
        lea     rdx, [0+rax*4]
        mov     rax, QWORD PTR [rbp-8]
        add     rax, rdx
        pop     rbp
        ret

Always look at optimized output (-O2) when you care about performance. QWORD PTR is GNU's spelling of NASM's qword.

Loops

c
long sum(const long *v, long n) {
    long total = 0;
    for (long i = 0; i < n; i++)
        total += v[i];
    return total;
}
nasm
; gcc -O1 (a straightforward loop)
sum:
        test    rsi, rsi
        jle     .L4                     ; n <= 0: return 0
        mov     rax, rdi                ; p = v
        lea     rcx, [rdi+rsi*8]        ; end = v + n
        mov     edx, 0                  ; total = 0
.L3:
        add     rdx, QWORD PTR [rax]
        add     rax, 8
        cmp     rax, rcx
        jne     .L3
.L1:
        mov     rax, rdx
        ret
.L4:
        mov     edx, 0
        jmp     .L1

Recognise the patterns from the Loops and Arrays lessons (at -O1 GCC writes mov edx, 0 rather than xor edx, edx; at -O2 it uses the shorter idiom): the count is checked once before the loop, the test is at the bottom, and the index became a pointer running to an end address. At -O3 GCC would also vectorize this loop with paddq on XMM registers.

Division by a constant

Division is slow, so compilers replace x / 10 with a multiplication by a "magic" reciprocal and a shift:

c
unsigned long div10(unsigned long x) { return x / 10; }
nasm
; gcc -O2
div10:
        movabs  rax, -3689348814741910323   ; 0xCCCCCCCCCCCCCCCD
        mul     rdi                         ; rdx:rax = magic * x
        mov     rax, rdx
        shr     rax, 3                      ; high half >> 3
        ret

The magic number is ⌈2^67 / 10⌉, so (x × magic) >> 67 equals x / 10 for every 64-bit x. Let's check it on a few values, including the largest one, against a real div:

nasm · try it yourself
section .data
tests:  dq 0, 7, 10, 99, 12345, 18446744073709551615
COUNT   equ ($ - tests) / 8

section .text
global _start
_start:
    xor ebx, ebx
.next:
    mov rax, [tests + rbx*8]
    mov rcx, 0xCCCCCCCCCCCCCCCD
    mul rcx                     ; rdx = high half of x * magic
    shr rdx, 3
    mov r12, rdx                ; the "compiler" result

    mov rax, [tests + rbx*8]
    xor edx, edx
    mov ecx, 10
    div rcx                     ; the real division

    cmp rax, r12
    jne .mismatch
    mov rdi, r12
    call print_uint
    inc ebx
    cmp ebx, COUNT
    jb .next
    mov rsi, all_ok
    mov edx, 13
    jmp .print
.mismatch:
    mov rsi, bad
    mov edx, 9
.print:
    mov eax, 1
    mov edi, 1
    syscall

    mov eax, 60
    xor edi, edi
    syscall

section .data
all_ok: db "all correct!", 10
bad:    db "mismatch", 10

section .text
; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
0
0
1
9
1234
1844674407370955161
all correct!

The section .text line before print_uint matters: without it the helper would land in the .data section, which isn't executable.

Recognising common idioms

You see It means
xor eax, eax = 0
test edi, edi / je if (x == 0)
lea eax, [rdi+rdi*2] x * 3
sar eax, 31 / shr eax, 31 the sign of x (−1/0 or 1/0)
cmovl, cmovg a ternary or min/max
movzx eax, BYTE PTR [rdi] loading a char/uint8_t
sete al / movzx eax, al a comparison returned as bool/int
imul rax, rax, 1000 multiplication by a constant
mov rax, QWORD PTR fs:40 … xor … jne __stack_chk_fail stack protector (canary check)
endbr64 at the start of a function a CET landing pad for control-flow protection
nop DWORD PTR [rax+0x0] padding to align a loop

Signed division by two

x / 2 for a signed int is not just sar, because sar rounds toward minus infinity while C rounds toward zero (see Shifts & Rotates). GCC adds the sign bit first:

c
int half(int x) { return x / 2; }
nasm
; gcc -O2
half:
        mov     eax, edi
        shr     eax, 31         ; 1 if x is negative, else 0
        add     eax, edi        ; x + (x < 0)
        sar     eax             ; >> 1
        ret

Here is that sequence in NASM, checked on negative and positive odd numbers:

nasm · try it yourself
section .text
global _start
_start:
    mov edi, -7
    call half
    movsxd rdi, eax
    call print_int              ; -3, like C

    mov edi, 7
    call half
    movsxd rdi, eax
    call print_int              ; 3

    mov eax, 60
    xor edi, edi
    syscall

half:
    mov eax, edi
    shr eax, 31
    add eax, edi
    sar eax, 1
    ret

; ---- print_int: print rdi as a signed decimal number and a newline ----
print_int:
    test rdi, rdi
    jns print_uint          ; not negative: print it as it is
    neg rdi                 ; make it positive
    push rdi                ; keep it (write and syscall clobber registers)
    push '-'                ; the minus sign, as a byte on the stack
    mov eax, 1              ; write(1, rsp, 1)
    mov edi, 1
    mov rsi, rsp
    mov edx, 1
    syscall
    pop rdi                 ; drop the '-'
    pop rdi                 ; the positive value again
    jmp print_uint          ; print_uint's ret returns to our caller

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
-3
3

Go further: How Compilers Translate if, Loops and switch reads the same shapes back out of a binary, as a reverse engineer does.

Test yourself

Why does gcc -O0 output store arguments on the stack?

  1. The ABI requires it
  2. So that a debugger can always find variables in memory; -O0 does no optimization
  3. To align the stack
  4. Because registers are slow

Why do compilers turn x / 10 into a multiplication?

  1. Division by constants is impossible
  2. Integer division is many times slower than multiplication
  3. To save registers
  4. To handle negative numbers

What does test edi, edi followed by je .L2 usually correspond to in C?

  1. if (x == 0) goto L2
  2. if (x != 0)
  3. x = 0
  4. a function call