Skip to content

Commit 1ead476

Browse files
committed
Auto merge of #119878 - scottmcm:inline-always-unwrap, r=workingjubilee
Tune the inlinability of `unwrap` Fixes #115463 cc `@thomcc` This tweaks `unwrap` on ~~`Option` &~~ `Result` to be two parts: - `#[inline(always)]` for checking the discriminant - `#[cold]` for actually panicking The idea here is that checking the discriminant on a `Result` ~~or `Option`~~ should always be trivial enough to be worth inlining, even in `opt-level=z`, especially compared to passing it to a function. As seen in the issue and codegen test, this will hopefully help particularly for things like `.try_into().unwrap()`s that are actually infallible, but in a way that's only visible with the inlining. EDIT: I've restricted this to `Result` to avoid combining effects
2 parents 73252d5 + b858c59 commit 1ead476

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

library/core/src/result.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1061,7 +1061,7 @@ impl<T, E> Result<T, E> {
10611061
/// let x: Result<u32, &str> = Err("emergency failure");
10621062
/// x.unwrap(); // panics with `emergency failure`
10631063
/// ```
1064-
#[inline]
1064+
#[inline(always)]
10651065
#[track_caller]
10661066
#[stable(feature = "rust1", since = "1.0.0")]
10671067
pub fn unwrap(self) -> T
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// compile-flags: -C opt-level=z --edition=2021
2+
// ignore-debug
3+
4+
#![crate_type = "lib"]
5+
6+
// From <https://github.com/rust-lang/rust/issues/115463>
7+
8+
// CHECK-LABEL: @read_up_to_8(
9+
#[no_mangle]
10+
pub fn read_up_to_8(buf: &[u8]) -> u64 {
11+
// CHECK-NOT: unwrap_failed
12+
if buf.len() < 4 {
13+
// actual instance has more code.
14+
return 0;
15+
}
16+
let lo = u32::from_le_bytes(buf[..4].try_into().unwrap()) as u64;
17+
let hi = u32::from_le_bytes(buf[buf.len() - 4..][..4].try_into().unwrap()) as u64;
18+
lo | (hi << 8 * (buf.len() as u64 - 4))
19+
}
20+
21+
// CHECK-LABEL: @checking_unwrap_expectation(
22+
#[no_mangle]
23+
pub fn checking_unwrap_expectation(buf: &[u8]) -> &[u8; 4] {
24+
// CHECK: call void @_ZN4core6result13unwrap_failed17h
25+
buf.try_into().unwrap()
26+
}

0 commit comments

Comments
 (0)