Re-worked the makefiles and includes to target z80 and gbz80 as well
[fw/sdcc] / device / lib / z80 / mul.s
1         ;; Originally from GBDK by Pascal Felber.
2         
3         .area   _CODE
4         
5 __mulschar::
6         ;; Need to sign extend before going in.
7         push    bc
8         ld      c,l
9         
10         ld      a,l
11         rla
12         sbc     a,a
13         ld      b,a
14
15         ld      a,e
16         rla
17         sbc     a,a
18         ld      d,a
19
20         jp      .mul16
21
22 __muluchar::
23 __mulsint::
24 __muluint::
25         ;; Parameters:
26         ;;      HL, DE (left, right irrelivent)
27         ;; Must preserve BC
28         push    bc
29         ld      b,h
30         ld      c,l
31         
32         ;; 16-bit multiplication
33         ;; 
34         ;; Entry conditions
35         ;;   BC = multiplicand
36         ;;   DE = multiplier
37         ;; 
38         ;; Exit conditions
39         ;;   DE = less significant word of product
40         ;;
41         ;; Register used: AF,BC,DE,HL
42 .mul16:
43 .mulu16:
44         LD      HL,#0x00        ; Product = 0
45         LD      A,#15           ; Count = bit length - 1
46         ;; Shift-and-add algorithm
47         ;; If MSB of multiplier is 1, add multiplicand to partial product
48         ;; Shift partial product, multiplier left 1 bit
49 .mlp:
50         SLA     E               ; Shift multiplier left 1 bit
51         RL      D
52         jp      NC,.mlp1        ; Jump if MSB of multiplier = 0
53         ADD     HL,BC           ; Add multiplicand to partial product
54 .mlp1:
55         ADD     HL,HL           ; Shift partial product left
56         DEC     A
57         jp      NZ,.mlp         ; Continue until count = 0
58         ;; Add multiplicand one last time if MSB of multiplier is 1
59         BIT     7,D             ; Get MSB of multiplier
60         JR      Z,.mend         ; Exit if MSB of multiplier is 0
61         ADD     HL,BC           ; Add multiplicand to product
62 .mend:
63                                 ; HL = result
64         pop     bc
65         ret
66