gbdev / gbdev/gb-opcodes

Change STOP byte count to 1

Open
#31 8 comments 0 reactions 0 assignees View on GitHub
Dominant language
SCSS
Stars
28
Forks
10
PR merge metrics
No merged PRs in 30d

Description

It doesn't make sense to have a 2-byte instruction which takes 1 M-cycle, as that's impossible to actually achieve on the CPU in any way (yes, that even includes `ADD HL, r16`, as it does ALU operation on both M-cycles, lower half first, then upper half in the second cycle).

There are two ways to solve this issue:
- make it 1B 1M, as that's what it actually is
- keep it as 2B, but make it 32769M (execution of STOP takes a single M-cycle, and wakeup from STOP mode fetches the next instruction on the 32768th cycle)

And yes, STOP *is* actually a single byte opcode, which can be observed when STOP fails to stop due to a button being held.
The short explaination of why STOP consumes two bytes can be summarized in these points:
- PC is always one byte ahead of the currently executed instruction
- if STOP enters stop mode, it fetches the next opcode, incrementing PC (PC points to STOP +2)
- **the fetched opcode is discarded, and replaced with NOP**
- on wakeup, the NOP fetches the instruction at STOP +2, and executes it in the next cycle
More details can be found [here](https://gist.github.com/SonoSooS/c0055300670d678b5ae8433e20bea595#nop-and-stop).

The reason HALT does not consume two bytes is because PC is not incremented when HALT fetches the next opcode, but otherwise works similar to STOP. More details [here](https://gist.github.com/SonoSooS/c0055300670d678b5ae8433e20bea595#halt).

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.