Debian Codegraph @

crt/aws-c-common/source/arch/intel/encoding_avx2.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <emmintrin.h>
7 #include <immintrin.h>
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12
13 #include <aws/common/common.h>
14
15 /***** Decode logic *****/
16
17 /*
18 * Decodes ranges of bytes in place
19 * For each byte of 'in' that is between lo and hi (inclusive), adds offset and _adds_ it to the corresponding offset in
20 * out.
21 */
22 static inline __m256i translate_range(__m256i in, uint8_t lo, uint8_t hi, uint8_t offset) {
23 __m256i lovec = _mm256_set1_epi8(lo);
24 __m256i hivec = _mm256_set1_epi8((char)(hi - lo));
25 __m256i offsetvec = _mm256_set1_epi8(offset);
26
27 __m256i tmp = _mm256_sub_epi8(in, lovec);
28 /*
29 * we'll use the unsigned min operator to do our comparison. Note that
30 * there's no unsigned compare as a comparison intrinsic.
31 */
32 __m256i mask = _mm256_min_epu8(tmp, hivec);
33 /* if mask = tmp, then keep that byte */
34 mask = _mm256_cmpeq_epi8(mask, tmp);
35
36 tmp = _mm256_add_epi8(tmp, offsetvec);
37 tmp = _mm256_and_si256(tmp, mask);
38 return tmp;
39 }
40
41 /*
42 * For each 8-bit element in in, if the element equals match, add to the corresponding element in out the value decode.
43 */
44 static inline __m256i translate_exact(__m256i in, uint8_t match, uint8_t decode) {
45 __m256i mask = _mm256_cmpeq_epi8(in, _mm256_set1_epi8(match));
46 return _mm256_and_si256(mask, _mm256_set1_epi8(decode));
47 }
48
49 /*
50 * Input: a pointer to a 256-bit vector of base64 characters
51 * The pointed-to-vector is replaced by a 256-bit vector of 6-bit decoded parts;
52 * on decode failure, returns false, else returns true on success.
53 */
54 static inline bool decode_vec(__m256i *in) {
55 __m256i tmp1, tmp2, tmp3, tmp4, tmp5;
56
57 /*
58 * Base64 decoding table, see RFC4648
59 *
60 * Note that we use multiple vector registers to try to allow the CPU to
61 * parallelize the merging ORs
62 */
63 tmp1 = translate_range(*in, 'A', 'Z', 0 + 1);
64 tmp2 = translate_range(*in, 'a', 'z', 26 + 1);
65 tmp3 = translate_range(*in, '0', '9', 52 + 1);
66 // Handle both '+' and '-' for value 62
67 tmp4 = translate_exact(*in, '+', 62 + 1);
68 tmp4 = _mm256_or_si256(tmp4, translate_exact(*in, '-', 62 + 1));
69
70 // Handle both '/' and '_' for value 63
71 tmp5 = translate_exact(*in, '/', 63 + 1);
72 tmp5 = _mm256_or_si256(tmp5, translate_exact(*in, '_', 63 + 1));
73
74 // Combine all results
75 tmp1 = _mm256_or_si256(tmp1, tmp4);
76 tmp2 = _mm256_or_si256(tmp2, tmp5);
77 tmp3 = _mm256_or_si256(tmp3, _mm256_or_si256(tmp1, tmp2));
78
79 /*
80 * We use 0 to mark decode failures, so everything is decoded to one higher
81 * than normal. We'll shift this down now.
82 */
83 *in = _mm256_sub_epi8(tmp3, _mm256_set1_epi8(1));
84
85 /* If any byte is now zero, we had a decode failure */
86 __m256i mask = _mm256_cmpeq_epi8(tmp3, _mm256_set1_epi8(0));
87 return _mm256_testz_si256(mask, mask);
88 }
89
90 AWS_ALIGNED_TYPEDEF(uint8_t, aligned256[32], 32);
91
92 /*
93 * Input: a 256-bit vector, interpreted as 32 * 6-bit values
94 * Output: a 256-bit vector, the lower 24 bytes of which contain the packed version of the input
95 */
96 static inline __m256i pack_vec(__m256i in) {
97 /*
98 * Our basic strategy is to split the input vector into three vectors, for each 6-bit component
99 * of each 24-bit group, shift the groups into place, then OR the vectors together. Conveniently,
100 * we can do this on a (32 bit) dword-by-dword basis.
101 *
102 * It's important to note that we're interpreting the vector as being little-endian. That is,
103 * on entry, we have dwords that look like this:
104 *
105 * MSB LSB
106 * 00DD DDDD 00CC CCCC 00BB BBBB 00AA AAAA
107 *
108 * And we want to translate to:
109 *
110 * MSB LSB
111 * 0000 0000 AAAA AABB BBBB CCCC CCDD DDDD
112 *
113 * After which point we can pack these dwords together to produce our final output.
114 */
115 __m256i maskA = _mm256_set1_epi32(0xFF); // low bits
116 __m256i maskB = _mm256_set1_epi32(0xFF00);
117 __m256i maskC = _mm256_set1_epi32(0xFF0000);
118 __m256i maskD = _mm256_set1_epi32((int)0xFF000000);
119
120 __m256i bitsA = _mm256_slli_epi32(_mm256_and_si256(in, maskA), 18);
121 __m256i bitsB = _mm256_slli_epi32(_mm256_and_si256(in, maskB), 4);
122 __m256i bitsC = _mm256_srli_epi32(_mm256_and_si256(in, maskC), 10);
123 __m256i bitsD = _mm256_srli_epi32(_mm256_and_si256(in, maskD), 24);
124
125 __m256i dwords = _mm256_or_si256(_mm256_or_si256(bitsA, bitsB), _mm256_or_si256(bitsC, bitsD));
126 /*
127 * Now we have a series of dwords with empty MSBs.
128 * We need to pack them together (and shift down) with a shuffle operation.
129 * Unfortunately the shuffle operation operates independently within each 128-bit lane,
130 * so we'll need to do this in two steps: First we compact dwords within each lane, then
131 * we do a dword shuffle to compact the two lanes together.
132
133 * 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00 <- byte index (little endian)
134 * -- 09 0a 0b -- 06 07 08 -- 03 04 05 -- 00 01 02 <- data index
135 *
136 * We also reverse the order of 3-byte fragments within each lane; we've constructed
137 * those fragments in little endian but the order of fragments within the overall
138 * vector is in memory order (big endian)
139 */
140 const aligned256 shufvec_buf = {
141 /* clang-format off */
142 /* MSB */
143 0xFF, 0xFF, 0xFF, 0xFF, /* Zero out the top 4 bytes of the lane */
144 2, 1, 0,
145 6, 5, 4,
146 10, 9, 8,
147 14, 13, 12,
148
149 0xFF, 0xFF, 0xFF, 0xFF, /* Zero out the top 4 bytes of the lane */
150 2, 1, 0,
151 6, 5, 4,
152 10, 9, 8,
153 14, 13, 12
154 /* LSB */
155 /* clang-format on */
156 };
157 __m256i shufvec = _mm256_load_si256((__m256i const *)&shufvec_buf);
158
159 dwords = _mm256_shuffle_epi8(dwords, shufvec);
160 /*
161 * Now shuffle the 32-bit words:
162 * A B C 0 D E F 0 -> 0 0 A B C D E F
163 */
164 __m256i shuf32 = _mm256_set_epi32(0, 0, 7, 6, 5, 3, 2, 1);
165
166 dwords = _mm256_permutevar8x32_epi32(dwords, shuf32);
167
168 return dwords;
169 }
170
171 static inline bool decode(const unsigned char *in, unsigned char *out) {
172 __m256i vec = _mm256_loadu_si256((__m256i const *)in);
173 if (!decode_vec(&vec)) {
174 return false;
175 }
176 vec = pack_vec(vec);
177
178 /*
179 * We'll do overlapping writes to get both the low 128 bits and the high 64-bits written.
180 * Input (memory order): 0 1 2 3 4 5 - - (dwords)
181 * Input (little endian) - - 5 4 3 2 1 0
182 * Output in memory:
183 * [0 1 2 3] [4 5]
184 */
185 __m128i lo = _mm256_extracti128_si256(vec, 0);
186 /*
187 * Unfortunately some compilers don't support _mm256_extract_epi64,
188 * so we'll just copy right out of the vector as a fallback
189 */
190
191 #ifdef AWS_HAVE_MM256_EXTRACT_EPI64
192 uint64_t hi = _mm256_extract_epi64(vec, 2);
193 const uint64_t *p_hi = &hi;
194 #else
195 const uint64_t *p_hi = (uint64_t *)&vec + 2;
196 #endif
197
198 _mm_storeu_si128((__m128i *)out, lo);
199 memcpy(out + 16, p_hi, sizeof(*p_hi));
200
201 return true;
202 }
203
204 size_t aws_common_private_base64_decode_sse41(const unsigned char *in, unsigned char *out, size_t len) {
205 if (len % 4) {
206 return SIZE_MAX;
207 }
208
209 size_t outlen = 0;
210 while (len > 32) {
211 if (!decode(in, out)) {
212 return SIZE_MAX;
213 }
214 len -= 32;
215 in += 32;
216 out += 24;
217 outlen += 24;
218 }
219
220 if (len > 0) {
221 unsigned char tmp_in[32];
222 unsigned char tmp_out[24];
223
224 memset(tmp_out, 0xEE, sizeof(tmp_out));
225
226 /* We need to ensure the vector contains valid b64 characters */
227 memset(tmp_in, 'A', sizeof(tmp_in));
228 memcpy(tmp_in, in, len);
229
230 size_t final_out = (3 * len) / 4;
231
232 /* Check for end-of-string padding (up to 2 characters) */
233 for (int i = 0; i < 2; i++) {
234 if (tmp_in[len - 1] == '=') {
235 tmp_in[len - 1] = 'A'; /* make sure the inner loop doesn't bail out */
236 len--;
237 final_out--;
238 }
239 }
240
241 if (!decode(tmp_in, tmp_out)) {
242 return SIZE_MAX;
243 }
244
245 /* Check that there are no trailing ones bits */
246 for (size_t i = final_out; i < sizeof(tmp_out); i++) {
247 if (tmp_out[i]) {
248 return SIZE_MAX;
249 }
250 }
251
252 memcpy(out, tmp_out, final_out);
253 outlen += final_out;
254 }
255 return outlen;
256 }
257
258 /***** Encode logic *****/
259 static inline __m256i encode_chars(__m256i in) {
260 __m256i tmp1, tmp2, tmp3;
261
262 /*
263 * Base64 encoding table, see RFC4648
264 *
265 * We again use fan-in for the ORs here.
266 */
267 tmp1 = translate_range(in, 0, 25, 'A');
268 tmp2 = translate_range(in, 26, 26 + 25, 'a');
269 tmp3 = translate_range(in, 52, 61, '0');
270 tmp1 = _mm256_or_si256(tmp1, translate_exact(in, 62, '+'));
271 tmp2 = _mm256_or_si256(tmp2, translate_exact(in, 63, '/'));
272
273 return _mm256_or_si256(tmp3, _mm256_or_si256(tmp1, tmp2));
274 }
275
276 /*
277 * Input: A 256-bit vector, interpreted as 24 bytes (LSB) plus 8 bytes of high-byte padding
278 * Output: A 256-bit vector of base64 characters
279 */
280 static inline __m256i encode_stride(__m256i vec) {
281 /*
282 * First, since byte-shuffle operations operate within 128-bit subvectors, swap around the dwords
283 * to balance the amount of actual data between 128-bit subvectors.
284 * After this we want the LE representation to look like: -- XX XX XX -- XX XX XX
285 */
286 __m256i shuf32 = _mm256_set_epi32(7, 5, 4, 3, 6, 2, 1, 0);
287 vec = _mm256_permutevar8x32_epi32(vec, shuf32);
288
289 /*
290 * Next, within each group of 3 bytes, we need to byteswap into little endian form so our bitshifts
291 * will work properly. We also shuffle around so that each dword has one 3-byte group, plus one byte
292 * (MSB) of zero-padding.
293 * Because this is a byte-shuffle, indexes are within each 128-bit subvector.
294 *
295 * -- -- -- -- 11 10 09 08 07 06 05 04 03 02 01 00
296 */
297
298 const aligned256 shufvec_buf = {
299 /* clang-format off */
300 /* MSB */
301 2, 1, 0, 0xFF,
302 5, 4, 3, 0xFF,
303 8, 7, 6, 0xFF,
304 11, 10, 9, 0xFF,
305
306 2, 1, 0, 0xFF,
307 5, 4, 3, 0xFF,
308 8, 7, 6, 0xFF,
309 11, 10, 9, 0xFF
310 /* LSB */
311 /* clang-format on */
312 };
313 vec = _mm256_shuffle_epi8(vec, _mm256_load_si256((__m256i const *)&shufvec_buf));
314
315 /*
316 * Now shift and mask to split out 6-bit groups.
317 * We'll also do a second byteswap to get back into big-endian
318 */
319 __m256i mask0 = _mm256_set1_epi32(0x3F);
320 __m256i mask1 = _mm256_set1_epi32(0x3F << 6);
321 __m256i mask2 = _mm256_set1_epi32(0x3F << 12);
322 __m256i mask3 = _mm256_set1_epi32(0x3F << 18);
323
324 __m256i digit0 = _mm256_and_si256(mask0, vec);
325 __m256i digit1 = _mm256_and_si256(mask1, vec);
326 __m256i digit2 = _mm256_and_si256(mask2, vec);
327 __m256i digit3 = _mm256_and_si256(mask3, vec);
328
329 /*
330 * Because we want to byteswap, the low-order digit0 goes into the
331 * high-order byte
332 */
333 digit0 = _mm256_slli_epi32(digit0, 24);
334 digit1 = _mm256_slli_epi32(digit1, 10);
335 digit2 = _mm256_srli_epi32(digit2, 4);
336 digit3 = _mm256_srli_epi32(digit3, 18);
337
338 vec = _mm256_or_si256(_mm256_or_si256(digit0, digit1), _mm256_or_si256(digit2, digit3));
339
340 /* Finally translate to the base64 character set */
341 return encode_chars(vec);
342 }
343
344 void aws_common_private_base64_encode_sse41(const uint8_t *input, uint8_t *output, size_t inlen) {
345 __m256i instride, outstride;
346
347 while (inlen >= 32) {
348 /*
349 * Where possible, we'll load a full vector at a time and ignore the over-read.
350 * However, if we have < 32 bytes left, this would result in a potential read
351 * of unreadable pages, so we use bounce buffers below.
352 */
353 instride = _mm256_loadu_si256((__m256i const *)input);
354 outstride = encode_stride(instride);
355 _mm256_storeu_si256((__m256i *)output, outstride);
356
357 input += 24;
358 output += 32;
359 inlen -= 24;
360 }
361
362 while (inlen) {
363 /*
364 * We need to go through a bounce buffer for anything remaining, as we
365 * don't want to over-read or over-write the ends of the buffers.
366 */
367 size_t stridelen = inlen > 24 ? 24 : inlen;
368 size_t outlen = ((stridelen + 2) / 3) * 4;
369
370 memset(&instride, 0, sizeof(instride));
371 memcpy(&instride, input, stridelen);
372
373 outstride = encode_stride(instride);
374 memcpy(output, &outstride, outlen);
375
376 if (inlen < 24) {
377 if (inlen % 3 >= 1) {
378 /* AA== or AAA= */
379 output[outlen - 1] = '=';
380 }
381 if (inlen % 3 == 1) {
382 /* AA== */
383 output[outlen - 2] = '=';
384 }
385
386 return;
387 }
388
389 input += stridelen;
390 output += outlen;
391 inlen -= stridelen;
392 }
393 }