Skip to main content

core/intrinsics/
fallback.rs

1#![unstable(
2    feature = "core_intrinsics_fallbacks",
3    reason = "The fallbacks will never be stable, as they exist only to be called \
4              by the fallback MIR, but they're exported so they can be tested on \
5              platforms where the fallback MIR isn't actually used",
6    issue = "none"
7)]
8#![allow(missing_docs)]
9
10#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
11pub const trait CarryingMulAdd: Copy + 'static {
12    type Unsigned: Copy + 'static;
13    fn carrying_mul_add(
14        self,
15        multiplicand: Self,
16        addend: Self,
17        carry: Self,
18    ) -> (Self::Unsigned, Self);
19}
20
21macro_rules! impl_carrying_mul_add_by_widening {
22    ($($t:ident $u:ident $w:ident,)+) => {$(
23        #[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
24        const impl CarryingMulAdd for $t {
25            type Unsigned = $u;
26            #[inline]
27            #[ferrocene::prevalidated]
28            fn carrying_mul_add(self, a: Self, b: Self, c: Self) -> ($u, $t) {
29                let wide = (self as $w) * (a as $w) + (b as $w) + (c as $w);
30                (wide as _, (wide >> Self::BITS) as _)
31            }
32        }
33    )+};
34}
35impl_carrying_mul_add_by_widening! {
36    u8 u8 u16,
37    u16 u16 u32,
38    u32 u32 u64,
39    u64 u64 u128,
40    usize usize UDoubleSize,
41    i8 u8 i16,
42    i16 u16 i32,
43    i32 u32 i64,
44    i64 u64 i128,
45    isize usize UDoubleSize,
46}
47
48#[cfg(target_pointer_width = "16")]
49type UDoubleSize = u32;
50#[cfg(target_pointer_width = "32")]
51type UDoubleSize = u64;
52#[cfg(target_pointer_width = "64")]
53type UDoubleSize = u128;
54
55#[inline]
56#[ferrocene::prevalidated]
57const fn wide_mul_u128(a: u128, b: u128) -> (u128, u128) {
58    #[inline]
59    #[ferrocene::prevalidated]
60    const fn to_low_high(x: u128) -> [u128; 2] {
61        const MASK: u128 = u64::MAX as _;
62        [x & MASK, x >> 64]
63    }
64    #[inline]
65    #[ferrocene::prevalidated]
66    const fn from_low_high(x: [u128; 2]) -> u128 {
67        x[0] | (x[1] << 64)
68    }
69    #[inline]
70    #[ferrocene::prevalidated]
71    const fn scalar_mul(low_high: [u128; 2], k: u128) -> [u128; 3] {
72        let [x, c] = to_low_high(k * low_high[0]);
73        let [y, z] = to_low_high(k * low_high[1] + c);
74        [x, y, z]
75    }
76    let a = to_low_high(a);
77    let b = to_low_high(b);
78    let low = scalar_mul(a, b[0]);
79    let high = scalar_mul(a, b[1]);
80    let r0 = low[0];
81    let [r1, c] = to_low_high(low[1] + high[0]);
82    let [r2, c] = to_low_high(low[2] + high[1] + c);
83    let r3 = high[2] + c;
84    (from_low_high([r0, r1]), from_low_high([r2, r3]))
85}
86
87#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
88const impl CarryingMulAdd for u128 {
89    type Unsigned = u128;
90    #[inline]
91    #[ferrocene::prevalidated]
92    fn carrying_mul_add(self, b: u128, c: u128, d: u128) -> (u128, u128) {
93        let (low, mut high) = wide_mul_u128(self, b);
94        let (low, carry) = u128::overflowing_add(low, c);
95        high += carry as u128;
96        let (low, carry) = u128::overflowing_add(low, d);
97        high += carry as u128;
98        (low, high)
99    }
100}
101
102#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
103const impl CarryingMulAdd for i128 {
104    type Unsigned = u128;
105    #[inline]
106    #[ferrocene::prevalidated]
107    fn carrying_mul_add(self, b: i128, c: i128, d: i128) -> (u128, i128) {
108        let (low, high) = wide_mul_u128(self as u128, b as u128);
109        let mut high = high as i128;
110        high = high.wrapping_add(i128::wrapping_mul(self >> 127, b));
111        high = high.wrapping_add(i128::wrapping_mul(self, b >> 127));
112        let (low, carry) = u128::overflowing_add(low, c as u128);
113        high = high.wrapping_add((carry as i128) + (c >> 127));
114        let (low, carry) = u128::overflowing_add(low, d as u128);
115        high = high.wrapping_add((carry as i128) + (d >> 127));
116        (low, high)
117    }
118}
119
120#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
121pub const trait DisjointBitOr: Copy + 'static {
122    /// We just need the trait indirection to handle different types
123    /// since calling intrinsics with generics doesn't work.
124    ///
125    /// # Safety
126    ///
127    /// See [`super::disjoint_bitor`], with `self` corresponding to `a` and
128    /// `other` corresponding to `b`.
129    unsafe fn disjoint_bitor(self, other: Self) -> Self;
130}
131macro_rules! zero {
132    (bool) => {
133        false
134    };
135    ($t:ident) => {
136        0
137    };
138}
139macro_rules! impl_disjoint_bitor {
140    ($($t:ident,)+) => {$(
141        #[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
142        const impl DisjointBitOr for $t {
143            #[cfg_attr(miri, track_caller)]
144            #[inline]
145            #[ferrocene::prevalidated]
146            unsafe fn disjoint_bitor(self, other: Self) -> Self {
147                // Note that the assume here is required for UB detection in Miri!
148
149                // SAFETY: our precondition is that there are no bits in common,
150                // so this is just telling that to the backend.
151                unsafe { super::assume((self & other) == zero!($t)) };
152                self | other
153            }
154        }
155    )+};
156}
157impl_disjoint_bitor! {
158    bool,
159    u8, u16, u32, u64, u128, usize,
160    i8, i16, i32, i64, i128, isize,
161}
162
163pub trait FunnelShift: Copy + 'static {
164    /// We just need the trait indirection to handle different types
165    /// since calling intrinsics with generics doesn't work.
166    ///
167    /// # Safety
168    ///
169    /// See [`super::unchecked_funnel_shl`], with `self` corresponding to `a` and
170    /// `right` corresponding to `b`.
171    unsafe fn unchecked_funnel_shl(self, right: Self, shift: u32) -> Self;
172
173    /// We just need the trait indirection to handle different types
174    /// since calling intrinsics with generics doesn't work.
175    ///
176    /// # Safety
177    ///
178    /// See [`super::unchecked_funnel_shr`], with `self` corresponding to `a` and
179    /// `right` corresponding to `b`.
180    unsafe fn unchecked_funnel_shr(self, right: Self, shift: u32) -> Self;
181}
182
183macro_rules! impl_funnel_shifts {
184    ($($type:ident),*) => {$(
185        impl FunnelShift for $type {
186            #[inline]
187            #[ferrocene::prevalidated]
188            unsafe fn unchecked_funnel_shl(self, right: Self, shift: u32) -> Self {
189                if shift == 0 {
190                    self
191                } else {
192                    // SAFETY:
193                    //  - `shift < T::BITS`, which satisfies `unchecked_shl`
194                    //  - this also ensures that `T::BITS - shift < T::BITS` (shift = 0 is checked
195                    //    above), which satisfies `unchecked_shr`
196                    //  - because the types are unsigned, the combination are disjoint bits (this is
197                    //    not true if they're signed, since SHR will fill in the empty space with a
198                    //    sign bit, not zero)
199                    unsafe {
200                        super::disjoint_bitor(
201                            super::unchecked_shl(self, shift),
202                            super::unchecked_shr(right, $type::BITS - shift),
203                        )
204                    }
205                }
206            }
207
208            #[inline]
209            #[ferrocene::prevalidated]
210            unsafe fn unchecked_funnel_shr(self, right: Self, shift: u32) -> Self {
211                if shift == 0 {
212                    right
213                } else {
214                    // SAFETY:
215                    //  - `shift < T::BITS`, which satisfies `unchecked_shr`
216                    //  - this also ensures that `T::BITS - shift < T::BITS` (shift = 0 is checked
217                    //    above), which satisfies `unchecked_shl`
218                    //  - because the types are unsigned, the combination are disjoint bits (this is
219                    //    not true if they're signed, since SHR will fill in the empty space with a
220                    //    sign bit, not zero)
221                    unsafe {
222                        super::disjoint_bitor(
223                            super::unchecked_shl(self, $type::BITS - shift),
224                            super::unchecked_shr(right, shift),
225                        )
226                    }
227                }
228            }
229        }
230    )*};
231}
232
233impl_funnel_shifts! {
234    u8, u16, u32, u64, u128, usize
235}
236
237#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
238pub const trait CarrylessMul: Copy + 'static {
239    /// See [`super::carryless_mul`]; we just need the trait indirection to handle
240    /// different types since calling intrinsics with generics doesn't work.
241    fn carryless_mul(self, rhs: Self) -> Self;
242}
243
244macro_rules! impl_carryless_mul{
245    ($($type:ident),*) => {$(
246        #[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
247        const impl CarrylessMul for $type {
248            #[inline]
249            #[ferrocene::prevalidated]
250            fn carryless_mul(self, rhs: Self) -> Self {
251                let mut result = 0;
252                let mut i = 0;
253
254                while i < $type::BITS {
255                    // If the i-th bit in rhs is set.
256                    if (rhs >> i) & 1 != 0 {
257                        // Then xor the result with `self` shifted to the left by i positions.
258                        result ^= self << i;
259                    }
260                    i += 1;
261                }
262
263                result
264            }
265        }
266    )*};
267}
268
269impl_carryless_mul! {
270    u8, u16, u32, u64, u128, usize
271}