RFR: 8332856: C2: Add new transform for bool eq/ne (cmp (and (urshift X const1) const2) 0) [v2]

Tobias Hotz duke at openjdk.org
Sat Jun 22 12:51:15 UTC 2024


On Tue, 28 May 2024 20:11:35 GMT, Tobias Hotz <duke at openjdk.org> wrote:

>> This PR adds a new ideal optimization for the following pattern:
>> 
>> public boolean testFunc(int a) {
>>     int mask = 0b101;
>>     int shift = 12;
>>     return ((a >> shift) & mask) == 0;
>> }
>> 
>> Where the mask and shift are constant values and a is a variable. For this optimization to work, the right shift has to be idealized to a unsinged right shift earlier in the pipeline, which here: https://github.com/openjdk/jdk/blob/b92bd671835c37cff58e2cdcecd0fe4277557d7f/src/hotspot/share/opto/mulnode.cpp#L731
>> If the shift is already an unsiged bit shift, it works as well.
>> On AMD64 CPUs, this means that this whole line computation can be reduced to a simple `test` instruction.
>
> Tobias Hotz has updated the pull request incrementally with two additional commits since the last revision:
> 
>  - LF endings...
>  - Add a benchmark to measure effect of new ideal transformation

Implementing this in the backend is a bit harder, as it can't just match `(AndI(ShiftI x const1) const2)`, because (as previously said) the transform is only valid if that result is used for bool eq/ne operations.
Also, I'm not sure if the transformation would does not make sense for RISC targets in many (or most) cases. Looking at gcc and clang output for Arm64 and RISC-V, identical transformations are sometimes used (and sometimes not). See https://godbolt.org/z/oK3r3z7T7

IMO, it could make sense to apply this optimization here and maybe add some backend-specific enhancements for RISC-V and/or Arm64 that emit better instructions for some specific constants with AND, as this would allow better code gen on other patterns as well. But this is not the scope for this PR.
I unfortunally do not own any RISC machine I can test this on nor do I have any deeper knowledge about the topic, so more thoughts on this would be appreciated.

-------------

PR Comment: https://git.openjdk.org/jdk/pull/19310#issuecomment-2184020786


More information about the hotspot-compiler-dev mailing list