Skip to content

Inefficient code generation: bitwise AND of disjoint booleans from equal and bitwise AND may not be optimized to constant 0 #56294

Closed
@pmor13

Description

@pmor13

clang -O3 optimizes this code:

_Bool f1(char x)
{
    _Bool b1 = x == 4;
    _Bool b2 = x & 3;
    return b1 & b2;
}

to:

f1:
        xor     eax, eax
        ret

However, clang -O3 does not optimize this code:

_Bool f1(char x)
{
    _Bool b1 = x == 2;
    _Bool b2 = x & 1;
    return b1 & b2;
}
f1:
        cmp     dil, 2
        sete    al
        and     al, dil
        ret

Why?

Note: the & b1 & b2 is used intentionally. If && is used, then clang -O3 optimizes it to:

f1:
        xor     eax, eax
        ret

How it can be explained?

Extra: if #define LOGIC_AND is uncommitted here, then the whole program transfers into a no-op. Courtesy of Lundin.

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