https://gcc.gnu.org/bugzilla/show_bug.cgi?id=125707
--- Comment #5 from Kael Franco <kaelfandrew at gmail dot com> --- Comment on attachment 64700 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=64700 Proposed patch >From c3d7d4fe221e3940bd5957165f3e613f41962341 Mon Sep 17 00:00:00 2001 From: Kael Andrew Alonzo Franco <[email protected]> Date: Thu, 11 Jun 2026 14:56:26 -0400 Subject: [PATCH] match: Optimize (~a) >> a to -1 for signed a [PR125707] Since ~a is negative, then (~a) >> a is -1 since it set all the lower bits to one via >>. Bootstrapped and tested on x86_64-pc-linux-gnu PR tree-optimization/125707 gcc/ChangeLog: PR tree-optimization/125707 * match.pd: Add (~a) >> a to -1 for signed a. gcc/testsuite/ChangeLog: PR tree-optimization/125707 * gcc.dg/pr125707.c: New test. Signed-off-by: Kael Franco <[email protected]> --- gcc/match.pd | 7 +++++++ gcc/testsuite/gcc.dg/pr125707.c | 16 ++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 gcc/testsuite/gcc.dg/pr125707.c diff --git a/gcc/match.pd b/gcc/match.pd index e0d7ef80e14..ea4a447f081 100644 --- a/gcc/match.pd +++ b/gcc/match.pd @@ -1831,6 +1831,13 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT) && wi::to_wide (@1) != wi::min_value (TYPE_PRECISION (type), SIGNED)) (minus (plus @1 { build_minus_one_cst (type); }) @0)))) + +/* (~X) >> X -> -1 for signed X. */ +(simplify + (rshift (bit_not @0) (convert? @0)) + (if (INTEGRAL_TYPE_P (type) + && !TYPE_UNSIGNED (type)) + { build_minus_one_cst (type); })) #endif /* ~(X >> Y) -> ~X >> Y if ~X can be simplified. */ diff --git a/gcc/testsuite/gcc.dg/pr125707.c b/gcc/testsuite/gcc.dg/pr125707.c new file mode 100644 index 00000000000..7c1de1249c4 --- /dev/null +++ b/gcc/testsuite/gcc.dg/pr125707.c @@ -0,0 +1,16 @@ +/* { dg-do compile } */ +/* { dg-options "-O2 -fdump-tree-optimized" } */ + +int +rshift_bit_not_int_x_x (int x) +{ + return (~x) >> x; +} + +long +rshift_bit_not_long_x_x (long x) +{ + return (~x) >> x; +} + +/* { dg-final { scan-tree-dump-times "return -1;" 2 "optimized" } } */ -- 2.54.0
