1 -- | Graph coloring register allocator.
4 -- The function that choosing the potential spills could be a bit cleverer.
5 -- Colors in graphviz graphs could be nicer.
7 {-# OPTIONS -fno-warn-missing-signatures #-}
16 import qualified GraphColor as Color
37 -- | The maximum number of build/spill cycles we'll allow.
38 -- We should only need 3 or 4 cycles tops.
39 -- If we run for any longer than this we're probably in an infinite loop,
40 -- It's probably better just to bail out and report a bug at this stage.
45 -- | The top level of the graph coloring register allocator.
49 -> UniqFM (UniqSet Reg) -- ^ the registers we can use for allocation
50 -> UniqSet Int -- ^ the set of available spill slots.
51 -> [LiveCmmTop] -- ^ code annotated with liveness information.
53 ( [NatCmmTop] -- ^ code with registers allocated.
54 , [RegAllocStats] ) -- ^ stats for each stage of allocation
56 regAlloc dflags regsFree slotsFree code
58 (code_final, debug_codeGraphs, _)
59 <- regAlloc_spin dflags 0 trivColorable regsFree slotsFree [] code
62 , reverse debug_codeGraphs )
64 regAlloc_spin dflags (spinCount :: Int) triv regsFree slotsFree debug_codeGraphs code
66 -- if any of these dump flags are turned on we want to hang on to
67 -- intermediate structures in the allocator - otherwise tell the
68 -- allocator to ditch them early so we don't end up creating space leaks.
70 [ dopt Opt_D_dump_asm_regalloc_stages dflags
71 , dopt Opt_D_dump_asm_stats dflags
72 , dopt Opt_D_dump_asm_conflicts dflags ]
74 -- check that we're not running off down the garden path.
75 when (spinCount > maxSpinCount)
76 $ pprPanic "regAlloc_spin: max build/spill cycle count exceeded."
77 ( text "It looks like the register allocator is stuck in an infinite loop."
78 $$ text "max cycles = " <> int maxSpinCount
79 $$ text "regsFree = " <> (hcat $ punctuate space $ map (docToSDoc . pprUserReg)
80 $ uniqSetToList $ unionManyUniqSets $ eltsUFM regsFree)
81 $$ text "slotsFree = " <> ppr (sizeUniqSet slotsFree))
84 -- Brig's algorithm does reckless coalescing for all but the first allocation stage
85 -- Doing this seems to reduce the number of reg-reg moves, but at the cost-
86 -- of creating more spills. Probably better just to stick with conservative
87 -- coalescing in Color.colorGraph for now.
89 {- code_coalesced1 <- if (spinCount > 0)
93 let code_coalesced1 = code
96 -- build a conflict graph from the code.
97 graph <- {-# SCC "BuildGraph" #-} buildGraph code_coalesced1
100 -- We really do want the graph to be fully evaluated _before_ we start coloring.
101 -- If we don't do this now then when the call to Color.colorGraph forces bits of it,
102 -- the heap will be filled with half evaluated pieces of graph and zillions of apply thunks.
104 seqGraph graph `seq` return ()
107 -- build a map of how many instructions each reg lives for.
108 -- this is lazy, it won't be computed unless we need to spill
110 let fmLife = {-# SCC "LifetimeCount" #-} plusUFMs_C (\(r1, l1) (_, l2) -> (r1, l1 + l2))
111 $ map lifetimeCount code_coalesced1
113 -- record startup state
116 then Just $ RegAllocStatsStart
119 , raLifetimes = fmLife }
123 -- the function to choose regs to leave uncolored
124 let spill = chooseSpill_maxLife fmLife
126 -- try and color the graph
127 let (graph_colored, rsSpill, rmCoalesce)
128 = {-# SCC "ColorGraph" #-}
130 (dopt Opt_RegsIterative dflags)
132 regsFree triv spill graph
134 -- rewrite regs in the code that have been coalesced
135 let patchF reg = case lookupUFM rmCoalesce reg of
136 Just reg' -> patchF reg'
139 = map (patchEraseLive patchF) code_coalesced1
142 -- see if we've found a coloring
143 if isEmptyUniqSet rsSpill
145 -- patch the registers using the info in the graph
146 let code_patched = map (patchRegsFromGraph graph_colored) code_coalesced2
148 -- clean out unneeded SPILL/RELOADs
149 let code_spillclean = map cleanSpills code_patched
151 -- strip off liveness information
152 let code_nat = map stripLive code_spillclean
154 -- rewrite SPILL/RELOAD pseudos into real instructions
155 let spillNatTop = mapGenBlockTop spillNatBlock
156 let code_final = map spillNatTop code_nat
158 -- record what happened in this stage for debugging
161 { raGraph = graph_colored
162 , raCoalesced = rmCoalesce
163 , raPatched = code_patched
164 , raSpillClean = code_spillclean
165 , raFinal = code_final
166 , raSRMs = foldl' addSRM (0, 0, 0) $ map countSRMs code_spillclean }
170 if dump then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
173 -- space leak avoidance
174 seqList statList `seq` return ()
181 -- spill the uncolored regs
182 (code_spilled, slotsFree', spillStats)
183 <- regSpill code_coalesced2 slotsFree rsSpill
185 -- recalculate liveness
186 let code_nat = map stripLive code_spilled
187 code_relive <- mapM regLiveness code_nat
189 -- record what happened in this stage for debugging
192 { raGraph = graph_colored
193 , raCoalesced = rmCoalesce
194 , raSpillStats = spillStats
195 , raLifetimes = fmLife
196 , raSpilled = code_spilled }
200 then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
203 -- space leak avoidance
204 seqList statList `seq` return ()
206 regAlloc_spin dflags (spinCount + 1) triv regsFree slotsFree'
212 -- Simple maxconflicts isn't always good, because we
213 -- can naievely end up spilling vregs that only live for one or two instrs.
216 chooseSpill_maxConflicts
217 :: Color.Graph Reg RegClass Reg
220 chooseSpill_maxConflicts graph
221 = let node = maximumBy
223 (sizeUniqSet $ Color.nodeConflicts n1)
224 (sizeUniqSet $ Color.nodeConflicts n2))
225 $ eltsUFM $ Color.graphMap graph
233 -> Color.Graph Reg RegClass Reg
236 chooseSpill_maxLife life graph
237 = let node = maximumBy (\n1 n2 -> compare (getLife n1) (getLife n2))
238 $ eltsUFM $ Color.graphMap graph
240 -- Orphan vregs die in the same instruction they are born in.
241 -- They will be in the graph, but not in the liveness map.
242 -- Their liveness is 0.
244 = case lookupUFM life (Color.nodeId n) of
251 -- | Build a graph from the liveness and coalesce information in this code.
255 -> UniqSM (Color.Graph Reg RegClass Reg)
259 -- Slurp out the conflicts and reg->reg moves from this code
260 let (conflictList, moveList) =
261 unzip $ map slurpConflicts code
263 -- Slurp out the spill/reload coalesces
264 let moveList2 = map slurpReloadCoalesce code
266 -- Add the reg-reg conflicts to the graph
267 let conflictBag = unionManyBags conflictList
268 let graph_conflict = foldrBag graphAddConflictSet Color.initGraph conflictBag
270 -- Add the coalescences edges to the graph.
271 let moveBag = unionBags (unionManyBags moveList2) (unionManyBags moveList)
272 let graph_coalesce = foldrBag graphAddCoalesce graph_conflict moveBag
274 return graph_coalesce
277 -- | Add some conflict edges to the graph.
278 -- Conflicts between virtual and real regs are recorded as exclusions.
282 -> Color.Graph Reg RegClass Reg
283 -> Color.Graph Reg RegClass Reg
285 graphAddConflictSet set graph
286 = let reals = filterUFM isRealReg set
287 virtuals = filterUFM (not . isRealReg) set
289 graph1 = Color.addConflicts virtuals regClass graph
290 graph2 = foldr (\(r1, r2) -> Color.addExclusion r1 regClass r2)
293 | a <- uniqSetToList virtuals
294 , b <- uniqSetToList reals]
299 -- | Add some coalesence edges to the graph
300 -- Coalesences between virtual and real regs are recorded as preferences.
304 -> Color.Graph Reg RegClass Reg
305 -> Color.Graph Reg RegClass Reg
307 graphAddCoalesce (r1, r2) graph
309 = Color.addPreference (regWithClass r2) r1 graph
312 = Color.addPreference (regWithClass r1) r2 graph
315 = Color.addCoalesce (regWithClass r1) (regWithClass r2) graph
317 where regWithClass r = (r, regClass r)
320 -- | Patch registers in code using the reg -> reg mapping in this graph.
322 :: Color.Graph Reg RegClass Reg
323 -> LiveCmmTop -> LiveCmmTop
325 patchRegsFromGraph graph code
327 -- a function to lookup the hardreg for a virtual reg from the graph.
329 -- leave real regs alone.
333 -- this virtual has a regular node in the graph.
334 | Just node <- Color.lookupNode graph reg
335 = case Color.nodeColor node of
339 -- no node in the graph for this virtual, bad news.
341 = pprPanic "patchRegsFromGraph: register mapping failed."
342 ( text "There is no node in the graph for register " <> ppr reg
344 $$ Color.dotGraph (\_ -> text "white") trivColorable graph)
346 in patchEraseLive patchF code
349 plusUFMs_C :: (elt -> elt -> elt) -> [UniqFM elt] -> UniqFM elt
351 = foldl' (plusUFM_C f) emptyUFM maps
355 -- for when laziness just isn't what you wanted...
357 seqGraph :: Color.Graph Reg RegClass Reg -> ()
358 seqGraph graph = seqNodes (eltsUFM (Color.graphMap graph))
360 seqNodes :: [Color.Node Reg RegClass Reg] -> ()
364 (n : ns) -> seqNode n `seq` seqNodes ns
366 seqNode :: Color.Node Reg RegClass Reg -> ()
368 = seqReg (Color.nodeId node)
369 `seq` seqRegClass (Color.nodeClass node)
370 `seq` seqMaybeReg (Color.nodeColor node)
371 `seq` (seqRegList (uniqSetToList (Color.nodeConflicts node)))
372 `seq` (seqRegList (uniqSetToList (Color.nodeExclusions node)))
373 `seq` (seqRegList (Color.nodePreference node))
374 `seq` (seqRegList (uniqSetToList (Color.nodeCoalesce node)))
385 seqRegClass :: RegClass -> ()
392 seqMaybeReg :: Maybe Reg -> ()
398 seqRegList :: [Reg] -> ()
402 (r : rs) -> seqReg r `seq` seqRegList rs
408 (r : rs) -> r `seq` seqList rs