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