Skip to main content

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
56use crate::ffi::va_list::{VaArgSafe, VaList};
57use crate::marker::{ConstParamTy, DiscriminantKind, PointeeSized, Tuple};
58use crate::{mem, ptr};
59
60mod bounds;
61pub mod fallback;
62pub mod gpu;
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#[allow(missing_docs)]
75#[derive(Debug, ConstParamTy, PartialEq, Eq)]
76pub enum AtomicOrdering {
77    // These values must match the compiler's `AtomicOrdering` defined in
78    // `rustc_middle/src/ty/consts/int.rs`!
79    Relaxed = 0,
80    Release = 1,
81    Acquire = 2,
82    AcqRel = 3,
83    SeqCst = 4,
84}
85
86// N.B., these intrinsics take raw pointers because they mutate aliased
87// memory, which is not valid for either `&` or `&mut`.
88
89/// Stores a value if the current value is the same as the `old` value.
90/// `T` must be an integer or pointer type.
91///
92/// The stabilized version of this intrinsic is available on the
93/// [`atomic`] types via the `compare_exchange` method.
94/// For example, [`AtomicBool::compare_exchange`].
95#[rustc_intrinsic]
96#[rustc_nounwind]
97pub unsafe fn atomic_cxchg<
98    T: Copy,
99    const ORD_SUCC: AtomicOrdering,
100    const ORD_FAIL: AtomicOrdering,
101>(
102    dst: *mut T,
103    old: T,
104    src: T,
105) -> (T, bool);
106
107/// Stores a value if the current value is the same as the `old` value.
108/// `T` must be an integer or pointer type. The comparison may spuriously fail.
109///
110/// The stabilized version of this intrinsic is available on the
111/// [`atomic`] types via the `compare_exchange_weak` method.
112/// For example, [`AtomicBool::compare_exchange_weak`].
113#[rustc_intrinsic]
114#[rustc_nounwind]
115pub unsafe fn atomic_cxchgweak<
116    T: Copy,
117    const ORD_SUCC: AtomicOrdering,
118    const ORD_FAIL: AtomicOrdering,
119>(
120    _dst: *mut T,
121    _old: T,
122    _src: T,
123) -> (T, bool);
124
125/// Loads the current value of the pointer.
126/// `T` must be an integer or pointer type.
127///
128/// The stabilized version of this intrinsic is available on the
129/// [`atomic`] types via the `load` method. For example, [`AtomicBool::load`].
130#[rustc_intrinsic]
131#[rustc_nounwind]
132pub unsafe fn atomic_load<T: Copy, const ORD: AtomicOrdering>(src: *const T) -> T;
133
134/// Stores the value at the specified memory location.
135/// `T` must be an integer or pointer type.
136///
137/// The stabilized version of this intrinsic is available on the
138/// [`atomic`] types via the `store` method. For example, [`AtomicBool::store`].
139#[rustc_intrinsic]
140#[rustc_nounwind]
141pub unsafe fn atomic_store<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, val: T);
142
143/// Stores the value at the specified memory location, returning the old value.
144/// `T` must be an integer or pointer type.
145///
146/// The stabilized version of this intrinsic is available on the
147/// [`atomic`] types via the `swap` method. For example, [`AtomicBool::swap`].
148#[rustc_intrinsic]
149#[rustc_nounwind]
150pub unsafe fn atomic_xchg<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
151
152/// Adds to the current value, returning the previous value.
153/// `T` must be an integer or pointer type.
154/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
155///
156/// The stabilized version of this intrinsic is available on the
157/// [`atomic`] types via the `fetch_add` method. For example, [`AtomicIsize::fetch_add`].
158#[rustc_intrinsic]
159#[rustc_nounwind]
160pub unsafe fn atomic_xadd<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
161
162/// Subtract from the current value, returning the previous value.
163/// `T` must be an integer or pointer type.
164/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
165///
166/// The stabilized version of this intrinsic is available on the
167/// [`atomic`] types via the `fetch_sub` method. For example, [`AtomicIsize::fetch_sub`].
168#[rustc_intrinsic]
169#[rustc_nounwind]
170pub unsafe fn atomic_xsub<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
171
172/// Bitwise and with the current value, returning the previous value.
173/// `T` must be an integer or pointer type.
174/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
175///
176/// The stabilized version of this intrinsic is available on the
177/// [`atomic`] types via the `fetch_and` method. For example, [`AtomicBool::fetch_and`].
178#[rustc_intrinsic]
179#[rustc_nounwind]
180pub unsafe fn atomic_and<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
181
182/// Bitwise nand with the current value, returning the previous value.
183/// `T` must be an integer or pointer type.
184/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
185///
186/// The stabilized version of this intrinsic is available on the
187/// [`AtomicBool`] type via the `fetch_nand` method. For example, [`AtomicBool::fetch_nand`].
188#[rustc_intrinsic]
189#[rustc_nounwind]
190pub unsafe fn atomic_nand<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
191
192/// Bitwise or with the current value, returning the previous value.
193/// `T` must be an integer or pointer type.
194/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
195///
196/// The stabilized version of this intrinsic is available on the
197/// [`atomic`] types via the `fetch_or` method. For example, [`AtomicBool::fetch_or`].
198#[rustc_intrinsic]
199#[rustc_nounwind]
200pub unsafe fn atomic_or<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
201
202/// Bitwise xor with the current value, returning the previous value.
203/// `T` must be an integer or pointer type.
204/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
205///
206/// The stabilized version of this intrinsic is available on the
207/// [`atomic`] types via the `fetch_xor` method. For example, [`AtomicBool::fetch_xor`].
208#[rustc_intrinsic]
209#[rustc_nounwind]
210pub unsafe fn atomic_xor<T: Copy, U: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: U) -> T;
211
212/// Maximum with the current value using a signed comparison.
213/// `T` must be a signed integer type.
214///
215/// The stabilized version of this intrinsic is available on the
216/// [`atomic`] signed integer types via the `fetch_max` method. For example, [`AtomicI32::fetch_max`].
217#[rustc_intrinsic]
218#[rustc_nounwind]
219pub unsafe fn atomic_max<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
220
221/// Minimum with the current value using a signed comparison.
222/// `T` must be a signed integer type.
223///
224/// The stabilized version of this intrinsic is available on the
225/// [`atomic`] signed integer types via the `fetch_min` method. For example, [`AtomicI32::fetch_min`].
226#[rustc_intrinsic]
227#[rustc_nounwind]
228pub unsafe fn atomic_min<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
229
230/// Minimum with the current value using an unsigned comparison.
231/// `T` must be an unsigned integer type.
232///
233/// The stabilized version of this intrinsic is available on the
234/// [`atomic`] unsigned integer types via the `fetch_min` method. For example, [`AtomicU32::fetch_min`].
235#[rustc_intrinsic]
236#[rustc_nounwind]
237pub unsafe fn atomic_umin<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
238
239/// Maximum with the current value using an unsigned comparison.
240/// `T` must be an unsigned integer type.
241///
242/// The stabilized version of this intrinsic is available on the
243/// [`atomic`] unsigned integer types via the `fetch_max` method. For example, [`AtomicU32::fetch_max`].
244#[rustc_intrinsic]
245#[rustc_nounwind]
246pub unsafe fn atomic_umax<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
247
248/// An atomic fence.
249///
250/// The stabilized version of this intrinsic is available in
251/// [`atomic::fence`].
252#[rustc_intrinsic]
253#[rustc_nounwind]
254pub unsafe fn atomic_fence<const ORD: AtomicOrdering>();
255
256/// An atomic fence for synchronization within a single thread.
257///
258/// The stabilized version of this intrinsic is available in
259/// [`atomic::compiler_fence`].
260#[rustc_intrinsic]
261#[rustc_nounwind]
262pub unsafe fn atomic_singlethreadfence<const ORD: AtomicOrdering>();
263
264/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
265/// for the given address if supported; otherwise, it is a no-op.
266/// Prefetches have no effect on the behavior of the program but can change its performance
267/// characteristics.
268///
269/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
270/// to (3) - extremely local keep in cache.
271///
272/// This intrinsic does not have a stable counterpart.
273#[rustc_intrinsic]
274#[rustc_nounwind]
275#[miri::intrinsic_fallback_is_spec]
276pub const fn prefetch_read_data<T, const LOCALITY: i32>(data: *const T) {
277    // This operation is a no-op, unless it is overridden by the backend.
278    let _ = data;
279}
280
281/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
282/// for the given address if supported; otherwise, it is a no-op.
283/// Prefetches have no effect on the behavior of the program but can change its performance
284/// characteristics.
285///
286/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
287/// to (3) - extremely local keep in cache.
288///
289/// This intrinsic does not have a stable counterpart.
290#[rustc_intrinsic]
291#[rustc_nounwind]
292#[miri::intrinsic_fallback_is_spec]
293pub const fn prefetch_write_data<T, const LOCALITY: i32>(data: *const T) {
294    // This operation is a no-op, unless it is overridden by the backend.
295    let _ = data;
296}
297
298/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
299/// for the given address if supported; otherwise, it is a no-op.
300/// Prefetches have no effect on the behavior of the program but can change its performance
301/// characteristics.
302///
303/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
304/// to (3) - extremely local keep in cache.
305///
306/// This intrinsic does not have a stable counterpart.
307#[rustc_intrinsic]
308#[rustc_nounwind]
309#[miri::intrinsic_fallback_is_spec]
310pub const fn prefetch_read_instruction<T, const LOCALITY: i32>(data: *const T) {
311    // This operation is a no-op, unless it is overridden by the backend.
312    let _ = data;
313}
314
315/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
316/// for the given address if supported; otherwise, it is a no-op.
317/// Prefetches have no effect on the behavior of the program but can change its performance
318/// characteristics.
319///
320/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
321/// to (3) - extremely local keep in cache.
322///
323/// This intrinsic does not have a stable counterpart.
324#[rustc_intrinsic]
325#[rustc_nounwind]
326#[miri::intrinsic_fallback_is_spec]
327pub const fn prefetch_write_instruction<T, const LOCALITY: i32>(data: *const T) {
328    // This operation is a no-op, unless it is overridden by the backend.
329    let _ = data;
330}
331
332/// Executes a breakpoint trap, for inspection by a debugger.
333///
334/// This intrinsic does not have a stable counterpart.
335#[rustc_intrinsic]
336#[rustc_nounwind]
337pub fn breakpoint();
338
339/// Magic intrinsic that derives its meaning from attributes
340/// attached to the function.
341///
342/// For example, dataflow uses this to inject static assertions so
343/// that `rustc_peek(potentially_uninitialized)` would actually
344/// double-check that dataflow did indeed compute that it is
345/// uninitialized at that point in the control flow.
346///
347/// This intrinsic should not be used outside of the compiler.
348#[rustc_nounwind]
349#[rustc_intrinsic]
350pub fn rustc_peek<T>(_: T) -> T;
351
352/// Aborts the execution of the process.
353///
354/// Note that, unlike most intrinsics, this is safe to call;
355/// it does not require an `unsafe` block.
356/// Therefore, implementations must not require the user to uphold
357/// any safety invariants.
358///
359/// [`std::process::abort`](../../std/process/fn.abort.html) is to be preferred if possible,
360/// as its behavior is more user-friendly and more stable.
361///
362/// The current implementation of `intrinsics::abort` is to invoke an invalid instruction,
363/// on most platforms.
364/// On Unix, the
365/// process will probably terminate with a signal like `SIGABRT`, `SIGILL`, `SIGTRAP`, `SIGSEGV` or
366/// `SIGBUS`.  The precise behavior is not guaranteed and not stable.
367#[rustc_nounwind]
368#[rustc_intrinsic]
369pub fn abort() -> !;
370
371/// Informs the optimizer that this point in the code is not reachable,
372/// enabling further optimizations.
373///
374/// N.B., this is very different from the `unreachable!()` macro: Unlike the
375/// macro, which panics when it is executed, it is *undefined behavior* to
376/// reach code marked with this function.
377///
378/// The stabilized version of this intrinsic is [`core::hint::unreachable_unchecked`].
379#[rustc_intrinsic_const_stable_indirect]
380#[rustc_nounwind]
381#[rustc_intrinsic]
382pub const unsafe fn unreachable() -> !;
383
384/// Informs the optimizer that a condition is always true.
385/// If the condition is false, the behavior is undefined.
386///
387/// No code is generated for this intrinsic, but the optimizer will try
388/// to preserve it (and its condition) between passes, which may interfere
389/// with optimization of surrounding code and reduce performance. It should
390/// not be used if the invariant can be discovered by the optimizer on its
391/// own, or if it does not enable any significant optimizations.
392///
393/// The stabilized version of this intrinsic is [`core::hint::assert_unchecked`].
394#[rustc_intrinsic_const_stable_indirect]
395#[rustc_nounwind]
396#[unstable(feature = "core_intrinsics", issue = "none")]
397#[rustc_intrinsic]
398pub const unsafe fn assume(b: bool) {
399    if !b {
400        // SAFETY: the caller must guarantee the argument is never `false`
401        unsafe { unreachable() }
402    }
403}
404
405/// Hints to the compiler that current code path is cold.
406///
407/// Note that, unlike most intrinsics, this is safe to call;
408/// it does not require an `unsafe` block.
409/// Therefore, implementations must not require the user to uphold
410/// any safety invariants.
411///
412/// This intrinsic does not have a stable counterpart.
413#[unstable(feature = "core_intrinsics", issue = "none")]
414#[rustc_intrinsic]
415#[rustc_nounwind]
416#[miri::intrinsic_fallback_is_spec]
417#[cold]
418pub const fn cold_path() {}
419
420/// Hints to the compiler that branch condition is likely to be true.
421/// Returns the value passed to it.
422///
423/// Any use other than with `if` statements will probably not have an effect.
424///
425/// Note that, unlike most intrinsics, this is safe to call;
426/// it does not require an `unsafe` block.
427/// Therefore, implementations must not require the user to uphold
428/// any safety invariants.
429///
430/// This intrinsic does not have a stable counterpart.
431#[unstable(feature = "core_intrinsics", issue = "none")]
432#[rustc_nounwind]
433#[inline(always)]
434pub const fn likely(b: bool) -> bool {
435    if b {
436        true
437    } else {
438        cold_path();
439        false
440    }
441}
442
443/// Hints to the compiler that branch condition is likely to be false.
444/// Returns the value passed to it.
445///
446/// Any use other than with `if` statements will probably not have an effect.
447///
448/// Note that, unlike most intrinsics, this is safe to call;
449/// it does not require an `unsafe` block.
450/// Therefore, implementations must not require the user to uphold
451/// any safety invariants.
452///
453/// This intrinsic does not have a stable counterpart.
454#[unstable(feature = "core_intrinsics", issue = "none")]
455#[rustc_nounwind]
456#[inline(always)]
457pub const fn unlikely(b: bool) -> bool {
458    if b {
459        cold_path();
460        true
461    } else {
462        false
463    }
464}
465
466/// Returns either `true_val` or `false_val` depending on condition `b` with a
467/// hint to the compiler that this condition is unlikely to be correctly
468/// predicted by a CPU's branch predictor (e.g. a binary search).
469///
470/// This is otherwise functionally equivalent to `if b { true_val } else { false_val }`.
471///
472/// Note that, unlike most intrinsics, this is safe to call;
473/// it does not require an `unsafe` block.
474/// Therefore, implementations must not require the user to uphold
475/// any safety invariants.
476///
477/// The public form of this intrinsic is [`core::hint::select_unpredictable`].
478/// However unlike the public form, the intrinsic will not drop the value that
479/// is not selected.
480#[unstable(feature = "core_intrinsics", issue = "none")]
481#[rustc_const_unstable(feature = "const_select_unpredictable", issue = "145938")]
482#[rustc_intrinsic]
483#[rustc_nounwind]
484#[miri::intrinsic_fallback_is_spec]
485#[inline]
486pub const fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
487    if b {
488        forget(false_val);
489        true_val
490    } else {
491        forget(true_val);
492        false_val
493    }
494}
495
496/// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited:
497/// This will statically either panic, or do nothing. It does not *guarantee* to ever panic,
498/// and should only be called if an assertion failure will imply language UB in the following code.
499///
500/// This intrinsic does not have a stable counterpart.
501#[rustc_intrinsic_const_stable_indirect]
502#[rustc_nounwind]
503#[rustc_intrinsic]
504pub const fn assert_inhabited<T>();
505
506/// A guard for unsafe functions that cannot ever be executed if `T` does not permit
507/// zero-initialization: This will statically either panic, or do nothing. It does not *guarantee*
508/// to ever panic, and should only be called if an assertion failure will imply language UB in the
509/// following code.
510///
511/// This intrinsic does not have a stable counterpart.
512#[rustc_intrinsic_const_stable_indirect]
513#[rustc_nounwind]
514#[rustc_intrinsic]
515pub const fn assert_zero_valid<T>();
516
517/// A guard for `std::mem::uninitialized`. This will statically either panic, or do nothing. It does
518/// not *guarantee* to ever panic, and should only be called if an assertion failure will imply
519/// language UB in the following code.
520///
521/// This intrinsic does not have a stable counterpart.
522#[rustc_intrinsic_const_stable_indirect]
523#[rustc_nounwind]
524#[rustc_intrinsic]
525pub const fn assert_mem_uninitialized_valid<T>();
526
527/// Gets a reference to a static `Location` indicating where it was called.
528///
529/// Note that, unlike most intrinsics, this is safe to call;
530/// it does not require an `unsafe` block.
531/// Therefore, implementations must not require the user to uphold
532/// any safety invariants.
533///
534/// Consider using [`core::panic::Location::caller`] instead.
535#[rustc_intrinsic_const_stable_indirect]
536#[rustc_nounwind]
537#[rustc_intrinsic]
538pub const fn caller_location() -> &'static crate::panic::Location<'static>;
539
540/// Moves a value out of scope without running drop glue.
541///
542/// This exists solely for [`crate::mem::forget_unsized`]; normal `forget` uses
543/// `ManuallyDrop` instead.
544///
545/// Note that, unlike most intrinsics, this is safe to call;
546/// it does not require an `unsafe` block.
547/// Therefore, implementations must not require the user to uphold
548/// any safety invariants.
549#[rustc_intrinsic_const_stable_indirect]
550#[rustc_nounwind]
551#[rustc_intrinsic]
552pub const fn forget<T: ?Sized>(_: T);
553
554/// Reinterprets the bits of a value of one type as another type.
555///
556/// Both types must have the same size. Compilation will fail if this is not guaranteed.
557///
558/// `transmute` is semantically equivalent to a bitwise move of one type
559/// into another. It copies the bits from the source value into the
560/// destination value, then forgets the original. Note that source and destination
561/// are passed by-value, which means if `Src` or `Dst` contain padding, that padding
562/// is *not* guaranteed to be preserved by `transmute`.
563///
564/// Both the argument and the result must be [valid](../../nomicon/what-unsafe-does.html) at
565/// their given type. Violating this condition leads to [undefined behavior][ub]. The compiler
566/// will generate code *assuming that you, the programmer, ensure that there will never be
567/// undefined behavior*. It is therefore your responsibility to guarantee that every value
568/// passed to `transmute` is valid at both types `Src` and `Dst`. Failing to uphold this condition
569/// may lead to unexpected and unstable compilation results. This makes `transmute` **incredibly
570/// unsafe**. `transmute` should be the absolute last resort.
571///
572/// Because `transmute` is a by-value operation, alignment of the *transmuted values
573/// themselves* is not a concern. As with any other function, the compiler already ensures
574/// both `Src` and `Dst` are properly aligned. However, when transmuting values that *point
575/// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper
576/// alignment of the pointed-to values.
577///
578/// The [nomicon](../../nomicon/transmutes.html) has additional documentation.
579///
580/// [ub]: ../../reference/behavior-considered-undefined.html
581///
582/// # Transmutation between pointers and integers
583///
584/// Special care has to be taken when transmuting between pointers and integers, e.g.
585/// transmuting between `*const ()` and `usize`.
586///
587/// Transmuting *pointers to integers* in a `const` context is [undefined behavior][ub], unless
588/// the pointer was originally created *from* an integer. (That includes this function
589/// specifically, integer-to-pointer casts, and helpers like [`dangling`][crate::ptr::dangling],
590/// but also semantically-equivalent conversions such as punning through `repr(C)` union
591/// fields.) Any attempt to use the resulting value for integer operations will abort
592/// const-evaluation. (And even outside `const`, such transmutation is touching on many
593/// unspecified aspects of the Rust memory model and should be avoided. See below for
594/// alternatives.)
595///
596/// Transmuting *integers to pointers* is a largely unspecified operation. It is likely *not*
597/// equivalent to an `as` cast. Doing non-zero-sized memory accesses with a pointer constructed
598/// this way is currently considered undefined behavior.
599///
600/// All this also applies when the integer is nested inside an array, tuple, struct, or enum.
601/// However, `MaybeUninit<usize>` is not considered an integer type for the purpose of this
602/// section. Transmuting `*const ()` to `MaybeUninit<usize>` is fine---but then calling
603/// `assume_init()` on that result is considered as completing the pointer-to-integer transmute
604/// and thus runs into the issues discussed above.
605///
606/// In particular, doing a pointer-to-integer-to-pointer roundtrip via `transmute` is *not* a
607/// lossless process. If you want to round-trip a pointer through an integer in a way that you
608/// can get back the original pointer, you need to use `as` casts, or replace the integer type
609/// by `MaybeUninit<$int>` (and never call `assume_init()`). If you are looking for a way to
610/// store data of arbitrary type, also use `MaybeUninit<T>` (that will also handle uninitialized
611/// memory due to padding). If you specifically need to store something that is "either an
612/// integer or a pointer", use `*mut ()`: integers can be converted to pointers and back without
613/// any loss (via `as` casts or via `transmute`).
614///
615/// # Examples
616///
617/// There are a few things that `transmute` is really useful for.
618///
619/// Turning a pointer into a function pointer. This is *not* portable to
620/// machines where function pointers and data pointers have different sizes.
621///
622/// ```
623/// fn foo() -> i32 {
624///     0
625/// }
626/// // Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
627/// // This avoids an integer-to-pointer `transmute`, which can be problematic.
628/// // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
629/// let pointer = foo as fn() -> i32 as *const ();
630/// let function = unsafe {
631///     std::mem::transmute::<*const (), fn() -> i32>(pointer)
632/// };
633/// assert_eq!(function(), 0);
634/// ```
635///
636/// Extending a lifetime, or shortening an invariant lifetime. This is
637/// advanced, very unsafe Rust!
638///
639/// ```
640/// struct R<'a>(&'a i32);
641/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
642///     unsafe { std::mem::transmute::<R<'b>, R<'static>>(r) }
643/// }
644///
645/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
646///                                              -> &'b mut R<'c> {
647///     unsafe { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) }
648/// }
649/// ```
650///
651/// # Alternatives
652///
653/// Don't despair: many uses of `transmute` can be achieved through other means.
654/// Below are common applications of `transmute` which can be replaced with safer
655/// constructs.
656///
657/// Turning raw bytes (`[u8; SZ]`) into `u32`, `f64`, etc.:
658///
659/// ```
660/// # #![allow(unnecessary_transmutes)]
661/// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
662///
663/// let num = unsafe {
664///     std::mem::transmute::<[u8; 4], u32>(raw_bytes)
665/// };
666///
667/// // use `u32::from_ne_bytes` instead
668/// let num = u32::from_ne_bytes(raw_bytes);
669/// // or use `u32::from_le_bytes` or `u32::from_be_bytes` to specify the endianness
670/// let num = u32::from_le_bytes(raw_bytes);
671/// assert_eq!(num, 0x12345678);
672/// let num = u32::from_be_bytes(raw_bytes);
673/// assert_eq!(num, 0x78563412);
674/// ```
675///
676/// Turning a pointer into a `usize`:
677///
678/// ```no_run
679/// let ptr = &0;
680/// let ptr_num_transmute = unsafe {
681///     std::mem::transmute::<&i32, usize>(ptr)
682/// };
683///
684/// // Use an `as` cast instead
685/// let ptr_num_cast = ptr as *const i32 as usize;
686/// ```
687///
688/// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined
689/// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave
690/// as expected -- this is touching on many unspecified aspects of the Rust memory model.
691/// Depending on what the code is doing, the following alternatives are preferable to
692/// pointer-to-integer transmutation:
693/// - If the code just wants to store data of arbitrary type in some buffer and needs to pick a
694///   type for that buffer, it can use [`MaybeUninit`][crate::mem::MaybeUninit].
695/// - If the code actually wants to work on the address the pointer points to, it can use `as`
696///   casts or [`ptr.addr()`][pointer::addr].
697///
698/// Turning a `*mut T` into a `&mut T`:
699///
700/// ```
701/// let ptr: *mut i32 = &mut 0;
702/// let ref_transmuted = unsafe {
703///     std::mem::transmute::<*mut i32, &mut i32>(ptr)
704/// };
705///
706/// // Use a reborrow instead
707/// let ref_casted = unsafe { &mut *ptr };
708/// ```
709///
710/// Turning a `&mut T` into a `&mut U`:
711///
712/// ```
713/// let ptr = &mut 0;
714/// let val_transmuted = unsafe {
715///     std::mem::transmute::<&mut i32, &mut u32>(ptr)
716/// };
717///
718/// // Now, put together `as` and reborrowing - note the chaining of `as`
719/// // `as` is not transitive
720/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
721/// ```
722///
723/// Turning a `&str` into a `&[u8]`:
724///
725/// ```
726/// // this is not a good way to do this.
727/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
728/// assert_eq!(slice, &[82, 117, 115, 116]);
729///
730/// // You could use `str::as_bytes`
731/// let slice = "Rust".as_bytes();
732/// assert_eq!(slice, &[82, 117, 115, 116]);
733///
734/// // Or, just use a byte string, if you have control over the string
735/// // literal
736/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
737/// ```
738///
739/// Turning a `Vec<&T>` into a `Vec<Option<&T>>`.
740///
741/// To transmute the inner type of the contents of a container, you must make sure to not
742/// violate any of the container's invariants. For `Vec`, this means that both the size
743/// *and alignment* of the inner types have to match. Other containers might rely on the
744/// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't
745/// be possible at all without violating the container invariants.
746///
747/// ```
748/// let store = [0, 1, 2, 3];
749/// let v_orig = store.iter().collect::<Vec<&i32>>();
750///
751/// // clone the vector as we will reuse them later
752/// let v_clone = v_orig.clone();
753///
754/// // Using transmute: this relies on the unspecified data layout of `Vec`, which is a
755/// // bad idea and could cause Undefined Behavior.
756/// // However, it is no-copy.
757/// let v_transmuted = unsafe {
758///     std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(v_clone)
759/// };
760///
761/// let v_clone = v_orig.clone();
762///
763/// // This is the suggested, safe way.
764/// // It may copy the entire vector into a new one though, but also may not.
765/// let v_collected = v_clone.into_iter()
766///                          .map(Some)
767///                          .collect::<Vec<Option<&i32>>>();
768///
769/// let v_clone = v_orig.clone();
770///
771/// // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the
772/// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but
773/// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`),
774/// // this has all the same caveats. Besides the information provided above, also consult the
775/// // [`from_raw_parts`] documentation.
776/// let (ptr, len, capacity) = v_clone.into_raw_parts();
777/// let v_from_raw = unsafe {
778///     Vec::from_raw_parts(ptr.cast::<*mut Option<&i32>>(), len, 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_const_stable_indirect]
1318#[rustc_intrinsic]
1319#[rustc_nounwind]
1320pub const fn fmaf16(a: f16, b: f16, c: f16) -> f16;
1321/// Returns `a * b + c` for `f32` values.
1322///
1323/// The stabilized version of this intrinsic is
1324/// [`f32::mul_add`](../../std/primitive.f32.html#method.mul_add)
1325#[rustc_intrinsic_const_stable_indirect]
1326#[rustc_intrinsic]
1327#[rustc_nounwind]
1328pub const fn fmaf32(a: f32, b: f32, c: f32) -> f32;
1329/// Returns `a * b + c` for `f64` values.
1330///
1331/// The stabilized version of this intrinsic is
1332/// [`f64::mul_add`](../../std/primitive.f64.html#method.mul_add)
1333#[rustc_intrinsic_const_stable_indirect]
1334#[rustc_intrinsic]
1335#[rustc_nounwind]
1336pub const fn fmaf64(a: f64, b: f64, c: f64) -> f64;
1337/// Returns `a * b + c` for `f128` values.
1338///
1339/// The stabilized version of this intrinsic is
1340/// [`f128::mul_add`](../../std/primitive.f128.html#method.mul_add)
1341#[rustc_intrinsic_const_stable_indirect]
1342#[rustc_intrinsic]
1343#[rustc_nounwind]
1344pub const fn fmaf128(a: f128, b: f128, c: f128) -> f128;
1345
1346/// Returns `a * b + c` for `f16` values, non-deterministically executing
1347/// either a fused multiply-add or two operations with rounding of the
1348/// intermediate result.
1349///
1350/// The operation is fused if the code generator determines that target
1351/// instruction set has support for a fused operation, and that the fused
1352/// operation is more efficient than the equivalent, separate pair of mul
1353/// and add instructions. It is unspecified whether or not a fused operation
1354/// is selected, and that may depend on optimization level and context, for
1355/// example.
1356#[rustc_intrinsic]
1357#[rustc_nounwind]
1358pub const fn fmuladdf16(a: f16, b: f16, c: f16) -> f16;
1359/// Returns `a * b + c` for `f32` values, non-deterministically executing
1360/// either a fused multiply-add or two operations with rounding of the
1361/// intermediate result.
1362///
1363/// The operation is fused if the code generator determines that target
1364/// instruction set has support for a fused operation, and that the fused
1365/// operation is more efficient than the equivalent, separate pair of mul
1366/// and add instructions. It is unspecified whether or not a fused operation
1367/// is selected, and that may depend on optimization level and context, for
1368/// example.
1369#[rustc_intrinsic]
1370#[rustc_nounwind]
1371pub const fn fmuladdf32(a: f32, b: f32, c: f32) -> f32;
1372/// Returns `a * b + c` for `f64` values, non-deterministically executing
1373/// either a fused multiply-add or two operations with rounding of the
1374/// intermediate result.
1375///
1376/// The operation is fused if the code generator determines that target
1377/// instruction set has support for a fused operation, and that the fused
1378/// operation is more efficient than the equivalent, separate pair of mul
1379/// and add instructions. It is unspecified whether or not a fused operation
1380/// is selected, and that may depend on optimization level and context, for
1381/// example.
1382#[rustc_intrinsic]
1383#[rustc_nounwind]
1384pub const fn fmuladdf64(a: f64, b: f64, c: f64) -> f64;
1385/// Returns `a * b + c` for `f128` values, non-deterministically executing
1386/// either a fused multiply-add or two operations with rounding of the
1387/// intermediate result.
1388///
1389/// The operation is fused if the code generator determines that target
1390/// instruction set has support for a fused operation, and that the fused
1391/// operation is more efficient than the equivalent, separate pair of mul
1392/// and add instructions. It is unspecified whether or not a fused operation
1393/// is selected, and that may depend on optimization level and context, for
1394/// example.
1395#[rustc_intrinsic]
1396#[rustc_nounwind]
1397pub const fn fmuladdf128(a: f128, b: f128, c: f128) -> f128;
1398
1399/// Returns the largest integer less than or equal to an `f16`.
1400///
1401/// The stabilized version of this intrinsic is
1402/// [`f16::floor`](../../std/primitive.f16.html#method.floor)
1403#[rustc_intrinsic_const_stable_indirect]
1404#[rustc_intrinsic]
1405#[rustc_nounwind]
1406pub const fn floorf16(x: f16) -> f16;
1407/// Returns the largest integer less than or equal to an `f32`.
1408///
1409/// The stabilized version of this intrinsic is
1410/// [`f32::floor`](../../std/primitive.f32.html#method.floor)
1411#[rustc_intrinsic_const_stable_indirect]
1412#[rustc_intrinsic]
1413#[rustc_nounwind]
1414pub const fn floorf32(x: f32) -> f32;
1415/// Returns the largest integer less than or equal to an `f64`.
1416///
1417/// The stabilized version of this intrinsic is
1418/// [`f64::floor`](../../std/primitive.f64.html#method.floor)
1419#[rustc_intrinsic_const_stable_indirect]
1420#[rustc_intrinsic]
1421#[rustc_nounwind]
1422pub const fn floorf64(x: f64) -> f64;
1423/// Returns the largest integer less than or equal to an `f128`.
1424///
1425/// The stabilized version of this intrinsic is
1426/// [`f128::floor`](../../std/primitive.f128.html#method.floor)
1427#[rustc_intrinsic_const_stable_indirect]
1428#[rustc_intrinsic]
1429#[rustc_nounwind]
1430pub const fn floorf128(x: f128) -> f128;
1431
1432/// Returns the smallest integer greater than or equal to an `f16`.
1433///
1434/// The stabilized version of this intrinsic is
1435/// [`f16::ceil`](../../std/primitive.f16.html#method.ceil)
1436#[rustc_intrinsic_const_stable_indirect]
1437#[rustc_intrinsic]
1438#[rustc_nounwind]
1439pub const fn ceilf16(x: f16) -> f16;
1440/// Returns the smallest integer greater than or equal to an `f32`.
1441///
1442/// The stabilized version of this intrinsic is
1443/// [`f32::ceil`](../../std/primitive.f32.html#method.ceil)
1444#[rustc_intrinsic_const_stable_indirect]
1445#[rustc_intrinsic]
1446#[rustc_nounwind]
1447pub const fn ceilf32(x: f32) -> f32;
1448/// Returns the smallest integer greater than or equal to an `f64`.
1449///
1450/// The stabilized version of this intrinsic is
1451/// [`f64::ceil`](../../std/primitive.f64.html#method.ceil)
1452#[rustc_intrinsic_const_stable_indirect]
1453#[rustc_intrinsic]
1454#[rustc_nounwind]
1455pub const fn ceilf64(x: f64) -> f64;
1456/// Returns the smallest integer greater than or equal to an `f128`.
1457///
1458/// The stabilized version of this intrinsic is
1459/// [`f128::ceil`](../../std/primitive.f128.html#method.ceil)
1460#[rustc_intrinsic_const_stable_indirect]
1461#[rustc_intrinsic]
1462#[rustc_nounwind]
1463pub const fn ceilf128(x: f128) -> f128;
1464
1465/// Returns the integer part of an `f16`.
1466///
1467/// The stabilized version of this intrinsic is
1468/// [`f16::trunc`](../../std/primitive.f16.html#method.trunc)
1469#[rustc_intrinsic_const_stable_indirect]
1470#[rustc_intrinsic]
1471#[rustc_nounwind]
1472pub const fn truncf16(x: f16) -> f16;
1473/// Returns the integer part of an `f32`.
1474///
1475/// The stabilized version of this intrinsic is
1476/// [`f32::trunc`](../../std/primitive.f32.html#method.trunc)
1477#[rustc_intrinsic_const_stable_indirect]
1478#[rustc_intrinsic]
1479#[rustc_nounwind]
1480pub const fn truncf32(x: f32) -> f32;
1481/// Returns the integer part of an `f64`.
1482///
1483/// The stabilized version of this intrinsic is
1484/// [`f64::trunc`](../../std/primitive.f64.html#method.trunc)
1485#[rustc_intrinsic_const_stable_indirect]
1486#[rustc_intrinsic]
1487#[rustc_nounwind]
1488pub const fn truncf64(x: f64) -> f64;
1489/// Returns the integer part of an `f128`.
1490///
1491/// The stabilized version of this intrinsic is
1492/// [`f128::trunc`](../../std/primitive.f128.html#method.trunc)
1493#[rustc_intrinsic_const_stable_indirect]
1494#[rustc_intrinsic]
1495#[rustc_nounwind]
1496pub const fn truncf128(x: f128) -> f128;
1497
1498/// Returns the nearest integer to an `f16`. Rounds half-way cases to the number with an even
1499/// least significant digit.
1500///
1501/// The stabilized version of this intrinsic is
1502/// [`f16::round_ties_even`](../../std/primitive.f16.html#method.round_ties_even)
1503#[rustc_intrinsic_const_stable_indirect]
1504#[rustc_intrinsic]
1505#[rustc_nounwind]
1506pub const fn round_ties_even_f16(x: f16) -> f16;
1507
1508/// Returns the nearest integer to an `f32`. Rounds half-way cases to the number with an even
1509/// least significant digit.
1510///
1511/// The stabilized version of this intrinsic is
1512/// [`f32::round_ties_even`](../../std/primitive.f32.html#method.round_ties_even)
1513#[rustc_intrinsic_const_stable_indirect]
1514#[rustc_intrinsic]
1515#[rustc_nounwind]
1516pub const fn round_ties_even_f32(x: f32) -> f32;
1517
1518/// Returns the nearest integer to an `f64`. Rounds half-way cases to the number with an even
1519/// least significant digit.
1520///
1521/// The stabilized version of this intrinsic is
1522/// [`f64::round_ties_even`](../../std/primitive.f64.html#method.round_ties_even)
1523#[rustc_intrinsic_const_stable_indirect]
1524#[rustc_intrinsic]
1525#[rustc_nounwind]
1526pub const fn round_ties_even_f64(x: f64) -> f64;
1527
1528/// Returns the nearest integer to an `f128`. Rounds half-way cases to the number with an even
1529/// least significant digit.
1530///
1531/// The stabilized version of this intrinsic is
1532/// [`f128::round_ties_even`](../../std/primitive.f128.html#method.round_ties_even)
1533#[rustc_intrinsic_const_stable_indirect]
1534#[rustc_intrinsic]
1535#[rustc_nounwind]
1536pub const fn round_ties_even_f128(x: f128) -> f128;
1537
1538/// Returns the nearest integer to an `f16`. Rounds half-way cases away from zero.
1539///
1540/// The stabilized version of this intrinsic is
1541/// [`f16::round`](../../std/primitive.f16.html#method.round)
1542#[rustc_intrinsic_const_stable_indirect]
1543#[rustc_intrinsic]
1544#[rustc_nounwind]
1545pub const fn roundf16(x: f16) -> f16;
1546/// Returns the nearest integer to an `f32`. Rounds half-way cases away from zero.
1547///
1548/// The stabilized version of this intrinsic is
1549/// [`f32::round`](../../std/primitive.f32.html#method.round)
1550#[rustc_intrinsic_const_stable_indirect]
1551#[rustc_intrinsic]
1552#[rustc_nounwind]
1553pub const fn roundf32(x: f32) -> f32;
1554/// Returns the nearest integer to an `f64`. Rounds half-way cases away from zero.
1555///
1556/// The stabilized version of this intrinsic is
1557/// [`f64::round`](../../std/primitive.f64.html#method.round)
1558#[rustc_intrinsic_const_stable_indirect]
1559#[rustc_intrinsic]
1560#[rustc_nounwind]
1561pub const fn roundf64(x: f64) -> f64;
1562/// Returns the nearest integer to an `f128`. Rounds half-way cases away from zero.
1563///
1564/// The stabilized version of this intrinsic is
1565/// [`f128::round`](../../std/primitive.f128.html#method.round)
1566#[rustc_intrinsic_const_stable_indirect]
1567#[rustc_intrinsic]
1568#[rustc_nounwind]
1569pub const fn roundf128(x: f128) -> f128;
1570
1571/// Float addition that allows optimizations based on algebraic rules.
1572/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1573///
1574/// This intrinsic does not have a stable counterpart.
1575#[rustc_intrinsic]
1576#[rustc_nounwind]
1577pub unsafe fn fadd_fast<T: Copy>(a: T, b: T) -> T;
1578
1579/// Float subtraction that allows optimizations based on algebraic rules.
1580/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1581///
1582/// This intrinsic does not have a stable counterpart.
1583#[rustc_intrinsic]
1584#[rustc_nounwind]
1585pub unsafe fn fsub_fast<T: Copy>(a: T, b: T) -> T;
1586
1587/// Float multiplication that allows optimizations based on algebraic rules.
1588/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1589///
1590/// This intrinsic does not have a stable counterpart.
1591#[rustc_intrinsic]
1592#[rustc_nounwind]
1593pub unsafe fn fmul_fast<T: Copy>(a: T, b: T) -> T;
1594
1595/// Float division that allows optimizations based on algebraic rules.
1596/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1597///
1598/// This intrinsic does not have a stable counterpart.
1599#[rustc_intrinsic]
1600#[rustc_nounwind]
1601pub unsafe fn fdiv_fast<T: Copy>(a: T, b: T) -> T;
1602
1603/// Float remainder that allows optimizations based on algebraic rules.
1604/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1605///
1606/// This intrinsic does not have a stable counterpart.
1607#[rustc_intrinsic]
1608#[rustc_nounwind]
1609pub unsafe fn frem_fast<T: Copy>(a: T, b: T) -> T;
1610
1611/// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range
1612/// (<https://github.com/rust-lang/rust/issues/10184>)
1613///
1614/// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`].
1615#[rustc_intrinsic]
1616#[rustc_nounwind]
1617pub unsafe fn float_to_int_unchecked<Float: Copy, Int: Copy>(value: Float) -> Int;
1618
1619/// Float addition that allows optimizations based on algebraic rules.
1620///
1621/// Stabilized as [`f16::algebraic_add`], [`f32::algebraic_add`], [`f64::algebraic_add`] and [`f128::algebraic_add`].
1622#[rustc_nounwind]
1623#[rustc_intrinsic]
1624pub const fn fadd_algebraic<T: Copy>(a: T, b: T) -> T;
1625
1626/// Float subtraction that allows optimizations based on algebraic rules.
1627///
1628/// Stabilized as [`f16::algebraic_sub`], [`f32::algebraic_sub`], [`f64::algebraic_sub`] and [`f128::algebraic_sub`].
1629#[rustc_nounwind]
1630#[rustc_intrinsic]
1631pub const fn fsub_algebraic<T: Copy>(a: T, b: T) -> T;
1632
1633/// Float multiplication that allows optimizations based on algebraic rules.
1634///
1635/// Stabilized as [`f16::algebraic_mul`], [`f32::algebraic_mul`], [`f64::algebraic_mul`] and [`f128::algebraic_mul`].
1636#[rustc_nounwind]
1637#[rustc_intrinsic]
1638pub const fn fmul_algebraic<T: Copy>(a: T, b: T) -> T;
1639
1640/// Float division that allows optimizations based on algebraic rules.
1641///
1642/// Stabilized as [`f16::algebraic_div`], [`f32::algebraic_div`], [`f64::algebraic_div`] and [`f128::algebraic_div`].
1643#[rustc_nounwind]
1644#[rustc_intrinsic]
1645pub const fn fdiv_algebraic<T: Copy>(a: T, b: T) -> T;
1646
1647/// Float remainder that allows optimizations based on algebraic rules.
1648///
1649/// Stabilized as [`f16::algebraic_rem`], [`f32::algebraic_rem`], [`f64::algebraic_rem`] and [`f128::algebraic_rem`].
1650#[rustc_nounwind]
1651#[rustc_intrinsic]
1652pub const fn frem_algebraic<T: Copy>(a: T, b: T) -> T;
1653
1654/// Returns the number of bits set in an integer type `T`
1655///
1656/// Note that, unlike most intrinsics, this is safe to call;
1657/// it does not require an `unsafe` block.
1658/// Therefore, implementations must not require the user to uphold
1659/// any safety invariants.
1660///
1661/// The stabilized versions of this intrinsic are available on the integer
1662/// primitives via the `count_ones` method. For example,
1663/// [`u32::count_ones`]
1664#[rustc_intrinsic_const_stable_indirect]
1665#[rustc_nounwind]
1666#[rustc_intrinsic]
1667pub const fn ctpop<T: Copy>(x: T) -> u32;
1668
1669/// Returns the number of leading unset bits (zeroes) in an integer type `T`.
1670///
1671/// Note that, unlike most intrinsics, this is safe to call;
1672/// it does not require an `unsafe` block.
1673/// Therefore, implementations must not require the user to uphold
1674/// any safety invariants.
1675///
1676/// The stabilized versions of this intrinsic are available on the integer
1677/// primitives via the `leading_zeros` method. For example,
1678/// [`u32::leading_zeros`]
1679///
1680/// # Examples
1681///
1682/// ```
1683/// #![feature(core_intrinsics)]
1684/// # #![allow(internal_features)]
1685///
1686/// use std::intrinsics::ctlz;
1687///
1688/// let x = 0b0001_1100_u8;
1689/// let num_leading = ctlz(x);
1690/// assert_eq!(num_leading, 3);
1691/// ```
1692///
1693/// An `x` with value `0` will return the bit width of `T`.
1694///
1695/// ```
1696/// #![feature(core_intrinsics)]
1697/// # #![allow(internal_features)]
1698///
1699/// use std::intrinsics::ctlz;
1700///
1701/// let x = 0u16;
1702/// let num_leading = ctlz(x);
1703/// assert_eq!(num_leading, 16);
1704/// ```
1705#[rustc_intrinsic_const_stable_indirect]
1706#[rustc_nounwind]
1707#[rustc_intrinsic]
1708pub const fn ctlz<T: Copy>(x: T) -> u32;
1709
1710/// Like `ctlz`, but extra-unsafe as it returns `undef` when
1711/// given an `x` with value `0`.
1712///
1713/// This intrinsic does not have a stable counterpart.
1714///
1715/// # Examples
1716///
1717/// ```
1718/// #![feature(core_intrinsics)]
1719/// # #![allow(internal_features)]
1720///
1721/// use std::intrinsics::ctlz_nonzero;
1722///
1723/// let x = 0b0001_1100_u8;
1724/// let num_leading = unsafe { ctlz_nonzero(x) };
1725/// assert_eq!(num_leading, 3);
1726/// ```
1727#[rustc_intrinsic_const_stable_indirect]
1728#[rustc_nounwind]
1729#[rustc_intrinsic]
1730pub const unsafe fn ctlz_nonzero<T: Copy>(x: T) -> u32;
1731
1732/// Returns the number of trailing unset bits (zeroes) in an integer type `T`.
1733///
1734/// Note that, unlike most intrinsics, this is safe to call;
1735/// it does not require an `unsafe` block.
1736/// Therefore, implementations must not require the user to uphold
1737/// any safety invariants.
1738///
1739/// The stabilized versions of this intrinsic are available on the integer
1740/// primitives via the `trailing_zeros` method. For example,
1741/// [`u32::trailing_zeros`]
1742///
1743/// # Examples
1744///
1745/// ```
1746/// #![feature(core_intrinsics)]
1747/// # #![allow(internal_features)]
1748///
1749/// use std::intrinsics::cttz;
1750///
1751/// let x = 0b0011_1000_u8;
1752/// let num_trailing = cttz(x);
1753/// assert_eq!(num_trailing, 3);
1754/// ```
1755///
1756/// An `x` with value `0` will return the bit width of `T`:
1757///
1758/// ```
1759/// #![feature(core_intrinsics)]
1760/// # #![allow(internal_features)]
1761///
1762/// use std::intrinsics::cttz;
1763///
1764/// let x = 0u16;
1765/// let num_trailing = cttz(x);
1766/// assert_eq!(num_trailing, 16);
1767/// ```
1768#[rustc_intrinsic_const_stable_indirect]
1769#[rustc_nounwind]
1770#[rustc_intrinsic]
1771pub const fn cttz<T: Copy>(x: T) -> u32;
1772
1773/// Like `cttz`, but extra-unsafe as it returns `undef` when
1774/// given an `x` with value `0`.
1775///
1776/// This intrinsic does not have a stable counterpart.
1777///
1778/// # Examples
1779///
1780/// ```
1781/// #![feature(core_intrinsics)]
1782/// # #![allow(internal_features)]
1783///
1784/// use std::intrinsics::cttz_nonzero;
1785///
1786/// let x = 0b0011_1000_u8;
1787/// let num_trailing = unsafe { cttz_nonzero(x) };
1788/// assert_eq!(num_trailing, 3);
1789/// ```
1790#[rustc_intrinsic_const_stable_indirect]
1791#[rustc_nounwind]
1792#[rustc_intrinsic]
1793pub const unsafe fn cttz_nonzero<T: Copy>(x: T) -> u32;
1794
1795/// Reverses the bytes in an integer type `T`.
1796///
1797/// Note that, unlike most intrinsics, this is safe to call;
1798/// it does not require an `unsafe` block.
1799/// Therefore, implementations must not require the user to uphold
1800/// any safety invariants.
1801///
1802/// The stabilized versions of this intrinsic are available on the integer
1803/// primitives via the `swap_bytes` method. For example,
1804/// [`u32::swap_bytes`]
1805#[rustc_intrinsic_const_stable_indirect]
1806#[rustc_nounwind]
1807#[rustc_intrinsic]
1808pub const fn bswap<T: Copy>(x: T) -> T;
1809
1810/// Reverses the bits in an integer type `T`.
1811///
1812/// Note that, unlike most intrinsics, this is safe to call;
1813/// it does not require an `unsafe` block.
1814/// Therefore, implementations must not require the user to uphold
1815/// any safety invariants.
1816///
1817/// The stabilized versions of this intrinsic are available on the integer
1818/// primitives via the `reverse_bits` method. For example,
1819/// [`u32::reverse_bits`]
1820#[rustc_intrinsic_const_stable_indirect]
1821#[rustc_nounwind]
1822#[rustc_intrinsic]
1823pub const fn bitreverse<T: Copy>(x: T) -> T;
1824
1825/// Does a three-way comparison between the two arguments,
1826/// which must be of character or integer (signed or unsigned) type.
1827///
1828/// This was originally added because it greatly simplified the MIR in `cmp`
1829/// implementations, and then LLVM 20 added a backend intrinsic for it too.
1830///
1831/// The stabilized version of this intrinsic is [`Ord::cmp`].
1832#[rustc_intrinsic_const_stable_indirect]
1833#[rustc_nounwind]
1834#[rustc_intrinsic]
1835pub const fn three_way_compare<T: Copy>(lhs: T, rhss: T) -> crate::cmp::Ordering;
1836
1837/// Combine two values which have no bits in common.
1838///
1839/// This allows the backend to implement it as `a + b` *or* `a | b`,
1840/// depending which is easier to implement on a specific target.
1841///
1842/// # Safety
1843///
1844/// Requires that `(a & b) == 0`, or equivalently that `(a | b) == (a + b)`.
1845///
1846/// Otherwise it's immediate UB.
1847#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1848#[rustc_nounwind]
1849#[rustc_intrinsic]
1850#[track_caller]
1851#[miri::intrinsic_fallback_is_spec] // the fallbacks all `assume` to tell Miri
1852pub const unsafe fn disjoint_bitor<T: [const] fallback::DisjointBitOr>(a: T, b: T) -> T {
1853    // SAFETY: same preconditions as this function.
1854    unsafe { fallback::DisjointBitOr::disjoint_bitor(a, b) }
1855}
1856
1857/// Performs checked integer addition.
1858///
1859/// Note that, unlike most intrinsics, this is safe to call;
1860/// it does not require an `unsafe` block.
1861/// Therefore, implementations must not require the user to uphold
1862/// any safety invariants.
1863///
1864/// The stabilized versions of this intrinsic are available on the integer
1865/// primitives via the `overflowing_add` method. For example,
1866/// [`u32::overflowing_add`]
1867#[rustc_intrinsic_const_stable_indirect]
1868#[rustc_nounwind]
1869#[rustc_intrinsic]
1870pub const fn add_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1871
1872/// Performs checked integer subtraction
1873///
1874/// Note that, unlike most intrinsics, this is safe to call;
1875/// it does not require an `unsafe` block.
1876/// Therefore, implementations must not require the user to uphold
1877/// any safety invariants.
1878///
1879/// The stabilized versions of this intrinsic are available on the integer
1880/// primitives via the `overflowing_sub` method. For example,
1881/// [`u32::overflowing_sub`]
1882#[rustc_intrinsic_const_stable_indirect]
1883#[rustc_nounwind]
1884#[rustc_intrinsic]
1885pub const fn sub_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1886
1887/// Performs checked integer multiplication
1888///
1889/// Note that, unlike most intrinsics, this is safe to call;
1890/// it does not require an `unsafe` block.
1891/// Therefore, implementations must not require the user to uphold
1892/// any safety invariants.
1893///
1894/// The stabilized versions of this intrinsic are available on the integer
1895/// primitives via the `overflowing_mul` method. For example,
1896/// [`u32::overflowing_mul`]
1897#[rustc_intrinsic_const_stable_indirect]
1898#[rustc_nounwind]
1899#[rustc_intrinsic]
1900pub const fn mul_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1901
1902/// Performs full-width multiplication and addition with a carry:
1903/// `multiplier * multiplicand + addend + carry`.
1904///
1905/// This is possible without any overflow.  For `uN`:
1906///    MAX * MAX + MAX + MAX
1907/// => (2ⁿ-1) × (2ⁿ-1) + (2ⁿ-1) + (2ⁿ-1)
1908/// => (2²ⁿ - 2ⁿ⁺¹ + 1) + (2ⁿ⁺¹ - 2)
1909/// => 2²ⁿ - 1
1910///
1911/// For `iN`, the upper bound is MIN * MIN + MAX + MAX => 2²ⁿ⁻² + 2ⁿ - 2,
1912/// and the lower bound is MAX * MIN + MIN + MIN => -2²ⁿ⁻² - 2ⁿ + 2ⁿ⁺¹.
1913///
1914/// This currently supports unsigned integers *only*, no signed ones.
1915/// The stabilized versions of this intrinsic are available on integers.
1916#[unstable(feature = "core_intrinsics", issue = "none")]
1917#[rustc_const_unstable(feature = "const_carrying_mul_add", issue = "85532")]
1918#[rustc_nounwind]
1919#[rustc_intrinsic]
1920#[miri::intrinsic_fallback_is_spec]
1921pub const fn carrying_mul_add<T: [const] fallback::CarryingMulAdd<Unsigned = U>, U>(
1922    multiplier: T,
1923    multiplicand: T,
1924    addend: T,
1925    carry: T,
1926) -> (U, T) {
1927    multiplier.carrying_mul_add(multiplicand, addend, carry)
1928}
1929
1930/// Performs an exact division, resulting in undefined behavior where
1931/// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`
1932///
1933/// This intrinsic does not have a stable counterpart.
1934#[rustc_intrinsic_const_stable_indirect]
1935#[rustc_nounwind]
1936#[rustc_intrinsic]
1937pub const unsafe fn exact_div<T: Copy>(x: T, y: T) -> T;
1938
1939/// Performs an unchecked division, resulting in undefined behavior
1940/// where `y == 0` or `x == T::MIN && y == -1`
1941///
1942/// Safe wrappers for this intrinsic are available on the integer
1943/// primitives via the `checked_div` method. For example,
1944/// [`u32::checked_div`]
1945#[rustc_intrinsic_const_stable_indirect]
1946#[rustc_nounwind]
1947#[rustc_intrinsic]
1948pub const unsafe fn unchecked_div<T: Copy>(x: T, y: T) -> T;
1949/// Returns the remainder of an unchecked division, resulting in
1950/// undefined behavior when `y == 0` or `x == T::MIN && y == -1`
1951///
1952/// Safe wrappers for this intrinsic are available on the integer
1953/// primitives via the `checked_rem` method. For example,
1954/// [`u32::checked_rem`]
1955#[rustc_intrinsic_const_stable_indirect]
1956#[rustc_nounwind]
1957#[rustc_intrinsic]
1958pub const unsafe fn unchecked_rem<T: Copy>(x: T, y: T) -> T;
1959
1960/// Performs an unchecked left shift, resulting in undefined behavior when
1961/// `y < 0` or `y >= N`, where N is the width of T in bits.
1962///
1963/// Safe wrappers for this intrinsic are available on the integer
1964/// primitives via the `checked_shl` method. For example,
1965/// [`u32::checked_shl`]
1966#[rustc_intrinsic_const_stable_indirect]
1967#[rustc_nounwind]
1968#[rustc_intrinsic]
1969pub const unsafe fn unchecked_shl<T: Copy, U: Copy>(x: T, y: U) -> T;
1970/// Performs an unchecked right shift, resulting in undefined behavior when
1971/// `y < 0` or `y >= N`, where N is the width of T in bits.
1972///
1973/// Safe wrappers for this intrinsic are available on the integer
1974/// primitives via the `checked_shr` method. For example,
1975/// [`u32::checked_shr`]
1976#[rustc_intrinsic_const_stable_indirect]
1977#[rustc_nounwind]
1978#[rustc_intrinsic]
1979pub const unsafe fn unchecked_shr<T: Copy, U: Copy>(x: T, y: U) -> T;
1980
1981/// Returns the result of an unchecked addition, resulting in
1982/// undefined behavior when `x + y > T::MAX` or `x + y < T::MIN`.
1983///
1984/// The stable counterpart of this intrinsic is `unchecked_add` on the various
1985/// integer types, such as [`u16::unchecked_add`] and [`i64::unchecked_add`].
1986#[rustc_intrinsic_const_stable_indirect]
1987#[rustc_nounwind]
1988#[rustc_intrinsic]
1989pub const unsafe fn unchecked_add<T: Copy>(x: T, y: T) -> T;
1990
1991/// Returns the result of an unchecked subtraction, resulting in
1992/// undefined behavior when `x - y > T::MAX` or `x - y < T::MIN`.
1993///
1994/// The stable counterpart of this intrinsic is `unchecked_sub` on the various
1995/// integer types, such as [`u16::unchecked_sub`] and [`i64::unchecked_sub`].
1996#[rustc_intrinsic_const_stable_indirect]
1997#[rustc_nounwind]
1998#[rustc_intrinsic]
1999pub const unsafe fn unchecked_sub<T: Copy>(x: T, y: T) -> T;
2000
2001/// Returns the result of an unchecked multiplication, resulting in
2002/// undefined behavior when `x * y > T::MAX` or `x * y < T::MIN`.
2003///
2004/// The stable counterpart of this intrinsic is `unchecked_mul` on the various
2005/// integer types, such as [`u16::unchecked_mul`] and [`i64::unchecked_mul`].
2006#[rustc_intrinsic_const_stable_indirect]
2007#[rustc_nounwind]
2008#[rustc_intrinsic]
2009pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
2010
2011/// Performs rotate left.
2012///
2013/// Note that, unlike most intrinsics, this is safe to call;
2014/// it does not require an `unsafe` block.
2015/// Therefore, implementations must not require the user to uphold
2016/// any safety invariants.
2017///
2018/// The stabilized versions of this intrinsic are available on the integer
2019/// primitives via the `rotate_left` method. For example,
2020/// [`u32::rotate_left`]
2021#[rustc_intrinsic_const_stable_indirect]
2022#[rustc_nounwind]
2023#[rustc_intrinsic]
2024#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2025#[miri::intrinsic_fallback_is_spec]
2026pub const fn rotate_left<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
2027    // Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2028    // SAFETY: we modulo `shift` so that the result is definitely less than the size of
2029    // `T` in bits.
2030    unsafe { unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>() as u32 * 8)) }
2031}
2032
2033/// Performs rotate right.
2034///
2035/// Note that, unlike most intrinsics, this is safe to call;
2036/// it does not require an `unsafe` block.
2037/// Therefore, implementations must not require the user to uphold
2038/// any safety invariants.
2039///
2040/// The stabilized versions of this intrinsic are available on the integer
2041/// primitives via the `rotate_right` method. For example,
2042/// [`u32::rotate_right`]
2043#[rustc_intrinsic_const_stable_indirect]
2044#[rustc_nounwind]
2045#[rustc_intrinsic]
2046#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2047#[miri::intrinsic_fallback_is_spec]
2048pub const fn rotate_right<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
2049    // Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2050    // SAFETY: we modulo `shift` so that the result is definitely less than the size of
2051    // `T` in bits.
2052    unsafe { unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>() as u32 * 8)) }
2053}
2054
2055/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
2056///
2057/// Note that, unlike most intrinsics, this is safe to call;
2058/// it does not require an `unsafe` block.
2059/// Therefore, implementations must not require the user to uphold
2060/// any safety invariants.
2061///
2062/// The stabilized versions of this intrinsic are available on the integer
2063/// primitives via the `wrapping_add` method. For example,
2064/// [`u32::wrapping_add`]
2065#[rustc_intrinsic_const_stable_indirect]
2066#[rustc_nounwind]
2067#[rustc_intrinsic]
2068pub const fn wrapping_add<T: Copy>(a: T, b: T) -> T;
2069/// Returns (a - b) mod 2<sup>N</sup>, where N is the width of T in bits.
2070///
2071/// Note that, unlike most intrinsics, this is safe to call;
2072/// it does not require an `unsafe` block.
2073/// Therefore, implementations must not require the user to uphold
2074/// any safety invariants.
2075///
2076/// The stabilized versions of this intrinsic are available on the integer
2077/// primitives via the `wrapping_sub` method. For example,
2078/// [`u32::wrapping_sub`]
2079#[rustc_intrinsic_const_stable_indirect]
2080#[rustc_nounwind]
2081#[rustc_intrinsic]
2082pub const fn wrapping_sub<T: Copy>(a: T, b: T) -> T;
2083/// Returns (a * b) mod 2<sup>N</sup>, where N is the width of T in bits.
2084///
2085/// Note that, unlike most intrinsics, this is safe to call;
2086/// it does not require an `unsafe` block.
2087/// Therefore, implementations must not require the user to uphold
2088/// any safety invariants.
2089///
2090/// The stabilized versions of this intrinsic are available on the integer
2091/// primitives via the `wrapping_mul` method. For example,
2092/// [`u32::wrapping_mul`]
2093#[rustc_intrinsic_const_stable_indirect]
2094#[rustc_nounwind]
2095#[rustc_intrinsic]
2096pub const fn wrapping_mul<T: Copy>(a: T, b: T) -> T;
2097
2098/// Computes `a + b`, saturating at numeric bounds.
2099///
2100/// Note that, unlike most intrinsics, this is safe to call;
2101/// it does not require an `unsafe` block.
2102/// Therefore, implementations must not require the user to uphold
2103/// any safety invariants.
2104///
2105/// The stabilized versions of this intrinsic are available on the integer
2106/// primitives via the `saturating_add` method. For example,
2107/// [`u32::saturating_add`]
2108#[rustc_intrinsic_const_stable_indirect]
2109#[rustc_nounwind]
2110#[rustc_intrinsic]
2111pub const fn saturating_add<T: Copy>(a: T, b: T) -> T;
2112/// Computes `a - b`, saturating at numeric bounds.
2113///
2114/// Note that, unlike most intrinsics, this is safe to call;
2115/// it does not require an `unsafe` block.
2116/// Therefore, implementations must not require the user to uphold
2117/// any safety invariants.
2118///
2119/// The stabilized versions of this intrinsic are available on the integer
2120/// primitives via the `saturating_sub` method. For example,
2121/// [`u32::saturating_sub`]
2122#[rustc_intrinsic_const_stable_indirect]
2123#[rustc_nounwind]
2124#[rustc_intrinsic]
2125pub const fn saturating_sub<T: Copy>(a: T, b: T) -> T;
2126
2127/// Funnel Shift left.
2128///
2129/// Concatenates `a` and `b` (with `a` in the most significant half),
2130/// creating an integer twice as wide. Then shift this integer left
2131/// by `shift`), and extract the most significant half. If `a` and `b`
2132/// are the same, this is equivalent to a rotate left operation.
2133///
2134/// It is undefined behavior if `shift` is greater than or equal to the
2135/// bit size of `T`.
2136///
2137/// Safe versions of this intrinsic are available on the integer primitives
2138/// via the `funnel_shl` method. For example, [`u32::funnel_shl`].
2139#[rustc_intrinsic]
2140#[rustc_nounwind]
2141#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
2142#[unstable(feature = "funnel_shifts", issue = "145686")]
2143#[track_caller]
2144#[miri::intrinsic_fallback_is_spec]
2145pub const unsafe fn unchecked_funnel_shl<T: [const] fallback::FunnelShift>(
2146    a: T,
2147    b: T,
2148    shift: u32,
2149) -> T {
2150    // SAFETY: caller ensures that `shift` is in-range
2151    unsafe { a.unchecked_funnel_shl(b, shift) }
2152}
2153
2154/// Funnel Shift right.
2155///
2156/// Concatenates `a` and `b` (with `a` in the most significant half),
2157/// creating an integer twice as wide. Then shift this integer right
2158/// by `shift` (taken modulo the bit size of `T`), and extract the
2159/// least significant half. If `a` and `b` are the same, this is equivalent
2160/// to a rotate right operation.
2161///
2162/// It is undefined behavior if `shift` is greater than or equal to the
2163/// bit size of `T`.
2164///
2165/// Safer versions of this intrinsic are available on the integer primitives
2166/// via the `funnel_shr` method. For example, [`u32::funnel_shr`]
2167#[rustc_intrinsic]
2168#[rustc_nounwind]
2169#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
2170#[unstable(feature = "funnel_shifts", issue = "145686")]
2171#[track_caller]
2172#[miri::intrinsic_fallback_is_spec]
2173pub const unsafe fn unchecked_funnel_shr<T: [const] fallback::FunnelShift>(
2174    a: T,
2175    b: T,
2176    shift: u32,
2177) -> T {
2178    // SAFETY: caller ensures that `shift` is in-range
2179    unsafe { a.unchecked_funnel_shr(b, shift) }
2180}
2181
2182/// This is an implementation detail of [`crate::ptr::read`] and should
2183/// not be used anywhere else.  See its comments for why this exists.
2184///
2185/// This intrinsic can *only* be called where the pointer is a local without
2186/// projections (`read_via_copy(ptr)`, not `read_via_copy(*ptr)`) so that it
2187/// trivially obeys runtime-MIR rules about derefs in operands.
2188#[rustc_intrinsic_const_stable_indirect]
2189#[rustc_nounwind]
2190#[rustc_intrinsic]
2191pub const unsafe fn read_via_copy<T>(ptr: *const T) -> T;
2192
2193/// This is an implementation detail of [`crate::ptr::write`] and should
2194/// not be used anywhere else.  See its comments for why this exists.
2195///
2196/// This intrinsic can *only* be called where the pointer is a local without
2197/// projections (`write_via_move(ptr, x)`, not `write_via_move(*ptr, x)`) so
2198/// that it trivially obeys runtime-MIR rules about derefs in operands.
2199#[rustc_intrinsic_const_stable_indirect]
2200#[rustc_nounwind]
2201#[rustc_intrinsic]
2202pub const unsafe fn write_via_move<T>(ptr: *mut T, value: T);
2203
2204/// Returns the value of the discriminant for the variant in 'v';
2205/// if `T` has no discriminant, returns `0`.
2206///
2207/// Note that, unlike most intrinsics, this is safe to call;
2208/// it does not require an `unsafe` block.
2209/// Therefore, implementations must not require the user to uphold
2210/// any safety invariants.
2211///
2212/// The stabilized version of this intrinsic is [`core::mem::discriminant`].
2213#[rustc_intrinsic_const_stable_indirect]
2214#[rustc_nounwind]
2215#[rustc_intrinsic]
2216pub const fn discriminant_value<T>(v: &T) -> <T as DiscriminantKind>::Discriminant;
2217
2218/// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the
2219/// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs.
2220/// Returns `1` if unwinding occurred and `catch_fn` was called; returns `0` otherwise.
2221///
2222/// `catch_fn` must not unwind.
2223///
2224/// The third argument is a function called if an unwind occurs (both Rust `panic` and foreign
2225/// unwinds). This function takes the data pointer and a pointer to the target- and
2226/// runtime-specific exception object that was caught.
2227///
2228/// Note that in the case of a foreign unwinding operation, the exception object data may not be
2229/// safely usable from Rust, and should not be directly exposed via the standard library. To
2230/// prevent unsafe access, the library implementation may either abort the process or present an
2231/// opaque error type to the user.
2232///
2233/// For more information, see the compiler's source, as well as the documentation for the stable
2234/// version of this intrinsic, `std::panic::catch_unwind`.
2235#[rustc_intrinsic]
2236#[rustc_nounwind]
2237pub unsafe fn catch_unwind(
2238    _try_fn: fn(*mut u8),
2239    _data: *mut u8,
2240    _catch_fn: fn(*mut u8, *mut u8),
2241) -> i32;
2242
2243/// Emits a `nontemporal` store, which gives a hint to the CPU that the data should not be held
2244/// in cache. Except for performance, this is fully equivalent to `ptr.write(val)`.
2245///
2246/// Not all architectures provide such an operation. For instance, x86 does not: while `MOVNT`
2247/// exists, that operation is *not* equivalent to `ptr.write(val)` (`MOVNT` writes can be reordered
2248/// in ways that are not allowed for regular writes).
2249#[rustc_intrinsic]
2250#[rustc_nounwind]
2251pub unsafe fn nontemporal_store<T>(ptr: *mut T, val: T);
2252
2253/// See documentation of `<*const T>::offset_from` for details.
2254#[rustc_intrinsic_const_stable_indirect]
2255#[rustc_nounwind]
2256#[rustc_intrinsic]
2257pub const unsafe fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
2258
2259/// See documentation of `<*const T>::offset_from_unsigned` for details.
2260#[rustc_nounwind]
2261#[rustc_intrinsic]
2262#[rustc_intrinsic_const_stable_indirect]
2263pub const unsafe fn ptr_offset_from_unsigned<T>(ptr: *const T, base: *const T) -> usize;
2264
2265/// See documentation of `<*const T>::guaranteed_eq` for details.
2266/// Returns `2` if the result is unknown.
2267/// Returns `1` if the pointers are guaranteed equal.
2268/// Returns `0` if the pointers are guaranteed inequal.
2269#[rustc_intrinsic]
2270#[rustc_nounwind]
2271#[rustc_do_not_const_check]
2272#[inline]
2273#[miri::intrinsic_fallback_is_spec]
2274pub const fn ptr_guaranteed_cmp<T>(ptr: *const T, other: *const T) -> u8 {
2275    (ptr == other) as u8
2276}
2277
2278/// Determines whether the raw bytes of the two values are equal.
2279///
2280/// This is particularly handy for arrays, since it allows things like just
2281/// comparing `i96`s instead of forcing `alloca`s for `[6 x i16]`.
2282///
2283/// Above some backend-decided threshold this will emit calls to `memcmp`,
2284/// like slice equality does, instead of causing massive code size.
2285///
2286/// Since this works by comparing the underlying bytes, the actual `T` is
2287/// not particularly important.  It will be used for its size and alignment,
2288/// but any validity restrictions will be ignored, not enforced.
2289///
2290/// # Safety
2291///
2292/// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized.
2293/// Note that this is a stricter criterion than just the *values* being
2294/// fully-initialized: if `T` has padding, it's UB to call this intrinsic.
2295///
2296/// At compile-time, it is furthermore UB to call this if any of the bytes
2297/// in `*a` or `*b` have provenance.
2298///
2299/// (The implementation is allowed to branch on the results of comparisons,
2300/// which is UB if any of their inputs are `undef`.)
2301#[rustc_nounwind]
2302#[rustc_intrinsic]
2303pub const unsafe fn raw_eq<T>(a: &T, b: &T) -> bool;
2304
2305/// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)`
2306/// as unsigned bytes, returning negative if `left` is less, zero if all the
2307/// bytes match, or positive if `left` is greater.
2308///
2309/// This underlies things like `<[u8]>::cmp`, and will usually lower to `memcmp`.
2310///
2311/// # Safety
2312///
2313/// `left` and `right` must each be [valid] for reads of `bytes` bytes.
2314///
2315/// Note that this applies to the whole range, not just until the first byte
2316/// that differs.  That allows optimizations that can read in large chunks.
2317///
2318/// [valid]: crate::ptr#safety
2319#[rustc_nounwind]
2320#[rustc_intrinsic]
2321#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2322pub const unsafe fn compare_bytes(left: *const u8, right: *const u8, bytes: usize) -> i32;
2323
2324/// See documentation of [`std::hint::black_box`] for details.
2325///
2326/// [`std::hint::black_box`]: crate::hint::black_box
2327#[rustc_nounwind]
2328#[rustc_intrinsic]
2329#[rustc_intrinsic_const_stable_indirect]
2330pub const fn black_box<T>(dummy: T) -> T;
2331
2332/// Selects which function to call depending on the context.
2333///
2334/// If this function is evaluated at compile-time, then a call to this
2335/// intrinsic will be replaced with a call to `called_in_const`. It gets
2336/// replaced with a call to `called_at_rt` otherwise.
2337///
2338/// This function is safe to call, but note the stability concerns below.
2339///
2340/// # Type Requirements
2341///
2342/// The two functions must be both function items. They cannot be function
2343/// pointers or closures. The first function must be a `const fn`.
2344///
2345/// `arg` will be the tupled arguments that will be passed to either one of
2346/// the two functions, therefore, both functions must accept the same type of
2347/// arguments. Both functions must return RET.
2348///
2349/// # Stability concerns
2350///
2351/// Rust has not yet decided that `const fn` are allowed to tell whether
2352/// they run at compile-time or at runtime. Therefore, when using this
2353/// intrinsic anywhere that can be reached from stable, it is crucial that
2354/// the end-to-end behavior of the stable `const fn` is the same for both
2355/// modes of execution. (Here, Undefined Behavior is considered "the same"
2356/// as any other behavior, so if the function exhibits UB at runtime then
2357/// it may do whatever it wants at compile-time.)
2358///
2359/// Here is an example of how this could cause a problem:
2360/// ```no_run
2361/// #![feature(const_eval_select)]
2362/// #![feature(core_intrinsics)]
2363/// # #![allow(internal_features)]
2364/// use std::intrinsics::const_eval_select;
2365///
2366/// // Standard library
2367/// pub const fn inconsistent() -> i32 {
2368///     fn runtime() -> i32 { 1 }
2369///     const fn compiletime() -> i32 { 2 }
2370///
2371///     // ⚠ This code violates the required equivalence of `compiletime`
2372///     // and `runtime`.
2373///     const_eval_select((), compiletime, runtime)
2374/// }
2375///
2376/// // User Crate
2377/// const X: i32 = inconsistent();
2378/// let x = inconsistent();
2379/// assert_eq!(x, X);
2380/// ```
2381///
2382/// Currently such an assertion would always succeed; until Rust decides
2383/// otherwise, that principle should not be violated.
2384#[rustc_const_unstable(feature = "const_eval_select", issue = "124625")]
2385#[rustc_intrinsic]
2386pub const fn const_eval_select<ARG: Tuple, F, G, RET>(
2387    _arg: ARG,
2388    _called_in_const: F,
2389    _called_at_rt: G,
2390) -> RET
2391where
2392    G: FnOnce<ARG, Output = RET>,
2393    F: const FnOnce<ARG, Output = RET>;
2394
2395/// A macro to make it easier to invoke const_eval_select. Use as follows:
2396/// ```rust,ignore (just a macro example)
2397/// const_eval_select!(
2398///     @capture { arg1: i32 = some_expr, arg2: T = other_expr } -> U:
2399///     if const #[attributes_for_const_arm] {
2400///         // Compile-time code goes here.
2401///     } else #[attributes_for_runtime_arm] {
2402///         // Run-time code goes here.
2403///     }
2404/// )
2405/// ```
2406/// The `@capture` block declares which surrounding variables / expressions can be
2407/// used inside the `if const`.
2408/// Note that the two arms of this `if` really each become their own function, which is why the
2409/// macro supports setting attributes for those functions. Both functions are marked as `#[inline]`.
2410///
2411/// See [`const_eval_select()`] for the rules and requirements around that intrinsic.
2412pub(crate) macro const_eval_select {
2413    (
2414        @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? :
2415        if const
2416            $(#[$compiletime_attr:meta])* $compiletime:block
2417        else
2418            $(#[$runtime_attr:meta])* $runtime:block
2419    ) => {{
2420        #[inline]
2421        $(#[$runtime_attr])*
2422        fn runtime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2423            $runtime
2424        }
2425
2426        #[inline]
2427        $(#[$compiletime_attr])*
2428        const fn compiletime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2429            // Don't warn if one of the arguments is unused.
2430            $(let _ = $arg;)*
2431
2432            $compiletime
2433        }
2434
2435        const_eval_select(($($val,)*), compiletime, runtime)
2436    }},
2437    // We support leaving away the `val` expressions for *all* arguments
2438    // (but not for *some* arguments, that's too tricky).
2439    (
2440        @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty),* $(,)? } $( -> $ret:ty )? :
2441        if const
2442            $(#[$compiletime_attr:meta])* $compiletime:block
2443        else
2444            $(#[$runtime_attr:meta])* $runtime:block
2445    ) => {
2446        $crate::intrinsics::const_eval_select!(
2447            @capture$([$($binders)*])? { $($arg : $ty = $arg),* } $(-> $ret)? :
2448            if const
2449                $(#[$compiletime_attr])* $compiletime
2450            else
2451                $(#[$runtime_attr])* $runtime
2452        )
2453    },
2454}
2455
2456/// Returns whether the argument's value is statically known at
2457/// compile-time.
2458///
2459/// This is useful when there is a way of writing the code that will
2460/// be *faster* when some variables have known values, but *slower*
2461/// in the general case: an `if is_val_statically_known(var)` can be used
2462/// to select between these two variants. The `if` will be optimized away
2463/// and only the desired branch remains.
2464///
2465/// Formally speaking, this function non-deterministically returns `true`
2466/// or `false`, and the caller has to ensure sound behavior for both cases.
2467/// In other words, the following code has *Undefined Behavior*:
2468///
2469/// ```no_run
2470/// #![feature(core_intrinsics)]
2471/// # #![allow(internal_features)]
2472/// use std::hint::unreachable_unchecked;
2473/// use std::intrinsics::is_val_statically_known;
2474///
2475/// if !is_val_statically_known(0) { unsafe { unreachable_unchecked(); } }
2476/// ```
2477///
2478/// This also means that the following code's behavior is unspecified; it
2479/// may panic, or it may not:
2480///
2481/// ```no_run
2482/// #![feature(core_intrinsics)]
2483/// # #![allow(internal_features)]
2484/// use std::intrinsics::is_val_statically_known;
2485///
2486/// assert_eq!(is_val_statically_known(0), is_val_statically_known(0));
2487/// ```
2488///
2489/// Unsafe code may not rely on `is_val_statically_known` returning any
2490/// particular value, ever. However, the compiler will generally make it
2491/// return `true` only if the value of the argument is actually known.
2492///
2493/// # Stability concerns
2494///
2495/// While it is safe to call, this intrinsic may behave differently in
2496/// a `const` context than otherwise. See the [`const_eval_select()`]
2497/// documentation for an explanation of the issues this can cause. Unlike
2498/// `const_eval_select`, this intrinsic isn't guaranteed to behave
2499/// deterministically even in a `const` context.
2500///
2501/// # Type Requirements
2502///
2503/// `T` must be either a `bool`, a `char`, a primitive numeric type (e.g. `f32`,
2504/// but not `NonZeroISize`), or any thin pointer (e.g. `*mut String`).
2505/// Any other argument types *may* cause a compiler error.
2506///
2507/// ## Pointers
2508///
2509/// When the input is a pointer, only the pointer itself is
2510/// ever considered. The pointee has no effect. Currently, these functions
2511/// behave identically:
2512///
2513/// ```
2514/// #![feature(core_intrinsics)]
2515/// # #![allow(internal_features)]
2516/// use std::intrinsics::is_val_statically_known;
2517///
2518/// fn foo(x: &i32) -> bool {
2519///     is_val_statically_known(x)
2520/// }
2521///
2522/// fn bar(x: &i32) -> bool {
2523///     is_val_statically_known(
2524///         (x as *const i32).addr()
2525///     )
2526/// }
2527/// # _ = foo(&5_i32);
2528/// # _ = bar(&5_i32);
2529/// ```
2530#[rustc_const_stable_indirect]
2531#[rustc_nounwind]
2532#[unstable(feature = "core_intrinsics", issue = "none")]
2533#[rustc_intrinsic]
2534pub const fn is_val_statically_known<T: Copy>(_arg: T) -> bool {
2535    false
2536}
2537
2538/// Non-overlapping *typed* swap of a single value.
2539///
2540/// The codegen backends will replace this with a better implementation when
2541/// `T` is a simple type that can be loaded and stored as an immediate.
2542///
2543/// The stabilized form of this intrinsic is [`crate::mem::swap`].
2544///
2545/// # Safety
2546/// Behavior is undefined if any of the following conditions are violated:
2547///
2548/// * Both `x` and `y` must be [valid] for both reads and writes.
2549///
2550/// * Both `x` and `y` must be properly aligned.
2551///
2552/// * The region of memory beginning at `x` must *not* overlap with the region of memory
2553///   beginning at `y`.
2554///
2555/// * The memory pointed by `x` and `y` must both contain values of type `T`.
2556///
2557/// [valid]: crate::ptr#safety
2558#[rustc_nounwind]
2559#[inline]
2560#[rustc_intrinsic]
2561#[rustc_intrinsic_const_stable_indirect]
2562pub const unsafe fn typed_swap_nonoverlapping<T>(x: *mut T, y: *mut T) {
2563    // SAFETY: The caller provided single non-overlapping items behind
2564    // pointers, so swapping them with `count: 1` is fine.
2565    unsafe { ptr::swap_nonoverlapping(x, y, 1) };
2566}
2567
2568/// Returns whether we should perform some UB-checking at runtime. This eventually evaluates to
2569/// `cfg!(ub_checks)`, but behaves different from `cfg!` when mixing crates built with different
2570/// flags: if the crate has UB checks enabled or carries the `#[rustc_preserve_ub_checks]`
2571/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2572/// a crate that does not delay evaluation further); otherwise it can happen any time.
2573///
2574/// The common case here is a user program built with ub_checks linked against the distributed
2575/// sysroot which is built without ub_checks but with `#[rustc_preserve_ub_checks]`.
2576/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2577/// `#[inline]`), gating assertions on `ub_checks()` rather than `cfg!(ub_checks)` means that
2578/// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the
2579/// user has UB checks disabled, the checks will still get optimized out. This intrinsic is
2580/// primarily used by [`crate::ub_checks::assert_unsafe_precondition`].
2581#[rustc_intrinsic_const_stable_indirect] // just for UB checks
2582#[inline(always)]
2583#[rustc_intrinsic]
2584pub const fn ub_checks() -> bool {
2585    cfg!(ub_checks)
2586}
2587
2588/// Returns whether we should perform some overflow-checking at runtime. This eventually evaluates to
2589/// `cfg!(overflow_checks)`, but behaves different from `cfg!` when mixing crates built with different
2590/// flags: if the crate has overflow checks enabled or carries the `#[rustc_inherit_overflow_checks]`
2591/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2592/// a crate that does not delay evaluation further); otherwise it can happen any time.
2593///
2594/// The common case here is a user program built with overflow_checks linked against the distributed
2595/// sysroot which is built without overflow_checks but with `#[rustc_inherit_overflow_checks]`.
2596/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2597/// `#[inline]`), gating assertions on `overflow_checks()` rather than `cfg!(overflow_checks)` means that
2598/// assertions are enabled whenever the *user crate* has overflow checks enabled. However if the
2599/// user has overflow checks disabled, the checks will still get optimized out.
2600#[inline(always)]
2601#[rustc_intrinsic]
2602pub const fn overflow_checks() -> bool {
2603    cfg!(debug_assertions)
2604}
2605
2606/// Allocates a block of memory at compile time.
2607/// At runtime, just returns a null pointer.
2608///
2609/// # Safety
2610///
2611/// - The `align` argument must be a power of two.
2612///    - At compile time, a compile error occurs if this constraint is violated.
2613///    - At runtime, it is not checked.
2614#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2615#[rustc_nounwind]
2616#[rustc_intrinsic]
2617#[miri::intrinsic_fallback_is_spec]
2618pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 {
2619    // const eval overrides this function, but runtime code for now just returns null pointers.
2620    // See <https://github.com/rust-lang/rust/issues/93935>.
2621    crate::ptr::null_mut()
2622}
2623
2624/// Deallocates a memory which allocated by `intrinsics::const_allocate` at compile time.
2625/// At runtime, it does nothing.
2626///
2627/// # Safety
2628///
2629/// - The `align` argument must be a power of two.
2630///    - At compile time, a compile error occurs if this constraint is violated.
2631///    - At runtime, it is not checked.
2632/// - If the `ptr` is created in an another const, this intrinsic doesn't deallocate it.
2633/// - If the `ptr` is pointing to a local variable, this intrinsic doesn't deallocate it.
2634#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2635#[unstable(feature = "core_intrinsics", issue = "none")]
2636#[rustc_nounwind]
2637#[rustc_intrinsic]
2638#[miri::intrinsic_fallback_is_spec]
2639pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {
2640    // Runtime NOP
2641}
2642
2643/// Convert the allocation this pointer points to into immutable global memory.
2644/// The pointer must point to the beginning of a heap allocation.
2645/// This operation only makes sense during compile time. At runtime, it does nothing.
2646#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2647#[rustc_nounwind]
2648#[rustc_intrinsic]
2649#[miri::intrinsic_fallback_is_spec]
2650pub const unsafe fn const_make_global(ptr: *mut u8) -> *const u8 {
2651    // const eval overrides this function; at runtime, it is a NOP.
2652    ptr
2653}
2654
2655/// Check if the pre-condition `cond` has been met.
2656///
2657/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2658/// returns false.
2659///
2660/// Note that this function is a no-op during constant evaluation.
2661#[unstable(feature = "contracts_internals", issue = "128044")]
2662// Calls to this function get inserted by an AST expansion pass, which uses the equivalent of
2663// `#[allow_internal_unstable]` to allow using `contracts_internals` functions. Const-checking
2664// doesn't honor `#[allow_internal_unstable]`, so for the const feature gate we use the user-facing
2665// `contracts` feature rather than the perma-unstable `contracts_internals`
2666#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2667#[lang = "contract_check_requires"]
2668#[rustc_intrinsic]
2669pub const fn contract_check_requires<C: Fn() -> bool + Copy>(cond: C) {
2670    const_eval_select!(
2671        @capture[C: Fn() -> bool + Copy] { cond: C } :
2672        if const {
2673                // Do nothing
2674        } else {
2675            if !cond() {
2676                // Emit no unwind panic in case this was a safety requirement.
2677                crate::panicking::panic_nounwind("failed requires check");
2678            }
2679        }
2680    )
2681}
2682
2683/// Check if the post-condition `cond` has been met.
2684///
2685/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2686/// returns false.
2687///
2688/// If `cond` is `None`, then no postcondition checking is performed.
2689///
2690/// Note that this function is a no-op during constant evaluation.
2691#[unstable(feature = "contracts_internals", issue = "128044")]
2692// Similar to `contract_check_requires`, we need to use the user-facing
2693// `contracts` feature rather than the perma-unstable `contracts_internals`.
2694// Const-checking doesn't honor allow_internal_unstable logic used by contract expansion.
2695#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2696#[lang = "contract_check_ensures"]
2697#[rustc_intrinsic]
2698pub const fn contract_check_ensures<C: Fn(&Ret) -> bool + Copy, Ret>(
2699    cond: Option<C>,
2700    ret: Ret,
2701) -> Ret {
2702    const_eval_select!(
2703        @capture[C: Fn(&Ret) -> bool + Copy, Ret] { cond: Option<C>, ret: Ret } -> Ret :
2704        if const {
2705            // Do nothing
2706            ret
2707        } else {
2708            match cond {
2709                crate::option::Option::Some(cond) => {
2710                    if !cond(&ret) {
2711                        // Emit no unwind panic in case this was a safety requirement.
2712                        crate::panicking::panic_nounwind("failed ensures check");
2713                    }
2714                },
2715                crate::option::Option::None => {},
2716            }
2717            ret
2718        }
2719    )
2720}
2721
2722/// The intrinsic will return the size stored in that vtable.
2723///
2724/// # Safety
2725///
2726/// `ptr` must point to a vtable.
2727#[rustc_nounwind]
2728#[unstable(feature = "core_intrinsics", issue = "none")]
2729#[rustc_intrinsic]
2730pub unsafe fn vtable_size(ptr: *const ()) -> usize;
2731
2732/// The intrinsic will return the alignment stored in that vtable.
2733///
2734/// # Safety
2735///
2736/// `ptr` must point to a vtable.
2737#[rustc_nounwind]
2738#[unstable(feature = "core_intrinsics", issue = "none")]
2739#[rustc_intrinsic]
2740pub unsafe fn vtable_align(ptr: *const ()) -> usize;
2741
2742/// The intrinsic returns the `U` vtable for `T` if `T` can be coerced to the trait object type `U`.
2743///
2744/// # Compile-time failures
2745/// Determining whether `T` can be coerced to the trait object type `U` requires trait resolution by the compiler.
2746/// In some cases, that resolution can exceed the recursion limit,
2747/// and compilation will fail instead of this function returning `None`.
2748#[rustc_nounwind]
2749#[unstable(feature = "core_intrinsics", issue = "none")]
2750#[rustc_intrinsic]
2751pub const fn vtable_for<T, U: ptr::Pointee<Metadata = ptr::DynMetadata<U>> + ?Sized>()
2752-> Option<ptr::DynMetadata<U>>;
2753
2754/// The size of a type in bytes.
2755///
2756/// Note that, unlike most intrinsics, this is safe to call;
2757/// it does not require an `unsafe` block.
2758/// Therefore, implementations must not require the user to uphold
2759/// any safety invariants.
2760///
2761/// More specifically, this is the offset in bytes between successive
2762/// items of the same type, including alignment padding.
2763///
2764/// Note that, unlike most intrinsics, this can only be called at compile-time
2765/// as backends do not have an implementation for it. The only caller (its
2766/// stable counterpart) wraps this intrinsic call in a `const` block so that
2767/// backends only see an evaluated constant.
2768///
2769/// The stabilized version of this intrinsic is [`core::mem::size_of`].
2770#[rustc_nounwind]
2771#[unstable(feature = "core_intrinsics", issue = "none")]
2772#[rustc_intrinsic_const_stable_indirect]
2773#[rustc_intrinsic]
2774pub const fn size_of<T>() -> usize;
2775
2776/// The minimum alignment of a type.
2777///
2778/// Note that, unlike most intrinsics, this is safe to call;
2779/// it does not require an `unsafe` block.
2780/// Therefore, implementations must not require the user to uphold
2781/// any safety invariants.
2782///
2783/// Note that, unlike most intrinsics, this can only be called at compile-time
2784/// as backends do not have an implementation for it. The only caller (its
2785/// stable counterpart) wraps this intrinsic call in a `const` block so that
2786/// backends only see an evaluated constant.
2787///
2788/// The stabilized version of this intrinsic is [`core::mem::align_of`].
2789#[rustc_nounwind]
2790#[unstable(feature = "core_intrinsics", issue = "none")]
2791#[rustc_intrinsic_const_stable_indirect]
2792#[rustc_intrinsic]
2793pub const fn align_of<T>() -> usize;
2794
2795/// The offset of a field inside a type.
2796///
2797/// Note that, unlike most intrinsics, this is safe to call;
2798/// it does not require an `unsafe` block.
2799/// Therefore, implementations must not require the user to uphold
2800/// any safety invariants.
2801///
2802/// This intrinsic can only be evaluated at compile-time, and should only appear in
2803/// constants or inline const blocks.
2804///
2805/// The stabilized version of this intrinsic is [`core::mem::offset_of`].
2806/// This intrinsic is also a lang item so `offset_of!` can desugar to calls to it.
2807#[rustc_nounwind]
2808#[unstable(feature = "core_intrinsics", issue = "none")]
2809#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")]
2810#[rustc_intrinsic_const_stable_indirect]
2811#[rustc_intrinsic]
2812#[lang = "offset_of"]
2813pub const fn offset_of<T: PointeeSized>(variant: u32, field: u32) -> usize;
2814
2815/// Returns the number of variants of the type `T` cast to a `usize`;
2816/// if `T` has no variants, returns `0`. Uninhabited variants will be counted.
2817///
2818/// Note that, unlike most intrinsics, this can only be called at compile-time
2819/// as backends do not have an implementation for it. The only caller (its
2820/// stable counterpart) wraps this intrinsic call in a `const` block so that
2821/// backends only see an evaluated constant.
2822///
2823/// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`].
2824#[rustc_nounwind]
2825#[unstable(feature = "core_intrinsics", issue = "none")]
2826#[rustc_intrinsic]
2827pub const fn variant_count<T>() -> usize;
2828
2829/// The size of the referenced value in bytes.
2830///
2831/// The stabilized version of this intrinsic is [`core::mem::size_of_val`].
2832///
2833/// # Safety
2834///
2835/// See [`crate::mem::size_of_val_raw`] for safety conditions.
2836#[rustc_nounwind]
2837#[unstable(feature = "core_intrinsics", issue = "none")]
2838#[rustc_intrinsic]
2839#[rustc_intrinsic_const_stable_indirect]
2840pub const unsafe fn size_of_val<T: ?Sized>(ptr: *const T) -> usize;
2841
2842/// The required alignment of the referenced value.
2843///
2844/// The stabilized version of this intrinsic is [`core::mem::align_of_val`].
2845///
2846/// # Safety
2847///
2848/// See [`crate::mem::align_of_val_raw`] for safety conditions.
2849#[rustc_nounwind]
2850#[unstable(feature = "core_intrinsics", issue = "none")]
2851#[rustc_intrinsic]
2852#[rustc_intrinsic_const_stable_indirect]
2853pub const unsafe fn align_of_val<T: ?Sized>(ptr: *const T) -> usize;
2854
2855/// Compute the type information of a concrete type.
2856/// It can only be called at compile time, the backends do
2857/// not implement it.
2858#[rustc_intrinsic]
2859#[unstable(feature = "core_intrinsics", issue = "none")]
2860pub const fn type_of(_id: crate::any::TypeId) -> crate::mem::type_info::Type {
2861    panic!("`TypeId::info` can only be called at compile-time")
2862}
2863
2864/// Gets a static string slice containing the name of a type.
2865///
2866/// Note that, unlike most intrinsics, this can only be called at compile-time
2867/// as backends do not have an implementation for it. The only caller (its
2868/// stable counterpart) wraps this intrinsic call in a `const` block so that
2869/// backends only see an evaluated constant.
2870///
2871/// The stabilized version of this intrinsic is [`core::any::type_name`].
2872#[rustc_nounwind]
2873#[unstable(feature = "core_intrinsics", issue = "none")]
2874#[rustc_intrinsic]
2875pub const fn type_name<T: ?Sized>() -> &'static str;
2876
2877/// Gets an identifier which is globally unique to the specified type. This
2878/// function will return the same value for a type regardless of whichever
2879/// crate it is invoked in.
2880///
2881/// Note that, unlike most intrinsics, this can only be called at compile-time
2882/// as backends do not have an implementation for it. The only caller (its
2883/// stable counterpart) wraps this intrinsic call in a `const` block so that
2884/// backends only see an evaluated constant.
2885///
2886/// The stabilized version of this intrinsic is [`core::any::TypeId::of`].
2887#[rustc_nounwind]
2888#[unstable(feature = "core_intrinsics", issue = "none")]
2889#[rustc_intrinsic]
2890pub const fn type_id<T: ?Sized + 'static>() -> crate::any::TypeId;
2891
2892/// Tests (at compile-time) if two [`crate::any::TypeId`] instances identify the
2893/// same type. This is necessary because at const-eval time the actual discriminating
2894/// data is opaque and cannot be inspected directly.
2895///
2896/// The stabilized version of this intrinsic is the [PartialEq] impl for [`core::any::TypeId`].
2897#[rustc_nounwind]
2898#[unstable(feature = "core_intrinsics", issue = "none")]
2899#[rustc_intrinsic]
2900#[rustc_do_not_const_check]
2901pub const fn type_id_eq(a: crate::any::TypeId, b: crate::any::TypeId) -> bool {
2902    a.data == b.data
2903}
2904
2905/// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`.
2906///
2907/// This is used to implement functions like `slice::from_raw_parts_mut` and
2908/// `ptr::from_raw_parts` in a way compatible with the compiler being able to
2909/// change the possible layouts of pointers.
2910#[rustc_nounwind]
2911#[unstable(feature = "core_intrinsics", issue = "none")]
2912#[rustc_intrinsic_const_stable_indirect]
2913#[rustc_intrinsic]
2914pub const fn aggregate_raw_ptr<P: bounds::BuiltinDeref, D, M>(data: D, meta: M) -> P
2915where
2916    <P as bounds::BuiltinDeref>::Pointee: ptr::Pointee<Metadata = M>;
2917
2918/// Lowers in MIR to `Rvalue::UnaryOp` with `UnOp::PtrMetadata`.
2919///
2920/// This is used to implement functions like `ptr::metadata`.
2921#[rustc_nounwind]
2922#[unstable(feature = "core_intrinsics", issue = "none")]
2923#[rustc_intrinsic_const_stable_indirect]
2924#[rustc_intrinsic]
2925pub const fn ptr_metadata<P: ptr::Pointee<Metadata = M> + PointeeSized, M>(ptr: *const P) -> M;
2926
2927/// This is an accidentally-stable alias to [`ptr::copy_nonoverlapping`]; use that instead.
2928// Note (intentionally not in the doc comment): `ptr::copy_nonoverlapping` adds some extra
2929// debug assertions; if you are writing compiler tests or code inside the standard library
2930// that wants to avoid those debug assertions, directly call this intrinsic instead.
2931#[stable(feature = "rust1", since = "1.0.0")]
2932#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2933#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2934#[rustc_nounwind]
2935#[rustc_intrinsic]
2936pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
2937
2938/// This is an accidentally-stable alias to [`ptr::copy`]; use that instead.
2939// Note (intentionally not in the doc comment): `ptr::copy` adds some extra
2940// debug assertions; if you are writing compiler tests or code inside the standard library
2941// that wants to avoid those debug assertions, directly call this intrinsic instead.
2942#[stable(feature = "rust1", since = "1.0.0")]
2943#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2944#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2945#[rustc_nounwind]
2946#[rustc_intrinsic]
2947pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize);
2948
2949/// This is an accidentally-stable alias to [`ptr::write_bytes`]; use that instead.
2950// Note (intentionally not in the doc comment): `ptr::write_bytes` adds some extra
2951// debug assertions; if you are writing compiler tests or code inside the standard library
2952// that wants to avoid those debug assertions, directly call this intrinsic instead.
2953#[stable(feature = "rust1", since = "1.0.0")]
2954#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2955#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2956#[rustc_nounwind]
2957#[rustc_intrinsic]
2958pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
2959
2960/// Returns the minimum of two `f16` values, ignoring NaN.
2961///
2962/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
2963/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
2964/// and `-0.0`), either input may be returned non-deterministically.
2965///
2966/// Note that, unlike most intrinsics, this is safe to call;
2967/// it does not require an `unsafe` block.
2968/// Therefore, implementations must not require the user to uphold
2969/// any safety invariants.
2970///
2971/// The stabilized version of this intrinsic is [`f16::min`].
2972#[rustc_nounwind]
2973#[rustc_intrinsic]
2974pub const fn minnumf16(x: f16, y: f16) -> f16;
2975
2976/// Returns the minimum of two `f32` values, ignoring NaN.
2977///
2978/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
2979/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
2980/// and `-0.0`), either input may be returned non-deterministically.
2981///
2982/// Note that, unlike most intrinsics, this is safe to call;
2983/// it does not require an `unsafe` block.
2984/// Therefore, implementations must not require the user to uphold
2985/// any safety invariants.
2986///
2987/// The stabilized version of this intrinsic is [`f32::min`].
2988#[rustc_nounwind]
2989#[rustc_intrinsic_const_stable_indirect]
2990#[rustc_intrinsic]
2991pub const fn minnumf32(x: f32, y: f32) -> f32;
2992
2993/// Returns the minimum of two `f64` values, ignoring NaN.
2994///
2995/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
2996/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
2997/// and `-0.0`), either input may be returned non-deterministically.
2998///
2999/// Note that, unlike most intrinsics, this is safe to call;
3000/// it does not require an `unsafe` block.
3001/// Therefore, implementations must not require the user to uphold
3002/// any safety invariants.
3003///
3004/// The stabilized version of this intrinsic is [`f64::min`].
3005#[rustc_nounwind]
3006#[rustc_intrinsic_const_stable_indirect]
3007#[rustc_intrinsic]
3008pub const fn minnumf64(x: f64, y: f64) -> f64;
3009
3010/// Returns the minimum of two `f128` values, ignoring NaN.
3011///
3012/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3013/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3014/// and `-0.0`), either input may be returned non-deterministically.
3015///
3016/// Note that, unlike most intrinsics, this is safe to call;
3017/// it does not require an `unsafe` block.
3018/// Therefore, implementations must not require the user to uphold
3019/// any safety invariants.
3020///
3021/// The stabilized version of this intrinsic is [`f128::min`].
3022#[rustc_nounwind]
3023#[rustc_intrinsic]
3024pub const fn minnumf128(x: f128, y: f128) -> f128;
3025
3026/// Returns the minimum of two `f16` values, propagating NaN.
3027///
3028/// This behaves like IEEE 754-2019 minimum. In particular:
3029/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3030/// For this operation, -0.0 is considered to be strictly less than +0.0.
3031///
3032/// Note that, unlike most intrinsics, this is safe to call;
3033/// it does not require an `unsafe` block.
3034/// Therefore, implementations must not require the user to uphold
3035/// any safety invariants.
3036#[rustc_nounwind]
3037#[rustc_intrinsic]
3038pub const fn minimumf16(x: f16, y: f16) -> f16 {
3039    if x < y {
3040        x
3041    } else if y < x {
3042        y
3043    } else if x == y {
3044        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3045    } else {
3046        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3047        x + y
3048    }
3049}
3050
3051/// Returns the minimum of two `f32` values, propagating NaN.
3052///
3053/// This behaves like IEEE 754-2019 minimum. In particular:
3054/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3055/// For this operation, -0.0 is considered to be strictly less than +0.0.
3056///
3057/// Note that, unlike most intrinsics, this is safe to call;
3058/// it does not require an `unsafe` block.
3059/// Therefore, implementations must not require the user to uphold
3060/// any safety invariants.
3061#[rustc_nounwind]
3062#[rustc_intrinsic]
3063pub const fn minimumf32(x: f32, y: f32) -> f32 {
3064    if x < y {
3065        x
3066    } else if y < x {
3067        y
3068    } else if x == y {
3069        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3070    } else {
3071        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3072        x + y
3073    }
3074}
3075
3076/// Returns the minimum of two `f64` values, propagating NaN.
3077///
3078/// This behaves like IEEE 754-2019 minimum. In particular:
3079/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3080/// For this operation, -0.0 is considered to be strictly less than +0.0.
3081///
3082/// Note that, unlike most intrinsics, this is safe to call;
3083/// it does not require an `unsafe` block.
3084/// Therefore, implementations must not require the user to uphold
3085/// any safety invariants.
3086#[rustc_nounwind]
3087#[rustc_intrinsic]
3088pub const fn minimumf64(x: f64, y: f64) -> f64 {
3089    if x < y {
3090        x
3091    } else if y < x {
3092        y
3093    } else if x == y {
3094        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3095    } else {
3096        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3097        x + y
3098    }
3099}
3100
3101/// Returns the minimum of two `f128` values, propagating NaN.
3102///
3103/// This behaves like IEEE 754-2019 minimum. In particular:
3104/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3105/// For this operation, -0.0 is considered to be strictly less than +0.0.
3106///
3107/// Note that, unlike most intrinsics, this is safe to call;
3108/// it does not require an `unsafe` block.
3109/// Therefore, implementations must not require the user to uphold
3110/// any safety invariants.
3111#[rustc_nounwind]
3112#[rustc_intrinsic]
3113pub const fn minimumf128(x: f128, y: f128) -> f128 {
3114    if x < y {
3115        x
3116    } else if y < x {
3117        y
3118    } else if x == y {
3119        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3120    } else {
3121        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3122        x + y
3123    }
3124}
3125
3126/// Returns the maximum of two `f16` values, ignoring NaN.
3127///
3128/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3129/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3130/// and `-0.0`), either input may be returned non-deterministically.
3131///
3132/// Note that, unlike most intrinsics, this is safe to call;
3133/// it does not require an `unsafe` block.
3134/// Therefore, implementations must not require the user to uphold
3135/// any safety invariants.
3136///
3137/// The stabilized version of this intrinsic is [`f16::max`].
3138#[rustc_nounwind]
3139#[rustc_intrinsic]
3140pub const fn maxnumf16(x: f16, y: f16) -> f16;
3141
3142/// Returns the maximum of two `f32` values, ignoring NaN.
3143///
3144/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3145/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3146/// and `-0.0`), either input may be returned non-deterministically.
3147///
3148/// Note that, unlike most intrinsics, this is safe to call;
3149/// it does not require an `unsafe` block.
3150/// Therefore, implementations must not require the user to uphold
3151/// any safety invariants.
3152///
3153/// The stabilized version of this intrinsic is [`f32::max`].
3154#[rustc_nounwind]
3155#[rustc_intrinsic_const_stable_indirect]
3156#[rustc_intrinsic]
3157pub const fn maxnumf32(x: f32, y: f32) -> f32;
3158
3159/// Returns the maximum of two `f64` values, ignoring NaN.
3160///
3161/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3162/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3163/// and `-0.0`), either input may be returned non-deterministically.
3164///
3165/// Note that, unlike most intrinsics, this is safe to call;
3166/// it does not require an `unsafe` block.
3167/// Therefore, implementations must not require the user to uphold
3168/// any safety invariants.
3169///
3170/// The stabilized version of this intrinsic is [`f64::max`].
3171#[rustc_nounwind]
3172#[rustc_intrinsic_const_stable_indirect]
3173#[rustc_intrinsic]
3174pub const fn maxnumf64(x: f64, y: f64) -> f64;
3175
3176/// Returns the maximum of two `f128` values, ignoring NaN.
3177///
3178/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3179/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3180/// and `-0.0`), either input may be returned non-deterministically.
3181///
3182/// Note that, unlike most intrinsics, this is safe to call;
3183/// it does not require an `unsafe` block.
3184/// Therefore, implementations must not require the user to uphold
3185/// any safety invariants.
3186///
3187/// The stabilized version of this intrinsic is [`f128::max`].
3188#[rustc_nounwind]
3189#[rustc_intrinsic]
3190pub const fn maxnumf128(x: f128, y: f128) -> f128;
3191
3192/// Returns the maximum of two `f16` values, propagating NaN.
3193///
3194/// This behaves like IEEE 754-2019 maximum. In particular:
3195/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3196/// For this operation, -0.0 is considered to be strictly less than +0.0.
3197///
3198/// Note that, unlike most intrinsics, this is safe to call;
3199/// it does not require an `unsafe` block.
3200/// Therefore, implementations must not require the user to uphold
3201/// any safety invariants.
3202#[rustc_nounwind]
3203#[rustc_intrinsic]
3204pub const fn maximumf16(x: f16, y: f16) -> f16 {
3205    if x > y {
3206        x
3207    } else if y > x {
3208        y
3209    } else if x == y {
3210        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3211    } else {
3212        x + y
3213    }
3214}
3215
3216/// Returns the maximum of two `f32` values, propagating NaN.
3217///
3218/// This behaves like IEEE 754-2019 maximum. In particular:
3219/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3220/// For this operation, -0.0 is considered to be strictly less than +0.0.
3221///
3222/// Note that, unlike most intrinsics, this is safe to call;
3223/// it does not require an `unsafe` block.
3224/// Therefore, implementations must not require the user to uphold
3225/// any safety invariants.
3226#[rustc_nounwind]
3227#[rustc_intrinsic]
3228pub const fn maximumf32(x: f32, y: f32) -> f32 {
3229    if x > y {
3230        x
3231    } else if y > x {
3232        y
3233    } else if x == y {
3234        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3235    } else {
3236        x + y
3237    }
3238}
3239
3240/// Returns the maximum of two `f64` values, propagating NaN.
3241///
3242/// This behaves like IEEE 754-2019 maximum. In particular:
3243/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3244/// For this operation, -0.0 is considered to be strictly less than +0.0.
3245///
3246/// Note that, unlike most intrinsics, this is safe to call;
3247/// it does not require an `unsafe` block.
3248/// Therefore, implementations must not require the user to uphold
3249/// any safety invariants.
3250#[rustc_nounwind]
3251#[rustc_intrinsic]
3252pub const fn maximumf64(x: f64, y: f64) -> f64 {
3253    if x > y {
3254        x
3255    } else if y > x {
3256        y
3257    } else if x == y {
3258        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3259    } else {
3260        x + y
3261    }
3262}
3263
3264/// Returns the maximum of two `f128` values, propagating NaN.
3265///
3266/// This behaves like IEEE 754-2019 maximum. In particular:
3267/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3268/// For this operation, -0.0 is considered to be strictly less than +0.0.
3269///
3270/// Note that, unlike most intrinsics, this is safe to call;
3271/// it does not require an `unsafe` block.
3272/// Therefore, implementations must not require the user to uphold
3273/// any safety invariants.
3274#[rustc_nounwind]
3275#[rustc_intrinsic]
3276pub const fn maximumf128(x: f128, y: f128) -> f128 {
3277    if x > y {
3278        x
3279    } else if y > x {
3280        y
3281    } else if x == y {
3282        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3283    } else {
3284        x + y
3285    }
3286}
3287
3288/// Returns the absolute value of an `f16`.
3289///
3290/// The stabilized version of this intrinsic is
3291/// [`f16::abs`](../../std/primitive.f16.html#method.abs)
3292#[rustc_nounwind]
3293#[rustc_intrinsic]
3294pub const fn fabsf16(x: f16) -> f16;
3295
3296/// Returns the absolute value of an `f32`.
3297///
3298/// The stabilized version of this intrinsic is
3299/// [`f32::abs`](../../std/primitive.f32.html#method.abs)
3300#[rustc_nounwind]
3301#[rustc_intrinsic_const_stable_indirect]
3302#[rustc_intrinsic]
3303pub const fn fabsf32(x: f32) -> f32;
3304
3305/// Returns the absolute value of an `f64`.
3306///
3307/// The stabilized version of this intrinsic is
3308/// [`f64::abs`](../../std/primitive.f64.html#method.abs)
3309#[rustc_nounwind]
3310#[rustc_intrinsic_const_stable_indirect]
3311#[rustc_intrinsic]
3312pub const fn fabsf64(x: f64) -> f64;
3313
3314/// Returns the absolute value of an `f128`.
3315///
3316/// The stabilized version of this intrinsic is
3317/// [`f128::abs`](../../std/primitive.f128.html#method.abs)
3318#[rustc_nounwind]
3319#[rustc_intrinsic]
3320pub const fn fabsf128(x: f128) -> f128;
3321
3322/// Copies the sign from `y` to `x` for `f16` values.
3323///
3324/// The stabilized version of this intrinsic is
3325/// [`f16::copysign`](../../std/primitive.f16.html#method.copysign)
3326#[rustc_nounwind]
3327#[rustc_intrinsic]
3328pub const fn copysignf16(x: f16, y: f16) -> f16;
3329
3330/// Copies the sign from `y` to `x` for `f32` values.
3331///
3332/// The stabilized version of this intrinsic is
3333/// [`f32::copysign`](../../std/primitive.f32.html#method.copysign)
3334#[rustc_nounwind]
3335#[rustc_intrinsic_const_stable_indirect]
3336#[rustc_intrinsic]
3337pub const fn copysignf32(x: f32, y: f32) -> f32;
3338/// Copies the sign from `y` to `x` for `f64` values.
3339///
3340/// The stabilized version of this intrinsic is
3341/// [`f64::copysign`](../../std/primitive.f64.html#method.copysign)
3342#[rustc_nounwind]
3343#[rustc_intrinsic_const_stable_indirect]
3344#[rustc_intrinsic]
3345pub const fn copysignf64(x: f64, y: f64) -> f64;
3346
3347/// Copies the sign from `y` to `x` for `f128` values.
3348///
3349/// The stabilized version of this intrinsic is
3350/// [`f128::copysign`](../../std/primitive.f128.html#method.copysign)
3351#[rustc_nounwind]
3352#[rustc_intrinsic]
3353pub const fn copysignf128(x: f128, y: f128) -> f128;
3354
3355/// Generates the LLVM body for the automatic differentiation of `f` using Enzyme,
3356/// with `df` as the derivative function and `args` as its arguments.
3357///
3358/// Used internally as the body of `df` when expanding the `#[autodiff_forward]`
3359/// and `#[autodiff_reverse]` attribute macros.
3360///
3361/// Type Parameters:
3362/// - `F`: The original function to differentiate. Must be a function item.
3363/// - `G`: The derivative function. Must be a function item.
3364/// - `T`: A tuple of arguments passed to `df`.
3365/// - `R`: The return type of the derivative function.
3366///
3367/// This shows where the `autodiff` intrinsic is used during macro expansion:
3368///
3369/// ```rust,ignore (macro example)
3370/// #[autodiff_forward(df1, Dual, Const, Dual)]
3371/// pub fn f1(x: &[f64], y: f64) -> f64 {
3372///     unimplemented!()
3373/// }
3374/// ```
3375///
3376/// expands to:
3377///
3378/// ```rust,ignore (macro example)
3379/// #[rustc_autodiff]
3380/// #[inline(never)]
3381/// pub fn f1(x: &[f64], y: f64) -> f64 {
3382///     ::core::panicking::panic("not implemented")
3383/// }
3384/// #[rustc_autodiff(Forward, 1, Dual, Const, Dual)]
3385/// pub fn df1(x: &[f64], bx_0: &[f64], y: f64) -> (f64, f64) {
3386///     ::core::intrinsics::autodiff(f1::<>, df1::<>, (x, bx_0, y))
3387/// }
3388/// ```
3389#[rustc_nounwind]
3390#[rustc_intrinsic]
3391pub const fn autodiff<F, G, T: crate::marker::Tuple, R>(f: F, df: G, args: T) -> R;
3392
3393/// Generates the LLVM body of a wrapper function to offload a kernel `f`.
3394///
3395/// Type Parameters:
3396/// - `F`: The kernel to offload. Must be a function item.
3397/// - `T`: A tuple of arguments passed to `f`.
3398/// - `R`: The return type of the kernel.
3399///
3400/// Arguments:
3401/// - `f`: The kernel function to offload.
3402/// - `workgroup_dim`: A 3D size specifying the number of workgroups to launch.
3403/// - `thread_dim`: A 3D size specifying the number of threads per workgroup.
3404/// - `args`: A tuple of arguments forwarded to `f`.
3405///
3406/// Example usage (pseudocode):
3407///
3408/// ```rust,ignore (pseudocode)
3409/// fn kernel(x: *mut [f64; 128]) {
3410///     core::intrinsics::offload(kernel_1, [256, 1, 1], [32, 1, 1], (x,))
3411/// }
3412///
3413/// #[cfg(target_os = "linux")]
3414/// extern "C" {
3415///     pub fn kernel_1(array_b: *mut [f64; 128]);
3416/// }
3417///
3418/// #[cfg(not(target_os = "linux"))]
3419/// #[rustc_offload_kernel]
3420/// extern "gpu-kernel" fn kernel_1(x: *mut [f64; 128]) {
3421///     unsafe { (*x)[0] = 21.0 };
3422/// }
3423/// ```
3424///
3425/// For reference, see the Clang documentation on offloading:
3426/// <https://clang.llvm.org/docs/OffloadingDesign.html>.
3427#[rustc_nounwind]
3428#[rustc_intrinsic]
3429pub const fn offload<F, T: crate::marker::Tuple, R>(
3430    f: F,
3431    workgroup_dim: [u32; 3],
3432    thread_dim: [u32; 3],
3433    args: T,
3434) -> R;
3435
3436/// Inform Miri that a given pointer definitely has a certain alignment.
3437#[cfg(miri)]
3438#[rustc_allow_const_fn_unstable(const_eval_select)]
3439pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize) {
3440    unsafe extern "Rust" {
3441        /// Miri-provided extern function to promise that a given pointer is properly aligned for
3442        /// "symbolic" alignment checks. Will fail if the pointer is not actually aligned or `align` is
3443        /// not a power of two. Has no effect when alignment checks are concrete (which is the default).
3444        fn miri_promise_symbolic_alignment(ptr: *const (), align: usize);
3445    }
3446
3447    const_eval_select!(
3448        @capture { ptr: *const (), align: usize}:
3449        if const {
3450            // Do nothing.
3451        } else {
3452            // SAFETY: this call is always safe.
3453            unsafe {
3454                miri_promise_symbolic_alignment(ptr, align);
3455            }
3456        }
3457    )
3458}
3459
3460/// Loads an argument of type `T` from the `va_list` `ap` and increment the
3461/// argument `ap` points to.
3462///
3463/// # Safety
3464///
3465/// This function is only sound to call when:
3466///
3467/// - there is a next variable argument available.
3468/// - the next argument's type must be ABI-compatible with the type `T`.
3469/// - the next argument must have a properly initialized value of type `T`.
3470///
3471/// Calling this function with an incompatible type, an invalid value, or when there
3472/// are no more variable arguments, is unsound.
3473///
3474#[rustc_intrinsic]
3475#[rustc_nounwind]
3476pub unsafe fn va_arg<T: VaArgSafe>(ap: &mut VaList<'_>) -> T;
3477
3478/// Duplicates a variable argument list. The returned list is initially at the same position as
3479/// the one in `src`, but can be advanced independently.
3480///
3481/// Codegen backends should not have custom behavior for this intrinsic, they should always use
3482/// this fallback implementation. This intrinsic *does not* map to the LLVM `va_copy` intrinsic.
3483///
3484/// This intrinsic exists only as a hook for Miri and constant evaluation, and is used to detect UB
3485/// when a variable argument list is used incorrectly.
3486#[rustc_intrinsic]
3487#[rustc_nounwind]
3488pub fn va_copy<'f>(src: &VaList<'f>) -> VaList<'f> {
3489    src.duplicate()
3490}
3491
3492/// Destroy the variable argument list `ap` after initialization with `va_start` (part of the
3493/// desugaring of `...`) or `va_copy`.
3494///
3495/// Code generation backends should not provide a custom implementation for this intrinsic. This
3496/// intrinsic *does not* map to the LLVM `va_end` intrinsic.
3497///
3498/// This function is a no-op on all current targets, but used as a hook for const evaluation to
3499/// detect UB when a variable argument list is used incorrectly.
3500///
3501/// # Safety
3502///
3503/// `ap` must not be used to access variable arguments after this call.
3504///
3505#[rustc_intrinsic]
3506#[rustc_nounwind]
3507pub unsafe fn va_end(ap: &mut VaList<'_>) {
3508    /* deliberately does nothing */
3509}