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
?
Thank you.
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 your 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
.