emulationgameboy

Gameboy Emulator pop off empty stack


I'm working on a Gameboy Emulator, and I've reached a point in the ROM where I get opcode 0xD1 (pop DE off stack) but the stack is empty (no values have been pushed onto it). All unknown opcodes return an error, and all other instructions seem to be working fine.

Is it an error in my programming, the ROM, or is this just a quick way for the program to set DE to 0x0000?


Solution

  • Even if no value has been PUSHed to the stack, POP will retrieve the value stored at the address in SP to the specified register pair, and SP will be incremented by 2.

    In your example, if SP has been initialized to, say wD000, and that the WRAM is initialized to 0 beforehand, POP DE would effectively load 0 to DE, and increment the Stack Pointer by 2.

    21 00 C0         ld   hl,C000       ;Start of WRAM
    01 FF 1F         ld   bc,1FFF       ;Length of WRAM
    AF               xor  a             ;a = 0
    22               ldi  (hl),a        ;Blanks WRAM
    0B               dec  bc
    78               ld   a,b
    B1               or   c
    20 F9            jr   nz,0158       ;Loops until WRAM is cleared
    21 00 D0         ld   hl,D000
    F9               ld   sp,hl         ;SP = 0xD000
    D1               pop  de            ;de = 0x0000, SP = 0xD002
    

    Also, please note that the CALL instruction pushes the return address to the stack, and decrements SP by 2. In the same way, RET retrieves the address from the stack, and increases SP by 2.