Skip to main content

core/intrinsics/
mod.rs

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