core/
hint.rs

1#![stable(feature = "core_hint", since = "1.27.0")]
2
3//! Hints to compiler that affects how code should be emitted or optimized.
4//!
5//! Hints may be compile time or runtime.
6
7#[cfg(not(feature = "ferrocene_certified"))]
8use crate::mem::MaybeUninit;
9use crate::{intrinsics, ub_checks};
10
11/// Informs the compiler that the site which is calling this function is not
12/// reachable, possibly enabling further optimizations.
13///
14/// # Safety
15///
16/// Reaching this function is *Undefined Behavior*.
17///
18/// As the compiler assumes that all forms of Undefined Behavior can never
19/// happen, it will eliminate all branches in the surrounding code that it can
20/// determine will invariably lead to a call to `unreachable_unchecked()`.
21///
22/// If the assumptions embedded in using this function turn out to be wrong -
23/// that is, if the site which is calling `unreachable_unchecked()` is actually
24/// reachable at runtime - the compiler may have generated nonsensical machine
25/// instructions for this situation, including in seemingly unrelated code,
26/// causing difficult-to-debug problems.
27///
28/// Use this function sparingly. Consider using the [`unreachable!`] macro,
29/// which may prevent some optimizations but will safely panic in case it is
30/// actually reached at runtime. Benchmark your code to find out if using
31/// `unreachable_unchecked()` comes with a performance benefit.
32///
33/// # Examples
34///
35/// `unreachable_unchecked()` can be used in situations where the compiler
36/// can't prove invariants that were previously established. Such situations
37/// have a higher chance of occurring if those invariants are upheld by
38/// external code that the compiler can't analyze.
39/// ```
40/// fn prepare_inputs(divisors: &mut Vec<u32>) {
41///     // Note to future-self when making changes: The invariant established
42///     // here is NOT checked in `do_computation()`; if this changes, you HAVE
43///     // to change `do_computation()`.
44///     divisors.retain(|divisor| *divisor != 0)
45/// }
46///
47/// /// # Safety
48/// /// All elements of `divisor` must be non-zero.
49/// unsafe fn do_computation(i: u32, divisors: &[u32]) -> u32 {
50///     divisors.iter().fold(i, |acc, divisor| {
51///         // Convince the compiler that a division by zero can't happen here
52///         // and a check is not needed below.
53///         if *divisor == 0 {
54///             // Safety: `divisor` can't be zero because of `prepare_inputs`,
55///             // but the compiler does not know about this. We *promise*
56///             // that we always call `prepare_inputs`.
57///             unsafe { std::hint::unreachable_unchecked() }
58///         }
59///         // The compiler would normally introduce a check here that prevents
60///         // a division by zero. However, if `divisor` was zero, the branch
61///         // above would reach what we explicitly marked as unreachable.
62///         // The compiler concludes that `divisor` can't be zero at this point
63///         // and removes the - now proven useless - check.
64///         acc / divisor
65///     })
66/// }
67///
68/// let mut divisors = vec![2, 0, 4];
69/// prepare_inputs(&mut divisors);
70/// let result = unsafe {
71///     // Safety: prepare_inputs() guarantees that divisors is non-zero
72///     do_computation(100, &divisors)
73/// };
74/// assert_eq!(result, 12);
75///
76/// ```
77///
78/// While using `unreachable_unchecked()` is perfectly sound in the following
79/// example, as the compiler is able to prove that a division by zero is not
80/// possible, benchmarking reveals that `unreachable_unchecked()` provides
81/// no benefit over using [`unreachable!`], while the latter does not introduce
82/// the possibility of Undefined Behavior.
83///
84/// ```
85/// fn div_1(a: u32, b: u32) -> u32 {
86///     use std::hint::unreachable_unchecked;
87///
88///     // `b.saturating_add(1)` is always positive (not zero),
89///     // hence `checked_div` will never return `None`.
90///     // Therefore, the else branch is unreachable.
91///     a.checked_div(b.saturating_add(1))
92///         .unwrap_or_else(|| unsafe { unreachable_unchecked() })
93/// }
94///
95/// assert_eq!(div_1(7, 0), 7);
96/// assert_eq!(div_1(9, 1), 4);
97/// assert_eq!(div_1(11, u32::MAX), 0);
98/// ```
99#[inline]
100#[stable(feature = "unreachable", since = "1.27.0")]
101#[rustc_const_stable(feature = "const_unreachable_unchecked", since = "1.57.0")]
102#[track_caller]
103#[coverage(off)] // Ferrocene addition: this function breaks llvm-cov
104pub const unsafe fn unreachable_unchecked() -> ! {
105    ub_checks::assert_unsafe_precondition!(
106        check_language_ub,
107        "hint::unreachable_unchecked must never be reached",
108        () => false
109    );
110    // SAFETY: the safety contract for `intrinsics::unreachable` must
111    // be upheld by the caller.
112    unsafe { intrinsics::unreachable() }
113}
114
115/// Makes a *soundness* promise to the compiler that `cond` holds.
116///
117/// This may allow the optimizer to simplify things, but it might also make the generated code
118/// slower. Either way, calling it will most likely make compilation take longer.
119///
120/// You may know this from other places as
121/// [`llvm.assume`](https://llvm.org/docs/LangRef.html#llvm-assume-intrinsic) or, in C,
122/// [`__builtin_assume`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-assume).
123///
124/// This promotes a correctness requirement to a soundness requirement. Don't do that without
125/// very good reason.
126///
127/// # Usage
128///
129/// This is a situational tool for micro-optimization, and is allowed to do nothing. Any use
130/// should come with a repeatable benchmark to show the value, with the expectation to drop it
131/// later should the optimizer get smarter and no longer need it.
132///
133/// The more complicated the condition, the less likely this is to be useful. For example,
134/// `assert_unchecked(foo.is_sorted())` is a complex enough value that the compiler is unlikely
135/// to be able to take advantage of it.
136///
137/// There's also no need to `assert_unchecked` basic properties of things.  For example, the
138/// compiler already knows the range of `count_ones`, so there is no benefit to
139/// `let n = u32::count_ones(x); assert_unchecked(n <= u32::BITS);`.
140///
141/// `assert_unchecked` is logically equivalent to `if !cond { unreachable_unchecked(); }`. If
142/// ever you are tempted to write `assert_unchecked(false)`, you should instead use
143/// [`unreachable_unchecked()`] directly.
144///
145/// # Safety
146///
147/// `cond` must be `true`. It is immediate UB to call this with `false`.
148///
149/// # Example
150///
151/// ```
152/// use core::hint;
153///
154/// /// # Safety
155/// ///
156/// /// `p` must be nonnull and valid
157/// pub unsafe fn next_value(p: *const i32) -> i32 {
158///     // SAFETY: caller invariants guarantee that `p` is not null
159///     unsafe { hint::assert_unchecked(!p.is_null()) }
160///
161///     if p.is_null() {
162///         return -1;
163///     } else {
164///         // SAFETY: caller invariants guarantee that `p` is valid
165///         unsafe { *p + 1 }
166///     }
167/// }
168/// ```
169///
170/// Without the `assert_unchecked`, the above function produces the following with optimizations
171/// enabled:
172///
173/// ```asm
174/// next_value:
175///         test    rdi, rdi
176///         je      .LBB0_1
177///         mov     eax, dword ptr [rdi]
178///         inc     eax
179///         ret
180/// .LBB0_1:
181///         mov     eax, -1
182///         ret
183/// ```
184///
185/// Adding the assertion allows the optimizer to remove the extra check:
186///
187/// ```asm
188/// next_value:
189///         mov     eax, dword ptr [rdi]
190///         inc     eax
191///         ret
192/// ```
193///
194/// This example is quite unlike anything that would be used in the real world: it is redundant
195/// to put an assertion right next to code that checks the same thing, and dereferencing a
196/// pointer already has the builtin assumption that it is nonnull. However, it illustrates the
197/// kind of changes the optimizer can make even when the behavior is less obviously related.
198#[track_caller]
199#[inline(always)]
200#[doc(alias = "assume")]
201#[stable(feature = "hint_assert_unchecked", since = "1.81.0")]
202#[rustc_const_stable(feature = "hint_assert_unchecked", since = "1.81.0")]
203#[cfg(not(feature = "ferrocene_certified"))]
204pub const unsafe fn assert_unchecked(cond: bool) {
205    // SAFETY: The caller promised `cond` is true.
206    unsafe {
207        ub_checks::assert_unsafe_precondition!(
208            check_language_ub,
209            "hint::assert_unchecked must never be called when the condition is false",
210            (cond: bool = cond) => cond,
211        );
212        crate::intrinsics::assume(cond);
213    }
214}
215
216/// Emits a machine instruction to signal the processor that it is running in
217/// a busy-wait spin-loop ("spin lock").
218///
219/// Upon receiving the spin-loop signal the processor can optimize its behavior by,
220/// for example, saving power or switching hyper-threads.
221///
222/// This function is different from [`thread::yield_now`] which directly
223/// yields to the system's scheduler, whereas `spin_loop` does not interact
224/// with the operating system.
225///
226/// A common use case for `spin_loop` is implementing bounded optimistic
227/// spinning in a CAS loop in synchronization primitives. To avoid problems
228/// like priority inversion, it is strongly recommended that the spin loop is
229/// terminated after a finite amount of iterations and an appropriate blocking
230/// syscall is made.
231///
232/// **Note**: On platforms that do not support receiving spin-loop hints this
233/// function does not do anything at all.
234///
235/// # Examples
236///
237/// ```ignore-wasm
238/// use std::sync::atomic::{AtomicBool, Ordering};
239/// use std::sync::Arc;
240/// use std::{hint, thread};
241///
242/// // A shared atomic value that threads will use to coordinate
243/// let live = Arc::new(AtomicBool::new(false));
244///
245/// // In a background thread we'll eventually set the value
246/// let bg_work = {
247///     let live = live.clone();
248///     thread::spawn(move || {
249///         // Do some work, then make the value live
250///         do_some_work();
251///         live.store(true, Ordering::Release);
252///     })
253/// };
254///
255/// // Back on our current thread, we wait for the value to be set
256/// while !live.load(Ordering::Acquire) {
257///     // The spin loop is a hint to the CPU that we're waiting, but probably
258///     // not for very long
259///     hint::spin_loop();
260/// }
261///
262/// // The value is now set
263/// # fn do_some_work() {}
264/// do_some_work();
265/// bg_work.join()?;
266/// # Ok::<(), Box<dyn core::any::Any + Send + 'static>>(())
267/// ```
268///
269/// [`thread::yield_now`]: ../../std/thread/fn.yield_now.html
270#[inline(always)]
271#[stable(feature = "renamed_spin_loop", since = "1.49.0")]
272#[cfg(not(feature = "ferrocene_certified"))]
273pub fn spin_loop() {
274    #[cfg(target_arch = "x86")]
275    {
276        // SAFETY: the `cfg` attr ensures that we only execute this on x86 targets.
277        unsafe { crate::arch::x86::_mm_pause() };
278    }
279
280    #[cfg(target_arch = "x86_64")]
281    {
282        // SAFETY: the `cfg` attr ensures that we only execute this on x86_64 targets.
283        unsafe { crate::arch::x86_64::_mm_pause() };
284    }
285
286    #[cfg(target_arch = "riscv32")]
287    {
288        crate::arch::riscv32::pause();
289    }
290
291    #[cfg(target_arch = "riscv64")]
292    {
293        crate::arch::riscv64::pause();
294    }
295
296    #[cfg(any(target_arch = "aarch64", target_arch = "arm64ec"))]
297    {
298        // SAFETY: the `cfg` attr ensures that we only execute this on aarch64 targets.
299        unsafe { crate::arch::aarch64::__isb(crate::arch::aarch64::SY) };
300    }
301
302    #[cfg(all(target_arch = "arm", target_feature = "v6"))]
303    {
304        // SAFETY: the `cfg` attr ensures that we only execute this on arm targets
305        // with support for the v6 feature.
306        unsafe { crate::arch::arm::__yield() };
307    }
308}
309
310/// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
311/// `black_box` could do.
312///
313/// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
314/// use `dummy` in any possible valid way that Rust code is allowed to without introducing undefined
315/// behavior in the calling code. This property makes `black_box` useful for writing code in which
316/// certain optimizations are not desired, such as benchmarks.
317///
318/// <div class="warning">
319///
320/// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
321/// extent to which it can block optimisations may vary depending upon the platform and code-gen
322/// backend used. Programs cannot rely on `black_box` for *correctness*, beyond it behaving as the
323/// identity function. As such, it **must not be relied upon to control critical program behavior.**
324/// This also means that this function does not offer any guarantees for cryptographic or security
325/// purposes.
326///
327/// This limitation is not specific to `black_box`; there is no mechanism in the entire Rust
328/// language that can provide the guarantees required for constant-time cryptography.
329/// (There is also no such mechanism in LLVM, so the same is true for every other LLVM-based compiler.)
330///
331/// </div>
332///
333/// [`std::convert::identity`]: crate::convert::identity
334///
335/// # When is this useful?
336///
337/// While not suitable in those mission-critical cases, `black_box`'s functionality can generally be
338/// relied upon for benchmarking, and should be used there. It will try to ensure that the
339/// compiler doesn't optimize away part of the intended test code based on context. For
340/// example:
341///
342/// ```
343/// fn contains(haystack: &[&str], needle: &str) -> bool {
344///     haystack.iter().any(|x| x == &needle)
345/// }
346///
347/// pub fn benchmark() {
348///     let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
349///     let needle = "ghi";
350///     for _ in 0..10 {
351///         contains(&haystack, needle);
352///     }
353/// }
354/// ```
355///
356/// The compiler could theoretically make optimizations like the following:
357///
358/// - The `needle` and `haystack` do not change, move the call to `contains` outside the loop and
359///   delete the loop
360/// - Inline `contains`
361/// - `needle` and `haystack` have values known at compile time, `contains` is always true. Remove
362///   the call and replace with `true`
363/// - Nothing is done with the result of `contains`: delete this function call entirely
364/// - `benchmark` now has no purpose: delete this function
365///
366/// It is not likely that all of the above happens, but the compiler is definitely able to make some
367/// optimizations that could result in a very inaccurate benchmark. This is where `black_box` comes
368/// in:
369///
370/// ```
371/// use std::hint::black_box;
372///
373/// // Same `contains` function.
374/// fn contains(haystack: &[&str], needle: &str) -> bool {
375///     haystack.iter().any(|x| x == &needle)
376/// }
377///
378/// pub fn benchmark() {
379///     let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
380///     let needle = "ghi";
381///     for _ in 0..10 {
382///         // Force the compiler to run `contains`, even though it is a pure function whose
383///         // results are unused.
384///         black_box(contains(
385///             // Prevent the compiler from making assumptions about the input.
386///             black_box(&haystack),
387///             black_box(needle),
388///         ));
389///     }
390/// }
391/// ```
392///
393/// This essentially tells the compiler to block optimizations across any calls to `black_box`. So,
394/// it now:
395///
396/// - Treats both arguments to `contains` as unpredictable: the body of `contains` can no longer be
397///   optimized based on argument values
398/// - Treats the call to `contains` and its result as volatile: the body of `benchmark` cannot
399///   optimize this away
400///
401/// This makes our benchmark much more realistic to how the function would actually be used, where
402/// arguments are usually not known at compile time and the result is used in some way.
403///
404/// # How to use this
405///
406/// In practice, `black_box` serves two purposes:
407///
408/// 1. It prevents the compiler from making optimizations related to the value returned by `black_box`
409/// 2. It forces the value passed to `black_box` to be calculated, even if the return value of `black_box` is unused
410///
411/// ```
412/// use std::hint::black_box;
413///
414/// let zero = 0;
415/// let five = 5;
416///
417/// // The compiler will see this and remove the `* five` call, because it knows that multiplying
418/// // any integer by 0 will result in 0.
419/// let c = zero * five;
420///
421/// // Adding `black_box` here disables the compiler's ability to reason about the first operand in the multiplication.
422/// // It is forced to assume that it can be any possible number, so it cannot remove the `* five`
423/// // operation.
424/// let c = black_box(zero) * five;
425/// ```
426///
427/// While most cases will not be as clear-cut as the above example, it still illustrates how
428/// `black_box` can be used. When benchmarking a function, you usually want to wrap its inputs in
429/// `black_box` so the compiler cannot make optimizations that would be unrealistic in real-life
430/// use.
431///
432/// ```
433/// use std::hint::black_box;
434///
435/// // This is a simple function that increments its input by 1. Note that it is pure, meaning it
436/// // has no side-effects. This function has no effect if its result is unused. (An example of a
437/// // function *with* side-effects is `println!()`.)
438/// fn increment(x: u8) -> u8 {
439///     x + 1
440/// }
441///
442/// // Here, we call `increment` but discard its result. The compiler, seeing this and knowing that
443/// // `increment` is pure, will eliminate this function call entirely. This may not be desired,
444/// // though, especially if we're trying to track how much time `increment` takes to execute.
445/// let _ = increment(black_box(5));
446///
447/// // Here, we force `increment` to be executed. This is because the compiler treats `black_box`
448/// // as if it has side-effects, and thus must compute its input.
449/// let _ = black_box(increment(black_box(5)));
450/// ```
451///
452/// There may be additional situations where you want to wrap the result of a function in
453/// `black_box` to force its execution. This is situational though, and may not have any effect
454/// (such as when the function returns a zero-sized type such as [`()` unit][unit]).
455///
456/// Note that `black_box` has no effect on how its input is treated, only its output. As such,
457/// expressions passed to `black_box` may still be optimized:
458///
459/// ```
460/// use std::hint::black_box;
461///
462/// // The compiler sees this...
463/// let y = black_box(5 * 10);
464///
465/// // ...as this. As such, it will likely simplify `5 * 10` to just `50`.
466/// let _0 = 5 * 10;
467/// let y = black_box(_0);
468/// ```
469///
470/// In the above example, the `5 * 10` expression is considered distinct from the `black_box` call,
471/// and thus is still optimized by the compiler. You can prevent this by moving the multiplication
472/// operation outside of `black_box`:
473///
474/// ```
475/// use std::hint::black_box;
476///
477/// // No assumptions can be made about either operand, so the multiplication is not optimized out.
478/// let y = black_box(5) * black_box(10);
479/// ```
480///
481/// During constant evaluation, `black_box` is treated as a no-op.
482#[inline]
483#[stable(feature = "bench_black_box", since = "1.66.0")]
484#[rustc_const_stable(feature = "const_black_box", since = "1.86.0")]
485#[cfg(not(feature = "ferrocene_certified"))]
486pub const fn black_box<T>(dummy: T) -> T {
487    crate::intrinsics::black_box(dummy)
488}
489
490/// An identity function that causes an `unused_must_use` warning to be
491/// triggered if the given value is not used (returned, stored in a variable,
492/// etc) by the caller.
493///
494/// This is primarily intended for use in macro-generated code, in which a
495/// [`#[must_use]` attribute][must_use] either on a type or a function would not
496/// be convenient.
497///
498/// [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
499///
500/// # Example
501///
502/// ```
503/// #![feature(hint_must_use)]
504///
505/// use core::fmt;
506///
507/// pub struct Error(/* ... */);
508///
509/// #[macro_export]
510/// macro_rules! make_error {
511///     ($($args:expr),*) => {
512///         core::hint::must_use({
513///             let error = $crate::make_error(core::format_args!($($args),*));
514///             error
515///         })
516///     };
517/// }
518///
519/// // Implementation detail of make_error! macro.
520/// #[doc(hidden)]
521/// pub fn make_error(args: fmt::Arguments<'_>) -> Error {
522///     Error(/* ... */)
523/// }
524///
525/// fn demo() -> Option<Error> {
526///     if true {
527///         // Oops, meant to write `return Some(make_error!("..."));`
528///         Some(make_error!("..."));
529///     }
530///     None
531/// }
532/// #
533/// # // Make rustdoc not wrap the whole snippet in fn main, so that $crate::make_error works
534/// # fn main() {}
535/// ```
536///
537/// In the above example, we'd like an `unused_must_use` lint to apply to the
538/// value created by `make_error!`. However, neither `#[must_use]` on a struct
539/// nor `#[must_use]` on a function is appropriate here, so the macro expands
540/// using `core::hint::must_use` instead.
541///
542/// - We wouldn't want `#[must_use]` on the `struct Error` because that would
543///   make the following unproblematic code trigger a warning:
544///
545///   ```
546///   # struct Error;
547///   #
548///   fn f(arg: &str) -> Result<(), Error>
549///   # { Ok(()) }
550///
551///   #[test]
552///   fn t() {
553///       // Assert that `f` returns error if passed an empty string.
554///       // A value of type `Error` is unused here but that's not a problem.
555///       f("").unwrap_err();
556///   }
557///   ```
558///
559/// - Using `#[must_use]` on `fn make_error` can't help because the return value
560///   *is* used, as the right-hand side of a `let` statement. The `let`
561///   statement looks useless but is in fact necessary for ensuring that
562///   temporaries within the `format_args` expansion are not kept alive past the
563///   creation of the `Error`, as keeping them alive past that point can cause
564///   autotrait issues in async code:
565///
566///   ```
567///   # #![feature(hint_must_use)]
568///   #
569///   # struct Error;
570///   #
571///   # macro_rules! make_error {
572///   #     ($($args:expr),*) => {
573///   #         core::hint::must_use({
574///   #             // If `let` isn't used, then `f()` produces a non-Send future.
575///   #             let error = make_error(core::format_args!($($args),*));
576///   #             error
577///   #         })
578///   #     };
579///   # }
580///   #
581///   # fn make_error(args: core::fmt::Arguments<'_>) -> Error {
582///   #     Error
583///   # }
584///   #
585///   async fn f() {
586///       // Using `let` inside the make_error expansion causes temporaries like
587///       // `unsync()` to drop at the semicolon of that `let` statement, which
588///       // is prior to the await point. They would otherwise stay around until
589///       // the semicolon on *this* statement, which is after the await point,
590///       // and the enclosing Future would not implement Send.
591///       log(make_error!("look: {:p}", unsync())).await;
592///   }
593///
594///   async fn log(error: Error) {/* ... */}
595///
596///   // Returns something without a Sync impl.
597///   fn unsync() -> *const () {
598///       0 as *const ()
599///   }
600///   #
601///   # fn test() {
602///   #     fn assert_send(_: impl Send) {}
603///   #     assert_send(f());
604///   # }
605///   ```
606#[unstable(feature = "hint_must_use", issue = "94745")]
607#[must_use] // <-- :)
608#[inline(always)]
609#[cfg(not(feature = "ferrocene_certified"))]
610pub const fn must_use<T>(value: T) -> T {
611    value
612}
613
614/// Hints to the compiler that a branch condition is likely to be true.
615/// Returns the value passed to it.
616///
617/// It can be used with `if` or boolean `match` expressions.
618///
619/// When used outside of a branch condition, it may still influence a nearby branch, but
620/// probably will not have any effect.
621///
622/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
623/// compound expressions, such as `likely(a && b)`. When applied to compound expressions, it has
624/// the following effect:
625/// ```text
626///     likely(!a) => !unlikely(a)
627///     likely(a && b) => likely(a) && likely(b)
628///     likely(a || b) => a || likely(b)
629/// ```
630///
631/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
632///
633/// # Examples
634///
635/// ```
636/// #![feature(likely_unlikely)]
637/// use core::hint::likely;
638///
639/// fn foo(x: i32) {
640///     if likely(x > 0) {
641///         println!("this branch is likely to be taken");
642///     } else {
643///         println!("this branch is unlikely to be taken");
644///     }
645///
646///     match likely(x > 0) {
647///         true => println!("this branch is likely to be taken"),
648///         false => println!("this branch is unlikely to be taken"),
649///     }
650///
651///     // Use outside of a branch condition may still influence a nearby branch
652///     let cond = likely(x != 0);
653///     if cond {
654///         println!("this branch is likely to be taken");
655///     }
656/// }
657/// ```
658///
659///
660#[unstable(feature = "likely_unlikely", issue = "136873")]
661#[inline(always)]
662#[cfg(not(feature = "ferrocene_certified"))]
663pub const fn likely(b: bool) -> bool {
664    crate::intrinsics::likely(b)
665}
666
667/// Hints to the compiler that a branch condition is unlikely to be true.
668/// Returns the value passed to it.
669///
670/// It can be used with `if` or boolean `match` expressions.
671///
672/// When used outside of a branch condition, it may still influence a nearby branch, but
673/// probably will not have any effect.
674///
675/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
676/// compound expressions, such as `unlikely(a && b)`. When applied to compound expressions, it has
677/// the following effect:
678/// ```text
679///     unlikely(!a) => !likely(a)
680///     unlikely(a && b) => a && unlikely(b)
681///     unlikely(a || b) => unlikely(a) || unlikely(b)
682/// ```
683///
684/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
685///
686/// # Examples
687///
688/// ```
689/// #![feature(likely_unlikely)]
690/// use core::hint::unlikely;
691///
692/// fn foo(x: i32) {
693///     if unlikely(x > 0) {
694///         println!("this branch is unlikely to be taken");
695///     } else {
696///         println!("this branch is likely to be taken");
697///     }
698///
699///     match unlikely(x > 0) {
700///         true => println!("this branch is unlikely to be taken"),
701///         false => println!("this branch is likely to be taken"),
702///     }
703///
704///     // Use outside of a branch condition may still influence a nearby branch
705///     let cond = unlikely(x != 0);
706///     if cond {
707///         println!("this branch is likely to be taken");
708///     }
709/// }
710/// ```
711#[unstable(feature = "likely_unlikely", issue = "136873")]
712#[inline(always)]
713#[cfg(not(feature = "ferrocene_certified"))]
714pub const fn unlikely(b: bool) -> bool {
715    crate::intrinsics::unlikely(b)
716}
717
718/// Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may
719/// choose to optimize paths that are not cold at the expense of paths that are cold.
720///
721/// # Examples
722///
723/// ```
724/// #![feature(cold_path)]
725/// use core::hint::cold_path;
726///
727/// fn foo(x: &[i32]) {
728///     if let Some(first) = x.get(0) {
729///         // this is the fast path
730///     } else {
731///         // this path is unlikely
732///         cold_path();
733///     }
734/// }
735///
736/// fn bar(x: i32) -> i32 {
737///     match x {
738///         1 => 10,
739///         2 => 100,
740///         3 => { cold_path(); 1000 }, // this branch is unlikely
741///         _ => { cold_path(); 10000 }, // this is also unlikely
742///     }
743/// }
744/// ```
745#[unstable(feature = "cold_path", issue = "136873")]
746#[inline(always)]
747#[cfg(not(feature = "ferrocene_certified"))]
748pub const fn cold_path() {
749    crate::intrinsics::cold_path()
750}
751
752/// Returns either `true_val` or `false_val` depending on the value of
753/// `condition`, with a hint to the compiler that `condition` is unlikely to be
754/// correctly predicted by a CPU’s branch predictor.
755///
756/// This method is functionally equivalent to
757/// ```ignore (this is just for illustrative purposes)
758/// fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
759///     if b { true_val } else { false_val }
760/// }
761/// ```
762/// but might generate different assembly. In particular, on platforms with
763/// a conditional move or select instruction (like `cmov` on x86 or `csel`
764/// on ARM) the optimizer might use these instructions to avoid branches,
765/// which can benefit performance if the branch predictor is struggling
766/// with predicting `condition`, such as in an implementation of binary
767/// search.
768///
769/// Note however that this lowering is not guaranteed (on any platform) and
770/// should not be relied upon when trying to write cryptographic constant-time
771/// code. Also be aware that this lowering might *decrease* performance if
772/// `condition` is well-predictable. It is advisable to perform benchmarks to
773/// tell if this function is useful.
774///
775/// # Examples
776///
777/// Distribute values evenly between two buckets:
778/// ```
779/// use std::hash::BuildHasher;
780/// use std::hint;
781///
782/// fn append<H: BuildHasher>(hasher: &H, v: i32, bucket_one: &mut Vec<i32>, bucket_two: &mut Vec<i32>) {
783///     let hash = hasher.hash_one(&v);
784///     let bucket = hint::select_unpredictable(hash % 2 == 0, bucket_one, bucket_two);
785///     bucket.push(v);
786/// }
787/// # let hasher = std::collections::hash_map::RandomState::new();
788/// # let mut bucket_one = Vec::new();
789/// # let mut bucket_two = Vec::new();
790/// # append(&hasher, 42, &mut bucket_one, &mut bucket_two);
791/// # assert_eq!(bucket_one.len() + bucket_two.len(), 1);
792/// ```
793#[inline(always)]
794#[stable(feature = "select_unpredictable", since = "1.88.0")]
795#[cfg(not(feature = "ferrocene_certified"))]
796pub fn select_unpredictable<T>(condition: bool, true_val: T, false_val: T) -> T {
797    // FIXME(https://github.com/rust-lang/unsafe-code-guidelines/issues/245):
798    // Change this to use ManuallyDrop instead.
799    let mut true_val = MaybeUninit::new(true_val);
800    let mut false_val = MaybeUninit::new(false_val);
801    // SAFETY: The value that is not selected is dropped, and the selected one
802    // is returned. This is necessary because the intrinsic doesn't drop the
803    // value that is  not selected.
804    unsafe {
805        crate::intrinsics::select_unpredictable(!condition, &mut true_val, &mut false_val)
806            .assume_init_drop();
807        crate::intrinsics::select_unpredictable(condition, true_val, false_val).assume_init()
808    }
809}