{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}

-----------------------------------------------------------------------------
--
-- The register liveness determinator
--
-- (c) The University of Glasgow 2004-2013
--
-----------------------------------------------------------------------------

module RegAlloc.Liveness (
        RegSet,
        RegMap, emptyRegMap,
        BlockMap, mapEmpty,
        LiveCmmDecl,
        InstrSR   (..),
        LiveInstr (..),
        Liveness (..),
        LiveInfo (..),
        LiveBasicBlock,

        mapBlockTop,    mapBlockTopM,   mapSCCM,
        mapGenBlockTop, mapGenBlockTopM,
        stripLive,
        stripLiveBlock,
        slurpConflicts,
        slurpReloadCoalesce,
        eraseDeltasLive,
        patchEraseLive,
        patchRegsLiveInstr,
        reverseBlocksInTops,
        regLiveness,
        cmmTopLiveness
  ) where
import GhcPrelude

import Reg
import Instruction

import BlockId
import CFG
import Hoopl.Collections
import Hoopl.Label
import Cmm hiding (RegSet, emptyRegSet)
import PprCmm()

import Digraph
import DynFlags
import MonadUtils
import Outputable
import Platform
import UniqSet
import UniqFM
import UniqSupply
import Bag
import State

import Data.List
import Data.Maybe
import Data.IntSet              (IntSet)

-----------------------------------------------------------------------------
type RegSet = UniqSet Reg

type RegMap a = UniqFM a

emptyRegMap :: UniqFM a
emptyRegMap = emptyUFM

emptyRegSet :: RegSet
emptyRegSet = emptyUniqSet

type BlockMap a = LabelMap a

-- | A top level thing which carries liveness information.
type LiveCmmDecl statics instr
        = GenCmmDecl
                statics
                LiveInfo
                [SCC (LiveBasicBlock instr)]

-- | The register allocator also wants to use SPILL/RELOAD meta instructions,
--   so we'll keep those here.
data InstrSR instr
        -- | A real machine instruction
        = Instr  instr

        -- | spill this reg to a stack slot
        | SPILL  Reg Int

        -- | reload this reg from a stack slot
        | RELOAD Int Reg

instance Instruction instr => Instruction (InstrSR instr) where
        regUsageOfInstr platform i
         = case i of
                Instr  instr    -> regUsageOfInstr platform instr
                SPILL  reg _    -> RU [reg] []
                RELOAD _ reg    -> RU [] [reg]

        patchRegsOfInstr i f
         = case i of
                Instr instr     -> Instr (patchRegsOfInstr instr f)
                SPILL  reg slot -> SPILL (f reg) slot
                RELOAD slot reg -> RELOAD slot (f reg)

        isJumpishInstr i
         = case i of
                Instr instr     -> isJumpishInstr instr
                _               -> False

        jumpDestsOfInstr i
         = case i of
                Instr instr     -> jumpDestsOfInstr instr
                _               -> []

        patchJumpInstr i f
         = case i of
                Instr instr     -> Instr (patchJumpInstr instr f)
                _               -> i

        mkSpillInstr            = error "mkSpillInstr[InstrSR]: Not making SPILL meta-instr"
        mkLoadInstr             = error "mkLoadInstr[InstrSR]: Not making LOAD meta-instr"

        takeDeltaInstr i
         = case i of
                Instr instr     -> takeDeltaInstr instr
                _               -> Nothing

        isMetaInstr i
         = case i of
                Instr instr     -> isMetaInstr instr
                _               -> False

        mkRegRegMoveInstr platform r1 r2
            = Instr (mkRegRegMoveInstr platform r1 r2)

        takeRegRegMoveInstr i
         = case i of
                Instr instr     -> takeRegRegMoveInstr instr
                _               -> Nothing

        mkJumpInstr target      = map Instr (mkJumpInstr target)

        mkStackAllocInstr platform amount =
             Instr <$> mkStackAllocInstr platform amount

        mkStackDeallocInstr platform amount =
             Instr <$> mkStackDeallocInstr platform amount

-- | An instruction with liveness information.
data LiveInstr instr
        = LiveInstr (InstrSR instr) (Maybe Liveness)

-- | Liveness information.
--   The regs which die are ones which are no longer live in the *next* instruction
--   in this sequence.
--   (NB. if the instruction is a jump, these registers might still be live
--   at the jump target(s) - you have to check the liveness at the destination
--   block to find out).

data Liveness
        = Liveness
        { liveBorn      :: RegSet       -- ^ registers born in this instruction (written to for first time).
        , liveDieRead   :: RegSet       -- ^ registers that died because they were read for the last time.
        , liveDieWrite  :: RegSet }     -- ^ registers that died because they were clobbered by something.

-- | Stash regs live on entry to each basic block in the info part of the cmm code.
data LiveInfo
        = LiveInfo
                (LabelMap CmmStatics)     -- cmm info table static stuff
                [BlockId]                 -- entry points (first one is the
                                          -- entry point for the proc).
                (BlockMap RegSet)         -- argument locals live on entry to this block
                (BlockMap IntSet)         -- stack slots live on entry to this block

-- | A basic block with liveness information.
type LiveBasicBlock instr
        = GenBasicBlock (LiveInstr instr)

instance Outputable instr
      => Outputable (InstrSR instr) where

        ppr (Instr realInstr)
           = ppr realInstr

        ppr (SPILL reg slot)
           = hcat [
                text "\tSPILL",
                char ' ',
                ppr reg,
                comma,
                text "SLOT" <> parens (int slot)]

        ppr (RELOAD slot reg)
           = hcat [
                text "\tRELOAD",
                char ' ',
                text "SLOT" <> parens (int slot),
                comma,
                ppr reg]

instance Outputable instr
      => Outputable (LiveInstr instr) where

        ppr (LiveInstr instr Nothing)
         = ppr instr

        ppr (LiveInstr instr (Just live))
         =  ppr instr
                $$ (nest 8
                        $ vcat
                        [ pprRegs (text "# born:    ") (liveBorn live)
                        , pprRegs (text "# r_dying: ") (liveDieRead live)
                        , pprRegs (text "# w_dying: ") (liveDieWrite live) ]
                    $+$ space)

         where  pprRegs :: SDoc -> RegSet -> SDoc
                pprRegs name regs
                 | isEmptyUniqSet regs  = empty
                 | otherwise            = name <>
                     (pprUFM (getUniqSet regs) (hcat . punctuate space . map ppr))

instance Outputable LiveInfo where
    ppr (LiveInfo mb_static entryIds liveVRegsOnEntry liveSlotsOnEntry)
        =  (ppr mb_static)
        $$ text "# entryIds         = " <> ppr entryIds
        $$ text "# liveVRegsOnEntry = " <> ppr liveVRegsOnEntry
        $$ text "# liveSlotsOnEntry = " <> text (show liveSlotsOnEntry)

-- | map a function across all the basic blocks in this code
--
mapBlockTop
        :: (LiveBasicBlock instr -> LiveBasicBlock instr)
        -> LiveCmmDecl statics instr -> LiveCmmDecl statics instr

mapBlockTop f cmm
        = evalState (mapBlockTopM (\x -> return $ f x) cmm) ()

-- | map a function across all the basic blocks in this code (monadic version)
--
mapBlockTopM
        :: Monad m
        => (LiveBasicBlock instr -> m (LiveBasicBlock instr))
        -> LiveCmmDecl statics instr -> m (LiveCmmDecl statics instr)

mapBlockTopM _ cmm@(CmmData{})
        = return cmm

mapBlockTopM f (CmmProc header label live sccs)
 = do   sccs'   <- mapM (mapSCCM f) sccs
        return  $ CmmProc header label live sccs'

mapSCCM :: Monad m => (a -> m b) -> SCC a -> m (SCC b)
mapSCCM f (AcyclicSCC x)
 = do   x'      <- f x
        return  $ AcyclicSCC x'

mapSCCM f (CyclicSCC xs)
 = do   xs'     <- mapM f xs
        return  $ CyclicSCC xs'

-- map a function across all the basic blocks in this code
mapGenBlockTop
        :: (GenBasicBlock             i -> GenBasicBlock            i)
        -> (GenCmmDecl d h (ListGraph i) -> GenCmmDecl d h (ListGraph i))

mapGenBlockTop f cmm
        = evalState (mapGenBlockTopM (\x -> return $ f x) cmm) ()

-- | map a function across all the basic blocks in this code (monadic version)
mapGenBlockTopM
        :: Monad m
        => (GenBasicBlock            i  -> m (GenBasicBlock            i))
        -> (GenCmmDecl d h (ListGraph i) -> m (GenCmmDecl d h (ListGraph i)))

mapGenBlockTopM _ cmm@(CmmData{})
        = return cmm

