https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124958

            Bug ID: 124958
           Summary: GCC 16: wrong code at `-O3` — IPA-SRA-cloned lambda
                    body reads uninitialized stack slot when its captured
                    pointer is `do_not_optimize`-clobbered and the called
                    method has a `pre()` contract precondition
           Product: gcc
           Version: 16.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: ipa
          Assignee: unassigned at gcc dot gnu.org
          Reporter: uct03f1h at gmail dot com
  Target Milestone: ---

Created attachment 64255
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=64255&action=edit
the 19-line minimal source

GCC 16: wrong code at -O3 -- IPA-SRA-cloned lambda body reads
uninitialized stack slot when its captured pointer is do_not_optimize-
clobbered and the called method has a pre() contract precondition.

================================================================================
SUMMARY
================================================================================

GCC 16 emits wrong code (deterministic SIGSEGV -- 200/200 with stack-
randomized environments) for a [&]-capturing lambda body whose captured
'const T*' is passed through

    asm volatile("" : "+m,r"(p) : : "memory")

(the canonical Google-Benchmark DoNotOptimize(T&) idiom) immediately
before the call, when the inlined method invoked through that pointer
has a pre(...) contract precondition.

The lambda receives an address that does NOT point at the captured
variable's storage. Specifically, the store 'pp = &p' writes to one
stack slot; the lambda's '&pp' argument resolves to a different stack
slot (off by sizeof(captured_type) bytes -- 16 in our reproducer with
alignas(16)). The lambda dereferences uninitialized memory.

This is NOT PR121936 (vague-linkage derefinement) and NOT PR124088
(whether -fcontracts-conservative-ipa is necessary). However, the
__tu_terminate_wrapper introduced by commit cac79586e1ab (the workaround
for PR121936, on by default via -fcontracts-conservative-ipa) is a
precondition for the present defect: without it, IPA-SRA picks .part.0
partial inlining instead of .isra.0 parameter splitting, and the defect
is not exhibited.


================================================================================
REPRODUCTION
================================================================================

Build:

    g++-16 -std=c++26 -fcontracts -O3 -march=native \
        bug_minimal.cpp handler.cpp -o bug

Run:

    ./bug         # SIGSEGV

Expected output: 2
Actual:          SIGSEGV before any output is written.

Also reproduces with bug_realistic.cpp -- the same defect framed as a
normal-looking microbenchmark of a memory pool with a precondition-
checked hot accessor (the form in which the defect was originally
encountered in production code).

The code does NOT invoke any undefined behavior (verified -- see
"PRE-FILING DILIGENCE" below).


================================================================================
COMPILER
================================================================================

    gcc version 16.0.1 20260416 (Red Hat 16.0.1-0) (GCC)
    Target: x86_64-redhat-linux
    Configured with: ../configure --enable-bootstrap
       
--enable-languages=c,c++,fortran,objc,obj-c++,ada,go,d,m2,cobol,algol68,lto
        --prefix=/usr --enable-checking=release --enable-multilib
        --with-system-zlib --enable-__cxa_atexit --enable-shared
        --enable-threads=posix --with-tune=generic
        --build=x86_64-redhat-linux  [...]

Full 'gcc -v' output is in gcc-v.txt. Build is the Fedora rawhide RPM
gcc-16.0.1-0.11.fc45 (upstream-trunk snapshot of 2026-04-16).


================================================================================
NECESSARY TRIGGER CONDITIONS
================================================================================

Each condition, when removed individually, eliminates the miscompile
(verified by bisection):

 1. -fcontracts is active and a pre(...) clause is present on the method.
    Replacing pre() with assert(), if/abort, [[assume(...)]], or
    __builtin_unreachable() does NOT trigger the defect.

 2. [[gnu::cold, gnu::noinline]] on the constructor that builds the
    object. Either attribute alone is insufficient.

 3. [[gnu::always_inline]] on the contract-bearing method.

 4. sizeof(class) > 8 bytes. In the minimal reproducer this is forced
    via alignas(16) on a struct containing two uint32_t. An 8-byte class
    with the same surrounding code does NOT trigger the defect.

 5. A heap-allocating standard container in main() -- specifically
    std::vector<int> or std::deque<int>. std::array, raw locals, and
    hand-rolled vectors do NOT trigger.

 6. Two push_back([]{ IIFE }()) calls; both IIFEs construct the object.
    A single push_back, or a first IIFE that omits object construction,
    does NOT trigger.

 7. Named inner lambda invoked twice:
        auto body = [&]{ ... };
        body(); body();
    Anonymous form
        [&]{ ... }(); [&]{ ... }();
    does NOT trigger.

 8. asm volatile("" : "+m,r"(pp) : : "memory") on the captured pointer.
    The "+m,r" (input-output) overload triggers; the "r,m" (input-only)
    form does NOT.

 9. Reference capture [&] of pp. By-value capture [pp] does NOT trigger.

