-O0 vs -O2: How Optimisation Changes the Picture
The same source compiled twice can produce two binaries that hardly look related. At -O0 the compiler translates each statement on its own and keeps every variable in memory: verbose, slow, and easy to map back to the source. At -O2 it keeps values in registers, inlines small functions, folds constants, replaces loops with formulas, removes code whose result is never used, and reorders everything. Release builds, and therefore almost every binary an analyst meets, are optimised. Knowing what the optimiser does keeps you from looking for code that no longer exists, and occasionally reveals a security bug the optimiser created. Optimization Basics in the assembly course shows the same transformations from the writer's side.
What each level typically does (GCC and Clang)
| Level | Typical effects visible in a disassembly |
|---|---|
-O0 |
every variable on the stack, loads and stores around each statement, frame pointer, no inlining: one source line = a few instructions |
-O1 |
values in registers, dead code removed, simple branches become setcc/cmov, frame pointer omitted |
-O2 |
plus inlining of small functions, common-subexpression elimination, loop transformations, tail calls (jmp instead of call + ret), and in GCC 12+ cheap vectorisation |
-O3 |
plus aggressive inlining and vectorisation (SSE/AVX loops with a scalar tail), loop unrolling |
-Os, -Oz |
optimise for size: fewer unrolled loops, shorter instruction choices |
One function, four levels
The session compiles the same small function at four levels and counts its instructions. sum_squares adds the squares of an array.
cat > opt.c <<'SRC'
int sum_squares(const int *a, int n) {
int s = 0;
for (int i = 0; i < n; i++)
s += a[i] * a[i];
return s;
}
SRC
for lvl in O0 O1 O2 O3; do
gcc -$lvl -c opt.c -o opt-$lvl.o
n=$(objdump -d --no-show-raw-insn opt-$lvl.o | grep -cE '^\s+[0-9a-f]+:')
vec=$(objdump -d opt-$lvl.o | grep -cE 'xmm|ymm')
printf -- '-%s %3d instructions %2d using SSE registers\n' "$lvl" "$n" "$vec"
done
echo "== -O0, the first instructions"
objdump -d -M intel --no-show-raw-insn opt-O0.o | grep -E '^\s+[0-9a-f]+:' | sed 's/^ *//' | head -8-O0 29 instructions 0 using SSE registers
-O1 17 instructions 0 using SSE registers
-O2 19 instructions 0 using SSE registers
-O3 63 instructions 17 using SSE registers
== -O0, the first instructions
0: endbr64
4: push rbp
5: mov rbp,rsp
8: mov QWORD PTR [rbp-0x18],rdi
c: mov DWORD PTR [rbp-0x1c],esi
f: mov DWORD PTR [rbp-0x8],0x0
16: mov DWORD PTR [rbp-0x4],0x0
1d: jmp 55 <sum_squares+0x55>
-O0 spills both arguments to the stack, initialises s at [rbp-0x8] and i at [rbp-0x4] in memory, and jumps to the loop test at the bottom (offset 0x55); every iteration reloads both from memory, so you can point at the C statement for every few lines. -O1 is the compact scalar loop, and -O2 is about the same size here (GCC 13's cheap vectorisation at -O2 doesn't apply to this loop, so no SSE registers). At -O3 the instruction count grows again because the loop is vectorised: it squares four ints at once in SSE registers and has a scalar tail for the leftover elements. A longer function in a release build is not necessarily a more complex one.
Loops that become formulas, and code that disappears
Two transformations matter especially for reading binaries. Clang recognises some loops and replaces them with a closed formula, so the loop you expect simply isn't there. And both compilers remove stores to memory that is never read again (dead-store elimination), which can delete code the author wrote for security.
cat > gone.c <<'SRC'
#include <string.h>
unsigned triangle(unsigned n) { /* 0 + 1 + ... + (n-1) */
unsigned s = 0;
for (unsigned i = 0; i < n; i++) s += i;
return s;
}
void load_key(char *k);
void use_key(const char *k);
void handle_secret(void) {
char key[32];
load_key(key);
use_key(key);
memset(key, 0, sizeof key); /* wipe the key before returning */
}
void handle_secret_fixed(void) {
char key[32];
load_key(key);
use_key(key);
explicit_bzero(key, sizeof key); /* a wipe the compiler must keep */
}
SRC
echo "== clang -O2 triangle: any backward jump?"
clang -O2 -c gone.c -o gone-clang.o
objdump -d -M intel --no-show-raw-insn --disassemble=triangle gone-clang.o | grep -E '^\s+[0-9a-f]+:' | sed 's/^ *//'
for lvl in O0 O2; do
gcc -$lvl -c gone.c -o gone-$lvl.o 2>/dev/null
printf -- '-%s handle_secret: memset calls %s\n' $lvl \
"$(objdump -dr --disassemble=handle_secret gone-$lvl.o | grep -c 'memset')"
printf -- '-%s handle_secret_fixed: explicit_bzero calls %s\n' $lvl \
"$(objdump -dr --disassemble=handle_secret_fixed gone-$lvl.o | grep -c 'explicit_bzero')"
done== clang -O2 triangle: any backward jump?
0: test edi,edi
2: je 17 <triangle+0x17>
4: lea eax,[rdi-0x1]
7: lea ecx,[rdi-0x2]
a: imul rcx,rax
e: shr rcx,1
11: lea eax,[rdi+rcx*1]
14: dec eax
16: ret
17: xor eax,eax
19: ret
-O0 handle_secret: memset calls 1
-O0 handle_secret_fixed: explicit_bzero calls 1
-O2 handle_secret: memset calls 0
-O2 handle_secret_fixed: explicit_bzero calls 1
Clang's triangle has no loop: one forward je handles n = 0, and the rest computes (n-1)(n-2)/2 + n - 1 with imul and shr, which equals n(n-1)/2, the formula rearranged so the intermediate product can't overflow. And the wipe of the key is gone at -O2: key is never read after the memset, so by the language rules the store is useless and the compiler deletes it. The secret stays in the dead stack frame until something overwrites it. explicit_bzero (glibc, the BSDs), memset_s (C11 Annex K, rarely available), SecureZeroMemory (Windows) and C23's memset_explicit exist precisely to survive this optimisation, and the fixed function keeps its call at both levels.
How this matters for detection and review
- Audit the binary, not only the source, when a security property depends on code the optimiser may judge useless: key wipes, constant-time comparisons (a compiler may turn a careful loop back into an early-exit one), checks for undefined behaviour such as
if (p + len < p)(pointer overflow is undefined, so the check may be removed). - Function boundaries move: inlined functions don't exist as functions; their code appears inside the caller, possibly several times. A string or a constant used by the inlined code is still there and leads you to it.
- Identify the compiler and level:
-O0code withrbpframes and stack spills often means a debug build was shipped, which may also contain assertions, logging and symbols an attacker could use.
How these problems are prevented
- Use wipe functions the compiler can't remove (
explicit_bzero,memset_explicit), or a crypto library's own (OPENSSL_cleanse, libsodium'ssodium_memzero). - Use
-fno-delete-null-pointer-checks,-fwrapvor, better, write checks that don't rely on undefined behaviour (if (len > SIZE_MAX - off)); compile with-fsanitize=undefinedin tests. - Keep optimised release builds and their unoptimised debug builds clearly separate, and check what you ship.
Pitfalls
- Expecting the source structure: a loop may be unrolled, vectorised, replaced by a formula or by a call to
memcpy/memsetthe compiler recognised. - "The function is missing": it was inlined or merged with an identical one (identical code folding).
- Counting instructions as complexity:
-O3code is longer and does the same thing faster. -O2differs between compilers and versions: GCC 13 and Clang 18 produce different code from the same source, which is one way analysts guess the compiler.
Practice
1. A function in a release binary has no prologue, keeps everything in registers and ends with jmp to another function. Which optimisations do you recognise?
Register allocation and frame-pointer omission (-O1 and up) and a tail call (-O2): the last call was turned into a jump.
2. Why is the memset in handle_secret legal for the compiler to remove?
The C standard only requires the program's observable behaviour to be preserved. key is a local that is never read after the memset, so the store has no observable effect and is a dead store.
3. You need to write a password comparison that takes the same time for every input. Why should you check the compiled code?
The optimiser may add an early exit or a branch that leaks timing; constant-time code has to be verified in the binary (or use a vetted function such as CRYPTO_memcmp or hmac.compare_digest).
Test yourself
At -O0, where are local variables usually kept?
- Only in registers
- On the stack, reloaded around each statement
- In .rodata
- In the GOT
Why did -O3 produce more instructions than -O1 for sum_squares?
- It is less optimised
- The loop is vectorised with SSE and has a scalar tail for leftover elements
- It adds debug code
- It includes the C library
What happened to the memset that wiped key at -O2?
- It was kept
- It was removed as a dead store, leaving the secret in memory
- It became explicit_bzero
- It moved to main
Clang compiled the triangle loop without any backward jump. Why?
- It deleted the function
- It replaced the loop with a closed formula for the sum
- It called a library function
- The loop was empty