# SV Overview This document provides an overview and introduction as to why SV (a Cray-style Vector augmentation to OpenPOWER) exists, and how it works. Links: * [[discussion]] and [bugreport](https://bugs.libre-soc.org/show_bug.cgi?id=556) feel free to add comments, questions. * [[SV|sv]] * [[sv/svp64]] Contents: [[!toc]] # Introduction: SIMD and Cray Vectors SIMD, the primary method for easy parallelism of the past 30 years in Computer Architectures, is [known to be harmful](https://www.sigarch.org/simd-instructions-considered-harmful/). SIMD provides a seductive simplicity that is easy to implement in hardware. With each doubling in width it promises increases in raw performance without the complexity of either multi-issue or out-of-order execution. Unfortunately, even with predication added, SIMD only becomes more and more problematic with each power of two SIMD width increase introduced through an ISA revision. The opcode proliferation, at O(N^6), inexorably spirals out of control in the ISA, detrimentally impacting the hardware, the software, the compilers and the testing and compliance. Cray-style variable-length Vectors on the other hand result in stunningly elegant and small loops, exceptionally high data throughput per instruction (by one *or greater* orders of magnitude than SIMD), with no alarmingly high setup and cleanup code, where at the hardware level the microarchitecture may execute from one element right the way through to tens of thousands at a time, yet the executable remains exactly the same and the ISA remains clear, true to the RISC paradigm, and clean. Unlike in SIMD, powers of two limitations are not involved in the ISA or in the assembly code. SimpleV takes the Cray style Vector principle and applies it in the abstract to a Scalar ISA, in the process allowing register file size increases using "tagging" (similar to how x86 originally extended registers from 32 to 64 bit). ## SV The fundamentals are: * The Program Counter (PC) gains a "Sub Counter" context (Sub-PC) * Vectorisation pauses the PC and runs a Sub-PC loop from 0 to VL-1 (where VL is Vector Length) * The [[Program Order]] of "Sub-PC" instructions must be preserved, just as is expected of instructions ordered by the PC. * Some registers may be "tagged" as Vectors * During the loop, "Vector"-tagged register are incremented by one with each iteration, executing the *same instruction* but with *different registers* * Once the loop is completed *only then* is the Program Counter allowed to move to the next instruction. Hardware (and simulator) implementors are free and clear to implement this as literally a for-loop, sitting in between instruction decode and issue. Higher performance systems may deploy SIMD backends, multi-issue and out-of-order execution, although it is strongly recommended to add predication capability directly into SIMD backend units. In OpenPOWER ISA v3.0B pseudo-code form, an ADD operation, assuming both source and destination have been "tagged" as Vectors, is simply: for i = 0 to VL-1: GPR(RT+i) = GPR(RA+i) + GPR(RB+i) At its heart, SimpleV really is this simple. On top of this fundamental basis further refinements can be added which build up towards an extremely powerful Vector augmentation system, with very little in the way of additional opcodes required: simply external "context". x86 was originally only 80 instructions: prior to AVX512 over 1,300 additional instructions have been added, almost all of them SIMD. RISC-V RVV as of version 0.9 is over 188 instructions (more than the rest of RV64G combined: 80 for RV64G and 27 for C). Over 95% of that functionality is added to OpenPOWER v3 0B, by SimpleV augmentation, with around 5 to 8 instructions. Even in OpenPOWER v3.0B, the Scalar Integer ISA is around 150 instructions, with IEEE754 FP adding approximately 80 more. VSX, being based on SIMD design principles, adds somewhere in the region of 600 more. SimpleV again provides over 95% of VSX functionality, simply by augmenting the *Scalar* OpenPOWER ISA, and in the process providing features such as predication, which VSX is entirely missing. AVX512, SVE2, VSX, RVV, all of these systems have to provide different types of register files: Scalar and Vector is the minimum. AVX512 even provides a mini mask regfile, followed by explicit instructions that handle operations on each of them *and map between all of them*. SV simply not only uses the existing scalar regfiles (including CRs), but because operations exist within OpenPOWER to cover interactions between the scalar regfiles (`mfcr`, `fcvt`) there is very little that needs to be added. In fairness to both VSX and RVV, there are things that are not provided by SimpleV: * 128 bit or above arithmetic and other operations (VSX Rijndael and SHA primitives; VSX shuffle and bitpermute operations) * register files above 128 entries * Vector lengths over 64 * Unit-strided LD/ST and other comprehensive memory operations (struct-based LD/ST from RVV for example) * 32-bit instruction lengths. [[svp64]] had to be added as 64 bit. These limitations, which stem inherently from the adaptation process of starting from a Scalar ISA, are not insurmountable. Over time, they may well be addressed in future revisions of SV. The rest of this document builds on the above simple loop to add: * Vector-Scalar, Scalar-Vector and Scalar-Scalar operation (of all register files: Integer, FP *and CRs*) * Traditional Vector operations (VSPLAT, VINSERT, VCOMPRESS etc) * Predication masks (essential for parallel if/else constructs) * 8, 16 and 32 bit integer operations, and both FP16 and BF16. * Compacted operations into registers (normally only provided by SIMD) * Fail-on-first (introduced in ARM SVE2) * A new concept: Data-dependent fail-first * Condition-Register based *post-result* predication (also new) * A completely new concept: "Twin Predication" * vec2/3/4 "Subvectors" and Swizzling (standard fare for 3D) All of this is *without modifying the OpenPOWER v3.0B ISA*, except to add "wrapping context", similar to how v3.1B 64 Prefixes work. # Adding Scalar / Vector The first augmentation to the simple loop is to add the option for all source and destinations to all be either scalar or vector. As a FSM this is where our "simple" loop gets its first complexity. function op_add(RT, RA, RB) # add not VADD! int id=0, irs1=0, irs2=0; for i = 0 to VL-1: ireg[RT+id] <= ireg[RA+irs1] + ireg[RB+irs2]; if (!RT.isvec) break; if (RT.isvec) { id += 1; } if (RA.isvec) { irs1 += 1; } if (RB.isvec) { irs2 += 1; } This could have been written out as eight separate cases: one each for when each of `RA`, `RB` or `RT` is scalar or vector. Those eight cases, when optimally combined, result in the pseudocode above. With some walkthroughs it is clear that the loop exits immediately after the first scalar destination result is written, and that when the destination is a Vector the loop proceeds to fill up the register file, sequentially, starting at `RT` and ending at `RT+VL-1`. The two source registers will, independently, either remain pointing at `RB` or `RA` respectively, or, if marked as Vectors, will march incrementally in lockstep, producing element results along the way, as the destination also progresses through elements. In this way all the eight permutations of Scalar and Vector behaviour are covered, although without predication the scalar-destination ones are reduced in usefulness. It does however clearly illustrate the principle. Note in particular: there is no separate Scalar add instruction and separate Vector instruction and separate Scalar-Vector instruction, *and there is no separate Vector register file*: it's all the same instruction, on the standard register file, just with a loop. Scalar happens to set that loop size to one. The important insight from the above is that, strictly speaking, Simple-V is not really a Vectorisation scheme at all: it is more of a hardware ISA "Compression scheme", allowing as it does for what would normally require multiple sequential instructions to be replaced with just one. This is where the rule that Program Order must be preserved in Sub-PC execution derives from. However in other ways, which will emerge below, the "tagging" concept presents an opportunity to include features definitely not common outside of Vector ISAs, and in that regard it's definitely a xlass of Vectorisation. ## Register "tagging" As an aside: in [[sv/svp64]] the encoding which allows SV to both extend the range beyond r0-r31 and to determine whether it is a scalar or vector is encoded in two to three bits, depending on the instruction. The reason for using so few bits is because there are up to *four* registers to mark in this way (`fma`, `isel`) which starts to be of concern when there are only 24 available bits to specify the entire SV Vectorisation Context. In fact, for a small subset of instructions it is just not possible to tag every single register. Under these rare circumstances a tag has to be shared between two registers. Below is the pseudocode which expresses the relationship which is usually applied to *every* register: if extra3_mode: spec = EXTRA3 # bit 2 s/v, 0-1 extends range else: spec = EXTRA2 << 1 # same as EXTRA3, shifted if spec[2]: # vector RA.isvec = True return (RA << 2) | spec[0:1] else: # scalar RA.isvec = False return (spec[0:1] << 5) | RA Here we can see that the scalar registers are extended in the top bits, whilst vectors are shifted up by 2 bits, and then extended in the LSBs. Condition Registers have a slightly different scheme, along the same principle, which takes into account the fact that each CR may be bit-level addressed by Condition Register operations. Readers familiar with OpenPOWER will know of Rc=1 operations that create an associated post-result "test", placing this test into an implicit Condition Register. The original researchers who created the POWER ISA chose CR0 for Integer, and CR1 for Floating Point. These *also become Vectorised* - implicitly - if the associated destination register is also Vectorised. This allows for some very interesting savings on instruction count due to the very same CR Vectors being predication masks. # Adding single predication The next step is to add a single predicate mask. This is where it gets interesting. Predicate masks are a bitvector, each bit specifying, in order, whether the element operation is to be skipped ("masked out") or allowed. If there is no predicate, it is set to all 1s, which is effectively the same as "no predicate". function op_add(RT, RA, RB) # add not VADD! int id=0, irs1=0, irs2=0; predval = get_pred_val(FALSE, rd); for i = 0 to VL-1: if (predval & 1< All good Vector ISAs have the usual bitwidths for operations: 8/16/32/64 bit integer operations, and IEEE754 FP32 and 64. Often also included is FP16 and more recently BF16. The *really* good Vector ISAs have variable-width vectors right down to bitlevel, and as high as 1024 bit arithmetic per element, as well as IEEE754 FP128. SV has an "override" system that *changes* the bitwidth of operations that were intended by the original scalar ISA designers to have (for example) 64 bit operations (only). The override widths are 8, 16 and 32 for integer, and FP16 and FP32 for IEEE754 (with BF16 to be added in the future). This presents a particularly intriguing conundrum given that the OpenPOWER Scalar ISA was never designed with for example 8 bit operations in mind, let alone Vectors of 8 bit. The solution comes in terms of rethinking the definition of a Register File. The typical regfile may be considered to be a multi-ported SRAM block, 64 bits wide and usually 32 entries deep, to give 32 64 bit registers. In c this would be: typedef uint64_t reg_t; reg_t int_regfile[32]; // standard scalar 32x 64bit Conceptually, to get our variable element width vectors, we may think of the regfile as instead being the following c-based data structure: typedef union { uint8_t actual_bytes[8]; uint8_t b[0]; // array of type uint8_t uint16_t s[0]; uint32_t i[0]; uint64_t l[0]; // default OpenPOWER ISA uses this } reg_t; reg_t int_regfile[128]; // SV extends to 128 regs Then, our simple loop, instead of accessing the array of regfile entries with a computed index, would access the appropriate element of the appropriate type. Thus we have a series of overlapping conceptual arrays that each start at what is traditionally thought of as "a register". It then helps if we have a couple of routines: get_polymorphed_reg(reg, bitwidth, offset): reg_t res = 0; if (!reg.isvec): # scalar offset = 0 if bitwidth == 8: reg.b = int_regfile[reg].b[offset] elif bitwidth == 16: reg.s = int_regfile[reg].s[offset] elif bitwidth == 32: reg.i = int_regfile[reg].i[offset] elif bitwidth == default: # 64 reg.l = int_regfile[reg].l[offset] return res set_polymorphed_reg(reg, bitwidth, offset, val): if (!reg.isvec): # scalar offset = 0 if bitwidth == 8: int_regfile[reg].b[offset] = val elif bitwidth == 16: int_regfile[reg].s[offset] = val elif bitwidth == 32: int_regfile[reg].i[offset] = val elif bitwidth == default: # 64 int_regfile[reg].l[offset] = val These basically provide a convenient parameterised way to access the register file, at an arbitrary vector element offset and an arbitrary element width. Our first simple loop thus becomes: for i = 0 to VL-1: src1 = get_polymorphed_reg(RA, srcwid, i) src2 = get_polymorphed_reg(RB, srcwid, i) result = src1 + src2 # actual add here set_polymorphed_reg(rd, destwid, i, result) With this loop, if elwidth=16 and VL=3 the first 48 bits of the target register will contain three 16 bit addition results, and the upper 16 bits will be *unaltered*. Note that things such as zero/sign-extension (and predication) have been left out to illustrate the elwidth concept. Also note that it turns out to be important to perform the operation at the maximum bitwidth - `max(srcwid, destwid)` - such that any truncation, rounding errors or other artefacts may all be ironed out. This turns out to be important when applying Saturation for Audio DSP workloads. Other than that, element width overrides, which can be applied to *either* source or destination or both, are pretty straightforward, conceptually. The details, for hardware engineers, involve byte-level write-enable lines, which is exactly what is used on SRAMs anyway. Compiler writers have to alter Register Allocation Tables to byte-level granularity. One critical thing to note: upper parts of the underlying 64 bit register are *not zero'd out* by a write involving a non-aligned Vector Length. An 8 bit operation with VL=7 will *not* overwrite the 8th byte of the destination. The only situation where a full overwrite occurs is on "default" behaviour. This is extremely important to consider the register file as a byte-level store, not a 64-bit-level store. # Quick recap so far The above functionality pretty much covers around 85% of Vector ISA needs. Predication is provided so that parallel if/then/else constructs can be performed: critical given that sequential if/then statements and branches simply do not translate successfully to Vector workloads. VSPLAT capability is provided which is approximately 20% of all GPU workload operations. Also covered, with elwidth overriding, is the smaller arithmetic operations that caused ISAs developed from the late 80s onwards to get themselves into a tiz when adding "Multimedia" acceleration aka "SIMD" instructions. Experienced Vector ISA readers will however have noted that VCOMPRESS and VEXPAND are missing, as is Vector "reduce" (mapreduce) capability and VGATHER and VSCATTER. Compress and Expand are covered by Twin Predication, and yet to also be covered is fail-on-first, CR-based result predication, and Subvectors and Swizzle. ## SUBVL Adding in support for SUBVL is a matter of adding in an extra inner for-loop, where register src and dest are still incremented inside the inner part. Predication is still taken from the VL index, however it is applied to the whole subvector: function op_add(RT, RA, RB) # add not VADD!  int id=0, irs1=0, irs2=0;  predval = get_pred_val(FALSE, rd); for i = 0 to VL-1: if (predval & 1< Swizzle is particularly important for 3D work. It allows in-place reordering of XYZW, ARGB etc. and access of sub-portions of the same in arbitrary order *without* requiring timeconsuming scalar mv instructions (scalar due to the convoluted offsets). Swizzling does not just do permutations: it allows multiple copying of vec2/3/4 elements, such as XXXW as the source operand, which will take 3 copies of the vec4 first element. With somewhere between 10% and 30% of operations in 3D Shaders involving swizzle this is a huge saving and reduces pressure on register files. In SV given the percentage of operations that also involve initialisation to 0.0 or 1.0 into subvector elements the decision was made to include those: swizzle = get_swizzle_immed() # 12 bits for (s = 0; s < SUBVL; s++) remap = (swizzle >> 3*s) & 0b111 if remap < 4: sm = id*SUBVL + remap ireg[rd+s] <= ireg[RA+sm] elif remap == 4: ireg[rd+s] <= 0.0 elif remap == 5: ireg[rd+s] <= 1.0 Note that a value of 6 (and 7) will leave the target subvector element untouched. This is equivalent to a predicate mask which is built-in, in immediate form, into the [[sv/mv.swizzle]] operation. mv.swizzle is rare in that it is one of the few instructions needed to be added that are never going to be part of a Scalar ISA. Even in High Performance Compute workloads it is unusual: it is only because SV is targetted at 3D and Video that it is being considered. Some 3D GPU ISAs also allow for two-operand subvector swizzles. These are sufficiently unusual, and the immediate opcode space required so large, that the tradeoff balance was decided in SV to only add mv.swizzle. # Twin Predication Twin Predication is cool. Essentially it is a back-to-back VCOMPRESS-VEXPAND (a multiple sequentially ordered VINSERT). The compress part is covered by the source predicate and the expand part by the destination predicate. Of course, if either of those is all 1s then the operation degenerates *to* VCOMPRESS or VEXPAND, respectively. function op(RT, RS):  ps = get_pred_val(FALSE, RS); # predication on src  pd = get_pred_val(FALSE, RT); # ... AND on dest  for (int i = 0, int j = 0; i < VL && j < VL;): if (RS.isvec) while (!(ps & 1<