Chains of checked_add could get better codegen
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Here are two slightly different but likely related codegen issues. (Note that I am not entirely comfortable with rust ABI convention so this may be total horseshit)
1
fn f(x: u64, y: u64) -> Option<u64> {
let Some(x) = x.checked_add(y) else {
return None;
};
let Some(x) = x.checked_add(y) else {
return None;
};
Some(x)
}
gets compiled to (notice the useless move)
f:
xor eax, eax
add rdi, rsi
jae .LBB0_2
;; This move is useless
mov rdx, rdi
ret
.LBB0_2:
add rdi, rsi
setae al
mov rdx, rdi
ret
2
fn f(x: u64, y: u64) -> Option<u64> {
let Some(x) = x.checked_add(y) else {
return None;
};
let Some(x) = x.checked_add(y) else {
return None;
};
let Some(x) = x.checked_add(y) else {
return None;
};
Some(x)
}
gets compiled to
f:
add rdi, rsi
jb .LBB0_1
add rdi, rsi
jae .LBB0_3
.LBB0_1:
xor eax, eax
mov rdx, rdi
ret
.LBB0_3:
xor eax, eax
add rdi, rsi
setae al
mov rdx, rdi
ret
But could be
f:
xor eax, eax
add rdi, rsi
jb .LBB0_1
add rdi, rsi
jb .LBB0_1
add rdi, rsi
setae al
mov rdx, rdi
ret
.LBB0_1:
ret
@rustbot label +A-codegen +A-LLVM +C-optimization +I-slow +S-has-mcve +I-heavy +T-compiler -needs-triage
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 with the Rust reproducer and compare the generated x86-64 assembly for the two- and three-check_add cases. Investigate the compiler codegen path responsible for checked_add chains; done when the generated control flow avoids the reported useless move and merges overflow paths as shown.
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
- 35/100