What are the hardware reasons why a routine must be within 128 or -127 bytes of the issued branching instruction?
The hardware reasons are two-fold:
first, the 6502 is an 8-bit processor, which means a single byte can hold unsigned values from 0 to 255, or if bit 7 is used to indicate sign (two's complement) then -128 to +127.
second, Chuck Peddle designed the branch instruction as a two-byte operation - the first byte represents the branch condition (opcode) and the second a signed offset value (operand) to be added to the Program Counter [PC] if the condition is true.
As is now apparent, the use of a single signed offset byte as the branch operand means the maximum 'jump' range that a BRx
instruction can accommodate is either 128 locations back from the current PC, or 127 locations ahead.
This limitation can be cumbersome to overcome in cases where you need to branch (as opposed to jump, see below) further than the range allows; however, practice and experience in 6502 assembly programming techniques and a deep understanding of the flow and organisation of your code will often permit artful design that avoids the need to branch over larger distances.
The CPU architecture more than compensates for the range limit by having BRx
be an incredibly fast instruction - only 2 cycles if the branch is not taken, and just one more cycle if it is (i.e. 2 cycles to read the opcode and operand and set up the compare mask in an internal register, and then just one more to add the operand to PC if the condition is true).
The JMP
instruction, by comparison, allows program flow to jump anywhere in the 16-bit address range as it uses a two-byte address operand - but exhibits a flat 3-cycle cost and is unconditional. Careful construction of a jump table or self-modifying code using JMP
and indexed by a branch allows the programmer to capitalise on the speed and conditionality of BRx
and only incur the 'far jump' cost when the condition is true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With