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

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

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

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

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

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

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

        } cleave
    ] [ call ] [ ] tri* new-imm-insn ; inline

:: combine-imm ( insn quot op -- insn )
    insn op combine-imm? [
        insn quot op (combine-imm)
    ] [
        insn
    ] if ; inline

M: ##add-imm rewrite
    {
        { [ dup \ ##add-imm combine-imm? ] [ [ + ] \ ##add-imm (combine-imm) ] }
        { [ dup \ ##sub-imm combine-imm? ] [ [ - ] \ ##sub-imm (combine-imm) ] }
        [ ]
    } cond ;

M: ##sub-imm rewrite
    {
        { [ dup \ ##add-imm combine-imm? ] [ [ - ] \ ##add-imm (combine-imm) ] }
        { [ dup \ ##sub-imm combine-imm? ] [ [ + ] \ ##sub-imm (combine-imm) ] }
        [ ]
    } cond ;

