Skip to content

Optimization: If (x & y) == y then (x - y) == (x xor y) == (x & ~y) #155187

@Explorer09

Description

@Explorer09

This is an optimization feature request.

For unsigned integers x and y, if it's checked in a conditional that (x & y) == y, then the three expressions (x - y), (x xor y) and (x & ~y) should equal to each other. The compiler should be able to emit any of the three forms in assembly, looking at which takes the least clock cycles or which is the smallest in code size.

Note that Clang is already able to optimize the condition (x & y) == y to (~x & y) == 0.

#include <stdlib.h>
unsigned int test1(unsigned int x, unsigned int y) {
    if ((x & y) == y)
        return x - y;
    abort();
}
unsigned int test2(unsigned int x, unsigned int y) {
    if ((x & y) == y)
        return x ^ y;
    abort();
}
unsigned int test3(unsigned int x, unsigned int y) {
    if ((x & y) == y)
        return x & ~y;
    abort();
}

Update: The same bug report in GCC

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions