Skip to content

Commit

Permalink
Auto merge of #81354 - SkiFire13:binary-search-assume, r=nagisa
Browse files Browse the repository at this point in the history
Instruct LLVM that binary_search returns a valid index

This allows removing bound checks when the return value of `binary_search` is used to index into the slice it was call on. I also added a codegen test for this, not sure if it's the right thing to do (I didn't find anything on the dev guide), but it felt so.
  • Loading branch information
bors committed Mar 28, 2021
2 parents 3bfc851 + c9d04c2 commit 1df2056
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,8 @@ impl<T> [T] {
} else if cmp == Greater {
right = mid;
} else {
// SAFETY: same as the `get_unchecked` above
unsafe { crate::intrinsics::assume(mid < self.len()) };
return Ok(mid);
}

Expand Down
19 changes: 19 additions & 0 deletions src/test/codegen/binary-search-index-no-bound-check.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// min-llvm-version: 11.0.0
// compile-flags: -O
// ignore-debug: the debug assertions get in the way
#![crate_type = "lib"]

// Make sure no bounds checks are emitted when slicing or indexing
// with an index from `binary_search`.

// CHECK-LABEL: @binary_search_index_no_bounds_check
#[no_mangle]
pub fn binary_search_index_no_bounds_check(s: &[u8]) -> u8 {
// CHECK-NOT: panic
// CHECK-NOT: slice_index_len_fail
if let Ok(idx) = s.binary_search(&b'\\') {
s[idx]
} else {
42

This comment has been minimized.

Copy link
@MrIceman

MrIceman Mar 28, 2021

what does this 42 mean?

}
}

0 comments on commit 1df2056

Please sign in to comment.