RISC-V difference between jal and jalr
Asked Answered
T

2

21

I came across the instruction named jal and jalr while studying RISC-V assembly language.

I quite having hard times to understand the differences between jal and jalr.

jal x1, X 

It seems that above code is meaning that jump to X, and save the return address which is normally PC+4 to the x1.

But after that, jalr x0, 0(x1) comes.

0(x1) means that going back to the address which is the return address, but what is x0?

Essentially x0 is zero in RISC-V, so why do we need x0?

What is the actual difference between those two instructions, jal and jalr?

Tullusus answered 8/10, 2019 at 4:10 Comment(0)
D
26

As we can see in specification (page 15), the main difference between jal and jalr is the address value encoding.

jal use immediate (20bits) encoding for destination address and can jump +-1MiB range. And save the actual address + 4 in register rd. (x1 in your example).

jalr use indirect address (x1 in your example) plus a constant of 12bits (0 in your example). It save the actual address + 4 in register rd too. In your example you set x0 as return address register because you «don't care».

When you return from subroutine for example, the return address is not usefull then we set x0.

Dx answered 8/10, 2019 at 8:10 Comment(0)
O
-1

Ok so i checked on the manual of RISC-V: https://riscv.org/wp-content/uploads/2017/05/riscv-spec-v2.2.pdf

Apparently, jal uses J as encoding type while jalr uses I type. In jalr, x0 is used as destination because the result is not required, we only need to give the control back to the calling program (at least this is my guess).

Here's the text from the manual: "The indirect jump instruction JALR (jump-and-link register) uses the I-type encoding. The target address is obtained by adding the 12-bit signed I-immediate to the register rs1, then setting the least-significant bit of the result to zero. The address of the instruction following the jump(pc+4) is written to register rd. Register x0 can be used as the destination if the result is not required."

Obvolute answered 26/5, 2023 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.