Skip to main content

miri/intrinsics/x86/
avx2.rs

1use rustc_span::Symbol;
2
3use super::{
4    ShiftOp, mpsadbw, packssdw, packsswb, packusdw, packuswb, pavg, permute, pmaddbw, pmaddwd,
5    pmulh, pmulhrsw, psadbw, pshufb, psign, shift_simd_by_scalar, shift_simd_by_simd,
6};
7use crate::*;
8
9impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
10pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
11    fn emulate_x86_avx2_intrinsic(
12        &mut self,
13        link_name: Symbol,
14        args: &[OpTy<'tcx>],
15        dest: &MPlaceTy<'tcx>,
16    ) -> InterpResult<'tcx, EmulateItemResult> {
17        let ecx = self.eval_context_mut();
18        ecx.expect_target_feature_for_intrinsic(link_name, "avx2")?;
19        // Prefix should have already been checked.
20        let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.avx2.").unwrap();
21
22        match unprefixed_name {
23            // Used to implement the _mm256_avg_epu8 and _mm256_avg_epu16 functions.
24            // Averages packed unsigned 8/16-bit integers in `left` and `right`.
25            "pavg.b" | "pavg.w" => {
26                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
27                pavg(ecx, left, right, dest)?;
28            }
29            // Used to implement the _mm256_mulhi_epi16 and _mm256_mulhi_epu16 functions.
30            "pmulh.w" | "pmulhu.w" => {
31                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
32                pmulh(ecx, left, right, dest)?;
33            }
34            // Used to implement `_mm{,_mask}_{i32,i64}gather_{epi32,epi64,pd,ps}` functions
35            // Gathers elements from `slice` using `offsets * scale` as indices.
36            // When the highest bit of the corresponding element of `mask` is 0,
37            // the value is copied from `src` instead.
38            "gather.d.d" | "gather.d.d.256" | "gather.d.q" | "gather.d.q.256" | "gather.q.d"
39            | "gather.q.d.256" | "gather.q.q" | "gather.q.q.256" | "gather.d.pd"
40            | "gather.d.pd.256" | "gather.q.pd" | "gather.q.pd.256" | "gather.d.ps"
41            | "gather.d.ps.256" | "gather.q.ps" | "gather.q.ps.256" => {
42                let [src, slice, offsets, mask, scale] =
43                    ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
44
45                assert_eq!(dest.layout, src.layout);
46
47                let (src, _) = ecx.project_to_simd(src)?;
48                let (offsets, offsets_len) = ecx.project_to_simd(offsets)?;
49                let (mask, mask_len) = ecx.project_to_simd(mask)?;
50                let (dest, dest_len) = ecx.project_to_simd(dest)?;
51
52                // There are cases like dest: i32x4, offsets: i64x2
53                // If dest has more elements than offset, extra dest elements are filled with zero.
54                // If offsets has more elements than dest, extra offsets are ignored.
55                let actual_len = dest_len.min(offsets_len);
56
57                assert_eq!(dest_len, mask_len);
58
59                let mask_item_size = mask.layout.field(ecx, 0).size;
60                let high_bit_offset = mask_item_size.bits().strict_sub(1);
61
62                let scale = ecx.read_scalar(scale)?.to_i8()?;
63                if !matches!(scale, 1 | 2 | 4 | 8) {
64                    panic!("invalid gather scale {scale}");
65                }
66                let scale = i64::from(scale);
67
68                let slice = ecx.read_pointer(slice)?;
69                for i in 0..actual_len {
70                    let mask = ecx.project_index(&mask, i)?;
71                    let dest = ecx.project_index(&dest, i)?;
72
73                    if ecx.read_scalar(&mask)?.to_uint(mask_item_size)? >> high_bit_offset != 0 {
74                        let offset = ecx.project_index(&offsets, i)?;
75                        let offset =
76                            i64::try_from(ecx.read_scalar(&offset)?.to_int(offset.layout.size)?)
77                                .unwrap();
78                        let ptr = slice.wrapping_signed_offset(offset.strict_mul(scale), &ecx.tcx);
79                        // Unaligned copy, which is what we want.
80                        ecx.mem_copy(
81                            ptr,
82                            dest.ptr(),
83                            dest.layout.size,
84                            /*nonoverlapping*/ true,
85                        )?;
86                    } else {
87                        ecx.copy_op(&ecx.project_index(&src, i)?, &dest)?;
88                    }
89                }
90                for i in actual_len..dest_len {
91                    let dest = ecx.project_index(&dest, i)?;
92                    ecx.write_scalar(Scalar::from_int(0, dest.layout.size), &dest)?;
93                }
94            }
95            // Used to implement the _mm256_maddubs_epi16 function.
96            "pmadd.ub.sw" => {
97                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
98                pmaddbw(ecx, left, right, dest)?;
99            }
100            // Used to implement the _mm256_mpsadbw_epu8 function.
101            // Compute the sum of absolute differences of quadruplets of unsigned
102            // 8-bit integers in `left` and `right`, and store the 16-bit results
103            // in `right`. Quadruplets are selected from `left` and `right` with
104            // offsets specified in `imm`.
105            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mpsadbw_epu8
106            "mpsadbw" => {
107                let [left, right, imm] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
108                mpsadbw(ecx, left, right, imm, dest)?;
109            }
110            // Used to implement the _mm256_mulhrs_epi16 function.
111            // Multiplies packed 16-bit signed integer values, truncates the 32-bit
112            // product to the 18 most significant bits by right-shifting, and then
113            // divides the 18-bit value by 2 (rounding to nearest) by first adding
114            // 1 and then taking the bits `1..=16`.
115            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mulhrs_epi16
116            "pmul.hr.sw" => {
117                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
118                pmulhrsw(ecx, left, right, dest)?;
119            }
120            // Used to implement the _mm256_packs_epi16 function.
121            // Converts two 16-bit integer vectors to a single 8-bit integer
122            // vector with signed saturation.
123            "packsswb" => {
124                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
125                packsswb(ecx, left, right, dest)?;
126            }
127            // Used to implement the _mm256_packs_epi32 function.
128            // Converts two 32-bit integer vectors to a single 16-bit integer
129            // vector with signed saturation.
130            "packssdw" => {
131                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
132                packssdw(ecx, left, right, dest)?;
133            }
134            // Used to implement the _mm256_packus_epi16 function.
135            // Converts two 16-bit signed integer vectors to a single 8-bit
136            // unsigned integer vector with saturation.
137            "packuswb" => {
138                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
139                packuswb(ecx, left, right, dest)?;
140            }
141            // Used to implement the _mm256_packus_epi32 function.
142            // Concatenates two 32-bit signed integer vectors and converts
143            // the result to a 16-bit unsigned integer vector with saturation.
144            "packusdw" => {
145                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
146                packusdw(ecx, left, right, dest)?;
147            }
148            // Used to implement _mm256_permutevar8x32_epi32 and _mm256_permutevar8x32_ps.
149            "permd" | "permps" => {
150                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
151                permute(ecx, left, right, dest)?;
152            }
153            // Used to implement the _mm256_sad_epu8 function.
154            "psad.bw" => {
155                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
156                psadbw(ecx, left, right, dest)?
157            }
158            // Used to implement the _mm256_shuffle_epi8 intrinsic.
159            // Shuffles bytes from `left` using `right` as pattern.
160            // Each 128-bit block is shuffled independently.
161            "pshuf.b" => {
162                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
163                pshufb(ecx, left, right, dest)?;
164            }
165            // Used to implement the _mm256_sign_epi{8,16,32} functions.
166            // Negates elements from `left` when the corresponding element in
167            // `right` is negative. If an element from `right` is zero, zero
168            // is written to the corresponding output element.
169            // Basically, we multiply `left` with `right.signum()`.
170            "psign.b" | "psign.w" | "psign.d" => {
171                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
172                psign(ecx, left, right, dest)?;
173            }
174            // Used to implement the _mm256_{sll,srl,sra}_epi{16,32,64} functions
175            // (except _mm256_sra_epi64, which is not available in AVX2).
176            // Shifts N-bit packed integers in left by the amount in right.
177            // `right` is as 128-bit vector. but it is interpreted as a single
178            // 64-bit integer (remaining bits are ignored).
179            // For logic shifts, when right is larger than N - 1, zero is produced.
180            // For arithmetic shifts, when right is larger than N - 1, the sign bit
181            // is copied to remaining bits.
182            "psll.w" | "psrl.w" | "psra.w" | "psll.d" | "psrl.d" | "psra.d" | "psll.q"
183            | "psrl.q" => {
184                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
185
186                let which = match unprefixed_name {
187                    "psll.w" | "psll.d" | "psll.q" => ShiftOp::Left,
188                    "psrl.w" | "psrl.d" | "psrl.q" => ShiftOp::RightLogic,
189                    "psra.w" | "psra.d" => ShiftOp::RightArith,
190                    _ => unreachable!(),
191                };
192
193                shift_simd_by_scalar(ecx, left, right, which, dest)?;
194            }
195            // Used to implement the _mm256_madd_epi16 function.
196            // Multiplies packed signed 16-bit integers in `left` and `right`, producing
197            // intermediate signed 32-bit integers. Horizontally add adjacent pairs of
198            // intermediate 32-bit integers, and pack the results in `dest`.
199            "pmadd.wd" => {
200                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
201
202                pmaddwd(ecx, left, right, dest)?;
203            }
204            // Used to implement the _mm{,256}_{sllv,srlv,srav}_epi{32,64} functions
205            // (except _mm{,256}_srav_epi64, which are not available in AVX2).
206            "psllv.d" | "psllv.d.256" | "psllv.q" | "psllv.q.256" | "psrlv.d" | "psrlv.d.256"
207            | "psrlv.q" | "psrlv.q.256" | "psrav.d" | "psrav.d.256" => {
208                let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
209
210                let which = match unprefixed_name {
211                    "psllv.d" | "psllv.d.256" | "psllv.q" | "psllv.q.256" => ShiftOp::Left,
212                    "psrlv.d" | "psrlv.d.256" | "psrlv.q" | "psrlv.q.256" => ShiftOp::RightLogic,
213                    "psrav.d" | "psrav.d.256" => ShiftOp::RightArith,
214                    _ => unreachable!(),
215                };
216
217                shift_simd_by_simd(ecx, left, right, which, dest)?;
218            }
219
220            _ => return interp_ok(EmulateItemResult::NotSupported),
221        }
222        interp_ok(EmulateItemResult::NeedsReturn)
223    }
224}