add WIP cldivrem -- see if [[!inline ...]] works
[libreriscv.git] / openpower / sv / bitmanip.mdwn
1 [[!tag standards]]
2
3 # Implementation Log
4
5 * ternlogi <https://bugs.libre-soc.org/show_bug.cgi?id=745>
6 * grev <https://bugs.libre-soc.org/show_bug.cgi?id=755>
7 * remove Rc=1 from ternlog due to conflicts in encoding as well
8 as saving space <https://bugs.libre-soc.org/show_bug.cgi?id=753#c5>
9 * GF2^M <https://bugs.libre-soc.org/show_bug.cgi?id=782>
10
11 # bitmanipulation
12
13 **DRAFT STATUS**
14
15 pseudocode: <https://libre-soc.org/openpower/isa/bitmanip/>
16
17 this extension amalgamates bitmanipulation primitives from many sources, including RISC-V bitmanip, Packed SIMD, AVX-512 and OpenPOWER VSX. Vectorisation and SIMD are removed: these are straight scalar (element) operations making them suitable for embedded applications.
18 Vectorisation Context is provided by [[openpower/sv]].
19
20 When combined with SV, scalar variants of bitmanip operations found in VSX are added so that VSX may be retired as "legacy" in the far future (10 to 20 years). Also, VSX is hundreds of opcodes, requires 128 bit pathways, and is wholly unsuited to low power or embedded scenarios.
21
22 ternlogv is experimental and is the only operation that may be considered a "Packed SIMD". It is added as a variant of the already well-justified ternlog operation (done in AVX512 as an immediate only) "because it looks fun". As it is based on the LUT4 concept it will allow accelerated emulation of FPGAs. Other vendors of ISAs are buying FPGA companies to achieve similar objectives.
23
24 general-purpose Galois Field 2^M operations are added so as to avoid huge custom opcode proliferation across many areas of Computer Science. however for convenience and also to avoid setup costs, some of the more common operations (clmul, crc32) are also added. The expectation is that these operations would all be covered by the same pipeline.
25
26 note that there are brownfield spaces below that could incorporate some of the set-before-first and other scalar operations listed in [[sv/vector_ops]], and
27 the [[sv/av_opcodes]] as well as [[sv/setvl]]
28
29 Useful resource:
30
31 * <https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders>
32 * <https://maths-people.anu.edu.au/~brent/pd/rpb232tr.pdf>
33
34 # summary
35
36 two major opcodes are needed
37
38 ternlog has its own major opcode
39
40 | 29.30 |31| name |
41 | ------ |--| --------- |
42 | 0 0 |Rc| ternlogi |
43 | 0 1 |sz| ternlogv |
44 | 1 iv | | grevlogi |
45
46 2nd major opcode for other bitmanip: minor opcode allocation
47
48 | 28.30 |31| name |
49 | ------ |--| --------- |
50 | -00 |0 | xpermi |
51 | -00 |1 | grevlog |
52 | -01 | | crternlog |
53 | 010 |Rc| bitmask |
54 | 011 | | gf/cl madd* |
55 | 110 |Rc| 1/2-op |
56 | 111 | | bmrevi |
57
58
59 1-op and variants
60
61 | dest | src1 | subop | op |
62 | ---- | ---- | ----- | -------- |
63 | RT | RA | .. | bmatflip |
64
65 2-op and variants
66
67 | dest | src1 | src2 | subop | op |
68 | ---- | ---- | ---- | ----- | -------- |
69 | RT | RA | RB | or | bmatflip |
70 | RT | RA | RB | xor | bmatflip |
71 | RT | RA | RB | | grev |
72 | RT | RA | RB | | clmul* |
73 | RT | RA | RB | | gorc |
74 | RT | RA | RB | shuf | shuffle |
75 | RT | RA | RB | unshuf| shuffle |
76 | RT | RA | RB | width | xperm |
77 | RT | RA | RB | type | minmax |
78 | RT | RA | RB | | av abs avgadd |
79 | RT | RA | RB | type | vmask ops |
80 | RT | RA | RB | | |
81
82 3 ops
83
84 * grevlog
85 * GF mul-add
86 * bitmask-reverse
87
88 TODO: convert all instructions to use RT and not RS
89
90 | 0.5|6.8 | 9.11|12.14|15.17|18.20|21.28 | 29.30|31|name|
91 | -- | -- | --- | --- | --- |-----|----- | -----|--|----|
92 | NN | BT | BA | BB | BC |m0-2 | imm | 10 |m3|crternlog|
93
94 | 0.5|6.10|11.15|16.20 |21..25 | 26....30 |31| name |
95 | -- | -- | --- | --- | ----- | -------- |--| ------ |
96 | NN | RT | RA |itype/| im0-4 | im5-7 00 |0 | xpermi |
97 | NN | RT | RA | RB | im0-4 | im5-7 00 |1 | grevlog |
98 | NN | | | | | ..... 01 |0 | crternlog |
99 | NN | RT | RA | RB | RC | mode 010 |Rc| bitmask* |
100 | NN | RS | RA | RB | RC | 00 011 |0 | gfbmadd |
101 | NN | RS | RA | RB | RC | 00 011 |1 | gfbmaddsub |
102 | NN | RS | RA | RB | RC | 01 011 |0 | clmadd |
103 | NN | RS | RA | RB | RC | 01 011 |1 | clmaddsub |
104 | NN | RS | RA | RB | RC | 10 011 |0 | gfpmadd |
105 | NN | RS | RA | RB | RC | 10 011 |1 | gfpmaddsub |
106 | NN | RS | RA | RB | RC | 11 011 | | rsvd |
107 | NN | RT | RA | RB | sh0-4 | sh5 1 111 |Rc| bmrevi |
108
109 ops (note that av avg and abs as well as vec scalar mask
110 are included here)
111
112 TODO: convert from RA, RB, and RC to correct field names of RT, RA, and RB, and
113 double check that instructions didn't need 3 inputs.
114
115 | 0.5|6.10|11.15|16.20| 21 | 22.23 | 24....30 |31| name |
116 | -- | -- | --- | --- | -- | ----- | -------- |--| ---- |
117 | NN | RT | RA | RB | 0 | | 0000 110 |Rc| rsvd |
118 | NN | RT | RA | RB | 1 | itype | 0000 110 |Rc| xperm |
119 | NN | RA | RB | RC | 0 | itype | 0100 110 |Rc| minmax |
120 | NN | RA | RB | RC | 1 | 00 | 0100 110 |Rc| av avgadd |
121 | NN | RA | RB | RC | 1 | 01 | 0100 110 |Rc| av abs |
122 | NN | RA | RB | | 1 | 10 | 0100 110 |Rc| rsvd |
123 | NN | RA | RB | | 1 | 11 | 0100 110 |Rc| rsvd |
124 | NN | RA | RB | sh | SH | itype | 1000 110 |Rc| bmopsi |
125 | NN | RT | RA | RB | | | 1100 110 |Rc| srsvd |
126 | NN | RT | RA | RB | 1 | 00 | 0001 110 |Rc| cldiv |
127 | NN | RT | RA | RB | 1 | 01 | 0001 110 |Rc| clmod |
128 | NN | RT | RA | RB | 1 | 10 | 0001 110 |Rc| |
129 | NN | RT | RB | RB | 1 | 11 | 0001 110 |Rc| clinv |
130 | NN | RA | RB | RC | 0 | 00 | 0001 110 |Rc| vec sbfm |
131 | NN | RA | RB | RC | 0 | 01 | 0001 110 |Rc| vec sofm |
132 | NN | RA | RB | RC | 0 | 10 | 0001 110 |Rc| vec sifm |
133 | NN | RA | RB | RC | 0 | 11 | 0001 110 |Rc| vec cprop |
134 | NN | RA | RB | | 0 | | 0101 110 |Rc| rsvd |
135 | NN | RA | RB | RC | 0 | 00 | 0010 110 |Rc| gorc |
136 | NN | RA | RB | sh | SH | 00 | 1010 110 |Rc| gorci |
137 | NN | RA | RB | RC | 0 | 00 | 0110 110 |Rc| gorcw |
138 | NN | RA | RB | sh | 0 | 00 | 1110 110 |Rc| gorcwi |
139 | NN | RA | RB | RC | 1 | 00 | 1110 110 |Rc| bmator |
140 | NN | RA | RB | RC | 0 | 01 | 0010 110 |Rc| grev |
141 | NN | RA | RB | RC | 1 | 01 | 0010 110 |Rc| clmul |
142 | NN | RA | RB | sh | SH | 01 | 1010 110 |Rc| grevi |
143 | NN | RA | RB | RC | 0 | 01 | 0110 110 |Rc| grevw |
144 | NN | RA | RB | sh | 0 | 01 | 1110 110 |Rc| grevwi |
145 | NN | RA | RB | RC | 1 | 01 | 1110 110 |Rc| bmatxor |
146 | NN | RA | RB | RC | | 10 | --10 110 |Rc| rsvd |
147 | NN | RA | RB | RC | 0 | 11 | 1110 110 |Rc| clmulr |
148 | NN | RA | RB | RC | 1 | 11 | 1110 110 |Rc| clmulh |
149 | NN | | | | | | --11 110 |Rc| setvl |
150
151 # ternlog bitops
152
153 Similar to FPGA LUTs: for every bit perform a lookup into a table using an 8bit immediate, or in another register.
154
155 Like the x86 AVX512F [vpternlogd/vpternlogq](https://www.felixcloutier.com/x86/vpternlogd:vpternlogq) instructions.
156
157 ## ternlogi
158
159 | 0.5|6.10|11.15|16.20| 21..28|29.30|31|
160 | -- | -- | --- | --- | ----- | --- |--|
161 | NN | RT | RA | RB | im0-7 | 00 |Rc|
162
163 lut3(imm, a, b, c):
164 idx = c << 2 | b << 1 | a
165 return imm[idx] # idx by LSB0 order
166
167 for i in range(64):
168 RT[i] = lut3(imm, RB[i], RA[i], RT[i])
169
170 ## ternlogv
171
172 also, another possible variant involving swizzle-like selection
173 and masking, this only requires 3 64 bit registers (RA, RS, RB) and
174 only 16 LUT3s.
175
176 Note however that unless XLEN matches sz, this instruction
177 is a Read-Modify-Write: RS must be read as a second operand
178 and all unmodified bits preserved. SVP64 may provide limited
179 alternative destination for RS from RS-as-source, but again
180 all unmodified bits must still be copied.
181
182 | 0.5|6.10|11.15|16.20|21.28 | 29.30 |31|
183 | -- | -- | --- | --- | ---- | ----- |--|
184 | NN | RS | RA | RB |idx0-3| 01 |sz|
185
186 SZ = (1+sz) * 8 # 8 or 16
187 raoff = MIN(XLEN, idx0 * SZ)
188 rboff = MIN(XLEN, idx1 * SZ)
189 rcoff = MIN(XLEN, idx2 * SZ)
190 rsoff = MIN(XLEN, idx3 * SZ)
191 imm = RB[0:8]
192 for i in range(MIN(XLEN, SZ)):
193 ra = RA[raoff:+i]
194 rb = RA[rboff+i]
195 rc = RA[rcoff+i]
196 res = lut3(imm, ra, rb, rc)
197 RS[rsoff+i] = res
198
199 ## ternlogcr
200
201 another mode selection would be CRs not Ints.
202
203 | 0.5|6.8 | 9.11|12.14|15.17|18.20|21.28 | 29.30|31|
204 | -- | -- | --- | --- | --- |-----|----- | -----|--|
205 | NN | BT | BA | BB | BC |m0-2 | imm | 10 |m3|
206
207 mask = m0-3,m4
208 for i in range(4):
209 if not mask[i] continue
210 crregs[BT][i] = lut3(imm,
211 crregs[BA][i],
212 crregs[BB][i],
213 crregs[BC][i])
214
215
216 # int min/max
217
218 signed and unsigned min/max for integer. this is sort-of partly synthesiseable in [[sv/svp64]] with pred-result as long as the dest reg is one of the sources, but not both signed and unsigned. when the dest is also one of the srces and the mv fails due to the CR bittest failing this will only overwrite the dest where the src is greater (or less).
219
220 signed/unsigned min/max gives more flexibility.
221
222 ```
223 uint_xlen_t min(uint_xlen_t rs1, uint_xlen_t rs2)
224 { return (int_xlen_t)rs1 < (int_xlen_t)rs2 ? rs1 : rs2;
225 }
226 uint_xlen_t max(uint_xlen_t rs1, uint_xlen_t rs2)
227 { return (int_xlen_t)rs1 > (int_xlen_t)rs2 ? rs1 : rs2;
228 }
229 uint_xlen_t minu(uint_xlen_t rs1, uint_xlen_t rs2)
230 { return rs1 < rs2 ? rs1 : rs2;
231 }
232 uint_xlen_t maxu(uint_xlen_t rs1, uint_xlen_t rs2)
233 { return rs1 > rs2 ? rs1 : rs2;
234 }
235 ```
236
237
238 ## cmix
239
240 based on RV bitmanip, covered by ternlog bitops
241
242 ```
243 uint_xlen_t cmix(uint_xlen_t RA, uint_xlen_t RB, uint_xlen_t RC) {
244 return (RA & RB) | (RC & ~RB);
245 }
246 ```
247
248
249 # bitmask set
250
251 based on RV bitmanip singlebit set, instruction format similar to shift
252 [[isa/fixedshift]]. bmext is actually covered already (shift-with-mask rldicl but only immediate version).
253 however bitmask-invert is not, and set/clr are not covered, although they can use the same Shift ALU.
254
255 bmext (RB) version is not the same as rldicl because bmext is a right shift by RC, where rldicl is a left rotate. for the immediate version this does not matter, so a bmexti is not required.
256 bmrev however there is no direct equivalent and consequently a bmrevi is required.
257
258 bmset (register for mask amount) is particularly useful for creating
259 predicate masks where the length is a dynamic runtime quantity.
260 bmset(RA=0, RB=0, RC=mask) will produce a run of ones of length "mask" in a single instruction without needing to initialise or depend on any other registers.
261
262 | 0.5|6.10|11.15|16.20|21.25| 26..30 |31| name |
263 | -- | -- | --- | --- | --- | ------- |--| ----- |
264 | NN | RS | RA | RB | RC | mode 010 |Rc| bm* |
265
266 Immediate-variant is an overwrite form:
267
268 | 0.5|6.10|11.15|16.20| 21 | 22.23 | 24....30 |31| name |
269 | -- | -- | --- | --- | -- | ----- | -------- |--| ---- |
270 | NN | RS | RB | sh | SH | itype | 1000 110 |Rc| bm*i |
271
272 ```
273 uint_xlen_t bmset(RS, RB, sh)
274 {
275 int shamt = RB & (XLEN - 1);
276 mask = (2<<sh)-1;
277 return RS | (mask << shamt);
278 }
279
280 uint_xlen_t bmclr(RS, RB, sh)
281 {
282 int shamt = RB & (XLEN - 1);
283 mask = (2<<sh)-1;
284 return RS & ~(mask << shamt);
285 }
286
287 uint_xlen_t bminv(RS, RB, sh)
288 {
289 int shamt = RB & (XLEN - 1);
290 mask = (2<<sh)-1;
291 return RS ^ (mask << shamt);
292 }
293
294 uint_xlen_t bmext(RS, RB, sh)
295 {
296 int shamt = RB & (XLEN - 1);
297 mask = (2<<sh)-1;
298 return mask & (RS >> shamt);
299 }
300 ```
301
302 bitmask extract with reverse. can be done by bitinverting all of RB and getting bits of RB from the opposite end.
303
304 when RA is zero, no shift occurs. this makes bmextrev useful for
305 simply reversing all bits of a register.
306
307 ```
308 msb = ra[5:0];
309 rev[0:msb] = rb[msb:0];
310 rt = ZE(rev[msb:0]);
311
312 uint_xlen_t bmextrev(RA, RB, sh)
313 {
314 int shamt = XLEN-1;
315 if (RA != 0) (GPR(RA) & (XLEN - 1));
316 shamt = (XLEN-1)-shamt; # shift other end
317 bra = bitreverse(RB) # swap LSB-MSB
318 mask = (2<<sh)-1;
319 return mask & (bra >> shamt);
320 }
321 ```
322
323 | 0.5|6.10|11.15|16.20|21.26| 27..30 |31| name |
324 | -- | -- | --- | --- | --- | ------- |--| ------ |
325 | NN | RT | RA | RB | sh | 1 011 |Rc| bmrevi |
326
327
328 # grevlut
329
330 generalised reverse combined with a pair of LUT2s and allowing
331 a constant `0b0101...0101` when RA=0, and an option to invert
332 (including when RA=0, giving a constant 0b1010...1010 as the
333 initial value) provides a wide range of instructions
334 and a means to set regular 64 bit patterns in one
335 32 bit instruction.
336
337 the two LUT2s are applied left-half (when not swapping)
338 and right-half (when swapping) so as to allow a wider
339 range of options.
340
341 <img src="/openpower/sv/grevlut2x2.jpg" width=700 />
342
343 * A value of `0b11001010` for the immediate provides
344 the functionality of a standard "grev".
345 * `0b11101110` provides gorc
346
347 grevlut should be arranged so as to produce the constants
348 needed to put into bext (bitextract) so as in turn to
349 be able to emulate x86 pmovmask instructions <https://www.felixcloutier.com/x86/pmovmskb>.
350 This only requires 2 instructions (grevlut, bext).
351
352 Note that if the mask is required to be placed
353 directly into CR Fields (for use as CR Predicate
354 masks rather than a integer mask) then sv.ori
355 may be used instead, bearing in mind that sv.ori
356 is a 64-bit instruction, and `VL` must have been
357 set to the required length:
358
359 sv.ori./elwid=8 r10.v, r10.v, 0
360
361 The following settings provide the required mask constants:
362
363 | RA | RB | imm | iv | result |
364 | ------- | ------- | ---------- | -- | ---------- |
365 | 0x555.. | 0b10 | 0b01101100 | 0 | 0x111111... |
366 | 0x555.. | 0b110 | 0b01101100 | 0 | 0x010101... |
367 | 0x555.. | 0b1110 | 0b01101100 | 0 | 0x00010001... |
368 | 0x555.. | 0b10 | 0b11000110 | 1 | 0x88888... |
369 | 0x555.. | 0b110 | 0b11000110 | 1 | 0x808080... |
370 | 0x555.. | 0b1110 | 0b11000110 | 1 | 0x80008000... |
371
372 Better diagram showing the correct ordering of shamt (RB). A LUT2
373 is applied to all locations marked in red using the first 4
374 bits of the immediate, and a separate LUT2 applied to all
375 locations in green using the upper 4 bits of the immediate.
376
377 <img src="/openpower/sv/grevlut.png" width=700 />
378
379 demo code [[openpower/sv/grevlut.py]]
380
381 ```
382 lut2(imm, a, b):
383 idx = b << 1 | a
384 return imm[idx] # idx by LSB0 order
385
386 dorow(imm8, step_i, chunksize):
387 for j in 0 to 63:
388 if (j&chunk_size) == 0
389 imm = imm8[0..3]
390 else
391 imm = imm8[4..7]
392 step_o[j] = lut2(imm, step_i[j], step_i[j ^ chunk_size])
393 return step_o
394
395 uint64_t grevlut64(uint64_t RA, uint64_t RB, uint8 imm, bool iv)
396 {
397 uint64_t x = 0x5555_5555_5555_5555;
398 if (RA != 0) x = GPR(RA);
399 if (iv) x = ~x;
400 int shamt = RB & 63;
401 for i in 0 to 6
402 step = 1<<i
403 if (shamt & step) x = dorow(imm, x, step)
404 return x;
405 }
406
407 ```
408
409 | 0.5|6.10|11.15|16.20 |21..25 | 26....30 |31| name |
410 | -- | -- | --- | --- | ----- | -------- |--| ------ |
411 | NN | RT | RA | s0-4 | im0-4 | im5-7 1 iv |s5| grevlogi |
412 | NN | RT | RA | RB | im0-4 | im5-7 00 |1 | grevlog |
413
414
415 # grev
416
417 based on RV bitmanip, this is also known as a butterfly network. however
418 where a butterfly network allows setting of every crossbar setting in
419 every row and every column, generalised-reverse (grev) only allows
420 a per-row decision: every entry in the same row must either switch or
421 not-switch.
422
423 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Butterfly_Network.jpg/474px-Butterfly_Network.jpg" />
424
425 ```
426 uint64_t grev64(uint64_t RA, uint64_t RB)
427 {
428 uint64_t x = RA;
429 int shamt = RB & 63;
430 if (shamt & 1) x = ((x & 0x5555555555555555LL) << 1) |
431 ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
432 if (shamt & 2) x = ((x & 0x3333333333333333LL) << 2) |
433 ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
434 if (shamt & 4) x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) |
435 ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
436 if (shamt & 8) x = ((x & 0x00FF00FF00FF00FFLL) << 8) |
437 ((x & 0xFF00FF00FF00FF00LL) >> 8);
438 if (shamt & 16) x = ((x & 0x0000FFFF0000FFFFLL) << 16) |
439 ((x & 0xFFFF0000FFFF0000LL) >> 16);
440 if (shamt & 32) x = ((x & 0x00000000FFFFFFFFLL) << 32) |
441 ((x & 0xFFFFFFFF00000000LL) >> 32);
442 return x;
443 }
444
445 ```
446
447 # xperm
448
449 based on RV bitmanip.
450
451 RA contains a vector of indices to select parts of RB to be
452 copied to RT. The immediate-variant allows up to an 8 bit
453 pattern (repeated) to be targetted at different parts of RT
454
455 ```
456 uint_xlen_t xpermi(uint8_t imm8, uint_xlen_t RB, int sz_log2)
457 {
458 uint_xlen_t r = 0;
459 uint_xlen_t sz = 1LL << sz_log2;
460 uint_xlen_t mask = (1LL << sz) - 1;
461 uint_xlen_t RA = imm8 | imm8<<8 | ... | imm8<<56;
462 for (int i = 0; i < XLEN; i += sz) {
463 uint_xlen_t pos = ((RA >> i) & mask) << sz_log2;
464 if (pos < XLEN)
465 r |= ((RB >> pos) & mask) << i;
466 }
467 return r;
468 }
469 uint_xlen_t xperm(uint_xlen_t RA, uint_xlen_t RB, int sz_log2)
470 {
471 uint_xlen_t r = 0;
472 uint_xlen_t sz = 1LL << sz_log2;
473 uint_xlen_t mask = (1LL << sz) - 1;
474 for (int i = 0; i < XLEN; i += sz) {
475 uint_xlen_t pos = ((RA >> i) & mask) << sz_log2;
476 if (pos < XLEN)
477 r |= ((RB >> pos) & mask) << i;
478 }
479 return r;
480 }
481 uint_xlen_t xperm_n (uint_xlen_t RA, uint_xlen_t RB)
482 { return xperm(RA, RB, 2); }
483 uint_xlen_t xperm_b (uint_xlen_t RA, uint_xlen_t RB)
484 { return xperm(RA, RB, 3); }
485 uint_xlen_t xperm_h (uint_xlen_t RA, uint_xlen_t RB)
486 { return xperm(RA, RB, 4); }
487 uint_xlen_t xperm_w (uint_xlen_t RA, uint_xlen_t RB)
488 { return xperm(RA, RB, 5); }
489 ```
490
491 # gorc
492
493 based on RV bitmanip
494
495 ```
496 uint32_t gorc32(uint32_t RA, uint32_t RB)
497 {
498 uint32_t x = RA;
499 int shamt = RB & 31;
500 if (shamt & 1) x |= ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
501 if (shamt & 2) x |= ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2);
502 if (shamt & 4) x |= ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4);
503 if (shamt & 8) x |= ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8);
504 if (shamt & 16) x |= ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16);
505 return x;
506 }
507 uint64_t gorc64(uint64_t RA, uint64_t RB)
508 {
509 uint64_t x = RA;
510 int shamt = RB & 63;
511 if (shamt & 1) x |= ((x & 0x5555555555555555LL) << 1) |
512 ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
513 if (shamt & 2) x |= ((x & 0x3333333333333333LL) << 2) |
514 ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
515 if (shamt & 4) x |= ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) |
516 ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
517 if (shamt & 8) x |= ((x & 0x00FF00FF00FF00FFLL) << 8) |
518 ((x & 0xFF00FF00FF00FF00LL) >> 8);
519 if (shamt & 16) x |= ((x & 0x0000FFFF0000FFFFLL) << 16) |
520 ((x & 0xFFFF0000FFFF0000LL) >> 16);
521 if (shamt & 32) x |= ((x & 0x00000000FFFFFFFFLL) << 32) |
522 ((x & 0xFFFFFFFF00000000LL) >> 32);
523 return x;
524 }
525
526 ```
527
528 # Instructions for Carry-less Operations aka. Polynomials with coefficients in `GF(2)`
529
530 Carry-less addition/subtraction is simply XOR, so a `cladd`
531 instruction is not provided since the `xor[i]` instruction can be used instead.
532
533 These are operations on polynomials with coefficients in `GF(2)`, with the
534 polynomial's coefficients packed into integers with the following algorithm:
535
536 ```python
537 def pack_poly(poly):
538 """`poly` is a list where `poly[i]` is the coefficient for `x ** i`"""
539 retval = 0
540 for i, v in enumerate(poly):
541 retval |= v << i
542 return retval
543
544 def unpack_poly(v):
545 """returns a list `poly`, where `poly[i]` is the coefficient for `x ** i`.
546 """
547 poly = []
548 while v != 0:
549 poly.append(v & 1)
550 v >>= 1
551 return poly
552 ```
553
554 ## Carry-less Multiply Instructions
555
556 based on RV bitmanip
557 see <https://en.wikipedia.org/wiki/CLMUL_instruction_set> and
558 <https://www.felixcloutier.com/x86/pclmulqdq> and
559 <https://en.m.wikipedia.org/wiki/Carry-less_product>
560
561 They are worth adding as their own non-overwrite operations
562 (in the same pipeline).
563
564 ### `clmul` Carry-less Multiply
565
566 ```c
567 uint_xlen_t clmul(uint_xlen_t RA, uint_xlen_t RB)
568 {
569 uint_xlen_t x = 0;
570 for (int i = 0; i < XLEN; i++)
571 if ((RB >> i) & 1)
572 x ^= RA << i;
573 return x;
574 }
575 ```
576
577 ### `clmulh` Carry-less Multiply High
578
579 ```c
580 uint_xlen_t clmulh(uint_xlen_t RA, uint_xlen_t RB)
581 {
582 uint_xlen_t x = 0;
583 for (int i = 1; i < XLEN; i++)
584 if ((RB >> i) & 1)
585 x ^= RA >> (XLEN-i);
586 return x;
587 }
588 ```
589
590 ### `clmulr` Carry-less Multiply (Reversed)
591
592 Useful for CRCs. Equivalent to bit-reversing the result of `clmul` on
593 bit-reversed inputs.
594
595 ```c
596 uint_xlen_t clmulr(uint_xlen_t RA, uint_xlen_t RB)
597 {
598 uint_xlen_t x = 0;
599 for (int i = 0; i < XLEN; i++)
600 if ((RB >> i) & 1)
601 x ^= RA >> (XLEN-i-1);
602 return x;
603 }
604 ```
605
606 ## `clmadd` Carry-less Multiply-Add
607
608 ```
609 clmadd RT, RA, RB, RC
610 ```
611
612 ```
613 (RT) = clmul((RA), (RB)) ^ (RC)
614 ```
615
616 ## `cltmadd` Twin Carry-less Multiply-Add (for FFTs)
617
618 ```
619 cltmadd RT, RA, RB, RC
620 ```
621
622 TODO: add link to explanation for where `RS` comes from.
623
624 ```
625 temp = clmul((RA), (RB)) ^ (RC)
626 (RT) = temp
627 (RS) = temp
628 ```
629
630 ## `cldivrem` Carry-less Division and Remainder
631
632 `cldivrem` isn't an actual instruction, but is just used in the pseudo-code
633 for other instructions.
634
635 [[!inline pages="bitmanip_inlines/cldivrem.py" raw="true"]]
636
637 ## `cldiv` Carry-less Division
638
639 ```
640 cldiv RT, RA, RB
641 ```
642
643 TODO: decide what happens on division by zero
644
645 ```
646 (RT) = cldiv((RA), (RB))
647 ```
648
649 ## `clrem` Carry-less Remainder
650
651 ```
652 clrem RT, RA, RB
653 ```
654
655 TODO: decide what happens on division by zero
656
657 ```
658 (RT) = clrem((RA), (RB))
659 ```
660
661 # Instructions for Binary Galois Fields `GF(2^m)`
662
663 see:
664
665 * <https://courses.csail.mit.edu/6.857/2016/files/ffield.py>
666 * <https://engineering.purdue.edu/kak/compsec/NewLectures/Lecture7.pdf>
667 * <https://foss.heptapod.net/math/libgf2/-/blob/branch/default/src/libgf2/gf2.py>
668
669 Binary Galois Field addition/subtraction is simply XOR, so a `gfbadd`
670 instruction is not provided since the `xor[i]` instruction can be used instead.
671
672 ## `GFBREDPOLY` SPR -- Reducing Polynomial
673
674 In order to save registers and to make operations orthogonal with standard
675 arithmetic, the reducing polynomial is stored in a dedicated SPR `GFBREDPOLY`.
676 This also allows hardware to pre-compute useful parameters (such as the
677 degree, or look-up tables) based on the reducing polynomial, and store them
678 alongside the SPR in hidden registers, only recomputing them whenever the SPR
679 is written to, rather than having to recompute those values for every
680 instruction.
681
682 Because Galois Fields require the reducing polynomial to be an irreducible
683 polynomial, that guarantees that any polynomial of `degree > 1` must have
684 the LSB set, since otherwise it would be divisible by the polynomial `x`,
685 making it reducible, making whatever we're working on no longer a Field.
686 Therefore, we can reuse the LSB to indicate `degree == XLEN`.
687
688 ```python
689 def decode_reducing_polynomial(GFBREDPOLY, XLEN):
690 """returns the decoded coefficient list in LSB to MSB order,
691 len(retval) == degree + 1"""
692 v = GFBREDPOLY & ((1 << XLEN) - 1) # mask to XLEN bits
693 if v == 0 or v == 2: # GF(2)
694 return [0, 1] # degree = 1, poly = x
695 if v & 1:
696 degree = floor_log2(v)
697 else:
698 # all reducing polynomials of degree > 1 must have the LSB set,
699 # because they must be irreducible polynomials (meaning they
700 # can't be factored), if the LSB was clear, then they would
701 # have `x` as a factor. Therefore, we can reuse the LSB clear
702 # to instead mean the polynomial has degree XLEN.
703 degree = XLEN
704 v |= 1 << XLEN
705 v |= 1 # LSB must be set
706 return [(v >> i) & 1 for i in range(1 + degree)]
707 ```
708
709 ## `gfbredpoly` -- Set the Reducing Polynomial SPR `GFBREDPOLY`
710
711 unless this is an immediate op, `mtspr` is completely sufficient.
712
713 ## `gfbmul` -- Binary Galois Field `GF(2^m)` Multiplication
714
715 ```
716 gfbmul RT, RA, RB
717 ```
718
719 ```
720 (RT) = gfbmul((RA), (RB))
721 ```
722
723 ## `gfbmadd` -- Binary Galois Field `GF(2^m)` Multiply-Add
724
725 ```
726 gfbmadd RT, RA, RB, RC
727 ```
728
729 ```
730 (RT) = gfbadd(gfbmul((RA), (RB)), (RC))
731 ```
732
733 ## `gfbtmadd` -- Binary Galois Field `GF(2^m)` Twin Multiply-Add (for FFT)
734
735 ```
736 gfbtmadd RT, RA, RB, RC
737 ```
738
739 TODO: add link to explanation for where `RS` comes from.
740
741 ```
742 temp = gfbadd(gfbmul((RA), (RB)), (RC))
743 (RT) = temp
744 (RS) = temp
745 ```
746
747 ## `gfbinv` -- Binary Galois Field `GF(2^m)` Inverse
748
749 ```
750 gfbinv RT, RA
751 ```
752
753 ```
754 (RT) = gfbinv((RA))
755 ```
756
757 # Instructions for Prime Galois Fields `GF(p)`
758
759 ## Helper algorithms
760
761 ```python
762 def int_to_gfp(int_value, prime):
763 return int_value % prime # follows Python remainder semantics
764 ```
765
766 ## `GFPRIME` SPR -- Prime Modulus For `gfp*` Instructions
767
768 ## `gfpadd` Prime Galois Field `GF(p)` Addition
769
770 ```
771 gfpadd RT, RA, RB
772 ```
773
774 ```
775 (RT) = int_to_gfp((RA) + (RB), GFPRIME)
776 ```
777
778 the addition happens on infinite-precision integers
779
780 ## `gfpsub` Prime Galois Field `GF(p)` Subtraction
781
782 ```
783 gfpsub RT, RA, RB
784 ```
785
786 ```
787 (RT) = int_to_gfp((RA) - (RB), GFPRIME)
788 ```
789
790 the subtraction happens on infinite-precision integers
791
792 ## `gfpmul` Prime Galois Field `GF(p)` Multiplication
793
794 ```
795 gfpmul RT, RA, RB
796 ```
797
798 ```
799 (RT) = int_to_gfp((RA) * (RB), GFPRIME)
800 ```
801
802 the multiplication happens on infinite-precision integers
803
804 ## `gfpinv` Prime Galois Field `GF(p)` Invert
805
806 ```
807 gfpinv RT, RA
808 ```
809
810 Some potential hardware implementations are found in:
811 <https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.5233&rep=rep1&type=pdf>
812
813 ```
814 (RT) = gfpinv((RA), GFPRIME)
815 ```
816
817 the multiplication happens on infinite-precision integers
818
819 ## `gfpmadd` Prime Galois Field `GF(p)` Multiply-Add
820
821 ```
822 gfpmadd RT, RA, RB, RC
823 ```
824
825 ```
826 (RT) = int_to_gfp((RA) * (RB) + (RC), GFPRIME)
827 ```
828
829 the multiplication and addition happens on infinite-precision integers
830
831 ## `gfpmsub` Prime Galois Field `GF(p)` Multiply-Subtract
832
833 ```
834 gfpmsub RT, RA, RB, RC
835 ```
836
837 ```
838 (RT) = int_to_gfp((RA) * (RB) - (RC), GFPRIME)
839 ```
840
841 the multiplication and subtraction happens on infinite-precision integers
842
843 ## `gfpmsubr` Prime Galois Field `GF(p)` Multiply-Subtract-Reversed
844
845 ```
846 gfpmsubr RT, RA, RB, RC
847 ```
848
849 ```
850 (RT) = int_to_gfp((RC) - (RA) * (RB), GFPRIME)
851 ```
852
853 the multiplication and subtraction happens on infinite-precision integers
854
855 ## `gfpmaddsubr` Prime Galois Field `GF(p)` Multiply-Add and Multiply-Sub-Reversed (for FFT)
856
857 ```
858 gfpmaddsubr RT, RA, RB, RC
859 ```
860
861 TODO: add link to explanation for where `RS` comes from.
862
863 ```
864 product = (RA) * (RB)
865 term = (RC)
866 (RT) = int_to_gfp(product + term, GFPRIME)
867 (RS) = int_to_gfp(term - product, GFPRIME)
868 ```
869
870 the multiplication, addition, and subtraction happens on infinite-precision integers
871
872 ## Twin Butterfly (Tukey-Cooley) Mul-add-sub
873
874 used in combination with SV FFT REMAP to perform
875 a full NTT in-place. possible by having 3-in 2-out,
876 to avoid the need for a temp register. RS is written
877 to as well as RT.
878
879 gffmadd RT,RA,RC,RB (Rc=0)
880 gffmadd. RT,RA,RC,RB (Rc=1)
881
882 Pseudo-code:
883
884 RT <- GFADD(GFMUL(RA, RC), RB))
885 RS <- GFADD(GFMUL(RA, RC), RB))
886
887
888 ## Multiply
889
890 with the modulo and degree being in an SPR, multiply can be identical
891 equivalent to standard integer add
892
893 RS = GFMUL(RA, RB)
894
895 | 0.5|6.10|11.15|16.20|21.25| 26..30 |31|
896 | -- | -- | --- | --- | --- | ------ |--|
897 | NN | RT | RA | RB |11000| 01110 |Rc|
898
899
900
901 ```
902 from functools import reduce
903
904 def gf_degree(a) :
905 res = 0
906 a >>= 1
907 while (a != 0) :
908 a >>= 1;
909 res += 1;
910 return res
911
912 # constants used in the multGF2 function
913 mask1 = mask2 = polyred = None
914
915 def setGF2(irPoly):
916 """Define parameters of binary finite field GF(2^m)/g(x)
917 - irPoly: coefficients of irreducible polynomial g(x)
918 """
919 # degree: extension degree of binary field
920 degree = gf_degree(irPoly)
921
922 def i2P(sInt):
923 """Convert an integer into a polynomial"""
924 return [(sInt >> i) & 1
925 for i in reversed(range(sInt.bit_length()))]
926
927 global mask1, mask2, polyred
928 mask1 = mask2 = 1 << degree
929 mask2 -= 1
930 polyred = reduce(lambda x, y: (x << 1) + y, i2P(irPoly)[1:])
931
932 def multGF2(p1, p2):
933 """Multiply two polynomials in GF(2^m)/g(x)"""
934 p = 0
935 while p2:
936 # standard long-multiplication: check LSB and add
937 if p2 & 1:
938 p ^= p1
939 p1 <<= 1
940 # standard modulo: check MSB and add polynomial
941 if p1 & mask1:
942 p1 ^= polyred
943 p2 >>= 1
944 return p & mask2
945
946 if __name__ == "__main__":
947
948 # Define binary field GF(2^3)/x^3 + x + 1
949 setGF2(0b1011) # degree 3
950
951 # Evaluate the product (x^2 + x + 1)(x^2 + 1)
952 print("{:02x}".format(multGF2(0b111, 0b101)))
953
954 # Define binary field GF(2^8)/x^8 + x^4 + x^3 + x + 1
955 # (used in the Advanced Encryption Standard-AES)
956 setGF2(0b100011011) # degree 8
957
958 # Evaluate the product (x^7)(x^7 + x + 1)
959 print("{:02x}".format(multGF2(0b10000000, 0b10000011)))
960 ```
961
962 ## GF(2^M) Inverse
963
964 ```
965 # https://bugs.libre-soc.org/show_bug.cgi?id=782#c33
966 # https://ftp.libre-soc.org/ARITH18_Kobayashi.pdf
967 def gf_invert(a) :
968
969 s = getGF2() # get the full polynomial (including the MSB)
970 r = a
971 v = 0
972 u = 1
973 j = 0
974
975 for i in range(1, 2*degree+1):
976 # could use count-trailing-1s here to skip ahead
977 if r & mask1: # test MSB of r
978 if s & mask1: # test MSB of s
979 s ^= r
980 v ^= u
981 s <<= 1 # shift left 1
982 if j == 0:
983 r, s = s, r # swap r,s
984 u, v = v<<1, u # shift v and swap
985 j = 1
986 else:
987 u >>= 1 # right shift left
988 j -= 1
989 else:
990 r <<= 1 # shift left 1
991 u <<= 1 # shift left 1
992 j += 1
993
994 return u
995 ```
996
997 # GF2 (Carryless)
998
999 ## GF2 (carryless) div and mod
1000
1001 ```
1002 def gf_degree(a) :
1003 res = 0
1004 a >>= 1
1005 while (a != 0) :
1006 a >>= 1;
1007 res += 1;
1008 return res
1009
1010 def FullDivision(self, f, v):
1011 """
1012 Takes two arguments, f, v
1013 fDegree and vDegree are the degrees of the field elements
1014 f and v represented as a polynomials.
1015 This method returns the field elements a and b such that
1016
1017 f(x) = a(x) * v(x) + b(x).
1018
1019 That is, a is the divisor and b is the remainder, or in
1020 other words a is like floor(f/v) and b is like f modulo v.
1021 """
1022
1023 fDegree, vDegree = gf_degree(f), gf_degree(v)
1024 res, rem = 0, f
1025 for i in reversed(range(vDegree, fDegree+1):
1026 if ((rem >> i) & 1): # check bit
1027 res ^= (1 << (i - vDegree))
1028 rem ^= ( v << (i - vDegree)))
1029 return (res, rem)
1030 ```
1031
1032 | 0.5|6.10|11.15|16.20| 21 | 22.23 | 24....30 |31| name |
1033 | -- | -- | --- | --- | -- | ----- | -------- |--| ---- |
1034 | NN | RT | RA | RB | 1 | 00 | 0001 110 |Rc| cldiv |
1035 | NN | RT | RA | RB | 1 | 01 | 0001 110 |Rc| clmod |
1036
1037 ## GF2 carryless mul
1038
1039 based on RV bitmanip
1040 see <https://en.wikipedia.org/wiki/CLMUL_instruction_set> and
1041 <https://www.felixcloutier.com/x86/pclmulqdq> and
1042 <https://en.m.wikipedia.org/wiki/Carry-less_product>
1043
1044 these are GF2 operations with the modulo set to 2^degree.
1045 they are worth adding as their own non-overwrite operations
1046 (in the same pipeline).
1047
1048 ```
1049 uint_xlen_t clmul(uint_xlen_t RA, uint_xlen_t RB)
1050 {
1051 uint_xlen_t x = 0;
1052 for (int i = 0; i < XLEN; i++)
1053 if ((RB >> i) & 1)
1054 x ^= RA << i;
1055 return x;
1056 }
1057 uint_xlen_t clmulh(uint_xlen_t RA, uint_xlen_t RB)
1058 {
1059 uint_xlen_t x = 0;
1060 for (int i = 1; i < XLEN; i++)
1061 if ((RB >> i) & 1)
1062 x ^= RA >> (XLEN-i);
1063 return x;
1064 }
1065 uint_xlen_t clmulr(uint_xlen_t RA, uint_xlen_t RB)
1066 {
1067 uint_xlen_t x = 0;
1068 for (int i = 0; i < XLEN; i++)
1069 if ((RB >> i) & 1)
1070 x ^= RA >> (XLEN-i-1);
1071 return x;
1072 }
1073 ```
1074 ## carryless Twin Butterfly (Tukey-Cooley) Mul-add-sub
1075
1076 used in combination with SV FFT REMAP to perform
1077 a full NTT in-place. possible by having 3-in 2-out,
1078 to avoid the need for a temp register. RS is written
1079 to as well as RT.
1080
1081 clfmadd RT,RA,RC,RB (Rc=0)
1082 clfmadd. RT,RA,RC,RB (Rc=1)
1083
1084 Pseudo-code:
1085
1086 RT <- CLMUL(RA, RC) ^ RB
1087 RS <- CLMUL(RA, RC) ^ RB
1088
1089
1090 # bitmatrix
1091
1092 ```
1093 uint64_t bmatflip(uint64_t RA)
1094 {
1095 uint64_t x = RA;
1096 x = shfl64(x, 31);
1097 x = shfl64(x, 31);
1098 x = shfl64(x, 31);
1099 return x;
1100 }
1101 uint64_t bmatxor(uint64_t RA, uint64_t RB)
1102 {
1103 // transpose of RB
1104 uint64_t RBt = bmatflip(RB);
1105 uint8_t u[8]; // rows of RA
1106 uint8_t v[8]; // cols of RB
1107 for (int i = 0; i < 8; i++) {
1108 u[i] = RA >> (i*8);
1109 v[i] = RBt >> (i*8);
1110 }
1111 uint64_t x = 0;
1112 for (int i = 0; i < 64; i++) {
1113 if (pcnt(u[i / 8] & v[i % 8]) & 1)
1114 x |= 1LL << i;
1115 }
1116 return x;
1117 }
1118 uint64_t bmator(uint64_t RA, uint64_t RB)
1119 {
1120 // transpose of RB
1121 uint64_t RBt = bmatflip(RB);
1122 uint8_t u[8]; // rows of RA
1123 uint8_t v[8]; // cols of RB
1124 for (int i = 0; i < 8; i++) {
1125 u[i] = RA >> (i*8);
1126 v[i] = RBt >> (i*8);
1127 }
1128 uint64_t x = 0;
1129 for (int i = 0; i < 64; i++) {
1130 if ((u[i / 8] & v[i % 8]) != 0)
1131 x |= 1LL << i;
1132 }
1133 return x;
1134 }
1135
1136 ```
1137
1138 # Already in POWER ISA
1139
1140 ## count leading/trailing zeros with mask
1141
1142 in v3.1 p105
1143
1144 ```
1145 count = 0
1146 do i = 0 to 63 if((RB)i=1) then do
1147 if((RS)i=1) then break end end count ← count + 1
1148 RA ← EXTZ64(count)
1149 ```
1150
1151 ## bit deposit
1152
1153 vpdepd VRT,VRA,VRB, identical to RV bitmamip bdep, found already in v3.1 p106
1154
1155 do while(m < 64)
1156 if VSR[VRB+32].dword[i].bit[63-m]=1 then do
1157 result = VSR[VRA+32].dword[i].bit[63-k]
1158 VSR[VRT+32].dword[i].bit[63-m] = result
1159 k = k + 1
1160 m = m + 1
1161
1162 ```
1163
1164 uint_xlen_t bdep(uint_xlen_t RA, uint_xlen_t RB)
1165 {
1166 uint_xlen_t r = 0;
1167 for (int i = 0, j = 0; i < XLEN; i++)
1168 if ((RB >> i) & 1) {
1169 if ((RA >> j) & 1)
1170 r |= uint_xlen_t(1) << i;
1171 j++;
1172 }
1173 return r;
1174 }
1175
1176 ```
1177
1178 # bit extract
1179
1180 other way round: identical to RV bext, found in v3.1 p196
1181
1182 ```
1183 uint_xlen_t bext(uint_xlen_t RA, uint_xlen_t RB)
1184 {
1185 uint_xlen_t r = 0;
1186 for (int i = 0, j = 0; i < XLEN; i++)
1187 if ((RB >> i) & 1) {
1188 if ((RA >> i) & 1)
1189 r |= uint_xlen_t(1) << j;
1190 j++;
1191 }
1192 return r;
1193 }
1194 ```
1195
1196 # centrifuge
1197
1198 found in v3.1 p106 so not to be added here
1199
1200 ```
1201 ptr0 = 0
1202 ptr1 = 0
1203 do i = 0 to 63
1204 if((RB)i=0) then do
1205 resultptr0 = (RS)i
1206 end
1207 ptr0 = ptr0 + 1
1208 if((RB)63-i==1) then do
1209 result63-ptr1 = (RS)63-i
1210 end
1211 ptr1 = ptr1 + 1
1212 RA = result
1213 ```
1214
1215 # bit to byte permute
1216
1217 similar to matrix permute in RV bitmanip, which has XOR and OR variants,
1218 these perform a transpose.
1219
1220 do j = 0 to 7
1221 do k = 0 to 7
1222 b = VSR[VRB+32].dword[i].byte[k].bit[j]
1223 VSR[VRT+32].dword[i].byte[j].bit[k] = b
1224