Open
Description
Consider following function:
pub fn foo(mut a: Vec<u64>) -> Vec<u64> {
let val = 15;
if let Err(idx) = a.binary_search(&val) {
a.insert(idx, val);
}
a
}
On current rust 1.61.0 you can expect following output:
...
.LBB3_12:
mov rdi, rbx
mov rsi, r12
call qword ptr [rip + alloc::vec::Vec<T,A>::insert::assert_failed@GOTPCREL]
ud2
...
It would be nice to have some attribute or other way of saying that binary search is always returning a valid insert index and bounds check should be eliminated. You can get an expected output in current rustc versions via:
pub fn foo(mut a: Vec<u64>) -> Vec<u64> {
let val = 15;
if let Err(idx) = a.binary_search(&val) {
if idx > a.len() {
unsafe { std::hint::unreachable_unchecked() };
}
a.insert(idx, val);
}
a
}
Since performing a search and then inserting is one of main binary_search
use cases it might be worthwhile to implement such an optimization.
See godbolt link for a whole example
Metadata
Metadata
Assignees
Labels
Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.Category: An issue highlighting optimization opportunities or PRs implementing suchIssue: Problems and improvements with respect to performance of generated code.Relevant to the compiler team, which will review and decide on the PR/issue.