jrpseudo

jr

pseudo
RISC-V Assembly Reference

lyszt.net covers jr and other RISC-V instructions in more detail.

Description

jr jumps to an address stored in a register. The name stands for jump register. j jumps to a fixed label written in the code. jr jumps to whatever address a register holds, which the program works out while it runs. It saves no return address.

jr is a pseudo-instruction for the line below, a register jump that discards the return address (see jalr).

jalr zero, rs, 0

A jump table is an array in memory that holds the addresses of several routines, and jr is used with it. To pick routine number i, the program computes its slot in the table, loads the address stored there into a register and uses jr to jump to it. One lookup and one jump replace a long series of comparisons (is it case 0, case 1, case 2 and so on), whatever the number of cases. Dense switch statements and the inner loop of an interpreter dispatch this way.

The RISC-V manual encodes plain unconditional indirect jumps as a jalr with rd set to x0. It notes that jalr does not treat its immediate as a multiple of 2 bytes, unlike the conditional branches, and that most uses of jalr have a zero immediate or come after a lui or auipc.

Returning from a function is a jump to the address in ra, so ret is jr ra under another name. The group of jump instructions differs in where the address comes from and whether a return address is saved.

Expands to

jalr zero, rs, 0

The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.

Example

la t0, target
jr t0            # jump to the address held in t0