1 -----------------------------------------------------------------------------
3 -- The register liveness determinator
5 -- (c) The University of Glasgow 2004
7 -----------------------------------------------------------------------------
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/WorkingConventions#Warnings
19 BlockMap, emptyBlockMap,
26 mapBlockTop, mapBlockTopM,
27 mapGenBlockTop, mapGenBlockTopM,
39 #include "HsVersions.h"
59 -----------------------------------------------------------------------------
60 type RegSet = UniqSet Reg
62 type RegMap a = UniqFM a
63 emptyRegMap = emptyUFM
65 type BlockMap a = UniqFM a
66 emptyBlockMap = emptyUFM
69 -- | A top level thing which carries liveness information.
74 (GenBasicBlock LiveInstr)
75 -- the "instructions" here are actually more blocks,
76 -- single blocks are acyclic
77 -- multiple blocks are taken to be cyclic.
79 -- | An instruction with liveness information.
81 = Instr Instr (Maybe Liveness)
83 -- | Liveness information.
84 -- The regs which die are ones which are no longer live in the *next* instruction
86 -- (NB. if the instruction is a jump, these registers might still be live
87 -- at the jump target(s) - you have to check the liveness at the destination
88 -- block to find out).
92 { liveBorn :: RegSet -- ^ registers born in this instruction (written to for first time).
93 , liveDieRead :: RegSet -- ^ registers that died because they were read for the last time.
94 , liveDieWrite :: RegSet } -- ^ registers that died because they were clobbered by something.
97 -- | Stash regs live on entry to each basic block in the info part of the cmm code.
100 [CmmStatic] -- cmm static stuff
101 (Maybe BlockId) -- id of the first block
102 (BlockMap RegSet) -- argument locals live on entry to this block
104 -- | A basic block with liveness information.
106 = GenBasicBlock LiveInstr
109 instance Outputable LiveInstr where
110 ppr (Instr instr Nothing)
113 ppr (Instr instr (Just live))
117 [ pprRegs (ptext SLIT("# born: ")) (liveBorn live)
118 , pprRegs (ptext SLIT("# r_dying: ")) (liveDieRead live)
119 , pprRegs (ptext SLIT("# w_dying: ")) (liveDieWrite live) ]
122 where pprRegs :: SDoc -> RegSet -> SDoc
124 | isEmptyUniqSet regs = empty
125 | otherwise = name <> (hcat $ punctuate space $ map (docToSDoc . pprUserReg) $ uniqSetToList regs)
128 instance Outputable LiveInfo where
129 ppr (LiveInfo static firstId liveOnEntry)
130 = (vcat $ map ppr static)
131 $$ text "# firstId = " <> ppr firstId
132 $$ text "# liveOnEntry = " <> ppr liveOnEntry
135 -- | map a function across all the basic blocks in this code
138 :: (LiveBasicBlock -> LiveBasicBlock)
139 -> LiveCmmTop -> LiveCmmTop
142 = evalState (mapBlockTopM (\x -> return $ f x) cmm) ()
145 -- | map a function across all the basic blocks in this code (monadic version)
149 => (LiveBasicBlock -> m LiveBasicBlock)
150 -> LiveCmmTop -> m LiveCmmTop
152 mapBlockTopM f cmm@(CmmData{})
155 mapBlockTopM f (CmmProc header label params comps)
156 = do comps' <- mapM (mapBlockCompM f) comps
157 return $ CmmProc header label params comps'
159 mapBlockCompM f (BasicBlock i blocks)
160 = do blocks' <- mapM f blocks
161 return $ BasicBlock i blocks'
164 -- map a function across all the basic blocks in this code
166 :: (GenBasicBlock i -> GenBasicBlock i)
167 -> (GenCmmTop d h i -> GenCmmTop d h i)
170 = evalState (mapGenBlockTopM (\x -> return $ f x) cmm) ()
173 -- | map a function across all the basic blocks in this code (monadic version)
176 => (GenBasicBlock i -> m (GenBasicBlock i))
177 -> (GenCmmTop d h i -> m (GenCmmTop d h i))
179 mapGenBlockTopM f cmm@(CmmData{})
182 mapGenBlockTopM f (CmmProc header label params blocks)
183 = do blocks' <- mapM f blocks
184 return $ CmmProc header label params blocks'
187 -- | Slurp out the list of register conflicts and reg-reg moves from this top level thing.
188 -- Slurping of conflicts and moves is wrapped up together so we don't have
189 -- to make two passes over the same code when we want to build the graph.
191 slurpConflicts :: LiveCmmTop -> (Bag (UniqSet Reg), Bag (Reg, Reg))
193 = slurpCmm (emptyBag, emptyBag) live
195 where slurpCmm rs CmmData{} = rs
196 slurpCmm rs (CmmProc info _ _ blocks)
197 = foldl' (slurpComp info) rs blocks
199 slurpComp info rs (BasicBlock i blocks)
200 = foldl' (slurpBlock info) rs blocks
202 slurpBlock info rs (BasicBlock blockId instrs)
203 | LiveInfo _ _ blockLive <- info
204 , Just rsLiveEntry <- lookupUFM blockLive blockId
205 , (conflicts, moves) <- slurpLIs rsLiveEntry rs instrs
206 = (consBag rsLiveEntry conflicts, moves)
209 = error "RegLiveness.slurpBlock: bad block"
211 slurpLIs rsLive (conflicts, moves) []
212 = (consBag rsLive conflicts, moves)
214 slurpLIs rsLive rs (Instr _ Nothing : lis) = slurpLIs rsLive rs lis
216 slurpLIs rsLiveEntry (conflicts, moves) (li@(Instr instr (Just live)) : lis)
218 -- regs that die because they are read for the last time at the start of an instruction
219 -- are not live across it.
220 rsLiveAcross = rsLiveEntry `minusUniqSet` (liveDieRead live)
222 -- regs live on entry to the next instruction.
223 -- be careful of orphans, make sure to delete dying regs _after_ unioning
224 -- in the ones that are born here.
225 rsLiveNext = (rsLiveAcross `unionUniqSets` (liveBorn live))
226 `minusUniqSet` (liveDieWrite live)
228 -- orphan vregs are the ones that die in the same instruction they are born in.
229 -- these are likely to be results that are never used, but we still
230 -- need to assign a hreg to them..
231 rsOrphans = intersectUniqSets
233 (unionUniqSets (liveDieWrite live) (liveDieRead live))
236 rsConflicts = unionUniqSets rsLiveNext rsOrphans
238 in case isRegRegMove instr of
239 Just rr -> slurpLIs rsLiveNext
240 ( consBag rsConflicts conflicts
241 , consBag rr moves) lis
243 Nothing -> slurpLIs rsLiveNext
244 ( consBag rsConflicts conflicts
248 -- | Strip away liveness information, yielding NatCmmTop
250 stripLive :: LiveCmmTop -> NatCmmTop
254 where stripCmm (CmmData sec ds) = CmmData sec ds
255 stripCmm (CmmProc (LiveInfo info _ _) label params comps)
256 = CmmProc info label params (concatMap stripComp comps)
258 stripComp (BasicBlock i blocks) = map stripBlock blocks
259 stripBlock (BasicBlock i instrs) = BasicBlock i (map stripLI instrs)
260 stripLI (Instr instr _) = instr
263 -- | Make real spill instructions out of SPILL, RELOAD pseudos
265 spillNatBlock :: NatBasicBlock -> NatBasicBlock
266 spillNatBlock (BasicBlock i is)
267 = BasicBlock i instrs'
269 = runState (spillNat [] is) 0
272 = return (reverse acc)
274 spillNat acc (instr@(DELTA i) : instrs)
278 spillNat acc (SPILL reg slot : instrs)
280 spillNat (mkSpillInstr reg delta slot : acc) instrs
282 spillNat acc (RELOAD slot reg : instrs)
284 spillNat (mkLoadInstr reg delta slot : acc) instrs
286 spillNat acc (instr : instrs)
287 = spillNat (instr : acc) instrs
290 -- | Slurp out a map of how many times each register was live upon entry to an instruction.
294 -> UniqFM (Reg, Int) -- ^ reg -> (reg, count)
297 = countCmm emptyUFM cmm
299 countCmm fm CmmData{} = fm
300 countCmm fm (CmmProc info _ _ blocks)
301 = foldl' (countComp info) fm blocks
303 countComp info fm (BasicBlock i blocks)
304 = foldl' (countBlock info) fm blocks
306 countBlock info fm (BasicBlock blockId instrs)
307 | LiveInfo _ _ blockLive <- info
308 , Just rsLiveEntry <- lookupUFM blockLive blockId
309 = countLIs rsLiveEntry fm instrs
312 = error "RegLiveness.countBlock: bad block"
314 countLIs rsLive fm [] = fm
315 countLIs rsLive fm (Instr _ Nothing : lis) = countLIs rsLive fm lis
317 countLIs rsLiveEntry fm (Instr _ (Just live) : lis)
319 rsLiveAcross = rsLiveEntry `minusUniqSet` (liveDieRead live)
321 rsLiveNext = (rsLiveAcross `unionUniqSets` (liveBorn live))
322 `minusUniqSet` (liveDieWrite live)
324 add r fm = addToUFM_C
325 (\(r1, l1) (_, l2) -> (r1, l1 + l2))
328 fm' = foldUniqSet add fm rsLiveEntry
329 in countLIs rsLiveNext fm' lis
332 -- | Erase Delta instructions.
334 eraseDeltasLive :: LiveCmmTop -> LiveCmmTop
336 = mapBlockTop eraseBlock cmm
338 isDelta (DELTA _) = True
341 eraseBlock (BasicBlock id lis)
343 $ filter (\(Instr i _) -> not $ isDelta i)
347 -- | Patch the registers in this code according to this register mapping.
348 -- also erase reg -> reg moves when the reg is the same.
349 -- also erase reg -> reg moves when the destination dies in this instr.
353 -> LiveCmmTop -> LiveCmmTop
355 patchEraseLive patchF cmm
358 patchCmm cmm@CmmData{} = cmm
360 patchCmm cmm@(CmmProc info label params comps)
361 | LiveInfo static id blockMap <- info
362 = let patchRegSet set = mkUniqSet $ map patchF $ uniqSetToList set
363 blockMap' = mapUFM patchRegSet blockMap
365 info' = LiveInfo static id blockMap'
366 in CmmProc info' label params $ map patchComp comps
368 patchComp (BasicBlock id blocks)
369 = BasicBlock id $ map patchBlock blocks
371 patchBlock (BasicBlock id lis)
372 = BasicBlock id $ patchInstrs lis
375 patchInstrs (li : lis)
377 | Instr i (Just live) <- li'
378 , Just (r1, r2) <- isRegRegMove i
383 = li' : patchInstrs lis
385 where li' = patchRegsLiveInstr patchF li
388 -- source and destination regs are the same
391 -- desination reg is never used
392 | elementOfUniqSet r2 (liveBorn live)
393 , elementOfUniqSet r2 (liveDieRead live) || elementOfUniqSet r2 (liveDieWrite live)
399 -- | Patch registers in this LiveInstr, including the liveness information.
403 -> LiveInstr -> LiveInstr
405 patchRegsLiveInstr patchF li
408 -> Instr (patchRegs instr patchF) Nothing
410 Instr instr (Just live)
412 (patchRegs instr patchF)
414 { -- WARNING: have to go via lists here because patchF changes the uniq in the Reg
415 liveBorn = mkUniqSet $ map patchF $ uniqSetToList $ liveBorn live
416 , liveDieRead = mkUniqSet $ map patchF $ uniqSetToList $ liveDieRead live
417 , liveDieWrite = mkUniqSet $ map patchF $ uniqSetToList $ liveDieWrite live })
420 ---------------------------------------------------------------------------------
421 -- Annotate code with register liveness information
427 regLiveness cmm@(CmmData sec d)
428 = returnUs $ CmmData sec d
430 regLiveness cmm@(CmmProc info lbl params [])
432 (LiveInfo info Nothing emptyUFM)
435 regLiveness cmm@(CmmProc info lbl params blocks@(first:rest))
436 = let first_id = blockId first
437 sccs = sccBlocks blocks
438 (ann_sccs, block_live) = computeLiveness sccs
441 = map (\scc -> case scc of
442 AcyclicSCC b@(BasicBlock l _) -> BasicBlock l [b]
443 CyclicSCC bs@(BasicBlock l _ : _) -> BasicBlock l bs
445 -> panic "RegLiveness.regLiveness: no blocks in scc list")
448 in returnUs $ CmmProc
449 (LiveInfo info (Just first_id) block_live)
450 lbl params liveBlocks
453 sccBlocks :: [NatBasicBlock] -> [SCC NatBasicBlock]
454 sccBlocks blocks = stronglyConnComp graph
456 getOutEdges :: [Instr] -> [BlockId]
457 getOutEdges instrs = foldl' (\a x -> jumpDests x a) [] instrs
459 graph = [ (block, getUnique id, map getUnique (getOutEdges instrs))
460 | block@(BasicBlock id instrs) <- blocks ]
463 -- -----------------------------------------------------------------------------
464 -- Computing liveness
467 :: [SCC NatBasicBlock]
468 -> ([SCC LiveBasicBlock], -- instructions annotated with list of registers
469 -- which are "dead after this instruction".
470 BlockMap RegSet) -- blocks annontated with set of live registers
471 -- on entry to the block.
473 -- NOTE: on entry, the SCCs are in "reverse" order: later blocks may transfer
474 -- control to earlier ones only. The SCCs returned are in the *opposite*
475 -- order, which is exactly what we want for the next pass.
478 = livenessSCCs emptyBlockMap [] sccs
483 -> [SCC LiveBasicBlock] -- accum
484 -> [SCC NatBasicBlock]
485 -> ([SCC LiveBasicBlock], BlockMap RegSet)
487 livenessSCCs blockmap done [] = (done, blockmap)
489 livenessSCCs blockmap done (AcyclicSCC block : sccs)
490 = let (blockmap', block') = livenessBlock blockmap block
491 in livenessSCCs blockmap' (AcyclicSCC block' : done) sccs
493 livenessSCCs blockmap done
494 (CyclicSCC blocks : sccs) =
495 livenessSCCs blockmap' (CyclicSCC blocks':done) sccs
496 where (blockmap', blocks')
497 = iterateUntilUnchanged linearLiveness equalBlockMaps
500 iterateUntilUnchanged
501 :: (a -> b -> (a,c)) -> (a -> a -> Bool)
505 iterateUntilUnchanged f eq a b
508 groupBy (\(a1, _) (a2, _) -> eq a1 a2) $
509 iterate (\(a, _) -> f a b) $
510 (a, error "RegisterAlloc.livenessSCCs")
513 linearLiveness :: BlockMap RegSet -> [NatBasicBlock]
514 -> (BlockMap RegSet, [LiveBasicBlock])
515 linearLiveness = mapAccumL livenessBlock
517 -- probably the least efficient way to compare two
518 -- BlockMaps for equality.
521 where a' = map f $ ufmToList a
522 b' = map f $ ufmToList b
523 f (key,elt) = (key, uniqSetToList elt)
527 -- | Annotate a basic block with register liveness information.
532 -> (BlockMap RegSet, LiveBasicBlock)
534 livenessBlock blockmap block@(BasicBlock block_id instrs)
536 (regsLiveOnEntry, instrs1)
537 = livenessBack emptyUniqSet blockmap [] (reverse instrs)
538 blockmap' = addToUFM blockmap block_id regsLiveOnEntry
540 instrs2 = livenessForward regsLiveOnEntry instrs1
542 output = BasicBlock block_id instrs2
544 in ( blockmap', output)
546 -- | Calculate liveness going forwards,
547 -- filling in when regs are born
550 :: RegSet -- regs live on this instr
551 -> [LiveInstr] -> [LiveInstr]
553 livenessForward rsLiveEntry [] = []
554 livenessForward rsLiveEntry (li@(Instr instr mLive) : lis)
556 = li : livenessForward rsLiveEntry lis
559 , RU read written <- regUsage instr
561 -- Regs that are written to but weren't live on entry to this instruction
562 -- are recorded as being born here.
564 $ filter (\r -> not $ elementOfUniqSet r rsLiveEntry) written
566 rsLiveNext = (rsLiveEntry `unionUniqSets` rsBorn)
567 `minusUniqSet` (liveDieRead live)
568 `minusUniqSet` (liveDieWrite live)
570 in Instr instr (Just live { liveBorn = rsBorn })
571 : livenessForward rsLiveNext lis
574 -- | Calculate liveness going backwards,
575 -- filling in when regs die, and what regs are live across each instruction
578 :: RegSet -- regs live on this instr
579 -> BlockMap RegSet -- regs live on entry to other BBs
580 -> [LiveInstr] -- instructions (accum)
581 -> [Instr] -- instructions
582 -> (RegSet, [LiveInstr])
584 livenessBack liveregs blockmap done [] = (liveregs, done)
586 livenessBack liveregs blockmap acc (instr : instrs)
587 = let (liveregs', instr') = liveness1 liveregs blockmap instr
588 in livenessBack liveregs' blockmap (instr' : acc) instrs
590 -- don't bother tagging comments or deltas with liveness
591 liveness1 liveregs blockmap (instr@COMMENT{})
592 = (liveregs, Instr instr Nothing)
594 liveness1 liveregs blockmap (instr@DELTA{})
595 = (liveregs, Instr instr Nothing)
597 liveness1 liveregs blockmap instr
600 = (liveregs1, Instr instr
602 { liveBorn = emptyUniqSet
603 , liveDieRead = mkUniqSet r_dying
604 , liveDieWrite = mkUniqSet w_dying }))
607 = (liveregs_br, Instr instr
609 { liveBorn = emptyUniqSet
610 , liveDieRead = mkUniqSet r_dying_br
611 , liveDieWrite = mkUniqSet w_dying }))
614 RU read written = regUsage instr
616 -- registers that were written here are dead going backwards.
617 -- registers that were read here are live going backwards.
618 liveregs1 = (liveregs `delListFromUniqSet` written)
619 `addListToUniqSet` read
621 -- registers that are not live beyond this point, are recorded
623 r_dying = [ reg | reg <- read, reg `notElem` written,
624 not (elementOfUniqSet reg liveregs) ]
626 w_dying = [ reg | reg <- written,
627 not (elementOfUniqSet reg liveregs) ]
629 -- union in the live regs from all the jump destinations of this
631 targets = jumpDests instr [] -- where we go from here
632 not_a_branch = null targets
634 targetLiveRegs target
635 = case lookupUFM blockmap target of
637 Nothing -> emptyBlockMap
639 live_from_branch = unionManyUniqSets (map targetLiveRegs targets)
641 liveregs_br = liveregs1 `unionUniqSets` live_from_branch
643 -- registers that are live only in the branch targets should
644 -- be listed as dying here.
645 live_branch_only = live_from_branch `minusUniqSet` liveregs
646 r_dying_br = uniqSetToList (mkUniqSet r_dying `unionUniqSets`