Saturday, March 3, 2012

SWEET16 on the Replica 1

SWEET16 is an interpreted 16-bit virtual machine written by Steve Wozniak as part of the Integer BASIC ROM in the Apple II.

He had found that manipulating 16-bit data on the 8-bit 6502 took a lot of code. His solution was to implement a 16-bit processor in software. He figured it saved a significant amount of code size at the expense of speed. The interpreter only takes about 300 bytes of code.

You can read more about SWEET 16 in the references listed at the end of the posting.

While SWEET16 was written for the Apple II, it is mostly portable and has been ported to other 6502-based computers. I decided to port it to the Replica 1. The main effort was just adapting the source code to a different assembler. In my case I used the CA65 cross-assembler. I even found a shortcut - the port to the Atari computer was already very close to the CA65 format and only need a few changes. The port only tool an hours or so.

Essentially these were all the changes needed:

  • changes for comment format
  • adding colons to labels
  • moved the location of the 16 16-bit registers from page zero $E0..$FF to $00..$1F
  • changed start address to $0289
Note that some of the code in SWEET16 needs to be all on the same page. This start address ensures that. If you don't ensure this then the code will crash (as I learned).

Once it was ported and assembled I tried some sample SWEET16 code and confirmed that it ran okay.

Below is some sample code with the SWEET16 instructions listed in comments. You do a subroutine call to SWEET16 and it starts interpreting the instructions that follow. A SWEET16 RTN (return) instruction passes control back to native 6502 code.

;  Sample Sweet16 code program
   JSR SWEET16
  .BYTE $11,$00,$70 ; SET R1,$7000
  .BYTE $12,$02,$70 ; SET R2,$7002
  .BYTE $13,$01,$00 ; SET R3,1
;LOOP:
  .BYTE $41   ; LD @R1
  .BYTE $52   ; ST @R2
  .BYTE $F3   ; DCR R3
  .BYTE $07,$FB ; BNZ LOOP
  .BYTE $00   ; RTN
  RTS 

A nice feature of the CA65 assembler is that it has support for SWEET16 opcodes and you can switch between 6502 and SWEET16 code in the same source file. Here is an example of doing that:

; Example SWEET16 code
  SWEET16 = $0289
  .SETCPU "6502"
  JSR SWEET16
  .SETCPU "sweet16"
  SET R1,$7000
  SET R2,$7002
  SET R3,10
LOOP:
  LD @R1
  ST @R2
  DCR R3
  BNZ LOOP
  RTN
  .SETCPU "6502"
  RTS

I found one bug in CA65's SWEET16 support, it did not recognize the "SUB" instruction. I figured out a fix for it and submitted a patch back to the CA65 author.

If you would like a copy of the SWEET16 port for the Replica 1, drop me a line and I will be happy to send it to you.

References:

  1. http://en.wikipedia.org/wiki/SWEET16
  2. http://www.6502.org/source/interpreters/sweet16.htm
  3. http://atariwiki.strotmann.de/wiki/Wiki.jsp?page=Sweet16Mac65

No comments: