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

            Bug ID: 109992
           Summary: Addition/subtraction to the last bitfield of a struct
                    can be optimized
           Product: gcc
           Version: 14.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lh_mouse at 126 dot com
  Target Milestone: ---

For an unsigned bit field:
```
struct foo
  {
    unsigned a :  3;
    unsigned b : 29;
  };

void
bad_add(struct foo* p, unsigned add)
  {
    p->b += add;
  }
```

GCC:
```
bad_add:
        mov     eax, DWORD PTR [rdi]
        mov     edx, eax
        and     eax, 7
        shr     edx, 3
        add     edx, esi
        sal     edx, 3
        or      eax, edx
        mov     DWORD PTR [rdi], eax
        ret
```

Clang:
```
bad_add:                                # @bad_add
        shl     esi, 3
        add     dword ptr [rdi], esi
        ret
```

It looks like GCC extracts the bitfield first, performs the addition, then
inserts it back.

The result is almost the same for a signed bitfield, but not exacting the
bitfield first is subject to overflows, so it may be a different story.

Reply via email to