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
7use crate::marker::Destruct;
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")]
203pub const unsafe fn assert_unchecked(cond: bool) {
204    // SAFETY: The caller promised `cond` is true.
205    unsafe {
206        ub_checks::assert_unsafe_precondition!(
207            check_language_ub,
208            "hint::assert_unchecked must never be called when the condition is false",
209            (cond: bool = cond) => cond,
210        );
211        crate::intrinsics::assume(cond);
212    }
213}
214
215/// Emits a machine instruction to signal the processor that it is running in
216/// a busy-wait spin-loop ("spin lock").
217///
218/// Upon receiving the spin-loop signal the processor can optimize its behavior by,
219/// for example, saving power or switching hyper-threads.
220///
221/// This function is different from [`thread::yield_now`] which directly
222/// yields to the system's scheduler, whereas `spin_loop` does not interact
223/// with the operating system.
224///
225/// A common use case for `spin_loop` is implementing bounded optimistic
226/// spinning in a CAS loop in synchronization primitives. To avoid problems
227/// like priority inversion, it is strongly recommended that the spin loop is
228/// terminated after a finite amount of iterations and an appropriate blocking
229/// syscall is made.
230///
231/// **Note**: On platforms that do not support receiving spin-loop hints this
232/// function does not do anything at all.
233///
234/// # Examples
235///
236/// ```ignore-wasm
237/// use std::sync::atomic::{AtomicBool, Ordering};
238/// use std::sync::Arc;
239/// use std::{hint, thread};
240///
241/// // A shared atomic value that threads will use to coordinate
242/// let live = Arc::new(AtomicBool::new(false));
243///
244/// // In a background thread we'll eventually set the value
245/// let bg_work = {
246///     let live = live.clone();
247///     thread::spawn(move || {
248///         // Do some work, then make the value live
249///         do_some_work();
250///         live.store(true, Ordering::Release);
251///     })
252/// };
253///
254/// // Back on our current thread, we wait for the value to be set
255/// while !live.load(Ordering::Acquire) {
256///     // The spin loop is a hint to the CPU that we're waiting, but probably
257///     // not for very long
258///     hint::spin_loop();
259/// }
260///
261/// // The value is now set
262/// # fn do_some_work() {}
263/// do_some_work();
264/// bg_work.join()?;
265/// # Ok::<(), Box<dyn core::any::Any + Send + 'static>>(())
266/// ```
267///
268/// [`thread::yield_now`]: ../../std/thread/fn.yield_now.html
269#[inline(always)]
270#[stable(feature = "renamed_spin_loop", since = "1.49.0")]
271#[cfg(not(feature = "ferrocene_subset"))]
272pub fn spin_loop() {
273    crate::cfg_select! {
274        miri => {
275            unsafe extern "Rust" {
276                safe fn miri_spin_loop();
277            }
278
279            // Miri does support some of the intrinsics that are called below, but to guarantee
280            // consistent behavior across targets, this custom function is used.
281            miri_spin_loop();
282        }
283        target_arch = "x86" => {
284            // SAFETY: the `cfg` attr ensures that we only execute this on x86 targets.
285            crate::arch::x86::_mm_pause()
286        }
287        target_arch = "x86_64" => {
288            // SAFETY: the `cfg` attr ensures that we only execute this on x86_64 targets.
289            crate::arch::x86_64::_mm_pause()
290        }
291        target_arch = "riscv32" => crate::arch::riscv32::pause(),
292        target_arch = "riscv64" => crate::arch::riscv64::pause(),
293        any(target_arch = "aarch64", target_arch = "arm64ec") => {
294            // SAFETY: the `cfg` attr ensures that we only execute this on aarch64 targets.
295            unsafe { crate::arch::aarch64::__isb(crate::arch::aarch64::SY) }
296        }
297        all(target_arch = "arm", target_feature = "v6") => {
298            // SAFETY: the `cfg` attr ensures that we only execute this on arm targets
299            // with support for the v6 feature.
300            unsafe { crate::arch::arm::__yield() }
301        }
302        target_arch = "loongarch32" => crate::arch::loongarch32::ibar::<0>(),
303        target_arch = "loongarch64" => crate::arch::loongarch64::ibar::<0>(),
304        _ => { /* do nothing */ }
305    }
306}
307
308/// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
309/// `black_box` could do.
310///
311/// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
312/// use `dummy` in any possible valid way that Rust code is allowed to without introducing undefined
313/// behavior in the calling code. This property makes `black_box` useful for writing code in which
314/// certain optimizations are not desired, such as benchmarks.
315///
316/// <div class="warning">
317///
318/// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
319/// extent to which it can block optimisations may vary depending upon the platform and code-gen
320/// backend used. Programs cannot rely on `black_box` for *correctness*, beyond it behaving as the
321/// identity function. As such, it **must not be relied upon to control critical program behavior.**
322/// This also means that this function does not offer any guarantees for cryptographic or security
323/// purposes.
324///
325/// This limitation is not specific to `black_box`; there is no mechanism in the entire Rust
326/// language that can provide the guarantees required for constant-time cryptography.
327/// (There is also no such mechanism in LLVM, so the same is true for every other LLVM-based compiler.)
328///
329/// </div>
330///
331/// [`std::convert::identity`]: crate::convert::identity
332///
333/// # When is this useful?
334///
335/// While not suitable in those mission-critical cases, `black_box`'s functionality can generally be
336/// relied upon for benchmarking, and should be used there. It will try to ensure that the
337/// compiler doesn't optimize away part of the intended test code based on context. For
338/// example:
339///
340/// ```
341/// fn contains(haystack: &[&str], needle: &str) -> bool {
342///     haystack.iter().any(|x| x == &needle)
343/// }
344///
345/// pub fn benchmark() {
346///     let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
347///     let needle = "ghi";
348///     for _ in 0..10 {
349///         contains(&haystack, needle);
350///     }
351/// }
352/// ```
353///
354/// The compiler could theoretically make optimizations like the following:
355///
356/// - The `needle` and `haystack` do not change, move the call to `contains` outside the loop and
357///   delete the loop
358/// - Inline `contains`
359/// - `needle` and `haystack` have values known at compile time, `contains` is always true. Remove
360///   the call and replace with `true`
361/// - Nothing is done with the result of `contains`: delete this function call entirely
362/// - `benchmark` now has no purpose: delete this function
363///
364/// It is not likely that all of the above happens, but the compiler is definitely able to make some
365/// optimizations that could result in a very inaccurate benchmark. This is where `black_box` comes
366/// in:
367///
368/// ```
369/// use std::hint::black_box;
370///
371/// // Same `contains` function.
372/// fn contains(haystack: &[&str], needle: &str) -> bool {
373///     haystack.iter().any(|x| x == &needle)
374/// }
375///
376/// pub fn benchmark() {
377///     let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
378///     let needle = "ghi";
379///     for _ in 0..10 {
380///         // Force the compiler to run `contains`, even though it is a pure function whose
381///         // results are unused.
382///         black_box(contains(
383///             // Prevent the compiler from making assumptions about the input.
384///             black_box(&haystack),
385///             black_box(needle),
386///         ));
387///     }
388/// }
389/// ```
390///
391/// This essentially tells the compiler to block optimizations across any calls to `black_box`. So,
392/// it now:
393///
394/// - Treats both arguments to `contains` as unpredictable: the body of `contains` can no longer be
395///   optimized based on argument values
396/// - Treats the call to `contains` and its result as volatile: the body of `benchmark` cannot
397///   optimize this away
398///
399/// This makes our benchmark much more realistic to how the function would actually be used, where
400/// arguments are usually not known at compile time and the result is used in some way.
401///
402/// # How to use this
403///
404/// In practice, `black_box` serves two purposes:
405///
406/// 1. It prevents the compiler from making optimizations related to the value returned by `black_box`
407/// 2. It forces the value passed to `black_box` to be calculated, even if the return value of `black_box` is unused
408///
409/// ```
410/// use std::hint::black_box;
411///
412/// let zero = 0;
413/// let five = 5;
414///
415/// // The compiler will see this and remove the `* five` call, because it knows that multiplying
416/// // any integer by 0 will result in 0.
417/// let c = zero * five;
418///
419/// // Adding `black_box` here disables the compiler's ability to reason about the first operand in the multiplication.
420/// // It is forced to assume that it can be any possible number, so it cannot remove the `* five`
421/// // operation.
422/// let c = black_box(zero) * five;
423/// ```
424///
425/// While most cases will not be as clear-cut as the above example, it still illustrates how
426/// `black_box` can be used. When benchmarking a function, you usually want to wrap its inputs in
427/// `black_box` so the compiler cannot make optimizations that would be unrealistic in real-life
428/// use.
429///
430/// ```
431/// use std::hint::black_box;
432///
433/// // This is a simple function that increments its input by 1. Note that it is pure, meaning it
434/// // has no side-effects. This function has no effect if its result is unused. (An example of a
435/// // function *with* side-effects is `println!()`.)
436/// fn increment(x: u8) -> u8 {
437///     x + 1
438/// }
439///
440/// // Here, we call `increment` but discard its result. The compiler, seeing this and knowing that
441/// // `increment` is pure, will eliminate this function call entirely. This may not be desired,
442/// // though, especially if we're trying to track how much time `increment` takes to execute.
443/// let _ = increment(black_box(5));
444///
445/// // Here, we force `increment` to be executed. This is because the compiler treats `black_box`
446/// // as if it has side-effects, and thus must compute its input.
447/// let _ = black_box(increment(black_box(5)));
448/// ```
449///
450/// There may be additional situations where you want to wrap the result of a function in
451/// `black_box` to force its execution. This is situational though, and may not have any effect
452/// (such as when the function returns a zero-sized type such as [`()` unit][unit]).
453///
454/// Note that `black_box` has no effect on how its input is treated, only its output. As such,
455/// expressions passed to `black_box` may still be optimized:
456///
457/// ```
458/// use std::hint::black_box;
459///
460/// // The compiler sees this...
461/// let y = black_box(5 * 10);
462///
463/// // ...as this. As such, it will likely simplify `5 * 10` to just `50`.
464/// let _0 = 5 * 10;
465/// let y = black_box(_0);
466/// ```
467///
468/// In the above example, the `5 * 10` expression is considered distinct from the `black_box` call,
469/// and thus is still optimized by the compiler. You can prevent this by moving the multiplication
470/// operation outside of `black_box`:
471///
472/// ```
473/// use std::hint::black_box;
474///
475/// // No assumptions can be made about either operand, so the multiplication is not optimized out.
476/// let y = black_box(5) * black_box(10);
477/// ```
478///
479/// During constant evaluation, `black_box` is treated as a no-op.
480#[inline]
481#[stable(feature = "bench_black_box", since = "1.66.0")]
482#[rustc_const_stable(feature = "const_black_box", since = "1.86.0")]
483#[cfg(not(feature = "ferrocene_subset"))]
484pub const fn black_box<T>(dummy: T) -> T {
485    crate::intrinsics::black_box(dummy)
486}
487
488/// An identity function that causes an `unused_must_use` warning to be
489/// triggered if the given value is not used (returned, stored in a variable,
490/// etc) by the caller.
491///
492/// This is primarily intended for use in macro-generated code, in which a
493/// [`#[must_use]` attribute][must_use] either on a type or a function would not
494/// be convenient.
495///
496/// [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
497///
498/// # Example
499///
500/// ```
501/// #![feature(hint_must_use)]
502///
503/// use core::fmt;
504///
505/// pub struct Error(/* ... */);
506///
507/// #[macro_export]
508/// macro_rules! make_error {
509///     ($($args:expr),*) => {
510///         core::hint::must_use({
511///             let error = $crate::make_error(core::format_args!($($args),*));
512///             error
513///         })
514///     };
515/// }
516///
517/// // Implementation detail of make_error! macro.
518/// #[doc(hidden)]
519/// pub fn make_error(args: fmt::Arguments<'_>) -> Error {
520///     Error(/* ... */)
521/// }
522///
523/// fn demo() -> Option<Error> {
524///     if true {
525///         // Oops, meant to write `return Some(make_error!("..."));`
526///         Some(make_error!("..."));
527///     }
528///     None
529/// }
530/// #
531/// # // Make rustdoc not wrap the whole snippet in fn main, so that $crate::make_error works
532/// # fn main() {}
533/// ```
534///
535/// In the above example, we'd like an `unused_must_use` lint to apply to the
536/// value created by `make_error!`. However, neither `#[must_use]` on a struct
537/// nor `#[must_use]` on a function is appropriate here, so the macro expands
538/// using `core::hint::must_use` instead.
539///
540/// - We wouldn't want `#[must_use]` on the `struct Error` because that would
541///   make the following unproblematic code trigger a warning:
542///
543///   ```
544///   # struct Error;
545///   #
546///   fn f(arg: &str) -> Result<(), Error>
547///   # { Ok(()) }
548///
549///   #[test]
550///   fn t() {
551///       // Assert that `f` returns error if passed an empty string.
552///       // A value of type `Error` is unused here but that's not a problem.
553///       f("").unwrap_err();
554///   }
555///   ```
556///
557/// - Using `#[must_use]` on `fn make_error` can't help because the return value
558///   *is* used, as the right-hand side of a `let` statement. The `let`
559///   statement looks useless but is in fact necessary for ensuring that
560///   temporaries within the `format_args` expansion are not kept alive past the
561///   creation of the `Error`, as keeping them alive past that point can cause
562///   autotrait issues in async code:
563///
564///   ```
565///   # #![feature(hint_must_use)]
566///   #
567///   # struct Error;
568///   #
569///   # macro_rules! make_error {
570///   #     ($($args:expr),*) => {
571///   #         core::hint::must_use({
572///   #             // If `let` isn't used, then `f()` produces a non-Send future.
573///   #             let error = make_error(core::format_args!($($args),*));
574///   #             error
575///   #         })
576///   #     };
577///   # }
578///   #
579///   # fn make_error(args: core::fmt::Arguments<'_>) -> Error {
580///   #     Error
581///   # }
582///   #
583///   async fn f() {
584///       // Using `let` inside the make_error expansion causes temporaries like
585///       // `unsync()` to drop at the semicolon of that `let` statement, which
586///       // is prior to the await point. They would otherwise stay around until
587///       // the semicolon on *this* statement, which is after the await point,
588///       // and the enclosing Future would not implement Send.
589///       log(make_error!("look: {:p}", unsync())).await;
590///   }
591///
592///   async fn log(error: Error) {/* ... */}
593///
594///   // Returns something without a Sync impl.
595///   fn unsync() -> *const () {
596///       0 as *const ()
597///   }
598///   #
599///   # fn test() {
600///   #     fn assert_send(_: impl Send) {}
601///   #     assert_send(f());
602///   # }
603///   ```
604#[unstable(feature = "hint_must_use", issue = "94745")]
605#[must_use] // <-- :)
606#[inline(always)]
607#[cfg(not(feature = "ferrocene_subset"))]
608pub const fn must_use<T>(value: T) -> T {
609    value
610}
611
612/// Hints to the compiler that a branch condition is likely to be true.
613/// Returns the value passed to it.
614///
615/// It can be used with `if` or boolean `match` expressions.
616///
617/// When used outside of a branch condition, it may still influence a nearby branch, but
618/// probably will not have any effect.
619///
620/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
621/// compound expressions, such as `likely(a && b)`. When applied to compound expressions, it has
622/// the following effect:
623/// ```text
624///     likely(!a) => !unlikely(a)
625///     likely(a && b) => likely(a) && likely(b)
626///     likely(a || b) => a || likely(b)
627/// ```
628///
629/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
630///
631/// # Examples
632///
633/// ```
634/// #![feature(likely_unlikely)]
635/// use core::hint::likely;
636///
637/// fn foo(x: i32) {
638///     if likely(x > 0) {
639///         println!("this branch is likely to be taken");
640///     } else {
641///         println!("this branch is unlikely to be taken");
642///     }
643///
644///     match likely(x > 0) {
645///         true => println!("this branch is likely to be taken"),
646///         false => println!("this branch is unlikely to be taken"),
647///     }
648///
649///     // Use outside of a branch condition may still influence a nearby branch
650///     let cond = likely(x != 0);
651///     if cond {
652///         println!("this branch is likely to be taken");
653///     }
654/// }
655/// ```
656#[unstable(feature = "likely_unlikely", issue = "136873")]
657#[inline(always)]
658#[cfg(not(feature = "ferrocene_subset"))]
659pub const fn likely(b: bool) -> bool {
660    crate::intrinsics::likely(b)
661}
662
663/// Hints to the compiler that a branch condition is unlikely to be true.
664/// Returns the value passed to it.
665///
666/// It can be used with `if` or boolean `match` expressions.
667///
668/// When used outside of a branch condition, it may still influence a nearby branch, but
669/// probably will not have any effect.
670///
671/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
672/// compound expressions, such as `unlikely(a && b)`. When applied to compound expressions, it has
673/// the following effect:
674/// ```text
675///     unlikely(!a) => !likely(a)
676///     unlikely(a && b) => a && unlikely(b)
677///     unlikely(a || b) => unlikely(a) || unlikely(b)
678/// ```
679///
680/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
681///
682/// # Examples
683///
684/// ```
685/// #![feature(likely_unlikely)]
686/// use core::hint::unlikely;
687///
688/// fn foo(x: i32) {
689///     if unlikely(x > 0) {
690///         println!("this branch is unlikely to be taken");
691///     } else {
692///         println!("this branch is likely to be taken");
693///     }
694///
695///     match unlikely(x > 0) {
696///         true => println!("this branch is unlikely to be taken"),
697///         false => println!("this branch is likely to be taken"),
698///     }
699///
700///     // Use outside of a branch condition may still influence a nearby branch
701///     let cond = unlikely(x != 0);
702///     if cond {
703///         println!("this branch is likely to be taken");
704///     }
705/// }
706/// ```
707#[unstable(feature = "likely_unlikely", issue = "136873")]
708#[inline(always)]
709#[cfg(not(feature = "ferrocene_subset"))]
710pub const fn unlikely(b: bool) -> bool {
711    crate::intrinsics::unlikely(b)
712}
713
714/// Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may
715/// choose to optimize paths that are not cold at the expense of paths that are cold.
716///
717/// # Examples
718///
719/// ```
720/// #![feature(cold_path)]
721/// use core::hint::cold_path;
722///
723/// fn foo(x: &[i32]) {
724///     if let Some(first) = x.get(0) {
725///         // this is the fast path
726///     } else {
727///         // this path is unlikely
728///         cold_path();
729///     }
730/// }
731///
732/// fn bar(x: i32) -> i32 {
733///     match x {
734///         1 => 10,
735///         2 => 100,
736///         3 => { cold_path(); 1000 }, // this branch is unlikely
737///         _ => { cold_path(); 10000 }, // this is also unlikely
738///     }
739/// }
740/// ```
741#[unstable(feature = "cold_path", issue = "136873")]
742#[inline(always)]
743#[cfg(not(feature = "ferrocene_subset"))]
744pub const fn cold_path() {
745    crate::intrinsics::cold_path()
746}
747
748/// Returns either `true_val` or `false_val` depending on the value of
749/// `condition`, with a hint to the compiler that `condition` is unlikely to be
750/// correctly predicted by a CPU’s branch predictor.
751///
752/// This method is functionally equivalent to
753/// ```ignore (this is just for illustrative purposes)
754/// fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
755///     if b { true_val } else { false_val }
756/// }
757/// ```
758/// but might generate different assembly. In particular, on platforms with
759/// a conditional move or select instruction (like `cmov` on x86 or `csel`
760/// on ARM) the optimizer might use these instructions to avoid branches,
761/// which can benefit performance if the branch predictor is struggling
762/// with predicting `condition`, such as in an implementation of binary
763/// search.
764///
765/// Note however that this lowering is not guaranteed (on any platform) and
766/// should not be relied upon when trying to write cryptographic constant-time
767/// code. Also be aware that this lowering might *decrease* performance if
768/// `condition` is well-predictable. It is advisable to perform benchmarks to
769/// tell if this function is useful.
770///
771/// # Examples
772///
773/// Distribute values evenly between two buckets:
774/// ```
775/// use std::hash::BuildHasher;
776/// use std::hint;
777///
778/// fn append<H: BuildHasher>(hasher: &H, v: i32, bucket_one: &mut Vec<i32>, bucket_two: &mut Vec<i32>) {
779///     let hash = hasher.hash_one(&v);
780///     let bucket = hint::select_unpredictable(hash % 2 == 0, bucket_one, bucket_two);
781///     bucket.push(v);
782/// }
783/// # let hasher = std::collections::hash_map::RandomState::new();
784/// # let mut bucket_one = Vec::new();
785/// # let mut bucket_two = Vec::new();
786/// # append(&hasher, 42, &mut bucket_one, &mut bucket_two);
787/// # assert_eq!(bucket_one.len() + bucket_two.len(), 1);
788/// ```
789#[inline(always)]
790#[stable(feature = "select_unpredictable", since = "1.88.0")]
791#[rustc_const_unstable(feature = "const_select_unpredictable", issue = "145938")]
792pub const fn select_unpredictable<T>(condition: bool, true_val: T, false_val: T) -> T
793where
794    T: [const] Destruct,
795{
796    // FIXME(https://github.com/rust-lang/unsafe-code-guidelines/issues/245):
797    // Change this to use ManuallyDrop instead.
798    let mut true_val = MaybeUninit::new(true_val);
799    let mut false_val = MaybeUninit::new(false_val);
800
801    struct DropOnPanic<T> {
802        // Invariant: valid pointer and points to an initialized value that is not further used,
803        // i.e. it can be dropped by this guard.
804        inner: *mut T,
805    }
806
807    impl<T> Drop for DropOnPanic<T> {
808        fn drop(&mut self) {
809            // SAFETY: Must be guaranteed on construction of local type `DropOnPanic`.
810            unsafe { self.inner.drop_in_place() }
811        }
812    }
813
814    let true_ptr = true_val.as_mut_ptr();
815    let false_ptr = false_val.as_mut_ptr();
816
817    // SAFETY: The value that is not selected is dropped, and the selected one
818    // is returned. This is necessary because the intrinsic doesn't drop the
819    // value that is  not selected.
820    unsafe {
821        // Extract the selected value first, ensure it is dropped as well if dropping the unselected
822        // value panics. We construct a temporary by-pointer guard around the selected value while
823        // dropping the unselected value. Arguments overlap here, so we can not use mutable
824        // reference for these arguments.
825        let guard = crate::intrinsics::select_unpredictable(condition, true_ptr, false_ptr);
826        let drop = crate::intrinsics::select_unpredictable(condition, false_ptr, true_ptr);
827
828        // SAFETY: both pointers are well-aligned and point to initialized values inside a
829        // `MaybeUninit` each. In both possible values for `condition` the pointer `guard` and
830        // `drop` do not alias (even though the two argument pairs we have selected from did alias
831        // each other).
832        let guard = DropOnPanic { inner: guard };
833        drop.drop_in_place();
834        crate::mem::forget(guard);
835
836        // Note that it is important to use the values here. Reading from the pointer we got makes
837        // LLVM forget the !unpredictable annotation sometimes (in tests, integer sized values in
838        // particular seemed to confuse it, also observed in llvm/llvm-project #82340).
839        crate::intrinsics::select_unpredictable(condition, true_val, false_val).assume_init()
840    }
841}
842
843/// The expected temporal locality of a memory prefetch operation.
844///
845/// Locality expresses how likely the prefetched data is to be reused soon,
846/// and therefore which level of cache it should be brought into.
847///
848/// The locality is just a hint, and may be ignored on some targets or by the hardware.
849///
850/// Used with functions like [`prefetch_read`] and [`prefetch_write`].
851///
852/// [`prefetch_read`]: crate::hint::prefetch_read
853/// [`prefetch_write`]: crate::hint::prefetch_write
854#[cfg(not(feature = "ferrocene_subset"))]
855#[unstable(feature = "hint_prefetch", issue = "146941")]
856#[non_exhaustive]
857#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
858pub enum Locality {
859    /// Data is expected to be reused eventually.
860    ///
861    /// Typically prefetches into L3 cache (if the CPU supports it).
862    L3,
863    /// Data is expected to be reused in the near future.
864    ///
865    /// Typically prefetches into L2 cache.
866    L2,
867    /// Data is expected to be reused very soon.
868    ///
869    /// Typically prefetches into L1 cache.
870    L1,
871}
872
873#[cfg(not(feature = "ferrocene_subset"))]
874impl Locality {
875    /// Convert to the constant that LLVM associates with a locality.
876    const fn to_llvm(self) -> i32 {
877        match self {
878            Self::L3 => 1,
879            Self::L2 => 2,
880            Self::L1 => 3,
881        }
882    }
883}
884
885/// Prefetch the cache line containing `ptr` for a future read.
886///
887/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
888/// soon after, but may also increase bandwidth usage or evict other cache lines.
889///
890/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
891///
892/// Passing a dangling or invalid pointer is permitted: the memory will not
893/// actually be dereferenced, and no faults are raised.
894///
895/// # Examples
896///
897/// ```
898/// #![feature(hint_prefetch)]
899/// use std::hint::{Locality, prefetch_read};
900/// use std::mem::size_of_val;
901///
902/// // Prefetch all of `slice` into the L1 cache.
903/// fn prefetch_slice<T>(slice: &[T]) {
904///     // On most systems the cache line size is 64 bytes.
905///     for offset in (0..size_of_val(slice)).step_by(64) {
906///         prefetch_read(slice.as_ptr().wrapping_add(offset), Locality::L1);
907///     }
908/// }
909/// ```
910#[cfg(not(feature = "ferrocene_subset"))]
911#[inline(always)]
912#[unstable(feature = "hint_prefetch", issue = "146941")]
913pub const fn prefetch_read<T>(ptr: *const T, locality: Locality) {
914    match locality {
915        Locality::L3 => intrinsics::prefetch_read_data::<T, { Locality::L3.to_llvm() }>(ptr),
916        Locality::L2 => intrinsics::prefetch_read_data::<T, { Locality::L2.to_llvm() }>(ptr),
917        Locality::L1 => intrinsics::prefetch_read_data::<T, { Locality::L1.to_llvm() }>(ptr),
918    }
919}
920
921/// Prefetch the cache line containing `ptr` for a single future read, but attempt to avoid
922/// polluting the cache.
923///
924/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
925/// soon after, but may also increase bandwidth usage or evict other cache lines.
926///
927/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
928///
929/// Passing a dangling or invalid pointer is permitted: the memory will not
930/// actually be dereferenced, and no faults are raised.
931#[cfg(not(feature = "ferrocene_subset"))]
932#[inline(always)]
933#[unstable(feature = "hint_prefetch", issue = "146941")]
934pub const fn prefetch_read_non_temporal<T>(ptr: *const T, locality: Locality) {
935    // The LLVM intrinsic does not currently support specifying the locality.
936    let _ = locality;
937    intrinsics::prefetch_read_data::<T, 0>(ptr)
938}
939
940/// Prefetch the cache line containing `ptr` for a future write.
941///
942/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
943/// soon after, but may also increase bandwidth usage or evict other cache lines.
944///
945/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
946///
947/// Passing a dangling or invalid pointer is permitted: the memory will not
948/// actually be dereferenced, and no faults are raised.
949#[cfg(not(feature = "ferrocene_subset"))]
950#[inline(always)]
951#[unstable(feature = "hint_prefetch", issue = "146941")]
952pub const fn prefetch_write<T>(ptr: *mut T, locality: Locality) {
953    match locality {
954        Locality::L3 => intrinsics::prefetch_write_data::<T, { Locality::L3.to_llvm() }>(ptr),
955        Locality::L2 => intrinsics::prefetch_write_data::<T, { Locality::L2.to_llvm() }>(ptr),
956        Locality::L1 => intrinsics::prefetch_write_data::<T, { Locality::L1.to_llvm() }>(ptr),
957    }
958}
959
960/// Prefetch the cache line containing `ptr` for a single future write, but attempt to avoid
961/// polluting the cache.
962///
963/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
964/// soon after, but may also increase bandwidth usage or evict other cache lines.
965///
966/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
967///
968/// Passing a dangling or invalid pointer is permitted: the memory will not
969/// actually be dereferenced, and no faults are raised.
970#[cfg(not(feature = "ferrocene_subset"))]
971#[inline(always)]
972#[unstable(feature = "hint_prefetch", issue = "146941")]
973pub const fn prefetch_write_non_temporal<T>(ptr: *const T, locality: Locality) {
974    // The LLVM intrinsic does not currently support specifying the locality.
975    let _ = locality;
976    intrinsics::prefetch_write_data::<T, 0>(ptr)
977}
978
979/// Prefetch the cache line containing `ptr` into the instruction cache for a future read.
980///
981/// A strategically placed prefetch can reduce cache miss latency if the instructions are
982/// accessed soon after, but may also increase bandwidth usage or evict other cache lines.
983///
984/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
985///
986/// Passing a dangling or invalid pointer is permitted: the memory will not
987/// actually be dereferenced, and no faults are raised.
988#[cfg(not(feature = "ferrocene_subset"))]
989#[inline(always)]
990#[unstable(feature = "hint_prefetch", issue = "146941")]
991pub const fn prefetch_read_instruction<T>(ptr: *const T, locality: Locality) {
992    match locality {
993        Locality::L3 => intrinsics::prefetch_read_instruction::<T, { Locality::L3.to_llvm() }>(ptr),
994        Locality::L2 => intrinsics::prefetch_read_instruction::<T, { Locality::L2.to_llvm() }>(ptr),
995        Locality::L1 => intrinsics::prefetch_read_instruction::<T, { Locality::L1.to_llvm() }>(ptr),
996    }
997}