Skip to main content

miri/intrinsics/x86/
avx2.rs

1use rustc_span::Symbol;
2
3use super::{
4    ShiftOp, mpsadbw, packssdw, packsswb, packusdw, packuswb, permute, pmaddbw, pmaddwd, pmulhrsw,
5    psadbw, pshufb, psign, shift_simd_by_scalar,
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 this = self.eval_context_mut();
18        this.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 `_mm{,_mask}_{i32,i64}gather_{epi32,epi64,pd,ps}` functions
24            // Gathers elements from `slice` using `offsets * scale` as indices.
25            // When the highest bit of the corresponding element of `mask` is 0,
26            // the value is copied from `src` instead.
27            "gather.d.d" | "gather.d.d.256" | "gather.d.q" | "gather.d.q.256" | "gather.q.d"
28            | "gather.q.d.256" | "gather.q.q" | "gather.q.q.256" | "gather.d.pd"
29            | "gather.d.pd.256" | "gather.q.pd" | "gather.q.pd.256" | "gather.d.ps"
30            | "gather.d.ps.256" | "gather.q.ps" | "gather.q.ps.256" => {
31                let [src, slice, offsets, mask, scale] =
32                    this.check_shim_sig_llvm_intrinsic(link_name, args)?;
33
34                assert_eq!(dest.layout, src.layout);
35
36                let (src, _) = this.project_to_simd(src)?;
37                let (offsets, offsets_len) = this.project_to_simd(offsets)?;
38                let (mask, mask_len) = this.project_to_simd(mask)?;
39                let (dest, dest_len) = this.project_to_simd(dest)?;
40
41                // There are cases like dest: i32x4, offsets: i64x2
42                // If dest has more elements than offset, extra dest elements are filled with zero.
43                // If offsets has more elements than dest, extra offsets are ignored.
44                let actual_len = dest_len.min(offsets_len);
45
46                assert_eq!(dest_len, mask_len);
47
48                let mask_item_size = mask.layout.field(this, 0).size;
49                let high_bit_offset = mask_item_size.bits().strict_sub(1);
50
51                let scale = this.read_scalar(scale)?.to_i8()?;
52                if !matches!(scale, 1 | 2 | 4 | 8) {
53                    panic!("invalid gather scale {scale}");
54                }
55                let scale = i64::from(scale);
56
57                let slice = this.read_pointer(slice)?;
58                for i in 0..actual_len {
59                    let mask = this.project_index(&mask, i)?;
60                    let dest = this.project_index(&dest, i)?;
61
62                    if this.read_scalar(&mask)?.to_uint(mask_item_size)? >> high_bit_offset != 0 {
63                        let offset = this.project_index(&offsets, i)?;
64                        let offset =
65                            i64::try_from(this.read_scalar(&offset)?.to_int(offset.layout.size)?)
66                                .unwrap();
67                        let ptr = slice.wrapping_signed_offset(offset.strict_mul(scale), &this.tcx);
68                        // Unaligned copy, which is what we want.
69                        this.mem_copy(
70                            ptr,
71                            dest.ptr(),
72                            dest.layout.size,
73                            /*nonoverlapping*/ true,
74                        )?;
75                    } else {
76                        this.copy_op(&this.project_index(&src, i)?, &dest)?;
77                    }
78                }
79                for i in actual_len..dest_len {
80                    let dest = this.project_index(&dest, i)?;
81                    this.write_scalar(Scalar::from_int(0, dest.layout.size), &dest)?;
82                }
83            }
84            // Used to implement the _mm256_maddubs_epi16 function.
85            "pmadd.ub.sw" => {
86                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
87
88                pmaddbw(this, left, right, dest)?;
89            }
90            // Used to implement the _mm256_mpsadbw_epu8 function.
91            // Compute the sum of absolute differences of quadruplets of unsigned
92            // 8-bit integers in `left` and `right`, and store the 16-bit results
93            // in `right`. Quadruplets are selected from `left` and `right` with
94            // offsets specified in `imm`.
95            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mpsadbw_epu8
96            "mpsadbw" => {
97                let [left, right, imm] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
98
99                mpsadbw(this, left, right, imm, dest)?;
100            }
101            // Used to implement the _mm256_mulhrs_epi16 function.
102            // Multiplies packed 16-bit signed integer values, truncates the 32-bit
103            // product to the 18 most significant bits by right-shifting, and then
104            // divides the 18-bit value by 2 (rounding to nearest) by first adding
105            // 1 and then taking the bits `1..=16`.
106            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_mulhrs_epi16
107            "pmul.hr.sw" => {
108                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
109
110                pmulhrsw(this, left, right, dest)?;
111            }
112            // Used to implement the _mm256_packs_epi16 function.
113            // Converts two 16-bit integer vectors to a single 8-bit integer
114            // vector with signed saturation.
115            "packsswb" => {
116                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
117
118                packsswb(this, left, right, dest)?;
119            }
120            // Used to implement the _mm256_packs_epi32 function.
121            // Converts two 32-bit integer vectors to a single 16-bit integer
122            // vector with signed saturation.
123            "packssdw" => {
124                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
125
126                packssdw(this, left, right, dest)?;
127            }
128            // Used to implement the _mm256_packus_epi16 function.
129            // Converts two 16-bit signed integer vectors to a single 8-bit
130            // unsigned integer vector with saturation.
131            "packuswb" => {
132                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
133
134                packuswb(this, left, right, dest)?;
135            }
136            // Used to implement the _mm256_packus_epi32 function.
137            // Concatenates two 32-bit signed integer vectors and converts
138            // the result to a 16-bit unsigned integer vector with saturation.
139            "packusdw" => {
140                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
141
142                packusdw(this, left, right, dest)?;
143            }
144            // Used to implement _mm256_permutevar8x32_epi32 and _mm256_permutevar8x32_ps.
145            "permd" | "permps" => {
146                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
147
148                permute(this, left, right, dest)?;
149            }
150            // Used to implement the _mm256_sad_epu8 function.
151            "psad.bw" => {
152                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
153
154                psadbw(this, left, right, dest)?
155            }
156            // Used to implement the _mm256_shuffle_epi8 intrinsic.
157            // Shuffles bytes from `left` using `right` as pattern.
158            // Each 128-bit block is shuffled independently.
159            "pshuf.b" => {
160                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
161
162                pshufb(this, left, right, dest)?;
163            }
164            // Used to implement the _mm256_sign_epi{8,16,32} functions.
165            // Negates elements from `left` when the corresponding element in
166            // `right` is negative. If an element from `right` is zero, zero
167            // is written to the corresponding output element.
168            // Basically, we multiply `left` with `right.signum()`.
169            "psign.b" | "psign.w" | "psign.d" => {
170                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
171
172                psign(this, 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] = this.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(this, 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] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
201
202                pmaddwd(this, left, right, dest)?;
203            }
204            _ => return interp_ok(EmulateItemResult::NotSupported),
205        }
206        interp_ok(EmulateItemResult::NeedsReturn)
207    }
208}