From fd67be0d891d03ce5f49c0aa9d1be5d45a7ee458 Mon Sep 17 00:00:00 2001 From: Konstantin Nazarov Date: Mon, 9 Dec 2024 00:44:53 +0000 Subject: [PATCH] Move registers and pc counter to the VM class --- src/vm.cpp | 20 +++++++++----------- src/vm.hpp | 6 ++++++ 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/vm.cpp b/src/vm.cpp index b04a73b..3f62218 100644 --- a/src/vm.cpp +++ b/src/vm.cpp @@ -7,7 +7,6 @@ #include #include -const int NUM_REGISTERS = 32; // Standard RISC-V has 32 registers inline int32_t sign_extend(int32_t value, int bits) { int32_t mask = 1 << (bits - 1); @@ -53,22 +52,21 @@ std::vector VM::read_memory(size_t start, size_t size) { memory_.begin() + start + size); } +uint32_t VM::read_register(size_t regnum) { + if (regnum >= NUM_REGISTERS) { + throw std::runtime_error("Register out of range"); + } + + return registers[regnum]; +} + void VM::eval() { size_t memory_size = memory_.size(); uint8_t *memory = &memory_[0]; - uint32_t registers[NUM_REGISTERS] = {0}; - uint32_t pc = 0; - - auto fetch_instruction = [&memory, &pc]() -> uint32_t { - uint32_t instruction = 0; - std::memcpy(&instruction, memory + pc, sizeof(uint32_t)); // Load 4 bytes (little-endian) - return instruction; - }; - bool running = true; while (pc < memory_size && running) { - uint32_t instr = fetch_instruction(); + uint32_t instr = *(uint32_t*)&memory[pc]; if (instr == 0) break; //std::cout << "pc: " << std::hex << pc << std::dec << "\n"; // std::cout << "instr: " << std::hex << instr << "\n"; diff --git a/src/vm.hpp b/src/vm.hpp index 7bfbc2b..571e9b0 100644 --- a/src/vm.hpp +++ b/src/vm.hpp @@ -5,6 +5,8 @@ #include #include +const int NUM_REGISTERS = 32; // Standard RISC-V has 32 registers + std::vector load_program(const std::string& filename, size_t memory_size); class VM { @@ -14,7 +16,11 @@ public: void eval(); std::vector read_memory(size_t start, size_t size); + uint32_t read_register(size_t regnum); private: std::vector memory_; + + uint32_t registers[NUM_REGISTERS] = {0}; + uint32_t pc = 0; };