Understanding MIPS Jump Instruction encoding

54 views Asked by At

I'm struggling to comprehend the details of the MIPS jump instruction encoding, specifically when dealing with the instruction located at address 0x00400008. The context involves the jump to the address specified by foo, where the label foo is at address 0x00400024.

enter image description here enter image description here

The answer should be 0x08100009.

From what I know, you need to compute the jump target address using the given information:

  • Two least significant bits are always 0 due to word alignment.
  • Four most significant bits are from the PC+4, and that we set addr = target >> 2.
  • Expected result: 0x08100009.

But if the 2 least significant bits are 0, why do we end up with the number 0x0…9?

2

There are 2 answers

0
Jester On

Judging from the expected result, you are actually encoding the instruction not trying to decode the jump target that the formula applies to. Also it uses address(label) incorrectly: it's missing a bit range 27:2. Chopping off the 2 least significant bits is equivalent to dividing by 4. The rationale is that instructions are 32 bits in size and naturally aligned so you don't need to store the two zero bits at the end.

To get the machine code you need to know the instruction format which is simply 0000 10 address[27:2] in binary. The 0000 10 is the opcode.

In your case the target address is 0x00400024. Just divide by 4 to get the appropriate bits: 0x100009. Prepend the opcode to get the expected 0x08100009 (beware that the opcode is 6 bits so you have to be careful doing it in hex)

0
user22405329 On

In MIPS, all instructions are 32 bit numbers. There are 3 types of instructions:

  • R-type. Those instructions can have 3 register operands and a 5 bit constant operand.
  • I-type. Those can have only 2 register operands, but a larger 16 bit constant operand.
  • J-type. Those only have a single 26 bit constant operand.

The top 6 bits is an opcode field. For J- and I- instructions, it decides both the type and the instruction itself. For R-type, it only says it is an R-type instruction: R-type has another field to select a specific instruction.

The j is a J-type instruction. It's top 6 bit opcode is 000010, which translates to 0x08000000. The bottom 26 bits is a constant field for a target address of a jump.

26 bits is not enough to store a 32 bit address, so two tricks are used:

  • First, the top 4 bits are preserved from PC+4, so they are not stored. That means, that the target address must have the same topmost hex digit as the current address. In your case, both digits are 0: PC+4=0x0040000C, target address = 0x00400024.
  • Because all valid instruction addresses have bottom two bits equal 00, those bits are not stored. Instead, it stores address/4. For address 0x_0400024 (with top 4 bits removed), the stored value is 0x_0100009.

Joining both the opcode 0x08000000 and the address value 0x_0100009 gives 0x08100009.