2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 % $Id: CgTailCall.lhs,v 1.17 1998/12/18 17:40:53 simonpj Exp $
6 %********************************************************
8 \section[CgTailCall]{Tail calls: converting @StgApps@}
10 %********************************************************
15 performReturn, performPrimReturn,
16 mkStaticAlgReturnCode, mkDynamicAlgReturnCode,
17 mkUnboxedTupleReturnCode, returnUnboxedTuple,
27 #include "HsVersions.h"
32 import AbsCUtils ( mkAbstractCs, mkAbsCStmts, getAmodeRep )
33 import CgBindery ( getArgAmodes, getCAddrMode, getCAddrModeAndInfo )
34 import CgRetConv ( dataReturnConvPrim,
35 ctrlReturnConvAlg, CtrlReturnConvention(..),
36 assignAllRegs, assignRegs
38 import CgStackery ( adjustRealSp, mkTaggedStkAmodes, adjustStackHW )
39 import CgUsages ( getSpRelOffset )
40 import CgUpdate ( pushSeqFrame )
41 import CLabel ( mkUpdEntryLabel, mkRtsPrimOpLabel )
42 import ClosureInfo ( nodeMustPointToIt,
43 getEntryConvention, EntryConvention(..),
46 import CmdLineOpts ( opt_DoSemiTagging )
47 import Id ( Id, idType, idName )
48 import DataCon ( DataCon, dataConTyCon, dataConTag, fIRST_TAG )
49 import Const ( mkMachInt )
50 import Maybes ( assocMaybe )
51 import PrimRep ( PrimRep(..) )
52 import StgSyn ( StgArg, GenStgArg(..) )
53 import Type ( isUnLiftedType )
54 import TyCon ( TyCon )
55 import PrimOp ( PrimOp )
56 import Util ( zipWithEqual )
58 import Panic ( panic, assertPanic )
61 %************************************************************************
63 \subsection[tailcall-doc]{Documentation}
65 %************************************************************************
68 cgTailCall :: Id -> [StgArg] -> Code
71 Here's the code we generate for a tail call. (NB there may be no
72 arguments, in which case this boils down to just entering a variable.)
75 \item Adjust the stack ptr to \tr{tailSp + #args}.
76 \item Put args in the top locations of the resulting stack.
77 \item Make Node point to the function closure.
78 \item Enter the function closure.
81 Things to be careful about:
83 \item Don't overwrite stack locations before you have finished with
84 them (remember you need the function and the as-yet-unmoved
86 \item Preferably, generate no code to replace x by x on the stack (a
87 common situation in tail-recursion).
88 \item Adjust the stack high water mark appropriately.
91 Treat unboxed locals exactly like literals (above) except use the addr
92 mode for the local instead of (CLit lit) in the assignment.
94 Case for unboxed @Ids@ first:
97 | isUnLiftedType (idType fun)
98 = getCAddrMode fun `thenFC` \ amode ->
99 performPrimReturn (ppr fun) amode
102 The general case (@fun@ is boxed):
104 cgTailCall fun args = performTailCall fun args
107 %************************************************************************
109 \subsection[return-and-tail-call]{Return and tail call}
111 %************************************************************************
114 performPrimReturn :: SDoc -- Just for debugging (sigh)
115 -> CAddrMode -- The thing to return
118 performPrimReturn doc amode
120 kind = getAmodeRep amode
121 ret_reg = dataReturnConvPrim kind
123 assign_possibly = case kind of
125 kind -> (CAssign (CReg ret_reg) amode)
127 performReturn assign_possibly (mkPrimReturnCode doc)
129 mkPrimReturnCode :: SDoc -- Debugging only
132 mkPrimReturnCode doc UpdateCode = pprPanic "mkPrimReturnCode: Upd" doc
133 mkPrimReturnCode doc sequel = sequelToAmode sequel `thenFC` \ dest_amode ->
134 absC (CReturn dest_amode DirectReturn)
135 -- Direct, no vectoring
137 -- Constructor is built on the heap; Node is set.
138 -- All that remains is
139 -- (a) to set TagReg, if necessary
140 -- (c) to do the right sort of jump.
142 mkStaticAlgReturnCode :: DataCon -- The constructor
143 -> Sequel -- where to return to
146 mkStaticAlgReturnCode con sequel
147 = -- Generate profiling code if necessary
148 (case return_convention of
149 VectoredReturn sz -> profCtrC SLIT("TICK_VEC_RETURN") [mkIntCLit sz]
153 -- Set tag if necessary
154 -- This is done by a macro, because if we are short of registers
155 -- we don't set TagReg; instead the continuation gets the tag
156 -- by indexing off the info ptr
157 (case return_convention of
159 UnvectoredReturn no_of_constrs
161 -> absC (CMacroStmt SET_TAG [mkIntCLit zero_indexed_tag])
166 -- Generate the right jump or return
168 UpdateCode -> -- Ha! We can go direct to the update code,
169 -- (making sure to jump to the *correct* update
171 absC (CReturn (CLbl mkUpdEntryLabel CodePtrRep)
174 CaseAlts _ (Just (alts, _)) -> -- Ho! We know the constructor so
175 -- we can go right to the alternative
177 case assocMaybe alts tag of
178 Just (alt_absC, join_lbl) ->
179 absC (CJump (CLbl join_lbl CodePtrRep))
180 Nothing -> panic "mkStaticAlgReturnCode: default"
181 -- The Nothing case should never happen;
182 -- it's the subject of a wad of special-case
183 -- code in cgReturnCon
185 -- can't be a SeqFrame, because we're returning a constructor
187 other -> -- OnStack, or (CaseAlts ret_amode Nothing)
188 sequelToAmode sequel `thenFC` \ ret_amode ->
189 absC (CReturn ret_amode return_info)
194 tycon = dataConTyCon con
195 return_convention = ctrlReturnConvAlg tycon
196 zero_indexed_tag = tag - fIRST_TAG -- Adjust tag to be zero-indexed
197 -- cf AbsCUtils.mkAlgAltsCSwitch
200 case return_convention of
201 UnvectoredReturn _ -> DirectReturn
202 VectoredReturn _ -> StaticVectoredReturn zero_indexed_tag
204 mkUnboxedTupleReturnCode :: Sequel -> Code
205 mkUnboxedTupleReturnCode sequel
207 -- can't update with an unboxed tuple!
208 UpdateCode -> panic "mkUnboxedTupleReturnCode"
210 CaseAlts _ (Just ([(_,(alt_absC,join_lbl))], _)) ->
211 absC (CJump (CLbl join_lbl CodePtrRep))
213 -- can't be a SeqFrame
215 other -> -- OnStack, or (CaseAlts ret_amode something)
216 sequelToAmode sequel `thenFC` \ ret_amode ->
217 absC (CReturn ret_amode DirectReturn)
219 -- This function is used by PrimOps that return enumerated types (i.e.
220 -- all the comparison operators).
222 mkDynamicAlgReturnCode :: TyCon -> CAddrMode -> Sequel -> Code
224 mkDynamicAlgReturnCode tycon dyn_tag sequel
225 = case ctrlReturnConvAlg tycon of
228 profCtrC SLIT("TICK_VEC_RETURN") [mkIntCLit sz] `thenC`
229 sequelToAmode sequel `thenFC` \ ret_addr ->
230 absC (CReturn ret_addr (DynamicVectoredReturn dyn_tag))
232 UnvectoredReturn no_of_constrs ->
234 -- Set tag if necessary
235 -- This is done by a macro, because if we are short of registers
236 -- we don't set TagReg; instead the continuation gets the tag
237 -- by indexing off the info ptr
238 (if no_of_constrs > 1 then
239 absC (CMacroStmt SET_TAG [dyn_tag])
245 sequelToAmode sequel `thenFC` \ ret_addr ->
246 -- Generate the right jump or return
247 absC (CReturn ret_addr DirectReturn)
251 performReturn :: AbstractC -- Simultaneous assignments to perform
252 -> (Sequel -> Code) -- The code to execute to actually do
253 -- the return, given an addressing mode
254 -- for the return address
257 -- this is just a special case of doTailCall, later.
258 performReturn sim_assts finish_code
259 = getEndOfBlockInfo `thenFC` \ eob@(EndOfBlockInfo args_sp sequel) ->
261 -- Do the simultaneous assignments,
262 doSimAssts sim_assts `thenC`
264 -- push a return address if necessary
265 -- (after the assignments above, in case we clobber a live
267 pushReturnAddress eob `thenC`
269 -- Adjust stack pointer
270 adjustRealSp args_sp `thenC`
273 finish_code sequel -- "sequel" is `robust' in that it doesn't
274 -- depend on stk-ptr values
277 Returning unboxed tuples. This is mainly to support _ccall_GC_, where
278 we want to do things in a slightly different order to normal:
280 - push return address
281 - adjust stack pointer
283 - assign regs for unboxed tuple (usually just R1 = r)
284 - return to continuation
286 The return address (i.e. stack frame) must be on the stack before
287 doing the call in case the call ends up in the garbage collector.
289 Sadly, the information about the continuation is lost after we push it
290 (in order to avoid pushing it again), so we end up doing a needless
291 indirect jump (ToDo).
294 returnUnboxedTuple :: [CAddrMode] -> Code -> Code
295 returnUnboxedTuple amodes before_jump
296 = getEndOfBlockInfo `thenFC` \ eob@(EndOfBlockInfo args_sp sequel) ->
298 -- push a return address if necessary
299 pushReturnAddress eob `thenC`
300 setEndOfBlockInfo (EndOfBlockInfo args_sp (OnStack args_sp)) (
302 -- Adjust stack pointer
303 adjustRealSp args_sp `thenC`
307 let (ret_regs, leftovers) = assignRegs [] (map getAmodeRep amodes)
310 doTailCall amodes ret_regs
311 mkUnboxedTupleReturnCode
312 (length leftovers) {- fast args arity -}
313 AbsCNop {-no pending assigments-}
314 Nothing {-not a let-no-escape-}
315 False {-node doesn't point-}
320 performTailCall :: Id -- Function
324 performTailCall fun args
325 = -- Get all the info we have about the function and args and go on to
327 getCAddrModeAndInfo fun `thenFC` \ (fun_amode, lf_info) ->
328 getArgAmodes args `thenFC` \ arg_amodes ->
331 fun fun_amode lf_info arg_amodes
332 AbsCNop {- No pending assignments -}
335 -- generating code for a tail call to a function (or closure)
337 tailCallFun :: Id -> CAddrMode -- Function and its amode
338 -> LambdaFormInfo -- Info about the function
339 -> [CAddrMode] -- Arguments
341 -> AbstractC -- Pending simultaneous assignments
342 -- *** GUARANTEED to contain only stack
345 -- In ptic, we don't need to look in
346 -- here to discover all live regs
350 tailCallFun fun fun_amode lf_info arg_amodes pending_assts
351 = nodeMustPointToIt lf_info `thenFC` \ node_points ->
352 getEntryConvention (idName fun) lf_info
353 (map getAmodeRep arg_amodes) `thenFC` \ entry_conv ->
356 = if node_points then
357 CAssign (CReg node) fun_amode
361 (arg_regs, finish_code, arity)
365 profCtrC SLIT("TICK_ENT_VIA_NODE") [] `thenC`
366 absC (CJump (CMacroExpr CodePtrRep ENTRY_CODE
367 [CVal (nodeRel 0) DataPtrRep]))
369 StdEntry lbl -> ([], absC (CJump (CLbl lbl CodePtrRep)), 0)
370 DirectEntry lbl arity regs ->
371 (regs, absC (CJump (CLbl lbl CodePtrRep)),
374 -- set up for a let-no-escape if necessary
375 join_sp = case fun_amode of
376 CJoinPoint sp -> Just sp
379 doTailCall arg_amodes arg_regs (const finish_code) arity
380 (mkAbstractCs [node_asst,pending_assts]) join_sp node_points
383 -- this generic tail call code is used for both function calls and returns.
386 :: [CAddrMode] -- args to pass to function
387 -> [MagicId] -- registers to use
388 -> (Sequel->Code) -- code to perform jump
389 -> Int -- number of "fast" stack arguments
390 -> AbstractC -- pending assignments
391 -> Maybe VirtualSpOffset -- sp offset to trim stack to
392 -> Bool -- node points to the closure to enter
395 doTailCall arg_amodes arg_regs finish_code arity pending_assts
396 maybe_join_sp node_points
397 = getEndOfBlockInfo `thenFC` \ eob@(EndOfBlockInfo args_sp sequel) ->
400 no_of_args = length arg_amodes
402 (reg_arg_amodes, stk_arg_amodes) = splitAt (length arg_regs) arg_amodes
403 -- We get some stk_arg_amodes if (a) no regs, or
404 -- (b) args beyond arity
407 = mkAbstractCs (zipWithEqual "assign_to_reg2"
408 assign_to_reg arg_regs reg_arg_amodes)
410 assign_to_reg reg_id amode = CAssign (CReg reg_id) amode
412 join_sp = case maybe_join_sp of
413 Just sp -> ASSERT(not (args_sp > sp)) sp
414 -- If ASSERTion fails: Oops: the join point has *lower*
415 -- stack ptrs than the continuation Note that we take
416 -- the Sp point without the return address here. The
417 -- return address is put on by the let-no-escapey thing
421 (fast_stk_amodes, tagged_stk_amodes) =
422 splitAt arity stk_arg_amodes
424 -- We can omit tags on the arguments passed to the fast entry point,
425 -- but we have to be careful to fill in the tags on any *extra*
426 -- arguments we're about to push on the stack.
428 mkTaggedStkAmodes join_sp tagged_stk_amodes `thenFC`
429 \ (fast_sp, tagged_arg_assts, tag_assts) ->
431 mkTaggedStkAmodes fast_sp fast_stk_amodes `thenFC`
432 \ (final_sp, fast_arg_assts, _) ->
434 -- adjust the high-water mark if necessary
435 adjustStackHW final_sp `thenC`
437 -- The stack space for the pushed return addess,
438 -- with any args pushed on top, is recorded in final_sp.
440 -- Do the simultaneous assignments,
441 doSimAssts (mkAbstractCs [pending_assts,
447 -- push a return address if necessary
448 -- (after the assignments above, in case we clobber a live
450 pushReturnAddress eob `thenC`
452 -- Final adjustment of stack pointer
453 adjustRealSp final_sp `thenC`
455 -- Now decide about semi-tagging
457 semi_tagging_on = opt_DoSemiTagging
459 case (semi_tagging_on, arg_amodes, node_points, sequel) of
462 -- *************** The semi-tagging case ***************
464 {- XXX leave this out for now.
465 ( True, [], True, CaseAlts _ (Just (st_alts, maybe_deflt_join_details))) ->
467 -- Whoppee! Semi-tagging rules OK!
468 -- (a) semi-tagging is switched on
469 -- (b) there are no arguments,
470 -- (c) Node points to the closure
471 -- (d) we have a case-alternative sequel with
472 -- some visible alternatives
474 -- Why is test (c) necessary?
475 -- Usually Node will point to it at this point, because we're
476 -- scrutinsing something which is either a thunk or a
478 -- But not always! The example I came across is when we have
479 -- a top-level Double:
481 -- ... (case lit.3 of ...) ...
482 -- Here, lit.3 is built as a re-entrant thing, which you must enter.
483 -- (OK, the simplifier should have eliminated this, but it's
484 -- easy to deal with the case anyway.)
486 join_details_to_code (load_regs_and_profiling_code, join_lbl)
487 = load_regs_and_profiling_code `mkAbsCStmts`
488 CJump (CLbl join_lbl CodePtrRep)
490 semi_tagged_alts = [ (mkMachInt (fromInt (tag - fIRST_TAG)),
491 join_details_to_code join_details)
492 | (tag, join_details) <- st_alts
496 -- Enter Node (we know infoptr will have the info ptr in it)!
498 CCallProfCtrMacro SLIT("RET_SEMI_FAILED")
499 [CMacroExpr IntRep INFO_TAG [CReg infoptr]],
500 CJump (CMacroExpr CodePtrRep ENTRY_CODE [CReg infoptr]) ]
504 CAssign (CReg infoptr)
505 (CVal (NodeRel zeroOff) DataPtrRep),
507 case maybe_deflt_join_details of
509 CSwitch (CMacroExpr IntRep INFO_TAG [CReg infoptr])
513 CSwitch (CMacroExpr IntRep EVAL_TAG [CReg infoptr])
514 [(mkMachInt 0, enter_jump)]
516 (CMacroExpr IntRep INFO_TAG [CReg infoptr])
518 (join_details_to_code details))
523 -- *************** The non-semi-tagging case ***************
525 other -> finish_code sequel
528 %************************************************************************
530 \subsection[tailCallPrimOp]{@tailCallPrimOp@}
532 %************************************************************************
535 tailCallPrimOp :: PrimOp -> [StgArg] -> Code
536 tailCallPrimOp op args =
537 -- we're going to perform a normal-looking tail call,
538 -- except that *all* the arguments will be in registers.
539 getArgAmodes args `thenFC` \ arg_amodes ->
540 let (arg_regs, leftovers) = assignAllRegs [] (map getAmodeRep arg_amodes)
542 ASSERT(null leftovers) -- no stack-resident args
543 doTailCall arg_amodes arg_regs
544 (const (absC (CJump (CLbl (mkRtsPrimOpLabel op) CodePtrRep))))
545 0 {- arity shouldn't matter, all args in regs -}
546 AbsCNop {- no pending assignments -}
547 Nothing {- not a let-no-escape -}
548 False {- node doesn't point -}
551 %************************************************************************
553 \subsection[doSimAssts]{@doSimAssts@}
555 %************************************************************************
557 @doSimAssts@ happens at the end of every block of code.
558 They are separate because we sometimes do some jiggery-pokery in between.
561 doSimAssts :: AbstractC -> Code
564 = absC (CSimultaneous sim_assts)
567 %************************************************************************
569 \subsection[retAddr]{@Return Addresses@}
571 %************************************************************************
573 We always push the return address just before performing a tail call
574 or return. The reason we leave it until then is because the stack
575 slot that the return address is to go into might contain something
578 If the end of block info is CaseAlts, then we're in the scrutinee of a
579 case expression and the return address is still to be pushed.
581 There are cases where it doesn't look necessary to push the return
582 address: for example, just before doing a return to a known
583 continuation. However, the continuation will expect to find the
584 return address on the stack in case it needs to do a heap check.
587 pushReturnAddress :: EndOfBlockInfo -> Code
588 pushReturnAddress (EndOfBlockInfo args_sp sequel@(CaseAlts amode _)) =
589 getSpRelOffset args_sp `thenFC` \ sp_rel ->
590 absC (CAssign (CVal sp_rel RetRep) amode)
591 pushReturnAddress (EndOfBlockInfo args_sp sequel@(SeqFrame amode _)) =
592 pushSeqFrame args_sp `thenFC` \ ret_sp ->
593 getSpRelOffset ret_sp `thenFC` \ sp_rel ->
594 absC (CAssign (CVal sp_rel RetRep) amode)
595 pushReturnAddress _ = nopC