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