Search code examples
6502

How does a branch instruction work on the 6502 with a relative offset of 0x00 (fetch / execute cycle)?


Edit: i'm not using any debuggers since i don't intend on installing any software, but recommendations are appreciated

Suppose we stumble upon the instruction BPL $0x00

Base Address(PC): 0x400 value: BPL $00

Intuitively one might assume that the program will hang at address 0x400.

However, im more inclined to say, it will first fetch the opcode at 0x400, increment PC, decode that it needs to read an operand, fetch the operand, increment PC.

That leaves us at address 0x402. By then the processor would decode the instruction and opcode and execute before fetching the next opcode.

So what ends up happening then? does the program branch to address 0x400, or does it branch to address 0x402 like I predict?


Solution

  • As commented already, the offset is added to the address following the instruction, so an offset of 00 makes the branch instruction add nothing if the branch is true. Be aware, however, that a NULL branch does have an effect on code execution, albeit a minor one involving timing, since a branch taken needs three cycles to complete, while a branch skipped needs only two.

    LDA #45
    BPL +00 ; branch taken, execution time 3 clock cycles
    LDA #FE 
    BPL +00 ; branch skipped, execution time 2 clock cycles
    

    All of this information is provided in the 6500 Programming Manual, http://6502.org/documents/books/mcs6500_family_programming_manual.pdf, pp. 40-45.