https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128820
Bug ID: 128820
Summary: fold-mem-offsets: a memory-to-memory move keeps a
stale destination offset
Product: gcc
Version: 16.2.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: rtl-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: bernie at codewiz dot org
Target Milestone: ---
Created attachment 66202
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=66202&action=edit
proposed patch
fold-mem-offsets miscompiles a memory-to-memory move whose destination
address uses a register defined by an add the pass folds.
get_fold_mem_root (get_fold_mem_offset_root on trunk) returns the source
MEM of such a move, so the insn is a root for its source operand only.
The checks on the uses of a folded register don't look at which operand
of a root the register appears in, so an add feeding the destination's
base register is folded and deleted, the new offset goes into the other
root insns, and the destination keeps its old displacement: the store
lands at the wrong address.
Seen on m68k, which has memory-to-memory moves, at -O2. Two independent
cases on m68k-amigaos (gcc 16.2, AmigaPorts and bebbo's ports):
1. A compound literal stored on the stack, reduced from a printf
implementation: two of three stores got the folded frame offset and
the third, move.l (a1),N(a0), stayed at its old displacement, below
the stack pointer. The attached test is this case.
2. At -O2 -m68040 or -m68060, p = out + here + 8 folded into four byte
stores through p, one of them move.b (a1),2(a0), which kept 2 where
10 is correct.
-fno-fold-mem-offsets avoids both. I haven't reproduced either with an
m68k-linux-gnu cross compiler, whose register allocation addresses these
stores without a separate add, so there is no add for the pass to fold.
PR113357 (m68k-linux-gnu bootstrap miscompiles tree-switch-conversion.cc,
bisected to r14-4664, gone with -fno-fold-mem-offsets) shows the same
kind of symptom, a deleted lea feeding a store, and may be this bug, but
I haven't confirmed it.
The proposed patch has been carried by AmigaPorts' gcc since October 2026:
https://github.com/AmigaPorts/gcc/commit/1e6714c8f37
Testing: trunk with the patch builds as an m68k-linux-gnu cross compiler
and compiles the tests; the new test passes on x86_64 at -O0 to -O3 and -Os.
Not yet: a bootstrap and regtest on a primary target, and an m68k run of
the testsuite.