]> git.ipfire.org Git - thirdparty/gcc.git/commit
i386: Optimize ptestz(x,-1) as ptestz(x,x) on x86
authorRoger Sayle <roger@nextmovesoftware.com>
Tue, 19 May 2026 11:29:08 +0000 (07:29 -0400)
committerRoger Sayle <roger@nextmovesoftware.com>
Tue, 19 May 2026 11:29:08 +0000 (07:29 -0400)
commita87cdfd2ca3260126d3c75ddfb5cdea6e721d8d0
treecb36348b3b326fcb7d8540a146f42209bfbdd3b9
parent90f2f90d2b5c3a2f156b649d717c7dad0ebf1bf0
i386: Optimize ptestz(x,-1) as ptestz(x,x) on x86

This patch, inspired by PR target/90483 and libstdc++/118416, implements
some RTL expansion-time simplifications of ptest. A common idiom for
testing a vector against zero is to use ptestz(mask,-1).  Alas the code
generated for this is suboptimal, requiring materialization of an all_ones
vector.  Given that ptestz(x,y) is defined as (x & y) == 0, an equivalent
form is ptestz(mask,mask), saving an instruction (if ~0 isn't available).

Consider the function:

typedef long long v2di __attribute__ ((__vector_size__ (16)));

int foo (v2di x)
{
  return __builtin_ia32_ptestz128(x,~(v2di){0,0});
}

with -O2 -mavx2, GCC currently generates:

foo: vpcmpeqd        %xmm1, %xmm1, %xmm1
        xorl    %eax, %eax
        vptest  %xmm1, %xmm0
        sete    %al
        ret

with this patch, it now generates:

foo: xorl    %eax, %eax
        vptest  %xmm0, %xmm0
        sete    %al
        ret

2026-05-19  Roger Sayle  <roger@nextmovesoftware.com>

gcc/ChangeLog
PR target/90483
PR libstdc++/118416
* config/i386/i386-expand.cc (ix86_expand_sse_ptest):  Refactor
with optimizations for PTESTZ*, PTESTC* and PTESTNZC*, including
transforming ptestz(x,-1) into ptestz(x,x).

gcc/testsuite/ChangeLog
PR target/90483
PR libstdc++/118416
* gcc.target/i386/sse4_1-ptest-8.c: New test case.
* gcc.target/i386/sse4_1-ptest-9.c: Likewise.
gcc/config/i386/i386-expand.cc
gcc/testsuite/gcc.target/i386/sse4_1-ptest-8.c [new file with mode: 0644]
gcc/testsuite/gcc.target/i386/sse4_1-ptest-9.c [new file with mode: 0644]