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