10. Non-top-level-const pointer 'const T* pp'. Top-level const
    'const T* const pp' does NOT trigger.


================================================================================
WORKAROUNDS
================================================================================

Verified by stress test (>= 100 runs each, randomized stack via
environment padding):

    default flags                            200/200 crash
    -fno-ipa-sra                               0/100 crash  (FIX)
    -fno-tree-fre                              0/100 crash  (FIX)
    -fno-tree-vrp                              0/100 crash  (FIX)
    -fno-tree-slp-vectorize                    0/100 crash  (FIX)
    -fno-contracts-conservative-ipa            0/100 crash  (FIX)
    -fcontract-evaluation-semantic=ignore      0/100 crash  (FIX)
    -O0, -O1, -Os                              0/100 crash  (FIX)
    -O2                                      200/200 crash
    -fno-tree-dce / -fno-tree-dse                  crash
    -fno-strict-aliasing / -fwrapv                 crash  (rules out
aliasing/overflow UB classes)
    -fno-aggressive-loop-optimizations             crash
    -D_GLIBCXX_ASSERTIONS                          crash

The only contract-related workaround that fixes the crash is
-fcontract-evaluation-semantic=ignore (i.e., disabling contract
evaluation entirely). -fcontracts-conservative-ipa is on by default;
turning it off fixes the present defect but, per PR124088 discussion,
may re-expose users to the vague-linkage derefinement issue PR121936
was working around.


================================================================================
RUNTIME EVIDENCE (THE OFF-BY-16)
================================================================================

GDB at the lambda entry, immediately before the crashing dereference:

    Breakpoint at _ZZZ4mainENKUlvE0_clEvENKUlvE_clEv.isra.0
    (gdb) frame 1                  # caller frame (main, second IIFE)

    (gdb) p &pp                    # debug info: address of pp
    $1 = (const Pool **) 0x7fffffffd448

    (gdb) p &p                     # the Pool we want to point to
    $2 = (Pool *) 0x7fffffffd460

    (gdb) p pp                     # pp's value at &pp
    $3 = 0x12000                   # <-- UNINITIALIZED garbage

    (gdb) info reg rdi
    rdi  0x7fffffffd448             # call passed &pp = 0x7fffffffd448

    (gdb) printf "memory at &pp - 16 = 0x%lx\n", \
                 *((long*)((char*)&pp - 16))
    memory at &pp - 16 = 0x7fffffffd460  # <-- &p, the value pp = &p stored

    (gdb) p p.n_                   # the Pool itself is correctly initialized
    $4 = 100

Interpretation:

  - The store 'pp = &p' correctly wrote &p (= 0x7fffffffd460) to
    address &pp - 16 (= 0x7fffffffd438).

  - The call operator().isra(&pp) passes &pp (= 0x7fffffffd448) -- 16
    bytes higher in the stack frame than where the store landed.

  - That slot is uninitialized; its contents vary with whatever random
    noise was left on the stack by the caller frame. In one run we
    observed 0x12000; in another, a pointer into libc heap memory. The
    value is non-deterministic across runs even though the crash itself
    is (stack randomization produces 200/200 crashes, but with different
    failure modes: mostly SIGSEGV on the offset-4 load, occasionally a
    clean SIGABRT via the contract-violation path).

  - The lambda dereferences (rdi) to load pp's value and gets garbage.
    It then reads offset 4 (the n_ field of the supposed Pool*) and
    either segfaults (most random pointers) or reads nonsense (rare
    lucky pointers).

The 16-byte offset matches sizeof(Pool) with alignas(16). Reducing the
alignment to a struct of <= 8 bytes makes the defect disappear (item 4
of the trigger conditions).


================================================================================
DISASSEMBLY EVIDENCE (CALL SITE IN MAIN, SECOND IIFE)
================================================================================

    ; Pool::Pool(&second_pool, 100) initializes the Pool at slot 0x40(%rsp)
    4005a3: call   _ZN4PoolC1Ej

    ; pp = &p     stores &p at slot 0x18(%rsp)
    4005a8: mov    %rbx,0x18(%rsp)

    ; lambda call passes 0x28(%rsp) -- 16 bytes HIGHER than where pp was stored
    4005ad: lea    0x28(%rsp),%rdi
    4005b2: call   _ZZZ4mainENKUlvE0_clEvENKUlvE_clEv.isra.0
    4005b7: lea    0x28(%rsp),%rdi
    4005bc: call   _ZZZ4mainENKUlvE0_clEvENKUlvE_clEv.isra.0

There is NO store to 0x28(%rsp) anywhere in main before the call.

The IPA-SRA-cloned lambda body:

    <_ZZZ4mainENKUlvE0_clEvENKUlvE_clEv.isra.0>:
      push   %rbx
      mov    (%rdi),%rbx              ; rbx = *(rdi) -- load whatever rdi
points to
      cmpl   $0x0,0x4(%rbx)           ; check Pool::n_ at offset 4 (pre(0 <
n_))
      jne    .L_ok
      mov    $.Lcontract_violation0,%edi
      call   handle_contract_violation
      call   __tu_terminate_wrapper   ; noipa wrapper added by commit
cac79586e1ab
    .L_ok:
      mov    0x4(%rbx),%eax           ; return n_
      pop    %rbx
      ret

The body itself is correct GIVEN a valid &pp. The defect is in the
call site's argument: it passes 0x28(%rsp) instead of 0x18(%rsp).


================================================================================
IR-PASS-LEVEL ANALYSIS (WHAT WAS OBSERVED)
================================================================================

Tracking the GIMPLE statement 'body.__pp = &pp' (where 'body' is the
closure struct generated by the C++ frontend for the inner [&] lambda)
across the pipeline, with -fdump-tree-all-raw:

    Pass                   body.__pp = &pp ?    Lambda call form
    --------------------   -------------------  ----------------------
    031i.targetclone1      yes                  operator()(&body) (x4)
    051t.tailr1            yes                  operator()(&body)
    074i.targetclone2      yes                  operator()(&body)
    093i.sra (IPA-SRA)     -- (rewrites call)   &body -> &pp
    127t.threadfull1       yes                  operator().isra(&pp)
    128t.vrp1              yes                  operator().isra(&pp)
    130t.dse2              GONE                 operator().isra(&pp)
    final optimized        gone                 operator().isra(&pp)

Sequence of events:

  - The C++ frontend emits 'body = {.__pp = &pp}; operator()(&body)'.
  - IPA-SRA at pass 093i.sra splits the closure parameter and rewrites
    the call to 'operator().isra(&pp)'.
  - After the rewrite, 'body.__pp' has no remaining reader.
  - tree-ssa-dse pass 2 (130t.dse2) removes the now-dead store.

The final-optimized GIMPLE is correct on paper:

    pp = &p;
    __asm__ __volatile__("" : "=m,r" pp : "m,0" &p : "memory");
    gimple_call <operator().isra, NULL, &pp>     // raw IR: ADDR_EXPR of pp

But during RTL expand, '&pp' resolves to a stack slot 16 bytes off from
the slot that 'pp = &p' wrote to. The mismatch is consistent with
'body' and 'pp' being assigned to different slots that the post-IPA-SRA
code expected to be the same.

The pretty-printer shows '&pp' for the call argument, but RTL's lea
computes 'virtual-stack-vars - 72', while the store 'pp = &p' lowers
to 'mov %rbx, [virtual-stack-vars - 88]'. The slot allocator
(gcc/cfgexpand.cc) chose two different slots for what should be the
same variable.

Note: with -fno-tree-fre, the 'body.__pp = &pp' store survives (FRE
does not fold the dead store away), and 'body's slot at runtime does
hold &pp because '&body' and '&pp' collapse to the same stack address
under that compilation -- the lambda's first deref reads &pp, the
second deref then reads pp's actual value, and execution succeeds.
This is consistent with the slots being merged in some compilation
pipelines and not in others, depending on whether the dead store is
observable at expand time.


================================================================================
HYPOTHESIZED SOURCE LOCATION
================================================================================

