https://gcc.gnu.org/g:b3ade4e315e5bab56eced1e22eceabbf1a8f15c4

commit r17-1527-gb3ade4e315e5bab56eced1e22eceabbf1a8f15c4
Author: Kael Andrew Alonzo Franco <[email protected]>
Date:   Fri Jun 12 05:55:56 2026 -0400

    match: Optimize (~a) >> a to -1 for signed a [PR125707]
    
    For signed a, (~a) >> a is the same as ~(a>>a) which is ~0 aka -1.
    
    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]>

Diff:
---
 gcc/match.pd                    |  7 +++++++
 gcc/testsuite/gcc.dg/pr125707.c | 16 ++++++++++++++++
 2 files changed, 23 insertions(+)

diff --git a/gcc/match.pd b/gcc/match.pd
index e0d7ef80e14d..ea4a447f0814 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 000000000000..7c1de1249c40
--- /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" } } */

Reply via email to