Skip to content

Bad codegen when not using range in switch prong  #22100

@ghost

Description

Zig Version

0.14.0-dev.2273+73dcd1914

Steps to Reproduce and Observed Behavior

export fn a(x: u8) bool {
    return switch (x) {
        99, 1, 2 => true,
        else => false,
    };
}

export fn b(x: u8) bool {
    return switch (x) {
        99, 1...2 => true,
        else => false,
    };
}

The codegen for these two functions that clearly do the exact same thing differs, with the version not using ranges probably having inferior codegen:

a:
        mov     al, 1
        lea     ecx, [rdi - 1]
        cmp     ecx, 2
        jb      .LBB0_3
        cmp     edi, 99
        je      .LBB0_3
        xor     eax, eax
.LBB0_3:
        ret

b:
        cmp     edi, 99
        sete    cl
        lea     eax, [rdi - 1]
        cmp     al, 2
        setb    al
        or      al, cl
        ret

https://zig.godbolt.org/z/fhWK7vs9K

Expected Behavior

Both versions should compile down to the same optimal codegen.
This applies to multiple architectures in both ReleaseFast and ReleaseSmall.

Metadata

Metadata

Assignees

No one assigned

    Labels

    backend-llvmThe LLVM backend outputs an LLVM IR Module.bugObserved behavior contradicts documented or intended behavioroptimization

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions