Bug 125104 - `(a & ~CST) ^ CST` -> `a | CST`
Summary: `(a & ~CST) ^ CST` -> `a | CST`
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 16.0
: P3 enhancement
Target Milestone: 17.0
Assignee: Not yet assigned to anyone
URL:
Keywords: easyhack, missed-optimization, TREE
Depends on:
Blocks:
 
Reported: 2026-04-30 08:05 UTC by Drea Pinski
Modified: 2026-05-24 16:31 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2026-04-30 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Drea Pinski 2026-04-30 08:05:36 UTC
Take:
```
int f1(int a, int b)
{
  a &= ~1;
  a ^= 1;
  return a;
}
```

We don't optimize this at the gimple level to just `a | 1`.


If we had `|=` instead of `^=`. The match pattern:
```
 /* (~x | y) & x -> x & y */
 /* (~x & y) | x -> x | y */
 (simplify
  (bitop:c (rbitop:c @2 @1) @0)
  (with { bool wascmp; }
   (if (bitwise_inverted_equal_p (@0, @2, wascmp)
        && (!wascmp || element_precision (type) == 1))
    (bitop @0 @1))))

```

Is hit.
Comment 1 Richard Biener 2026-04-30 10:48:15 UTC
Confirmed.
Comment 2 GCC Commits 2026-05-24 16:31:13 UTC
The trunk branch has been updated by Andrew Pinski <pinskia@gcc.gnu.org>:

https://gcc.gnu.org/g:365e5618bc6fcb62560450677e0fe4f5ba96345e

commit r17-705-g365e5618bc6fcb62560450677e0fe4f5ba96345e
Author: Raven Hallsby <karl@hallsby.com>
Date:   Sat May 23 21:09:16 2026 -0500

    match: Optimize `(~y & x) ^ y` into (y | x) [PR125104]
    
    Despite a similar rule existing earlier in match.pd, this simplify
    rule is needed because the front-end (before pass 006.original)
    performs trivial constant optimizations, such as ~1 -> -2 on
    integers (at least those defined as `int`).
    
            PR tree-optimization/125104
    
    gcc/ChangeLog:
    
            * match.pd (`(~y & x) ^ y`): New Pattern.
    
    gcc/testsuite/ChangeLog:
    
            * gcc.dg/tree-ssa/pr125104.c: New test.
Comment 3 Drea Pinski 2026-05-24 16:31:52 UTC
Fixed.