add scalar detection diagram
[libreriscv.git] / simple_v_extension.mdwn
1 # Variable-width Variable-packed SIMD / Simple-V / Parallelism Extension Proposal
2
3 * TODO 23may2018: CSR-CAM-ify regfile tables
4 * TODO 23may2018: zero-mark predication CSR
5 * TODO 23may2018: impl. detail on scalar-only ops (see appendix)
6
7 Key insight: Simple-V is intended as an abstraction layer to provide
8 a consistent "API" to parallelisation of existing *and future* operations.
9 *Actual* internal hardware-level parallelism is *not* required, such
10 that Simple-V may be viewed as providing a "compact" or "consolidated"
11 means of issuing multiple near-identical arithmetic instructions to an
12 instruction queue (FIFO), pending execution.
13
14 *Actual* parallelism, if added independently of Simple-V in the form
15 of Out-of-order restructuring (including parallel ALU lanes) or VLIW
16 implementations, or SIMD, or anything else, would then benefit *if*
17 Simple-V was added on top.
18
19 [[!toc ]]
20
21 # Introduction
22
23 This proposal exists so as to be able to satisfy several disparate
24 requirements: power-conscious, area-conscious, and performance-conscious
25 designs all pull an ISA and its implementation in different conflicting
26 directions, as do the specific intended uses for any given implementation.
27
28 The existing P (SIMD) proposal and the V (Vector) proposals,
29 whilst each extremely powerful in their own right and clearly desirable,
30 are also:
31
32 * Clearly independent in their origins (Cray and AndesStar v3 respectively)
33 so need work to adapt to the RISC-V ethos and paradigm
34 * Are sufficiently large so as to make adoption (and exploration for
35 analysis and review purposes) prohibitively expensive
36 * Both contain partial duplication of pre-existing RISC-V instructions
37 (an undesirable characteristic)
38 * Both have independent, incompatible and disparate methods for introducing
39 parallelism at the instruction level
40 * Both require that their respective parallelism paradigm be implemented
41 along-side and integral to their respective functionality *or not at all*.
42 * Both independently have methods for introducing parallelism that
43 could, if separated, benefit
44 *other areas of RISC-V not just DSP or Floating-point respectively*.
45
46 There are also key differences between Vectorisation and SIMD (full
47 details outlined in the Appendix), the key points being:
48
49 * SIMD has an extremely seductively compelling ease of implementation argument:
50 each operation is passed to the ALU, which is where the parallelism
51 lies. There is *negligeable* (if any) impact on the rest of the core
52 (with life instead being made hell for compiler writers and applications
53 writers due to extreme ISA proliferation).
54 * By contrast, Vectorisation has quite some complexity (for considerable
55 flexibility, reduction in opcode proliferation and much more).
56 * Vectorisation typically includes much more comprehensive memory load
57 and store schemes (unit stride, constant-stride and indexed), which
58 in turn have ramifications: virtual memory misses (TLB cache misses)
59 and even multiple page-faults... all caused by a *single instruction*,
60 yet with a clear benefit that the regularisation of LOAD/STOREs can
61 be optimised for minimal impact on caches and maximised throughput.
62 * By contrast, SIMD can use "standard" memory load/stores (32-bit aligned
63 to pages), and these load/stores have absolutely nothing to do with the
64 SIMD / ALU engine, no matter how wide the operand. Simplicity but with
65 more impact on instruction and data caches.
66
67 Overall it makes a huge amount of sense to have a means and method
68 of introducing instruction parallelism in a flexible way that provides
69 implementors with the option to choose exactly where they wish to offer
70 performance improvements and where they wish to optimise for power
71 and/or area (and if that can be offered even on a per-operation basis that
72 would provide even more flexibility).
73
74 Additionally it makes sense to *split out* the parallelism inherent within
75 each of P and V, and to see if each of P and V then, in *combination* with
76 a "best-of-both" parallelism extension, could be added on *on top* of
77 this proposal, to topologically provide the exact same functionality of
78 each of P and V. Each of P and V then can focus on providing the best
79 operations possible for their respective target areas, without being
80 hugely concerned about the actual parallelism.
81
82 Furthermore, an additional goal of this proposal is to reduce the number
83 of opcodes utilised by each of P and V as they currently stand, leveraging
84 existing RISC-V opcodes where possible, and also potentially allowing
85 P and V to make use of Compressed Instructions as a result.
86
87 # Analysis and discussion of Vector vs SIMD
88
89 There are six combined areas between the two proposals that help with
90 parallelism (increased performance, reduced power / area) without
91 over-burdening the ISA with a huge proliferation of
92 instructions:
93
94 * Fixed vs variable parallelism (fixed or variable "M" in SIMD)
95 * Implicit vs fixed instruction bit-width (integral to instruction or not)
96 * Implicit vs explicit type-conversion (compounded on bit-width)
97 * Implicit vs explicit inner loops.
98 * Single-instruction LOAD/STORE.
99 * Masks / tagging (selecting/preventing certain indexed elements from execution)
100
101 The pros and cons of each are discussed and analysed below.
102
103 ## Fixed vs variable parallelism length
104
105 In David Patterson and Andrew Waterman's analysis of SIMD and Vector
106 ISAs, the analysis comes out clearly in favour of (effectively) variable
107 length SIMD. As SIMD is a fixed width, typically 4, 8 or in extreme cases
108 16 or 32 simultaneous operations, the setup, teardown and corner-cases of SIMD
109 are extremely burdensome except for applications whose requirements
110 *specifically* match the *precise and exact* depth of the SIMD engine.
111
112 Thus, SIMD, no matter what width is chosen, is never going to be acceptable
113 for general-purpose computation, and in the context of developing a
114 general-purpose ISA, is never going to satisfy 100 percent of implementors.
115
116 To explain this further: for increased workloads over time, as the
117 performance requirements increase for new target markets, implementors
118 choose to extend the SIMD width (so as to again avoid mixing parallelism
119 into the instruction issue phases: the primary "simplicity" benefit of
120 SIMD in the first place), with the result that the entire opcode space
121 effectively doubles with each new SIMD width that's added to the ISA.
122
123 That basically leaves "variable-length vector" as the clear *general-purpose*
124 winner, at least in terms of greatly simplifying the instruction set,
125 reducing the number of instructions required for any given task, and thus
126 reducing power consumption for the same.
127
128 ## Implicit vs fixed instruction bit-width
129
130 SIMD again has a severe disadvantage here, over Vector: huge proliferation
131 of specialist instructions that target 8-bit, 16-bit, 32-bit, 64-bit, and
132 have to then have operations *for each and between each*. It gets very
133 messy, very quickly.
134
135 The V-Extension on the other hand proposes to set the bit-width of
136 future instructions on a per-register basis, such that subsequent instructions
137 involving that register are *implicitly* of that particular bit-width until
138 otherwise changed or reset.
139
140 This has some extremely useful properties, without being particularly
141 burdensome to implementations, given that instruction decode already has
142 to direct the operation to a correctly-sized width ALU engine, anyway.
143
144 Not least: in places where an ISA was previously constrained (due for
145 whatever reason, including limitations of the available operand space),
146 implicit bit-width allows the meaning of certain operations to be
147 type-overloaded *without* pollution or alteration of frozen and immutable
148 instructions, in a fully backwards-compatible fashion.
149
150 ## Implicit and explicit type-conversion
151
152 The Draft 2.3 V-extension proposal has (deprecated) polymorphism to help
153 deal with over-population of instructions, such that type-casting from
154 integer (and floating point) of various sizes is automatically inferred
155 due to "type tagging" that is set with a special instruction. A register
156 will be *specifically* marked as "16-bit Floating-Point" and, if added
157 to an operand that is specifically tagged as "32-bit Integer" an implicit
158 type-conversion will take place *without* requiring that type-conversion
159 to be explicitly done with its own separate instruction.
160
161 However, implicit type-conversion is not only quite burdensome to
162 implement (explosion of inferred type-to-type conversion) but also is
163 never really going to be complete. It gets even worse when bit-widths
164 also have to be taken into consideration. Each new type results in
165 an increased O(N^2) conversion space that, as anyone who has examined
166 python's source code (which has built-in polymorphic type-conversion),
167 knows that the task is more complex than it first seems.
168
169 Overall, type-conversion is generally best to leave to explicit
170 type-conversion instructions, or in definite specific use-cases left to
171 be part of an actual instruction (DSP or FP)
172
173 ## Zero-overhead loops vs explicit loops
174
175 The initial Draft P-SIMD Proposal by Chuanhua Chang of Andes Technology
176 contains an extremely interesting feature: zero-overhead loops. This
177 proposal would basically allow an inner loop of instructions to be
178 repeated indefinitely, a fixed number of times.
179
180 Its specific advantage over explicit loops is that the pipeline in a DSP
181 can potentially be kept completely full *even in an in-order single-issue
182 implementation*. Normally, it requires a superscalar architecture and
183 out-of-order execution capabilities to "pre-process" instructions in
184 order to keep ALU pipelines 100% occupied.
185
186 By bringing that capability in, this proposal could offer a way to increase
187 pipeline activity even in simpler implementations in the one key area
188 which really matters: the inner loop.
189
190 However when looking at much more comprehensive schemes
191 "A portable specification of zero-overhead loop control hardware
192 applied to embedded processors" (ZOLC), optimising only the single
193 inner loop seems inadequate, tending to suggest that ZOLC may be
194 better off being proposed as an entirely separate Extension.
195
196 ## Single-instruction LOAD/STORE
197
198 In traditional Vector Architectures there are instructions which
199 result in multiple register-memory transfer operations resulting
200 from a single instruction. They're complicated to implement in hardware,
201 yet the benefits are a huge consistent regularisation of memory accesses
202 that can be highly optimised with respect to both actual memory and any
203 L1, L2 or other caches. In Hwacha EECS-2015-263 it is explicitly made
204 clear the consequences of getting this architecturally wrong:
205 L2 cache-thrashing at the very least.
206
207 Complications arise when Virtual Memory is involved: TLB cache misses
208 need to be dealt with, as do page faults. Some of the tradeoffs are
209 discussed in <http://people.eecs.berkeley.edu/~krste/thesis.pdf>, Section
210 4.6, and an article by Jeff Bush when faced with some of these issues
211 is particularly enlightening
212 <https://jbush001.github.io/2015/11/03/lost-in-translation.html>
213
214 Interestingly, none of this complexity is faced in SIMD architectures...
215 but then they do not get the opportunity to optimise for highly-streamlined
216 memory accesses either.
217
218 With the "bang-per-buck" ratio being so high and the indirect improvement
219 in L1 Instruction Cache usage (reduced instruction count), as well as
220 the opportunity to optimise L1 and L2 cache usage, the case for including
221 Vector LOAD/STORE is compelling.
222
223 ## Mask and Tagging (Predication)
224
225 Tagging (aka Masks aka Predication) is a pseudo-method of implementing
226 simplistic branching in a parallel fashion, by allowing execution on
227 elements of a vector to be switched on or off depending on the results
228 of prior operations in the same array position.
229
230 The reason for considering this is simple: by *definition* it
231 is not possible to perform individual parallel branches in a SIMD
232 (Single-Instruction, **Multiple**-Data) context. Branches (modifying
233 of the Program Counter) will result in *all* parallel data having
234 a different instruction executed on it: that's just the definition of
235 SIMD, and it is simply unavoidable.
236
237 So these are the ways in which conditional execution may be implemented:
238
239 * explicit compare and branch: BNE x, y -> offs would jump offs
240 instructions if x was not equal to y
241 * explicit store of tag condition: CMP x, y -> tagbit
242 * implicit (condition-code) such as ADD results in a carry, carry bit
243 implicitly (or sometimes explicitly) goes into a "tag" (mask) register
244
245 The first of these is a "normal" branch method, which is flat-out impossible
246 to parallelise without look-ahead and effectively rewriting instructions.
247 This would defeat the purpose of RISC.
248
249 The latter two are where parallelism becomes easy to do without complexity:
250 every operation is modified to be "conditionally executed" (in an explicit
251 way directly in the instruction format *or* implicitly).
252
253 RVV (Vector-Extension) proposes to have *explicit* storing of the compare
254 in a tag/mask register, and to *explicitly* have every vector operation
255 *require* that its operation be "predicated" on the bits within an
256 explicitly-named tag/mask register.
257
258 SIMD (P-Extension) has not yet published precise documentation on what its
259 schema is to be: there is however verbal indication at the time of writing
260 that:
261
262 > The "compare" instructions in the DSP/SIMD ISA proposed by Andes will
263 > be executed using the same compare ALU logic for the base ISA with some
264 > minor modifications to handle smaller data types. The function will not
265 > be duplicated.
266
267 This is an *implicit* form of predication as the base RV ISA does not have
268 condition-codes or predication. By adding a CSR it becomes possible
269 to also tag certain registers as "predicated if referenced as a destination".
270 Example:
271
272 // in future operations from now on, if r0 is the destination use r5 as
273 // the PREDICATION register
274 SET_IMPLICIT_CSRPREDICATE r0, r5
275 // store the compares in r5 as the PREDICATION register
276 CMPEQ8 r5, r1, r2
277 // r0 is used here. ah ha! that means it's predicated using r5!
278 ADD8 r0, r1, r3
279
280 With enough registers (and in RISC-V there are enough registers) some fairly
281 complex predication can be set up and yet still execute without significant
282 stalling, even in a simple non-superscalar architecture.
283
284 (For details on how Branch Instructions would be retro-fitted to indirectly
285 predicated equivalents, see Appendix)
286
287 ## Conclusions
288
289 In the above sections the five different ways where parallel instruction
290 execution has closely and loosely inter-related implications for the ISA and
291 for implementors, were outlined. The pluses and minuses came out as
292 follows:
293
294 * Fixed vs variable parallelism: <b>variable</b>
295 * Implicit (indirect) vs fixed (integral) instruction bit-width: <b>indirect</b>
296 * Implicit vs explicit type-conversion: <b>explicit</b>
297 * Implicit vs explicit inner loops: <b>implicit but best done separately</b>
298 * Single-instruction Vector LOAD/STORE: <b>Complex but highly beneficial</b>
299 * Tag or no-tag: <b>Complex but highly beneficial</b>
300
301 In particular:
302
303 * variable-length vectors came out on top because of the high setup, teardown
304 and corner-cases associated with the fixed width of SIMD.
305 * Implicit bit-width helps to extend the ISA to escape from
306 former limitations and restrictions (in a backwards-compatible fashion),
307 whilst also leaving implementors free to simmplify implementations
308 by using actual explicit internal parallelism.
309 * Implicit (zero-overhead) loops provide a means to keep pipelines
310 potentially 100% occupied in a single-issue in-order implementation
311 i.e. *without* requiring a super-scalar or out-of-order architecture,
312 but doing a proper, full job (ZOLC) is an entirely different matter.
313
314 Constructing a SIMD/Simple-Vector proposal based around four of these six
315 requirements would therefore seem to be a logical thing to do.
316
317 # Note on implementation of parallelism
318
319 One extremely important aspect of this proposal is to respect and support
320 implementors desire to focus on power, area or performance. In that regard,
321 it is proposed that implementors be free to choose whether to implement
322 the Vector (or variable-width SIMD) parallelism as sequential operations
323 with a single ALU, fully parallel (if practical) with multiple ALUs, or
324 a hybrid combination of both.
325
326 In Broadcom's Videocore-IV, they chose hybrid, and called it "Virtual
327 Parallelism". They achieve a 16-way SIMD at an **instruction** level
328 by providing a combination of a 4-way parallel ALU *and* an externally
329 transparent loop that feeds 4 sequential sets of data into each of the
330 4 ALUs.
331
332 Also in the same core, it is worth noting that particularly uncommon
333 but essential operations (Reciprocal-Square-Root for example) are
334 *not* part of the 4-way parallel ALU but instead have a *single* ALU.
335 Under the proposed Vector (varible-width SIMD) implementors would
336 be free to do precisely that: i.e. free to choose *on a per operation
337 basis* whether and how much "Virtual Parallelism" to deploy.
338
339 It is absolutely critical to note that it is proposed that such choices MUST
340 be **entirely transparent** to the end-user and the compiler. Whilst
341 a Vector (varible-width SIMD) may not precisely match the width of the
342 parallelism within the implementation, the end-user **should not care**
343 and in this way the performance benefits are gained but the ISA remains
344 straightforward. All that happens at the end of an instruction run is: some
345 parallel units (if there are any) would remain offline, completely
346 transparently to the ISA, the program, and the compiler.
347
348 To make that clear: should an implementor choose a particularly wide
349 SIMD-style ALU, each parallel unit *must* have predication so that
350 the parallel SIMD ALU may emulate variable-length parallel operations.
351 Thus the "SIMD considered harmful" trap of having huge complexity and extra
352 instructions to deal with corner-cases is thus avoided, and implementors
353 get to choose precisely where to focus and target the benefits of their
354 implementation efforts, without "extra baggage".
355
356 In addition, implementors will be free to choose whether to provide an
357 absolute bare minimum level of compliance with the "API" (software-traps
358 when vectorisation is detected), all the way up to full supercomputing
359 level all-hardware parallelism. Options are covered in the Appendix.
360
361 # CSRs <a name="csrs"></a>
362
363 There are a number of CSRs needed, which are used at the instruction
364 decode phase to re-interpret RV opcodes (a practice that has
365 precedent in the setting of MISA to enable / disable extensions).
366
367 * Integer Register N is Vector of length M: r(N) -> r(N..N+M-1)
368 * Integer Register N is of implicit bitwidth M (M=default,8,16,32,64)
369 * Floating-point Register N is Vector of length M: r(N) -> r(N..N+M-1)
370 * Floating-point Register N is of implicit bitwidth M (M=default,8,16,32,64)
371 * Integer Register N is a Predication Register (note: a key-value store)
372 * Vector Length CSR (VSETVL, VGETVL)
373
374 Also (see Appendix, "Context Switch Example") it may turn out to be important
375 to have a separate (smaller) set of CSRs for M-Mode (and S-Mode) so that
376 Vectorised LOAD / STORE may be used to load and store multiple registers:
377 something that is missing from the Base RV ISA.
378
379 Notes:
380
381 * for the purposes of LOAD / STORE, Integer Registers which are
382 marked as a Vector will result in a Vector LOAD / STORE.
383 * Vector Lengths are *not* the same as vsetl but are an integral part
384 of vsetl.
385 * Actual vector length is *multipled* by how many blocks of length
386 "bitwidth" may fit into an XLEN-sized register file.
387 * Predication is a key-value store due to the implicit referencing,
388 as opposed to having the predicate register explicitly in the instruction.
389 * Whilst the predication CSR is a key-value store it *generates* easier-to-use
390 state information.
391 * TODO: assess whether the same technique could be applied to the other
392 Vector CSRs, particularly as pointed out in Section 17.8 (Draft RV 0.4,
393 V2.3-Draft ISA Reference) it becomes possible to greatly reduce state
394 needed for context-switches (empty slots need never be stored).
395
396 ## Predication CSR
397
398 The Predication CSR is a key-value store indicating whether, if a given
399 destination register (integer or floating-point) is referred to in an
400 instruction, it is to be predicated. The first entry is whether predication
401 is enabled. The second entry is whether the register index refers to a
402 floating-point or an integer register. The third entry is the index
403 of that register which is to be predicated (if referred to). The fourth entry
404 is the integer register that is treated as a bitfield, indexable by the
405 vector element index.
406
407 | RegNo | 6 | 5 | (4..0) | (4..0) |
408 | ----- | - | - | ------- | ------- |
409 | r0 | pren0 | i/f | regidx | predidx |
410 | r1 | pren1 | i/f | regidx | predidx |
411 | .. | pren.. | i/f | regidx | predidx |
412 | r15 | pren15 | i/f | regidx | predidx |
413
414 The Predication CSR Table is a key-value store, so implementation-wise
415 it will be faster to turn the table around (maintain topologically
416 equivalent state):
417
418 fp_pred_enabled[32];
419 int_pred_enabled[32];
420 for (i = 0; i < 16; i++)
421 if CSRpred[i].pren:
422 idx = CSRpred[i].regidx
423 predidx = CSRpred[i].predidx
424 if CSRpred[i].type == 0: # integer
425 int_pred_enabled[idx] = 1
426 int_pred_reg[idx] = predidx
427 else:
428 fp_pred_enabled[idx] = 1
429 fp_pred_reg[idx] = predidx
430
431 So when an operation is to be predicated, it is the internal state that
432 is used. In Section 6.4.2 of Hwacha's Manual (EECS-2015-262) the following
433 pseudo-code for operations is given, where p is the explicit (direct)
434 reference to the predication register to be used:
435
436 for (int i=0; i<vl; ++i)
437 if ([!]preg[p][i])
438 (d ? vreg[rd][i] : sreg[rd]) =
439 iop(s1 ? vreg[rs1][i] : sreg[rs1],
440 s2 ? vreg[rs2][i] : sreg[rs2]); // for insts with 2 inputs
441
442 This instead becomes an *indirect* reference using the *internal* state
443 table generated from the Predication CSR key-value store:
444
445 if type(iop) == INT:
446 pred_enabled = int_pred_enabled
447 preg = int_pred_reg[rd]
448 else:
449 pred_enabled = fp_pred_enabled
450 preg = fp_pred_reg[rd]
451
452 for (int i=0; i<vl; ++i)
453 if (preg_enabled[rd] && [!]preg[i])
454 (d ? vreg[rd][i] : sreg[rd]) =
455 iop(s1 ? vreg[rs1][i] : sreg[rs1],
456 s2 ? vreg[rs2][i] : sreg[rs2]); // for insts with 2 inputs
457
458 ## MAXVECTORDEPTH
459
460 MAXVECTORDEPTH is the same concept as MVL in RVV. However in Simple-V,
461 given that its primary (base, unextended) purpose is for 3D, Video and
462 other purposes (not requiring supercomputing capability), it makes sense
463 to limit MAXVECTORDEPTH to the regfile bitwidth (32 for RV32, 64 for RV64
464 and so on).
465
466 The reason for setting this limit is so that predication registers, when
467 marked as such, may fit into a single register as opposed to fanning out
468 over several registers. This keeps the implementation a little simpler.
469 Note also (as also described in the VSETVL section) that the *minimum*
470 for MAXVECTORDEPTH must be the total number of registers (15 for RV32E
471 and 31 for RV32 or RV64).
472
473 Note that RVV on top of Simple-V may choose to over-ride this decision.
474
475 ## Vector-length CSRs
476
477 Vector lengths are interpreted as meaning "any instruction referring to
478 r(N) generates implicit identical instructions referring to registers
479 r(N+M-1) where M is the Vector Length". Vector Lengths may be set to
480 use up to 16 registers in the register file.
481
482 One separate CSR table is needed for each of the integer and floating-point
483 register files:
484
485 | RegNo | (3..0) |
486 | ----- | ------ |
487 | r0 | vlen0 |
488 | r1 | vlen1 |
489 | .. | vlen.. |
490 | r31 | vlen31 |
491
492 An array of 32 4-bit CSRs is needed (4 bits per register) to indicate
493 whether a register was, if referred to in any standard instructions,
494 implicitly to be treated as a vector.
495
496 Note:
497
498 * A vector length of 1 indicates that it is to be treated as a scalar.
499 Bitwidths (on the same register) are interpreted and meaningful.
500 * A vector length of 0 indicates that the parallelism is to be switched
501 off for this register (treated as a scalar). When length is 0,
502 the bitwidth CSR for the register is *ignored*.
503
504 Internally, implementations may choose to use the non-zero vector length
505 to set a bit-field per register, to be used in the instruction decode phase.
506 In this way any standard (current or future) operation involving
507 register operands may detect if the operation is to be vector-vector,
508 vector-scalar or scalar-scalar (standard) simply through a single
509 bit test.
510
511 Note that when using the "vsetl rs1, rs2" instruction (caveat: when the
512 bitwidth is specifically not set) it becomes:
513
514 CSRvlength = MIN(MIN(CSRvectorlen[rs1], MAXVECTORDEPTH), rs2)
515
516 This is in contrast to RVV:
517
518 CSRvlength = MIN(MIN(rs1, MAXVECTORDEPTH), rs2)
519
520 ## Element (SIMD) bitwidth CSRs
521
522 Element bitwidths may be specified with a per-register CSR, and indicate
523 how a register (integer or floating-point) is to be subdivided.
524
525 | RegNo | (2..0) |
526 | ----- | ------ |
527 | r0 | vew0 |
528 | r1 | vew1 |
529 | .. | vew.. |
530 | r31 | vew31 |
531
532 vew may be one of the following (giving a table "bytestable", used below):
533
534 | vew | bitwidth |
535 | --- | -------- |
536 | 000 | default |
537 | 001 | 8 |
538 | 010 | 16 |
539 | 011 | 32 |
540 | 100 | 64 |
541 | 101 | 128 |
542 | 110 | rsvd |
543 | 111 | rsvd |
544
545 Extending this table (with extra bits) is covered in the section
546 "Implementing RVV on top of Simple-V".
547
548 Note that when using the "vsetl rs1, rs2" instruction, taking bitwidth
549 into account, it becomes:
550
551 vew = CSRbitwidth[rs1]
552 if (vew == 0)
553 bytesperreg = (XLEN/8) # or FLEN as appropriate
554 else:
555 bytesperreg = bytestable[vew] # 1 2 4 8 16
556 simdmult = (XLEN/8) / bytesperreg # or FLEN as appropriate
557 vlen = CSRvectorlen[rs1] * simdmult
558 CSRvlength = MIN(MIN(vlen, MAXVECTORDEPTH), rs2)
559
560 The reason for multiplying the vector length by the number of SIMD elements
561 (in each individual register) is so that each SIMD element may optionally be
562 predicated.
563
564 An example of how to subdivide the register file when bitwidth != default
565 is given in the section "Bitwidth Virtual Register Reordering".
566
567 # Instructions
568
569 By being a topological remap of RVV concepts, the following RVV instructions
570 remain exactly the same: VMPOP, VMFIRST, VEXTRACT, VINSERT, VMERGE, VSELECT,
571 VSLIDE, VCLASS and VPOPC. Two instructions, VCLIP and VCLIPI, do not
572 have RV Standard equivalents, so are left out of Simple-V.
573 All other instructions from RVV are topologically re-mapped and retain
574 their complete functionality, intact.
575
576 ## Instruction Format
577
578 The instruction format for Simple-V does not actually have *any* explicit
579 compare operations, *any* arithmetic, floating point or *any*
580 memory instructions.
581 Instead it *overloads* pre-existing branch operations into predicated
582 variants, and implicitly overloads arithmetic operations and LOAD/STORE
583 depending on CSR configurations for vector length, bitwidth and
584 predication. *This includes Compressed instructions* as well as any
585 future instructions and Custom Extensions.
586
587 * For analysis of RVV see [[v_comparative_analysis]] which begins to
588 outline topologically-equivalent mappings of instructions
589 * Also see Appendix "Retro-fitting Predication into branch-explicit ISA"
590 for format of Branch opcodes.
591
592 **TODO**: *analyse and decide whether the implicit nature of predication
593 as proposed is or is not a lot of hassle, and if explicit prefixes are
594 a better idea instead. Parallelism therefore effectively may end up
595 as always being 64-bit opcodes (32 for the prefix, 32 for the instruction)
596 with some opportunities for to use Compressed bringing it down to 48.
597 Also to consider is whether one or both of the last two remaining Compressed
598 instruction codes in Quadrant 1 could be used as a parallelism prefix,
599 bringing parallelised opcodes down to 32-bit (when combined with C)
600 and having the benefit of being explicit.*
601
602 ## VSETVL
603
604 VSETVL is slightly different from RVV in that the minimum vector length
605 is required to be at least the number of registers in the register file,
606 and no more than XLEN. This allows vector LOAD/STORE to be used to switch
607 the entire bank of registers using a single instruction (see Appendix,
608 "Context Switch Example"). The reason for limiting VSETVL to XLEN is
609 down to the fact that predication bits fit into a single register of length
610 XLEN bits.
611
612 The second minor change is that when VSETVL is requested to be stored
613 into x0, it is *ignored* silently.
614
615 Unlike RVV, implementors *must* provide pseudo-parallelism (using sequential
616 loops in hardware) if actual hardware-parallelism in the ALUs is not deployed.
617 A hybrid is also permitted (as used in Broadcom's VideoCore-IV) however this
618 must be *entirely* transparent to the ISA.
619
620 ## Branch Instruction:
621
622 Branch operations use standard RV opcodes that are reinterpreted to be
623 "predicate variants" in the instance where either of the two src registers
624 have their corresponding CSRvectorlen[src] entry as non-zero. When this
625 reinterpretation is enabled the predicate target register rs3 is to be
626 treated as a bitfield (up to a maximum of XLEN bits corresponding to a
627 maximum of XLEN elements).
628
629 If either of src1 or src2 are scalars (CSRvectorlen[src] == 0) the comparison
630 goes ahead as vector-scalar or scalar-vector. Implementors should note that
631 this could require considerable multi-porting of the register file in order
632 to parallelise properly, so may have to involve the use of register cacheing
633 and transparent copying (see Multiple-Banked Register File Architectures
634 paper).
635
636 In instances where no vectorisation is detected on either src registers
637 the operation is treated as an absolutely standard scalar branch operation.
638
639 This is the overloaded table for Integer-base Branch operations. Opcode
640 (bits 6..0) is set in all cases to 1100011.
641
642 [[!table data="""
643 31 .. 25 |24 ... 20 | 19 15 | 14 12 | 11 .. 8 | 7 | 6 ... 0 |
644 imm[12,10:5]| rs2 | rs1 | funct3 | imm[4:1] | imm[11] | opcode |
645 7 | 5 | 5 | 3 | 4 | 1 | 7 |
646 reserved | src2 | src1 | BPR | predicate rs3 || BRANCH |
647 reserved | src2 | src1 | 000 | predicate rs3 || BEQ |
648 reserved | src2 | src1 | 001 | predicate rs3 || BNE |
649 reserved | src2 | src1 | 010 | predicate rs3 || rsvd |
650 reserved | src2 | src1 | 011 | predicate rs3 || rsvd |
651 reserved | src2 | src1 | 100 | predicate rs3 || BLE |
652 reserved | src2 | src1 | 101 | predicate rs3 || BGE |
653 reserved | src2 | src1 | 110 | predicate rs3 || BLTU |
654 reserved | src2 | src1 | 111 | predicate rs3 || BGEU |
655 """]]
656
657 Note that just as with the standard (scalar, non-predicated) branch
658 operations, BLT, BGT, BLEU and BTGU may be synthesised by inverting
659 src1 and src2.
660
661 Below is the overloaded table for Floating-point Predication operations.
662 Interestingly no change is needed to the instruction format because
663 FP Compare already stores a 1 or a zero in its "rd" integer register
664 target, i.e. it's not actually a Branch at all: it's a compare.
665 The target needs to simply change to be a predication bitfield (done
666 implicitly).
667
668 As with
669 Standard RVF/D/Q, Opcode (bits 6..0) is set in all cases to 1010011.
670 Likewise Single-precision, fmt bits 26..25) is still set to 00.
671 Double-precision is still set to 01, whilst Quad-precision
672 appears not to have a definition in V2.3-Draft (but should be unaffected).
673
674 It is however noted that an entry "FNE" (the opposite of FEQ) is missing,
675 and whilst in ordinary branch code this is fine because the standard
676 RVF compare can always be followed up with an integer BEQ or a BNE (or
677 a compressed comparison to zero or non-zero), in predication terms that
678 becomes more of an impact as an explicit (scalar) instruction is needed
679 to invert the predicate bitmask. An additional encoding funct3=011 is
680 therefore proposed to cater for this.
681
682 [[!table data="""
683 31 .. 27| 26 .. 25 |24 ... 20 | 19 15 | 14 12 | 11 .. 7 | 6 ... 0 |
684 funct5 | fmt | rs2 | rs1 | funct3 | rd | opcode |
685 5 | 2 | 5 | 5 | 3 | 4 | 7 |
686 10100 | 00/01/11 | src2 | src1 | 010 | pred rs3 | FEQ |
687 10100 | 00/01/11 | src2 | src1 | **011**| pred rs3 | FNE |
688 10100 | 00/01/11 | src2 | src1 | 001 | pred rs3 | FLT |
689 10100 | 00/01/11 | src2 | src1 | 000 | pred rs3 | FLE |
690 """]]
691
692 Note (**TBD**): floating-point exceptions will need to be extended
693 to cater for multiple exceptions (and statuses of the same). The
694 usual approach is to have an array of status codes and bit-fields,
695 and one exception, rather than throw separate exceptions for each
696 Vector element.
697
698 In Hwacha EECS-2015-262 Section 6.7.2 the following pseudocode is given
699 for predicated compare operations of function "cmp":
700
701 for (int i=0; i<vl; ++i)
702 if ([!]preg[p][i])
703 preg[pd][i] = cmp(s1 ? vreg[rs1][i] : sreg[rs1],
704 s2 ? vreg[rs2][i] : sreg[rs2]);
705
706 With associated predication, vector-length adjustments and so on,
707 and temporarily ignoring bitwidth (which makes the comparisons more
708 complex), this becomes:
709
710 if I/F == INT: # integer type cmp
711 pred_enabled = int_pred_enabled # TODO: exception if not set!
712 preg = int_pred_reg[rd]
713 reg = int_regfile
714 else:
715 pred_enabled = fp_pred_enabled # TODO: exception if not set!
716 preg = fp_pred_reg[rd]
717 reg = fp_regfile
718
719 s1 = CSRvectorlen[src1] > 1;
720 s2 = CSRvectorlen[src2] > 1;
721 for (int i=0; i<vl; ++i)
722 preg[rs3][i] = cmp(s1 ? reg[src1+i] : reg[src1],
723 s2 ? reg[src2+i] : reg[src2]);
724
725 Notes:
726
727 * Predicated SIMD comparisons would break src1 and src2 further down
728 into bitwidth-sized chunks (see Appendix "Bitwidth Virtual Register
729 Reordering") setting Vector-Length times (number of SIMD elements) bits
730 in Predicate Register rs3 as opposed to just Vector-Length bits.
731 * Predicated Branches do not actually have an adjustment to the Program
732 Counter, so all of bits 25 through 30 in every case are not needed.
733 * There are plenty of reserved opcodes for which bits 25 through 30 could
734 be put to good use if there is a suitable use-case.
735 * FEQ and FNE (and BEQ and BNE) are included in order to save one
736 instruction having to invert the resultant predicate bitfield.
737 FLT and FLE may be inverted to FGT and FGE if needed by swapping
738 src1 and src2 (likewise the integer counterparts).
739
740 ## Compressed Branch Instruction:
741
742 [[!table data="""
743 15..13 | 12...10 | 9..7 | 6..5 | 4..2 | 1..0 | name |
744 funct3 | imm | rs10 | imm | | op | |
745 3 | 3 | 3 | 2 | 3 | 2 | |
746 C.BPR | pred rs3 | src1 | I/F B | src2 | C1 | |
747 110 | pred rs3 | src1 | I/F 0 | src2 | C1 | P.EQ |
748 111 | pred rs3 | src1 | I/F 0 | src2 | C1 | P.NE |
749 110 | pred rs3 | src1 | I/F 1 | src2 | C1 | P.LT |
750 111 | pred rs3 | src1 | I/F 1 | src2 | C1 | P.LE |
751 """]]
752
753 Notes:
754
755 * Bits 5 13 14 and 15 make up the comparator type
756 * Bit 6 indicates whether to use integer or floating-point comparisons
757 * In both floating-point and integer cases there are four predication
758 comparators: EQ/NEQ/LT/LE (with GT and GE being synthesised by inverting
759 src1 and src2).
760
761 ## LOAD / STORE Instructions <a name="load_store"></a>
762
763 For full analysis of topological adaptation of RVV LOAD/STORE
764 see [[v_comparative_analysis]]. All three types (LD, LD.S and LD.X)
765 may be implicitly overloaded into the one base RV LOAD instruction,
766 and likewise for STORE.
767
768 Revised LOAD:
769
770 [[!table data="""
771 31 | 30 | 29 25 | 24 20 | 19 15 | 14 12 | 11 7 | 6 0 |
772 imm[11:0] |||| rs1 | funct3 | rd | opcode |
773 1 | 1 | 5 | 5 | 5 | 3 | 5 | 7 |
774 ? | s | rs2 | imm[4:0] | base | width | dest | LOAD |
775 """]]
776
777 The exact same corresponding adaptation is also carried out on the single,
778 double and quad precision floating-point LOAD-FP and STORE-FP operations,
779 which fit the exact same instruction format. Thus all three types
780 (unit, stride and indexed) may be fitted into FLW, FLD and FLQ,
781 as well as FSW, FSD and FSQ.
782
783 Notes:
784
785 * LOAD remains functionally (topologically) identical to RVV LOAD
786 (for both integer and floating-point variants).
787 * Predication CSR-marking register is not explicitly shown in instruction, it's
788 implicit based on the CSR predicate state for the rd (destination) register
789 * rs2, the source, may *also be marked as a vector*, which implicitly
790 is taken to indicate "Indexed Load" (LD.X)
791 * Bit 30 indicates "element stride" or "constant-stride" (LD or LD.S)
792 * Bit 31 is reserved (ideas under consideration: auto-increment)
793 * **TODO**: include CSR SIMD bitwidth in the pseudo-code below.
794 * **TODO**: clarify where width maps to elsize
795
796 Pseudo-code (excludes CSR SIMD bitwidth for simplicity):
797
798 if (unit-strided) stride = elsize;
799 else stride = areg[as2]; // constant-strided
800
801 pred_enabled = int_pred_enabled
802 preg = int_pred_reg[rd]
803
804 for (int i=0; i<vl; ++i)
805 if (preg_enabled[rd] && [!]preg[i])
806 for (int j=0; j<seglen+1; j++)
807 {
808 if CSRvectorised[rs2])
809 offs = vreg[rs2][i]
810 else
811 offs = i*(seglen+1)*stride;
812 vreg[rd+j][i] = mem[sreg[base] + offs + j*stride];
813 }
814
815 Taking CSR (SIMD) bitwidth into account involves using the vector
816 length and register encoding according to the "Bitwidth Virtual Register
817 Reordering" scheme shown in the Appendix (see function "regoffs").
818
819 A similar instruction exists for STORE, with identical topological
820 translation of all features. **TODO**
821
822 ## Compressed LOAD / STORE Instructions
823
824 Compressed LOAD and STORE are of the same format, where bits 2-4 are
825 a src register instead of dest:
826
827 [[!table data="""
828 15 13 | 12 10 | 9 7 | 6 5 | 4 2 | 1 0 |
829 funct3 | imm | rs10 | imm | rd0 | op |
830 3 | 3 | 3 | 2 | 3 | 2 |
831 C.LW | offset[5:3] | base | offset[2|6] | dest | C0 |
832 """]]
833
834 Unfortunately it is not possible to fit the full functionality
835 of vectorised LOAD / STORE into C.LD / C.ST: the "X" variants (Indexed)
836 require another operand (rs2) in addition to the operand width
837 (which is also missing), offset, base, and src/dest.
838
839 However a close approximation may be achieved by taking the top bit
840 of the offset in each of the five types of LD (and ST), reducing the
841 offset to 4 bits and utilising the 5th bit to indicate whether "stride"
842 is to be enabled. In this way it is at least possible to introduce
843 that functionality.
844
845 (**TODO**: *assess whether the loss of one bit from offset is worth having
846 "stride" capability.*)
847
848 We also assume (including for the "stride" variant) that the "width"
849 parameter, which is missing, is derived and implicit, just as it is
850 with the standard Compressed LOAD/STORE instructions. For C.LW, C.LD
851 and C.LQ, the width is implicitly 4, 8 and 16 respectively, whilst for
852 C.FLW and C.FLD the width is implicitly 4 and 8 respectively.
853
854 Interestingly we note that the Vectorised Simple-V variant of
855 LOAD/STORE (Compressed and otherwise), due to it effectively using the
856 standard register file(s), is the direct functional equivalent of
857 standard load-multiple and store-multiple instructions found in other
858 processors.
859
860 In Section 12.3 riscv-isa manual V2.3-draft it is noted the comments on
861 page 76, "For virtual memory systems some data accesses could be resident
862 in physical memory and some not". The interesting question then arises:
863 how does RVV deal with the exact same scenario?
864 Expired U.S. Patent 5895501 (Filing Date Sep 3 1996) describes a method
865 of detecting early page / segmentation faults and adjusting the TLB
866 in advance, accordingly: other strategies are explored in the Appendix
867 Section "Virtual Memory Page Faults".
868
869 # Exceptions
870
871 > What does an ADD of two different-sized vectors do in simple-V?
872
873 * if the two source operands are not the same, throw an exception.
874 * if the destination operand is also a vector, and the source is longer
875 than the destination, throw an exception.
876
877 > And what about instructions like JALR? 
878 > What does jumping to a vector do?
879
880 * Throw an exception. Whether that actually results in spawning threads
881 as part of the trap-handling remains to be seen.
882
883 # Impementing V on top of Simple-V
884
885 With Simple-V converting the original RVV draft concept-for-concept
886 from explicit opcodes to implicit overloading of existing RV Standard
887 Extensions, certain features were (deliberately) excluded that need
888 to be added back in for RVV to reach its full potential. This is
889 made slightly complicated by the fact that RVV itself has two
890 levels: Base and reserved future functionality.
891
892 * Representation Encoding is entirely left out of Simple-V in favour of
893 implicitly taking the exact (explicit) meaning from RV Standard Extensions.
894 * VCLIP and VCLIPI do not have corresponding RV Standard Extension
895 opcodes (and are the only such operations).
896 * Extended Element bitwidths (1 through to 24576 bits) were left out
897 of Simple-V as, again, there is no corresponding RV Standard Extension
898 that covers anything even below 32-bit operands.
899 * Polymorphism was entirely left out of Simple-V due to the inherent
900 complexity of automatic type-conversion.
901 * Vector Register files were specifically left out of Simple-V in favour
902 of fitting on top of the integer and floating-point files. An
903 "RVV re-retro-fit" needs to be able to mark (implicitly marked)
904 registers as being actually in a separate *vector* register file.
905 * Fortunately in RVV (Draft 0.4, V2.3-Draft), the "base" vector
906 register file size is 5 bits (32 registers), whilst the "Extended"
907 variant of RVV specifies 8 bits (256 registers) and has yet to
908 be published.
909 * One big difference: Sections 17.12 and 17.17, there are only two possible
910 predication registers in RVV "Base". Through the "indirect" method,
911 Simple-V provides a key-value CSR table that allows (arbitrarily)
912 up to 16 (TBD) of either the floating-point or integer registers to
913 be marked as "predicated" (key), and if so, which integer register to
914 use as the predication mask (value).
915
916 **TODO**
917
918 # Implementing P (renamed to DSP) on top of Simple-V
919
920 * Implementors indicate chosen bitwidth support in Vector-bitwidth CSR
921 (caveat: anything not specified drops through to software-emulation / traps)
922 * TODO
923
924 # Appendix
925
926 ## V-Extension to Simple-V Comparative Analysis
927
928 This section has been moved to its own page [[v_comparative_analysis]]
929
930 ## P-Ext ISA
931
932 This section has been moved to its own page [[p_comparative_analysis]]
933
934 ## Comparison of "Traditional" SIMD, Alt-RVP, Simple-V and RVV Proposals <a name="parallelism_comparisons"></a>
935
936 This section compares the various parallelism proposals as they stand,
937 including traditional SIMD, in terms of features, ease of implementation,
938 complexity, flexibility, and die area.
939
940 ### [[harmonised_rvv_rvp]]
941
942 This is an interesting proposal under development to retro-fit the AndesStar
943 P-Ext into V-Ext.
944
945 ### [[alt_rvp]]
946
947 Primary benefit of Alt-RVP is the simplicity with which parallelism
948 may be introduced (effective multiplication of regfiles and associated ALUs).
949
950 * plus: the simplicity of the lanes (combined with the regularity of
951 allocating identical opcodes multiple independent registers) meaning
952 that SRAM or 2R1W can be used for entire regfile (potentially).
953 * minus: a more complex instruction set where the parallelism is much
954 more explicitly directly specified in the instruction and
955 * minus: if you *don't* have an explicit instruction (opcode) and you
956 need one, the only place it can be added is... in the vector unit and
957 * minus: opcode functions (and associated ALUs) duplicated in Alt-RVP are
958 not useable or accessible in other Extensions.
959 * plus-and-minus: Lanes may be utilised for high-speed context-switching
960 but with the down-side that they're an all-or-nothing part of the Extension.
961 No Alt-RVP: no fast register-bank switching.
962 * plus: Lane-switching would mean that complex operations not suited to
963 parallelisation can be carried out, followed by further parallel Lane-based
964 work, without moving register contents down to memory (and back)
965 * minus: Access to registers across multiple lanes is challenging. "Solution"
966 is to drop data into memory and immediately back in again (like MMX).
967
968 ### Simple-V
969
970 Primary benefit of Simple-V is the OO abstraction of parallel principles
971 from actual (internal) parallel hardware. It's an API in effect that's
972 designed to be slotted in to an existing implementation (just after
973 instruction decode) with minimum disruption and effort.
974
975 * minus: the complexity (if full parallelism is to be exploited)
976 of having to use register renames, OoO, VLIW, register file cacheing,
977 all of which has been done before but is a pain
978 * plus: transparent re-use of existing opcodes as-is just indirectly
979 saying "this register's now a vector" which
980 * plus: means that future instructions also get to be inherently
981 parallelised because there's no "separate vector opcodes"
982 * plus: Compressed instructions may also be (indirectly) parallelised
983 * minus: the indirect nature of Simple-V means that setup (setting
984 a CSR register to indicate vector length, a separate one to indicate
985 that it is a predicate register and so on) means a little more setup
986 time than Alt-RVP or RVV's "direct and within the (longer) instruction"
987 approach.
988 * plus: shared register file meaning that, like Alt-RVP, complex
989 operations not suited to parallelisation may be carried out interleaved
990 between parallelised instructions *without* requiring data to be dropped
991 down to memory and back (into a separate vectorised register engine).
992 * plus-and-maybe-minus: re-use of integer and floating-point 32-wide register
993 files means that huge parallel workloads would use up considerable
994 chunks of the register file. However in the case of RV64 and 32-bit
995 operations, that effectively means 64 slots are available for parallel
996 operations.
997 * plus: inherent parallelism (actual parallel ALUs) doesn't actually need to
998 be added, yet the instruction opcodes remain unchanged (and still appear
999 to be parallel). consistent "API" regardless of actual internal parallelism:
1000 even an in-order single-issue implementation with a single ALU would still
1001 appear to have parallel vectoristion.
1002 * hard-to-judge: if actual inherent underlying ALU parallelism is added it's
1003 hard to say if there would be pluses or minuses (on die area). At worse it
1004 would be "no worse" than existing register renaming, OoO, VLIW and register
1005 file cacheing schemes.
1006
1007 ### RVV (as it stands, Draft 0.4 Section 17, RISC-V ISA V2.3-Draft)
1008
1009 RVV is extremely well-designed and has some amazing features, including
1010 2D reorganisation of memory through LOAD/STORE "strides".
1011
1012 * plus: regular predictable workload means that implementations may
1013 streamline effects on L1/L2 Cache.
1014 * plus: regular and clear parallel workload also means that lanes
1015 (similar to Alt-RVP) may be used as an implementation detail,
1016 using either SRAM or 2R1W registers.
1017 * plus: separate engine with no impact on the rest of an implementation
1018 * minus: separate *complex* engine with no RTL (ALUs, Pipeline stages) reuse
1019 really feasible.
1020 * minus: no ISA abstraction or re-use either: additions to other Extensions
1021 do not gain parallelism, resulting in prolific duplication of functionality
1022 inside RVV *and out*.
1023 * minus: when operations require a different approach (scalar operations
1024 using the standard integer or FP regfile) an entire vector must be
1025 transferred out to memory, into standard regfiles, then back to memory,
1026 then back to the vector unit, this to occur potentially multiple times.
1027 * minus: will never fit into Compressed instruction space (as-is. May
1028 be able to do so if "indirect" features of Simple-V are partially adopted).
1029 * plus-and-slight-minus: extended variants may address up to 256
1030 vectorised registers (requires 48/64-bit opcodes to do it).
1031 * minus-and-partial-plus: separate engine plus complexity increases
1032 implementation time and die area, meaning that adoption is likely only
1033 to be in high-performance specialist supercomputing (where it will
1034 be absolutely superb).
1035
1036 ### Traditional SIMD
1037
1038 The only really good things about SIMD are how easy it is to implement and
1039 get good performance. Unfortunately that makes it quite seductive...
1040
1041 * plus: really straightforward, ALU basically does several packed operations
1042 at once. Parallelism is inherent at the ALU, making the addition of
1043 SIMD-style parallelism an easy decision that has zero significant impact
1044 on the rest of any given architectural design and layout.
1045 * plus (continuation): SIMD in simple in-order single-issue designs can
1046 therefore result in superb throughput, easily achieved even with a very
1047 simple execution model.
1048 * minus: ridiculously complex setup and corner-cases that disproportionately
1049 increase instruction count on what would otherwise be a "simple loop",
1050 should the number of elements in an array not happen to exactly match
1051 the SIMD group width.
1052 * minus: getting data usefully out of registers (if separate regfiles
1053 are used) means outputting to memory and back.
1054 * minus: quite a lot of supplementary instructions for bit-level manipulation
1055 are needed in order to efficiently extract (or prepare) SIMD operands.
1056 * minus: MASSIVE proliferation of ISA both in terms of opcodes in one
1057 dimension and parallelism (width): an at least O(N^2) and quite probably
1058 O(N^3) ISA proliferation that often results in several thousand
1059 separate instructions. all requiring separate and distinct corner-case
1060 algorithms!
1061 * minus: EVEN BIGGER proliferation of SIMD ISA if the functionality of
1062 8, 16, 32 or 64-bit reordering is built-in to the SIMD instruction.
1063 For example: add (high|low) 16-bits of r1 to (low|high) of r2 requires
1064 four separate and distinct instructions: one for (r1:low r2:high),
1065 one for (r1:high r2:low), one for (r1:high r2:high) and one for
1066 (r1:low r2:low) *per function*.
1067 * minus: EVEN BIGGER proliferation of SIMD ISA if there is a mismatch
1068 between operand and result bit-widths. In combination with high/low
1069 proliferation the situation is made even worse.
1070 * minor-saving-grace: some implementations *may* have predication masks
1071 that allow control over individual elements within the SIMD block.
1072
1073 ## Comparison *to* Traditional SIMD: Alt-RVP, Simple-V and RVV Proposals <a name="simd_comparison"></a>
1074
1075 This section compares the various parallelism proposals as they stand,
1076 *against* traditional SIMD as opposed to *alongside* SIMD. In other words,
1077 the question is asked "How can each of the proposals effectively implement
1078 (or replace) SIMD, and how effective would they be"?
1079
1080 ### [[alt_rvp]]
1081
1082 * Alt-RVP would not actually replace SIMD but would augment it: just as with
1083 a SIMD architecture where the ALU becomes responsible for the parallelism,
1084 Alt-RVP ALUs would likewise be so responsible... with *additional*
1085 (lane-based) parallelism on top.
1086 * Thus at least some of the downsides of SIMD ISA O(N^5) proliferation by
1087 at least one dimension are avoided (architectural upgrades introducing
1088 128-bit then 256-bit then 512-bit variants of the exact same 64-bit
1089 SIMD block)
1090 * Thus, unfortunately, Alt-RVP would suffer the same inherent proliferation
1091 of instructions as SIMD, albeit not quite as badly (due to Lanes).
1092 * In the same discussion for Alt-RVP, an additional proposal was made to
1093 be able to subdivide the bits of each register lane (columns) down into
1094 arbitrary bit-lengths (RGB 565 for example).
1095 * A recommendation was given instead to make the subdivisions down to 32-bit,
1096 16-bit or even 8-bit, effectively dividing the registerfile into
1097 Lane0(H), Lane0(L), Lane1(H) ... LaneN(L) or further. If inter-lane
1098 "swapping" instructions were then introduced, some of the disadvantages
1099 of SIMD could be mitigated.
1100
1101 ### RVV
1102
1103 * RVV is designed to replace SIMD with a better paradigm: arbitrary-length
1104 parallelism.
1105 * However whilst SIMD is usually designed for single-issue in-order simple
1106 DSPs with a focus on Multimedia (Audio, Video and Image processing),
1107 RVV's primary focus appears to be on Supercomputing: optimisation of
1108 mathematical operations that fit into the OpenCL space.
1109 * Adding functions (operations) that would normally fit (in parallel)
1110 into a SIMD instruction requires an equivalent to be added to the
1111 RVV Extension, if one does not exist. Given the specialist nature of
1112 some SIMD instructions (8-bit or 16-bit saturated or halving add),
1113 this possibility seems extremely unlikely to occur, even if the
1114 implementation overhead of RVV were acceptable (compared to
1115 normal SIMD/DSP-style single-issue in-order simplicity).
1116
1117 ### Simple-V
1118
1119 * Simple-V borrows hugely from RVV as it is intended to be easy to
1120 topologically transplant every single instruction from RVV (as
1121 designed) into Simple-V equivalents, with *zero loss of functionality
1122 or capability*.
1123 * With the "parallelism" abstracted out, a hypothetical SIMD-less "DSP"
1124 Extension which contained the basic primitives (non-parallelised
1125 8, 16 or 32-bit SIMD operations) inherently *become* parallel,
1126 automatically.
1127 * Additionally, standard operations (ADD, MUL) that would normally have
1128 to have special SIMD-parallel opcodes added need no longer have *any*
1129 of the length-dependent variants (2of 32-bit ADDs in a 64-bit register,
1130 4of 32-bit ADDs in a 128-bit register) because Simple-V takes the
1131 *standard* RV opcodes (present and future) and automatically parallelises
1132 them.
1133 * By inheriting the RVV feature of arbitrary vector-length, then just as
1134 with RVV the corner-cases and ISA proliferation of SIMD is avoided.
1135 * Whilst not entirely finalised, registers are expected to be
1136 capable of being subdivided down to an implementor-chosen bitwidth
1137 in the underlying hardware (r1 becomes r1[31..24] r1[23..16] r1[15..8]
1138 and r1[7..0], or just r1[31..16] r1[15..0]) where implementors can
1139 choose to have separate independent 8-bit ALUs or dual-SIMD 16-bit
1140 ALUs that perform twin 8-bit operations as they see fit, or anything
1141 else including no subdivisions at all.
1142 * Even though implementors have that choice even to have full 64-bit
1143 (with RV64) SIMD, they *must* provide predication that transparently
1144 switches off appropriate units on the last loop, thus neatly fitting
1145 underlying SIMD ALU implementations *into* the arbitrary vector-length
1146 RVV paradigm, keeping the uniform consistent API that is a key strategic
1147 feature of Simple-V.
1148 * With Simple-V fitting into the standard register files, certain classes
1149 of SIMD operations such as High/Low arithmetic (r1[31..16] + r2[15..0])
1150 can be done by applying *Parallelised* Bit-manipulation operations
1151 followed by parallelised *straight* versions of element-to-element
1152 arithmetic operations, even if the bit-manipulation operations require
1153 changing the bitwidth of the "vectors" to do so. Predication can
1154 be utilised to skip high words (or low words) in source or destination.
1155 * In essence, the key downside of SIMD - massive duplication of
1156 identical functions over time as an architecture evolves from 32-bit
1157 wide SIMD all the way up to 512-bit, is avoided with Simple-V, through
1158 vector-style parallelism being dropped on top of 8-bit or 16-bit
1159 operations, all the while keeping a consistent ISA-level "API" irrespective
1160 of implementor design choices (or indeed actual implementations).
1161
1162 ### Example Instruction translation: <a name="example_translation"></a>
1163
1164 Instructions "ADD r2 r4 r4" would result in three instructions being
1165 generated and placed into the FIFO:
1166
1167 * ADD r2 r4 r4
1168 * ADD r2 r5 r5
1169 * ADD r2 r6 r6
1170
1171 ## Example of vector / vector, vector / scalar, scalar / scalar => vector add
1172
1173 register CSRvectorlen[XLEN][4]; # not quite decided yet about this one...
1174 register CSRpredicate[XLEN][4]; # 2^4 is max vector length
1175 register CSRreg_is_vectorised[XLEN]; # just for fun support scalars as well
1176 register x[32][XLEN];
1177
1178 function op_add(rd, rs1, rs2, predr)
1179 {
1180    /* note that this is ADD, not PADD */
1181    int i, id, irs1, irs2;
1182    # checks CSRvectorlen[rd] == CSRvectorlen[rs] etc. ignored
1183    # also destination makes no sense as a scalar but what the hell...
1184    for (i = 0, id=0, irs1=0, irs2=0; i<CSRvectorlen[rd]; i++)
1185       if (CSRpredicate[predr][i]) # i *think* this is right...
1186          x[rd+id] <= x[rs1+irs1] + x[rs2+irs2];
1187       # now increment the idxs
1188       if (CSRreg_is_vectorised[rd]) # bitfield check rd, scalar/vector?
1189          id += 1;
1190       if (CSRreg_is_vectorised[rs1]) # bitfield check rs1, scalar/vector?
1191          irs1 += 1;
1192       if (CSRreg_is_vectorised[rs2]) # bitfield check rs2, scalar/vector?
1193          irs2 += 1;
1194 }
1195
1196 ## Retro-fitting Predication into branch-explicit ISA <a name="predication_retrofit"></a>
1197
1198 One of the goals of this parallelism proposal is to avoid instruction
1199 duplication. However, with the base ISA having been designed explictly
1200 to *avoid* condition-codes entirely, shoe-horning predication into it
1201 bcomes quite challenging.
1202
1203 However what if all branch instructions, if referencing a vectorised
1204 register, were instead given *completely new analogous meanings* that
1205 resulted in a parallel bit-wise predication register being set? This
1206 would have to be done for both C.BEQZ and C.BNEZ, as well as BEQ, BNE,
1207 BLT and BGE.
1208
1209 We might imagine that FEQ, FLT and FLT would also need to be converted,
1210 however these are effectively *already* in the precise form needed and
1211 do not need to be converted *at all*! The difference is that FEQ, FLT
1212 and FLE *specifically* write a 1 to an integer register if the condition
1213 holds, and 0 if not. All that needs to be done here is to say, "if
1214 the integer register is tagged with a bit that says it is a predication
1215 register, the **bit** in the integer register is set based on the
1216 current vector index" instead.
1217
1218 There is, in the standard Conditional Branch instruction, more than
1219 adequate space to interpret it in a similar fashion:
1220
1221 [[!table data="""
1222 31 |30 ..... 25 |24..20|19..15| 14...12| 11.....8 | 7 | 6....0 |
1223 imm[12] | imm[10:5] |rs2 | rs1 | funct3 | imm[4:1] | imm[11] | opcode |
1224 1 | 6 | 5 | 5 | 3 | 4 | 1 | 7 |
1225 offset[12,10:5] || src2 | src1 | BEQ | offset[11,4:1] || BRANCH |
1226 """]]
1227
1228 This would become:
1229
1230 [[!table data="""
1231 31 | 30 .. 25 |24 ... 20 | 19 15 | 14 12 | 11 .. 8 | 7 | 6 ... 0 |
1232 imm[12] | imm[10:5]| rs2 | rs1 | funct3 | imm[4:1] | imm[11] | opcode |
1233 1 | 6 | 5 | 5 | 3 | 4 | 1 | 7 |
1234 reserved || src2 | src1 | BEQ | predicate rs3 || BRANCH |
1235 """]]
1236
1237 Similarly the C.BEQZ and C.BNEZ instruction format may be retro-fitted,
1238 with the interesting side-effect that there is space within what is presently
1239 the "immediate offset" field to reinterpret that to add in not only a bit
1240 field to distinguish between floating-point compare and integer compare,
1241 not only to add in a second source register, but also use some of the bits as
1242 a predication target as well.
1243
1244 [[!table data="""
1245 15..13 | 12 ....... 10 | 9...7 | 6 ......... 2 | 1 .. 0 |
1246 funct3 | imm | rs10 | imm | op |
1247 3 | 3 | 3 | 5 | 2 |
1248 C.BEQZ | offset[8,4:3] | src | offset[7:6,2:1,5] | C1 |
1249 """]]
1250
1251 Now uses the CS format:
1252
1253 [[!table data="""
1254 15..13 | 12 . 10 | 9 .. 7 | 6 .. 5 | 4..2 | 1 .. 0 |
1255 funct3 | imm | rs10 | imm | | op |
1256 3 | 3 | 3 | 2 | 3 | 2 |
1257 C.BEQZ | pred rs3 | src1 | I/F B | src2 | C1 |
1258 """]]
1259
1260 Bit 6 would be decoded as "operation refers to Integer or Float" including
1261 interpreting src1 and src2 accordingly as outlined in Table 12.2 of the
1262 "C" Standard, version 2.0,
1263 whilst Bit 5 would allow the operation to be extended, in combination with
1264 funct3 = 110 or 111: a combination of four distinct (predicated) comparison
1265 operators. In both floating-point and integer cases those could be
1266 EQ/NEQ/LT/LE (with GT and GE being synthesised by inverting src1 and src2).
1267
1268 ## Register reordering <a name="register_reordering"></a>
1269
1270 ### Register File
1271
1272 | Reg Num | Bits |
1273 | ------- | ---- |
1274 | r0 | (32..0) |
1275 | r1 | (32..0) |
1276 | r2 | (32..0) |
1277 | r3 | (32..0) |
1278 | r4 | (32..0) |
1279 | r5 | (32..0) |
1280 | r6 | (32..0) |
1281 | r7 | (32..0) |
1282 | .. | (32..0) |
1283 | r31| (32..0) |
1284
1285 ### Vectorised CSR
1286
1287 May not be an actual CSR: may be generated from Vector Length CSR:
1288 single-bit is less burdensome on instruction decode phase.
1289
1290 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
1291 | - | - | - | - | - | - | - | - |
1292 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 |
1293
1294 ### Vector Length CSR
1295
1296 | Reg Num | (3..0) |
1297 | ------- | ---- |
1298 | r0 | 2 |
1299 | r1 | 0 |
1300 | r2 | 1 |
1301 | r3 | 1 |
1302 | r4 | 3 |
1303 | r5 | 0 |
1304 | r6 | 0 |
1305 | r7 | 1 |
1306
1307 ### Virtual Register Reordering
1308
1309 This example assumes the above Vector Length CSR table
1310
1311 | Reg Num | Bits (0) | Bits (1) | Bits (2) |
1312 | ------- | -------- | -------- | -------- |
1313 | r0 | (32..0) | (32..0) |
1314 | r2 | (32..0) |
1315 | r3 | (32..0) |
1316 | r4 | (32..0) | (32..0) | (32..0) |
1317 | r7 | (32..0) |
1318
1319 ### Bitwidth Virtual Register Reordering
1320
1321 This example goes a little further and illustrates the effect that a
1322 bitwidth CSR has been set on a register. Preconditions:
1323
1324 * RV32 assumed
1325 * CSRintbitwidth[2] = 010 # integer r2 is 16-bit
1326 * CSRintvlength[2] = 3 # integer r2 is a vector of length 3
1327 * vsetl rs1, 5 # set the vector length to 5
1328
1329 This is interpreted as follows:
1330
1331 * Given that the context is RV32, ELEN=32.
1332 * With ELEN=32 and bitwidth=16, the number of SIMD elements is 2
1333 * Therefore the actual vector length is up to *six* elements
1334 * However vsetl sets a length 5 therefore the last "element" is skipped
1335
1336 So when using an operation that uses r2 as a source (or destination)
1337 the operation is carried out as follows:
1338
1339 * 16-bit operation on r2(15..0) - vector element index 0
1340 * 16-bit operation on r2(31..16) - vector element index 1
1341 * 16-bit operation on r3(15..0) - vector element index 2
1342 * 16-bit operation on r3(31..16) - vector element index 3
1343 * 16-bit operation on r4(15..0) - vector element index 4
1344 * 16-bit operation on r4(31..16) **NOT** carried out due to length being 5
1345
1346 Predication has been left out of the above example for simplicity, however
1347 predication is ANDed with the latter stages (vsetl not equal to maximum
1348 capacity).
1349
1350 Note also that it is entirely an implementor's choice as to whether to have
1351 actual separate ALUs down to the minimum bitwidth, or whether to have something
1352 more akin to traditional SIMD (at any level of subdivision: 8-bit SIMD
1353 operations carried out 32-bits at a time is perfectly acceptable, as is
1354 8-bit SIMD operations carried out 16-bits at a time requiring two ALUs).
1355 Regardless of the internal parallelism choice, *predication must
1356 still be respected*, making Simple-V in effect the "consistent public API".
1357
1358 vew may be one of the following (giving a table "bytestable", used below):
1359
1360 | vew | bitwidth | bytestable |
1361 | --- | -------- | ---------- |
1362 | 000 | default | XLEN/8 |
1363 | 001 | 8 | 1 |
1364 | 010 | 16 | 2 |
1365 | 011 | 32 | 4 |
1366 | 100 | 64 | 8 |
1367 | 101 | 128 | 16 |
1368 | 110 | rsvd | rsvd |
1369 | 111 | rsvd | rsvd |
1370
1371 Pseudocode for vector length taking CSR SIMD-bitwidth into account:
1372
1373 vew = CSRbitwidth[rs1]
1374 if (vew == 0)
1375 bytesperreg = (XLEN/8) # or FLEN as appropriate
1376 else:
1377 bytesperreg = bytestable[vew] # 1 2 4 8 16
1378 simdmult = (XLEN/8) / bytesperreg # or FLEN as appropriate
1379 vlen = CSRvectorlen[rs1] * simdmult
1380
1381 To index an element in a register rnum where the vector element index is i:
1382
1383 function regoffs(rnum, i):
1384 regidx = floor(i / simdmult) # integer-div rounded down
1385 byteidx = i % simdmult # integer-remainder
1386 return rnum + regidx, # actual real register
1387 byteidx * 8, # low
1388 byteidx * 8 + (vew-1), # high
1389
1390 ### Insights
1391
1392 SIMD register file splitting still to consider. For RV64, benefits of doubling
1393 (quadrupling in the case of Half-Precision IEEE754 FP) the apparent
1394 size of the floating point register file to 64 (128 in the case of HP)
1395 seem pretty clear and worth the complexity.
1396
1397 64 virtual 32-bit F.P. registers and given that 32-bit FP operations are
1398 done on 64-bit registers it's not so conceptually difficult.  May even
1399 be achieved by *actually* splitting the regfile into 64 virtual 32-bit
1400 registers such that a 64-bit FP scalar operation is dropped into (r0.H
1401 r0.L) tuples.  Implementation therefore hidden through register renaming.
1402
1403 Implementations intending to introduce VLIW, OoO and parallelism
1404 (even without Simple-V) would then find that the instructions are
1405 generated quicker (or in a more compact fashion that is less heavy
1406 on caches). Interestingly we observe then that Simple-V is about
1407 "consolidation of instruction generation", where actual parallelism
1408 of underlying hardware is an implementor-choice that could just as
1409 equally be applied *without* Simple-V even being implemented.
1410
1411 ## Analysis of CSR decoding on latency <a name="csr_decoding_analysis"></a>
1412
1413 It could indeed have been logically deduced (or expected), that there
1414 would be additional decode latency in this proposal, because if
1415 overloading the opcodes to have different meanings, there is guaranteed
1416 to be some state, some-where, directly related to registers.
1417
1418 There are several cases:
1419
1420 * All operands vector-length=1 (scalars), all operands
1421 packed-bitwidth="default": instructions are passed through direct as if
1422 Simple-V did not exist.  Simple-V is, in effect, completely disabled.
1423 * At least one operand vector-length > 1, all operands
1424 packed-bitwidth="default": any parallel vector ALUs placed on "alert",
1425 virtual parallelism looping may be activated.
1426 * All operands vector-length=1 (scalars), at least one
1427 operand packed-bitwidth != default: degenerate case of SIMD,
1428 implementation-specific complexity here (packed decode before ALUs or
1429 *IN* ALUs)
1430 * At least one operand vector-length > 1, at least one operand
1431 packed-bitwidth != default: parallel vector ALUs (if any)
1432 placed on "alert", virtual parallelsim looping may be activated,
1433 implementation-specific SIMD complexity kicks in (packed decode before
1434 ALUs or *IN* ALUs).
1435
1436 Bear in mind that the proposal includes that the decision whether
1437 to parallelise in hardware or whether to virtual-parallelise (to
1438 dramatically simplify compilers and also not to run into the SIMD
1439 instruction proliferation nightmare) *or* a transprent combination
1440 of both, be done on a *per-operand basis*, so that implementors can
1441 specifically choose to create an application-optimised implementation
1442 that they believe (or know) will sell extremely well, without having
1443 "Extra Standards-Mandated Baggage" that would otherwise blow their area
1444 or power budget completely out the window.
1445
1446 Additionally, two possible CSR schemes have been proposed, in order to
1447 greatly reduce CSR space:
1448
1449 * per-register CSRs (vector-length and packed-bitwidth)
1450 * a smaller number of CSRs with the same information but with an *INDEX*
1451 specifying WHICH register in one of three regfiles (vector, fp, int)
1452 the length and bitwidth applies to.
1453
1454 (See "CSR vector-length and CSR SIMD packed-bitwidth" section for details)
1455
1456 In addition, LOAD/STORE has its own associated proposed CSRs that
1457 mirror the STRIDE (but not yet STRIDE-SEGMENT?) functionality of
1458 V (and Hwacha).
1459
1460 Also bear in mind that, for reasons of simplicity for implementors,
1461 I was coming round to the idea of permitting implementors to choose
1462 exactly which bitwidths they would like to support in hardware and which
1463 to allow to fall through to software-trap emulation.
1464
1465 So the question boils down to:
1466
1467 * whether either (or both) of those two CSR schemes have significant
1468 latency that could even potentially require an extra pipeline decode stage
1469 * whether there are implementations that can be thought of which do *not*
1470 introduce significant latency
1471 * whether it is possible to explicitly (through quite simply
1472 disabling Simple-V-Ext) or implicitly (detect the case all-vlens=1,
1473 all-simd-bitwidths=default) switch OFF any decoding, perhaps even to
1474 the extreme of skipping an entire pipeline stage (if one is needed)
1475 * whether packed bitwidth and associated regfile splitting is so complex
1476 that it should definitely, definitely be made mandatory that implementors
1477 move regfile splitting into the ALU, and what are the implications of that
1478 * whether even if that *is* made mandatory, is software-trapped
1479 "unsupported bitwidths" still desirable, on the basis that SIMD is such
1480 a complete nightmare that *even* having a software implementation is
1481 better, making Simple-V have more in common with a software API than
1482 anything else.
1483
1484 Whilst the above may seem to be severe minuses, there are some strong
1485 pluses:
1486
1487 * Significant reduction of V's opcode space: over 95%.
1488 * Smaller reduction of P's opcode space: around 10%.
1489 * The potential to use Compressed instructions in both Vector and SIMD
1490 due to the overloading of register meaning (implicit vectorisation,
1491 implicit packing)
1492 * Not only present but also future extensions automatically gain parallelism.
1493 * Already mentioned but worth emphasising: the simplification to compiler
1494 writers and assembly-level writers of having the same consistent ISA
1495 regardless of whether the internal level of parallelism (number of
1496 parallel ALUs) is only equal to one ("virtual" parallelism), or is
1497 greater than one, should not be underestimated.
1498
1499 ## Reducing Register Bank porting
1500
1501 This looks quite reasonable.
1502 <https://www.princeton.edu/~rblee/ELE572Papers/MultiBankRegFile_ISCA2000.pdf>
1503
1504 The main details are outlined on page 4.  They propose a 2-level register
1505 cache hierarchy, note that registers are typically only read once, that
1506 you never write back from upper to lower cache level but always go in a
1507 cycle lower -> upper -> ALU -> lower, and at the top of page 5 propose
1508 a scheme where you look ahead by only 2 instructions to determine which
1509 registers to bring into the cache.
1510
1511 The nice thing about a vector architecture is that you *know* that
1512 *even more* registers are going to be pulled in: Hwacha uses this fact
1513 to optimise L1/L2 cache-line usage (avoid thrashing), strangely enough
1514 by *introducing* deliberate latency into the execution phase.
1515
1516 ## Overflow registers in combination with predication
1517
1518 **TODO**: propose overflow registers be actually one of the integer regs
1519 (flowing to multiple regs).
1520
1521 **TODO**: propose "mask" (predication) registers likewise. combination with
1522 standard RV instructions and overflow registers extremely powerful, see
1523 Aspex ASP.
1524
1525 When integer overflow is stored in an easily-accessible bit (or another
1526 register), parallelisation turns this into a group of bits which can
1527 potentially be interacted with in predication, in interesting and powerful
1528 ways. For example, by taking the integer-overflow result as a predication
1529 field and shifting it by one, a predicated vectorised "add one" can emulate
1530 "carry" on arbitrary (unlimited) length addition.
1531
1532 However despite RVV having made room for floating-point exceptions, neither
1533 RVV nor base RV have taken integer-overflow (carry) into account, which
1534 makes proposing it quite challenging given that the relevant (Base) RV
1535 sections are frozen. Consequently it makes sense to forgo this feature.
1536
1537 ## Context Switch Example <a name="context_switch"></a>
1538
1539 An unusual side-effect of Simple-V mapping onto the standard register files
1540 is that LOAD-multiple and STORE-multiple are accidentally available, as long
1541 as it is acceptable that the register(s) to be loaded/stored are contiguous
1542 (per instruction). An additional accidental benefit is that Compressed LD/ST
1543 may also be used.
1544
1545 To illustrate how this works, here is some example code from FreeRTOS
1546 (GPLv2 licensed, portasm.S):
1547
1548 /* Macro for saving task context */
1549 .macro portSAVE_CONTEXT
1550 .global pxCurrentTCB
1551 /* make room in stack */
1552 addi sp, sp, -REGBYTES * 32
1553
1554 /* Save Context */
1555 STORE x1, 0x0(sp)
1556 STORE x2, 1 * REGBYTES(sp)
1557 STORE x3, 2 * REGBYTES(sp)
1558 ...
1559 ...
1560 STORE x30, 29 * REGBYTES(sp)
1561 STORE x31, 30 * REGBYTES(sp)
1562
1563 /* Store current stackpointer in task control block (TCB) */
1564 LOAD t0, pxCurrentTCB //pointer
1565 STORE sp, 0x0(t0)
1566 .endm
1567
1568 /* Saves current error program counter (EPC) as task program counter */
1569 .macro portSAVE_EPC
1570 csrr t0, mepc
1571 STORE t0, 31 * REGBYTES(sp)
1572 .endm
1573
1574 /* Saves current return adress (RA) as task program counter */
1575 .macro portSAVE_RA
1576 STORE ra, 31 * REGBYTES(sp)
1577 .endm
1578
1579 /* Macro for restoring task context */
1580 .macro portRESTORE_CONTEXT
1581
1582 .global pxCurrentTCB
1583 /* Load stack pointer from the current TCB */
1584 LOAD sp, pxCurrentTCB
1585 LOAD sp, 0x0(sp)
1586
1587 /* Load task program counter */
1588 LOAD t0, 31 * REGBYTES(sp)
1589 csrw mepc, t0
1590
1591 /* Run in machine mode */
1592 li t0, MSTATUS_PRV1
1593 csrs mstatus, t0
1594
1595 /* Restore registers,
1596 Skip global pointer because that does not change */
1597 LOAD x1, 0x0(sp)
1598 LOAD x4, 3 * REGBYTES(sp)
1599 LOAD x5, 4 * REGBYTES(sp)
1600 ...
1601 ...
1602 LOAD x30, 29 * REGBYTES(sp)
1603 LOAD x31, 30 * REGBYTES(sp)
1604
1605 addi sp, sp, REGBYTES * 32
1606 mret
1607 .endm
1608
1609 The important bits are the Load / Save context, which may be replaced
1610 with firstly setting up the Vectors and secondly using a *single* STORE
1611 (or LOAD) including using C.ST or C.LD, to indicate that the entire
1612 bank of registers is to be loaded/saved:
1613
1614 /* a few things are assumed here: (a) that when switching to
1615 M-Mode an entirely different set of CSRs is used from that
1616 which is used in U-Mode and (b) that the M-Mode x1 and x4
1617 vectors are also not used anywhere else in M-Mode, consequently
1618 only need to be set up just the once.
1619 */
1620 .macroVectorSetup
1621 MVECTORCSRx1 = 31, defaultlen
1622 MVECTORCSRx4 = 28, defaultlen
1623
1624 /* Save Context */
1625 SETVL x0, x0, 31 /* x0 ignored silently */
1626 STORE x1, 0x0(sp) // x1 marked as 31-long vector of default bitwidth
1627
1628 /* Restore registers,
1629 Skip global pointer because that does not change */
1630 LOAD x1, 0x0(sp)
1631 SETVL x0, x0, 28 /* x0 ignored silently */
1632 LOAD x4, 3 * REGBYTES(sp) // x4 marked as 28-long default bitwidth
1633
1634 Note that although it may just be a bug in portasm.S, x2 and x3 appear not
1635 to be being restored. If however this is a bug and they *do* need to be
1636 restored, then the SETVL call may be moved to *outside* the Save / Restore
1637 Context assembly code, into the macroVectorSetup, as long as vectors are
1638 never used anywhere else (i.e. VL is never altered by M-Mode).
1639
1640 In effect the entire bank of repeated LOAD / STORE instructions is replaced
1641 by one single (compressed if it is available) instruction.
1642
1643 ## Virtual Memory page-faults on LOAD/STORE
1644
1645
1646 ### Notes from conversations
1647
1648 > I was going through the C.LOAD / C.STORE section 12.3 of V2.3-Draft
1649 > riscv-isa-manual in order to work out how to re-map RVV onto the standard
1650 > ISA, and came across an interesting comments at the bottom of pages 75
1651 > and 76:
1652
1653 > " A common mechanism used in other ISAs to further reduce save/restore
1654 > code size is load- multiple and store-multiple instructions. "
1655
1656 > Fascinatingly, due to Simple-V proposing to use the *standard* register
1657 > file, both C.LOAD / C.STORE *and* LOAD / STORE would in effect be exactly
1658 > that: load-multiple and store-multiple instructions. Which brings us
1659 > on to this comment:
1660
1661 > "For virtual memory systems, some data accesses could be resident in
1662 > physical memory and
1663 > some could not, which requires a new restart mechanism for partially
1664 > executed instructions."
1665
1666 > Which then of course brings us to the interesting question: how does RVV
1667 > cope with the scenario when, particularly with LD.X (Indexed / indirect
1668 > loads), part-way through the loading a page fault occurs?
1669
1670 > Has this been noted or discussed before?
1671
1672 For applications-class platforms, the RVV exception model is
1673 element-precise (that is, if an exception occurs on element j of a
1674 vector instruction, elements 0..j-1 have completed execution and elements
1675 j+1..vl-1 have not executed).
1676
1677 Certain classes of embedded platforms where exceptions are always fatal
1678 might choose to offer resumable/swappable interrupts but not precise
1679 exceptions.
1680
1681
1682 > Is RVV designed in any way to be re-entrant?
1683
1684 Yes.
1685
1686
1687 > What would the implications be for instructions that were in a FIFO at
1688 > the time, in out-of-order and VLIW implementations, where partial decode
1689 > had taken place?
1690
1691 The usual bag of tricks for maintaining precise exceptions applies to
1692 vector machines as well. Register renaming makes the job easier, and
1693 it's relatively cheaper for vectors, since the control cost is amortized
1694 over longer registers.
1695
1696
1697 > Would it be reasonable at least to say *bypass* (and freeze) the
1698 > instruction FIFO (drop down to a single-issue execution model temporarily)
1699 > for the purposes of executing the instructions in the interrupt (whilst
1700 > setting up the VM page), then re-continue the instruction with all
1701 > state intact?
1702
1703 This approach has been done successfully, but it's desirable to be
1704 able to swap out the vector unit state to support context switches on
1705 exceptions that result in long-latency I/O.
1706
1707
1708 > Or would it be better to switch to an entirely separate secondary
1709 > hyperthread context?
1710
1711 > Does anyone have any ideas or know if there is any academic literature
1712 > on solutions to this problem?
1713
1714 The Vector VAX offered imprecise but restartable and swappable exceptions:
1715 http://mprc.pku.edu.cn/~liuxianhua/chn/corpus/Notes/articles/isca/1990/VAX%20vector%20architecture.pdf
1716
1717 Sec. 4.6 of Krste's dissertation assesses some of
1718 the tradeoffs and references a bunch of related work:
1719 http://people.eecs.berkeley.edu/~krste/thesis.pdf
1720
1721
1722 ----
1723
1724 Started reading section 4.6 of Krste's thesis, noted the "IEE85 F.P
1725 exceptions" and thought, "hmmm that could go into a CSR, must re-read
1726 the section on FP state CSRs in RVV 0.4-Draft again" then i suddenly
1727 thought, "ah ha! what if the memory exceptions were, instead of having
1728 an immediate exception thrown, were simply stored in a type of predication
1729 bit-field with a flag "error this element failed"?
1730
1731 Then, *after* the vector load (or store, or even operation) was
1732 performed, you could *then* raise an exception, at which point it
1733 would be possible (yes in software... I know....) to go "hmmm, these
1734 indexed operations didn't work, let's get them into memory by triggering
1735 page-loads", then *re-run the entire instruction* but this time with a
1736 "memory-predication CSR" that stops the already-performed operations
1737 (whether they be loads, stores or an arithmetic / FP operation) from
1738 being carried out a second time.
1739
1740 This theoretically could end up being done multiple times in an SMP
1741 environment, and also for LD.X there would be the remote outside annoying
1742 possibility that the indexed memory address could end up being modified.
1743
1744 The advantage would be that the order of execution need not be
1745 sequential, which potentially could have some big advantages.
1746 Am still thinking through the implications as any dependent operations
1747 (particularly ones already decoded and moved into the execution FIFO)
1748 would still be there (and stalled). hmmm.
1749
1750 ----
1751
1752 > > # assume internal parallelism of 8 and MAXVECTORLEN of 8
1753 > > VSETL r0, 8
1754 > > FADD x1, x2, x3
1755 >
1756 > > x3[0]: ok
1757 > > x3[1]: exception
1758 > > x3[2]: ok
1759 > > ...
1760 > > ...
1761 > > x3[7]: ok
1762 >
1763 > > what happens to result elements 2-7?  those may be *big* results
1764 > > (RV128)
1765 > > or in the RVV-Extended may be arbitrary bit-widths far greater.
1766 >
1767 >  (you replied:)
1768 >
1769 > Thrown away.
1770
1771 discussion then led to the question of OoO architectures
1772
1773 > The costs of the imprecise-exception model are greater than the benefit.
1774 > Software doesn't want to cope with it.  It's hard to debug.  You can't
1775 > migrate state between different microarchitectures--unless you force all
1776 > implementations to support the same imprecise-exception model, which would
1777 > greatly limit implementation flexibility.  (Less important, but still
1778 > relevant, is that the imprecise model increases the size of the context
1779 > structure, as the microarchitectural guts have to be spilled to memory.)
1780
1781 ## Zero/Non-zero Predication
1782
1783 >> >  it just occurred to me that there's another reason why the data
1784 >> > should be left instead of zeroed.  if the standard register file is
1785 >> > used, such that vectorised operations are translated to mean "please
1786 >> > insert multiple register-contiguous operations into the instruction
1787 >> > FIFO" and predication is used to *skip* some of those, then if the
1788 >> > next "vector" operation uses the (standard) registers that were masked
1789 >> > *out* of the previous operation it may proceed without blocking.
1790 >> >
1791 >> >  if however zeroing is made mandatory then that optimisation becomes
1792 >> > flat-out impossible to deploy.
1793 >> >
1794 >> >  whilst i haven't fully thought through the full implications, i
1795 >> > suspect RVV might also be able to benefit by being able to fit more
1796 >> > overlapping operations into the available SRAM by doing something
1797 >> > similar.
1798 >
1799 >
1800 > Luke, this is called density time masking. It doesn’t apply to only your
1801 > model with the “standard register file” is used. it applies to any
1802 > architecture that attempts to speed up by skipping computation and writeback
1803 > of masked elements.
1804 >
1805 > That said, the writing of zeros need not be explicit. It is possible to add
1806 > a “zero bit” per element that, when set, forces a zero to be read from the
1807 > vector (although the underlying storage may have old data). In this case,
1808 > there may be a way to implement DTM as well.
1809
1810
1811 ## Implementation detail for scalar-only op detection <a name="scalar_detection"></a>
1812
1813 Note 1: this idea is a pipeline-bypass concept, which may *or may not* be
1814 worthwhile.
1815
1816 Note 2: this is just one possible implementation. Another implementation
1817 may choose to treat *all* operations as vectorised (including treating
1818 scalars as vectors of length 1), choosing to add an extra pipeline stage
1819 dedicated to *all* instructions.
1820
1821 This section *specifically* covers the implementor's freedom to choose
1822 that they wish to minimise disruption to an existing design by detecting
1823 "scalar-only operations", bypassing the vectorisation phase (which may
1824 or may not require an additional pipeline stage)
1825
1826 [[scalardetect.png]]
1827
1828 >> For scalar ops an implementation may choose to compare 2-3 bits through an
1829 >> AND gate: are src & dest scalar? Yep, ok send straight to ALU  (or instr
1830 >> FIFO).
1831
1832 > Those bits cannot be known until after the registers are decoded from the
1833 > instruction and a lookup in the "vector length table" has completed.
1834 > Considering that one of the reasons RISC-V keeps registers in invariant
1835 > positions across all instructions is to simplify register decoding, I expect
1836 > that inserting an SRAM read would lengthen the critical path in most
1837 > implementations.
1838
1839 reply:
1840
1841 > briefly: the trick i mentioned about ANDing bits together to check if
1842 > an op was fully-scalar or not was to be read out of a single 32-bit
1843 > 3R1W SRAM (64-bit if FPU exists). the 32/64-bit SRAM contains 1 bit per
1844 > register indicating "is register vectorised yes no". 3R because you need
1845 > to check src1, src2 and dest simultaneously. the entries are *generated*
1846 > from the CSRs and are an optimisation that on slower embedded systems
1847 > would likely not be needed.
1848
1849 > is there anything unreasonable that anyone can foresee about that?
1850 > what are the down-sides?
1851
1852
1853 ## Implementation Paradigms <a name="implementation_paradigms"></a>
1854
1855 TODO: assess various implementation paradigms. These are listed roughly
1856 in order of simplicity (minimum compliance, for ultra-light-weight
1857 embedded systems or to reduce design complexity and the burden of
1858 design implementation and compliance, in non-critical areas), right the
1859 way to high-performance systems.
1860
1861 * Full (or partial) software-emulated (via traps): full support for CSRs
1862 required, however when a register is used that is detected (in hardware)
1863 to be vectorised, an exception is thrown.
1864 * Single-issue In-order, reduced pipeline depth (traditional SIMD / DSP)
1865 * In-order 5+ stage pipelines with instruction FIFOs and mild register-renaming
1866 * Out-of-order with instruction FIFOs and aggressive register-renaming
1867 * VLIW
1868
1869 Also to be taken into consideration:
1870
1871 * "Virtual" vectorisation: single-issue loop, no internal ALU parallelism
1872 * Comphrensive vectorisation: FIFOs and internal parallelism
1873 * Hybrid Parallelism
1874
1875 ### Full or partial software-emulation
1876
1877 The absolute, absolute minimal implementation is to provide the full
1878 set of CSRs and detection logic for when any of the source or destination
1879 registers are vectorised. On detection, a trap is thrown, whether it's
1880 a branch, LOAD, STORE, or an arithmetic operation.
1881
1882 Implementors are entirely free to choose whether to allow absolutely every
1883 single operation to be software-emulated, or whether to provide some emulation
1884 and some hardware support. In particular, for an RV32E implementation
1885 where fast context-switching is a requirement (see "Context Switch Example"),
1886 it makes no sense to allow Vectorised-LOAD/STORE to be implemented as an
1887 exception, as every context-switch will result in double-traps.
1888
1889 # TODO Research
1890
1891 > For great floating point DSPs check TI’s C3x, C4X, and C6xx DSPs
1892
1893 Idea: basic simple butterfly swap on a few element indices, primarily targetted
1894 at SIMD / DSP. High-byte low-byte swapping, high-word low-word swapping,
1895 perhaps allow reindexing of permutations up to 4 elements? 8? Reason:
1896 such operations are less costly than a full indexed-shuffle, which requires
1897 a separate instruction cycle.
1898
1899 Predication "all zeros" needs to be "leave alone". Detection of
1900 ADD r1, rs1, rs0 cases result in nop on predication index 0, whereas
1901 ADD r0, rs1, rs2 is actually a desirable copy from r2 into r0.
1902 Destruction of destination indices requires a copy of the entire vector
1903 in advance to avoid.
1904
1905 TBD: floating-point compare and other exception handling
1906
1907 # References
1908
1909 * SIMD considered harmful <https://www.sigarch.org/simd-instructions-considered-harmful/>
1910 * Link to first proposal <https://groups.google.com/a/groups.riscv.org/forum/#!topic/isa-dev/GuukrSjgBH8>
1911 * Recommendation by Jacob Bachmeyer to make zero-overhead loop an
1912 "implicit program-counter" <https://groups.google.com/a/groups.riscv.org/d/msg/isa-dev/vYVi95gF2Mo/SHz6a4_lAgAJ>
1913 * Re-continuing P-Extension proposal <https://groups.google.com/a/groups.riscv.org/forum/#!msg/isa-dev/IkLkQn3HvXQ/SEMyC9IlAgAJ>
1914 * First Draft P-SIMD (DSP) proposal <https://groups.google.com/a/groups.riscv.org/forum/#!topic/isa-dev/vYVi95gF2Mo>
1915 * B-Extension discussion <https://groups.google.com/a/groups.riscv.org/forum/#!topic/isa-dev/zi_7B15kj6s>
1916 * Broadcom VideoCore-IV <https://docs.broadcom.com/docs/12358545>
1917 Figure 2 P17 and Section 3 on P16.
1918 * Hwacha <https://www2.eecs.berkeley.edu/Pubs/TechRpts/2015/EECS-2015-262.html>
1919 * Hwacha <https://www2.eecs.berkeley.edu/Pubs/TechRpts/2015/EECS-2015-263.html>
1920 * Vector Workshop <http://riscv.org/wp-content/uploads/2015/06/riscv-vector-workshop-june2015.pdf>
1921 * Predication <https://groups.google.com/a/groups.riscv.org/forum/#!topic/isa-dev/XoP4BfYSLXA>
1922 * Branch Divergence <https://jbush001.github.io/2014/12/07/branch-divergence-in-parallel-kernels.html>
1923 * Life of Triangles (3D) <https://jbush001.github.io/2016/02/27/life-of-triangle.html>
1924 * Videocore-IV <https://github.com/hermanhermitage/videocoreiv/wiki/VideoCore-IV-3d-Graphics-Pipeline>
1925 * Discussion proposing CSRs that change ISA definition
1926 <https://groups.google.com/a/groups.riscv.org/forum/#!topic/isa-dev/InzQ1wr_3Ak>
1927 * Zero-overhead loops <https://pdfs.semanticscholar.org/dbaa/66985cc730d4b44d79f519e96ec9c43ab5b7.pdf>
1928 * Multi-ported VLIW Register File Implementation <https://ce-publications.et.tudelft.nl/publications/1517_multiple_contexts_in_a_multiported_vliw_register_file_impl.pdf>
1929 * Fast context save/restore proposal <https://groups.google.com/a/groups.riscv.org/d/msgid/isa-dev/57F823FA.6030701%40gmail.com>
1930 * Register File Bank Cacheing <https://www.princeton.edu/~rblee/ELE572Papers/MultiBankRegFile_ISCA2000.pdf>
1931 * Expired Patent on Vector Virtual Memory solutions
1932 <https://patentimages.storage.googleapis.com/fc/f6/e2/2cbee92fcd8743/US5895501.pdf>
1933 * Discussion on RVV "re-entrant" capabilities allowing operations to be
1934 restarted if an exception occurs (VM page-table miss)
1935 <https://groups.google.com/a/groups.riscv.org/d/msg/isa-dev/IuNFitTw9fM/CCKBUlzsAAAJ>
1936 * Dot Product Vector <https://people.eecs.berkeley.edu/~biancolin/papers/arith17.pdf>
1937 * RVV slides 2017 <https://content.riscv.org/wp-content/uploads/2017/12/Wed-1330-RISCVRogerEspasaVEXT-v4.pdf>
1938 * Wavefront skipping using BRAMS <http://www.ece.ubc.ca/~lemieux/publications/severance-fpga2015.pdf>
1939 * Streaming Pipelines <http://www.ece.ubc.ca/~lemieux/publications/severance-fpga2014.pdf>
1940 * Barcelona SIMD Presentation <https://content.riscv.org/wp-content/uploads/2018/05/09.05.2018-9.15-9.30am-RISCV201805-Andes-proposed-P-extension.pdf>
1941 * <http://www.ece.ubc.ca/~lemieux/publications/severance-fpga2015.pdf>