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

            Bug ID: 128038
           Summary: x86-64: redundant byte cast causes duplicate offset
                    masking
           Product: gcc
           Version: 16.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: adamant.pwn at gmail dot com
  Target Milestone: ---
            Target: x86_64-pc-linux-gnu

A redundant unsigned-char cast makes GCC compute the same offset mask twice in
this packed-integer read:

using u64 = unsigned long long;
u64 read(u64 const *data, u64 bit, unsigned char width, u64 const *masks) {
    unsigned offset = static_cast<unsigned char>(bit % 64);
    u64 value = data[bit / 64] >> offset;
    if (offset <= 64 - width)
        return value & masks[width];
    u64 high = data[bit / 64 + 1] & masks[offset + width - 64];
    return value | ((high >> offset) | (high << ((-offset) & 63)));
}

Compile with:
g++ -std=c++20 -O3 -march=haswell -S repro.cpp

The generated code computes both r10d = esi & 63 and ecx = esi & 63. The former
is used for the boundary comparison and mask index; the latter for the
shifts/rotate. One masked offset should suffice.

Removing static_cast<unsigned char> from the offset initialization leaves one
AND with local GCC 16.2.1. The cast cannot change the value because bit % 64 is
already in [0, 63].

Reproduced on x86-64 with GCC 16.2.1 20260810, Compiler Explorer GCC 16.2.0,
and GCC trunk 17.0.0 20261020 (26fca5456858ed8ef78eaae4d45beb183471a78f). No
diagnostics. The testcase has no includes.

Local compiler configuration (g++ -v):
Using built-in specs.
COLLECT_GCC=/usr/bin/g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/16/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: ../gcc/configure
--enable-languages=ada,c,c++,d,fortran,go,lto,m2,objc,obj-c++,rust,cobol
--enable-bootstrap --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib
--mandir=/usr/share/man --infodir=/usr/share/info
--with-bugurl=https://github.com/CachyOS/CachyOS-PKGBUILDS/issues
--with-build-config=bootstrap-lto --with-gcc-major-version-only
--with-linker-hash-style=gnu --with-system-zlib --enable-cet=auto
--enable-checking=release --enable-clocale=gnu --enable-default-pie
--enable-default-ssp --enable-gnu-indirect-function --enable-gnu-unique-object
--enable-libstdcxx-backtrace --enable-link-serialization=1
--enable-linker-build-id --enable-lto --enable-multilib --enable-plugin
--enable-shared --enable-threads=posix --disable-fixincludes --disable-libssp
--disable-libstdcxx-pch --disable-werror
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 16.2.1 20260810 (GCC) 

Assisted by OpenAI Codex and Anthropic Claude.
  • [Bug rtl-optimization/128038] Ne... adamant.pwn at gmail dot com via Gcc-bugs

Reply via email to