Skip to content

Compiler cannot remove unneccessary loop in case of unwrap_unchecked and Vec collect() optimization #91194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
AngelicosPhosphoros opened this issue Nov 24, 2021 · 2 comments
Labels
C-bug Category: This is a bug.

Comments

@AngelicosPhosphoros
Copy link
Contributor

I tried this code:

pub fn unwrap_all(vv: Vec<Option<Box<i32>>>)->Vec<Box<i32>>{
    vv
        .into_iter()
        .map(|x| unsafe{
            x.unwrap_unchecked()
        })
        .collect()
}

I expected to see this happen: code compiles into noop essentially, like transmute.

Expected code
example::unwrap_all_transmute:
        mov     rax, rdi
        mov     rcx, qword ptr [rsi + 16]
        mov     qword ptr [rdi + 16], rcx
        movups  xmm0, xmmword ptr [rsi]
        movups  xmmword ptr [rdi], xmm0
        ret

Instead, this happened: code iterates over the vec without toching real backing buffer. This is a loop without side effects so it should be removed by LLVM.

Generated code
example::unwrap_all:
        mov     rax, rdi
        mov     rcx, qword ptr [rsi]
        mov     r8, qword ptr [rsi + 8]
        mov     rdi, qword ptr [rsi + 16]
        mov     rsi, rcx
        test    rdi, rdi
        je      .LBB0_8
        lea     r9, [8*rdi - 8]
        mov     edx, r9d
        shr     edx, 3
        add     edx, 1
        and     rdx, 7
        je      .LBB0_2
        neg     rdx
        mov     rsi, rcx
.LBB0_4:
        add     rsi, 8
        inc     rdx
        jne     .LBB0_4
        cmp     r9, 56
        jae     .LBB0_6
        jmp     .LBB0_8
.LBB0_2:
        mov     rsi, rcx
        cmp     r9, 56
        jb      .LBB0_8
.LBB0_6:
        lea     rdx, [rcx + 8*rdi]
.LBB0_7:
        add     rsi, 64
        cmp     rsi, rdx
        jne     .LBB0_7
.LBB0_8:
        sub     rsi, rcx
        sar     rsi, 3
        mov     qword ptr [rax], rcx
        mov     qword ptr [rax + 8], r8
        mov     qword ptr [rax + 16], rsi
        ret

Meta

rustc --version --verbose:

rustc 1.58.0-nightly (936f2600b 2021-11-22)

Godbolt link with code

@AngelicosPhosphoros AngelicosPhosphoros added the C-bug Category: This is a bug. label Nov 24, 2021
@the8472
Copy link
Member

the8472 commented Nov 24, 2021

dup of #79308

@AngelicosPhosphoros
Copy link
Contributor Author

Yeah, forgot about those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: This is a bug.
Projects
None yet
Development

No branches or pull requests

2 participants