Skip to content

Assembly for Rc::<str>::default() looks quite inefficient #135784

Closed
@jhorstmann

Description

@jhorstmann

I tried this code:

#[no_mangle]
pub fn rc_str() -> std::rc::Rc<str> {
    std::rc::Rc::<str>::default()
}

I expected this to allocate with a known layout and and handle potential allocation errors.

Instead, before the allocation, the assembly contains not one, but two calls to rc_inner_layout_for_value_layout (indirect via call r15) (compiler explorer):

rc_str:
        push    r15
        push    r14
        push    rbx
        mov     r15, qword ptr [rip + alloc::rc::rc_inner_layout_for_value_layout::h02e271ca20ae9f03@GOTPCREL]
        mov     edi, 1
        xor     esi, esi
        call    r15
        mov     rbx, rax
        mov     r14, rdx
        mov     edi, 1
        xor     esi, esi
        call    r15
        test    rdx, rdx
        je      .LBB0_2
        mov     rcx, qword ptr [rip + __rust_no_alloc_shim_is_unstable@GOTPCREL]
        movzx   ecx, byte ptr [rcx]
        mov     rdi, rdx
        mov     rsi, rax
        call    qword ptr [rip + __rust_alloc@GOTPCREL]
.LBB0_2:
        test    rax, rax
        je      .LBB0_4
        mov     qword ptr [rax], 1
        mov     qword ptr [rax + 8], 1
        xor     edx, edx
        pop     rbx
        pop     r14
        pop     r15
        ret
.LBB0_4:
        mov     rdi, rbx
        mov     rsi, r14
        call    qword ptr [rip + alloc::alloc::handle_alloc_error::ha0642996a160fa99@GOTPCREL]

The two calls seem to correspond to the source code (line 257 and 2076), but I would have expected the compiler to be smart enough to see those should be the same, and even to compute that value at compile time.

Meta

rustc --version --verbose:

rustc 1.86.0-nightly (6067b3631 2025-01-17)
binary: rustc
commit-hash: 6067b36314ab5eb2eb47cecc464545ba58e1ad24
commit-date: 2025-01-17
host: x86_64-unknown-linux-gnu
release: 1.86.0-nightly
LLVM version: 19.1.7
Compiler returned: 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions