Hasin Sadique
Hasin Sadique

Reputation: 17

MIPS jump and BNE address calculation

Suppose the program counter (PC) is set to 0x20000000.Is it possible to use the jump (j) MIPS assembly instruction to set the PC to the address 0x40000000? Is it possible to use the branch-on-equal (beq) MIPS assembly instruction to set the PC to this same address?

Upvotes: 1

Views: 4287

Answers (2)

Minn
Minn

Reputation: 6124

I believe you could use jr to jump to a 32bit address

li $t0, 0x40000000
jr $t0

Similarly you could use a branch and combine it with the above to perform this jump.

The reason why BNE is not suited for this is that it only operates on 16-bit offsets due to how instructions are encoded.

0001 01ss ssst tttt iiii iiii iiii iiii represents a BNE instruction where sssss and ttttt are the compared registers and iiii iiii iiii iiii the 16-bit offset (twos-complement to allow backwards offset as well). This means that the 0x20000000 offset cannot be expressed in the 16-bits provided by this encoding.

The jump instruction behaves a bit differently in the way it uses the current PC to calculate the destination address. This is done by concatenating the first 6 bits of the current PC (which would be 0010 00 in this case) together with the destination stored in the immediate part of the encoding (which would be 26-bits filled with 0). Thus the resulting address can only be 0x20000000.

Jump-Register (JR) on the other hand allows to jump to full 32-bit addresses since it uses a register for the destination address and is not bound by the aforementioned instruction limitations.

Upvotes: 4

Jevgeni Geurtsen
Jevgeni Geurtsen

Reputation: 3133

The documentation states the following in the programming notes section of the BEQ-instruction:

Description: if rs = rt then branch An 18-bit signed offset (the 16-bit offset field shifted left 2 bits) is added to the address of the instruction following the branch (not the branch itself), in the branch delay slot, to form a PC-relative effective target address.

Programming Notes: With the 18-bit signed instruction offset, the conditional branch range is ± 128 Kbytes. Use jump (J) or jump register (JR) instructions to branch to addresses outside this range.

So you cannot use the BEQ instruction to jump to 0x40000000 (starting from 0x20000000 it would have to jump over 0x20000000 = 536870912b = 536871kb). Thus you must use the jump register instructions to jump to 0x40000000.

Upvotes: 1

Related Questions