Move registers and pc counter to the VM class

This commit is contained in:
Konstantin Nazarov 2024-12-09 00:44:53 +00:00
parent 78a2a460e8
commit fd67be0d89
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
2 changed files with 15 additions and 11 deletions

View file

@ -7,7 +7,6 @@
#include <vector> #include <vector>
#include <fstream> #include <fstream>
const int NUM_REGISTERS = 32; // Standard RISC-V has 32 registers
inline int32_t sign_extend(int32_t value, int bits) { inline int32_t sign_extend(int32_t value, int bits) {
int32_t mask = 1 << (bits - 1); int32_t mask = 1 << (bits - 1);
@ -53,22 +52,21 @@ std::vector<uint8_t> VM::read_memory(size_t start, size_t size) {
memory_.begin() + start + 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() { void VM::eval() {
size_t memory_size = memory_.size(); size_t memory_size = memory_.size();
uint8_t *memory = &memory_[0]; 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; bool running = true;
while (pc < memory_size && running) { while (pc < memory_size && running) {
uint32_t instr = fetch_instruction(); uint32_t instr = *(uint32_t*)&memory[pc];
if (instr == 0) break; if (instr == 0) break;
//std::cout << "pc: " << std::hex << pc << std::dec << "\n"; //std::cout << "pc: " << std::hex << pc << std::dec << "\n";
// std::cout << "instr: " << std::hex << instr << "\n"; // std::cout << "instr: " << std::hex << instr << "\n";

View file

@ -5,6 +5,8 @@
#include <string> #include <string>
#include <vector> #include <vector>
const int NUM_REGISTERS = 32; // Standard RISC-V has 32 registers
std::vector<uint8_t> load_program(const std::string& filename, size_t memory_size); std::vector<uint8_t> load_program(const std::string& filename, size_t memory_size);
class VM { class VM {
@ -14,7 +16,11 @@ public:
void eval(); void eval();
std::vector<uint8_t> read_memory(size_t start, size_t size); std::vector<uint8_t> read_memory(size_t start, size_t size);
uint32_t read_register(size_t regnum);
private: private:
std::vector<uint8_t> memory_; std::vector<uint8_t> memory_;
uint32_t registers[NUM_REGISTERS] = {0};
uint32_t pc = 0;
}; };