(no commit message)
[libreriscv.git] / openpower / sv / bitmanip.mdwn
index b165dd7ff8fa556bbaf0e92aa74da8365f6795cd..850a11e9515dc91abbcf009c3bc85969120a0a30 100644 (file)
@@ -1,18 +1,19 @@
 [[!tag standards]]
 
+[[!toc levels=1]]
+
 # Implementation Log
 
 * ternlogi <https://bugs.libre-soc.org/show_bug.cgi?id=745>
 * grev <https://bugs.libre-soc.org/show_bug.cgi?id=755>
-* remove Rc=1 from ternlog due to conflicts in encoding as well
-  as saving space <https://bugs.libre-soc.org/show_bug.cgi?id=753#c5>
 * GF2^M <https://bugs.libre-soc.org/show_bug.cgi?id=782>
 
+
 # bitmanipulation
 
 **DRAFT STATUS**
 
-pseudocode: <https://libre-soc.org/openpower/isa/bitmanip/>
+pseudocode: [[openpower/isa/bitmanip]]
 
 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.
 Vectorisation Context is provided by [[openpower/sv]].
@@ -39,17 +40,17 @@ ternlog has its own major opcode
 
 |  29.30 |31| name      |
 | ------ |--| --------- |
-|   00   |Rc| ternlogi  |
-|   01   |sz| ternlogv  |
-|   10   |0 | crternlog |
+|   0  0   |Rc| ternlogi  |
+|   0  1   |sz| ternlogv  |
+|   1 iv   |  | grevlogi |
 
 2nd major opcode for other bitmanip: minor opcode allocation
 
 |  28.30 |31| name      |
 | ------ |--| --------- |
-|  -00   |0 |           |
+|  -00   |0 | xpermi    |
 |  -00   |1 | grevlog   |
-|  -01   |  | grevlogi  |
+|  -01   |  | crternlog  |
 |  010   |Rc| bitmask   |
 |  011   |  | gf/cl madd*  |
 |  110   |Rc| 1/2-op    |
@@ -74,7 +75,7 @@ ternlog has its own major opcode
 | RT   | RA   | RB   | shuf  | shuffle | 
 | RT   | RA   | RB   | unshuf| shuffle | 
 | RT   | RA   | RB   | width | xperm  | 
-| RT   | RA   | RB   | type | minmax | 
+| RT   | RA   | RB   | type | av minmax | 
 | RT   | RA   | RB   |      | av abs avgadd  | 
 | RT   | RA   | RB   | type | vmask ops | 
 | RT   | RA   | RB   |      |       | 
@@ -87,38 +88,33 @@ ternlog has its own major opcode
 
 TODO: convert all instructions to use RT and not RS
 
+| 0.5|6.8 | 9.11|12.14|15.17|18.20|21.28 | 29.30|31|name|
+| -- | -- | --- | --- | --- |-----|----- | -----|--|----|
+| NN | BT | BA  | BB  | BC  |m0-2 | imm  |  10  |m3|crternlog|
+
 | 0.5|6.10|11.15|16.20 |21..25   | 26....30  |31| name |
 | -- | -- | --- | ---  | -----   | --------  |--| ------ |
 | NN | RT | RA  |itype/| im0-4   | im5-7  00 |0 | xpermi  |
 | NN | RT | RA  | RB   | im0-4   | im5-7  00 |1 | grevlog |
-| NN | RT | RA  | s0-4 | im0-4   | im5-7  01 |s5| grevlogi |
+| NN |    |     |      |         | .....  01 |0 | crternlog |
 | NN | RT | RA  | RB   | RC      | mode  010 |Rc| bitmask* |
-| NN | RS | RA  | RB   | RC      | 00    011 |0 | gfbmadd |
-| NN | RS | RA  | RB   | RC      | 00    011 |1 | gfbmaddsub |
-| NN | RS | RA  | RB   | RC      | 01    011 |0 | clmadd |
-| NN | RS | RA  | RB   | RC      | 01    011 |1 | clmaddsub |
-| NN | RS | RA  | RB   | RC      | 10    011 |0 | gfpmadd |
-| NN | RS | RA  | RB   | RC      | 10    011 |1 | gfpmaddsub |
-| NN | RS | RA  | RB   | RC      | 11    011 |  | rsvd |
+| NN |    |     |      |         | 00    011 |  | rsvd |
+| NN |    |     |      |         | 01    011 |  | rsvd |
+| NN |    |     |      |         | 10    011 |  | rsvd |
+| NN |    |     |      |         | 11    011 |Rc| setvl |
 | NN | RT | RA  | RB   | sh0-4   | sh5 1 111 |Rc| bmrevi |
 
 ops (note that av avg and abs as well as vec scalar mask
-are included here)
+are included here [[sv/vector_ops]], and
+the [[sv/av_opcodes]])
 
 TODO: convert from RA, RB, and RC to correct field names of RT, RA, and RB, and
 double check that instructions didn't need 3 inputs.
 
 | 0.5|6.10|11.15|16.20| 21 | 22.23 | 24....30 |31| name |
 | -- | -- | --- | --- | -- | ----- | -------- |--| ---- |
