Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- int32_t signext(int32_t immediate) // sign-extend
- {
- int32_t value = (0x0000FFFF & immediate);
- if (0x00008000 & immediate)
- {
- value |= 0xFFFF0000;
- }
- return value;
- }
- int main()
- {
- // components of Processor
- int N;
- scanf("%d",&N);
- int32_t imem[N];
- int32_t regfile[32] = {0};
- int32_t dmem[1000] = {0};
- // get instructions put em into imem
- for(int i = 0;i<N;i++)
- {
- scanf("%d",&imem[i]);
- }
- int PC = 0;
- while(PC != N)
- {
- printf("PC: %d\n",PC);
- // fetch instruction
- int32_t instr = imem[PC];
- uint32_t opcode, rs, rt, rd, funct, jta;
- int32_t immediate;
- opcode = instr >> 26;
- rs = (instr << 6) >> 27;
- rt = (instr << 11) >> 27;
- rd = (instr << 16) >> 27;
- funct = (instr << 26) >> 26;
- immediate = signext((instr << 16) >> 16);
- jta = (instr << 6) >> 6;
- if(opcode == 0) // R-type
- {
- if(funct == 0x20) // add
- {
- if(rd != 0)
- {
- regfile[rd] = regfile[rs] + regfile[rt];
- }
- PC++;
- continue;
- }
- else if(funct == 0x22) // sub
- {
- if(rd != 0)
- {
- regfile[rd] = regfile[rs] - regfile[rt];
- }
- PC++;
- continue;
- }
- else if(funct == 0x24) // and
- {
- if(rd != 0)
- {
- regfile[rd] = regfile[rs] & regfile[rt];
- }
- PC++;
- continue;
- }
- else if(funct == 0x25) // or
- {
- if(rd != 0)
- {
- regfile[rd] = regfile[rs] | regfile[rt];
- }
- PC++;
- continue;
- }
- else if(funct == 0x2a) // slt
- {
- if(rd != 0)
- {
- regfile[rd] = (regfile[rs] < regfile[rt])? 1 : 0;
- }
- PC++;
- continue;
- }
- else if(funct == 0xc) // syscall
- {
- if(regfile[2] == 34)
- {
- printf("0x%8X\n",regfile[4]);
- PC++;
- }
- else if(regfile[2] == 10)
- {
- PC = N;
- }
- continue;
- }
- }
- else if(opcode == 0x9) // addiu
- {
- if(rt != 0)
- {
- regfile[rt] = regfile[rs] + immediate;
- }
- PC++;
- continue;
- }
- else if(opcode == 0x4) // beq
- {
- if(regfile[rs] == regfile[rt])
- {
- PC = PC + 1 + immediate;
- }
- else
- {
- PC++;
- }
- continue;
- }
- else if(opcode == 0x23) // lw
- {
- if(rt != 0)
- {
- regfile[rt] = dmem[regfile[rs] + immediate];
- }
- PC++;
- continue;
- }
- else if(opcode == 0x2b)
- {
- dmem[regfile[rs] + immediate] = regfile[rt];
- PC++;
- continue;
- }
- else if(opcode == 0x2)
- {
- PC = jta;
- continue;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement