core/intrinsics/mod.rs
1//! Compiler intrinsics.
2//!
3//! The functions in this module are implementation details of `core` and should
4//! not be used outside of the standard library. We generally provide access to
5//! intrinsics via stable wrapper functions. Use these instead.
6//!
7//! These are the imports making intrinsics available to Rust code. The actual implementations live in the compiler.
8//! Some of these intrinsics are lowered to MIR in <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_mir_transform/src/lower_intrinsics.rs>.
9//! The remaining intrinsics are implemented for the LLVM backend in <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs>
10//! and <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_codegen_llvm/src/intrinsic.rs>,
11//! and for const evaluation in <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_const_eval/src/interpret/intrinsics.rs>.
12//!
13//! # Const intrinsics
14//!
15//! In order to make an intrinsic unstable usable at compile-time, copy the implementation from
16//! <https://github.com/rust-lang/miri/blob/master/src/intrinsics> to
17//! <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_const_eval/src/interpret/intrinsics.rs>
18//! and make the intrinsic declaration below a `const fn`. This should be done in coordination with
19//! wg-const-eval.
20//!
21//! If an intrinsic is supposed to be used from a `const fn` with a `rustc_const_stable` attribute,
22//! `#[rustc_intrinsic_const_stable_indirect]` needs to be added to the intrinsic. Such a change requires
23//! T-lang approval, because it may bake a feature into the language that cannot be replicated in
24//! user code without compiler support.
25//!
26//! # Volatiles
27//!
28//! The volatile intrinsics provide operations intended to act on I/O
29//! memory, which are guaranteed to not be reordered by the compiler
30//! across other volatile intrinsics. See [`read_volatile`][ptr::read_volatile]
31//! and [`write_volatile`][ptr::write_volatile].
32//!
33//! # Atomics
34//!
35//! The atomic intrinsics provide common atomic operations on machine
36//! words, with multiple possible memory orderings. See the
37//! [atomic types][atomic] docs for details.
38//!
39//! # Unwinding
40//!
41//! Rust intrinsics may, in general, unwind. If an intrinsic can never unwind, add the
42//! `#[rustc_nounwind]` attribute so that the compiler can make use of this fact.
43//!
44//! However, even for intrinsics that may unwind, rustc assumes that a Rust intrinsics will never
45//! initiate a foreign (non-Rust) unwind, and thus for panic=abort we can always assume that these
46//! intrinsics cannot unwind.
47
48#![unstable(
49 feature = "core_intrinsics",
50 reason = "intrinsics are unlikely to ever be stabilized, instead \
51 they should be used through stabilized interfaces \
52 in the rest of the standard library",
53 issue = "none"
54)]
55#![allow(missing_docs)]
56
57use crate::ffi::va_list::{VaArgSafe, VaListImpl};
58use crate::marker::{ConstParamTy, Destruct, DiscriminantKind, PointeeSized, Tuple};
59use crate::ptr;
60
61mod bounds;
62pub mod fallback;
63pub mod mir;
64pub mod simd;
65
66// These imports are used for simplifying intra-doc links
67#[allow(unused_imports)]
68#[cfg(all(target_has_atomic = "8", target_has_atomic = "32", target_has_atomic = "ptr"))]
69use crate::sync::atomic::{self, AtomicBool, AtomicI32, AtomicIsize, AtomicU32, Ordering};
70
71/// A type for atomic ordering parameters for intrinsics. This is a separate type from
72/// `atomic::Ordering` so that we can make it `ConstParamTy` and fix the values used here without a
73/// risk of leaking that to stable code.
74#[derive(Debug, ConstParamTy, PartialEq, Eq)]
75pub enum AtomicOrdering {
76 // These values must match the compiler's `AtomicOrdering` defined in
77 // `rustc_middle/src/ty/consts/int.rs`!
78 Relaxed = 0,
79 Release = 1,
80 Acquire = 2,
81 AcqRel = 3,
82 SeqCst = 4,
83}
84
85// N.B., these intrinsics take raw pointers because they mutate aliased
86// memory, which is not valid for either `&` or `&mut`.
87
88/// Stores a value if the current value is the same as the `old` value.
89/// `T` must be an integer or pointer type.
90///
91/// The stabilized version of this intrinsic is available on the
92/// [`atomic`] types via the `compare_exchange` method.
93/// For example, [`AtomicBool::compare_exchange`].
94#[rustc_intrinsic]
95#[rustc_nounwind]
96pub unsafe fn atomic_cxchg<
97 T: Copy,
98 const ORD_SUCC: AtomicOrdering,
99 const ORD_FAIL: AtomicOrdering,
100>(
101 dst: *mut T,
102 old: T,
103 src: T,
104) -> (T, bool);
105
106/// Stores a value if the current value is the same as the `old` value.
107/// `T` must be an integer or pointer type. The comparison may spuriously fail.
108///
109/// The stabilized version of this intrinsic is available on the
110/// [`atomic`] types via the `compare_exchange_weak` method.
111/// For example, [`AtomicBool::compare_exchange_weak`].
112#[rustc_intrinsic]
113#[rustc_nounwind]
114pub unsafe fn atomic_cxchgweak<
115 T: Copy,
116 const ORD_SUCC: AtomicOrdering,
117 const ORD_FAIL: AtomicOrdering,
118>(
119 _dst: *mut T,
120 _old: T,
121 _src: T,
122) -> (T, bool);
123
124/// Loads the current value of the pointer.
125/// `T` must be an integer or pointer type.
126///
127/// The stabilized version of this intrinsic is available on the
128/// [`atomic`] types via the `load` method. For example, [`AtomicBool::load`].
129#[rustc_intrinsic]
130#[rustc_nounwind]
131pub unsafe fn atomic_load<T: Copy, const ORD: AtomicOrdering>(src: *const T) -> T;
132
133/// Stores the value at the specified memory location.
134/// `T` must be an integer or pointer type.
135///
136/// The stabilized version of this intrinsic is available on the
137/// [`atomic`] types via the `store` method. For example, [`AtomicBool::store`].
138#[rustc_intrinsic]
139#[rustc_nounwind]
140pub unsafe fn atomic_store<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, val: T);
141
142/// Stores the value at the specified memory location, returning the old value.
143/// `T` must be an integer or pointer type.
144///
145/// The stabilized version of this intrinsic is available on the
146/// [`atomic`] types via the `swap` method. For example, [`AtomicBool::swap`].
147#[rustc_intrinsic]
148#[rustc_nounwind]
149pub unsafe fn atomic_xchg<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
150
151/// Adds to the current value, returning the previous value.
152/// `T` must be an integer or pointer type.
153/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
154///
155/// The stabilized version of this intrinsic is available on the
156/// [`atomic`] types via the `fetch_add` method. For example, [`AtomicIsize::fetch_add`].
157#[rustc_intrinsic]
158#[rustc_nounwind]
159pub unsafe fn atomic_xadd<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
160
161/// Subtract from the current value, returning the previous value.
162/// `T` must be an integer or pointer type.
163/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
164///
165/// The stabilized version of this intrinsic is available on the
166/// [`atomic`] types via the `fetch_sub` method. For example, [`AtomicIsize::fetch_sub`].
167#[rustc_intrinsic]
168#[rustc_nounwind]
169pub unsafe fn atomic_xsub<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
170
171/// Bitwise and with the current value, returning the previous value.
172/// `T` must be an integer or pointer type.
173/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
174///
175/// The stabilized version of this intrinsic is available on the
176/// [`atomic`] types via the `fetch_and` method. For example, [`AtomicBool::fetch_and`].
177#[rustc_intrinsic]
178#[rustc_nounwind]
179pub unsafe fn atomic_and<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
180
181/// Bitwise nand with the current value, returning the previous value.
182/// `T` must be an integer or pointer type.
183/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
184///
185/// The stabilized version of this intrinsic is available on the
186/// [`AtomicBool`] type via the `fetch_nand` method. For example, [`AtomicBool::fetch_nand`].
187#[rustc_intrinsic]
188#[rustc_nounwind]
189pub unsafe fn atomic_nand<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
190
191/// Bitwise or with the current value, returning the previous value.
192/// `T` must be an integer or pointer type.
193/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
194///
195/// The stabilized version of this intrinsic is available on the
196/// [`atomic`] types via the `fetch_or` method. For example, [`AtomicBool::fetch_or`].
197#[rustc_intrinsic]
198#[rustc_nounwind]
199pub unsafe fn atomic_or<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
200
201/// Bitwise xor with the current value, returning the previous value.
202/// `T` must be an integer or pointer type.
203/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
204///
205/// The stabilized version of this intrinsic is available on the
206/// [`atomic`] types via the `fetch_xor` method. For example, [`AtomicBool::fetch_xor`].
207#[rustc_intrinsic]
208#[rustc_nounwind]
209pub unsafe fn atomic_xor<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
210
211/// Maximum with the current value using a signed comparison.
212/// `T` must be a signed integer type.
213///
214/// The stabilized version of this intrinsic is available on the
215/// [`atomic`] signed integer types via the `fetch_max` method. For example, [`AtomicI32::fetch_max`].
216#[rustc_intrinsic]
217#[rustc_nounwind]
218pub unsafe fn atomic_max<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
219
220/// Minimum with the current value using a signed comparison.
221/// `T` must be a signed integer type.
222///
223/// The stabilized version of this intrinsic is available on the
224/// [`atomic`] signed integer types via the `fetch_min` method. For example, [`AtomicI32::fetch_min`].
225#[rustc_intrinsic]
226#[rustc_nounwind]
227pub unsafe fn atomic_min<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
228
229/// Minimum with the current value using an unsigned comparison.
230/// `T` must be an unsigned integer type.
231///
232/// The stabilized version of this intrinsic is available on the
233/// [`atomic`] unsigned integer types via the `fetch_min` method. For example, [`AtomicU32::fetch_min`].
234#[rustc_intrinsic]
235#[rustc_nounwind]
236pub unsafe fn atomic_umin<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
237
238/// Maximum with the current value using an unsigned comparison.
239/// `T` must be an unsigned integer type.
240///
241/// The stabilized version of this intrinsic is available on the
242/// [`atomic`] unsigned integer types via the `fetch_max` method. For example, [`AtomicU32::fetch_max`].
243#[rustc_intrinsic]
244#[rustc_nounwind]
245pub unsafe fn atomic_umax<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
246
247/// An atomic fence.
248///
249/// The stabilized version of this intrinsic is available in
250/// [`atomic::fence`].
251#[rustc_intrinsic]
252#[rustc_nounwind]
253pub unsafe fn atomic_fence<const ORD: AtomicOrdering>();
254
255/// An atomic fence for synchronization within a single thread.
256///
257/// The stabilized version of this intrinsic is available in
258/// [`atomic::compiler_fence`].
259#[rustc_intrinsic]
260#[rustc_nounwind]
261pub unsafe fn atomic_singlethreadfence<const ORD: AtomicOrdering>();
262
263/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
264/// for the given address if supported; otherwise, it is a no-op.
265/// Prefetches have no effect on the behavior of the program but can change its performance
266/// characteristics.
267///
268/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
269/// to (3) - extremely local keep in cache.
270///
271/// This intrinsic does not have a stable counterpart.
272#[rustc_intrinsic]
273#[rustc_nounwind]
274#[miri::intrinsic_fallback_is_spec]
275pub const fn prefetch_read_data<T, const LOCALITY: i32>(data: *const T) {
276 // This operation is a no-op, unless it is overridden by the backend.
277 let _ = data;
278}
279
280/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
281/// for the given address if supported; otherwise, it is a no-op.
282/// Prefetches have no effect on the behavior of the program but can change its performance
283/// characteristics.
284///
285/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
286/// to (3) - extremely local keep in cache.
287///
288/// This intrinsic does not have a stable counterpart.
289#[rustc_intrinsic]
290#[rustc_nounwind]
291#[miri::intrinsic_fallback_is_spec]
292pub const fn prefetch_write_data<T, const LOCALITY: i32>(data: *const T) {
293 // This operation is a no-op, unless it is overridden by the backend.
294 let _ = data;
295}
296
297/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
298/// for the given address if supported; otherwise, it is a no-op.
299/// Prefetches have no effect on the behavior of the program but can change its performance
300/// characteristics.
301///
302/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
303/// to (3) - extremely local keep in cache.
304///
305/// This intrinsic does not have a stable counterpart.
306#[rustc_intrinsic]
307#[rustc_nounwind]
308#[miri::intrinsic_fallback_is_spec]
309pub const fn prefetch_read_instruction<T, const LOCALITY: i32>(data: *const T) {
310 // This operation is a no-op, unless it is overridden by the backend.
311 let _ = data;
312}
313
314/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
315/// for the given address if supported; otherwise, it is a no-op.
316/// Prefetches have no effect on the behavior of the program but can change its performance
317/// characteristics.
318///
319/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
320/// to (3) - extremely local keep in cache.
321///
322/// This intrinsic does not have a stable counterpart.
323#[rustc_intrinsic]
324#[rustc_nounwind]
325#[miri::intrinsic_fallback_is_spec]
326pub const fn prefetch_write_instruction<T, const LOCALITY: i32>(data: *const T) {
327 // This operation is a no-op, unless it is overridden by the backend.
328 let _ = data;
329}
330
331/// Executes a breakpoint trap, for inspection by a debugger.
332///
333/// This intrinsic does not have a stable counterpart.
334#[rustc_intrinsic]
335#[rustc_nounwind]
336pub fn breakpoint();
337
338/// Magic intrinsic that derives its meaning from attributes
339/// attached to the function.
340///
341/// For example, dataflow uses this to inject static assertions so
342/// that `rustc_peek(potentially_uninitialized)` would actually
343/// double-check that dataflow did indeed compute that it is
344/// uninitialized at that point in the control flow.
345///
346/// This intrinsic should not be used outside of the compiler.
347#[rustc_nounwind]
348#[rustc_intrinsic]
349pub fn rustc_peek<T>(_: T) -> T;
350
351/// Aborts the execution of the process.
352///
353/// Note that, unlike most intrinsics, this is safe to call;
354/// it does not require an `unsafe` block.
355/// Therefore, implementations must not require the user to uphold
356/// any safety invariants.
357///
358/// [`std::process::abort`](../../std/process/fn.abort.html) is to be preferred if possible,
359/// as its behavior is more user-friendly and more stable.
360///
361/// The current implementation of `intrinsics::abort` is to invoke an invalid instruction,
362/// on most platforms.
363/// On Unix, the
364/// process will probably terminate with a signal like `SIGABRT`, `SIGILL`, `SIGTRAP`, `SIGSEGV` or
365/// `SIGBUS`. The precise behavior is not guaranteed and not stable.
366#[rustc_nounwind]
367#[rustc_intrinsic]
368pub fn abort() -> !;
369
370/// Informs the optimizer that this point in the code is not reachable,
371/// enabling further optimizations.
372///
373/// N.B., this is very different from the `unreachable!()` macro: Unlike the
374/// macro, which panics when it is executed, it is *undefined behavior* to
375/// reach code marked with this function.
376///
377/// The stabilized version of this intrinsic is [`core::hint::unreachable_unchecked`].
378#[rustc_intrinsic_const_stable_indirect]
379#[rustc_nounwind]
380#[rustc_intrinsic]
381pub const unsafe fn unreachable() -> !;
382
383/// Informs the optimizer that a condition is always true.
384/// If the condition is false, the behavior is undefined.
385///
386/// No code is generated for this intrinsic, but the optimizer will try
387/// to preserve it (and its condition) between passes, which may interfere
388/// with optimization of surrounding code and reduce performance. It should
389/// not be used if the invariant can be discovered by the optimizer on its
390/// own, or if it does not enable any significant optimizations.
391///
392/// The stabilized version of this intrinsic is [`core::hint::assert_unchecked`].
393#[rustc_intrinsic_const_stable_indirect]
394#[rustc_nounwind]
395#[unstable(feature = "core_intrinsics", issue = "none")]
396#[rustc_intrinsic]
397pub const unsafe fn assume(b: bool) {
398 if !b {
399 // SAFETY: the caller must guarantee the argument is never `false`
400 unsafe { unreachable() }
401 }
402}
403
404/// Hints to the compiler that current code path is cold.
405///
406/// Note that, unlike most intrinsics, this is safe to call;
407/// it does not require an `unsafe` block.
408/// Therefore, implementations must not require the user to uphold
409/// any safety invariants.
410///
411/// This intrinsic does not have a stable counterpart.
412#[unstable(feature = "core_intrinsics", issue = "none")]
413#[rustc_intrinsic]
414#[rustc_nounwind]
415#[miri::intrinsic_fallback_is_spec]
416#[cold]
417pub const fn cold_path() {}
418
419/// Hints to the compiler that branch condition is likely to be true.
420/// Returns the value passed to it.
421///
422/// Any use other than with `if` statements will probably not have an effect.
423///
424/// Note that, unlike most intrinsics, this is safe to call;
425/// it does not require an `unsafe` block.
426/// Therefore, implementations must not require the user to uphold
427/// any safety invariants.
428///
429/// This intrinsic does not have a stable counterpart.
430#[unstable(feature = "core_intrinsics", issue = "none")]
431#[rustc_nounwind]
432#[inline(always)]
433pub const fn likely(b: bool) -> bool {
434 if b {
435 true
436 } else {
437 cold_path();
438 false
439 }
440}
441
442/// Hints to the compiler that branch condition is likely to be false.
443/// Returns the value passed to it.
444///
445/// Any use other than with `if` statements will probably not have an effect.
446///
447/// Note that, unlike most intrinsics, this is safe to call;
448/// it does not require an `unsafe` block.
449/// Therefore, implementations must not require the user to uphold
450/// any safety invariants.
451///
452/// This intrinsic does not have a stable counterpart.
453#[unstable(feature = "core_intrinsics", issue = "none")]
454#[rustc_nounwind]
455#[inline(always)]
456pub const fn unlikely(b: bool) -> bool {
457 if b {
458 cold_path();
459 true
460 } else {
461 false
462 }
463}
464
465/// Returns either `true_val` or `false_val` depending on condition `b` with a
466/// hint to the compiler that this condition is unlikely to be correctly
467/// predicted by a CPU's branch predictor (e.g. a binary search).
468///
469/// This is otherwise functionally equivalent to `if b { true_val } else { false_val }`.
470///
471/// Note that, unlike most intrinsics, this is safe to call;
472/// it does not require an `unsafe` block.
473/// Therefore, implementations must not require the user to uphold
474/// any safety invariants.
475///
476/// The public form of this intrinsic is [`core::hint::select_unpredictable`].
477/// However unlike the public form, the intrinsic will not drop the value that
478/// is not selected.
479#[unstable(feature = "core_intrinsics", issue = "none")]
480#[rustc_const_unstable(feature = "const_select_unpredictable", issue = "145938")]
481#[rustc_intrinsic]
482#[rustc_nounwind]
483#[miri::intrinsic_fallback_is_spec]
484#[inline]
485pub const fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T
486where
487 T: [const] Destruct,
488{
489 if b { true_val } else { false_val }
490}
491
492/// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited:
493/// This will statically either panic, or do nothing. It does not *guarantee* to ever panic,
494/// and should only be called if an assertion failure will imply language UB in the following code.
495///
496/// This intrinsic does not have a stable counterpart.
497#[rustc_intrinsic_const_stable_indirect]
498#[rustc_nounwind]
499#[rustc_intrinsic]
500pub const fn assert_inhabited<T>();
501
502/// A guard for unsafe functions that cannot ever be executed if `T` does not permit
503/// zero-initialization: This will statically either panic, or do nothing. It does not *guarantee*
504/// to ever panic, and should only be called if an assertion failure will imply language UB in the
505/// following code.
506///
507/// This intrinsic does not have a stable counterpart.
508#[rustc_intrinsic_const_stable_indirect]
509#[rustc_nounwind]
510#[rustc_intrinsic]
511pub const fn assert_zero_valid<T>();
512
513/// A guard for `std::mem::uninitialized`. This will statically either panic, or do nothing. It does
514/// not *guarantee* to ever panic, and should only be called if an assertion failure will imply
515/// language UB in the following code.
516///
517/// This intrinsic does not have a stable counterpart.
518#[rustc_intrinsic_const_stable_indirect]
519#[rustc_nounwind]
520#[rustc_intrinsic]
521pub const fn assert_mem_uninitialized_valid<T>();
522
523/// Gets a reference to a static `Location` indicating where it was called.
524///
525/// Note that, unlike most intrinsics, this is safe to call;
526/// it does not require an `unsafe` block.
527/// Therefore, implementations must not require the user to uphold
528/// any safety invariants.
529///
530/// Consider using [`core::panic::Location::caller`] instead.
531#[rustc_intrinsic_const_stable_indirect]
532#[rustc_nounwind]
533#[rustc_intrinsic]
534pub const fn caller_location() -> &'static crate::panic::Location<'static>;
535
536/// Moves a value out of scope without running drop glue.
537///
538/// This exists solely for [`crate::mem::forget_unsized`]; normal `forget` uses
539/// `ManuallyDrop` instead.
540///
541/// Note that, unlike most intrinsics, this is safe to call;
542/// it does not require an `unsafe` block.
543/// Therefore, implementations must not require the user to uphold
544/// any safety invariants.
545#[rustc_intrinsic_const_stable_indirect]
546#[rustc_nounwind]
547#[rustc_intrinsic]
548pub const fn forget<T: ?Sized>(_: T);
549
550/// Reinterprets the bits of a value of one type as another type.
551///
552/// Both types must have the same size. Compilation will fail if this is not guaranteed.
553///
554/// `transmute` is semantically equivalent to a bitwise move of one type
555/// into another. It copies the bits from the source value into the
556/// destination value, then forgets the original. Note that source and destination
557/// are passed by-value, which means if `Src` or `Dst` contain padding, that padding
558/// is *not* guaranteed to be preserved by `transmute`.
559///
560/// Both the argument and the result must be [valid](../../nomicon/what-unsafe-does.html) at
561/// their given type. Violating this condition leads to [undefined behavior][ub]. The compiler
562/// will generate code *assuming that you, the programmer, ensure that there will never be
563/// undefined behavior*. It is therefore your responsibility to guarantee that every value
564/// passed to `transmute` is valid at both types `Src` and `Dst`. Failing to uphold this condition
565/// may lead to unexpected and unstable compilation results. This makes `transmute` **incredibly
566/// unsafe**. `transmute` should be the absolute last resort.
567///
568/// Because `transmute` is a by-value operation, alignment of the *transmuted values
569/// themselves* is not a concern. As with any other function, the compiler already ensures
570/// both `Src` and `Dst` are properly aligned. However, when transmuting values that *point
571/// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper
572/// alignment of the pointed-to values.
573///
574/// The [nomicon](../../nomicon/transmutes.html) has additional documentation.
575///
576/// [ub]: ../../reference/behavior-considered-undefined.html
577///
578/// # Transmutation between pointers and integers
579///
580/// Special care has to be taken when transmuting between pointers and integers, e.g.
581/// transmuting between `*const ()` and `usize`.
582///
583/// Transmuting *pointers to integers* in a `const` context is [undefined behavior][ub], unless
584/// the pointer was originally created *from* an integer. (That includes this function
585/// specifically, integer-to-pointer casts, and helpers like [`dangling`][crate::ptr::dangling],
586/// but also semantically-equivalent conversions such as punning through `repr(C)` union
587/// fields.) Any attempt to use the resulting value for integer operations will abort
588/// const-evaluation. (And even outside `const`, such transmutation is touching on many
589/// unspecified aspects of the Rust memory model and should be avoided. See below for
590/// alternatives.)
591///
592/// Transmuting *integers to pointers* is a largely unspecified operation. It is likely *not*
593/// equivalent to an `as` cast. Doing non-zero-sized memory accesses with a pointer constructed
594/// this way is currently considered undefined behavior.
595///
596/// All this also applies when the integer is nested inside an array, tuple, struct, or enum.
597/// However, `MaybeUninit<usize>` is not considered an integer type for the purpose of this
598/// section. Transmuting `*const ()` to `MaybeUninit<usize>` is fine---but then calling
599/// `assume_init()` on that result is considered as completing the pointer-to-integer transmute
600/// and thus runs into the issues discussed above.
601///
602/// In particular, doing a pointer-to-integer-to-pointer roundtrip via `transmute` is *not* a
603/// lossless process. If you want to round-trip a pointer through an integer in a way that you
604/// can get back the original pointer, you need to use `as` casts, or replace the integer type
605/// by `MaybeUninit<$int>` (and never call `assume_init()`). If you are looking for a way to
606/// store data of arbitrary type, also use `MaybeUninit<T>` (that will also handle uninitialized
607/// memory due to padding). If you specifically need to store something that is "either an
608/// integer or a pointer", use `*mut ()`: integers can be converted to pointers and back without
609/// any loss (via `as` casts or via `transmute`).
610///
611/// # Examples
612///
613/// There are a few things that `transmute` is really useful for.
614///
615/// Turning a pointer into a function pointer. This is *not* portable to
616/// machines where function pointers and data pointers have different sizes.
617///
618/// ```
619/// fn foo() -> i32 {
620/// 0
621/// }
622/// // Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
623/// // This avoids an integer-to-pointer `transmute`, which can be problematic.
624/// // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
625/// let pointer = foo as fn() -> i32 as *const ();
626/// let function = unsafe {
627/// std::mem::transmute::<*const (), fn() -> i32>(pointer)
628/// };
629/// assert_eq!(function(), 0);
630/// ```
631///
632/// Extending a lifetime, or shortening an invariant lifetime. This is
633/// advanced, very unsafe Rust!
634///
635/// ```
636/// struct R<'a>(&'a i32);
637/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
638/// unsafe { std::mem::transmute::<R<'b>, R<'static>>(r) }
639/// }
640///
641/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
642/// -> &'b mut R<'c> {
643/// unsafe { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) }
644/// }
645/// ```
646///
647/// # Alternatives
648///
649/// Don't despair: many uses of `transmute` can be achieved through other means.
650/// Below are common applications of `transmute` which can be replaced with safer
651/// constructs.
652///
653/// Turning raw bytes (`[u8; SZ]`) into `u32`, `f64`, etc.:
654///
655/// ```
656/// # #![allow(unnecessary_transmutes)]
657/// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
658///
659/// let num = unsafe {
660/// std::mem::transmute::<[u8; 4], u32>(raw_bytes)
661/// };
662///
663/// // use `u32::from_ne_bytes` instead
664/// let num = u32::from_ne_bytes(raw_bytes);
665/// // or use `u32::from_le_bytes` or `u32::from_be_bytes` to specify the endianness
666/// let num = u32::from_le_bytes(raw_bytes);
667/// assert_eq!(num, 0x12345678);
668/// let num = u32::from_be_bytes(raw_bytes);
669/// assert_eq!(num, 0x78563412);
670/// ```
671///
672/// Turning a pointer into a `usize`:
673///
674/// ```no_run
675/// let ptr = &0;
676/// let ptr_num_transmute = unsafe {
677/// std::mem::transmute::<&i32, usize>(ptr)
678/// };
679///
680/// // Use an `as` cast instead
681/// let ptr_num_cast = ptr as *const i32 as usize;
682/// ```
683///
684/// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined
685/// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave
686/// as expected -- this is touching on many unspecified aspects of the Rust memory model.
687/// Depending on what the code is doing, the following alternatives are preferable to
688/// pointer-to-integer transmutation:
689/// - If the code just wants to store data of arbitrary type in some buffer and needs to pick a
690/// type for that buffer, it can use [`MaybeUninit`][crate::mem::MaybeUninit].
691/// - If the code actually wants to work on the address the pointer points to, it can use `as`
692/// casts or [`ptr.addr()`][pointer::addr].
693///
694/// Turning a `*mut T` into a `&mut T`:
695///
696/// ```
697/// let ptr: *mut i32 = &mut 0;
698/// let ref_transmuted = unsafe {
699/// std::mem::transmute::<*mut i32, &mut i32>(ptr)
700/// };
701///
702/// // Use a reborrow instead
703/// let ref_casted = unsafe { &mut *ptr };
704/// ```
705///
706/// Turning a `&mut T` into a `&mut U`:
707///
708/// ```
709/// let ptr = &mut 0;
710/// let val_transmuted = unsafe {
711/// std::mem::transmute::<&mut i32, &mut u32>(ptr)
712/// };
713///
714/// // Now, put together `as` and reborrowing - note the chaining of `as`
715/// // `as` is not transitive
716/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
717/// ```
718///
719/// Turning a `&str` into a `&[u8]`:
720///
721/// ```
722/// // this is not a good way to do this.
723/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
724/// assert_eq!(slice, &[82, 117, 115, 116]);
725///
726/// // You could use `str::as_bytes`
727/// let slice = "Rust".as_bytes();
728/// assert_eq!(slice, &[82, 117, 115, 116]);
729///
730/// // Or, just use a byte string, if you have control over the string
731/// // literal
732/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
733/// ```
734///
735/// Turning a `Vec<&T>` into a `Vec<Option<&T>>`.
736///
737/// To transmute the inner type of the contents of a container, you must make sure to not
738/// violate any of the container's invariants. For `Vec`, this means that both the size
739/// *and alignment* of the inner types have to match. Other containers might rely on the
740/// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't
741/// be possible at all without violating the container invariants.
742///
743/// ```
744/// let store = [0, 1, 2, 3];
745/// let v_orig = store.iter().collect::<Vec<&i32>>();
746///
747/// // clone the vector as we will reuse them later
748/// let v_clone = v_orig.clone();
749///
750/// // Using transmute: this relies on the unspecified data layout of `Vec`, which is a
751/// // bad idea and could cause Undefined Behavior.
752/// // However, it is no-copy.
753/// let v_transmuted = unsafe {
754/// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(v_clone)
755/// };
756///
757/// let v_clone = v_orig.clone();
758///
759/// // This is the suggested, safe way.
760/// // It may copy the entire vector into a new one though, but also may not.
761/// let v_collected = v_clone.into_iter()
762/// .map(Some)
763/// .collect::<Vec<Option<&i32>>>();
764///
765/// let v_clone = v_orig.clone();
766///
767/// // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the
768/// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but
769/// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`),
770/// // this has all the same caveats. Besides the information provided above, also consult the
771/// // [`from_raw_parts`] documentation.
772/// let v_from_raw = unsafe {
773// FIXME Update this when vec_into_raw_parts is stabilized
774/// // Ensure the original vector is not dropped.
775/// let mut v_clone = std::mem::ManuallyDrop::new(v_clone);
776/// Vec::from_raw_parts(v_clone.as_mut_ptr() as *mut Option<&i32>,
777/// v_clone.len(),
778/// v_clone.capacity())
779/// };
780/// ```
781///
782/// [`from_raw_parts`]: ../../std/vec/struct.Vec.html#method.from_raw_parts
783///
784/// Implementing `split_at_mut`:
785///
786/// ```
787/// use std::{slice, mem};
788///
789/// // There are multiple ways to do this, and there are multiple problems
790/// // with the following (transmute) way.
791/// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
792/// -> (&mut [T], &mut [T]) {
793/// let len = slice.len();
794/// assert!(mid <= len);
795/// unsafe {
796/// let slice2 = mem::transmute::<&mut [T], &mut [T]>(slice);
797/// // first: transmute is not type safe; all it checks is that T and
798/// // U are of the same size. Second, right here, you have two
799/// // mutable references pointing to the same memory.
800/// (&mut slice[0..mid], &mut slice2[mid..len])
801/// }
802/// }
803///
804/// // This gets rid of the type safety problems; `&mut *` will *only* give
805/// // you a `&mut T` from a `&mut T` or `*mut T`.
806/// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
807/// -> (&mut [T], &mut [T]) {
808/// let len = slice.len();
809/// assert!(mid <= len);
810/// unsafe {
811/// let slice2 = &mut *(slice as *mut [T]);
812/// // however, you still have two mutable references pointing to
813/// // the same memory.
814/// (&mut slice[0..mid], &mut slice2[mid..len])
815/// }
816/// }
817///
818/// // This is how the standard library does it. This is the best method, if
819/// // you need to do something like this
820/// fn split_at_stdlib<T>(slice: &mut [T], mid: usize)
821/// -> (&mut [T], &mut [T]) {
822/// let len = slice.len();
823/// assert!(mid <= len);
824/// unsafe {
825/// let ptr = slice.as_mut_ptr();
826/// // This now has three mutable references pointing at the same
827/// // memory. `slice`, the rvalue ret.0, and the rvalue ret.1.
828/// // `slice` is never used after `let ptr = ...`, and so one can
829/// // treat it as "dead", and therefore, you only have two real
830/// // mutable slices.
831/// (slice::from_raw_parts_mut(ptr, mid),
832/// slice::from_raw_parts_mut(ptr.add(mid), len - mid))
833/// }
834/// }
835/// ```
836#[stable(feature = "rust1", since = "1.0.0")]
837#[rustc_allowed_through_unstable_modules = "import this function via `std::mem` instead"]
838#[rustc_const_stable(feature = "const_transmute", since = "1.56.0")]
839#[rustc_diagnostic_item = "transmute"]
840#[rustc_nounwind]
841#[rustc_intrinsic]
842pub const unsafe fn transmute<Src, Dst>(src: Src) -> Dst;
843
844/// Like [`transmute`], but even less checked at compile-time: rather than
845/// giving an error for `size_of::<Src>() != size_of::<Dst>()`, it's
846/// **Undefined Behavior** at runtime.
847///
848/// Prefer normal `transmute` where possible, for the extra checking, since
849/// both do exactly the same thing at runtime, if they both compile.
850///
851/// This is not expected to ever be exposed directly to users, rather it
852/// may eventually be exposed through some more-constrained API.
853#[rustc_intrinsic_const_stable_indirect]
854#[rustc_nounwind]
855#[rustc_intrinsic]
856pub const unsafe fn transmute_unchecked<Src, Dst>(src: Src) -> Dst;
857
858/// Returns `true` if the actual type given as `T` requires drop
859/// glue; returns `false` if the actual type provided for `T`
860/// implements `Copy`.
861///
862/// If the actual type neither requires drop glue nor implements
863/// `Copy`, then the return value of this function is unspecified.
864///
865/// Note that, unlike most intrinsics, this can only be called at compile-time
866/// as backends do not have an implementation for it. The only caller (its
867/// stable counterpart) wraps this intrinsic call in a `const` block so that
868/// backends only see an evaluated constant.
869///
870/// The stabilized version of this intrinsic is [`mem::needs_drop`](crate::mem::needs_drop).
871#[rustc_intrinsic_const_stable_indirect]
872#[rustc_nounwind]
873#[rustc_intrinsic]
874pub const fn needs_drop<T: ?Sized>() -> bool;
875
876/// Calculates the offset from a pointer.
877///
878/// This is implemented as an intrinsic to avoid converting to and from an
879/// integer, since the conversion would throw away aliasing information.
880///
881/// This can only be used with `Ptr` as a raw pointer type (`*mut` or `*const`)
882/// to a `Sized` pointee and with `Delta` as `usize` or `isize`. Any other
883/// instantiations may arbitrarily misbehave, and that's *not* a compiler bug.
884///
885/// # Safety
886///
887/// If the computed offset is non-zero, then both the starting and resulting pointer must be
888/// either in bounds or at the end of an allocation. If either pointer is out
889/// of bounds or arithmetic overflow occurs then this operation is undefined behavior.
890///
891/// The stabilized version of this intrinsic is [`pointer::offset`].
892#[must_use = "returns a new pointer rather than modifying its argument"]
893#[rustc_intrinsic_const_stable_indirect]
894#[rustc_nounwind]
895#[rustc_intrinsic]
896pub const unsafe fn offset<Ptr: bounds::BuiltinDeref, Delta>(dst: Ptr, offset: Delta) -> Ptr;
897
898/// Calculates the offset from a pointer, potentially wrapping.
899///
900/// This is implemented as an intrinsic to avoid converting to and from an
901/// integer, since the conversion inhibits certain optimizations.
902///
903/// # Safety
904///
905/// Unlike the `offset` intrinsic, this intrinsic does not restrict the
906/// resulting pointer to point into or at the end of an allocated
907/// object, and it wraps with two's complement arithmetic. The resulting
908/// value is not necessarily valid to be used to actually access memory.
909///
910/// The stabilized version of this intrinsic is [`pointer::wrapping_offset`].
911#[must_use = "returns a new pointer rather than modifying its argument"]
912#[rustc_intrinsic_const_stable_indirect]
913#[rustc_nounwind]
914#[rustc_intrinsic]
915pub const unsafe fn arith_offset<T>(dst: *const T, offset: isize) -> *const T;
916
917/// Projects to the `index`-th element of `slice_ptr`, as the same kind of pointer
918/// as the slice was provided -- so `&mut [T] → &mut T`, `&[T] → &T`,
919/// `*mut [T] → *mut T`, or `*const [T] → *const T` -- without a bounds check.
920///
921/// This is exposed via `<usize as SliceIndex>::get(_unchecked)(_mut)`,
922/// and isn't intended to be used elsewhere.
923///
924/// Expands in MIR to `{&, &mut, &raw const, &raw mut} (*slice_ptr)[index]`,
925/// depending on the types involved, so no backend support is needed.
926///
927/// # Safety
928///
929/// - `index < PtrMetadata(slice_ptr)`, so the indexing is in-bounds for the slice
930/// - the resulting offsetting is in-bounds of the allocation, which is
931/// always the case for references, but needs to be upheld manually for pointers
932#[rustc_nounwind]
933#[rustc_intrinsic]
934pub const unsafe fn slice_get_unchecked<
935 ItemPtr: bounds::ChangePointee<[T], Pointee = T, Output = SlicePtr>,
936 SlicePtr,
937 T,
938>(
939 slice_ptr: SlicePtr,
940 index: usize,
941) -> ItemPtr;
942
943/// Masks out bits of the pointer according to a mask.
944///
945/// Note that, unlike most intrinsics, this is safe to call;
946/// it does not require an `unsafe` block.
947/// Therefore, implementations must not require the user to uphold
948/// any safety invariants.
949///
950/// Consider using [`pointer::mask`] instead.
951#[rustc_nounwind]
952#[rustc_intrinsic]
953pub fn ptr_mask<T>(ptr: *const T, mask: usize) -> *const T;
954
955/// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with
956/// a size of `count` * `size_of::<T>()` and an alignment of `align_of::<T>()`.
957///
958/// This intrinsic does not have a stable counterpart.
959/// # Safety
960///
961/// The safety requirements are consistent with [`copy_nonoverlapping`]
962/// while the read and write behaviors are volatile,
963/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
964///
965/// [`copy_nonoverlapping`]: ptr::copy_nonoverlapping
966#[rustc_intrinsic]
967#[rustc_nounwind]
968pub unsafe fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize);
969/// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with
970/// a size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
971///
972/// The volatile parameter is set to `true`, so it will not be optimized out
973/// unless size is equal to zero.
974///
975/// This intrinsic does not have a stable counterpart.
976#[rustc_intrinsic]
977#[rustc_nounwind]
978pub unsafe fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize);
979/// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a
980/// size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
981///
982/// This intrinsic does not have a stable counterpart.
983/// # Safety
984///
985/// The safety requirements are consistent with [`write_bytes`] while the write behavior is volatile,
986/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
987///
988/// [`write_bytes`]: ptr::write_bytes
989#[rustc_intrinsic]
990#[rustc_nounwind]
991pub unsafe fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize);
992
993/// Performs a volatile load from the `src` pointer.
994///
995/// The stabilized version of this intrinsic is [`core::ptr::read_volatile`].
996#[rustc_intrinsic]
997#[rustc_nounwind]
998pub unsafe fn volatile_load<T>(src: *const T) -> T;
999/// Performs a volatile store to the `dst` pointer.
1000///
1001/// The stabilized version of this intrinsic is [`core::ptr::write_volatile`].
1002#[rustc_intrinsic]
1003#[rustc_nounwind]
1004pub unsafe fn volatile_store<T>(dst: *mut T, val: T);
1005
1006/// Performs a volatile load from the `src` pointer
1007/// The pointer is not required to be aligned.
1008///
1009/// This intrinsic does not have a stable counterpart.
1010#[rustc_intrinsic]
1011#[rustc_nounwind]
1012#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_load"]
1013pub unsafe fn unaligned_volatile_load<T>(src: *const T) -> T;
1014/// Performs a volatile store to the `dst` pointer.
1015/// The pointer is not required to be aligned.
1016///
1017/// This intrinsic does not have a stable counterpart.
1018#[rustc_intrinsic]
1019#[rustc_nounwind]
1020#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_store"]
1021pub unsafe fn unaligned_volatile_store<T>(dst: *mut T, val: T);
1022
1023/// Returns the square root of an `f16`
1024///
1025/// The stabilized version of this intrinsic is
1026/// [`f16::sqrt`](../../std/primitive.f16.html#method.sqrt)
1027#[rustc_intrinsic]
1028#[rustc_nounwind]
1029pub fn sqrtf16(x: f16) -> f16;
1030/// Returns the square root of an `f32`
1031///
1032/// The stabilized version of this intrinsic is
1033/// [`f32::sqrt`](../../std/primitive.f32.html#method.sqrt)
1034#[rustc_intrinsic]
1035#[rustc_nounwind]
1036pub fn sqrtf32(x: f32) -> f32;
1037/// Returns the square root of an `f64`
1038///
1039/// The stabilized version of this intrinsic is
1040/// [`f64::sqrt`](../../std/primitive.f64.html#method.sqrt)
1041#[rustc_intrinsic]
1042#[rustc_nounwind]
1043pub fn sqrtf64(x: f64) -> f64;
1044/// Returns the square root of an `f128`
1045///
1046/// The stabilized version of this intrinsic is
1047/// [`f128::sqrt`](../../std/primitive.f128.html#method.sqrt)
1048#[rustc_intrinsic]
1049#[rustc_nounwind]
1050pub fn sqrtf128(x: f128) -> f128;
1051
1052/// Raises an `f16` to an integer power.
1053///
1054/// The stabilized version of this intrinsic is
1055/// [`f16::powi`](../../std/primitive.f16.html#method.powi)
1056#[rustc_intrinsic]
1057#[rustc_nounwind]
1058pub fn powif16(a: f16, x: i32) -> f16;
1059/// Raises an `f32` to an integer power.
1060///
1061/// The stabilized version of this intrinsic is
1062/// [`f32::powi`](../../std/primitive.f32.html#method.powi)
1063#[rustc_intrinsic]
1064#[rustc_nounwind]
1065pub fn powif32(a: f32, x: i32) -> f32;
1066/// Raises an `f64` to an integer power.
1067///
1068/// The stabilized version of this intrinsic is
1069/// [`f64::powi`](../../std/primitive.f64.html#method.powi)
1070#[rustc_intrinsic]
1071#[rustc_nounwind]
1072pub fn powif64(a: f64, x: i32) -> f64;
1073/// Raises an `f128` to an integer power.
1074///
1075/// The stabilized version of this intrinsic is
1076/// [`f128::powi`](../../std/primitive.f128.html#method.powi)
1077#[rustc_intrinsic]
1078#[rustc_nounwind]
1079pub fn powif128(a: f128, x: i32) -> f128;
1080
1081/// Returns the sine of an `f16`.
1082///
1083/// The stabilized version of this intrinsic is
1084/// [`f16::sin`](../../std/primitive.f16.html#method.sin)
1085#[rustc_intrinsic]
1086#[rustc_nounwind]
1087pub fn sinf16(x: f16) -> f16;
1088/// Returns the sine of an `f32`.
1089///
1090/// The stabilized version of this intrinsic is
1091/// [`f32::sin`](../../std/primitive.f32.html#method.sin)
1092#[rustc_intrinsic]
1093#[rustc_nounwind]
1094pub fn sinf32(x: f32) -> f32;
1095/// Returns the sine of an `f64`.
1096///
1097/// The stabilized version of this intrinsic is
1098/// [`f64::sin`](../../std/primitive.f64.html#method.sin)
1099#[rustc_intrinsic]
1100#[rustc_nounwind]
1101pub fn sinf64(x: f64) -> f64;
1102/// Returns the sine of an `f128`.
1103///
1104/// The stabilized version of this intrinsic is
1105/// [`f128::sin`](../../std/primitive.f128.html#method.sin)
1106#[rustc_intrinsic]
1107#[rustc_nounwind]
1108pub fn sinf128(x: f128) -> f128;
1109
1110/// Returns the cosine of an `f16`.
1111///
1112/// The stabilized version of this intrinsic is
1113/// [`f16::cos`](../../std/primitive.f16.html#method.cos)
1114#[rustc_intrinsic]
1115#[rustc_nounwind]
1116pub fn cosf16(x: f16) -> f16;
1117/// Returns the cosine of an `f32`.
1118///
1119/// The stabilized version of this intrinsic is
1120/// [`f32::cos`](../../std/primitive.f32.html#method.cos)
1121#[rustc_intrinsic]
1122#[rustc_nounwind]
1123pub fn cosf32(x: f32) -> f32;
1124/// Returns the cosine of an `f64`.
1125///
1126/// The stabilized version of this intrinsic is
1127/// [`f64::cos`](../../std/primitive.f64.html#method.cos)
1128#[rustc_intrinsic]
1129#[rustc_nounwind]
1130pub fn cosf64(x: f64) -> f64;
1131/// Returns the cosine of an `f128`.
1132///
1133/// The stabilized version of this intrinsic is
1134/// [`f128::cos`](../../std/primitive.f128.html#method.cos)
1135#[rustc_intrinsic]
1136#[rustc_nounwind]
1137pub fn cosf128(x: f128) -> f128;
1138
1139/// Raises an `f16` to an `f16` power.
1140///
1141/// The stabilized version of this intrinsic is
1142/// [`f16::powf`](../../std/primitive.f16.html#method.powf)
1143#[rustc_intrinsic]
1144#[rustc_nounwind]
1145pub fn powf16(a: f16, x: f16) -> f16;
1146/// Raises an `f32` to an `f32` power.
1147///
1148/// The stabilized version of this intrinsic is
1149/// [`f32::powf`](../../std/primitive.f32.html#method.powf)
1150#[rustc_intrinsic]
1151#[rustc_nounwind]
1152pub fn powf32(a: f32, x: f32) -> f32;
1153/// Raises an `f64` to an `f64` power.
1154///
1155/// The stabilized version of this intrinsic is
1156/// [`f64::powf`](../../std/primitive.f64.html#method.powf)
1157#[rustc_intrinsic]
1158#[rustc_nounwind]
1159pub fn powf64(a: f64, x: f64) -> f64;
1160/// Raises an `f128` to an `f128` power.
1161///
1162/// The stabilized version of this intrinsic is
1163/// [`f128::powf`](../../std/primitive.f128.html#method.powf)
1164#[rustc_intrinsic]
1165#[rustc_nounwind]
1166pub fn powf128(a: f128, x: f128) -> f128;
1167
1168/// Returns the exponential of an `f16`.
1169///
1170/// The stabilized version of this intrinsic is
1171/// [`f16::exp`](../../std/primitive.f16.html#method.exp)
1172#[rustc_intrinsic]
1173#[rustc_nounwind]
1174pub fn expf16(x: f16) -> f16;
1175/// Returns the exponential of an `f32`.
1176///
1177/// The stabilized version of this intrinsic is
1178/// [`f32::exp`](../../std/primitive.f32.html#method.exp)
1179#[rustc_intrinsic]
1180#[rustc_nounwind]
1181pub fn expf32(x: f32) -> f32;
1182/// Returns the exponential of an `f64`.
1183///
1184/// The stabilized version of this intrinsic is
1185/// [`f64::exp`](../../std/primitive.f64.html#method.exp)
1186#[rustc_intrinsic]
1187#[rustc_nounwind]
1188pub fn expf64(x: f64) -> f64;
1189/// Returns the exponential of an `f128`.
1190///
1191/// The stabilized version of this intrinsic is
1192/// [`f128::exp`](../../std/primitive.f128.html#method.exp)
1193#[rustc_intrinsic]
1194#[rustc_nounwind]
1195pub fn expf128(x: f128) -> f128;
1196
1197/// Returns 2 raised to the power of an `f16`.
1198///
1199/// The stabilized version of this intrinsic is
1200/// [`f16::exp2`](../../std/primitive.f16.html#method.exp2)
1201#[rustc_intrinsic]
1202#[rustc_nounwind]
1203pub fn exp2f16(x: f16) -> f16;
1204/// Returns 2 raised to the power of an `f32`.
1205///
1206/// The stabilized version of this intrinsic is
1207/// [`f32::exp2`](../../std/primitive.f32.html#method.exp2)
1208#[rustc_intrinsic]
1209#[rustc_nounwind]
1210pub fn exp2f32(x: f32) -> f32;
1211/// Returns 2 raised to the power of an `f64`.
1212///
1213/// The stabilized version of this intrinsic is
1214/// [`f64::exp2`](../../std/primitive.f64.html#method.exp2)
1215#[rustc_intrinsic]
1216#[rustc_nounwind]
1217pub fn exp2f64(x: f64) -> f64;
1218/// Returns 2 raised to the power of an `f128`.
1219///
1220/// The stabilized version of this intrinsic is
1221/// [`f128::exp2`](../../std/primitive.f128.html#method.exp2)
1222#[rustc_intrinsic]
1223#[rustc_nounwind]
1224pub fn exp2f128(x: f128) -> f128;
1225
1226/// Returns the natural logarithm of an `f16`.
1227///
1228/// The stabilized version of this intrinsic is
1229/// [`f16::ln`](../../std/primitive.f16.html#method.ln)
1230#[rustc_intrinsic]
1231#[rustc_nounwind]
1232pub fn logf16(x: f16) -> f16;
1233/// Returns the natural logarithm of an `f32`.
1234///
1235/// The stabilized version of this intrinsic is
1236/// [`f32::ln`](../../std/primitive.f32.html#method.ln)
1237#[rustc_intrinsic]
1238#[rustc_nounwind]
1239pub fn logf32(x: f32) -> f32;
1240/// Returns the natural logarithm of an `f64`.
1241///
1242/// The stabilized version of this intrinsic is
1243/// [`f64::ln`](../../std/primitive.f64.html#method.ln)
1244#[rustc_intrinsic]
1245#[rustc_nounwind]
1246pub fn logf64(x: f64) -> f64;
1247/// Returns the natural logarithm of an `f128`.
1248///
1249/// The stabilized version of this intrinsic is
1250/// [`f128::ln`](../../std/primitive.f128.html#method.ln)
1251#[rustc_intrinsic]
1252#[rustc_nounwind]
1253pub fn logf128(x: f128) -> f128;
1254
1255/// Returns the base 10 logarithm of an `f16`.
1256///
1257/// The stabilized version of this intrinsic is
1258/// [`f16::log10`](../../std/primitive.f16.html#method.log10)
1259#[rustc_intrinsic]
1260#[rustc_nounwind]
1261pub fn log10f16(x: f16) -> f16;
1262/// Returns the base 10 logarithm of an `f32`.
1263///
1264/// The stabilized version of this intrinsic is
1265/// [`f32::log10`](../../std/primitive.f32.html#method.log10)
1266#[rustc_intrinsic]
1267#[rustc_nounwind]
1268pub fn log10f32(x: f32) -> f32;
1269/// Returns the base 10 logarithm of an `f64`.
1270///
1271/// The stabilized version of this intrinsic is
1272/// [`f64::log10`](../../std/primitive.f64.html#method.log10)
1273#[rustc_intrinsic]
1274#[rustc_nounwind]
1275pub fn log10f64(x: f64) -> f64;
1276/// Returns the base 10 logarithm of an `f128`.
1277///
1278/// The stabilized version of this intrinsic is
1279/// [`f128::log10`](../../std/primitive.f128.html#method.log10)
1280#[rustc_intrinsic]
1281#[rustc_nounwind]
1282pub fn log10f128(x: f128) -> f128;
1283
1284/// Returns the base 2 logarithm of an `f16`.
1285///
1286/// The stabilized version of this intrinsic is
1287/// [`f16::log2`](../../std/primitive.f16.html#method.log2)
1288#[rustc_intrinsic]
1289#[rustc_nounwind]
1290pub fn log2f16(x: f16) -> f16;
1291/// Returns the base 2 logarithm of an `f32`.
1292///
1293/// The stabilized version of this intrinsic is
1294/// [`f32::log2`](../../std/primitive.f32.html#method.log2)
1295#[rustc_intrinsic]
1296#[rustc_nounwind]
1297pub fn log2f32(x: f32) -> f32;
1298/// Returns the base 2 logarithm of an `f64`.
1299///
1300/// The stabilized version of this intrinsic is
1301/// [`f64::log2`](../../std/primitive.f64.html#method.log2)
1302#[rustc_intrinsic]
1303#[rustc_nounwind]
1304pub fn log2f64(x: f64) -> f64;
1305/// Returns the base 2 logarithm of an `f128`.
1306///
1307/// The stabilized version of this intrinsic is
1308/// [`f128::log2`](../../std/primitive.f128.html#method.log2)
1309#[rustc_intrinsic]
1310#[rustc_nounwind]
1311pub fn log2f128(x: f128) -> f128;
1312
1313/// Returns `a * b + c` for `f16` values.
1314///
1315/// The stabilized version of this intrinsic is
1316/// [`f16::mul_add`](../../std/primitive.f16.html#method.mul_add)
1317#[rustc_intrinsic]
1318#[rustc_nounwind]
1319pub const fn fmaf16(a: f16, b: f16, c: f16) -> f16;
1320/// Returns `a * b + c` for `f32` values.
1321///
1322/// The stabilized version of this intrinsic is
1323/// [`f32::mul_add`](../../std/primitive.f32.html#method.mul_add)
1324#[rustc_intrinsic]
1325#[rustc_nounwind]
1326pub const fn fmaf32(a: f32, b: f32, c: f32) -> f32;
1327/// Returns `a * b + c` for `f64` values.
1328///
1329/// The stabilized version of this intrinsic is
1330/// [`f64::mul_add`](../../std/primitive.f64.html#method.mul_add)
1331#[rustc_intrinsic]
1332#[rustc_nounwind]
1333pub const fn fmaf64(a: f64, b: f64, c: f64) -> f64;
1334/// Returns `a * b + c` for `f128` values.
1335///
1336/// The stabilized version of this intrinsic is
1337/// [`f128::mul_add`](../../std/primitive.f128.html#method.mul_add)
1338#[rustc_intrinsic]
1339#[rustc_nounwind]
1340pub const fn fmaf128(a: f128, b: f128, c: f128) -> f128;
1341
1342/// Returns `a * b + c` for `f16` values, non-deterministically executing
1343/// either a fused multiply-add or two operations with rounding of the
1344/// intermediate result.
1345///
1346/// The operation is fused if the code generator determines that target
1347/// instruction set has support for a fused operation, and that the fused
1348/// operation is more efficient than the equivalent, separate pair of mul
1349/// and add instructions. It is unspecified whether or not a fused operation
1350/// is selected, and that may depend on optimization level and context, for
1351/// example.
1352#[rustc_intrinsic]
1353#[rustc_nounwind]
1354pub const fn fmuladdf16(a: f16, b: f16, c: f16) -> f16;
1355/// Returns `a * b + c` for `f32` values, non-deterministically executing
1356/// either a fused multiply-add or two operations with rounding of the
1357/// intermediate result.
1358///
1359/// The operation is fused if the code generator determines that target
1360/// instruction set has support for a fused operation, and that the fused
1361/// operation is more efficient than the equivalent, separate pair of mul
1362/// and add instructions. It is unspecified whether or not a fused operation
1363/// is selected, and that may depend on optimization level and context, for
1364/// example.
1365#[rustc_intrinsic]
1366#[rustc_nounwind]
1367pub const fn fmuladdf32(a: f32, b: f32, c: f32) -> f32;
1368/// Returns `a * b + c` for `f64` values, non-deterministically executing
1369/// either a fused multiply-add or two operations with rounding of the
1370/// intermediate result.
1371///
1372/// The operation is fused if the code generator determines that target
1373/// instruction set has support for a fused operation, and that the fused
1374/// operation is more efficient than the equivalent, separate pair of mul
1375/// and add instructions. It is unspecified whether or not a fused operation
1376/// is selected, and that may depend on optimization level and context, for
1377/// example.
1378#[rustc_intrinsic]
1379#[rustc_nounwind]
1380pub const fn fmuladdf64(a: f64, b: f64, c: f64) -> f64;
1381/// Returns `a * b + c` for `f128` values, non-deterministically executing
1382/// either a fused multiply-add or two operations with rounding of the
1383/// intermediate result.
1384///
1385/// The operation is fused if the code generator determines that target
1386/// instruction set has support for a fused operation, and that the fused
1387/// operation is more efficient than the equivalent, separate pair of mul
1388/// and add instructions. It is unspecified whether or not a fused operation
1389/// is selected, and that may depend on optimization level and context, for
1390/// example.
1391#[rustc_intrinsic]
1392#[rustc_nounwind]
1393pub const fn fmuladdf128(a: f128, b: f128, c: f128) -> f128;
1394
1395/// Returns the largest integer less than or equal to an `f16`.
1396///
1397/// The stabilized version of this intrinsic is
1398/// [`f16::floor`](../../std/primitive.f16.html#method.floor)
1399#[rustc_intrinsic_const_stable_indirect]
1400#[rustc_intrinsic]
1401#[rustc_nounwind]
1402pub const fn floorf16(x: f16) -> f16;
1403/// Returns the largest integer less than or equal to an `f32`.
1404///
1405/// The stabilized version of this intrinsic is
1406/// [`f32::floor`](../../std/primitive.f32.html#method.floor)
1407#[rustc_intrinsic_const_stable_indirect]
1408#[rustc_intrinsic]
1409#[rustc_nounwind]
1410pub const fn floorf32(x: f32) -> f32;
1411/// Returns the largest integer less than or equal to an `f64`.
1412///
1413/// The stabilized version of this intrinsic is
1414/// [`f64::floor`](../../std/primitive.f64.html#method.floor)
1415#[rustc_intrinsic_const_stable_indirect]
1416#[rustc_intrinsic]
1417#[rustc_nounwind]
1418pub const fn floorf64(x: f64) -> f64;
1419/// Returns the largest integer less than or equal to an `f128`.
1420///
1421/// The stabilized version of this intrinsic is
1422/// [`f128::floor`](../../std/primitive.f128.html#method.floor)
1423#[rustc_intrinsic_const_stable_indirect]
1424#[rustc_intrinsic]
1425#[rustc_nounwind]
1426pub const fn floorf128(x: f128) -> f128;
1427
1428/// Returns the smallest integer greater than or equal to an `f16`.
1429///
1430/// The stabilized version of this intrinsic is
1431/// [`f16::ceil`](../../std/primitive.f16.html#method.ceil)
1432#[rustc_intrinsic_const_stable_indirect]
1433#[rustc_intrinsic]
1434#[rustc_nounwind]
1435pub const fn ceilf16(x: f16) -> f16;
1436/// Returns the smallest integer greater than or equal to an `f32`.
1437///
1438/// The stabilized version of this intrinsic is
1439/// [`f32::ceil`](../../std/primitive.f32.html#method.ceil)
1440#[rustc_intrinsic_const_stable_indirect]
1441#[rustc_intrinsic]
1442#[rustc_nounwind]
1443pub const fn ceilf32(x: f32) -> f32;
1444/// Returns the smallest integer greater than or equal to an `f64`.
1445///
1446/// The stabilized version of this intrinsic is
1447/// [`f64::ceil`](../../std/primitive.f64.html#method.ceil)
1448#[rustc_intrinsic_const_stable_indirect]
1449#[rustc_intrinsic]
1450#[rustc_nounwind]
1451pub const fn ceilf64(x: f64) -> f64;
1452/// Returns the smallest integer greater than or equal to an `f128`.
1453///
1454/// The stabilized version of this intrinsic is
1455/// [`f128::ceil`](../../std/primitive.f128.html#method.ceil)
1456#[rustc_intrinsic_const_stable_indirect]
1457#[rustc_intrinsic]
1458#[rustc_nounwind]
1459pub const fn ceilf128(x: f128) -> f128;
1460
1461/// Returns the integer part of an `f16`.
1462///
1463/// The stabilized version of this intrinsic is
1464/// [`f16::trunc`](../../std/primitive.f16.html#method.trunc)
1465#[rustc_intrinsic_const_stable_indirect]
1466#[rustc_intrinsic]
1467#[rustc_nounwind]
1468pub const fn truncf16(x: f16) -> f16;
1469/// Returns the integer part of an `f32`.
1470///
1471/// The stabilized version of this intrinsic is
1472/// [`f32::trunc`](../../std/primitive.f32.html#method.trunc)
1473#[rustc_intrinsic_const_stable_indirect]
1474#[rustc_intrinsic]
1475#[rustc_nounwind]
1476pub const fn truncf32(x: f32) -> f32;
1477/// Returns the integer part of an `f64`.
1478///
1479/// The stabilized version of this intrinsic is
1480/// [`f64::trunc`](../../std/primitive.f64.html#method.trunc)
1481#[rustc_intrinsic_const_stable_indirect]
1482#[rustc_intrinsic]
1483#[rustc_nounwind]
1484pub const fn truncf64(x: f64) -> f64;
1485/// Returns the integer part of an `f128`.
1486///
1487/// The stabilized version of this intrinsic is
1488/// [`f128::trunc`](../../std/primitive.f128.html#method.trunc)
1489#[rustc_intrinsic_const_stable_indirect]
1490#[rustc_intrinsic]
1491#[rustc_nounwind]
1492pub const fn truncf128(x: f128) -> f128;
1493
1494/// Returns the nearest integer to an `f16`. Rounds half-way cases to the number with an even
1495/// least significant digit.
1496///
1497/// The stabilized version of this intrinsic is
1498/// [`f16::round_ties_even`](../../std/primitive.f16.html#method.round_ties_even)
1499#[rustc_intrinsic_const_stable_indirect]
1500#[rustc_intrinsic]
1501#[rustc_nounwind]
1502pub const fn round_ties_even_f16(x: f16) -> f16;
1503
1504/// Returns the nearest integer to an `f32`. Rounds half-way cases to the number with an even
1505/// least significant digit.
1506///
1507/// The stabilized version of this intrinsic is
1508/// [`f32::round_ties_even`](../../std/primitive.f32.html#method.round_ties_even)
1509#[rustc_intrinsic_const_stable_indirect]
1510#[rustc_intrinsic]
1511#[rustc_nounwind]
1512pub const fn round_ties_even_f32(x: f32) -> f32;
1513
1514/// Returns the nearest integer to an `f64`. Rounds half-way cases to the number with an even
1515/// least significant digit.
1516///
1517/// The stabilized version of this intrinsic is
1518/// [`f64::round_ties_even`](../../std/primitive.f64.html#method.round_ties_even)
1519#[rustc_intrinsic_const_stable_indirect]
1520#[rustc_intrinsic]
1521#[rustc_nounwind]
1522pub const fn round_ties_even_f64(x: f64) -> f64;
1523
1524/// Returns the nearest integer to an `f128`. Rounds half-way cases to the number with an even
1525/// least significant digit.
1526///
1527/// The stabilized version of this intrinsic is
1528/// [`f128::round_ties_even`](../../std/primitive.f128.html#method.round_ties_even)
1529#[rustc_intrinsic_const_stable_indirect]
1530#[rustc_intrinsic]
1531#[rustc_nounwind]
1532pub const fn round_ties_even_f128(x: f128) -> f128;
1533
1534/// Returns the nearest integer to an `f16`. Rounds half-way cases away from zero.
1535///
1536/// The stabilized version of this intrinsic is
1537/// [`f16::round`](../../std/primitive.f16.html#method.round)
1538#[rustc_intrinsic_const_stable_indirect]
1539#[rustc_intrinsic]
1540#[rustc_nounwind]
1541pub const fn roundf16(x: f16) -> f16;
1542/// Returns the nearest integer to an `f32`. Rounds half-way cases away from zero.
1543///
1544/// The stabilized version of this intrinsic is
1545/// [`f32::round`](../../std/primitive.f32.html#method.round)
1546#[rustc_intrinsic_const_stable_indirect]
1547#[rustc_intrinsic]
1548#[rustc_nounwind]
1549pub const fn roundf32(x: f32) -> f32;
1550/// Returns the nearest integer to an `f64`. Rounds half-way cases away from zero.
1551///
1552/// The stabilized version of this intrinsic is
1553/// [`f64::round`](../../std/primitive.f64.html#method.round)
1554#[rustc_intrinsic_const_stable_indirect]
1555#[rustc_intrinsic]
1556#[rustc_nounwind]
1557pub const fn roundf64(x: f64) -> f64;
1558/// Returns the nearest integer to an `f128`. Rounds half-way cases away from zero.
1559///
1560/// The stabilized version of this intrinsic is
1561/// [`f128::round`](../../std/primitive.f128.html#method.round)
1562#[rustc_intrinsic_const_stable_indirect]
1563#[rustc_intrinsic]
1564#[rustc_nounwind]
1565pub const fn roundf128(x: f128) -> f128;
1566
1567/// Float addition that allows optimizations based on algebraic rules.
1568/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1569///
1570/// This intrinsic does not have a stable counterpart.
1571#[rustc_intrinsic]
1572#[rustc_nounwind]
1573pub unsafe fn fadd_fast<T: Copy>(a: T, b: T) -> T;
1574
1575/// Float subtraction that allows optimizations based on algebraic rules.
1576/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1577///
1578/// This intrinsic does not have a stable counterpart.
1579#[rustc_intrinsic]
1580#[rustc_nounwind]
1581pub unsafe fn fsub_fast<T: Copy>(a: T, b: T) -> T;
1582
1583/// Float multiplication that allows optimizations based on algebraic rules.
1584/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1585///
1586/// This intrinsic does not have a stable counterpart.
1587#[rustc_intrinsic]
1588#[rustc_nounwind]
1589pub unsafe fn fmul_fast<T: Copy>(a: T, b: T) -> T;
1590
1591/// Float division that allows optimizations based on algebraic rules.
1592/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1593///
1594/// This intrinsic does not have a stable counterpart.
1595#[rustc_intrinsic]
1596#[rustc_nounwind]
1597pub unsafe fn fdiv_fast<T: Copy>(a: T, b: T) -> T;
1598
1599/// Float remainder that allows optimizations based on algebraic rules.
1600/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1601///
1602/// This intrinsic does not have a stable counterpart.
1603#[rustc_intrinsic]
1604#[rustc_nounwind]
1605pub unsafe fn frem_fast<T: Copy>(a: T, b: T) -> T;
1606
1607/// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range
1608/// (<https://github.com/rust-lang/rust/issues/10184>)
1609///
1610/// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`].
1611#[rustc_intrinsic]
1612#[rustc_nounwind]
1613pub unsafe fn float_to_int_unchecked<Float: Copy, Int: Copy>(value: Float) -> Int;
1614
1615/// Float addition that allows optimizations based on algebraic rules.
1616///
1617/// Stabilized as [`f16::algebraic_add`], [`f32::algebraic_add`], [`f64::algebraic_add`] and [`f128::algebraic_add`].
1618#[rustc_nounwind]
1619#[rustc_intrinsic]
1620pub const fn fadd_algebraic<T: Copy>(a: T, b: T) -> T;
1621
1622/// Float subtraction that allows optimizations based on algebraic rules.
1623///
1624/// Stabilized as [`f16::algebraic_sub`], [`f32::algebraic_sub`], [`f64::algebraic_sub`] and [`f128::algebraic_sub`].
1625#[rustc_nounwind]
1626#[rustc_intrinsic]
1627pub const fn fsub_algebraic<T: Copy>(a: T, b: T) -> T;
1628
1629/// Float multiplication that allows optimizations based on algebraic rules.
1630///
1631/// Stabilized as [`f16::algebraic_mul`], [`f32::algebraic_mul`], [`f64::algebraic_mul`] and [`f128::algebraic_mul`].
1632#[rustc_nounwind]
1633#[rustc_intrinsic]
1634pub const fn fmul_algebraic<T: Copy>(a: T, b: T) -> T;
1635
1636/// Float division that allows optimizations based on algebraic rules.
1637///
1638/// Stabilized as [`f16::algebraic_div`], [`f32::algebraic_div`], [`f64::algebraic_div`] and [`f128::algebraic_div`].
1639#[rustc_nounwind]
1640#[rustc_intrinsic]
1641pub const fn fdiv_algebraic<T: Copy>(a: T, b: T) -> T;
1642
1643/// Float remainder that allows optimizations based on algebraic rules.
1644///
1645/// Stabilized as [`f16::algebraic_rem`], [`f32::algebraic_rem`], [`f64::algebraic_rem`] and [`f128::algebraic_rem`].
1646#[rustc_nounwind]
1647#[rustc_intrinsic]
1648pub const fn frem_algebraic<T: Copy>(a: T, b: T) -> T;
1649
1650/// Returns the number of bits set in an integer type `T`
1651///
1652/// Note that, unlike most intrinsics, this is safe to call;
1653/// it does not require an `unsafe` block.
1654/// Therefore, implementations must not require the user to uphold
1655/// any safety invariants.
1656///
1657/// The stabilized versions of this intrinsic are available on the integer
1658/// primitives via the `count_ones` method. For example,
1659/// [`u32::count_ones`]
1660#[rustc_intrinsic_const_stable_indirect]
1661#[rustc_nounwind]
1662#[rustc_intrinsic]
1663pub const fn ctpop<T: Copy>(x: T) -> u32;
1664
1665/// Returns the number of leading unset bits (zeroes) in an integer type `T`.
1666///
1667/// Note that, unlike most intrinsics, this is safe to call;
1668/// it does not require an `unsafe` block.
1669/// Therefore, implementations must not require the user to uphold
1670/// any safety invariants.
1671///
1672/// The stabilized versions of this intrinsic are available on the integer
1673/// primitives via the `leading_zeros` method. For example,
1674/// [`u32::leading_zeros`]
1675///
1676/// # Examples
1677///
1678/// ```
1679/// #![feature(core_intrinsics)]
1680/// # #![allow(internal_features)]
1681///
1682/// use std::intrinsics::ctlz;
1683///
1684/// let x = 0b0001_1100_u8;
1685/// let num_leading = ctlz(x);
1686/// assert_eq!(num_leading, 3);
1687/// ```
1688///
1689/// An `x` with value `0` will return the bit width of `T`.
1690///
1691/// ```
1692/// #![feature(core_intrinsics)]
1693/// # #![allow(internal_features)]
1694///
1695/// use std::intrinsics::ctlz;
1696///
1697/// let x = 0u16;
1698/// let num_leading = ctlz(x);
1699/// assert_eq!(num_leading, 16);
1700/// ```
1701#[rustc_intrinsic_const_stable_indirect]
1702#[rustc_nounwind]
1703#[rustc_intrinsic]
1704pub const fn ctlz<T: Copy>(x: T) -> u32;
1705
1706/// Like `ctlz`, but extra-unsafe as it returns `undef` when
1707/// given an `x` with value `0`.
1708///
1709/// This intrinsic does not have a stable counterpart.
1710///
1711/// # Examples
1712///
1713/// ```
1714/// #![feature(core_intrinsics)]
1715/// # #![allow(internal_features)]
1716///
1717/// use std::intrinsics::ctlz_nonzero;
1718///
1719/// let x = 0b0001_1100_u8;
1720/// let num_leading = unsafe { ctlz_nonzero(x) };
1721/// assert_eq!(num_leading, 3);
1722/// ```
1723#[rustc_intrinsic_const_stable_indirect]
1724#[rustc_nounwind]
1725#[rustc_intrinsic]
1726pub const unsafe fn ctlz_nonzero<T: Copy>(x: T) -> u32;
1727
1728/// Returns the number of trailing unset bits (zeroes) in an integer type `T`.
1729///
1730/// Note that, unlike most intrinsics, this is safe to call;
1731/// it does not require an `unsafe` block.
1732/// Therefore, implementations must not require the user to uphold
1733/// any safety invariants.
1734///
1735/// The stabilized versions of this intrinsic are available on the integer
1736/// primitives via the `trailing_zeros` method. For example,
1737/// [`u32::trailing_zeros`]
1738///
1739/// # Examples
1740///
1741/// ```
1742/// #![feature(core_intrinsics)]
1743/// # #![allow(internal_features)]
1744///
1745/// use std::intrinsics::cttz;
1746///
1747/// let x = 0b0011_1000_u8;
1748/// let num_trailing = cttz(x);
1749/// assert_eq!(num_trailing, 3);
1750/// ```
1751///
1752/// An `x` with value `0` will return the bit width of `T`:
1753///
1754/// ```
1755/// #![feature(core_intrinsics)]
1756/// # #![allow(internal_features)]
1757///
1758/// use std::intrinsics::cttz;
1759///
1760/// let x = 0u16;
1761/// let num_trailing = cttz(x);
1762/// assert_eq!(num_trailing, 16);
1763/// ```
1764#[rustc_intrinsic_const_stable_indirect]
1765#[rustc_nounwind]
1766#[rustc_intrinsic]
1767pub const fn cttz<T: Copy>(x: T) -> u32;
1768
1769/// Like `cttz`, but extra-unsafe as it returns `undef` when
1770/// given an `x` with value `0`.
1771///
1772/// This intrinsic does not have a stable counterpart.
1773///
1774/// # Examples
1775///
1776/// ```
1777/// #![feature(core_intrinsics)]
1778/// # #![allow(internal_features)]
1779///
1780/// use std::intrinsics::cttz_nonzero;
1781///
1782/// let x = 0b0011_1000_u8;
1783/// let num_trailing = unsafe { cttz_nonzero(x) };
1784/// assert_eq!(num_trailing, 3);
1785/// ```
1786#[rustc_intrinsic_const_stable_indirect]
1787#[rustc_nounwind]
1788#[rustc_intrinsic]
1789pub const unsafe fn cttz_nonzero<T: Copy>(x: T) -> u32;
1790
1791/// Reverses the bytes in an integer type `T`.
1792///
1793/// Note that, unlike most intrinsics, this is safe to call;
1794/// it does not require an `unsafe` block.
1795/// Therefore, implementations must not require the user to uphold
1796/// any safety invariants.
1797///
1798/// The stabilized versions of this intrinsic are available on the integer
1799/// primitives via the `swap_bytes` method. For example,
1800/// [`u32::swap_bytes`]
1801#[rustc_intrinsic_const_stable_indirect]
1802#[rustc_nounwind]
1803#[rustc_intrinsic]
1804pub const fn bswap<T: Copy>(x: T) -> T;
1805
1806/// Reverses the bits in an integer type `T`.
1807///
1808/// Note that, unlike most intrinsics, this is safe to call;
1809/// it does not require an `unsafe` block.
1810/// Therefore, implementations must not require the user to uphold
1811/// any safety invariants.
1812///
1813/// The stabilized versions of this intrinsic are available on the integer
1814/// primitives via the `reverse_bits` method. For example,
1815/// [`u32::reverse_bits`]
1816#[rustc_intrinsic_const_stable_indirect]
1817#[rustc_nounwind]
1818#[rustc_intrinsic]
1819pub const fn bitreverse<T: Copy>(x: T) -> T;
1820
1821/// Does a three-way comparison between the two arguments,
1822/// which must be of character or integer (signed or unsigned) type.
1823///
1824/// This was originally added because it greatly simplified the MIR in `cmp`
1825/// implementations, and then LLVM 20 added a backend intrinsic for it too.
1826///
1827/// The stabilized version of this intrinsic is [`Ord::cmp`].
1828#[rustc_intrinsic_const_stable_indirect]
1829#[rustc_nounwind]
1830#[rustc_intrinsic]
1831pub const fn three_way_compare<T: Copy>(lhs: T, rhss: T) -> crate::cmp::Ordering;
1832
1833/// Combine two values which have no bits in common.
1834///
1835/// This allows the backend to implement it as `a + b` *or* `a | b`,
1836/// depending which is easier to implement on a specific target.
1837///
1838/// # Safety
1839///
1840/// Requires that `(a & b) == 0`, or equivalently that `(a | b) == (a + b)`.
1841///
1842/// Otherwise it's immediate UB.
1843#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1844#[rustc_nounwind]
1845#[rustc_intrinsic]
1846#[track_caller]
1847#[miri::intrinsic_fallback_is_spec] // the fallbacks all `assume` to tell Miri
1848pub const unsafe fn disjoint_bitor<T: [const] fallback::DisjointBitOr>(a: T, b: T) -> T {
1849 // SAFETY: same preconditions as this function.
1850 unsafe { fallback::DisjointBitOr::disjoint_bitor(a, b) }
1851}
1852
1853/// Performs checked integer addition.
1854///
1855/// Note that, unlike most intrinsics, this is safe to call;
1856/// it does not require an `unsafe` block.
1857/// Therefore, implementations must not require the user to uphold
1858/// any safety invariants.
1859///
1860/// The stabilized versions of this intrinsic are available on the integer
1861/// primitives via the `overflowing_add` method. For example,
1862/// [`u32::overflowing_add`]
1863#[rustc_intrinsic_const_stable_indirect]
1864#[rustc_nounwind]
1865#[rustc_intrinsic]
1866pub const fn add_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1867
1868/// Performs checked integer subtraction
1869///
1870/// Note that, unlike most intrinsics, this is safe to call;
1871/// it does not require an `unsafe` block.
1872/// Therefore, implementations must not require the user to uphold
1873/// any safety invariants.
1874///
1875/// The stabilized versions of this intrinsic are available on the integer
1876/// primitives via the `overflowing_sub` method. For example,
1877/// [`u32::overflowing_sub`]
1878#[rustc_intrinsic_const_stable_indirect]
1879#[rustc_nounwind]
1880#[rustc_intrinsic]
1881pub const fn sub_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1882
1883/// Performs checked integer multiplication
1884///
1885/// Note that, unlike most intrinsics, this is safe to call;
1886/// it does not require an `unsafe` block.
1887/// Therefore, implementations must not require the user to uphold
1888/// any safety invariants.
1889///
1890/// The stabilized versions of this intrinsic are available on the integer
1891/// primitives via the `overflowing_mul` method. For example,
1892/// [`u32::overflowing_mul`]
1893#[rustc_intrinsic_const_stable_indirect]
1894#[rustc_nounwind]
1895#[rustc_intrinsic]
1896pub const fn mul_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1897
1898/// Performs full-width multiplication and addition with a carry:
1899/// `multiplier * multiplicand + addend + carry`.
1900///
1901/// This is possible without any overflow. For `uN`:
1902/// MAX * MAX + MAX + MAX
1903/// => (2ⁿ-1) × (2ⁿ-1) + (2ⁿ-1) + (2ⁿ-1)
1904/// => (2²ⁿ - 2ⁿ⁺¹ + 1) + (2ⁿ⁺¹ - 2)
1905/// => 2²ⁿ - 1
1906///
1907/// For `iN`, the upper bound is MIN * MIN + MAX + MAX => 2²ⁿ⁻² + 2ⁿ - 2,
1908/// and the lower bound is MAX * MIN + MIN + MIN => -2²ⁿ⁻² - 2ⁿ + 2ⁿ⁺¹.
1909///
1910/// This currently supports unsigned integers *only*, no signed ones.
1911/// The stabilized versions of this intrinsic are available on integers.
1912#[unstable(feature = "core_intrinsics", issue = "none")]
1913#[rustc_const_unstable(feature = "const_carrying_mul_add", issue = "85532")]
1914#[rustc_nounwind]
1915#[rustc_intrinsic]
1916#[miri::intrinsic_fallback_is_spec]
1917pub const fn carrying_mul_add<T: [const] fallback::CarryingMulAdd<Unsigned = U>, U>(
1918 multiplier: T,
1919 multiplicand: T,
1920 addend: T,
1921 carry: T,
1922) -> (U, T) {
1923 multiplier.carrying_mul_add(multiplicand, addend, carry)
1924}
1925
1926/// Performs an exact division, resulting in undefined behavior where
1927/// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`
1928///
1929/// This intrinsic does not have a stable counterpart.
1930#[rustc_intrinsic_const_stable_indirect]
1931#[rustc_nounwind]
1932#[rustc_intrinsic]
1933pub const unsafe fn exact_div<T: Copy>(x: T, y: T) -> T;
1934
1935/// Performs an unchecked division, resulting in undefined behavior
1936/// where `y == 0` or `x == T::MIN && y == -1`
1937///
1938/// Safe wrappers for this intrinsic are available on the integer
1939/// primitives via the `checked_div` method. For example,
1940/// [`u32::checked_div`]
1941#[rustc_intrinsic_const_stable_indirect]
1942#[rustc_nounwind]
1943#[rustc_intrinsic]
1944pub const unsafe fn unchecked_div<T: Copy>(x: T, y: T) -> T;
1945/// Returns the remainder of an unchecked division, resulting in
1946/// undefined behavior when `y == 0` or `x == T::MIN && y == -1`
1947///
1948/// Safe wrappers for this intrinsic are available on the integer
1949/// primitives via the `checked_rem` method. For example,
1950/// [`u32::checked_rem`]
1951#[rustc_intrinsic_const_stable_indirect]
1952#[rustc_nounwind]
1953#[rustc_intrinsic]
1954pub const unsafe fn unchecked_rem<T: Copy>(x: T, y: T) -> T;
1955
1956/// Performs an unchecked left shift, resulting in undefined behavior when
1957/// `y < 0` or `y >= N`, where N is the width of T in bits.
1958///
1959/// Safe wrappers for this intrinsic are available on the integer
1960/// primitives via the `checked_shl` method. For example,
1961/// [`u32::checked_shl`]
1962#[rustc_intrinsic_const_stable_indirect]
1963#[rustc_nounwind]
1964#[rustc_intrinsic]
1965pub const unsafe fn unchecked_shl<T: Copy, U: Copy>(x: T, y: U) -> T;
1966/// Performs an unchecked right shift, resulting in undefined behavior when
1967/// `y < 0` or `y >= N`, where N is the width of T in bits.
1968///
1969/// Safe wrappers for this intrinsic are available on the integer
1970/// primitives via the `checked_shr` method. For example,
1971/// [`u32::checked_shr`]
1972#[rustc_intrinsic_const_stable_indirect]
1973#[rustc_nounwind]
1974#[rustc_intrinsic]
1975pub const unsafe fn unchecked_shr<T: Copy, U: Copy>(x: T, y: U) -> T;
1976
1977/// Returns the result of an unchecked addition, resulting in
1978/// undefined behavior when `x + y > T::MAX` or `x + y < T::MIN`.
1979///
1980/// The stable counterpart of this intrinsic is `unchecked_add` on the various
1981/// integer types, such as [`u16::unchecked_add`] and [`i64::unchecked_add`].
1982#[rustc_intrinsic_const_stable_indirect]
1983#[rustc_nounwind]
1984#[rustc_intrinsic]
1985pub const unsafe fn unchecked_add<T: Copy>(x: T, y: T) -> T;
1986
1987/// Returns the result of an unchecked subtraction, resulting in
1988/// undefined behavior when `x - y > T::MAX` or `x - y < T::MIN`.
1989///
1990/// The stable counterpart of this intrinsic is `unchecked_sub` on the various
1991/// integer types, such as [`u16::unchecked_sub`] and [`i64::unchecked_sub`].
1992#[rustc_intrinsic_const_stable_indirect]
1993#[rustc_nounwind]
1994#[rustc_intrinsic]
1995pub const unsafe fn unchecked_sub<T: Copy>(x: T, y: T) -> T;
1996
1997/// Returns the result of an unchecked multiplication, resulting in
1998/// undefined behavior when `x * y > T::MAX` or `x * y < T::MIN`.
1999///
2000/// The stable counterpart of this intrinsic is `unchecked_mul` on the various
2001/// integer types, such as [`u16::unchecked_mul`] and [`i64::unchecked_mul`].
2002#[rustc_intrinsic_const_stable_indirect]
2003#[rustc_nounwind]
2004#[rustc_intrinsic]
2005pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
2006
2007/// Performs rotate left.
2008///
2009/// Note that, unlike most intrinsics, this is safe to call;
2010/// it does not require an `unsafe` block.
2011/// Therefore, implementations must not require the user to uphold
2012/// any safety invariants.
2013///
2014/// The stabilized versions of this intrinsic are available on the integer
2015/// primitives via the `rotate_left` method. For example,
2016/// [`u32::rotate_left`]
2017#[rustc_intrinsic_const_stable_indirect]
2018#[rustc_nounwind]
2019#[rustc_intrinsic]
2020pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
2021
2022/// Performs rotate right.
2023///
2024/// Note that, unlike most intrinsics, this is safe to call;
2025/// it does not require an `unsafe` block.
2026/// Therefore, implementations must not require the user to uphold
2027/// any safety invariants.
2028///
2029/// The stabilized versions of this intrinsic are available on the integer
2030/// primitives via the `rotate_right` method. For example,
2031/// [`u32::rotate_right`]
2032#[rustc_intrinsic_const_stable_indirect]
2033#[rustc_nounwind]
2034#[rustc_intrinsic]
2035pub const fn rotate_right<T: Copy>(x: T, shift: u32) -> T;
2036
2037/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
2038///
2039/// Note that, unlike most intrinsics, this is safe to call;
2040/// it does not require an `unsafe` block.
2041/// Therefore, implementations must not require the user to uphold
2042/// any safety invariants.
2043///
2044/// The stabilized versions of this intrinsic are available on the integer
2045/// primitives via the `wrapping_add` method. For example,
2046/// [`u32::wrapping_add`]
2047#[rustc_intrinsic_const_stable_indirect]
2048#[rustc_nounwind]
2049#[rustc_intrinsic]
2050pub const fn wrapping_add<T: Copy>(a: T, b: T) -> T;
2051/// Returns (a - b) mod 2<sup>N</sup>, where N is the width of T in bits.
2052///
2053/// Note that, unlike most intrinsics, this is safe to call;
2054/// it does not require an `unsafe` block.
2055/// Therefore, implementations must not require the user to uphold
2056/// any safety invariants.
2057///
2058/// The stabilized versions of this intrinsic are available on the integer
2059/// primitives via the `wrapping_sub` method. For example,
2060/// [`u32::wrapping_sub`]
2061#[rustc_intrinsic_const_stable_indirect]
2062#[rustc_nounwind]
2063#[rustc_intrinsic]
2064pub const fn wrapping_sub<T: Copy>(a: T, b: T) -> T;
2065/// Returns (a * b) mod 2<sup>N</sup>, where N is the width of T in bits.
2066///
2067/// Note that, unlike most intrinsics, this is safe to call;
2068/// it does not require an `unsafe` block.
2069/// Therefore, implementations must not require the user to uphold
2070/// any safety invariants.
2071///
2072/// The stabilized versions of this intrinsic are available on the integer
2073/// primitives via the `wrapping_mul` method. For example,
2074/// [`u32::wrapping_mul`]
2075#[rustc_intrinsic_const_stable_indirect]
2076#[rustc_nounwind]
2077#[rustc_intrinsic]
2078pub const fn wrapping_mul<T: Copy>(a: T, b: T) -> T;
2079
2080/// Computes `a + b`, saturating at numeric bounds.
2081///
2082/// Note that, unlike most intrinsics, this is safe to call;
2083/// it does not require an `unsafe` block.
2084/// Therefore, implementations must not require the user to uphold
2085/// any safety invariants.
2086///
2087/// The stabilized versions of this intrinsic are available on the integer
2088/// primitives via the `saturating_add` method. For example,
2089/// [`u32::saturating_add`]
2090#[rustc_intrinsic_const_stable_indirect]
2091#[rustc_nounwind]
2092#[rustc_intrinsic]
2093pub const fn saturating_add<T: Copy>(a: T, b: T) -> T;
2094/// Computes `a - b`, saturating at numeric bounds.
2095///
2096/// Note that, unlike most intrinsics, this is safe to call;
2097/// it does not require an `unsafe` block.
2098/// Therefore, implementations must not require the user to uphold
2099/// any safety invariants.
2100///
2101/// The stabilized versions of this intrinsic are available on the integer
2102/// primitives via the `saturating_sub` method. For example,
2103/// [`u32::saturating_sub`]
2104#[rustc_intrinsic_const_stable_indirect]
2105#[rustc_nounwind]
2106#[rustc_intrinsic]
2107pub const fn saturating_sub<T: Copy>(a: T, b: T) -> T;
2108
2109/// Funnel Shift left.
2110///
2111/// Concatenates `a` and `b` (with `a` in the most significant half),
2112/// creating an integer twice as wide. Then shift this integer left
2113/// by `shift`), and extract the most significant half. If `a` and `b`
2114/// are the same, this is equivalent to a rotate left operation.
2115///
2116/// It is undefined behavior if `shift` is greater than or equal to the
2117/// bit size of `T`.
2118///
2119/// Safe versions of this intrinsic are available on the integer primitives
2120/// via the `funnel_shl` method. For example, [`u32::funnel_shl`].
2121#[rustc_intrinsic]
2122#[rustc_nounwind]
2123#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
2124#[unstable(feature = "funnel_shifts", issue = "145686")]
2125#[track_caller]
2126#[miri::intrinsic_fallback_is_spec]
2127pub const unsafe fn unchecked_funnel_shl<T: [const] fallback::FunnelShift>(
2128 a: T,
2129 b: T,
2130 shift: u32,
2131) -> T {
2132 // SAFETY: caller ensures that `shift` is in-range
2133 unsafe { a.unchecked_funnel_shl(b, shift) }
2134}
2135
2136/// Funnel Shift right.
2137///
2138/// Concatenates `a` and `b` (with `a` in the most significant half),
2139/// creating an integer twice as wide. Then shift this integer right
2140/// by `shift` (taken modulo the bit size of `T`), and extract the
2141/// least significant half. If `a` and `b` are the same, this is equivalent
2142/// to a rotate right operation.
2143///
2144/// It is undefined behavior if `shift` is greater than or equal to the
2145/// bit size of `T`.
2146///
2147/// Safer versions of this intrinsic are available on the integer primitives
2148/// via the `funnel_shr` method. For example, [`u32::funnel_shr`]
2149#[rustc_intrinsic]
2150#[rustc_nounwind]
2151#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
2152#[unstable(feature = "funnel_shifts", issue = "145686")]
2153#[track_caller]
2154#[miri::intrinsic_fallback_is_spec]
2155pub const unsafe fn unchecked_funnel_shr<T: [const] fallback::FunnelShift>(
2156 a: T,
2157 b: T,
2158 shift: u32,
2159) -> T {
2160 // SAFETY: caller ensures that `shift` is in-range
2161 unsafe { a.unchecked_funnel_shr(b, shift) }
2162}
2163
2164/// This is an implementation detail of [`crate::ptr::read`] and should
2165/// not be used anywhere else. See its comments for why this exists.
2166///
2167/// This intrinsic can *only* be called where the pointer is a local without
2168/// projections (`read_via_copy(ptr)`, not `read_via_copy(*ptr)`) so that it
2169/// trivially obeys runtime-MIR rules about derefs in operands.
2170#[rustc_intrinsic_const_stable_indirect]
2171#[rustc_nounwind]
2172#[rustc_intrinsic]
2173pub const unsafe fn read_via_copy<T>(ptr: *const T) -> T;
2174
2175/// This is an implementation detail of [`crate::ptr::write`] and should
2176/// not be used anywhere else. See its comments for why this exists.
2177///
2178/// This intrinsic can *only* be called where the pointer is a local without
2179/// projections (`write_via_move(ptr, x)`, not `write_via_move(*ptr, x)`) so
2180/// that it trivially obeys runtime-MIR rules about derefs in operands.
2181#[rustc_intrinsic_const_stable_indirect]
2182#[rustc_nounwind]
2183#[rustc_intrinsic]
2184pub const unsafe fn write_via_move<T>(ptr: *mut T, value: T);
2185
2186/// Returns the value of the discriminant for the variant in 'v';
2187/// if `T` has no discriminant, returns `0`.
2188///
2189/// Note that, unlike most intrinsics, this is safe to call;
2190/// it does not require an `unsafe` block.
2191/// Therefore, implementations must not require the user to uphold
2192/// any safety invariants.
2193///
2194/// The stabilized version of this intrinsic is [`core::mem::discriminant`].
2195#[rustc_intrinsic_const_stable_indirect]
2196#[rustc_nounwind]
2197#[rustc_intrinsic]
2198pub const fn discriminant_value<T>(v: &T) -> <T as DiscriminantKind>::Discriminant;
2199
2200/// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the
2201/// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs.
2202/// Returns `1` if unwinding occurred and `catch_fn` was called; returns `0` otherwise.
2203///
2204/// `catch_fn` must not unwind.
2205///
2206/// The third argument is a function called if an unwind occurs (both Rust `panic` and foreign
2207/// unwinds). This function takes the data pointer and a pointer to the target- and
2208/// runtime-specific exception object that was caught.
2209///
2210/// Note that in the case of a foreign unwinding operation, the exception object data may not be
2211/// safely usable from Rust, and should not be directly exposed via the standard library. To
2212/// prevent unsafe access, the library implementation may either abort the process or present an
2213/// opaque error type to the user.
2214///
2215/// For more information, see the compiler's source, as well as the documentation for the stable
2216/// version of this intrinsic, `std::panic::catch_unwind`.
2217#[rustc_intrinsic]
2218#[rustc_nounwind]
2219pub unsafe fn catch_unwind(
2220 _try_fn: fn(*mut u8),
2221 _data: *mut u8,
2222 _catch_fn: fn(*mut u8, *mut u8),
2223) -> i32;
2224
2225/// Emits a `nontemporal` store, which gives a hint to the CPU that the data should not be held
2226/// in cache. Except for performance, this is fully equivalent to `ptr.write(val)`.
2227///
2228/// Not all architectures provide such an operation. For instance, x86 does not: while `MOVNT`
2229/// exists, that operation is *not* equivalent to `ptr.write(val)` (`MOVNT` writes can be reordered
2230/// in ways that are not allowed for regular writes).
2231#[rustc_intrinsic]
2232#[rustc_nounwind]
2233pub unsafe fn nontemporal_store<T>(ptr: *mut T, val: T);
2234
2235/// See documentation of `<*const T>::offset_from` for details.
2236#[rustc_intrinsic_const_stable_indirect]
2237#[rustc_nounwind]
2238#[rustc_intrinsic]
2239pub const unsafe fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
2240
2241/// See documentation of `<*const T>::offset_from_unsigned` for details.
2242#[rustc_nounwind]
2243#[rustc_intrinsic]
2244#[rustc_intrinsic_const_stable_indirect]
2245pub const unsafe fn ptr_offset_from_unsigned<T>(ptr: *const T, base: *const T) -> usize;
2246
2247/// See documentation of `<*const T>::guaranteed_eq` for details.
2248/// Returns `2` if the result is unknown.
2249/// Returns `1` if the pointers are guaranteed equal.
2250/// Returns `0` if the pointers are guaranteed inequal.
2251#[rustc_intrinsic]
2252#[rustc_nounwind]
2253#[rustc_do_not_const_check]
2254#[inline]
2255#[miri::intrinsic_fallback_is_spec]
2256pub const fn ptr_guaranteed_cmp<T>(ptr: *const T, other: *const T) -> u8 {
2257 (ptr == other) as u8
2258}
2259
2260/// Determines whether the raw bytes of the two values are equal.
2261///
2262/// This is particularly handy for arrays, since it allows things like just
2263/// comparing `i96`s instead of forcing `alloca`s for `[6 x i16]`.
2264///
2265/// Above some backend-decided threshold this will emit calls to `memcmp`,
2266/// like slice equality does, instead of causing massive code size.
2267///
2268/// Since this works by comparing the underlying bytes, the actual `T` is
2269/// not particularly important. It will be used for its size and alignment,
2270/// but any validity restrictions will be ignored, not enforced.
2271///
2272/// # Safety
2273///
2274/// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized.
2275/// Note that this is a stricter criterion than just the *values* being
2276/// fully-initialized: if `T` has padding, it's UB to call this intrinsic.
2277///
2278/// At compile-time, it is furthermore UB to call this if any of the bytes
2279/// in `*a` or `*b` have provenance.
2280///
2281/// (The implementation is allowed to branch on the results of comparisons,
2282/// which is UB if any of their inputs are `undef`.)
2283#[rustc_nounwind]
2284#[rustc_intrinsic]
2285pub const unsafe fn raw_eq<T>(a: &T, b: &T) -> bool;
2286
2287/// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)`
2288/// as unsigned bytes, returning negative if `left` is less, zero if all the
2289/// bytes match, or positive if `left` is greater.
2290///
2291/// This underlies things like `<[u8]>::cmp`, and will usually lower to `memcmp`.
2292///
2293/// # Safety
2294///
2295/// `left` and `right` must each be [valid] for reads of `bytes` bytes.
2296///
2297/// Note that this applies to the whole range, not just until the first byte
2298/// that differs. That allows optimizations that can read in large chunks.
2299///
2300/// [valid]: crate::ptr#safety
2301#[rustc_nounwind]
2302#[rustc_intrinsic]
2303#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2304pub const unsafe fn compare_bytes(left: *const u8, right: *const u8, bytes: usize) -> i32;
2305
2306/// See documentation of [`std::hint::black_box`] for details.
2307///
2308/// [`std::hint::black_box`]: crate::hint::black_box
2309#[rustc_nounwind]
2310#[rustc_intrinsic]
2311#[rustc_intrinsic_const_stable_indirect]
2312pub const fn black_box<T>(dummy: T) -> T;
2313
2314/// Selects which function to call depending on the context.
2315///
2316/// If this function is evaluated at compile-time, then a call to this
2317/// intrinsic will be replaced with a call to `called_in_const`. It gets
2318/// replaced with a call to `called_at_rt` otherwise.
2319///
2320/// This function is safe to call, but note the stability concerns below.
2321///
2322/// # Type Requirements
2323///
2324/// The two functions must be both function items. They cannot be function
2325/// pointers or closures. The first function must be a `const fn`.
2326///
2327/// `arg` will be the tupled arguments that will be passed to either one of
2328/// the two functions, therefore, both functions must accept the same type of
2329/// arguments. Both functions must return RET.
2330///
2331/// # Stability concerns
2332///
2333/// Rust has not yet decided that `const fn` are allowed to tell whether
2334/// they run at compile-time or at runtime. Therefore, when using this
2335/// intrinsic anywhere that can be reached from stable, it is crucial that
2336/// the end-to-end behavior of the stable `const fn` is the same for both
2337/// modes of execution. (Here, Undefined Behavior is considered "the same"
2338/// as any other behavior, so if the function exhibits UB at runtime then
2339/// it may do whatever it wants at compile-time.)
2340///
2341/// Here is an example of how this could cause a problem:
2342/// ```no_run
2343/// #![feature(const_eval_select)]
2344/// #![feature(core_intrinsics)]
2345/// # #![allow(internal_features)]
2346/// use std::intrinsics::const_eval_select;
2347///
2348/// // Standard library
2349/// pub const fn inconsistent() -> i32 {
2350/// fn runtime() -> i32 { 1 }
2351/// const fn compiletime() -> i32 { 2 }
2352///
2353/// // ⚠ This code violates the required equivalence of `compiletime`
2354/// // and `runtime`.
2355/// const_eval_select((), compiletime, runtime)
2356/// }
2357///
2358/// // User Crate
2359/// const X: i32 = inconsistent();
2360/// let x = inconsistent();
2361/// assert_eq!(x, X);
2362/// ```
2363///
2364/// Currently such an assertion would always succeed; until Rust decides
2365/// otherwise, that principle should not be violated.
2366#[rustc_const_unstable(feature = "const_eval_select", issue = "124625")]
2367#[rustc_intrinsic]
2368pub const fn const_eval_select<ARG: Tuple, F, G, RET>(
2369 _arg: ARG,
2370 _called_in_const: F,
2371 _called_at_rt: G,
2372) -> RET
2373where
2374 G: FnOnce<ARG, Output = RET>,
2375 F: const FnOnce<ARG, Output = RET>;
2376
2377/// A macro to make it easier to invoke const_eval_select. Use as follows:
2378/// ```rust,ignore (just a macro example)
2379/// const_eval_select!(
2380/// @capture { arg1: i32 = some_expr, arg2: T = other_expr } -> U:
2381/// if const #[attributes_for_const_arm] {
2382/// // Compile-time code goes here.
2383/// } else #[attributes_for_runtime_arm] {
2384/// // Run-time code goes here.
2385/// }
2386/// )
2387/// ```
2388/// The `@capture` block declares which surrounding variables / expressions can be
2389/// used inside the `if const`.
2390/// Note that the two arms of this `if` really each become their own function, which is why the
2391/// macro supports setting attributes for those functions. The runtime function is always
2392/// marked as `#[inline]`.
2393///
2394/// See [`const_eval_select()`] for the rules and requirements around that intrinsic.
2395pub(crate) macro const_eval_select {
2396 (
2397 @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? :
2398 if const
2399 $(#[$compiletime_attr:meta])* $compiletime:block
2400 else
2401 $(#[$runtime_attr:meta])* $runtime:block
2402 ) => {
2403 // Use the `noinline` arm, after adding explicit `inline` attributes
2404 $crate::intrinsics::const_eval_select!(
2405 @capture$([$($binders)*])? { $($arg : $ty = $val),* } $(-> $ret)? :
2406 #[noinline]
2407 if const
2408 #[inline] // prevent codegen on this function
2409 $(#[$compiletime_attr])*
2410 $compiletime
2411 else
2412 #[inline] // avoid the overhead of an extra fn call
2413 $(#[$runtime_attr])*
2414 $runtime
2415 )
2416 },
2417 // With a leading #[noinline], we don't add inline attributes
2418 (
2419 @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? :
2420 #[noinline]
2421 if const
2422 $(#[$compiletime_attr:meta])* $compiletime:block
2423 else
2424 $(#[$runtime_attr:meta])* $runtime:block
2425 ) => {{
2426 $(#[$runtime_attr])*
2427 fn runtime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2428 $runtime
2429 }
2430
2431 $(#[$compiletime_attr])*
2432 const fn compiletime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2433 // Don't warn if one of the arguments is unused.
2434 $(let _ = $arg;)*
2435
2436 $compiletime
2437 }
2438
2439 const_eval_select(($($val,)*), compiletime, runtime)
2440 }},
2441 // We support leaving away the `val` expressions for *all* arguments
2442 // (but not for *some* arguments, that's too tricky).
2443 (
2444 @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty),* $(,)? } $( -> $ret:ty )? :
2445 if const
2446 $(#[$compiletime_attr:meta])* $compiletime:block
2447 else
2448 $(#[$runtime_attr:meta])* $runtime:block
2449 ) => {
2450 $crate::intrinsics::const_eval_select!(
2451 @capture$([$($binders)*])? { $($arg : $ty = $arg),* } $(-> $ret)? :
2452 if const
2453 $(#[$compiletime_attr])* $compiletime
2454 else
2455 $(#[$runtime_attr])* $runtime
2456 )
2457 },
2458}
2459
2460/// Returns whether the argument's value is statically known at
2461/// compile-time.
2462///
2463/// This is useful when there is a way of writing the code that will
2464/// be *faster* when some variables have known values, but *slower*
2465/// in the general case: an `if is_val_statically_known(var)` can be used
2466/// to select between these two variants. The `if` will be optimized away
2467/// and only the desired branch remains.
2468///
2469/// Formally speaking, this function non-deterministically returns `true`
2470/// or `false`, and the caller has to ensure sound behavior for both cases.
2471/// In other words, the following code has *Undefined Behavior*:
2472///
2473/// ```no_run
2474/// #![feature(core_intrinsics)]
2475/// # #![allow(internal_features)]
2476/// use std::hint::unreachable_unchecked;
2477/// use std::intrinsics::is_val_statically_known;
2478///
2479/// if !is_val_statically_known(0) { unsafe { unreachable_unchecked(); } }
2480/// ```
2481///
2482/// This also means that the following code's behavior is unspecified; it
2483/// may panic, or it may not:
2484///
2485/// ```no_run
2486/// #![feature(core_intrinsics)]
2487/// # #![allow(internal_features)]
2488/// use std::intrinsics::is_val_statically_known;
2489///
2490/// assert_eq!(is_val_statically_known(0), is_val_statically_known(0));
2491/// ```
2492///
2493/// Unsafe code may not rely on `is_val_statically_known` returning any
2494/// particular value, ever. However, the compiler will generally make it
2495/// return `true` only if the value of the argument is actually known.
2496///
2497/// # Stability concerns
2498///
2499/// While it is safe to call, this intrinsic may behave differently in
2500/// a `const` context than otherwise. See the [`const_eval_select()`]
2501/// documentation for an explanation of the issues this can cause. Unlike
2502/// `const_eval_select`, this intrinsic isn't guaranteed to behave
2503/// deterministically even in a `const` context.
2504///
2505/// # Type Requirements
2506///
2507/// `T` must be either a `bool`, a `char`, a primitive numeric type (e.g. `f32`,
2508/// but not `NonZeroISize`), or any thin pointer (e.g. `*mut String`).
2509/// Any other argument types *may* cause a compiler error.
2510///
2511/// ## Pointers
2512///
2513/// When the input is a pointer, only the pointer itself is
2514/// ever considered. The pointee has no effect. Currently, these functions
2515/// behave identically:
2516///
2517/// ```
2518/// #![feature(core_intrinsics)]
2519/// # #![allow(internal_features)]
2520/// use std::intrinsics::is_val_statically_known;
2521///
2522/// fn foo(x: &i32) -> bool {
2523/// is_val_statically_known(x)
2524/// }
2525///
2526/// fn bar(x: &i32) -> bool {
2527/// is_val_statically_known(
2528/// (x as *const i32).addr()
2529/// )
2530/// }
2531/// # _ = foo(&5_i32);
2532/// # _ = bar(&5_i32);
2533/// ```
2534#[rustc_const_stable_indirect]
2535#[rustc_nounwind]
2536#[unstable(feature = "core_intrinsics", issue = "none")]
2537#[rustc_intrinsic]
2538pub const fn is_val_statically_known<T: Copy>(_arg: T) -> bool {
2539 false
2540}
2541
2542/// Non-overlapping *typed* swap of a single value.
2543///
2544/// The codegen backends will replace this with a better implementation when
2545/// `T` is a simple type that can be loaded and stored as an immediate.
2546///
2547/// The stabilized form of this intrinsic is [`crate::mem::swap`].
2548///
2549/// # Safety
2550/// Behavior is undefined if any of the following conditions are violated:
2551///
2552/// * Both `x` and `y` must be [valid] for both reads and writes.
2553///
2554/// * Both `x` and `y` must be properly aligned.
2555///
2556/// * The region of memory beginning at `x` must *not* overlap with the region of memory
2557/// beginning at `y`.
2558///
2559/// * The memory pointed by `x` and `y` must both contain values of type `T`.
2560///
2561/// [valid]: crate::ptr#safety
2562#[rustc_nounwind]
2563#[inline]
2564#[rustc_intrinsic]
2565#[rustc_intrinsic_const_stable_indirect]
2566pub const unsafe fn typed_swap_nonoverlapping<T>(x: *mut T, y: *mut T) {
2567 // SAFETY: The caller provided single non-overlapping items behind
2568 // pointers, so swapping them with `count: 1` is fine.
2569 unsafe { ptr::swap_nonoverlapping(x, y, 1) };
2570}
2571
2572/// Returns whether we should perform some UB-checking at runtime. This eventually evaluates to
2573/// `cfg!(ub_checks)`, but behaves different from `cfg!` when mixing crates built with different
2574/// flags: if the crate has UB checks enabled or carries the `#[rustc_preserve_ub_checks]`
2575/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2576/// a crate that does not delay evaluation further); otherwise it can happen any time.
2577///
2578/// The common case here is a user program built with ub_checks linked against the distributed
2579/// sysroot which is built without ub_checks but with `#[rustc_preserve_ub_checks]`.
2580/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2581/// `#[inline]`), gating assertions on `ub_checks()` rather than `cfg!(ub_checks)` means that
2582/// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the
2583/// user has UB checks disabled, the checks will still get optimized out. This intrinsic is
2584/// primarily used by [`crate::ub_checks::assert_unsafe_precondition`].
2585#[rustc_intrinsic_const_stable_indirect] // just for UB checks
2586#[inline(always)]
2587#[rustc_intrinsic]
2588pub const fn ub_checks() -> bool {
2589 cfg!(ub_checks)
2590}
2591
2592/// Returns whether we should perform some overflow-checking at runtime. This eventually evaluates to
2593/// `cfg!(overflow_checks)`, but behaves different from `cfg!` when mixing crates built with different
2594/// flags: if the crate has overflow checks enabled or carries the `#[rustc_inherit_overflow_checks]`
2595/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2596/// a crate that does not delay evaluation further); otherwise it can happen any time.
2597///
2598/// The common case here is a user program built with overflow_checks linked against the distributed
2599/// sysroot which is built without overflow_checks but with `#[rustc_inherit_overflow_checks]`.
2600/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2601/// `#[inline]`), gating assertions on `overflow_checks()` rather than `cfg!(overflow_checks)` means that
2602/// assertions are enabled whenever the *user crate* has overflow checks enabled. However if the
2603/// user has overflow checks disabled, the checks will still get optimized out.
2604#[inline(always)]
2605#[rustc_intrinsic]
2606pub const fn overflow_checks() -> bool {
2607 cfg!(debug_assertions)
2608}
2609
2610/// Allocates a block of memory at compile time.
2611/// At runtime, just returns a null pointer.
2612///
2613/// # Safety
2614///
2615/// - The `align` argument must be a power of two.
2616/// - At compile time, a compile error occurs if this constraint is violated.
2617/// - At runtime, it is not checked.
2618#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2619#[rustc_nounwind]
2620#[rustc_intrinsic]
2621#[miri::intrinsic_fallback_is_spec]
2622pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 {
2623 // const eval overrides this function, but runtime code for now just returns null pointers.
2624 // See <https://github.com/rust-lang/rust/issues/93935>.
2625 crate::ptr::null_mut()
2626}
2627
2628/// Deallocates a memory which allocated by `intrinsics::const_allocate` at compile time.
2629/// At runtime, does nothing.
2630///
2631/// # Safety
2632///
2633/// - The `align` argument must be a power of two.
2634/// - At compile time, a compile error occurs if this constraint is violated.
2635/// - At runtime, it is not checked.
2636/// - If the `ptr` is created in an another const, this intrinsic doesn't deallocate it.
2637/// - If the `ptr` is pointing to a local variable, this intrinsic doesn't deallocate it.
2638#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2639#[unstable(feature = "core_intrinsics", issue = "none")]
2640#[rustc_nounwind]
2641#[rustc_intrinsic]
2642#[miri::intrinsic_fallback_is_spec]
2643pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {
2644 // Runtime NOP
2645}
2646
2647#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2648#[rustc_nounwind]
2649#[rustc_intrinsic]
2650#[miri::intrinsic_fallback_is_spec]
2651pub const unsafe fn const_make_global(ptr: *mut u8) -> *const u8 {
2652 // const eval overrides this function; at runtime, it is a NOP.
2653 ptr
2654}
2655
2656/// Check if the pre-condition `cond` has been met.
2657///
2658/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2659/// returns false.
2660///
2661/// Note that this function is a no-op during constant evaluation.
2662#[unstable(feature = "contracts_internals", issue = "128044")]
2663// Calls to this function get inserted by an AST expansion pass, which uses the equivalent of
2664// `#[allow_internal_unstable]` to allow using `contracts_internals` functions. Const-checking
2665// doesn't honor `#[allow_internal_unstable]`, so for the const feature gate we use the user-facing
2666// `contracts` feature rather than the perma-unstable `contracts_internals`
2667#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2668#[lang = "contract_check_requires"]
2669#[rustc_intrinsic]
2670pub const fn contract_check_requires<C: Fn() -> bool + Copy>(cond: C) {
2671 const_eval_select!(
2672 @capture[C: Fn() -> bool + Copy] { cond: C } :
2673 if const {
2674 // Do nothing
2675 } else {
2676 if !cond() {
2677 // Emit no unwind panic in case this was a safety requirement.
2678 crate::panicking::panic_nounwind("failed requires check");
2679 }
2680 }
2681 )
2682}
2683
2684/// Check if the post-condition `cond` has been met.
2685///
2686/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2687/// returns false.
2688///
2689/// If `cond` is `None`, then no postcondition checking is performed.
2690///
2691/// Note that this function is a no-op during constant evaluation.
2692#[unstable(feature = "contracts_internals", issue = "128044")]
2693// Similar to `contract_check_requires`, we need to use the user-facing
2694// `contracts` feature rather than the perma-unstable `contracts_internals`.
2695// Const-checking doesn't honor allow_internal_unstable logic used by contract expansion.
2696#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2697#[lang = "contract_check_ensures"]
2698#[rustc_intrinsic]
2699pub const fn contract_check_ensures<C: Fn(&Ret) -> bool + Copy, Ret>(
2700 cond: Option<C>,
2701 ret: Ret,
2702) -> Ret {
2703 const_eval_select!(
2704 @capture[C: Fn(&Ret) -> bool + Copy, Ret] { cond: Option<C>, ret: Ret } -> Ret :
2705 if const {
2706 // Do nothing
2707 ret
2708 } else {
2709 match cond {
2710 crate::option::Option::Some(cond) => {
2711 if !cond(&ret) {
2712 // Emit no unwind panic in case this was a safety requirement.
2713 crate::panicking::panic_nounwind("failed ensures check");
2714 }
2715 },
2716 crate::option::Option::None => {},
2717 }
2718 ret
2719 }
2720 )
2721}
2722
2723/// The intrinsic will return the size stored in that vtable.
2724///
2725/// # Safety
2726///
2727/// `ptr` must point to a vtable.
2728#[rustc_nounwind]
2729#[unstable(feature = "core_intrinsics", issue = "none")]
2730#[rustc_intrinsic]
2731pub unsafe fn vtable_size(ptr: *const ()) -> usize;
2732
2733/// The intrinsic will return the alignment stored in that vtable.
2734///
2735/// # Safety
2736///
2737/// `ptr` must point to a vtable.
2738#[rustc_nounwind]
2739#[unstable(feature = "core_intrinsics", issue = "none")]
2740#[rustc_intrinsic]
2741pub unsafe fn vtable_align(ptr: *const ()) -> usize;
2742
2743/// The size of a type in bytes.
2744///
2745/// Note that, unlike most intrinsics, this is safe to call;
2746/// it does not require an `unsafe` block.
2747/// Therefore, implementations must not require the user to uphold
2748/// any safety invariants.
2749///
2750/// More specifically, this is the offset in bytes between successive
2751/// items of the same type, including alignment padding.
2752///
2753/// Note that, unlike most intrinsics, this can only be called at compile-time
2754/// as backends do not have an implementation for it. The only caller (its
2755/// stable counterpart) wraps this intrinsic call in a `const` block so that
2756/// backends only see an evaluated constant.
2757///
2758/// The stabilized version of this intrinsic is [`core::mem::size_of`].
2759#[rustc_nounwind]
2760#[unstable(feature = "core_intrinsics", issue = "none")]
2761#[rustc_intrinsic_const_stable_indirect]
2762#[rustc_intrinsic]
2763pub const fn size_of<T>() -> usize;
2764
2765/// The minimum alignment of a type.
2766///
2767/// Note that, unlike most intrinsics, this is safe to call;
2768/// it does not require an `unsafe` block.
2769/// Therefore, implementations must not require the user to uphold
2770/// any safety invariants.
2771///
2772/// Note that, unlike most intrinsics, this can only be called at compile-time
2773/// as backends do not have an implementation for it. The only caller (its
2774/// stable counterpart) wraps this intrinsic call in a `const` block so that
2775/// backends only see an evaluated constant.
2776///
2777/// The stabilized version of this intrinsic is [`core::mem::align_of`].
2778#[rustc_nounwind]
2779#[unstable(feature = "core_intrinsics", issue = "none")]
2780#[rustc_intrinsic_const_stable_indirect]
2781#[rustc_intrinsic]
2782pub const fn align_of<T>() -> usize;
2783
2784/// Returns the number of variants of the type `T` cast to a `usize`;
2785/// if `T` has no variants, returns `0`. Uninhabited variants will be counted.
2786///
2787/// Note that, unlike most intrinsics, this can only be called at compile-time
2788/// as backends do not have an implementation for it. The only caller (its
2789/// stable counterpart) wraps this intrinsic call in a `const` block so that
2790/// backends only see an evaluated constant.
2791///
2792/// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`].
2793#[rustc_nounwind]
2794#[unstable(feature = "core_intrinsics", issue = "none")]
2795#[rustc_intrinsic]
2796pub const fn variant_count<T>() -> usize;
2797
2798/// The size of the referenced value in bytes.
2799///
2800/// The stabilized version of this intrinsic is [`core::mem::size_of_val`].
2801///
2802/// # Safety
2803///
2804/// See [`crate::mem::size_of_val_raw`] for safety conditions.
2805#[rustc_nounwind]
2806#[unstable(feature = "core_intrinsics", issue = "none")]
2807#[rustc_intrinsic]
2808#[rustc_intrinsic_const_stable_indirect]
2809pub const unsafe fn size_of_val<T: ?Sized>(ptr: *const T) -> usize;
2810
2811/// The required alignment of the referenced value.
2812///
2813/// The stabilized version of this intrinsic is [`core::mem::align_of_val`].
2814///
2815/// # Safety
2816///
2817/// See [`crate::mem::align_of_val_raw`] for safety conditions.
2818#[rustc_nounwind]
2819#[unstable(feature = "core_intrinsics", issue = "none")]
2820#[rustc_intrinsic]
2821#[rustc_intrinsic_const_stable_indirect]
2822pub const unsafe fn align_of_val<T: ?Sized>(ptr: *const T) -> usize;
2823
2824/// Gets a static string slice containing the name of a type.
2825///
2826/// Note that, unlike most intrinsics, this can only be called at compile-time
2827/// as backends do not have an implementation for it. The only caller (its
2828/// stable counterpart) wraps this intrinsic call in a `const` block so that
2829/// backends only see an evaluated constant.
2830///
2831/// The stabilized version of this intrinsic is [`core::any::type_name`].
2832#[rustc_nounwind]
2833#[unstable(feature = "core_intrinsics", issue = "none")]
2834#[rustc_intrinsic]
2835pub const fn type_name<T: ?Sized>() -> &'static str;
2836
2837/// Gets an identifier which is globally unique to the specified type. This
2838/// function will return the same value for a type regardless of whichever
2839/// crate it is invoked in.
2840///
2841/// Note that, unlike most intrinsics, this can only be called at compile-time
2842/// as backends do not have an implementation for it. The only caller (its
2843/// stable counterpart) wraps this intrinsic call in a `const` block so that
2844/// backends only see an evaluated constant.
2845///
2846/// The stabilized version of this intrinsic is [`core::any::TypeId::of`].
2847#[rustc_nounwind]
2848#[unstable(feature = "core_intrinsics", issue = "none")]
2849#[rustc_intrinsic]
2850pub const fn type_id<T: ?Sized + 'static>() -> crate::any::TypeId;
2851
2852/// Tests (at compile-time) if two [`crate::any::TypeId`] instances identify the
2853/// same type. This is necessary because at const-eval time the actual discriminating
2854/// data is opaque and cannot be inspected directly.
2855///
2856/// The stabilized version of this intrinsic is the [PartialEq] impl for [`core::any::TypeId`].
2857#[rustc_nounwind]
2858#[unstable(feature = "core_intrinsics", issue = "none")]
2859#[rustc_intrinsic]
2860#[rustc_do_not_const_check]
2861pub const fn type_id_eq(a: crate::any::TypeId, b: crate::any::TypeId) -> bool {
2862 a.data == b.data
2863}
2864
2865/// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`.
2866///
2867/// This is used to implement functions like `slice::from_raw_parts_mut` and
2868/// `ptr::from_raw_parts` in a way compatible with the compiler being able to
2869/// change the possible layouts of pointers.
2870#[rustc_nounwind]
2871#[unstable(feature = "core_intrinsics", issue = "none")]
2872#[rustc_intrinsic_const_stable_indirect]
2873#[rustc_intrinsic]
2874pub const fn aggregate_raw_ptr<P: bounds::BuiltinDeref, D, M>(data: D, meta: M) -> P
2875where
2876 <P as bounds::BuiltinDeref>::Pointee: ptr::Pointee<Metadata = M>;
2877
2878/// Lowers in MIR to `Rvalue::UnaryOp` with `UnOp::PtrMetadata`.
2879///
2880/// This is used to implement functions like `ptr::metadata`.
2881#[rustc_nounwind]
2882#[unstable(feature = "core_intrinsics", issue = "none")]
2883#[rustc_intrinsic_const_stable_indirect]
2884#[rustc_intrinsic]
2885pub const fn ptr_metadata<P: ptr::Pointee<Metadata = M> + PointeeSized, M>(ptr: *const P) -> M;
2886
2887/// This is an accidentally-stable alias to [`ptr::copy_nonoverlapping`]; use that instead.
2888// Note (intentionally not in the doc comment): `ptr::copy_nonoverlapping` adds some extra
2889// debug assertions; if you are writing compiler tests or code inside the standard library
2890// that wants to avoid those debug assertions, directly call this intrinsic instead.
2891#[stable(feature = "rust1", since = "1.0.0")]
2892#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2893#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2894#[rustc_nounwind]
2895#[rustc_intrinsic]
2896pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
2897
2898/// This is an accidentally-stable alias to [`ptr::copy`]; use that instead.
2899// Note (intentionally not in the doc comment): `ptr::copy` adds some extra
2900// debug assertions; if you are writing compiler tests or code inside the standard library
2901// that wants to avoid those debug assertions, directly call this intrinsic instead.
2902#[stable(feature = "rust1", since = "1.0.0")]
2903#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2904#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2905#[rustc_nounwind]
2906#[rustc_intrinsic]
2907pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize);
2908
2909/// This is an accidentally-stable alias to [`ptr::write_bytes`]; use that instead.
2910// Note (intentionally not in the doc comment): `ptr::write_bytes` adds some extra
2911// debug assertions; if you are writing compiler tests or code inside the standard library
2912// that wants to avoid those debug assertions, directly call this intrinsic instead.
2913#[stable(feature = "rust1", since = "1.0.0")]
2914#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2915#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2916#[rustc_nounwind]
2917#[rustc_intrinsic]
2918pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
2919
2920/// Returns the minimum (IEEE 754-2008 minNum) of two `f16` values.
2921///
2922/// Note that, unlike most intrinsics, this is safe to call;
2923/// it does not require an `unsafe` block.
2924/// Therefore, implementations must not require the user to uphold
2925/// any safety invariants.
2926///
2927/// The stabilized version of this intrinsic is
2928/// [`f16::min`]
2929#[rustc_nounwind]
2930#[rustc_intrinsic]
2931pub const fn minnumf16(x: f16, y: f16) -> f16;
2932
2933/// Returns the minimum (IEEE 754-2008 minNum) of two `f32` values.
2934///
2935/// Note that, unlike most intrinsics, this is safe to call;
2936/// it does not require an `unsafe` block.
2937/// Therefore, implementations must not require the user to uphold
2938/// any safety invariants.
2939///
2940/// The stabilized version of this intrinsic is
2941/// [`f32::min`]
2942#[rustc_nounwind]
2943#[rustc_intrinsic_const_stable_indirect]
2944#[rustc_intrinsic]
2945pub const fn minnumf32(x: f32, y: f32) -> f32;
2946
2947/// Returns the minimum (IEEE 754-2008 minNum) of two `f64` values.
2948///
2949/// Note that, unlike most intrinsics, this is safe to call;
2950/// it does not require an `unsafe` block.
2951/// Therefore, implementations must not require the user to uphold
2952/// any safety invariants.
2953///
2954/// The stabilized version of this intrinsic is
2955/// [`f64::min`]
2956#[rustc_nounwind]
2957#[rustc_intrinsic_const_stable_indirect]
2958#[rustc_intrinsic]
2959pub const fn minnumf64(x: f64, y: f64) -> f64;
2960
2961/// Returns the minimum (IEEE 754-2008 minNum) of two `f128` values.
2962///
2963/// Note that, unlike most intrinsics, this is safe to call;
2964/// it does not require an `unsafe` block.
2965/// Therefore, implementations must not require the user to uphold
2966/// any safety invariants.
2967///
2968/// The stabilized version of this intrinsic is
2969/// [`f128::min`]
2970#[rustc_nounwind]
2971#[rustc_intrinsic]
2972pub const fn minnumf128(x: f128, y: f128) -> f128;
2973
2974/// Returns the minimum (IEEE 754-2019 minimum) of two `f16` values.
2975///
2976/// Note that, unlike most intrinsics, this is safe to call;
2977/// it does not require an `unsafe` block.
2978/// Therefore, implementations must not require the user to uphold
2979/// any safety invariants.
2980#[rustc_nounwind]
2981#[rustc_intrinsic]
2982pub const fn minimumf16(x: f16, y: f16) -> f16 {
2983 if x < y {
2984 x
2985 } else if y < x {
2986 y
2987 } else if x == y {
2988 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
2989 } else {
2990 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
2991 x + y
2992 }
2993}
2994
2995/// Returns the minimum (IEEE 754-2019 minimum) of two `f32` values.
2996///
2997/// Note that, unlike most intrinsics, this is safe to call;
2998/// it does not require an `unsafe` block.
2999/// Therefore, implementations must not require the user to uphold
3000/// any safety invariants.
3001#[rustc_nounwind]
3002#[rustc_intrinsic]
3003pub const fn minimumf32(x: f32, y: f32) -> f32 {
3004 if x < y {
3005 x
3006 } else if y < x {
3007 y
3008 } else if x == y {
3009 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3010 } else {
3011 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3012 x + y
3013 }
3014}
3015
3016/// Returns the minimum (IEEE 754-2019 minimum) of two `f64` values.
3017///
3018/// Note that, unlike most intrinsics, this is safe to call;
3019/// it does not require an `unsafe` block.
3020/// Therefore, implementations must not require the user to uphold
3021/// any safety invariants.
3022#[rustc_nounwind]
3023#[rustc_intrinsic]
3024pub const fn minimumf64(x: f64, y: f64) -> f64 {
3025 if x < y {
3026 x
3027 } else if y < x {
3028 y
3029 } else if x == y {
3030 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3031 } else {
3032 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3033 x + y
3034 }
3035}
3036
3037/// Returns the minimum (IEEE 754-2019 minimum) of two `f128` values.
3038///
3039/// Note that, unlike most intrinsics, this is safe to call;
3040/// it does not require an `unsafe` block.
3041/// Therefore, implementations must not require the user to uphold
3042/// any safety invariants.
3043#[rustc_nounwind]
3044#[rustc_intrinsic]
3045pub const fn minimumf128(x: f128, y: f128) -> f128 {
3046 if x < y {
3047 x
3048 } else if y < x {
3049 y
3050 } else if x == y {
3051 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3052 } else {
3053 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3054 x + y
3055 }
3056}
3057
3058/// Returns the maximum (IEEE 754-2008 maxNum) of two `f16` values.
3059///
3060/// Note that, unlike most intrinsics, this is safe to call;
3061/// it does not require an `unsafe` block.
3062/// Therefore, implementations must not require the user to uphold
3063/// any safety invariants.
3064///
3065/// The stabilized version of this intrinsic is
3066/// [`f16::max`]
3067#[rustc_nounwind]
3068#[rustc_intrinsic]
3069pub const fn maxnumf16(x: f16, y: f16) -> f16;
3070
3071/// Returns the maximum (IEEE 754-2008 maxNum) of two `f32` values.
3072///
3073/// Note that, unlike most intrinsics, this is safe to call;
3074/// it does not require an `unsafe` block.
3075/// Therefore, implementations must not require the user to uphold
3076/// any safety invariants.
3077///
3078/// The stabilized version of this intrinsic is
3079/// [`f32::max`]
3080#[rustc_nounwind]
3081#[rustc_intrinsic_const_stable_indirect]
3082#[rustc_intrinsic]
3083pub const fn maxnumf32(x: f32, y: f32) -> f32;
3084
3085/// Returns the maximum (IEEE 754-2008 maxNum) of two `f64` values.
3086///
3087/// Note that, unlike most intrinsics, this is safe to call;
3088/// it does not require an `unsafe` block.
3089/// Therefore, implementations must not require the user to uphold
3090/// any safety invariants.
3091///
3092/// The stabilized version of this intrinsic is
3093/// [`f64::max`]
3094#[rustc_nounwind]
3095#[rustc_intrinsic_const_stable_indirect]
3096#[rustc_intrinsic]
3097pub const fn maxnumf64(x: f64, y: f64) -> f64;
3098
3099/// Returns the maximum (IEEE 754-2008 maxNum) of two `f128` values.
3100///
3101/// Note that, unlike most intrinsics, this is safe to call;
3102/// it does not require an `unsafe` block.
3103/// Therefore, implementations must not require the user to uphold
3104/// any safety invariants.
3105///
3106/// The stabilized version of this intrinsic is
3107/// [`f128::max`]
3108#[rustc_nounwind]
3109#[rustc_intrinsic]
3110pub const fn maxnumf128(x: f128, y: f128) -> f128;
3111
3112/// Returns the maximum (IEEE 754-2019 maximum) of two `f16` values.
3113///
3114/// Note that, unlike most intrinsics, this is safe to call;
3115/// it does not require an `unsafe` block.
3116/// Therefore, implementations must not require the user to uphold
3117/// any safety invariants.
3118#[rustc_nounwind]
3119#[rustc_intrinsic]
3120pub const fn maximumf16(x: f16, y: f16) -> f16 {
3121 if x > y {
3122 x
3123 } else if y > x {
3124 y
3125 } else if x == y {
3126 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3127 } else {
3128 x + y
3129 }
3130}
3131
3132/// Returns the maximum (IEEE 754-2019 maximum) of two `f32` values.
3133///
3134/// Note that, unlike most intrinsics, this is safe to call;
3135/// it does not require an `unsafe` block.
3136/// Therefore, implementations must not require the user to uphold
3137/// any safety invariants.
3138#[rustc_nounwind]
3139#[rustc_intrinsic]
3140pub const fn maximumf32(x: f32, y: f32) -> f32 {
3141 if x > y {
3142 x
3143 } else if y > x {
3144 y
3145 } else if x == y {
3146 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3147 } else {
3148 x + y
3149 }
3150}
3151
3152/// Returns the maximum (IEEE 754-2019 maximum) of two `f64` values.
3153///
3154/// Note that, unlike most intrinsics, this is safe to call;
3155/// it does not require an `unsafe` block.
3156/// Therefore, implementations must not require the user to uphold
3157/// any safety invariants.
3158#[rustc_nounwind]
3159#[rustc_intrinsic]
3160pub const fn maximumf64(x: f64, y: f64) -> f64 {
3161 if x > y {
3162 x
3163 } else if y > x {
3164 y
3165 } else if x == y {
3166 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3167 } else {
3168 x + y
3169 }
3170}
3171
3172/// Returns the maximum (IEEE 754-2019 maximum) of two `f128` values.
3173///
3174/// Note that, unlike most intrinsics, this is safe to call;
3175/// it does not require an `unsafe` block.
3176/// Therefore, implementations must not require the user to uphold
3177/// any safety invariants.
3178#[rustc_nounwind]
3179#[rustc_intrinsic]
3180pub const fn maximumf128(x: f128, y: f128) -> f128 {
3181 if x > y {
3182 x
3183 } else if y > x {
3184 y
3185 } else if x == y {
3186 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3187 } else {
3188 x + y
3189 }
3190}
3191
3192/// Returns the absolute value of an `f16`.
3193///
3194/// The stabilized version of this intrinsic is
3195/// [`f16::abs`](../../std/primitive.f16.html#method.abs)
3196#[rustc_nounwind]
3197#[rustc_intrinsic]
3198pub const fn fabsf16(x: f16) -> f16;
3199
3200/// Returns the absolute value of an `f32`.
3201///
3202/// The stabilized version of this intrinsic is
3203/// [`f32::abs`](../../std/primitive.f32.html#method.abs)
3204#[rustc_nounwind]
3205#[rustc_intrinsic_const_stable_indirect]
3206#[rustc_intrinsic]
3207pub const fn fabsf32(x: f32) -> f32;
3208
3209/// Returns the absolute value of an `f64`.
3210///
3211/// The stabilized version of this intrinsic is
3212/// [`f64::abs`](../../std/primitive.f64.html#method.abs)
3213#[rustc_nounwind]
3214#[rustc_intrinsic_const_stable_indirect]
3215#[rustc_intrinsic]
3216pub const fn fabsf64(x: f64) -> f64;
3217
3218/// Returns the absolute value of an `f128`.
3219///
3220/// The stabilized version of this intrinsic is
3221/// [`f128::abs`](../../std/primitive.f128.html#method.abs)
3222#[rustc_nounwind]
3223#[rustc_intrinsic]
3224pub const fn fabsf128(x: f128) -> f128;
3225
3226/// Copies the sign from `y` to `x` for `f16` values.
3227///
3228/// The stabilized version of this intrinsic is
3229/// [`f16::copysign`](../../std/primitive.f16.html#method.copysign)
3230#[rustc_nounwind]
3231#[rustc_intrinsic]
3232pub const fn copysignf16(x: f16, y: f16) -> f16;
3233
3234/// Copies the sign from `y` to `x` for `f32` values.
3235///
3236/// The stabilized version of this intrinsic is
3237/// [`f32::copysign`](../../std/primitive.f32.html#method.copysign)
3238#[rustc_nounwind]
3239#[rustc_intrinsic_const_stable_indirect]
3240#[rustc_intrinsic]
3241pub const fn copysignf32(x: f32, y: f32) -> f32;
3242/// Copies the sign from `y` to `x` for `f64` values.
3243///
3244/// The stabilized version of this intrinsic is
3245/// [`f64::copysign`](../../std/primitive.f64.html#method.copysign)
3246#[rustc_nounwind]
3247#[rustc_intrinsic_const_stable_indirect]
3248#[rustc_intrinsic]
3249pub const fn copysignf64(x: f64, y: f64) -> f64;
3250
3251/// Copies the sign from `y` to `x` for `f128` values.
3252///
3253/// The stabilized version of this intrinsic is
3254/// [`f128::copysign`](../../std/primitive.f128.html#method.copysign)
3255#[rustc_nounwind]
3256#[rustc_intrinsic]
3257pub const fn copysignf128(x: f128, y: f128) -> f128;
3258
3259/// Generates the LLVM body for the automatic differentiation of `f` using Enzyme,
3260/// with `df` as the derivative function and `args` as its arguments.
3261///
3262/// Used internally as the body of `df` when expanding the `#[autodiff_forward]`
3263/// and `#[autodiff_reverse]` attribute macros.
3264///
3265/// Type Parameters:
3266/// - `F`: The original function to differentiate. Must be a function item.
3267/// - `G`: The derivative function. Must be a function item.
3268/// - `T`: A tuple of arguments passed to `df`.
3269/// - `R`: The return type of the derivative function.
3270///
3271/// This shows where the `autodiff` intrinsic is used during macro expansion:
3272///
3273/// ```rust,ignore (macro example)
3274/// #[autodiff_forward(df1, Dual, Const, Dual)]
3275/// pub fn f1(x: &[f64], y: f64) -> f64 {
3276/// unimplemented!()
3277/// }
3278/// ```
3279///
3280/// expands to:
3281///
3282/// ```rust,ignore (macro example)
3283/// #[rustc_autodiff]
3284/// #[inline(never)]
3285/// pub fn f1(x: &[f64], y: f64) -> f64 {
3286/// ::core::panicking::panic("not implemented")
3287/// }
3288/// #[rustc_autodiff(Forward, 1, Dual, Const, Dual)]
3289/// pub fn df1(x: &[f64], bx_0: &[f64], y: f64) -> (f64, f64) {
3290/// ::core::intrinsics::autodiff(f1::<>, df1::<>, (x, bx_0, y))
3291/// }
3292/// ```
3293#[rustc_nounwind]
3294#[rustc_intrinsic]
3295pub const fn autodiff<F, G, T: crate::marker::Tuple, R>(f: F, df: G, args: T) -> R;
3296
3297/// Inform Miri that a given pointer definitely has a certain alignment.
3298#[cfg(miri)]
3299#[rustc_allow_const_fn_unstable(const_eval_select)]
3300pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize) {
3301 unsafe extern "Rust" {
3302 /// Miri-provided extern function to promise that a given pointer is properly aligned for
3303 /// "symbolic" alignment checks. Will fail if the pointer is not actually aligned or `align` is
3304 /// not a power of two. Has no effect when alignment checks are concrete (which is the default).
3305 fn miri_promise_symbolic_alignment(ptr: *const (), align: usize);
3306 }
3307
3308 const_eval_select!(
3309 @capture { ptr: *const (), align: usize}:
3310 if const {
3311 // Do nothing.
3312 } else {
3313 // SAFETY: this call is always safe.
3314 unsafe {
3315 miri_promise_symbolic_alignment(ptr, align);
3316 }
3317 }
3318 )
3319}
3320
3321/// Copies the current location of arglist `src` to the arglist `dst`.
3322///
3323/// FIXME: document safety requirements
3324#[rustc_intrinsic]
3325#[rustc_nounwind]
3326pub unsafe fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
3327
3328/// Loads an argument of type `T` from the `va_list` `ap` and increment the
3329/// argument `ap` points to.
3330///
3331/// FIXME: document safety requirements
3332#[rustc_intrinsic]
3333#[rustc_nounwind]
3334pub unsafe fn va_arg<T: VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
3335
3336/// Destroy the arglist `ap` after initialization with `va_start` or `va_copy`.
3337///
3338/// FIXME: document safety requirements
3339#[rustc_intrinsic]
3340#[rustc_nounwind]
3341pub unsafe fn va_end(ap: &mut VaListImpl<'_>);