-| NN | RT | RA  | RB  | 0  |       | 0000 110 |Rc| rsvd   |
-| NN | RT | RA  | RB  | 1  | itype | 0000 110 |Rc| xperm |
-| NN | RA | RB  | RC  | 0  | itype | 0100 110 |Rc| minmax |
-| NN | RA | RB  | RC  | 1  |   00  | 0100 110 |Rc| av avgadd |
-| NN | RA | RB  | RC  | 1  |   01  | 0100 110 |Rc| av abs |
-| NN | RA | RB  |     | 1  |   10  | 0100 110 |Rc| rsvd |
-| NN | RA | RB  |     | 1  |   11  | 0100 110 |Rc| rsvd |
-| NN | RA | RB  | sh  | SH | itype | 1000 110 |Rc| bmopsi |
-| NN | RT | RA  | RB  |    |       | 1100 110 |Rc| srsvd |
+| NN | RS | me  | sh  | SH | ME 0  | nn00 110 |Rc| bmopsi |
+| NN | RS | RB  | sh  | SH | 0   1 | nn00 110 |Rc| bmopsi |
 | NN | RT | RA  | RB  | 1  |  00   | 0001 110 |Rc| cldiv |
 | NN | RT | RA  | RB  | 1  |  01   | 0001 110 |Rc| clmod |
 | NN | RT | RA  | RB  | 1  |  10   | 0001 110 |Rc|       |
@@ -127,7 +123,14 @@ double check that instructions didn't need 3 inputs.
 | NN | RA | RB  | RC  | 0  |   01  | 0001 110 |Rc| vec sofm |
 | NN | RA | RB  | RC  | 0  |   10  | 0001 110 |Rc| vec sifm |
 | NN | RA | RB  | RC  | 0  |   11  | 0001 110 |Rc| vec cprop |
-| NN | RA | RB  |     | 0  |       | 0101 110 |Rc| rsvd |
+| NN | RT | RA  | RB  | 0  |       | 0101 110 |Rc| rsvd |
+| NN | RT | RA  | RB  | 1  | itype | 0101 110 |Rc| xperm |
+| NN | RA | RB  | RC  | 0  | itype | 1001 110 |Rc| av minmax |
+| NN | RA | RB  | RC  | 1  |   00  | 1001 110 |Rc| av abss |
+| NN | RA | RB  | RC  | 1  |   01  | 1001 110 |Rc| av absu|
+| NN | RA | RB  |     | 1  |   10  | 1001 110 |Rc| av avgadd |
+| NN | RA | RB  |     | 1  |   11  | 1001 110 |Rc| rsvd |
+| NN | RA | RB  |     |    |       | 1101 110 |Rc| rsvd |
 | NN | RA | RB  | RC  | 0  | 00    | 0010 110 |Rc| gorc |
 | NN | RA | RB  | sh  | SH | 00    | 1010 110 |Rc| gorci |
 | NN | RA | RB  | RC  | 0  | 00    | 0110 110 |Rc| gorcw |
@@ -139,13 +142,10 @@ double check that instructions didn't need 3 inputs.
 | NN | RA | RB  | RC  | 0  | 01    | 0110 110 |Rc| grevw |
 | NN | RA | RB  | sh  | 0  | 01    | 1110 110 |Rc| grevwi |
 | NN | RA | RB  | RC  | 1  | 01    | 1110 110 |Rc| bmatxor   |
-| NN | RA | RB  | RC  | 0  | 10    | 0010 110 |Rc| shfl |
-| NN | RA | RB  | sh  | SH | 10    | 1010 110 |Rc| shfli |
-| NN | RA | RB  | RC  | 0  | 10    | 0110 110 |Rc| shflw |
-| NN | RA | RB  | RC  |    | 10    | 1110 110 |Rc| rsvd    |
+| NN | RA | RB  | RC  |    | 10    | --10 110 |Rc| rsvd  |
 | NN | RA | RB  | RC  | 0  | 11    | 1110 110 |Rc| clmulr  |
 | NN | RA | RB  | RC  | 1  | 11    | 1110 110 |Rc| clmulh  |
-| NN |    |     |     |    |       | --11 110 |Rc| setvl  |
+| NN |    |     |     |    |       | --11 110 |Rc| rsvd  |
 
 # ternlog bitops
 
@@ -155,7 +155,6 @@ Like the x86 AVX512F [vpternlogd/vpternlogq](https://www.felixcloutier.com/x86/v
 
 ## ternlogi
 
-
 | 0.5|6.10|11.15|16.20| 21..28|29.30|31|
 | -- | -- | --- | --- | ----- | --- |--|
 | NN | RT | RA  | RB  | im0-7 |  00 |Rc|
@@ -202,7 +201,7 @@ another mode selection would be CRs not Ints.
 
 | 0.5|6.8 | 9.11|12.14|15.17|18.20|21.28 | 29.30|31|
 | -- | -- | --- | --- | --- |-----|----- | -----|--|
-| NN | BT | BA  | BB  | BC  |m0-3 | imm  |  10  |m4|
+| NN | BT | BA  | BB  | BC  |m0-2 | imm  |  10  |m3|
 
     mask = m0-3,m4
     for i in range(4):
@@ -215,6 +214,9 @@ another mode selection would be CRs not Ints.
 
 # int min/max
 
+required for
+the [[sv/av_opcodes]]
+
 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).
 
 signed/unsigned min/max gives more flexibility.
@@ -270,6 +272,20 @@ Immediate-variant is an overwrite form:
 | NN | RS | RB  | sh  | SH | itype | 1000 110 |Rc| bm*i |
 
 ```
+def MASK(x, y):
+     if x < y:
+         x = x+1
+         mask_a = ((1 << x) - 1) & ((1 << 64) - 1)
+         mask_b = ((1 << y) - 1) & ((1 << 64) - 1)
+     elif x == y:
+         return 1 << x
+     else:
+         x = x+1
+         mask_a = ((1 << x) - 1) & ((1 << 64) - 1)
+         mask_b = (~((1 << y) - 1)) & ((1 << 64) - 1)
+     return mask_a ^ mask_b
+
+
 uint_xlen_t bmset(RS, RB, sh)
 {
     int shamt = RB & (XLEN - 1);
@@ -299,7 +315,7 @@ uint_xlen_t bmext(RS, RB, sh)
 }
 ```
 
