假設我們有以下程式碼:
int remainder(int a, int b)
{
while (a >= b)
a -= b;
return a;
}
對於一個 RISC 架構(特別是 RV32),我們的 RISC-V 編譯器生成以下的組合語言代碼:
loop:
blt x1, x2, done
sub x1, x1, x2
j loop
done:
...
假設 RISC-V 指令每個佔 4 位元組,資料值也是每個佔 4 位元組。
問:RISC-V 程式有多少位元組?
D01 = 12
假設 a = 7 且 b = 3。問:在 RISC-V 程式中有多少資料位元組被加載或儲存?
D02 = 0
假設我們有一個簡單的整數向量加法實作:
# for (i = 0; i < N; i++)
# c[i] = a[i] + b[i]
Loop:
lw x2, 0(x1) # load a[i]
lw x4, 0(x3) # load b[i]
add x5, x2, x4 # c[i] = a[i] + b[i]
__D03__ # store c[i]
addi x1, x1, 4 # bump pointer
addi x3, x3, 4 # bump pointer
addi x6, x6, 4 # bump pointer
addi x7, x7, 1 # i++
__D04__ # x8 holds N
對應的 RISC-V 組合語言代碼如下:
D03 = sw x5, 0(x6)
D04 = bne x7, x8, Loop
接下來,考慮一個展開迴圈並重新安排指令的編譯器,假設迴圈對向量中的偶數個元素進行操作。如下圖所示:
Loop:
lw x2, 0(x1) # load a[i]
addi x1, x1, 8 # bump pointer a
lw x4, 0(x3) # load b[i]
addi x3, x3, 8 # bump pointer b
__D05__ # load a[i+1]
add x5, x2, x4 # c[i] = a[i] + b[i]
__D06__ # load b[i+1]
addi x7, x7, 2 # i+=2
__D07__ # store c[i]
add x10, x8, x9 # c[i+1] = a[i+1] + b[i+1]
__D08__ # store c[i+1]
__D09__ # bump pointer c
__D10__ # x11 holds N
D05 = lw x8, -4(x1)
D06 = lw x9, -4(x3)
D07 = sw x5, 0(x6)
D08 = sw x10, 4(x6)
D09 = addi x6, x6, 8
D10 = bne x7, x11, Loop