pokche
pokche

Reputation: 1149

How represent each mips instruction line in c++ struct?

I am trying to simulate virtual MIPS architecture using c++. During this process I have to store each line of mips architecture as struct and store it into vector so I can simulate 5 stages of pipeline. My problem is, how can I represent each line of instruction, eg:

Loop: ST R1 R2 //store to M[R2] the contents of R1
ADD R1 R2 R3  // R1 R2 and R3 are register
SUB R1 1
BRNZ  R1 Loop //if R1 is not 0 then loop

Each line looks different and I am trying to find a generic way to represent this in struct.

Upvotes: 3

Views: 1224

Answers (1)

Jack
Jack

Reputation: 133587

You should take a look in how these instructions are implemented in hardware. First of all MIPS is a RISC architecture, and this comes at your help, since all instructions have the same length.

Then MIPS has three instruction types, which are summarized in this image:

enter image description here

Starting from this you can easily develop your own structure by using bit packed instructions together with unions:

struct Instruction {
  u8 opcode : 6;
  union {
    struct {
      u8 rs : 5;
      u8 rt : 5;
      u16 imm;
    } i;
    struct {
      u8 rs : 5;
      u8 rt : 5;
      u8 rd : 5;
      u8 shift : 5;
      u8 funct : 6;
    } r;
    struct {
      u32 address : 24;
    } j;
  }
};

In this way you can access any specific instruction type easily

Instruction instruction;

i.i.rs = ..
i.i.rt = ..
i.i.imm = ..

Mind that if you keep opcode separated from the 3 structs inside the union (instead that replicating it) the padding will enforce a larger size for the whole struct, compared to the real hardware but this shouldn't be an issue in your case.

Upvotes: 6

Related Questions