The final batch of changes for the new coercion representation
[ghc-hetmet.git] / compiler / stgSyn / CoreToStg.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[CoreToStg]{Converts Core to STG Syntax}
5
6 And, as we have the info in hand, we may convert some lets to
7 let-no-escapes.
8
9 \begin{code}
10 module CoreToStg ( coreToStg, coreExprToStg ) where
11
12 #include "HsVersions.h"
13
14 import CoreSyn
15 import CoreUtils        ( exprType, findDefault )
16 import CoreArity        ( manifestArity )
17 import StgSyn
18
19 import Type
20 import TyCon
21 import MkId             ( coercionTokenId )
22 import Id
23 import IdInfo
24 import DataCon
25 import CostCentre       ( noCCS )
26 import VarSet
27 import VarEnv
28 import Maybes           ( maybeToBool )
29 import Name             ( getOccName, isExternalName, nameOccName )
30 import OccName          ( occNameString, occNameFS )
31 import BasicTypes       ( Arity )
32 import Module
33 import Outputable
34 import MonadUtils
35 import FastString
36 import Util
37 import ForeignCall
38 import PrimOp           ( PrimCall(..) )
39 \end{code}
40
41 %************************************************************************
42 %*                                                                      *
43 \subsection[live-vs-free-doc]{Documentation}
44 %*                                                                      *
45 %************************************************************************
46
47 (There is other relevant documentation in codeGen/CgLetNoEscape.)
48
49 The actual Stg datatype is decorated with {\em live variable}
50 information, as well as {\em free variable} information.  The two are
51 {\em not} the same.  Liveness is an operational property rather than a
52 semantic one.  A variable is live at a particular execution point if
53 it can be referred to {\em directly} again.  In particular, a dead
54 variable's stack slot (if it has one):
55 \begin{enumerate}
56 \item
57 should be stubbed to avoid space leaks, and
58 \item
59 may be reused for something else.
60 \end{enumerate}
61
62 There ought to be a better way to say this.  Here are some examples:
63 \begin{verbatim}
64         let v = [q] \[x] -> e
65         in
66         ...v...  (but no q's)
67 \end{verbatim}
68
69 Just after the `in', v is live, but q is dead.  If the whole of that
70 let expression was enclosed in a case expression, thus:
71 \begin{verbatim}
72         case (let v = [q] \[x] -> e in ...v...) of
73                 alts[...q...]
74 \end{verbatim}
75 (ie @alts@ mention @q@), then @q@ is live even after the `in'; because
76 we'll return later to the @alts@ and need it.
77
78 Let-no-escapes make this a bit more interesting:
79 \begin{verbatim}
80         let-no-escape v = [q] \ [x] -> e
81         in
82         ...v...
83 \end{verbatim}
84 Here, @q@ is still live at the `in', because @v@ is represented not by
85 a closure but by the current stack state.  In other words, if @v@ is
86 live then so is @q@.  Furthermore, if @e@ mentions an enclosing
87 let-no-escaped variable, then {\em its} free variables are also live
88 if @v@ is.
89
90 %************************************************************************
91 %*                                                                      *
92 \subsection[caf-info]{Collecting live CAF info}
93 %*                                                                      *
94 %************************************************************************
95
96 In this pass we also collect information on which CAFs are live for
97 constructing SRTs (see SRT.lhs).
98
99 A top-level Id has CafInfo, which is
100
101         - MayHaveCafRefs, if it may refer indirectly to
102           one or more CAFs, or
103         - NoCafRefs if it definitely doesn't
104
105 The CafInfo has already been calculated during the CoreTidy pass.
106
107 During CoreToStg, we then pin onto each binding and case expression, a
108 list of Ids which represents the "live" CAFs at that point.  The meaning
109 of "live" here is the same as for live variables, see above (which is
110 why it's convenient to collect CAF information here rather than elsewhere).
111
112 The later SRT pass takes these lists of Ids and uses them to construct
113 the actual nested SRTs, and replaces the lists of Ids with (offset,length)
114 pairs.
115
116
117 Interaction of let-no-escape with SRTs   [Sept 01]
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119 Consider
120
121         let-no-escape x = ...caf1...caf2...
122         in
123         ...x...x...x...
124
125 where caf1,caf2 are CAFs.  Since x doesn't have a closure, we
126 build SRTs just as if x's defn was inlined at each call site, and
127 that means that x's CAF refs get duplicated in the overall SRT.
128
129 This is unlike ordinary lets, in which the CAF refs are not duplicated.
130
131 We could fix this loss of (static) sharing by making a sort of pseudo-closure
132 for x, solely to put in the SRTs lower down.
133
134
135 %************************************************************************
136 %*                                                                      *
137 \subsection[binds-StgVarInfo]{Setting variable info: top-level, binds, RHSs}
138 %*                                                                      *
139 %************************************************************************
140
141 \begin{code}
142 coreToStg :: PackageId -> [CoreBind] -> IO [StgBinding]
143 coreToStg this_pkg pgm
144   = return pgm'
145   where (_, _, pgm') = coreTopBindsToStg this_pkg emptyVarEnv pgm
146
147 coreExprToStg :: CoreExpr -> StgExpr
148 coreExprToStg expr
149   = new_expr where (new_expr,_,_) = initLne emptyVarEnv (coreToStgExpr expr)
150
151
152 coreTopBindsToStg
153     :: PackageId
154     -> IdEnv HowBound           -- environment for the bindings
155     -> [CoreBind]
156     -> (IdEnv HowBound, FreeVarsInfo, [StgBinding])
157
158 coreTopBindsToStg _        env [] = (env, emptyFVInfo, [])
159 coreTopBindsToStg this_pkg env (b:bs)
160   = (env2, fvs2, b':bs')
161   where
162         -- Notice the mutually-recursive "knot" here:
163         --   env accumulates down the list of binds,
164         --   fvs accumulates upwards
165         (env1, fvs2, b' ) = coreTopBindToStg this_pkg env fvs1 b
166         (env2, fvs1, bs') = coreTopBindsToStg this_pkg env1 bs
167
168 coreTopBindToStg
169         :: PackageId
170         -> IdEnv HowBound
171         -> FreeVarsInfo         -- Info about the body
172         -> CoreBind
173         -> (IdEnv HowBound, FreeVarsInfo, StgBinding)
174
175 coreTopBindToStg this_pkg env body_fvs (NonRec id rhs)
176   = let
177         env'      = extendVarEnv env id how_bound
178         how_bound = LetBound TopLet $! manifestArity rhs
179
180         (stg_rhs, fvs') =
181             initLne env $ do
182               (stg_rhs, fvs') <- coreToTopStgRhs this_pkg body_fvs (id,rhs)
183               return (stg_rhs, fvs')
184
185         bind = StgNonRec id stg_rhs
186     in
187     ASSERT2(consistentCafInfo id bind, ppr id )
188       -- NB: previously the assertion printed 'rhs' and 'bind'
189       --     as well as 'id', but that led to a black hole
190       --     where printing the assertion error tripped the
191       --     assertion again!
192     (env', fvs' `unionFVInfo` body_fvs, bind)
193
194 coreTopBindToStg this_pkg env body_fvs (Rec pairs)
195   = ASSERT( not (null pairs) )
196     let
197         binders = map fst pairs
198
199         extra_env' = [ (b, LetBound TopLet $! manifestArity rhs)
200                      | (b, rhs) <- pairs ]
201         env' = extendVarEnvList env extra_env'
202
203         (stg_rhss, fvs')
204           = initLne env' $ do
205                (stg_rhss, fvss') <- mapAndUnzipM (coreToTopStgRhs this_pkg body_fvs) pairs
206                let fvs' = unionFVInfos fvss'
207                return (stg_rhss, fvs')
208
209         bind = StgRec (zip binders stg_rhss)
210     in
211     ASSERT2(consistentCafInfo (head binders) bind, ppr binders)
212     (env', fvs' `unionFVInfo` body_fvs, bind)
213
214
215 -- Assertion helper: this checks that the CafInfo on the Id matches
216 -- what CoreToStg has figured out about the binding's SRT.  The
217 -- CafInfo will be exact in all cases except when CorePrep has
218 -- floated out a binding, in which case it will be approximate.
219 consistentCafInfo :: Id -> GenStgBinding Var Id -> Bool
220 consistentCafInfo id bind
221   = WARN( not (exact || is_sat_thing) , ppr id <+> ppr id_marked_caffy <+> ppr binding_is_caffy )
222     safe
223   where
224     safe  = id_marked_caffy || not binding_is_caffy
225     exact = id_marked_caffy == binding_is_caffy
226     id_marked_caffy  = mayHaveCafRefs (idCafInfo id)
227     binding_is_caffy = stgBindHasCafRefs bind
228     is_sat_thing = occNameFS (nameOccName (idName id)) == fsLit "sat"
229 \end{code}
230
231 \begin{code}
232 coreToTopStgRhs
233         :: PackageId
234         -> FreeVarsInfo         -- Free var info for the scope of the binding
235         -> (Id,CoreExpr)
236         -> LneM (StgRhs, FreeVarsInfo)
237
238 coreToTopStgRhs this_pkg scope_fv_info (bndr, rhs)
239   = do { (new_rhs, rhs_fvs, _) <- coreToStgExpr rhs
240        ; lv_info <- freeVarsToLiveVars rhs_fvs
241
242        ; let stg_rhs   = mkTopStgRhs this_pkg rhs_fvs (mkSRT lv_info) bndr_info new_rhs
243              stg_arity = stgRhsArity stg_rhs
244        ; return (ASSERT2( arity_ok stg_arity, mk_arity_msg stg_arity) stg_rhs,
245                  rhs_fvs) }
246   where
247     bndr_info = lookupFVInfo scope_fv_info bndr
248
249         -- It's vital that the arity on a top-level Id matches
250         -- the arity of the generated STG binding, else an importing
251         -- module will use the wrong calling convention
252         --      (Trac #2844 was an example where this happened)
253         -- NB1: we can't move the assertion further out without
254         --      blocking the "knot" tied in coreTopBindsToStg
255         -- NB2: the arity check is only needed for Ids with External
256         --      Names, because they are externally visible.  The CorePrep
257         --      pass introduces "sat" things with Local Names and does
258         --      not bother to set their Arity info, so don't fail for those
259     arity_ok stg_arity
260        | isExternalName (idName bndr) = id_arity == stg_arity
261        | otherwise                    = True
262     id_arity  = idArity bndr
263     mk_arity_msg stg_arity
264         = vcat [ppr bndr,
265                 ptext (sLit "Id arity:") <+> ppr id_arity,
266                 ptext (sLit "STG arity:") <+> ppr stg_arity]
267
268 mkTopStgRhs :: PackageId -> FreeVarsInfo
269             -> SRT -> StgBinderInfo -> StgExpr
270             -> StgRhs
271
272 mkTopStgRhs _ rhs_fvs srt binder_info (StgLam _ bndrs body)
273   = StgRhsClosure noCCS binder_info
274                   (getFVs rhs_fvs)
275                   ReEntrant
276                   srt
277                   bndrs body
278
279 mkTopStgRhs this_pkg _ _ _ (StgConApp con args)
280   | not (isDllConApp this_pkg con args)  -- Dynamic StgConApps are updatable
281   = StgRhsCon noCCS con args
282
283 mkTopStgRhs _ rhs_fvs srt binder_info rhs
284   = StgRhsClosure noCCS binder_info
285                   (getFVs rhs_fvs)
286                   Updatable
287                   srt
288                   [] rhs
289 \end{code}
290
291
292 -- ---------------------------------------------------------------------------
293 -- Expressions
294 -- ---------------------------------------------------------------------------
295
296 \begin{code}
297 coreToStgExpr
298         :: CoreExpr
299         -> LneM (StgExpr,       -- Decorated STG expr
300                  FreeVarsInfo,  -- Its free vars (NB free, not live)
301                  EscVarsSet)    -- Its escapees, a subset of its free vars;
302                                 -- also a subset of the domain of the envt
303                                 -- because we are only interested in the escapees
304                                 -- for vars which might be turned into
305                                 -- let-no-escaped ones.
306 \end{code}
307
308 The second and third components can be derived in a simple bottom up pass, not
309 dependent on any decisions about which variables will be let-no-escaped or
310 not.  The first component, that is, the decorated expression, may then depend
311 on these components, but it in turn is not scrutinised as the basis for any
312 decisions.  Hence no black holes.
313
314 \begin{code}
315 coreToStgExpr (Lit l)      = return (StgLit l, emptyFVInfo, emptyVarSet)
316 coreToStgExpr (Var v)      = coreToStgApp Nothing v               []
317 coreToStgExpr (Coercion _) = coreToStgApp Nothing coercionTokenId []
318
319 coreToStgExpr expr@(App _ _)
320   = coreToStgApp Nothing f args
321   where
322     (f, args) = myCollectArgs expr
323
324 coreToStgExpr expr@(Lam _ _)
325   = let
326         (args, body) = myCollectBinders expr
327         args'        = filterStgBinders args
328     in
329     extendVarEnvLne [ (a, LambdaBound) | a <- args' ] $ do
330     (body, body_fvs, body_escs) <- coreToStgExpr body
331     let
332         fvs             = args' `minusFVBinders` body_fvs
333         escs            = body_escs `delVarSetList` args'
334         result_expr | null args' = body
335                     | otherwise  = StgLam (exprType expr) args' body
336
337     return (result_expr, fvs, escs)
338
339 coreToStgExpr (Note (SCC cc) expr) = do
340     (expr2, fvs, escs) <- coreToStgExpr expr
341     return (StgSCC cc expr2, fvs, escs)
342
343 coreToStgExpr (Case (Var id) _bndr _ty [(DEFAULT,[],expr)])
344   | Just (TickBox m n) <- isTickBoxOp_maybe id = do
345     (expr2, fvs, escs) <- coreToStgExpr expr
346     return (StgTick m n expr2, fvs, escs)
347
348 coreToStgExpr (Note _ expr)
349   = coreToStgExpr expr
350
351 coreToStgExpr (Cast expr _)
352   = coreToStgExpr expr
353
354 -- Cases require a little more real work.
355
356 coreToStgExpr (Case scrut bndr _ alts) = do
357     (alts2, alts_fvs, alts_escs)
358        <- extendVarEnvLne [(bndr, LambdaBound)] $ do
359             (alts2, fvs_s, escs_s) <- mapAndUnzip3M vars_alt alts
360             return ( alts2,
361                      unionFVInfos fvs_s,
362                      unionVarSets escs_s )
363     let
364         -- Determine whether the default binder is dead or not
365         -- This helps the code generator to avoid generating an assignment
366         -- for the case binder (is extremely rare cases) ToDo: remove.
367         bndr' | bndr `elementOfFVInfo` alts_fvs = bndr
368               | otherwise                       = bndr `setIdOccInfo` IAmDead
369
370         -- Don't consider the default binder as being 'live in alts',
371         -- since this is from the point of view of the case expr, where
372         -- the default binder is not free.
373         alts_fvs_wo_bndr  = bndr `minusFVBinder` alts_fvs
374         alts_escs_wo_bndr = alts_escs `delVarSet` bndr
375
376     alts_lv_info <- freeVarsToLiveVars alts_fvs_wo_bndr
377
378         -- We tell the scrutinee that everything
379         -- live in the alts is live in it, too.
380     (scrut2, scrut_fvs, _scrut_escs, scrut_lv_info)
381        <- setVarsLiveInCont alts_lv_info $ do
382             (scrut2, scrut_fvs, scrut_escs) <- coreToStgExpr scrut
383             scrut_lv_info <- freeVarsToLiveVars scrut_fvs
384             return (scrut2, scrut_fvs, scrut_escs, scrut_lv_info)
385
386     return (
387       StgCase scrut2 (getLiveVars scrut_lv_info)
388                      (getLiveVars alts_lv_info)
389                      bndr'
390                      (mkSRT alts_lv_info)
391                      (mkStgAltType bndr alts)
392                      alts2,
393       scrut_fvs `unionFVInfo` alts_fvs_wo_bndr,
394       alts_escs_wo_bndr `unionVarSet` getFVSet scrut_fvs
395                 -- You might think we should have scrut_escs, not
396                 -- (getFVSet scrut_fvs), but actually we can't call, and
397                 -- then return from, a let-no-escape thing.
398       )
399   where
400     vars_alt (con, binders, rhs)
401       = let     -- Remove type variables
402             binders' = filterStgBinders binders
403         in
404         extendVarEnvLne [(b, LambdaBound) | b <- binders'] $ do
405         (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
406         let
407                 -- Records whether each param is used in the RHS
408             good_use_mask = [ b `elementOfFVInfo` rhs_fvs | b <- binders' ]
409
410         return ( (con, binders', good_use_mask, rhs2),
411                  binders' `minusFVBinders` rhs_fvs,
412                  rhs_escs `delVarSetList` binders' )
413                 -- ToDo: remove the delVarSet;
414                 -- since escs won't include any of these binders
415 \end{code}
416
417 Lets not only take quite a bit of work, but this is where we convert
418 then to let-no-escapes, if we wish.
419
420 (Meanwhile, we don't expect to see let-no-escapes...)
421 \begin{code}
422 coreToStgExpr (Let bind body) = do
423     (new_let, fvs, escs, _)
424        <- mfix (\ ~(_, _, _, no_binder_escapes) ->
425              coreToStgLet no_binder_escapes bind body
426           )
427
428     return (new_let, fvs, escs)
429
430 coreToStgExpr e = pprPanic "coreToStgExpr" (ppr e)
431 \end{code}
432
433 \begin{code}
434 mkStgAltType :: Id -> [CoreAlt] -> AltType
435 mkStgAltType bndr alts
436   = case splitTyConApp_maybe (repType (idType bndr)) of
437         Just (tc,_) | isUnboxedTupleTyCon tc -> UbxTupAlt tc
438                     | isUnLiftedTyCon tc     -> PrimAlt tc
439                     | isHiBootTyCon tc       -> look_for_better_tycon
440                     | isAlgTyCon tc          -> AlgAlt tc
441                     | otherwise              -> ASSERT2( _is_poly_alt_tycon tc, ppr tc )
442                                                 PolyAlt
443         Nothing                              -> PolyAlt
444
445   where
446    _is_poly_alt_tycon tc
447         =  isFunTyCon tc
448         || isPrimTyCon tc   -- "Any" is lifted but primitive
449         || isFamilyTyCon tc   -- Type family; e.g. arising from strict
450                             -- function application where argument has a
451                             -- type-family type
452
453    -- Sometimes, the TyCon is a HiBootTyCon which may not have any
454    -- constructors inside it.  Then we can get a better TyCon by
455    -- grabbing the one from a constructor alternative
456    -- if one exists.
457    look_for_better_tycon
458         | ((DataAlt con, _, _) : _) <- data_alts =
459                 AlgAlt (dataConTyCon con)
460         | otherwise =
461                 ASSERT(null data_alts)
462                 PolyAlt
463         where
464                 (data_alts, _deflt) = findDefault alts
465 \end{code}
466
467
468 -- ---------------------------------------------------------------------------
469 -- Applications
470 -- ---------------------------------------------------------------------------
471
472 \begin{code}
473 coreToStgApp
474          :: Maybe UpdateFlag            -- Just upd <=> this application is
475                                         -- the rhs of a thunk binding
476                                         --      x = [...] \upd [] -> the_app
477                                         -- with specified update flag
478         -> Id                           -- Function
479         -> [CoreArg]                    -- Arguments
480         -> LneM (StgExpr, FreeVarsInfo, EscVarsSet)
481
482
483 coreToStgApp _ f args = do
484     (args', args_fvs) <- coreToStgArgs args
485     how_bound <- lookupVarLne f
486
487     let
488         n_val_args       = valArgCount args
489         not_letrec_bound = not (isLetBound how_bound)
490         fun_fvs = singletonFVInfo f how_bound fun_occ
491             -- e.g. (f :: a -> int) (x :: a)
492             -- Here the free variables are "f", "x" AND the type variable "a"
493             -- coreToStgArgs will deal with the arguments recursively
494
495         -- Mostly, the arity info of a function is in the fn's IdInfo
496         -- But new bindings introduced by CoreSat may not have no
497         -- arity info; it would do us no good anyway.  For example:
498         --      let f = \ab -> e in f
499         -- No point in having correct arity info for f!
500         -- Hence the hasArity stuff below.
501         -- NB: f_arity is only consulted for LetBound things
502         f_arity   = stgArity f how_bound
503         saturated = f_arity <= n_val_args
504
505         fun_occ
506          | not_letrec_bound         = noBinderInfo      -- Uninteresting variable
507          | f_arity > 0 && saturated = stgSatOcc -- Saturated or over-saturated function call
508          | otherwise                = stgUnsatOcc       -- Unsaturated function or thunk
509
510         fun_escs
511          | not_letrec_bound      = emptyVarSet  -- Only letrec-bound escapees are interesting
512          | f_arity == n_val_args = emptyVarSet  -- A function *or thunk* with an exactly
513                                                 -- saturated call doesn't escape
514                                                 -- (let-no-escape applies to 'thunks' too)
515
516          | otherwise         = unitVarSet f     -- Inexact application; it does escape
517
518         -- At the moment of the call:
519
520         --  either the function is *not* let-no-escaped, in which case
521         --         nothing is live except live_in_cont
522         --      or the function *is* let-no-escaped in which case the
523         --         variables it uses are live, but still the function
524         --         itself is not.  PS.  In this case, the function's
525         --         live vars should already include those of the
526         --         continuation, but it does no harm to just union the
527         --         two regardless.
528
529         res_ty = exprType (mkApps (Var f) args)
530         app = case idDetails f of
531                 DataConWorkId dc | saturated -> StgConApp dc args'
532
533                 -- Some primitive operator that might be implemented as a library call.
534                 PrimOpId op      -> ASSERT( saturated )
535                                     StgOpApp (StgPrimOp op) args' res_ty
536
537                 -- A call to some primitive Cmm function.
538                 FCallId (CCall (CCallSpec (StaticTarget lbl (Just pkgId)) PrimCallConv _))
539                                  -> ASSERT( saturated )
540                                     StgOpApp (StgPrimCallOp (PrimCall lbl pkgId)) args' res_ty
541
542                 -- A regular foreign call.
543                 FCallId call     -> ASSERT( saturated )
544                                     StgOpApp (StgFCallOp call (idUnique f)) args' res_ty
545
546                 TickBoxOpId {}   -> pprPanic "coreToStg TickBox" $ ppr (f,args')
547                 _other           -> StgApp f args'
548         fvs = fun_fvs  `unionFVInfo` args_fvs
549         vars = fun_escs `unionVarSet` (getFVSet args_fvs)
550                                 -- All the free vars of the args are disqualified
551                                 -- from being let-no-escaped.
552
553     -- Forcing these fixes a leak in the code generator, noticed while
554     -- profiling for trac #4367
555     app `seq` fvs `seq` seqVarSet vars `seq` return (
556         app,
557         fvs,
558         vars
559      )
560
561
562
563 -- ---------------------------------------------------------------------------
564 -- Argument lists
565 -- This is the guy that turns applications into A-normal form
566 -- ---------------------------------------------------------------------------
567
568 coreToStgArgs :: [CoreArg] -> LneM ([StgArg], FreeVarsInfo)
569 coreToStgArgs []
570   = return ([], emptyFVInfo)
571
572 coreToStgArgs (Type _ : args) = do     -- Type argument
573     (args', fvs) <- coreToStgArgs args
574     return (args', fvs)
575
576 coreToStgArgs (Coercion _ : args)  -- Coercion argument; replace with place holder
577   = do { (args', fvs) <- coreToStgArgs args
578        ; return (StgVarArg coercionTokenId : args', fvs) }
579
580 coreToStgArgs (arg : args) = do         -- Non-type argument
581     (stg_args, args_fvs) <- coreToStgArgs args
582     (arg', arg_fvs, _escs) <- coreToStgExpr arg
583     let
584         fvs = args_fvs `unionFVInfo` arg_fvs
585         stg_arg = case arg' of
586                        StgApp v []      -> StgVarArg v
587                        StgConApp con [] -> StgVarArg (dataConWorkId con)
588                        StgLit lit       -> StgLitArg lit
589                        _                -> pprPanic "coreToStgArgs" (ppr arg)
590
591         -- WARNING: what if we have an argument like (v `cast` co)
592         --          where 'co' changes the representation type?
593         --          (This really only happens if co is unsafe.)
594         -- Then all the getArgAmode stuff in CgBindery will set the
595         -- cg_rep of the CgIdInfo based on the type of v, rather
596         -- than the type of 'co'.
597         -- This matters particularly when the function is a primop
598         -- or foreign call.
599         -- Wanted: a better solution than this hacky warning
600     let
601         arg_ty = exprType arg
602         stg_arg_ty = stgArgType stg_arg
603         bad_args = (isUnLiftedType arg_ty && not (isUnLiftedType stg_arg_ty))
604                 || (typePrimRep arg_ty /= typePrimRep stg_arg_ty)
605         -- In GHCi we coerce an argument of type BCO# (unlifted) to HValue (lifted),
606         -- and pass it to a function expecting an HValue (arg_ty).  This is ok because
607         -- we can treat an unlifted value as lifted.  But the other way round
608         -- we complain.
609         -- We also want to check if a pointer is cast to a non-ptr etc
610
611     WARN( bad_args, ptext (sLit "Dangerous-looking argument. Probable cause: bad unsafeCoerce#") $$ ppr arg )
612      return (stg_arg : stg_args, fvs)
613
614
615 -- ---------------------------------------------------------------------------
616 -- The magic for lets:
617 -- ---------------------------------------------------------------------------
618
619 coreToStgLet
620          :: Bool        -- True <=> yes, we are let-no-escaping this let
621          -> CoreBind    -- bindings
622          -> CoreExpr    -- body
623          -> LneM (StgExpr,      -- new let
624                   FreeVarsInfo, -- variables free in the whole let
625                   EscVarsSet,   -- variables that escape from the whole let
626                   Bool)         -- True <=> none of the binders in the bindings
627                                 -- is among the escaping vars
628
629 coreToStgLet let_no_escape bind body = do
630     (bind2, bind_fvs, bind_escs, bind_lvs,
631      body2, body_fvs, body_escs, body_lvs)
632        <- mfix $ \ ~(_, _, _, _, _, rec_body_fvs, _, _) -> do
633
634           -- Do the bindings, setting live_in_cont to empty if
635           -- we ain't in a let-no-escape world
636           live_in_cont <- getVarsLiveInCont
637           ( bind2, bind_fvs, bind_escs, bind_lv_info, env_ext)
638                 <- setVarsLiveInCont (if let_no_escape
639                                           then live_in_cont
640                                           else emptyLiveInfo)
641                                      (vars_bind rec_body_fvs bind)
642
643           -- Do the body
644           extendVarEnvLne env_ext $ do
645              (body2, body_fvs, body_escs) <- coreToStgExpr body
646              body_lv_info <- freeVarsToLiveVars body_fvs
647
648              return (bind2, bind_fvs, bind_escs, getLiveVars bind_lv_info,
649                      body2, body_fvs, body_escs, getLiveVars body_lv_info)
650
651
652         -- Compute the new let-expression
653     let
654         new_let | let_no_escape = StgLetNoEscape live_in_whole_let bind_lvs bind2 body2
655                 | otherwise     = StgLet bind2 body2
656
657         free_in_whole_let
658           = binders `minusFVBinders` (bind_fvs `unionFVInfo` body_fvs)
659
660         live_in_whole_let
661           = bind_lvs `unionVarSet` (body_lvs `delVarSetList` binders)
662
663         real_bind_escs = if let_no_escape then
664                             bind_escs
665                          else
666                             getFVSet bind_fvs
667                             -- Everything escapes which is free in the bindings
668
669         let_escs = (real_bind_escs `unionVarSet` body_escs) `delVarSetList` binders
670
671         all_escs = bind_escs `unionVarSet` body_escs    -- Still includes binders of
672                                                         -- this let(rec)
673
674         no_binder_escapes = isEmptyVarSet (set_of_binders `intersectVarSet` all_escs)
675
676         -- Debugging code as requested by Andrew Kennedy
677         checked_no_binder_escapes
678                 | debugIsOn && not no_binder_escapes && any is_join_var binders
679                 = pprTrace "Interesting!  A join var that isn't let-no-escaped" (ppr binders)
680                   False
681                 | otherwise = no_binder_escapes
682
683                 -- Mustn't depend on the passed-in let_no_escape flag, since
684                 -- no_binder_escapes is used by the caller to derive the flag!
685     return (
686         new_let,
687         free_in_whole_let,
688         let_escs,
689         checked_no_binder_escapes
690       )
691   where
692     set_of_binders = mkVarSet binders
693     binders        = bindersOf bind
694
695     mk_binding bind_lv_info binder rhs
696         = (binder, LetBound (NestedLet live_vars) (manifestArity rhs))
697         where
698            live_vars | let_no_escape = addLiveVar bind_lv_info binder
699                      | otherwise     = unitLiveVar binder
700                 -- c.f. the invariant on NestedLet
701
702     vars_bind :: FreeVarsInfo           -- Free var info for body of binding
703               -> CoreBind
704               -> LneM (StgBinding,
705                        FreeVarsInfo,
706                        EscVarsSet,        -- free vars; escapee vars
707                        LiveInfo,          -- Vars and CAFs live in binding
708                        [(Id, HowBound)])  -- extension to environment
709
710
711     vars_bind body_fvs (NonRec binder rhs) = do
712         (rhs2, bind_fvs, bind_lv_info, escs) <- coreToStgRhs body_fvs [] (binder,rhs)
713         let
714             env_ext_item = mk_binding bind_lv_info binder rhs
715
716         return (StgNonRec binder rhs2,
717                 bind_fvs, escs, bind_lv_info, [env_ext_item])
718
719
720     vars_bind body_fvs (Rec pairs)
721       = mfix $ \ ~(_, rec_rhs_fvs, _, bind_lv_info, _) ->
722            let
723                 rec_scope_fvs = unionFVInfo body_fvs rec_rhs_fvs
724                 binders = map fst pairs
725                 env_ext = [ mk_binding bind_lv_info b rhs
726                           | (b,rhs) <- pairs ]
727            in
728            extendVarEnvLne env_ext $ do
729               (rhss2, fvss, lv_infos, escss)
730                      <- mapAndUnzip4M (coreToStgRhs rec_scope_fvs binders) pairs
731               let
732                         bind_fvs = unionFVInfos fvss
733                         bind_lv_info = foldr unionLiveInfo emptyLiveInfo lv_infos
734                         escs     = unionVarSets escss
735
736               return (StgRec (binders `zip` rhss2),
737                       bind_fvs, escs, bind_lv_info, env_ext)
738
739
740 is_join_var :: Id -> Bool
741 -- A hack (used only for compiler debuggging) to tell if
742 -- a variable started life as a join point ($j)
743 is_join_var j = occNameString (getOccName j) == "$j"
744 \end{code}
745
746 \begin{code}
747 coreToStgRhs :: FreeVarsInfo            -- Free var info for the scope of the binding
748              -> [Id]
749              -> (Id,CoreExpr)
750              -> LneM (StgRhs, FreeVarsInfo, LiveInfo, EscVarsSet)
751
752 coreToStgRhs scope_fv_info binders (bndr, rhs) = do
753     (new_rhs, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
754     lv_info <- freeVarsToLiveVars (binders `minusFVBinders` rhs_fvs)
755     return (mkStgRhs rhs_fvs (mkSRT lv_info) bndr_info new_rhs,
756             rhs_fvs, lv_info, rhs_escs)
757   where
758     bndr_info = lookupFVInfo scope_fv_info bndr
759
760 mkStgRhs :: FreeVarsInfo -> SRT -> StgBinderInfo -> StgExpr -> StgRhs
761
762 mkStgRhs _ _ _ (StgConApp con args) = StgRhsCon noCCS con args
763
764 mkStgRhs rhs_fvs srt binder_info (StgLam _ bndrs body)
765   = StgRhsClosure noCCS binder_info
766                   (getFVs rhs_fvs)
767                   ReEntrant
768                   srt bndrs body
769
770 mkStgRhs rhs_fvs srt binder_info rhs
771   = StgRhsClosure noCCS binder_info
772                   (getFVs rhs_fvs)
773                   upd_flag srt [] rhs
774   where
775    upd_flag = Updatable
776   {-
777     SDM: disabled.  Eval/Apply can't handle functions with arity zero very
778     well; and making these into simple non-updatable thunks breaks other
779     assumptions (namely that they will be entered only once).
780
781     upd_flag | isPAP env rhs  = ReEntrant
782              | otherwise      = Updatable
783   -}
784
785 {- ToDo:
786           upd = if isOnceDem dem
787                     then (if isNotTop toplev
788                             then SingleEntry    -- HA!  Paydirt for "dem"
789                             else
790 #ifdef DEBUG
791                      trace "WARNING: SE CAFs unsupported, forcing UPD instead" $
792 #endif
793                      Updatable)
794                 else Updatable
795         -- For now we forbid SingleEntry CAFs; they tickle the
796         -- ASSERT in rts/Storage.c line 215 at newCAF() re mut_link,
797         -- and I don't understand why.  There's only one SE_CAF (well,
798         -- only one that tickled a great gaping bug in an earlier attempt
799         -- at ClosureInfo.getEntryConvention) in the whole of nofib,
800         -- specifically Main.lvl6 in spectral/cryptarithm2.
801         -- So no great loss.  KSW 2000-07.
802 -}
803 \end{code}
804
805 Detect thunks which will reduce immediately to PAPs, and make them
806 non-updatable.  This has several advantages:
807
808         - the non-updatable thunk behaves exactly like the PAP,
809
810         - the thunk is more efficient to enter, because it is
811           specialised to the task.
812
813         - we save one update frame, one stg_update_PAP, one update
814           and lots of PAP_enters.
815
816         - in the case where the thunk is top-level, we save building
817           a black hole and futhermore the thunk isn't considered to
818           be a CAF any more, so it doesn't appear in any SRTs.
819
820 We do it here, because the arity information is accurate, and we need
821 to do it before the SRT pass to save the SRT entries associated with
822 any top-level PAPs.
823
824 isPAP env (StgApp f args) = listLengthCmp args arity == LT -- idArity f > length args
825                           where
826                             arity = stgArity f (lookupBinding env f)
827 isPAP env _               = False
828
829
830 %************************************************************************
831 %*                                                                      *
832 \subsection[LNE-monad]{A little monad for this let-no-escaping pass}
833 %*                                                                      *
834 %************************************************************************
835
836 There's a lot of stuff to pass around, so we use this @LneM@ monad to
837 help.  All the stuff here is only passed *down*.
838
839 \begin{code}
840 newtype LneM a = LneM
841     { unLneM :: IdEnv HowBound
842              -> LiveInfo                -- Vars and CAFs live in continuation
843              -> a
844     }
845
846 type LiveInfo = (StgLiveVars,   -- Dynamic live variables;
847                                 -- i.e. ones with a nested (non-top-level) binding
848                  CafSet)        -- Static live variables;
849                                 -- i.e. top-level variables that are CAFs or refer to them
850
851 type EscVarsSet = IdSet
852 type CafSet     = IdSet
853
854 data HowBound
855   = ImportBound         -- Used only as a response to lookupBinding; never
856                         -- exists in the range of the (IdEnv HowBound)
857
858   | LetBound            -- A let(rec) in this module
859         LetInfo         -- Whether top level or nested
860         Arity           -- Its arity (local Ids don't have arity info at this point)
861
862   | LambdaBound         -- Used for both lambda and case
863
864 data LetInfo
865   = TopLet              -- top level things
866   | NestedLet LiveInfo  -- For nested things, what is live if this
867                         -- thing is live?  Invariant: the binder
868                         -- itself is always a member of
869                         -- the dynamic set of its own LiveInfo
870
871 isLetBound :: HowBound -> Bool
872 isLetBound (LetBound _ _) = True
873 isLetBound _              = False
874
875 topLevelBound :: HowBound -> Bool
876 topLevelBound ImportBound         = True
877 topLevelBound (LetBound TopLet _) = True
878 topLevelBound _                   = False
879 \end{code}
880
881 For a let(rec)-bound variable, x, we record LiveInfo, the set of
882 variables that are live if x is live.  This LiveInfo comprises
883         (a) dynamic live variables (ones with a non-top-level binding)
884         (b) static live variabes (CAFs or things that refer to CAFs)
885
886 For "normal" variables (a) is just x alone.  If x is a let-no-escaped
887 variable then x is represented by a code pointer and a stack pointer
888 (well, one for each stack).  So all of the variables needed in the
889 execution of x are live if x is, and are therefore recorded in the
890 LetBound constructor; x itself *is* included.
891
892 The set of dynamic live variables is guaranteed ot have no further let-no-escaped
893 variables in it.
894
895 \begin{code}
896 emptyLiveInfo :: LiveInfo
897 emptyLiveInfo = (emptyVarSet,emptyVarSet)
898
899 unitLiveVar :: Id -> LiveInfo
900 unitLiveVar lv = (unitVarSet lv, emptyVarSet)
901
902 unitLiveCaf :: Id -> LiveInfo
903 unitLiveCaf caf = (emptyVarSet, unitVarSet caf)
904
905 addLiveVar :: LiveInfo -> Id -> LiveInfo
906 addLiveVar (lvs, cafs) id = (lvs `extendVarSet` id, cafs)
907
908 unionLiveInfo :: LiveInfo -> LiveInfo -> LiveInfo
909 unionLiveInfo (lv1,caf1) (lv2,caf2) = (lv1 `unionVarSet` lv2, caf1 `unionVarSet` caf2)
910
911 mkSRT :: LiveInfo -> SRT
912 mkSRT (_, cafs) = SRTEntries cafs
913
914 getLiveVars :: LiveInfo -> StgLiveVars
915 getLiveVars (lvs, _) = lvs
916 \end{code}
917
918
919 The std monad functions:
920 \begin{code}
921 initLne :: IdEnv HowBound -> LneM a -> a
922 initLne env m = unLneM m env emptyLiveInfo
923
924
925
926 {-# INLINE thenLne #-}
927 {-# INLINE returnLne #-}
928
929 returnLne :: a -> LneM a
930 returnLne e = LneM $ \_ _ -> e
931
932 thenLne :: LneM a -> (a -> LneM b) -> LneM b
933 thenLne m k = LneM $ \env lvs_cont
934   -> unLneM (k (unLneM m env lvs_cont)) env lvs_cont
935
936 instance Monad LneM where
937     return = returnLne
938     (>>=)  = thenLne
939
940 instance MonadFix LneM where
941     mfix expr = LneM $ \env lvs_cont ->
942                        let result = unLneM (expr result) env lvs_cont
943                        in  result
944 \end{code}
945
946 Functions specific to this monad:
947
948 \begin{code}
949 getVarsLiveInCont :: LneM LiveInfo
950 getVarsLiveInCont = LneM $ \_env lvs_cont -> lvs_cont
951
952 setVarsLiveInCont :: LiveInfo -> LneM a -> LneM a
953 setVarsLiveInCont new_lvs_cont expr
954    =    LneM $   \env _lvs_cont
955    -> unLneM expr env new_lvs_cont
956
957 extendVarEnvLne :: [(Id, HowBound)] -> LneM a -> LneM a
958 extendVarEnvLne ids_w_howbound expr
959    =    LneM $   \env lvs_cont
960    -> unLneM expr (extendVarEnvList env ids_w_howbound) lvs_cont
961
962 lookupVarLne :: Id -> LneM HowBound
963 lookupVarLne v = LneM $ \env _lvs_cont -> lookupBinding env v
964
965 lookupBinding :: IdEnv HowBound -> Id -> HowBound
966 lookupBinding env v = case lookupVarEnv env v of
967                         Just xx -> xx
968                         Nothing -> ASSERT2( isGlobalId v, ppr v ) ImportBound
969
970
971 -- The result of lookupLiveVarsForSet, a set of live variables, is
972 -- only ever tacked onto a decorated expression. It is never used as
973 -- the basis of a control decision, which might give a black hole.
974
975 freeVarsToLiveVars :: FreeVarsInfo -> LneM LiveInfo
976 freeVarsToLiveVars fvs = LneM freeVarsToLiveVars'
977  where
978   freeVarsToLiveVars' _env live_in_cont = live_info
979    where
980     live_info    = foldr unionLiveInfo live_in_cont lvs_from_fvs
981     lvs_from_fvs = map do_one (allFreeIds fvs)
982
983     do_one (v, how_bound)
984       = case how_bound of
985           ImportBound                     -> unitLiveCaf v      -- Only CAF imports are
986                                                                 -- recorded in fvs
987           LetBound TopLet _
988                 | mayHaveCafRefs (idCafInfo v) -> unitLiveCaf v
989                 | otherwise                    -> emptyLiveInfo
990
991           LetBound (NestedLet lvs) _      -> lvs        -- lvs already contains v
992                                                         -- (see the invariant on NestedLet)
993
994           _lambda_or_case_binding         -> unitLiveVar v      -- Bound by lambda or case
995 \end{code}
996
997 %************************************************************************
998 %*                                                                      *
999 \subsection[Free-var info]{Free variable information}
1000 %*                                                                      *
1001 %************************************************************************
1002
1003 \begin{code}
1004 type FreeVarsInfo = VarEnv (Var, HowBound, StgBinderInfo)
1005         -- The Var is so we can gather up the free variables
1006         -- as a set.
1007         --
1008         -- The HowBound info just saves repeated lookups;
1009         -- we look up just once when we encounter the occurrence.
1010         -- INVARIANT: Any ImportBound Ids are HaveCafRef Ids
1011         --            Imported Ids without CAF refs are simply
1012         --            not put in the FreeVarsInfo for an expression.
1013         --            See singletonFVInfo and freeVarsToLiveVars
1014         --
1015         -- StgBinderInfo records how it occurs; notably, we
1016         -- are interested in whether it only occurs in saturated
1017         -- applications, because then we don't need to build a
1018         -- curried version.
1019         -- If f is mapped to noBinderInfo, that means
1020         -- that f *is* mentioned (else it wouldn't be in the
1021         -- IdEnv at all), but perhaps in an unsaturated applications.
1022         --
1023         -- All case/lambda-bound things are also mapped to
1024         -- noBinderInfo, since we aren't interested in their
1025         -- occurence info.
1026         --
1027         -- For ILX we track free var info for type variables too;
1028         -- hence VarEnv not IdEnv
1029 \end{code}
1030
1031 \begin{code}
1032 emptyFVInfo :: FreeVarsInfo
1033 emptyFVInfo = emptyVarEnv
1034
1035 singletonFVInfo :: Id -> HowBound -> StgBinderInfo -> FreeVarsInfo
1036 -- Don't record non-CAF imports at all, to keep free-var sets small
1037 singletonFVInfo id ImportBound info
1038    | mayHaveCafRefs (idCafInfo id) = unitVarEnv id (id, ImportBound, info)
1039    | otherwise                     = emptyVarEnv
1040 singletonFVInfo id how_bound info  = unitVarEnv id (id, how_bound, info)
1041
1042 unionFVInfo :: FreeVarsInfo -> FreeVarsInfo -> FreeVarsInfo
1043 unionFVInfo fv1 fv2 = plusVarEnv_C plusFVInfo fv1 fv2
1044
1045 unionFVInfos :: [FreeVarsInfo] -> FreeVarsInfo
1046 unionFVInfos fvs = foldr unionFVInfo emptyFVInfo fvs
1047
1048 minusFVBinders :: [Id] -> FreeVarsInfo -> FreeVarsInfo
1049 minusFVBinders vs fv = foldr minusFVBinder fv vs
1050
1051 minusFVBinder :: Id -> FreeVarsInfo -> FreeVarsInfo
1052 minusFVBinder v fv = fv `delVarEnv` v
1053         -- When removing a binder, remember to add its type variables
1054         -- c.f. CoreFVs.delBinderFV
1055
1056 elementOfFVInfo :: Id -> FreeVarsInfo -> Bool
1057 elementOfFVInfo id fvs = maybeToBool (lookupVarEnv fvs id)
1058
1059 lookupFVInfo :: FreeVarsInfo -> Id -> StgBinderInfo
1060 -- Find how the given Id is used.
1061 -- Externally visible things may be used any old how
1062 lookupFVInfo fvs id
1063   | isExternalName (idName id) = noBinderInfo
1064   | otherwise = case lookupVarEnv fvs id of
1065                         Nothing         -> noBinderInfo
1066                         Just (_,_,info) -> info
1067
1068 allFreeIds :: FreeVarsInfo -> [(Id,HowBound)]   -- Both top level and non-top-level Ids
1069 allFreeIds fvs = ASSERT( all (isId . fst) ids ) ids
1070       where
1071         ids = [(id,how_bound) | (id,how_bound,_) <- varEnvElts fvs]
1072
1073 -- Non-top-level things only, both type variables and ids
1074 getFVs :: FreeVarsInfo -> [Var]
1075 getFVs fvs = [id | (id, how_bound, _) <- varEnvElts fvs,
1076                     not (topLevelBound how_bound) ]
1077
1078 getFVSet :: FreeVarsInfo -> VarSet
1079 getFVSet fvs = mkVarSet (getFVs fvs)
1080
1081 plusFVInfo :: (Var, HowBound, StgBinderInfo)
1082            -> (Var, HowBound, StgBinderInfo)
1083            -> (Var, HowBound, StgBinderInfo)
1084 plusFVInfo (id1,hb1,info1) (id2,hb2,info2)
1085   = ASSERT (id1 == id2 && hb1 `check_eq_how_bound` hb2)
1086     (id1, hb1, combineStgBinderInfo info1 info2)
1087
1088 -- The HowBound info for a variable in the FVInfo should be consistent
1089 check_eq_how_bound :: HowBound -> HowBound -> Bool
1090 check_eq_how_bound ImportBound        ImportBound        = True
1091 check_eq_how_bound LambdaBound        LambdaBound        = True
1092 check_eq_how_bound (LetBound li1 ar1) (LetBound li2 ar2) = ar1 == ar2 && check_eq_li li1 li2
1093 check_eq_how_bound _                  _                  = False
1094
1095 check_eq_li :: LetInfo -> LetInfo -> Bool
1096 check_eq_li (NestedLet _) (NestedLet _) = True
1097 check_eq_li TopLet        TopLet        = True
1098 check_eq_li _             _             = False
1099 \end{code}
1100
1101 Misc.
1102 \begin{code}
1103 filterStgBinders :: [Var] -> [Var]
1104 filterStgBinders bndrs = filter isId bndrs
1105 \end{code}
1106
1107
1108 \begin{code}
1109         -- Ignore all notes except SCC
1110 myCollectBinders :: Expr Var -> ([Var], Expr Var)
1111 myCollectBinders expr
1112   = go [] expr
1113   where
1114     go bs (Lam b e)          = go (b:bs) e
1115     go bs e@(Note (SCC _) _) = (reverse bs, e)
1116     go bs (Cast e _)         = go bs e
1117     go bs (Note _ e)         = go bs e
1118     go bs e                  = (reverse bs, e)
1119
1120 myCollectArgs :: CoreExpr -> (Id, [CoreArg])
1121         -- We assume that we only have variables
1122         -- in the function position by now
1123 myCollectArgs expr
1124   = go expr []
1125   where
1126     go (Var v)          as = (v, as)
1127     go (App f a) as        = go f (a:as)
1128     go (Note (SCC _) _) _  = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1129     go (Cast e _)       as = go e as
1130     go (Note _ e)       as = go e as
1131     go (Lam b e)        as
1132        | isTyVar b         = go e as  -- Note [Collect args]
1133     go _                _  = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1134 \end{code}
1135
1136 Note [Collect args]
1137 ~~~~~~~~~~~~~~~~~~~
1138 This big-lambda case occurred following a rather obscure eta expansion.
1139 It all seems a bit yukky to me.
1140
1141 \begin{code}
1142 stgArity :: Id -> HowBound -> Arity
1143 stgArity _ (LetBound _ arity) = arity
1144 stgArity f ImportBound        = idArity f
1145 stgArity _ LambdaBound        = 0
1146 \end{code}