1 -- | Graph coloring register allocator.
3 -- TODO: The colors in graphviz graphs for x86_64 and ppc could be nicer.
5 {-# OPTIONS -fno-warn-missing-signatures #-}
14 import qualified GraphColor as Color
36 -- | The maximum number of build/spill cycles we'll allow.
37 -- We should only need 3 or 4 cycles tops.
38 -- If we run for any longer than this we're probably in an infinite loop,
39 -- It's probably better just to bail out and report a bug at this stage.
44 -- | The top level of the graph coloring register allocator.
48 -> UniqFM (UniqSet Reg) -- ^ the registers we can use for allocation
49 -> UniqSet Int -- ^ the set of available spill slots.
50 -> [LiveCmmTop] -- ^ code annotated with liveness information.
52 ( [NatCmmTop] -- ^ code with registers allocated.
53 , [RegAllocStats] ) -- ^ stats for each stage of allocation
55 regAlloc dflags regsFree slotsFree code
57 (code_final, debug_codeGraphs, _)
58 <- regAlloc_spin dflags 0 trivColorable regsFree slotsFree [] code
61 , reverse debug_codeGraphs )
63 regAlloc_spin dflags (spinCount :: Int) triv regsFree slotsFree debug_codeGraphs code
65 -- if any of these dump flags are turned on we want to hang on to
66 -- intermediate structures in the allocator - otherwise tell the
67 -- allocator to ditch them early so we don't end up creating space leaks.
69 [ dopt Opt_D_dump_asm_regalloc_stages dflags
70 , dopt Opt_D_dump_asm_stats dflags
71 , dopt Opt_D_dump_asm_conflicts dflags ]
73 -- check that we're not running off down the garden path.
74 when (spinCount > maxSpinCount)
75 $ pprPanic "regAlloc_spin: max build/spill cycle count exceeded."
76 ( text "It looks like the register allocator is stuck in an infinite loop."
77 $$ text "max cycles = " <> int maxSpinCount
78 $$ text "regsFree = " <> (hcat $ punctuate space $ map (docToSDoc . pprUserReg)
79 $ uniqSetToList $ unionManyUniqSets $ eltsUFM regsFree)
80 $$ text "slotsFree = " <> ppr (sizeUniqSet slotsFree))
82 -- build a conflict graph from the code.
83 graph <- {-# SCC "BuildGraph" #-} buildGraph code
86 -- We really do want the graph to be fully evaluated _before_ we start coloring.
87 -- If we don't do this now then when the call to Color.colorGraph forces bits of it,
88 -- the heap will be filled with half evaluated pieces of graph and zillions of apply thunks.
90 seqGraph graph `seq` return ()
93 -- build a map of the cost of spilling each instruction
94 -- this will only actually be computed if we have to spill something.
95 let spillCosts = foldl' plusSpillCostInfo zeroSpillCostInfo
96 $ map slurpSpillCostInfo code
98 -- the function to choose regs to leave uncolored
99 let spill = chooseSpill spillCosts
101 -- record startup state
104 then Just $ RegAllocStatsStart
107 , raSpillCosts = spillCosts }
110 -- try and color the graph
111 let (graph_colored, rsSpill, rmCoalesce)
112 = {-# SCC "ColorGraph" #-}
114 (dopt Opt_RegsIterative dflags)
116 regsFree triv spill graph
118 -- rewrite regs in the code that have been coalesced
119 let patchF reg = case lookupUFM rmCoalesce reg of
120 Just reg' -> patchF reg'
123 = map (patchEraseLive patchF) code
126 -- see if we've found a coloring
127 if isEmptyUniqSet rsSpill
129 -- if -fasm-lint is turned on then validate the graph
130 let graph_colored_lint =
131 if dopt Opt_DoAsmLinting dflags
132 then Color.validateGraph (text "")
133 True -- require all nodes to be colored
137 -- patch the registers using the info in the graph
138 let code_patched = map (patchRegsFromGraph graph_colored_lint) code_coalesced
140 -- clean out unneeded SPILL/RELOADs
141 let code_spillclean = map cleanSpills code_patched
143 -- strip off liveness information
144 let code_nat = map stripLive code_spillclean
146 -- rewrite SPILL/RELOAD pseudos into real instructions
147 let spillNatTop = mapGenBlockTop spillNatBlock
148 let code_final = map spillNatTop code_nat
150 -- record what happened in this stage for debugging
154 , raGraphColored = graph_colored_lint
155 , raCoalesced = rmCoalesce
156 , raPatched = code_patched
157 , raSpillClean = code_spillclean
158 , raFinal = code_final
159 , raSRMs = foldl' addSRM (0, 0, 0) $ map countSRMs code_spillclean }
163 if dump then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
166 -- space leak avoidance
167 seqList statList `seq` return ()
171 , graph_colored_lint)
173 -- we couldn't find a coloring, time to spill something
175 -- if -fasm-lint is turned on then validate the graph
176 let graph_colored_lint =
177 if dopt Opt_DoAsmLinting dflags
178 then Color.validateGraph (text "")
179 False -- don't require nodes to be colored
183 -- spill the uncolored regs
184 (code_spilled, slotsFree', spillStats)
185 <- regSpill code_coalesced slotsFree rsSpill
187 -- recalculate liveness
188 let code_nat = map stripLive code_spilled
189 code_relive <- mapM regLiveness code_nat
191 -- record what happened in this stage for debugging
194 { raGraph = graph_colored_lint
195 , raCoalesced = rmCoalesce
196 , raSpillStats = spillStats
197 , raSpillCosts = spillCosts
198 , raSpilled = code_spilled }
202 then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
205 -- space leak avoidance
206 seqList statList `seq` return ()
208 regAlloc_spin dflags (spinCount + 1) triv regsFree slotsFree'
214 -- | Build a graph from the liveness and coalesce information in this code.
218 -> UniqSM (Color.Graph Reg RegClass Reg)
222 -- Slurp out the conflicts and reg->reg moves from this code
223 let (conflictList, moveList) =
224 unzip $ map slurpConflicts code
226 -- Slurp out the spill/reload coalesces
227 let moveList2 = map slurpReloadCoalesce code
229 -- Add the reg-reg conflicts to the graph
230 let conflictBag = unionManyBags conflictList
231 let graph_conflict = foldrBag graphAddConflictSet Color.initGraph conflictBag
233 -- Add the coalescences edges to the graph.
234 let moveBag = unionBags (unionManyBags moveList2) (unionManyBags moveList)
235 let graph_coalesce = foldrBag graphAddCoalesce graph_conflict moveBag
237 return graph_coalesce
240 -- | Add some conflict edges to the graph.
241 -- Conflicts between virtual and real regs are recorded as exclusions.
245 -> Color.Graph Reg RegClass Reg
246 -> Color.Graph Reg RegClass Reg
248 graphAddConflictSet set graph
249 = let reals = filterUFM isRealReg set
250 virtuals = filterUFM (not . isRealReg) set
252 graph1 = Color.addConflicts virtuals regClass graph
253 graph2 = foldr (\(r1, r2) -> Color.addExclusion r1 regClass r2)
256 | a <- uniqSetToList virtuals
257 , b <- uniqSetToList reals]
262 -- | Add some coalesence edges to the graph
263 -- Coalesences between virtual and real regs are recorded as preferences.
267 -> Color.Graph Reg RegClass Reg
268 -> Color.Graph Reg RegClass Reg
270 graphAddCoalesce (r1, r2) graph
272 = Color.addPreference (regWithClass r2) r1 graph
275 = Color.addPreference (regWithClass r1) r2 graph
278 = Color.addCoalesce (regWithClass r1) (regWithClass r2) graph
280 where regWithClass r = (r, regClass r)
283 -- | Patch registers in code using the reg -> reg mapping in this graph.
285 :: Color.Graph Reg RegClass Reg
286 -> LiveCmmTop -> LiveCmmTop
288 patchRegsFromGraph graph code
290 -- a function to lookup the hardreg for a virtual reg from the graph.
292 -- leave real regs alone.
296 -- this virtual has a regular node in the graph.
297 | Just node <- Color.lookupNode graph reg
298 = case Color.nodeColor node of
302 -- no node in the graph for this virtual, bad news.
304 = pprPanic "patchRegsFromGraph: register mapping failed."
305 ( text "There is no node in the graph for register " <> ppr reg
307 $$ Color.dotGraph (\_ -> text "white") trivColorable graph)
309 in patchEraseLive patchF code
313 -- for when laziness just isn't what you wanted...
315 seqGraph :: Color.Graph Reg RegClass Reg -> ()
316 seqGraph graph = seqNodes (eltsUFM (Color.graphMap graph))
318 seqNodes :: [Color.Node Reg RegClass Reg] -> ()
322 (n : ns) -> seqNode n `seq` seqNodes ns
324 seqNode :: Color.Node Reg RegClass Reg -> ()
326 = seqReg (Color.nodeId node)
327 `seq` seqRegClass (Color.nodeClass node)
328 `seq` seqMaybeReg (Color.nodeColor node)
329 `seq` (seqRegList (uniqSetToList (Color.nodeConflicts node)))
330 `seq` (seqRegList (uniqSetToList (Color.nodeExclusions node)))
331 `seq` (seqRegList (Color.nodePreference node))
332 `seq` (seqRegList (uniqSetToList (Color.nodeCoalesce node)))
343 seqRegClass :: RegClass -> ()
350 seqMaybeReg :: Maybe Reg -> ()
356 seqRegList :: [Reg] -> ()
360 (r : rs) -> seqReg r `seq` seqRegList rs
366 (r : rs) -> r `seq` seqList rs