[gcc r17-2812] match.pd: Optimize .PARITY (.BITREVERSE (x))

Jakub Jelinek via Gcc-cvs <[email protected]> Thu, 30 Jul 2026 07:59:13 +0000 (GMT)
Newsgroups gmane.comp.gcc.cvs
Message-ID <[email protected]>
https://gcc.gnu.org/g:1e5dca08d72f83a6c4ea3bcd2f7cc80bdfd6fc0b

commit r17-2812-g1e5dca08d72f83a6c4ea3bcd2f7cc80bdfd6fc0b
Author: Jakub Jelinek <[email protected]>
Date:   Thu Jul 30 09:53:50 2026 +0200

    match.pd: Optimize .PARITY (.BITREVERSE (x))
    
    When working on the last patch, I've noticed that the parity(bswap(x))
    optimization only optimizes the 16/32/64/128-bit bswaps, but not
    generic _BitInt bswap, and doesn't optimize any of the bitreverses.
    Both all bswap and all bitreverse builtins/ifns preserve values of all the
    bits, just permute them, so parity (and popcount too) can be optimized.
    
    2026-07-30  Jakub Jelinek  <[email protected]>
    
            * match.pd (parity(bswap(x)) is parity(x)): Use BSWAP BITREVERSE
            instead of BUILT_IN_BSWAP16 BUILT_IN_BSWAP32 BUILT_IN_BSWAP64
            BUILT_IN_BSWAP128.
    
            * gcc.dg/bitint-140.c: New test.
    
    Reviewed-by: Richard Biener <[email protected]>

Diff:
---
 gcc/match.pd                      |  3 +--
 gcc/testsuite/gcc.dg/bitint-140.c | 17 +++++++++++++++++
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/gcc/match.pd b/gcc/match.pd
index d6702f66733d..3658a355c40c 100644
--- a/gcc/match.pd
+++ b/gcc/match.pd
@@ -10758,8 +10758,7 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
 
 /* parity(bswap(x)) is parity(x).  */
 (for parity (PARITY)
-  (for bswap (BUILT_IN_BSWAP16 BUILT_IN_BSWAP32
-	      BUILT_IN_BSWAP64 BUILT_IN_BSWAP128)
+  (for bswap (BSWAP BITREVERSE)
     (simplify
       (parity (convert?@0 (bswap:s@1 @2)))
       (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
diff --git a/gcc/testsuite/gcc.dg/bitint-140.c b/gcc/testsuite/gcc.dg/bitint-140.c
new file mode 100644
index 000000000000..35550830d9d3
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/bitint-140.c
@@ -0,0 +1,17 @@
+/* { dg-do compile { target bitint575 } } */
+/* { dg-options "-O2 -fdump-tree-cplxlower1" } */
+/* { dg-final { scan-tree-dump-not "\.BSWAP \\\(" "cplxlower1" } } */
+/* { dg-final { scan-tree-dump-not "\.BITREVERSE \\\(" "cplxlower1" } } */
+/* { dg-final { scan-tree-dump-times "\.PARITY \\\(x_" 2 "cplxlower1" } } */
+
+int
+foo (unsigned _BitInt(512) x)
+{
+  return __builtin_parityg (__builtin_bswapg (x));
+}
+
+int
+bar (unsigned _BitInt(575) x)
+{
+  return __builtin_parityg (__builtin_bitreverseg (x));
+}