CS61C Summer 2018 Discussion 3 - RISC-V
CS61C Summer 2018 Discussion 3 - RISC-V
struct ll {
int val;
struct ll* next;
}
1. lw t0, 0(s0)
lw t1, 8(s0)
add t2, t0, t1
sw t2, 4(s0)
1
2 RISC-V Instruction Formats
2.1 Overview
Instructions in RISC-V can be turned into binary numbers that the machine actually reads. There are different
formats to the instructions, based on what information is need. Each of the fields above is filled in with binary
that represents the information. Each of the registers takes a 5 bit number that is the numeric name of the
register (i.e. zero = 0, ra = 1, s1 = 9). See your reference card to know which register corresponds to which
number.
I type instructions fill the immediate into the code. These numbers are signed 12 bit numbers.
2.2 Exercises
1. Expand addi s0 t0 -1
2. Expand lw s4 5(sp)
(a) jal
(b) lw
(c) beq
(d) add
(e) jalr
(f) sb
(g) lui
2
3 Translating between C and RISC-V
Translate between the C and RISC-V code. You may want to use the RISC-V Green Card as a reference.
We show you how the different variables map to registers – you don’t have to worry about the stack or any
memory-related issues.
C RISC-V
// Nth_Fibonacci(n):
// s0 -> n, s1 -> fib
// t0 -> i, t1 -> j
// Assume fib, i, j are already these values
int fib = 1, i = 1, j = 1;
if (n==0) return 0;
else if (n==1) return 1;
n -= 2;
while (n != 0) {
fib = i + j;
j = i;
i = fib;
n--;
}
return fib;
5. Which values need to be restored before using jalr to return from a function?