Skip to content

Commit 3965209

Browse files
committed
Add hint::assert_unchecked
1 parent 5c97719 commit 3965209

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

library/core/src/hint.rs

+36
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,42 @@ pub const unsafe fn unreachable_unchecked() -> ! {
106106
}
107107
}
108108

109+
/// Makes a *soundness* promise to the compiler that `cond` holds.
110+
///
111+
/// This may allow the optimizer to simplify things,
112+
/// but it might also make the generated code slower.
113+
/// Either way, calling it will most likely make compilation take longer.
114+
///
115+
/// This is a situational tool for micro-optimization, and is allowed to do nothing.
116+
/// Any use should come with a repeatable benchmark to show the value
117+
/// and allow removing it later should the optimizer get smarter and no longer need it.
118+
///
119+
/// The more complicated the condition the less likely this is to be fruitful.
120+
/// For example, `assert_unchecked(foo.is_sorted())` is a complex enough value
121+
/// that the compiler is unlikely to be able to take advantage of it.
122+
///
123+
/// There's also no need to `assert_unchecked` basic properties of things. For
124+
/// example, the compiler already knows the range of `count_ones`, so there's no
125+
/// benefit to `let n = u32::count_ones(x); assert_unchecked(n <= u32::BITS);`.
126+
///
127+
/// You may know this from other places
128+
/// as [`llvm.assume`](https://llvm.org/docs/LangRef.html#llvm-assume-intrinsic)
129+
/// or [`__builtin_assume`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-assume).
130+
///
131+
/// This promotes a correctness requirement to a soundness requirement.
132+
/// Don't do that without very good reason.
133+
///
134+
/// # Safety
135+
///
136+
/// `cond` must be `true`. It's immediate UB to call this with `false`.
137+
///
138+
#[inline(always)]
139+
#[doc(alias = "assume")]
140+
#[unstable(feature = "hint_assert_unchecked", issue = "119131")]
141+
pub const unsafe fn assert_unchecked(cond: bool) {
142+
unsafe { crate::intrinsics::assume(cond) }
143+
}
144+
109145
/// Emits a machine instruction to signal the processor that it is running in
110146
/// a busy-wait spin-loop ("spin lock").
111147
///

0 commit comments

Comments
 (0)