HomeAbout UsContact Us

Fixing Missing volatile on ISR Variables Breaking -O2 Builds

By Jithin Tom
Published in Embedded C/C++
December 05, 2026
8 min read
Fixing Missing volatile on ISR Variables Breaking -O2 Builds

Table Of Contents

01
The Optimization Paradox
02
Root Cause: Control-Flow and Data-Race Assumptions
03
Five Patterns That Break Under Optimization
04
The Register Update Race: Not UB, But Broken Anyway
05
Debugging a Release Build Failure
06
Compiler Warning Flags for CI
07
When volatile Is Not Enough
08
Summary
09
Related Reading
10
References
11
Frequently Asked Questions

Your firmware passes every test at -O0. You flip the switch to -O2 for the release build and suddenly the device hangs, corrupts data, or lands in HardFault_Handler. The compiler did not break your code: it exposed a bug that was already there.

The most frequent culprit is a variable shared between an ISR and the main loop that is missing volatile. At -O0, the compiler keeps variables in their home memory locations between statements, so the main loop reloads the ISR’s write. At -O2, the compiler hoists that load out of the loop into a register, and your code spins forever on a stale value.

This article explains why that happens, how to spot it in Cortex-M disassembly, and the exact fixes — including when volatile alone is not enough.

The Optimization Paradox

Engineers often blame the compiler: “It worked in debug, -O2 broke it.” When undefined behavior (UB) is present, the C standard places no requirements on the program at the point of violation. Optimization makes the consequences visible because the compiler uses language guarantees when folding expressions, eliminating checks, or reordering permitted operations.

A debug build is not a reference implementation of code with UB. Before concluding UB is the cause, also check:

  • Missing volatile on MMIO and ISR-shared variables
  • Interrupt synchronization (read-modify-write races)
  • Linker configuration (stack/heap placement, section alignment)
  • Resource or timing changes between build configurations
+------------------------------------------------------------------+
| OPTIMIZATION EXPOSES BUGS |
+------------------------------------------------------------------+
| |
| -O0 (Debug) -O2 (Release) |
| ----------- ------------- |
| Reloaded from memory Hoisted/cached in registers |
| Minimal reordering Loads/stores reordered |
| Checks preserved Dead/redundant code removed |
| Minimal inlining Aggressive inlining |
| |
| Result: ISR write observed Result: ISR write MISSED |
| Loop re-reads flag Loop spins on cached register |
| |
| The bug existed at -O0. Optimization revealed it. |
| |
+------------------------------------------------------------------+

Root Cause: Control-Flow and Data-Race Assumptions

Unless instructed otherwise via volatile or _Atomic, a C compiler optimizes each function assuming objects are modified only along visible control-flow paths without unmodeled asynchronous updates or data races. The compiler has no visibility into hardware interrupt vectors: it sees an ISR (EXTI0_IRQHandler) that is never called from main(). When a polling loop such as while (!flag) { } contains no opaque external calls, compiler barriers, or volatile accesses, the optimizer concludes flag cannot legitimately change between iterations.

#include <stdbool.h>
void process_data(void);
/* BUG: missing volatile -- works at -O0, fails at -O2 */
bool flag = false; // NOT volatile!
void EXTI0_IRQHandler(void) {
flag = true; // ISR writes to memory
}
int main(void) {
while (!flag) { } // Compiler: "flag never changes in this loop"
process_data(); // Unreachable at -O2 if flag was false on entry
}

At -O2, GCC targeting ARM Cortex-M loads the 1-byte bool (ldrb, assuming r4 holds &flag) once before the loop instead of on every iteration:

/* Without volatile -- load hoisted out of loop (r4 = &flag) */
ldrb r3, [r4] @ Load 1-byte bool flag ONCE into r3
cmp r3, #0
bne .proceed @ If already non-zero on entry, continue
.loop_forever:
b .loop_forever @ Spin forever without re-reading memory
.proceed:
bl process_data

The load is hoisted out of the loop. Even after the ISR writes 1 to flag in SRAM, main() never reads memory again and spins forever in .loop_forever.

With volatile, every iteration is forced to perform a fresh byte load from memory:

/* With volatile -- fresh load every iteration (r4 = &flag) */
.loop:
ldrb r3, [r4] @ Load flag from memory EACH iteration
cmp r3, #0
beq .loop @ Re-check memory on next iteration
bl process_data

This optimization is not a compiler bug — it is valid behavior under the C abstract machine. Qualifying flag as volatile tells the compiler that accesses to that object have observable side effects outside normal control flow.

Five Patterns That Break Under Optimization

In embedded C troubleshooting across Cortex-M families (such as STM32, NXP, and TI devices), these five patterns account for most “works at -O0, fails at -O2” reports.

1. Missing volatile on ISR-Shared Variables

Symptom: Main loop never exits, a flag set by an ISR is never observed, or adding a printf / function call inside the loop makes the bug disappear (an opaque call forces the compiler to reload non-local globals).

Fix: Qualify bare flags and scalars shared between an ISR and main context as volatile (unless accessed through C11 _Atomic or inside a critical section / compiler barrier). This applies in both directions: if main() writes a non-volatile flag that an ISR reads, -O2 may optimize away the write via dead-store elimination.

#include <stdbool.h>
void process_rx_data(void);
/* CORRECT: volatile forces re-read every iteration */
volatile bool data_ready = false;
void UART_IRQHandler(void) {
data_ready = true; // ISR writes
}
int main(void) {
while (!data_ready) { // Compiler must reload each iteration
/* wait */
}
process_rx_data();
}

Rule: Any bare shared variable polled or modified across main/ISR contexts without _Atomic or barriers must be volatile.

2. Signed Integer Overflow

Signed arithmetic overflow is undefined behavior in C17 (6.5/5). At -O0, hardware multiply/add instructions may appear to wrap in two’s complement. At -O2, GCC assumes signed operations in a defined program do not overflow and folds comparisons or eliminates overflow checks based on that assumption.

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* DANGEROUS: signed multiplication overflows if out of range */
int32_t scale_sensor(int32_t raw, int32_t factor) {
return raw * factor; // UB if mathematical product overflows int32_t
}
/* SAFE: widen to int64_t and clamp (int32_t * int32_t always fits in int64_t) */
int32_t scale_sensor_safe(int32_t raw, int32_t factor) {
int64_t prod = (int64_t)raw * (int64_t)factor;
if (prod > INT32_MAX) return INT32_MAX;
if (prod < INT32_MIN) return INT32_MIN;
return (int32_t)prod;
}
/* SAFE for GCC/Clang: checked builtin.
* Callers must ignore *out when the function returns false. */
bool scale_sensor_checked(int32_t raw, int32_t factor, int32_t *out) {
if (out == NULL) return false;
return !__builtin_mul_overflow(raw, factor, out);
}

The builtin evaluates the exact mathematical product in infinite signed precision, casts that result to int32_t (storing the wrapped representation in *out), and returns true if the value could not be represented in int32_t — never invoking UB.

3. Strict Aliasing Violations

Accessing an object through a pointer to an incompatible effective type violates C’s strict aliasing rules (C17 6.5/7). At -O2 (-fstrict-aliasing is enabled by default), GCC assumes pointers of incompatible types do not alias the same object and may reorder, cache, or eliminate loads and stores.

#include <stdint.h>
#include <string.h>
/* DANGEROUS: strict aliasing violation on a float object */
uint32_t float_bits_unsafe(float f) {
return *(const uint32_t *)&f; // UB: incompatible effective type
}
/* SAFE: memcpy transfers object representation without aliasing UB */
uint32_t float_bits_safe(float f) {
uint32_t bits;
_Static_assert(sizeof(float) == sizeof(uint32_t), "Assumes 32-bit float");
memcpy(&bits, &f, sizeof(bits)); // GCC compiles this to a register move
return bits;
}

Character types (char *, unsigned char *, signed char *; on 8-bit-byte platforms uint8_t is typically unsigned char) are exempt from strict aliasing. C unions also permit reading another member for representation inspection under C17 (6.5.2.3), though inactive-member reads are not portable in C++ (use std::bit_cast in C++20). Never use memcpy on volatile memory-mapped peripheral registers, because memcpy drops volatile and may emit unaligned or byte-width accesses unsupported by Device memory.

4. Uninitialized Automatic Variables

Reading an uninitialized automatic variable whose value is indeterminate produces undefined behavior in C17 (6.3.2.1p2, notably for automatic variables whose address is never taken). A debug build does not zero-initialize stack slots; apparent zero values are accidental stack residue. Optimization can change register allocation and expose garbage values or trigger dead-code elimination along branches that rely on uninitialized state.

#include <stdbool.h>
#include <stdint.h>
/* BAD: flags is indeterminate when enable is false */
void configure_peripheral_bad(volatile uint32_t *control_reg,
bool enable, uint32_t enable_bit) {
uint32_t flags;
if (enable) flags = enable_bit;
*control_reg = flags; // UB if enable == false
}
/* SAFE: initialized on all paths before MMIO write */
void configure_peripheral_safe(volatile uint32_t *control_reg,
bool enable, uint32_t enable_bit) {
uint32_t flags = 0; // Initialized at declaration
if (enable) flags = enable_bit;
*control_reg = flags;
}

Enable -Wall (which activates -Wuninitialized and, when optimizing, -Wmaybe-uninitialized). These static checks are valuable but not exhaustive, and UBSan does not generally detect reads of uninitialized stack memory.

5. Out-of-Bounds Array Access

Accesses outside an array object’s bounds (including dereferencing one-past-the-end) are UB. Off-by-one loop bounds (<= instead of <) and unvalidated length arguments commonly corrupt neighboring stack variables or fault only when -O2 alters stack layout or removes redundant guards.

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
void do_something(uint8_t byte);
/* DANGEROUS: off-by-one (i == len is OOB) and no capacity check */
void process_buffer(const uint8_t *buf, size_t len) {
for (size_t i = 0; i <= len; i++) { // Reads 1 byte past buf[len - 1]
do_something(buf[i]);
}
}
/* SAFE: validate pointer and length against actual buffer capacity */
bool process_buffer_safe(const uint8_t *buf, size_t capacity, size_t len) {
if (buf == NULL || len > capacity) return false;
for (size_t i = 0; i < len; i++) {
do_something(buf[i]);
}
return true;
}

Enable -Warray-bounds=2 at -O2 or higher (value-range propagation is required for full bounds diagnostics).

The Register Update Race: Not UB, But Broken Anyway

A volatile peripheral-register update such as REG |= BIT is a read-modify-write (RMW) sequence, not a single indivisible transaction. If main code and an ISR both update the same read/write register, an interrupt between the load and the store causes a lost update (for ordinary non-atomic RAM shared across C threads, concurrent conflicting accesses are also a C data race). Note also that write-1-to-clear (W1C) interrupt status registers must never be updated with |= at all, because writing back 1 to other set bits clears unrelated pending flags.

+----------------------------------+----------------------------------+
| MAIN CONTEXT | ISR CONTEXT |
+----------------------------------+----------------------------------+
| T0: LOAD REG (0x00) | |
| T1: OR 0x00 | 0x01 -> 0x01 | |
| <-- interrupted before store | |
| | T2: LOAD REG (0x00) |
| | T3: OR 0x00 | 0x08 -> 0x08 |
| | T4: STORE REG (0x08) |
| <-- ISR returns | |
| T5: STORE REG (0x01) | |
| BIT 3 (0x08) LOST! | |
+----------------------------------+----------------------------------+
| volatile preserves every load/store, but cannot make RMW atomic. |
+---------------------------------------------------------------------+

Four Correct Patterns for RMW Races

1. Hardware Atomic Register Aliases (RP2040 APB/AHB Peripherals)

#include <stdint.h>
/* RP2040 Datasheet Section 2.1.2:
* Supported peripheral blocks expose +0x1000 (XOR), +0x2000 (SET), +0x3000 (CLR).
* Note: SIO does NOT use these bus aliases (SIO GPIO has dedicated _SET/_CLR regs). */
static inline void rp2040_reg_set(uintptr_t reg_addr, uint32_t bits) {
*(volatile uint32_t *)(reg_addr + UINT32_C(0x2000)) = bits;
}
static inline void rp2040_reg_clr(uintptr_t reg_addr, uint32_t bits) {
*(volatile uint32_t *)(reg_addr + UINT32_C(0x3000)) = bits;
}

2. Dedicated Set/Reset Registers (STM32 GPIO BSRR)

#include <stdint.h>
/* Requires the device STM32 CMSIS header (for example, "stm32f4xx.h"). */
/* STM32F4 RM0090 Section 8.4.7: GPIOx_BSRR is write-only and atomic.
* Bits [15:0] set ODR bits; bits [31:16] reset (clear) ODR bits.
* (STM32F4 has no separate BRR register; some other STM32 families also provide BRR.) */
static inline void set_pa5(void) {
GPIOA->BSRR = (UINT32_C(1) << 5); // Set PA5 atomically
}
static inline void clear_pa5(void) {
GPIOA->BSRR = (UINT32_C(1) << (5 + 16)); // Clear PA5 atomically
}

Using UINT32_C(1) instead of signed 1 avoids signed left-shift undefined behavior if a caller resets pin 15 (1 << 31).

3. Critical Section (Cortex-M PRIMASK)

#include <stdint.h>
#include "cmsis_compiler.h" // Provides __get_PRIMASK, __disable_irq, __set_PRIMASK
/* Save PRIMASK, disable configurable interrupts, update, restore PRIMASK.
* Protects against preempting IRQs on this core (not NMI, HardFault, DMA, or other cores). */
static inline void critical_section_update(volatile uint32_t *reg, uint32_t bits) {
uint32_t primask = __get_PRIMASK();
__disable_irq(); // Includes compiler "memory" clobber in CMSIS
*reg |= bits;
__set_PRIMASK(primask); // Restore previous state (safe when nested)
}

Always save and restore PRIMASK rather than unconditionally calling __enable_irq() — nested critical sections must not re-enable interrupts prematurely. In an RTOS (such as FreeRTOS using BASEPRI), use the kernel’s critical-section macros around RTOS-managed data.

4. C11 _Atomic for Shared RAM (GCC 4.9+, Clang 3.8+)

#include <stdatomic.h>
#include <stdint.h>
#define EVENT_BIT (UINT32_C(1) << 0)
_Atomic uint32_t shared_flags = 0;
/* Verify lock-free support before calling from an ISR */
_Static_assert(ATOMIC_INT_LOCK_FREE == 2 && ATOMIC_LONG_LOCK_FREE == 2,
"Requires lock-free 32-bit atomics");
/* ISR: atomic fetch-or */
void set_event_from_isr(void) {
atomic_fetch_or_explicit(&shared_flags, EVENT_BIT, memory_order_relaxed);
}
/* Main: atomic fetch-and */
uint32_t clear_event_from_main(void) {
return atomic_fetch_and_explicit(&shared_flags, ~EVENT_BIT, memory_order_relaxed);
}

On ARMv7-M (Cortex-M3/M4/M7) and ARMv8-M Mainline (Cortex-M33), GCC compiles lock-free 32-bit _Atomic RMW operations to LDREX/STREX loops that are ISR-safe. However, Cortex-M0/M0+ (ARMv6-M) lacks LDREX/STREX, so _Atomic RMW calls libatomic locking helpers that are unsuitable for ISRs or fail to link in bare metal — check atomic_is_lock_free(&shared_flags) and use PRIMASK critical sections on ARMv6-M. Never use C11 _Atomic on peripheral MMIO registers (LDREX/STREX on Device memory is unsupported/unpredictable), and remember memory_order_relaxed does not order unrelated payload buffers (use memory_order_release/memory_order_acquire for producer-consumer handoff).

Debugging a Release Build Failure

When -O2 breaks previously working code, follow this systematic workflow:

Step 1: Isolate the Change

Rebuild the same source and configuration with only the optimization level changed. If that reproduces the issue, selectively compile translation units at -O2 to locate the sensitive file.

# Build suspect translation unit at -O2 while keeping others at -O0
arm-none-eabi-gcc -O2 -c sensitive.c -o sensitive_O2.o
arm-none-eabi-gcc -O0 -c other.c -o other_O0.o
# Link and test

Check for differing NDEBUG, LTO (-flto), linker scripts, and compiler versions as separate variables. You can temporarily bisect down to a single function using __attribute__((optimize("O0"))), but never ship that as a substitute for fixing the root bug.

Step 2: Compare Assembly

Compile both builds with -g and inspect interleaved C/disassembly via objdump:

arm-none-eabi-objdump -dS firmware_O0.elf > asm_O0.txt
arm-none-eabi-objdump -dS firmware_O2.elf > asm_O2.txt
diff -u asm_O0.txt asm_O2.txt | less

Look for:

  • Optimized-away checks (null-pointer tests, bounds checks, overflow guards)
  • Changes to MMIO or flag accesses (load hoisted out of loop, dead store removed)
  • Changed stack usage (larger frames, reused stack slots)
  • Inlining decisions (function calls eliminated, removing implicit global reload barriers)

These differences are clues, not proof of UB.

Step 3: Instrument Reproductions

Run host unit tests with UBSan and AddressSanitizer:

gcc -Og -g -fsanitize=undefined,address -fno-sanitize-recover=all test.c -o test

For Cortex-M target diagnostics without libubsan, use trap-mode UBSan (-fsanitize-trap=undefined in modern GCC, or -fsanitize-undefined-trap-on-error on older GCC):

arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -Og -g \
-fsanitize=signed-integer-overflow,shift,bounds,null,integer-divide-by-zero \
-fsanitize-trap=undefined \
-c firmware.c -o firmware_ubsan.o

On ARMv7-M/ARMv8-M Mainline, a trap compiles to an undefined instruction (UDF), raising UsageFault (if enabled via SCB->SHCSR) or escalating to HardFault; on Cortex-M0/M0+ (ARMv6-M), UDF enters HardFault directly. Inspect the disassembly and capture the stacked PC.

Step 4: Inspect Runtime Evidence

Add a naked HardFault_Handler stub so the compiler does not emit a stack-pushing prologue that corrupts MSP before reading the exception frame (for ARMv7-M/ARMv8-M Mainline such as Cortex-M3/M4/M7/M33; Cortex-M0/M0+ lacks ite and CFSR/HFSR/MMFAR/BFAR):

#include <stdint.h>
/* Requires the device CMSIS core header (providing SCB and SCB_CFSR_*_Msk). */
__attribute__((used))
void hard_fault_c(const uint32_t *stack) {
uint32_t r0 = stack[0];
uint32_t r1 = stack[1];
uint32_t r2 = stack[2];
uint32_t r3 = stack[3];
uint32_t r12 = stack[4];
uint32_t lr = stack[5];
uint32_t pc = stack[6];
uint32_t xpsr = stack[7];
uint32_t cfsr = SCB->CFSR; // Configurable Fault Status Register
uint32_t hfsr = SCB->HFSR; // HardFault Status Register
uint32_t mmfar = (cfsr & SCB_CFSR_MMARVALID_Msk) ? SCB->MMFAR : 0U;
uint32_t bfar = (cfsr & SCB_CFSR_BFARVALID_Msk) ? SCB->BFAR : 0U;
(void)r0; (void)r1; (void)r2; (void)r3;
(void)r12; (void)lr; (void)pc; (void)xpsr;
(void)hfsr; (void)mmfar; (void)bfar;
// Log cfsr, hfsr, mmfar, bfar, pc, lr to UART/RTT/flash, then halt
while (1) { __asm volatile("bkpt #0"); }
}
__attribute__((naked))
void HardFault_Handler(void) {
__asm volatile (
"tst lr, #4\n" // Check EXC_RETURN bit 2 (0 = MSP, 1 = PSP)
"ite eq\n"
"mrseq r0, msp\n" // MSP was active
"mrsne r0, psp\n" // PSP was active
"b hard_fault_c\n"
);
}

