You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`cold_path` is becoming stable [1] in the upcoming Rust 1.95.0 (expected
2026-04-16).
`cold_path()` can be used directly, but it also allows us to provide
`likely()` and `unlikely()`, based on `cold_path()`, similar to the C
side ones.
For instance, given:
fn f1(a: i32) -> i32 {
if a < 0 {
return 123;
}
42
}
fn f2(a: i32) -> i32 {
if likely(a < 0) {
return 124;
}
42
}
fn f3(a: i32) -> i32 {
if unlikely(a < 0) {
return 125;
}
42
}
LLVM emits the same code it would for similar C functions:
f1:
test %edi,%edi
mov $0x7b,%ecx
mov $0x2a,%eax
cmovs %ecx,%eax
ret
f2:
mov $0x7c,%eax
test %edi,%edi
/-- jns <f2+0xa>
| ret
\-> mov $0x2a,%eax
ret
f3:
test %edi,%edi
/-- js <f3+0xa>
| mov $0x2a,%eax
| ret
\-> mov $0x7d,%eax
ret
The feature itself, `feature(cold_path)`, was added in Rust 1.86.0
[2]. For context, Rust 1.85.0 is likely going to be our next minimum
supported version.
Previously, a PR in Rust 1.84.0 [3] fixed a number of issues with the
`likely()` and `unlikely()` intrinsics (by implementing them on top of
the new `cold_path()` intrinsic).
Thus add support for `cold_path()` by applying several approaches:
- For Rust >= 1.86.0, `use` directly `core`'s `cold_path()`.
- For Rust >= 1.84.0, we could choose to provide a no-op, but given Rust
1.85.0 will likely be our next minimum, do some effort to support the
feature by vendoring `core`'s implementation based on the intrinsic.
- For older versions, provide a no-op implementation since it is simpler
(there was no `cold_path()` intrinsic), since the other intrinsics
(`{,un}likely()`) were fixed later and since we will bump the minimum
soon anyway.
And, for all versions, simply provide `likely()` and `unlikely()` based
on `cold_path()`, by vendoring `core`'s version (saving a layer using
the intrinsics implementation).
In the future, if `likely()` and `unlikely()` become stable, we may want
to use them directly as well.
Now, in the C side, the `likely()` and `unlikely()` macros come
from `compiler.h`, which means it is pretty much available everywhere
directly. Thus just add these to the prelude (instead of e.g. re-exporting
them in the root or in a new `hint` module).
This will also mean less churn when we can remove the `cold_path()`
version from `std_vendor` (and potentially the other two too).
I tested that Rust 1.84.1 and 1.93.0 both generate the code above,
and that Rust 1.83.0 and 1.78.0 do not, as expected.
Link: rust-lang/rust#151576 [1]
Link: rust-lang/rust#133695 [2]
Link: rust-lang/rust#120370 [3]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
0 commit comments