Skip to content

(a < 2 and b < 2) should be optimized to (a | b) < 2 #77432

Closed as not planned
Closed as not planned
@Validark

Description

@Validark

Update: This logic gets optimized properly in C, but not Zig. Maybe this has to do with the LLVM bitcode that Zig produces?

https://zig.godbolt.org/z/6GTxKMvoP


Currently, this code gets emitted naïvely:

export fn foo(a: u32, b: u32) bool {
    return a < 2 and b < 2;
}

This can be optimized to:

export fn foo(a: u32, b: u32) bool {
    return (a | b) < 2;
}

Reasoning: since a and b must be 0 and/or 1 for the condition to be true, then the bitwise OR of these must also be 0 or 1 for the condition to be true. 2 could be substituted for other powers of 2, and would be applicable for any amount of numbers being checked with an AND between them.

E.g. (a < 8 and b < 8 and c < 8 and d < 8) -> (a | b | c | d) < 8

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions