Skip to content

Commit

Permalink
Implement PUSH, POP opcodes
Browse files Browse the repository at this point in the history
  • Loading branch information
maxfierke committed Dec 19, 2023
1 parent d9fce3e commit 1dba3bd
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
35 changes: 35 additions & 0 deletions cpu/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,24 +91,48 @@ func (cpu *CPU) Execute(mmu *mem.MMU, inst *isa.Instruction) (nextPC uint16, cyc
case 0x87:
// ADD A, A
cpu.add8(cpu.Reg.A, cpu.Reg.A.Read())
case 0xC1:
// POP BC
cpu.Reg.BC.Write(cpu.pop(mmu))
case 0xC2:
// JP NZ, a16
return cpu.jump(mmu, opcode, !cpu.Reg.F.Zero)
case 0xC3:
// JP a16
return cpu.jump(mmu, opcode, true)
case 0xC5:
// PUSH BC
cpu.push(mmu, cpu.Reg.BC.Read())
case 0xCA:
// JP Z, a16
return cpu.jump(mmu, opcode, cpu.Reg.F.Zero)
case 0xD1:
// POP DE
cpu.Reg.DE.Write(cpu.pop(mmu))
case 0xD2:
// JP NC, a16
return cpu.jump(mmu, opcode, !cpu.Reg.F.Carry)
case 0xD5:
// PUSH DE
cpu.push(mmu, cpu.Reg.DE.Read())
case 0xDA:
// JP C, a16
return cpu.jump(mmu, opcode, cpu.Reg.F.Carry)
case 0xE1:
// POP HL
cpu.Reg.HL.Write(cpu.pop(mmu))
case 0xE5:
// PUSH HL
cpu.push(mmu, cpu.Reg.HL.Read())
case 0xE9:
// JP HL
return cpu.Reg.HL.Read(), uint8(opcode.Cycles[0])
case 0xF1:
// POP AF
cpu.Reg.AF.Write(cpu.pop(mmu))
case 0xF5:
// PUSH AF
cpu.push(mmu, cpu.Reg.AF.Read())
default:
log.Fatalf("Unimplemented instruction @ 0x%X: %s", inst.Addr, opcode)
}
Expand Down Expand Up @@ -188,6 +212,17 @@ func (cpu *CPU) jump(mmu *mem.MMU, opcode *isa.Opcode, should_jump bool) (nextPC
}
}

func (cpu *CPU) pop(mmu *mem.MMU) uint16 {
value := mmu.Read16(cpu.SP.Read())
cpu.SP.Inc(2)
return value
}

func (cpu *CPU) push(mmu *mem.MMU, value uint16) {
cpu.SP.Dec(2)
mmu.Write16(cpu.SP.Read(), value)
}

// Did the aVal carry over from the lower half of the byte to the upper half?
func isHalfCarry8(aVal uint8, bVal uint8) bool {
fourBitMask := uint8(0xF)
Expand Down
23 changes: 23 additions & 0 deletions cpu/cpu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,29 @@ func TestExecuteJumpHL(t *testing.T) {
assertNextPC(t, nextPC, expectedNextPC)
}

func TestExecutePushPop(t *testing.T) {
cpu, _ := NewCPU()
ram := make([]byte, 0xFFFF)
mmu := mem.NewMMU(ram)

cpu.Reg.B.Write(0x4)
cpu.Reg.C.Write(0x89)
cpu.SP.Write(0x10)

inst, _ := cpu.opcodes.InstructionFromByte(cpu.PC.Read(), 0xC5, false)
cpu.Execute(mmu, inst)

assertRegEquals(t, mmu.Read8(0xF), 0x4)
assertRegEquals(t, mmu.Read8(0xE), 0x89)
assertRegEquals(t, cpu.SP.Read(), 0xE)

inst, _ = cpu.opcodes.InstructionFromByte(cpu.PC.Read(), 0xD1, false)
cpu.Execute(mmu, inst)

assertRegEquals(t, cpu.Reg.D.Read(), 0x04)
assertRegEquals(t, cpu.Reg.E.Read(), 0x89)
}

func TestCPUReset(t *testing.T) {
cpu, _ := NewCPU()

Expand Down

0 comments on commit 1dba3bd

Please sign in to comment.