A few bug fixes; some improvements spurred by paper writing
[ghc.git] / compiler / cmm / CmmContFlowOpt.hs
1
2 module CmmContFlowOpt
3 ( runCmmOpts, cmmCfgOpts, cmmCfgOptsZ
4 , branchChainElimZ, removeUnreachableBlocksZ, predMap
5 , replaceLabelsZ, replaceBranches, runCmmContFlowOptsZs
6 )
7 where
8
9 import BlockId
10 import Cmm
11 import CmmTx
12 import qualified ZipCfg as G
13 import ZipCfg
14 import ZipCfgCmmRep
15
16 import Maybes
17 import Monad
18 import Outputable
19 import Prelude hiding (unzip, zip)
20 import Util
21
22 ------------------------------------
23 runCmmContFlowOptsZs :: [CmmZ] -> [CmmZ]
24 runCmmContFlowOptsZs prog
25 = [ runTx (runCmmOpts cmmCfgOptsZ) cmm_top
26 | cmm_top <- prog ]
27
28 cmmCfgOpts :: Tx (ListGraph CmmStmt)
29 cmmCfgOptsZ :: Tx (a, CmmGraph)
30
31 cmmCfgOpts = branchChainElim -- boring, but will get more exciting later
32 cmmCfgOptsZ g =
33 optGraph
34 (branchChainElimZ `seqTx` blockConcatZ `seqTx` removeUnreachableBlocksZ) g
35 -- Here branchChainElim can ultimately be replaced
36 -- with a more exciting combination of optimisations
37
38 runCmmOpts :: Tx g -> Tx (GenCmm d h g)
39 runCmmOpts opt = mapProcs (optProc opt)
40
41 optProc :: Tx g -> Tx (GenCmmTop d h g)
42 optProc _ top@(CmmData {}) = noTx top
43 optProc opt (CmmProc info lbl formals g) =
44 fmap (CmmProc info lbl formals) (opt g)
45
46 optGraph :: Tx g -> Tx (a, g)
47 optGraph opt (a, g) = fmap (\g' -> (a, g')) (opt g)
48
49 ------------------------------------
50 mapProcs :: Tx (GenCmmTop d h s) -> Tx (GenCmm d h s)
51 mapProcs f (Cmm tops) = fmap Cmm (mapTx f tops)
52
53 ----------------------------------------------------------------
54 branchChainElim :: Tx (ListGraph CmmStmt)
55 -- If L is not captured in an instruction, we can remove any
56 -- basic block of the form L: goto L', and replace L with L' everywhere else.
57 -- How does L get captured? In a CallArea.
58 branchChainElim (ListGraph blocks)
59 | null lone_branch_blocks -- No blocks to remove
60 = noTx (ListGraph blocks)
61 | otherwise
62 = aTx (ListGraph new_blocks)
63 where
64 (lone_branch_blocks, others) = partitionWith isLoneBranch blocks
65 new_blocks = map (replaceLabels env) others
66 env = mkClosureBlockEnv lone_branch_blocks
67
68 isLoneBranch :: CmmBasicBlock -> Either (BlockId, BlockId) CmmBasicBlock
69 isLoneBranch (BasicBlock id [CmmBranch target]) | id /= target = Left (id, target)
70 isLoneBranch other_block = Right other_block
71 -- An infinite loop is not a link in a branch chain!
72
73 replaceLabels :: BlockEnv BlockId -> CmmBasicBlock -> CmmBasicBlock
74 replaceLabels env (BasicBlock id stmts)
75 = BasicBlock id (map replace stmts)
76 where
77 replace (CmmBranch id) = CmmBranch (lookup id)
78 replace (CmmCondBranch e id) = CmmCondBranch e (lookup id)
79 replace (CmmSwitch e tbl) = CmmSwitch e (map (fmap lookup) tbl)
80 replace other_stmt = other_stmt
81
82 lookup id = lookupBlockEnv env id `orElse` id
83 ----------------------------------------------------------------
84 branchChainElimZ :: Tx CmmGraph
85 -- Remove any basic block of the form L: goto L',
86 -- and replace L with L' everywhere else
87 branchChainElimZ g@(G.LGraph eid _)
88 | null lone_branch_blocks -- No blocks to remove
89 = noTx g
90 | otherwise
91 = aTx $ replaceLabelsZ env $ G.of_block_list eid (self_branches ++ others)
92 where
93 (lone_branch_blocks, others) = partitionWith isLoneBranchZ (G.to_block_list g)
94 env = mkClosureBlockEnvZ lone_branch_blocks
95 self_branches =
96 let loop_to (id, _) =
97 if lookup id == id then
98 Just (G.Block id (G.ZLast (G.mkBranchNode id)))
99 else
100 Nothing
101 in mapMaybe loop_to lone_branch_blocks
102 lookup id = lookupBlockEnv env id `orElse` id
103
104 isLoneBranchZ :: CmmBlock -> Either (BlockId, BlockId) CmmBlock
105 isLoneBranchZ (G.Block id (G.ZLast (G.LastOther (LastBranch target))))
106 | id /= target = Left (id,target)
107 isLoneBranchZ other = Right other
108 -- An infinite loop is not a link in a branch chain!
109
110 replaceLabelsZ :: BlockEnv BlockId -> CmmGraph -> CmmGraph
111 replaceLabelsZ env = replace_eid . G.map_nodes id middle last
112 where
113 replace_eid (G.LGraph eid blocks) = G.LGraph (lookup eid) blocks
114 middle = mapExpDeepMiddle exp
115 last l = mapExpDeepLast exp (last' l)
116 last' (LastBranch bid) = LastBranch (lookup bid)
117 last' (LastCondBranch p t f) = LastCondBranch p (lookup t) (lookup f)
118 last' (LastSwitch e arms) = LastSwitch e (map (liftM lookup) arms)
119 last' (LastCall t k a res r) = LastCall t (liftM lookup k) a res r
120 exp (CmmLit (CmmBlock bid)) = CmmLit (CmmBlock (lookup bid))
121 exp (CmmStackSlot (CallArea (Young id)) i) =
122 CmmStackSlot (CallArea (Young (lookup id))) i
123 exp e = e
124 lookup id = fmap lookup (lookupBlockEnv env id) `orElse` id
125
126 replaceBranches :: BlockEnv BlockId -> CmmGraph -> CmmGraph
127 replaceBranches env g = map_nodes id id last g
128 where
129 last (LastBranch id) = LastBranch (lookup id)
130 last (LastCondBranch e ti fi) = LastCondBranch e (lookup ti) (lookup fi)
131 last (LastSwitch e tbl) = LastSwitch e (map (fmap lookup) tbl)
132 last l@(LastCall {}) = l
133 lookup id = fmap lookup (lookupBlockEnv env id) `orElse` id
134
135 ----------------------------------------------------------------
136 -- Build a map from a block to its set of predecessors. Very useful.
137 predMap :: G.LastNode l => G.LGraph m l -> BlockEnv BlockSet
138 predMap g = G.fold_blocks add_preds emptyBlockEnv g -- find the back edges
139 where add_preds b env = foldl (add b) env (G.succs b)
140 add (G.Block bid _) env b' =
141 extendBlockEnv env b' $
142 extendBlockSet (lookupBlockEnv env b' `orElse` emptyBlockSet) bid
143 ----------------------------------------------------------------
144 -- If a block B branches to a label L, and L has no other predecessors,
145 -- then we can splice the block starting with L onto the end of B.
146 -- Because this optmization can be inhibited by unreachable blocks,
147 -- we first take a pass to drops unreachable blocks.
148 -- Order matters, so we work bottom up (reverse postorder DFS).
149 --
150 -- To ensure correctness, we have to make sure that the BlockId of the block
151 -- we are about to eliminate is not named in another instruction.
152 --
153 -- Note: This optimization does _not_ subsume branch chain elimination.
154 blockConcatZ :: Tx CmmGraph
155 blockConcatZ = removeUnreachableBlocksZ `seqTx` blockConcatZ'
156 blockConcatZ' :: Tx CmmGraph
157 blockConcatZ' g@(G.LGraph eid blocks) =
158 tx $ replaceLabelsZ concatMap $ G.LGraph eid blocks'
159 where (changed, blocks', concatMap) =
160 foldr maybe_concat (False, blocks, emptyBlockEnv) $ G.postorder_dfs g
161 maybe_concat b@(G.Block bid _) (changed, blocks', concatMap) =
162 let unchanged = (changed, extendBlockEnv blocks' bid b, concatMap)
163 in case G.goto_end $ G.unzip b of
164 (h, G.LastOther (LastBranch b')) ->
165 if canConcatWith b' then
166 (True, extendBlockEnv blocks' bid $ splice blocks' h b',
167 extendBlockEnv concatMap b' bid)
168 else unchanged
169 _ -> unchanged
170 num_preds bid = liftM sizeBlockSet (lookupBlockEnv backEdges bid) `orElse` 0
171 canConcatWith b' = num_preds b' == 1
172 backEdges = predMap g
173 splice blocks' h bid' =
174 case lookupBlockEnv blocks' bid' of
175 Just (G.Block _ t) -> G.zip $ G.ZBlock h t
176 Nothing -> pprPanic "unknown successor block" (ppr bid' <+> ppr blocks' <+> ppr blocks)
177 tx = if changed then aTx else noTx
178 ----------------------------------------------------------------
179 mkClosureBlockEnv :: [(BlockId, BlockId)] -> BlockEnv BlockId
180 mkClosureBlockEnv blocks = mkBlockEnv $ map follow blocks
181 where singleEnv = mkBlockEnv blocks
182 follow (id, next) = (id, endChain id next)
183 endChain orig id = case lookupBlockEnv singleEnv id of
184 Just id' | id /= orig -> endChain orig id'
185 _ -> id
186 mkClosureBlockEnvZ :: [(BlockId, BlockId)] -> BlockEnv BlockId
187 mkClosureBlockEnvZ blocks = mkBlockEnv $ map follow blocks
188 where singleEnv = mkBlockEnv blocks
189 follow (id, next) = (id, endChain id next)
190 endChain orig id = case lookupBlockEnv singleEnv id of
191 Just id' | id /= orig -> endChain orig id'
192 _ -> id
193 ----------------------------------------------------------------
194 removeUnreachableBlocksZ :: Tx CmmGraph
195 removeUnreachableBlocksZ g@(G.LGraph id blocks) =
196 if length blocks' < sizeBEnv blocks then aTx $ G.of_block_list id blocks'
197 else noTx g
198 where blocks' = G.postorder_dfs g