; CLARITAS TIP u32/1 - checked_mul_u32.inc
; Public: UMUL32CHK

; CS617 chapter01-u32calc-v2 r010 checked multiplication CANDIDATE
; Entry: $15..18 lhs U32, $5..8 rhs U32 (UA=14).
; Return $4=0 valid with $15..18 product; $4=1 unsigned overflow.
; Depends on UDIV32NZ, UMUL32. No global RAM; 12-byte stack scratch.
; Preflight via quotient bound: for nonzero rhs, lhs <= MAX_U32/rhs.
; This safely detects overflow before calling destructive UMUL32.
; Strictly not a modification of accepted lib-set-01.
#LIST
UMUL32CHK:
        LD      $0,$5
        OR      $0,$6
        OR      $0,$7
        OR      $0,$8
        AN      $0,$0
        JR      NZ,_UMC_NONZERO
; Zero multiplier: always exact, including MAX * 0.
        CAL     UMUL32
        LD      $4,0
        RTN
_UMC_NONZERO:
; HD61 PHSM operand names the LAST register of a descending block;
; PPSM names the FIRST register of an ascending block.
; Preserve both original operands while checking against MAX / rhs.
        PHSM    $18,4    ; HD61 pushes $18,$17,$16,$15 (NOT $15..18)
        PHSM    $8,4     ; pushes $8,$7,$6,$5 (NOT $5..8)
        LDW     $15,&HFFFF
        LDW     $17,&HFFFF
        CAL     UDIV32NZ
; Store quotient temporarily in $19..22, restore original operands.
        PHSM    $18,4    ; save quotient $15..18 for bounded compare
        PPSM    $19,4
        PPSM    $5,4
        PPSM    $15,4
        SBCW    $17,$21
        JR      C,_UMC_VALID
        JR      NZ,_UMC_OVER
        SBCW    $15,$19
        JR      C,_UMC_VALID
        JR      Z,_UMC_VALID
_UMC_OVER:
        LD      $4,1
        RTN
_UMC_VALID:
        CAL     UMUL32
        LD      $4,0
        RTN
