1 from core
import BBlock
, CFGPrinter
5 CFGPrinter(cfg
).print()
8 def save_cfg(cfg
, suffix
):
9 with
open(cfg
.filename
+ suffix
, "w") as out
:
10 p
= CFGPrinter(cfg
, out
)
14 def swap_if_branches(cfg
, node
):
15 "Assuming `node` is 'if' node, swap its branches and invert condition."
16 succ
= cfg
.sorted_succ(node
)
17 print(succ
, cfg
[node
, succ
[0]])
18 cond
= cfg
[node
, succ
[0]]["cond"]
19 cfg
[node
, succ
[0]]["cond"] = None
20 cfg
[node
, succ
[1]]["cond"] = cond
.neg()
23 def detach_node(cfg
, n
):
24 din
= cfg
.degree_in(n
)
25 dout
= cfg
.degree_out(n
)
26 assert din
== 1 or dout
== 1
29 cfg
.move_succ(n
, pred
)
32 cfg
.move_pred(n
, succ
)
36 def foreach_node(cfg
, func
):
37 """Call function for each node of graph, passing node's properties.
39 for addr
, info
in cfg
.iter_sorted_nodes():
43 def foreach_bblock(cfg
, func
, join_func
=lambda a
, b
: a
or b
, **kwargs
):
44 """Apply basic-block level transformation to each block in CFG.
45 Return cumulative status (OR of each block's status).
48 for addr
, info
in cfg
.iter_sorted_nodes():
50 r
= func(bblock
, **kwargs
)
54 res
= join_func(res
, r
)
58 def foreach_bblock_and_subblock(cfg
, func
):
59 def apply(bblock
, func
):
60 if type(bblock
) is BBlock
:
63 for sub
in bblock
.subblocks():
66 for addr
, info
in cfg
.iter_sorted_nodes():
71 def foreach_inst(cfg
, func
, **kwargs
):
72 def inst_handler(bblock
):
73 for inst
in bblock
.items
:
75 foreach_bblock_and_subblock(cfg
, inst_handler
)
78 def copy_bblocks_props(cfg_from
, cfg_to
):
80 cfg_to
[bblock
.addr
]["val"].props
= bblock
.props
.copy()
82 foreach_bblock(cfg_from
, copy
)