Debian Codegraph @

gcc/testsuite/g++.target/loongarch/crc.C

raw
1 /* { dg-do run } */
2 /* { dg-options "-O2" } */
3
4 typedef __UINT8_TYPE__ uint8_t;
5 typedef __UINT16_TYPE__ uint16_t;
6 typedef __UINT32_TYPE__ uint32_t;
7 typedef __UINT64_TYPE__ uint64_t;
8 typedef __SIZE_TYPE__ size_t;
9
10 template <class T, uint32_t poly>
11 __attribute__ ((always_inline)) inline uint32_t
12 crc32_impl (const T *data, size_t len)
13 {
14 uint32_t ret = 0xffffffffu;
15 for (size_t k = 0; k < len; k++)
16 {
17 ret ^= data[k];
18 for (int i = 0; i < 8 * sizeof (T); i++)
19 if (ret & 1)
20 ret = (ret >> 1) ^ poly;
21 else
22 ret >>= 1;
23 }
24 return ret;
25 }
26
27 template <class T, uint32_t poly>
28 __attribute__ ((noipa, optimize (0))) uint32_t
29 crc32_ref (const T *data, size_t len)
30 {
31 return crc32_impl<T, poly> (data, len);
32 }
33
34 template <class T, uint32_t poly>
35 __attribute__ ((noipa)) uint32_t
36 crc32_opt (const T *data, size_t len)
37 {
38 return crc32_impl<T, poly> (data, len);
39 }
40
41 template <class T, uint32_t poly>
42 __attribute__ ((noipa)) uint32_t
43 crc32_alt (const T *data, size_t len)
44 {
45 uint32_t ret = 0xffffffffu;
46 for (size_t k = 0; k < len; k++)
47 {
48 T x = data[k];
49 for (int i = 0; i < 8 * sizeof (T); i++)
50 {
51 if ((ret & 1) ^ (x & 1))
52 ret = (ret >> 1) ^ poly;
53 else
54 ret >>= 1;
55 x >>= 1;
56 }
57 }
58 return ret;
59 }
60
61 union test_data_t
62 {
63 uint8_t u8[1024];
64 uint16_t u16[512];
65 uint32_t u32[256];
66
67 operator const uint8_t * () const { return u8; }
68 operator const uint16_t * () const { return u16; }
69 operator const uint32_t * () const { return u32; }
70
71 constexpr
72 test_data_t ()
73 : u8{}
74 {
75 }
76 };
77
78 /* Generate test data at compile time with minstd_rand0 algorithm. */
79 constexpr test_data_t
80 gen (uint64_t seed)
81 {
82 uint64_t state = seed;
83 test_data_t ret;
84 for (int i = 0; i < sizeof (ret); i++)
85 {
86 state = state * 16807 % 2147483647;
87 ret.u8[i] = (uint8_t)state;
88 }
89 return ret;
90 }
91
92 constexpr union test_data_t test_data = gen (0xdeadbeef);
93
94 void
95 assert_eq (uint32_t x, uint32_t y)
96 {
97 if (x != y)
98 __builtin_trap ();
99 }
100
101 template <class T, uint32_t poly>
102 void
103 test_crc32 ()
104 {
105 constexpr size_t len = sizeof (test_data) / sizeof (T);
106 uint32_t ref = crc32_ref<T, poly> (test_data, len);
107 assert_eq (ref, crc32_opt<T, poly> (test_data, len));
108 assert_eq (ref, crc32_alt<T, poly> (test_data, len));
109 }
110
111 int
112 main (void)
113 {
114 test_crc32<uint32_t, 0xEDB88320u> ();
115 test_crc32<uint16_t, 0xEDB88320u> ();
116 test_crc32<uint8_t, 0xEDB88320u> ();
117 test_crc32<uint32_t, 0x82F63B78u> ();
118 test_crc32<uint16_t, 0x82F63B78u> ();
119 test_crc32<uint8_t, 0x82F63B78u> ();
120 }