[project @ 2004-12-22 12:06:13 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CorePrep.lhs
1 %
2 % (c) The University of Glasgow, 1994-2000
3 %
4 \section{Core pass to saturate constructors and PrimOps}
5
6 \begin{code}
7 module CorePrep (
8       corePrepPgm, corePrepExpr
9   ) where
10
11 #include "HsVersions.h"
12
13 import CoreUtils( exprType, exprIsValue, etaExpand, exprArity, exprOkForSpeculation )
14 import CoreFVs  ( exprFreeVars )
15 import CoreLint ( endPass )
16 import CoreSyn
17 import Type     ( Type, applyTy, splitFunTy_maybe, 
18                   isUnLiftedType, isUnboxedTupleType, seqType )
19 import NewDemand  ( Demand, isStrictDmd, lazyDmd, StrictSig(..), DmdType(..) )
20 import Var      ( Var, Id, setVarUnique )
21 import VarSet
22 import VarEnv
23 import Id       ( mkSysLocal, idType, idNewDemandInfo, idArity,
24                   isFCallId, isGlobalId, isImplicitId,
25                   isLocalId, hasNoBinding, idNewStrictness, 
26                   idUnfolding, isDataConWorkId_maybe
27                 )
28 import HscTypes   ( TypeEnv, typeEnvElts, TyThing( AnId ) )
29 import BasicTypes ( TopLevelFlag(..), isTopLevel, isNotTopLevel,
30                     RecFlag(..), isNonRec
31                   )
32 import UniqSupply
33 import Maybes
34 import OrdList
35 import ErrUtils
36 import CmdLineOpts
37 import Util       ( listLengthCmp )
38 import Outputable
39 \end{code}
40
41 -- ---------------------------------------------------------------------------
42 -- Overview
43 -- ---------------------------------------------------------------------------
44
45 The goal of this pass is to prepare for code generation.
46
47 1.  Saturate constructor and primop applications.
48
49 2.  Convert to A-normal form:
50
51     * Use case for strict arguments:
52         f E ==> case E of x -> f x
53         (where f is strict)
54
55     * Use let for non-trivial lazy arguments
56         f E ==> let x = E in f x
57         (were f is lazy and x is non-trivial)
58
59 3.  Similarly, convert any unboxed lets into cases.
60     [I'm experimenting with leaving 'ok-for-speculation' 
61      rhss in let-form right up to this point.]
62
63 4.  Ensure that lambdas only occur as the RHS of a binding
64     (The code generator can't deal with anything else.)
65
66 5.  [Not any more; nuked Jun 2002] Do the seq/par munging.
67
68 6.  Clone all local Ids.
69     This means that all such Ids are unique, rather than the 
70     weaker guarantee of no clashes which the simplifier provides.
71     And that is what the code generator needs.
72
73     We don't clone TyVars. The code gen doesn't need that, 
74     and doing so would be tiresome because then we'd need
75     to substitute in types.
76
77
78 7.  Give each dynamic CCall occurrence a fresh unique; this is
79     rather like the cloning step above.
80
81 8.  Inject bindings for the "implicit" Ids:
82         * Constructor wrappers
83         * Constructor workers
84         * Record selectors
85     We want curried definitions for all of these in case they
86     aren't inlined by some caller.
87         
88 This is all done modulo type applications and abstractions, so that
89 when type erasure is done for conversion to STG, we don't end up with
90 any trivial or useless bindings.
91
92   
93
94 -- -----------------------------------------------------------------------------
95 -- Top level stuff
96 -- -----------------------------------------------------------------------------
97
98 \begin{code}
99 corePrepPgm :: DynFlags -> [CoreBind] -> TypeEnv -> IO [CoreBind]
100 corePrepPgm dflags binds types
101   = do  showPass dflags "CorePrep"
102         us <- mkSplitUniqSupply 's'
103
104         let implicit_binds = mkImplicitBinds types
105                 -- NB: we must feed mkImplicitBinds through corePrep too
106                 -- so that they are suitably cloned and eta-expanded
107
108             binds_out = initUs_ us (
109                           corePrepTopBinds binds        `thenUs` \ floats1 ->
110                           corePrepTopBinds implicit_binds       `thenUs` \ floats2 ->
111                           returnUs (deFloatTop (floats1 `appendFloats` floats2))
112                         )
113             
114         endPass dflags "CorePrep" Opt_D_dump_prep binds_out
115         return binds_out
116
117 corePrepExpr :: DynFlags -> CoreExpr -> IO CoreExpr
118 corePrepExpr dflags expr
119   = do showPass dflags "CorePrep"
120        us <- mkSplitUniqSupply 's'
121        let new_expr = initUs_ us (corePrepAnExpr emptyVarEnv expr)
122        dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" 
123                      (ppr new_expr)
124        return new_expr
125 \end{code}
126
127 -- -----------------------------------------------------------------------------
128 -- Implicit bindings
129 -- -----------------------------------------------------------------------------
130
131 Create any necessary "implicit" bindings (data constructors etc).
132 Namely:
133         * Constructor workers
134         * Constructor wrappers
135         * Data type record selectors
136         * Class op selectors
137
138 In the latter three cases, the Id contains the unfolding to use for
139 the binding.  In the case of data con workers we create the rather 
140 strange (non-recursive!) binding
141
142         $wC = \x y -> $wC x y
143
144 i.e. a curried constructor that allocates.  This means that we can
145 treat the worker for a constructor like any other function in the rest
146 of the compiler.  The point here is that CoreToStg will generate a
147 StgConApp for the RHS, rather than a call to the worker (which would
148 give a loop).  As Lennart says: the ice is thin here, but it works.
149
150 Hmm.  Should we create bindings for dictionary constructors?  They are
151 always fully applied, and the bindings are just there to support
152 partial applications. But it's easier to let them through.
153
154 \begin{code}
155 mkImplicitBinds type_env
156   = [ NonRec id (get_unfolding id)
157     | AnId id <- typeEnvElts type_env, isImplicitId id ]
158         -- The type environment already contains all the implicit Ids, 
159         -- so we just filter them out
160         --
161         -- The etaExpand is so that the manifest arity of the
162         -- binding matches its claimed arity, which is an 
163         -- invariant of top level bindings going into the code gen
164
165 get_unfolding id        -- See notes above
166   | Just data_con <- isDataConWorkId_maybe id = Var id  -- The ice is thin here, but it works
167                                                         -- CorePrep will eta-expand it
168   | otherwise                                 = unfoldingTemplate (idUnfolding id)
169 \end{code}
170         
171
172 \begin{code}
173 -- ---------------------------------------------------------------------------
174 -- Dealing with bindings
175 -- ---------------------------------------------------------------------------
176
177 data FloatingBind = FloatLet CoreBind
178                   | FloatCase Id CoreExpr Bool
179                         -- The bool indicates "ok-for-speculation"
180
181 data Floats = Floats OkToSpec (OrdList FloatingBind)
182
183 -- Can we float these binds out of the rhs of a let?  We cache this decision
184 -- to avoid having to recompute it in a non-linear way when there are
185 -- deeply nested lets.
186 data OkToSpec
187    = NotOkToSpec        -- definitely not
188    | OkToSpec           -- yes
189    | IfUnboxedOk        -- only if floating an unboxed binding is ok
190
191 emptyFloats :: Floats
192 emptyFloats = Floats OkToSpec nilOL
193
194 addFloat :: Floats -> FloatingBind -> Floats
195 addFloat (Floats ok_to_spec floats) new_float
196   = Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
197   where
198     check (FloatLet _)                = OkToSpec
199     check (FloatCase _ _ ok_for_spec) 
200         | ok_for_spec  =  IfUnboxedOk
201         | otherwise    =  NotOkToSpec
202         -- The ok-for-speculation flag says that it's safe to
203         -- float this Case out of a let, and thereby do it more eagerly
204         -- We need the top-level flag because it's never ok to float
205         -- an unboxed binding to the top level
206
207 unitFloat :: FloatingBind -> Floats
208 unitFloat = addFloat emptyFloats
209
210 appendFloats :: Floats -> Floats -> Floats
211 appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
212   = Floats (combine spec1 spec2) (floats1 `appOL` floats2)
213
214 concatFloats :: [Floats] -> Floats
215 concatFloats = foldr appendFloats emptyFloats
216
217 combine NotOkToSpec _ = NotOkToSpec
218 combine _ NotOkToSpec = NotOkToSpec
219 combine IfUnboxedOk _ = IfUnboxedOk
220 combine _ IfUnboxedOk = IfUnboxedOk
221 combine _ _           = OkToSpec
222     
223 instance Outputable FloatingBind where
224   ppr (FloatLet bind)        = text "FloatLet" <+> ppr bind
225   ppr (FloatCase b rhs spec) = text "FloatCase" <+> ppr b <+> ppr spec <+> equals <+> ppr rhs
226
227 type CloneEnv = IdEnv Id        -- Clone local Ids
228
229 deFloatTop :: Floats -> [CoreBind]
230 -- For top level only; we don't expect any FloatCases
231 deFloatTop (Floats _ floats)
232   = foldrOL get [] floats
233   where
234     get (FloatLet b) bs = b:bs
235     get b            bs = pprPanic "corePrepPgm" (ppr b)
236
237 allLazy :: TopLevelFlag -> RecFlag -> Floats -> Bool
238 allLazy top_lvl is_rec (Floats ok_to_spec _)
239   = case ok_to_spec of
240         OkToSpec -> True
241         NotOkToSpec -> False
242         IfUnboxedOk -> isNotTopLevel top_lvl && isNonRec is_rec
243
244 -- ---------------------------------------------------------------------------
245 --                      Bindings
246 -- ---------------------------------------------------------------------------
247
248 corePrepTopBinds :: [CoreBind] -> UniqSM Floats
249 corePrepTopBinds binds 
250   = go emptyVarEnv binds
251   where
252     go env []             = returnUs emptyFloats
253     go env (bind : binds) = corePrepTopBind env bind    `thenUs` \ (env', bind') ->
254                             go env' binds               `thenUs` \ binds' ->
255                             returnUs (bind' `appendFloats` binds')
256
257 -- NB: we do need to float out of top-level bindings
258 -- Consider     x = length [True,False]
259 -- We want to get
260 --              s1 = False : []
261 --              s2 = True  : s1
262 --              x  = length s2
263
264 -- We return a *list* of bindings, because we may start with
265 --      x* = f (g y)
266 -- where x is demanded, in which case we want to finish with
267 --      a = g y
268 --      x* = f a
269 -- And then x will actually end up case-bound
270 --
271 -- What happens to the CafInfo on the floated bindings?  By
272 -- default, all the CafInfos will be set to MayHaveCafRefs,
273 -- which is safe.
274 --
275 -- This might be pessimistic, because eg. s1 & s2
276 -- might not refer to any CAFs and the GC will end up doing
277 -- more traversal than is necessary, but it's still better
278 -- than not floating the bindings at all, because then
279 -- the GC would have to traverse the structure in the heap
280 -- instead.  Given this, we decided not to try to get
281 -- the CafInfo on the floated bindings correct, because
282 -- it looks difficult.
283
284 --------------------------------
285 corePrepTopBind :: CloneEnv -> CoreBind -> UniqSM (CloneEnv, Floats)
286 corePrepTopBind env (NonRec bndr rhs) 
287   = cloneBndr env bndr                                  `thenUs` \ (env', bndr') ->
288     corePrepRhs TopLevel NonRecursive env (bndr, rhs)   `thenUs` \ (floats, rhs') -> 
289     returnUs (env', addFloat floats (FloatLet (NonRec bndr' rhs')))
290
291 corePrepTopBind env (Rec pairs) = corePrepRecPairs TopLevel env pairs
292
293 --------------------------------
294 corePrepBind ::  CloneEnv -> CoreBind -> UniqSM (CloneEnv, Floats)
295         -- This one is used for *local* bindings
296 corePrepBind env (NonRec bndr rhs)
297   = etaExpandRhs bndr rhs                               `thenUs` \ rhs1 ->
298     corePrepExprFloat env rhs1                          `thenUs` \ (floats, rhs2) ->
299     cloneBndr env bndr                                  `thenUs` \ (env', bndr') ->
300     mkLocalNonRec bndr' (bdrDem bndr') floats rhs2      `thenUs` \ floats' ->
301     returnUs (env', floats')
302
303 corePrepBind env (Rec pairs) = corePrepRecPairs NotTopLevel env pairs
304
305 --------------------------------
306 corePrepRecPairs :: TopLevelFlag -> CloneEnv
307                  -> [(Id,CoreExpr)]     -- Recursive bindings
308                  -> UniqSM (CloneEnv, Floats)
309 -- Used for all recursive bindings, top level and otherwise
310 corePrepRecPairs lvl env pairs
311   = cloneBndrs env (map fst pairs)                              `thenUs` \ (env', bndrs') ->
312     mapAndUnzipUs (corePrepRhs lvl Recursive env') pairs        `thenUs` \ (floats_s, rhss') ->
313     returnUs (env', unitFloat (FloatLet (Rec (flatten (concatFloats floats_s) bndrs' rhss'))))
314   where
315         -- Flatten all the floats, and the currrent
316         -- group into a single giant Rec
317     flatten (Floats _ floats) bndrs rhss = foldrOL get (bndrs `zip` rhss) floats
318
319     get (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
320     get (FloatLet (Rec prs1))   prs2 = prs1 ++ prs2
321
322 --------------------------------
323 corePrepRhs :: TopLevelFlag -> RecFlag
324             -> CloneEnv -> (Id, CoreExpr)
325             -> UniqSM (Floats, CoreExpr)
326 -- Used for top-level bindings, and local recursive bindings
327 corePrepRhs top_lvl is_rec env (bndr, rhs)
328   = etaExpandRhs bndr rhs       `thenUs` \ rhs' ->
329     corePrepExprFloat env rhs'  `thenUs` \ floats_w_rhs ->
330     floatRhs top_lvl is_rec bndr floats_w_rhs
331
332
333 -- ---------------------------------------------------------------------------
334 -- Making arguments atomic (function args & constructor args)
335 -- ---------------------------------------------------------------------------
336
337 -- This is where we arrange that a non-trivial argument is let-bound
338 corePrepArg :: CloneEnv -> CoreArg -> RhsDemand
339            -> UniqSM (Floats, CoreArg)
340 corePrepArg env arg dem
341   = corePrepExprFloat env arg           `thenUs` \ (floats, arg') ->
342     if exprIsTrivial arg'
343     then returnUs (floats, arg')
344     else newVar (exprType arg')                 `thenUs` \ v ->
345          mkLocalNonRec v dem floats arg'        `thenUs` \ floats' -> 
346          returnUs (floats', Var v)
347
348 -- version that doesn't consider an scc annotation to be trivial.
349 exprIsTrivial (Var v)                  = True
350 exprIsTrivial (Type _)                 = True
351 exprIsTrivial (Lit lit)                = True
352 exprIsTrivial (App e arg)              = isTypeArg arg && exprIsTrivial e
353 exprIsTrivial (Note (SCC _) e)         = False
354 exprIsTrivial (Note _ e)               = exprIsTrivial e
355 exprIsTrivial (Lam b body) | isTyVar b = exprIsTrivial body
356 exprIsTrivial other                    = False
357
358 -- ---------------------------------------------------------------------------
359 -- Dealing with expressions
360 -- ---------------------------------------------------------------------------
361
362 corePrepAnExpr :: CloneEnv -> CoreExpr -> UniqSM CoreExpr
363 corePrepAnExpr env expr
364   = corePrepExprFloat env expr          `thenUs` \ (floats, expr) ->
365     mkBinds floats expr
366
367
368 corePrepExprFloat :: CloneEnv -> CoreExpr -> UniqSM (Floats, CoreExpr)
369 -- If
370 --      e  ===>  (bs, e')
371 -- then 
372 --      e = let bs in e'        (semantically, that is!)
373 --
374 -- For example
375 --      f (g x)   ===>   ([v = g x], f v)
376
377 corePrepExprFloat env (Var v)
378   = fiddleCCall v                               `thenUs` \ v1 ->
379     let v2 = lookupVarEnv env v1 `orElse` v1 in
380     maybeSaturate v2 (Var v2) 0 (idType v2)     `thenUs` \ app ->
381     returnUs (emptyFloats, app)
382
383 corePrepExprFloat env expr@(Type _)
384   = returnUs (emptyFloats, expr)
385
386 corePrepExprFloat env expr@(Lit lit)
387   = returnUs (emptyFloats, expr)
388
389 corePrepExprFloat env (Let bind body)
390   = corePrepBind env bind               `thenUs` \ (env', new_binds) ->
391     corePrepExprFloat env' body         `thenUs` \ (floats, new_body) ->
392     returnUs (new_binds `appendFloats` floats, new_body)
393
394 corePrepExprFloat env (Note n@(SCC _) expr)
395   = corePrepAnExpr env expr             `thenUs` \ expr1 ->
396     deLamFloat expr1                    `thenUs` \ (floats, expr2) ->
397     returnUs (floats, Note n expr2)
398
399 corePrepExprFloat env (Note other_note expr)
400   = corePrepExprFloat env expr          `thenUs` \ (floats, expr') ->
401     returnUs (floats, Note other_note expr')
402
403 corePrepExprFloat env expr@(Lam _ _)
404   = cloneBndrs env bndrs                `thenUs` \ (env', bndrs') ->
405     corePrepAnExpr env' body            `thenUs` \ body' ->
406     returnUs (emptyFloats, mkLams bndrs' body')
407   where
408     (bndrs,body) = collectBinders expr
409
410 corePrepExprFloat env (Case scrut bndr ty alts)
411   = corePrepExprFloat env scrut         `thenUs` \ (floats1, scrut1) ->
412     deLamFloat scrut1                   `thenUs` \ (floats2, scrut2) ->
413     cloneBndr env bndr                  `thenUs` \ (env', bndr') ->
414     mapUs (sat_alt env') alts           `thenUs` \ alts' ->
415     returnUs (floats1 `appendFloats` floats2 , Case scrut2 bndr' ty alts')
416   where
417     sat_alt env (con, bs, rhs)
418           = cloneBndrs env bs           `thenUs` \ (env', bs') ->
419             corePrepAnExpr env' rhs     `thenUs` \ rhs1 ->
420             deLam rhs1                  `thenUs` \ rhs2 ->
421             returnUs (con, bs', rhs2)
422
423 corePrepExprFloat env expr@(App _ _)
424   = collect_args expr 0  `thenUs` \ (app, (head,depth), ty, floats, ss) ->
425     ASSERT(null ss)     -- make sure we used all the strictness info
426
427         -- Now deal with the function
428     case head of
429       Var fn_id -> maybeSaturate fn_id app depth ty `thenUs` \ app' -> 
430                    returnUs (floats, app')
431
432       _other    -> returnUs (floats, app)
433
434   where
435
436     -- Deconstruct and rebuild the application, floating any non-atomic
437     -- arguments to the outside.  We collect the type of the expression,
438     -- the head of the application, and the number of actual value arguments,
439     -- all of which are used to possibly saturate this application if it
440     -- has a constructor or primop at the head.
441
442     collect_args
443         :: CoreExpr
444         -> Int                            -- current app depth
445         -> UniqSM (CoreExpr,              -- the rebuilt expression
446                    (CoreExpr,Int),        -- the head of the application,
447                                           -- and no. of args it was applied to
448                    Type,                  -- type of the whole expr
449                    Floats,                -- any floats we pulled out
450                    [Demand])              -- remaining argument demands
451
452     collect_args (App fun arg@(Type arg_ty)) depth
453         = collect_args fun depth   `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
454           returnUs (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss)
455
456     collect_args (App fun arg) depth
457         = collect_args fun (depth+1)   `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
458           let
459               (ss1, ss_rest)   = case ss of
460                                    (ss1:ss_rest) -> (ss1,     ss_rest)
461                                    []            -> (lazyDmd, [])
462               (arg_ty, res_ty) = expectJust "corePrepExprFloat:collect_args" $
463                                  splitFunTy_maybe fun_ty
464           in
465           corePrepArg env arg (mkDemTy ss1 arg_ty)      `thenUs` \ (fs, arg') ->
466           returnUs (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest)
467
468     collect_args (Var v) depth
469         = fiddleCCall v `thenUs` \ v1 ->
470           let v2 = lookupVarEnv env v1 `orElse` v1 in
471           returnUs (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts)
472         where
473           stricts = case idNewStrictness v of
474                         StrictSig (DmdType _ demands _)
475                             | listLengthCmp demands depth /= GT -> demands
476                                     -- length demands <= depth
477                             | otherwise                         -> []
478                 -- If depth < length demands, then we have too few args to 
479                 -- satisfy strictness  info so we have to  ignore all the 
480                 -- strictness info, e.g. + (error "urk")
481                 -- Here, we can't evaluate the arg strictly, because this 
482                 -- partial application might be seq'd
483
484
485     collect_args (Note (Coerce ty1 ty2) fun) depth
486         = collect_args fun depth  `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
487           returnUs (Note (Coerce ty1 ty2) fun', hd, ty1, floats, ss)
488
489     collect_args (Note note fun) depth
490         | ignore_note note 
491         = collect_args fun depth   `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
492           returnUs (Note note fun', hd, fun_ty, floats, ss)
493
494         -- non-variable fun, better let-bind it
495         -- ToDo: perhaps we can case-bind rather than let-bind this closure,
496         -- since it is sure to be evaluated.
497     collect_args fun depth
498         = corePrepExprFloat env fun                     `thenUs` \ (fun_floats, fun') ->
499           newVar ty                                     `thenUs` \ fn_id ->
500           mkLocalNonRec fn_id onceDem fun_floats fun'   `thenUs` \ floats ->
501           returnUs (Var fn_id, (Var fn_id, depth), ty, floats, [])
502         where
503           ty = exprType fun
504
505     ignore_note (CoreNote _) = True 
506     ignore_note InlineCall   = True
507     ignore_note InlineMe     = True
508     ignore_note _other       = False
509         -- We don't ignore SCCs, since they require some code generation
510
511 ------------------------------------------------------------------------------
512 -- Building the saturated syntax
513 -- ---------------------------------------------------------------------------
514
515 -- maybeSaturate deals with saturating primops and constructors
516 -- The type is the type of the entire application
517 maybeSaturate :: Id -> CoreExpr -> Int -> Type -> UniqSM CoreExpr
518 maybeSaturate fn expr n_args ty
519   | hasNoBinding fn = saturate_it
520   | otherwise       = returnUs expr
521   where
522     fn_arity     = idArity fn
523     excess_arity = fn_arity - n_args
524     saturate_it  = getUniquesUs                 `thenUs` \ us ->
525                    returnUs (etaExpand excess_arity us expr ty)
526
527 -- ---------------------------------------------------------------------------
528 -- Precipitating the floating bindings
529 -- ---------------------------------------------------------------------------
530
531 floatRhs :: TopLevelFlag -> RecFlag
532          -> Id
533          -> (Floats, CoreExpr)  -- Rhs: let binds in body
534          -> UniqSM (Floats,     -- Floats out of this bind
535                     CoreExpr)   -- Final Rhs
536
537 floatRhs top_lvl is_rec bndr (floats, rhs)
538   | isTopLevel top_lvl || exprIsValue rhs,      -- Float to expose value or 
539     allLazy top_lvl is_rec floats               -- at top level
540   =     -- Why the test for allLazy? 
541         --      v = f (x `divInt#` y)
542         -- we don't want to float the case, even if f has arity 2,
543         -- because floating the case would make it evaluated too early
544         --
545         -- Finally, eta-expand the RHS, for the benefit of the code gen
546     returnUs (floats, rhs)
547     
548   | otherwise
549         -- Don't float; the RHS isn't a value
550   = mkBinds floats rhs          `thenUs` \ rhs' ->
551     returnUs (emptyFloats, rhs')
552
553 -- mkLocalNonRec is used only for *nested*, *non-recursive* bindings
554 mkLocalNonRec :: Id  -> RhsDemand       -- Lhs: id with demand
555               -> Floats -> CoreExpr     -- Rhs: let binds in body
556               -> UniqSM Floats
557
558 mkLocalNonRec bndr dem floats rhs
559   | isUnLiftedType (idType bndr)
560         -- If this is an unlifted binding, we always make a case for it.
561   = ASSERT( not (isUnboxedTupleType (idType bndr)) )
562     let
563         float = FloatCase bndr rhs (exprOkForSpeculation rhs)
564     in
565     returnUs (addFloat floats float)
566
567   | isStrict dem 
568         -- It's a strict let so we definitely float all the bindings
569  = let          -- Don't make a case for a value binding,
570                 -- even if it's strict.  Otherwise we get
571                 --      case (\x -> e) of ...!
572         float | exprIsValue rhs = FloatLet (NonRec bndr rhs)
573               | otherwise       = FloatCase bndr rhs (exprOkForSpeculation rhs)
574     in
575     returnUs (addFloat floats float)
576
577   | otherwise
578   = floatRhs NotTopLevel NonRecursive bndr (floats, rhs)        `thenUs` \ (floats', rhs') ->
579     returnUs (addFloat floats' (FloatLet (NonRec bndr rhs')))
580
581
582 mkBinds :: Floats -> CoreExpr -> UniqSM CoreExpr
583 mkBinds (Floats _ binds) body 
584   | isNilOL binds = returnUs body
585   | otherwise     = deLam body          `thenUs` \ body' ->
586                     returnUs (foldrOL mk_bind body' binds)
587   where
588     mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
589     mk_bind (FloatLet bind)        body = Let bind body
590
591 etaExpandRhs bndr rhs
592   =     -- Eta expand to match the arity claimed by the binder
593         -- Remember, after CorePrep we must not change arity
594         --
595         -- Eta expansion might not have happened already, 
596         -- because it is done by the simplifier only when 
597         -- there at least one lambda already.
598         -- 
599         -- NB1:we could refrain when the RHS is trivial (which can happen
600         --     for exported things).  This would reduce the amount of code
601         --     generated (a little) and make things a little words for
602         --     code compiled without -O.  The case in point is data constructor
603         --     wrappers.
604         --
605         -- NB2: we have to be careful that the result of etaExpand doesn't
606         --    invalidate any of the assumptions that CorePrep is attempting
607         --    to establish.  One possible cause is eta expanding inside of
608         --    an SCC note - we're now careful in etaExpand to make sure the
609         --    SCC is pushed inside any new lambdas that are generated.
610         --
611         -- NB3: It's important to do eta expansion, and *then* ANF-ising
612         --              f = /\a -> g (h 3)      -- h has arity 2
613         -- If we ANF first we get
614         --              f = /\a -> let s = h 3 in g s
615         -- and now eta expansion gives
616         --              f = /\a -> \ y -> (let s = h 3 in g s) y
617         -- which is horrible.
618         -- Eta expanding first gives
619         --              f = /\a -> \y -> let s = h 3 in g s y
620         --
621     getUniquesUs                `thenUs` \ us ->
622     returnUs (etaExpand arity us rhs (idType bndr))
623   where
624         -- For a GlobalId, take the Arity from the Id.
625         -- It was set in CoreTidy and must not change
626         -- For all others, just expand at will
627     arity | isGlobalId bndr = idArity bndr
628           | otherwise       = exprArity rhs
629
630 -- ---------------------------------------------------------------------------
631 -- Eliminate Lam as a non-rhs (STG doesn't have such a thing)
632 -- We arrange that they only show up as the RHS of a let(rec)
633 -- ---------------------------------------------------------------------------
634
635 deLam :: CoreExpr -> UniqSM CoreExpr
636 deLam expr = 
637   deLamFloat expr   `thenUs` \ (floats, expr) ->
638   mkBinds floats expr
639
640
641 deLamFloat :: CoreExpr -> UniqSM (Floats, CoreExpr)
642 -- Remove top level lambdas by let-bindinig
643
644 deLamFloat (Note n expr)
645   =     -- You can get things like
646         --      case e of { p -> coerce t (\s -> ...) }
647     deLamFloat expr     `thenUs` \ (floats, expr') ->
648     returnUs (floats, Note n expr')
649
650 deLamFloat expr 
651   | null bndrs = returnUs (emptyFloats, expr)
652   | otherwise 
653   = case tryEta bndrs body of
654       Just no_lam_result -> returnUs (emptyFloats, no_lam_result)
655       Nothing            -> newVar (exprType expr)      `thenUs` \ fn ->
656                             returnUs (unitFloat (FloatLet (NonRec fn expr)), 
657                                       Var fn)
658   where
659     (bndrs,body) = collectBinders expr
660
661 -- Why try eta reduction?  Hasn't the simplifier already done eta?
662 -- But the simplifier only eta reduces if that leaves something
663 -- trivial (like f, or f Int).  But for deLam it would be enough to
664 -- get to a partial application, like (map f).
665
666 tryEta bndrs expr@(App _ _)
667   | ok_to_eta_reduce f &&
668     n_remaining >= 0 &&
669     and (zipWith ok bndrs last_args) &&
670     not (any (`elemVarSet` fvs_remaining) bndrs)
671   = Just remaining_expr
672   where
673     (f, args) = collectArgs expr
674     remaining_expr = mkApps f remaining_args
675     fvs_remaining = exprFreeVars remaining_expr
676     (remaining_args, last_args) = splitAt n_remaining args
677     n_remaining = length args - length bndrs
678
679     ok bndr (Var arg) = bndr == arg
680     ok bndr other     = False
681
682           -- we can't eta reduce something which must be saturated.
683     ok_to_eta_reduce (Var f) = not (hasNoBinding f)
684     ok_to_eta_reduce _       = False --safe. ToDo: generalise
685
686 tryEta bndrs (Let bind@(NonRec b r) body)
687   | not (any (`elemVarSet` fvs) bndrs)
688   = case tryEta bndrs body of
689         Just e -> Just (Let bind e)
690         Nothing -> Nothing
691   where
692     fvs = exprFreeVars r
693
694 tryEta bndrs _ = Nothing
695 \end{code}
696
697
698 -- -----------------------------------------------------------------------------
699 -- Demands
700 -- -----------------------------------------------------------------------------
701
702 \begin{code}
703 data RhsDemand
704      = RhsDemand { isStrict :: Bool,  -- True => used at least once
705                    isOnceDem   :: Bool   -- True => used at most once
706                  }
707
708 mkDem :: Demand -> Bool -> RhsDemand
709 mkDem strict once = RhsDemand (isStrictDmd strict) once
710
711 mkDemTy :: Demand -> Type -> RhsDemand
712 mkDemTy strict ty = RhsDemand (isStrictDmd strict) 
713                               False {- For now -}
714
715 bdrDem :: Id -> RhsDemand
716 bdrDem id = mkDem (idNewDemandInfo id)
717                   False {- For now -}
718
719 -- safeDem :: RhsDemand
720 -- safeDem = RhsDemand False False  -- always safe to use this
721
722 onceDem :: RhsDemand
723 onceDem = RhsDemand False True   -- used at most once
724 \end{code}
725
726
727
728
729 %************************************************************************
730 %*                                                                      *
731 \subsection{Cloning}
732 %*                                                                      *
733 %************************************************************************
734
735 \begin{code}
736 ------------------------------------------------------------------------------
737 -- Cloning binders
738 -- ---------------------------------------------------------------------------
739
740 cloneBndrs :: CloneEnv -> [Var] -> UniqSM (CloneEnv, [Var])
741 cloneBndrs env bs = mapAccumLUs cloneBndr env bs
742
743 cloneBndr  :: CloneEnv -> Var -> UniqSM (CloneEnv, Var)
744 cloneBndr env bndr
745   | isLocalId bndr
746   = getUniqueUs   `thenUs` \ uniq ->
747     let
748         bndr' = setVarUnique bndr uniq
749     in
750     returnUs (extendVarEnv env bndr bndr', bndr')
751
752   | otherwise   -- Top level things, which we don't want
753                 -- to clone, have become GlobalIds by now
754                 -- And we don't clone tyvars
755   = returnUs (env, bndr)
756   
757
758 ------------------------------------------------------------------------------
759 -- Cloning ccall Ids; each must have a unique name,
760 -- to give the code generator a handle to hang it on
761 -- ---------------------------------------------------------------------------
762
763 fiddleCCall :: Id -> UniqSM Id
764 fiddleCCall id 
765   | isFCallId id = getUniqueUs          `thenUs` \ uniq ->
766                    returnUs (id `setVarUnique` uniq)
767   | otherwise    = returnUs id
768
769 ------------------------------------------------------------------------------
770 -- Generating new binders
771 -- ---------------------------------------------------------------------------
772
773 newVar :: Type -> UniqSM Id
774 newVar ty
775  = seqType ty                   `seq`
776    getUniqueUs                  `thenUs` \ uniq ->
777    returnUs (mkSysLocal FSLIT("sat") uniq ty)
778 \end{code}