******************************************************************************* * Example of a 'jump table' for easy68k. * * A 'jump table' is an array of pointers to locations in the code; see the * construction of JMPTBL in terms of labels op1, op2, op3, and op4 below. * * The purpose of a jump table is to replace a potentially long sequence of * comparisons and branches with a single jump based on an index interpretation * of a set of bits. For example, consider acting on the values the two bits * d0[5:4]. One option is to do something inefficient (and tedious) like the * following: * * cmp.b #$00,d0 * beq op1 * cmp.b #$10,d0 * beq op2 * cmp.b #$20,d0 * beq op3 * cmp.b #$30,d0 * beq op4 * * Another option is to do as in the function 'decode' below. * * Of course, in practice one must sometimes be creative in how one constructs * and uses a jump table. * * On a related note, I noticed that some students wrote a lot of code to * decode the lower six bits in lab #3, while some used the organization of the * string table to quickly access the appropriate string based on the bit * pattern. Jump tables are used in essentially the same way as the latter * approach to how to choose the correct string. ******************************************************************************* org $3000 START * macro for reading number read MACRO move.l #4,d0 ; read long from keyboard trap #15 ENDM * macro for print string pstr MACRO lea \1,a1 move.l #13,d0 trap #15 ENDM ******************************************************************************* * Simple _main to test 'decode'. Enter an integer to be decoded. Try in * particular the integers 0, 16, 32, 48. ******************************************************************************* _main: read ; read a long cmp.l #-1,d1 ; if it's -1, exit beq exit move.l d1,d0 ; otherwise, decode it jsr decode bra _main ; loop exit move.l #9,d0 ; exit trap #15 ******************************************************************************* * In: d0.l - long to decode * Looks at d0[5:4] to determine which operation to perform. Uses jump table * to avoid a sequence of comparisons and branches. ******************************************************************************* decode: andi.l #$30,d0 ; d0[5:4] hold bits of interest lsr.b #2,d0 ; shift right twice: 4 * d0[5:4] lea JMPTBL,a0 move.l (a0,d0),a1 ; load entry from jump table into a1 jmp (a1) ; and jump op1 pstr MSG1 bra done op2 pstr MSG2 bra done op3 pstr MSG3 bra done op4 pstr MSG4 bra done done rts * The jump table: pointers to locations in the code. JMPTBL dc.l op1,op2,op3,op4 * Messages. MSG1 dc.b 'Doing operation 1',0 MSG2 dc.b 'Doing operation 2',0 MSG3 dc.b 'Doing operation 3',0 MSG4 dc.b 'Doing operation 4',0 end START