1 {-# OPTIONS -fno-warn-missing-signatures #-}
2 -- | Graph coloring register allocator.
4 -- TODO: The colors in graphviz graphs for x86_64 and ppc could be nicer.
7 module RegAlloc.Graph.Main (
13 import qualified GraphColor as Color
14 import RegAlloc.Liveness
15 import RegAlloc.Graph.Spill
16 import RegAlloc.Graph.SpillClean
17 import RegAlloc.Graph.SpillCost
18 import RegAlloc.Graph.Stats
19 import RegAlloc.Graph.TrivColorable
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.
48 :: (Outputable instr, Instruction instr)
50 -> UniqFM (UniqSet Reg) -- ^ the registers we can use for allocation
51 -> UniqSet Int -- ^ the set of available spill slots.
52 -> [LiveCmmTop instr] -- ^ code annotated with liveness information.
53 -> UniqSM ( [NatCmmTop instr], [RegAllocStats instr] )
54 -- ^ code with registers allocated and stats for each stage of
57 regAlloc dflags regsFree slotsFree code
59 -- TODO: the regClass function is currently hard coded to the default target
60 -- architecture. Would prefer to determine this from dflags.
61 -- There are other uses of targetRegClass later in this module.
62 let triv = trivColorable targetRegClass
64 (code_final, debug_codeGraphs, _)
65 <- regAlloc_spin dflags 0
67 regsFree slotsFree [] code
70 , reverse debug_codeGraphs )
72 regAlloc_spin dflags spinCount triv regsFree slotsFree debug_codeGraphs code
74 -- if any of these dump flags are turned on we want to hang on to
75 -- intermediate structures in the allocator - otherwise tell the
76 -- allocator to ditch them early so we don't end up creating space leaks.
78 [ dopt Opt_D_dump_asm_regalloc_stages dflags
79 , dopt Opt_D_dump_asm_stats dflags
80 , dopt Opt_D_dump_asm_conflicts dflags ]
82 -- check that we're not running off down the garden path.
83 when (spinCount > maxSpinCount)
84 $ pprPanic "regAlloc_spin: max build/spill cycle count exceeded."
85 ( text "It looks like the register allocator is stuck in an infinite loop."
86 $$ text "max cycles = " <> int maxSpinCount
87 $$ text "regsFree = " <> (hcat $ punctuate space $ map ppr
88 $ uniqSetToList $ unionManyUniqSets $ eltsUFM regsFree)
89 $$ text "slotsFree = " <> ppr (sizeUniqSet slotsFree))
91 -- build a conflict graph from the code.
92 graph <- {-# SCC "BuildGraph" #-} buildGraph code
95 -- We really do want the graph to be fully evaluated _before_ we start coloring.
96 -- If we don't do this now then when the call to Color.colorGraph forces bits of it,
97 -- the heap will be filled with half evaluated pieces of graph and zillions of apply thunks.
99 seqGraph graph `seq` return ()
102 -- build a map of the cost of spilling each instruction
103 -- this will only actually be computed if we have to spill something.
104 let spillCosts = foldl' plusSpillCostInfo zeroSpillCostInfo
105 $ map slurpSpillCostInfo code
107 -- the function to choose regs to leave uncolored
108 let spill = chooseSpill spillCosts
110 -- record startup state
113 then Just $ RegAllocStatsStart
116 , raSpillCosts = spillCosts }
119 -- try and color the graph
120 let (graph_colored, rsSpill, rmCoalesce)
121 = {-# SCC "ColorGraph" #-}
123 (dopt Opt_RegsIterative dflags)
125 regsFree triv spill graph
127 -- rewrite regs in the code that have been coalesced
128 let patchF reg = case lookupUFM rmCoalesce reg of
129 Just reg' -> patchF reg'
132 = map (patchEraseLive patchF) code
135 -- see if we've found a coloring
136 if isEmptyUniqSet rsSpill
138 -- if -fasm-lint is turned on then validate the graph
139 let graph_colored_lint =
140 if dopt Opt_DoAsmLinting dflags
141 then Color.validateGraph (text "")
142 True -- require all nodes to be colored
146 -- patch the registers using the info in the graph
147 let code_patched = map (patchRegsFromGraph graph_colored_lint) code_coalesced
149 -- clean out unneeded SPILL/RELOADs
150 let code_spillclean = map cleanSpills code_patched
152 -- strip off liveness information,
153 -- and rewrite SPILL/RELOAD pseudos into real instructions along the way
154 let code_final = map stripLive code_spillclean
156 -- let spillNatTop = mapGenBlockTop spillNatBlock
157 -- let code_final = map spillNatTop code_nat
159 -- record what happened in this stage for debugging
163 , raGraphColored = graph_colored_lint
164 , raCoalesced = rmCoalesce
165 , raPatched = code_patched
166 , raSpillClean = code_spillclean
167 , raFinal = code_final
168 , raSRMs = foldl' addSRM (0, 0, 0) $ map countSRMs code_spillclean }
172 if dump then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
175 -- space leak avoidance
176 seqList statList `seq` return ()
180 , graph_colored_lint)
182 -- we couldn't find a coloring, time to spill something
184 -- if -fasm-lint is turned on then validate the graph
185 let graph_colored_lint =
186 if dopt Opt_DoAsmLinting dflags
187 then Color.validateGraph (text "")
188 False -- don't require nodes to be colored
192 -- spill the uncolored regs
193 (code_spilled, slotsFree', spillStats)
194 <- regSpill code_coalesced slotsFree rsSpill
196 -- recalculate liveness
197 let code_nat = map stripLive code_spilled
198 code_relive <- mapM regLiveness code_nat
200 -- record what happened in this stage for debugging
203 { raGraph = graph_colored_lint
204 , raCoalesced = rmCoalesce
205 , raSpillStats = spillStats
206 , raSpillCosts = spillCosts
207 , raSpilled = code_spilled }
211 then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
214 -- space leak avoidance
215 seqList statList `seq` return ()
217 regAlloc_spin dflags (spinCount + 1) triv regsFree slotsFree'
223 -- | Build a graph from the liveness and coalesce information in this code.
227 => [LiveCmmTop instr]
228 -> UniqSM (Color.Graph Reg RegClass Reg)
232 -- Slurp out the conflicts and reg->reg moves from this code
233 let (conflictList, moveList) =
234 unzip $ map slurpConflicts code
236 -- Slurp out the spill/reload coalesces
237 let moveList2 = map slurpReloadCoalesce code
239 -- Add the reg-reg conflicts to the graph
240 let conflictBag = unionManyBags conflictList
241 let graph_conflict = foldrBag graphAddConflictSet Color.initGraph conflictBag
243 -- Add the coalescences edges to the graph.
244 let moveBag = unionBags (unionManyBags moveList2) (unionManyBags moveList)
245 let graph_coalesce = foldrBag graphAddCoalesce graph_conflict moveBag
247 return graph_coalesce
250 -- | Add some conflict edges to the graph.
251 -- Conflicts between virtual and real regs are recorded as exclusions.
255 -> Color.Graph Reg RegClass Reg
256 -> Color.Graph Reg RegClass Reg
258 graphAddConflictSet set graph
259 = let reals = filterUFM isRealReg set
260 virtuals = filterUFM (not . isRealReg) set
262 graph1 = Color.addConflicts virtuals targetRegClass graph
263 graph2 = foldr (\(r1, r2) -> Color.addExclusion r1 targetRegClass r2)
266 | a <- uniqSetToList virtuals
267 , b <- uniqSetToList reals]
272 -- | Add some coalesence edges to the graph
273 -- Coalesences between virtual and real regs are recorded as preferences.
277 -> Color.Graph Reg RegClass Reg
278 -> Color.Graph Reg RegClass Reg
280 graphAddCoalesce (r1, r2) graph
282 = Color.addPreference (regWithClass r2) r1 graph
285 = Color.addPreference (regWithClass r1) r2 graph
288 = Color.addCoalesce (regWithClass r1) (regWithClass r2) graph
290 where regWithClass r = (r, targetRegClass r)
293 -- | Patch registers in code using the reg -> reg mapping in this graph.
295 :: (Outputable instr, Instruction instr)
296 => Color.Graph Reg RegClass Reg
297 -> LiveCmmTop instr -> LiveCmmTop instr
299 patchRegsFromGraph graph code
301 -- a function to lookup the hardreg for a virtual reg from the graph.
303 -- leave real regs alone.
307 -- this virtual has a regular node in the graph.
308 | Just node <- Color.lookupNode graph reg
309 = case Color.nodeColor node of
313 -- no node in the graph for this virtual, bad news.
315 = pprPanic "patchRegsFromGraph: register mapping failed."
316 ( text "There is no node in the graph for register " <> ppr reg
318 $$ Color.dotGraph (\_ -> text "white") (trivColorable targetRegClass) graph)
320 in patchEraseLive patchF code
324 -- for when laziness just isn't what you wanted...
326 seqGraph :: Color.Graph Reg RegClass Reg -> ()
327 seqGraph graph = seqNodes (eltsUFM (Color.graphMap graph))
329 seqNodes :: [Color.Node Reg RegClass Reg] -> ()
333 (n : ns) -> seqNode n `seq` seqNodes ns
335 seqNode :: Color.Node Reg RegClass Reg -> ()
337 = seqReg (Color.nodeId node)
338 `seq` seqRegClass (Color.nodeClass node)
339 `seq` seqMaybeReg (Color.nodeColor node)
340 `seq` (seqRegList (uniqSetToList (Color.nodeConflicts node)))
341 `seq` (seqRegList (uniqSetToList (Color.nodeExclusions node)))
342 `seq` (seqRegList (Color.nodePreference node))
343 `seq` (seqRegList (uniqSetToList (Color.nodeCoalesce node)))
354 seqRegClass :: RegClass -> ()
361 seqMaybeReg :: Maybe Reg -> ()
367 seqRegList :: [Reg] -> ()
371 (r : rs) -> seqReg r `seq` seqRegList rs
377 (r : rs) -> r `seq` seqList rs