c5c9b578a21de73b2e1a16fa9ee7a5e61b756ba3
[ghc-hetmet.git] / compiler / utils / Digraph.lhs
1 %
2 % (c) The University of Glasgow 2006
3 %
4
5 \begin{code}
6 module Digraph(
7
8         -- At present the only one with a "nice" external interface
9         stronglyConnComp, stronglyConnCompR, SCC(..), flattenSCC, flattenSCCs,
10
11         Graph, Vertex,
12         graphFromEdges, graphFromEdges',
13         buildG, transposeG, reverseE, outdegree, indegree,
14
15         Tree(..), Forest,
16         showTree, showForest,
17
18         dfs, dff,
19         topSort,
20         components,
21         scc,
22         back, cross, forward,
23         reachable, path,
24         bcc
25     ) where
26
27 # include "HsVersions.h"
28
29 ------------------------------------------------------------------------------
30 -- A version of the graph algorithms described in:
31 --
32 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
33 --   by David King and John Launchbury
34 --
35 -- Also included is some additional code for printing tree structures ...
36 ------------------------------------------------------------------------------
37
38
39 import Util        ( sortLe )
40 import Outputable
41
42 -- Extensions
43 import Control.Monad.ST
44
45 -- std interfaces
46 import Data.Maybe
47 import Data.Array
48 import Data.List
49
50 #if __GLASGOW_HASKELL__ > 604
51 import Data.Array.ST
52 #else
53 import Data.Array.ST  hiding ( indices, bounds )
54 #endif
55 \end{code}
56
57
58 %************************************************************************
59 %*                                                                      *
60 %*      External interface
61 %*                                                                      *
62 %************************************************************************
63
64 \begin{code}
65 data SCC vertex = AcyclicSCC vertex
66                 | CyclicSCC  [vertex]
67
68 flattenSCCs :: [SCC a] -> [a]
69 flattenSCCs = concatMap flattenSCC
70
71 flattenSCC (AcyclicSCC v) = [v]
72 flattenSCC (CyclicSCC vs) = vs
73
74 instance Outputable a => Outputable (SCC a) where
75    ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
76    ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
77 \end{code}
78
79 \begin{code}
80 stronglyConnComp
81         :: Ord key
82         => [(node, key, [key])]         -- The graph; its ok for the
83                                         -- out-list to contain keys which arent
84                                         -- a vertex key, they are ignored
85         -> [SCC node]   -- Returned in topologically sorted order
86                         -- Later components depend on earlier ones, but not vice versa
87
88 stronglyConnComp edges
89   = map get_node (stronglyConnCompR edges)
90   where
91     get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
92     get_node (CyclicSCC triples)     = CyclicSCC [n | (n,_,_) <- triples]
93
94 -- The "R" interface is used when you expect to apply SCC to
95 -- the (some of) the result of SCC, so you dont want to lose the dependency info
96 stronglyConnCompR
97         :: Ord key
98         => [(node, key, [key])]         -- The graph; its ok for the
99                                         -- out-list to contain keys which arent
100                                         -- a vertex key, they are ignored
101         -> [SCC (node, key, [key])]     -- Topologically sorted
102
103 stronglyConnCompR [] = []  -- added to avoid creating empty array in graphFromEdges -- SOF
104 stronglyConnCompR edges
105   = map decode forest
106   where
107     (graph, vertex_fn) = {-# SCC "graphFromEdges" #-} graphFromEdges edges
108     forest             = {-# SCC "Digraph.scc" #-} scc graph
109     decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
110                        | otherwise         = AcyclicSCC (vertex_fn v)
111     decode other = CyclicSCC (dec other [])
112                  where
113                    dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
114     mentions_itself v = v `elem` (graph ! v)
115 \end{code}
116
117 %************************************************************************
118 %*                                                                      *
119 %*      Graphs
120 %*                                                                      *
121 %************************************************************************
122
123
124 \begin{code}
125 type Vertex  = Int
126 type Table a = Array Vertex a
127 type Graph   = Table [Vertex]
128 type Bounds  = (Vertex, Vertex)
129 type Edge    = (Vertex, Vertex)
130 \end{code}
131
132 \begin{code}
133 vertices :: Graph -> [Vertex]
134 vertices  = indices
135
136 edges    :: Graph -> [Edge]
137 edges g   = [ (v, w) | v <- vertices g, w <- g!v ]
138
139 mapT    :: (Vertex -> a -> b) -> Table a -> Table b
140 mapT f t = array (bounds t) [ (v, f v (t ! v)) | v <- indices t ]
141
142 buildG :: Bounds -> [Edge] -> Graph
143 buildG bounds edges = accumArray (flip (:)) [] bounds edges
144
145 transposeG  :: Graph -> Graph
146 transposeG g = buildG (bounds g) (reverseE g)
147
148 reverseE    :: Graph -> [Edge]
149 reverseE g   = [ (w, v) | (v, w) <- edges g ]
150
151 outdegree :: Graph -> Table Int
152 outdegree  = mapT numEdges
153              where numEdges v ws = length ws
154
155 indegree :: Graph -> Table Int
156 indegree  = outdegree . transposeG
157 \end{code}
158
159
160 \begin{code}
161 graphFromEdges
162         :: Ord key
163         => [(node, key, [key])]
164         -> (Graph, Vertex -> (node, key, [key]))
165 graphFromEdges edges =
166   case graphFromEdges' edges of (graph, vertex_fn, _) -> (graph, vertex_fn)
167
168 graphFromEdges'
169         :: Ord key
170         => [(node, key, [key])]
171         -> (Graph, Vertex -> (node, key, [key]), key -> Maybe Vertex)
172 graphFromEdges' edges
173   = (graph, \v -> vertex_map ! v, key_vertex)
174   where
175     max_v           = length edges - 1
176     bounds          = (0,max_v) :: (Vertex, Vertex)
177     sorted_edges    = let
178                          (_,k1,_) `le` (_,k2,_) = case k1 `compare` k2 of { GT -> False; other -> True }
179                       in
180                         sortLe le edges
181     edges1          = zipWith (,) [0..] sorted_edges
182
183     graph           = array bounds [ (v, mapMaybe key_vertex ks)
184                                | (v, (_,    _, ks)) <- edges1]
185     key_map         = array bounds [ (v, k)
186                                | (v, (_,    k, _ )) <- edges1]
187     vertex_map      = array bounds edges1
188
189
190     -- key_vertex :: key -> Maybe Vertex
191     --  returns Nothing for non-interesting vertices
192     key_vertex k   = find 0 max_v
193                    where
194                      find a b | a > b
195                               = Nothing
196                      find a b = case compare k (key_map ! mid) of
197                                    LT -> find a (mid-1)
198                                    EQ -> Just mid
199                                    GT -> find (mid+1) b
200                               where
201                                 mid = (a + b) `div` 2
202 \end{code}
203
204 %************************************************************************
205 %*                                                                      *
206 %*      Trees and forests
207 %*                                                                      *
208 %************************************************************************
209
210 \begin{code}
211 data Tree a   = Node a (Forest a)
212 type Forest a = [Tree a]
213
214 mapTree              :: (a -> b) -> (Tree a -> Tree b)
215 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
216 \end{code}
217
218 \begin{code}
219 instance Show a => Show (Tree a) where
220   showsPrec p t s = showTree t ++ s
221
222 showTree :: Show a => Tree a -> String
223 showTree  = drawTree . mapTree show
224
225 showForest :: Show a => Forest a -> String
226 showForest  = unlines . map showTree
227
228 drawTree        :: Tree String -> String
229 drawTree         = unlines . draw
230
231 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
232  where this          = s1 ++ x ++ " "
233
234        space n       = replicate n ' '
235
236        stLoop []     = [""]
237        stLoop [t]    = grp s2 "  " (draw t)
238        stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
239
240        rsLoop [t]    = grp s5 "  " (draw t)
241        rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
242
243        grp fst rst   = zipWith (++) (fst:repeat rst)
244
245        [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
246 \end{code}
247
248
249 %************************************************************************
250 %*                                                                      *
251 %*      Depth first search
252 %*                                                                      *
253 %************************************************************************
254
255 \begin{code}
256 type Set s    = STArray s Vertex Bool
257
258 mkEmpty      :: Bounds -> ST s (Set s)
259 mkEmpty bnds  = newArray bnds False
260
261 contains     :: Set s -> Vertex -> ST s Bool
262 contains m v  = readArray m v
263
264 include      :: Set s -> Vertex -> ST s ()
265 include m v   = writeArray m v True
266 \end{code}
267
268 \begin{code}
269 dff          :: Graph -> Forest Vertex
270 dff g         = dfs g (vertices g)
271
272 dfs          :: Graph -> [Vertex] -> Forest Vertex
273 dfs g vs      = prune (bounds g) (map (generate g) vs)
274
275 generate     :: Graph -> Vertex -> Tree Vertex
276 generate g v  = Node v (map (generate g) (g!v))
277
278 prune        :: Bounds -> Forest Vertex -> Forest Vertex
279 prune bnds ts = runST (mkEmpty bnds  >>= \m ->
280                        chop m ts)
281
282 chop         :: Set s -> Forest Vertex -> ST s (Forest Vertex)
283 chop m []     = return []
284 chop m (Node v ts : us)
285               = contains m v >>= \visited ->
286                 if visited then
287                   chop m us
288                 else
289                   include m v >>= \_  ->
290                   chop m ts   >>= \as ->
291                   chop m us   >>= \bs ->
292                   return (Node v as : bs)
293 \end{code}
294
295
296 %************************************************************************
297 %*                                                                      *
298 %*      Algorithms
299 %*                                                                      *
300 %************************************************************************
301
302 ------------------------------------------------------------
303 -- Algorithm 1: depth first search numbering
304 ------------------------------------------------------------
305
306 \begin{code}
307 --preorder            :: Tree a -> [a]
308 preorder (Node a ts) = a : preorderF ts
309
310 preorderF           :: Forest a -> [a]
311 preorderF ts         = concat (map preorder ts)
312
313 tabulate        :: Bounds -> [Vertex] -> Table Int
314 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
315
316 preArr          :: Bounds -> Forest Vertex -> Table Int
317 preArr bnds      = tabulate bnds . preorderF
318 \end{code}
319
320
321 ------------------------------------------------------------
322 -- Algorithm 2: topological sorting
323 ------------------------------------------------------------
324
325 \begin{code}
326 postorder :: Tree a -> [a] -> [a]
327 postorder (Node a ts) = postorderF ts . (a :)
328
329 postorderF   :: Forest a -> [a] -> [a]
330 postorderF ts = foldr (.) id $ map postorder ts
331
332 postOrd :: Graph -> [Vertex]
333 postOrd g = postorderF (dff g) []
334
335 topSort :: Graph -> [Vertex]
336 topSort = reverse . postOrd
337 \end{code}
338
339
340 ------------------------------------------------------------
341 -- Algorithm 3: connected components
342 ------------------------------------------------------------
343
344 \begin{code}
345 components   :: Graph -> Forest Vertex
346 components    = dff . undirected
347
348 undirected   :: Graph -> Graph
349 undirected g  = buildG (bounds g) (edges g ++ reverseE g)
350 \end{code}
351
352
353 -- Algorithm 4: strongly connected components
354
355 \begin{code}
356 scc  :: Graph -> Forest Vertex
357 scc g = dfs g (reverse (postOrd (transposeG g)))
358 \end{code}
359
360
361 ------------------------------------------------------------
362 -- Algorithm 5: Classifying edges
363 ------------------------------------------------------------
364
365 \begin{code}
366 back              :: Graph -> Table Int -> Graph
367 back g post        = mapT select g
368  where select v ws = [ w | w <- ws, post!v < post!w ]
369
370 cross             :: Graph -> Table Int -> Table Int -> Graph
371 cross g pre post   = mapT select g
372  where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
373
374 forward           :: Graph -> Graph -> Table Int -> Graph
375 forward g tree pre = mapT select g
376  where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
377 \end{code}
378
379
380 ------------------------------------------------------------
381 -- Algorithm 6: Finding reachable vertices
382 ------------------------------------------------------------
383
384 \begin{code}
385 reachable    :: Graph -> Vertex -> [Vertex]
386 reachable g v = preorderF (dfs g [v])
387
388 path         :: Graph -> Vertex -> Vertex -> Bool
389 path g v w    = w `elem` (reachable g v)
390 \end{code}
391
392
393 ------------------------------------------------------------
394 -- Algorithm 7: Biconnected components
395 ------------------------------------------------------------
396
397 \begin{code}
398 bcc :: Graph -> Forest [Vertex]
399 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
400  where forest = dff g
401        dnum   = preArr (bounds g) forest
402
403 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
404 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
405  where us = map (do_label g dnum) ts
406        lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
407                      ++ [lu | Node (u,du,lu) xs <- us])
408
409 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
410 bicomps (Node (v,dv,lv) ts)
411       = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
412
413 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
414 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
415  where collected = map collect ts
416        vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
417        cs = concat [ if lw<dv then us else [Node (v:ws) us]
418                         | (lw, Node ws us) <- collected ]
419 \end{code}
420