-! Copyright (C) 2008 Slava Pestov.
+! Copyright (C) 2008 Slava Pestov, Doug Coleman.
 ! See http://factorcode.org/license.txt for BSD license.
 USING: accessors combinators combinators.short-circuit
-compiler.cfg.hats compiler.cfg.instructions
+arrays compiler.cfg.hats compiler.cfg.instructions
 compiler.cfg.value-numbering.expressions
 compiler.cfg.value-numbering.graph
 compiler.cfg.value-numbering.simplify fry kernel layouts math
-namespaces sequences cpu.architecture math.bitwise locals ;
+namespaces sequences cpu.architecture math.bitwise ;
 IN: compiler.cfg.value-numbering.rewrite
 
 GENERIC: rewrite ( insn -- insn' )

        ] when
    ] when ;

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

:: combine-imm ( insn quot op -- insn )
    insn
    [ dst>> ]
    [ src1>> vreg>expr [ in1>> vn>vreg ] [ in2>> vn>constant ] bi ]
    [ src2>> ] tri

    quot call cell-bits bits

    dup small-enough? [
        op new-insn dup number-values
    ] [
        3drop 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 ;


    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
