1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math accessors sequences namespaces make
7 compiler.cfg.instructions ;
8 IN: compiler.cfg.linearization
10 ! Convert CFG IR to machine IR.
11 GENERIC: linearize-insn ( basic-block insn -- )
13 : linearize-insns ( basic-block -- )
14 dup instructions>> [ linearize-insn ] with each ; inline
16 M: insn linearize-insn , drop ;
18 : useless-branch? ( basic-block successor -- ? )
19 #! If our successor immediately follows us in RPO, then we
20 #! don't need to branch.
21 [ number>> ] bi@ 1- = ; inline
23 : branch-to-branch? ( successor -- ? )
24 #! A branch to a block containing just a jump return is cloned.
25 instructions>> dup length 2 = [
27 [ second [ ##return? ] [ ##jump? ] bi or ] bi and
30 : emit-branch ( basic-block successor -- )
32 { [ 2dup useless-branch? ] [ 2drop ] }
33 { [ dup branch-to-branch? ] [ nip linearize-insns ] }
34 [ nip number>> _branch ]
37 M: ##branch linearize-insn
38 drop dup successors>> first emit-branch ;
40 : (binary-conditional) ( basic-block insn -- basic-block successor1 successor2 src1 src2 cc )
41 [ dup successors>> first2 ]
42 [ [ src1>> ] [ src2>> ] [ cc>> ] tri ] bi* ; inline
44 : binary-conditional ( basic-block insn -- basic-block successor label2 src1 src2 cc )
45 [ (binary-conditional) ]
46 [ drop dup successors>> second useless-branch? ] 2bi
47 [ [ swap number>> ] 3dip ] [ [ number>> ] 3dip negate-cc ] if ;
49 M: ##compare-branch linearize-insn
50 binary-conditional _compare-branch emit-branch ;
52 M: ##compare-imm-branch linearize-insn
53 binary-conditional _compare-imm-branch emit-branch ;
55 M: ##compare-float-branch linearize-insn
56 binary-conditional _compare-float-branch emit-branch ;
68 : linearize-basic-block ( bb -- )
74 : linearize-basic-blocks ( rpo -- insns )
75 [ [ linearize-basic-block ] each ] { } make ;
77 : build-mr ( cfg -- mr )
78 [ entry>> reverse-post-order linearize-basic-blocks ]
79 [ word>> ] [ label>> ]