11

The Galaksija ROM disassembly has a link to "A tutorial on how to use "ld" instructions instead of "jr" and save a few bytes in the process."

My question is how does this work! It can see at l038ch it gets an address which points to executable code, and puts it on the stack, leaving a copy in HL. I can imagine that a following RTS would "jump" to that address, but I don't see one.

1 Answer 1

16

It's the db 1 at the end that the comment is referring to. That's the opcode for LD BC, nnnn without a supplied operand. So it acts to swallow the load at l0393h, which in turn swallows that at l0396h, which gets you to PARSE from 0392 without using a JR and without having done anything to change what you wanted in HL.

So, if you enter at 038c then the z80 will perform:

LD HL, <value 1>
PUSH HL
LD L, <value 2>
LD BC, xx
LD BC, xx
(arrive at PARSE)

But if you enter at 0393 then instead it'll perform:

LD L, <value 3>
LD BC, xx
(arrive at PARSE)

... and if you enter at 0396:

LD L, <value 4>
(arrive at PARSE)

The value in HL and BC when you arrive at PARSE depends upon the entry point, but BC is intentional junk. You've spent one byte on the opcode for LD BC in two places you'd otherwise have used a JR. In each of those places you've saved a byte.

3
  • 3
    Oh I see. The sacrifice is you clobber BC with garbage and it takes a bit more time, but each of those entry points, takes up a little less space.
    – Lorraine
    Apr 6, 2017 at 12:04
  • 1
    @Wilson: It actually saves time as well as space, since the Z80 can perform an LD BC,xxxx using four cycles for the first fetch and three for each of the others. A JR instruction takes 7 cycles to fetch the opcode and operand, but an additional 5 cycles to add the operand to the low half of the PC and then handle the possibility of carry/borrow to/from the upper half. The only "downside" to the LD is that it loads BC with a value that is likely meaningless.
    – supercat
    Apr 12, 2017 at 16:10
  • @supercat Of course, if you're going to POP BC immediately after the "load slide" then it doesn't matter anyway :-) Nov 5, 2021 at 10:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .