Blargg Test 'POP AF' in '01 - special' logic question

Discussion of programming and development for the original Game Boy and Game Boy Color.
Post Reply
theotherjim
Posts: 6
Joined: Sun May 17, 2015 2:14 pm
Location: seattle

Blargg Test 'POP AF' in '01 - special' logic question

Post by theotherjim »

Hi, I have a question about the logic in one of the blargg's tests in 01 - special. Test #5: POP AF has some logic that I don't quite understand.

First let's look at the source for that test:

Code: Select all

    LD BC,$1200       ;start with BC=$1200
-   PUSH BC           ; save bc on the stack
    POP AF            ; pop the stack into af (effectively AF = BC)
    PUSH AF           ; push AF onto the stack
    POP DE            ; pop the stack into DE (effectively DE = AF (= BC))
    LD A,C            ; load C into A
    AND $FO           ; only keep the high 4 bits of A
    CP E              ; compare E to A
    JP NZ,test_failed ; if they're not equal, the test is failed
    INC B             ; otherwise, increment B
    INC C             ; and C
    JR NZ,-           ; and do it again until C = $00
Now, I think I understand what the operations of the test are, but I would imagine this to always fail for the second iteration (BC = $1301) because of this:

Code: Select all

LD A,C   ; load $01 to A 
AND $F0  ; keep only high bits ($01 -> $00)
CP E     ; compare A ($00) with E ($01) -> not same, test failed
I feel like there's something I'm missing, but I'm not sure what it is. I've been pouring over any documents I can find, but haven't found anything that would suggest different behavior from what I expect. Can anyone shed some light on this?
Shonumi
Posts: 342
Joined: Sun Jan 26, 2014 9:31 am

Re: Blargg Test 'POP AF' in '01 - special' logic question

Post by Shonumi »

Let me try to remember... I believe that you can only write to the top 4 bits of the F register. It only holds 4 flags, the rest of the bits are supposed to go unused. When performing a POP AF instruction, bits 0 - 3 are ignored/masked out. Therefore:

Code: Select all

PUSH BC		 ;BC being 1301, B hold $13, C holds $1
POP AF		  ;Basically stores B into A, and C into F
              ;F ignores $1, however, so now you have AF = $1300
PUSH AF       ;Puts $1300 on the stack
POP DE        ;Pulls $1300 from the stack, with E being $0, D being $13
LD A, C       ;Load $1 into A
AND $F0       ;Masks lower nibble of A, $A is now $0
CP E          ;Both A and E are $0, so the zero flag is set
I recall that being a bit of a head-scratching moment myself when I was writing my first emulator. That should be what the test is looking for. It's been a while, but that's what I can pull of the top of my head.
theotherjim
Posts: 6
Joined: Sun May 17, 2015 2:14 pm
Location: seattle

Re: Blargg Test 'POP AF' in '01 - special' logic question

Post by theotherjim »

Ahh!! That's it! Thank you. That makes a lot more sense now.
Post Reply