llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

GlobalOptPass turns global that only takes two values into a bool even if the values can be represented by a byte on the target

Open xor-shift opened this issue 6 months ago • 2 comments

The following program:

static int v;

void maybe_called_from_another_tu() {
    v = 123;
}

int main() {
    return v;
}

gets compiled into:

maybe_called_from_another_tu:
        mov     byte ptr [rip + v], 1
        ret

main:
        xor     ecx, ecx
        cmp     byte ptr [rip + v], 0
        mov     eax, 123
        cmove   eax, ecx
        ret

even though it could've been:

maybe_called_from_another_tu:
        mov     byte ptr [rip + v], 123
        ret

main:
        movzx     eax, byte ptr [rip + v]
        ret

This optimisation would and does make more sense if the value written was greater than 255 but the i32 turning into an i1 doesn't make sense to me when it ends up being stored as an i8 that could've stored the actual value in this case.

godbolt: https://godbolt.org/z/EsoabcGWP

xor-shift avatar May 25 '26 08:05 xor-shift

@llvm/issue-subscribers-clang-codegen

Author: Uygar (xor-shift)

The following program:
static int v;

void maybe_called_from_another_tu() {
    v = 123;
}

int main() {
    return v;
}

gets compiled into:

maybe_called_from_another_tu:
        mov     byte ptr [rip + v], 1
        ret

main:
        xor     ecx, ecx
        cmp     byte ptr [rip + v], 0
        mov     eax, 123
        cmove   eax, ecx
        ret

even though it could've been:

maybe_called_from_another_tu:
        mov     byte ptr [rip + v], 123
        ret

main:
        movzx     eax, byte ptr [rip + v]
        ret

This optimisation would and does make more sense if the value written was greater than 255 but the i32 turning into an i1 doesn't make sense to me when it ends up being stored as an i8 that could've stored the actual value in this case.

godbolt: https://godbolt.org/z/EsoabcGWP

hey can you assign this to me??

AnkitDubeycs25 avatar May 25 '26 13:05 AnkitDubeycs25