We were unable to pinpoint the exact source line that introduces the
two-slots-for-one-variable behavior. Candidate locations, ranked by
likelihood:

  HIGH    gcc/cp/lambda.cc -- value-expr annotation propagation.
          The lambda's scope_block declares
              pp [value-expr: __closure->__pp]
          (visible in -fdump-tree-optimized).  After the closure is
          removed by IPA-SRA, this alias may be materialized as its own
          VAR_DECL with its own stack slot, instead of being collapsed
          into the captured variable's DECL.

  HIGH    gcc/cfgexpand.cc -- expand_used_vars / partition_stack_vars.
          Two stack slots for what should be one variable -- this is
          where DECLs map to slots.

  MEDIUM  gcc/ipa-param-manipulation.cc:692 --
          ipa_param_adjustments::modify_call, the SPLIT branch around
          line 858 (fold_build2_loc(loc, MEM_REF, type, base, off)).
          Synthesizes the new call argument; raw IR shows '&pp' not
          MEM_REF, but the substitution may go through a synthetic
          VAR_DECL that does not get remapped.

  MEDIUM  gcc/ipa-sra.cc:4160 -- process_isra_node_results then
          create_virtual_clone. The clone+caller-update path that
          calls modify_call.

The __tu_terminate_wrapper (gcc/cp/contracts.cc:2339-2393) is a
TRIGGER but not the defect itself: removing it changes the IPA-SRA
decision from parameter-splitting (.isra.0) to partial inlining
(.part.0), bypassing the buggy code path. The wrapper is correctly
emitted for its intended purpose (PR121936 mitigation).


================================================================================
PRE-FILING DILIGENCE
================================================================================

GCC bug filing guidelines ask for the following checks before
submission; all completed:

    -Wall -Wextra clean                                  yes
    -fno-strict-aliasing changes behavior?               no (still crashes)
    -fwrapv changes behavior?                            no
    -fno-aggressive-loop-optimizations changes behavior? no
    -fsanitize=address runtime-clean?                    yes
    -fsanitize=undefined runtime-clean?                  yes
    -D_GLIBCXX_ASSERTIONS changes behavior?              no (still crashes)
    Linked against rawhide libstdc++ 16
        (__GLIBCXX__ = 20260416)?                        yes
    Reproduces with system libstdc++ 15
        (forced via LD_LIBRARY_PATH)?                    yes (rules out lib
mismatch)
    Reproducer self-contained
        (no missing headers, no archive)?                yes -- two .cpp files
                                                              shipped together;
                                                              handler.cpp is
                                                              mandated by
                                                              libstdc++ when
                                                              -fcontracts is on


================================================================================
RELATED BUGS
================================================================================

PR121936 (open, NEW): "Invalid optimisation (at O3) based on bodies of
    vague linkage functions". Different mechanism (vague-linkage
    derefinement versus our IPA-SRA stack-slot split). The workaround
    for PR121936 (commit cac79586e1ab, the __tu_terminate_wrapper) is
    what causes IPA-SRA to select the buggy code path here, but the
    underlying issue is separate.
    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121936

PR124088 (open, UNCONFIRMED): "-fcontracts-conservative-ipa is
    unnecessary and wrong". Argues for removing the workaround for
    PR121936. The present defect is independent evidence that the
    workaround has its own problems.
    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124088

PR124648 (fixed): "Account for lambda captures in pre/post". The
    closest related fix in the contracts-frontend area; the present
    defect is in a different stage (IPA + RTL expand interaction).
    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124648


================================================================================
FILES SUPPLIED WITH THIS REPORT
================================================================================

    bug_minimal.cpp                -- 19-line minimal reproducer
    bug_realistic.cpp              -- same defect as a normal-looking
                                      microbenchmark
    handler.cpp                    -- handle_contract_violation definition
                                      (libstdc++ requires when -fcontracts
                                      is on)
    bug_minimal.preprocessed.ii    -- preprocessed bug_minimal.cpp
                                      (per GCC filing guidelines)
    bug_realistic.preprocessed.ii  -- preprocessed bug_realistic.cpp
    handler.preprocessed.ii        -- preprocessed handler.cpp
    gcc-v.txt                      -- output of g++ -v (per GCC filing
                                      guidelines)
    REPORT.md                      -- this file


================================================================================
DISCOVERY AND REDUCTION
================================================================================

A production microbenchmark using the do_not_optimize idiom on a
typed pointer-to-class crashed at -O3 only when the class's hot
method had a pre() precondition. Removing the clobber on the pointer
(while keeping it on the method's return value) eliminated the crash.
The 19-line form was reached through approximately 50 successive
reduction iterations, each toggling one source-level dimension
(struct layout, lambda capture mode, container choice, attribute set,
optimization level, or individual optimization passes via -fno-*
flags).

Reply via email to