whitespace
[libreriscv.git] / openpower / sv / rfc / ls010.mdwn
1 # RFC ls010 SVP64 Zero-Overhead Loop Prefix Subsystem
2
3 Credits and acknowledgements:
4
5 * Luke Leighton
6 * Jacob Lifshay
7 * Hendrik Boom
8 * Richard Wilbur
9 * Alexandre Oliva
10 * Cesar Strauss
11 * NLnet Foundation, for funding
12 * OpenPOWER Foundation
13 * Paul Mackerras
14 * Toshaan Bharvani
15 * IBM for the Power ISA itself
16
17 Links:
18
19 * <https://bugs.libre-soc.org/show_bug.cgi?id=1045>
20
21 # Introduction
22
23 Simple-V is a type of Vectorisation best described as a "Prefix Loop
24 Subsystem" similar to the 5 decades-old Zilog Z80 `LDIR` instruction and
25 to the 8086 `REP` Prefix instruction. More advanced features are similar
26 to the Z80 `CPIR` instruction. If viewed one-dimensionally as an actual
27 Vector ISA it introduces over 1.5 million 64-bit Vector instructions.
28 SVP64, the instruction format used by Simple-V, is therefore best viewed
29 as an orthogonal RISC-paradigm "Prefixing" subsystem instead.
30
31 Except where explicitly stated all bit numbers remain as in the rest of
32 the Power ISA: in MSB0 form (the bits are numbered from 0 at the MSB on
33 the left and counting up as you move rightwards to the LSB end). All bit
34 ranges are inclusive (so `4:6` means bits 4, 5, and 6, in MSB0 order).
35 **All register numbering and element numbering however is LSB0 ordering**
36 which is a different convention from that used elsewhere in the Power ISA.
37
38 The SVP64 prefix always comes before the suffix in PC order and must be
39 considered an independent "Defined word" that augments the behaviour of
40 the following instruction, but does **not** change the actual Decoding
41 of that following instruction. **All prefixed instructions retain their
42 non-prefixed encoding and definition**.
43
44 Two apparent exceptions to the above hard rule exist: SV Branch-Conditional
45 operations and LD/ST-update "Post-Increment" Mode. Post-Increment
46 was considered sufficiently high priority (significantly reducing hot-loop
47 instruction count) that one bit in the Prefix is reserved for it.
48 Vectorised Branch-Conditional operations "embed" the original Scalar
49 Branch-Conditional behaviour into a much more advanced variant that
50 is highly suited to High-Performance Computation (HPC), Supercomputing,
51 and parallel GPU Workloads.
52
53 *Architectural Resource Allocation note: it is prohibited to accept RFCs
54 which fundamentally violate this hard requirement. Under no circumstances
55 must the Suffix space have an alternate instruction encoding allocated
56 within SVP64 that is entirely different from the non-prefixed Defined
57 Word. Hardware Implementors critically rely on this inviolate guarantee
58 to implement High-Performance Multi-Issue micro-architectures that can
59 sustain 100% throughput*
60
61 Subset implementations in hardware are permitted, as long as certain
62 rules are followed, allowing for full soft-emulation including future
63 revisions. Compliancy Subsets exist to ensure minimum levels of binary
64 interoperability expectations within certain environments.
65
66 ## SVP64 encoding features
67
68 A number of features need to be compacted into a very small space of
69 only 24 bits:
70
71 * Independent per-register Scalar/Vector tagging and range extension on
72 every register
73 * Element width overrides on both source and destination
74 * Predication on both source and destination
75 * Two different sources of predication: INT and CR Fields
76 * SV Modes including saturation (for Audio, Video and DSP), mapreduce,
77 fail-first and predicate-result mode.
78
79 Different classes of operations require different formats. The earlier
80 sections cover the common formats and the four separate modes follow:
81 CR operations (crops), Arithmetic/Logical (termed "normal"), Load/Store
82 and Branch-Conditional.
83
84 ## Definition of Reserved in this spec.
85
86 For the new fields added in SVP64, instructions that have any of their
87 fields set to a reserved value must cause an illegal instruction trap,
88 to allow emulation of future instruction sets, or for subsets of SVP64 to
89 be implemented in hardware and the rest emulated. This includes SVP64
90 SPRs: reading or writing values which are not supported in hardware
91 must also raise illegal instruction traps in order to allow emulation.
92 Unless otherwise stated, reserved values are always all zeros.
93
94 This is unlike OpenPower ISA v3.1, which in many instances does not
95 require a trap if reserved fields are nonzero. Where the standard Power
96 ISA definition is intended the red keyword `RESERVED` is used.
97
98 ## Definition of "UnVectoriseable"
99
100 Any operation that inherently makes no sense if repeated is termed
101 "UnVectoriseable" or "UnVectorised". Examples include `sc` or `sync`
102 which have no registers. `mtmsr` is also classed as UnVectoriseable
103 because there is only one `MSR`.
104
105 ## Register files, elements, and Element-width Overrides
106
107 In the Upper Compliancy Levels of SVP64 the size of the GPR and FPR
108 Register files are expanded from 32 to 128 entries, and the number of
109 CR Fields expanded from CR0-CR7 to CR0-CR127. (Note: A future version
110 of SVP64 is anticipated to extend the VSR register file).
111
112 Memory access remains exactly the same: the effects of `MSR.LE` remain
113 exactly the same, affecting as they already do and remain **only**
114 on the Load and Store memory-register operation byte-order, and having
115 nothing to do with the ordering of the contents of register files or
116 register-register operations.
117
118 To be absolutely clear:
119
120 ```
121 There are no conceptual arithmetic ordering or other changes over the
122 Scalar Power ISA definitions to registers or register files or to
123 arithmetic or Logical Operations beyond element-width subdivision
124 ```
125
126 Element offset
127 numbering is naturally **LSB0-sequentially-incrementing from zero, not
128 MSB0-incrementing** including when element-width overrides are used,
129 at which point the elements progress through each register
130 sequentially from the LSB end
131 (confusingly numbered the highest in MSB0 ordering) and progress
132 incrementally to the MSB end (confusingly numbered the lowest in
133 MSB0 ordering).
134
135 When exclusively using MSB0-numbering, SVP64
136 becomes unnecessarily complex to both express and subsequently understand:
137 the required conditional subtractions from 63,
138 31, 15 and 7 needed to express the fact that elements are LSB0-sequential
139 unfortunately become a hostile minefield, obscuring both
140 intent and meaning. Therefore for the
141 purposes of this section the more natural **LSB0 numbering is assumed**
142 and it is left to the reader to translate to MSB0 numbering.
143
144 The Canonical specification for how element-sequential numbering and
145 element-width overrides is defined is expressed in the following c
146 structure, assuming a Little-Endian system, and naturally using LSB0
147 numbering everywhere because the ANSI c specification is inherently LSB0:
148
149 ```
150 #pragma pack
151 typedef union {
152 uint8_t b[]; // elwidth 8
153 uint16_t s[]; // elwidth 16
154 uint32_t i[]; // elwidth 32
155 uint64_t l[]; // elwidth 64
156 uint8_t actual_bytes[8];
157 } el_reg_t;
158
159 elreg_t int_regfile[128];
160
161 void get_register_element(el_reg_t* el, int gpr, int element, int width) {
162 switch (width) {
163 case 64: el->l = int_regfile[gpr].l[element];
164 case 32: el->i = int_regfile[gpr].i[element];
165 case 16: el->s = int_regfile[gpr].s[element];
166 case 8 : el->b = int_regfile[gpr].b[element];
167 }
168 }
169 void set_register_element(el_reg_t* el, int gpr, int element, int width) {
170 switch (width) {
171 case 64: int_regfile[gpr].l[element] = el->l;
172 case 32: int_regfile[gpr].i[element] = el->i;
173 case 16: int_regfile[gpr].s[element] = el->s;
174 case 8 : int_regfile[gpr].b[element] = el->b;
175 }
176 }
177 ```
178
179 Example Vector-looped add operation implementation when elwidths are 64-bit:
180
181 ```
182 # vector-add RT, RA,RB using the "uint64_t" union member, "l"
183 for i in range(VL):
184 int_regfile[RT].l[i] = int_regfile[RA].l[i] + int_regfile[RB].l[i]
185 ```
186
187 However if elwidth overrides are set to 16 for both source and destination:
188
189 ```
190 # vector-add RT, RA, RB using the "uint64_t" union member "s"
191 for i in range(VL):
192 int_regfile[RT].s[i] = int_regfile[RA].s[i] + int_regfile[RB].s[i]
193 ```
194
195 Hardware Architectural note: to avoid a Read-Modify-Write at the register
196 file it is strongly recommended to implement byte-level write-enable lines
197 exactly as has been implemented in DRAM ICs for many decades. Additionally
198 the predicate mask bit is advised to be associated with the element
199 operation and alongside the result ultimately passed to the register file.
200 When element-width is set to 64-bit the relevant predicate mask bit
201 may be repeated eight times and pull all eight write-port byte-level
202 lines HIGH. Clearly when element-width is set to 8-bit the relevant
203 predicate mask bit corresponds directly with one single byte-level
204 write-enable line. It is up to the Hardware Architect to then amortise
205 (merge) elements together into both PredicatedSIMD Pipelines as well
206 as simultaneous non-overlapping Register File writes, to achieve High
207 Performance designs.
208
209 ## Scalar Identity Behaviour
210
211 SVP64 is designed so that when the prefix is all zeros, and VL=1, no
212 effect or influence occurs (no augmentation) such that all standard Power
213 ISA v3.0/v3 1 instructions covered by the prefix are "unaltered". This
214 is termed `scalar identity behaviour` (based on the mathematical
215 definition for "identity", as in, "identity matrix" or better "identity
216 transformation").
217
218 Note that this is completely different from when VL=0. VL=0 turns all
219 operations under its influence into `nops` (regardless of the prefix)
220 whereas when VL=1 and the SV prefix is all zeros, the operation simply
221 acts as if SV had not been applied at all to the instruction (an
222 "identity transformation").
223
224 The fact that `VL` is dynamic and can be set to any value at runtime based
225 on program conditions and behaviour means very specifically that
226 `scalar identity behaviour` is **not** a redundant encoding. If the
227 only means by which VL could be set was by way of static-compiled
228 immediates then this assertion would be false. VL should not
229 be confused with MAXVL when understanding this key aspect of SimpleV.
230
231 ## Register Naming and size
232
233 As indicated above SV Registers are simply the GPR, FPR and CR
234 register files extended linearly to larger sizes; SV Vectorisation
235 iterates sequentially through these registers (LSB0 sequential ordering
236 from 0 to VL-1).
237
238 Where the integer regfile in standard scalar Power ISA v3.0B/v3.1B is
239 r0 to r31, SV extends this as r0 to r127. Likewise FP registers are
240 extended to 128 (fp0 to fp127), and CR Fields are extended to 128 entries,
241 CR0 thru CR127.
242
243 The names of the registers therefore reflects a simple linear extension
244 of the Power ISA v3.0B / v3.1B register naming, and in hardware this
245 would be reflected by a linear increase in the size of the underlying
246 SRAM used for the regfiles.
247
248 Note: when an EXTRA field (defined below) is zero, SV is deliberately
249 designed so that the register fields are identical to as if SV was not in
250 effect i.e. under these circumstances (EXTRA=0) the register field names
251 RA, RB etc. are interpreted and treated as v3.0B / v3.1B scalar registers.
252 This is part of `scalar identity behaviour` described above.
253
254 **Condition Register(s)**
255
256 The Scalar Power ISA Condition Register is a 64 bit register where the top
257 32 MSBs (numbered 0:31 in MSB0 numbering) are not used. This convention is
258 *preserved*
259 in SVP64 and an additional 15 Condition Registers provided in
260 order to store the new CR Fields, CR8-CR15, CR16-CR23 etc. sequentially.
261 The top 32 MSBs in each new SVP64 Condition Register are *also* not used:
262 only the bottom 32 bits (numbered 32:63 in MSB0 numbering).
263
264 *Programmer's note: using `sv.mfcr` without element-width overrides
265 to take into account the fact that the top 32 MSBs are zero and thus
266 effectively doubling the number of GPR registers required to hold all 128
267 CR Fields would seem the only option because normally elwidth overrides
268 would halve the capacity of the instruction. However in this case it
269 is possible to use destination element-width overrides (for `sv.mfcr`.
270 source overrides would be used on the GPR of `sv.mtocrf`), whereupon
271 truncation of the 64-bit Condition Register(s) occurs, throwing away
272 the zeros and storing the remaining (valid, desired) 32-bit values
273 sequentially into (LSB0-convention) lower-numbered and upper-numbered
274 halves of GPRs respectively. The programmer is expected to be aware
275 however that the full width of the entire 64-bit Condition Register
276 is considered to be "an element". This is **not** like any other
277 Condition-Register instructions because all other CR instructions,
278 on closer investigation, will be observed to all be CR-bit or CR-Field
279 related. Thus a `VL` of 16 must be used*
280
281 ## Future expansion.
282
283 With the way that EXTRA fields are defined and applied to register fields,
284 future versions of SV may involve 256 or greater registers. Backwards
285 binary compatibility may be achieved with a PCR bit (Program Compatibility
286 Register) or an MSR bit analogous to SF.
287 Further discussion is out of scope for this version of SVP64.
288
289 Additionally, a future variant of SVP64 will be applied to the Scalar
290 (Quad-precision and 128-bit) VSX instructions. Element-width overrides
291 are an opportunity to expand a future version of the Power ISA
292 to 256-bit, 512-bit and
293 1024-bit operations, as well as doubling or quadrupling the number
294 of VSX registers to 128 or 256. Again further discussion is out of
295 scope for this version of SVP64.
296
297 --------
298
299 \newpage{}
300
301 # New 64-bit Instruction Encoding spaces
302
303 The following seven new areas are defined within Primary Opcode 9 (EXT009)
304 as a new 64-bit encoding space, alongside EXT1xx.
305
306 | 0-5 | 6 | 7 | 8-31 | 32| Description |
307 |-----|---|---|-------|---|------------------------------------|
308 | PO | 0 | x | xxxx | 0 | `RESERVED2` (56-bit) |
309 | PO | 0 | 0 | !zero | 1 | SVP64Single:EXT232-263, or `RESERVED3` |
310 | PO | 0 | 0 | 0000 | 1 | Scalar EXT232-263 |
311 | PO | 0 | 1 | nnnn | 1 | SVP64:EXT232-263 |
312 | PO | 1 | 0 | 0000 | x | `RESERVED1` (32-bit) |
313 | PO | 1 | 0 | !zero | n | SVP64Single:EXT000-063 or `RESERVED4` |
314 | PO | 1 | 1 | nnnn | n | SVP64:EXT000-063 |
315
316 Note that for the future SVP64Single Encoding (currently RESERVED3 and 4)
317 it is prohibited to have bits 8-31 be zero, unlike for SVP64 Vector space,
318 for which bits 8-31 can be zero (termed `scalar identity behaviour`). This
319 prohibition allows SVP64Single to share its Encoding space with Scalar
320 Ext232-263 and Scalar EXT300-363.
321
322 Also that RESERVED1 and 2 are candidates for future Major opcode
323 areas EXT200-231 and EXT300-363 respectively, however as RESERVED areas
324 they may equally be allocated entirely differently.
325
326 *Architectural Resource Allocation Note: **under no circumstances** must
327 different Defined Words be allocated within any `EXT{z}` prefixed
328 or unprefixed space for a given value of `z`. Even if UnVectoriseable
329 an instruction Defined Word space must have the exact same Instruction
330 and exact same Instruction Encoding in all spaces (including
331 being RESERVED if UnVectoriseable) or not be allocated at all.
332 This is required as an inviolate hard rule governing Primary Opcode 9
333 that may not be revoked under any circumstances. A useful way to think
334 of this is that the Prefix Encoding is, like the 8086 REP instruction,
335 an independent 32-bit Defined Word. The only semi-exceptions are
336 the Post-Increment Mode of LD/ST-Update and Vectorised Branch-Conditional.*
337
338 Ecoding spaces and their potential are illustrated:
339
340 | Encoding | Available bits | Scalar | Vectoriseable | SVP64Single |
341 |----------|----------------|--------|---------------|--------------|
342 |EXT000-063| 32 | yes | yes |yes |
343 |EXT100-163| 64 (?) | yes | no |no |
344 |R3SERVED2 | 56 | N/A |not applicable |not applicable|
345 |EXT232-263| 32 | yes | yes |yes |
346 |RESERVED1 | 32 | N/A | no |no |
347
348 Prefixed-Prefixed (96-bit) instructions are prohibited. RESERVED2 presently
349 remains unallocated as of yet and therefore its potential is not yet defined
350 (Not Applicable). RESERVED1 is also unallocated at present, but it is
351 known in advance that the area is UnVectoriseable and also cannot be
352 Prefixed with SVP64Single.
353
354 # Remapped Encoding (`RM[0:23]`)
355
356 In the SVP64 Vector Prefix spaces, the 24 bits 8-31 are termed `RM`. Bits
357 32-37 are the Primary Opcode of the Suffix "Defined Word". 38-63 are the
358 remainder of the Defined Word. Note that the new EXT232-263 SVP64 area
359 it is obviously mandatory that bit 32 is required to be set to 1.
360
361 | 0-5 | 6 | 7 | 8-31 | 32-37 | 38-64 |Description |
362 |-----|---|---|----------|--------|----------|-----------------------|
363 | PO | 0 | 1 | RM[0:23] | 1nnnnn | xxxxxxxx | SVP64:EXT232-263 |
364 | PO | 1 | 1 | RM[0:23] | nnnnnn | xxxxxxxx | SVP64:EXT000-063 |
365
366 It is important to note that unlike v3.1 64-bit prefixed instructions
367 there is insufficient space in `RM` to provide identification of
368 any SVP64 Fields without first partially decoding the 32-bit suffix.
369 Similar to the "Forms" (X-Form, D-Form) the `RM` format is individually
370 associated with every instruction. However this still does not adversely
371 affect Multi-Issue Decoding because the identification of the *length*
372 of anything in the 64-bit space has been kept brutally simple (EXT009),
373 and further decoding of any number of 64-bit Encodings in parallel at
374 that point is fully independent.
375
376 Extreme caution and care must be taken when extending SVP64
377 in future, to not create unnecessary relationships between prefix and
378 suffix that could complicate decoding, adding latency.
379
380 ## Common RM fields
381
382 The following fields are common to all Remapped Encodings:
383
384 | Field Name | Field bits | Description |
385 |------------|------------|----------------------------------------|
386 | MASKMODE | `0` | Execution (predication) Mask Kind |
387 | MASK | `1:3` | Execution Mask |
388 | SUBVL | `8:9` | Sub-vector length |
389
390 The following fields are optional or encoded differently depending
391 on context after decoding of the Scalar suffix:
392
393 | Field Name | Field bits | Description |
394 |------------|------------|----------------------------------------|
395 | ELWIDTH | `4:5` | Element Width |
396 | ELWIDTH_SRC | `6:7` | Element Width for Source |
397 | EXTRA | `10:18` | Register Extra encoding |
398 | MODE | `19:23` | changes Vector behaviour |
399
400 * MODE changes the behaviour of the SV operation (result saturation,
401 mapreduce)
402 * SUBVL groups elements together into vec2, vec3, vec4 for use in 3D
403 and Audio/Video DSP work
404 * ELWIDTH and ELWIDTH_SRC overrides the instruction's destination and
405 source operand width
406 * MASK (and MASK_SRC) and MASKMODE provide predication (two types of
407 sources: scalar INT and Vector CR).
408 * Bits 10 to 18 (EXTRA) are further decoded depending on the RM category
409 for the instruction, which is determined only by decoding the Scalar 32
410 bit suffix.
411
412 Similar to Power ISA `X-Form` etc. EXTRA bits are given designations,
413 such as `RM-1P-3S1D` which indicates for this example that the operation
414 is to be single-predicated and that there are 3 source operand EXTRA
415 tags and one destination operand tag.
416
417 Note that if ELWIDTH != ELWIDTH_SRC this may result in reduced performance
418 or increased latency in some implementations due to lane-crossing.
419
420 ## Mode
421
422 Mode is an augmentation of SV behaviour. Different types of instructions
423 have different needs, similar to Power ISA v3.1 64 bit prefix 8LS and MTRR
424 formats apply to different instruction types. Modes include Reduction,
425 Iteration, arithmetic saturation, and Fail-First. More specific details
426 in each section and in the SVP64 appendix
427
428 * For condition register operations see [[sv/cr_ops]]
429 * For LD/ST Modes, see [[sv/ldst]].
430 * For Branch modes, see [[sv/branches]]
431 * For arithmetic and logical, see [[sv/normal]]
432
433 ## ELWIDTH Encoding
434
435 Default behaviour is set to 0b00 so that zeros follow the convention
436 of `scalar identity behaviour`. In this case it means that elwidth
437 overrides are not applicable. Thus if a 32 bit instruction operates
438 on 32 bit, `elwidth=0b00` specifies that this behaviour is unmodified.
439 Likewise when a processor is switched from 64 bit to 32 bit mode,
440 `elwidth=0b00` states that, again, the behaviour is not to be modified.
441
442 Only when elwidth is nonzero is the element width overridden to the
443 explicitly required value.
444
445 ### Elwidth for Integers:
446
447 | Value | Mnemonic | Description |
448 |-------|----------------|------------------------------------|
449 | 00 | DEFAULT | default behaviour for operation |
450 | 01 | `ELWIDTH=w` | Word: 32-bit integer |
451 | 10 | `ELWIDTH=h` | Halfword: 16-bit integer |
452 | 11 | `ELWIDTH=b` | Byte: 8-bit integer |
453
454 This encoding is chosen such that the byte width may be computed as
455 `8<<(3-ew)`
456
457 ### Elwidth for FP Registers:
458
459 | Value | Mnemonic | Description |
460 |-------|----------------|------------------------------------|
461 | 00 | DEFAULT | default behaviour for FP operation |
462 | 01 | `ELWIDTH=f32` | 32-bit IEEE 754 Single floating-point |
463 | 10 | `ELWIDTH=f16` | 16-bit IEEE 754 Half floating-point |
464 | 11 | `ELWIDTH=bf16` | Reserved for `bf16` |
465
466 Note:
467 [`bf16`](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format)
468 is reserved for a future implementation of SV
469
470 Note that any IEEE754 FP operation in Power ISA ending in "s" (`fadds`)
471 shall perform its operation at **half** the ELWIDTH then padded back out
472 to ELWIDTH. `sv.fadds/ew=f32` shall perform an IEEE754 FP16 operation
473 that is then "padded" to fill out to an IEEE754 FP32. When ELWIDTH=DEFAULT
474 clearly the behaviour of `sv.fadds` is performed at 32-bit accuracy
475 then padded back out to fit in IEEE754 FP64, exactly as for Scalar
476 v3.0B "single" FP. Any FP operation ending in "s" where ELWIDTH=f16 or
477 ELWIDTH=bf16 is reserved and must raise an illegal instruction (IEEE754
478 FP8 or BF8 are not defined).
479
480 ### Elwidth for CRs (no meaning)
481
482 Element-width overrides for CR Fields has no meaning. The bits
483 are therefore used for other purposes, or when Rc=1, the Elwidth
484 applies to the result being tested (a GPR or FPR), but not to the
485 Vector of CR Fields.
486
487 ## SUBVL Encoding
488
489 The default for SUBVL is 1 and its encoding is 0b00 to indicate that
490 SUBVL is effectively disabled (a SUBVL for-loop of only one element). this
491 lines up in combination with all other "default is all zeros" behaviour.
492
493 | Value | Mnemonic | Subvec | Description |
494 |-------|-----------|---------|------------------------|
495 | 00 | `SUBVL=1` | single | Sub-vector length of 1 |
496 | 01 | `SUBVL=2` | vec2 | Sub-vector length of 2 |
497 | 10 | `SUBVL=3` | vec3 | Sub-vector length of 3 |
498 | 11 | `SUBVL=4` | vec4 | Sub-vector length of 4 |
499
500 The SUBVL encoding value may be thought of as an inclusive range of a
501 sub-vector. SUBVL=2 represents a vec2, its encoding is 0b01, therefore
502 this may be considered to be elements 0b00 to 0b01 inclusive.
503
504 ## MASK/MASK_SRC & MASKMODE Encoding
505
506 One bit (`MASKMODE`) indicates the mode: CR or Int predication. The two
507 types may not be mixed.
508
509 Special note: to disable predication this field must be set to zero in
510 combination with Integer Predication also being set to 0b000. this has the
511 effect of enabling "all 1s" in the predicate mask, which is equivalent to
512 "not having any predication at all" and consequently, in combination with
513 all other default zeros, fully disables SV (`scalar identity behaviour`).
514
515 `MASKMODE` may be set to one of 2 values:
516
517 | Value | Description |
518 |-----------|------------------------------------------------------|
519 | 0 | MASK/MASK_SRC are encoded using Integer Predication |
520 | 1 | MASK/MASK_SRC are encoded using CR-based Predication |
521
522 Integer Twin predication has a second set of 3 bits that uses the same
523 encoding thus allowing either the same register (r3, r10 or r31) to be
524 used for both src and dest, or different regs (one for src, one for dest).
525
526 Likewise CR based twin predication has a second set of 3 bits, allowing
527 a different test to be applied.
528
529 Note that it is assumed that Predicate Masks (whether INT or CR) are
530 read *before* the operations proceed. In practice (for CR Fields)
531 this creates an unnecessary block on parallelism. Therefore, it is up
532 to the programmer to ensure that the CR fields used as Predicate Masks
533 are not being written to by any parallel Vector Loop. Doing so results
534 in **UNDEFINED** behaviour, according to the definition outlined in the
535 Power ISA v3.0B Specification.
536
537 Hardware Implementations are therefore free and clear to delay reading
538 of individual CR fields until the actual predicated element operation
539 needs to take place, safe in the knowledge that no programmer will have
540 issued a Vector Instruction where previous elements could have overwritten
541 (destroyed) not-yet-executed CR-Predicated element operations.
542
543 ### Integer Predication (MASKMODE=0)
544
545 When the predicate mode bit is zero the 3 bits are interpreted as below.
546 Twin predication has an identical 3 bit field similarly encoded.
547
548 `MASK` and `MASK_SRC` may be set to one of 8 values, to provide the
549 following meaning:
550
551 | Value | Mnemonic | Element `i` enabled if: |
552 |-------|----------|------------------------------|
553 | 000 | ALWAYS | predicate effectively all 1s |
554 | 001 | 1 << R3 | `i == R3` |
555 | 010 | R3 | `R3 & (1 << i)` is non-zero |
556 | 011 | ~R3 | `R3 & (1 << i)` is zero |
557 | 100 | R10 | `R10 & (1 << i)` is non-zero |
558 | 101 | ~R10 | `R10 & (1 << i)` is zero |
559 | 110 | R30 | `R30 & (1 << i)` is non-zero |
560 | 111 | ~R30 | `R30 & (1 << i)` is zero |
561
562 r10 and r30 are at the high end of temporary and unused registers,
563 so as not to interfere with register allocation from ABIs.
564
565 ### CR-based Predication (MASKMODE=1)
566
567 When the predicate mode bit is one the 3 bits are interpreted as below.
568 Twin predication has an identical 3 bit field similarly encoded.
569
570 `MASK` and `MASK_SRC` may be set to one of 8 values, to provide the
571 following meaning:
572
573 | Value | Mnemonic | Element `i` is enabled if |
574 |-------|----------|--------------------------|
575 | 000 | lt | `CR[offs+i].LT` is set |
576 | 001 | nl/ge | `CR[offs+i].LT` is clear |
577 | 010 | gt | `CR[offs+i].GT` is set |
578 | 011 | ng/le | `CR[offs+i].GT` is clear |
579 | 100 | eq | `CR[offs+i].EQ` is set |
580 | 101 | ne | `CR[offs+i].EQ` is clear |
581 | 110 | so/un | `CR[offs+i].FU` is set |
582 | 111 | ns/nu | `CR[offs+i].FU` is clear |
583
584 `offs` is defined as CR32 (4x8) so as to mesh cleanly with Vectorised
585 Rc=1 operations (see below). Rc=1 operations start from CR8 (TBD).
586
587 The CR Predicates chosen must start on a boundary that Vectorised CR
588 operations can access cleanly, in full. With EXTRA2 restricting starting
589 points to multiples of 8 (CR0, CR8, CR16...) both Vectorised Rc=1 and
590 CR Predicate Masks have to be adapted to fit on these boundaries as well.
591
592 ## Extra Remapped Encoding <a name="extra_remap"> </a>
593
594 Shows all instruction-specific fields in the Remapped Encoding
595 `RM[10:18]` for all instruction variants. Note that due to the very
596 tight space, the encoding mode is *not* included in the prefix itself.
597 The mode is "applied", similar to Power ISA "Forms" (X-Form, D-Form)
598 on a per-instruction basis, and, like "Forms" are given a designation
599 (below) of the form `RM-nP-nSnD`. The full list of which instructions
600 use which remaps is here [[opcode_regs_deduped]].
601
602 **Please note the following**:
603
604 ```
605 Machine-readable CSV files have been provided which will make the task
606 of creating SV-aware ISA decoders, documentation, assembler tools
607 compiler tools Simulators documentation all aspects of SVP64 easier
608 and less prone to mistakes. Please avoid manual re-creation of
609 information from the written specification wording, and use the
610 CSV files or use the Canonical tool which creates the CSV files,
611 named sv_analysis.py. The information contained within sv_analysis.py
612 is considered to be part of this Specification, even encoded as it
613 is in python3.
614 ```
615
616 The mappings are part of the SVP64 Specification in exactly the same
617 way as X-Form, D-Form. New Scalar instructions added to the Power ISA
618 will need a corresponding SVP64 Mapping, which can be derived by-rote
619 from examining the Register "Profile" of the instruction.
620
621 There are two categories: Single and Twin Predication. Due to space
622 considerations further subdivision of Single Predication is based on
623 whether the number of src operands is 2 or 3. With only 9 bits available
624 some compromises have to be made.
625
626 * `RM-1P-3S1D` Single Predication dest/src1/2/3, applies to 4-operand
627 instructions (fmadd, isel, madd).
628 * `RM-1P-2S1D` Single Predication dest/src1/2 applies to 3-operand
629 instructions (src1 src2 dest)
630 * `RM-2P-1S1D` Twin Predication (src=1, dest=1)
631 * `RM-2P-2S1D` Twin Predication (src=2, dest=1) primarily for LDST (Indexed)
632 * `RM-2P-1S2D` Twin Predication (src=1, dest=2) primarily for LDST Update
633
634 ### RM-1P-3S1D
635
636 | Field Name | Field bits | Description |
637 |------------|------------|----------------------------------------|
638 | Rdest\_EXTRA2 | `10:11` | extends Rdest (R\*\_EXTRA2 Encoding) |
639 | Rsrc1\_EXTRA2 | `12:13` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
640 | Rsrc2\_EXTRA2 | `14:15` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
641 | Rsrc3\_EXTRA2 | `16:17` | extends Rsrc3 (R\*\_EXTRA2 Encoding) |
642 | EXTRA2_MODE | `18` | used by `divmod2du` and `maddedu` for RS |
643
644 These are for 3 operand in and either 1 or 2 out instructions.
645 3-in 1-out includes `madd RT,RA,RB,RC`. (DRAFT) instructions
646 such as `maddedu` have an implicit second destination, RS, the
647 selection of which is determined by bit 18.
648
649 ### RM-1P-2S1D
650
651 | Field Name | Field bits | Description |
652 |------------|------------|-------------------------------------------|
653 | Rdest\_EXTRA3 | `10:12` | extends Rdest |
654 | Rsrc1\_EXTRA3 | `13:15` | extends Rsrc1 |
655 | Rsrc2\_EXTRA3 | `16:18` | extends Rsrc3 |
656
657 These are for 2 operand 1 dest instructions, such as `add RT, RA,
658 RB`. However also included are unusual instructions with an implicit
659 dest that is identical to its src reg, such as `rlwinmi`.
660
661 Normally, with instructions such as `rlwinmi`, the scalar v3.0B ISA would
662 not have sufficient bit fields to allow an alternative destination.
663 With SV however this becomes possible. Therefore, the fact that the
664 dest is implicitly also a src should not mislead: due to the *prefix*
665 they are different SV regs.
666
667 * `rlwimi RA, RS, ...`
668 * Rsrc1_EXTRA3 applies to RS as the first src
669 * Rsrc2_EXTRA3 applies to RA as the secomd src
670 * Rdest_EXTRA3 applies to RA to create an **independent** dest.
671
672 With the addition of the EXTRA bits, the three registers
673 each may be *independently* made vector or scalar, and be independently
674 augmented to 7 bits in length.
675
676 ### RM-2P-1S1D/2S
677
678 | Field Name | Field bits | Description |
679 |------------|------------|----------------------------|
680 | Rdest_EXTRA3 | `10:12` | extends Rdest |
681 | Rsrc1_EXTRA3 | `13:15` | extends Rsrc1 |
682 | MASK_SRC | `16:18` | Execution Mask for Source |
683
684 `RM-2P-2S` is for `stw` etc. and is Rsrc1 Rsrc2.
685
686 ### RM-1P-2S1D
687
688 single-predicate, three registers (2 read, 1 write)
689
690 | Field Name | Field bits | Description |
691 |------------|------------|----------------------------|
692 | Rdest_EXTRA3 | `10:12` | extends Rdest |
693 | Rsrc1_EXTRA3 | `13:15` | extends Rsrc1 |
694 | Rsrc2_EXTRA3 | `16:18` | extends Rsrc2 |
695
696 ### RM-2P-2S1D/1S2D/3S
697
698 The primary purpose for this encoding is for Twin Predication on LOAD
699 and STORE operations. see [[sv/ldst]] for detailed anslysis.
700
701 **RM-2P-2S1D:**
702
703 | Field Name | Field bits | Description |
704 |------------|------------|----------------------------|
705 | Rdest_EXTRA2 | `10:11` | extends Rdest (R\*\_EXTRA2 Encoding) |
706 | Rsrc1_EXTRA2 | `12:13` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
707 | Rsrc2_EXTRA2 | `14:15` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
708 | MASK_SRC | `16:18` | Execution Mask for Source |
709
710 **RM-2P-1S2D:**
711
712 For RM-2P-1S2D the EXTRA2 dest and src names are switched (Rsrc_EXTRA2
713 is in bits 10:11, Rdest1_EXTRA2 in 12:13)
714
715 | Field Name | Field bits | Description |
716 |------------|------------|----------------------------|
717 | Rsrc2_EXTRA2 | `10:11` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
718 | Rsrc1_EXTRA2 | `12:13` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
719 | Rdest_EXTRA2 | `14:15` | extends Rdest (R\*\_EXTRA2 Encoding) |
720 | MASK_SRC | `16:18` | Execution Mask for Source |
721
722 **RM-2P-3S:**
723
724 Also that for RM-2P-3S (to cover `stdx` etc.) the names are switched to 3 src:
725 Rsrc1_EXTRA2, Rsrc2_EXTRA2, Rsrc3_EXTRA2.
726
727 | Field Name | Field bits | Description |
728 |------------|------------|----------------------------|
729 | Rsrc1_EXTRA2 | `10:11` | extends Rsrc1 (R\*\_EXTRA2 Encoding) |
730 | Rsrc2_EXTRA2 | `12:13` | extends Rsrc2 (R\*\_EXTRA2 Encoding) |
731 | Rsrc3_EXTRA2 | `14:15` | extends Rsrc3 (R\*\_EXTRA2 Encoding) |
732 | MASK_SRC | `16:18` | Execution Mask for Source |
733
734 Note also that LD with update indexed, which takes 2 src and
735 creates 2 dest registers (e.g. `lhaux RT,RA,RB`), does not have room
736 for 4 registers and also Twin Predication. Therefore these are treated as
737 RM-2P-2S1D and the src spec for RA is also used for the same RA as a dest.
738
739 Note that if ELWIDTH != ELWIDTH_SRC this may result in reduced performance
740 or increased latency in some implementations due to lane-crossing.
741
742 ## R\*\_EXTRA2/3
743
744 EXTRA is the means by which two things are achieved:
745
746 1. Registers are marked as either Vector *or Scalar*
747 2. Register field numbers (limited typically to 5 bit)
748 are extended in range, both for Scalar and Vector.
749
750 The register files are therefore extended:
751
752 * INT (GPR) is extended from r0-31 to r0-127
753 * FP (FPR) is extended from fp0-32 to fp0-fp127
754 * CR Fields are extended from CR0-7 to CR0-127
755
756 However due to pressure in `RM.EXTRA` not all these registers
757 are accessible by all instructions, particularly those with
758 a large number of operands (`madd`, `isel`).
759
760 In the following tables register numbers are constructed from the
761 standard v3.0B / v3.1B 32 bit register field (RA, FRA) and the EXTRA2 or
762 EXTRA3 field from the SV Prefix, determined by the specific RM-xx-yyyy
763 designation for a given instruction. The prefixing is arranged so that
764 interoperability between prefixing and nonprefixing of scalar registers
765 is direct and convenient (when the EXTRA field is all zeros).
766
767 A pseudocode algorithm explains the relationship, for INT/FP (see
768 SVP64 appendix for CRs)
769
770 ```
771 if extra3_mode:
772 spec = EXTRA3
773 else:
774 spec = EXTRA2 << 1 # same as EXTRA3, shifted
775 if spec[0]: # vector
776 return (RA << 2) | spec[1:2]
777 else: # scalar
778 return (spec[1:2] << 5) | RA
779 ```
780
781 Future versions may extend to 256 by shifting Vector numbering up.
782 Scalar will not be altered.
783
784 Note that in some cases the range of starting points for Vectors
785 is limited.
786
787 ### INT/FP EXTRA3
788
789 If EXTRA3 is zero, maps to "scalar identity" (scalar Power ISA field
790 naming).
791
792 Fields are as follows:
793
794 * Value: R_EXTRA3
795 * Mode: register is tagged as scalar or vector
796 * Range/Inc: the range of registers accessible from this EXTRA
797 encoding, and the "increment" (accessibility). "/4" means
798 that this EXTRA encoding may only give access (starting point)
799 every 4th register.
800 * MSB..LSB: the bit field showing how the register opcode field
801 combines with EXTRA to give (extend) the register number (GPR)
802
803 | Value | Mode | Range/Inc | 6..0 |
804 |-----------|-------|---------------|---------------------|
805 | 000 | Scalar | `r0-r31`/1 | `0b00 RA` |
806 | 001 | Scalar | `r32-r63`/1 | `0b01 RA` |
807 | 010 | Scalar | `r64-r95`/1 | `0b10 RA` |
808 | 011 | Scalar | `r96-r127`/1 | `0b11 RA` |
809 | 100 | Vector | `r0-r124`/4 | `RA 0b00` |
810 | 101 | Vector | `r1-r125`/4 | `RA 0b01` |
811 | 110 | Vector | `r2-r126`/4 | `RA 0b10` |
812 | 111 | Vector | `r3-r127`/4 | `RA 0b11` |
813
814 ### INT/FP EXTRA2
815
816 If EXTRA2 is zero will map to
817 "scalar identity behaviour" i.e Scalar Power ISA register naming:
818
819 | Value | Mode | Range/inc | 6..0 |
820 |----------|-------|---------------|-----------|
821 | 00 | Scalar | `r0-r31`/1 | `0b00 RA` |
822 | 01 | Scalar | `r32-r63`/1 | `0b01 RA` |
823 | 10 | Vector | `r0-r124`/4 | `RA 0b00` |
824 | 11 | Vector | `r2-r126`/4 | `RA 0b10` |
825
826 **Note that unlike in EXTRA3, in EXTRA2**:
827
828 * the GPR Vectors may only start from
829 `r0, r2, r4, r6, r8` and likewise FPR Vectors.
830 * the GPR Scalars may only go from `r0, r1, r2.. r63` and likewise FPR Scalars.
831
832 as there is insufficient bits to cover the full range.
833
834 ### CR Field EXTRA3
835
836 CR Field encoding is essentially the same but made more complex due to CRs
837 being bit-based, because the application of SVP64 element-numbering applies
838 to the CR *Field* numbering not the CR register *bit* numbering.
839 Note that Vectors may only start from `CR0, CR4, CR8, CR12, CR16, CR20`...
840 and Scalars may only go from `CR0, CR1, ... CR31`
841
842 Encoding shown MSB down to LSB
843
844 For a 5-bit operand (BA, BB, BT):
845
846 | Value | Mode | Range/Inc | 8..5 | 4..2 | 1..0 |
847 |-------|------|---------------|-----------| --------|---------|
848 | 000 | Scalar | `CR0-CR7`/1 | 0b0000 | BA[0:2] | BA[3:4] |
849 | 001 | Scalar | `CR8-CR15`/1 | 0b0001 | BA[0:2] | BA[3:4] |
850 | 010 | Scalar | `CR16-CR23`/1 | 0b0010 | BA[0:2] | BA[3:4] |
851 | 011 | Scalar | `CR24-CR31`/1 | 0b0011 | BA[0:2] | BA[3:4] |
852 | 100 | Vector | `CR0-CR112`/16 | BA[0:2] 0 | 0b000 | BA[3:4] |
853 | 101 | Vector | `CR4-CR116`/16 | BA[0:2] 0 | 0b100 | BA[3:4] |
854 | 110 | Vector | `CR8-CR120`/16 | BA[0:2] 1 | 0b000 | BA[3:4] |
855 | 111 | Vector | `CR12-CR124`/16 | BA[0:2] 1 | 0b100 | BA[3:4] |
856
857 For a 3-bit operand (e.g. BFA):
858
859 | Value | Mode | Range/Inc | 6..3 | 2..0 |
860 |-------|------|---------------|-----------| --------|
861 | 000 | Scalar | `CR0-CR7`/1 | 0b0000 | BFA |
862 | 001 | Scalar | `CR8-CR15`/1 | 0b0001 | BFA |
863 | 010 | Scalar | `CR16-CR23`/1 | 0b0010 | BFA |
864 | 011 | Scalar | `CR24-CR31`/1 | 0b0011 | BFA |
865 | 100 | Vector | `CR0-CR112`/16 | BFA 0 | 0b000 |
866 | 101 | Vector | `CR4-CR116`/16 | BFA 0 | 0b100 |
867 | 110 | Vector | `CR8-CR120`/16 | BFA 1 | 0b000 |
868 | 111 | Vector | `CR12-CR124`/16 | BFA 1 | 0b100 |
869
870 ### CR EXTRA2
871
872 CR encoding is essentially the same but made more complex due to CRs
873 being bit-based, because the application of SVP64 element-numbering applies
874 to the CR *Field* numbering not the CR register *bit* numbering.
875 See separate section for explanation and pseudocode.
876 Note that Vectors may only start from CR0, CR8, CR16, CR24, CR32...
877
878 Encoding shown MSB down to LSB
879
880 For a 5-bit operand (BA, BB, BC):
881
882 | Value | Mode | Range/Inc | 8..5 | 4..2 | 1..0 |
883 |-------|--------|----------------|---------|---------|---------|
884 | 00 | Scalar | `CR0-CR7`/1 | 0b0000 | BA[0:2] | BA[3:4] |
885 | 01 | Scalar | `CR8-CR15`/1 | 0b0001 | BA[0:2] | BA[3:4] |
886 | 10 | Vector | `CR0-CR112`/16 | BA[0:2] 0 | 0b000 | BA[3:4] |
887 | 11 | Vector | `CR8-CR120`/16 | BA[0:2] 1 | 0b000 | BA[3:4] |
888
889 For a 3-bit operand (e.g. BFA):
890
891 | Value | Mode | Range/Inc | 6..3 | 2..0 |
892 |-------|------|---------------|-----------| --------|
893 | 00 | Scalar | `CR0-CR7`/1 | 0b0000 | BFA |
894 | 01 | Scalar | `CR8-CR15`/1 | 0b0001 | BFA |
895 | 10 | Vector | `CR0-CR112`/16 | BFA 0 | 0b000 |
896 | 11 | Vector | `CR8-CR120`/16 | BFA 1 | 0b000 |
897
898 --------
899
900 \newpage{}
901
902
903 # Normal SVP64 Modes, for Arithmetic and Logical Operations
904
905 Normal SVP64 Mode covers Arithmetic and Logical operations
906 to provide suitable additional behaviour. The Mode
907 field is bits 19-23 of the [[svp64]] RM Field.
908
909 ## Mode
910
911 Mode is an augmentation of SV behaviour, providing additional
912 functionality. Some of these alterations are element-based (saturation),
913 others involve post-analysis (predicate result) and others are
914 Vector-based (mapreduce, fail-on-first).
915
916 [[sv/ldst]], [[sv/cr_ops]] and [[sv/branches]] are covered separately:
917 the following Modes apply to Arithmetic and Logical SVP64 operations:
918
919 * **simple** mode is straight vectorisation. no augmentations: the
920 vector comprises an array of independently created results.
921 * **ffirst** or data-dependent fail-on-first: see separate section.
922 the vector may be truncated depending on certain criteria.
923 *VL is altered as a result*.
924 * **sat mode** or saturation: clamps each element result to a min/max
925 rather than overflows / wraps. allows signed and unsigned clamping
926 for both INT and FP.
927 * **reduce mode**. if used correctly, a mapreduce (or a prefix sum)
928 is performed. see [[svp64/appendix]].
929 note that there are comprehensive caveats when using this mode.
930 * **pred-result** will test the result (CR testing selects a bit of CR
931 and inverts it, just like branch conditional testing) and if the
932 test fails it is as if the *destination* predicate bit was zero even
933 before starting the operation. When Rc=1 the CR element however is
934 still stored in the CR regfile, even if the test failed. See appendix
935 for details.
936
937 Note that ffirst and reduce modes are not anticipated to be
938 high-performance in some implementations. ffirst due to interactions
939 with VL, and reduce due to it requiring additional operations to produce
940 a result. simple, saturate and pred-result are however inter-element
941 independent and may easily be parallelised to give high performance,
942 regardless of the value of VL.
943
944 The Mode table for Arithmetic and Logical operations is laid out as
945 follows:
946
947 | 0-1 | 2 | 3 4 | description |
948 | --- | --- |---------|-------------------------- |
949 | 00 | 0 | dz sz | simple mode |
950 | 00 | 1 | 0 RG | scalar reduce mode (mapreduce) |
951 | 00 | 1 | 1 / | reserved |
952 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
953 | 01 | inv | VLi RC1 | Rc=0: ffirst z/nonz |
954 | 10 | N | dz sz | sat mode: N=0/1 u/s |
955 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
956 | 11 | inv | zz RC1 | Rc=0: pred-result z/nonz |
957
958 Fields:
959
960 * **sz / dz** if predication is enabled will put zeros into the dest
961 (or as src in the case of twin pred) when the predicate bit is zero.
962 otherwise the element is ignored or skipped, depending on context.
963 * **zz**: both sz and dz are set equal to this flag
964 * **inv CR bit** just as in branches (BO) these bits allow testing of
965 a CR bit and whether it is set (inv=0) or unset (inv=1)
966 * **RG** inverts the Vector Loop order (VL-1 downto 0) rather
967 than the normal 0..VL-1
968 * **N** sets signed/unsigned saturation.
969 * **RC1** as if Rc=1, enables access to `VLi`.
970 * **VLi** VL inclusive: in fail-first mode, the truncation of
971 VL *includes* the current element at the failure point rather
972 than excludes it from the count.
973
974 For LD/ST Modes, see [[sv/ldst]]. For Condition Registers see
975 [[sv/cr_ops]]. For Branch modes, see [[sv/branches]].
976
977 ## Rounding, clamp and saturate
978
979 To help ensure for example that audio quality is not compromised by
980 overflow, "saturation" is provided, as well as a way to detect when
981 saturation occurred if desired (Rc=1). When Rc=1 there will be a *vector*
982 of CRs, one CR per element in the result (Note: this is different from
983 VSX which has a single CR per block).
984
985 When N=0 the result is saturated to within the maximum range of an
986 unsigned value. For integer ops this will be 0 to 2^elwidth-1. Similar
987 logic applies to FP operations, with the result being saturated to
988 maximum rather than returning INF, and the minimum to +0.0
989
990 When N=1 the same occurs except that the result is saturated to the min
991 or max of a signed result, and for FP to the min and max value rather
992 than returning +/- INF.
993
994 When Rc=1, the CR "overflow" bit is set on the CR associated with
995 the element, to indicate whether saturation occurred. Note that
996 due to the hugely detrimental effect it has on parallel processing,
997 XER.SO is **ignored** completely and is **not** brought into play here.
998 The CR overflow bit is therefore simply set to zero if saturation did
999 not occur, and to one if it did. This behaviour (ignoring XER.SO) is
1000 actually optional in the SFFS Compliancy Subset: for SVP64 it is made
1001 mandatory *but only on Vectorised instructions*.
1002
1003 Note also that saturate on operations that set OE=1 must raise an Illegal
1004 Instruction due to the conflicting use of the CR.so bit for storing
1005 if saturation occurred. Vectorised Integer Operations that produce a
1006 Carry-Out (CA, CA32): these two bits will be `UNDEFINED` if saturation
1007 is also requested.
1008
1009 Note that the operation takes place at the maximum bitwidth (max of
1010 src and dest elwidth) and that truncation occurs to the range of the
1011 dest elwidth.
1012
1013 *Programmer's Note: Post-analysis of the Vector of CRs to find out if any
1014 given element hit saturation may be done using a mapreduced CR op (cror),
1015 or by using the new crrweird instruction with Rc=1, which will transfer
1016 the required CR bits to a scalar integer and update CR0, which will allow
1017 testing the scalar integer for nonzero. see [[sv/cr_int_predication]].
1018 Alternatively, a Data-Dependent Fail-First may be used to truncate the
1019 Vector Length to non-saturated elements, greatly increasing the productivity
1020 of parallelised inner hot-loops.*
1021
1022 ## Reduce mode
1023
1024 Reduction in SVP64 is similar in essence to other Vector Processing ISAs,
1025 but leverages the underlying scalar Base v3.0B operations. Thus it is
1026 more a convention that the programmer may utilise to give the appearance
1027 and effect of a Horizontal Vector Reduction. Due to the unusual decoupling
1028 it is also possible to perform prefix-sum (Fibonacci Series) in certain
1029 circumstances. Details are in the SVP64 appendix
1030
1031 Reduce Mode should not be confused with Parallel Reduction [[sv/remap]].
1032 As explained in the [[sv/appendix]] Reduce Mode switches off the check
1033 which would normally stop looping if the result register is scalar.
1034 Thus, the result scalar register, if also used as a source scalar,
1035 may be used to perform sequential accumulation. This *deliberately*
1036 sets up a chain of Register Hazard Dependencies, whereas Parallel Reduce
1037 [[sv/remap]] deliberately issues a Tree-Schedule of operations that may
1038 be parallelised.
1039
1040 ## Data-dependent Fail-on-first
1041
1042 Data-dependent fail-on-first is very different from LD/ST Fail-First
1043 (also known as Fault-First) and is actually CR-field-driven.
1044 Vector elements are required to appear
1045 to be executed in sequential Program Order. When REMAP is not active,
1046 element 0 would be the first.
1047
1048 Data-driven (CR-driven) fail-on-first activates when Rc=1 or other
1049 CR-creating operation produces a result (including cmp). Similar to
1050 branch, an analysis of the CR is performed and if the test fails, the
1051 vector operation terminates and discards all element operations **at and
1052 above the current one**, and VL is truncated to either the *previous*
1053 element or the current one, depending on whether VLi (VL "inclusive")
1054 is clear or set, respectively.
1055
1056 Thus the new VL comprises a contiguous vector of results, all of which
1057 pass the testing criteria (equal to zero, less than zero etc as defined
1058 by the CR-bit test).
1059
1060 *Note: when VLi is clear, the behaviour at first seems counter-intuitive.
1061 A result is calculated but if the test fails it is prohibited from being
1062 actually written. This becomes intuitive again when it is remembered
1063 that the length that VL is set to is the number of *written* elements, and
1064 only when VLI is set will the current element be included in that count.*
1065
1066 The CR-based data-driven fail-on-first is "new" and not found in ARM SVE
1067 or RVV. At the same time it is "old" because it is almost identical to
1068 a generalised form of Z80's `CPIR` instruction. It is extremely useful
1069 for reducing instruction count, however requires speculative execution
1070 involving modifications of VL to get high performance implementations.
1071 An additional mode (RC1=1) effectively turns what would otherwise be an
1072 arithmetic operation into a type of `cmp`. The CR is stored (and the
1073 CR.eq bit tested against the `inv` field). If the CR.eq bit is equal to
1074 `inv` then the Vector is truncated and the loop ends.
1075
1076 VLi is only available as an option when `Rc=0` (or for instructions
1077 which do not have Rc). When set, the current element is always also
1078 included in the count (the new length that VL will be set to). This may
1079 be useful in combination with "inv" to truncate the Vector to *exclude*
1080 elements that fail a test, or, in the case of implementations of strncpy,
1081 to include the terminating zero.
1082
1083 In CR-based data-driven fail-on-first there is only the option to select
1084 and test one bit of each CR (just as with branch BO). For more complex
1085 tests this may be insufficient. If that is the case, a vectorised crop
1086 such as crand, cror or [[sv/cr_int_predication]] crweirder may be used,
1087 and ffirst applied to the crop instead of to the arithmetic vector. Note
1088 that crops are covered by the [[sv/cr_ops]] Mode format.
1089
1090 Use of Fail-on-first with Vertical-First Mode is not prohibited but is
1091 not really recommended. The effect of truncating VL
1092 may have unintended and unexpected consequences on subsequent instructions.
1093 VLi set will be fine: it is when VLi is clear that problems may be faced.
1094
1095 *Programmer's note: `VLi` is only accessible in normal operations which in
1096 turn limits the CR field bit-testing to only `EQ/NE`. [[sv/cr_ops]] are
1097 not so limited. Thus it is possible to use for example `sv.cror/ff=gt/vli
1098 *0,*0,*0`, which is not a `nop` because it allows Fail-First Mode to
1099 perform a test and truncate VL.*
1100
1101 *Hardware implementor's note: effective Sequential Program Order must
1102 be preserved. Speculative Execution is perfectly permitted as long as
1103 the speculative elements are held back from writing to register files
1104 (kept in Resevation Stations), until such time as the relevant CR Field
1105 bit(s) has been analysed. All Speculative elements sequentially beyond
1106 the test-failure point **MUST** be cancelled. This is no different from
1107 standard Out-of-Order Execution and the modification effort to efficiently
1108 support Data-Dependent Fail-First within a pre-existing Multi-Issue
1109 Out-of-Order Engine is anticipated to be minimal. In-Order systems on
1110 the other hand are expected, unavoidably, to be low-performance*.
1111
1112 Two extremely important aspects of ffirst are:
1113
1114 * LDST ffirst may never set VL equal to zero. This because on the first
1115 element an exception must be raised "as normal".
1116 * CR-based data-dependent ffirst on the other hand **can** set VL equal
1117 to zero. This is the only means in the entirety of SV that VL may be set
1118 to zero (with the exception of via the SV.STATE SPR). When VL is set
1119 zero due to the first element failing the CR bit-test, all subsequent
1120 vectorised operations are effectively `nops` which is
1121 *precisely the desired and intended behaviour*.
1122
1123 The second crucial aspect, compared to LDST Ffirst:
1124
1125 * LD/ST Failfirst may (beyond the initial first element
1126 conditions) truncate VL for any architecturally suitable reason. Beyond
1127 the first element LD/ST Failfirst is arbitrarily speculative and 100%
1128 non-deterministic.
1129 * CR-based data-dependent first on the other hand MUST NOT truncate VL
1130 arbitrarily to a length decided by the hardware: VL MUST only be
1131 truncated based explicitly on whether a test fails. This because it is
1132 a precise Deterministic test on which algorithms can and will will rely.
1133
1134 **Floating-point Exceptions**
1135
1136 When Floating-point exceptions are enabled VL must be truncated at
1137 the point where the Exception appears not to have occurred. If `VLi`
1138 is set then VL must include the faulting element, and thus the faulting
1139 element will always raise its exception. If however `VLi` is clear then
1140 VL **excludes** the faulting element and thus the exception will **never**
1141 be raised.
1142
1143 Although very strongly discouraged the Exception Mode that permits
1144 Floating Point Exception notification to arrive too late to unwind
1145 is permitted (under protest, due it violating the otherwise 100%
1146 Deterministic nature of Data-dependent Fail-first) and is `UNDEFINED`
1147 behaviour.
1148
1149 **Use of lax FP Exception Notification Mode could result in parallel
1150 computations proceeding with invalid results that have to be explicitly
1151 detected, whereas with the strict FP Execption Mode enabled, FFirst
1152 truncates VL, allows subsequent parallel computation to avoid the
1153 exceptions entirely**
1154
1155 ## Data-dependent fail-first on CR operations (crand etc)
1156
1157 Operations that actually produce or alter CR Field as a result have
1158 their own SVP64 Mode, described in [[sv/cr_ops]].
1159
1160 ## pred-result mode
1161
1162 This mode merges common CR testing with predication, saving on instruction
1163 count. Below is the pseudocode excluding predicate zeroing and elwidth
1164 overrides. Note that the pseudocode for SVP64 CR-ops is slightly different.
1165
1166 ```
1167 for i in range(VL):
1168 # predication test, skip all masked out elements.
1169 if predicate_masked_out(i):
1170 continue
1171 result = op(iregs[RA+i], iregs[RB+i])
1172 CRnew = analyse(result) # calculates eq/lt/gt
1173 # Rc=1 always stores the CR field
1174 if Rc=1 or RC1:
1175 CR.field[offs+i] = CRnew
1176 # now test CR, similar to branch
1177 if RC1 or CR.field[BO[0:1]] != BO[2]:
1178 continue # test failed: cancel store
1179 # result optionally stored but CR always is
1180 iregs[RT+i] = result
1181 ```
1182
1183 The reason for allowing the CR element to be stored is so that
1184 post-analysis of the CR Vector may be carried out. For example:
1185 Saturation may have occurred (and been prevented from updating, by the
1186 test) but it is desirable to know *which* elements fail saturation.
1187
1188 Note that RC1 Mode basically turns all operations into `cmp`. The
1189 calculation is performed but it is only the CR that is written. The
1190 element result is *always* discarded, never written (just like `cmp`).
1191
1192 Note that predication is still respected: predicate zeroing is slightly
1193 different: elements that fail the CR test *or* are masked out are zero'd.
1194
1195 --------
1196
1197 \newpage{}
1198
1199 # SV Load and Store
1200
1201 **Rationale**
1202
1203 All Vector ISAs dating back fifty years have extensive and comprehensive
1204 Load and Store operations that go far beyond the capabilities of Scalar
1205 RISC and most CISC processors, yet at their heart on an individual element
1206 basis may be found to be no different from RISC Scalar equivalents.
1207
1208 The resource savings from Vector LD/ST are significant and stem
1209 from the fact that one single instruction can trigger a dozen (or in
1210 some microarchitectures such as Cray or NEC SX Aurora) hundreds of
1211 element-level Memory accesses.
1212
1213 Additionally, and simply: if the Arithmetic side of an ISA supports
1214 Vector Operations, then in order to keep the ALUs 100% occupied the
1215 Memory infrastructure (and the ISA itself) correspondingly needs Vector
1216 Memory Operations as well.
1217
1218 Vectorised Load and Store also presents an extra dimension (literally)
1219 which creates scenarios unique to Vector applications, that a Scalar (and
1220 even a SIMD) ISA simply never encounters. SVP64 endeavours to add the
1221 modes typically found in *all* Scalable Vector ISAs, without changing the
1222 behaviour of the underlying Base (Scalar) v3.0B operations in any way.
1223 (The sole apparent exception is Post-Increment Mode on LD/ST-update
1224 instructions)
1225
1226 ## Modes overview
1227
1228 Vectorisation of Load and Store requires creation, from scalar operations,
1229 a number of different modes:
1230
1231 * **fixed aka "unit" stride** - contiguous sequence with no gaps
1232 * **element strided** - sequential but regularly offset, with gaps
1233 * **vector indexed** - vector of base addresses and vector of offsets
1234 * **Speculative fail-first** - where it makes sense to do so
1235 * **Structure Packing** - covered in SV by [[sv/remap]] and Pack/Unpack Mode.
1236
1237 *Despite being constructed from Scalar LD/ST none of these Modes exist
1238 or make sense in any Scalar ISA. They **only** exist in Vector ISAs*
1239
1240 Also included in SVP64 LD/ST is both signed and unsigned Saturation,
1241 as well as Element-width overrides and Twin-Predication.
1242
1243 Note also that Indexed [[sv/remap]] mode may be applied to both v3.0
1244 LD/ST Immediate instructions *and* v3.0 LD/ST Indexed instructions.
1245 LD/ST-Indexed should not be conflated with Indexed REMAP mode:
1246 clarification is provided below.
1247
1248 **Determining the LD/ST Modes**
1249
1250 A minor complication (caused by the retro-fitting of modern Vector
1251 features to a Scalar ISA) is that certain features do not exactly make
1252 sense or are considered a security risk. Fail-first on Vector Indexed
1253 would allow attackers to probe large numbers of pages from userspace,
1254 where strided fail-first (by creating contiguous sequential LDs) does not.
1255
1256 In addition, reduce mode makes no sense. Realistically we need an
1257 alternative table definition for [[sv/svp64]] `RM.MODE`. The following
1258 modes make sense:
1259
1260 * saturation
1261 * predicate-result (mostly for cache-inhibited LD/ST)
1262 * simple (no augmentation)
1263 * fail-first (where Vector Indexed is banned)
1264 * Signed Effective Address computation (Vector Indexed only)
1265
1266 More than that however it is necessary to fit the usual Vector ISA
1267 capabilities onto both Power ISA LD/ST with immediate and to LD/ST
1268 Indexed. They present subtly different Mode tables, which, due to lack
1269 of space, have the following quirks:
1270
1271 * LD/ST Immediate has no individual control over src/dest zeroing,
1272 whereas LD/ST Indexed does.
1273 * LD/ST Indexed has limited zeroing on pred-result, LD/ST Immediate has
1274 *no* option to select zeroing on pred-result.
1275
1276 ## Format and fields
1277
1278 Fields used in tables below:
1279
1280 * **sz / dz** if predication is enabled will put zeros into the dest
1281 (or as src in the case of twin pred) when the predicate bit is zero.
1282 otherwise the element is ignored or skipped, depending on context.
1283 * **zz**: both sz and dz are set equal to this flag.
1284 * **inv CR bit** just as in branches (BO) these bits allow testing of
1285 a CR bit and whether it is set (inv=0) or unset (inv=1)
1286 * **N** sets signed/unsigned saturation.
1287 * **RC1** as if Rc=1, stores CRs *but not the result*
1288 * **SEA** - Signed Effective Address, if enabled performs sign-extension on
1289 registers that have been reduced due to elwidth overrides
1290 * **PI** - post-increment mode (applies to LD/ST with update only).
1291 the Effective Address utilised is always just RA, i.e. the computation of
1292 EA is stored in RA **after** it is actually used.
1293 * **LF** - Load/Store Fail or Fault First: for any reason Load or Store Vectors
1294 may be truncated to (at least) one element, and VL altered to indicate such.
1295
1296 **LD/ST immediate**
1297
1298 The table for [[sv/svp64]] for `immed(RA)` which is `RM.MODE`
1299 (bits 19:23 of `RM`) is:
1300
1301 | 0-1 | 2 | 3 4 | description |
1302 | --- | --- |---------|--------------------------- |
1303 | 00 | 0 | zz els | simple mode |
1304 | 00 | 1 | PI LF | post-increment and Fault-First |
1305 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
1306 | 01 | inv | els RC1 | Rc=0: ffirst z/nonz |
1307 | 10 | N | zz els | sat mode: N=0/1 u/s |
1308 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
1309 | 11 | inv | els RC1 | Rc=0: pred-result z/nonz |
1310
1311 The `els` bit is only relevant when `RA.isvec` is clear: this indicates
1312 whether stride is unit or element:
1313
1314 ```
1315 if RA.isvec:
1316 svctx.ldstmode = indexed
1317 elif els == 0:
1318 svctx.ldstmode = unitstride
1319 elif immediate != 0:
1320 svctx.ldstmode = elementstride
1321 ```
1322
1323 An immediate of zero is a safety-valve to allow `LD-VSPLAT`: in effect
1324 the multiplication of the immediate-offset by zero results in reading from
1325 the exact same memory location, *even with a Vector register*. (Normally
1326 this type of behaviour is reserved for the mapreduce modes)
1327
1328 For `LD-VSPLAT`, on non-cache-inhibited Loads, the read can occur just
1329 the once and be copied, rather than hitting the Data Cache multiple
1330 times with the same memory read at the same location. The benefit of
1331 Cache-inhibited LD-splats is that it allows for memory-mapped peripherals
1332 to have multiple data values read in quick succession and stored in
1333 sequentially numbered registers (but, see Note below).
1334
1335 For non-cache-inhibited ST from a vector source onto a scalar destination:
1336 with the Vector loop effectively creating multiple memory writes to
1337 the same location, we can deduce that the last of these will be the
1338 "successful" one. Thus, implementations are free and clear to optimise
1339 out the overwriting STs, leaving just the last one as the "winner".
1340 Bear in mind that predicate masks will skip some elements (in source
1341 non-zeroing mode). Cache-inhibited ST operations on the other hand
1342 **MUST** write out a Vector source multiple successive times to the exact
1343 same Scalar destination. Just like Cache-inhibited LDs, multiple values
1344 may be written out in quick succession to a memory-mapped peripheral
1345 from sequentially-numbered registers.
1346
1347 Note that any memory location may be Cache-inhibited
1348 (Power ISA v3.1, Book III, 1.6.1, p1033)
1349
1350 *Programmer's Note: an immediate also with a Scalar source as a "VSPLAT"
1351 mode is simply not possible: there are not enough Mode bits. One single
1352 Scalar Load operation may be used instead, followed by any arithmetic
1353 operation (including a simple mv) in "Splat" mode.*
1354
1355 **LD/ST Indexed**
1356
1357 The modes for `RA+RB` indexed version are slightly different
1358 but are the same `RM.MODE` bits (19:23 of `RM`):
1359
1360 | 0-1 | 2 | 3 4 | description |
1361 | --- | --- |---------|-------------------------- |
1362 | 00 | SEA | dz sz | simple mode |
1363 | 01 | SEA | dz sz | Strided (scalar only source) |
1364 | 10 | N | dz sz | sat mode: N=0/1 u/s |
1365 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
1366 | 11 | inv | zz RC1 | Rc=0: pred-result z/nonz |
1367
1368 Vector Indexed Strided Mode is qualified as follows:
1369
1370 if mode = 0b01 and !RA.isvec and !RB.isvec:
1371 svctx.ldstmode = elementstride
1372
1373 A summary of the effect of Vectorisation of src or dest:
1374
1375 ```
1376 imm(RA) RT.v RA.v no stride allowed
1377 imm(RA) RT.s RA.v no stride allowed
1378 imm(RA) RT.v RA.s stride-select allowed
1379 imm(RA) RT.s RA.s not vectorised
1380 RA,RB RT.v {RA|RB}.v Standard Indexed
1381 RA,RB RT.s {RA|RB}.v Indexed but single LD (no VSPLAT)
1382 RA,RB RT.v {RA&RB}.s VSPLAT possible. stride selectable
1383 RA,RB RT.s {RA&RB}.s not vectorised (scalar identity)
1384 ```
1385
1386 Signed Effective Address computation is only relevant for Vector Indexed
1387 Mode, when elwidth overrides are applied. The source override applies to
1388 RB, and before adding to RA in order to calculate the Effective Address,
1389 if SEA is set RB is sign-extended from elwidth bits to the full 64 bits.
1390 For other Modes (ffirst, saturate), all EA computation with elwidth
1391 overrides is unsigned.
1392
1393 Note that cache-inhibited LD/ST when VSPLAT is activated will perform
1394 **multiple** LD/ST operations, sequentially. Even with scalar src
1395 a Cache-inhibited LD will read the same memory location *multiple
1396 times*, storing the result in successive Vector destination registers.
1397 This because the cache-inhibit instructions are typically used to read
1398 and write memory-mapped peripherals. If a genuine cache-inhibited
1399 LD-VSPLAT is required then a single *scalar* cache-inhibited LD should
1400 be performed, followed by a VSPLAT-augmented mv, copying the one *scalar*
1401 value into multiple register destinations.
1402
1403 Note also that cache-inhibited VSPLAT with Predicate-result is possible.
1404 This allows for example to issue a massive batch of memory-mapped
1405 peripheral reads, stopping at the first NULL-terminated character and
1406 truncating VL to that point. No branch is needed to issue that large
1407 burst of LDs, which may be valuable in Embedded scenarios.
1408
1409 ## Vectorisation of Scalar Power ISA v3.0B
1410
1411 Scalar Power ISA Load/Store operations may be seen from their
1412 pseudocode to be of the form:
1413
1414 ```
1415 lbux RT, RA, RB
1416 EA <- (RA) + (RB)
1417 RT <- MEM(EA)
1418 ```
1419
1420 and for immediate variants:
1421
1422 ```
1423 lb RT,D(RA)
1424 EA <- RA + EXTS(D)
1425 RT <- MEM(EA)
1426 ```
1427
1428 Thus in the first example, the source registers may each be independently
1429 marked as scalar or vector, and likewise the destination; in the second
1430 example only the one source and one dest may be marked as scalar or
1431 vector.
1432
1433 Thus we can see that Vector Indexed may be covered, and, as demonstrated
1434 with the pseudocode below, the immediate can be used to give unit
1435 stride or element stride. With there being no way to tell which from
1436 the Power v3.0B Scalar opcode alone, the choice is provided instead by
1437 the SV Context.
1438
1439 ```
1440 # LD not VLD! format - ldop RT, immed(RA)
1441 # op_width: lb=1, lh=2, lw=4, ld=8
1442 op_load(RT, RA, op_width, immed, svctx, RAupdate):
1443  ps = get_pred_val(FALSE, RA); # predication on src
1444  pd = get_pred_val(FALSE, RT); # ... AND on dest
1445  for (i=0, j=0, u=0; i < VL && j < VL;):
1446 # skip nonpredicates elements
1447 if (RA.isvec) while (!(ps & 1<<i)) i++;
1448 if (RAupdate.isvec) while (!(ps & 1<<u)) u++;
1449 if (RT.isvec) while (!(pd & 1<<j)) j++;
1450 if postinc:
1451 offs = 0; # added afterwards
1452 if RA.isvec: srcbase = ireg[RA+i]
1453 else srcbase = ireg[RA]
1454 elif svctx.ldstmode == elementstride:
1455 # element stride mode
1456 srcbase = ireg[RA]
1457 offs = i * immed # j*immed for a ST
1458 elif svctx.ldstmode == unitstride:
1459 # unit stride mode
1460 srcbase = ireg[RA]
1461 offs = immed + (i * op_width) # j*op_width for ST
1462 elif RA.isvec:
1463 # quirky Vector indexed mode but with an immediate
1464 srcbase = ireg[RA+i]
1465 offs = immed;
1466 else
1467 # standard scalar mode (but predicated)
1468 # no stride multiplier means VSPLAT mode
1469 srcbase = ireg[RA]
1470 offs = immed
1471
1472 # compute EA
1473 EA = srcbase + offs
1474 # load from memory
1475 ireg[RT+j] <= MEM[EA];
1476 # check post-increment of EA
1477 if postinc: EA = srcbase + immed;
1478 # update RA?
1479 if RAupdate: ireg[RAupdate+u] = EA;
1480 if (!RT.isvec)
1481 break # destination scalar, end now
1482 if (RA.isvec) i++;
1483 if (RAupdate.isvec) u++;
1484 if (RT.isvec) j++;
1485 ```
1486
1487 Indexed LD is:
1488
1489 ```
1490 # format: ldop RT, RA, RB
1491 function op_ldx(RT, RA, RB, RAupdate=False) # LD not VLD!
1492  ps = get_pred_val(FALSE, RA); # predication on src
1493  pd = get_pred_val(FALSE, RT); # ... AND on dest
1494  for (i=0, j=0, k=0, u=0; i < VL && j < VL && k < VL):
1495 # skip nonpredicated RA, RB and RT
1496 if (RA.isvec) while (!(ps & 1<<i)) i++;
1497 if (RAupdate.isvec) while (!(ps & 1<<u)) u++;
1498 if (RB.isvec) while (!(ps & 1<<k)) k++;
1499 if (RT.isvec) while (!(pd & 1<<j)) j++;
1500 if svctx.ldstmode == elementstride:
1501 EA = ireg[RA] + ireg[RB]*j # register-strided
1502 else
1503 EA = ireg[RA+i] + ireg[RB+k] # indexed address
1504 if RAupdate: ireg[RAupdate+u] = EA
1505 ireg[RT+j] <= MEM[EA];
1506 if (!RT.isvec)
1507 break # destination scalar, end immediately
1508 if (RA.isvec) i++;
1509 if (RAupdate.isvec) u++;
1510 if (RB.isvec) k++;
1511 if (RT.isvec) j++;
1512 ```
1513
1514 Note that Element-Strided uses the Destination Step because with both
1515 sources being Scalar as a prerequisite condition of activation of
1516 Element-Stride Mode, the source step (being Scalar) would never advance.
1517
1518 Note in both cases that [[sv/svp64]] allows RA-as-a-dest in "update"
1519 mode (`ldux`) to be effectively a *completely different* register from
1520 RA-as-a-source. This because there is room in svp64 to extend RA-as-src
1521 as well as RA-as-dest, both independently as scalar or vector *and*
1522 independently extending their range.
1523
1524 *Programmer's note: being able to set RA-as-a-source as separate from
1525 RA-as-a-destination as Scalar is **extremely valuable** once it is
1526 remembered that Simple-V element operations must be in Program Order,
1527 especially in loops, for saving on multiple address computations. Care
1528 does have to be taken however that RA-as-src is not overwritten by
1529 RA-as-dest unless intentionally desired, especially in element-strided
1530 Mode.*
1531
1532 ## LD/ST Indexed vs Indexed REMAP
1533
1534 Unfortunately the word "Indexed" is used twice in completely different
1535 contexts, potentially causing confusion.
1536
1537 * There has existed instructions in the Power ISA `ld RT,RA,RB` since
1538 its creation: these are called "LD/ST Indexed" instructions and their
1539 name and meaning is well-established.
1540 * There now exists, in Simple-V, a REMAP mode called "Indexed"
1541 Mode that can be applied to *any* instruction **including those
1542 named LD/ST Indexed**.
1543
1544 Whilst it may be costly in terms of register reads to allow REMAP Indexed
1545 Mode to be applied to any Vectorised LD/ST Indexed operation such as
1546 `sv.ld *RT,RA,*RB`, or even misleadingly labelled as redundant, firstly
1547 the strict application of the RISC Paradigm that Simple-V follows makes
1548 it awkward to consider *preventing* the application of Indexed REMAP to
1549 such operations, and secondly they are not actually the same at all.
1550
1551 Indexed REMAP, as applied to RB in the instruction `sv.ld *RT,RA,*RB`
1552 effectively performs an *in-place* re-ordering of the offsets, RB.
1553 To achieve the same effect without Indexed REMAP would require taking
1554 a *copy* of the Vector of offsets starting at RB, manually explicitly
1555 reordering them, and finally using the copy of re-ordered offsets in a
1556 non-REMAP'ed `sv.ld`. Using non-strided LD as an example, pseudocode
1557 showing what actually occurs, where the pseudocode for `indexed_remap`
1558 may be found in [[sv/remap]]:
1559
1560 ```
1561 # sv.ld *RT,RA,*RB with Index REMAP applied to RB
1562 for i in 0..VL-1:
1563 if remap.indexed:
1564 rb_idx = indexed_remap(i) # remap
1565 else:
1566 rb_idx = i # use the index as-is
1567 EA = GPR(RA) + GPR(RB+rb_idx)
1568 GPR(RT+i) = MEM(EA, 8)
1569 ```
1570
1571 Thus it can be seen that the use of Indexed REMAP saves copying
1572 and manual reordering of the Vector of RB offsets.
1573
1574 ## LD/ST ffirst
1575
1576 LD/ST ffirst treats the first LD/ST in a vector (element 0 if REMAP
1577 is not active) as an ordinary one, with all behaviour with respect to
1578 Interrupts Exceptions Page Faults Memory Management being identical
1579 in every regard to Scalar v3.0 Power ISA LD/ST. However for elements
1580 1 and above, if an exception would occur, then VL is **truncated**
1581 to the previous element: the exception is **not** then raised because
1582 the LD/ST that would otherwise have caused an exception is *required*
1583 to be cancelled. Additionally an implementor may choose to truncate VL
1584 for any arbitrary reason *except for the very first*.
1585
1586 ffirst LD/ST to multiple pages via a Vectorised Index base is
1587 considered a security risk due to the abuse of probing multiple
1588 pages in rapid succession and getting speculative feedback on which
1589 pages would fail. Therefore Vector Indexed LD/ST is prohibited
1590 entirely, and the Mode bit instead used for element-strided LD/ST.
1591
1592 ```
1593 for(i = 0; i < VL; i++)
1594 reg[rt + i] = mem[reg[ra] + i * reg[rb]];
1595 ```
1596
1597 High security implementations where any kind of speculative probing of
1598 memory pages is considered a risk should take advantage of the fact
1599 that implementations may truncate VL at any point, without requiring
1600 software to be rewritten and made non-portable. Such implementations may
1601 choose to *always* set VL=1 which will have the effect of terminating
1602 any speculative probing (and also adversely affect performance), but
1603 will at least not require applications to be rewritten.
1604
1605 Low-performance simpler hardware implementations may also choose (always)
1606 to also set VL=1 as the bare minimum compliant implementation of LD/ST
1607 Fail-First. It is however critically important to remember that the first
1608 element LD/ST **MUST** be treated as an ordinary LD/ST, i.e. **MUST**
1609 raise exceptions exactly like an ordinary LD/ST.
1610
1611 For ffirst LD/STs, VL may be truncated arbitrarily to a nonzero value
1612 for any implementation-specific reason. For example: it is perfectly
1613 reasonable for implementations to alter VL when ffirst LD or ST operations
1614 are initiated on a nonaligned boundary, such that within a loop the
1615 subsequent iteration of that loop begins the following ffirst LD/ST
1616 operations on an aligned boundary such as the beginning of a cache line,
1617 or beginning of a Virtual Memory page. Likewise, to reduce workloads or
1618 balance resources.
1619
1620 Vertical-First Mode is slightly strange in that only one element at a time
1621 is ever executed anyway. Given that programmers may legitimately choose
1622 to alter srcstep and dststep in non-sequential order as part of explicit
1623 loops, it is neither possible nor safe to make speculative assumptions
1624 about future LD/STs. Therefore, Fail-First LD/ST in Vertical-First is
1625 `UNDEFINED`. This is very different from Arithmetic (Data-dependent)
1626 FFirst where Vertical-First Mode is fully deterministic, not speculative.
1627
1628 ## LOAD/STORE Elwidths <a name="elwidth"></a>
1629
1630 Loads and Stores are almost unique in that the Power Scalar ISA
1631 provides a width for the operation (lb, lh, lw, ld). Only `extsb` and
1632 others like it provide an explicit operation width. There are therefore
1633 *three* widths involved:
1634
1635 * operation width (lb=8, lh=16, lw=32, ld=64)
1636 * src element width override (8/16/32/default)
1637 * destination element width override (8/16/32/default)
1638
1639 Some care is therefore needed to express and make clear the transformations,
1640 which are expressly in this order:
1641
1642 * Calculate the Effective Address from RA at full width
1643 but (on Indexed Load) allow srcwidth overrides on RB
1644 * Load at the operation width (lb/lh/lw/ld) as usual
1645 * byte-reversal as usual
1646 * Non-saturated mode:
1647 - zero-extension or truncation from operation width to dest elwidth
1648 - place result in destination at dest elwidth
1649 * Saturated mode:
1650 - Sign-extension or truncation from operation width to dest width
1651 - signed/unsigned saturation down to dest elwidth
1652
1653 In order to respect Power v3.0B Scalar behaviour the memory side
1654 is treated effectively as completely separate and distinct from SV
1655 augmentation. This is primarily down to quirks surrounding LE/BE and
1656 byte-reversal.
1657
1658 It is rather unfortunately possible to request an elwidth override on
1659 the memory side which does not mesh with the overridden operation width:
1660 these result in `UNDEFINED` behaviour. The reason is that the effect
1661 of attempting a 64-bit `sv.ld` operation with a source elwidth override
1662 of 8/16/32 would result in overlapping memory requests, particularly
1663 on unit and element strided operations. Thus it is `UNDEFINED` when
1664 the elwidth is smaller than the memory operation width. Examples include
1665 `sv.lw/sw=16/els` which requests (overlapping) 4-byte memory reads offset
1666 from each other at 2-byte intervals. Store likewise is also `UNDEFINED`
1667 where the dest elwidth override is less than the operation width.
1668
1669 Note the following regarding the pseudocode to follow:
1670
1671 * `scalar identity behaviour` SV Context parameter conditions turn this
1672 into a straight absolute fully-compliant Scalar v3.0B LD operation
1673 * `brev` selects whether the operation is the byte-reversed variant (`ldbrx`
1674 rather than `ld`)
1675 * `op_width` specifies the operation width (`lb`, `lh`, `lw`, `ld`) as
1676 a "normal" part of Scalar v3.0B LD
1677 * `imm_offs` specifies the immediate offset `ld r3, imm_offs(r5)`, again
1678 as a "normal" part of Scalar v3.0B LD
1679 * `svctx` specifies the SV Context and includes VL as well as
1680 source and destination elwidth overrides.
1681
1682 Below is the pseudocode for Unit-Strided LD (which includes Vector
1683 capability). Observe in particular that RA, as the base address in both
1684 Immediate and Indexed LD/ST, does not have element-width overriding
1685 applied to it.
1686
1687 Note that predication, predication-zeroing, and other modes except
1688 saturation have all been removed, for clarity and simplicity:
1689
1690 ```
1691 # LD not VLD!
1692 # this covers unit stride mode and a type of vector offset
1693 function op_ld(RT, RA, op_width, imm_offs, svctx)
1694 for (int i = 0, int j = 0; i < svctx.VL && j < svctx.VL):
1695 if not svctx.unit/el-strided:
1696 # strange vector mode, compute 64 bit address which is
1697 # not polymorphic! elwidth hardcoded to 64 here
1698 srcbase = get_polymorphed_reg(RA, 64, i)
1699 else:
1700 # unit / element stride mode, compute 64 bit address
1701 srcbase = get_polymorphed_reg(RA, 64, 0)
1702 # adjust for unit/el-stride
1703 srcbase += ....
1704
1705 # read the underlying memory
1706 memread <= MEM(srcbase + imm_offs, op_width)
1707
1708 # check saturation.
1709 if svpctx.saturation_mode:
1710 # ... saturation adjustment...
1711 memread = clamp(memread, op_width, svctx.dest_elwidth)
1712 else:
1713 # truncate/extend to over-ridden dest width.
1714 memread = adjust_wid(memread, op_width, svctx.dest_elwidth)
1715
1716 # takes care of inserting memory-read (now correctly byteswapped)
1717 # into regfile underlying LE-defined order, into the right place
1718 # within the NEON-like register, respecting destination element
1719 # bitwidth, and the element index (j)
1720 set_polymorphed_reg(RT, svctx.dest_elwidth, j, memread)
1721
1722 # increments both src and dest element indices (no predication here)
1723 i++;
1724 j++;
1725 ```
1726
1727 Note above that the source elwidth is *not used at all* in LD-immediate.
1728
1729 For LD/Indexed, the key is that in the calculation of the Effective Address,
1730 RA has no elwidth override but RB does. Pseudocode below is simplified
1731 for clarity: predication and all modes except saturation are removed:
1732
1733 ```
1734 # LD not VLD! ld*rx if brev else ld*
1735 function op_ld(RT, RA, RB, op_width, svctx, brev)
1736 for (int i = 0, int j = 0; i < svctx.VL && j < svctx.VL):
1737 if not svctx.el-strided:
1738 # RA not polymorphic! elwidth hardcoded to 64 here
1739 srcbase = get_polymorphed_reg(RA, 64, i)
1740 else:
1741 # element stride mode, again RA not polymorphic
1742 srcbase = get_polymorphed_reg(RA, 64, 0)
1743 # RB *is* polymorphic
1744 offs = get_polymorphed_reg(RB, svctx.src_elwidth, i)
1745 # sign-extend
1746 if svctx.SEA: offs = sext(offs, svctx.src_elwidth, 64)
1747
1748 # takes care of (merges) processor LE/BE and ld/ldbrx
1749 bytereverse = brev XNOR MSR.LE
1750
1751 # read the underlying memory
1752 memread <= MEM(srcbase + offs, op_width)
1753
1754 # optionally performs byteswap at op width
1755 if (bytereverse):
1756 memread = byteswap(memread, op_width)
1757
1758 if svpctx.saturation_mode:
1759 # ... saturation adjustment...
1760 memread = clamp(memread, op_width, svctx.dest_elwidth)
1761 else:
1762 # truncate/extend to over-ridden dest width.
1763 memread = adjust_wid(memread, op_width, svctx.dest_elwidth)
1764
1765 # takes care of inserting memory-read (now correctly byteswapped)
1766 # into regfile underlying LE-defined order, into the right place
1767 # within the NEON-like register, respecting destination element
1768 # bitwidth, and the element index (j)
1769 set_polymorphed_reg(RT, svctx.dest_elwidth, j, memread)
1770
1771 # increments both src and dest element indices (no predication here)
1772 i++;
1773 j++;
1774 ```
1775
1776 ## Remapped LD/ST
1777
1778 In the [[sv/remap]] page the concept of "Remapping" is described. Whilst
1779 it is expensive to set up (2 64-bit opcodes minimum) it provides a way to
1780 arbitrarily perform 1D, 2D and 3D "remapping" of up to 64 elements worth
1781 of LDs or STs. The usual interest in such re-mapping is for example in
1782 separating out 24-bit RGB channel data into separate contiguous registers.
1783
1784 REMAP easily covers this capability, and with dest elwidth overrides
1785 and saturation may do so with built-in conversion that would normally
1786 require additional width-extension, sign-extension and min/max Vectorised
1787 instructions as post-processing stages.
1788
1789 Thus we do not need to provide specialist LD/ST "Structure Packed" opcodes
1790 because the generic abstracted concept of "Remapping", when applied to
1791 LD/ST, will give that same capability, with far more flexibility.
1792
1793 It is worth noting that Pack/Unpack Modes of SVSTATE, which may be
1794 established through `svstep`, are also an easy way to perform regular
1795 Structure Packing, at the vec2/vec3/vec4 granularity level. Beyond that,
1796 REMAP will need to be used.
1797
1798 --------
1799
1800 \newpage{}
1801
1802 # Condition Register SVP64 Operations
1803
1804 Condition Register Fields are only 4 bits wide: this presents some
1805 interesting conceptual challenges for SVP64, which was designed
1806 primarily for vectors of arithmetic and logical operations. However
1807 if predicates may be bits of CR Fields it makes sense to extend
1808 Simple-V to cover CR Operations, especially given that Vectorised Rc=1
1809 may be processed by Vectorised CR Operations tbat usefully in turn
1810 may become Predicate Masks to yet more Vector operations, like so:
1811
1812 ```
1813 sv.cmpi/ew=8 *B,*ra,0 # compare bytes against zero
1814 sv.cmpi/ew=8 *B2,*ra,13. # and against newline
1815 sv.cror PM.EQ,B.EQ,B2.EQ # OR compares to create mask
1816 sv.stb/sm=EQ ... # store only nonzero/newline
1817 ```
1818
1819 Element width however is clearly meaningless for a 4-bit collation of
1820 Conditions, EQ LT GE SO. Likewise, arithmetic saturation (an important
1821 part of Arithmetic SVP64) has no meaning. An alternative Mode Format is
1822 required, and given that elwidths are meaningless for CR Fields the bits
1823 in SVP64 `RM` may be used for other purposes.
1824
1825 This alternative mapping **only** applies to instructions that **only**
1826 reference a CR Field or CR bit as the sole exclusive result. This section
1827 **does not** apply to instructions which primarily produce arithmetic
1828 results that also, as an aside, produce a corresponding CR Field (such as
1829 when Rc=1). Instructions that involve Rc=1 are definitively arithmetic
1830 in nature, where the corresponding Condition Register Field can be
1831 considered to be a "co-result". Such CR Field "co-result" arithmeric
1832 operations are firmly out of scope for this section, being covered fully
1833 by [[sv/normal]].
1834
1835 * Examples of v3.0B instructions to which this section does
1836 apply is
1837 - `mfcr` and `cmpi` (3 bit operands) and
1838 - `crnor` and `crand` (5 bit operands).
1839 * Examples to which this section does **not** apply include
1840 `fadds.` and `subf.` which both produce arithmetic results
1841 (and a CR Field co-result).
1842
1843 The CR Mode Format still applies to `sv.cmpi` because despite
1844 taking a GPR as input, the output from the Base Scalar v3.0B `cmpi`
1845 instruction is purely to a Condition Register Field.
1846
1847 Other modes are still applicable and include:
1848
1849 * **Data-dependent fail-first**.
1850 useful to truncate VL based on analysis of a Condition Register result bit.
1851 * **Reduction**.
1852 Reduction is useful for analysing a Vector of Condition Register Fields
1853 and reducing it to one single Condition Register Field.
1854
1855 Predicate-result does not make any sense because when Rc=1 a co-result
1856 is created (a CR Field). Testing the co-result allows the decision to
1857 be made to store or not store the main result, and for CR Ops the CR
1858 Field result *is* the main result.
1859
1860 ## Format
1861
1862 SVP64 RM `MODE` (includes `ELWIDTH_SRC` bits) for CR-based operations:
1863
1864 |6 | 7 |19-20| 21 | 22 23 | description |
1865 |--|---|-----| --- |---------|----------------- |
1866 |/ | / |0 RG | 0 | dz sz | simple mode |
1867 |/ | / |0 RG | 1 | dz sz | scalar reduce mode (mapreduce) |
1868 |zz|SNZ|1 VLI| inv | CR-bit | Ffirst 3-bit mode |
1869 |/ |SNZ|1 VLI| inv | dz sz | Ffirst 5-bit mode (implies CR-bit from result) |
1870
1871 Fields:
1872
1873 * **sz / dz** if predication is enabled will put zeros into the dest
1874 (or as src in the case of twin pred) when the predicate bit is zero.
1875 otherwise the element is ignored or skipped, depending on context.
1876 * **zz** set both sz and dz equal to this flag
1877 * **SNZ** In fail-first mode, on the bit being tested, when sz=1 and
1878 SNZ=1 a value "1" is put in place of "0".
1879 * **inv CR-bit** just as in branches (BO) these bits allow testing of
1880 a CR bit and whether it is set (inv=0) or unset (inv=1)
1881 * **RG** inverts the Vector Loop order (VL-1 downto 0) rather
1882 than the normal 0..VL-1
1883 * **SVM** sets "subvector" reduce mode
1884 * **VLi** VL inclusive: in fail-first mode, the truncation of
1885 VL *includes* the current element at the failure point rather
1886 than excludes it from the count.
1887
1888 ## Data-dependent fail-first on CR operations
1889
1890 The principle of data-dependent fail-first is that if, during the course
1891 of sequentially evaluating an element's Condition Test, one such test
1892 is encountered which fails, then VL (Vector Length) is truncated (set)
1893 at that point. In the case of Arithmetic SVP64 Operations the Condition
1894 Register Field generated from Rc=1 is used as the basis for the truncation
1895 decision. However with CR-based operations that CR Field result to be
1896 tested is provided *by the operation itself*.
1897
1898 Data-dependent SVP64 Vectorised Operations involving the creation
1899 or modification of a CR can require an extra two bits, which are not
1900 available in the compact space of the SVP64 RM `MODE` Field. With the
1901 concept of element width overrides being meaningless for CR Fields it
1902 is possible to use the `ELWIDTH` field for alternative purposes.
1903
1904 Condition Register based operations such as `sv.mfcr` and `sv.crand`
1905 can thus be made more flexible. However the rules that apply in this
1906 section also apply to future CR-based instructions.
1907
1908 There are two primary different types of CR operations:
1909
1910 * Those which have a 3-bit operand field (referring to a CR Field)
1911 * Those which have a 5-bit operand (referring to a bit within the
1912 whole 32-bit CR)
1913
1914 Examining these two types it is observed that the difference may
1915 be considered to be that the 5-bit variant *already* provides the
1916 prerequisite information about which CR Field bit (EQ, GE, LT, SO) is
1917 to be operated on by the instruction. Thus, logically, we may set the
1918 following rule:
1919
1920 * When a 5-bit CR Result field is used in an instruction, the
1921 5-bit variant of Data-Dependent Fail-First
1922 must be used. i.e. the bit of the CR field to be tested is
1923 the one that has just been modified (created) by the operation.
1924 * When a 3-bit CR Result field is used the 3-bit variant
1925 must be used, providing as it does the missing `CRbit` field
1926 in order to select which CR Field bit of the result shall
1927 be tested (EQ, LE, GE, SO)
1928
1929 The reason why the 3-bit CR variant needs the additional CR-bit field
1930 should be obvious from the fact that the 3-bit CR Field from the base
1931 Power ISA v3.0B operation clearly does not contain and is missing the
1932 two CR Field Selector bits. Thus, these two bits (to select EQ, LE,
1933 GE or SO) must be provided in another way.
1934
1935 Examples of the former type:
1936
1937 * crand, cror, crnor. These all are 5-bit (BA, BB, BT). The bit
1938 to be tested against `inv` is the one selected by `BT`
1939 * mcrf. This has only 3-bit (BF, BFA). In order to select the
1940 bit to be tested, the alternative encoding must be used.
1941 With `CRbit` coming from the SVP64 RM bits 22-23 the bit
1942 of BF to be tested is identified.
1943
1944 Just as with SVP64 [[sv/branches]] there is the option to truncate
1945 VL to include the element being tested (`VLi=1`) and to exclude it
1946 (`VLi=0`).
1947
1948 Also exactly as with [[sv/normal]] fail-first, VL cannot, unlike
1949 [[sv/ldst]], be set to an arbitrary value. Deterministic behaviour
1950 is *required*.
1951
1952 ## Reduction and Iteration
1953
1954 Bearing in mind as described in the svp64 Appendix, SVP64 Horizontal
1955 Reduction is a deterministic schedule on top of base Scalar v3.0
1956 operations, the same rules apply to CR Operations, i.e. that programmers
1957 must follow certain conventions in order for an *end result* of a
1958 reduction to be achieved. Unlike other Vector ISAs *there are no explicit
1959 reduction opcodes* in SVP64: Schedules however achieve the same effect.
1960
1961 Due to these conventions only reduction on operations such as `crand`
1962 and `cror` are meaningful because these have Condition Register Fields
1963 as both input and output. Meaningless operations are not prohibited
1964 because the cost in hardware of doing so is prohibitive, but neither
1965 are they `UNDEFINED`. Implementations are still required to execute them
1966 but are at liberty to optimise out any operations that would ultimately
1967 be overwritten, as long as Strict Program Order is still obvservable by
1968 the programmer.
1969
1970 Also bear in mind that 'Reverse Gear' may be enabled, which can be
1971 used in combination with overlapping CR operations to iteratively
1972 accumulate results. Issuing a `sv.crand` operation for example with
1973 `BA` differing from `BB` by one Condition Register Field would result
1974 in a cascade effect, where the first-encountered CR Field would set the
1975 result to zero, and also all subsequent CR Field elements thereafter:
1976
1977 ```
1978 # sv.crand/mr/rg CR4.ge.v, CR5.ge.v, CR4.ge.v
1979 for i in VL-1 downto 0 # reverse gear
1980 CR.field[4+i].ge &= CR.field[5+i].ge
1981 ```
1982
1983 `sv.crxor` with reduction would be particularly useful for parity
1984 calculation for example, although there are many ways in which the same
1985 calculation could be carried out after transferring a vector of CR Fields
1986 to a GPR using crweird operations.
1987
1988 Implementations are free and clear to optimise these reductions in any way
1989 they see fit, as long as the end-result is compatible with Strict Program
1990 Order being observed, and Interrupt latency is not adversely impacted.
1991
1992 ## Unusual and quirky CR operations
1993
1994 **cmp and other compare ops**
1995
1996 `cmp` and `cmpi` etc take GPRs as sources and create a CR Field as a result.
1997
1998 cmpli BF,L,RA,UI
1999 cmpeqb BF,RA,RB
2000
2001 With `ELWIDTH` applying to the source GPR operands this is perfectly fine.
2002
2003 **crweird operations**
2004
2005 There are 4 weird CR-GPR operations and one reasonable one in
2006 the [[cr_int_predication]] set:
2007
2008 * crrweird
2009 * mtcrweird
2010 * crweirder
2011 * crweird
2012 * mcrfm - reasonably normal and referring to CR Fields for src and dest.
2013
2014 The "weird" operations have a non-standard behaviour, being able to
2015 treat *individual bits* of a GPR effectively as elements. They are
2016 expected to be Micro-coded by most Hardware implementations.
2017
2018
2019 --------
2020
2021 \newpage{}
2022
2023 # SVP64 Branch Conditional behaviour
2024
2025 Please note: although similar, SVP64 Branch instructions should be
2026 considered completely separate and distinct from standard scalar
2027 OpenPOWER-approved v3.0B branches. **v3.0B branches are in no way
2028 impacted, altered, changed or modified in any way, shape or form by the
2029 SVP64 Vectorised Variants**.
2030
2031 It is also extremely important to note that Branches are the sole
2032 pseudo-exception in SVP64 to `Scalar Identity Behaviour`. SVP64 Branches
2033 contain additional modes that are useful for scalar operations (i.e. even
2034 when VL=1 or when using single-bit predication).
2035
2036 **Rationale**
2037
2038 Scalar 3.0B Branch Conditional operations, `bc`, `bctar` etc. test
2039 a Condition Register. However for parallel processing it is simply
2040 impossible to perform multiple independent branches: the Program
2041 Counter simply cannot branch to multiple destinations based on multiple
2042 conditions. The best that can be done is to test multiple Conditions
2043 and make a decision of a *single* branch, based on analysis of a *Vector*
2044 of CR Fields which have just been calculated from a *Vector* of results.
2045
2046 In 3D Shader binaries, which are inherently parallelised and predicated,
2047 testing all or some results and branching based on multiple tests is
2048 extremely common, and a fundamental part of Shader Compilers. Example:
2049 without such multi-condition test-and-branch, if a predicate mask is
2050 all zeros a large batch of instructions may be masked out to `nop`,
2051 and it would waste CPU cycles to run them. 3D GPU ISAs can test for
2052 this scenario and, with the appropriate predicate-analysis instruction,
2053 jump over fully-masked-out operations, by spotting that *all* Conditions
2054 are false.
2055
2056 Unless Branches are aware and capable of such analysis, additional
2057 instructions would be required which perform Horizontal Cumulative
2058 analysis of Vectorised Condition Register Fields, in order to reduce
2059 the Vector of CR Fields down to one single yes or no decision that a
2060 Scalar-only v3.0B Branch-Conditional could cope with. Such instructions
2061 would be unavoidable, required, and costly by comparison to a single
2062 Vector-aware Branch. Therefore, in order to be commercially competitive,
2063 `sv.bc` and other Vector-aware Branch Conditional instructions are a
2064 high priority for 3D GPU (and OpenCL-style) workloads.
2065
2066 Given that Power ISA v3.0B is already quite powerful, particularly
2067 the Condition Registers and their interaction with Branches, there are
2068 opportunities to create extremely flexible and compact Vectorised Branch
2069 behaviour. In addition, the side-effects (updating of CTR, truncation
2070 of VL, described below) make it a useful instruction even if the branch
2071 points to the next instruction (no actual branch).
2072
2073 ## Overview
2074
2075 When considering an "array" of branch-tests, there are four
2076 primarily-useful modes: AND, OR, NAND and NOR of all Conditions.
2077 NAND and NOR may be synthesised from AND and OR by inverting `BO[1]`
2078 which just leaves two modes:
2079
2080 * Branch takes place on the **first** CR Field test to succeed
2081 (a Great Big OR of all condition tests). Exit occurs
2082 on the first **successful** test.
2083 * Branch takes place only if **all** CR field tests succeed:
2084 a Great Big AND of all condition tests. Exit occurs
2085 on the first **failed** test.
2086
2087 Early-exit is enacted such that the Vectorised Branch does not
2088 perform needless extra tests, which will help reduce reads on
2089 the Condition Register file.
2090
2091 *Note: Early-exit is **MANDATORY** (required) behaviour. Branches
2092 **MUST** exit at the first sequentially-encountered failure point,
2093 for exactly the same reasons for which it is mandatory in programming
2094 languages doing early-exit: to avoid damaging side-effects and to provide
2095 deterministic behaviour. Speculative testing of Condition Register
2096 Fields is permitted, as is speculative calculation of CTR, as long as,
2097 as usual in any Out-of-Order microarchitecture, that speculative testing
2098 is cancelled should an early-exit occur. i.e. the speculation must be
2099 "precise": Program Order must be preserved*
2100
2101 Also note that when early-exit occurs in Horizontal-first Mode, srcstep,
2102 dststep etc. are all reset, ready to begin looping from the beginning
2103 for the next instruction. However for Vertical-first Mode srcstep
2104 etc. are incremented "as usual" i.e. an early-exit has no special impact,
2105 regardless of whether the branch occurred or not. This can leave srcstep
2106 etc. in what may be considered an unusual state on exit from a loop and
2107 it is up to the programmer to reset srcstep, dststep etc. to known-good
2108 values *(easily achieved with `setvl`)*.
2109
2110 Additional useful behaviour involves two primary Modes (both of which
2111 may be enabled and combined):
2112
2113 * **VLSET Mode**: identical to Data-Dependent Fail-First Mode
2114 for Arithmetic SVP64 operations, with more
2115 flexibility and a close interaction and integration into the
2116 underlying base Scalar v3.0B Branch instruction.
2117 Truncation of VL takes place around the early-exit point.
2118 * **CTR-test Mode**: gives much more flexibility over when and why
2119 CTR is decremented, including options to decrement if a Condition
2120 test succeeds *or if it fails*.
2121
2122 With these side-effects, basic Boolean Logic Analysis advises that it
2123 is important to provide a means to enact them each based on whether
2124 testing succeeds *or fails*. This results in a not-insignificant number
2125 of additional Mode Augmentation bits, accompanying VLSET and CTR-test
2126 Modes respectively.
2127
2128 Predicate skipping or zeroing may, as usual with SVP64, be controlled by
2129 `sz`. Where the predicate is masked out and zeroing is enabled, then in
2130 such circumstances the same Boolean Logic Analysis dictates that rather
2131 than testing only against zero, the option to test against one is also
2132 prudent. This introduces a new immediate field, `SNZ`, which works in
2133 conjunction with `sz`.
2134
2135 Vectorised Branches can be used in either SVP64 Horizontal-First or
2136 Vertical-First Mode. Essentially, at an element level, the behaviour
2137 is identical in both Modes, although the `ALL` bit is meaningless in
2138 Vertical-First Mode.
2139
2140 It is also important to bear in mind that, fundamentally, Vectorised
2141 Branch-Conditional is still extremely close to the Scalar v3.0B
2142 Branch-Conditional instructions, and that the same v3.0B Scalar
2143 Branch-Conditional instructions are still *completely separate and
2144 independent*, being unaltered and unaffected by their SVP64 variants in
2145 every conceivable way.
2146
2147 *Programming note: One important point is that SVP64 instructions are
2148 64 bit. (8 bytes not 4). This needs to be taken into consideration
2149 when computing branch offsets: the offset is relative to the start of
2150 the instruction, which **includes** the SVP64 Prefix*
2151
2152 ## Format and fields
2153
2154 With element-width overrides being meaningless for Condition Register
2155 Fields, bits 4 thru 7 of SVP64 RM may be used for additional Mode bits.
2156
2157 SVP64 RM `MODE` (includes repurposing `ELWIDTH` bits 4:5, and
2158 `ELWIDTH_SRC` bits 6-7 for *alternate* uses) for Branch Conditional:
2159
2160 | 4 | 5 | 6 | 7 | 17 | 18 | 19 | 20 | 21 | 22 23 | description |
2161 | - | - | - | - | -- | -- | -- | -- | --- |--------|----------------- |
2162 |ALL|SNZ| / | / | SL |SLu | 0 | 0 | / | LRu sz | simple mode |
2163 |ALL|SNZ| / |VSb| SL |SLu | 0 | 1 | VLI | LRu sz | VLSET mode |
2164 |ALL|SNZ|CTi| / | SL |SLu | 1 | 0 | / | LRu sz | CTR-test mode |
2165 |ALL|SNZ|CTi|VSb| SL |SLu | 1 | 1 | VLI | LRu sz | CTR-test+VLSET mode |
2166
2167 Brief description of fields:
2168
2169 * **sz=1** if predication is enabled and `sz=1` and a predicate
2170 element bit is zero, `SNZ` will
2171 be substituted in place of the CR bit selected by `BI`,
2172 as the Condition tested.
2173 Contrast this with
2174 normal SVP64 `sz=1` behaviour, where *only* a zero is put in
2175 place of masked-out predicate bits.
2176 * **sz=0** When `sz=0` skipping occurs as usual on
2177 masked-out elements, but unlike all
2178 other SVP64 behaviour which entirely skips an element with
2179 no related side-effects at all, there are certain
2180 special circumstances where CTR
2181 may be decremented. See CTR-test Mode, below.
2182 * **ALL** when set, all branch conditional tests must pass in order for
2183 the branch to succeed. When clear, it is the first sequentially
2184 encountered successful test that causes the branch to succeed.
2185 This is identical behaviour to how programming languages perform
2186 early-exit on Boolean Logic chains.
2187 * **VLI** VLSET is identical to Data-dependent Fail-First mode.
2188 In VLSET mode, VL *may* (depending on `VSb`) be truncated.
2189 If VLI (Vector Length Inclusive) is clear,
2190 VL is truncated to *exclude* the current element, otherwise it is
2191 included. SVSTATE.MVL is not altered: only VL.
2192 * **SL** identical to `LR` except applicable to SVSTATE. If `SL`
2193 is set, SVSTATE is transferred to SVLR (conditionally on
2194 whether `SLu` is set).
2195 * **SLu**: SVSTATE Link Update, like `LRu` except applies to SVSTATE.
2196 * **LRu**: Link Register Update, used in conjunction with LK=1
2197 to make LR update conditional
2198 * **VSb** In VLSET Mode, after testing,
2199 if VSb is set, VL is truncated if the test succeeds. If VSb is clear,
2200 VL is truncated if a test *fails*. Masked-out (skipped)
2201 bits are not considered
2202 part of testing when `sz=0`
2203 * **CTi** CTR inversion. CTR-test Mode normally decrements per element
2204 tested. CTR inversion decrements if a test *fails*. Only relevant
2205 in CTR-test Mode.
2206
2207 LRu and CTR-test modes are where SVP64 Branches subtly differ from
2208 Scalar v3.0B Branches. `sv.bcl` for example will always update LR,
2209 whereas `sv.bcl/lru` will only update LR if the branch succeeds.
2210
2211 Of special interest is that when using ALL Mode (Great Big AND of all
2212 Condition Tests), if `VL=0`, which is rare but can occur in Data-Dependent
2213 Modes, the Branch will always take place because there will be no failing
2214 Condition Tests to prevent it. Likewise when not using ALL Mode (Great
2215 Big OR of all Condition Tests) and `VL=0` the Branch is guaranteed not
2216 to occur because there will be no *successful* Condition Tests to make
2217 it happen.
2218
2219 ## Vectorised CR Field numbering, and Scalar behaviour
2220
2221 It is important to keep in mind that just like all SVP64 instructions,
2222 the `BI` field of the base v3.0B Branch Conditional instruction may be
2223 extended by SVP64 EXTRA augmentation, as well as be marked as either
2224 Scalar or Vector. It is also crucially important to keep in mind that for
2225 CRs, SVP64 sequentially increments the CR *Field* numbers. CR *Fields*
2226 are treated as elements, not bit-numbers of the CR *register*.
2227
2228 The `BI` operand of Branch Conditional operations is five bits, in scalar
2229 v3.0B this would select one bit of the 32 bit CR, comprising eight CR
2230 Fields of 4 bits each. In SVP64 there are 16 32 bit CRs, containing
2231 128 4-bit CR Fields. Therefore, the 2 LSBs of `BI` select the bit from
2232 the CR Field (EQ LT GT SO), and the top 3 bits are extended to either
2233 scalar or vector and to select CR Fields 0..127 as specified in SVP64
2234 [[sv/svp64/appendix]].
2235
2236 When the CR Fields selected by SVP64-Augmented `BI` is marked as scalar,
2237 then as the usual SVP64 rules apply: the Vector loop ends at the first
2238 element tested (the first CR *Field*), after taking predication into
2239 consideration. Thus, also as usual, when a predicate mask is given, and
2240 `BI` marked as scalar, and `sz` is zero, srcstep skips forward to the
2241 first non-zero predicated element, and only that one element is tested.
2242
2243 In other words, the fact that this is a Branch Operation (instead of an
2244 arithmetic one) does not result, ultimately, in significant changes as
2245 to how SVP64 is fundamentally applied, except with respect to:
2246
2247 * the unique properties associated with conditionally
2248 changing the Program Counter (aka "a Branch"), resulting in early-out
2249 opportunities
2250 * CTR-testing
2251
2252 Both are outlined below, in later sections.
2253
2254 ## Horizontal-First and Vertical-First Modes
2255
2256 In SVP64 Horizontal-First Mode, the first failure in ALL mode (Great Big
2257 AND) results in early exit: no more updates to CTR occur (if requested);
2258 no branch occurs, and LR is not updated (if requested). Likewise for
2259 non-ALL mode (Great Big Or) on first success early exit also occurs,
2260 however this time with the Branch proceeding. In both cases the testing
2261 of the Vector of CRs should be done in linear sequential order (or in
2262 REMAP re-sequenced order): such that tests that are sequentially beyond
2263 the exit point are *not* carried out. (*Note: it is standard practice
2264 in Programming languages to exit early from conditional tests, however a
2265 little unusual to consider in an ISA that is designed for Parallel Vector
2266 Processing. The reason is to have strictly-defined guaranteed behaviour*)
2267
2268 In Vertical-First Mode, setting the `ALL` bit results in `UNDEFINED`
2269 behaviour. Given that only one element is being tested at a time in
2270 Vertical-First Mode, a test designed to be done on multiple bits is
2271 meaningless.
2272
2273 ## Description and Modes
2274
2275 Predication in both INT and CR modes may be applied to `sv.bc` and other
2276 SVP64 Branch Conditional operations, exactly as they may be applied to
2277 other SVP64 operations. When `sz` is zero, any masked-out Branch-element
2278 operations are not included in condition testing, exactly like all other
2279 SVP64 operations, *including* side-effects such as potentially updating
2280 LR or CTR, which will also be skipped. There is *one* exception here,
2281 which is when `BO[2]=0, sz=0, CTR-test=0, CTi=1` and the relevant element
2282 predicate mask bit is also zero: under these special circumstances CTR
2283 will also decrement.
2284
2285 When `sz` is non-zero, this normally requests insertion of a zero in
2286 place of the input data, when the relevant predicate mask bit is zero.
2287 This would mean that a zero is inserted in place of `CR[BI+32]` for
2288 testing against `BO`, which may not be desirable in all circumstances.
2289 Therefore, an extra field is provided `SNZ`, which, if set, will insert
2290 a **one** in place of a masked-out element, instead of a zero.
2291
2292 (*Note: Both options are provided because it is useful to deliberately
2293 cause the Branch-Conditional Vector testing to fail at a specific point,
2294 controlled by the Predicate mask. This is particularly useful in `VLSET`
2295 mode, which will truncate SVSTATE.VL at the point of the first failed
2296 test.*)
2297
2298 Normally, CTR mode will decrement once per Condition Test, resulting under
2299 normal circumstances that CTR reduces by up to VL in Horizontal-First
2300 Mode. Just as when v3.0B Branch-Conditional saves at least one instruction
2301 on tight inner loops through auto-decrementation of CTR, likewise it
2302 is also possible to save instruction count for SVP64 loops in both
2303 Vertical-First and Horizontal-First Mode, particularly in circumstances
2304 where there is conditional interaction between the element computation
2305 and testing, and the continuation (or otherwise) of a given loop. The
2306 potential combinations of interactions is why CTR testing options have
2307 been added.
2308
2309 Also, the unconditional bit `BO[0]` is still relevant when Predication
2310 is applied to the Branch because in `ALL` mode all nonmasked bits have
2311 to be tested, and when `sz=0` skipping occurs. Even when VLSET mode is
2312 not used, CTR may still be decremented by the total number of nonmasked
2313 elements, acting in effect as either a popcount or cntlz depending
2314 on which mode bits are set. In short, Vectorised Branch becomes an
2315 extremely powerful tool.
2316
2317 **Micro-Architectural Implementation Note**: *when implemented on top
2318 of a Multi-Issue Out-of-Order Engine it is possible to pass a copy of
2319 the predicate and the prerequisite CR Fields to all Branch Units, as
2320 well as the current value of CTR at the time of multi-issue, and for
2321 each Branch Unit to compute how many times CTR would be subtracted,
2322 in a fully-deterministic and parallel fashion. A SIMD-based Branch
2323 Unit, receiving and processing multiple CR Fields covered by multiple
2324 predicate bits, would do the exact same thing. Obviously, however, if
2325 CTR is modified within any given loop (mtctr) the behaviour of CTR is
2326 no longer deterministic.*
2327
2328 ### Link Register Update
2329
2330 For a Scalar Branch, unconditional updating of the Link Register LR
2331 is useful and practical. However, if a loop of CR Fields is tested,
2332 unconditional updating of LR becomes problematic.
2333
2334 For example when using `bclr` with `LRu=1,LK=0` in Horizontal-First Mode,
2335 LR's value will be unconditionally overwritten after the first element,
2336 such that for execution (testing) of the second element, LR has the value
2337 `CIA+8`. This is covered in the `bclrl` example, in a later section.
2338
2339 The addition of a LRu bit modifies behaviour in conjunction with LK,
2340 as follows:
2341
2342 * `sv.bc` When LRu=0,LK=0, Link Register is not updated
2343 * `sv.bcl` When LRu=0,LK=1, Link Register is updated unconditionally
2344 * `sv.bcl/lru` When LRu=1,LK=1, Link Register will
2345 only be updated if the Branch Condition fails.
2346 * `sv.bc/lru` When LRu=1,LK=0, Link Register will only be updated if
2347 the Branch Condition succeeds.
2348
2349 This avoids destruction of LR during loops (particularly Vertical-First
2350 ones).
2351
2352 **SVLR and SVSTATE**
2353
2354 For precisely the reasons why `LK=1` was added originally to the Power
2355 ISA, with SVSTATE being a peer of the Program Counter it becomes necessary
2356 to also add an SVLR (SVSTATE Link Register) and corresponding control bits
2357 `SL` and `SLu`.
2358
2359 ### CTR-test
2360
2361 Where a standard Scalar v3.0B branch unconditionally decrements CTR when
2362 `BO[2]` is clear, CTR-test Mode introduces more flexibility which allows
2363 CTR to be used for many more types of Vector loops constructs.
2364
2365 CTR-test mode and CTi interaction is as follows: note that `BO[2]`
2366 is still required to be clear for CTR decrements to be considered,
2367 exactly as is the case in Scalar Power ISA v3.0B
2368
2369 * **CTR-test=0, CTi=0**: CTR decrements on a per-element basis
2370 if `BO[2]` is zero. Masked-out elements when `sz=0` are
2371 skipped (i.e. CTR is *not* decremented when the predicate
2372 bit is zero and `sz=0`).
2373 * **CTR-test=0, CTi=1**: CTR decrements on a per-element basis
2374 if `BO[2]` is zero and a masked-out element is skipped
2375 (`sz=0` and predicate bit is zero). This one special case is the
2376 **opposite** of other combinations, as well as being
2377 completely different from normal SVP64 `sz=0` behaviour)
2378 * **CTR-test=1, CTi=0**: CTR decrements on a per-element basis
2379 if `BO[2]` is zero and the Condition Test succeeds.
2380 Masked-out elements when `sz=0` are skipped (including
2381 not decrementing CTR)
2382 * **CTR-test=1, CTi=1**: CTR decrements on a per-element basis
2383 if `BO[2]` is zero and the Condition Test *fails*.
2384 Masked-out elements when `sz=0` are skipped (including
2385 not decrementing CTR)
2386
2387 `CTR-test=0, CTi=1, sz=0` requires special emphasis because it is the
2388 only time in the entirety of SVP64 that has side-effects when
2389 a predicate mask bit is clear. **All** other SVP64 operations
2390 entirely skip an element when sz=0 and a predicate mask bit is zero.
2391 It is also critical to emphasise that in this unusual mode,
2392 no other side-effects occur: **only** CTR is decremented, i.e. the
2393 rest of the Branch operation is skipped.
2394
2395 ### VLSET Mode
2396
2397 VLSET Mode truncates the Vector Length so that subsequent instructions
2398 operate on a reduced Vector Length. This is similar to Data-dependent
2399 Fail-First and LD/ST Fail-First, where for VLSET the truncation occurs
2400 at the Branch decision-point.
2401
2402 Interestingly, due to the side-effects of `VLSET` mode it is actually
2403 useful to use Branch Conditional even to perform no actual branch
2404 operation, i.e to point to the instruction after the branch. Truncation of
2405 VL would thus conditionally occur yet control flow alteration would not.
2406
2407 `VLSET` mode with Vertical-First is particularly unusual. Vertical-First
2408 is designed to be used for explicit looping, where an explicit call to
2409 `svstep` is required to move both srcstep and dststep on to the next
2410 element, until VL (or other condition) is reached. Vertical-First Looping
2411 is expected (required) to terminate if the end of the Vector, VL, is
2412 reached. If however that loop is terminated early because VL is truncated,
2413 VLSET with Vertical-First becomes meaningless. Resolving this would
2414 require two branches: one Conditional, the other branching unconditionally
2415 to create the loop, where the Conditional one jumps over it.
2416
2417 Therefore, with `VSb`, the option to decide whether truncation should
2418 occur if the branch succeeds *or* if the branch condition fails allows
2419 for the flexibility required. This allows a Vertical-First Branch to
2420 *either* be used as a branch-back (loop) *or* as part of a conditional
2421 exit or function call from *inside* a loop, and for VLSET to be integrated
2422 into both types of decision-making.
2423
2424 In the case of a Vertical-First branch-back (loop), with `VSb=0` the
2425 branch takes place if success conditions are met, but on exit from that
2426 loop (branch condition fails), VL will be truncated. This is extremely
2427 useful.
2428
2429 `VLSET` mode with Horizontal-First when `VSb=0` is still useful, because
2430 it can be used to truncate VL to the first predicated (non-masked-out)
2431 element.
2432
2433 The truncation point for VL, when VLi is clear, must not include skipped
2434 elements that preceded the current element being tested. Example:
2435 `sz=0, VLi=0, predicate mask = 0b110010` and the Condition Register
2436 failure point is at CR Field element 4.
2437
2438 * Testing at element 0 is skipped because its predicate bit is zero
2439 * Testing at element 1 passed
2440 * Testing elements 2 and 3 are skipped because their
2441 respective predicate mask bits are zero
2442 * Testing element 4 fails therefore VL is truncated to **2**
2443 not 4 due to elements 2 and 3 being skipped.
2444
2445 If `sz=1` in the above example *then* VL would have been set to 4 because
2446 in non-zeroing mode the zero'd elements are still effectively part of the
2447 Vector (with their respective elements set to `SNZ`)
2448
2449 If `VLI=1` then VL would be set to 5 regardless of sz, due to being inclusive
2450 of the element actually being tested.
2451
2452 ### VLSET and CTR-test combined
2453
2454 If both CTR-test and VLSET Modes are requested, it is important to
2455 observe the correct order. What occurs depends on whether VLi is enabled,
2456 because VLi affects the length, VL.
2457
2458 If VLi (VL truncate inclusive) is set:
2459
2460 1. compute the test including whether CTR triggers
2461 2. (optionally) decrement CTR
2462 3. (optionally) truncate VL (VSb inverts the decision)
2463 4. decide (based on step 1) whether to terminate looping
2464 (including not executing step 5)
2465 5. decide whether to branch.
2466
2467 If VLi is clear, then when a test fails that element
2468 and any following it
2469 should **not** be considered part of the Vector. Consequently:
2470
2471 1. compute the branch test including whether CTR triggers
2472 2. if the test fails against VSb, truncate VL to the *previous*
2473 element, and terminate looping. No further steps executed.
2474 3. (optionally) decrement CTR
2475 4. decide whether to branch.
2476
2477 ## Boolean Logic combinations
2478
2479 In a Scalar ISA, Branch-Conditional testing even of vector results may be
2480 performed through inversion of tests. NOR of all tests may be performed
2481 by inversion of the scalar condition and branching *out* from the scalar
2482 loop around elements, using scalar operations.
2483
2484 In a parallel (Vector) ISA it is the ISA itself which must perform
2485 the prerequisite logic manipulation. Thus for SVP64 there are an
2486 extraordinary number of nesessary combinations which provide completely
2487 different and useful behaviour. Available options to combine:
2488
2489 * `BO[0]` to make an unconditional branch would seem irrelevant if
2490 it were not for predication and for side-effects (CTR Mode
2491 for example)
2492 * Enabling CTR-test Mode and setting `BO[2]` can still result in the
2493 Branch
2494 taking place, not because the Condition Test itself failed, but
2495 because CTR reached zero **because**, as required by CTR-test mode,
2496 CTR was decremented as a **result** of Condition Tests failing.
2497 * `BO[1]` to select whether the CR bit being tested is zero or nonzero
2498 * `R30` and `~R30` and other predicate mask options including CR and
2499 inverted CR bit testing
2500 * `sz` and `SNZ` to insert either zeros or ones in place of masked-out
2501 predicate bits
2502 * `ALL` or `ANY` behaviour corresponding to `AND` of all tests and
2503 `OR` of all tests, respectively.
2504 * Predicate Mask bits, which combine in effect with the CR being
2505 tested.
2506 * Inversion of Predicate Masks (`~r3` instead of `r3`, or using
2507 `NE` rather than `EQ`) which results in an additional
2508 level of possible ANDing, ORing etc. that would otherwise
2509 need explicit instructions.
2510
2511 The most obviously useful combinations here are to set `BO[1]` to zero
2512 in order to turn `ALL` into Great-Big-NAND and `ANY` into Great-Big-NOR.
2513 Other Mode bits which perform behavioural inversion then have to work
2514 round the fact that the Condition Testing is NOR or NAND. The alternative
2515 to not having additional behavioural inversion (`SNZ`, `VSb`, `CTi`)
2516 would be to have a second (unconditional) branch directly after the first,
2517 which the first branch jumps over. This contrivance is avoided by the
2518 behavioural inversion bits.
2519
2520 ## Pseudocode and examples
2521
2522 Please see the SVP64 appendix regarding CR bit ordering and for
2523 the definition of `CR{n}`
2524
2525 For comparative purposes this is a copy of the v3.0B `bc` pseudocode
2526
2527 ```
2528 if (mode_is_64bit) then M <- 0
2529 else M <- 32
2530 if ¬BO[2] then CTR <- CTR - 1
2531 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2532 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2533 if ctr_ok & cond_ok then
2534 if AA then NIA <-iea EXTS(BD || 0b00)
2535 else NIA <-iea CIA + EXTS(BD || 0b00)
2536 if LK then LR <-iea CIA + 4
2537 ```
2538
2539 Simplified pseudocode including LRu and CTR skipping, which illustrates
2540 clearly that SVP64 Scalar Branches (VL=1) are **not** identical to
2541 v3.0B Scalar Branches. The key areas where differences occur are the
2542 inclusion of predication (which can still be used when VL=1), in when and
2543 why CTR is decremented (CTRtest Mode) and whether LR is updated (which
2544 is unconditional in v3.0B when LK=1, and conditional in SVP64 when LRu=1).
2545
2546 Inline comments highlight the fact that the Scalar Branch behaviour and
2547 pseudocode is still clearly visible and embedded within the Vectorised
2548 variant:
2549
2550 ```
2551 if (mode_is_64bit) then M <- 0
2552 else M <- 32
2553 # the bit of CR to test, if the predicate bit is zero,
2554 # is overridden
2555 testbit = CR[BI+32]
2556 if ¬predicate_bit then testbit = SVRMmode.SNZ
2557 # otherwise apart from the override ctr_ok and cond_ok
2558 # are exactly the same
2559 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2560 cond_ok <- BO[0] | ¬(testbit ^ BO[1])
2561 if ¬predicate_bit & ¬SVRMmode.sz then
2562 # this is entirely new: CTR-test mode still decrements CTR
2563 # even when predicate-bits are zero
2564 if ¬BO[2] & CTRtest & ¬CTi then
2565 CTR = CTR - 1
2566 # instruction finishes here
2567 else
2568 # usual BO[2] CTR-mode now under CTR-test mode as well
2569 if ¬BO[2] & ¬(CTRtest & (cond_ok ^ CTi)) then CTR <- CTR - 1
2570 # new VLset mode, conditional test truncates VL
2571 if VLSET and VSb = (cond_ok & ctr_ok) then
2572 if SVRMmode.VLI then SVSTATE.VL = srcstep+1
2573 else SVSTATE.VL = srcstep
2574 # usual LR is now conditional, but also joined by SVLR
2575 lr_ok <- LK
2576 svlr_ok <- SVRMmode.SL
2577 if ctr_ok & cond_ok then
2578 if AA then NIA <-iea EXTS(BD || 0b00)
2579 else NIA <-iea CIA + EXTS(BD || 0b00)
2580 if SVRMmode.LRu then lr_ok <- ¬lr_ok
2581 if SVRMmode.SLu then svlr_ok <- ¬svlr_ok
2582 if lr_ok then LR <-iea CIA + 4
2583 if svlr_ok then SVLR <- SVSTATE
2584 ```
2585
2586 Below is the pseudocode for SVP64 Branches, which is a little less
2587 obvious but identical to the above. The lack of obviousness is down to
2588 the early-exit opportunities.
2589
2590 Effective pseudocode for Horizontal-First Mode:
2591
2592 ```
2593 if (mode_is_64bit) then M <- 0
2594 else M <- 32
2595 cond_ok = not SVRMmode.ALL
2596 for srcstep in range(VL):
2597 # select predicate bit or zero/one
2598 if predicate[srcstep]:
2599 # get SVP64 extended CR field 0..127
2600 SVCRf = SVP64EXTRA(BI>>2)
2601 CRbits = CR{SVCRf}
2602 testbit = CRbits[BI & 0b11]
2603 # testbit = CR[BI+32+srcstep*4]
2604 else if not SVRMmode.sz:
2605 # inverted CTR test skip mode
2606 if ¬BO[2] & CTRtest & ¬CTI then
2607 CTR = CTR - 1
2608 continue # skip to next element
2609 else
2610 testbit = SVRMmode.SNZ
2611 # actual element test here
2612 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2613 el_cond_ok <- BO[0] | ¬(testbit ^ BO[1])
2614 # check if CTR dec should occur
2615 ctrdec = ¬BO[2]
2616 if CTRtest & (el_cond_ok ^ CTi) then
2617 ctrdec = 0b0
2618 if ctrdec then CTR <- CTR - 1
2619 # merge in the test
2620 if SVRMmode.ALL:
2621 cond_ok &= (el_cond_ok & ctr_ok)
2622 else
2623 cond_ok |= (el_cond_ok & ctr_ok)
2624 # test for VL to be set (and exit)
2625 if VLSET and VSb = (el_cond_ok & ctr_ok) then
2626 if SVRMmode.VLI then SVSTATE.VL = srcstep+1
2627 else SVSTATE.VL = srcstep
2628 break
2629 # early exit?
2630 if SVRMmode.ALL != (el_cond_ok & ctr_ok):
2631 break
2632 # SVP64 rules about Scalar registers still apply!
2633 if SVCRf.scalar:
2634 break
2635 # loop finally done, now test if branch (and update LR)
2636 lr_ok <- LK
2637 svlr_ok <- SVRMmode.SL
2638 if cond_ok then
2639 if AA then NIA <-iea EXTS(BD || 0b00)
2640 else NIA <-iea CIA + EXTS(BD || 0b00)
2641 if SVRMmode.LRu then lr_ok <- ¬lr_ok
2642 if SVRMmode.SLu then svlr_ok <- ¬svlr_ok
2643 if lr_ok then LR <-iea CIA + 4
2644 if svlr_ok then SVLR <- SVSTATE
2645 ```
2646
2647 Pseudocode for Vertical-First Mode:
2648
2649 ```
2650 # get SVP64 extended CR field 0..127
2651 SVCRf = SVP64EXTRA(BI>>2)
2652 CRbits = CR{SVCRf}
2653 # select predicate bit or zero/one
2654 if predicate[srcstep]:
2655 if BRc = 1 then # CR0 vectorised
2656 CR{SVCRf+srcstep} = CRbits
2657 testbit = CRbits[BI & 0b11]
2658 else if not SVRMmode.sz:
2659 # inverted CTR test skip mode
2660 if ¬BO[2] & CTRtest & ¬CTI then
2661 CTR = CTR - 1
2662 SVSTATE.srcstep = new_srcstep
2663 exit # no branch testing
2664 else
2665 testbit = SVRMmode.SNZ
2666 # actual element test here
2667 cond_ok <- BO[0] | ¬(testbit ^ BO[1])
2668 # test for VL to be set (and exit)
2669 if VLSET and cond_ok = VSb then
2670 if SVRMmode.VLI
2671 SVSTATE.VL = new_srcstep+1
2672 else
2673 SVSTATE.VL = new_srcstep
2674 ```
2675
2676 ### Example Shader code
2677
2678 ```
2679 // assume f() g() or h() modify a and/or b
2680 while(a > 2) {
2681 if(b < 5)
2682 f();
2683 else
2684 g();
2685 h();
2686 }
2687 ```
2688
2689 which compiles to something like:
2690
2691 ```
2692 vec<i32> a, b;
2693 // ...
2694 pred loop_pred = a > 2;
2695 // loop continues while any of a elements greater than 2
2696 while(loop_pred.any()) {
2697 // vector of predicate bits
2698 pred if_pred = loop_pred & (b < 5);
2699 // only call f() if at least 1 bit set
2700 if(if_pred.any()) {
2701 f(if_pred);
2702 }
2703 label1:
2704 // loop mask ANDs with inverted if-test
2705 pred else_pred = loop_pred & ~if_pred;
2706 // only call g() if at least 1 bit set
2707 if(else_pred.any()) {
2708 g(else_pred);
2709 }
2710 h(loop_pred);
2711 }
2712 ```
2713
2714 which will end up as:
2715
2716 ```
2717 # start from while loop test point
2718 b looptest
2719 while_loop:
2720 sv.cmpi CR80.v, b.v, 5 # vector compare b into CR64 Vector
2721 sv.bc/m=r30/~ALL/sz CR80.v.LT skip_f # skip when none
2722 # only calculate loop_pred & pred_b because needed in f()
2723 sv.crand CR80.v.SO, CR60.v.GT, CR80.V.LT # if = loop & pred_b
2724 f(CR80.v.SO)
2725 skip_f:
2726 # illustrate inversion of pred_b. invert r30, test ALL
2727 # rather than SOME, but masked-out zero test would FAIL,
2728 # therefore masked-out instead is tested against 1 not 0
2729 sv.bc/m=~r30/ALL/SNZ CR80.v.LT skip_g
2730 # else = loop & ~pred_b, need this because used in g()
2731 sv.crternari(A&~B) CR80.v.SO, CR60.v.GT, CR80.V.LT
2732 g(CR80.v.SO)
2733 skip_g:
2734 # conditionally call h(r30) if any loop pred set
2735 sv.bclr/m=r30/~ALL/sz BO[1]=1 h()
2736 looptest:
2737 sv.cmpi CR60.v a.v, 2 # vector compare a into CR60 vector
2738 sv.crweird r30, CR60.GT # transfer GT vector to r30
2739 sv.bc/m=r30/~ALL/sz BO[1]=1 while_loop
2740 end:
2741 ```
2742
2743 ### LRu example
2744
2745 show why LRu would be useful in a loop. Imagine the following
2746 c code:
2747
2748 ```
2749 for (int i = 0; i < 8; i++) {
2750 if (x < y) break;
2751 }
2752 ```
2753
2754 Under these circumstances exiting from the loop is not only based on
2755 CTR it has become conditional on a CR result. Thus it is desirable that
2756 NIA *and* LR only be modified if the conditions are met
2757
2758 v3.0 pseudocode for `bclrl`:
2759
2760 ```
2761 if (mode_is_64bit) then M <- 0
2762 else M <- 32
2763 if ¬BO[2] then CTR <- CTR - 1
2764 ctr_ok <- BO[2] | ((CTR[M:63] != 0) ^ BO[3])
2765 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2766 if ctr_ok & cond_ok then NIA <-iea LR[0:61] || 0b00
2767 if LK then LR <-iea CIA + 4
2768 ```
2769
2770 the latter part for SVP64 `bclrl` becomes:
2771
2772 ```
2773 for i in 0 to VL-1:
2774 ...
2775 ...
2776 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2777 lr_ok <- LK
2778 if ctr_ok & cond_ok then
2779 NIA <-iea LR[0:61] || 0b00
2780 if SVRMmode.LRu then lr_ok <- ¬lr_ok
2781 if lr_ok then LR <-iea CIA + 4
2782 # if NIA modified exit loop
2783 ```
2784
2785 The reason why should be clear from this being a Vector loop:
2786 unconditional destruction of LR when LK=1 makes `sv.bclrl` ineffective,
2787 because the intention going into the loop is that the branch should be to
2788 the copy of LR set at the *start* of the loop, not half way through it.
2789 However if the change to LR only occurs if the branch is taken then it
2790 becomes a useful instruction.
2791
2792 The following pseudocode should **not** be implemented because it
2793 violates the fundamental principle of SVP64 which is that SVP64 looping
2794 is a thin wrapper around Scalar Instructions. The pseducode below is
2795 more an actual Vector ISA Branch and as such is not at all appropriate:
2796
2797 ```
2798 for i in 0 to VL-1:
2799 ...
2800 ...
2801 cond_ok <- BO[0] | ¬(CR[BI+32] ^ BO[1])
2802 if ctr_ok & cond_ok then NIA <-iea LR[0:61] || 0b00
2803 # only at the end of looping is LK checked.
2804 # this completely violates the design principle of SVP64
2805 # and would actually need to be a separate (scalar)
2806 # instruction "set LR to CIA+4 but retrospectively"
2807 # which is clearly impossible
2808 if LK then LR <-iea CIA + 4
2809 ```
2810
2811 [[!tag opf_rfc]]