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