1 -- | Basic operations on graphs.
3 -- TODO: refine coalescing crieteria
5 {-# OPTIONS -fno-warn-missing-signatures #-}
8 addNode, delNode, getNode, lookupNode, modNode,
11 addConflict, delConflict, addConflicts,
12 addCoalesce, delCoalesce,
15 coalesceNodes, coalesceGraph,
16 freezeNode, freezeOneInGraph, freezeAllInGraph,
20 slurpNodeConflictCount
31 import Data.List hiding (union)
34 -- | Lookup a node from the graph.
38 -> k -> Maybe (Node k cls color)
41 = lookupUFM (graphMap graph) k
44 -- | Get a node from the graph, throwing an error if it's not there
48 -> k -> Node k cls color
51 = case lookupUFM (graphMap graph) k of
53 Nothing -> panic "ColorOps.getNode: not found"
56 -- | Add a node to the graph, linking up its edges
57 addNode :: Uniquable k
58 => k -> Node k cls color
59 -> Graph k cls color -> Graph k cls color
63 -- add back conflict edges from other nodes to this one
66 (adjustUFM (\n -> n { nodeConflicts = addOneToUniqSet (nodeConflicts n) k}))
70 -- add back coalesce edges from other nodes to this one
73 (adjustUFM (\n -> n { nodeCoalesce = addOneToUniqSet (nodeCoalesce n) k}))
78 { graphMap = addToUFM map_coalesce k node}
82 -- | Delete a node and all its edges from the graph.
83 -- Throws an error if it's not there.
84 delNode :: Uniquable k
85 => k -> Graph k cls color -> Graph k cls color
88 = let Just node = lookupNode graph k
90 -- delete conflict edges from other nodes to this one.
91 graph1 = foldl' (\g k1 -> let Just g' = delConflict k1 k g in g') graph
92 $ uniqSetToList (nodeConflicts node)
94 -- delete coalesce edge from other nodes to this one.
95 graph2 = foldl' (\g k1 -> let Just g' = delCoalesce k1 k g in g') graph1
96 $ uniqSetToList (nodeCoalesce node)
99 graph3 = graphMapModify (\fm -> delFromUFM fm k) graph2
104 -- | Modify a node in the graph.
105 -- returns Nothing if the node isn't present.
107 modNode :: Uniquable k
108 => (Node k cls color -> Node k cls color)
109 -> k -> Graph k cls color -> Maybe (Graph k cls color)
112 = case lookupNode graph k of
116 (\fm -> let Just node = lookupUFM fm k
118 in addToUFM fm k node')
124 -- | Get the size of the graph, O(n)
126 => Graph k cls color -> Int
129 = sizeUFM $ graphMap graph
132 -- | Union two graphs together.
134 => Graph k cls color -> Graph k cls color -> Graph k cls color
138 { graphMap = plusUFM (graphMap graph1) (graphMap graph2) }
141 -- | Add a conflict between nodes to the graph, creating the nodes required.
142 -- Conflicts are virtual regs which need to be colored differently.
145 => (k, cls) -> (k, cls)
146 -> Graph k cls color -> Graph k cls color
148 addConflict (u1, c1) (u2, c2)
149 = let addNeighbor u c u'
150 = adjustWithDefaultUFM
151 (\node -> node { nodeConflicts = addOneToUniqSet (nodeConflicts node) u' })
152 (newNode u c) { nodeConflicts = unitUniqSet u' }
156 ( addNeighbor u1 c1 u2
157 . addNeighbor u2 c2 u1)
160 -- | Delete a conflict edge. k1 -> k2
161 -- returns Nothing if the node isn't in the graph
165 -> Graph k cls color -> Maybe (Graph k cls color)
169 (\node -> node { nodeConflicts = delOneFromUniqSet (nodeConflicts node) k2 })
173 -- | Add some conflicts to the graph, creating nodes if required.
174 -- All the nodes in the set are taken to conflict with each other.
177 => UniqSet k -> (k -> cls)
178 -> Graph k cls color -> Graph k cls color
180 addConflicts conflicts getClass
182 -- just a single node, but no conflicts, create the node anyway.
183 | (u : []) <- uniqSetToList conflicts
185 $ adjustWithDefaultUFM
187 (newNode u (getClass u))
192 $ (\fm -> foldl' (\g u -> addConflictSet1 u getClass conflicts g) fm
193 $ uniqSetToList conflicts)
196 addConflictSet1 u getClass set
197 = case delOneFromUniqSet set u of
198 set' -> adjustWithDefaultUFM
199 (\node -> node { nodeConflicts = unionUniqSets set' (nodeConflicts node) } )
200 (newNode u (getClass u)) { nodeConflicts = set' }
204 -- | Add an exclusion to the graph, creating nodes if required.
205 -- These are extra colors that the node cannot use.
207 :: (Uniquable k, Uniquable color)
208 => k -> (k -> cls) -> color
209 -> Graph k cls color -> Graph k cls color
211 addExclusion u getClass color
213 $ adjustWithDefaultUFM
214 (\node -> node { nodeExclusions = addOneToUniqSet (nodeExclusions node) color })
215 (newNode u (getClass u)) { nodeExclusions = unitUniqSet color }
219 -- | Add a coalescence edge to the graph, creating nodes if requried.
220 -- It is considered adventageous to assign the same color to nodes in a coalesence.
223 => (k, cls) -> (k, cls)
224 -> Graph k cls color -> Graph k cls color
226 addCoalesce (u1, c1) (u2, c2)
227 = let addCoalesce u c u'
228 = adjustWithDefaultUFM
229 (\node -> node { nodeCoalesce = addOneToUniqSet (nodeCoalesce node) u' })
230 (newNode u c) { nodeCoalesce = unitUniqSet u' }
234 ( addCoalesce u1 c1 u2
235 . addCoalesce u2 c2 u1)
238 -- | Delete a coalescence edge (k1 -> k2) from the graph.
242 -> Graph k cls color -> Maybe (Graph k cls color)
245 = modNode (\node -> node { nodeCoalesce = delOneFromUniqSet (nodeCoalesce node) k2 })
249 -- | Add a color preference to the graph, creating nodes if required.
250 -- The most recently added preference is the most prefered.
251 -- The algorithm tries to assign a node it's prefered color if possible.
256 -> Graph k cls color -> Graph k cls color
258 addPreference (u, c) color
260 $ adjustWithDefaultUFM
261 (\node -> node { nodePreference = color : (nodePreference node) })
262 (newNode u c) { nodePreference = [color] }
266 -- | Do agressive coalescing on this graph.
267 -- returns the new graph and the list of pairs of nodes that got coaleced together.
268 -- for each pair, the resulting node will have the least key and be second in the pair.
271 :: (Uniquable k, Ord k, Eq cls, Outputable k)
272 => Bool -- ^ If True, coalesce nodes even if this might make the graph
273 -- less colorable (aggressive coalescing)
276 -> (Graph k cls color, [(k, k)])
278 coalesceGraph aggressive triv graph
279 = coalesceGraph' aggressive triv graph []
281 coalesceGraph' aggressive triv graph kkPairsAcc
283 -- find all the nodes that have coalescence edges
284 cNodes = filter (\node -> not $ isEmptyUniqSet (nodeCoalesce node))
285 $ eltsUFM $ graphMap graph
287 -- build a list of pairs of keys for node's we'll try and coalesce
288 -- every pair of nodes will appear twice in this list
289 -- ie [(k1, k2), (k2, k1) ... ]
290 -- This is ok, GrapOps.coalesceNodes handles this and it's convenient for
291 -- build a list of what nodes get coalesced together for later on.
293 cList = [ (nodeId node1, k2)
295 , k2 <- uniqSetToList $ nodeCoalesce node1 ]
297 -- do the coalescing, returning the new graph and a list of pairs of keys
298 -- that got coalesced together.
300 = mapAccumL (coalesceNodes aggressive triv) graph cList
302 -- keep running until there are no more coalesces can be found
303 in case catMaybes mPairs of
304 [] -> (graph', kkPairsAcc)
305 pairs -> coalesceGraph' aggressive triv graph' (pairs ++ kkPairsAcc)
308 -- | Coalesce this pair of nodes unconditionally / agressively.
309 -- The resulting node is the one with the least key.
311 -- returns: Just the pair of keys if the nodes were coalesced
312 -- the second element of the pair being the least one
314 -- Nothing if either of the nodes weren't in the graph
317 :: (Uniquable k, Ord k, Eq cls, Outputable k)
318 => Bool -- ^ If True, coalesce nodes even if this might make the graph
319 -- less colorable (aggressive coalescing)
322 -> (k, k) -- ^ keys of the nodes to be coalesced
323 -> (Graph k cls color, Maybe (k, k))
325 coalesceNodes aggressive triv graph (k1, k2)
326 | (kMin, kMax) <- if k1 < k2
330 -- the nodes being coalesced must be in the graph
331 , Just nMin <- lookupNode graph kMin
332 , Just nMax <- lookupNode graph kMax
334 -- can't coalesce conflicting modes
335 , not $ elementOfUniqSet kMin (nodeConflicts nMax)
336 , not $ elementOfUniqSet kMax (nodeConflicts nMin)
338 = coalesceNodes_merge aggressive triv graph kMin kMax nMin nMax
340 -- don't do the coalescing after all
344 coalesceNodes_merge aggressive triv graph kMin kMax nMin nMax
347 | nodeClass nMin /= nodeClass nMax
348 = error "GraphOps.coalesceNodes: can't coalesce nodes of different classes."
350 | not (isNothing (nodeColor nMin) && isNothing (nodeColor nMax))
351 = error "GraphOps.coalesceNodes: can't coalesce colored nodes."
356 -- the new node gets all the edges from its two components
359 , nodeClass = nodeClass nMin
360 , nodeColor = Nothing
362 -- nodes don't conflict with themselves..
364 = (unionUniqSets (nodeConflicts nMin) (nodeConflicts nMax))
365 `delOneFromUniqSet` kMin
366 `delOneFromUniqSet` kMax
368 , nodeExclusions = unionUniqSets (nodeExclusions nMin) (nodeExclusions nMax)
369 , nodePreference = nodePreference nMin ++ nodePreference nMax
371 -- nodes don't coalesce with themselves..
373 = (unionUniqSets (nodeCoalesce nMin) (nodeCoalesce nMax))
374 `delOneFromUniqSet` kMin
375 `delOneFromUniqSet` kMax
378 in coalesceNodes_check aggressive triv graph kMin kMax node
380 coalesceNodes_check aggressive triv graph kMin kMax node
382 -- Unless we're coalescing aggressively, if the result node is not trivially
383 -- colorable then don't do the coalescing.
385 , not $ triv (nodeClass node) (nodeConflicts node) (nodeExclusions node)
389 = let -- delete the old nodes from the graph and add the new one
390 graph' = addNode kMin node
395 in (graph', Just (kMax, kMin))
399 -- This is for the iterative coalescer.
400 -- By freezing a node we give up on ever coalescing it.
401 -- Move all its coalesce edges into the frozen set - and update
402 -- back edges from other nodes.
406 => k -- ^ key of the node to freeze
407 -> Graph k cls color -- ^ the graph
408 -> Graph k cls color -- ^ graph with that node frozen
414 -- freeze all the edges in the node to be frozen
415 Just node = lookupUFM fm k
417 { nodeCoalesce = emptyUniqSet }
419 fm1 = addToUFM fm k node'
421 -- update back edges pointing to this node
423 = if elementOfUniqSet k (nodeCoalesce node)
425 { nodeCoalesce = delOneFromUniqSet (nodeCoalesce node) k }
426 else panic "GraphOps.freezeNode: edge to freeze wasn't in the coalesce set"
428 fm2 = foldUniqSet (adjustUFM (freezeEdge k)) fm1
434 -- | Freeze one node in the graph
435 -- This if for the iterative coalescer.
436 -- Look for a move related node of low degree and freeze it.
438 -- We probably don't need to scan the whole graph looking for the node of absolute
439 -- lowest degree. Just sample the first few and choose the one with the lowest
440 -- degree out of those. Also, we don't make any distinction between conflicts of different
441 -- classes.. this is just a heuristic, after all.
443 -- IDEA: freezing a node might free it up for Simplify.. would be good to check for triv
444 -- right here, and add it to a worklist if known triv/non-move nodes.
447 :: (Uniquable k, Outputable k)
449 -> ( Graph k cls color -- the new graph
450 , Bool ) -- whether we found a node to freeze
452 freezeOneInGraph graph
453 = let compareNodeDegree n1 n2
454 = compare (sizeUniqSet $ nodeConflicts n1) (sizeUniqSet $ nodeConflicts n2)
457 = sortBy compareNodeDegree
458 $ take 5 -- 5 isn't special, it's just a small number.
459 $ scanGraph (\node -> not $ isEmptyUniqSet (nodeCoalesce node)) graph
461 in case candidates of
463 -- there wasn't anything available to freeze
466 -- we found something to freeze
468 -> ( freezeNode (nodeId n) graph
472 -- | Freeze all the nodes in the graph
473 -- for debugging the iterative allocator.
476 :: (Uniquable k, Outputable k)
480 freezeAllInGraph graph
481 = foldr freezeNode graph
483 $ eltsUFM $ graphMap graph
486 -- | Find all the nodes in the graph that meet some criteria
490 => (Node k cls color -> Bool)
492 -> [Node k cls color]
494 scanGraph match graph
495 = filter match $ eltsUFM $ graphMap graph
498 -- | validate the internal structure of a graph
499 -- all its edges should point to valid nodes
500 -- if they don't then throw an error
503 :: (Uniquable k, Outputable k)
508 validateGraph doc graph
509 = let edges = unionManyUniqSets
510 ( (map nodeConflicts $ eltsUFM $ graphMap graph)
511 ++ (map nodeCoalesce $ eltsUFM $ graphMap graph))
513 nodes = mkUniqSet $ map nodeId $ eltsUFM $ graphMap graph
515 badEdges = minusUniqSet edges nodes
517 in if isEmptyUniqSet badEdges
519 else pprPanic "GraphOps.validateGraph"
520 ( text "-- bad edges"
521 $$ vcat (map ppr $ uniqSetToList badEdges)
522 $$ text "----------------------------"
526 -- | Slurp out a map of how many nodes had a certain number of conflict neighbours
528 slurpNodeConflictCount
531 -> UniqFM (Int, Int) -- ^ (conflict neighbours, num nodes with that many conflicts)
533 slurpNodeConflictCount graph
535 (\(c1, n1) (_, n2) -> (c1, n1 + n2))
538 -> let count = sizeUniqSet $ nodeConflicts node
539 in (count, (count, 1)))
544 -- | Set the color of a certain node
548 -> Graph k cls color -> Graph k cls color
553 (\n -> n { nodeColor = Just color })
557 {-# INLINE adjustWithDefaultUFM #-}
560 => (a -> a) -> a -> k
561 -> UniqFM a -> UniqFM a
563 adjustWithDefaultUFM f def k map
569 {-# INLINE adjustUFM #-}
573 -> k -> UniqFM a -> UniqFM a
576 = case lookupUFM map k of
578 Just a -> addToUFM map k (f a)