1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow 1993-2004
5 -- The native code generator's monad.
7 -- -----------------------------------------------------------------------------
10 NatM_State(..), mkNatM_State,
12 NatM, -- instance Monad
13 initNat, addImportNat, getUniqueNat,
14 mapAccumLNat, setDeltaNat, getDeltaNat,
15 getBlockIdNat, getNewLabelNat, getNewRegNat, getNewRegPairNat,
16 getPicBaseMaybeNat, getPicBaseNat
19 #include "HsVersions.h"
21 import Cmm ( BlockId(..) )
22 import CLabel ( CLabel, mkAsmTempLabel )
24 import MachOp ( MachRep )
26 import Unique ( Unique )
29 data NatM_State = NatM_State {
30 natm_us :: UniqSupply,
32 natm_imports :: [(CLabel)],
36 newtype NatM result = NatM (NatM_State -> (result, NatM_State))
40 mkNatM_State :: UniqSupply -> Int -> NatM_State
41 mkNatM_State us delta = NatM_State us delta [] Nothing
43 initNat :: NatM_State -> NatM a -> (a, NatM_State)
44 initNat init_st m = case unNat m init_st of { (r,st) -> (r,st) }
46 instance Monad NatM where
50 thenNat :: NatM a -> (a -> NatM b) -> NatM b
52 = NatM $ \st -> case unNat expr st of
53 (result, st') -> unNat (cont result) st'
55 returnNat :: a -> NatM a
56 returnNat result = NatM $ \st -> (result, st)
58 mapAccumLNat :: (acc -> x -> NatM (acc, y))
65 mapAccumLNat f b (x:xs)
66 = do (b__2, x__2) <- f b x
67 (b__3, xs__2) <- mapAccumLNat f b__2 xs
68 return (b__3, x__2:xs__2)
70 getUniqueNat :: NatM Unique
71 getUniqueNat = NatM $ \ (NatM_State us delta imports pic) ->
72 case splitUniqSupply us of
73 (us1,us2) -> (uniqFromSupply us1, (NatM_State us2 delta imports pic))
75 getDeltaNat :: NatM Int
76 getDeltaNat = NatM $ \ st -> (natm_delta st, st)
78 setDeltaNat :: Int -> NatM ()
79 setDeltaNat delta = NatM $ \ (NatM_State us _ imports pic) ->
80 ((), NatM_State us delta imports pic)
82 addImportNat :: CLabel -> NatM ()
83 addImportNat imp = NatM $ \ (NatM_State us delta imports pic) ->
84 ((), NatM_State us delta (imp:imports) pic)
86 getBlockIdNat :: NatM BlockId
87 getBlockIdNat = do u <- getUniqueNat; return (BlockId u)
89 getNewLabelNat :: NatM CLabel
90 getNewLabelNat = do u <- getUniqueNat; return (mkAsmTempLabel u)
92 getNewRegNat :: MachRep -> NatM Reg
93 getNewRegNat rep = do u <- getUniqueNat; return (mkVReg u rep)
95 getNewRegPairNat :: MachRep -> NatM (Reg,Reg)
96 getNewRegPairNat rep = do
98 let lo = mkVReg u rep; hi = getHiVRegFromLo lo
101 getPicBaseMaybeNat :: NatM (Maybe Reg)
102 getPicBaseMaybeNat = NatM (\state -> (natm_pic state, state))
104 getPicBaseNat :: MachRep -> NatM Reg
105 getPicBaseNat rep = do
106 mbPicBase <- getPicBaseMaybeNat
108 Just picBase -> return picBase
110 reg <- getNewRegNat rep
111 NatM (\state -> (reg, state { natm_pic = Just reg }))