New utility functions for traversing graphs and creating lattices.
[packages/hoopl.git] / src / Compiler / Hoopl / Util.hs
1 {-# LANGUAGE GADTs, ScopedTypeVariables, FlexibleInstances, RankNTypes #-}
2
3 module Compiler.Hoopl.Util
4 ( gUnitOO, gUnitOC, gUnitCO, gUnitCC
5 , graphMapBlocks
6 , zblockGraph
7 , postorder_dfs, postorder_dfs_from, postorder_dfs_from_except
8 , preorder_dfs, preorder_dfs_from_except
9 , labelsDefined, labelsUsed, externalEntryLabels
10 , LabelsPtr(..)
11 )
12 where
13
14 import Control.Monad
15
16 import Compiler.Hoopl.Graph
17 import Compiler.Hoopl.Label
18 import Compiler.Hoopl.Zipper
19
20
21 ----------------------------------------------------------------
22
23 gUnitOO :: block n O O -> Graph' block n O O
24 gUnitOC :: block n O C -> Graph' block n O C
25 gUnitCO :: block n C O -> Graph' block n C O
26 gUnitCC :: block n C C -> Graph' block n C C
27 gUnitOO b = GUnit b
28 gUnitOC b = GMany (JustO b) BodyEmpty NothingO
29 gUnitCO b = GMany NothingO BodyEmpty (JustO b)
30 gUnitCC b = GMany NothingO (BodyUnit b) NothingO
31
32 zblockGraph :: ZBlock n e x -> ZGraph n e x
33 zblockGraph b@(ZFirst {}) = gUnitCO b
34 zblockGraph b@(ZMiddle {}) = gUnitOO b
35 zblockGraph b@(ZLast {}) = gUnitOC b
36 zblockGraph b@(ZCat {}) = gUnitOO b
37 zblockGraph b@(ZHead {}) = gUnitCO b
38 zblockGraph b@(ZTail {}) = gUnitOC b
39 zblockGraph b@(ZClosed {}) = gUnitCC b
40
41
42 graphMapBlocks :: forall block n block' n' e x .
43 (forall e x . block n e x -> block' n' e x)
44 -> (Graph' block n e x -> Graph' block' n' e x)
45 bodyMapBlocks :: forall block n block' n' .
46 (block n C C -> block' n' C C)
47 -> (Body' block n -> Body' block' n')
48
49 graphMapBlocks f = map
50 where map :: Graph' block n e x -> Graph' block' n' e x
51 map GNil = GNil
52 map (GUnit b) = GUnit (f b)
53 map (GMany e b x) = GMany (fmap f e) (bodyMapBlocks f b) (fmap f x)
54
55 bodyMapBlocks f = map
56 where map BodyEmpty = BodyEmpty
57 map (BodyUnit b) = BodyUnit (f b)
58 map (BodyCat b1 b2) = BodyCat (map b1) (map b2)
59
60
61 ----------------------------------------------------------------
62
63 class LabelsPtr l where
64 targetLabels :: l -> [Label]
65
66 instance Edges n => LabelsPtr (n e C) where
67 targetLabels n = successors n
68
69 instance LabelsPtr Label where
70 targetLabels l = [l]
71
72 instance LabelsPtr LabelSet where
73 targetLabels = labelSetElems
74
75 instance LabelsPtr l => LabelsPtr [l] where
76 targetLabels = concatMap targetLabels
77
78
79 -- | Traversal: 'postorder_dfs' returns a list of blocks reachable
80 -- from the entry of enterable graph. The entry and exit are *not* included.
81 -- The list has the following property:
82 --
83 -- Say a "back reference" exists if one of a block's
84 -- control-flow successors precedes it in the output list
85 --
86 -- Then there are as few back references as possible
87 --
88 -- The output is suitable for use in
89 -- a forward dataflow problem. For a backward problem, simply reverse
90 -- the list. ('postorder_dfs' is sufficiently tricky to implement that
91 -- one doesn't want to try and maintain both forward and backward
92 -- versions.)
93
94 postorder_dfs :: Edges (block n) => Graph' block n O x -> [block n C C]
95 preorder_dfs :: Edges (block n) => Graph' block n O x -> [block n C C]
96
97 -- | This is the most important traversal over this data structure. It drops
98 -- unreachable code and puts blocks in an order that is good for solving forward
99 -- dataflow problems quickly. The reverse order is good for solving backward
100 -- dataflow problems quickly. The forward order is also reasonably good for
101 -- emitting instructions, except that it will not usually exploit Forrest
102 -- Baskett's trick of eliminating the unconditional branch from a loop. For
103 -- that you would need a more serious analysis, probably based on dominators, to
104 -- identify loop headers.
105 --
106 -- The ubiquity of 'postorder_dfs' is one reason for the ubiquity of the 'LGraph'
107 -- representation, when for most purposes the plain 'Graph' representation is
108 -- more mathematically elegant (but results in more complicated code).
109 --
110 -- Here's an easy way to go wrong! Consider
111 -- @
112 -- A -> [B,C]
113 -- B -> D
114 -- C -> D
115 -- @
116 -- Then ordinary dfs would give [A,B,D,C] which has a back ref from C to D.
117 -- Better to get [A,B,C,D]
118
119
120 graphDfs :: (Edges (block n))
121 => (LabelMap (block n C C) -> block n O C -> LabelSet -> [block n C C])
122 -> (Graph' block n O x -> [block n C C])
123 graphDfs _ (GNil) = []
124 graphDfs _ (GUnit{}) = []
125 graphDfs order (GMany (JustO entry) body _) = order blockenv entry emptyLabelSet
126 where blockenv = bodyMap body
127
128 postorder_dfs = graphDfs postorder_dfs_from_except
129 preorder_dfs = graphDfs preorder_dfs_from_except
130
131 postorder_dfs_from_except :: forall block e . (Edges block, LabelsPtr e)
132 => LabelMap (block C C) -> e -> LabelSet -> [block C C]
133 postorder_dfs_from_except blocks b visited =
134 vchildren (get_children b) (\acc _visited -> acc) [] visited
135 where
136 vnode :: block C C -> ([block C C] -> LabelSet -> a) -> [block C C] -> LabelSet -> a
137 vnode block cont acc visited =
138 if elemLabelSet id visited then
139 cont acc visited
140 else
141 let cont' acc visited = cont (block:acc) visited in
142 vchildren (get_children block) cont' acc (extendLabelSet visited id)
143 where id = entryLabel block
144 vchildren bs cont acc visited = next bs acc visited
145 where next children acc visited =
146 case children of [] -> cont acc visited
147 (b:bs) -> vnode b (next bs) acc visited
148 get_children block = foldr add_id [] $ targetLabels block
149 add_id id rst = case lookupFact blocks id of
150 Just b -> b : rst
151 Nothing -> rst
152
153 postorder_dfs_from
154 :: (Edges block, LabelsPtr b) => LabelMap (block C C) -> b -> [block C C]
155 postorder_dfs_from blocks b = postorder_dfs_from_except blocks b emptyLabelSet
156
157
158 ----------------------------------------------------------------
159
160 data VM a = VM { unVM :: LabelSet -> (a, LabelSet) }
161 marked :: Label -> VM Bool
162 mark :: Label -> VM ()
163 instance Monad VM where
164 return a = VM $ \visited -> (a, visited)
165 m >>= k = VM $ \visited -> let (a, v') = unVM m visited in unVM (k a) v'
166 marked l = VM $ \v -> (elemLabelSet l v, v)
167 mark l = VM $ \v -> ((), extendLabelSet v l)
168
169 preorder_dfs_from_except :: forall block e . (Edges block, LabelsPtr e)
170 => LabelMap (block C C) -> e -> LabelSet -> [block C C]
171 preorder_dfs_from_except blocks b visited =
172 (fst $ unVM (children (get_children b)) visited) []
173 where children [] = return id
174 children (b:bs) = liftM2 (.) (visit b) (children bs)
175 visit :: block C C -> VM (HL (block C C))
176 visit b = do already <- marked (entryLabel b)
177 if already then return id
178 else do mark (entryLabel b)
179 bs <- children $ get_children b
180 return $ b `cons` bs
181 get_children block = foldr add_id [] $ targetLabels block
182 add_id id rst = case lookupFact blocks id of
183 Just b -> b : rst
184 Nothing -> rst
185
186 type HL a = [a] -> [a] -- Hughes list (constant-time concatenation)
187 cons :: a -> HL a -> HL a
188 cons a as tail = a : as tail
189
190 ----------------------------------------------------------------
191
192 labelsDefined :: forall block n e x . Edges (block n) => Graph' block n e x -> LabelSet
193 labelsDefined GNil = emptyLabelSet
194 labelsDefined (GUnit{}) = emptyLabelSet
195 labelsDefined (GMany _ body x) = foldBodyBlocks addEntry body $ exitLabel x
196 where addEntry block labels = extendLabelSet labels (entryLabel block)
197 exitLabel :: MaybeO x (block n C O) -> LabelSet
198 exitLabel NothingO = emptyLabelSet
199 exitLabel (JustO b) = mkLabelSet [entryLabel b]
200
201 labelsUsed :: forall block n e x. Edges (block n) => Graph' block n e x -> LabelSet
202 labelsUsed GNil = emptyLabelSet
203 labelsUsed (GUnit{}) = emptyLabelSet
204 labelsUsed (GMany e body _) = foldBodyBlocks addTargets body $ entryTargets e
205 where addTargets block labels = foldl extendLabelSet labels (successors block)
206 entryTargets :: MaybeO e (block n O C) -> LabelSet
207 entryTargets NothingO = emptyLabelSet
208 entryTargets (JustO b) = addTargets b emptyLabelSet
209
210 foldBodyBlocks :: (block n C C -> a -> a) -> Body' block n -> a -> a
211 foldBodyBlocks _ BodyEmpty = id
212 foldBodyBlocks f (BodyUnit b) = f b
213 foldBodyBlocks f (BodyCat b b') = foldBodyBlocks f b . foldBodyBlocks f b'
214
215 externalEntryLabels :: Edges (block n) => Body' block n -> LabelSet
216 externalEntryLabels body = defined `minusLabelSet` used
217 where defined = labelsDefined g
218 used = labelsUsed g
219 g = GMany NothingO body NothingO