|
| 1 | +//@ compile-flags: -Copt-level=3 |
| 2 | +#![crate_type = "lib"] |
| 3 | + |
| 4 | +/// Ensure that the ascii-prefix loop for `str::to_lowercase` and `str::to_uppercase` uses vector |
| 5 | +/// instructions. Since these methods do not get inlined, the relevant code is duplicated here and |
| 6 | +/// should be updated when the implementation changes. |
| 7 | +// CHECK-LABEL: @lower_while_ascii |
| 8 | +// CHECK: [[A:%[0-9]]] = load <16 x i8> |
| 9 | +// CHECK-NEXT: [[B:%[0-9]]] = icmp slt <16 x i8> [[A]], zeroinitializer |
| 10 | +// CHECK-NEXT: [[C:%[0-9]]] = bitcast <16 x i1> [[B]] to i16 |
| 11 | +#[no_mangle] |
| 12 | +pub fn lower_while_ascii(mut input: &[u8], mut output: &mut [u8]) -> usize { |
| 13 | + // process the input in chunks to enable auto-vectorization |
| 14 | + const USIZE_SIZE: usize = core::mem::size_of::<usize>(); |
| 15 | + const MAGIC_UNROLL: usize = 2; |
| 16 | + const N: usize = USIZE_SIZE * MAGIC_UNROLL; |
| 17 | + |
| 18 | + output = &mut output[..input.len()]; |
| 19 | + |
| 20 | + let mut ascii_prefix_len = 0_usize; |
| 21 | + let mut is_ascii = [false; N]; |
| 22 | + |
| 23 | + while input.len() >= N { |
| 24 | + let chunk = unsafe { input.get_unchecked(..N) }; |
| 25 | + let out_chunk = unsafe { output.get_unchecked_mut(..N) }; |
| 26 | + |
| 27 | + for j in 0..N { |
| 28 | + is_ascii[j] = chunk[j] <= 127; |
| 29 | + } |
| 30 | + |
| 31 | + // auto-vectorization for this check is a bit fragile, |
| 32 | + // sum and comparing against the chunk size gives the best result, |
| 33 | + // specifically a pmovmsk instruction on x86. |
| 34 | + if is_ascii.iter().map(|x| *x as u8).sum::<u8>() as usize != N { |
| 35 | + break; |
| 36 | + } |
| 37 | + |
| 38 | + for j in 0..N { |
| 39 | + out_chunk[j] = chunk[j].to_ascii_lowercase(); |
| 40 | + } |
| 41 | + |
| 42 | + ascii_prefix_len += N; |
| 43 | + input = unsafe { input.get_unchecked(N..) }; |
| 44 | + output = unsafe { output.get_unchecked_mut(N..) }; |
| 45 | + } |
| 46 | + |
| 47 | + ascii_prefix_len |
| 48 | +} |
0 commit comments