mapGenBlockTopM f (CmmProc header label live (ListGraph blocks))
 = do   blocks' <- mapM f blocks
        return  $ CmmProc header label live (ListGraph blocks')

-- | Slurp out the list of register conflicts and reg-reg moves from this top level thing.
--   Slurping of conflicts and moves is wrapped up together so we don't have
--   to make two passes over the same code when we want to build the graph.
--
slurpConflicts
        :: Instruction instr
        => LiveCmmDecl statics instr
        -> (Bag (UniqSet Reg), Bag (Reg, Reg))

slurpConflicts live
        = slurpCmm (emptyBag, emptyBag) live

 where  slurpCmm   rs  CmmData{}                = rs
        slurpCmm   rs (CmmProc info _ _ sccs)
                = foldl' (slurpSCC info) rs sccs

        slurpSCC  info rs (AcyclicSCC b)
                = slurpBlock info rs b

        slurpSCC  info rs (CyclicSCC bs)
                = foldl'  (slurpBlock info) rs bs

        slurpBlock info rs (BasicBlock blockId instrs)
                | LiveInfo _ _ blockLive _        <- info
                , Just rsLiveEntry                <- mapLookup blockId blockLive
                , (conflicts, moves)              <- slurpLIs rsLiveEntry rs instrs
                = (consBag rsLiveEntry conflicts, moves)

                | otherwise
                = panic "Liveness.slurpConflicts: bad block"

        slurpLIs rsLive (conflicts, moves) []
                = (consBag rsLive conflicts, moves)

        slurpLIs rsLive rs (LiveInstr _ Nothing     : lis)
                = slurpLIs rsLive rs lis

        slurpLIs rsLiveEntry (conflicts, moves) (LiveInstr instr (Just live) : lis)
         = let
                -- regs that die because they are read for the last time at the start of an instruction
                --      are not live across it.
                rsLiveAcross    = rsLiveEntry `minusUniqSet` (liveDieRead live)

                -- regs live on entry to the next instruction.
                --      be careful of orphans, make sure to delete dying regs _after_ unioning
                --      in the ones that are born here.
                rsLiveNext      = (rsLiveAcross `unionUniqSets` (liveBorn     live))
                                                `minusUniqSet`  (liveDieWrite live)

                -- orphan vregs are the ones that die in the same instruction they are born in.
                --      these are likely to be results that are never used, but we still
                --      need to assign a hreg to them..
                rsOrphans       = intersectUniqSets
                                        (liveBorn live)
                                        (unionUniqSets (liveDieWrite live) (liveDieRead live))

                --
                rsConflicts     = unionUniqSets rsLiveNext rsOrphans

          in    case takeRegRegMoveInstr instr of
                 Just rr        -> slurpLIs rsLiveNext
                                        ( consBag rsConflicts conflicts
                                        , consBag rr moves) lis

                 Nothing        -> slurpLIs rsLiveNext
                                        ( consBag rsConflicts conflicts
                                        , moves) lis

-- | For spill\/reloads
--
--   SPILL  v1, slot1
--   ...
--   RELOAD slot1, v2
--
--   If we can arrange that v1 and v2 are allocated to the same hreg it's more likely
--   the spill\/reload instrs can be cleaned and replaced by a nop reg-reg move.
--
--
slurpReloadCoalesce
        :: forall statics instr. Instruction instr
        => LiveCmmDecl statics instr
        -> Bag (Reg, Reg)

slurpReloadCoalesce live
        = slurpCmm emptyBag live

 where
        slurpCmm :: Bag (Reg, Reg)
                 -> GenCmmDecl t t1 [SCC (LiveBasicBlock instr)]
                 -> Bag (Reg, Reg)
        slurpCmm cs CmmData{}   = cs
        slurpCmm cs (CmmProc _ _ _ sccs)
                = slurpComp cs (flattenSCCs sccs)

        slurpComp :: Bag (Reg, Reg)
                     -> [LiveBasicBlock instr]
                     -> Bag (Reg, Reg)
        slurpComp  cs blocks
         = let  (moveBags, _)   = runState (slurpCompM blocks) emptyUFM
           in   unionManyBags (cs : moveBags)

        slurpCompM :: [LiveBasicBlock instr]
                   -> State (UniqFM [UniqFM Reg]) [Bag (Reg, Reg)]
        slurpCompM blocks
         = do   -- run the analysis once to record the mapping across jumps.
                mapM_   (slurpBlock False) blocks

                -- run it a second time while using the information from the last pass.
                --      We /could/ run this many more times to deal with graphical control
                --      flow and propagating info across multiple jumps, but it's probably
                --      not worth the trouble.
                mapM    (slurpBlock True) blocks

        slurpBlock :: Bool -> LiveBasicBlock instr
                   -> State (UniqFM [UniqFM Reg]) (Bag (Reg, Reg))
        slurpBlock propagate (BasicBlock blockId instrs)
         = do   -- grab the slot map for entry to this block
                slotMap         <- if propagate
                                        then getSlotMap blockId
                                        else return emptyUFM

                (_, mMoves)     <- mapAccumLM slurpLI slotMap instrs
                return $ listToBag $ catMaybes mMoves

        slurpLI :: UniqFM Reg                           -- current slotMap
                -> LiveInstr instr
                -> State (UniqFM [UniqFM Reg])          -- blockId -> [slot -> reg]
                                                        --      for tracking slotMaps across jumps

                         ( UniqFM Reg                   -- new slotMap
                         , Maybe (Reg, Reg))            -- maybe a new coalesce edge

        slurpLI slotMap li

                -- remember what reg was stored into the slot
                | LiveInstr (SPILL reg slot) _  <- li
                , slotMap'                      <- addToUFM slotMap slot reg
                = return (slotMap', Nothing)

                -- add an edge between the this reg and the last one stored into the slot
                | LiveInstr (RELOAD slot reg) _ <- li
                = case lookupUFM slotMap slot of
                        Just reg2
                         | reg /= reg2  -> return (slotMap, Just (reg, reg2))
                         | otherwise    -> return (slotMap, Nothing)

                        Nothing         -> return (slotMap, Nothing)

                -- if we hit a jump, remember the current slotMap
                | LiveInstr (Instr instr) _     <- li
                , targets                       <- jumpDestsOfInstr instr
                , not $ null targets
                = do    mapM_   (accSlotMap slotMap) targets
                        return  (slotMap, Nothing)

                | otherwise
                = return (slotMap, Nothing)

        -- record a slotmap for an in edge to this block
        accSlotMap slotMap blockId
                = modify (\s -> addToUFM_C (++) s blockId [slotMap])

        -- work out the slot map on entry to this block
        --      if we have slot maps for multiple in-edges then we need to merge them.
        getSlotMap blockId
         = do   map             <- get
                let slotMaps    = fromMaybe [] (lookupUFM map blockId)
                return          $ foldr mergeSlotMaps emptyUFM slotMaps

        mergeSlotMaps :: UniqFM Reg -> UniqFM Reg -> UniqFM Reg
        mergeSlotMaps map1 map2
                = listToUFM
                $ [ (k, r1)
                  | (k, r1) <- nonDetUFMToList map1
                  -- This is non-deterministic but we do not
                  -- currently support deterministic code-generation.
                  -- See Note [Unique Determinism and code generation]
                  , case lookupUFM map2 k of
                          Nothing -> False
                          Just r2 -> r1 == r2 ]

-- | Strip away liveness information, yielding NatCmmDecl
stripLive
        :: (Outputable statics, Outputable instr, Instruction instr)
        => DynFlags
        -> LiveCmmDecl statics instr
        -> NatCmmDecl statics instr

stripLive dflags live
        = stripCmm live

 where  stripCmm :: (Outputable statics, Outputable instr, Instruction instr)
                 => LiveCmmDecl statics instr -> NatCmmDecl statics instr
        stripCmm (CmmData sec ds)       = CmmData sec ds
        stripCmm (CmmProc (LiveInfo info (first_id:_) _ _) label live sccs)
         = let  final_blocks    = flattenSCCs sccs

                -- make sure the block that was first in the input list
                --      stays at the front of the output. This is the entry point
                --      of the proc, and it needs to come first.
                ((first':_), rest')
                                = partition ((== first_id) . blockId) final_blocks

           in   CmmProc info label live
                          (ListGraph $ map (stripLiveBlock dflags) $ first' : rest')

        -- If the proc has blocks but we don't know what the first one was, then we're dead.
        stripCmm proc
                 = pprPanic "RegAlloc.Liveness.stripLive: no first_id on proc" (ppr proc)

-- | Strip away liveness information from a basic block,
--   and make real spill instructions out of SPILL, RELOAD pseudos along the way.

stripLiveBlock
        :: Instruction instr
        => DynFlags
        -> LiveBasicBlock instr
        -> NatBasicBlock instr

stripLiveBlock dflags (BasicBlock i lis)
 =      BasicBlock i instrs'

 where  (instrs', _)
                = runState (spillNat [] lis) 0

        spillNat acc []
         =      return (reverse acc)

        spillNat acc (LiveInstr (SPILL reg slot) _ : instrs)
         = do   delta   <- get
                spillNat (mkSpillInstr dflags reg delta slot : acc) instrs

        spillNat acc (LiveInstr (RELOAD slot reg) _ : instrs)
         = do   delta   <- get
                spillNat (mkLoadInstr dflags reg delta slot : acc) instrs

        spillNat acc (LiveInstr (Instr instr) _ : instrs)
         | Just i <- takeDeltaInstr instr
         = do   put i
                spillNat acc instrs

        spillNat acc (LiveInstr (Instr instr) _ : instrs)
         =      spillNat (instr : acc) instrs

-- | Erase Delta instructions.

eraseDeltasLive
        :: Instruction instr
        => LiveCmmDecl statics instr
        -> LiveCmmDecl statics instr

eraseDeltasLive cmm
        = mapBlockTop eraseBlock cmm
 where
        eraseBlock (BasicBlock id lis)
                = BasicBlock id
                $ filter (\(LiveInstr i _) -> not $ isJust $ takeDeltaInstr i)
                $ lis

-- | Patch the registers in this code according to this register mapping.
--   also erase reg -> reg moves when the reg is the same.
--   also erase reg -> reg moves when the destination dies in this instr.
patchEraseLive
        :: Instruction instr
        => (Reg -> Reg)
        -> LiveCmmDecl statics instr -> LiveCmmDecl statics instr

patchEraseLive patchF cmm
        = patchCmm cmm
 where
        patchCmm cmm@CmmData{}  = cmm

        patchCmm (CmmProc info label live sccs)
         | LiveInfo static id blockMap mLiveSlots <- info
         = let
                patchRegSet set = mkUniqSet $ map patchF $ nonDetEltsUFM set
                  -- See Note [Unique Determinism and code generation]
                blockMap'       = mapMap (patchRegSet . getUniqSet) blockMap

                info'           = LiveInfo static id blockMap' mLiveSlots
           in   CmmProc info' label live $ map patchSCC sccs

        patchSCC (AcyclicSCC b)  = AcyclicSCC (patchBlock b)
        patchSCC (CyclicSCC  bs) = CyclicSCC  (map patchBlock bs)

        patchBlock (BasicBlock id lis)
                = BasicBlock id $ patchInstrs lis

        patchInstrs []          = []
        patchInstrs (li : lis)

                | LiveInstr i (Just live)       <- li'
                , Just (r1, r2) <- takeRegRegMoveInstr i
                , eatMe r1 r2 live
                = patchInstrs lis

                | otherwise
                = li' : patchInstrs lis

                where   li'     = patchRegsLiveInstr patchF li

        eatMe   r1 r2 live
                -- source and destination regs are the same
                | r1 == r2      = True

                -- destination reg is never used
                | elementOfUniqSet r2 (liveBorn live)
                , elementOfUniqSet r2 (liveDieRead live) || elementOfUniqSet r2 (liveDieWrite live)
                = True

                | otherwise     = False

-- | Patch registers in this LiveInstr, including the liveness information.
--
patchRegsLiveInstr
        :: Instruction instr
        => (Reg -> Reg)
        -> LiveInstr instr -> LiveInstr instr

patchRegsLiveInstr patchF li
 = case li of
        LiveInstr instr Nothing
         -> LiveInstr (patchRegsOfInstr instr patchF) Nothing

        LiveInstr instr (Just live)
         -> LiveInstr
                (patchRegsOfInstr instr patchF)
                (Just live
                        { -- WARNING: have to go via lists here because patchF changes the uniq in the Reg
                          liveBorn      = mapUniqSet patchF $ liveBorn live
                        , liveDieRead   = mapUniqSet patchF $ liveDieRead live
                        , liveDieWrite  = mapUniqSet patchF $ liveDieWrite live })
                          -- See Note [Unique Determinism and code generation]

--------------------------------------------------------------------------------
-- | Convert a NatCmmDecl to a LiveCmmDecl, with liveness information

cmmTopLiveness
        :: (Outputable instr, Instruction instr)
        => Maybe CFG -> Platform
        -> NatCmmDecl statics instr
        -> UniqSM (LiveCmmDecl statics instr)
cmmTopLiveness cfg platform cmm
        = regLiveness platform $ natCmmTopToLive cfg cmm

natCmmTopToLive
        :: (Instruction instr, Outputable instr)
        => Maybe CFG -> NatCmmDecl statics instr
        -> LiveCmmDecl statics instr

natCmmTopToLive _ (CmmData i d)
        = CmmData i d

natCmmTopToLive _ (CmmProc info lbl live (ListGraph []))
        = CmmProc (LiveInfo info [] mapEmpty mapEmpty) lbl live []

natCmmTopToLive mCfg proc@(CmmProc info lbl live (ListGraph blocks@(first : _)))
        = CmmProc (LiveInfo info' (first_id : entry_ids) mapEmpty mapEmpty)
                lbl live sccsLive
   where
        first_id        = blockId first
        all_entry_ids   = entryBlocks proc
        sccs            = sccBlocks blocks all_entry_ids mCfg
        sccsLive        = map (fmap (\(BasicBlock l instrs) ->
                                       BasicBlock l (map (\i -> LiveInstr (Instr i) Nothing) instrs)))
                        $ sccs

        entry_ids       = filter (reachable_node) .
                          filter (/= first_id) $ all_entry_ids
        info'           = mapFilterWithKey (\node _ -> reachable_node node) info
        reachable_node
          | Just cfg <- mCfg
          = hasNode cfg
          | otherwise
          = const True

--
-- Compute the liveness graph of the set of basic blocks.  Important:
-- we also discard any unreachable code here, starting from the entry
-- points (the first block in the list, and any blocks with info
-- tables).  Unreachable code arises when code blocks are orphaned in
-- earlier optimisation passes, and may confuse the register allocator
-- by referring to registers that are not initialised.  It's easy to
-- discard the unreachable code as part of the SCC pass, so that's
-- exactly what we do. (#7574)
--
sccBlocks
        :: forall instr . Instruction instr
        => [NatBasicBlock instr]
        -> [BlockId]
        -> Maybe CFG
        -> [SCC (NatBasicBlock instr)]

sccBlocks blocks entries mcfg = map (fmap node_payload) sccs
  where
        nodes :: [ Node BlockId (NatBasicBlock instr) ]
        nodes = [ DigraphNode block id (getOutEdges instrs)
                | block@(BasicBlock id instrs) <- blocks ]

        g1 = graphFromEdgedVerticesUniq nodes

        reachable :: LabelSet
        reachable
            | Just cfg <- mcfg
            -- Our CFG only contains reachable nodes by construction.
            = getCfgNodes cfg
            | otherwise
            = setFromList $ [ node_key node | node <- reachablesG g1 roots ]

        g2 = graphFromEdgedVerticesUniq [ node | node <- nodes
                                               , node_key node
                                                  `setMember` reachable ]

        sccs = stronglyConnCompG g2

        getOutEdges :: Instruction instr => [instr] -> [BlockId]
        getOutEdges instrs = concat $ map jumpDestsOfInstr instrs

        -- This is truly ugly, but I don't see a good alternative.
        -- Digraph just has the wrong API.  We want to identify nodes
        -- by their keys (BlockId), but Digraph requires the whole
        -- node: (NatBasicBlock, BlockId, [BlockId]).  This takes
        -- advantage of the fact that Digraph only looks at the key,
        -- even though it asks for the whole triple.
        roots = [DigraphNode (panic "sccBlocks") b (panic "sccBlocks")
                | b <- entries ]

--------------------------------------------------------------------------------
-- Annotate code with register liveness information
--

regLiveness
        :: (Outputable instr, Instruction instr)
        => Platform
        -> LiveCmmDecl statics instr
        -> UniqSM (LiveCmmDecl statics instr)

regLiveness _ (CmmData i d)
        = return $ CmmData i d

regLiveness _ (CmmProc info lbl live [])
        | LiveInfo static mFirst _ _    <- info
        = return $ CmmProc
                        (LiveInfo static mFirst mapEmpty mapEmpty)
                        lbl live []

regLiveness platform (CmmProc info lbl live sccs)
        | LiveInfo static mFirst _ liveSlotsOnEntry     <- info
        = let   (ann_sccs, block_live)  = computeLiveness platform sccs

          in    return $ CmmProc (LiveInfo static mFirst block_live liveSlotsOnEntry)
                           lbl live ann_sccs

-- -----------------------------------------------------------------------------
-- | Check ordering of Blocks
--   The computeLiveness function requires SCCs to be in reverse
--   dependent order.  If they're not the liveness information will be
--   wrong, and we'll get a bad allocation.  Better to check for this
--   precondition explicitly or some other poor sucker will waste a
--   day staring at bad assembly code..
--
checkIsReverseDependent
        :: Instruction instr
        => [SCC (LiveBasicBlock instr)]         -- ^ SCCs of blocks that we're about to run the liveness determinator on.
        -> Maybe BlockId                        -- ^ BlockIds that fail the test (if any)

checkIsReverseDependent sccs'
 = go emptyUniqSet sccs'

 where  go _ []
         = Nothing

        go blocksSeen (AcyclicSCC block : sccs)
         = let  dests           = slurpJumpDestsOfBlock block
                blocksSeen'     = unionUniqSets blocksSeen $ mkUniqSet [blockId block]
                badDests        = dests `minusUniqSet` blocksSeen'
           in   case nonDetEltsUniqSet badDests of
                 -- See Note [Unique Determinism and code generation]
                 []             -> go blocksSeen' sccs
                 bad : _        -> Just bad

        go blocksSeen (CyclicSCC blocks : sccs)
         = let  dests           = unionManyUniqSets $ map slurpJumpDestsOfBlock blocks
                blocksSeen'     = unionUniqSets blocksSeen $ mkUniqSet $ map blockId blocks
                badDests        = dests `minusUniqSet` blocksSeen'
           in   case nonDetEltsUniqSet badDests of
                 -- See Note [Unique Determinism and code generation]
                 []             -> go blocksSeen' sccs
                 bad : _        -> Just bad

        slurpJumpDestsOfBlock (BasicBlock _ instrs)
                = unionManyUniqSets
                $ map (mkUniqSet . jumpDestsOfInstr)
                        [ i | LiveInstr i _ <- instrs]

-- | If we've compute liveness info for this code already we have to reverse
--   the SCCs in each top to get them back to the right order so we can do it again.
reverseBlocksInTops :: LiveCmmDecl statics instr -> LiveCmmDecl statics instr
reverseBlocksInTops top
 = case top of
        CmmData{}                       -> top
        CmmProc info lbl live sccs      -> CmmProc info lbl live (reverse sccs)

-- | Computing liveness
--
--  On entry, the SCCs must be in "reverse" order: later blocks may transfer
--  control to earlier ones only, else `panic`.
--
--  The SCCs returned are in the *opposite* order, which is exactly what we
--  want for the next pass.
--
computeLiveness
        :: (Outputable instr, Instruction instr)
        => Platform
        -> [SCC (LiveBasicBlock instr)]
        -> ([SCC (LiveBasicBlock instr)],       -- instructions annotated with list of registers
                                                -- which are "dead after this instruction".
               BlockMap RegSet)                 -- blocks annotated with set of live registers
                                                -- on entry to the block.

computeLiveness platform sccs
 = case checkIsReverseDependent sccs of
        Nothing         -> livenessSCCs platform mapEmpty [] sccs
        Just bad        -> pprPanic "RegAlloc.Liveness.computeLiveness"
                                (vcat   [ text "SCCs aren't in reverse dependent order"
                                        , text "bad blockId" <+> ppr bad
                                        , ppr sccs])

livenessSCCs
       :: Instruction instr
       => Platform
       -> BlockMap RegSet
       -> [SCC (LiveBasicBlock instr)]          -- accum
       -> [SCC (LiveBasicBlock instr)]
       -> ( [SCC (LiveBasicBlock instr)]
          , BlockMap RegSet)

livenessSCCs _ blockmap done []
        = (done, blockmap)

livenessSCCs platform blockmap done (AcyclicSCC block : sccs)
 = let  (blockmap', block')     = livenessBlock platform blockmap block
   in   livenessSCCs platform blockmap' (AcyclicSCC block' : done) sccs

livenessSCCs platform blockmap done
        (CyclicSCC blocks : sccs) =
        livenessSCCs platform blockmap' (CyclicSCC blocks':done) sccs
 where      (blockmap', blocks')
                = iterateUntilUnchanged linearLiveness equalBlockMaps
                                      blockmap blocks

            iterateUntilUnchanged
                :: (a -> b -> (a,c)) -> (a -> a -> Bool)
                -> a -> b
                -> (a,c)

            iterateUntilUnchanged f eq a b
                = head $
                  concatMap tail $
                  groupBy (\(a1, _) (a2, _) -> eq a1 a2) $
                  iterate (\(a, _) -> f a b) $
                  (a, panic "RegLiveness.livenessSCCs")

            linearLiveness
                :: Instruction instr
                => BlockMap RegSet -> [LiveBasicBlock instr]
                -> (BlockMap RegSet, [LiveBasicBlock instr])

            linearLiveness = mapAccumL (livenessBlock platform)

                -- probably the least efficient way to compare two
                -- BlockMaps for equality.
            equalBlockMaps a b
                = a' == b'
              where a' = map f $ mapToList a
                    b' = map f $ mapToList b
                    f (key,elt) = (key, nonDetEltsUniqSet elt)
                    -- See Note [Unique Determinism and code generation]

-- | Annotate a basic block with register liveness information.
--
livenessBlock
        :: Instruction instr
        => Platform
        -> BlockMap RegSet
        -> LiveBasicBlock instr
        -> (BlockMap RegSet, LiveBasicBlock instr)

livenessBlock platform blockmap (BasicBlock block_id instrs)
 = let
        (regsLiveOnEntry, instrs1)
            = livenessBack platform emptyUniqSet blockmap [] (reverse instrs)
        blockmap'       = mapInsert block_id regsLiveOnEntry blockmap

        instrs2         = livenessForward platform regsLiveOnEntry instrs1

        output          = BasicBlock block_id instrs2

   in   ( blockmap', output)

-- | Calculate liveness going forwards,
--   filling in when regs are born

livenessForward
        :: Instruction instr
        => Platform
        -> RegSet                       -- regs live on this instr
        -> [LiveInstr instr] -> [LiveInstr instr]

livenessForward _        _           []  = []
livenessForward platform rsLiveEntry (li@(LiveInstr instr mLive) : lis)
        | Just live <- mLive
        = let
                RU _ written  = regUsageOfInstr platform instr
                -- Regs that are written to but weren't live on entry to this instruction
                --      are recorded as being born here.
                rsBorn          = mkUniqSet
                                $ filter (\r -> not $ elementOfUniqSet r rsLiveEntry) written

                rsLiveNext      = (rsLiveEntry `unionUniqSets` rsBorn)
                                        `minusUniqSet` (liveDieRead live)
                                        `minusUniqSet` (liveDieWrite live)

        in LiveInstr instr (Just live { liveBorn = rsBorn })
                : livenessForward platform rsLiveNext lis

        | otherwise
        = li : livenessForward platform rsLiveEntry lis

-- | Calculate liveness going backwards,
--   filling in when regs die, and what regs are live across each instruction

livenessBack
        :: Instruction instr
        => Platform
        -> RegSet                       -- regs live on this instr
        -> BlockMap RegSet              -- regs live on entry to other BBs
        -> [LiveInstr instr]            -- instructions (accum)
        -> [LiveInstr instr]            -- instructions
        -> (RegSet, [LiveInstr instr])

livenessBack _        liveregs _        done []  = (liveregs, done)

livenessBack platform liveregs blockmap acc (instr : instrs)
 = let  (liveregs', instr')     = liveness1 platform liveregs blockmap instr
   in   livenessBack platform liveregs' blockmap (instr' : acc) instrs

-- don't bother tagging comments or deltas with liveness
liveness1
        :: Instruction instr
        => Platform
        -> RegSet
        -> BlockMap RegSet
        -> LiveInstr instr
        -> (RegSet, LiveInstr instr)

liveness1 _ liveregs _ (LiveInstr instr _)
        | isMetaInstr instr
        = (liveregs, LiveInstr instr Nothing)

liveness1 platform liveregs blockmap (LiveInstr instr _)

        | not_a_branch
        = (liveregs1, LiveInstr instr
                        (Just $ Liveness
                        { liveBorn      = emptyUniqSet
                        , liveDieRead   = mkUniqSet r_dying
                        , liveDieWrite  = mkUniqSet w_dying }))

        | otherwise
        = (liveregs_br, LiveInstr instr
                        (Just $ Liveness
                        { liveBorn      = emptyUniqSet
                        , liveDieRead   = mkUniqSet r_dying_br
                        , liveDieWrite  = mkUniqSet w_dying }))

        where
            !(RU read written) = regUsageOfInstr platform instr

            -- registers that were written here are dead going backwards.
            -- registers that were read here are live going backwards.
            liveregs1   = (liveregs `delListFromUniqSet` written)
                                    `addListToUniqSet` read

            -- registers that are not live beyond this point, are recorded
            --  as dying here.
            r_dying     = [ reg | reg <- read, reg `notElem` written,
                              not (elementOfUniqSet reg liveregs) ]

            w_dying     = [ reg | reg <- written,
                             not (elementOfUniqSet reg liveregs) ]

            -- union in the live regs from all the jump destinations of this
            -- instruction.
            targets      = jumpDestsOfInstr instr -- where we go from here
            not_a_branch = null targets

            targetLiveRegs target
                  = case mapLookup target blockmap of
                                Just ra -> ra
                                Nothing -> emptyRegSet

            live_from_branch = unionManyUniqSets (map targetLiveRegs targets)

            liveregs_br = liveregs1 `unionUniqSets` live_from_branch

            -- registers that are live only in the branch targets should
            -- be listed as dying here.
            live_branch_only = live_from_branch `minusUniqSet` liveregs
            r_dying_br  = nonDetEltsUniqSet (mkUniqSet r_dying `unionUniqSets`
                                             live_branch_only)
                          -- See Note [Unique Determinism and code generation]


-- | Utils for calculating general worst, bound, squeese and free, functions.
--
--   as per: "A Generalized Algorithm for Graph-Coloring Register Allocation"
--           Michael Smith, Normal Ramsey, Glenn Holloway.
--           PLDI 2004
--
--   These general versions are not used in GHC proper because they are too slow.
--   Instead, hand written optimised versions are provided for each architecture
--   in MachRegs*.hs
--
--   This code is here because we can test the architecture specific code against
--   it.
--
module RegAlloc.Graph.ArchBase (
        RegClass(..),
        Reg(..),
        RegSub(..),

        worst,
        bound,
        squeese
) where
import GhcPrelude

import UniqSet
import UniqFM
import Unique

-- Some basic register classes.
--      These aren't necessarily in 1-to-1 correspondence with the allocatable
--      RegClasses in MachRegs.hs
data RegClass
        -- general purpose regs
        = ClassG32      -- 32 bit GPRs
        | ClassG16      -- 16 bit GPRs
        | ClassG8       -- 8  bit GPRs

        -- floating point regs
        | ClassF64      -- 64 bit FPRs
        deriving (Show, Eq, Enum)

-- | A register of some class
data Reg
        -- a register of some class
        = Reg RegClass Int

        -- a sub-component of one of the other regs
        | RegSub RegSub Reg
        deriving (Show, Eq)

-- | so we can put regs in UniqSets
instance Uniquable Reg where
        getUnique (Reg c i)
         = mkRegSingleUnique
         $ fromEnum c * 1000 + i

        getUnique (RegSub s (Reg c i))
         = mkRegSubUnique
         $ fromEnum s * 10000 + fromEnum c * 1000 + i

        getUnique (RegSub _ (RegSub _ _))
          = error "RegArchBase.getUnique: can't have a sub-reg of a sub-reg."

-- | A subcomponent of another register
data RegSub
        = SubL16        -- lowest 16 bits
        | SubL8         -- lowest  8 bits
        | SubL8H        -- second lowest 8 bits
        deriving (Show, Enum, Ord, Eq)

-- | Worst case displacement
--
--      a node N of classN has some number of neighbors,
--      all of which are from classC.
--
--      (worst neighbors classN classC) is the maximum number of potential
--      colors for N that can be lost by coloring its neighbors.
--
-- This should be hand coded/cached for each particular architecture,
--      because the compute time is very long..
worst   :: (RegClass    -> UniqSet Reg)
        -> (Reg         -> UniqSet Reg)
        -> Int -> RegClass -> RegClass -> Int

worst regsOfClass regAlias neighbors classN classC
 = let  regAliasS regs  = unionManyUniqSets
                        $ map regAlias
                        $ nonDetEltsUniqSet regs
                        -- This is non-deterministic but we do not
                        -- currently support deterministic code-generation.
                        -- See Note [Unique Determinism and code generation]

        -- all the regs in classes N, C
        regsN           = regsOfClass classN
        regsC           = regsOfClass classC

        -- all the possible subsets of c which have size < m
        regsS           = filter (\s -> sizeUniqSet s >= 1
                                     && sizeUniqSet s <= neighbors)
                        $ powersetLS regsC

        -- for each of the subsets of C, the regs which conflict
        -- with posiblities for N
        regsS_conflict
                = map (\s -> intersectUniqSets regsN (regAliasS s)) regsS

  in    maximum $ map sizeUniqSet $ regsS_conflict

-- | For a node N of classN and neighbors of classesC
--      (bound classN classesC) is the maximum number of potential
--      colors for N that can be lost by coloring its neighbors.
bound   :: (RegClass    -> UniqSet Reg)
        -> (Reg         -> UniqSet Reg)
        -> RegClass -> [RegClass] -> Int

bound regsOfClass regAlias classN classesC
 = let  regAliasS regs  = unionManyUniqSets
                        $ map regAlias
                        $ nonDetEltsUFM regs
                        -- See Note [Unique Determinism and code generation]

        regsC_aliases
                = unionManyUniqSets
                $ map (regAliasS . getUniqSet . regsOfClass) classesC

        overlap = intersectUniqSets (regsOfClass classN) regsC_aliases

   in   sizeUniqSet overlap

-- | The total squeese on a particular node with a list of neighbors.
--
--   A version of this should be constructed for each particular architecture,
--   possibly including uses of bound, so that alised registers don't get
--   counted twice, as per the paper.
squeese :: (RegClass    -> UniqSet Reg)
        -> (Reg         -> UniqSet Reg)
        -> RegClass -> [(Int, RegClass)] -> Int

squeese regsOfClass regAlias classN countCs
        = sum
        $ map (\(i, classC) -> worst regsOfClass regAlias i classN classC)
        $ countCs

-- | powerset (for lists)
powersetL :: [a] -> [[a]]
powersetL       = map concat . mapM (\x -> [[],[x]])

-- | powersetLS (list of sets)
powersetLS :: Uniquable a => UniqSet a -> [UniqSet a]
powersetLS s    = map mkUniqSet $ powersetL $ nonDetEltsUniqSet s
  -- See Note [Unique Determinism and code generation]


-- | A description of the register set of the X86.
--
--   This isn't used directly in GHC proper.
--
--   See RegArchBase.hs for the reference.
--   See MachRegs.hs for the actual trivColorable function used in GHC.
--
module RegAlloc.Graph.ArchX86 (
        classOfReg,
        regsOfClass,
        regName,
        regAlias,
        worst,
        squeese,
) where

import GhcPrelude

import RegAlloc.Graph.ArchBase  (Reg(..), RegSub(..), RegClass(..))
import UniqSet

import qualified Data.Array as A

-- | Determine the class of a register
classOfReg :: Reg -> RegClass
classOfReg reg
 = case reg of
        Reg c _         -> c

        RegSub SubL16 _ -> ClassG16
        RegSub SubL8  _ -> ClassG8
        RegSub SubL8H _ -> ClassG8

-- | Determine all the regs that make up a certain class.
regsOfClass :: RegClass -> UniqSet Reg
regsOfClass c
 = case c of
        ClassG32
         -> mkUniqSet   [ Reg ClassG32  i
                        | i <- [0..7] ]

        ClassG16
         -> mkUniqSet   [ RegSub SubL16 (Reg ClassG32 i)
                        | i <- [0..7] ]

        ClassG8
         -> unionUniqSets
                (mkUniqSet [ RegSub SubL8  (Reg ClassG32 i) | i <- [0..3] ])
                (mkUniqSet [ RegSub SubL8H (Reg ClassG32 i) | i <- [0..3] ])

        ClassF64
         -> mkUniqSet   [ Reg ClassF64  i
                        | i <- [0..5] ]

-- | Determine the common name of a reg
--      returns Nothing if this reg is not part of the machine.
regName :: Reg -> Maybe String
regName reg
 = case reg of
        Reg ClassG32 i
         | i <= 7 ->
           let names = A.listArray (0,8)
                       [ "eax", "ebx", "ecx", "edx"
                       , "ebp", "esi", "edi", "esp" ]
           in Just $ names A.! i

        RegSub SubL16 (Reg ClassG32 i)
         | i <= 7 ->
           let names = A.listArray (0,8)
                       [ "ax", "bx", "cx", "dx"
                       , "bp", "si", "di", "sp"]
           in Just $ names A.! i

        RegSub SubL8  (Reg ClassG32 i)
         | i <= 3 ->
           let names = A.listArray (0,4) [ "al", "bl", "cl", "dl"]
           in Just $ names A.! i

        RegSub SubL8H (Reg ClassG32 i)
         | i <= 3 ->
           let names = A.listArray (0,4) [ "ah", "bh", "ch", "dh"]
           in Just $ names A.! i

        _         -> Nothing

-- | Which regs alias what other regs.
regAlias :: Reg -> UniqSet Reg
regAlias reg
 = case reg of

        -- 32 bit regs alias all of the subregs
        Reg ClassG32 i

         -- for eax, ebx, ecx, eds
         |  i <= 3
         -> mkUniqSet
         $ [ Reg ClassG32 i,   RegSub SubL16 reg
           , RegSub SubL8 reg, RegSub SubL8H reg ]

         -- for esi, edi, esp, ebp
         | 4 <= i && i <= 7
         -> mkUniqSet
         $ [ Reg ClassG32 i,   RegSub SubL16 reg ]

        -- 16 bit subregs alias the whole reg
        RegSub SubL16 r@(Reg ClassG32 _)
         ->     regAlias r

        -- 8 bit subregs alias the 32 and 16, but not the other 8 bit subreg
        RegSub SubL8  r@(Reg ClassG32 _)
         -> mkUniqSet $ [ r, RegSub SubL16 r, RegSub SubL8 r ]

        RegSub SubL8H r@(Reg ClassG32 _)
         -> mkUniqSet $ [ r, RegSub SubL16 r, RegSub SubL8H r ]

        -- fp
        Reg ClassF64 _
         -> unitUniqSet reg

        _ -> error "regAlias: invalid register"

-- | Optimised versions of RegColorBase.{worst, squeese} specific to x86
worst :: Int -> RegClass -> RegClass -> Int
worst n classN classC
 = case classN of
        ClassG32
         -> case classC of
                ClassG32        -> min n 8
                ClassG16        -> min n 8
                ClassG8         -> min n 4
                ClassF64        -> 0

        ClassG16
         -> case classC of
                ClassG32        -> min n 8
                ClassG16        -> min n 8
                ClassG8         -> min n 4
                ClassF64        -> 0

        ClassG8
         -> case classC of
                ClassG32        -> min (n*2) 8
                ClassG16        -> min (n*2) 8
                ClassG8         -> min n 8
                ClassF64        -> 0

        ClassF64
         -> case classC of
                ClassF64        -> min n 6
                _               -> 0

squeese :: RegClass -> [(Int, RegClass)] -> Int
squeese classN countCs
        = sum (map (\(i, classC) -> worst i classN classC) countCs)


-- | Register coalescing.
module RegAlloc.Graph.Coalesce (
        regCoalesce,
        slurpJoinMovs
) where
import GhcPrelude

import RegAlloc.Liveness
import Instruction
import Reg

import Cmm
import Bag
import Digraph
import UniqFM
import UniqSet
import UniqSupply

-- | Do register coalescing on this top level thing
--
--   For Reg -> Reg moves, if the first reg dies at the same time the
--   second reg is born then the mov only serves to join live ranges.
--   The two regs can be renamed to be the same and the move instruction
--   safely erased.
regCoalesce
        :: Instruction instr
        => [LiveCmmDecl statics instr]
        -> UniqSM [LiveCmmDecl statics instr]

regCoalesce code
 = do
        let joins       = foldl' unionBags emptyBag
                        $ map slurpJoinMovs code

        let alloc       = foldl' buildAlloc emptyUFM
                        $ bagToList joins

        let patched     = map (patchEraseLive (sinkReg alloc)) code

        return patched

-- | Add a v1 = v2 register renaming to the map.
--   The register with the lowest lexical name is set as the
--   canonical version.
buildAlloc :: UniqFM Reg -> (Reg, Reg) -> UniqFM Reg
buildAlloc fm (r1, r2)
 = let  rmin    = min r1 r2
        rmax    = max r1 r2
   in   addToUFM fm rmax rmin

-- | Determine the canonical name for a register by following
--   v1 = v2 renamings in this map.
sinkReg :: UniqFM Reg -> Reg -> Reg
sinkReg fm r
 = case lookupUFM fm r of
        Nothing -> r
        Just r' -> sinkReg fm r'

-- | Slurp out mov instructions that only serve to join live ranges.
--
--   During a mov, if the source reg dies and the destination reg is
--   born then we can rename the two regs to the same thing and
--   eliminate the move.
slurpJoinMovs
        :: Instruction instr
        => LiveCmmDecl statics instr
        -> Bag (Reg, Reg)

slurpJoinMovs live
        = slurpCmm emptyBag live
 where
        slurpCmm   rs  CmmData{}
         = rs

        slurpCmm   rs (CmmProc _ _ _ sccs)
         = foldl' slurpBlock rs (flattenSCCs sccs)

        slurpBlock rs (BasicBlock _ instrs)
         = foldl' slurpLI    rs instrs

        slurpLI    rs (LiveInstr _      Nothing)    = rs
        slurpLI    rs (LiveInstr instr (Just live))
                | Just (r1, r2) <- takeRegRegMoveInstr instr
                , elementOfUniqSet r1 $ liveDieRead live
                , elementOfUniqSet r2 $ liveBorn live

                -- only coalesce movs between two virtuals for now,
                -- else we end up with allocatable regs in the live
                -- regs list..
                , isVirtualReg r1 && isVirtualReg r2
                = consBag (r1, r2) rs

                | otherwise
                = rs


{-# LANGUAGE ScopedTypeVariables #-}

-- | Graph coloring register allocator.
module RegAlloc.Graph.Main (
        regAlloc
) where
import GhcPrelude

import qualified GraphColor as Color
import RegAlloc.Liveness
import RegAlloc.Graph.Spill
import RegAlloc.Graph.SpillClean
import RegAlloc.Graph.SpillCost
import RegAlloc.Graph.Stats
import RegAlloc.Graph.TrivColorable
import Instruction
import TargetReg
import RegClass
import Reg

import Bag
import DynFlags
import Outputable
import Platform
import UniqFM
import UniqSet
import UniqSupply
import Util (seqList)
import CFG

import Data.Maybe
import Control.Monad

-- | The maximum number of build\/spill cycles we'll allow.
--
--   It should only take 3 or 4 cycles for the allocator to converge.
--   If it takes any longer than this it's probably in an infinite loop,
--   so it's better just to bail out and report a bug.
maxSpinCount    :: Int
maxSpinCount    = 10

-- | The top level of the graph coloring register allocator.
regAlloc
        :: (Outputable statics, Outputable instr, Instruction instr)
        => DynFlags
        -> UniqFM (UniqSet RealReg)     -- ^ registers we can use for allocation
        -> UniqSet Int                  -- ^ set of available spill slots.
        -> Int                          -- ^ current number of spill slots
        -> [LiveCmmDecl statics instr]  -- ^ code annotated with liveness information.
        -> Maybe CFG                    -- ^ CFG of basic blocks if available
        -> UniqSM ( [NatCmmDecl statics instr]
                  , Maybe Int, [RegAllocStats statics instr] )
           -- ^ code with registers allocated, additional stacks required
           -- and stats for each stage of allocation

regAlloc dflags regsFree slotsFree slotsCount code cfg
 = do
        -- TODO: the regClass function is currently hard coded to the default
        --       target architecture. Would prefer to determine this from dflags.
        --       There are other uses of targetRegClass later in this module.
        let platform = targetPlatform dflags
            triv = trivColorable platform
                        (targetVirtualRegSqueeze platform)
                        (targetRealRegSqueeze platform)

        (code_final, debug_codeGraphs, slotsCount', _)
                <- regAlloc_spin dflags 0
                        triv
                        regsFree slotsFree slotsCount [] code cfg

        let needStack
                | slotsCount == slotsCount'
                = Nothing
                | otherwise
                = Just slotsCount'

        return  ( code_final
                , needStack
                , reverse debug_codeGraphs )

-- | Perform solver iterations for the graph coloring allocator.
--
--   We extract a register confict graph from the provided cmm code,
--   and try to colour it. If that works then we use the solution rewrite
--   the code with real hregs. If coloring doesn't work we add spill code
--   and try to colour it again. After `maxSpinCount` iterations we give up.
--
regAlloc_spin
        :: forall instr statics.
           (Instruction instr,
            Outputable instr,
            Outputable statics)
        => DynFlags
        -> Int  -- ^ Number of solver iterations we've already performed.
        -> Color.Triv VirtualReg RegClass RealReg
                -- ^ Function for calculating whether a register is trivially
                --   colourable.
        -> UniqFM (UniqSet RealReg)      -- ^ Free registers that we can allocate.
        -> UniqSet Int                   -- ^ Free stack slots that we can use.
        -> Int                           -- ^ Number of spill slots in use
        -> [RegAllocStats statics instr] -- ^ Current regalloc stats to add to.
        -> [LiveCmmDecl statics instr]   -- ^ Liveness annotated code to allocate.
        -> Maybe CFG
        -> UniqSM ( [NatCmmDecl statics instr]
                  , [RegAllocStats statics instr]
                  , Int                  -- Slots in use
                  , Color.Graph VirtualReg RegClass RealReg)

regAlloc_spin dflags spinCount triv regsFree slotsFree slotsCount debug_codeGraphs code cfg
 = do
        let platform = targetPlatform dflags

        -- If any of these dump flags are turned on we want to hang on to
        -- intermediate structures in the allocator - otherwise tell the
        -- allocator to ditch them early so we don't end up creating space leaks.
        let dump = or
                [ dopt Opt_D_dump_asm_regalloc_stages dflags
                , dopt Opt_D_dump_asm_stats dflags
                , dopt Opt_D_dump_asm_conflicts dflags ]

        -- Check that we're not running off down the garden path.
        when (spinCount > maxSpinCount)
         $ pprPanic "regAlloc_spin: max build/spill cycle count exceeded."
           (  text "It looks like the register allocator is stuck in an infinite loop."
           $$ text "max cycles  = " <> int maxSpinCount
           $$ text "regsFree    = " <> (hcat $ punctuate space $ map ppr
                                             $ nonDetEltsUniqSet $ unionManyUniqSets
                                             $ nonDetEltsUFM regsFree)
              -- This is non-deterministic but we do not
              -- currently support deterministic code-generation.
              -- See Note [Unique Determinism and code generation]
           $$ text "slotsFree   = " <> ppr (sizeUniqSet slotsFree))

        -- Build the register conflict graph from the cmm code.
        (graph  :: Color.Graph VirtualReg RegClass RealReg)
                <- {-# SCC "BuildGraph" #-} buildGraph code

        -- VERY IMPORTANT:
        --   We really do want the graph to be fully evaluated _before_ we
        --   start coloring. If we don't do this now then when the call to
        --   Color.colorGraph forces bits of it, the heap will be filled with
        --   half evaluated pieces of graph and zillions of apply thunks.
        seqGraph graph `seq` return ()

        -- Build a map of the cost of spilling each instruction.
        -- This is a lazy binding, so the map will only be computed if we
        -- actually have to spill to the stack.
        let spillCosts  = foldl' plusSpillCostInfo zeroSpillCostInfo
                        $ map (slurpSpillCostInfo platform cfg) code

        -- The function to choose regs to leave uncolored.
        let spill       = chooseSpill spillCosts

        -- Record startup state in our log.
        let stat1
             = if spinCount == 0
                 then   Just $ RegAllocStatsStart
                        { raLiveCmm     = code
                        , raGraph       = graph
                        , raSpillCosts  = spillCosts }
                 else   Nothing

        -- Try and color the graph.
        let (graph_colored, rsSpill, rmCoalesce)
                = {-# SCC "ColorGraph" #-}
                  Color.colorGraph
                       (gopt Opt_RegsIterative dflags)
                       spinCount
                       regsFree triv spill graph

        -- Rewrite registers in the code that have been coalesced.
        let patchF reg
                | RegVirtual vr <- reg
                = case lookupUFM rmCoalesce vr of
                        Just vr'        -> patchF (RegVirtual vr')
                        Nothing         -> reg

                | otherwise
                = reg

        let (code_coalesced :: [LiveCmmDecl statics instr])
                = map (patchEraseLive patchF) code

        -- Check whether we've found a coloring.
        if isEmptyUniqSet rsSpill

         -- Coloring was successful because no registers needed to be spilled.
         then do
                -- if -fasm-lint is turned on then validate the graph.
                -- This checks for bugs in the graph allocator itself.
                let graph_colored_lint  =
                        if gopt Opt_DoAsmLinting dflags
                                then Color.validateGraph (text "")
                                        True    -- Require all nodes to be colored.
                                        graph_colored
                                else graph_colored

                -- Rewrite the code to use real hregs, using the colored graph.
                let code_patched
                        = map (patchRegsFromGraph platform graph_colored_lint)
                              code_coalesced

                -- Clean out unneeded SPILL/RELOAD meta instructions.
                --   The spill code generator just spills the entire live range
                --   of a vreg, but it might not need to be on the stack for
                --   its entire lifetime.
                let code_spillclean
                        = map (cleanSpills platform) code_patched

                -- Strip off liveness information from the allocated code.
                -- Also rewrite SPILL/RELOAD meta instructions into real machine
                -- instructions along the way
                let code_final
                        = map (stripLive dflags) code_spillclean

                -- Record what happened in this stage for debugging
                let stat
                     =  RegAllocStatsColored
                        { raCode                = code
                        , raGraph               = graph
                        , raGraphColored        = graph_colored_lint
                        , raCoalesced           = rmCoalesce
                        , raCodeCoalesced       = code_coalesced
                        , raPatched             = code_patched
                        , raSpillClean          = code_spillclean
                        , raFinal               = code_final
                        , raSRMs                = foldl' addSRM (0, 0, 0)
                                                $ map countSRMs code_spillclean }

                -- Bundle up all the register allocator statistics.
                --   .. but make sure to drop them on the floor if they're not
                --      needed, otherwise we'll get a space leak.
                let statList =
                        if dump then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
                                else []

                -- Ensure all the statistics are evaluated, to avoid space leaks.
                seqList statList (return ())

                return  ( code_final
                        , statList
                        , slotsCount
                        , graph_colored_lint)

         -- Coloring was unsuccessful. We need to spill some register to the
         -- stack, make a new graph, and try to color it again.
         else do
                -- if -fasm-lint is turned on then validate the graph
                let graph_colored_lint  =
                        if gopt Opt_DoAsmLinting dflags
                                then Color.validateGraph (text "")
                                        False   -- don't require nodes to be colored
                                        graph_colored
                                else graph_colored

                -- Spill uncolored regs to the stack.
                (code_spilled, slotsFree', slotsCount', spillStats)
                        <- regSpill platform code_coalesced slotsFree slotsCount rsSpill

                -- Recalculate liveness information.
                -- NOTE: we have to reverse the SCCs here to get them back into
                --       the reverse-dependency order required by computeLiveness.
                --       If they're not in the correct order that function will panic.
                code_relive     <- mapM (regLiveness platform . reverseBlocksInTops)
                                        code_spilled

                -- Record what happened in this stage for debugging.
                let stat        =
                        RegAllocStatsSpill
                        { raCode        = code
                        , raGraph       = graph_colored_lint
                        , raCoalesced   = rmCoalesce
                        , raSpillStats  = spillStats
                        , raSpillCosts  = spillCosts
                        , raSpilled     = code_spilled }

                -- Bundle up all the register allocator statistics.
                --   .. but make sure to drop them on the floor if they're not
                --      needed, otherwise we'll get a space leak.
                let statList =
                        if dump
                                then [stat] ++ maybeToList stat1 ++ debug_codeGraphs
                                else []

                -- Ensure all the statistics are evaluated, to avoid space leaks.
                seqList statList (return ())

                regAlloc_spin dflags (spinCount + 1) triv regsFree slotsFree'
                              slotsCount' statList code_relive cfg

-- | Build a graph from the liveness and coalesce information in this code.
buildGraph
        :: Instruction instr
        => [LiveCmmDecl statics instr]
        -> UniqSM (Color.Graph VirtualReg RegClass RealReg)

buildGraph code
 = do
        -- Slurp out the conflicts and reg->reg moves from this code.
        let (conflictList, moveList) =
                unzip $ map slurpConflicts code

        -- Slurp out the spill/reload coalesces.
        let moveList2           = map slurpReloadCoalesce code

        -- Add the reg-reg conflicts to the graph.
        let conflictBag         = unionManyBags conflictList
        let graph_conflict
                = foldrBag graphAddConflictSet Color.initGraph conflictBag

        -- Add the coalescences edges to the graph.
        let moveBag
                = unionBags (unionManyBags moveList2)
                            (unionManyBags moveList)

        let graph_coalesce
                = foldrBag graphAddCoalesce graph_conflict moveBag

        return  graph_coalesce

-- | Add some conflict edges to the graph.
--   Conflicts between virtual and real regs are recorded as exclusions.
graphAddConflictSet
        :: UniqSet Reg
        -> Color.Graph VirtualReg RegClass RealReg
        -> Color.Graph VirtualReg RegClass RealReg

graphAddConflictSet set graph
 = let  virtuals        = mkUniqSet
                        [ vr | RegVirtual vr <- nonDetEltsUniqSet set ]

        graph1  = Color.addConflicts virtuals classOfVirtualReg graph

        graph2  = foldr (\(r1, r2) -> Color.addExclusion r1 classOfVirtualReg r2)
                        graph1
                        [ (vr, rr)
                                | RegVirtual vr <- nonDetEltsUniqSet set
                                , RegReal    rr <- nonDetEltsUniqSet set]
                          -- See Note [Unique Determinism and code generation]

   in   graph2

-- | Add some coalesence edges to the graph
--   Coalesences between virtual and real regs are recorded as preferences.
graphAddCoalesce
        :: (Reg, Reg)
        -> Color.Graph VirtualReg RegClass RealReg
        -> Color.Graph VirtualReg RegClass RealReg

graphAddCoalesce (r1, r2) graph
        | RegReal rr            <- r1
        , RegVirtual vr         <- r2
        = Color.addPreference (vr, classOfVirtualReg vr) rr graph

        | RegReal rr            <- r2
        , RegVirtual vr         <- r1
        = Color.addPreference (vr, classOfVirtualReg vr) rr graph

        | RegVirtual vr1        <- r1
        , RegVirtual vr2        <- r2
        = Color.addCoalesce
                (vr1, classOfVirtualReg vr1)
                (vr2, classOfVirtualReg vr2)
                graph

        -- We can't coalesce two real regs, but there could well be existing
        --      hreg,hreg moves in the input code. We'll just ignore these
        --      for coalescing purposes.
        | RegReal _             <- r1
        , RegReal _             <- r2
        = graph

        | otherwise
        = panic "graphAddCoalesce"

-- | Patch registers in code using the reg -> reg mapping in this graph.
patchRegsFromGraph
        :: (Outputable statics, Outputable instr, Instruction instr)
        => Platform -> Color.Graph VirtualReg RegClass RealReg
        -> LiveCmmDecl statics instr -> LiveCmmDecl statics instr

patchRegsFromGraph platform graph code
 = patchEraseLive patchF code
 where
        -- Function to lookup the hardreg for a virtual reg from the graph.
        patchF reg
                -- leave real regs alone.
                | RegReal{}     <- reg
                = reg

                -- this virtual has a regular node in the graph.
                | RegVirtual vr <- reg
                , Just node     <- Color.lookupNode graph vr
                = case Color.nodeColor node of
                        Just color      -> RegReal    color
                        Nothing         -> RegVirtual vr

                -- no node in the graph for this virtual, bad news.
                | otherwise
                = pprPanic "patchRegsFromGraph: register mapping failed."
                        (  text "There is no node in the graph for register "
                                <> ppr reg
                        $$ ppr code
                        $$ Color.dotGraph
                                (\_ -> text "white")
                                (trivColorable platform
                                        (targetVirtualRegSqueeze platform)
                                        (targetRealRegSqueeze platform))
                                graph)

-----
-- for when laziness just isn't what you wanted...
--  We need to deepSeq the whole graph before trying to colour it to avoid
--  space leaks.
seqGraph :: Color.Graph VirtualReg RegClass RealReg -> ()
seqGraph graph          = seqNodes (nonDetEltsUFM (Color.graphMap graph))
   -- See Note [Unique Determinism and code generation]

seqNodes :: [Color.Node VirtualReg RegClass RealReg] -> ()
seqNodes ns
 = case ns of
        []              -> ()
        (n : ns)        -> seqNode n `seq` seqNodes ns

seqNode :: Color.Node VirtualReg RegClass RealReg -> ()
seqNode node
        =     seqVirtualReg     (Color.nodeId node)
        `seq` seqRegClass       (Color.nodeClass node)
        `seq` seqMaybeRealReg   (Color.nodeColor node)
        `seq` (seqVirtualRegList (nonDetEltsUniqSet (Color.nodeConflicts node)))
        `seq` (seqRealRegList    (nonDetEltsUniqSet (Color.nodeExclusions node)))
        `seq` (seqRealRegList (Color.nodePreference node))
        `seq` (seqVirtualRegList (nonDetEltsUniqSet (Color.nodeCoalesce node)))
              -- It's OK to use nonDetEltsUniqSet for seq

seqVirtualReg :: VirtualReg -> ()
seqVirtualReg reg = reg `seq` ()

seqRealReg :: RealReg -> ()
seqRealReg reg = reg `seq` ()

seqRegClass :: RegClass -> ()
seqRegClass c = c `seq` ()

seqMaybeRealReg :: Maybe RealReg -> ()
seqMaybeRealReg mr
 = case mr of
        Nothing         -> ()
        Just r          -> seqRealReg r

seqVirtualRegList :: [VirtualReg] -> ()
seqVirtualRegList rs
 = case rs of
        []              -> ()
        (r : rs)        -> seqVirtualReg r `seq` seqVirtualRegList rs

seqRealRegList :: [RealReg] -> ()
seqRealRegList rs
 = case rs of
        []              -> ()
        (r : rs)        -> seqRealReg r `seq` seqRealRegList rs


-- | When there aren't enough registers to hold all the vregs we have to spill
--   some of those vregs to slots on the stack. This module is used modify the
--   code to use those slots.
module RegAlloc.Graph.Spill (
        regSpill,
        SpillStats(..),
        accSpillSL
) where
import GhcPrelude

import RegAlloc.Liveness
import Instruction
import Reg
import Cmm hiding (RegSet)
import BlockId
import Hoopl.Collections

import MonadUtils
import State
import Unique
import UniqFM
import UniqSet
import UniqSupply
import Outputable
import Platform

import Data.List
import Data.Maybe
import Data.IntSet              (IntSet)
import qualified Data.IntSet    as IntSet

-- | Spill all these virtual regs to stack slots.
--
--   Bumps the number of required stack slots if required.
--
--
--   TODO: See if we can split some of the live ranges instead of just globally
--         spilling the virtual reg. This might make the spill cleaner's job easier.
--
--   TODO: On CISCy x86 and x86_64 we don't necessarily have to add a mov instruction
--         when making spills. If an instr is using a spilled virtual we may be able to
--         address the spill slot directly.
--
regSpill
        :: Instruction instr
        => Platform
        -> [LiveCmmDecl statics instr]  -- ^ the code
        -> UniqSet Int                  -- ^ available stack slots
        -> Int                          -- ^ current number of spill slots.
        -> UniqSet VirtualReg           -- ^ the regs to spill
        -> UniqSM
            ([LiveCmmDecl statics instr]
                 -- code with SPILL and RELOAD meta instructions added.
            , UniqSet Int               -- left over slots
            , Int                       -- slot count in use now.
            , SpillStats )              -- stats about what happened during spilling

regSpill platform code slotsFree slotCount regs

        -- Not enough slots to spill these regs.
        | sizeUniqSet slotsFree < sizeUniqSet regs
        = -- pprTrace "Bumping slot count:" (ppr slotCount <> text " -> " <> ppr (slotCount+512)) $
          let slotsFree' = (addListToUniqSet slotsFree [slotCount+1 .. slotCount+512])
          in regSpill platform code slotsFree' (slotCount+512) regs

        | otherwise
        = do
                -- Allocate a slot for each of the spilled regs.
                let slots       = take (sizeUniqSet regs) $ nonDetEltsUniqSet slotsFree
                let regSlotMap  = listToUFM
                                $ zip (nonDetEltsUniqSet regs) slots
                    -- This is non-deterministic but we do not
                    -- currently support deterministic code-generation.
                    -- See Note [Unique Determinism and code generation]

                -- Grab the unique supply from the monad.
                us      <- getUniqueSupplyM

                -- Run the spiller on all the blocks.
                let (code', state')     =
                        runState (mapM (regSpill_top platform regSlotMap) code)
                                 (initSpillS us)

                return  ( code'
                        , minusUniqSet slotsFree (mkUniqSet slots)
                        , slotCount
                        , makeSpillStats state')

-- | Spill some registers to stack slots in a top-level thing.
regSpill_top
        :: Instruction instr
        => Platform
        -> RegMap Int
                -- ^ map of vregs to slots they're being spilled to.
        -> LiveCmmDecl statics instr
                -- ^ the top level thing.
        -> SpillM (LiveCmmDecl statics instr)

regSpill_top platform regSlotMap cmm
 = case cmm of
        CmmData{}
         -> return cmm

        CmmProc info label live sccs
         |  LiveInfo static firstId liveVRegsOnEntry liveSlotsOnEntry <- info
         -> do
                -- The liveVRegsOnEntry contains the set of vregs that are live
                -- on entry to each basic block. If we spill one of those vregs
                -- we remove it from that set and add the corresponding slot
                -- number to the liveSlotsOnEntry set. The spill cleaner needs
                -- this information to erase unneeded spill and reload instructions
                -- after we've done a successful allocation.
                let liveSlotsOnEntry' :: BlockMap IntSet
                    liveSlotsOnEntry'
                        = mapFoldlWithKey patchLiveSlot
                                          liveSlotsOnEntry liveVRegsOnEntry

                let info'
                        = LiveInfo static firstId
                                liveVRegsOnEntry
                                liveSlotsOnEntry'

                -- Apply the spiller to all the basic blocks in the CmmProc.
                sccs'   <- mapM (mapSCCM (regSpill_block platform regSlotMap)) sccs

                return  $ CmmProc info' label live sccs'

 where  -- Given a BlockId and the set of registers live in it,
        -- if registers in this block are being spilled to stack slots,
        -- then record the fact that these slots are now live in those blocks
        -- in the given slotmap.
        patchLiveSlot
                :: BlockMap IntSet -> BlockId -> RegSet -> BlockMap IntSet

        patchLiveSlot slotMap blockId regsLive
         = let
                -- Slots that are already recorded as being live.
                curSlotsLive    = fromMaybe IntSet.empty
                                $ mapLookup blockId slotMap

                moreSlotsLive   = IntSet.fromList
                                $ catMaybes
                                $ map (lookupUFM regSlotMap)
                                $ nonDetEltsUniqSet regsLive
                    -- See Note [Unique Determinism and code generation]

                slotMap'
                 = mapInsert blockId (IntSet.union curSlotsLive moreSlotsLive)
                             slotMap

           in   slotMap'

-- | Spill some registers to stack slots in a basic block.
regSpill_block
        :: Instruction instr
        => Platform
        -> UniqFM Int   -- ^ map of vregs to slots they're being spilled to.
        -> LiveBasicBlock instr
        -> SpillM (LiveBasicBlock instr)

regSpill_block platform regSlotMap (BasicBlock i instrs)
 = do   instrss'        <- mapM (regSpill_instr platform regSlotMap) instrs
        return  $ BasicBlock i (concat instrss')

-- | Spill some registers to stack slots in a single instruction.
--   If the instruction uses registers that need to be spilled, then it is
--   prefixed (or postfixed) with the appropriate RELOAD or SPILL meta
--   instructions.
regSpill_instr
        :: Instruction instr
        => Platform
        -> UniqFM Int -- ^ map of vregs to slots they're being spilled to.
        -> LiveInstr instr
        -> SpillM [LiveInstr instr]

regSpill_instr _ _ li@(LiveInstr _ Nothing)
 = do   return [li]

regSpill_instr platform regSlotMap
        (LiveInstr instr (Just _))
 = do
        -- work out which regs are read and written in this instr
        let RU rlRead rlWritten = regUsageOfInstr platform instr

        -- sometimes a register is listed as being read more than once,
        --      nub this so we don't end up inserting two lots of spill code.
        let rsRead_             = nub rlRead
        let rsWritten_          = nub rlWritten

        -- if a reg is modified, it appears in both lists, want to undo this..
        let rsRead              = rsRead_    \\ rsWritten_
        let rsWritten           = rsWritten_ \\ rsRead_
        let rsModify            = intersect rsRead_ rsWritten_

        -- work out if any of the regs being used are currently being spilled.
        let rsSpillRead         = filter (\r -> elemUFM r regSlotMap) rsRead
        let rsSpillWritten      = filter (\r -> elemUFM r regSlotMap) rsWritten
        let rsSpillModify       = filter (\r -> elemUFM r regSlotMap) rsModify

        -- rewrite the instr and work out spill code.
        (instr1, prepost1)      <- mapAccumLM (spillRead   regSlotMap) instr  rsSpillRead
        (instr2, prepost2)      <- mapAccumLM (spillWrite  regSlotMap) instr1 rsSpillWritten
        (instr3, prepost3)      <- mapAccumLM (spillModify regSlotMap) instr2 rsSpillModify

        let (mPrefixes, mPostfixes)     = unzip (prepost1 ++ prepost2 ++ prepost3)
        let prefixes                    = concat mPrefixes
        let postfixes                   = concat mPostfixes

        -- final code
        let instrs'     =  prefixes
                        ++ [LiveInstr instr3 Nothing]
                        ++ postfixes

        return $ instrs'

-- | Add a RELOAD met a instruction to load a value for an instruction that
--   writes to a vreg that is being spilled.
spillRead
        :: Instruction instr
        => UniqFM Int
        -> instr
        -> Reg
        -> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))

spillRead regSlotMap instr reg
 | Just slot     <- lookupUFM regSlotMap reg
 = do    (instr', nReg)  <- patchInstr reg instr

         modify $ \s -> s
                { stateSpillSL  = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 0, 1) }

         return  ( instr'
                 , ( [LiveInstr (RELOAD slot nReg) Nothing]
                 , []) )

 | otherwise     = panic "RegSpill.spillRead: no slot defined for spilled reg"

-- | Add a SPILL meta instruction to store a value for an instruction that
--   writes to a vreg that is being spilled.
spillWrite
        :: Instruction instr
        => UniqFM Int
        -> instr
        -> Reg
        -> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))

spillWrite regSlotMap instr reg
 | Just slot     <- lookupUFM regSlotMap reg
 = do    (instr', nReg)  <- patchInstr reg instr

         modify $ \s -> s
                { stateSpillSL  = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 0) }

         return  ( instr'
                 , ( []
                   , [LiveInstr (SPILL nReg slot) Nothing]))

 | otherwise     = panic "RegSpill.spillWrite: no slot defined for spilled reg"

-- | Add both RELOAD and SPILL meta instructions for an instruction that
--   both reads and writes to a vreg that is being spilled.
spillModify
        :: Instruction instr
        => UniqFM Int
        -> instr
        -> Reg
        -> SpillM (instr, ([LiveInstr instr'], [LiveInstr instr']))

spillModify regSlotMap instr reg
 | Just slot     <- lookupUFM regSlotMap reg
 = do    (instr', nReg)  <- patchInstr reg instr

         modify $ \s -> s
                { stateSpillSL  = addToUFM_C accSpillSL (stateSpillSL s) reg (reg, 1, 1) }

         return  ( instr'
                 , ( [LiveInstr (RELOAD slot nReg) Nothing]
                   , [LiveInstr (SPILL nReg slot) Nothing]))

 | otherwise     = panic "RegSpill.spillModify: no slot defined for spilled reg"

-- | Rewrite uses of this virtual reg in an instr to use a different
--   virtual reg.
patchInstr
        :: Instruction instr
        => Reg -> instr -> SpillM (instr, Reg)

patchInstr reg instr
 = do   nUnique         <- newUnique

        -- The register we're rewriting is suppoed to be virtual.
        -- If it's not then something has gone horribly wrong.
        let nReg
             = case reg of
                RegVirtual vr
                 -> RegVirtual (renameVirtualReg nUnique vr)

                RegReal{}
                 -> panic "RegAlloc.Graph.Spill.patchIntr: not patching real reg"

        let instr'      = patchReg1 reg nReg instr
        return          (instr', nReg)

patchReg1
        :: Instruction instr
        => Reg -> Reg -> instr -> instr

patchReg1 old new instr
 = let  patchF r
                | r == old      = new
                | otherwise     = r
   in   patchRegsOfInstr instr patchF

-- Spiller monad --------------------------------------------------------------
-- | State monad for the spill code generator.
type SpillM a
        = State SpillS a

-- | Spill code generator state.
data SpillS
        = SpillS
        { -- | Unique supply for generating fresh vregs.
          stateUS       :: UniqSupply

          -- | Spilled vreg vs the number of times it was loaded, stored.
        , stateSpillSL  :: UniqFM (Reg, Int, Int) }

-- | Create a new spiller state.
initSpillS :: UniqSupply -> SpillS
initSpillS uniqueSupply
        = SpillS
        { stateUS       = uniqueSupply
        , stateSpillSL  = emptyUFM }

-- | Allocate a new unique in the spiller monad.
newUnique :: SpillM Unique
newUnique
 = do   us      <- gets stateUS
        case takeUniqFromSupply us of
         (uniq, us')
          -> do modify $ \s -> s { stateUS = us' }
                return uniq

-- | Add a spill/reload count to a stats record for a register.
accSpillSL :: (Reg, Int, Int) -> (Reg, Int, Int) -> (Reg, Int, Int)
accSpillSL (r1, s1, l1) (_, s2, l2)
        = (r1, s1 + s2, l1 + l2)

-- Spiller stats --------------------------------------------------------------
-- | Spiller statistics.
--   Tells us what registers were spilled.
data SpillStats
        = SpillStats
        { spillStoreLoad        :: UniqFM (Reg, Int, Int) }

-- | Extract spiller statistics from the spiller state.
makeSpillStats :: SpillS -> SpillStats
makeSpillStats s
        = SpillStats
        { spillStoreLoad        = stateSpillSL s }

instance Outputable SpillStats where
 ppr stats
        = pprUFM (spillStoreLoad stats)
                 (vcat . map (\(r, s, l) -> ppr r <+> int s <+> int l))