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