-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgenerate.c
1373 lines (1299 loc) · 47.7 KB
/
generate.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* MIT licensed (both this program, and what it creates); see LICENSE.md */
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void print_help(FILE* f, const char* self) {
#if defined(__arm__) || defined(__arm) || defined(__ARM__) || defined(__ARM) || defined(__aarch64__) || defined(_M_ARM64)
const char* self_isa = "neon";
#else
const char* self_isa = "sse";
#endif
if (!self) self = "./generate";
fprintf(f, "Usage: %s [OPTION]...\n", self);
fprintf(f, "Generate C code for computing CRC32.\n");
fprintf(f, "Example: %s -i %s -p crc32c -a v8s1_s2\n\n", self, self_isa);
fprintf(f, "Options controlling code generation:\n");
fprintf(f, " -i, --isa=ISA\n");
fprintf(f, " -p, --polynomial=POLY\n");
fprintf(f, " -a, --algorithm=ALGO\n");
fprintf(f, "\nOutput control:\n");
fprintf(f, " -o, --output=FILE\n");
fprintf(f, "\nPossible values for ISA are:\n");
fprintf(f, " neon (aarch64, tuned for pmull+eor fusion)\n");
fprintf(f, " neon_eor3 (aarch64, using pmull and eor3)\n");
fprintf(f, " sse, avx, avx2 (x86_64, using pclmulqdq)\n");
fprintf(f, " avx512 (x86_64, using pclmulqdq and vpternlogq)\n");
fprintf(f, " avx512_vpclmulqdq (x86_64, using vpclmulqdq and vpternlogq)\n");
fprintf(f, "\nPossible values for POLY include:\n");
fprintf(f, " crc32 (0x04C11DB7) - hardware accelerated on aarch64\n");
fprintf(f, " crc32c (0x1EDC6F41) - hardware accelerated on aarch64 and x86_64\n");
fprintf(f, " crc32k (0x741B8CD7)\n");
fprintf(f, " crc32k2 (0x32583499)\n");
fprintf(f, " crc32q (0x814141AB)\n");
fprintf(f, " or specify any 32-bit polynomial in hexadecimal form\n");
fprintf(f, "\nThe ALGO string consists of multiple phases, separated by underscores.\n");
fprintf(f, "Each phase can contain (with no spaces inbetween) any mixture of:\n");
fprintf(f, " vN[xM] use N vector accumulators, and NxM vector loads per iteration\n");
fprintf(f, " sN[xM] use N scalar accumulators, and NxM scalar loads per iteration\n");
fprintf(f, " kN use an outer loop over N bytes\n");
fprintf(f, " e use an end pointer for the (inner) loop condition\n");
fprintf(f, "\nSee https://github.com/corsix/fast-crc32/\n");
}
#define FATAL(fmt, ...) \
(fprintf(stderr, "FATAL error at %s:%d - " fmt "\n", __FILE__, __LINE__, ## __VA_ARGS__), fflush(stderr), exit(1))
#define FATAL_ISA() FATAL("bad ISA in %s", __func__)
/*
** Little string buffer library.
**
** Main entry points are:
** - `sb = sbuf_new();`
** - `put_str(sb, str);`
** - `put_fmt(sb, fmt, ...);`
** - `put_deferred_sbuf(sb, sb2);`
** - `put_deferred_fn(sb, fn);`
*/
typedef struct sbuf_t {
char* base;
uint32_t size;
uint32_t capacity;
} sbuf_t;
#define sbuf_new() (sbuf_t*)calloc(1, sizeof(sbuf_t))
static char* sbuf_emplace(sbuf_t* sb, uint32_t size) {
/* Reserve `size` bytes, but do not commit them. */
if (sb->size + size > sb->capacity) {
uint32_t new_capacity = (sb->capacity + size) * 2;
if (new_capacity < 32) new_capacity = 32;
sb->base = (char*)realloc(sb->base, new_capacity);
sb->capacity = new_capacity;
}
return sb->base + sb->size;
}
static char* sbuf_append(sbuf_t* sb, uint32_t size) {
/* Reserve and commit `size` bytes (caller has to populate them). */
char* result = sbuf_emplace(sb, size);
sb->size += size;
return result;
}
static void put_str_len(sbuf_t* sb, const char* str, size_t len) {
memcpy(sbuf_append(sb, (uint32_t)len), str, len);
}
static void put_str(sbuf_t* sb, const char* str) {
if (!str) str = "(null)";
put_str_len(sb, str, strlen(str));
}
/* For compile-time string literals. */
#define put_lit(sb, str) (put_str_len((sb), (str), sizeof((str))-1))
typedef enum sbuf_op_t {
SBUF_OP_END,
SBUF_OP_DEFERRED,
SBUF_OP_DEFERRED_FN
} sbuf_op_t;
static sbuf_t* put_deferred_sbuf(sbuf_t* sb, sbuf_t* x) {
char* dst = sbuf_append(sb, 2 + sizeof(x));
dst[0] = 0;
dst[1] = SBUF_OP_DEFERRED;
memcpy(dst + 2, &x, sizeof(x));
return x;
}
#define put_new_sbuf(sb) (put_deferred_sbuf((sb), sbuf_new()))
typedef void (*sbuf_fn_t)(sbuf_t*);
static void put_deferred_fn(sbuf_t* sb, sbuf_fn_t x) {
char* dst = sbuf_append(sb, 2 + sizeof(x));
dst[0] = 0;
dst[1] = SBUF_OP_DEFERRED_FN;
memcpy(dst + 2, &x, sizeof(x));
}
static void put_u32(sbuf_t* sb, uint32_t x) {
char tmp[17];
char* dst = sbuf_emplace(sb, 10);
char* itr = tmp + 10;
do {
*--itr = '0' + (x % 10u);
} while ((x /= 10u));
sb->size += (tmp + 10 - itr);
memcpy(dst, itr, 8);
}
static void put_u32_hex(sbuf_t* sb, uint32_t x) {
uint32_t i = 8;
char* s = sbuf_append(sb, i);
for (; i--; x >>= 4) {
s[i] = "0123456789abcdef"[x & 15u];
}
}
static void put_fmt(sbuf_t* sb, const char* fmt, ...) {
va_list args;
const char* base;
char c;
va_start(args, fmt);
for (;;) {
c = *fmt;
if (c == '%') {
c = fmt[1];
fmt += 2;
switch (c) {
case 's': put_str(sb, va_arg(args, const char*)); break;
case 'u': put_u32(sb, va_arg(args, uint32_t)); break;
case 'x': put_u32_hex(sb, va_arg(args, uint32_t)); break;
case '%': base = fmt - 1; goto lit;
default: FATAL("bad format char %c", c);
}
} else if (c != '\0') {
base = fmt;
lit:
do { ++fmt; } while (*fmt != '%' && *fmt != '\0');
put_str_len(sb, base, (size_t)(fmt - base));
} else {
break;
}
}
va_end(args);
}
static sbuf_t* g_out;
static sbuf_t* g_includes;
/* Other end of string buffers; write one out to file. */
typedef struct indent_state_t {
uint16_t stack;
uint8_t level;
uint8_t state;
} indent_state_t;
static void write_indenting(FILE* f, const char* base, const char* end, indent_state_t* state) {
const char* itr = base;
while (itr != end) {
char c = *itr++;
/*
** state == 0 means nothing interesting has happened
** state == 1 means previous character was '{'
** state == 2 means previous character was '\n'
** state == 2 + N means N '}' characters have been observed and removed, and before them was '\n'
*/
if (state->state >= 2) {
if (c == '}') {
/* Un-indent if matching '{' caused an indent. */
state->level -= (state->stack & 1);
state->stack >>= 1;
/* Store the '}' in state rather than writing it out. */
state->state += 1;
if ((itr - base) > 1) fwrite(base, 1, itr - base - 1, f);
base = itr;
continue;
}
if (c != '\n' || state->state > 2) {
/* Write out everything that came prior to c. */
if ((itr - base) > 1) fwrite(base, 1, itr - base - 1, f);
base = itr - 1;
/* Write indent before writing c. */
fwrite(" ", 2, state->level, f);
/* If any '}' were stored, write them out before writing c. */
fwrite("}}}}}}}}}}}}}}}}", 1, state->state - 2, f);
}
state->state = 0;
}
switch (c) {
case '{':
if (state->stack & 0x8000) FATAL("nesting too deep");
state->stack <<= 1;
state->state = 1;
break;
case '\n':
state->stack |= state->state;
state->level += state->state;
if (state->level > 16) FATAL("nesting too deep");
state->state = 2;
break;
case '}':
state->level -= (state->stack & 1);
state->stack >>= 1;
/* fallthrough */
default:
state->state = 0;
break;
}
}
if (itr != base) fwrite(base, 1, itr - base, f);
}
static void sbuf_set_end_marker(sbuf_t* b, sbuf_t* return_to, uint32_t return_idx) {
char* dst = sbuf_emplace(b, 2 + sizeof(sbuf_t*) + sizeof(uint32_t));
dst[0] = '\0';
dst[1] = SBUF_OP_END;
b->size = 0;
memcpy(dst + 2, &return_to, sizeof(sbuf_t*));
memcpy(dst + 2 + sizeof(sbuf_t*), &return_idx, sizeof(uint32_t));
}
static void flush_sbuf_to(sbuf_t* b, FILE* f) {
indent_state_t indent_state = {0};
char* itr;
char c;
sbuf_set_end_marker(b, NULL, 0);
itr = b->base;
for (;;) {
char* start = itr;
while ((c = *itr)) {
++itr;
}
if (itr != start) {
write_indenting(f, start, itr, &indent_state);
}
c = itr[1];
if (c == SBUF_OP_DEFERRED) {
sbuf_t* b2;
itr += 2;
memcpy(&b2, itr, sizeof(b2));
itr += sizeof(b2);
if (b2->size) {
sbuf_set_end_marker(b2, b, (uint32_t)(itr - b->base));
itr = b2->base;
b = b2;
}
} else if (c == SBUF_OP_DEFERRED_FN) {
sbuf_fn_t fn;
sbuf_t* tmp = sbuf_new();
itr[1] = SBUF_OP_DEFERRED;
memcpy(&fn, itr + 2, sizeof(fn));
memcpy(itr + 2, &tmp, sizeof(sbuf_t*));
fn(tmp);
} else if (c == SBUF_OP_END) {
b->size = itr - b->base;
itr += 2;
memcpy(&b, itr, sizeof(sbuf_t*));
if (b) {
uint32_t idx;
memcpy(&idx, itr + sizeof(sbuf_t*), sizeof(uint32_t));
itr = b->base + idx;
} else {
break;
}
} else {
FATAL("bad sbuf op %u", (unsigned)(unsigned char)c);
}
}
fflush(f);
}
/* Command line parsing. */
typedef enum isa_t {
ISA_NONE,
ISA_NEON,
ISA_NEON_EOR3,
ISA_SSE,
ISA_AVX512,
ISA_AVX512_VPCLMULQDQ
} isa_t;
#define REV_POLY_CRC32 0xedb88320
#define REV_POLY_CRC32C 0x82f63b78
typedef struct algo_phase_t {
uint32_t v_acc; /* Number of vector accumulators. */
uint32_t v_load; /* Number of vector loads (must be multiple of v_acc). */
uint32_t s_acc; /* Number of scalar accumulators. */
uint32_t s_load; /* Number of scalar loads (must be multiple of s_acc). */
uint32_t kernel_size; /* Outer loop step size, or 0. */
uint32_t use_end_ptr;
struct algo_phase_t* next;
} algo_phase_t;
static isa_t g_isa = ISA_NONE;
static uint32_t g_poly = REV_POLY_CRC32;
static algo_phase_t* g_algo;
static const char* g_out_path;
typedef struct cli_arg_t {
const char* const* spellings;
const char* value;
} cli_arg_t;
static const char* match_spelling(const char* const* spellings, const char* str, size_t n) {
const char* spelling;
while ((spelling = *spellings++)) {
if (strlen(spelling) == n && memcmp(spelling, str, n) == 0) {
break;
}
}
return spelling;
}
static cli_arg_t* match_arg(cli_arg_t** args, const char* str, size_t n) {
cli_arg_t* arg;
while ((arg = *args++)) {
if (match_spelling(arg->spellings, str, n)) {
break;
}
}
return arg;
}
static isa_t parse_isa(const char* isa) {
if (!strcmp(isa, "none")) return ISA_NONE;
else if (!strcmp(isa, "neon")) return ISA_NEON;
else if (!strcmp(isa, "neon_eor3")) return ISA_NEON_EOR3;
else if (!strcmp(isa, "sse") || !strcmp(isa, "avx") || !strcmp(isa, "avx2")) return ISA_SSE;
else if (!strcmp(isa, "avx512")) return ISA_AVX512;
else if (!strcmp(isa, "avx512_vpclmulqdq")) return ISA_AVX512_VPCLMULQDQ;
else FATAL("unknown ISA %s", isa);
}
static uint32_t rev32(uint32_t poly) {
uint32_t lo = 1u, hi = 0x80000000u;
do {
uint32_t mask = lo + hi;
uint32_t bits = poly & mask;
if (bits != 0 && bits != mask) {
poly ^= mask;
}
lo <<= 1;
hi >>= 1;
} while (lo < hi);
return poly;
}
static uint32_t parse_poly(const char* value) {
if (!strcmp(value, "crc32") || !strcmp(value, "CRC32")) return REV_POLY_CRC32;
else if (!strcmp(value, "crc32c") || !strcmp(value, "CRC32C")) return REV_POLY_CRC32C;
else if (!strcmp(value, "crc32k") || !strcmp(value, "CRC32K")) return 0xEB31D82E;
else if (!strcmp(value, "crc32k2") || !strcmp(value, "CRC32K2")) return 0x992C1A4C;
else if (!strcmp(value, "crc32q") || !strcmp(value, "CRC32Q")) return 0xD5828281;
else {
uint32_t poly = 0, i = 0;
char c;
if (value[0] == '0' && (value[1] == 'x' || value[1] == 'X') && value[2]) {
value += 2;
}
while ((c = value[i++])) {
if ('0' <= c && c <= '9') c -= '0';
else if ('a' <= c && c <= 'f') c = c - 'a' + 10;
else if ('A' <= c && c <= 'F') c = c - 'A' + 10;
else FATAL("invalid polynomial %s", value);
if (i > (8 + (value[0] == '1'))) FATAL("polynomial %s too long", value);
poly = (poly << 4) + (uint8_t)c;
}
if (i < 9) {
FATAL("polynomial %s too short", value);
}
return rev32(poly);
}
}
static algo_phase_t* parse_algo(const char* value) {
algo_phase_t* first = (algo_phase_t*)calloc(1, sizeof(algo_phase_t));
algo_phase_t* cur = first;
uint32_t i = 0, n, x;
char c, c2;
while ((c = value[i++])) {
if (c == 'v' || c == 's' || c == 'k') {
c2 = value[i++];
if (c2 < '0' || c2 > '9') {
FATAL("expected digit sequence after character %c in algorithm string %s", c, value);
}
n = c2 - '0';
for (; (c2 = value[i]), ('0' <= c2 && c2 <= '9'); ++i) {
n = n * 10 + (c2 - '0');
}
x = 1;
if (c2 == 'x' && c != 'k') {
c2 = value[++i];
if (c2 < '0' || c2 > '9') {
FATAL("expected digit sequence after character x in algorithm string %s", value);
}
x = c2 - '0';
for (; (c2 = value[++i]), ('0' <= c2 && c2 <= '9');) {
x = x * 10 + (c2 - '0');
}
}
if (c == 'v') {
cur->v_load += n * x;
if (cur->v_acc < n) cur->v_acc = n;
} else if (c == 's') {
cur->s_load += n * x;
if (cur->s_acc < n) cur->s_acc = n;
} else {
cur->kernel_size = n;
}
} else if (c == 'e') {
cur->use_end_ptr = 1;
} else if (c == '_') {
algo_phase_t* next = (algo_phase_t*)calloc(1, sizeof(algo_phase_t));
cur->next = next;
cur = next;
} else {
FATAL("unrecognised character %c in algorithm string %s", c, value);
}
}
for (cur = first; cur; cur = cur->next) {
if (!cur->s_acc && !cur->v_acc) {
cur->s_acc = cur->s_load = 1;
}
if (cur->s_acc && (cur->s_load % cur->s_acc)) {
FATAL("algorithm %s has s load count (%u) not an integer multiple of s acc count (%u)", value, cur->s_load, cur->s_acc);
}
if (cur->v_acc && (cur->v_load % cur->v_acc)) {
FATAL("algorithm %s has v load count (%u) not an integer multiple of v acc count (%u)", value, cur->v_load, cur->v_acc);
}
if (g_isa == ISA_NONE) {
if (cur->v_load) FATAL("need to specify an ISA to use vector accumulators");
if (cur->s_acc > 1) FATAL("need to specify an ISA to use more than one scalar accumulator");
}
}
return first;
}
static void parse_args(int argc, const char* const* argv) {
sbuf_t* b;
#define ARGS \
DEF_ARG(isa, "-i") \
DEF_ARG(poly, "-p", "--polynomial") \
DEF_ARG(algo, "-a", "--algorithm") \
DEF_ARG(out, "-o", "--output")
#define DEF_ARG(name, ...) static const char* name##_spellings[] = {"--" #name, __VA_ARGS__, NULL};
ARGS
#undef DEF_ARG
#define DEF_ARG(name, ...) cli_arg_t name = {name##_spellings, NULL};
ARGS
#undef DEF_ARG
#define DEF_ARG(name, ...) &name,
cli_arg_t* args[] = { ARGS NULL };
#undef DEF_ARG
#undef ARGS
int i;
for (i = 1; i < argc; ++i) {
const char* arg = argv[i];
if (!strcmp(arg, "--help") || !strcmp(arg, "-h") || !strcmp(arg, "-?")) {
print_help(stdout, argv[0]);
exit(0);
} else {
const char* eq = strchr(arg, '=');
size_t n = eq ? (size_t)(eq - arg) : strlen(arg);
cli_arg_t* m = match_arg(args, arg, n);
if (m) {
if (eq) {
m->value = eq + 1;
} else if (++i < argc) {
m->value = argv[i];
} else {
FATAL("missing value for option %.*s", (int)n, arg);
}
} else {
FATAL("unknown option %.*s", (int)n, arg);
}
}
}
if (isa.value && *isa.value) g_isa = parse_isa(isa.value);
if (poly.value && *poly.value) g_poly = parse_poly(poly.value);
if (algo.value && *algo.value) g_algo = parse_algo(algo.value);
g_out_path = out.value;
b = g_includes;
put_fmt(b, "/* Generated by https://github.com/corsix/fast-crc32/ using: */\n/* %s", argv[0]);
for (i = 0; i < (int)(sizeof(args)/sizeof(args[0]))-1; ++i) {
cli_arg_t* arg = args[i];
if (arg->value && arg != &out) {
put_fmt(b, " %s %s", arg->spellings[1], arg->value);
}
}
put_lit(b, " */\n");
put_lit(b, "/* MIT licensed */\n\n");
}
/* Polynomial math helpers. */
/* These operate on GF(2^n) polynomials, expressed as reversed bit strings. */
static uint64_t xndivp(uint32_t n) /* x^n div P (n <= 95) */ {
uint64_t q = 0;
uint32_t r = 1;
for (n = 95 - n; n < 64; ++n) {
q ^= (r & 1ull) << n;
r = (r >> 1) ^ ((r & 1) * g_poly);
}
return q;
}
static uint32_t xnmodp(uint64_t n) /* x^n mod P, in log(n) time */ {
uint64_t stack = ~(uint64_t)1, r;
uint32_t i;
for (; n > 31; n >>= 1) {
stack = (stack << 1) + (n & 1);
}
stack = ~stack;
r = ((uint32_t)0x80000000) >> n; /* r = x^n (n <= 31) */
while ((i = stack & 1), stack >>= 1) {
/* r = r^2 * x^1, and expand from 32 to 64 bits. */
/* In GF(2), (a + b)^2 == a^2 + b^2, so r^2 is computed by expressing r as
** the sum of its bits and then squaring each bit individually. The extra
** x^1 appears because the product of two 32-bit polynomials is a 63-bit
** polynomial, and going from 63 to 64 in the reversed domain is *x^1. */
r ^= r << 16, r &= 0x0000ffff0000ffffull;
r ^= r << 8, r &= 0x00ff00ff00ff00ffull;
r ^= r << 4, r &= 0x0f0f0f0f0f0f0f0full;
r ^= r << 2, r &= 0x3333333333333333ull;
r ^= r << 1, r &= 0x5555555555555555ull;
/* r = r / x^i (i <= 1) */
/* This conditionally removes the *x^1 from the previous step. */
r <<= i;
/* r = r mod P, and narrow back down to 32 bits. */
for (i = 0; i < 32; ++i) {
r = (r >> 1) ^ ((r & 1) * g_poly);
}
}
return (uint32_t)r;
}
/* Code generator. */
static const char* g_scalar1_fn = "crc_u8";
static const char* g_scalar4_fn = "crc_u32";
static const char* g_scalar8_fn = "crc_u64";
static const char* g_vec16_type;
static const char* g_vec16_lane8_fn;
static const char* g_vector_type;
static uint32_t g_scalar_natural_bytes = 8;
static uint32_t g_vector_bytes = 16;
static uint32_t g_table_planes = 0;
#define possible_header(name) \
static void need_##name##_h() { \
static int done = 0; \
if (!done) put_lit(g_includes, "#include <" #name ".h>\n"); \
done = 1; \
}
possible_header(arm_acle)
possible_header(arm_neon)
possible_header(nmmintrin)
possible_header(immintrin)
possible_header(wmmintrin)
#undef possible_header
static void emit_standard_preprocessor(void) {
put_lit(g_includes, "#include <stddef.h>\n");
put_lit(g_includes, "#include <stdint.h>\n");
put_lit(g_out, "\n#if defined(_MSC_VER)\n");
put_lit(g_out, "#define CRC_AINLINE static __forceinline\n");
put_lit(g_out, "#define CRC_ALIGN(n) __declspec(align(n))\n");
put_lit(g_out, "#else\n");
put_lit(g_out, "#define CRC_AINLINE static __inline __attribute__((always_inline))\n");
put_lit(g_out, "#define CRC_ALIGN(n) __attribute__((aligned(n)))\n");
put_lit(g_out, "#endif\n");
put_lit(g_out, "#define CRC_EXPORT extern\n\n");
}
static void generate_table(sbuf_t* b) {
uint32_t i, j, k;
put_fmt(b, "[%u][256] = {", g_table_planes);
for (i = 0; i < g_table_planes; ) {
put_lit(b, "{\n");
for (j = 0; j < 256; ) {
uint32_t crc = j;
for (k = (i + 1) * 8; k; --k) {
crc = (crc >> 1) ^ ((crc & 1) * g_poly);
}
++j;
put_fmt(b, "0x%x%s", crc, j >= 256 ? "" : j % 6 ? ", " : ",\n");
}
if (++i < g_table_planes) {
put_lit(b, "},");
} else {
put_lit(b, "\n}};\n\n");
}
}
}
static const char* need_crc_table(uint32_t planes) {
const char* table_var = "g_crc_table";
if (planes > g_table_planes) {
if (g_table_planes == 0) {
put_fmt(g_out, "static const uint32_t %s", table_var);
put_deferred_fn(g_out, generate_table);
}
g_table_planes = planes;
}
return table_var;
}
static void need_clmul_fn(const char* which, isa_t isa) {
static uint32_t done = 0;
uint32_t lo = which[0] == 'l';
uint32_t mask = 1u << (lo + 2 * (uint32_t)isa);
sbuf_t* b = g_out;
if (done & mask) return;
done |= mask;
switch (isa) {
case ISA_NEON:
need_arm_neon_h();
put_fmt(b, "CRC_AINLINE %s clmul_%s_e(%s a, %s b, %s c) {\n", g_vector_type, which, g_vector_type, g_vector_type, g_vector_type);
put_fmt(b, "%s r;\n", g_vector_type);
put_fmt(b, "__asm(\"pmull%s %%0.1q, %%2.%ud, %%3.%ud\\neor %%0.16b, %%0.16b, %%1.16b\\n\" : \"=w\"(r), \"+w\"(c) : \"w\"(a), \"w\"(b));\n", &"2"[lo], 2u - lo, 2u - lo);
put_lit(b, "return r;\n");
put_lit(b, "}\n\n");
break;
case ISA_NEON_EOR3:
need_arm_neon_h();
put_fmt(b, "CRC_AINLINE %s clmul_%s(%s a, %s b) {\n", g_vector_type, which, g_vector_type, g_vector_type);
put_fmt(b, "%s r;\n", g_vector_type);
put_fmt(b, "__asm(\"pmull%s %%0.1q, %%1.%ud, %%2.%ud\\n\" : \"=w\"(r) : \"w\"(a), \"w\"(b));\n", &"2"[lo], 2u - lo, 2u - lo);
put_lit(b, "return r;\n");
put_lit(b, "}\n\n");
break;
case ISA_SSE:
case ISA_AVX512:
need_wmmintrin_h();
put_fmt(b, "#define clmul_%s(a, b) (_mm_clmulepi64_si128((a), (b), %u))%s\n", which, (uint32_t)(0x11 * !lo), &"\n"[lo]);
break;
case ISA_AVX512_VPCLMULQDQ:
need_immintrin_h();
put_fmt(b, "#define clmul_%s(a, b) (_mm512_clmulepi64_epi128((a), (b), %u))%s\n", which, (uint32_t)(0x11 * !lo), &"\n"[lo]);
break;
default:
FATAL_ISA();
}
}
static void need_crc_scalar(uint32_t size) {
static uint32_t done = 0;
sbuf_t* b;
if (done & size) return;
done |= size;
if (size > 8) return;
b = sbuf_new();
if (size == 1) {
const char* table_var = need_crc_table(1);
put_fmt(b, "CRC_AINLINE uint32_t %s(uint32_t crc, uint8_t val) {\n", g_scalar1_fn);
put_fmt(b, "return (crc >> 8) ^ %s[0][(crc & 0xFF) ^ val];\n", table_var);
put_lit(b, "}\n\n");
} else if (size == 4) {
put_fmt(b, "CRC_AINLINE uint32_t %s(uint32_t crc, uint32_t val) {\n", g_scalar4_fn);
if (g_isa == ISA_NONE) {
const char* table_var = need_crc_table(4);
put_lit(b, "crc ^= val;\n");
put_fmt(b, "return %s[0][crc >> 24] ^ %s[1][(crc >> 16) & 0xFF] ^\n", table_var, table_var);
put_fmt(b, " %s[3][crc & 0xFF] ^ %s[2][(crc >> 8) & 0xFF];\n", table_var, table_var);
} else {
uint64_t q = xndivp(63);
if (g_isa == ISA_NEON || g_isa == ISA_NEON_EOR3) {
need_clmul_fn("lo", ISA_NEON_EOR3);
put_lit(b, "uint64x2_t a = vmovq_n_u64(crc ^ val);\n");
put_fmt(b, "a = clmul_lo(a, vmovq_n_u64(0x%x%xull));\n", (uint32_t)(q >> 32), (uint32_t)q);
put_fmt(b, "a = clmul_lo(a, vmovq_n_u64(0x%x%xull));\n", g_poly >> 31, g_poly * 2u + 1u);
put_lit(b, "return vgetq_lane_u32(vreinterpretq_u32_u64(a), 2);\n");
} else {
need_nmmintrin_h();
need_wmmintrin_h();
put_fmt(b, "__m128i k = _mm_setr_epi32(0x%x, 0x%x, 0x%x, %u);\n",
(uint32_t)q, (uint32_t)(q >> 32), g_poly * 2u + 1u, g_poly >> 31);
put_lit(b, "__m128i a = _mm_cvtsi32_si128(crc ^ val);\n");
put_lit(b, "__m128i b = _mm_clmulepi64_si128(a, k, 0x00);\n");
put_lit(b, "__m128i c = _mm_clmulepi64_si128(b, k, 0x10);\n");
put_lit(b, "return _mm_extract_epi32(c, 2);\n");
}
}
put_lit(b, "}\n\n");
} else if (size == 8) {
put_fmt(b, "CRC_AINLINE uint32_t %s(uint32_t crc, uint64_t val) {\n", g_scalar8_fn);
if (g_isa == ISA_NONE) {
need_crc_scalar(4);
put_fmt(b, "crc = %s(crc, (uint32_t)val);\n", g_scalar4_fn);
put_fmt(b, "return %s(crc, (uint32_t)(val >> 32));\n", g_scalar4_fn);
} else {
uint64_t q = xndivp(95);
if (g_isa == ISA_NEON || g_isa == ISA_NEON_EOR3) {
need_clmul_fn("lo", ISA_NEON_EOR3);
put_lit(b, "uint64x2_t a = vmovq_n_u64(crc ^ val);\n");
put_fmt(b, "a = clmul_lo(a, vmovq_n_u64(0x%x%xull));\n", (uint32_t)(q >> 32), (uint32_t)q);
put_fmt(b, "a = clmul_lo(a, vmovq_n_u64(0x%x%xull));\n", g_poly >> 31, g_poly * 2u + 1u);
put_lit(b, "return vgetq_lane_u32(vreinterpretq_u32_u64(a), 2);\n");
} else {
need_nmmintrin_h();
need_wmmintrin_h();
put_fmt(b, "__m128i k = _mm_setr_epi32(0x%x, 0x%x, 0x%x, %u);\n",
(uint32_t)q, (uint32_t)(q >> 32), g_poly * 2u + 1u, g_poly >> 31);
put_lit(b, "__m128i a = _mm_cvtsi64_si128(crc ^ val);\n");
put_lit(b, "__m128i b = _mm_clmulepi64_si128(a, k, 0x00);\n");
put_lit(b, "__m128i c = _mm_clmulepi64_si128(b, k, 0x10);\n");
put_lit(b, "return _mm_extract_epi32(c, 2);\n");
}
}
put_lit(b, "}\n\n");
}
put_deferred_sbuf(g_out, b);
}
static void init_isa(void) {
switch (g_isa) {
case ISA_NEON:
case ISA_NEON_EOR3:
g_vec16_type = "uint64x2_t";
g_vec16_lane8_fn = "vgetq_lane_u64";
break;
case ISA_AVX512_VPCLMULQDQ:
g_vector_bytes = 64;
g_vector_type = "__m512i";
/* fallthrough */
case ISA_SSE:
case ISA_AVX512:
g_vec16_type = "__m128i";
g_vec16_lane8_fn = "_mm_extract_epi64";
break;
case ISA_NONE:
g_scalar_natural_bytes = 4;
break;
}
if (g_vector_bytes == 16) {
g_vector_type = g_vec16_type;
}
if (g_poly == REV_POLY_CRC32) {
if (g_isa == ISA_NEON || g_isa == ISA_NEON_EOR3) {
need_arm_acle_h();
g_scalar1_fn = "__crc32b";
g_scalar4_fn = "__crc32w";
g_scalar8_fn = "__crc32d";
need_crc_scalar(15);
}
} else if (g_poly == REV_POLY_CRC32C) {
if (g_isa == ISA_NEON || g_isa == ISA_NEON_EOR3) {
need_arm_acle_h();
g_scalar1_fn = "__crc32cb";
g_scalar4_fn = "__crc32cw";
g_scalar8_fn = "__crc32cd";
need_crc_scalar(15);
} else if (g_isa == ISA_SSE || g_isa == ISA_AVX512 || g_isa == ISA_AVX512_VPCLMULQDQ) {
need_nmmintrin_h();
g_scalar1_fn = "_mm_crc32_u8";
g_scalar4_fn = "_mm_crc32_u32";
g_scalar8_fn = "_mm_crc32_u64";
need_crc_scalar(15);
}
}
}
static void need_clmul_scalar(void) {
static int done = 0;
sbuf_t* b = g_out;
if (done) return;
done = 1;
put_fmt(b, "CRC_AINLINE %s clmul_scalar(uint32_t a, uint32_t b) {\n", g_vec16_type);
if (g_isa == ISA_NEON || g_isa == ISA_NEON_EOR3) {
need_arm_neon_h();
put_lit(b, "uint64x2_t r;\n");
put_lit(b, "__asm(\"pmull %0.1q, %1.1d, %2.1d\\n\" : \"=w\"(r) : \"w\"(vmovq_n_u64(a)), \"w\"(vmovq_n_u64(b)));\n");
put_lit(b, "return r;\n");
} else {
need_wmmintrin_h();
put_lit(b, "return _mm_clmulepi64_si128(_mm_cvtsi32_si128(a), _mm_cvtsi32_si128(b), 0);\n");
}
put_lit(b, "}\n\n");
}
static void need_crc_shift(void) {
static int done = 0;
sbuf_t* b = g_out;
if (done) return;
done = 1;
need_clmul_scalar();
need_crc_scalar(4);
need_crc_scalar(8);
put_lit(b, "static uint32_t xnmodp(uint64_t n) /* x^n mod P, in log(n) time */ {\n");
put_lit(b, "uint64_t stack = ~(uint64_t)1;\n");
put_lit(b, "uint32_t acc, low;\n");
put_lit(b, "for (; n > 191; n = (n >> 1) - 16) {\n");
put_lit(b, "stack = (stack << 1) + (n & 1);\n");
put_lit(b, "}\n");
put_lit(b, "stack = ~stack;\n");
put_lit(b, "acc = ((uint32_t)0x80000000) >> (n & 31);\n");
put_lit(b, "for (n >>= 5; n; --n) {\n");
put_fmt(b, "acc = %s(acc, 0);\n", g_scalar4_fn);
put_lit(b, "}\n");
put_lit(b, "while ((low = stack & 1), stack >>= 1) {\n");
if (g_isa == ISA_NEON || g_isa == ISA_NEON_EOR3) {
put_lit(b, "poly8x8_t x = vreinterpret_p8_u64(vmov_n_u64(acc));\n");
put_lit(b, "uint64_t y = vgetq_lane_u64(vreinterpretq_u64_p16(vmull_p8(x, x)), 0);\n");
} else {
put_lit(b, "__m128i x = _mm_cvtsi32_si128(acc);\n");
put_lit(b, "uint64_t y = _mm_cvtsi128_si64(_mm_clmulepi64_si128(x, x, 0));\n");
}
put_fmt(b, "acc = %s(0, y << low);\n", g_scalar8_fn);
put_lit(b, "}\n");
put_lit(b, "return acc;\n");
put_lit(b, "}\n\n");
put_fmt(b, "CRC_AINLINE %s crc_shift(uint32_t crc, size_t nbytes) {\n", g_vec16_type);
put_lit(b, "return clmul_scalar(crc, xnmodp(nbytes * 8 - 33));\n");
put_lit(b, "}\n\n");
}
static void emit_scalar_fn_mem(sbuf_t* b, uint32_t acc, uint32_t size) {
need_crc_scalar(size);
put_fmt(b, "crc%u = ", acc);
if (size == 8) {
put_fmt(b, "%s(crc%u, *(const uint64_t*)", g_scalar8_fn, acc);
} else if (size == 4) {
put_fmt(b, "%s(crc%u, *(const uint32_t*)", g_scalar4_fn, acc);
} else if (size == 1) {
put_fmt(b, "%s(crc%u, *(const uint8_t*)", g_scalar1_fn, acc);
} else {
FATAL("bad size %d", (int)size);
}
}
static void emit_vector_load(sbuf_t* b, const char* base, uint32_t offset) {
switch (g_isa) {
case ISA_NEON:
case ISA_NEON_EOR3:
put_lit(b, "vld1q_u64((const uint64_t*)");
break;
case ISA_SSE:
case ISA_AVX512:
put_lit(b, "_mm_loadu_si128((const __m128i*)");
break;
case ISA_AVX512_VPCLMULQDQ:
put_lit(b, "_mm512_loadu_si512((const void*)");
break;
default:
FATAL_ISA();
}
if (offset) put_lit(b, "(");
put_str(b, base);
if (offset) put_fmt(b, " + %u)", offset);
put_lit(b, ")");
}
static void emit_product(sbuf_t* b, const char* lhs, uint32_t rhs) {
if (rhs == 0) {
put_lit(b, "0");
} else {
put_str(b, lhs);
if (rhs > 1) {
put_fmt(b, " * %u", rhs);
}
}
}
static void emit_vc_xor_tree(sbuf_t* b, uint32_t lo, uint32_t hi) {
uint32_t range = hi - lo;
if (range == 1) {
put_fmt(b, "vc%u", lo);
} else if (range >= 3 && (g_isa == ISA_NEON_EOR3 || g_isa == ISA_AVX512 || g_isa == ISA_AVX512_VPCLMULQDQ)) {
uint32_t m1 = lo + range / 3;
uint32_t m2 = hi - range / 3;
if (g_isa == ISA_NEON_EOR3) {
put_lit(b, "veor3q_u64(");
} else {
need_immintrin_h();
put_lit(b, "_mm_ternarylogic_epi64(");
}
emit_vc_xor_tree(b, lo, m1);
put_lit(b, ", ");
emit_vc_xor_tree(b, m1, m2);
put_lit(b, ", ");
emit_vc_xor_tree(b, m2, hi);
if (g_isa != ISA_NEON_EOR3) {
put_lit(b, ", 0x96");
}
put_lit(b, ")");
} else {
uint32_t mid = lo + range / 2;
if (g_isa == ISA_NEON_EOR3 || g_isa == ISA_NEON) {
put_lit(b, "veorq_u64(");
} else {
put_lit(b, "_mm_xor_si128(");
}
emit_vc_xor_tree(b, lo, mid);
put_lit(b, ", ");
emit_vc_xor_tree(b, mid, hi);
put_lit(b, ")");
}
}
static void emit_vector_set_k(sbuf_t* b, uint32_t k) {
uint32_t k1 = xnmodp(k * g_vector_bytes * 8 + 32 - 1);
uint32_t k2 = xnmodp(k * g_vector_bytes * 8 - 32 - 1);
if (g_isa == ISA_NEON || g_isa == ISA_NEON_EOR3) {
put_fmt(b, "{ static const uint64_t CRC_ALIGN(16) k_[] = {0x%x, 0x%x}; ", k1, k2);
put_lit(b, "k = vld1q_u64(k_); }\n");
} else {
put_lit(b, "k = ");
if (g_vector_bytes > 16) put_lit(b, "_mm512_broadcast_i32x4(");
put_fmt(b, "_mm_setr_epi32(0x%x, 0, 0x%x, 0)", k1, k2);
if (g_vector_bytes > 16) put_lit(b, ")");
put_lit(b, ";\n");
}
}
static void emit_xor_scalar_into_vector(sbuf_t* b, const char* scalar, const char* vector) {
switch (g_isa) {
case ISA_NEON:
case ISA_NEON_EOR3:
put_fmt(b, "%s = veorq_u64((uint64x2_t){%s, 0}, %s);\n", vector, scalar, vector);
break;
case ISA_SSE:
case ISA_AVX512:
put_fmt(b, "%s = _mm_xor_si128(_mm_cvtsi32_si128(%s), %s);\n", vector, scalar, vector);
break;
case ISA_AVX512_VPCLMULQDQ:
put_fmt(b, "%s = _mm512_xor_si512(_mm512_castsi128_si512(_mm_cvtsi32_si128(%s)), %s);\n", vector, scalar, vector);
break;
default:
FATAL_ISA();
}
}
static void emit_vector_fma(sbuf_t* p1, sbuf_t* p2, uint32_t reg, const char* addend, uint32_t offset) {
/* Does `x{reg} = x{reg} * k + addend` in two parts; part one written to `p1`, part two to `p2`. */
/* A previous emit_vector_set_k call will have set `k`. */
need_clmul_fn("lo", g_isa);
need_clmul_fn("hi", g_isa);
if (g_isa != ISA_NEON) {
put_fmt(p1, "y%u = clmul_lo(x%u, k), x%u = clmul_hi(x%u, k);\n", reg, reg, reg, reg);
}
switch (g_isa) {
case ISA_NEON: put_fmt(p2, "y%u = clmul_lo_e(x%u, k, ", reg, reg); break;
case ISA_NEON_EOR3: put_fmt(p2, "x%u = veor3q_u64(x%u, y%u, ", reg, reg, reg); break;
case ISA_SSE: put_fmt(p2, "y%u = _mm_xor_si128(y%u, ", reg, reg); break;
case ISA_AVX512: put_fmt(p2, "x%u = _mm_ternarylogic_epi64(x%u, y%u, ", reg, reg, reg); break;
case ISA_AVX512_VPCLMULQDQ: put_fmt(p2, "x%u = _mm512_ternarylogic_epi64(x%u, y%u, ", reg, reg, reg); break;
default: FATAL_ISA();
}
if (addend[1]) {
emit_vector_load(p2, addend, offset);
} else {
put_fmt(p2, "%s%u", addend, offset);
}
switch (g_isa) {
case ISA_NEON: put_fmt(p2, "), x%u = clmul_hi_e(x%u, k, y%u);\n", reg, reg, reg); break;
case ISA_NEON_EOR3: put_lit(p2, ");\n"); break;
case ISA_SSE: put_fmt(p2, "), x%u = _mm_xor_si128(x%u, y%u);\n", reg, reg, reg); break;
case ISA_AVX512: case ISA_AVX512_VPCLMULQDQ: put_lit(p2, ", 0x96);\n"); need_immintrin_h(); break;
default: FATAL_ISA();
}
}
static void emit_scalar_main(sbuf_t* b, algo_phase_t* ap) {
uint32_t i, j;