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