miri/shims/x86/sse2.rs
1use rustc_apfloat::ieee::Double;
2use rustc_middle::ty::Ty;
3use rustc_span::Symbol;
4use rustc_target::callconv::{Conv, FnAbi};
5
6use super::{
7 FloatBinOp, ShiftOp, bin_op_simd_float_all, bin_op_simd_float_first, convert_float_to_int,
8 packssdw, packsswb, packuswb, shift_simd_by_scalar,
9};
10use crate::*;
11
12impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
13pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
14 fn emulate_x86_sse2_intrinsic(
15 &mut self,
16 link_name: Symbol,
17 abi: &FnAbi<'tcx, Ty<'tcx>>,
18 args: &[OpTy<'tcx>],
19 dest: &MPlaceTy<'tcx>,
20 ) -> InterpResult<'tcx, EmulateItemResult> {
21 let this = self.eval_context_mut();
22 this.expect_target_feature_for_intrinsic(link_name, "sse2")?;
23 // Prefix should have already been checked.
24 let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.sse2.").unwrap();
25
26 // These intrinsics operate on 128-bit (f32x4, f64x2, i8x16, i16x8, i32x4, i64x2) SIMD
27 // vectors unless stated otherwise.
28 // Many intrinsic names are sufixed with "ps" (packed single), "ss" (scalar signle),
29 // "pd" (packed double) or "sd" (scalar double), where single means single precision
30 // floating point (f32) and double means double precision floating point (f64). "ps"
31 // and "pd" means thet the operation is performed on each element of the vector, while
32 // "ss" and "sd" means that the operation is performed only on the first element, copying
33 // the remaining elements from the input vector (for binary operations, from the left-hand
34 // side).
35 // Intrinsincs sufixed with "epiX" or "epuX" operate with X-bit signed or unsigned
36 // vectors.
37 match unprefixed_name {
38 // Used to implement the _mm_madd_epi16 function.
39 // Multiplies packed signed 16-bit integers in `left` and `right`, producing
40 // intermediate signed 32-bit integers. Horizontally add adjacent pairs of
41 // intermediate 32-bit integers, and pack the results in `dest`.
42 "pmadd.wd" => {
43 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
44
45 let (left, left_len) = this.project_to_simd(left)?;
46 let (right, right_len) = this.project_to_simd(right)?;
47 let (dest, dest_len) = this.project_to_simd(dest)?;
48
49 assert_eq!(left_len, right_len);
50 assert_eq!(dest_len.strict_mul(2), left_len);
51
52 for i in 0..dest_len {
53 let j1 = i.strict_mul(2);
54 let left1 = this.read_scalar(&this.project_index(&left, j1)?)?.to_i16()?;
55 let right1 = this.read_scalar(&this.project_index(&right, j1)?)?.to_i16()?;
56
57 let j2 = j1.strict_add(1);
58 let left2 = this.read_scalar(&this.project_index(&left, j2)?)?.to_i16()?;
59 let right2 = this.read_scalar(&this.project_index(&right, j2)?)?.to_i16()?;
60
61 let dest = this.project_index(&dest, i)?;
62
63 // Multiplications are i16*i16->i32, which will not overflow.
64 let mul1 = i32::from(left1).strict_mul(right1.into());
65 let mul2 = i32::from(left2).strict_mul(right2.into());
66 // However, this addition can overflow in the most extreme case
67 // (-0x8000)*(-0x8000)+(-0x8000)*(-0x8000) = 0x80000000
68 let res = mul1.wrapping_add(mul2);
69
70 this.write_scalar(Scalar::from_i32(res), &dest)?;
71 }
72 }
73 // Used to implement the _mm_sad_epu8 function.
74 // Computes the absolute differences of packed unsigned 8-bit integers in `a`
75 // and `b`, then horizontally sum each consecutive 8 differences to produce
76 // two unsigned 16-bit integers, and pack these unsigned 16-bit integers in
77 // the low 16 bits of 64-bit elements returned.
78 //
79 // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sad_epu8
80 "psad.bw" => {
81 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
82
83 let (left, left_len) = this.project_to_simd(left)?;
84 let (right, right_len) = this.project_to_simd(right)?;
85 let (dest, dest_len) = this.project_to_simd(dest)?;
86
87 // left and right are u8x16, dest is u64x2
88 assert_eq!(left_len, right_len);
89 assert_eq!(left_len, 16);
90 assert_eq!(dest_len, 2);
91
92 for i in 0..dest_len {
93 let dest = this.project_index(&dest, i)?;
94
95 let mut res: u16 = 0;
96 let n = left_len.strict_div(dest_len);
97 for j in 0..n {
98 let op_i = j.strict_add(i.strict_mul(n));
99 let left = this.read_scalar(&this.project_index(&left, op_i)?)?.to_u8()?;
100 let right =
101 this.read_scalar(&this.project_index(&right, op_i)?)?.to_u8()?;
102
103 res = res.strict_add(left.abs_diff(right).into());
104 }
105
106 this.write_scalar(Scalar::from_u64(res.into()), &dest)?;
107 }
108 }
109 // Used to implement the _mm_{sll,srl,sra}_epi{16,32,64} functions
110 // (except _mm_sra_epi64, which is not available in SSE2).
111 // Shifts N-bit packed integers in left by the amount in right.
112 // Both operands are 128-bit vectors. However, right is interpreted as
113 // a single 64-bit integer (remaining bits are ignored).
114 // For logic shifts, when right is larger than N - 1, zero is produced.
115 // For arithmetic shifts, when right is larger than N - 1, the sign bit
116 // is copied to remaining bits.
117 "psll.w" | "psrl.w" | "psra.w" | "psll.d" | "psrl.d" | "psra.d" | "psll.q"
118 | "psrl.q" => {
119 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
120
121 let which = match unprefixed_name {
122 "psll.w" | "psll.d" | "psll.q" => ShiftOp::Left,
123 "psrl.w" | "psrl.d" | "psrl.q" => ShiftOp::RightLogic,
124 "psra.w" | "psra.d" => ShiftOp::RightArith,
125 _ => unreachable!(),
126 };
127
128 shift_simd_by_scalar(this, left, right, which, dest)?;
129 }
130 // Used to implement the _mm_cvtps_epi32, _mm_cvttps_epi32, _mm_cvtpd_epi32
131 // and _mm_cvttpd_epi32 functions.
132 // Converts packed f32/f64 to packed i32.
133 "cvtps2dq" | "cvttps2dq" | "cvtpd2dq" | "cvttpd2dq" => {
134 let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
135
136 let (op_len, _) = op.layout.ty.simd_size_and_type(*this.tcx);
137 let (dest_len, _) = dest.layout.ty.simd_size_and_type(*this.tcx);
138 match unprefixed_name {
139 "cvtps2dq" | "cvttps2dq" => {
140 // f32x4 to i32x4 conversion
141 assert_eq!(op_len, 4);
142 assert_eq!(dest_len, op_len);
143 }
144 "cvtpd2dq" | "cvttpd2dq" => {
145 // f64x2 to i32x4 conversion
146 // the last two values are filled with zeros
147 assert_eq!(op_len, 2);
148 assert_eq!(dest_len, 4);
149 }
150 _ => unreachable!(),
151 }
152
153 let rnd = match unprefixed_name {
154 // "current SSE rounding mode", assume nearest
155 // https://www.felixcloutier.com/x86/cvtps2dq
156 // https://www.felixcloutier.com/x86/cvtpd2dq
157 "cvtps2dq" | "cvtpd2dq" => rustc_apfloat::Round::NearestTiesToEven,
158 // always truncate
159 // https://www.felixcloutier.com/x86/cvttps2dq
160 // https://www.felixcloutier.com/x86/cvttpd2dq
161 "cvttps2dq" | "cvttpd2dq" => rustc_apfloat::Round::TowardZero,
162 _ => unreachable!(),
163 };
164
165 convert_float_to_int(this, op, rnd, dest)?;
166 }
167 // Used to implement the _mm_packs_epi16 function.
168 // Converts two 16-bit integer vectors to a single 8-bit integer
169 // vector with signed saturation.
170 "packsswb.128" => {
171 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
172
173 packsswb(this, left, right, dest)?;
174 }
175 // Used to implement the _mm_packus_epi16 function.
176 // Converts two 16-bit signed integer vectors to a single 8-bit
177 // unsigned integer vector with saturation.
178 "packuswb.128" => {
179 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
180
181 packuswb(this, left, right, dest)?;
182 }
183 // Used to implement the _mm_packs_epi32 function.
184 // Converts two 32-bit integer vectors to a single 16-bit integer
185 // vector with signed saturation.
186 "packssdw.128" => {
187 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
188
189 packssdw(this, left, right, dest)?;
190 }
191 // Used to implement _mm_min_sd and _mm_max_sd functions.
192 // Note that the semantics are a bit different from Rust simd_min
193 // and simd_max intrinsics regarding handling of NaN and -0.0: Rust
194 // matches the IEEE min/max operations, while x86 has different
195 // semantics.
196 "min.sd" | "max.sd" => {
197 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
198
199 let which = match unprefixed_name {
200 "min.sd" => FloatBinOp::Min,
201 "max.sd" => FloatBinOp::Max,
202 _ => unreachable!(),
203 };
204
205 bin_op_simd_float_first::<Double>(this, which, left, right, dest)?;
206 }
207 // Used to implement _mm_min_pd and _mm_max_pd functions.
208 // Note that the semantics are a bit different from Rust simd_min
209 // and simd_max intrinsics regarding handling of NaN and -0.0: Rust
210 // matches the IEEE min/max operations, while x86 has different
211 // semantics.
212 "min.pd" | "max.pd" => {
213 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
214
215 let which = match unprefixed_name {
216 "min.pd" => FloatBinOp::Min,
217 "max.pd" => FloatBinOp::Max,
218 _ => unreachable!(),
219 };
220
221 bin_op_simd_float_all::<Double>(this, which, left, right, dest)?;
222 }
223 // Used to implement the _mm_cmp*_sd functions.
224 // Performs a comparison operation on the first component of `left`
225 // and `right`, returning 0 if false or `u64::MAX` if true. The remaining
226 // components are copied from `left`.
227 // _mm_cmp_sd is actually an AVX function where the operation is specified
228 // by a const parameter.
229 // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_sd are SSE2 functions
230 // with hard-coded operations.
231 "cmp.sd" => {
232 let [left, right, imm] = this.check_shim(abi, Conv::C, link_name, args)?;
233
234 let which =
235 FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?;
236
237 bin_op_simd_float_first::<Double>(this, which, left, right, dest)?;
238 }
239 // Used to implement the _mm_cmp*_pd functions.
240 // Performs a comparison operation on each component of `left`
241 // and `right`. For each component, returns 0 if false or `u64::MAX`
242 // if true.
243 // _mm_cmp_pd is actually an AVX function where the operation is specified
244 // by a const parameter.
245 // _mm_cmp{eq,lt,le,gt,ge,neq,nlt,nle,ngt,nge,ord,unord}_pd are SSE2 functions
246 // with hard-coded operations.
247 "cmp.pd" => {
248 let [left, right, imm] = this.check_shim(abi, Conv::C, link_name, args)?;
249
250 let which =
251 FloatBinOp::cmp_from_imm(this, this.read_scalar(imm)?.to_i8()?, link_name)?;
252
253 bin_op_simd_float_all::<Double>(this, which, left, right, dest)?;
254 }
255 // Used to implement _mm_{,u}comi{eq,lt,le,gt,ge,neq}_sd functions.
256 // Compares the first component of `left` and `right` and returns
257 // a scalar value (0 or 1).
258 "comieq.sd" | "comilt.sd" | "comile.sd" | "comigt.sd" | "comige.sd" | "comineq.sd"
259 | "ucomieq.sd" | "ucomilt.sd" | "ucomile.sd" | "ucomigt.sd" | "ucomige.sd"
260 | "ucomineq.sd" => {
261 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
262
263 let (left, left_len) = this.project_to_simd(left)?;
264 let (right, right_len) = this.project_to_simd(right)?;
265
266 assert_eq!(left_len, right_len);
267
268 let left = this.read_scalar(&this.project_index(&left, 0)?)?.to_f64()?;
269 let right = this.read_scalar(&this.project_index(&right, 0)?)?.to_f64()?;
270 // The difference between the com* and ucom* variants is signaling
271 // of exceptions when either argument is a quiet NaN. We do not
272 // support accessing the SSE status register from miri (or from Rust,
273 // for that matter), so we treat both variants equally.
274 let res = match unprefixed_name {
275 "comieq.sd" | "ucomieq.sd" => left == right,
276 "comilt.sd" | "ucomilt.sd" => left < right,
277 "comile.sd" | "ucomile.sd" => left <= right,
278 "comigt.sd" | "ucomigt.sd" => left > right,
279 "comige.sd" | "ucomige.sd" => left >= right,
280 "comineq.sd" | "ucomineq.sd" => left != right,
281 _ => unreachable!(),
282 };
283 this.write_scalar(Scalar::from_i32(i32::from(res)), dest)?;
284 }
285 // Use to implement the _mm_cvtsd_si32, _mm_cvttsd_si32,
286 // _mm_cvtsd_si64 and _mm_cvttsd_si64 functions.
287 // Converts the first component of `op` from f64 to i32/i64.
288 "cvtsd2si" | "cvttsd2si" | "cvtsd2si64" | "cvttsd2si64" => {
289 let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
290 let (op, _) = this.project_to_simd(op)?;
291
292 let op = this.read_immediate(&this.project_index(&op, 0)?)?;
293
294 let rnd = match unprefixed_name {
295 // "current SSE rounding mode", assume nearest
296 // https://www.felixcloutier.com/x86/cvtsd2si
297 "cvtsd2si" | "cvtsd2si64" => rustc_apfloat::Round::NearestTiesToEven,
298 // always truncate
299 // https://www.felixcloutier.com/x86/cvttsd2si
300 "cvttsd2si" | "cvttsd2si64" => rustc_apfloat::Round::TowardZero,
301 _ => unreachable!(),
302 };
303
304 let res = this.float_to_int_checked(&op, dest.layout, rnd)?.unwrap_or_else(|| {
305 // Fallback to minimum according to SSE semantics.
306 ImmTy::from_int(dest.layout.size.signed_int_min(), dest.layout)
307 });
308
309 this.write_immediate(*res, dest)?;
310 }
311 // Used to implement the _mm_cvtsd_ss and _mm_cvtss_sd functions.
312 // Converts the first f64/f32 from `right` to f32/f64 and copies
313 // the remaining elements from `left`
314 "cvtsd2ss" | "cvtss2sd" => {
315 let [left, right] = this.check_shim(abi, Conv::C, link_name, args)?;
316
317 let (left, left_len) = this.project_to_simd(left)?;
318 let (right, _) = this.project_to_simd(right)?;
319 let (dest, dest_len) = this.project_to_simd(dest)?;
320
321 assert_eq!(dest_len, left_len);
322
323 // Convert first element of `right`
324 let right0 = this.read_immediate(&this.project_index(&right, 0)?)?;
325 let dest0 = this.project_index(&dest, 0)?;
326 // `float_to_float_or_int` here will convert from f64 to f32 (cvtsd2ss) or
327 // from f32 to f64 (cvtss2sd).
328 let res0 = this.float_to_float_or_int(&right0, dest0.layout)?;
329 this.write_immediate(*res0, &dest0)?;
330
331 // Copy remaining from `left`
332 for i in 1..dest_len {
333 this.copy_op(&this.project_index(&left, i)?, &this.project_index(&dest, i)?)?;
334 }
335 }
336 _ => return interp_ok(EmulateItemResult::NotSupported),
337 }
338 interp_ok(EmulateItemResult::NeedsReturn)
339 }
340}