Skip to main content

miri/intrinsics/
aarch64.rs

1use rustc_middle::mir::BinOp;
2use rustc_span::Symbol;
3
4use crate::intrinsics::math::{compute_crc32, sha256};
5use crate::*;
6
7impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
8pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
9    fn emulate_aarch64_intrinsic(
10        &mut self,
11        link_name: Symbol,
12        args: &[OpTy<'tcx>],
13        dest: &MPlaceTy<'tcx>,
14    ) -> InterpResult<'tcx, EmulateItemResult> {
15        let this = self.eval_context_mut();
16        // Prefix should have already been checked.
17        let unprefixed_name = link_name.as_str().strip_prefix("llvm.aarch64.").unwrap();
18        match unprefixed_name {
19            // Used to implement the vpmaxq_u8 function.
20            // Computes the maximum of adjacent pairs; the first half of the output is produced from the
21            // `left` input, the second half of the output from the `right` input.
22            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vpmaxq_u8
23            "neon.umaxp.v16i8" => {
24                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
25
26                let (left, left_len) = this.project_to_simd(left)?;
27                let (right, right_len) = this.project_to_simd(right)?;
28                let (dest, lane_count) = this.project_to_simd(dest)?;
29                assert_eq!(left_len, right_len);
30                assert_eq!(lane_count, left_len);
31
32                for lane_idx in 0..lane_count {
33                    let src = if lane_idx < (lane_count / 2) { &left } else { &right };
34                    let src_idx = lane_idx.strict_rem(lane_count / 2);
35
36                    let lhs_lane =
37                        this.read_immediate(&this.project_index(src, src_idx.strict_mul(2))?)?;
38                    let rhs_lane = this.read_immediate(
39                        &this.project_index(src, src_idx.strict_mul(2).strict_add(1))?,
40                    )?;
41
42                    // Compute `if lhs > rhs { lhs } else { rhs }`, i.e., `max`.
43                    let res_lane = if this
44                        .binary_op(BinOp::Gt, &lhs_lane, &rhs_lane)?
45                        .to_scalar()
46                        .to_bool()?
47                    {
48                        lhs_lane
49                    } else {
50                        rhs_lane
51                    };
52
53                    let dest = this.project_index(&dest, lane_idx)?;
54                    this.write_immediate(*res_lane, &dest)?;
55                }
56            }
57
58            // Wrapping pairwise addition.
59            //
60            // Concatenates the two input vectors and adds adjacent elements. For input vectors `v`
61            // and `w` this computes `[v0 + v1, v2 + v3, ..., w0 + w1, w2 + w3, ...]`, using
62            // wrapping addition for `+`.
63            //
64            // Used by `vpadd_{s8, u8, s16, u16, s32, u32}`.
65            name if name.starts_with("neon.addp.") => {
66                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
67
68                let (left, left_len) = this.project_to_simd(left)?;
69                let (right, right_len) = this.project_to_simd(right)?;
70                let (dest, dest_len) = this.project_to_simd(dest)?;
71
72                assert_eq!(left_len, right_len);
73                assert_eq!(left_len, dest_len);
74
75                assert_eq!(left.layout, right.layout);
76                assert_eq!(left.layout, dest.layout);
77
78                assert!(dest_len.is_multiple_of(2));
79                let half_len = dest_len.strict_div(2);
80
81                for lane_idx in 0..dest_len {
82                    // The left and right vectors are concatenated.
83                    let (src, src_pair_idx) = if lane_idx < half_len {
84                        (&left, lane_idx)
85                    } else {
86                        (&right, lane_idx.strict_sub(half_len))
87                    };
88                    // Convert "pair index" into "index of first element of the pair".
89                    let i = src_pair_idx.strict_mul(2);
90
91                    let lhs = this.read_immediate(&this.project_index(src, i)?)?;
92                    let rhs = this.read_immediate(&this.project_index(src, i.strict_add(1))?)?;
93
94                    // Wrapping addition on the element type.
95                    let sum = this.binary_op(BinOp::Add, &lhs, &rhs)?;
96
97                    let dst_lane = this.project_index(&dest, lane_idx)?;
98                    this.write_immediate(*sum, &dst_lane)?;
99                }
100            }
101
102            // Widening pairwise addition.
103            //
104            // Takes a single input vector, and an output vector with half as many lanes and double
105            // the element width. Takes adjacent pairs of elements, widens both, and then adds them
106            // together.
107            //
108            // Used by `vpaddl_{u8, u16, u32}` and `vpaddlq_{u8, u16, u32}`.
109            name if name.starts_with("neon.uaddlp.") => {
110                let [src] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
111
112                let (src, src_len) = this.project_to_simd(src)?;
113                let (dest, dest_len) = this.project_to_simd(dest)?;
114
115                // Operates pairwise, so src has twice as many lanes.
116                assert_eq!(src_len, dest_len.strict_mul(2));
117
118                let src_elem_size = src.layout.field(this, 0).size;
119                let dest_elem_size = dest.layout.field(this, 0).size;
120
121                // Widens, so dest elements must be exactly twice as wide.
122                assert_eq!(dest_elem_size.bytes(), src_elem_size.bytes().strict_mul(2));
123
124                for dest_idx in 0..dest_len {
125                    let src_idx = dest_idx.strict_mul(2);
126
127                    let a_scalar = this.read_scalar(&this.project_index(&src, src_idx)?)?;
128                    let b_scalar =
129                        this.read_scalar(&this.project_index(&src, src_idx.strict_add(1))?)?;
130
131                    let a_val = a_scalar.to_uint(src_elem_size)?;
132                    let b_val = b_scalar.to_uint(src_elem_size)?;
133
134                    // Use addition on u128 to simulate widening addition for the destination type.
135                    // This cannot wrap since the element type is at most u64.
136                    let sum = a_val.strict_add(b_val);
137
138                    let dst_lane = this.project_index(&dest, dest_idx)?;
139                    this.write_scalar(Scalar::from_uint(sum, dest_elem_size), &dst_lane)?;
140                }
141            }
142
143            // Signed saturating doubling multiply returning the high half.
144            //
145            // Used by the `vqdmulh*` functions.
146            //
147            // This LLVM intrinsic multiplies the values of corresponding elements of the two source
148            // vector registers (which are signed integers), doubles the results, places the most significant half of the
149            // final results (using a saturating cast to fit the element type) into a vector, and writes the vector to the destination register.
150            //
151            // https://developer.arm.com/architectures/instruction-sets/intrinsics#f:@navigationhierarchiessimdisa=[Neon]&q=vqdmulh
152            name if name.starts_with("neon.sqdmulh.") => {
153                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
154
155                let (left, left_len) = this.project_to_simd(left)?;
156                let (right, right_len) = this.project_to_simd(right)?;
157                let (dest, dest_len) = this.project_to_simd(dest)?;
158                assert_eq!(left_len, right_len);
159                assert_eq!(left_len, dest_len);
160
161                let elem_size = dest.layout.field(this, 0).size;
162                let bits = elem_size.bits();
163                let min = elem_size.signed_int_min();
164                let max = elem_size.signed_int_max();
165
166                for i in 0..dest_len {
167                    let a = this.read_scalar(&this.project_index(&left, i)?)?.to_int(elem_size)?;
168                    let b = this.read_scalar(&this.project_index(&right, i)?)?.to_int(elem_size)?;
169
170                    // Uses i128 arithmetic, which cannot overflow because the intrinsic takes at most i32.
171                    let doubled = a.strict_mul(b).strict_mul(2);
172                    let res = (doubled >> bits).clamp(min, max);
173
174                    this.write_scalar(
175                        Scalar::from_int(res, elem_size),
176                        &this.project_index(&dest, i)?,
177                    )?;
178                }
179            }
180
181            // Vector table lookup: each index selects a byte from the table,
182            // out-of-range -> 0.
183            //
184            // Used to implement the vtblN, vqtblN and vqtblNq set of functions, e.g.:
185            //
186            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vtbl1_u8
187            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vqtbl1_u8
188            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vqtbl1q_s8
189            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vtbl2_u8
190            // - https://developer.arm.com/architectures/instruction-sets/intrinsics/vqtbl4q_s8
191            //
192            // LLVM does not have a portable shuffle that takes non-const indices
193            // so we need to implement this ourselves.
194            _ if unprefixed_name.starts_with("neon.tbl") => {
195                // The table segments always have 16 elements, the index vector and output vector
196                // have either 8 or 16 elements.
197                let (table_segments, indices) = match unprefixed_name {
198                    "neon.tbl1.v8i8" | "neon.tbl1.v16i8" => {
199                        let [table, indices] =
200                            this.check_shim_sig_llvm_intrinsic(link_name, args)?;
201                        let (table, len) = this.project_to_simd(table)?;
202                        assert_eq!(len, 16);
203                        (vec![table], indices)
204                    }
205                    "neon.tbl2.v8i8" | "neon.tbl2.v16i8" => {
206                        let [table0, table1, indices] =
207                            this.check_shim_sig_llvm_intrinsic(link_name, args)?;
208                        let (table0, len0) = this.project_to_simd(table0)?;
209                        let (table1, len1) = this.project_to_simd(table1)?;
210                        assert_eq!([len0, len1], [16; 2]);
211                        (vec![table0, table1], indices)
212                    }
213                    "neon.tbl3.v8i8" | "neon.tbl3.v16i8" => {
214                        let [table0, table1, table2, indices] =
215                            this.check_shim_sig_llvm_intrinsic(link_name, args)?;
216                        let (table0, len0) = this.project_to_simd(table0)?;
217                        let (table1, len1) = this.project_to_simd(table1)?;
218                        let (table2, len2) = this.project_to_simd(table2)?;
219                        assert_eq!([len0, len1, len2], [16; 3]);
220                        (vec![table0, table1, table2], indices)
221                    }
222                    "neon.tbl4.v8i8" | "neon.tbl4.v16i8" => {
223                        let [table0, table1, table2, table3, indices] =
224                            this.check_shim_sig_llvm_intrinsic(link_name, args)?;
225                        let (table0, len0) = this.project_to_simd(table0)?;
226                        let (table1, len1) = this.project_to_simd(table1)?;
227                        let (table2, len2) = this.project_to_simd(table2)?;
228                        let (table3, len3) = this.project_to_simd(table3)?;
229                        assert_eq!([len0, len1, len2, len3], [16; 4]);
230                        (vec![table0, table1, table2, table3], indices)
231                    }
232                    _ => unreachable!(),
233                };
234
235                let (indices, idx_len) = this.project_to_simd(indices)?;
236                let (dest, dest_len) = this.project_to_simd(dest)?;
237                assert_eq!(idx_len, dest_len);
238
239                for i in 0..dest_len {
240                    let idx = this.read_immediate(&this.project_index(&indices, i)?)?;
241                    let idx = idx.to_scalar().to_u8()?;
242
243                    // The LLVM intrinsic table segments always have 16 elements.
244                    let val = if usize::from(idx) < table_segments.len().strict_mul(16) {
245                        let table = &table_segments[usize::from(idx.strict_div(16))];
246                        let lane = u64::from(idx.strict_rem(16));
247                        let t = this.read_immediate(&this.project_index(table, lane)?)?;
248                        t.to_scalar()
249                    } else {
250                        Scalar::from_u8(0)
251                    };
252
253                    this.write_scalar(val, &this.project_index(&dest, i)?)?;
254                }
255            }
256            // Used to implement the __crc32{b,h,w,x} and __crc32c{b,h,w,x} functions.
257            // Polynomial 0x04C11DB7 (standard CRC-32):
258            // https://developer.arm.com/documentation/ddi0602/latest/Base-Instructions/CRC32B--CRC32H--CRC32W--CRC32X--CRC32-checksum-
259            // Polynomial 0x1EDC6F41 (CRC-32C / Castagnoli):
260            // https://developer.arm.com/documentation/ddi0602/latest/Base-Instructions/CRC32CB--CRC32CH--CRC32CW--CRC32CX--CRC32C-checksum-
261            "crc32b" | "crc32h" | "crc32w" | "crc32x" | "crc32cb" | "crc32ch" | "crc32cw"
262            | "crc32cx" => {
263                this.expect_target_feature_for_intrinsic(link_name, "crc")?;
264                // The polynomial constants below include the leading 1 bit
265                // (e.g. 0x104C11DB7 instead of 0x04C11DB7) which the ARM docs
266                // omit but the polynomial division algorithm requires.
267                let (bit_size, polynomial): (u32, u128) = match unprefixed_name {
268                    "crc32b" => (8, 0x104C11DB7),
269                    "crc32h" => (16, 0x104C11DB7),
270                    "crc32w" => (32, 0x104C11DB7),
271                    "crc32x" => (64, 0x104C11DB7),
272                    "crc32cb" => (8, 0x11EDC6F41),
273                    "crc32ch" => (16, 0x11EDC6F41),
274                    "crc32cw" => (32, 0x11EDC6F41),
275                    "crc32cx" => (64, 0x11EDC6F41),
276                    _ => unreachable!(),
277                };
278
279                let [crc, data] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
280                let crc = this.read_scalar(crc)?;
281                let data = this.read_scalar(data)?;
282
283                // The CRC accumulator is always u32. The data argument is u32 for
284                // b/h/w variants and u64 for the x variant, per the LLVM intrinsic
285                // definitions (all b/h/w take i32, only x takes i64).
286                // https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/IR/IntrinsicsAArch64.td
287                // If the higher bits are non-zero, `compute_crc32` will panic. We should probably
288                // raise a proper error instead, but outside stdarch nobody can trigger this anyway.
289                let crc = crc.to_u32()?;
290                let data = if bit_size == 64 { data.to_u64()? } else { u64::from(data.to_u32()?) };
291
292                let result = compute_crc32(crc, data, bit_size, polynomial);
293                this.write_scalar(Scalar::from_u32(result), dest)?;
294            }
295            // Polynomial multiply long (64-bit x 64-bit -> 128-bit).
296            //
297            // This is the same as "carryless" multiplication, see
298            // <https://en.wikipedia.org/wiki/Carry-less_product#Multiplication_of_polynomials>.
299            //
300            // Used to implement the vmull_p64 and vmull_high_p64 functions.
301            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vmull_p64
302            "neon.pmull64" => {
303                // LLVM and GCC group pmull with the AES intrinsics.
304                // Also see <https://gcc.gnu.org/pipermail/gcc-patches/2023-February/612088.html>.
305                this.expect_target_feature_for_intrinsic(link_name, "aes")?;
306
307                let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
308                let left = this.read_scalar(left)?.to_u64()?;
309                let right = this.read_scalar(right)?.to_u64()?;
310
311                let result = left.widening_carryless_mul(right);
312
313                // dest is int8x16_t, transmute to u128 for the write.
314                let dest = dest.transmute(this.machine.layouts.u128, this)?;
315                this.write_scalar(Scalar::from_u128(result), &dest)?;
316            }
317
318            // Used to implement the vsha256hq_u32 function.
319            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256hq_u32
320            "crypto.sha256h" => {
321                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
322
323                let [abcd, efgh, wk] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
324
325                let (abcd, abcd_len) = this.project_to_simd(abcd)?;
326                let (efgh, efgh_len) = this.project_to_simd(efgh)?;
327                let (wk, wk_len) = this.project_to_simd(wk)?;
328                let (dest, dest_len) = this.project_to_simd(dest)?;
329
330                assert_eq!(abcd_len, 4);
331                assert_eq!(efgh_len, 4);
332                assert_eq!(wk_len, 4);
333                assert_eq!(dest_len, 4);
334
335                let abcd: [u32; 4] = read_u32x4(this, &abcd)?;
336                let efgh: [u32; 4] = read_u32x4(this, &efgh)?;
337                let wk: [u32; 4] = read_u32x4(this, &wk)?;
338
339                let result = sha256h(abcd, efgh, wk);
340
341                write_u32x4(this, &dest, result)?;
342            }
343            // Used to implement the vsha256h2q_u32 function.
344            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256h2q_u32
345            "crypto.sha256h2" => {
346                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
347
348                let [efgh, abcd, wk] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
349
350                let (efgh, efgh_len) = this.project_to_simd(efgh)?;
351                let (abcd, abcd_len) = this.project_to_simd(abcd)?;
352                let (wk, wk_len) = this.project_to_simd(wk)?;
353                let (dest, dest_len) = this.project_to_simd(dest)?;
354
355                assert_eq!(efgh_len, 4);
356                assert_eq!(abcd_len, 4);
357                assert_eq!(wk_len, 4);
358                assert_eq!(dest_len, 4);
359
360                let efgh: [u32; 4] = read_u32x4(this, &efgh)?;
361                let abcd: [u32; 4] = read_u32x4(this, &abcd)?;
362                let wk: [u32; 4] = read_u32x4(this, &wk)?;
363
364                let result = sha256h2(efgh, abcd, wk);
365
366                write_u32x4(this, &dest, result)?;
367            }
368            // Used to implement the vsha256su0q_u32 function.
369            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256su0q_u32
370            "crypto.sha256su0" => {
371                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
372
373                let [a, b] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
374
375                let (a, a_len) = this.project_to_simd(a)?;
376                let (b, b_len) = this.project_to_simd(b)?;
377                let (dest, dest_len) = this.project_to_simd(dest)?;
378
379                assert_eq!(a_len, 4);
380                assert_eq!(b_len, 4);
381                assert_eq!(dest_len, 4);
382
383                let a: [u32; 4] = read_u32x4(this, &a)?;
384                let b: [u32; 4] = read_u32x4(this, &b)?;
385
386                let result = sha256su0(a, b);
387
388                write_u32x4(this, &dest, result)?;
389            }
390            // Used to implement the vsha256su1q_u32 function.
391            // https://developer.arm.com/architectures/instruction-sets/intrinsics/vsha256su1q_u32
392            "crypto.sha256su1" => {
393                this.expect_target_feature_for_intrinsic(link_name, "sha2")?;
394
395                let [a, b, c] = this.check_shim_sig_llvm_intrinsic(link_name, args)?;
396
397                let (a, a_len) = this.project_to_simd(a)?;
398                let (b, b_len) = this.project_to_simd(b)?;
399                let (c, c_len) = this.project_to_simd(c)?;
400                let (dest, dest_len) = this.project_to_simd(dest)?;
401
402                assert_eq!(a_len, 4);
403                assert_eq!(b_len, 4);
404                assert_eq!(c_len, 4);
405                assert_eq!(dest_len, 4);
406
407                let a: [u32; 4] = read_u32x4(this, &a)?;
408                let b: [u32; 4] = read_u32x4(this, &b)?;
409                let c: [u32; 4] = read_u32x4(this, &c)?;
410
411                let result = sha256su1(a, b, c);
412
413                write_u32x4(this, &dest, result)?;
414            }
415            _ => return interp_ok(EmulateItemResult::NotSupported),
416        }
417        interp_ok(EmulateItemResult::NeedsReturn)
418    }
419}
420
421/// Reads a `[u32; 4]` array.
422fn read_u32x4<'c>(ecx: &mut MiriInterpCx<'c>, vec: &OpTy<'c>) -> InterpResult<'c, [u32; 4]> {
423    let mut res = [0; 4];
424    for (i, dst) in res.iter_mut().enumerate() {
425        let projected = &ecx.project_index(vec, i.try_into().unwrap())?;
426        *dst = ecx.read_scalar(projected)?.to_u32()?;
427    }
428    interp_ok(res)
429}
430
431fn write_u32x4<'c>(
432    ecx: &mut MiriInterpCx<'c>,
433    dest: &MPlaceTy<'c>,
434    val: [u32; 4],
435) -> InterpResult<'c, ()> {
436    for (i, part) in val.into_iter().enumerate() {
437        let projected = &ecx.project_index(dest, i.to_u64())?;
438        ecx.write_scalar(Scalar::from_u32(part), projected)?;
439    }
440    interp_ok(())
441}
442
443fn sha256su0(v0: [u32; 4], v1: [u32; 4]) -> [u32; 4] {
444    [
445        v0[0].wrapping_add(sha256::sigma0(v0[1])),
446        v0[1].wrapping_add(sha256::sigma0(v0[2])),
447        v0[2].wrapping_add(sha256::sigma0(v0[3])),
448        v0[3].wrapping_add(sha256::sigma0(v1[0])),
449    ]
450}
451
452fn sha256su1(v0: [u32; 4], v1: [u32; 4], v2: [u32; 4]) -> [u32; 4] {
453    let r0 = v0[0].wrapping_add(v1[1]).wrapping_add(sha256::sigma1(v2[2]));
454    let r1 = v0[1].wrapping_add(v1[2]).wrapping_add(sha256::sigma1(v2[3]));
455    let r2 = v0[2].wrapping_add(v1[3]).wrapping_add(sha256::sigma1(r0));
456    let r3 = v0[3].wrapping_add(v2[0]).wrapping_add(sha256::sigma1(r1));
457    [r0, r1, r2, r3]
458}
459
460// SHA256H/SHA256H2 do four compression rounds on the abcd/efgh layout.
461// https://developer.arm.com/architectures/instruction-sets/intrinsics/#f:@navigationhierarchiesinstructiongroup=[Cryptography,SHA256]
462fn sha256hash(abcd: [u32; 4], efgh: [u32; 4], wk: [u32; 4]) -> ([u32; 4], [u32; 4]) {
463    let mut state = [abcd[0], abcd[1], abcd[2], abcd[3], efgh[0], efgh[1], efgh[2], efgh[3]];
464    for &wk_i in &wk {
465        state = sha256::round(state, wk_i);
466    }
467    ([state[0], state[1], state[2], state[3]], [state[4], state[5], state[6], state[7]])
468}
469
470fn sha256h(abcd: [u32; 4], efgh: [u32; 4], wk: [u32; 4]) -> [u32; 4] {
471    sha256hash(abcd, efgh, wk).0
472}
473
474// sha256h2 takes efgh as the first argument. abcd and efgh are swapped when calling sha256hash.
475fn sha256h2(efgh: [u32; 4], abcd: [u32; 4], wk: [u32; 4]) -> [u32; 4] {
476    sha256hash(abcd, efgh, wk).1
477}