9 // Vectors of pointers are not for public use at the current time.
12 use crate::simd::intrinsics;
13 use crate::simd::{LaneCount, Mask, MaskElement, SupportedLaneCount};
15 /// A SIMD vector of `LANES` elements of type `T`.
17 pub struct Simd<T, const LANES: usize>([T; LANES])
20 LaneCount<LANES>: SupportedLaneCount;
22 impl<T, const LANES: usize> Simd<T, LANES>
24 LaneCount<LANES>: SupportedLaneCount,
27 /// Number of lanes in this vector.
28 pub const LANES: usize = LANES;
30 /// Get the number of lanes in this vector.
31 pub const fn lanes(&self) -> usize {
35 /// Construct a SIMD vector by setting all lanes to the given value.
36 pub const fn splat(value: T) -> Self {
40 /// Returns an array reference containing the entire SIMD vector.
41 pub const fn as_array(&self) -> &[T; LANES] {
45 /// Returns a mutable array reference containing the entire SIMD vector.
46 pub fn as_mut_array(&mut self) -> &mut [T; LANES] {
50 /// Converts an array to a SIMD vector.
51 pub const fn from_array(array: [T; LANES]) -> Self {
55 /// Converts a SIMD vector to an array.
56 pub const fn to_array(self) -> [T; LANES] {
60 /// Converts a slice to a SIMD vector containing `slice[..LANES]`
62 /// `from_slice` will panic if the slice's `len` is less than the vector's `Simd::LANES`.
64 pub const fn from_slice(slice: &[T]) -> Self {
67 "slice length must be at least the number of lanes"
69 let mut array = [slice[0]; LANES];
78 /// Performs lanewise conversion of a SIMD vector's elements to another SIMD-valid type.
79 /// This follows the semantics of Rust's `as` conversion for casting
80 /// integers to unsigned integers (interpreting as the other type, so `-1` to `MAX`),
81 /// and from floats to integers (truncating, or saturating at the limits) for each lane,
86 /// # #![feature(portable_simd)]
87 /// # #[cfg(feature = "std")] use core_simd::Simd;
88 /// # #[cfg(not(feature = "std"))] use core::simd::Simd;
89 /// let floats: Simd<f32, 4> = Simd::from_array([1.9, -4.5, f32::INFINITY, f32::NAN]);
90 /// let ints = floats.cast::<i32>();
91 /// assert_eq!(ints, Simd::from_array([1, -4, i32::MAX, 0]));
93 /// // Formally equivalent, but `Simd::cast` can optimize better.
94 /// assert_eq!(ints, Simd::from_array(floats.to_array().map(|x| x as i32)));
96 /// // The float conversion does not round-trip.
97 /// let floats_again = ints.cast();
98 /// assert_ne!(floats, floats_again);
99 /// assert_eq!(floats_again, Simd::from_array([1.0, -4.0, 2147483647.0, 0.0]));
103 #[cfg(not(bootstrap))]
104 pub fn cast<U: SimdElement>(self) -> Simd<U, LANES> {
105 unsafe { intrinsics::simd_as(self) }
108 /// Reads from potentially discontiguous indices in `slice` to construct a SIMD vector.
109 /// If an index is out-of-bounds, the lane is instead selected from the `or` vector.
113 /// # #![feature(portable_simd)]
114 /// # #[cfg(feature = "std")] use core_simd::Simd;
115 /// # #[cfg(not(feature = "std"))] use core::simd::Simd;
116 /// let vec: Vec<i32> = vec![10, 11, 12, 13, 14, 15, 16, 17, 18];
117 /// let idxs = Simd::from_array([9, 3, 0, 5]);
118 /// let alt = Simd::from_array([-5, -4, -3, -2]);
120 /// let result = Simd::gather_or(&vec, idxs, alt); // Note the lane that is out-of-bounds.
121 /// assert_eq!(result, Simd::from_array([-5, 13, 10, 15]));
125 pub fn gather_or(slice: &[T], idxs: Simd<usize, LANES>, or: Self) -> Self {
126 Self::gather_select(slice, Mask::splat(true), idxs, or)
129 /// Reads from potentially discontiguous indices in `slice` to construct a SIMD vector.
130 /// If an index is out-of-bounds, the lane is set to the default value for the type.
134 /// # #![feature(portable_simd)]
135 /// # #[cfg(feature = "std")] use core_simd::Simd;
136 /// # #[cfg(not(feature = "std"))] use core::simd::Simd;
137 /// let vec: Vec<i32> = vec![10, 11, 12, 13, 14, 15, 16, 17, 18];
138 /// let idxs = Simd::from_array([9, 3, 0, 5]);
140 /// let result = Simd::gather_or_default(&vec, idxs); // Note the lane that is out-of-bounds.
141 /// assert_eq!(result, Simd::from_array([0, 13, 10, 15]));
145 pub fn gather_or_default(slice: &[T], idxs: Simd<usize, LANES>) -> Self
149 Self::gather_or(slice, idxs, Self::splat(T::default()))
152 /// Reads from potentially discontiguous indices in `slice` to construct a SIMD vector.
153 /// The mask `enable`s all `true` lanes and disables all `false` lanes.
154 /// If an index is disabled or is out-of-bounds, the lane is selected from the `or` vector.
158 /// # #![feature(portable_simd)]
159 /// # #[cfg(feature = "std")] use core_simd::{Simd, Mask};
160 /// # #[cfg(not(feature = "std"))] use core::simd::{Simd, Mask};
161 /// let vec: Vec<i32> = vec![10, 11, 12, 13, 14, 15, 16, 17, 18];
162 /// let idxs = Simd::from_array([9, 3, 0, 5]);
163 /// let alt = Simd::from_array([-5, -4, -3, -2]);
164 /// let enable = Mask::from_array([true, true, true, false]); // Note the mask of the last lane.
166 /// let result = Simd::gather_select(&vec, enable, idxs, alt); // Note the lane that is out-of-bounds.
167 /// assert_eq!(result, Simd::from_array([-5, 13, 10, -2]));
171 pub fn gather_select(
173 enable: Mask<isize, LANES>,
174 idxs: Simd<usize, LANES>,
177 let enable: Mask<isize, LANES> = enable & idxs.lanes_lt(Simd::splat(slice.len()));
178 // SAFETY: We have masked-off out-of-bounds lanes.
179 unsafe { Self::gather_select_unchecked(slice, enable, idxs, or) }
182 /// Reads from potentially discontiguous indices in `slice` to construct a SIMD vector.
183 /// The mask `enable`s all `true` lanes and disables all `false` lanes.
184 /// If an index is disabled, the lane is selected from the `or` vector.
188 /// Calling this function with an `enable`d out-of-bounds index is *[undefined behavior]*
189 /// even if the resulting value is not used.
193 /// # #![feature(portable_simd)]
194 /// # #[cfg(feature = "std")] use core_simd::{Simd, Mask};
195 /// # #[cfg(not(feature = "std"))] use core::simd::{Simd, Mask};
196 /// let vec: Vec<i32> = vec![10, 11, 12, 13, 14, 15, 16, 17, 18];
197 /// let idxs = Simd::from_array([9, 3, 0, 5]);
198 /// let alt = Simd::from_array([-5, -4, -3, -2]);
199 /// let enable = Mask::from_array([true, true, true, false]); // Note the final mask lane.
200 /// // If this mask was used to gather, it would be unsound. Let's fix that.
201 /// let enable = enable & idxs.lanes_lt(Simd::splat(vec.len()));
203 /// // We have masked the OOB lane, so it's safe to gather now.
204 /// let result = unsafe { Simd::gather_select_unchecked(&vec, enable, idxs, alt) };
205 /// assert_eq!(result, Simd::from_array([-5, 13, 10, -2]));
207 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
210 pub unsafe fn gather_select_unchecked(
212 enable: Mask<isize, LANES>,
213 idxs: Simd<usize, LANES>,
216 let base_ptr = crate::simd::ptr::SimdConstPtr::splat(slice.as_ptr());
217 // Ferris forgive me, I have done pointer arithmetic here.
218 let ptrs = base_ptr.wrapping_add(idxs);
219 // SAFETY: The ptrs have been bounds-masked to prevent memory-unsafe reads insha'allah
220 unsafe { intrinsics::simd_gather(or, ptrs, enable.to_int()) }
223 /// Writes the values in a SIMD vector to potentially discontiguous indices in `slice`.
224 /// If two lanes in the scattered vector would write to the same index
225 /// only the last lane is guaranteed to actually be written.
229 /// # #![feature(portable_simd)]
230 /// # #[cfg(feature = "std")] use core_simd::Simd;
231 /// # #[cfg(not(feature = "std"))] use core::simd::Simd;
232 /// let mut vec: Vec<i32> = vec![10, 11, 12, 13, 14, 15, 16, 17, 18];
233 /// let idxs = Simd::from_array([9, 3, 0, 0]);
234 /// let vals = Simd::from_array([-27, 82, -41, 124]);
236 /// vals.scatter(&mut vec, idxs); // index 0 receives two writes.
237 /// assert_eq!(vec, vec![124, 11, 12, 82, 14, 15, 16, 17, 18]);
240 pub fn scatter(self, slice: &mut [T], idxs: Simd<usize, LANES>) {
241 self.scatter_select(slice, Mask::splat(true), idxs)
244 /// Writes the values in a SIMD vector to multiple potentially discontiguous indices in `slice`.
245 /// The mask `enable`s all `true` lanes and disables all `false` lanes.
246 /// If an enabled index is out-of-bounds, the lane is not written.
247 /// If two enabled lanes in the scattered vector would write to the same index,
248 /// only the last lane is guaranteed to actually be written.
252 /// # #![feature(portable_simd)]
253 /// # #[cfg(feature = "std")] use core_simd::{Simd, Mask};
254 /// # #[cfg(not(feature = "std"))] use core::simd::{Simd, Mask};
255 /// let mut vec: Vec<i32> = vec![10, 11, 12, 13, 14, 15, 16, 17, 18];
256 /// let idxs = Simd::from_array([9, 3, 0, 0]);
257 /// let vals = Simd::from_array([-27, 82, -41, 124]);
258 /// let enable = Mask::from_array([true, true, true, false]); // Note the mask of the last lane.
260 /// vals.scatter_select(&mut vec, enable, idxs); // index 0's second write is masked, thus omitted.
261 /// assert_eq!(vec, vec![-41, 11, 12, 82, 14, 15, 16, 17, 18]);
264 pub fn scatter_select(
267 enable: Mask<isize, LANES>,
268 idxs: Simd<usize, LANES>,
270 let enable: Mask<isize, LANES> = enable & idxs.lanes_lt(Simd::splat(slice.len()));
271 // SAFETY: We have masked-off out-of-bounds lanes.
272 unsafe { self.scatter_select_unchecked(slice, enable, idxs) }
275 /// Writes the values in a SIMD vector to multiple potentially discontiguous indices in `slice`.
276 /// The mask `enable`s all `true` lanes and disables all `false` lanes.
277 /// If two enabled lanes in the scattered vector would write to the same index,
278 /// only the last lane is guaranteed to actually be written.
282 /// Calling this function with an enabled out-of-bounds index is *[undefined behavior]*,
283 /// and may lead to memory corruption.
287 /// # #![feature(portable_simd)]
288 /// # #[cfg(feature = "std")] use core_simd::{Simd, Mask};
289 /// # #[cfg(not(feature = "std"))] use core::simd::{Simd, Mask};
290 /// let mut vec: Vec<i32> = vec![10, 11, 12, 13, 14, 15, 16, 17, 18];
291 /// let idxs = Simd::from_array([9, 3, 0, 0]);
292 /// let vals = Simd::from_array([-27, 82, -41, 124]);
293 /// let enable = Mask::from_array([true, true, true, false]); // Note the mask of the last lane.
294 /// // If this mask was used to scatter, it would be unsound. Let's fix that.
295 /// let enable = enable & idxs.lanes_lt(Simd::splat(vec.len()));
297 /// // We have masked the OOB lane, so it's safe to scatter now.
298 /// unsafe { vals.scatter_select_unchecked(&mut vec, enable, idxs); }
299 /// // index 0's second write is masked, thus was omitted.
300 /// assert_eq!(vec, vec![-41, 11, 12, 82, 14, 15, 16, 17, 18]);
302 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
304 pub unsafe fn scatter_select_unchecked(
307 enable: Mask<isize, LANES>,
308 idxs: Simd<usize, LANES>,
310 // SAFETY: This block works with *mut T derived from &mut 'a [T],
311 // which means it is delicate in Rust's borrowing model, circa 2021:
312 // &mut 'a [T] asserts uniqueness, so deriving &'a [T] invalidates live *mut Ts!
313 // Even though this block is largely safe methods, it must be exactly this way
314 // to prevent invalidating the raw ptrs while they're live.
315 // Thus, entering this block requires all values to use being already ready:
316 // 0. idxs we want to write to, which are used to construct the mask.
317 // 1. enable, which depends on an initial &'a [T] and the idxs.
318 // 2. actual values to scatter (self).
319 // 3. &mut [T] which will become our base ptr.
321 // Now Entering ☢️ *mut T Zone
322 let base_ptr = crate::simd::ptr::SimdMutPtr::splat(slice.as_mut_ptr());
323 // Ferris forgive me, I have done pointer arithmetic here.
324 let ptrs = base_ptr.wrapping_add(idxs);
325 // The ptrs have been bounds-masked to prevent memory-unsafe writes insha'allah
326 intrinsics::simd_scatter(self, ptrs, enable.to_int())
327 // Cleared ☢️ *mut T Zone
332 impl<T, const LANES: usize> Copy for Simd<T, LANES>
335 LaneCount<LANES>: SupportedLaneCount,
339 impl<T, const LANES: usize> Clone for Simd<T, LANES>
342 LaneCount<LANES>: SupportedLaneCount,
344 fn clone(&self) -> Self {
349 impl<T, const LANES: usize> Default for Simd<T, LANES>
351 LaneCount<LANES>: SupportedLaneCount,
352 T: SimdElement + Default,
355 fn default() -> Self {
356 Self::splat(T::default())
360 impl<T, const LANES: usize> PartialEq for Simd<T, LANES>
362 LaneCount<LANES>: SupportedLaneCount,
363 T: SimdElement + PartialEq,
366 fn eq(&self, other: &Self) -> bool {
367 // TODO use SIMD equality
368 self.to_array() == other.to_array()
372 impl<T, const LANES: usize> PartialOrd for Simd<T, LANES>
374 LaneCount<LANES>: SupportedLaneCount,
375 T: SimdElement + PartialOrd,
378 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
379 // TODO use SIMD equality
380 self.to_array().partial_cmp(other.as_ref())
384 impl<T, const LANES: usize> Eq for Simd<T, LANES>
386 LaneCount<LANES>: SupportedLaneCount,
391 impl<T, const LANES: usize> Ord for Simd<T, LANES>
393 LaneCount<LANES>: SupportedLaneCount,
394 T: SimdElement + Ord,
397 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
398 // TODO use SIMD equality
399 self.to_array().cmp(other.as_ref())
403 impl<T, const LANES: usize> core::hash::Hash for Simd<T, LANES>
405 LaneCount<LANES>: SupportedLaneCount,
406 T: SimdElement + core::hash::Hash,
409 fn hash<H>(&self, state: &mut H)
411 H: core::hash::Hasher,
413 self.as_array().hash(state)
418 impl<T, const LANES: usize> AsRef<[T; LANES]> for Simd<T, LANES>
420 LaneCount<LANES>: SupportedLaneCount,
424 fn as_ref(&self) -> &[T; LANES] {
429 impl<T, const LANES: usize> AsMut<[T; LANES]> for Simd<T, LANES>
431 LaneCount<LANES>: SupportedLaneCount,
435 fn as_mut(&mut self) -> &mut [T; LANES] {
441 impl<T, const LANES: usize> AsRef<[T]> for Simd<T, LANES>
443 LaneCount<LANES>: SupportedLaneCount,
447 fn as_ref(&self) -> &[T] {
452 impl<T, const LANES: usize> AsMut<[T]> for Simd<T, LANES>
454 LaneCount<LANES>: SupportedLaneCount,
458 fn as_mut(&mut self) -> &mut [T] {
463 // vector/array conversion
464 impl<T, const LANES: usize> From<[T; LANES]> for Simd<T, LANES>
466 LaneCount<LANES>: SupportedLaneCount,
469 fn from(array: [T; LANES]) -> Self {
474 impl<T, const LANES: usize> From<Simd<T, LANES>> for [T; LANES]
476 LaneCount<LANES>: SupportedLaneCount,
479 fn from(vector: Simd<T, LANES>) -> Self {
489 /// Marker trait for types that may be used as SIMD vector elements.
490 /// SAFETY: This trait, when implemented, asserts the compiler can monomorphize
491 /// `#[repr(simd)]` structs with the marked type as an element.
492 /// Strictly, it is valid to impl if the vector will not be miscompiled.
493 /// Practically, it is user-unfriendly to impl it if the vector won't compile,
494 /// even when no soundness guarantees are broken by allowing the user to try.
495 pub unsafe trait SimdElement: Sealed + Copy {
496 /// The mask element type corresponding to this element type.
497 type Mask: MaskElement;
500 impl Sealed for u8 {}
501 unsafe impl SimdElement for u8 {
505 impl Sealed for u16 {}
506 unsafe impl SimdElement for u16 {
510 impl Sealed for u32 {}
511 unsafe impl SimdElement for u32 {
515 impl Sealed for u64 {}
516 unsafe impl SimdElement for u64 {
520 impl Sealed for usize {}
521 unsafe impl SimdElement for usize {
525 impl Sealed for i8 {}
526 unsafe impl SimdElement for i8 {
530 impl Sealed for i16 {}
531 unsafe impl SimdElement for i16 {
535 impl Sealed for i32 {}
536 unsafe impl SimdElement for i32 {
540 impl Sealed for i64 {}
541 unsafe impl SimdElement for i64 {
545 impl Sealed for isize {}
546 unsafe impl SimdElement for isize {
550 impl Sealed for f32 {}
551 unsafe impl SimdElement for f32 {
555 impl Sealed for f64 {}
556 unsafe impl SimdElement for f64 {