Skip to content

Missed optimization for unused zero-initialized vectors #90032

Closed
@Herohtar

Description

@Herohtar

Optimization doesn't seem to happen for unused zero-initialized vectors.

If I write a method that initializes a Vec with a non-zero value and call it a couple of times from main(), then when I build with --release (-O3) the compiler optimizes everything away into effectively a no-op:

Code

fn allocate() {
    let _a = vec![1; 100];
}

pub fn main() {
    allocate();
    allocate();
}

Output

example::main:
        ret

Godbolt link

However, if I instead initialize it with zero, the result is drastically different:

Code

fn allocate() {
    let _a = vec![0; 100];
}

pub fn main() {
    allocate();
    allocate();
}

Output

example::main:
        push    rax
        mov     edi, 400
        mov     esi, 4
        call    qword ptr [rip + __rust_alloc_zeroed@GOTPCREL]
        test    rax, rax
        je      .LBB0_2
        mov     esi, 400
        mov     edx, 4
        mov     rdi, rax
        call    qword ptr [rip + __rust_dealloc@GOTPCREL]
        mov     edi, 400
        mov     esi, 4
        call    qword ptr [rip + __rust_alloc_zeroed@GOTPCREL]
        test    rax, rax
        je      .LBB0_2
        mov     esi, 400
        mov     edx, 4
        mov     rdi, rax
        pop     rax
        jmp     qword ptr [rip + __rust_dealloc@GOTPCREL]
.LBB0_2:
        mov     edi, 400
        mov     esi, 4
        call    qword ptr [rip + alloc::alloc::handle_alloc_error@GOTPCREL]
        ud2

Godbolt link

Meta

rustc --version --verbose:

rustc 1.57.0-nightly (4e89811b4 2021-10-16)
binary: rustc
commit-hash: 4e89811b46323f432544f9c4006e40d5e5d7663f
commit-date: 2021-10-16
host: x86_64-unknown-linux-gnu
release: 1.57.0-nightly
LLVM version: 13.0.0

I tried out a few different rustc versions on Godbolt and it seems the behavior started in 1.18.0 -- before that, the zero-initialized code gets optimized away as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-bugCategory: This is a bug.I-slowIssue: Problems and improvements with respect to performance of generated code.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions