Simplified CPU state

This commit is contained in:
Eduard Urbach 2025-03-31 14:36:42 +02:00
parent 5bf2ce0bb5
commit 89ed2026e0
Signed by: eduard
GPG key ID: 49226B848C78F6C8
7 changed files with 23 additions and 40 deletions

View file

@ -1,41 +1,27 @@
package cpu
// State contains information about which registers are currently in use.
type State struct {
Reserved uint64
Used uint64
}
type State uint64
// Free will reset the reserved and used status which means the register can be allocated again.
func (s *State) Free(reg Register) {
s.Reserved &= ^(1 << reg)
s.Used &= ^(1 << reg)
}
// IsReserved returns true if the register was marked for future use.
func (s *State) IsReserved(reg Register) bool {
return s.Reserved&(1<<reg) != 0
*s &= ^(1 << reg)
}
// IsUsed returns true if the register is currently in use and holds a value.
func (s *State) IsUsed(reg Register) bool {
return s.Used&(1<<reg) != 0
}
// Reserve reserves a register for future use.
func (s *State) Reserve(reg Register) {
s.Reserved |= (1 << reg)
return *s&(1<<reg) != 0
}
// Use marks a register to be currently in use which means it must be preserved across function calls.
func (s *State) Use(reg Register) {
s.Used |= (1 << reg)
*s |= (1 << reg)
}
// FindFree tries to find a free register in the given slice of registers.
func (s *State) FindFree(registers []Register) (Register, bool) {
for _, reg := range registers {
if !s.IsReserved(reg) && !s.IsUsed(reg) {
if !s.IsUsed(reg) {
return reg, true
}
}

View file

@ -8,23 +8,17 @@ import (
)
func TestRegisterState(t *testing.T) {
s := cpu.State{}
assert.False(t, s.IsReserved(0))
assert.False(t, s.IsUsed(0))
s.Reserve(0)
assert.True(t, s.IsReserved(0))
var s cpu.State
assert.False(t, s.IsUsed(0))
s.Use(0)
assert.True(t, s.IsReserved(0))
assert.True(t, s.IsUsed(0))
s.Free(0)
assert.False(t, s.IsReserved(0))
assert.False(t, s.IsUsed(0))
}
func TestFindFree(t *testing.T) {
s := cpu.State{}
s.Reserve(0)
var s cpu.State
s.Use(0)
s.Use(1)
reg, found := s.FindFree([]cpu.Register{0, 1, 2, 3})
@ -36,8 +30,8 @@ func TestFindFree(t *testing.T) {
}
func TestMustFindFree(t *testing.T) {
s := cpu.State{}
s.Reserve(0)
var s cpu.State
s.Use(0)
s.Use(1)
reg := s.MustFindFree([]cpu.Register{0, 1, 2, 3})