-- | The assignment of virtual registers to stack slots

--      We have lots of stack slots. Memory-to-memory moves are a pain on most
--      architectures. Therefore, we avoid having to generate memory-to-memory moves
--      by simply giving every virtual register its own stack slot.

--      The StackMap stack map keeps track of virtual register - stack slot
--      associations and of which stack slots are still free. Once it has been
--      associated, a stack slot is never "freed" or removed from the StackMap again,
--      it remains associated until we are done with the current CmmProc.
--
module RegAlloc.Linear.StackMap (
        StackSlot,
        StackMap(..),
        emptyStackMap,
        getStackSlotFor,
        getStackUse
)

where

import GhcPrelude

import DynFlags
import UniqFM
import Unique


-- | Identifier for a stack slot.
type StackSlot = Int

data StackMap
        = StackMap
        { -- | The slots that are still available to be allocated.
          StackMap -> Int
stackMapNextFreeSlot  :: !Int

          -- | Assignment of vregs to stack slots.
        , StackMap -> UniqFM Int
stackMapAssignment    :: UniqFM StackSlot }


-- | An empty stack map, with all slots available.
emptyStackMap :: DynFlags -> StackMap
emptyStackMap :: DynFlags -> StackMap
emptyStackMap _ = Int -> UniqFM Int -> StackMap
StackMap 0 UniqFM Int
forall elt. UniqFM elt
emptyUFM


-- | If this vreg unique already has a stack assignment then return the slot number,
--      otherwise allocate a new slot, and update the map.
--
getStackSlotFor :: StackMap -> Unique -> (StackMap, Int)

getStackSlotFor :: StackMap -> Unique -> (StackMap, Int)
getStackSlotFor fs :: StackMap
fs@(StackMap _ reserved :: UniqFM Int
reserved) reg :: Unique
reg
  | Just slot :: Int
slot <- UniqFM Int -> Unique -> Maybe Int
forall key elt. Uniquable key => UniqFM elt -> key -> Maybe elt
lookupUFM UniqFM Int
reserved Unique
reg  =  (StackMap
fs, Int
slot)

getStackSlotFor (StackMap freeSlot :: Int
freeSlot reserved :: UniqFM Int
reserved) reg :: Unique
reg =
    (Int -> UniqFM Int -> StackMap
StackMap (Int
freeSlotInt -> Int -> Int
forall a. Num a => a -> a -> a
+1) (UniqFM Int -> Unique -> Int -> UniqFM Int
forall key elt.
Uniquable key =>
UniqFM elt -> key -> elt -> UniqFM elt
addToUFM UniqFM Int
reserved Unique
reg Int
freeSlot), Int
freeSlot)

-- | Return the number of stack slots that were allocated
getStackUse :: StackMap -> Int
getStackUse :: StackMap -> Int
getStackUse (StackMap freeSlot :: Int
freeSlot _) = Int
freeSlot