Jack Morgan
Jack Morgan

Reputation: 25

MIPS Branch Instruction - Getting Branch Location

I was wondering how to find the branch location of an instruction such as bne $s1, $s0, label_name. From what I understand the 16-bit immediate value is a relative offset that should be added to the PC to branch.

What I want to know is how the branch address is calculated as I am finding multiple, contradicting answers for the same thing.

What I have found so far:

  1. Increment current PC by four.
  2. Shift immediate value (16-bit) left by two (multiply by four).
  3. Sign extend immediate value to 32-bits.
  4. Add the PC and immediate value.

Is this correct? And if so, how would I sign extend this value in C?

Upvotes: 2

Views: 2121

Answers (1)

Adam
Adam

Reputation: 846

This equation clarify everything.

PC'= the next PC.

SignImm= sign extended immidiate

  PC' = PC + 4 + SignImm*4 

You can get the next PC (PC') as following.

  1. Add four to the current PC.

  2. Sign extend the 16 bit immediate.

  3. shift left it by 2 and add it to PC+4.

How would I sign extend it in C

     int16_t s = -890;
     int32_t i = s;

Upvotes: 2

Related Questions