by haberman · 6y ago · 0 comments
A few months back I set out to write a software emulator of RISC-V for fun. I expected the instruction set encoding to lend itself well to a very simple implementation, eg. something you could decode in 5-10 lines of C plus some tables.
But the instruction encoding is much more irregular than I expected: https://github.com/ucb-bar/riscv-sodor/blob/master/src/commo...
In particular:
- The bit patterns allocated to the simplest instructions
(eg. rv32i) seem random. Why not allocate starting from zero
to allow dense jump tables?
- I can't make any sense of the groupings. A bunch of instructions
have 0b1100011 in the lowest bits, do these instructions have
something in common?
I assume there is some rhyme and reason to all this? Where is this explained?The bit patterns are often designed to make it easier to write efficient hardware designs to implement them. For example, if an instruction encodes an "immediate" value, the most significant bit of the instruction will always hold that value's sign-extension bit. And if you compare the immediate values in I-/S-/B-/J-type instructions, you can see that bits [5:10] are always in the same place. It's not exactly intuitive, but there is some rhyme and reason.
In the base instruction set, the 0b1100011 opcode encodes a set of conditional branch instructions. They perform relative jumps if rs1 == rs2, or if rs1 < rs2, etc.
https://riscv.org/specifications/isa-spec-pdf/
Take a look at the "RV32/64G Instruction Set Listings" table to get a feel for the encodings.
For example, the operands all stay in the same position, which prevents putting decode on the critical path before you can figure out which registers you need to read (which is doubly important for superscalar designs which need to compute the register dependence graph). Likewise, the sign-extend bit for immediates is always in the same place, providing relief for another potential critical path.
Computer Organization and Design, RISC-V edition, goes into these. R-types have opcode = 0b0110011, SB (branch) types have opcode = 0b1100011, etc.
The lower bits also have extra meanings (16 bit, 48 bit, etc. instruction).
This allows hardware to just branch on these bits in sub-groups. The hardware pipeline for 16 bit is different than that of 48 bit, and the 48-bit is probably even optional.
Compressed was an afterthought on Risc-V. A well thought out afterthought, but you do things differently when you know in advance.
What, they are absolutely relevant in hardware and selected to optimize the resulting generated hardware.
To see what I mean, have a gander at this: