From 2e47ad73aead135ef9d14a17b1d522f9de0ff41d Mon Sep 17 00:00:00 2001 From: Konstantin Nazarov Date: Fri, 6 Dec 2024 21:39:01 +0000 Subject: [PATCH] Implement branches --- src/vm.cpp | 44 +++++++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/src/vm.cpp b/src/vm.cpp index ca6ca54..da7c793 100644 --- a/src/vm.cpp +++ b/src/vm.cpp @@ -136,22 +136,36 @@ void eval(uint8_t* memory, size_t memory_size) { } break; } - case 0x63: { // B-type (BEQ, BNE) - imm = ((instr >> 7) & 0x1E) | ((instr >> 20) & 0x7E0) | - ((instr >> 19) & 0x800) | ((instr >> 31) << 12); - imm = sign_extend(imm, 13); // Sign-extend 13-bit immediate - if (funct3 == 0x0) { // BEQ - if (registers[rs1] == registers[rs2]) { - pc += imm - 4; // Offset PC (adjust for pre-increment) - } - } else if (funct3 == 0x1) { // BNE - if (registers[rs1] != registers[rs2]) { - pc += imm - 4; // Offset PC - } - } else { - throw std::runtime_error("Unknown B-type instruction"); + case 0x63: { // B-type (branches) + imm = ((instr >> 7) & 0x1E) | ((instr >> 20) & 0x7E0) | + ((instr >> 19) & 0x800) | ((instr >> 31) << 12); + imm = sign_extend(imm, 13); // Sign-extend 13-bit immediate + if (funct3 == 0x0) { // BEQ + if (registers[rs1] == registers[rs2]) { + pc += imm - 4; // Offset PC (adjust for pre-increment) } - break; + } else if (funct3 == 0x1) { // BNE + if (registers[rs1] != registers[rs2]) { + pc += imm - 4; // Offset PC + } + } else if (funct3 == 0x4) { // BLT + if (static_cast(registers[rs1]) < + static_cast(registers[rs2])) { + pc += imm - 4; + } + } else if (funct3 == 0x5) { // BGE + if (static_cast(registers[rs1]) >= + static_cast(registers[rs2])) { + pc += imm - 4; + } + } else if (funct3 == 0x6) { // BLTU + if (registers[rs1] < registers[rs2]) pc += imm - 4; + } else if (funct3 == 0x7) { // BGEU + if (registers[rs1] >= registers[rs2]) pc += imm - 4; + } else { + throw std::runtime_error("Unknown B-type instruction"); + } + break; } case 0x03: { // I-type (loads) imm = sign_extend(instr >> 20, 12); // Extract 12-bit immediate