RISC-V Unconditional Jump Operations

The following are the direct jump and link operations in 32-bit RISC-V:

| Operation | Description |
| :-------: | :-----------------------------------------------------------: |
| jal rd label | Set rd to PC+4 (the line after the current line) and branch to [label]. |
| jalr rd rs1 imm | Set rd to PC+4 and jump to the line of code at rs1 + imm. |

Note!

There are two pseudoinstructions used when we do not need to return after a call:

  • Direct jumps to label using j label, which stands for jal x0 label.
  • Direct jumps to address using jr rs1, which stands for jalr x0 rs1 0.

C Loop

In C or any high-level programming language, one would write code in the following manner:

int A[20];
int sum = 0;
for (int i = 0; i < 20; i++) {
  sum += A[i]
}
printf("%d\n", sum)

In the RISC-V low-level language, however, such abstractions are not possible. However, we can roughly translate the C code above into RISC-V, assuming that x8 contains the address of the int array:

  mv x9 x8 # x9 = &A[0]
  mv x1 x0  # sum = 0
  mv x2 x0 # i = 0
  addi x3 x0 20 # x2 = length of A

Loop:
  bge x1 x2 Done  # if x1 >= x2 break
  lw x10 0(x9)  # x10 = *(&A[i])
  add x1 x1 x10  # sum += A[i]
  addi x9 x9 4 # x9 = &A[i+1]
  addi x2 x2 1 # i++
  j Loop
Done