Best way to create virtual registers in C++

I’m trying to create a barebones VM that can only execute x86 assembly code for a highschool project, and I figured to create all of the registers using structs. I have all of the instructions, opcodes, and operand logic implemented already, but I’m worried that this kind of botching of creating CPU registers won’t be good in the long term as the project grows and I’m mostly worried if it’s not the best way to implement virtual registers, not to mention it looks pretty ugly with all the repetitive code I made. If anybody could make it better or make it more efficient, that would be really helpful.

#include <iostream>
#include <cstdlib>

// 64-bit registers
    int64_t RAX; // accumulator
    int64_t RCX; // counter
    int64_t RDX; // data
    int64_t RBX; // base
    int64_t RSP; // stack pointer
    int64_t RBP; // stack base pointer
    int64_t RSI; // source index
    int64_t RDI; // destination index

// 32-bit registers
    int32_t EAX;
    int32_t ECX;
    int32_t EDX;
    int32_t EBX;
    int32_t ESP;
    int32_t EBP;
    int32_t ESI;
    int32_t EDI;

// 16-bit
    int16_t AX;
    int16_t CX;
    int16_t DX;
    int16_t BX;
    int16_t SP;
    int16_t BP;
    int16_t SI;
    int16_t DI;

// 8-bit registers
    int8_t AH;
    int8_t AL;
    int8_t CH;
    int8_t CL;
    int8_t DH;
    int8_t DL;
    int8_t BH;
    int8_t BL;

    int8_t SPL;
    int8_t BPL;
    int8_t SIL;
    int8_t DIL;

>Solution :

I wrote a PDP11 emulator in c++ recently I did this

   uint16_t registers[8];
   uint16_t &PC = registers[0];
   uint16_t &R1 = registers[1];  

ie create an array of registers so I can save them as a block or whatever but create references with the well known names for each register

Leave a Reply