Correlate the stacked pc and lr with the .map file and disassembly. Check ISR/task interactions, volatile qualifiers, DMA cache coherence, and timing assumptions.

Step 5: Audit the Failing Function

Match the symptom to the likely cause:

Symptom at -O2Likely CauseFix
Arithmetic gives wrong resultSigned overflowWiden/clamp, __builtin_mul_overflow, or unsigned
Bit mask evaluates to 0Invalid shift count / signed shiftUse UINT32_C(1) << n and check n < 32
Type-punned value corruptedStrict aliasing violationmemcpy (RAM only) or C union
Variable holds garbageUninitialized readInitialize at declaration
Loop skips/extra iterationsOOB array accessValidate bounds, enable -Warray-bounds=2
ISR register update lostPeripheral RMW raceAtomic alias, BSRR, or PRIMASK critical section
Flag never observedMissing volatile on ISR-sharedAdd volatile (or _Atomic for lock-free RAM)

Compiler Warning Flags for CI

Once the codebase is warning-clean, consider -Werror in CI:

arm-none-eabi-gcc -std=c17 -mcpu=cortex-m4 -mthumb -O2 \
-Wall -Wextra \
-Wshift-overflow=2 \
-Wconversion -Wsign-conversion -Wnull-dereference \
-Warray-bounds=2 -Wstrict-aliasing=2 \
-Werror=implicit-function-declaration \
-c firmware.c -o firmware.o
  • -Wall enables -Wuninitialized and (with optimization on) -Wmaybe-uninitialized
  • -Wshift-overflow=2 additionally diagnoses left-shifting 1 into the sign bit (such as 1 << 31 on 32-bit int) in C11/C17 mode
  • -Warray-bounds=2 requires -O2 or higher (VRP analysis), and -Wstrict-aliasing=2 requires -fstrict-aliasing (enabled at -O2)
  • These flags are GCC-focused; verify support before copying directly to Clang or vendor compilers

When volatile Is Not Enough

volatile prevents the compiler from omitting or caching memory accesses, but does not guarantee atomicity or hardware bus ordering.

64-bit Variables on 32-bit Cores

#include <stdint.h>
/* DANGEROUS: non-atomic 64-bit access on a 32-bit Cortex-M core */
volatile uint64_t system_timestamp;
void SysTick_Handler(void) {
system_timestamp++; // Multi-instruction 32-bit load/add/store
}
uint64_t get_timestamp(void) {
return system_timestamp; // Two 32-bit LDRs (or LDRD); can tear if interrupted
}

On ARMv7-M, neither a pair of LDR instructions nor LDRD is single-copy atomic across all 64 bits. If SysTick_Handler preempts get_timestamp() between the low-word and high-word reads (for instance across a 0x00000000FFFFFFFF to 0x0000000100000000 carry), get_timestamp() returns a torn 64-bit value.

Correct 64-Bit Access Patterns

Option 1: Disable Interrupts (Simple, Guaranteed on Single Core)

#include <stdint.h>
#include "cmsis_compiler.h"
extern volatile uint64_t system_timestamp;
uint64_t get_timestamp(void) {
uint32_t primask = __get_PRIMASK();
__disable_irq();
uint64_t ts = system_timestamp;
__set_PRIMASK(primask);
return ts;
}

Option 2: Double-Read Consistency (No Interrupt Disable, Sole Monotonic ISR Writer)

#include <stdint.h>
extern volatile uint64_t system_timestamp;
uint64_t get_timestamp(void) {
uint64_t a, b;
do {
a = system_timestamp;
b = system_timestamp;
} while (a != b);
return a;
}

Option 2 requires that the ISR is the sole monotonic writer, that updates occur much less frequently than the read loop (otherwise it can spin indefinitely under pathological IRQ rates), and that the read sequence is not preempted for 2^32 ticks between reads.

Compiler Barriers vs. Hardware Memory Barriers

Two volatile accesses are sequenced relative to each other by the compiler, but a volatile access and a non-volatile access have no such ordering guarantee:

#include <stdint.h>
volatile uint8_t flag;
uint8_t buffer[64];
/* COMPILER MAY REORDER: flag = 1 emitted before buffer[0] is written */
void publish_bad(uint8_t received_byte) {
buffer[0] = received_byte; // Non-volatile write
flag = 1; // Volatile write
}

Place a compiler barrier (__asm volatile("" ::: "memory") or CMSIS __COMPILER_BARRIER()) between the non-volatile payload and the volatile flag on both producer and consumer sides (so the consumer cannot speculatively read buffer[0] before checking flag), or prefer C11 _Atomic with memory_order_release / memory_order_acquire:

void publish_good(uint8_t received_byte) {
buffer[0] = received_byte;
__asm volatile("" ::: "memory"); // Compiler barrier: prevents compile-time reordering
flag = 1;
}
uint8_t consume_good(uint8_t fallback) {
if (flag == 0U) {
return fallback;
}
__asm volatile("" ::: "memory"); // Prevent speculative load before flag check
return buffer[0];
}

On a single-core CPU communicating with its own ISR, a compiler barrier suffices because exception entry/return preserves single-core program-order visibility. However, if DMA or a second core reads buffer and flag in Normal SRAM, a compiler barrier alone is not enough: insert __DMB() (hardware Data Memory Barrier) and, on D-cache cores like Cortex-M7, perform cache maintenance (SCB_CleanDCache_by_Addr() / SCB_InvalidateDCache_by_Addr()).

Summary

ProblemDetectionFix
Missing volatile on ISR flagLoop never exits at -O2Add volatile (or lock-free _Atomic in RAM)
Signed integer overflowWrong result at -O2Widen, clamp, or __builtin_mul_overflow
Strict aliasing violationCorrupted type-punned valuememcpy (RAM only) or C union
Uninitialized variableGarbage value, non-deterministicInitialize at declaration
OOB array accessCrash / corruption at -O2Check pointer/capacity, enable -Warray-bounds=2
Peripheral RMW raceLost bit updatesAtomic alias, BSRR, or PRIMASK critical section
64-bit torn readImpossible timestamp valuesPRIMASK critical section or double-read check
Compiler reorderingFlag set before payload readyCompiler barrier (plus __DMB() for DMA/multicore)

Key takeaways:

  • A failure seen only at -O2 is evidence to investigate, not a compiler bug; optimization exposes latent UB, missing volatile, concurrency races, or stack/timing assumptions
  • Declaring bare ISR-shared scalars volatile prevents load hoisting and dead-store elimination, but does not provide atomicity or hardware bus ordering
  • Use hardware atomic register aliases (RP2040), BSRR set/reset registers (STM32), short PRIMASK critical sections, or verified lock-free C11 _Atomic (ARMv7-M/v8-M Mainline RAM only) for concurrent updates
  • Enable -Wall -Wextra -Wshift-overflow=2 -Warray-bounds=2 -Wstrict-aliasing=2 with -O2 in CI
  • Run UBSan + ASan on host unit tests and trap-mode UBSan (-fsanitize-trap=undefined) on target builds, and always validate the optimized production configuration before deployment

