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/// The stabilized version of this intrinsic is [`core::hint::cold_path`].
413#[rustc_intrinsic]
414#[rustc_nounwind]
415#[miri::intrinsic_fallback_is_spec]
416#[cold]
417pub const fn cold_path() {}
418
419/// Hints to the compiler that branch condition is likely to be true.
420/// Returns the value passed to it.
421///
422/// Any use other than with `if` statements will probably not have an effect.
423///
424/// Note that, unlike most intrinsics, this is safe to call;
425/// it does not require an `unsafe` block.
426/// Therefore, implementations must not require the user to uphold
427/// any safety invariants.
428///
429/// This intrinsic does not have a stable counterpart.
430#[unstable(feature = "core_intrinsics", issue = "none")]
431#[rustc_nounwind]
432#[inline(always)]
433pub const fn likely(b: bool) -> bool {
434    if b {
435        true
436    } else {
437        cold_path();
438        false
439    }
440}
441
442/// Hints to the compiler that branch condition is likely to be false.
443/// Returns the value passed to it.
444///
445/// Any use other than with `if` statements will probably not have an effect.
446///
447/// Note that, unlike most intrinsics, this is safe to call;
448/// it does not require an `unsafe` block.
449/// Therefore, implementations must not require the user to uphold
450/// any safety invariants.
451///
452/// This intrinsic does not have a stable counterpart.
453#[unstable(feature = "core_intrinsics", issue = "none")]
454#[rustc_nounwind]
455#[inline(always)]
456pub const fn unlikely(b: bool) -> bool {
457    if b {
458        cold_path();
459        true
460    } else {
461        false
462    }
463}
464
465/// Returns either `true_val` or `false_val` depending on condition `b` with a
466/// hint to the compiler that this condition is unlikely to be correctly
467/// predicted by a CPU's branch predictor (e.g. a binary search).
468///
469/// This is otherwise functionally equivalent to `if b { true_val } else { false_val }`.
470///
471/// Note that, unlike most intrinsics, this is safe to call;
472/// it does not require an `unsafe` block.
473/// Therefore, implementations must not require the user to uphold
474/// any safety invariants.
475///
476/// The public form of this intrinsic is [`core::hint::select_unpredictable`].
477/// However unlike the public form, the intrinsic will not drop the value that
478/// is not selected.
479#[unstable(feature = "core_intrinsics", issue = "none")]
480#[rustc_const_unstable(feature = "const_select_unpredictable", issue = "145938")]
481#[rustc_intrinsic]
482#[rustc_nounwind]
483#[miri::intrinsic_fallback_is_spec]
484#[inline]
485pub const fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
486    if b {
487        forget(false_val);
488        true_val
489    } else {
490        forget(true_val);
491        false_val
492    }
493}
494
495/// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited:
496/// This will statically either panic, or do nothing. It does not *guarantee* to ever panic,
497/// and should only be called if an assertion failure will imply language UB in the following code.
498///
499/// This intrinsic does not have a stable counterpart.
500#[rustc_intrinsic_const_stable_indirect]
501#[rustc_nounwind]
502#[rustc_intrinsic]
503pub const fn assert_inhabited<T>();
504
505/// A guard for unsafe functions that cannot ever be executed if `T` does not permit
506/// zero-initialization: This will statically either panic, or do nothing. It does not *guarantee*
507/// to ever panic, and should only be called if an assertion failure will imply language UB in the
508/// following code.
509///
510/// This intrinsic does not have a stable counterpart.
511#[rustc_intrinsic_const_stable_indirect]
512#[rustc_nounwind]
513#[rustc_intrinsic]
514pub const fn assert_zero_valid<T>();
515
516/// A guard for `std::mem::uninitialized`. This will statically either panic, or do nothing. It does
517/// not *guarantee* to ever panic, and should only be called if an assertion failure will imply
518/// language UB in the following code.
519///
520/// This intrinsic does not have a stable counterpart.
521#[rustc_intrinsic_const_stable_indirect]
522#[rustc_nounwind]
523#[rustc_intrinsic]
524pub const fn assert_mem_uninitialized_valid<T>();
525
526/// Gets a reference to a static `Location` indicating where it was called.
527///
528/// Note that, unlike most intrinsics, this is safe to call;
529/// it does not require an `unsafe` block.
530/// Therefore, implementations must not require the user to uphold
531/// any safety invariants.
532///
533/// Consider using [`core::panic::Location::caller`] instead.
534#[rustc_intrinsic_const_stable_indirect]
535#[rustc_nounwind]
536#[rustc_intrinsic]
537pub const fn caller_location() -> &'static crate::panic::Location<'static>;
538
539/// Moves a value out of scope without running drop glue.
540///
541/// This exists solely for [`crate::mem::forget_unsized`]; normal `forget` uses
542/// `ManuallyDrop` instead.
543///
544/// Note that, unlike most intrinsics, this is safe to call;
545/// it does not require an `unsafe` block.
546/// Therefore, implementations must not require the user to uphold
547/// any safety invariants.
548#[rustc_intrinsic_const_stable_indirect]
549#[rustc_nounwind]
550#[rustc_intrinsic]
551pub const fn forget<T: ?Sized>(_: T);
552
553/// Reinterprets the bits of a value of one type as another type.
554///
555/// Both types must have the same size. Compilation will fail if this is not guaranteed.
556///
557/// `transmute` is semantically equivalent to a bitwise move of one type
558/// into another. It copies the bits from the source value into the
559/// destination value, then forgets the original. Note that source and destination
560/// are passed by-value, which means if `Src` or `Dst` contain padding, that padding
561/// is *not* guaranteed to be preserved by `transmute`.
562///
563/// Both the argument and the result must be [valid](../../nomicon/what-unsafe-does.html) at
564/// their given type. Violating this condition leads to [undefined behavior][ub]. The compiler
565/// will generate code *assuming that you, the programmer, ensure that there will never be
566/// undefined behavior*. It is therefore your responsibility to guarantee that every value
567/// passed to `transmute` is valid at both types `Src` and `Dst`. Failing to uphold this condition
568/// may lead to unexpected and unstable compilation results. This makes `transmute` **incredibly
569/// unsafe**. `transmute` should be the absolute last resort.
570///
571/// Because `transmute` is a by-value operation, alignment of the *transmuted values
572/// themselves* is not a concern. As with any other function, the compiler already ensures
573/// both `Src` and `Dst` are properly aligned. However, when transmuting values that *point
574/// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper
575/// alignment of the pointed-to values.
576///
577/// The [nomicon](../../nomicon/transmutes.html) has additional documentation.
578///
579/// [ub]: ../../reference/behavior-considered-undefined.html
580///
581/// # Transmutation between pointers and integers
582///
583/// Special care has to be taken when transmuting between pointers and integers, e.g.
584/// transmuting between `*const ()` and `usize`.
585///
586/// Transmuting *pointers to integers* in a `const` context is [undefined behavior][ub], unless
587/// the pointer was originally created *from* an integer. (That includes this function
588/// specifically, integer-to-pointer casts, and helpers like [`dangling`][crate::ptr::dangling],
589/// but also semantically-equivalent conversions such as punning through `repr(C)` union
590/// fields.) Any attempt to use the resulting value for integer operations will abort
591/// const-evaluation. (And even outside `const`, such transmutation is touching on many
592/// unspecified aspects of the Rust memory model and should be avoided. See below for
593/// alternatives.)
594///
595/// Transmuting *integers to pointers* is a largely unspecified operation. It is likely *not*
596/// equivalent to an `as` cast. Doing non-zero-sized memory accesses with a pointer constructed
597/// this way is currently considered undefined behavior.
598///
599/// All this also applies when the integer is nested inside an array, tuple, struct, or enum.
600/// However, `MaybeUninit<usize>` is not considered an integer type for the purpose of this
601/// section. Transmuting `*const ()` to `MaybeUninit<usize>` is fine---but then calling
602/// `assume_init()` on that result is considered as completing the pointer-to-integer transmute
603/// and thus runs into the issues discussed above.
604///
605/// In particular, doing a pointer-to-integer-to-pointer roundtrip via `transmute` is *not* a
606/// lossless process. If you want to round-trip a pointer through an integer in a way that you
607/// can get back the original pointer, you need to use `as` casts, or replace the integer type
608/// by `MaybeUninit<$int>` (and never call `assume_init()`). If you are looking for a way to
609/// store data of arbitrary type, also use `MaybeUninit<T>` (that will also handle uninitialized
610/// memory due to padding). If you specifically need to store something that is "either an
611/// integer or a pointer", use `*mut ()`: integers can be converted to pointers and back without
612/// any loss (via `as` casts or via `transmute`).
613///
614/// # Examples
615///
616/// There are a few things that `transmute` is really useful for.
617///
618/// Turning a pointer into a function pointer. This is *not* portable to
619/// machines where function pointers and data pointers have different sizes.
620///
621/// ```
622/// fn foo() -> i32 {
623///     0
624/// }
625/// // Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
626/// // This avoids an integer-to-pointer `transmute`, which can be problematic.
627/// // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
628/// let pointer = foo as fn() -> i32 as *const ();
629/// let function = unsafe {
630///     std::mem::transmute::<*const (), fn() -> i32>(pointer)
631/// };
632/// assert_eq!(function(), 0);
633/// ```
634///
635/// Extending a lifetime, or shortening an invariant lifetime. This is
636/// advanced, very unsafe Rust!
637///
638/// ```
639/// struct R<'a>(&'a i32);
640/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
641///     unsafe { std::mem::transmute::<R<'b>, R<'static>>(r) }
642/// }
643///
644/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
645///                                              -> &'b mut R<'c> {
646///     unsafe { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) }
647/// }
648/// ```
649///
650/// # Alternatives
651///
652/// Don't despair: many uses of `transmute` can be achieved through other means.
653/// Below are common applications of `transmute` which can be replaced with safer
654/// constructs.
655///
656/// Turning raw bytes (`[u8; SZ]`) into `u32`, `f64`, etc.:
657///
658/// ```
659/// # #![allow(unnecessary_transmutes)]
660/// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
661///
662/// let num = unsafe {
663///     std::mem::transmute::<[u8; 4], u32>(raw_bytes)
664/// };
665///
666/// // use `u32::from_ne_bytes` instead
667/// let num = u32::from_ne_bytes(raw_bytes);
668/// // or use `u32::from_le_bytes` or `u32::from_be_bytes` to specify the endianness
669/// let num = u32::from_le_bytes(raw_bytes);
670/// assert_eq!(num, 0x12345678);
671/// let num = u32::from_be_bytes(raw_bytes);
672/// assert_eq!(num, 0x78563412);
673/// ```
674///
675/// Turning a pointer into a `usize`:
676///
677/// ```no_run
678/// let ptr = &0;
679/// let ptr_num_transmute = unsafe {
680///     std::mem::transmute::<&i32, usize>(ptr)
681/// };
682///
683/// // Use an `as` cast instead
684/// let ptr_num_cast = ptr as *const i32 as usize;
685/// ```
686///
687/// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined
688/// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave
689/// as expected -- this is touching on many unspecified aspects of the Rust memory model.
690/// Depending on what the code is doing, the following alternatives are preferable to
691/// pointer-to-integer transmutation:
692/// - If the code just wants to store data of arbitrary type in some buffer and needs to pick a
693///   type for that buffer, it can use [`MaybeUninit`][crate::mem::MaybeUninit].
694/// - If the code actually wants to work on the address the pointer points to, it can use `as`
695///   casts or [`ptr.addr()`][pointer::addr].
696///
697/// Turning a `*mut T` into a `&mut T`:
698///
699/// ```
700/// let ptr: *mut i32 = &mut 0;
701/// let ref_transmuted = unsafe {
702///     std::mem::transmute::<*mut i32, &mut i32>(ptr)
703/// };
704///
705/// // Use a reborrow instead
706/// let ref_casted = unsafe { &mut *ptr };
707/// ```
708///
709/// Turning a `&mut T` into a `&mut U`:
710///
711/// ```
712/// let ptr = &mut 0;
713/// let val_transmuted = unsafe {
714///     std::mem::transmute::<&mut i32, &mut u32>(ptr)
715/// };
716///
717/// // Now, put together `as` and reborrowing - note the chaining of `as`
718/// // `as` is not transitive
719/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
720/// ```
721///
722/// Turning a `&str` into a `&[u8]`:
723///
724/// ```
725/// // this is not a good way to do this.
726/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
727/// assert_eq!(slice, &[82, 117, 115, 116]);
728///
729/// // You could use `str::as_bytes`
730/// let slice = "Rust".as_bytes();
731/// assert_eq!(slice, &[82, 117, 115, 116]);
732///
733/// // Or, just use a byte string, if you have control over the string
734/// // literal
735/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
736/// ```
737///
738/// Turning a `Vec<&T>` into a `Vec<Option<&T>>`.
739///
740/// To transmute the inner type of the contents of a container, you must make sure to not
741/// violate any of the container's invariants. For `Vec`, this means that both the size
742/// *and alignment* of the inner types have to match. Other containers might rely on the
743/// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't
744/// be possible at all without violating the container invariants.
745///
746/// ```
747/// let store = [0, 1, 2, 3];
748/// let v_orig = store.iter().collect::<Vec<&i32>>();
749///
750/// // clone the vector as we will reuse them later
751/// let v_clone = v_orig.clone();
752///
753/// // Using transmute: this relies on the unspecified data layout of `Vec`, which is a
754/// // bad idea and could cause Undefined Behavior.
755/// // However, it is no-copy.
756/// let v_transmuted = unsafe {
757///     std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(v_clone)
758/// };
759///
760/// let v_clone = v_orig.clone();
761///
762/// // This is the suggested, safe way.
763/// // It may copy the entire vector into a new one though, but also may not.
764/// let v_collected = v_clone.into_iter()
765///                          .map(Some)
766///                          .collect::<Vec<Option<&i32>>>();
767///
768/// let v_clone = v_orig.clone();
769///
770/// // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the
771/// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but
772/// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`),
773/// // this has all the same caveats. Besides the information provided above, also consult the
774/// // [`from_raw_parts`] documentation.
775/// let (ptr, len, capacity) = v_clone.into_raw_parts();
776/// let v_from_raw = unsafe {
777///     Vec::from_raw_parts(ptr.cast::<*mut Option<&i32>>(), len, capacity)
778/// };
779/// ```
780///
781/// [`from_raw_parts`]: ../../std/vec/struct.Vec.html#method.from_raw_parts
782///
783/// Implementing `split_at_mut`:
784///
785/// ```
786/// use std::{slice, mem};
787///
788/// // There are multiple ways to do this, and there are multiple problems
789/// // with the following (transmute) way.
790/// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
791///                              -> (&mut [T], &mut [T]) {
792///     let len = slice.len();
793///     assert!(mid <= len);
794///     unsafe {
795///         let slice2 = mem::transmute::<&mut [T], &mut [T]>(slice);
796///         // first: transmute is not type safe; all it checks is that T and
797///         // U are of the same size. Second, right here, you have two
798///         // mutable references pointing to the same memory.
799///         (&mut slice[0..mid], &mut slice2[mid..len])
800///     }
801/// }
802///
803/// // This gets rid of the type safety problems; `&mut *` will *only* give
804/// // you a `&mut T` from a `&mut T` or `*mut T`.
805/// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
806///                          -> (&mut [T], &mut [T]) {
807///     let len = slice.len();
808///     assert!(mid <= len);
809///     unsafe {
810///         let slice2 = &mut *(slice as *mut [T]);
811///         // however, you still have two mutable references pointing to
812///         // the same memory.
813///         (&mut slice[0..mid], &mut slice2[mid..len])
814///     }
815/// }
816///
817/// // This is how the standard library does it. This is the best method, if
818/// // you need to do something like this
819/// fn split_at_stdlib<T>(slice: &mut [T], mid: usize)
820///                       -> (&mut [T], &mut [T]) {
821///     let len = slice.len();
822///     assert!(mid <= len);
823///     unsafe {
824///         let ptr = slice.as_mut_ptr();
825///         // This now has three mutable references pointing at the same
826///         // memory. `slice`, the rvalue ret.0, and the rvalue ret.1.
827///         // `slice` is never used after `let ptr = ...`, and so one can
828///         // treat it as "dead", and therefore, you only have two real
829///         // mutable slices.
830///         (slice::from_raw_parts_mut(ptr, mid),
831///          slice::from_raw_parts_mut(ptr.add(mid), len - mid))
832///     }
833/// }
834/// ```
835#[stable(feature = "rust1", since = "1.0.0")]
836#[rustc_allowed_through_unstable_modules = "import this function via `std::mem` instead"]
837#[rustc_const_stable(feature = "const_transmute", since = "1.56.0")]
838#[rustc_diagnostic_item = "transmute"]
839#[rustc_nounwind]
840#[rustc_intrinsic]
841pub const unsafe fn transmute<Src, Dst>(src: Src) -> Dst;
842
843/// Like [`transmute`], but even less checked at compile-time: rather than
844/// giving an error for `size_of::<Src>() != size_of::<Dst>()`, it's
845/// **Undefined Behavior** at runtime.
846///
847/// Prefer normal `transmute` where possible, for the extra checking, since
848/// both do exactly the same thing at runtime, if they both compile.
849///
850/// This is not expected to ever be exposed directly to users, rather it
851/// may eventually be exposed through some more-constrained API.
852#[rustc_intrinsic_const_stable_indirect]
853#[rustc_nounwind]
854#[rustc_intrinsic]
855pub const unsafe fn transmute_unchecked<Src, Dst>(src: Src) -> Dst;
856
857/// Returns `true` if the actual type given as `T` requires drop
858/// glue; returns `false` if the actual type provided for `T`
859/// implements `Copy`.
860///
861/// If the actual type neither requires drop glue nor implements
862/// `Copy`, then the return value of this function is unspecified.
863///
864/// Note that, unlike most intrinsics, this can only be called at compile-time
865/// as backends do not have an implementation for it. The only caller (its
866/// stable counterpart) wraps this intrinsic call in a `const` block so that
867/// backends only see an evaluated constant.
868///
869/// The stabilized version of this intrinsic is [`mem::needs_drop`](crate::mem::needs_drop).
870#[rustc_intrinsic_const_stable_indirect]
871#[rustc_nounwind]
872#[rustc_intrinsic]
873pub const fn needs_drop<T: ?Sized>() -> bool;
874
875/// Calculates the offset from a pointer.
876///
877/// This is implemented as an intrinsic to avoid converting to and from an
878/// integer, since the conversion would throw away aliasing information.
879///
880/// This can only be used with `Ptr` as a raw pointer type (`*mut` or `*const`)
881/// to a `Sized` pointee and with `Delta` as `usize` or `isize`.  Any other
882/// instantiations may arbitrarily misbehave, and that's *not* a compiler bug.
883///
884/// # Safety
885///
886/// If the computed offset is non-zero, then both the starting and resulting pointer must be
887/// either in bounds or at the end of an allocation. If either pointer is out
888/// of bounds or arithmetic overflow occurs then this operation is undefined behavior.
889///
890/// The stabilized version of this intrinsic is [`pointer::offset`].
891#[must_use = "returns a new pointer rather than modifying its argument"]
892#[rustc_intrinsic_const_stable_indirect]
893#[rustc_nounwind]
894#[rustc_intrinsic]
895pub const unsafe fn offset<Ptr: bounds::BuiltinDeref, Delta>(dst: Ptr, offset: Delta) -> Ptr;
896
897/// Calculates the offset from a pointer, potentially wrapping.
898///
899/// This is implemented as an intrinsic to avoid converting to and from an
900/// integer, since the conversion inhibits certain optimizations.
901///
902/// # Safety
903///
904/// Unlike the `offset` intrinsic, this intrinsic does not restrict the
905/// resulting pointer to point into or at the end of an allocated
906/// object, and it wraps with two's complement arithmetic. The resulting
907/// value is not necessarily valid to be used to actually access memory.
908///
909/// The stabilized version of this intrinsic is [`pointer::wrapping_offset`].
910#[must_use = "returns a new pointer rather than modifying its argument"]
911#[rustc_intrinsic_const_stable_indirect]
912#[rustc_nounwind]
913#[rustc_intrinsic]
914pub const unsafe fn arith_offset<T>(dst: *const T, offset: isize) -> *const T;
915
916/// Projects to the `index`-th element of `slice_ptr`, as the same kind of pointer
917/// as the slice was provided -- so `&mut [T] → &mut T`, `&[T] → &T`,
918/// `*mut [T] → *mut T`, or `*const [T] → *const T` -- without a bounds check.
919///
920/// This is exposed via `<usize as SliceIndex>::get(_unchecked)(_mut)`,
921/// and isn't intended to be used elsewhere.
922///
923/// Expands in MIR to `{&, &mut, &raw const, &raw mut} (*slice_ptr)[index]`,
924/// depending on the types involved, so no backend support is needed.
925///
926/// # Safety
927///
928/// - `index < PtrMetadata(slice_ptr)`, so the indexing is in-bounds for the slice
929/// - the resulting offsetting is in-bounds of the allocation, which is
930///   always the case for references, but needs to be upheld manually for pointers
931#[rustc_nounwind]
932#[rustc_intrinsic]
933pub const unsafe fn slice_get_unchecked<
934    ItemPtr: bounds::ChangePointee<[T], Pointee = T, Output = SlicePtr>,
935    SlicePtr,
936    T,
937>(
938    slice_ptr: SlicePtr,
939    index: usize,
940) -> ItemPtr;
941
942/// Masks out bits of the pointer according to a mask.
943///
944/// Note that, unlike most intrinsics, this is safe to call;
945/// it does not require an `unsafe` block.
946/// Therefore, implementations must not require the user to uphold
947/// any safety invariants.
948///
949/// Consider using [`pointer::mask`] instead.
950#[rustc_nounwind]
951#[rustc_intrinsic]
952pub fn ptr_mask<T>(ptr: *const T, mask: usize) -> *const T;
953
954/// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with
955/// a size of `count` * `size_of::<T>()` and an alignment of `align_of::<T>()`.
956///
957/// This intrinsic does not have a stable counterpart.
958/// # Safety
959///
960/// The safety requirements are consistent with [`copy_nonoverlapping`]
961/// while the read and write behaviors are volatile,
962/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
963///
964/// [`copy_nonoverlapping`]: ptr::copy_nonoverlapping
965#[rustc_intrinsic]
966#[rustc_nounwind]
967pub unsafe fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize);
968/// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with
969/// a size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
970///
971/// The volatile parameter is set to `true`, so it will not be optimized out
972/// unless size is equal to zero.
973///
974/// This intrinsic does not have a stable counterpart.
975#[rustc_intrinsic]
976#[rustc_nounwind]
977pub unsafe fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize);
978/// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a
979/// size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
980///
981/// This intrinsic does not have a stable counterpart.
982/// # Safety
983///
984/// The safety requirements are consistent with [`write_bytes`] while the write behavior is volatile,
985/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
986///
987/// [`write_bytes`]: ptr::write_bytes
988#[rustc_intrinsic]
989#[rustc_nounwind]
990pub unsafe fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize);
991
992/// Performs a volatile load from the `src` pointer.
993///
994/// The stabilized version of this intrinsic is [`core::ptr::read_volatile`].
995#[rustc_intrinsic]
996#[rustc_nounwind]
997pub unsafe fn volatile_load<T>(src: *const T) -> T;
998/// Performs a volatile store to the `dst` pointer.
999///
1000/// The stabilized version of this intrinsic is [`core::ptr::write_volatile`].
1001#[rustc_intrinsic]
1002#[rustc_nounwind]
1003pub unsafe fn volatile_store<T>(dst: *mut T, val: T);
1004
1005/// Performs a volatile load from the `src` pointer
1006/// The pointer is not required to be aligned.
1007///
1008/// This intrinsic does not have a stable counterpart.
1009#[rustc_intrinsic]
1010#[rustc_nounwind]
1011#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_load"]
1012pub unsafe fn unaligned_volatile_load<T>(src: *const T) -> T;
1013/// Performs a volatile store to the `dst` pointer.
1014/// The pointer is not required to be aligned.
1015///
1016/// This intrinsic does not have a stable counterpart.
1017#[rustc_intrinsic]
1018#[rustc_nounwind]
1019#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_store"]
1020pub unsafe fn unaligned_volatile_store<T>(dst: *mut T, val: T);
1021
1022/// Returns the square root of an `f16`
1023///
1024/// The stabilized version of this intrinsic is
1025/// [`f16::sqrt`](../../std/primitive.f16.html#method.sqrt)
1026#[rustc_intrinsic]
1027#[rustc_nounwind]
1028pub fn sqrtf16(x: f16) -> f16;
1029/// Returns the square root of an `f32`
1030///
1031/// The stabilized version of this intrinsic is
1032/// [`f32::sqrt`](../../std/primitive.f32.html#method.sqrt)
1033#[rustc_intrinsic]
1034#[rustc_nounwind]
1035pub fn sqrtf32(x: f32) -> f32;
1036/// Returns the square root of an `f64`
1037///
1038/// The stabilized version of this intrinsic is
1039/// [`f64::sqrt`](../../std/primitive.f64.html#method.sqrt)
1040#[rustc_intrinsic]
1041#[rustc_nounwind]
1042pub fn sqrtf64(x: f64) -> f64;
1043/// Returns the square root of an `f128`
1044///
1045/// The stabilized version of this intrinsic is
1046/// [`f128::sqrt`](../../std/primitive.f128.html#method.sqrt)
1047#[rustc_intrinsic]
1048#[rustc_nounwind]
1049pub fn sqrtf128(x: f128) -> f128;
1050
1051/// Raises an `f16` to an integer power.
1052///
1053/// The stabilized version of this intrinsic is
1054/// [`f16::powi`](../../std/primitive.f16.html#method.powi)
1055#[rustc_intrinsic]
1056#[rustc_nounwind]
1057pub fn powif16(a: f16, x: i32) -> f16;
1058/// Raises an `f32` to an integer power.
1059///
1060/// The stabilized version of this intrinsic is
1061/// [`f32::powi`](../../std/primitive.f32.html#method.powi)
1062#[rustc_intrinsic]
1063#[rustc_nounwind]
1064pub fn powif32(a: f32, x: i32) -> f32;
1065/// Raises an `f64` to an integer power.
1066///
1067/// The stabilized version of this intrinsic is
1068/// [`f64::powi`](../../std/primitive.f64.html#method.powi)
1069#[rustc_intrinsic]
1070#[rustc_nounwind]
1071pub fn powif64(a: f64, x: i32) -> f64;
1072/// Raises an `f128` to an integer power.
1073///
1074/// The stabilized version of this intrinsic is
1075/// [`f128::powi`](../../std/primitive.f128.html#method.powi)
1076#[rustc_intrinsic]
1077#[rustc_nounwind]
1078pub fn powif128(a: f128, x: i32) -> f128;
1079
1080/// Returns the sine of an `f16`.
1081///
1082/// The stabilized version of this intrinsic is
1083/// [`f16::sin`](../../std/primitive.f16.html#method.sin)
1084#[rustc_intrinsic]
1085#[rustc_nounwind]
1086pub fn sinf16(x: f16) -> f16;
1087/// Returns the sine of an `f32`.
1088///
1089/// The stabilized version of this intrinsic is
1090/// [`f32::sin`](../../std/primitive.f32.html#method.sin)
1091#[rustc_intrinsic]
1092#[rustc_nounwind]
1093pub fn sinf32(x: f32) -> f32;
1094/// Returns the sine of an `f64`.
1095///
1096/// The stabilized version of this intrinsic is
1097/// [`f64::sin`](../../std/primitive.f64.html#method.sin)
1098#[rustc_intrinsic]
1099#[rustc_nounwind]
1100pub fn sinf64(x: f64) -> f64;
1101/// Returns the sine of an `f128`.
1102///
1103/// The stabilized version of this intrinsic is
1104/// [`f128::sin`](../../std/primitive.f128.html#method.sin)
1105#[rustc_intrinsic]
1106#[rustc_nounwind]
1107pub fn sinf128(x: f128) -> f128;
1108
1109/// Returns the cosine of an `f16`.
1110///
1111/// The stabilized version of this intrinsic is
1112/// [`f16::cos`](../../std/primitive.f16.html#method.cos)
1113#[rustc_intrinsic]
1114#[rustc_nounwind]
1115pub fn cosf16(x: f16) -> f16;
1116/// Returns the cosine of an `f32`.
1117///
1118/// The stabilized version of this intrinsic is
1119/// [`f32::cos`](../../std/primitive.f32.html#method.cos)
1120#[rustc_intrinsic]
1121#[rustc_nounwind]
1122pub fn cosf32(x: f32) -> f32;
1123/// Returns the cosine of an `f64`.
1124///
1125/// The stabilized version of this intrinsic is
1126/// [`f64::cos`](../../std/primitive.f64.html#method.cos)
1127#[rustc_intrinsic]
1128#[rustc_nounwind]
1129pub fn cosf64(x: f64) -> f64;
1130/// Returns the cosine of an `f128`.
1131///
1132/// The stabilized version of this intrinsic is
1133/// [`f128::cos`](../../std/primitive.f128.html#method.cos)
1134#[rustc_intrinsic]
1135#[rustc_nounwind]
1136pub fn cosf128(x: f128) -> f128;
1137
1138/// Raises an `f16` to an `f16` power.
1139///
1140/// The stabilized version of this intrinsic is
1141/// [`f16::powf`](../../std/primitive.f16.html#method.powf)
1142#[rustc_intrinsic]
1143#[rustc_nounwind]
1144pub fn powf16(a: f16, x: f16) -> f16;
1145/// Raises an `f32` to an `f32` power.
1146///
1147/// The stabilized version of this intrinsic is
1148/// [`f32::powf`](../../std/primitive.f32.html#method.powf)
1149#[rustc_intrinsic]
1150#[rustc_nounwind]
1151pub fn powf32(a: f32, x: f32) -> f32;
1152/// Raises an `f64` to an `f64` power.
1153///
1154/// The stabilized version of this intrinsic is
1155/// [`f64::powf`](../../std/primitive.f64.html#method.powf)
1156#[rustc_intrinsic]
1157#[rustc_nounwind]
1158pub fn powf64(a: f64, x: f64) -> f64;
1159/// Raises an `f128` to an `f128` power.
1160///
1161/// The stabilized version of this intrinsic is
1162/// [`f128::powf`](../../std/primitive.f128.html#method.powf)
1163#[rustc_intrinsic]
1164#[rustc_nounwind]
1165pub fn powf128(a: f128, x: f128) -> f128;
1166
1167/// Returns the exponential of an `f16`.
1168///
1169/// The stabilized version of this intrinsic is
1170/// [`f16::exp`](../../std/primitive.f16.html#method.exp)
1171#[rustc_intrinsic]
1172#[rustc_nounwind]
1173pub fn expf16(x: f16) -> f16;
1174/// Returns the exponential of an `f32`.
1175///
1176/// The stabilized version of this intrinsic is
1177/// [`f32::exp`](../../std/primitive.f32.html#method.exp)
1178#[rustc_intrinsic]
1179#[rustc_nounwind]
1180pub fn expf32(x: f32) -> f32;
1181/// Returns the exponential of an `f64`.
1182///
1183/// The stabilized version of this intrinsic is
1184/// [`f64::exp`](../../std/primitive.f64.html#method.exp)
1185#[rustc_intrinsic]
1186#[rustc_nounwind]
1187pub fn expf64(x: f64) -> f64;
1188/// Returns the exponential of an `f128`.
1189///
1190/// The stabilized version of this intrinsic is
1191/// [`f128::exp`](../../std/primitive.f128.html#method.exp)
1192#[rustc_intrinsic]
1193#[rustc_nounwind]
1194pub fn expf128(x: f128) -> f128;
1195
1196/// Returns 2 raised to the power of an `f16`.
1197///
1198/// The stabilized version of this intrinsic is
1199/// [`f16::exp2`](../../std/primitive.f16.html#method.exp2)
1200#[rustc_intrinsic]
1201#[rustc_nounwind]
1202pub fn exp2f16(x: f16) -> f16;
1203/// Returns 2 raised to the power of an `f32`.
1204///
1205/// The stabilized version of this intrinsic is
1206/// [`f32::exp2`](../../std/primitive.f32.html#method.exp2)
1207#[rustc_intrinsic]
1208#[rustc_nounwind]
1209pub fn exp2f32(x: f32) -> f32;
1210/// Returns 2 raised to the power of an `f64`.
1211///
1212/// The stabilized version of this intrinsic is
1213/// [`f64::exp2`](../../std/primitive.f64.html#method.exp2)
1214#[rustc_intrinsic]
1215#[rustc_nounwind]
1216pub fn exp2f64(x: f64) -> f64;
1217/// Returns 2 raised to the power of an `f128`.
1218///
1219/// The stabilized version of this intrinsic is
1220/// [`f128::exp2`](../../std/primitive.f128.html#method.exp2)
1221#[rustc_intrinsic]
1222#[rustc_nounwind]
1223pub fn exp2f128(x: f128) -> f128;
1224
1225/// Returns the natural logarithm of an `f16`.
1226///
1227/// The stabilized version of this intrinsic is
1228/// [`f16::ln`](../../std/primitive.f16.html#method.ln)
1229#[rustc_intrinsic]
1230#[rustc_nounwind]
1231pub fn logf16(x: f16) -> f16;
1232/// Returns the natural logarithm of an `f32`.
1233///
1234/// The stabilized version of this intrinsic is
1235/// [`f32::ln`](../../std/primitive.f32.html#method.ln)
1236#[rustc_intrinsic]
1237#[rustc_nounwind]
1238pub fn logf32(x: f32) -> f32;
1239/// Returns the natural logarithm of an `f64`.
1240///
1241/// The stabilized version of this intrinsic is
1242/// [`f64::ln`](../../std/primitive.f64.html#method.ln)
1243#[rustc_intrinsic]
1244#[rustc_nounwind]
1245pub fn logf64(x: f64) -> f64;
1246/// Returns the natural logarithm of an `f128`.
1247///
1248/// The stabilized version of this intrinsic is
1249/// [`f128::ln`](../../std/primitive.f128.html#method.ln)
1250#[rustc_intrinsic]
1251#[rustc_nounwind]
1252pub fn logf128(x: f128) -> f128;
1253
1254/// Returns the base 10 logarithm of an `f16`.
1255///
1256/// The stabilized version of this intrinsic is
1257/// [`f16::log10`](../../std/primitive.f16.html#method.log10)
1258#[rustc_intrinsic]
1259#[rustc_nounwind]
1260pub fn log10f16(x: f16) -> f16;
1261/// Returns the base 10 logarithm of an `f32`.
1262///
1263/// The stabilized version of this intrinsic is
1264/// [`f32::log10`](../../std/primitive.f32.html#method.log10)
1265#[rustc_intrinsic]
1266#[rustc_nounwind]
1267pub fn log10f32(x: f32) -> f32;
1268/// Returns the base 10 logarithm of an `f64`.
1269///
1270/// The stabilized version of this intrinsic is
1271/// [`f64::log10`](../../std/primitive.f64.html#method.log10)
1272#[rustc_intrinsic]
1273#[rustc_nounwind]
1274pub fn log10f64(x: f64) -> f64;
1275/// Returns the base 10 logarithm of an `f128`.
1276///
1277/// The stabilized version of this intrinsic is
1278/// [`f128::log10`](../../std/primitive.f128.html#method.log10)
1279#[rustc_intrinsic]
1280#[rustc_nounwind]
1281pub fn log10f128(x: f128) -> f128;
1282
1283/// Returns the base 2 logarithm of an `f16`.
1284///
1285/// The stabilized version of this intrinsic is
1286/// [`f16::log2`](../../std/primitive.f16.html#method.log2)
1287#[rustc_intrinsic]
1288#[rustc_nounwind]
1289pub fn log2f16(x: f16) -> f16;
1290/// Returns the base 2 logarithm of an `f32`.
1291///
1292/// The stabilized version of this intrinsic is
1293/// [`f32::log2`](../../std/primitive.f32.html#method.log2)
1294#[rustc_intrinsic]
1295#[rustc_nounwind]
1296pub fn log2f32(x: f32) -> f32;
1297/// Returns the base 2 logarithm of an `f64`.
1298///
1299/// The stabilized version of this intrinsic is
1300/// [`f64::log2`](../../std/primitive.f64.html#method.log2)
1301#[rustc_intrinsic]
1302#[rustc_nounwind]
1303pub fn log2f64(x: f64) -> f64;
1304/// Returns the base 2 logarithm of an `f128`.
1305///
1306/// The stabilized version of this intrinsic is
1307/// [`f128::log2`](../../std/primitive.f128.html#method.log2)
1308#[rustc_intrinsic]
1309#[rustc_nounwind]
1310pub fn log2f128(x: f128) -> f128;
1311
1312/// Returns `a * b + c` for `f16` values.
1313///
1314/// The stabilized version of this intrinsic is
1315/// [`f16::mul_add`](../../std/primitive.f16.html#method.mul_add)
1316#[rustc_intrinsic_const_stable_indirect]
1317#[rustc_intrinsic]
1318#[rustc_nounwind]
1319pub const fn fmaf16(a: f16, b: f16, c: f16) -> f16;
1320/// Returns `a * b + c` for `f32` values.
1321///
1322/// The stabilized version of this intrinsic is
1323/// [`f32::mul_add`](../../std/primitive.f32.html#method.mul_add)
1324#[rustc_intrinsic_const_stable_indirect]
1325#[rustc_intrinsic]
1326#[rustc_nounwind]
1327pub const fn fmaf32(a: f32, b: f32, c: f32) -> f32;
1328/// Returns `a * b + c` for `f64` values.
1329///
1330/// The stabilized version of this intrinsic is
1331/// [`f64::mul_add`](../../std/primitive.f64.html#method.mul_add)
1332#[rustc_intrinsic_const_stable_indirect]
1333#[rustc_intrinsic]
1334#[rustc_nounwind]
1335pub const fn fmaf64(a: f64, b: f64, c: f64) -> f64;
1336/// Returns `a * b + c` for `f128` values.
1337///
1338/// The stabilized version of this intrinsic is
1339/// [`f128::mul_add`](../../std/primitive.f128.html#method.mul_add)
1340#[rustc_intrinsic_const_stable_indirect]
1341#[rustc_intrinsic]
1342#[rustc_nounwind]
1343pub const fn fmaf128(a: f128, b: f128, c: f128) -> f128;
1344
1345/// Returns `a * b + c` for `f16` values, non-deterministically executing
1346/// either a fused multiply-add or two operations with rounding of the
1347/// intermediate result.
1348///
1349/// The operation is fused if the code generator determines that target
1350/// instruction set has support for a fused operation, and that the fused
1351/// operation is more efficient than the equivalent, separate pair of mul
1352/// and add instructions. It is unspecified whether or not a fused operation
1353/// is selected, and that may depend on optimization level and context, for
1354/// example.
1355#[rustc_intrinsic]
1356#[rustc_nounwind]
1357pub const fn fmuladdf16(a: f16, b: f16, c: f16) -> f16;
1358/// Returns `a * b + c` for `f32` values, non-deterministically executing
1359/// either a fused multiply-add or two operations with rounding of the
1360/// intermediate result.
1361///
1362/// The operation is fused if the code generator determines that target
1363/// instruction set has support for a fused operation, and that the fused
1364/// operation is more efficient than the equivalent, separate pair of mul
1365/// and add instructions. It is unspecified whether or not a fused operation
1366/// is selected, and that may depend on optimization level and context, for
1367/// example.
1368#[rustc_intrinsic]
1369#[rustc_nounwind]
1370pub const fn fmuladdf32(a: f32, b: f32, c: f32) -> f32;
1371/// Returns `a * b + c` for `f64` values, non-deterministically executing
1372/// either a fused multiply-add or two operations with rounding of the
1373/// intermediate result.
1374///
1375/// The operation is fused if the code generator determines that target
1376/// instruction set has support for a fused operation, and that the fused
1377/// operation is more efficient than the equivalent, separate pair of mul
1378/// and add instructions. It is unspecified whether or not a fused operation
1379/// is selected, and that may depend on optimization level and context, for
1380/// example.
1381#[rustc_intrinsic]
1382#[rustc_nounwind]
1383pub const fn fmuladdf64(a: f64, b: f64, c: f64) -> f64;
1384/// Returns `a * b + c` for `f128` values, non-deterministically executing
1385/// either a fused multiply-add or two operations with rounding of the
1386/// intermediate result.
1387///
1388/// The operation is fused if the code generator determines that target
1389/// instruction set has support for a fused operation, and that the fused
1390/// operation is more efficient than the equivalent, separate pair of mul
1391/// and add instructions. It is unspecified whether or not a fused operation
1392/// is selected, and that may depend on optimization level and context, for
1393/// example.
1394#[rustc_intrinsic]
1395#[rustc_nounwind]
1396pub const fn fmuladdf128(a: f128, b: f128, c: f128) -> f128;
1397
1398/// Returns the largest integer less than or equal to an `f16`.
1399///
1400/// The stabilized version of this intrinsic is
1401/// [`f16::floor`](../../std/primitive.f16.html#method.floor)
1402#[rustc_intrinsic_const_stable_indirect]
1403#[rustc_intrinsic]
1404#[rustc_nounwind]
1405pub const fn floorf16(x: f16) -> f16;
1406/// Returns the largest integer less than or equal to an `f32`.
1407///
1408/// The stabilized version of this intrinsic is
1409/// [`f32::floor`](../../std/primitive.f32.html#method.floor)
1410#[rustc_intrinsic_const_stable_indirect]
1411#[rustc_intrinsic]
1412#[rustc_nounwind]
1413pub const fn floorf32(x: f32) -> f32;
1414/// Returns the largest integer less than or equal to an `f64`.
1415///
1416/// The stabilized version of this intrinsic is
1417/// [`f64::floor`](../../std/primitive.f64.html#method.floor)
1418#[rustc_intrinsic_const_stable_indirect]
1419#[rustc_intrinsic]
1420#[rustc_nounwind]
1421pub const fn floorf64(x: f64) -> f64;
1422/// Returns the largest integer less than or equal to an `f128`.
1423///
1424/// The stabilized version of this intrinsic is
1425/// [`f128::floor`](../../std/primitive.f128.html#method.floor)
1426#[rustc_intrinsic_const_stable_indirect]
1427#[rustc_intrinsic]
1428#[rustc_nounwind]
1429pub const fn floorf128(x: f128) -> f128;
1430
1431/// Returns the smallest integer greater than or equal to an `f16`.
1432///
1433/// The stabilized version of this intrinsic is
1434/// [`f16::ceil`](../../std/primitive.f16.html#method.ceil)
1435#[rustc_intrinsic_const_stable_indirect]
1436#[rustc_intrinsic]
1437#[rustc_nounwind]
1438pub const fn ceilf16(x: f16) -> f16;
1439/// Returns the smallest integer greater than or equal to an `f32`.
1440///
1441/// The stabilized version of this intrinsic is
1442/// [`f32::ceil`](../../std/primitive.f32.html#method.ceil)
1443#[rustc_intrinsic_const_stable_indirect]
1444#[rustc_intrinsic]
1445#[rustc_nounwind]
1446pub const fn ceilf32(x: f32) -> f32;
1447/// Returns the smallest integer greater than or equal to an `f64`.
1448///
1449/// The stabilized version of this intrinsic is
1450/// [`f64::ceil`](../../std/primitive.f64.html#method.ceil)
1451#[rustc_intrinsic_const_stable_indirect]
1452#[rustc_intrinsic]
1453#[rustc_nounwind]
1454pub const fn ceilf64(x: f64) -> f64;
1455/// Returns the smallest integer greater than or equal to an `f128`.
1456///
1457/// The stabilized version of this intrinsic is
1458/// [`f128::ceil`](../../std/primitive.f128.html#method.ceil)
1459#[rustc_intrinsic_const_stable_indirect]
1460#[rustc_intrinsic]
1461#[rustc_nounwind]
1462pub const fn ceilf128(x: f128) -> f128;
1463
1464/// Returns the integer part of an `f16`.
1465///
1466/// The stabilized version of this intrinsic is
1467/// [`f16::trunc`](../../std/primitive.f16.html#method.trunc)
1468#[rustc_intrinsic_const_stable_indirect]
1469#[rustc_intrinsic]
1470#[rustc_nounwind]
1471pub const fn truncf16(x: f16) -> f16;
1472/// Returns the integer part of an `f32`.
1473///
1474/// The stabilized version of this intrinsic is
1475/// [`f32::trunc`](../../std/primitive.f32.html#method.trunc)
1476#[rustc_intrinsic_const_stable_indirect]
1477#[rustc_intrinsic]
1478#[rustc_nounwind]
1479pub const fn truncf32(x: f32) -> f32;
1480/// Returns the integer part of an `f64`.
1481///
1482/// The stabilized version of this intrinsic is
1483/// [`f64::trunc`](../../std/primitive.f64.html#method.trunc)
1484#[rustc_intrinsic_const_stable_indirect]
1485#[rustc_intrinsic]
1486#[rustc_nounwind]
1487pub const fn truncf64(x: f64) -> f64;
1488/// Returns the integer part of an `f128`.
1489///
1490/// The stabilized version of this intrinsic is
1491/// [`f128::trunc`](../../std/primitive.f128.html#method.trunc)
1492#[rustc_intrinsic_const_stable_indirect]
1493#[rustc_intrinsic]
1494#[rustc_nounwind]
1495pub const fn truncf128(x: f128) -> f128;
1496
1497/// Returns the nearest integer to an `f16`. Rounds half-way cases to the number with an even
1498/// least significant digit.
1499///
1500/// The stabilized version of this intrinsic is
1501/// [`f16::round_ties_even`](../../std/primitive.f16.html#method.round_ties_even)
1502#[rustc_intrinsic_const_stable_indirect]
1503#[rustc_intrinsic]
1504#[rustc_nounwind]
1505pub const fn round_ties_even_f16(x: f16) -> f16;
1506
1507/// Returns the nearest integer to an `f32`. Rounds half-way cases to the number with an even
1508/// least significant digit.
1509///
1510/// The stabilized version of this intrinsic is
1511/// [`f32::round_ties_even`](../../std/primitive.f32.html#method.round_ties_even)
1512#[rustc_intrinsic_const_stable_indirect]
1513#[rustc_intrinsic]
1514#[rustc_nounwind]
1515pub const fn round_ties_even_f32(x: f32) -> f32;
1516
1517/// Returns the nearest integer to an `f64`. Rounds half-way cases to the number with an even
1518/// least significant digit.
1519///
1520/// The stabilized version of this intrinsic is
1521/// [`f64::round_ties_even`](../../std/primitive.f64.html#method.round_ties_even)
1522#[rustc_intrinsic_const_stable_indirect]
1523#[rustc_intrinsic]
1524#[rustc_nounwind]
1525pub const fn round_ties_even_f64(x: f64) -> f64;
1526
1527/// Returns the nearest integer to an `f128`. Rounds half-way cases to the number with an even
1528/// least significant digit.
1529///
1530/// The stabilized version of this intrinsic is
1531/// [`f128::round_ties_even`](../../std/primitive.f128.html#method.round_ties_even)
1532#[rustc_intrinsic_const_stable_indirect]
1533#[rustc_intrinsic]
1534#[rustc_nounwind]
1535pub const fn round_ties_even_f128(x: f128) -> f128;
1536
1537/// Returns the nearest integer to an `f16`. Rounds half-way cases away from zero.
1538///
1539/// The stabilized version of this intrinsic is
1540/// [`f16::round`](../../std/primitive.f16.html#method.round)
1541#[rustc_intrinsic_const_stable_indirect]
1542#[rustc_intrinsic]
1543#[rustc_nounwind]
1544pub const fn roundf16(x: f16) -> f16;
1545/// Returns the nearest integer to an `f32`. Rounds half-way cases away from zero.
1546///
1547/// The stabilized version of this intrinsic is
1548/// [`f32::round`](../../std/primitive.f32.html#method.round)
1549#[rustc_intrinsic_const_stable_indirect]
1550#[rustc_intrinsic]
1551#[rustc_nounwind]
1552pub const fn roundf32(x: f32) -> f32;
1553/// Returns the nearest integer to an `f64`. Rounds half-way cases away from zero.
1554///
1555/// The stabilized version of this intrinsic is
1556/// [`f64::round`](../../std/primitive.f64.html#method.round)
1557#[rustc_intrinsic_const_stable_indirect]
1558#[rustc_intrinsic]
1559#[rustc_nounwind]
1560pub const fn roundf64(x: f64) -> f64;
1561/// Returns the nearest integer to an `f128`. Rounds half-way cases away from zero.
1562///
1563/// The stabilized version of this intrinsic is
1564/// [`f128::round`](../../std/primitive.f128.html#method.round)
1565#[rustc_intrinsic_const_stable_indirect]
1566#[rustc_intrinsic]
1567#[rustc_nounwind]
1568pub const fn roundf128(x: f128) -> f128;
1569
1570/// Float addition that allows optimizations based on algebraic rules.
1571/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1572///
1573/// This intrinsic does not have a stable counterpart.
1574#[rustc_intrinsic]
1575#[rustc_nounwind]
1576pub unsafe fn fadd_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1577
1578/// Float subtraction that allows optimizations based on algebraic rules.
1579/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1580///
1581/// This intrinsic does not have a stable counterpart.
1582#[rustc_intrinsic]
1583#[rustc_nounwind]
1584pub unsafe fn fsub_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1585
1586/// Float multiplication that allows optimizations based on algebraic rules.
1587/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1588///
1589/// This intrinsic does not have a stable counterpart.
1590#[rustc_intrinsic]
1591#[rustc_nounwind]
1592pub unsafe fn fmul_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1593
1594/// Float division that allows optimizations based on algebraic rules.
1595/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1596///
1597/// This intrinsic does not have a stable counterpart.
1598#[rustc_intrinsic]
1599#[rustc_nounwind]
1600pub unsafe fn fdiv_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1601
1602/// Float remainder that allows optimizations based on algebraic rules.
1603/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1604///
1605/// This intrinsic does not have a stable counterpart.
1606#[rustc_intrinsic]
1607#[rustc_nounwind]
1608pub unsafe fn frem_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1609
1610/// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range
1611/// (<https://github.com/rust-lang/rust/issues/10184>)
1612///
1613/// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`].
1614#[rustc_intrinsic]
1615#[rustc_nounwind]
1616pub unsafe fn float_to_int_unchecked<Float: bounds::FloatPrimitive, Int: Copy>(value: Float)
1617-> 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: bounds::FloatPrimitive>(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: bounds::FloatPrimitive>(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: bounds::FloatPrimitive>(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: bounds::FloatPrimitive>(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: bounds::FloatPrimitive>(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/// Carryless multiply.
2183///
2184/// Safe versions of this intrinsic are available on the integer primitives
2185/// via the `carryless_mul` method. For example, [`u32::carryless_mul`].
2186#[rustc_intrinsic]
2187#[rustc_nounwind]
2188#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
2189#[unstable(feature = "uint_carryless_mul", issue = "152080")]
2190#[miri::intrinsic_fallback_is_spec]
2191pub const fn carryless_mul<T: [const] fallback::CarrylessMul>(a: T, b: T) -> T {
2192    a.carryless_mul(b)
2193}
2194
2195/// This is an implementation detail of [`crate::ptr::read`] and should
2196/// not be used anywhere else.  See its comments for why this exists.
2197///
2198/// This intrinsic can *only* be called where the pointer is a local without
2199/// projections (`read_via_copy(ptr)`, not `read_via_copy(*ptr)`) so that it
2200/// trivially obeys runtime-MIR rules about derefs in operands.
2201#[rustc_intrinsic_const_stable_indirect]
2202#[rustc_nounwind]
2203#[rustc_intrinsic]
2204pub const unsafe fn read_via_copy<T>(ptr: *const T) -> T;
2205
2206/// This is an implementation detail of [`crate::ptr::write`] and should
2207/// not be used anywhere else.  See its comments for why this exists.
2208///
2209/// This intrinsic can *only* be called where the pointer is a local without
2210/// projections (`write_via_move(ptr, x)`, not `write_via_move(*ptr, x)`) so
2211/// that it trivially obeys runtime-MIR rules about derefs in operands.
2212#[rustc_intrinsic_const_stable_indirect]
2213#[rustc_nounwind]
2214#[rustc_intrinsic]
2215pub const unsafe fn write_via_move<T>(ptr: *mut T, value: T);
2216
2217/// Returns the value of the discriminant for the variant in 'v';
2218/// if `T` has no discriminant, returns `0`.
2219///
2220/// Note that, unlike most intrinsics, this is safe to call;
2221/// it does not require an `unsafe` block.
2222/// Therefore, implementations must not require the user to uphold
2223/// any safety invariants.
2224///
2225/// The stabilized version of this intrinsic is [`core::mem::discriminant`].
2226#[rustc_intrinsic_const_stable_indirect]
2227#[rustc_nounwind]
2228#[rustc_intrinsic]
2229pub const fn discriminant_value<T>(v: &T) -> <T as DiscriminantKind>::Discriminant;
2230
2231/// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the
2232/// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs.
2233/// Returns `1` if unwinding occurred and `catch_fn` was called; returns `0` otherwise.
2234///
2235/// `catch_fn` must not unwind.
2236///
2237/// The third argument is a function called if an unwind occurs (both Rust `panic` and foreign
2238/// unwinds). This function takes the data pointer and a pointer to the target- and
2239/// runtime-specific exception object that was caught.
2240///
2241/// Note that in the case of a foreign unwinding operation, the exception object data may not be
2242/// safely usable from Rust, and should not be directly exposed via the standard library. To
2243/// prevent unsafe access, the library implementation may either abort the process or present an
2244/// opaque error type to the user.
2245///
2246/// For more information, see the compiler's source, as well as the documentation for the stable
2247/// version of this intrinsic, `std::panic::catch_unwind`.
2248#[rustc_intrinsic]
2249#[rustc_nounwind]
2250pub unsafe fn catch_unwind(
2251    _try_fn: fn(*mut u8),
2252    _data: *mut u8,
2253    _catch_fn: fn(*mut u8, *mut u8),
2254) -> i32;
2255
2256/// Emits a `nontemporal` store, which gives a hint to the CPU that the data should not be held
2257/// in cache. Except for performance, this is fully equivalent to `ptr.write(val)`.
2258///
2259/// Not all architectures provide such an operation. For instance, x86 does not: while `MOVNT`
2260/// exists, that operation is *not* equivalent to `ptr.write(val)` (`MOVNT` writes can be reordered
2261/// in ways that are not allowed for regular writes).
2262#[rustc_intrinsic]
2263#[rustc_nounwind]
2264pub unsafe fn nontemporal_store<T>(ptr: *mut T, val: T);
2265
2266/// See documentation of `<*const T>::offset_from` for details.
2267#[rustc_intrinsic_const_stable_indirect]
2268#[rustc_nounwind]
2269#[rustc_intrinsic]
2270pub const unsafe fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
2271
2272/// See documentation of `<*const T>::offset_from_unsigned` for details.
2273#[rustc_nounwind]
2274#[rustc_intrinsic]
2275#[rustc_intrinsic_const_stable_indirect]
2276pub const unsafe fn ptr_offset_from_unsigned<T>(ptr: *const T, base: *const T) -> usize;
2277
2278/// See documentation of `<*const T>::guaranteed_eq` for details.
2279/// Returns `2` if the result is unknown.
2280/// Returns `1` if the pointers are guaranteed equal.
2281/// Returns `0` if the pointers are guaranteed inequal.
2282#[rustc_intrinsic]
2283#[rustc_nounwind]
2284#[rustc_do_not_const_check]
2285#[inline]
2286#[miri::intrinsic_fallback_is_spec]
2287pub const fn ptr_guaranteed_cmp<T>(ptr: *const T, other: *const T) -> u8 {
2288    (ptr == other) as u8
2289}
2290
2291/// Determines whether the raw bytes of the two values are equal.
2292///
2293/// This is particularly handy for arrays, since it allows things like just
2294/// comparing `i96`s instead of forcing `alloca`s for `[6 x i16]`.
2295///
2296/// Above some backend-decided threshold this will emit calls to `memcmp`,
2297/// like slice equality does, instead of causing massive code size.
2298///
2299/// Since this works by comparing the underlying bytes, the actual `T` is
2300/// not particularly important.  It will be used for its size and alignment,
2301/// but any validity restrictions will be ignored, not enforced.
2302///
2303/// # Safety
2304///
2305/// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized.
2306/// Note that this is a stricter criterion than just the *values* being
2307/// fully-initialized: if `T` has padding, it's UB to call this intrinsic.
2308///
2309/// At compile-time, it is furthermore UB to call this if any of the bytes
2310/// in `*a` or `*b` have provenance.
2311///
2312/// (The implementation is allowed to branch on the results of comparisons,
2313/// which is UB if any of their inputs are `undef`.)
2314#[rustc_nounwind]
2315#[rustc_intrinsic]
2316pub const unsafe fn raw_eq<T>(a: &T, b: &T) -> bool;
2317
2318/// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)`
2319/// as unsigned bytes, returning negative if `left` is less, zero if all the
2320/// bytes match, or positive if `left` is greater.
2321///
2322/// This underlies things like `<[u8]>::cmp`, and will usually lower to `memcmp`.
2323///
2324/// # Safety
2325///
2326/// `left` and `right` must each be [valid] for reads of `bytes` bytes.
2327///
2328/// Note that this applies to the whole range, not just until the first byte
2329/// that differs.  That allows optimizations that can read in large chunks.
2330///
2331/// [valid]: crate::ptr#safety
2332#[rustc_nounwind]
2333#[rustc_intrinsic]
2334#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2335pub const unsafe fn compare_bytes(left: *const u8, right: *const u8, bytes: usize) -> i32;
2336
2337/// See documentation of [`std::hint::black_box`] for details.
2338///
2339/// [`std::hint::black_box`]: crate::hint::black_box
2340#[rustc_nounwind]
2341#[rustc_intrinsic]
2342#[rustc_intrinsic_const_stable_indirect]
2343pub const fn black_box<T>(dummy: T) -> T;
2344
2345/// Selects which function to call depending on the context.
2346///
2347/// If this function is evaluated at compile-time, then a call to this
2348/// intrinsic will be replaced with a call to `called_in_const`. It gets
2349/// replaced with a call to `called_at_rt` otherwise.
2350///
2351/// This function is safe to call, but note the stability concerns below.
2352///
2353/// # Type Requirements
2354///
2355/// The two functions must be both function items. They cannot be function
2356/// pointers or closures. The first function must be a `const fn`.
2357///
2358/// `arg` will be the tupled arguments that will be passed to either one of
2359/// the two functions, therefore, both functions must accept the same type of
2360/// arguments. Both functions must return RET.
2361///
2362/// # Stability concerns
2363///
2364/// Rust has not yet decided that `const fn` are allowed to tell whether
2365/// they run at compile-time or at runtime. Therefore, when using this
2366/// intrinsic anywhere that can be reached from stable, it is crucial that
2367/// the end-to-end behavior of the stable `const fn` is the same for both
2368/// modes of execution. (Here, Undefined Behavior is considered "the same"
2369/// as any other behavior, so if the function exhibits UB at runtime then
2370/// it may do whatever it wants at compile-time.)
2371///
2372/// Here is an example of how this could cause a problem:
2373/// ```no_run
2374/// #![feature(const_eval_select)]
2375/// #![feature(core_intrinsics)]
2376/// # #![allow(internal_features)]
2377/// use std::intrinsics::const_eval_select;
2378///
2379/// // Standard library
2380/// pub const fn inconsistent() -> i32 {
2381///     fn runtime() -> i32 { 1 }
2382///     const fn compiletime() -> i32 { 2 }
2383///
2384///     // ⚠ This code violates the required equivalence of `compiletime`
2385///     // and `runtime`.
2386///     const_eval_select((), compiletime, runtime)
2387/// }
2388///
2389/// // User Crate
2390/// const X: i32 = inconsistent();
2391/// let x = inconsistent();
2392/// assert_eq!(x, X);
2393/// ```
2394///
2395/// Currently such an assertion would always succeed; until Rust decides
2396/// otherwise, that principle should not be violated.
2397#[rustc_const_unstable(feature = "const_eval_select", issue = "124625")]
2398#[rustc_intrinsic]
2399pub const fn const_eval_select<ARG: Tuple, F, G, RET>(
2400    _arg: ARG,
2401    _called_in_const: F,
2402    _called_at_rt: G,
2403) -> RET
2404where
2405    G: FnOnce<ARG, Output = RET>,
2406    F: const FnOnce<ARG, Output = RET>;
2407
2408/// A macro to make it easier to invoke const_eval_select. Use as follows:
2409/// ```rust,ignore (just a macro example)
2410/// const_eval_select!(
2411///     @capture { arg1: i32 = some_expr, arg2: T = other_expr } -> U:
2412///     if const #[attributes_for_const_arm] {
2413///         // Compile-time code goes here.
2414///     } else #[attributes_for_runtime_arm] {
2415///         // Run-time code goes here.
2416///     }
2417/// )
2418/// ```
2419/// The `@capture` block declares which surrounding variables / expressions can be
2420/// used inside the `if const`.
2421/// Note that the two arms of this `if` really each become their own function, which is why the
2422/// macro supports setting attributes for those functions. Both functions are marked as `#[inline]`.
2423///
2424/// See [`const_eval_select()`] for the rules and requirements around that intrinsic.
2425pub(crate) macro const_eval_select {
2426    (
2427        @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? :
2428        if const
2429            $(#[$compiletime_attr:meta])* $compiletime:block
2430        else
2431            $(#[$runtime_attr:meta])* $runtime:block
2432    ) => {{
2433        #[inline]
2434        $(#[$runtime_attr])*
2435        fn runtime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2436            $runtime
2437        }
2438
2439        #[inline]
2440        $(#[$compiletime_attr])*
2441        const fn compiletime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2442            // Don't warn if one of the arguments is unused.
2443            $(let _ = $arg;)*
2444
2445            $compiletime
2446        }
2447
2448        const_eval_select(($($val,)*), compiletime, runtime)
2449    }},
2450    // We support leaving away the `val` expressions for *all* arguments
2451    // (but not for *some* arguments, that's too tricky).
2452    (
2453        @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty),* $(,)? } $( -> $ret:ty )? :
2454        if const
2455            $(#[$compiletime_attr:meta])* $compiletime:block
2456        else
2457            $(#[$runtime_attr:meta])* $runtime:block
2458    ) => {
2459        $crate::intrinsics::const_eval_select!(
2460            @capture$([$($binders)*])? { $($arg : $ty = $arg),* } $(-> $ret)? :
2461            if const
2462                $(#[$compiletime_attr])* $compiletime
2463            else
2464                $(#[$runtime_attr])* $runtime
2465        )
2466    },
2467}
2468
2469/// Returns whether the argument's value is statically known at
2470/// compile-time.
2471///
2472/// This is useful when there is a way of writing the code that will
2473/// be *faster* when some variables have known values, but *slower*
2474/// in the general case: an `if is_val_statically_known(var)` can be used
2475/// to select between these two variants. The `if` will be optimized away
2476/// and only the desired branch remains.
2477///
2478/// Formally speaking, this function non-deterministically returns `true`
2479/// or `false`, and the caller has to ensure sound behavior for both cases.
2480/// In other words, the following code has *Undefined Behavior*:
2481///
2482/// ```no_run
2483/// #![feature(core_intrinsics)]
2484/// # #![allow(internal_features)]
2485/// use std::hint::unreachable_unchecked;
2486/// use std::intrinsics::is_val_statically_known;
2487///
2488/// if !is_val_statically_known(0) { unsafe { unreachable_unchecked(); } }
2489/// ```
2490///
2491/// This also means that the following code's behavior is unspecified; it
2492/// may panic, or it may not:
2493///
2494/// ```no_run
2495/// #![feature(core_intrinsics)]
2496/// # #![allow(internal_features)]
2497/// use std::intrinsics::is_val_statically_known;
2498///
2499/// assert_eq!(is_val_statically_known(0), is_val_statically_known(0));
2500/// ```
2501///
2502/// Unsafe code may not rely on `is_val_statically_known` returning any
2503/// particular value, ever. However, the compiler will generally make it
2504/// return `true` only if the value of the argument is actually known.
2505///
2506/// # Type Requirements
2507///
2508/// `T` must be either a `bool`, a `char`, a primitive numeric type (e.g. `f32`,
2509/// but not `NonZeroISize`), or any thin pointer (e.g. `*mut String`).
2510/// Any other argument types *may* cause a compiler error.
2511///
2512/// ## Pointers
2513///
2514/// When the input is a pointer, only the pointer itself is
2515/// ever considered. The pointee has no effect. Currently, these functions
2516/// behave identically:
2517///
2518/// ```
2519/// #![feature(core_intrinsics)]
2520/// # #![allow(internal_features)]
2521/// use std::intrinsics::is_val_statically_known;
2522///
2523/// fn foo(x: &i32) -> bool {
2524///     is_val_statically_known(x)
2525/// }
2526///
2527/// fn bar(x: &i32) -> bool {
2528///     is_val_statically_known(
2529///         (x as *const i32).addr()
2530///     )
2531/// }
2532/// # _ = foo(&5_i32);
2533/// # _ = bar(&5_i32);
2534/// ```
2535#[rustc_const_stable_indirect]
2536#[rustc_nounwind]
2537#[unstable(feature = "core_intrinsics", issue = "none")]
2538#[rustc_intrinsic]
2539pub const fn is_val_statically_known<T: Copy>(_arg: T) -> bool {
2540    false
2541}
2542
2543/// Non-overlapping *typed* swap of a single value.
2544///
2545/// The codegen backends will replace this with a better implementation when
2546/// `T` is a simple type that can be loaded and stored as an immediate.
2547///
2548/// The stabilized form of this intrinsic is [`crate::mem::swap`].
2549///
2550/// # Safety
2551/// Behavior is undefined if any of the following conditions are violated:
2552///
2553/// * Both `x` and `y` must be [valid] for both reads and writes.
2554///
2555/// * Both `x` and `y` must be properly aligned.
2556///
2557/// * The region of memory beginning at `x` must *not* overlap with the region of memory
2558///   beginning at `y`.
2559///
2560/// * The memory pointed by `x` and `y` must both contain values of type `T`.
2561///
2562/// [valid]: crate::ptr#safety
2563#[rustc_nounwind]
2564#[inline]
2565#[rustc_intrinsic]
2566#[rustc_intrinsic_const_stable_indirect]
2567pub const unsafe fn typed_swap_nonoverlapping<T>(x: *mut T, y: *mut T) {
2568    // SAFETY: The caller provided single non-overlapping items behind
2569    // pointers, so swapping them with `count: 1` is fine.
2570    unsafe { ptr::swap_nonoverlapping(x, y, 1) };
2571}
2572
2573/// Returns whether we should perform some UB-checking at runtime. This eventually evaluates to
2574/// `cfg!(ub_checks)`, but behaves different from `cfg!` when mixing crates built with different
2575/// flags: if the crate has UB checks enabled or carries the `#[rustc_preserve_ub_checks]`
2576/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2577/// a crate that does not delay evaluation further); otherwise it can happen any time.
2578///
2579/// The common case here is a user program built with ub_checks linked against the distributed
2580/// sysroot which is built without ub_checks but with `#[rustc_preserve_ub_checks]`.
2581/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2582/// `#[inline]`), gating assertions on `ub_checks()` rather than `cfg!(ub_checks)` means that
2583/// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the
2584/// user has UB checks disabled, the checks will still get optimized out. This intrinsic is
2585/// primarily used by [`crate::ub_checks::assert_unsafe_precondition`].
2586///
2587/// # Consteval
2588///
2589/// In consteval, this function currently returns `true`. This is because the value of the `ub_checks`
2590/// configuration can differ across crates, but we need this function to always return the same
2591/// value in consteval in order to avoid unsoundness.
2592#[rustc_intrinsic_const_stable_indirect] // just for UB checks
2593#[inline(always)]
2594#[rustc_intrinsic]
2595pub const fn ub_checks() -> bool {
2596    cfg!(ub_checks)
2597}
2598
2599/// Returns whether we should perform some overflow-checking at runtime. This eventually evaluates to
2600/// `cfg!(overflow_checks)`, but behaves different from `cfg!` when mixing crates built with different
2601/// flags: if the crate has overflow checks enabled or carries the `#[rustc_inherit_overflow_checks]`
2602/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2603/// a crate that does not delay evaluation further); otherwise it can happen any time.
2604///
2605/// The common case here is a user program built with overflow_checks linked against the distributed
2606/// sysroot which is built without overflow_checks but with `#[rustc_inherit_overflow_checks]`.
2607/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2608/// `#[inline]`), gating assertions on `overflow_checks()` rather than `cfg!(overflow_checks)` means that
2609/// assertions are enabled whenever the *user crate* has overflow checks enabled. However if the
2610/// user has overflow checks disabled, the checks will still get optimized out.
2611///
2612/// # Consteval
2613///
2614/// In consteval, this function currently returns `true`. This is because the value of the `overflow_checks`
2615/// configuration can differ across crates, but we need this function to always return the same
2616/// value in consteval in order to avoid unsoundness.
2617#[inline(always)]
2618#[rustc_intrinsic]
2619pub const fn overflow_checks() -> bool {
2620    cfg!(debug_assertions)
2621}
2622
2623/// Allocates a block of memory at compile time.
2624/// At runtime, just returns a null pointer.
2625///
2626/// # Safety
2627///
2628/// - The `align` argument must be a power of two.
2629///    - At compile time, a compile error occurs if this constraint is violated.
2630///    - At runtime, it is not checked.
2631#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2632#[rustc_nounwind]
2633#[rustc_intrinsic]
2634#[miri::intrinsic_fallback_is_spec]
2635pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 {
2636    // const eval overrides this function, but runtime code for now just returns null pointers.
2637    // See <https://github.com/rust-lang/rust/issues/93935>.
2638    crate::ptr::null_mut()
2639}
2640
2641/// Deallocates a memory which allocated by `intrinsics::const_allocate` at compile time.
2642/// At runtime, it does nothing.
2643///
2644/// # Safety
2645///
2646/// - The `align` argument must be a power of two.
2647///    - At compile time, a compile error occurs if this constraint is violated.
2648///    - At runtime, it is not checked.
2649/// - If the `ptr` is created in an another const, this intrinsic doesn't deallocate it.
2650/// - If the `ptr` is pointing to a local variable, this intrinsic doesn't deallocate it.
2651#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2652#[unstable(feature = "core_intrinsics", issue = "none")]
2653#[rustc_nounwind]
2654#[rustc_intrinsic]
2655#[miri::intrinsic_fallback_is_spec]
2656pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {
2657    // Runtime NOP
2658}
2659
2660/// Convert the allocation this pointer points to into immutable global memory.
2661/// The pointer must point to the beginning of a heap allocation.
2662/// This operation only makes sense during compile time. At runtime, it does nothing.
2663#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2664#[rustc_nounwind]
2665#[rustc_intrinsic]
2666#[miri::intrinsic_fallback_is_spec]
2667pub const unsafe fn const_make_global(ptr: *mut u8) -> *const u8 {
2668    // const eval overrides this function; at runtime, it is a NOP.
2669    ptr
2670}
2671
2672/// Check if the pre-condition `cond` has been met.
2673///
2674/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2675/// returns false.
2676///
2677/// Note that this function is a no-op during constant evaluation.
2678#[unstable(feature = "contracts_internals", issue = "128044")]
2679// Calls to this function get inserted by an AST expansion pass, which uses the equivalent of
2680// `#[allow_internal_unstable]` to allow using `contracts_internals` functions. Const-checking
2681// doesn't honor `#[allow_internal_unstable]`, so for the const feature gate we use the user-facing
2682// `contracts` feature rather than the perma-unstable `contracts_internals`
2683#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2684#[lang = "contract_check_requires"]
2685#[rustc_intrinsic]
2686pub const fn contract_check_requires<C: Fn() -> bool + Copy>(cond: C) {
2687    const_eval_select!(
2688        @capture[C: Fn() -> bool + Copy] { cond: C } :
2689        if const {
2690                // Do nothing
2691        } else {
2692            if !cond() {
2693                // Emit no unwind panic in case this was a safety requirement.
2694                crate::panicking::panic_nounwind("failed requires check");
2695            }
2696        }
2697    )
2698}
2699
2700/// Check if the post-condition `cond` has been met.
2701///
2702/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2703/// returns false.
2704///
2705/// If `cond` is `None`, then no postcondition checking is performed.
2706///
2707/// Note that this function is a no-op during constant evaluation.
2708#[unstable(feature = "contracts_internals", issue = "128044")]
2709// Similar to `contract_check_requires`, we need to use the user-facing
2710// `contracts` feature rather than the perma-unstable `contracts_internals`.
2711// Const-checking doesn't honor allow_internal_unstable logic used by contract expansion.
2712#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2713#[lang = "contract_check_ensures"]
2714#[rustc_intrinsic]
2715pub const fn contract_check_ensures<C: Fn(&Ret) -> bool + Copy, Ret>(
2716    cond: Option<C>,
2717    ret: Ret,
2718) -> Ret {
2719    const_eval_select!(
2720        @capture[C: Fn(&Ret) -> bool + Copy, Ret] { cond: Option<C>, ret: Ret } -> Ret :
2721        if const {
2722            // Do nothing
2723            ret
2724        } else {
2725            match cond {
2726                crate::option::Option::Some(cond) => {
2727                    if !cond(&ret) {
2728                        // Emit no unwind panic in case this was a safety requirement.
2729                        crate::panicking::panic_nounwind("failed ensures check");
2730                    }
2731                },
2732                crate::option::Option::None => {},
2733            }
2734            ret
2735        }
2736    )
2737}
2738
2739/// The intrinsic will return the size stored in that vtable.
2740///
2741/// # Safety
2742///
2743/// `ptr` must point to a vtable.
2744#[rustc_nounwind]
2745#[unstable(feature = "core_intrinsics", issue = "none")]
2746#[rustc_intrinsic]
2747pub unsafe fn vtable_size(ptr: *const ()) -> usize;
2748
2749/// The intrinsic will return the alignment stored in that vtable.
2750///
2751/// # Safety
2752///
2753/// `ptr` must point to a vtable.
2754#[rustc_nounwind]
2755#[unstable(feature = "core_intrinsics", issue = "none")]
2756#[rustc_intrinsic]
2757pub unsafe fn vtable_align(ptr: *const ()) -> usize;
2758
2759/// The size of a type in bytes.
2760///
2761/// Note that, unlike most intrinsics, this is safe to call;
2762/// it does not require an `unsafe` block.
2763/// Therefore, implementations must not require the user to uphold
2764/// any safety invariants.
2765///
2766/// More specifically, this is the offset in bytes between successive
2767/// items of the same type, including alignment padding.
2768///
2769/// Note that, unlike most intrinsics, this can only be called at compile-time
2770/// as backends do not have an implementation for it. The only caller (its
2771/// stable counterpart) wraps this intrinsic call in a `const` block so that
2772/// backends only see an evaluated constant.
2773///
2774/// The stabilized version of this intrinsic is [`core::mem::size_of`].
2775#[rustc_nounwind]
2776#[unstable(feature = "core_intrinsics", issue = "none")]
2777#[rustc_intrinsic_const_stable_indirect]
2778#[rustc_intrinsic]
2779pub const fn size_of<T>() -> usize;
2780
2781/// The minimum alignment of a type.
2782///
2783/// Note that, unlike most intrinsics, this is safe to call;
2784/// it does not require an `unsafe` block.
2785/// Therefore, implementations must not require the user to uphold
2786/// any safety invariants.
2787///
2788/// Note that, unlike most intrinsics, this can only be called at compile-time
2789/// as backends do not have an implementation for it. The only caller (its
2790/// stable counterpart) wraps this intrinsic call in a `const` block so that
2791/// backends only see an evaluated constant.
2792///
2793/// The stabilized version of this intrinsic is [`core::mem::align_of`].
2794#[rustc_nounwind]
2795#[unstable(feature = "core_intrinsics", issue = "none")]
2796#[rustc_intrinsic_const_stable_indirect]
2797#[rustc_intrinsic]
2798pub const fn align_of<T>() -> usize;
2799
2800/// The offset of a field inside a type.
2801///
2802/// Note that, unlike most intrinsics, this is safe to call;
2803/// it does not require an `unsafe` block.
2804/// Therefore, implementations must not require the user to uphold
2805/// any safety invariants.
2806///
2807/// This intrinsic can only be evaluated at compile-time, and should only appear in
2808/// constants or inline const blocks.
2809///
2810/// The stabilized version of this intrinsic is [`core::mem::offset_of`].
2811/// This intrinsic is also a lang item so `offset_of!` can desugar to calls to it.
2812#[rustc_nounwind]
2813#[unstable(feature = "core_intrinsics", issue = "none")]
2814#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")]
2815#[rustc_intrinsic_const_stable_indirect]
2816#[rustc_intrinsic]
2817#[lang = "offset_of"]
2818pub const fn offset_of<T: PointeeSized>(variant: u32, field: u32) -> usize;
2819
2820/// The offset of a field queried by its field representing type.
2821///
2822/// Returns the offset of the field represented by `F`. This function essentially does the same as
2823/// the [`offset_of`] intrinsic, but expects the field to be represented by a generic rather than
2824/// the variant and field indices. This also is a safe intrinsic and can only be evaluated at
2825/// compile-time, so it should only appear in constants or inline const blocks.
2826///
2827/// There should be no need to call this intrinsic manually, as its value is used to define
2828/// [`Field::OFFSET`](crate::field::Field::OFFSET), which is publicly accessible.
2829#[rustc_intrinsic]
2830#[unstable(feature = "field_projections", issue = "145383")]
2831#[rustc_const_unstable(feature = "field_projections", issue = "145383")]
2832pub const fn field_offset<F: crate::field::Field>() -> usize;
2833
2834/// Returns the number of variants of the type `T` cast to a `usize`;
2835/// if `T` has no variants, returns `0`. Uninhabited variants will be counted.
2836///
2837/// Note that, unlike most intrinsics, this can only be called at compile-time
2838/// as backends do not have an implementation for it. The only caller (its
2839/// stable counterpart) wraps this intrinsic call in a `const` block so that
2840/// backends only see an evaluated constant.
2841///
2842/// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`].
2843#[rustc_nounwind]
2844#[unstable(feature = "core_intrinsics", issue = "none")]
2845#[rustc_intrinsic]
2846pub const fn variant_count<T>() -> usize;
2847
2848/// The size of the referenced value in bytes.
2849///
2850/// The stabilized version of this intrinsic is [`core::mem::size_of_val`].
2851///
2852/// # Safety
2853///
2854/// See [`crate::mem::size_of_val_raw`] for safety conditions.
2855#[rustc_nounwind]
2856#[unstable(feature = "core_intrinsics", issue = "none")]
2857#[rustc_intrinsic]
2858#[rustc_intrinsic_const_stable_indirect]
2859pub const unsafe fn size_of_val<T: ?Sized>(ptr: *const T) -> usize;
2860
2861/// The required alignment of the referenced value.
2862///
2863/// The stabilized version of this intrinsic is [`core::mem::align_of_val`].
2864///
2865/// # Safety
2866///
2867/// See [`crate::mem::align_of_val_raw`] for safety conditions.
2868#[rustc_nounwind]
2869#[unstable(feature = "core_intrinsics", issue = "none")]
2870#[rustc_intrinsic]
2871#[rustc_intrinsic_const_stable_indirect]
2872pub const unsafe fn align_of_val<T: ?Sized>(ptr: *const T) -> usize;
2873
2874#[rustc_intrinsic]
2875#[unstable(feature = "core_intrinsics", issue = "none")]
2876/// Check if a type represented by a `TypeId` implements a trait represented by a `TypeId`.
2877/// It can only be called at compile time, the backends do
2878/// not implement it. If it implements the trait the dyn metadata gets returned for vtable access.
2879pub const fn type_id_vtable(
2880    _id: crate::any::TypeId,
2881    _trait: crate::any::TypeId,
2882) -> Option<ptr::DynMetadata<*const ()>> {
2883    panic!(
2884        "`TypeId::trait_info_of` and `trait_info_of_trait_type_id` can only be called at compile-time"
2885    )
2886}
2887
2888/// Compute the type information of a concrete type.
2889/// It can only be called at compile time, the backends do
2890/// not implement it.
2891#[rustc_intrinsic]
2892#[unstable(feature = "core_intrinsics", issue = "none")]
2893pub const fn type_of(_id: crate::any::TypeId) -> crate::mem::type_info::Type {
2894    panic!("`TypeId::info` can only be called at compile-time")
2895}
2896
2897/// Gets a static string slice containing the name of a type.
2898///
2899/// Note that, unlike most intrinsics, this can only be called at compile-time
2900/// as backends do not have an implementation for it. The only caller (its
2901/// stable counterpart) wraps this intrinsic call in a `const` block so that
2902/// backends only see an evaluated constant.
2903///
2904/// The stabilized version of this intrinsic is [`core::any::type_name`].
2905#[rustc_nounwind]
2906#[unstable(feature = "core_intrinsics", issue = "none")]
2907#[rustc_intrinsic]
2908pub const fn type_name<T: ?Sized>() -> &'static str;
2909
2910/// Gets an identifier which is globally unique to the specified type. This
2911/// function will return the same value for a type regardless of whichever
2912/// crate it is invoked in.
2913///
2914/// Note that, unlike most intrinsics, this can only be called at compile-time
2915/// as backends do not have an implementation for it. The only caller (its
2916/// stable counterpart) wraps this intrinsic call in a `const` block so that
2917/// backends only see an evaluated constant.
2918///
2919/// The stabilized version of this intrinsic is [`core::any::TypeId::of`].
2920#[rustc_nounwind]
2921#[unstable(feature = "core_intrinsics", issue = "none")]
2922#[rustc_intrinsic]
2923pub const fn type_id<T: ?Sized>() -> crate::any::TypeId;
2924
2925/// Tests (at compile-time) if two [`crate::any::TypeId`] instances identify the
2926/// same type. This is necessary because at const-eval time the actual discriminating
2927/// data is opaque and cannot be inspected directly.
2928///
2929/// The stabilized version of this intrinsic is the [PartialEq] impl for [`core::any::TypeId`].
2930#[rustc_nounwind]
2931#[unstable(feature = "core_intrinsics", issue = "none")]
2932#[rustc_intrinsic]
2933#[rustc_do_not_const_check]
2934pub const fn type_id_eq(a: crate::any::TypeId, b: crate::any::TypeId) -> bool {
2935    a.data == b.data
2936}
2937
2938/// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`.
2939///
2940/// This is used to implement functions like `slice::from_raw_parts_mut` and
2941/// `ptr::from_raw_parts` in a way compatible with the compiler being able to
2942/// change the possible layouts of pointers.
2943#[rustc_nounwind]
2944#[unstable(feature = "core_intrinsics", issue = "none")]
2945#[rustc_intrinsic_const_stable_indirect]
2946#[rustc_intrinsic]
2947pub const fn aggregate_raw_ptr<P: bounds::BuiltinDeref, D, M>(data: D, meta: M) -> P
2948where
2949    <P as bounds::BuiltinDeref>::Pointee: ptr::Pointee<Metadata = M>;
2950
2951/// Lowers in MIR to `Rvalue::UnaryOp` with `UnOp::PtrMetadata`.
2952///
2953/// This is used to implement functions like `ptr::metadata`.
2954#[rustc_nounwind]
2955#[unstable(feature = "core_intrinsics", issue = "none")]
2956#[rustc_intrinsic_const_stable_indirect]
2957#[rustc_intrinsic]
2958pub const fn ptr_metadata<P: ptr::Pointee<Metadata = M> + PointeeSized, M>(ptr: *const P) -> M;
2959
2960/// This is an accidentally-stable alias to [`ptr::copy_nonoverlapping`]; use that instead.
2961// Note (intentionally not in the doc comment): `ptr::copy_nonoverlapping` adds some extra
2962// debug assertions; if you are writing compiler tests or code inside the standard library
2963// that wants to avoid those debug assertions, directly call this intrinsic instead.
2964#[stable(feature = "rust1", since = "1.0.0")]
2965#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2966#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2967#[rustc_nounwind]
2968#[rustc_intrinsic]
2969pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
2970
2971/// This is an accidentally-stable alias to [`ptr::copy`]; use that instead.
2972// Note (intentionally not in the doc comment): `ptr::copy` adds some extra
2973// debug assertions; if you are writing compiler tests or code inside the standard library
2974// that wants to avoid those debug assertions, directly call this intrinsic instead.
2975#[stable(feature = "rust1", since = "1.0.0")]
2976#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2977#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2978#[rustc_nounwind]
2979#[rustc_intrinsic]
2980pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize);
2981
2982/// This is an accidentally-stable alias to [`ptr::write_bytes`]; use that instead.
2983// Note (intentionally not in the doc comment): `ptr::write_bytes` adds some extra
2984// debug assertions; if you are writing compiler tests or code inside the standard library
2985// that wants to avoid those debug assertions, directly call this intrinsic instead.
2986#[stable(feature = "rust1", since = "1.0.0")]
2987#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
2988#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
2989#[rustc_nounwind]
2990#[rustc_intrinsic]
2991pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
2992
2993/// Returns the minimum of two `f16` values, ignoring NaN.
2994///
2995/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
2996/// zeros deterministically. In particular:
2997/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
2998/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
2999/// and `-0.0`), either input may be returned non-deterministically.
3000///
3001/// Note that, unlike most intrinsics, this is safe to call;
3002/// it does not require an `unsafe` block.
3003/// Therefore, implementations must not require the user to uphold
3004/// any safety invariants.
3005///
3006/// The stabilized version of this intrinsic is [`f16::min`].
3007#[rustc_nounwind]
3008#[rustc_intrinsic]
3009pub const fn minimum_number_nsz_f16(x: f16, y: f16) -> f16 {
3010    if x.is_nan() || y <= x {
3011        y
3012    } else {
3013        // Either y > x or y is a NaN.
3014        x
3015    }
3016}
3017
3018/// Returns the minimum of two `f32` values, ignoring NaN.
3019///
3020/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3021/// zeros deterministically. In particular:
3022/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3023/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3024/// and `-0.0`), either input may be returned non-deterministically.
3025///
3026/// Note that, unlike most intrinsics, this is safe to call;
3027/// it does not require an `unsafe` block.
3028/// Therefore, implementations must not require the user to uphold
3029/// any safety invariants.
3030///
3031/// The stabilized version of this intrinsic is [`f32::min`].
3032#[rustc_nounwind]
3033#[rustc_intrinsic_const_stable_indirect]
3034#[rustc_intrinsic]
3035pub const fn minimum_number_nsz_f32(x: f32, y: f32) -> f32 {
3036    if x.is_nan() || y <= x {
3037        y
3038    } else {
3039        // Either y > x or y is a NaN.
3040        x
3041    }
3042}
3043
3044/// Returns the minimum of two `f64` values, ignoring NaN.
3045///
3046/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3047/// zeros deterministically. In particular:
3048/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3049/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3050/// and `-0.0`), either input may be returned non-deterministically.
3051///
3052/// Note that, unlike most intrinsics, this is safe to call;
3053/// it does not require an `unsafe` block.
3054/// Therefore, implementations must not require the user to uphold
3055/// any safety invariants.
3056///
3057/// The stabilized version of this intrinsic is [`f64::min`].
3058#[rustc_nounwind]
3059#[rustc_intrinsic_const_stable_indirect]
3060#[rustc_intrinsic]
3061pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 {
3062    if x.is_nan() || y <= x {
3063        y
3064    } else {
3065        // Either y > x or y is a NaN.
3066        x
3067    }
3068}
3069
3070/// Returns the minimum of two `f128` values, ignoring NaN.
3071///
3072/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3073/// zeros deterministically. In particular:
3074/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3075/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3076/// and `-0.0`), either input may be returned non-deterministically.
3077///
3078/// Note that, unlike most intrinsics, this is safe to call;
3079/// it does not require an `unsafe` block.
3080/// Therefore, implementations must not require the user to uphold
3081/// any safety invariants.
3082///
3083/// The stabilized version of this intrinsic is [`f128::min`].
3084#[rustc_nounwind]
3085#[rustc_intrinsic]
3086pub const fn minimum_number_nsz_f128(x: f128, y: f128) -> f128 {
3087    if x.is_nan() || y <= x {
3088        y
3089    } else {
3090        // Either y > x or y is a NaN.
3091        x
3092    }
3093}
3094
3095/// Returns the minimum of two `f16` values, propagating NaN.
3096///
3097/// This behaves like IEEE 754-2019 minimum. In particular:
3098/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3099/// For this operation, -0.0 is considered to be strictly less than +0.0.
3100///
3101/// Note that, unlike most intrinsics, this is safe to call;
3102/// it does not require an `unsafe` block.
3103/// Therefore, implementations must not require the user to uphold
3104/// any safety invariants.
3105#[rustc_nounwind]
3106#[rustc_intrinsic]
3107pub const fn minimumf16(x: f16, y: f16) -> f16 {
3108    if x < y {
3109        x
3110    } else if y < x {
3111        y
3112    } else if x == y {
3113        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3114    } else {
3115        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3116        x + y
3117    }
3118}
3119
3120/// Returns the minimum of two `f32` values, propagating NaN.
3121///
3122/// This behaves like IEEE 754-2019 minimum. In particular:
3123/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3124/// For this operation, -0.0 is considered to be strictly less than +0.0.
3125///
3126/// Note that, unlike most intrinsics, this is safe to call;
3127/// it does not require an `unsafe` block.
3128/// Therefore, implementations must not require the user to uphold
3129/// any safety invariants.
3130#[rustc_nounwind]
3131#[rustc_intrinsic]
3132pub const fn minimumf32(x: f32, y: f32) -> f32 {
3133    if x < y {
3134        x
3135    } else if y < x {
3136        y
3137    } else if x == y {
3138        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3139    } else {
3140        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3141        x + y
3142    }
3143}
3144
3145/// Returns the minimum of two `f64` values, propagating NaN.
3146///
3147/// This behaves like IEEE 754-2019 minimum. In particular:
3148/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3149/// For this operation, -0.0 is considered to be strictly less than +0.0.
3150///
3151/// Note that, unlike most intrinsics, this is safe to call;
3152/// it does not require an `unsafe` block.
3153/// Therefore, implementations must not require the user to uphold
3154/// any safety invariants.
3155#[rustc_nounwind]
3156#[rustc_intrinsic]
3157pub const fn minimumf64(x: f64, y: f64) -> f64 {
3158    if x < y {
3159        x
3160    } else if y < x {
3161        y
3162    } else if x == y {
3163        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3164    } else {
3165        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3166        x + y
3167    }
3168}
3169
3170/// Returns the minimum of two `f128` values, propagating NaN.
3171///
3172/// This behaves like IEEE 754-2019 minimum. In particular:
3173/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3174/// For this operation, -0.0 is considered to be strictly less than +0.0.
3175///
3176/// Note that, unlike most intrinsics, this is safe to call;
3177/// it does not require an `unsafe` block.
3178/// Therefore, implementations must not require the user to uphold
3179/// any safety invariants.
3180#[rustc_nounwind]
3181#[rustc_intrinsic]
3182pub const fn minimumf128(x: f128, y: f128) -> f128 {
3183    if x < y {
3184        x
3185    } else if y < x {
3186        y
3187    } else if x == y {
3188        if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3189    } else {
3190        // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3191        x + y
3192    }
3193}
3194
3195/// Returns the maximum of two `f16` values, ignoring NaN.
3196///
3197/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3198/// zeros deterministically. In particular:
3199/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3200/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3201/// and `-0.0`), either input may be returned non-deterministically.
3202///
3203/// Note that, unlike most intrinsics, this is safe to call;
3204/// it does not require an `unsafe` block.
3205/// Therefore, implementations must not require the user to uphold
3206/// any safety invariants.
3207///
3208/// The stabilized version of this intrinsic is [`f16::max`].
3209#[rustc_nounwind]
3210#[rustc_intrinsic]
3211pub const fn maximum_number_nsz_f16(x: f16, y: f16) -> f16 {
3212    if x.is_nan() || y >= x {
3213        y
3214    } else {
3215        // Either y < x or y is a NaN.
3216        x
3217    }
3218}
3219
3220/// Returns the maximum of two `f32` values, ignoring NaN.
3221///
3222/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3223/// zeros deterministically. In particular:
3224/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3225/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3226/// and `-0.0`), either input may be returned non-deterministically.
3227///
3228/// Note that, unlike most intrinsics, this is safe to call;
3229/// it does not require an `unsafe` block.
3230/// Therefore, implementations must not require the user to uphold
3231/// any safety invariants.
3232///
3233/// The stabilized version of this intrinsic is [`f32::max`].
3234#[rustc_nounwind]
3235#[rustc_intrinsic_const_stable_indirect]
3236#[rustc_intrinsic]
3237pub const fn maximum_number_nsz_f32(x: f32, y: f32) -> f32 {
3238    if x.is_nan() || y >= x {
3239        y
3240    } else {
3241        // Either y < x or y is a NaN.
3242        x
3243    }
3244}
3245
3246/// Returns the maximum of two `f64` values, ignoring NaN.
3247///
3248/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3249/// zeros deterministically. In particular:
3250/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3251/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3252/// and `-0.0`), either input may be returned non-deterministically.
3253///
3254/// Note that, unlike most intrinsics, this is safe to call;
3255/// it does not require an `unsafe` block.
3256/// Therefore, implementations must not require the user to uphold
3257/// any safety invariants.
3258///
3259/// The stabilized version of this intrinsic is [`f64::max`].
3260#[rustc_nounwind]
3261#[rustc_intrinsic_const_stable_indirect]
3262#[rustc_intrinsic]
3263pub const fn maximum_number_nsz_f64(x: f64, y: f64) -> f64 {
3264    if x.is_nan() || y >= x {
3265        y
3266    } else {
3267        // Either y < x or y is a NaN.
3268        x
3269    }
3270}
3271
3272/// Returns the maximum of two `f128` values, ignoring NaN.
3273///
3274/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3275/// zeros deterministically. In particular:
3276/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3277/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3278/// and `-0.0`), either input may be returned non-deterministically.
3279///
3280/// Note that, unlike most intrinsics, this is safe to call;
3281/// it does not require an `unsafe` block.
3282/// Therefore, implementations must not require the user to uphold
3283/// any safety invariants.
3284///
3285/// The stabilized version of this intrinsic is [`f128::max`].
3286#[rustc_nounwind]
3287#[rustc_intrinsic]
3288pub const fn maximum_number_nsz_f128(x: f128, y: f128) -> f128 {
3289    if x.is_nan() || y >= x {
3290        y
3291    } else {
3292        // Either y < x or y is a NaN.
3293        x
3294    }
3295}
3296
3297/// Returns the maximum of two `f16` values, propagating NaN.
3298///
3299/// This behaves like IEEE 754-2019 maximum. In particular:
3300/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3301/// For this operation, -0.0 is considered to be strictly less than +0.0.
3302///
3303/// Note that, unlike most intrinsics, this is safe to call;
3304/// it does not require an `unsafe` block.
3305/// Therefore, implementations must not require the user to uphold
3306/// any safety invariants.
3307#[rustc_nounwind]
3308#[rustc_intrinsic]
3309pub const fn maximumf16(x: f16, y: f16) -> f16 {
3310    if x > y {
3311        x
3312    } else if y > x {
3313        y
3314    } else if x == y {
3315        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3316    } else {
3317        x + y
3318    }
3319}
3320
3321/// Returns the maximum of two `f32` values, propagating NaN.
3322///
3323/// This behaves like IEEE 754-2019 maximum. In particular:
3324/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3325/// For this operation, -0.0 is considered to be strictly less than +0.0.
3326///
3327/// Note that, unlike most intrinsics, this is safe to call;
3328/// it does not require an `unsafe` block.
3329/// Therefore, implementations must not require the user to uphold
3330/// any safety invariants.
3331#[rustc_nounwind]
3332#[rustc_intrinsic]
3333pub const fn maximumf32(x: f32, y: f32) -> f32 {
3334    if x > y {
3335        x
3336    } else if y > x {
3337        y
3338    } else if x == y {
3339        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3340    } else {
3341        x + y
3342    }
3343}
3344
3345/// Returns the maximum of two `f64` values, propagating NaN.
3346///
3347/// This behaves like IEEE 754-2019 maximum. In particular:
3348/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3349/// For this operation, -0.0 is considered to be strictly less than +0.0.
3350///
3351/// Note that, unlike most intrinsics, this is safe to call;
3352/// it does not require an `unsafe` block.
3353/// Therefore, implementations must not require the user to uphold
3354/// any safety invariants.
3355#[rustc_nounwind]
3356#[rustc_intrinsic]
3357pub const fn maximumf64(x: f64, y: f64) -> f64 {
3358    if x > y {
3359        x
3360    } else if y > x {
3361        y
3362    } else if x == y {
3363        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3364    } else {
3365        x + y
3366    }
3367}
3368
3369/// Returns the maximum of two `f128` values, propagating NaN.
3370///
3371/// This behaves like IEEE 754-2019 maximum. In particular:
3372/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3373/// For this operation, -0.0 is considered to be strictly less than +0.0.
3374///
3375/// Note that, unlike most intrinsics, this is safe to call;
3376/// it does not require an `unsafe` block.
3377/// Therefore, implementations must not require the user to uphold
3378/// any safety invariants.
3379#[rustc_nounwind]
3380#[rustc_intrinsic]
3381pub const fn maximumf128(x: f128, y: f128) -> f128 {
3382    if x > y {
3383        x
3384    } else if y > x {
3385        y
3386    } else if x == y {
3387        if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3388    } else {
3389        x + y
3390    }
3391}
3392
3393/// Returns the absolute value of a floating-point value.
3394///
3395/// The stabilized versions of this intrinsic are available on the float
3396/// primitives via the `abs` method. For example, [`f32::abs`].
3397#[rustc_nounwind]
3398#[rustc_intrinsic_const_stable_indirect]
3399#[rustc_intrinsic]
3400pub const fn fabs<T: bounds::FloatPrimitive>(x: T) -> T;
3401
3402/// Copies the sign from `y` to `x` for `f16` values.
3403///
3404/// The stabilized version of this intrinsic is
3405/// [`f16::copysign`](../../std/primitive.f16.html#method.copysign)
3406#[rustc_nounwind]
3407#[rustc_intrinsic]
3408pub const fn copysignf16(x: f16, y: f16) -> f16;
3409
3410/// Copies the sign from `y` to `x` for `f32` values.
3411///
3412/// The stabilized version of this intrinsic is
3413/// [`f32::copysign`](../../std/primitive.f32.html#method.copysign)
3414#[rustc_nounwind]
3415#[rustc_intrinsic_const_stable_indirect]
3416#[rustc_intrinsic]
3417pub const fn copysignf32(x: f32, y: f32) -> f32;
3418/// Copies the sign from `y` to `x` for `f64` values.
3419///
3420/// The stabilized version of this intrinsic is
3421/// [`f64::copysign`](../../std/primitive.f64.html#method.copysign)
3422#[rustc_nounwind]
3423#[rustc_intrinsic_const_stable_indirect]
3424#[rustc_intrinsic]
3425pub const fn copysignf64(x: f64, y: f64) -> f64;
3426
3427/// Copies the sign from `y` to `x` for `f128` values.
3428///
3429/// The stabilized version of this intrinsic is
3430/// [`f128::copysign`](../../std/primitive.f128.html#method.copysign)
3431#[rustc_nounwind]
3432#[rustc_intrinsic]
3433pub const fn copysignf128(x: f128, y: f128) -> f128;
3434
3435/// Generates the LLVM body for the automatic differentiation of `f` using Enzyme,
3436/// with `df` as the derivative function and `args` as its arguments.
3437///
3438/// Used internally as the body of `df` when expanding the `#[autodiff_forward]`
3439/// and `#[autodiff_reverse]` attribute macros.
3440///
3441/// Type Parameters:
3442/// - `F`: The original function to differentiate. Must be a function item.
3443/// - `G`: The derivative function. Must be a function item.
3444/// - `T`: A tuple of arguments passed to `df`.
3445/// - `R`: The return type of the derivative function.
3446///
3447/// This shows where the `autodiff` intrinsic is used during macro expansion:
3448///
3449/// ```rust,ignore (macro example)
3450/// #[autodiff_forward(df1, Dual, Const, Dual)]
3451/// pub fn f1(x: &[f64], y: f64) -> f64 {
3452///     unimplemented!()
3453/// }
3454/// ```
3455///
3456/// expands to:
3457///
3458/// ```rust,ignore (macro example)
3459/// #[rustc_autodiff]
3460/// #[inline(never)]
3461/// pub fn f1(x: &[f64], y: f64) -> f64 {
3462///     ::core::panicking::panic("not implemented")
3463/// }
3464/// #[rustc_autodiff(Forward, 1, Dual, Const, Dual)]
3465/// pub fn df1(x: &[f64], bx_0: &[f64], y: f64) -> (f64, f64) {
3466///     ::core::intrinsics::autodiff(f1::<>, df1::<>, (x, bx_0, y))
3467/// }
3468/// ```
3469#[rustc_nounwind]
3470#[rustc_intrinsic]
3471pub const fn autodiff<F, G, T: crate::marker::Tuple, R>(f: F, df: G, args: T) -> R;
3472
3473/// Generates the LLVM body of a wrapper function to offload a kernel `f`.
3474///
3475/// Type Parameters:
3476/// - `F`: The kernel to offload. Must be a function item.
3477/// - `T`: A tuple of arguments passed to `f`.
3478/// - `R`: The return type of the kernel.
3479///
3480/// Arguments:
3481/// - `f`: The kernel function to offload.
3482/// - `workgroup_dim`: A 3D size specifying the number of workgroups to launch.
3483/// - `thread_dim`: A 3D size specifying the number of threads per workgroup.
3484/// - `args`: A tuple of arguments forwarded to `f`.
3485///
3486/// Example usage (pseudocode):
3487///
3488/// ```rust,ignore (pseudocode)
3489/// fn kernel(x: *mut [f64; 128]) {
3490///     core::intrinsics::offload(kernel_1, [256, 1, 1], [32, 1, 1], (x,))
3491/// }
3492///
3493/// #[cfg(target_os = "linux")]
3494/// extern "C" {
3495///     pub fn kernel_1(array_b: *mut [f64; 128]);
3496/// }
3497///
3498/// #[cfg(not(target_os = "linux"))]
3499/// #[rustc_offload_kernel]
3500/// extern "gpu-kernel" fn kernel_1(x: *mut [f64; 128]) {
3501///     unsafe { (*x)[0] = 21.0 };
3502/// }
3503/// ```
3504///
3505/// For reference, see the Clang documentation on offloading:
3506/// <https://clang.llvm.org/docs/OffloadingDesign.html>.
3507#[rustc_nounwind]
3508#[rustc_intrinsic]
3509pub const fn offload<F, T: crate::marker::Tuple, R>(
3510    f: F,
3511    workgroup_dim: [u32; 3],
3512    thread_dim: [u32; 3],
3513    args: T,
3514) -> R;
3515
3516/// Inform Miri that a given pointer definitely has a certain alignment.
3517#[cfg(miri)]
3518#[rustc_allow_const_fn_unstable(const_eval_select)]
3519pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize) {
3520    unsafe extern "Rust" {
3521        /// Miri-provided extern function to promise that a given pointer is properly aligned for
3522        /// "symbolic" alignment checks. Will fail if the pointer is not actually aligned or `align` is
3523        /// not a power of two. Has no effect when alignment checks are concrete (which is the default).
3524        fn miri_promise_symbolic_alignment(ptr: *const (), align: usize);
3525    }
3526
3527    const_eval_select!(
3528        @capture { ptr: *const (), align: usize}:
3529        if const {
3530            // Do nothing.
3531        } else {
3532            // SAFETY: this call is always safe.
3533            unsafe {
3534                miri_promise_symbolic_alignment(ptr, align);
3535            }
3536        }
3537    )
3538}
3539
3540/// Loads an argument of type `T` from the `va_list` `ap` and increment the
3541/// argument `ap` points to.
3542///
3543/// # Safety
3544///
3545/// This function is only sound to call when:
3546///
3547/// - there is a next variable argument available.
3548/// - the next argument's type must be ABI-compatible with the type `T`.
3549/// - the next argument must have a properly initialized value of type `T`.
3550///
3551/// Calling this function with an incompatible type, an invalid value, or when there
3552/// are no more variable arguments, is unsound.
3553///
3554#[rustc_intrinsic]
3555#[rustc_nounwind]
3556pub const unsafe fn va_arg<T: VaArgSafe>(ap: &mut VaList<'_>) -> T;
3557
3558/// Duplicates a variable argument list. The returned list is initially at the same position as
3559/// the one in `src`, but can be advanced independently.
3560///
3561/// Codegen backends should not have custom behavior for this intrinsic, they should always use
3562/// this fallback implementation. This intrinsic *does not* map to the LLVM `va_copy` intrinsic.
3563///
3564/// This intrinsic exists only as a hook for Miri and constant evaluation, and is used to detect UB
3565/// when a variable argument list is used incorrectly.
3566#[rustc_intrinsic]
3567#[rustc_nounwind]
3568pub const fn va_copy<'f>(src: &VaList<'f>) -> VaList<'f> {
3569    src.duplicate()
3570}
3571
3572/// Destroy the variable argument list `ap` after initialization with `va_start` (part of the
3573/// desugaring of `...`) or `va_copy`.
3574///
3575/// Code generation backends should not provide a custom implementation for this intrinsic. This
3576/// intrinsic *does not* map to the LLVM `va_end` intrinsic.
3577///
3578/// This function is a no-op on all current targets, but used as a hook for const evaluation to
3579/// detect UB when a variable argument list is used incorrectly.
3580///
3581/// # Safety
3582///
3583/// `ap` must not be used to access variable arguments after this call.
3584///
3585#[rustc_intrinsic]
3586#[rustc_nounwind]
3587pub const unsafe fn va_end(ap: &mut VaList<'_>) {
3588    /* deliberately does nothing */
3589}