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