6502 Illegal Opcode SAX: Sprite Tricks
The unofficial 6502 opcode SAX (sometimes referred to as AXS or AAX in different documentation sources) enables significant cycle savings in Commodore 64 assembly, especially when handling sprite properties under tight raster timing constraints. While “illegal” opcodes should be used cautiously, SAX has proven stable across all tested 6502 variants and remains widely used in modern C64 development.
The Challenge
Conventional sprite attribute manipulation demands multiple instruction sequences that quickly consume precious raster time. Clearing x-expansion, y-expansion, MSB, and MCM (multicolor mode) for sprite 04 illustrates this problem:
Conventional method: Four LDA/AND/STA combinations total around 32 CPU cycles, consuming nearly half a PAL raster line (63 cycles available per line). In complex scenes with multiple sprites requiring attribute changes, this approach becomes untenable.
The Optimization
SAX combines the accumulator and X-register through an AND operation, writing the result to memory while preserving both register values. This enables sharing a mask across multiple writes without reloading.
Improved method: Loading a single mask into X (LDX #%11101111) then applying it repeatedly using SAX takes just 26 cycles, saving 6 cycles per sprite—cycles that accumulate significantly when handling all eight hardware sprites.
Technical Mechanism
This instruction performs (A AND X), stores the result at the specified address, and leaves both source registers unchanged. The preservation of register contents distinguishes SAX from store-with-modification instructions that corrupt the accumulator.
Addressing modes available with SAX include zero page, zero page indexed by Y, absolute, and indirect indexed by X—covering most practical use cases in sprite management code.
Real-World Usage
Games like Parallaxian employ this technique throughout timing-critical routines where individual cycles directly impact smooth visual performance. During complex scenes with multiple parallax layers and sprite multiplexing, every saved cycle contributes to stable frame rates and artifact-free display.
The demoscene has extensively validated SAX behavior across different 6502 revisions, building confidence in its reliability for production code. Emulator support is universal among serious C64 emulators.
See also: EOR optimization tricks · sprite optimization context · wished-for 6502 instructions · addressing mode techniques