References

  1. Arm Limited, Arm Compiler for Embedded User Guide: Effect of the volatile keyword on compiler optimization
  2. Texas Instruments, 2.4.8. Use of volatile: C2000 C28x Optimization Guide
  3. SEI CERT C Coding Standard, INT32-C: Ensure that operations on signed integers do not result in overflow
  4. GCC Documentation, Instrumentation Options (-fsanitize=undefined, -fsanitize-trap=)
  5. GCC Documentation, Warning Options (-Wshift-overflow, -Warray-bounds, -Wstrict-aliasing, -Wuninitialized)
  6. Arm Limited, Armv7-M Architecture Reference Manual (DDI 0403): Section A3.5 Memory Types and Atomicity, Section B1.5 Exception Model, Section B3.2 System Control Space
  7. Memfault Interrupt Blog, How to debug a HardFault on an ARM Cortex-M MCU
  8. STMicroelectronics, RM0090 Reference Manual: STM32F405/415, STM32F407/417, STM32F427/437 and STM32F429/439 (Section 8.4.7 GPIOx_BSRR)
  9. Raspberry Pi Ltd., RP2040 Datasheet (Section 2.1.2 Atomic Register Access)
  10. ISO/IEC 9899:2018 (C17), Programming Languages — C (Section 6.3.2.1, Section 6.5, Section 6.7.3, Annex J.2)
  11. Arm Limited, Arm Cortex-M Programming Guide to Memory Barrier Instructions (DAI0321)
  12. Applied Embedded Electronics, Shared Data & Volatile Semantics
  13. ST Community, Why am I getting a HardFault with -O2 optimization only?

Frequently Asked Questions

Why does my embedded C code work at -O0 but crash or hang at -O2?

In embedded firmware, a missing volatile qualifier on an ISR-shared variable or peripheral register is a leading cause: at -O0 the compiler reloads variables from their home memory locations between statements, whereas at -O2 it can hoist a load into a register and spin on a stale value or dereference a stale pointer. Other frequent -O2 failure triggers are latent undefined behavior (out-of-bounds access, uninitialized locals, strict aliasing violations, signed integer overflow) and stack-size or timing changes.

Does volatile make ISR-shared variable access atomic?

No. volatile prevents the compiler from omitting, caching, or coalescing accesses, not from interrupting or tearing multi-instruction sequences. On Cortex-M, single naturally aligned 8-, 16-, and 32-bit loads and stores (LDR/STR) are single-copy atomic, whereas 64-bit variables (even LDRD/STRD), unaligned accesses, and read-modify-write sequences (flag |= bit) are not atomic and require a critical section (PRIMASK), hardware atomic register support, or lock-free _Atomic operations.

How do I fix a HardFault that only appears with optimization enabled?

First, add a naked HardFault handler that selects MSP or PSP from EXC_RETURN and passes the exception stack frame to C code to inspect stacked PC/LR (plus CFSR, HFSR, and validated MMFAR/BFAR on ARMv7-M and ARMv8-M Mainline; Cortex-M0/M0+ lacks CFSR/HFSR). Then audit for missing volatile on ISR-shared variables, uninitialized locals, signed integer overflow, strict aliasing violations, and out-of-bounds accesses, comparing -O0 and -O2 disassembly.

What compiler flags help catch these bugs before release?

Compile with -Wall -Wextra -Wshift-overflow=2 -Wstrict-aliasing=2 -Warray-bounds=2 -Wconversion -Wsign-conversion at -O2 (note that -Wall already enables -Wuninitialized and -Wmaybe-uninitialized during optimization). For runtime checks, run host tests with -fsanitize=undefined,address and use trap-mode UBSan (-fsanitize=signed-integer-overflow,shift,bounds,null,integer-divide-by-zero -fsanitize-trap=undefined) on supported targets.

Can I just add volatile to everything to fix optimization bugs?

No. Adding volatile to ordinary variables masks real concurrency or lifetime bugs and disables register optimization across the codebase. Use volatile for memory-mapped registers and bare scalars/flags shared with an ISR on a single core. For multi-word shared data on 32-bit MCUs, use a critical section or a barrier-ordered single-producer/single-consumer ring buffer, because _Atomic types wider than 32 bits are typically not lock-free on Cortex-M.

Tags

embedded-cvolatileoptimizationisrhardfaultcortex-m

Share


Previous Article
Fixing PREEMPT_RT Console Printing Thread Sleeping Warning
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing C Signed Integer Overflow With Checked Builtins
Fixing C Signed Integer Overflow With Checked Builtins
December 01, 2026
8 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media