[project @ 2003-07-02 13:12:33 by simonpj]
[ghc-hetmet.git] / ghc / compiler / codeGen / CgCon.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-1998
3 %
4 \section[CgCon]{Code generation for constructors}
5
6 This module provides the support code for @StgToAbstractC@ to deal
7 with {\em constructors} on the RHSs of let(rec)s.  See also
8 @CgClosure@, which deals with closures.
9
10 \begin{code}
11 module CgCon (
12         cgTopRhsCon, buildDynCon,
13         bindConArgs, bindUnboxedTupleComponents,
14         cgReturnDataCon
15     ) where
16
17 #include "HsVersions.h"
18
19 import CgMonad
20 import AbsCSyn
21 import StgSyn
22
23 import AbsCUtils        ( getAmodeRep )
24 import CgBindery        ( getArgAmodes, bindNewToNode,
25                           bindArgsToRegs, 
26                           idInfoToAmode, stableAmodeIdInfo,
27                           heapIdInfo, CgIdInfo, bindNewToStack
28                         )
29 import CgStackery       ( mkVirtStkOffsets, freeStackSlots, updateFrameSize )
30 import CgUsages         ( getRealSp, getVirtSp, setRealAndVirtualSp,
31                           getSpRelOffset )
32 import CgRetConv        ( assignRegs )
33 import Constants        ( mAX_INTLIKE, mIN_INTLIKE, mAX_CHARLIKE, mIN_CHARLIKE,
34                           mIN_UPD_SIZE )
35 import CgHeapery        ( allocDynClosure, inPlaceAllocDynClosure )
36 import CgTailCall       ( performReturn, mkStaticAlgReturnCode,
37                           returnUnboxedTuple )
38 import CLabel           ( mkClosureLabel )
39 import ClosureInfo      ( mkConLFInfo, mkLFArgument, layOutDynConstr, 
40                           layOutStaticConstr, closureSize, mkStaticClosure
41                         )
42 import CostCentre       ( currentOrSubsumedCCS, dontCareCCS, CostCentreStack,
43                           currentCCS )
44 import DataCon          ( DataCon, dataConTag, 
45                           isUnboxedTupleCon, isNullaryDataCon, dataConWorkId, 
46                           dataConName, dataConRepArity
47                         )
48 import Id               ( Id, idName, idPrimRep, isDeadBinder )
49 import Literal          ( Literal(..) )
50 import PrelInfo         ( maybeCharLikeCon, maybeIntLikeCon )
51 import PrimRep          ( PrimRep(..), isFollowableRep )
52 import Unique           ( Uniquable(..) )
53 import Util
54 import Outputable
55
56 import List             ( partition )
57 \end{code}
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection[toplevel-constructors]{Top-level constructors}
62 %*                                                                      *
63 %************************************************************************
64
65 \begin{code}
66 cgTopRhsCon :: Id               -- Name of thing bound to this RHS
67             -> DataCon          -- Id
68             -> [StgArg]         -- Args
69             -> FCode (Id, CgIdInfo)
70 cgTopRhsCon id con args
71   = ASSERT( not (isDllConApp con args) )        -- checks for litlit args too
72     ASSERT( args `lengthIs` dataConRepArity con )
73
74         -- LAY IT OUT
75     getArgAmodes args           `thenFC` \ amodes ->
76
77     let
78         name          = idName id
79         lf_info       = mkConLFInfo con
80         closure_label = mkClosureLabel name
81         (closure_info, amodes_w_offsets) 
82                 = layOutStaticConstr con getAmodeRep amodes
83         caffy = any stgArgHasCafRefs args
84     in
85
86         -- BUILD THE OBJECT
87     absC (mkStaticClosure
88             closure_label
89             closure_info
90             dontCareCCS                 -- because it's static data
91             (map fst amodes_w_offsets)  -- Sorted into ptrs first, then nonptrs
92             caffy                       -- has CAF refs
93           )                                     `thenC`
94                 -- NOTE: can't use idCafInfo instead of nonEmptySRT above,
95                 -- because top-level constructors that were floated by
96                 -- CorePrep don't have CafInfo attached.  The SRT is more
97                 -- reliable.
98
99         -- RETURN
100     returnFC (id, stableAmodeIdInfo id (CLbl closure_label PtrRep) lf_info)
101 \end{code}
102
103 %************************************************************************
104 %*                                                                      *
105 %* non-top-level constructors                                           *
106 %*                                                                      *
107 %************************************************************************
108 \subsection[code-for-constructors]{The code for constructors}
109
110 \begin{code}
111 buildDynCon :: Id               -- Name of the thing to which this constr will
112                                 -- be bound
113             -> CostCentreStack  -- Where to grab cost centre from;
114                                 -- current CCS if currentOrSubsumedCCS
115             -> DataCon          -- The data constructor
116             -> [CAddrMode]      -- Its args
117             -> FCode CgIdInfo   -- Return details about how to find it
118
119 -- We used to pass a boolean indicating whether all the
120 -- args were of size zero, so we could use a static
121 -- construtor; but I concluded that it just isn't worth it.
122 -- Now I/O uses unboxed tuples there just aren't any constructors
123 -- with all size-zero args.
124 --
125 -- The reason for having a separate argument, rather than looking at
126 -- the addr modes of the args is that we may be in a "knot", and
127 -- premature looking at the args will cause the compiler to black-hole!
128 \end{code}
129
130 First we deal with the case of zero-arity constructors.  Now, they
131 will probably be unfolded, so we don't expect to see this case much,
132 if at all, but it does no harm, and sets the scene for characters.
133
134 In the case of zero-arity constructors, or, more accurately, those
135 which have exclusively size-zero (VoidRep) args, we generate no code
136 at all.
137
138 \begin{code}
139 buildDynCon binder cc con []
140   = returnFC (stableAmodeIdInfo binder
141                                 (CLbl (mkClosureLabel (dataConName con)) PtrRep)
142                                 (mkConLFInfo con))
143 \end{code}
144
145 The following three paragraphs about @Char@-like and @Int@-like
146 closures are obsolete, but I don't understand the details well enough
147 to properly word them, sorry. I've changed the treatment of @Char@s to
148 be analogous to @Int@s: only a subset is preallocated, because @Char@
149 has now 31 bits. Only literals are handled here. -- Qrczak
150
151 Now for @Char@-like closures.  We generate an assignment of the
152 address of the closure to a temporary.  It would be possible simply to
153 generate no code, and record the addressing mode in the environment,
154 but we'd have to be careful if the argument wasn't a constant --- so
155 for simplicity we just always asssign to a temporary.
156
157 Last special case: @Int@-like closures.  We only special-case the
158 situation in which the argument is a literal in the range
159 @mIN_INTLIKE@..@mAX_INTLILKE@.  NB: for @Char@-like closures we can
160 work with any old argument, but for @Int@-like ones the argument has
161 to be a literal.  Reason: @Char@ like closures have an argument type
162 which is guaranteed in range.
163
164 Because of this, we use can safely return an addressing mode.
165
166 \begin{code}
167 buildDynCon binder cc con [arg_amode]
168   | maybeIntLikeCon con && in_range_int_lit arg_amode
169   = returnFC (stableAmodeIdInfo binder (CIntLike arg_amode) (mkConLFInfo con))
170   where
171     in_range_int_lit (CLit (MachInt val)) = val <= mAX_INTLIKE && val >= mIN_INTLIKE
172     in_range_int_lit _other_amode         = False
173
174 buildDynCon binder cc con [arg_amode]
175   | maybeCharLikeCon con && in_range_char_lit arg_amode
176   = returnFC (stableAmodeIdInfo binder (CCharLike arg_amode) (mkConLFInfo con))
177   where
178     in_range_char_lit (CLit (MachChar val)) = val <= mAX_CHARLIKE && val >= mIN_CHARLIKE
179     in_range_char_lit _other_amode          = False
180 \end{code}
181
182 Now the general case.
183
184 \begin{code}
185 buildDynCon binder ccs con args
186   = allocDynClosure closure_info use_cc blame_cc amodes_w_offsets `thenFC` \ hp_off ->
187     returnFC (heapIdInfo binder hp_off lf_info)
188   where
189     lf_info = mkConLFInfo con
190
191     (closure_info, amodes_w_offsets) = layOutDynConstr con getAmodeRep args
192
193     use_cc      -- cost-centre to stick in the object
194       = if currentOrSubsumedCCS ccs
195         then CReg CurCostCentre
196         else mkCCostCentreStack ccs
197
198     blame_cc = use_cc -- cost-centre on which to blame the alloc (same)
199 \end{code}
200
201
202 %************************************************************************
203 %*                                                                      *
204 %* constructor-related utility function:                                *
205 %*              bindConArgs is called from cgAlt of a case              *
206 %*                                                                      *
207 %************************************************************************
208 \subsection[constructor-utilities]{@bindConArgs@: constructor-related utility}
209
210 @bindConArgs@ $con args$ augments the environment with bindings for the
211 binders $args$, assuming that we have just returned from a @case@ which
212 found a $con$.
213
214 \begin{code}
215 bindConArgs 
216         :: DataCon -> [Id]              -- Constructor and args
217         -> Code
218
219 bindConArgs con args
220   = ASSERT(not (isUnboxedTupleCon con))
221     mapCs bind_arg args_w_offsets
222    where
223      bind_arg (arg, offset) = bindNewToNode arg offset (mkLFArgument arg)
224      (_, args_w_offsets)    = layOutDynConstr con idPrimRep args
225 \end{code}
226
227 Unboxed tuples are handled slightly differently - the object is
228 returned in registers and on the stack instead of the heap.
229
230 \begin{code}
231 bindUnboxedTupleComponents
232         :: [Id]                         -- Aargs
233         -> FCode ([MagicId],            -- Regs assigned
234                   Int,                  -- Number of pointer stack slots
235                   Int,                  -- Number of non-pointer stack slots
236                   VirtualSpOffset)      -- Offset of return address slot
237                                         -- (= realSP on entry)
238
239 bindUnboxedTupleComponents args
240  =      -- Assign as many components as possible to registers
241     let (arg_regs, _leftovers) = assignRegs [] (map idPrimRep args)
242         (reg_args, stk_args)   = splitAtList arg_regs args
243
244         -- separate the rest of the args into pointers and non-pointers
245         (ptr_args, nptr_args) = 
246            partition (isFollowableRep . idPrimRep) stk_args
247     in
248   
249     -- Allocate the rest on the stack
250     -- The real SP points to the return address, above which any 
251     -- leftover unboxed-tuple components will be allocated
252     getVirtSp `thenFC` \ vsp ->
253     getRealSp `thenFC` \ rsp ->
254     let 
255         (ptr_sp,  ptr_offsets)  = mkVirtStkOffsets rsp    idPrimRep ptr_args
256         (nptr_sp, nptr_offsets) = mkVirtStkOffsets ptr_sp idPrimRep nptr_args
257         ptrs  = ptr_sp - rsp
258         nptrs = nptr_sp - ptr_sp
259     in
260
261     -- The stack pointer points to the last stack-allocated component
262     setRealAndVirtualSp nptr_sp                 `thenC`
263
264     -- We have just allocated slots starting at real SP + 1, and set the new
265     -- virtual SP to the topmost allocated slot.  
266     -- If the virtual SP started *below* the real SP, we've just jumped over
267     -- some slots that won't be in the free-list, so put them there
268     -- This commonly happens because we've freed the return-address slot
269     -- (trimming back the virtual SP), but the real SP still points to that slot
270     freeStackSlots [vsp+1,vsp+2 .. rsp]         `thenC`
271
272     bindArgsToRegs reg_args arg_regs            `thenC`
273     mapCs bindNewToStack ptr_offsets            `thenC`
274     mapCs bindNewToStack nptr_offsets           `thenC`
275
276     returnFC (arg_regs, ptrs, nptrs, rsp)
277 \end{code}
278
279 %************************************************************************
280 %*                                                                      *
281 \subsubsection[CgRetConv-cgReturnDataCon]{Actually generate code for a constructor return}
282 %*                                                                      *
283 %************************************************************************
284
285
286 Note: it's the responsibility of the @cgReturnDataCon@ caller to be
287 sure the @amodes@ passed don't conflict with each other.
288 \begin{code}
289 cgReturnDataCon :: DataCon -> [CAddrMode] -> Code
290
291 cgReturnDataCon con amodes
292   = ASSERT( amodes `lengthIs` dataConRepArity con )
293     getEndOfBlockInfo   `thenFC` \ (EndOfBlockInfo args_sp sequel) ->
294
295     case sequel of
296
297       CaseAlts _ (Just (alts, Just (deflt_bndr, (_,deflt_lbl)))) False
298         | not (dataConTag con `is_elem` map fst alts)
299         ->
300                 -- Special case!  We're returning a constructor to the default case
301                 -- of an enclosing case.  For example:
302                 --
303                 --      case (case e of (a,b) -> C a b) of
304                 --        D x -> ...
305                 --        y   -> ...<returning here!>...
306                 --
307                 -- In this case,
308                 --      if the default is a non-bind-default (ie does not use y),
309                 --      then we should simply jump to the default join point;
310
311                 if isDeadBinder deflt_bndr
312                 then performReturn AbsCNop {- No reg assts -} jump_to_join_point
313                 else build_it_then jump_to_join_point
314         where
315           is_elem = isIn "cgReturnDataCon"
316           jump_to_join_point sequel = absC (CJump (CLbl deflt_lbl CodePtrRep))
317                 -- Ignore the sequel: we've already looked at it above
318
319         -- If the sequel is an update frame, we might be able to
320         -- do update in place...
321       UpdateCode
322         |  not (isNullaryDataCon con)  -- no nullary constructors, please
323         && not (any isFollowableRep (map getAmodeRep amodes))
324                                         -- no ptrs please (generational gc...)
325         && closureSize closure_info <= mIN_UPD_SIZE
326                                         -- don't know the real size of the
327                                         -- thunk, so assume mIN_UPD_SIZE
328
329         ->      -- get a new temporary and make it point to the updatee
330            let 
331                 uniq = getUnique con
332                 temp = CTemp uniq PtrRep 
333            in
334
335            profCtrC FSLIT("TICK_UPD_CON_IN_PLACE") 
336                         [mkIntCLit (length amodes)] `thenC`
337
338            getSpRelOffset args_sp                       `thenFC` \ sp_rel ->
339            absC (CAssign temp 
340                     (CMacroExpr PtrRep UPD_FRAME_UPDATEE [CAddr sp_rel])) 
341                 `thenC`
342
343                 -- stomp all over it with the new constructor
344            inPlaceAllocDynClosure closure_info temp (CReg CurCostCentre) stuff 
345                 `thenC`
346
347                 -- set Node to point to the closure being returned
348                 -- (can't be done earlier: node might conflict with amodes)
349            absC (CAssign (CReg node) temp) `thenC`
350
351                 -- pop the update frame off the stack, and do the proper
352                 -- return.
353            let new_sp = args_sp - updateFrameSize in
354            setEndOfBlockInfo (EndOfBlockInfo new_sp (OnStack new_sp)) $
355            performReturn (AbsCNop) (mkStaticAlgReturnCode con)
356
357         where
358            (closure_info, stuff) = layOutDynConstr con getAmodeRep amodes
359
360       other_sequel      -- The usual case
361           | isUnboxedTupleCon con -> returnUnboxedTuple amodes
362           | otherwise ->             build_it_then (mkStaticAlgReturnCode con)
363
364   where
365     move_to_reg :: CAddrMode -> MagicId -> AbstractC
366     move_to_reg src_amode dest_reg = CAssign (CReg dest_reg) src_amode
367
368     build_it_then return =
369                 -- BUILD THE OBJECT IN THE HEAP
370                 -- The first "con" says that the name bound to this
371                 -- closure is "con", which is a bit of a fudge, but it only
372                 -- affects profiling
373
374                 -- This Id is also used to get a unique for a
375                 -- temporary variable, if the closure is a CHARLIKE.
376                 -- funnily enough, this makes the unique always come
377                 -- out as '54' :-)
378           buildDynCon (dataConWorkId con) currentCCS con amodes `thenFC` \ idinfo ->
379           idInfoToAmode PtrRep idinfo                           `thenFC` \ amode ->
380
381
382                 -- RETURN
383           profCtrC FSLIT("TICK_RET_NEW") [mkIntCLit (length amodes)] `thenC`
384           -- could use doTailCall here.
385           performReturn (move_to_reg amode node) return
386 \end{code}