skip to content

Should a large C++ codebase full of legacy type-punning code build with -fno-strict-aliasing, and what does that choice cost and protect?

level: principalimportance: should knowfreq 32%

answer

  1. turns off type-based alias analysis
  2. the code stays non-conforming
  3. measure the performance cost
  4. a flag every build must keep
  5. migrate punning sites over time

basics

~20 s

Often yes, as containment: -fno-strict-aliasing stops GCC and Clang optimising on type-based aliasing, so pointer-cast punning is no longer miscompiled that way. It costs optimisation, binds every build to the flag, and leaves the code undefined in ISO C++.

solid answer

~50 s

`-fno-strict-aliasing` tells GCC and Clang not to use **type-based alias analysis**, so accesses through differently typed pointers are assumed to overlap. Code that puns through casts then behaves as written, which is why the flag is a standard containment step for a large legacy codebase. It is a judgment call: the cost is lost optimisation in pointer-heavy hot loops (measure it; it ranges from negligible to significant), and the protection holds only while every build — every target, library and toolchain — keeps the flag. The code remains undefined in ISO C++, other compilers may behave differently, and new punning keeps arriving because nothing fails. A defensible policy pairs the flag with a plan: inventory and replace punning sites with `std::memcpy` or `std::bit_cast`, keep the flag on the modules that still need it, gate new code with review and warnings, and remove the flag where the benchmark shows a gain.

code

cpp · 14 lines
cpp
#include <cstdio>

// The compiler may assume an int* and a float* never point at the same object.
__attribute__((noinline)) int store_both(int* count, float* scale) {
    *count = 1;
    *scale = 0.0f;
    return *count;           // with strict aliasing: folded to the constant 1
}

int main() {
    int x = 0;
    int r = store_both(&x, reinterpret_cast<float*>(&x));   // UB: float store into an int
    std::printf("returned %d, x is now %d\n", r, x);
}

go deeper

for a junior

Recall that -fno-strict-aliasing tells the compiler not to assume differently typed pointers never overlap, which hides some punning bugs.

for a middle

Explain what type-based alias analysis gains, which compilers enable it by default, and why the code stays undefined behaviour with the flag.

for a senior

Show a release-only miscompile caused by punning, how the flag removes it, and why the warning disappears with it, then propose targeted fixes.

for a principal

Weigh measured performance, build hygiene and migration effort to decide where the flag stays, with a plan and a metric for removing it.

## What the flag changes Strict aliasing is a promise the program makes and the optimiser relies on: accesses through unrelated types never touch the same object. With that promise, a compiler can keep a value in a register across a store through a pointer of another type, reorder loads and stores, and vectorise loops. GCC enables `-fstrict-aliasing` at `-O2`, `-O3` and `-Os`. Clang enables it by default, except on Windows MSVC and UEFI targets, where its default is `-fno-strict-aliasing`. `-fno-strict-aliasing` withdraws the promise. The optimiser then assumes that any two pointers may alias unless it can prove otherwise from addresses. Code like `store_both(&x, reinterpret_cast<float*>(&x))` stops being "optimised wrong": in the example below, Clang 21 at `-O2` returns 1 from a function that just overwrote the value, and with `-fno-strict-aliasing` it returns 0. ## What it protects, and what it does not | Protected | Not protected | |---|---| | casts that read one type's object through another type's pointer | union punning in constant expressions | | in-place struct casts over byte buffers, as far as aliasing goes | misaligned accesses, padding mismatches and byte order | | optimiser upgrades that strengthen alias analysis | ISO conformance: the code is still undefined behaviour | | | other compilers or tools that assume the standard rule | Clang's own manual describes the trade-off: code that violates strict aliasing "should generally be built with `-fno-strict-aliasing` if the violation cannot be fixed", and a program that works in one Clang version may not work in another as the optimiser changes. Clang 20, for instance, began distinguishing pointer types by pointee type in its aliasing analysis (restorable with `-fno-pointer-tbaa`), which is the kind of upgrade that breaks code that used to work. ## The costs a lead has to weigh - **Performance.** Numeric loops over arrays accessed through several pointer types lose reordering and vectorisation opportunities. The effect is workload-specific; benchmark the hot paths with and without the flag rather than guessing. - **Build hygiene.** The flag is a correctness requirement, not a tuning knob. Every target, every vendored library that contains punning, every new toolchain file and every IDE configuration must carry it. A single translation unit compiled without it reintroduces the risk for everything in that unit, including inline functions it instantiates from shared headers. - **Signal loss.** With the optimiser no longer exploiting violations, new punning code works and passes review. GCC's `-Wstrict-aliasing` (part of `-Wall`) only runs when `-fstrict-aliasing` is active, so the warning disappears with the flag. - **Portability.** Compilers without an equivalent flag, static analysers and future standards all treat the code as undefined. ## A policy that holds up 1. **Contain now.** Build the legacy modules with `-fno-strict-aliasing` so production behaviour is stable across compiler upgrades. 2. **Inventory.** Find punning sites: pointer casts between unrelated types, union reads, in-place buffer casts. Clang's experimental TypeSanitizer (`-fsanitize=type`) and code search help. 3. **Replace.** Route bit reinterpretation through `std::bit_cast` (C++20) or a `memcpy`-based helper, and byte-buffer parsing through a reader that copies. 4. **Shrink the scope.** Remove the flag module by module once a module is clean, keeping it only where the cost of migrating exceeds its benefit. 5. **Measure.** Track the benchmark difference so the decision to keep or drop the flag is based on numbers. ## Questions to settle before deciding - How much of the code base actually puns, and can it be found mechanically, or is it spread through macros and generated code? - Which binaries are performance-critical, and what does the benchmark say with the flag on and off for those binaries specifically? - Does every build path, including third-party code built from source, packaging scripts and developer presets, inherit the same compile options? - Who owns the migration, and how is progress measured, for example as the number of modules still built with the flag? There is no single right answer. A codebase with little hot numeric code and lots of hard-to-audit punning may sensibly keep the flag permanently; a performance-critical engine with a few punning sites should fix the sites and keep strict aliasing on.

  • Is the may_alias attribute a better alternative to a global -fno-strict-aliasing?
    Often yes, as a targeted fix. GCC's `may_alias` type attribute, also supported by Clang, makes accesses through a typedef'd type exempt from type-based alias analysis, like a character type, so only the punning sites lose optimisation. It is still a compiler extension, it must be applied at every site, and `std::memcpy` or `std::bit_cast` remain the portable fixes.
  • Why does -Wstrict-aliasing stop helping once the codebase builds with -fno-strict-aliasing?
    GCC documents that `-Wstrict-aliasing` is only active when `-fstrict-aliasing` is active. Turning strict aliasing off therefore also silences its warning, so new violations arrive unnoticed. Teams that keep the flag usually add a separate build or analysis job with strict aliasing on, purely to keep the warnings flowing.

  • -fno-strict-aliasing makes type punning legal C++.
  • The flag costs nothing, so every project should just turn it on.
  • Setting it in the main CMake target protects every library we link.
  • Once the flag is on, there is no reason to keep fixing punning sites.
  • Strict aliasing optimisations only exist in GCC, so Clang builds are unaffected.