module StgCmmUtils (
cgLit, mkSimpleLit,
emitDataLits, mkDataLits,
emitRODataLits, mkRODataLits,
emitRtsCall, emitRtsCallWithResult, emitRtsCallGen,
assignTemp, newTemp,
newUnboxedTupleRegs,
emitMultiAssign, emitCmmLitSwitch, emitSwitch,
tagToClosure, mkTaggedObjectLoad,
callerSaves, callerSaveVolatileRegs, get_GlobalReg_addr,
cmmAndWord, cmmOrWord, cmmNegate, cmmEqWord, cmmNeWord,
cmmUGtWord, cmmSubWord, cmmMulWord, cmmAddWord, cmmUShrWord,
cmmOffsetExprW, cmmOffsetExprB,
cmmRegOffW, cmmRegOffB,
cmmLabelOffW, cmmLabelOffB,
cmmOffsetW, cmmOffsetB,
cmmOffsetLitW, cmmOffsetLitB,
cmmLoadIndexW,
cmmConstrTag1,
cmmUntag, cmmIsTagged,
addToMem, addToMemE, addToMemLblE, addToMemLbl,
mkWordCLit,
newStringCLit, newByteStringCLit,
blankWord
) where
#include "HsVersions.h"
import StgCmmMonad
import StgCmmClosure
import Cmm
import BlockId
import MkGraph
import CodeGen.Platform
import CLabel
import CmmUtils
import ForeignCall
import IdInfo
import Type
import TyCon
import SMRep
import Module
import Literal
import Digraph
import ListSetOps
import Util
import Unique
import DynFlags
import FastString
import Outputable
import qualified Data.ByteString as BS
import Data.Char
import Data.List
import Data.Ord
import Data.Word
import Data.Maybe
cgLit :: Literal -> FCode CmmLit
cgLit (MachStr s) = newByteStringCLit (BS.unpack s)
cgLit other_lit = do dflags <- getDynFlags
return (mkSimpleLit dflags other_lit)
mkLtOp :: DynFlags -> Literal -> MachOp
mkLtOp dflags (MachInt _) = MO_S_Lt (wordWidth dflags)
mkLtOp _ (MachFloat _) = MO_F_Lt W32
mkLtOp _ (MachDouble _) = MO_F_Lt W64
mkLtOp dflags lit = MO_U_Lt (typeWidth (cmmLitType dflags (mkSimpleLit dflags lit)))
mkSimpleLit :: DynFlags -> Literal -> CmmLit
mkSimpleLit dflags (MachChar c) = CmmInt (fromIntegral (ord c)) (wordWidth dflags)
mkSimpleLit dflags MachNullAddr = zeroCLit dflags
mkSimpleLit dflags (MachInt i) = CmmInt i (wordWidth dflags)
mkSimpleLit _ (MachInt64 i) = CmmInt i W64
mkSimpleLit dflags (MachWord i) = CmmInt i (wordWidth dflags)
mkSimpleLit _ (MachWord64 i) = CmmInt i W64
mkSimpleLit _ (MachFloat r) = CmmFloat r W32
mkSimpleLit _ (MachDouble r) = CmmFloat r W64
mkSimpleLit _ (MachLabel fs ms fod)
= CmmLabel (mkForeignLabel fs ms labelSrc fod)
where
labelSrc = ForeignLabelInThisPackage
mkSimpleLit _ other = pprPanic "mkSimpleLit" (ppr other)
addToMemLbl :: CmmType -> CLabel -> Int -> CmmAGraph
addToMemLbl rep lbl n = addToMem rep (CmmLit (CmmLabel lbl)) n
addToMemLblE :: CmmType -> CLabel -> CmmExpr -> CmmAGraph
addToMemLblE rep lbl = addToMemE rep (CmmLit (CmmLabel lbl))
addToMem :: CmmType
-> CmmExpr
-> Int
-> CmmAGraph
addToMem rep ptr n = addToMemE rep ptr (CmmLit (CmmInt (toInteger n) (typeWidth rep)))
addToMemE :: CmmType
-> CmmExpr
-> CmmExpr
-> CmmAGraph
addToMemE rep ptr n
= mkStore ptr (CmmMachOp (MO_Add (typeWidth rep)) [CmmLoad ptr rep, n])
mkTaggedObjectLoad :: DynFlags -> LocalReg -> LocalReg -> WordOff -> DynTag -> CmmAGraph
mkTaggedObjectLoad dflags reg base offset tag
= mkAssign (CmmLocal reg)
(CmmLoad (cmmOffsetB dflags
(CmmReg (CmmLocal base))
(wORD_SIZE dflags * offset tag))
(localRegType reg))
tagToClosure :: DynFlags -> TyCon -> CmmExpr -> CmmExpr
tagToClosure dflags tycon tag
= CmmLoad (cmmOffsetExprW dflags closure_tbl tag) (bWord dflags)
where closure_tbl = CmmLit (CmmLabel lbl)
lbl = mkClosureTableLabel (tyConName tycon) NoCafRefs
emitRtsCall :: PackageId -> FastString -> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()
emitRtsCall pkg fun args safe = emitRtsCallGen [] (mkCmmCodeLabel pkg fun) args safe
emitRtsCallWithResult :: LocalReg -> ForeignHint -> PackageId -> FastString
-> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()
emitRtsCallWithResult res hint pkg fun args safe
= emitRtsCallGen [(res,hint)] (mkCmmCodeLabel pkg fun) args safe
emitRtsCallGen
:: [(LocalReg,ForeignHint)]
-> CLabel
-> [(CmmExpr,ForeignHint)]
-> Bool
-> FCode ()
emitRtsCallGen res lbl args safe
= do { dflags <- getDynFlags
; updfr_off <- getUpdFrameOff
; let (caller_save, caller_load) = callerSaveVolatileRegs dflags
; emit caller_save
; call updfr_off
; emit caller_load }
where
call updfr_off =
if safe then
emit =<< mkCmmCall fun_expr res' args' updfr_off
else do
let conv = ForeignConvention CCallConv arg_hints res_hints CmmMayReturn
emit $ mkUnsafeCall (ForeignTarget fun_expr conv) res' args'
(args', arg_hints) = unzip args
(res', res_hints) = unzip res
fun_expr = mkLblExpr lbl
callerSaveVolatileRegs :: DynFlags -> (CmmAGraph, CmmAGraph)
callerSaveVolatileRegs dflags = (caller_save, caller_load)
where
platform = targetPlatform dflags
caller_save = catAGraphs (map callerSaveGlobalReg regs_to_save)
caller_load = catAGraphs (map callerRestoreGlobalReg regs_to_save)
system_regs = [ Sp,SpLim,Hp,HpLim,CCCS,CurrentTSO,CurrentNursery
, BaseReg ]
regs_to_save = filter (callerSaves platform) system_regs
callerSaveGlobalReg reg
= mkStore (get_GlobalReg_addr dflags reg) (CmmReg (CmmGlobal reg))
callerRestoreGlobalReg reg
= mkAssign (CmmGlobal reg)
(CmmLoad (get_GlobalReg_addr dflags reg) (globalRegType dflags reg))
get_GlobalReg_addr :: DynFlags -> GlobalReg -> CmmExpr
get_GlobalReg_addr dflags BaseReg = regTableOffset dflags 0
get_GlobalReg_addr dflags mid
= get_Regtable_addr_from_offset dflags
(globalRegType dflags mid) (baseRegOffset dflags mid)
regTableOffset :: DynFlags -> Int -> CmmExpr
regTableOffset dflags n =
CmmLit (CmmLabelOff mkMainCapabilityLabel (oFFSET_Capability_r dflags + n))
get_Regtable_addr_from_offset :: DynFlags -> CmmType -> Int -> CmmExpr
get_Regtable_addr_from_offset dflags _rep offset =
if haveRegBase (targetPlatform dflags)
then CmmRegOff (CmmGlobal BaseReg) offset
else regTableOffset dflags offset
baseRegOffset :: DynFlags -> GlobalReg -> Int
baseRegOffset dflags Sp = oFFSET_StgRegTable_rSp dflags
baseRegOffset dflags SpLim = oFFSET_StgRegTable_rSpLim dflags
baseRegOffset dflags (LongReg 1) = oFFSET_StgRegTable_rL1 dflags
baseRegOffset dflags Hp = oFFSET_StgRegTable_rHp dflags
baseRegOffset dflags HpLim = oFFSET_StgRegTable_rHpLim dflags
baseRegOffset dflags CCCS = oFFSET_StgRegTable_rCCCS dflags
baseRegOffset dflags CurrentTSO = oFFSET_StgRegTable_rCurrentTSO dflags
baseRegOffset dflags CurrentNursery = oFFSET_StgRegTable_rCurrentNursery dflags
baseRegOffset dflags HpAlloc = oFFSET_StgRegTable_rHpAlloc dflags
baseRegOffset dflags GCEnter1 = oFFSET_stgGCEnter1 dflags
baseRegOffset dflags GCFun = oFFSET_stgGCFun dflags
baseRegOffset _ reg = pprPanic "baseRegOffset:" (ppr reg)
emitDataLits :: CLabel -> [CmmLit] -> FCode ()
emitDataLits lbl lits = emitDecl (mkDataLits Data lbl lits)
emitRODataLits :: CLabel -> [CmmLit] -> FCode ()
emitRODataLits lbl lits = emitDecl (mkRODataLits lbl lits)
newStringCLit :: String -> FCode CmmLit
newStringCLit str = newByteStringCLit (map (fromIntegral . ord) str)
newByteStringCLit :: [Word8] -> FCode CmmLit
newByteStringCLit bytes
= do { uniq <- newUnique
; let (lit, decl) = mkByteStringCLit uniq bytes
; emitDecl decl
; return lit }
assignTemp :: CmmExpr -> FCode LocalReg
assignTemp (CmmReg (CmmLocal reg)) = return reg
assignTemp e = do { dflags <- getDynFlags
; uniq <- newUnique
; let reg = LocalReg uniq (cmmExprType dflags e)
; emitAssign (CmmLocal reg) e
; return reg }
newTemp :: CmmType -> FCode LocalReg
newTemp rep = do { uniq <- newUnique
; return (LocalReg uniq rep) }
newUnboxedTupleRegs :: Type -> FCode ([LocalReg], [ForeignHint])
newUnboxedTupleRegs res_ty
= ASSERT( isUnboxedTupleType res_ty )
do { dflags <- getDynFlags
; sequel <- getSequel
; regs <- choose_regs dflags sequel
; ASSERT( regs `equalLength` reps )
return (regs, map primRepForeignHint reps) }
where
UbxTupleRep ty_args = repType res_ty
reps = [ rep
| ty <- ty_args
, let rep = typePrimRep ty
, not (isVoidRep rep) ]
choose_regs _ (AssignTo regs _) = return regs
choose_regs dflags _ = mapM (newTemp . primRepCmmType dflags) reps
emitMultiAssign :: [LocalReg] -> [CmmExpr] -> FCode ()
type Key = Int
type Vrtx = (Key, Stmt)
type Stmt = (LocalReg, CmmExpr)
emitMultiAssign [] [] = return ()
emitMultiAssign [reg] [rhs] = emitAssign (CmmLocal reg) rhs
emitMultiAssign regs rhss = ASSERT( equalLength regs rhss )
unscramble ([1..] `zip` (regs `zip` rhss))
unscramble :: [Vrtx] -> FCode ()
unscramble vertices = mapM_ do_component components
where
edges :: [ (Vrtx, Key, [Key]) ]
edges = [ (vertex, key1, edges_from stmt1)
| vertex@(key1, stmt1) <- vertices ]
edges_from :: Stmt -> [Key]
edges_from stmt1 = [ key2 | (key2, stmt2) <- vertices,
stmt1 `mustFollow` stmt2 ]
components :: [SCC Vrtx]
components = stronglyConnCompFromEdgedVertices edges
do_component :: SCC Vrtx -> FCode ()
do_component (AcyclicSCC (_,stmt)) = mk_graph stmt
do_component (CyclicSCC []) = panic "do_component"
do_component (CyclicSCC [(_,stmt)]) = mk_graph stmt
do_component (CyclicSCC ((_,first_stmt) : rest)) = do
dflags <- getDynFlags
u <- newUnique
let (to_tmp, from_tmp) = split dflags u first_stmt
mk_graph to_tmp
unscramble rest
mk_graph from_tmp
split :: DynFlags -> Unique -> Stmt -> (Stmt, Stmt)
split dflags uniq (reg, rhs)
= ((tmp, rhs), (reg, CmmReg (CmmLocal tmp)))
where
rep = cmmExprType dflags rhs
tmp = LocalReg uniq rep
mk_graph :: Stmt -> FCode ()
mk_graph (reg, rhs) = emitAssign (CmmLocal reg) rhs
mustFollow :: Stmt -> Stmt -> Bool
(reg, _) `mustFollow` (_, rhs) = CmmLocal reg `regUsedIn` rhs
emitSwitch :: CmmExpr
-> [(ConTagZ, CmmAGraph)]
-> Maybe CmmAGraph
-> ConTagZ -> ConTagZ
-> FCode ()
emitSwitch tag_expr branches mb_deflt lo_tag hi_tag
= do { dflags <- getDynFlags
; mkCmmSwitch (via_C dflags) tag_expr branches mb_deflt lo_tag hi_tag }
where
via_C dflags | HscC <- hscTarget dflags = True
| otherwise = False
mkCmmSwitch :: Bool
-> CmmExpr
-> [(ConTagZ, CmmAGraph)]
-> Maybe CmmAGraph
-> ConTagZ -> ConTagZ
-> FCode ()
mkCmmSwitch _ _ [] (Just code) _ _ = emit code
mkCmmSwitch _ _ [(_,code)] Nothing _ _ = emit code
mkCmmSwitch via_C tag_expr branches mb_deflt lo_tag hi_tag = do
join_lbl <- newLabelC
mb_deflt_lbl <- label_default join_lbl mb_deflt
branches_lbls <- label_branches join_lbl branches
tag_expr' <- assignTemp' tag_expr
emit =<< mk_switch tag_expr' (sortBy (comparing fst) branches_lbls)
mb_deflt_lbl lo_tag hi_tag via_C
emitLabel join_lbl
mk_switch :: CmmExpr -> [(ConTagZ, BlockId)]
-> Maybe BlockId
-> ConTagZ -> ConTagZ -> Bool
-> FCode CmmAGraph
mk_switch _tag_expr [(tag, lbl)] _ lo_tag hi_tag _via_C
| lo_tag == hi_tag
= ASSERT( tag == lo_tag )
return (mkBranch lbl)
mk_switch _tag_expr [(_tag,lbl)] Nothing _ _ _
= return (mkBranch lbl)
mk_switch tag_expr [(tag,lbl)] (Just deflt) _ _ _
= do dflags <- getDynFlags
let cond = cmmNeWord dflags tag_expr (mkIntExpr dflags tag)
return (mkCbranch cond deflt lbl)
mk_switch tag_expr branches mb_deflt lo_tag hi_tag via_C
| use_switch
= do let
find_branch :: ConTagZ -> Maybe BlockId
find_branch i = case (assocMaybe branches i) of
Just lbl -> Just lbl
Nothing -> mb_deflt
arms :: [Maybe BlockId]
arms = [ find_branch i | i <- [real_lo_tag..real_hi_tag]]
dflags <- getDynFlags
return (mkSwitch (cmmOffset dflags tag_expr ( real_lo_tag)) arms)
| Just deflt <- mb_deflt, (lowest_branch lo_tag) >= n_branches
= do dflags <- getDynFlags
stmts <- mk_switch tag_expr branches mb_deflt
lowest_branch hi_tag via_C
mkCmmIfThenElse
(cmmULtWord dflags tag_expr (mkIntExpr dflags lowest_branch))
(mkBranch deflt)
stmts
| Just deflt <- mb_deflt, (hi_tag highest_branch) >= n_branches
= do dflags <- getDynFlags
stmts <- mk_switch tag_expr branches mb_deflt
lo_tag highest_branch via_C
mkCmmIfThenElse
(cmmUGtWord dflags tag_expr (mkIntExpr dflags highest_branch))
(mkBranch deflt)
stmts
| otherwise
= do dflags <- getDynFlags
lo_stmts <- mk_switch tag_expr lo_branches mb_deflt
lo_tag (mid_tag1) via_C
hi_stmts <- mk_switch tag_expr hi_branches mb_deflt
mid_tag hi_tag via_C
mkCmmIfThenElse
(cmmUGeWord dflags tag_expr (mkIntExpr dflags mid_tag))
hi_stmts
lo_stmts
where
use_switch =
ASSERT( n_branches > 1 && n_tags > 1 )
n_tags > 2 && (via_C || (dense && big_enough))
big_enough = n_branches > 4
dense = n_branches > (n_tags `div` 2)
n_branches = length branches
lowest_branch = fst (head branches)
highest_branch = fst (last branches)
real_lo_tag
| isNothing mb_deflt = lowest_branch
| otherwise = lo_tag
real_hi_tag
| isNothing mb_deflt = highest_branch
| otherwise = hi_tag
n_tags = real_hi_tag real_lo_tag + 1
(mid_tag,_) = branches !! (n_branches `div` 2)
(lo_branches, hi_branches) = span is_lo branches
is_lo (t,_) = t < mid_tag
emitCmmLitSwitch :: CmmExpr
-> [(Literal, CmmAGraph)]
-> CmmAGraph
-> FCode ()
emitCmmLitSwitch _scrut [] deflt = emit deflt
emitCmmLitSwitch scrut branches deflt = do
scrut' <- assignTemp' scrut
join_lbl <- newLabelC
deflt_lbl <- label_code join_lbl deflt
branches_lbls <- label_branches join_lbl branches
emit =<< mk_lit_switch scrut' deflt_lbl
(sortBy (comparing fst) branches_lbls)
emitLabel join_lbl
mk_lit_switch :: CmmExpr -> BlockId
-> [(Literal,BlockId)]
-> FCode CmmAGraph
mk_lit_switch scrut deflt [(lit,blk)]
= do
dflags <- getDynFlags
let
cmm_lit = mkSimpleLit dflags lit
cmm_ty = cmmLitType dflags cmm_lit
rep = typeWidth cmm_ty
ne = if isFloatType cmm_ty then MO_F_Ne rep else MO_Ne rep
return (mkCbranch (CmmMachOp ne [scrut, CmmLit cmm_lit]) deflt blk)
mk_lit_switch scrut deflt_blk_id branches
= do dflags <- getDynFlags
lo_blk <- mk_lit_switch scrut deflt_blk_id lo_branches
hi_blk <- mk_lit_switch scrut deflt_blk_id hi_branches
mkCmmIfThenElse (cond dflags) lo_blk hi_blk
where
n_branches = length branches
(mid_lit,_) = branches !! (n_branches `div` 2)
(lo_branches, hi_branches) = span is_lo branches
is_lo (t,_) = t < mid_lit
cond dflags = CmmMachOp (mkLtOp dflags mid_lit)
[scrut, CmmLit (mkSimpleLit dflags mid_lit)]
label_default :: BlockId -> Maybe CmmAGraph -> FCode (Maybe BlockId)
label_default _ Nothing
= return Nothing
label_default join_lbl (Just code)
= do lbl <- label_code join_lbl code
return (Just lbl)
label_branches :: BlockId -> [(a,CmmAGraph)] -> FCode [(a,BlockId)]
label_branches _join_lbl []
= return []
label_branches join_lbl ((tag,code):branches)
= do lbl <- label_code join_lbl code
branches' <- label_branches join_lbl branches
return ((tag,lbl):branches')
label_code :: BlockId -> CmmAGraph -> FCode BlockId
label_code join_lbl code = do
lbl <- newLabelC
emitOutOfLine lbl (code <*> mkBranch join_lbl)
return lbl
assignTemp' :: CmmExpr -> FCode CmmExpr
assignTemp' e
| isTrivialCmmExpr e = return e
| otherwise = do
dflags <- getDynFlags
lreg <- newTemp (cmmExprType dflags e)
let reg = CmmLocal lreg
emitAssign reg e
return (CmmReg reg)