Skip to content

Non-optimal derived PartialEq for POD struct #41839

@jwilm

Description

@jwilm

Given a struct like

pub struct Foo {
    a: bool,
    b: bool,
    c: bool,
    d: bool
}

I would expect generated asm to be doing a dword comparison to check for equality. However, that's not what is seen unless explicitly transmuting before the comparison (interactive: https://godbolt.org/g/kYPaOh).

The PartialEq implementation looks something like:

pub fn eq(a: &Foo, b: &Foo) -> bool {
  a.a == b.a &&
    a.b == b.b &&
    a.c == b.c &&
    a.d == b.d
}

which produces the assembly:

example::eq:
        push    rbp
        mov     rbp, rsp
        mov     al, byte ptr [rdi]
        cmp     al, byte ptr [rsi]
        jne     .LBB0_1
        mov     al, byte ptr [rdi + 1]
        cmp     al, byte ptr [rsi + 1]
        jne     .LBB0_1
        mov     al, byte ptr [rdi + 2]
        cmp     al, byte ptr [rsi + 2]
        jne     .LBB0_1
        mov     cl, byte ptr [rdi + 3]
        mov     al, 1
        cmp     cl, byte ptr [rsi + 3]
        je      .LBB0_3
.LBB0_1:
        xor     eax, eax
.LBB0_3:
        pop     rbp
        ret

An optimized version using transmute (Rust):

pub fn eq_transmute(a: &Foo, b: &Foo) -> bool {
    unsafe {
        transmute_copy::<_, u32>(a) == transmute_copy::<_, u32>(b)
    }
}

produces the assembly:

example::eq_transmute:
        push    rbp
        mov     rbp, rsp
        mov     eax, dword ptr [rdi]
        cmp     eax, dword ptr [rsi]
        sete    al
        pop     rbp
        ret

Is this an optimization we should expect to be handled automatically?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-enhancementCategory: An issue proposing an enhancement or a PR with one.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchE-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.I-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions