1 -----------------------------------------------------------------------------
3 -- Code generation for foreign calls.
5 -- (c) The University of Glasgow 2004-2006
7 -----------------------------------------------------------------------------
14 emitSaveThreadState, -- will be needed by the Cmm parser
15 emitLoadThreadState, -- ditto
42 -- -----------------------------------------------------------------------------
43 -- Code generation for Foreign Calls
46 :: HintedCmmFormals -- where to put the results
47 -> ForeignCall -- the op
48 -> [StgArg] -- arguments
49 -> StgLiveVars -- live vars, in case we need to save them
51 cgForeignCall results fcall stg_args live
53 reps_n_amodes <- getArgAmodes stg_args
55 -- Get the *non-void* args, and jiggle them with shimForeignCall
56 arg_exprs = [ shimForeignCallArg stg_arg expr
57 | (stg_arg, (rep,expr)) <- stg_args `zip` reps_n_amodes,
60 arg_hints = zipWith CmmHinted
61 arg_exprs (map (typeForeignHint.stgArgType) stg_args)
63 emitForeignCall results fcall arg_hints live
67 :: HintedCmmFormals -- where to put the results
68 -> ForeignCall -- the op
69 -> [CmmHinted CmmExpr] -- arguments
70 -> StgLiveVars -- live vars, in case we need to save them
73 emitForeignCall results (CCall (CCallSpec target cconv safety)) args live
74 = do vols <- getVolatileRegs live
76 emitForeignCall' safety results
77 (CmmCallee cmm_target cconv) call_args (Just vols) srt CmmMayReturn
79 (call_args, cmm_target)
82 -- A target label known to be in the current package.
86 (mkForeignLabel lbl call_size ForeignLabelInThisPackage IsFunction)))
88 -- If the packageId is Nothing then the label is taken to be in the
89 -- package currently being compiled.
90 PackageTarget lbl mPkgId
93 Nothing -> ForeignLabelInThisPackage
94 Just pkgId -> ForeignLabelInPackage pkgId
97 (mkForeignLabel lbl call_size labelSource IsFunction)))
99 -- A label imported with "foreign import ccall "dynamic" ..."
100 -- Note: "dynamic" here doesn't mean "dynamic library".
101 -- Read the FFI spec for details.
102 DynamicTarget -> case args of
103 (CmmHinted fn _):rest -> (rest, fn)
104 [] -> panic "emitForeignCall: DynamicTarget []"
106 -- in the stdcall calling convention, the symbol needs @size appended
107 -- to it, where size is the total number of bytes of arguments. We
108 -- attach this info to the CLabel here, and the CLabel pretty printer
109 -- will generate the suffix when the label is printed.
111 | StdCallConv <- cconv = Just (sum (map (arg_size.cmmExprType.hintlessCmm) args))
112 | otherwise = Nothing
114 -- ToDo: this might not be correct for 64-bit API
115 arg_size rep = max (widthInBytes (typeWidth rep)) wORD_SIZE
118 -- alternative entry point, used by CmmParse
121 -> HintedCmmFormals -- where to put the results
122 -> CmmCallTarget -- the op
123 -> [CmmHinted CmmExpr] -- arguments
124 -> Maybe [GlobalReg] -- live vars, in case we need to save them
125 -> C_SRT -- the SRT of the calls continuation
128 emitForeignCall' safety results target args vols _srt ret
129 | not (playSafe safety) = do
130 temp_args <- load_args_into_temps args
131 let (caller_save, caller_load) = callerSaveVolatileRegs vols
133 stmtC (CmmCall target results temp_args CmmUnsafe ret)
137 -- Both 'id' and 'new_base' are GCKindNonPtr because they're
138 -- RTS only objects and are not subject to garbage collection
140 new_base <- newTemp (cmmRegType (CmmGlobal BaseReg))
141 temp_args <- load_args_into_temps args
142 temp_target <- load_target_into_temp target
143 let (caller_save, caller_load) = callerSaveVolatileRegs vols
146 -- The CmmUnsafe arguments are only correct because this part
147 -- of the code hasn't been moved into the CPS pass yet.
148 -- Once that happens, this function will just emit a (CmmSafe srt) call,
149 -- and the CPS will be the one to convert that
150 -- to this sequence of three CmmUnsafe calls.
151 stmtC (CmmCall (CmmCallee suspendThread CCallConv)
152 [ CmmHinted id AddrHint ]
153 [ CmmHinted (CmmReg (CmmGlobal BaseReg)) AddrHint ]
155 stmtC (CmmCall temp_target results temp_args CmmUnsafe ret)
156 stmtC (CmmCall (CmmCallee resumeThread CCallConv)
157 [ CmmHinted new_base AddrHint ]
158 [ CmmHinted (CmmReg (CmmLocal id)) AddrHint ]
160 -- Assign the result to BaseReg: we
161 -- might now have a different Capability!
162 stmtC (CmmAssign (CmmGlobal BaseReg) (CmmReg (CmmLocal new_base)))
166 suspendThread, resumeThread :: CmmExpr
167 suspendThread = CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "suspendThread")))
168 resumeThread = CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "resumeThread")))
171 -- we might need to load arguments into temporaries before
172 -- making the call, because certain global registers might
173 -- overlap with registers that the C calling convention uses
174 -- for passing arguments.
176 -- This is a HACK; really it should be done in the back end, but
177 -- it's easier to generate the temporaries here.
178 load_args_into_temps :: [CmmHinted CmmExpr] -> FCode [CmmHinted CmmExpr]
179 load_args_into_temps = mapM arg_assign_temp
180 where arg_assign_temp (CmmHinted e hint) = do
181 tmp <- maybe_assign_temp e
182 return (CmmHinted tmp hint)
184 load_target_into_temp :: CmmCallTarget -> FCode CmmCallTarget
185 load_target_into_temp (CmmCallee expr conv) = do
186 tmp <- maybe_assign_temp expr
187 return (CmmCallee tmp conv)
188 load_target_into_temp other_target =
191 maybe_assign_temp :: CmmExpr -> FCode CmmExpr
193 | hasNoGlobalRegs e = return e
195 -- don't use assignTemp, it uses its own notion of "trivial"
196 -- expressions, which are wrong here.
197 -- this is a NonPtr because it only duplicates an existing
198 reg <- newTemp (cmmExprType e) --TODO FIXME NOW
199 stmtC (CmmAssign (CmmLocal reg) e)
200 return (CmmReg (CmmLocal reg))
202 -- -----------------------------------------------------------------------------
203 -- Save/restore the thread state in the TSO
205 -- This stuff can't be done in suspendThread/resumeThread, because it
206 -- refers to global registers which aren't available in the C world.
208 emitSaveThreadState :: Code
209 emitSaveThreadState = do
210 -- CurrentTSO->sp = Sp;
211 stmtC $ CmmStore (cmmOffset stgCurrentTSO tso_SP) stgSp
213 -- and save the current cost centre stack in the TSO when profiling:
214 when opt_SccProfilingOn $
215 stmtC (CmmStore (cmmOffset stgCurrentTSO tso_CCCS) curCCS)
217 -- CurrentNursery->free = Hp+1;
218 emitCloseNursery :: Code
219 emitCloseNursery = stmtC $ CmmStore nursery_bdescr_free (cmmOffsetW stgHp 1)
221 emitLoadThreadState :: Code
222 emitLoadThreadState = do
223 tso <- newTemp bWord -- TODO FIXME NOW
226 CmmAssign (CmmLocal tso) stgCurrentTSO,
228 CmmAssign sp (CmmLoad (cmmOffset (CmmReg (CmmLocal tso)) tso_SP)
230 -- SpLim = tso->stack + RESERVED_STACK_WORDS;
231 CmmAssign spLim (cmmOffsetW (cmmOffset (CmmReg (CmmLocal tso)) tso_STACK)
232 rESERVED_STACK_WORDS),
234 -- HpAlloc is assumed to be set to non-zero only by a failed
235 -- a heap check, see HeapStackCheck.cmm:GC_GENERIC
236 CmmAssign hpAlloc (CmmLit zeroCLit)
239 -- and load the current cost centre stack from the TSO when profiling:
240 when opt_SccProfilingOn $
241 stmtC (CmmStore curCCSAddr
242 (CmmLoad (cmmOffset (CmmReg (CmmLocal tso)) tso_CCCS) bWord))
244 emitOpenNursery :: Code
245 emitOpenNursery = stmtsC [
246 -- Hp = CurrentNursery->free - 1;
247 CmmAssign hp (cmmOffsetW (CmmLoad nursery_bdescr_free gcWord) (-1)),
249 -- HpLim = CurrentNursery->start +
250 -- CurrentNursery->blocks*BLOCK_SIZE_W - 1;
253 (CmmLoad nursery_bdescr_start bWord)
255 (CmmMachOp mo_wordMul [
256 CmmMachOp (MO_SS_Conv W32 wordWidth)
257 [CmmLoad nursery_bdescr_blocks b32],
258 CmmLit (mkIntCLit bLOCK_SIZE)
265 nursery_bdescr_free, nursery_bdescr_start, nursery_bdescr_blocks :: CmmExpr
266 nursery_bdescr_free = cmmOffset stgCurrentNursery oFFSET_bdescr_free
267 nursery_bdescr_start = cmmOffset stgCurrentNursery oFFSET_bdescr_start
268 nursery_bdescr_blocks = cmmOffset stgCurrentNursery oFFSET_bdescr_blocks
270 tso_SP, tso_STACK, tso_CCCS :: ByteOff
271 tso_SP = tsoFieldB oFFSET_StgTSO_sp
272 tso_STACK = tsoFieldB oFFSET_StgTSO_stack
273 tso_CCCS = tsoProfFieldB oFFSET_StgTSO_CCCS
275 -- The TSO struct has a variable header, and an optional StgTSOProfInfo in
276 -- the middle. The fields we're interested in are after the StgTSOProfInfo.
277 tsoFieldB :: ByteOff -> ByteOff
279 | opt_SccProfilingOn = off + sIZEOF_StgTSOProfInfo + fixedHdrSize * wORD_SIZE
280 | otherwise = off + fixedHdrSize * wORD_SIZE
282 tsoProfFieldB :: ByteOff -> ByteOff
283 tsoProfFieldB off = off + fixedHdrSize * wORD_SIZE
285 stgSp, stgHp, stgCurrentTSO, stgCurrentNursery :: CmmExpr
288 stgCurrentTSO = CmmReg currentTSO
289 stgCurrentNursery = CmmReg currentNursery
291 sp, spLim, hp, hpLim, currentTSO, currentNursery, hpAlloc :: CmmReg
293 spLim = CmmGlobal SpLim
295 hpLim = CmmGlobal HpLim
296 currentTSO = CmmGlobal CurrentTSO
297 currentNursery = CmmGlobal CurrentNursery
298 hpAlloc = CmmGlobal HpAlloc
300 -- -----------------------------------------------------------------------------
301 -- For certain types passed to foreign calls, we adjust the actual
302 -- value passed to the call. For ByteArray#/Array# we pass the
303 -- address of the actual array, not the address of the heap object.
305 shimForeignCallArg :: StgArg -> CmmExpr -> CmmExpr
306 shimForeignCallArg arg expr
307 | tycon == arrayPrimTyCon || tycon == mutableArrayPrimTyCon
308 = cmmOffsetB expr arrPtrsHdrSize
310 | tycon == byteArrayPrimTyCon || tycon == mutableByteArrayPrimTyCon
311 = cmmOffsetB expr arrWordsHdrSize
315 -- should be a tycon app, since this is a foreign call
316 tycon = tyConAppTyCon (repType (stgArgType arg))