rust-lang / rust-lang/rust

Suboptimal code generation for array Element by Element replace/overwrite (Uneeded stores)

Open
#150,325 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-codegen A-LLVM C-optimization T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I noticed that the code generation on something I was working on was less than ideal. I was able to distill it down to some very simple examples here on compiler explorer: Compiler Explorer

I would expect the output to be similar to either test4() or test5() for the functions test1(), test2(), and test3().

For example here is test3():

fn test3(mut a: [u32; 3], b: &[u32; 3]) -> [u32;3] {
    *a.get_mut(0).unwrap() = b[0];
    *a.get_mut(1).unwrap() = b[1];
    *a.get_mut(2).unwrap() = b[2];
    return a;
}

The generated assembly is:

test3:
    mov rax, rdi
    mov rcx, qword ptr [rdx]
    mov qword ptr [rsi], rcx
    mov edx, dword ptr [rdx + 8]
    mov dword ptr [rsi + 8], edx
    mov dword ptr [rdi + 8], edx
    mov qword ptr [rdi], rcx
    ret

Where as if we look at test4() we can see that we can get rid of the spurious stores, by adding let mut a = a; What is interesting is this does nothing when using the index operator [], if you look at what I have on compiler explorer test2().

fn test4(mut a: [u32; 3], b: &[u32; 3]) -> [u32;3] {
    let mut a = a;
    *a.get_mut(0).unwrap() = b[0];
    *a.get_mut(1).unwrap() = b[1];
    *a.get_mut(2).unwrap() = b[2];
    return a;
}

The generated assembly for test4()

test4:
    mov rax, rdi
    mov ecx, dword ptr [rdx + 8]
    mov rdx, qword ptr [rdx]
    mov qword ptr [rdi], rdx
    mov dword ptr [rdi + 8], ecx
    ret

@rustbot label A-LLVM
@rustbot label C-optimization
@rustbot label A-codegen

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the test1() through test5() examples from the Compiler Explorer link and compare their generated assembly. Start by investigating the Rust codegen path for get_mut element assignments and the difference introduced by let mut a = a. Done means the unnecessary stores seen in test1(), test2(), and test3() are eliminated without changing the returned array.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
43/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.