d870523beb15827f763a5381ed0a9c088406e38e
[libreriscv.git] / simple_v_extension / daxpy_example.mdwn
1 # c code
2
3 ```
4 void daxpy(size_t n, double a, const double x[], double y[]) {
5 for (size_t i = 0; i < n; i++)
6 y[i] = a*x[i] + y[i];
7 }
8 ```
9
10 # SVP64 Power ISA version
11
12 Summary: 9 instructions, 5 of which are 64-bit
13 for a total of 14 "words".
14
15 Relies on post-increment, relies on no overlap between x and y
16 in memory, and critically relies on y overwrite. x is post-incremented
17 when read, but y is post-incremented on write. Element-Strided
18 ensures the Immediate (8) results in a contiguous LD (or store)
19 despite RA being marked Scalar. For `sv.lfdup`, RA is Scalar so that only one
20 LD/ST Update "wins": the last write to RA is the address for
21 the next block. However for `sv.lfd/els` the Element-Striding causes
22 a contiguous Vector Load *without* modifying RA.
23
24 ```
25 # r5: n count; r6: x ptr; r7: y ptr; fp1: a
26 1 addi r3,r7,0 # return result
27 2 mtctr 5 # move n to CTR
28 3 .L2
29 4 setvl MAXVL=32,VL=CTR # actually VL=MIN(MAXVL,CTR)
30 5 sv.lfdup/els *32,8(6) # load x into fp32-63, incr x
31 6 sv.lfd/els *64,8(7) # load y into fp64-95, NO INC
32 7 sv.fmadd *64,*64,1,*32 # (*y) = (*y) * (*x) + a
33 8 sv.stfdup/els *64,8(7) # store at y, incr y
34 9 sv.bc/ctr .L2 # decr CTR by VL, jump !zero
35 10 blr # return
36 ```
37
38 # RVV version
39
40 Summary: 12 instructions, 7 32-bit and 5 16-bit for a total of 9.5 "words"
41
42 ```
43 # a0 is n, a1 is pointer to x[0], a2 is pointer to y[0], fa0 is a
44 li t0, 2<<25
45 vsetdcfg t0 # enable 2 64b Fl.Pt. registers
46 loop:
47 setvl t0, a0 # vl = t0 = min(mvl, n)
48 vld v0, a1 # load vector x
49 c.slli t1, t0, 3 # t1 = vl * 8 (in bytes)
50 vld v1, a2 # load vector y
51 c.add a1, a1, t1 # increment pointer to x by vl*8
52 vfmadd v1, v0, fa0, v1 # v1 += v0 * fa0 (y = a * x + y)
53 c.sub a0, a0, t0 # n -= vl (t0)
54 vst v1, a2 # store Y
55 c.add a2, a2, t1 # increment pointer to y by vl*8
56 c.bnez a0, loop # repeat if n != 0
57 c.ret # return
58 ```
59
60 # SVE Version
61
62 Summary: 12 instructions, all 32-bit, for a total of 12 "words"
63
64 ```
65 1 // x0 = &x[0], x1 = &y[0], x2 = &a, x3 = &n
66 2 daxpy_:
67 3 ldrswx3, [x3] // x3=*n
68 4 movx4, #0 // x4=i=0
69 5 whilelt p0.d, x4, x3 // p0=while(i++<n)
70 6 ld1rdz0.d, p0/z, [x2] // p0:z0=bcast(*a)
71 7 .loop:
72 8 ld1d z1.d, p0/z, [x0, x4, lsl #3] // p0:z1=x[i]
73 9 ld1d z2.d, p0/z, [x1, x4, lsl #3] // p0:z2=y[i]
74 10 fmla z2.d, p0/m, z1.d, z0.d // p0?z2+=x[i]*a
75 11 st1d z2.d, p0, [x1, x4, lsl #3] // p0?y[i]=z2
76 12 incd x4 // i+=(VL/64)
77 13 .latch:
78 14 whilelt p0.d, x4, x3 // p0=while(i++<n)
79 15 b.first .loop // more to do?
80 16 ret
81 ```