-bitmask extract with reverse.  can be done by bitinverting all of RB and getting bits of RB from the opposite end.
+bitmask extract with reverse.  can be done by bit-order-inverting all of RB and getting bits of RB from the opposite end.
 
 when RA is zero, no shift occurs. this makes bmextrev useful for
 simply reversing all bits of a register.
@@ -312,7 +328,7 @@ rt = ZE(rev[msb:0]);
 uint_xlen_t bmextrev(RA, RB, sh)
 {
     int shamt = XLEN-1;
-    if (RA != 0) (GPR(RA) & (XLEN - 1));
+    if (RA != 0) shamt = (GPR(RA) & (XLEN - 1));
     shamt = (XLEN-1)-shamt;  # shift other end
     bra = bitreverse(RB)     # swap LSB-MSB
     mask = (2<<sh)-1;
@@ -328,19 +344,55 @@ uint_xlen_t bmextrev(RA, RB, sh)
 # grevlut
 
 generalised reverse combined with a pair of LUT2s and allowing
-zero when RA=0 provides a wide range of instructions
+a constant `0b0101...0101` when RA=0, and an option to invert
+(including when RA=0, giving a constant 0b1010...1010 as the
+initial value) provides a wide range of instructions
 and a means to set regular 64 bit patterns in one
 32 bit instruction.
 
 the two LUT2s are applied left-half (when not swapping)
 and right-half (when swapping) so as to allow a wider
-range of options
+range of options.
+
+<img src="/openpower/sv/grevlut2x2.jpg" width=700 />
+
+* A value of `0b11001010` for the immediate provides
+the functionality of a standard "grev".  
+* `0b11101110` provides gorc
 
 grevlut should be arranged so as to produce the constants
 needed to put into bext (bitextract) so as in turn to
-be able to emulate x86 pmovmask instructions <https://www.felixcloutier.com/x86/pmovmskb>
+be able to emulate x86 pmovmask instructions <https://www.felixcloutier.com/x86/pmovmskb>.
+This only requires 2 instructions (grevlut, bext).
 
-<img src="/openpower/sv/grevlut2x2.jpg" width=700 />
+Note that if the mask is required to be placed
+directly into CR Fields (for use as CR Predicate
+masks rather than a integer mask) then sv.ori
+may be used instead, bearing in mind that sv.ori
+is a 64-bit instruction, and `VL` must have been
+set to the required length:
+
+    sv.ori./elwid=8 r10.v, r10.v, 0
+
+The following settings provide the required mask constants:
+
+| RA       | RB      | imm        | iv | result        |
+| -------  | ------- | ---------- | -- | ----------    |
+| 0x555..  | 0b10    | 0b01101100 | 0  | 0x111111...   |
+| 0x555..  | 0b110   | 0b01101100 | 0  | 0x010101...   |
+| 0x555..  | 0b1110  | 0b01101100 | 0  | 0x00010001...   |
+| 0x555..  | 0b10    | 0b11000110 | 1  | 0x88888...   |
+| 0x555..  | 0b110   | 0b11000110 | 1  | 0x808080...   |
+| 0x555..  | 0b1110  | 0b11000110 | 1  | 0x80008000...   |
+
+Better diagram showing the correct ordering of shamt (RB).  A LUT2
+is applied to all locations marked in red using the first 4
+bits of the immediate, and a separate LUT2 applied to all
+locations in green using the upper 4 bits of the immediate.
+
+<img src="/openpower/sv/grevlut.png" width=700 />
+
+demo code [[openpower/sv/grevlut.py]]
 
 ```
 lut2(imm, a, b):
@@ -356,9 +408,11 @@ dorow(imm8, step_i, chunksize):
         step_o[j] = lut2(imm, step_i[j], step_i[j ^ chunk_size])
     return step_o
 
-uint64_t grevlut64(uint64_t RA, uint64_t RB, uint8 imm)
+uint64_t grevlut64(uint64_t RA, uint64_t RB, uint8 imm, bool iv)
 {
-    uint64_t x = RA;
+    uint64_t x = 0x5555_5555_5555_5555;
+    if (RA != 0) x = GPR(RA);
+    if (iv) x = ~x;
     int shamt = RB & 63;
     for i in 0 to 6
         step = 1<<i
@@ -368,6 +422,12 @@ uint64_t grevlut64(uint64_t RA, uint64_t RB, uint8 imm)
 
 ```
 
+| 0.5|6.10|11.15|16.20 |21..25   | 26....30    |31| name |
+| -- | -- | --- | ---  | -----   | --------    |--| ------ |
+| NN | RT | RA  | s0-4 | im0-4   | im5-7  1 iv |s5| grevlogi |
+| NN | RT | RA  | RB   | im0-4   | im5-7  00   |1 | grevlog |
+
+
 # grev
 
 based on RV bitmanip, this is also known as a butterfly network. however
@@ -400,72 +460,6 @@ uint64_t grev64(uint64_t RA, uint64_t RB)
 
 ```
 
-# shuffle / unshuffle
-
-based on RV bitmanip
-
-```
-uint32_t shfl32(uint32_t RA, uint32_t RB)
-{
-    uint32_t x = RA;
-    int shamt = RB & 15;
-    if (shamt & 8) x  = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8);
-    if (shamt & 4) x  = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4);
-    if (shamt & 2) x  = shuffle32_stage(x, 0x30303030, 0x0c0c0c0c, 2);
-    if (shamt & 1) x  = shuffle32_stage(x, 0x44444444, 0x22222222, 1);
-    return x;
-}
-uint32_t unshfl32(uint32_t RA, uint32_t RB)
-{
-    uint32_t x = RA;
-    int shamt = RB & 15;
-    if (shamt & 1) x  = shuffle32_stage(x, 0x44444444, 0x22222222, 1);
-    if (shamt & 2) x  = shuffle32_stage(x, 0x30303030, 0x0c0c0c0c, 2);
-    if (shamt & 4) x  = shuffle32_stage(x, 0x0f000f00, 0x00f000f0, 4);
-    if (shamt & 8) x  = shuffle32_stage(x, 0x00ff0000, 0x0000ff00, 8);
-    return x;
-}
-
-uint64_t shuffle64_stage(uint64_t src, uint64_t maskL, uint64_t maskR, int N)
-{
-    uint64_t x = src & ~(maskL | maskR);
-    x |= ((src << N) & maskL) | ((src >> N) & maskR);
-    return x;
-}
-uint64_t shfl64(uint64_t RA, uint64_t RB)
-{
-    uint64_t x = RA;
-    int shamt = RB & 31;
-    if (shamt & 16) x = shuffle64_stage(x, 0x0000ffff00000000LL,
-                                           0x00000000ffff0000LL, 16);
-    if (shamt & 8) x = shuffle64_stage(x, 0x00ff000000ff0000LL,
-                                           0x0000ff000000ff00LL, 8);
-    if (shamt & 4) x = shuffle64_stage(x, 0x0f000f000f000f00LL,
-                                           0x00f000f000f000f0LL, 4);
-    if (shamt & 2) x = shuffle64_stage(x, 0x3030303030303030LL,
-                                           0x0c0c0c0c0c0c0c0cLL, 2);
-    if (shamt & 1) x = shuffle64_stage(x, 0x4444444444444444LL,
-                                           0x2222222222222222LL, 1);
-    return x;
-}
-uint64_t unshfl64(uint64_t RA, uint64_t RB)
-{
-    uint64_t x = RA;
-    int shamt = RB & 31;
-    if (shamt &  1) x = shuffle64_stage(x, 0x4444444444444444LL,
-                                           0x2222222222222222LL, 1);
-    if (shamt &  2) x = shuffle64_stage(x, 0x3030303030303030LL,
-                                           0x0c0c0c0c0c0c0c0cLL, 2);
-    if (shamt &  4) x = shuffle64_stage(x, 0x0f000f000f000f00LL,
-                                           0x00f000f000f000f0LL, 4);
-    if (shamt &  8) x = shuffle64_stage(x, 0x00ff000000ff0000LL,
-                                           0x0000ff000000ff00LL, 8);
-    if (shamt & 16) x = shuffle64_stage(x, 0x0000ffff00000000LL,
-                                           0x00000000ffff0000LL, 16);
-    return x;
-}
-```
-
 # xperm
 
 based on RV bitmanip.
@@ -546,8 +540,63 @@ uint64_t gorc64(uint64_t RA, uint64_t RB)
 }
 
 ```
-
-# Instructions for Carry-less Operations aka. Polynomials with coefficients in `GF(2)`
+# Introduction to Carry-less and GF arithmetic
+
+* obligatory xkcd <https://xkcd.com/2595/>
+
+There are three completely separate types of Galois-Field-based
+arithmetic that we implement which are not well explained even in introductory literature.  A slightly oversimplified explanation
+is followed by more accurate descriptions:
+
+* `GF(2)` carry-less binary arithmetic. this is not actually a Galois Field,
+  but is accidentally referred to as GF(2) - see below as to why.
+* `GF(p)` modulo arithmetic with a Prime number, these are "proper" Galois Fields
+* `GF(2^N)` carry-less binary arithmetic with two limits: modulo a power-of-2
+  (2^N) and a second "reducing" polynomial (similar to a prime number), these
+  are said to be GF(2^N) arithmetic.
+
+further detailed and more precise explanations are provided below
+
+* **Polynomials with coefficients in `GF(2)`**
+  (aka. Carry-less arithmetic -- the `cl*` instructions).
+  This isn't actually a Galois Field, but its coefficients are. This is
+  basically binary integer addition, subtraction, and multiplication like
+  usual, except that carries aren't propagated at all, effectively turning
+  both addition and subtraction into the bitwise xor operation. Division and
+  remainder are defined to match how addition and multiplication works.
+* **Galois Fields with a prime size**
+  (aka. `GF(p)` or Prime Galois Fields -- the `gfp*` instructions).
+  This is basically just the integers mod `p`.
+* **Galois Fields with a power-of-a-prime size**
+  (aka. `GF(p^n)` or `GF(q)` where `q == p^n` for prime `p` and
+  integer `n > 0`).
+  We only implement these for `p == 2`, called Binary Galois Fields
+  (`GF(2^n)` -- the `gfb*` instructions).
+  For any prime `p`, `GF(p^n)` is implemented as polynomials with
+  coefficients in `GF(p)` and degree `< n`, where the polynomials are the
+  remainders of dividing by a specificly chosen polynomial in `GF(p)` called
+  the Reducing Polynomial (we will denote that by `red_poly`). The Reducing
+  Polynomial must be an irreducable polynomial (like primes, but for
+  polynomials), as well as have degree `n`. All `GF(p^n)` for the same `p`
+  and `n` are isomorphic to each other -- the choice of `red_poly` doesn't
+  affect `GF(p^n)`'s mathematical shape, all that changes is the specific
+  polynomials used to implement `GF(p^n)`.
+
+Many implementations and much of the literature do not make a clear
+distinction between these three categories, which makes it confusing
+to understand what their purpose and value is.
+
+* carry-less multiply is extremely common and is used for the ubiquitous
+  CRC32 algorithm. [TODO add many others, helps justify to ISA WG]
+* GF(2^N) forms the basis of Rijndael (the current AES standard) and
+  has significant uses throughout cryptography
+* GF(p) is the basis again of a significant quantity of algorithms
+  (TODO, list them, jacob knows what they are), even though the
+  modulo is limited to be below 64-bit (size of a scalar int)
+
+# Instructions for Carry-less Operations
+
+aka. Polynomials with coefficients in `GF(2)`
 
 Carry-less addition/subtraction is simply XOR, so a `cladd`
 instruction is not provided since the `xor[i]` instruction can be used instead.
@@ -556,21 +605,7 @@ These are operations on polynomials with coefficients in `GF(2)`, with the
 polynomial's coefficients packed into integers with the following algorithm:
 
 ```python
-def pack_poly(poly):
-    """`poly` is a list where `poly[i]` is the coefficient for `x ** i`"""
-    retval = 0
-    for i, v in enumerate(poly):
-        retval |= v << i
-    return retval
-
-def unpack_poly(v):
-    """returns a list `poly`, where `poly[i]` is the coefficient for `x ** i`.
-    """
-    poly = []
-    while v != 0:
-        poly.append(v & 1)
-        v >>= 1
-    return poly
+[[!inline pagenames="gf_reference/pack_poly.py" raw="yes"]]
 ```
 
 ## Carry-less Multiply Instructions
@@ -585,28 +620,14 @@ They are worth adding as their own non-overwrite operations
 
 ### `clmul` Carry-less Multiply
 
-```c
-uint_xlen_t clmul(uint_xlen_t RA, uint_xlen_t RB)
-{
-    uint_xlen_t x = 0;
-    for (int i = 0; i < XLEN; i++)
-        if ((RB >> i) & 1)
-            x ^= RA << i;
-    return x;
-}
+```python
+[[!inline pagenames="gf_reference/clmul.py" raw="yes"]]
 ```
 
 ### `clmulh` Carry-less Multiply High
 
-```c
-uint_xlen_t clmulh(uint_xlen_t RA, uint_xlen_t RB)
-{
-    uint_xlen_t x = 0;
-    for (int i = 1; i < XLEN; i++)
-        if ((RB >> i) & 1)
-            x ^= RA >> (XLEN-i);
-    return x;
-}
+```python
+[[!inline pagenames="gf_reference/clmulh.py" raw="yes"]]
 ```
 
 ### `clmulr` Carry-less Multiply (Reversed)
@@ -614,15 +635,8 @@ uint_xlen_t clmulh(uint_xlen_t RA, uint_xlen_t RB)
 Useful for CRCs. Equivalent to bit-reversing the result of `clmul` on
 bit-reversed inputs.
 
-```c
-uint_xlen_t clmulr(uint_xlen_t RA, uint_xlen_t RB)
-{
-    uint_xlen_t x = 0;
-    for (int i = 0; i < XLEN; i++)
-        if ((RB >> i) & 1)
-            x ^= RA >> (XLEN-i-1);
-    return x;
-}
+```python
+[[!inline pagenames="gf_reference/clmulr.py" raw="yes"]]
 ```
 
 ## `clmadd` Carry-less Multiply-Add
@@ -637,6 +651,17 @@ clmadd RT, RA, RB, RC
 
 ## `cltmadd` Twin Carry-less Multiply-Add (for FFTs)
 
+Used in combination with SV FFT REMAP to perform a full Discrete Fourier
+Transform of Polynomials over GF(2) in-place. Possible by having 3-in 2-out,
+to avoid the need for a temp register. RS is written to as well as RT.
+
+Note: Polynomials over GF(2) are a Ring rather than a Field, so, because the
+definition of the Inverse Discrete Fourier Transform involves calculating a
+multiplicative inverse, which may not exist in every Ring, therefore the
+Inverse Discrete Fourier Transform may not exist. (AFAICT the number of inputs
+to the IDFT must be odd for the IDFT to be defined for Polynomials over GF(2).
+TODO: check with someone who knows for sure if that's correct.)
+
 ```
 cltmadd RT, RA, RB, RC
 ```
@@ -644,9 +669,21 @@ cltmadd RT, RA, RB, RC
 TODO: add link to explanation for where `RS` comes from.
 
 ```
-temp = clmul((RA), (RB)) ^ (RC)
-(RT) = temp
-(RS) = temp
+a = (RA)
+c = (RC)
+# read all inputs before writing to any outputs in case
+# an input overlaps with an output register.
+(RT) = clmul(a, (RB)) ^ c
+(RS) = a ^ c
+```
+
+## `cldivrem` Carry-less Division and Remainder
+
+`cldivrem` isn't an actual instruction, but is just used in the pseudo-code
+for other instructions.
+
+```python
+[[!inline pagenames="gf_reference/cldivrem.py" raw="yes"]]
 ```
 
 ## `cldiv` Carry-less Division
@@ -655,10 +692,11 @@ temp = clmul((RA), (RB)) ^ (RC)
 cldiv RT, RA, RB
 ```
 
-TODO: decide what happens on division by zero
-
 ```
-(RT) = cldiv((RA), (RB))
+n = (RA)
+d = (RB)
+q, r = cldivrem(n, d, width=XLEN)
+(RT) = q
 ```
 
 ## `clrem` Carry-less Remainder
@@ -667,10 +705,11 @@ TODO: decide what happens on division by zero
 clrem RT, RA, RB
 ```
 
-TODO: decide what happens on division by zero
-
 ```
-(RT) = clrem((RA), (RB))
+n = (RA)
+d = (RB)
+q, r = cldivrem(n, d, width=XLEN)
+(RT) = r
 ```
 
 # Instructions for Binary Galois Fields `GF(2^m)`
@@ -701,38 +740,25 @@ making it reducible, making whatever we're working on no longer a Field.
 Therefore, we can reuse the LSB to indicate `degree == XLEN`.
 
 ```python
-def decode_reducing_polynomial(GFBREDPOLY, XLEN):
-    """returns the decoded coefficient list in LSB to MSB order,
-        len(retval) == degree + 1"""
-    v = GFBREDPOLY & ((1 << XLEN) - 1) # mask to XLEN bits
-    if v == 0 or v == 2: # GF(2)
-        return [0, 1] # degree = 1, poly = x
-    if v & 1:
-        degree = floor_log2(v)
-    else:
-        # all reducing polynomials of degree > 1 must have the LSB set,
-        # because they must be irreducible polynomials (meaning they
-        # can't be factored), if the LSB was clear, then they would
-        # have `x` as a factor. Therefore, we can reuse the LSB clear
-        # to instead mean the polynomial has degree XLEN.
-        degree = XLEN
-        v |= 1 << XLEN
-        v |= 1 # LSB must be set
-    return [(v >> i) & 1 for i in range(1 + degree)]
+[[!inline pagenames="gf_reference/decode_reducing_polynomial.py" raw="yes"]]
 ```
 
 ## `gfbredpoly` -- Set the Reducing Polynomial SPR `GFBREDPOLY`
 
 unless this is an immediate op, `mtspr` is completely sufficient.
 
+```python
+[[!inline pagenames="gf_reference/gfbredpoly.py" raw="yes"]]
+```
+
 ## `gfbmul` -- Binary Galois Field `GF(2^m)` Multiplication
 
 ```
 gfbmul RT, RA, RB
 ```
 
-```
-(RT) = gfbmul((RA), (RB))
+```python
+[[!inline pagenames="gf_reference/gfbmul.py" raw="yes"]]
 ```
 
 ## `gfbmadd` -- Binary Galois Field `GF(2^m)` Multiply-Add
@@ -741,12 +767,16 @@ gfbmul RT, RA, RB
 gfbmadd RT, RA, RB, RC
 ```
 
-```
-(RT) = gfbadd(gfbmul((RA), (RB)), (RC))
+```python
+[[!inline pagenames="gf_reference/gfbmadd.py" raw="yes"]]
 ```
 
 ## `gfbtmadd` -- Binary Galois Field `GF(2^m)` Twin Multiply-Add (for FFT)
 
+Used in combination with SV FFT REMAP to perform a full `GF(2^m)` Discrete
+Fourier Transform in-place. Possible by having 3-in 2-out, to avoid the need
+for a temp register. RS is written to as well as RT.
+
 ```
 gfbtmadd RT, RA, RB, RC
 ```
@@ -754,9 +784,13 @@ gfbtmadd RT, RA, RB, RC
 TODO: add link to explanation for where `RS` comes from.
 
 ```
-temp = gfbadd(gfbmul((RA), (RB)), (RC))
-(RT) = temp
-(RS) = temp
+a = (RA)
+c = (RC)
+# read all inputs before writing to any outputs in case
+# an input overlaps with an output register.
+(RT) = gfbmadd(a, (RB), c)
+# use gfbmadd again since it reduces the result
+(RS) = gfbmadd(a, 1, c) # "a * 1 + c"
 ```
 
 ## `gfbinv` -- Binary Galois Field `GF(2^m)` Inverse
@@ -765,19 +799,12 @@ temp = gfbadd(gfbmul((RA), (RB)), (RC))
 gfbinv RT, RA
 ```
 
-```
-(RT) = gfbinv((RA))
+```python
+[[!inline pagenames="gf_reference/gfbinv.py" raw="yes"]]
 ```
 
 # Instructions for Prime Galois Fields `GF(p)`
 
-## Helper algorithms
-
-```python
-def int_to_gfp(int_value, prime):
-    return int_value % prime # follows Python remainder semantics
-```
-
 ## `GFPRIME` SPR -- Prime Modulus For `gfp*` Instructions
 
 ## `gfpadd` Prime Galois Field `GF(p)` Addition
@@ -786,8 +813,8 @@ def int_to_gfp(int_value, prime):
 gfpadd RT, RA, RB
 ```
 
-```
-(RT) = int_to_gfp((RA) + (RB), GFPRIME)
+```python
+[[!inline pagenames="gf_reference/gfpadd.py" raw="yes"]]
 ```
 
 the addition happens on infinite-precision integers
@@ -798,8 +825,8 @@ the addition happens on infinite-precision integers
 gfpsub RT, RA, RB
 ```
 
-```
-(RT) = int_to_gfp((RA) - (RB), GFPRIME)
+```python
+[[!inline pagenames="gf_reference/gfpsub.py" raw="yes"]]
 ```
 
 the subtraction happens on infinite-precision integers
@@ -810,8 +837,8 @@ the subtraction happens on infinite-precision integers
 gfpmul RT, RA, RB
 ```
 
-```
-(RT) = int_to_gfp((RA) * (RB), GFPRIME)
+```python
+[[!inline pagenames="gf_reference/gfpmul.py" raw="yes"]]
 ```
 
 the multiplication happens on infinite-precision integers
@@ -825,11 +852,9 @@ gfpinv RT, RA
 Some potential hardware implementations are found in:
 <https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.5233&rep=rep1&type=pdf>
 
+```python
+[[!inline pagenames="gf_reference/gfpinv.py" raw="yes"]]
 ```
-(RT) = gfpinv((RA), GFPRIME)
-```
-
-the multiplication happens on infinite-precision integers
 
 ## `gfpmadd` Prime Galois Field `GF(p)` Multiply-Add
 
@@ -837,8 +862,8 @@ the multiplication happens on infinite-precision integers
 gfpmadd RT, RA, RB, RC
 ```
 
-```
-(RT) = int_to_gfp((RA) * (RB) + (RC), GFPRIME)
+```python
+[[!inline pagenames="gf_reference/gfpmadd.py" raw="yes"]]
 ```
 
 the multiplication and addition happens on infinite-precision integers
@@ -849,8 +874,8 @@ the multiplication and addition happens on infinite-precision integers
 gfpmsub RT, RA, RB, RC
 ```
 
-```
-(RT) = int_to_gfp((RA) * (RB) - (RC), GFPRIME)
+```python
+[[!inline pagenames="gf_reference/gfpmsub.py" raw="yes"]]
 ```
 
 the multiplication and subtraction happens on infinite-precision integers
@@ -861,14 +886,19 @@ the multiplication and subtraction happens on infinite-precision integers
 gfpmsubr RT, RA, RB, RC
 ```
 
-```
-(RT) = int_to_gfp((RC) - (RA) * (RB), GFPRIME)
+```python
+[[!inline pagenames="gf_reference/gfpmsubr.py" raw="yes"]]
 ```
 
 the multiplication and subtraction happens on infinite-precision integers
 
 ## `gfpmaddsubr` Prime Galois Field `GF(p)` Multiply-Add and Multiply-Sub-Reversed (for FFT)
 
+Used in combination with SV FFT REMAP to perform
+a full Number-Theoretic-Transform in-place. Possible by having 3-in 2-out,
+to avoid the need for a temp register. RS is written
+to as well as RT.
+
 ```
 gfpmaddsubr RT, RA, RB, RC
 ```
@@ -876,232 +906,15 @@ gfpmaddsubr RT, RA, RB, RC
 TODO: add link to explanation for where `RS` comes from.
 
 ```
-product = (RA) * (RB)
+factor1 = (RA)
+factor2 = (RB)
 term = (RC)
-(RT) = int_to_gfp(product + term, GFPRIME)
-(RS) = int_to_gfp(term - product, GFPRIME)
-```
-
-the multiplication, addition, and subtraction happens on infinite-precision integers
-
-## Twin Butterfly (Tukey-Cooley) Mul-add-sub
-
-used in combination with SV FFT REMAP to perform
-a full NTT in-place. possible by having 3-in 2-out,
-to avoid the need for a temp register.  RS is written
-to as well as RT.
-
-    gffmadd  RT,RA,RC,RB (Rc=0)
-    gffmadd. RT,RA,RC,RB (Rc=1)
-
-Pseudo-code:
-
-    RT <- GFADD(GFMUL(RA, RC), RB))
-    RS <- GFADD(GFMUL(RA, RC), RB))
-
-
-## Multiply
-
-with the modulo and degree being in an SPR, multiply can be identical
-equivalent to standard integer add
-
-    RS = GFMUL(RA, RB)
-
-| 0.5|6.10|11.15|16.20|21.25| 26..30 |31|
-| -- | -- | --- | --- | --- | ------ |--|
-| NN | RT | RA  | RB  |11000|  01110 |Rc|
-
-
-
-```
-from functools import reduce
-
-def gf_degree(a) :
-  res = 0
-  a >>= 1
-  while (a != 0) :
-    a >>= 1;
-    res += 1;
-  return res
-
-# constants used in the multGF2 function
-mask1 = mask2 = polyred = None
-
-def setGF2(irPoly):
-    """Define parameters of binary finite field GF(2^m)/g(x)
-       - irPoly: coefficients of irreducible polynomial g(x)
-    """
-    # degree: extension degree of binary field
-    degree = gf_degree(irPoly)
-
-    def i2P(sInt):
-        """Convert an integer into a polynomial"""
-        return [(sInt >> i) & 1
-                for i in reversed(range(sInt.bit_length()))]    
-    
-    global mask1, mask2, polyred
-    mask1 = mask2 = 1 << degree
-    mask2 -= 1
-    polyred = reduce(lambda x, y: (x << 1) + y, i2P(irPoly)[1:])
-        
-def multGF2(p1, p2):
-    """Multiply two polynomials in GF(2^m)/g(x)"""
-    p = 0
-    while p2:
-        # standard long-multiplication: check LSB and add
-        if p2 & 1:
-            p ^= p1
-        p1 <<= 1
-        # standard modulo: check MSB and add polynomial
-        if p1 & mask1:
-            p1 ^= polyred
-        p2 >>= 1
-    return p & mask2
-
-if __name__ == "__main__":
-  
-    # Define binary field GF(2^3)/x^3 + x + 1
-    setGF2(0b1011) # degree 3
-
-    # Evaluate the product (x^2 + x + 1)(x^2 + 1)
-    print("{:02x}".format(multGF2(0b111, 0b101)))
-    
-    # Define binary field GF(2^8)/x^8 + x^4 + x^3 + x + 1
-    # (used in the Advanced Encryption Standard-AES)
-    setGF2(0b100011011) # degree 8
-    
-    # Evaluate the product (x^7)(x^7 + x + 1)
-    print("{:02x}".format(multGF2(0b10000000, 0b10000011)))
-```
-
-## GF(2^M) Inverse
-
-```
-# https://bugs.libre-soc.org/show_bug.cgi?id=782#c33
-# https://ftp.libre-soc.org/ARITH18_Kobayashi.pdf
-def gf_invert(a) :
-
-    s = getGF2() # get the full polynomial (including the MSB)
-    r = a
-    v = 0
-    u = 1
-    j = 0
-
-    for i in range(1, 2*degree+1):
-        # could use count-trailing-1s here to skip ahead
-        if r & mask1:          # test MSB of r
-            if s & mask1:      # test MSB of s
-                s ^= r
-                v ^= u
-            s <<= 1            # shift left 1
-            if j == 0:
-                r, s = s, r    # swap r,s
-                u, v = v<<1, u # shift v and swap
-                j = 1
-            else:
-                u >>= 1        # right shift left
-                j -= 1
-        else:
-            r <<= 1            # shift left 1
-            u <<= 1            # shift left 1
-            j += 1
-
-    return u
-```
-
-# GF2 (Carryless)
-
-## GF2 (carryless) div and mod
-
-```
-def gf_degree(a) :
-  res = 0
-  a >>= 1
-  while (a != 0) :
-    a >>= 1;
-    res += 1;
-  return res
-
-def FullDivision(self, f, v):
-        """
-        Takes two arguments, f, v
-        fDegree and vDegree are the degrees of the field elements
-        f and v represented as a polynomials.
-        This method returns the field elements a and b such that
-
-            f(x) = a(x) * v(x) + b(x).  
-
-        That is, a is the divisor and b is the remainder, or in
-        other words a is like floor(f/v) and b is like f modulo v.
-        """
-
-        fDegree, vDegree = gf_degree(f), gf_degree(v)
-        res, rem = 0, f
-        for i in reversed(range(vDegree, fDegree+1):
-            if ((rem >> i) & 1): # check bit
-                res ^= (1 << (i - vDegree))
-                rem ^= ( v << (i - vDegree)))
-        return (res, rem)
+# read all inputs before writing to any outputs in case
+# an input overlaps with an output register.
+(RT) = gfpmadd(factor1, factor2, term)
+(RS) = gfpmsubr(factor1, factor2, term)
 ```
 
-| 0.5|6.10|11.15|16.20| 21 | 22.23 | 24....30 |31| name |
-| -- | -- | --- | --- | -- | ----- | -------- |--| ---- |
-| NN | RT | RA  | RB  | 1  |  00   | 0001 110 |Rc| cldiv |
-| NN | RT | RA  | RB  | 1  |  01   | 0001 110 |Rc| clmod |
-
-## GF2 carryless mul
-
-based on RV bitmanip
-see <https://en.wikipedia.org/wiki/CLMUL_instruction_set> and
-<https://www.felixcloutier.com/x86/pclmulqdq> and
-<https://en.m.wikipedia.org/wiki/Carry-less_product>
-
-these are GF2 operations with the modulo set to 2^degree.
-they are worth adding as their own non-overwrite operations
-(in the same pipeline).
-
-```
-uint_xlen_t clmul(uint_xlen_t RA, uint_xlen_t RB)
-{
-    uint_xlen_t x = 0;
-    for (int i = 0; i < XLEN; i++)
-        if ((RB >> i) & 1)
-            x ^= RA << i;
-    return x;
-}
-uint_xlen_t clmulh(uint_xlen_t RA, uint_xlen_t RB)
-{
-    uint_xlen_t x = 0;
-    for (int i = 1; i < XLEN; i++)
-        if ((RB >> i) & 1)
-            x ^= RA >> (XLEN-i);
-    return x;
-}
-uint_xlen_t clmulr(uint_xlen_t RA, uint_xlen_t RB)
-{
-    uint_xlen_t x = 0;
-    for (int i = 0; i < XLEN; i++)
-        if ((RB >> i) & 1)
-            x ^= RA >> (XLEN-i-1);
-    return x;
-}
-```
-## carryless Twin Butterfly (Tukey-Cooley) Mul-add-sub
-
-used in combination with SV FFT REMAP to perform
-a full NTT in-place. possible by having 3-in 2-out,
-to avoid the need for a temp register.  RS is written
-to as well as RT.
-
-    clfmadd  RT,RA,RC,RB (Rc=0)
-    clfmadd. RT,RA,RC,RB (Rc=1)
-
-Pseudo-code:
-
-    RT <- CLMUL(RA, RC) ^ RB
-    RS <- CLMUL(RA, RC) ^ RB
-
-
 # bitmatrix
 
 ```
@@ -1163,9 +976,9 @@ if((RS)i=1) then break end end count ← count + 1
 RA ← EXTZ64(count)
 ```
 
-##  bit deposit
+## bit deposit
 
-vpdepd VRT,VRA,VRB, identical to RV bitmamip bdep, found already in v3.1 p106
+pdepd VRT,VRA,VRB, identical to RV bitmamip bdep, found already in v3.1 p106
 
     do while(m < 64)
        if VSR[VRB+32].dword[i].bit[63-m]=1 then do
@@ -1190,9 +1003,9 @@ uint_xlen_t bdep(uint_xlen_t RA, uint_xlen_t RB)
 
 ```
 
-# bit extract
+## bit extract
 
-other way round: identical to RV bext, found in v3.1 p196
+other way round: identical to RV bext: pextd, found in v3.1 p196
 
 ```
 uint_xlen_t bext(uint_xlen_t RA, uint_xlen_t RB)
@@ -1208,7 +1021,7 @@ uint_xlen_t bext(uint_xlen_t RA, uint_xlen_t RB)
 }
 ```
 
-# centrifuge
+## centrifuge
 
 found in v3.1 p106 so not to be added here
 
@@ -1227,13 +1040,18 @@ do i = 0 to 63
 RA = result
 ```
 
-# bit to byte permute
+## bit to byte permute
 
 similar to matrix permute in RV bitmanip, which has XOR and OR variants,
-these perform a transpose.
+these perform a transpose. TODO this looks VSX is there a scalar variant
+in v3.0/1 already
 
     do j = 0 to 7
       do k = 0 to 7
          b = VSR[VRB+32].dword[i].byte[k].bit[j]
          VSR[VRT+32].dword[i].byte[j].bit[k] = b
 
+# Appendix
+
+see [[bitmanip/appendix]]
+