 : combine-imm? ( insn op -- ? )
     [ src1>> vreg>expr op>> ] dip = ;
 
-: combine-imm ( insn quot op -- insn )
+: (combine-imm) ( insn quot op -- insn )
     [
         {
             [ ]

        ] when
    ] when ;

: (new-imm-insn) ( insn dst src1 n op -- new-insn/insn )
    [ cell-bits bits ] dip over small-enough? [
        new-insn dup number-values nip
    ] [
        2drop 2drop
    ] if ; inline

: new-imm-insn ( insn dst src n op -- n' op' )
    2dup [ sgn ] dip 2array

        [ [ dst>> ] [ src1>> ] bi ] [ log2 ] bi* \ ##shl-imm new-insn
        dup number-values
    ] [
        drop [ * ] \ ##mul-imm combine-imm
    ] if ;

M: ##and-imm rewrite [ bitand ] \ ##and-imm combine-imm ;

M: ##or-imm rewrite [ bitor ] \ ##or-imm combine-imm ;

M: ##xor-imm rewrite [ bitxor ] \ ##xor-imm combine-imm ;

: rewrite-add? ( insn -- ? )
    src2>> {
        [ vreg>expr constant-expr? ]
        [ vreg>constant small-enough? ]
    } 1&& ;

M: ##add rewrite
    dup rewrite-add? [
        [ dst>> ]
        [ src1>> ]
        [ src2>> vreg>constant ] tri \ ##add-imm new-insn
        dup number-values
    ] when ;

M: ##sub rewrite constant-fold ;
