Missed optimization with Option
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
#[unsafe(no_mangle)]
pub fn f(x: &mut Option<u32>) {
let mut y = *x;
y = y.map(|a| a + 1);
*x = y;
}
#[unsafe(no_mangle)]
pub fn g(x: &mut Option<u32>) {
let mut y = *x;
if let Some(a) = &mut y {
*a += 1;
}
*x = y;
}
I expected both code to generate the same assembly, but instead I got the following with -Copt-level=3 (Godbolt):
f:
inc dword ptr [rdi + 4]
ret
g:
mov eax, dword ptr [rdi]
add dword ptr [rdi + 4], eax
ret
Since both functions are unconditionally doing a typed copy to *x, the compiler should be free to mutate the uninitialized bytes in a None value.
Meta
Godbolt compiler version:
rustc 1.94.0-nightly (fa5eda19b 2025-12-12)
binary: rustc
commit-hash: fa5eda19b95201468f5b1c5c035ec2fc06fccd66
commit-date: 2025-12-12
host: x86_64-unknown-linux-gnu
release: 1.94.0-nightly
LLVM version: 21.1.5
Internal compiler ID: nightly
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing functions f and g from the issue with rustc 1.94.0-nightly and -Copt-level=3, then compare their generated assembly through the linked Godbolt example. The report names no repository file or test entry point; done means identifying and correcting the missed optimization so the two equivalent cases compile to equivalent efficient code.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers, performance
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100