How do I concatenate immediate value of type B RISC-V instruction?

312 Views Asked by At

I have the following binary from a RISC-V instruction that I need to decode: 11111110000011100001100011100011

Using the RISC-V reference card, I know the following information:

  • Its opcode is 1100011, meaning it is a B-type format instruction
  • Its funct3 is 001 = 0x1, meaning bne (Branch !=)
  • Register rs1 is 11100 = x28 or t3
  • Register rs2 is 00000 = x0 or zero

So far, the instruction should look like bne t3 zero, but I am missing the immediate value. I have the following:

  • imm[12] = 1
  • imm[11] = 1
  • imm[10:5] = 111111
  • imm[4:1] = 1000

I am unable to understand how these should be concatenated/ordered in order to get the immediate value for the instruction. I assumed something like 111111111000, but what do I do from there?

1

There are 1 best solutions below

0
Peter Cordes On

Yes, that's correct: bits 12, 11, 10 through 5, and 4 through 1 of the immediate are separate fields in the instruction.

Bit 0 is implicitly zero since branch targets are always aligned by 2 (2-byte compressed instructions are a thing), so you're missing a low 0. In other words, left-shift by 1 on the value you have now.

Put them together in that order like you've done (with imm[0]=0), sign-extend to 32 or 64-bit, then consult the documentation for the instruction to see what it means. (RISC-V immediate operands are always sign-extended, not zero-extended.)

In this case it's a relative displacement, IIRC relative to the start of the branch instruction, unlike in some other ISAs where it's often relative to the end.

In general, see RISC-V: Immediate Encoding Variants for diagrams of where the immediate fields are, and the rationale for the design decision to break them up that way in different instruction formats. (Minimizing muxes and gate-delays for decoding different instruction formats, e.g. making sign-extension able to get started right away, unconditionally from the top bit of the instruction word.)

Also related: How exactly does the RISC-V immediate encoding notation work?