[project @ 2003-09-23 15:15:02 by simonpj]
[ghc-hetmet.git] / ghc / compiler / simplCore / Simplify.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[Simplify]{The main module of the simplifier}
5
6 \begin{code}
7 module Simplify ( simplTopBinds, simplExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( dopt, DynFlag(Opt_D_dump_inlinings),
12                           SimplifierSwitch(..)
13                         )
14 import SimplMonad
15 import SimplUtils       ( mkCase, mkLam, newId, prepareAlts,
16                           simplBinder, simplBinders, simplLamBndrs, simplRecBndrs, simplLetBndr,
17                           SimplCont(..), DupFlag(..), LetRhsFlag(..), 
18                           mkStop, mkBoringStop,  pushContArgs,
19                           contResultType, countArgs, contIsDupable, contIsRhsOrArg,
20                           getContArgs, interestingCallContext, interestingArg, isStrictType
21                         )
22 import Var              ( mustHaveLocalBinding )
23 import VarEnv
24 import Id               ( Id, idType, idInfo, idArity, isDataConWorkId, 
25                           setIdUnfolding, isDeadBinder,
26                           idNewDemandInfo, setIdInfo,
27                           setIdOccInfo, zapLamIdInfo, setOneShotLambda, 
28                         )
29 import OccName          ( encodeFS )
30 import IdInfo           ( OccInfo(..), isLoopBreaker,
31                           setArityInfo, zapDemandInfo,
32                           setUnfoldingInfo, 
33                           occInfo
34                         )
35 import NewDemand        ( isStrictDmd )
36 import DataCon          ( dataConNumInstArgs, dataConRepStrictness )
37 import CoreSyn
38 import PprCore          ( pprParendExpr, pprCoreExpr )
39 import CoreUnfold       ( mkOtherCon, mkUnfolding, callSiteInline )
40 import CoreUtils        ( exprIsDupable, exprIsTrivial, needsCaseBinding,
41                           exprIsConApp_maybe, mkPiTypes, findAlt, 
42                           exprType, exprIsValue, 
43                           exprOkForSpeculation, exprArity, 
44                           mkCoerce, mkCoerce2, mkSCC, mkInlineMe, mkAltExpr, applyTypeToArg
45                         )
46 import Rules            ( lookupRule )
47 import BasicTypes       ( isMarkedStrict )
48 import CostCentre       ( currentCCS )
49 import Type             ( isUnLiftedType, seqType, tyConAppArgs, funArgTy,
50                           splitFunTy_maybe, splitFunTy, eqType
51                         )
52 import Subst            ( mkSubst, substTy, substExpr, 
53                           isInScope, lookupIdSubst, simplIdInfo
54                         )
55 import TysPrim          ( realWorldStatePrimTy )
56 import PrelInfo         ( realWorldPrimId )
57 import BasicTypes       ( TopLevelFlag(..), isTopLevel, 
58                           RecFlag(..), isNonRec
59                         )
60 import OrdList
61 import Maybe            ( Maybe )
62 import Maybes           ( orElse )
63 import Outputable
64 import Util             ( notNull )
65 \end{code}
66
67
68 The guts of the simplifier is in this module, but the driver loop for
69 the simplifier is in SimplCore.lhs.
70
71
72 -----------------------------------------
73         *** IMPORTANT NOTE ***
74 -----------------------------------------
75 The simplifier used to guarantee that the output had no shadowing, but
76 it does not do so any more.   (Actually, it never did!)  The reason is
77 documented with simplifyArgs.
78
79
80 -----------------------------------------
81         *** IMPORTANT NOTE ***
82 -----------------------------------------
83 Many parts of the simplifier return a bunch of "floats" as well as an
84 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
85
86 All "floats" are let-binds, not case-binds, but some non-rec lets may
87 be unlifted (with RHS ok-for-speculation).
88
89
90
91 -----------------------------------------
92         ORGANISATION OF FUNCTIONS
93 -----------------------------------------
94 simplTopBinds
95   - simplify all top-level binders
96   - for NonRec, call simplRecOrTopPair
97   - for Rec,    call simplRecBind
98
99         
100         ------------------------------
101 simplExpr (applied lambda)      ==> simplNonRecBind
102 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
103 simplExpr (Let (Rec ...)    ..) ==> simplify binders; simplRecBind
104
105         ------------------------------
106 simplRecBind    [binders already simplfied]
107   - use simplRecOrTopPair on each pair in turn
108
109 simplRecOrTopPair [binder already simplified]
110   Used for: recursive bindings (top level and nested)
111             top-level non-recursive bindings
112   Returns: 
113   - check for PreInlineUnconditionally
114   - simplLazyBind
115
116 simplNonRecBind
117   Used for: non-top-level non-recursive bindings
118             beta reductions (which amount to the same thing)
119   Because it can deal with strict arts, it takes a 
120         "thing-inside" and returns an expression
121
122   - check for PreInlineUnconditionally
123   - simplify binder, including its IdInfo
124   - if strict binding
125         simplStrictArg
126         mkAtomicArgs
127         completeNonRecX
128     else
129         simplLazyBind
130         addFloats
131
132 simplNonRecX:   [given a *simplified* RHS, but an *unsimplified* binder]
133   Used for: binding case-binder and constr args in a known-constructor case
134   - check for PreInLineUnconditionally
135   - simplify binder
136   - completeNonRecX
137  
138         ------------------------------
139 simplLazyBind:  [binder already simplified, RHS not]
140   Used for: recursive bindings (top level and nested)
141             top-level non-recursive bindings
142             non-top-level, but *lazy* non-recursive bindings
143         [must not be strict or unboxed]
144   Returns floats + an augmented environment, not an expression
145   - substituteIdInfo and add result to in-scope 
146         [so that rules are available in rec rhs]
147   - simplify rhs
148   - mkAtomicArgs
149   - float if exposes constructor or PAP
150   - completeLazyBind
151
152
153 completeNonRecX:        [binder and rhs both simplified]
154   - if the the thing needs case binding (unlifted and not ok-for-spec)
155         build a Case
156    else
157         completeLazyBind
158         addFloats
159
160 completeLazyBind:       [given a simplified RHS]
161         [used for both rec and non-rec bindings, top level and not]
162   - try PostInlineUnconditionally
163   - add unfolding [this is the only place we add an unfolding]
164   - add arity
165
166
167
168 Right hand sides and arguments
169 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170 In many ways we want to treat 
171         (a) the right hand side of a let(rec), and 
172         (b) a function argument
173 in the same way.  But not always!  In particular, we would
174 like to leave these arguments exactly as they are, so they
175 will match a RULE more easily.
176         
177         f (g x, h x)    
178         g (+ x)
179
180 It's harder to make the rule match if we ANF-ise the constructor,
181 or eta-expand the PAP:
182
183         f (let { a = g x; b = h x } in (a,b))
184         g (\y. + x y)
185
186 On the other hand if we see the let-defns
187
188         p = (g x, h x)
189         q = + x
190
191 then we *do* want to ANF-ise and eta-expand, so that p and q
192 can be safely inlined.   
193
194 Even floating lets out is a bit dubious.  For let RHS's we float lets
195 out if that exposes a value, so that the value can be inlined more vigorously.
196 For example
197
198         r = let x = e in (x,x)
199
200 Here, if we float the let out we'll expose a nice constructor. We did experiments
201 that showed this to be a generally good thing.  But it was a bad thing to float
202 lets out unconditionally, because that meant they got allocated more often.
203
204 For function arguments, there's less reason to expose a constructor (it won't
205 get inlined).  Just possibly it might make a rule match, but I'm pretty skeptical.
206 So for the moment we don't float lets out of function arguments either.
207
208
209 Eta expansion
210 ~~~~~~~~~~~~~~
211 For eta expansion, we want to catch things like
212
213         case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
214
215 If the \x was on the RHS of a let, we'd eta expand to bring the two
216 lambdas together.  And in general that's a good thing to do.  Perhaps
217 we should eta expand wherever we find a (value) lambda?  Then the eta
218 expansion at a let RHS can concentrate solely on the PAP case.
219
220
221 %************************************************************************
222 %*                                                                      *
223 \subsection{Bindings}
224 %*                                                                      *
225 %************************************************************************
226
227 \begin{code}
228 simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
229
230 simplTopBinds env binds
231   =     -- Put all the top-level binders into scope at the start
232         -- so that if a transformation rule has unexpectedly brought
233         -- anything into scope, then we don't get a complaint about that.
234         -- It's rather as if the top-level binders were imported.
235     simplRecBndrs env (bindersOfBinds binds)    `thenSmpl` \ (env, bndrs') -> 
236     simpl_binds env binds bndrs'                `thenSmpl` \ (floats, _) ->
237     freeTick SimplifierDone                     `thenSmpl_`
238     returnSmpl (floatBinds floats)
239   where
240         -- We need to track the zapped top-level binders, because
241         -- they should have their fragile IdInfo zapped (notably occurrence info)
242         -- That's why we run down binds and bndrs' simultaneously.
243     simpl_binds :: SimplEnv -> [InBind] -> [OutId] -> SimplM (FloatsWith ())
244     simpl_binds env []           bs = ASSERT( null bs ) returnSmpl (emptyFloats env, ())
245     simpl_binds env (bind:binds) bs = simpl_bind env bind bs            `thenSmpl` \ (floats,env) ->
246                                       addFloats env floats              $ \env -> 
247                                       simpl_binds env binds (drop_bs bind bs)
248
249     drop_bs (NonRec _ _) (_ : bs) = bs
250     drop_bs (Rec prs)    bs       = drop (length prs) bs
251
252     simpl_bind env bind bs 
253       = getDOptsSmpl                            `thenSmpl` \ dflags ->
254         if dopt Opt_D_dump_inlinings dflags then
255            pprTrace "SimplBind" (ppr (bindersOf bind)) $ simpl_bind1 env bind bs
256         else
257            simpl_bind1 env bind bs
258
259     simpl_bind1 env (NonRec b r) (b':_) = simplRecOrTopPair env TopLevel b b' r
260     simpl_bind1 env (Rec pairs)  bs'    = simplRecBind      env TopLevel pairs bs'
261 \end{code}
262
263
264 %************************************************************************
265 %*                                                                      *
266 \subsection{simplNonRec}
267 %*                                                                      *
268 %************************************************************************
269
270 simplNonRecBind is used for
271   * non-top-level non-recursive lets in expressions
272   * beta reduction
273
274 It takes 
275   * An unsimplified (binder, rhs) pair
276   * The env for the RHS.  It may not be the same as the
277         current env because the bind might occur via (\x.E) arg
278
279 It uses the CPS form because the binding might be strict, in which
280 case we might discard the continuation:
281         let x* = error "foo" in (...x...)
282
283 It needs to turn unlifted bindings into a @case@.  They can arise
284 from, say:      (\x -> e) (4# + 3#)
285
286 \begin{code}
287 simplNonRecBind :: SimplEnv
288                 -> InId                                 -- Binder
289                 -> InExpr -> SimplEnv                   -- Arg, with its subst-env
290                 -> OutType                              -- Type of thing computed by the context
291                 -> (SimplEnv -> SimplM FloatsWithExpr)  -- The body
292                 -> SimplM FloatsWithExpr
293 #ifdef DEBUG
294 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
295   | isTyVar bndr
296   = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
297 #endif
298
299 simplNonRecBind env bndr rhs rhs_se cont_ty thing_inside
300   | preInlineUnconditionally env NotTopLevel bndr
301   = tick (PreInlineUnconditionally bndr)                `thenSmpl_`
302     thing_inside (extendSubst env bndr (ContEx (getSubstEnv rhs_se) rhs))
303
304
305   | isStrictDmd (idNewDemandInfo bndr) || isStrictType (idType bndr)    -- A strict let
306   =     -- Don't use simplBinder because that doesn't keep 
307         -- fragile occurrence info in the substitution
308     simplLetBndr env bndr                                       `thenSmpl` \ (env, bndr1) ->
309     simplStrictArg AnRhs env rhs rhs_se (idType bndr1) cont_ty  $ \ env1 rhs1 ->
310
311         -- Now complete the binding and simplify the body
312     let
313         -- simplLetBndr doesn't deal with the IdInfo, so we must
314         -- do so here (c.f. simplLazyBind)
315         bndr2  = bndr1 `setIdInfo` simplIdInfo (getSubst env) (idInfo bndr)
316         env2   = modifyInScope env1 bndr2 bndr2
317     in
318     completeNonRecX env2 True {- strict -} bndr bndr2 rhs1 thing_inside
319
320   | otherwise                                                   -- Normal, lazy case
321   =     -- Don't use simplBinder because that doesn't keep 
322         -- fragile occurrence info in the substitution
323     simplLetBndr env bndr                               `thenSmpl` \ (env, bndr') ->
324     simplLazyBind env NotTopLevel NonRecursive
325                   bndr bndr' rhs rhs_se                 `thenSmpl` \ (floats, env) ->
326     addFloats env floats thing_inside
327 \end{code}
328
329 A specialised variant of simplNonRec used when the RHS is already simplified, notably
330 in knownCon.  It uses case-binding where necessary.
331
332 \begin{code}
333 simplNonRecX :: SimplEnv
334              -> InId            -- Old binder
335              -> OutExpr         -- Simplified RHS
336              -> (SimplEnv -> SimplM FloatsWithExpr)
337              -> SimplM FloatsWithExpr
338
339 simplNonRecX env bndr new_rhs thing_inside
340   | needsCaseBinding (idType bndr) new_rhs
341         -- Make this test *before* the preInlineUnconditionally
342         -- Consider     case I# (quotInt# x y) of 
343         --                I# v -> let w = J# v in ...
344         -- If we gaily inline (quotInt# x y) for v, we end up building an
345         -- extra thunk:
346         --                let w = J# (quotInt# x y) in ...
347         -- because quotInt# can fail.
348   = simplBinder env bndr        `thenSmpl` \ (env, bndr') ->
349     thing_inside env            `thenSmpl` \ (floats, body) ->
350     returnSmpl (emptyFloats env, Case new_rhs bndr' [(DEFAULT, [], wrapFloats floats body)])
351
352   | preInlineUnconditionally env NotTopLevel  bndr
353         -- This happens; for example, the case_bndr during case of
354         -- known constructor:  case (a,b) of x { (p,q) -> ... }
355         -- Here x isn't mentioned in the RHS, so we don't want to
356         -- create the (dead) let-binding  let x = (a,b) in ...
357         --
358         -- Similarly, single occurrences can be inlined vigourously
359         -- e.g.  case (f x, g y) of (a,b) -> ....
360         -- If a,b occur once we can avoid constructing the let binding for them.
361   = thing_inside (extendSubst env bndr (ContEx emptySubstEnv new_rhs))
362
363   | otherwise
364   = simplBinder env bndr        `thenSmpl` \ (env, bndr') ->
365     completeNonRecX env False {- Non-strict; pessimistic -} 
366                     bndr bndr' new_rhs thing_inside
367
368 completeNonRecX env is_strict old_bndr new_bndr new_rhs thing_inside
369   = mkAtomicArgs is_strict 
370                  True {- OK to float unlifted -} 
371                  new_rhs                        `thenSmpl` \ (aux_binds, rhs2) ->
372
373         -- Make the arguments atomic if necessary, 
374         -- adding suitable bindings
375     addAtomicBindsE env (fromOL aux_binds)      $ \ env ->
376     completeLazyBind env NotTopLevel
377                      old_bndr new_bndr rhs2     `thenSmpl` \ (floats, env) ->
378     addFloats env floats thing_inside
379 \end{code}
380
381
382 %************************************************************************
383 %*                                                                      *
384 \subsection{Lazy bindings}
385 %*                                                                      *
386 %************************************************************************
387
388 simplRecBind is used for
389         * recursive bindings only
390
391 \begin{code}
392 simplRecBind :: SimplEnv -> TopLevelFlag
393              -> [(InId, InExpr)] -> [OutId]
394              -> SimplM (FloatsWith SimplEnv)
395 simplRecBind env top_lvl pairs bndrs'
396   = go env pairs bndrs'         `thenSmpl` \ (floats, env) ->
397     returnSmpl (flattenFloats floats, env)
398   where
399     go env [] _ = returnSmpl (emptyFloats env, env)
400         
401     go env ((bndr, rhs) : pairs) (bndr' : bndrs')
402         = simplRecOrTopPair env top_lvl bndr bndr' rhs  `thenSmpl` \ (floats, env) ->
403           addFloats env floats (\env -> go env pairs bndrs')
404 \end{code}
405
406
407 simplRecOrTopPair is used for
408         * recursive bindings (whether top level or not)
409         * top-level non-recursive bindings
410
411 It assumes the binder has already been simplified, but not its IdInfo.
412
413 \begin{code}
414 simplRecOrTopPair :: SimplEnv
415                   -> TopLevelFlag
416                   -> InId -> OutId              -- Binder, both pre-and post simpl
417                   -> InExpr                     -- The RHS and its environment
418                   -> SimplM (FloatsWith SimplEnv)
419
420 simplRecOrTopPair env top_lvl bndr bndr' rhs
421   | preInlineUnconditionally env top_lvl bndr   -- Check for unconditional inline
422   = tick (PreInlineUnconditionally bndr)        `thenSmpl_`
423     returnSmpl (emptyFloats env, extendSubst env bndr (ContEx (getSubstEnv env) rhs))
424
425   | otherwise
426   = simplLazyBind env top_lvl Recursive bndr bndr' rhs env
427         -- May not actually be recursive, but it doesn't matter
428 \end{code}
429
430
431 simplLazyBind is used for
432         * recursive bindings (whether top level or not)
433         * top-level non-recursive bindings
434         * non-top-level *lazy* non-recursive bindings
435
436 [Thus it deals with the lazy cases from simplNonRecBind, and all cases
437 from SimplRecOrTopBind]
438
439 Nota bene:
440     1. It assumes that the binder is *already* simplified, 
441        and is in scope, but not its IdInfo
442
443     2. It assumes that the binder type is lifted.
444
445     3. It does not check for pre-inline-unconditionallly;
446        that should have been done already.
447
448 \begin{code}
449 simplLazyBind :: SimplEnv
450               -> TopLevelFlag -> RecFlag
451               -> InId -> OutId          -- Binder, both pre-and post simpl
452               -> InExpr -> SimplEnv     -- The RHS and its environment
453               -> SimplM (FloatsWith SimplEnv)
454
455 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
456   = let -- Transfer the IdInfo of the original binder to the new binder
457         -- This is crucial: we must preserve
458         --      strictness
459         --      rules
460         --      worker info
461         -- etc.  To do this we must apply the current substitution, 
462         -- which incorporates earlier substitutions in this very letrec group.
463         --
464         -- NB 1.  We do this *before* processing the RHS of the binder, so that
465         -- its substituted rules are visible in its own RHS.
466         -- This is important.  Manuel found cases where he really, really
467         -- wanted a RULE for a recursive function to apply in that function's
468         -- own right-hand side.
469         --
470         -- NB 2: We do not transfer the arity (see Subst.substIdInfo)
471         -- The arity of an Id should not be visible
472         -- in its own RHS, else we eta-reduce
473         --      f = \x -> f x
474         -- to
475         --      f = f
476         -- which isn't sound.  And it makes the arity in f's IdInfo greater than
477         -- the manifest arity, which isn't good.
478         -- The arity will get added later.
479         --
480         -- NB 3: It's important that we *do* transer the loop-breaker OccInfo,
481         -- because that's what stops the Id getting inlined infinitely, in the body
482         -- of the letrec.
483
484         -- NB 4: does no harm for non-recursive bindings
485
486         bndr2             = bndr1 `setIdInfo` simplIdInfo (getSubst env) (idInfo bndr)
487         env1              = modifyInScope env bndr2 bndr2
488         rhs_env           = setInScope rhs_se env1
489         is_top_level      = isTopLevel top_lvl
490         ok_float_unlifted = not is_top_level && isNonRec is_rec
491         rhs_cont          = mkStop (idType bndr1) AnRhs
492     in
493         -- Simplify the RHS; note the mkStop, which tells 
494         -- the simplifier that this is the RHS of a let.
495     simplExprF rhs_env rhs rhs_cont             `thenSmpl` \ (floats, rhs1) ->
496
497         -- If any of the floats can't be floated, give up now
498         -- (The allLifted predicate says True for empty floats.)
499     if (not ok_float_unlifted && not (allLifted floats)) then
500         completeLazyBind env1 top_lvl bndr bndr2
501                          (wrapFloats floats rhs1)
502     else        
503
504         -- ANF-ise a constructor or PAP rhs
505     mkAtomicArgs False {- Not strict -} 
506                  ok_float_unlifted rhs1                 `thenSmpl` \ (aux_binds, rhs2) ->
507
508         -- If the result is a PAP, float the floats out, else wrap them
509         -- By this time it's already been ANF-ised (if necessary)
510     if isEmptyFloats floats && isNilOL aux_binds then   -- Shortcut a common case
511         completeLazyBind env1 top_lvl bndr bndr2 rhs2
512
513     else if is_top_level || exprIsTrivial rhs2 || exprIsValue rhs2 then
514         --      WARNING: long dodgy argument coming up
515         --      WANTED: a better way to do this
516         --              
517         -- We can't use "exprIsCheap" instead of exprIsValue, 
518         -- because that causes a strictness bug.
519         --         x = let y* = E in case (scc y) of { T -> F; F -> T}
520         -- The case expression is 'cheap', but it's wrong to transform to
521         --         y* = E; x = case (scc y) of {...}
522         -- Either we must be careful not to float demanded non-values, or
523         -- we must use exprIsValue for the test, which ensures that the
524         -- thing is non-strict.  So exprIsValue => bindings are non-strict
525         -- I think.  The WARN below tests for this.
526         --
527         -- We use exprIsTrivial here because we want to reveal lone variables.  
528         -- E.g.  let { x = letrec { y = E } in y } in ...
529         -- Here we definitely want to float the y=E defn. 
530         -- exprIsValue definitely isn't right for that.
531         --
532         -- Again, the floated binding can't be strict; if it's recursive it'll
533         -- be non-strict; if it's non-recursive it'd be inlined.
534         --
535         -- Note [SCC-and-exprIsTrivial]
536         -- If we have
537         --      y = let { x* = E } in scc "foo" x
538         -- then we do *not* want to float out the x binding, because
539         -- it's strict!  Fortunately, exprIsTrivial replies False to
540         -- (scc "foo" x).
541
542                 -- There's a subtlety here.  There may be a binding (x* = e) in the
543                 -- floats, where the '*' means 'will be demanded'.  So is it safe
544                 -- to float it out?  Answer no, but it won't matter because
545                 -- we only float if (a) arg' is a WHNF, or (b) it's going to top level
546                 -- and so there can't be any 'will be demanded' bindings in the floats.
547                 -- Hence the warning
548         ASSERT2( is_top_level || not (any demanded_float (floatBinds floats)), 
549                  ppr (filter demanded_float (floatBinds floats)) )
550
551         tick LetFloatFromLet                    `thenSmpl_` (
552         addFloats env1 floats                   $ \ env2 ->
553         addAtomicBinds env2 (fromOL aux_binds)  $ \ env3 ->
554         completeLazyBind env3 top_lvl bndr bndr2 rhs2)
555
556     else
557         completeLazyBind env1 top_lvl bndr bndr2 (wrapFloats floats rhs1)
558
559 #ifdef DEBUG
560 demanded_float (NonRec b r) = isStrictDmd (idNewDemandInfo b) && not (isUnLiftedType (idType b))
561                 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
562 demanded_float (Rec _)      = False
563 #endif
564 \end{code}
565
566
567 %************************************************************************
568 %*                                                                      *
569 \subsection{Completing a lazy binding}
570 %*                                                                      *
571 %************************************************************************
572
573 completeLazyBind
574         * deals only with Ids, not TyVars
575         * takes an already-simplified binder and RHS
576         * is used for both recursive and non-recursive bindings
577         * is used for both top-level and non-top-level bindings
578
579 It does the following:
580   - tries discarding a dead binding
581   - tries PostInlineUnconditionally
582   - add unfolding [this is the only place we add an unfolding]
583   - add arity
584
585 It does *not* attempt to do let-to-case.  Why?  Because it is used for
586         - top-level bindings (when let-to-case is impossible) 
587         - many situations where the "rhs" is known to be a WHNF
588                 (so let-to-case is inappropriate).
589
590 \begin{code}
591 completeLazyBind :: SimplEnv
592                  -> TopLevelFlag        -- Flag stuck into unfolding
593                  -> InId                -- Old binder
594                  -> OutId               -- New binder
595                  -> OutExpr             -- Simplified RHS
596                  -> SimplM (FloatsWith SimplEnv)
597 -- We return a new SimplEnv, because completeLazyBind may choose to do its work
598 -- by extending the substitution (e.g. let x = y in ...)
599 -- The new binding (if any) is returned as part of the floats.
600 -- NB: the returned SimplEnv has the right SubstEnv, but you should
601 --     (as usual) use the in-scope-env from the floats
602
603 completeLazyBind env top_lvl old_bndr new_bndr new_rhs
604   | postInlineUnconditionally env new_bndr occ_info new_rhs
605   =             -- Drop the binding
606     tick (PostInlineUnconditionally old_bndr)   `thenSmpl_`
607     returnSmpl (emptyFloats env, extendSubst env old_bndr (DoneEx new_rhs))
608                 -- Use the substitution to make quite, quite sure that the substitution
609                 -- will happen, since we are going to discard the binding
610
611   |  otherwise
612   = let
613                 -- Add arity info
614         new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
615
616         -- Add the unfolding *only* for non-loop-breakers
617         -- Making loop breakers not have an unfolding at all 
618         -- means that we can avoid tests in exprIsConApp, for example.
619         -- This is important: if exprIsConApp says 'yes' for a recursive
620         -- thing, then we can get into an infinite loop
621
622         -- If the unfolding is a value, the demand info may
623         -- go pear-shaped, so we nuke it.  Example:
624         --      let x = (a,b) in
625         --      case x of (p,q) -> h p q x
626         -- Here x is certainly demanded. But after we've nuked
627         -- the case, we'll get just
628         --      let x = (a,b) in h a b x
629         -- and now x is not demanded (I'm assuming h is lazy)
630         -- This really happens.  Similarly
631         --      let f = \x -> e in ...f..f...
632         -- After inling f at some of its call sites the original binding may
633         -- (for example) be no longer strictly demanded.
634         -- The solution here is a bit ad hoc...
635         unfolding  = mkUnfolding (isTopLevel top_lvl) new_rhs
636         info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
637         final_info | loop_breaker               = new_bndr_info
638                    | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
639                    | otherwise                  = info_w_unf
640
641         final_id = new_bndr `setIdInfo` final_info
642     in
643                 -- These seqs forces the Id, and hence its IdInfo,
644                 -- and hence any inner substitutions
645     final_id                                    `seq`
646     returnSmpl (unitFloat env final_id new_rhs, env)
647
648   where 
649     loop_breaker = isLoopBreaker occ_info
650     old_info     = idInfo old_bndr
651     occ_info     = occInfo old_info
652 \end{code}    
653
654
655
656 %************************************************************************
657 %*                                                                      *
658 \subsection[Simplify-simplExpr]{The main function: simplExpr}
659 %*                                                                      *
660 %************************************************************************
661
662 The reason for this OutExprStuff stuff is that we want to float *after*
663 simplifying a RHS, not before.  If we do so naively we get quadratic
664 behaviour as things float out.
665
666 To see why it's important to do it after, consider this (real) example:
667
668         let t = f x
669         in fst t
670 ==>
671         let t = let a = e1
672                     b = e2
673                 in (a,b)
674         in fst t
675 ==>
676         let a = e1
677             b = e2
678             t = (a,b)
679         in
680         a       -- Can't inline a this round, cos it appears twice
681 ==>
682         e1
683
684 Each of the ==> steps is a round of simplification.  We'd save a
685 whole round if we float first.  This can cascade.  Consider
686
687         let f = g d
688         in \x -> ...f...
689 ==>
690         let f = let d1 = ..d.. in \y -> e
691         in \x -> ...f...
692 ==>
693         let d1 = ..d..
694         in \x -> ...(\y ->e)...
695
696 Only in this second round can the \y be applied, and it 
697 might do the same again.
698
699
700 \begin{code}
701 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
702 simplExpr env expr = simplExprC env expr (mkStop expr_ty' AnArg)
703                    where
704                      expr_ty' = substTy (getSubst env) (exprType expr)
705         -- The type in the Stop continuation, expr_ty', is usually not used
706         -- It's only needed when discarding continuations after finding
707         -- a function that returns bottom.
708         -- Hence the lazy substitution
709
710
711 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
712         -- Simplify an expression, given a continuation
713 simplExprC env expr cont 
714   = simplExprF env expr cont    `thenSmpl` \ (floats, expr) ->
715     returnSmpl (wrapFloats floats expr)
716
717 simplExprF :: SimplEnv -> InExpr -> SimplCont -> SimplM FloatsWithExpr
718         -- Simplify an expression, returning floated binds
719
720 simplExprF env (Var v)          cont = simplVar env v cont
721 simplExprF env (Lit lit)        cont = rebuild env (Lit lit) cont
722 simplExprF env expr@(Lam _ _)   cont = simplLam env expr cont
723 simplExprF env (Note note expr) cont = simplNote env note expr cont
724 simplExprF env (App fun arg)    cont = simplExprF env fun (ApplyTo NoDup arg env cont)
725
726 simplExprF env (Type ty) cont
727   = ASSERT( contIsRhsOrArg cont )
728     simplType env ty                    `thenSmpl` \ ty' ->
729     rebuild env (Type ty') cont
730
731 simplExprF env (Case scrut bndr alts) cont
732   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
733   =     -- Simplify the scrutinee with a Select continuation
734     simplExprF env scrut (Select NoDup bndr alts env cont)
735
736   | otherwise
737   =     -- If case-of-case is off, simply simplify the case expression
738         -- in a vanilla Stop context, and rebuild the result around it
739     simplExprC env scrut case_cont      `thenSmpl` \ case_expr' ->
740     rebuild env case_expr' cont
741   where
742     case_cont = Select NoDup bndr alts env (mkBoringStop (contResultType cont))
743
744 simplExprF env (Let (Rec pairs) body) cont
745   = simplRecBndrs env (map fst pairs)           `thenSmpl` \ (env, bndrs') -> 
746         -- NB: bndrs' don't have unfoldings or rules
747         -- We add them as we go down
748
749     simplRecBind env NotTopLevel pairs bndrs'   `thenSmpl` \ (floats, env) ->
750     addFloats env floats                        $ \ env ->
751     simplExprF env body cont
752
753 -- A non-recursive let is dealt with by simplNonRecBind
754 simplExprF env (Let (NonRec bndr rhs) body) cont
755   = simplNonRecBind env bndr rhs env (contResultType cont)      $ \ env ->
756     simplExprF env body cont
757
758
759 ---------------------------------
760 simplType :: SimplEnv -> InType -> SimplM OutType
761         -- Kept monadic just so we can do the seqType
762 simplType env ty
763   = seqType new_ty   `seq`   returnSmpl new_ty
764   where
765     new_ty = substTy (getSubst env) ty
766 \end{code}
767
768
769 %************************************************************************
770 %*                                                                      *
771 \subsection{Lambdas}
772 %*                                                                      *
773 %************************************************************************
774
775 \begin{code}
776 simplLam env fun cont
777   = go env fun cont
778   where
779     zap_it  = mkLamBndrZapper fun (countArgs cont)
780     cont_ty = contResultType cont
781
782         -- Type-beta reduction
783     go env (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
784       = ASSERT( isTyVar bndr )
785         tick (BetaReduction bndr)                       `thenSmpl_`
786         simplType (setInScope arg_se env) ty_arg        `thenSmpl` \ ty_arg' ->
787         go (extendSubst env bndr (DoneTy ty_arg')) body body_cont
788
789         -- Ordinary beta reduction
790     go env (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
791       = tick (BetaReduction bndr)                               `thenSmpl_`
792         simplNonRecBind env (zap_it bndr) arg arg_se cont_ty    $ \ env -> 
793         go env body body_cont
794
795         -- Not enough args, so there are real lambdas left to put in the result
796     go env lam@(Lam _ _) cont
797       = simplLamBndrs env bndrs         `thenSmpl` \ (env, bndrs') ->
798         simplExpr env body              `thenSmpl` \ body' ->
799         mkLam env bndrs' body' cont     `thenSmpl` \ (floats, new_lam) ->
800         addFloats env floats            $ \ env -> 
801         rebuild env new_lam cont
802       where
803         (bndrs,body) = collectBinders lam
804
805         -- Exactly enough args
806     go env expr cont = simplExprF env expr cont
807
808 mkLamBndrZapper :: CoreExpr     -- Function
809                 -> Int          -- Number of args supplied, *including* type args
810                 -> Id -> Id     -- Use this to zap the binders
811 mkLamBndrZapper fun n_args
812   | n_args >= n_params fun = \b -> b            -- Enough args
813   | otherwise              = \b -> zapLamIdInfo b
814   where
815         -- NB: we count all the args incl type args
816         -- so we must count all the binders (incl type lambdas)
817     n_params (Note _ e) = n_params e
818     n_params (Lam b e)  = 1 + n_params e
819     n_params other      = 0::Int
820 \end{code}
821
822
823 %************************************************************************
824 %*                                                                      *
825 \subsection{Notes}
826 %*                                                                      *
827 %************************************************************************
828
829 \begin{code}
830 simplNote env (Coerce to from) body cont
831   = let
832         in_scope = getInScope env 
833
834         addCoerce s1 k1 (CoerceIt t1 cont)
835                 --      coerce T1 S1 (coerce S1 K1 e)
836                 -- ==>
837                 --      e,                      if T1=K1
838                 --      coerce T1 K1 e,         otherwise
839                 --
840                 -- For example, in the initial form of a worker
841                 -- we may find  (coerce T (coerce S (\x.e))) y
842                 -- and we'd like it to simplify to e[y/x] in one round 
843                 -- of simplification
844           | t1 `eqType` k1  = cont              -- The coerces cancel out
845           | otherwise       = CoerceIt t1 cont  -- They don't cancel, but 
846                                                 -- the inner one is redundant
847
848         addCoerce t1t2 s1s2 (ApplyTo dup arg arg_se cont)
849           | not (isTypeArg arg),        -- This whole case only works for value args
850                                         -- Could upgrade to have equiv thing for type apps too  
851             Just (s1, s2) <- splitFunTy_maybe s1s2
852                 --      (coerce (T1->T2) (S1->S2) F) E
853                 -- ===> 
854                 --      coerce T2 S2 (F (coerce S1 T1 E))
855                 --
856                 -- t1t2 must be a function type, T1->T2, because it's applied to something
857                 -- but s1s2 might conceivably not be
858                 --
859                 -- When we build the ApplyTo we can't mix the out-types
860                 -- with the InExpr in the argument, so we simply substitute
861                 -- to make it all consistent.  It's a bit messy.
862                 -- But it isn't a common case.
863           = let 
864                 (t1,t2) = splitFunTy t1t2
865                 new_arg = mkCoerce2 s1 t1 (substExpr (mkSubst in_scope (getSubstEnv arg_se)) arg)
866             in
867             ApplyTo dup new_arg (zapSubstEnv env) (addCoerce t2 s2 cont)
868                         
869         addCoerce to' _ cont = CoerceIt to' cont
870     in
871     simplType env to            `thenSmpl` \ to' ->
872     simplType env from          `thenSmpl` \ from' ->
873     simplExprF env body (addCoerce to' from' cont)
874
875                 
876 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
877 -- inlining.  All other CCCSs are mapped to currentCCS.
878 simplNote env (SCC cc) e cont
879   = simplExpr (setEnclosingCC env currentCCS) e         `thenSmpl` \ e' ->
880     rebuild env (mkSCC cc e') cont
881
882 simplNote env InlineCall e cont
883   = simplExprF env e (InlinePlease cont)
884
885 -- See notes with SimplMonad.inlineMode
886 simplNote env InlineMe e cont
887   | contIsRhsOrArg cont         -- Totally boring continuation; see notes above
888   =                             -- Don't inline inside an INLINE expression
889     simplExpr (setMode inlineMode env )  e      `thenSmpl` \ e' ->
890     rebuild env (mkInlineMe e') cont
891
892   | otherwise   -- Dissolve the InlineMe note if there's
893                 -- an interesting context of any kind to combine with
894                 -- (even a type application -- anything except Stop)
895   = simplExprF env e cont
896
897 simplNote env (CoreNote s) e cont
898   = simplExpr env e    `thenSmpl` \ e' ->
899     rebuild env (Note (CoreNote s) e') cont
900 \end{code}
901
902
903 %************************************************************************
904 %*                                                                      *
905 \subsection{Dealing with calls}
906 %*                                                                      *
907 %************************************************************************
908
909 \begin{code}
910 simplVar env var cont
911   = case lookupIdSubst (getSubst env) var of
912         DoneEx e        -> simplExprF (zapSubstEnv env) e cont
913         ContEx se e     -> simplExprF (setSubstEnv env se) e cont
914         DoneId var1 occ -> WARN( not (isInScope var1 (getSubst env)) && mustHaveLocalBinding var1,
915                                  text "simplVar:" <+> ppr var )
916                            completeCall (zapSubstEnv env) var1 occ cont
917                 -- The template is already simplified, so don't re-substitute.
918                 -- This is VITAL.  Consider
919                 --      let x = e in
920                 --      let y = \z -> ...x... in
921                 --      \ x -> ...y...
922                 -- We'll clone the inner \x, adding x->x' in the id_subst
923                 -- Then when we inline y, we must *not* replace x by x' in
924                 -- the inlined copy!!
925
926 ---------------------------------------------------------
927 --      Dealing with a call site
928
929 completeCall env var occ_info cont
930   =     -- Simplify the arguments
931     getDOptsSmpl                                        `thenSmpl` \ dflags ->
932     let
933         chkr                           = getSwitchChecker env
934         (args, call_cont, inline_call) = getContArgs chkr var cont
935         fn_ty                          = idType var
936     in
937     simplifyArgs env fn_ty args (contResultType call_cont)      $ \ env args ->
938
939         -- Next, look for rules or specialisations that match
940         --
941         -- It's important to simplify the args first, because the rule-matcher
942         -- doesn't do substitution as it goes.  We don't want to use subst_args
943         -- (defined in the 'where') because that throws away useful occurrence info,
944         -- and perhaps-very-important specialisations.
945         --
946         -- Some functions have specialisations *and* are strict; in this case,
947         -- we don't want to inline the wrapper of the non-specialised thing; better
948         -- to call the specialised thing instead.
949         -- We used to use the black-listing mechanism to ensure that inlining of 
950         -- the wrapper didn't occur for things that have specialisations till a 
951         -- later phase, so but now we just try RULES first
952         --
953         -- You might think that we shouldn't apply rules for a loop breaker: 
954         -- doing so might give rise to an infinite loop, because a RULE is
955         -- rather like an extra equation for the function:
956         --      RULE:           f (g x) y = x+y
957         --      Eqn:            f a     y = a-y
958         --
959         -- But it's too drastic to disable rules for loop breakers.  
960         -- Even the foldr/build rule would be disabled, because foldr 
961         -- is recursive, and hence a loop breaker:
962         --      foldr k z (build g) = g k z
963         -- So it's up to the programmer: rules can cause divergence
964
965     let
966         in_scope   = getInScope env
967         maybe_rule = case activeRule env of
968                         Nothing     -> Nothing  -- No rules apply
969                         Just act_fn -> lookupRule act_fn in_scope var args 
970     in
971     case maybe_rule of {
972         Just (rule_name, rule_rhs) -> 
973                 tick (RuleFired rule_name)                      `thenSmpl_`
974                 (if dopt Opt_D_dump_inlinings dflags then
975                    pprTrace "Rule fired" (vcat [
976                         text "Rule:" <+> ftext rule_name,
977                         text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
978                         text "After: " <+> pprCoreExpr rule_rhs,
979                         text "Cont:  " <+> ppr call_cont])
980                  else
981                         id)             $
982                 simplExprF env rule_rhs call_cont ;
983         
984         Nothing ->              -- No rules
985
986         -- Next, look for an inlining
987     let
988         arg_infos = [ interestingArg arg | arg <- args, isValArg arg]
989
990         interesting_cont = interestingCallContext (notNull args)
991                                                   (notNull arg_infos)
992                                                   call_cont
993
994         active_inline = activeInline env var occ_info
995         maybe_inline  = callSiteInline dflags active_inline inline_call occ_info
996                                        var arg_infos interesting_cont
997     in
998     case maybe_inline of {
999         Just unfolding          -- There is an inlining!
1000           ->  tick (UnfoldingDone var)          `thenSmpl_`
1001               makeThatCall env var unfolding args call_cont
1002
1003         ;
1004         Nothing ->              -- No inlining!
1005
1006         -- Done
1007     rebuild env (mkApps (Var var) args) call_cont
1008     }}
1009
1010 makeThatCall :: SimplEnv
1011              -> Id
1012              -> InExpr          -- Inlined function rhs 
1013              -> [OutExpr]       -- Arguments, already simplified
1014              -> SimplCont       -- After the call
1015              -> SimplM FloatsWithExpr
1016 -- Similar to simplLam, but this time 
1017 -- the arguments are already simplified
1018 makeThatCall orig_env var fun@(Lam _ _) args cont
1019   = go orig_env fun args
1020   where
1021     zap_it = mkLamBndrZapper fun (length args)
1022
1023         -- Type-beta reduction
1024     go env (Lam bndr body) (Type ty_arg : args)
1025       = ASSERT( isTyVar bndr )
1026         tick (BetaReduction bndr)                       `thenSmpl_`
1027         go (extendSubst env bndr (DoneTy ty_arg)) body args
1028
1029         -- Ordinary beta reduction
1030     go env (Lam bndr body) (arg : args)
1031       = tick (BetaReduction bndr)                       `thenSmpl_`
1032         simplNonRecX env (zap_it bndr) arg              $ \ env -> 
1033         go env body args
1034
1035         -- Not enough args, so there are real lambdas left to put in the result
1036     go env fun args
1037       = simplExprF env fun (pushContArgs orig_env args cont)
1038         -- NB: orig_env; the correct environment to capture with
1039         -- the arguments.... env has been augmented with substitutions 
1040         -- from the beta reductions.
1041
1042 makeThatCall env var fun args cont
1043   = simplExprF env fun (pushContArgs env args cont)
1044 \end{code}                 
1045
1046
1047 %************************************************************************
1048 %*                                                                      *
1049 \subsection{Arguments}
1050 %*                                                                      *
1051 %************************************************************************
1052
1053 \begin{code}
1054 ---------------------------------------------------------
1055 --      Simplifying the arguments of a call
1056
1057 simplifyArgs :: SimplEnv 
1058              -> OutType                         -- Type of the function
1059              -> [(InExpr, SimplEnv, Bool)]      -- Details of the arguments
1060              -> OutType                         -- Type of the continuation
1061              -> (SimplEnv -> [OutExpr] -> SimplM FloatsWithExpr)
1062              -> SimplM FloatsWithExpr
1063
1064 -- [CPS-like because of strict arguments]
1065
1066 -- Simplify the arguments to a call.
1067 -- This part of the simplifier may break the no-shadowing invariant
1068 -- Consider
1069 --      f (...(\a -> e)...) (case y of (a,b) -> e')
1070 -- where f is strict in its second arg
1071 -- If we simplify the innermost one first we get (...(\a -> e)...)
1072 -- Simplifying the second arg makes us float the case out, so we end up with
1073 --      case y of (a,b) -> f (...(\a -> e)...) e'
1074 -- So the output does not have the no-shadowing invariant.  However, there is
1075 -- no danger of getting name-capture, because when the first arg was simplified
1076 -- we used an in-scope set that at least mentioned all the variables free in its
1077 -- static environment, and that is enough.
1078 --
1079 -- We can't just do innermost first, or we'd end up with a dual problem:
1080 --      case x of (a,b) -> f e (...(\a -> e')...)
1081 --
1082 -- I spent hours trying to recover the no-shadowing invariant, but I just could
1083 -- not think of an elegant way to do it.  The simplifier is already knee-deep in
1084 -- continuations.  We have to keep the right in-scope set around; AND we have
1085 -- to get the effect that finding (error "foo") in a strict arg position will
1086 -- discard the entire application and replace it with (error "foo").  Getting
1087 -- all this at once is TOO HARD!
1088
1089 simplifyArgs env fn_ty args cont_ty thing_inside
1090   = go env fn_ty args thing_inside
1091   where
1092     go env fn_ty []         thing_inside = thing_inside env []
1093     go env fn_ty (arg:args) thing_inside = simplifyArg env fn_ty arg cont_ty            $ \ env arg' ->
1094                                            go env (applyTypeToArg fn_ty arg') args      $ \ env args' ->
1095                                            thing_inside env (arg':args')
1096
1097 simplifyArg env fn_ty (Type ty_arg, se, _) cont_ty thing_inside
1098   = simplType (setInScope se env) ty_arg        `thenSmpl` \ new_ty_arg ->
1099     thing_inside env (Type new_ty_arg)
1100
1101 simplifyArg env fn_ty (val_arg, arg_se, is_strict) cont_ty thing_inside 
1102   | is_strict 
1103   = simplStrictArg AnArg env val_arg arg_se arg_ty cont_ty thing_inside
1104
1105   | otherwise   -- Lazy argument
1106                 -- DO NOT float anything outside, hence simplExprC
1107                 -- There is no benefit (unlike in a let-binding), and we'd
1108                 -- have to be very careful about bogus strictness through 
1109                 -- floating a demanded let.
1110   = simplExprC (setInScope arg_se env) val_arg
1111                (mkStop arg_ty AnArg)            `thenSmpl` \ arg1 ->
1112    thing_inside env arg1
1113   where
1114     arg_ty = funArgTy fn_ty
1115
1116
1117 simplStrictArg ::  LetRhsFlag
1118                 -> SimplEnv             -- The env of the call
1119                 -> InExpr -> SimplEnv   -- The arg plus its env
1120                 -> OutType              -- arg_ty: type of the argument
1121                 -> OutType              -- cont_ty: Type of thing computed by the context
1122                 -> (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)       
1123                                         -- Takes an expression of type rhs_ty, 
1124                                         -- returns an expression of type cont_ty
1125                                         -- The env passed to this continuation is the
1126                                         -- env of the call, plus any new in-scope variables
1127                 -> SimplM FloatsWithExpr        -- An expression of type cont_ty
1128
1129 simplStrictArg is_rhs call_env arg arg_env arg_ty cont_ty thing_inside
1130   = simplExprF (setInScope arg_env call_env) arg
1131                (ArgOf is_rhs arg_ty cont_ty (\ new_env -> thing_inside (setInScope call_env new_env)))
1132   -- Notice the way we use arg_env (augmented with in-scope vars from call_env) 
1133   --    to simplify the argument
1134   -- and call-env (augmented with in-scope vars from the arg) to pass to the continuation
1135 \end{code}
1136
1137
1138 %************************************************************************
1139 %*                                                                      *
1140 \subsection{mkAtomicArgs}
1141 %*                                                                      *
1142 %************************************************************************
1143
1144 mkAtomicArgs takes a putative RHS, checks whether it's a PAP or
1145 constructor application and, if so, converts it to ANF, so that the 
1146 resulting thing can be inlined more easily.  Thus
1147         x = (f a, g b)
1148 becomes
1149         t1 = f a
1150         t2 = g b
1151         x = (t1,t2)
1152
1153 There are three sorts of binding context, specified by the two
1154 boolean arguments
1155
1156 Strict
1157    OK-unlifted
1158
1159 N  N    Top-level or recursive                  Only bind args of lifted type
1160
1161 N  Y    Non-top-level and non-recursive,        Bind args of lifted type, or
1162                 but lazy                        unlifted-and-ok-for-speculation
1163
1164 Y  Y    Non-top-level, non-recursive,           Bind all args
1165                  and strict (demanded)
1166         
1167
1168 For example, given
1169
1170         x = MkC (y div# z)
1171
1172 there is no point in transforming to
1173
1174         x = case (y div# z) of r -> MkC r
1175
1176 because the (y div# z) can't float out of the let. But if it was
1177 a *strict* let, then it would be a good thing to do.  Hence the
1178 context information.
1179
1180 \begin{code}
1181 mkAtomicArgs :: Bool    -- A strict binding
1182              -> Bool    -- OK to float unlifted args
1183              -> OutExpr
1184              -> SimplM (OrdList (OutId,OutExpr),  -- The floats (unusually) may include
1185                         OutExpr)                  -- things that need case-binding,
1186                                                   -- if the strict-binding flag is on
1187
1188 mkAtomicArgs is_strict ok_float_unlifted rhs
1189   | (Var fun, args) <- collectArgs rhs,                         -- It's an application
1190     isDataConWorkId fun || valArgCount args < idArity fun       -- And it's a constructor or PAP
1191   = go fun nilOL [] args        -- Have a go
1192
1193   | otherwise = bale_out        -- Give up
1194
1195   where
1196     bale_out = returnSmpl (nilOL, rhs)
1197
1198     go fun binds rev_args [] 
1199         = returnSmpl (binds, mkApps (Var fun) (reverse rev_args))
1200
1201     go fun binds rev_args (arg : args) 
1202         | exprIsTrivial arg     -- Easy case
1203         = go fun binds (arg:rev_args) args
1204
1205         | not can_float_arg     -- Can't make this arg atomic
1206         = bale_out              -- ... so give up
1207
1208         | otherwise     -- Don't forget to do it recursively
1209                         -- E.g.  x = a:b:c:[]
1210         =  mkAtomicArgs is_strict ok_float_unlifted arg `thenSmpl` \ (arg_binds, arg') ->
1211            newId FSLIT("a") arg_ty                      `thenSmpl` \ arg_id ->
1212            go fun ((arg_binds `snocOL` (arg_id,arg')) `appOL` binds) 
1213               (Var arg_id : rev_args) args
1214         where
1215           arg_ty        = exprType arg
1216           can_float_arg =  is_strict 
1217                         || not (isUnLiftedType arg_ty)
1218                         || (ok_float_unlifted && exprOkForSpeculation arg)
1219
1220
1221 addAtomicBinds :: SimplEnv -> [(OutId,OutExpr)]
1222                -> (SimplEnv -> SimplM (FloatsWith a))
1223                -> SimplM (FloatsWith a)
1224 addAtomicBinds env []         thing_inside = thing_inside env
1225 addAtomicBinds env ((v,r):bs) thing_inside = addAuxiliaryBind env (NonRec v r) $ \ env -> 
1226                                              addAtomicBinds env bs thing_inside
1227
1228 addAtomicBindsE :: SimplEnv -> [(OutId,OutExpr)]
1229                 -> (SimplEnv -> SimplM FloatsWithExpr)
1230                 -> SimplM FloatsWithExpr
1231 -- Same again, but this time we're in an expression context,
1232 -- and may need to do some case bindings
1233
1234 addAtomicBindsE env [] thing_inside 
1235   = thing_inside env
1236 addAtomicBindsE env ((v,r):bs) thing_inside 
1237   | needsCaseBinding (idType v) r
1238   = addAtomicBindsE (addNewInScopeIds env [v]) bs thing_inside  `thenSmpl` \ (floats, expr) ->
1239     WARN( exprIsTrivial expr, ppr v <+> pprCoreExpr expr )
1240     returnSmpl (emptyFloats env, Case r v [(DEFAULT,[], wrapFloats floats expr)])
1241
1242   | otherwise
1243   = addAuxiliaryBind env (NonRec v r)   $ \ env -> 
1244     addAtomicBindsE env bs thing_inside
1245 \end{code}
1246
1247
1248 %************************************************************************
1249 %*                                                                      *
1250 \subsection{The main rebuilder}
1251 %*                                                                      *
1252 %************************************************************************
1253
1254 \begin{code}
1255 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
1256
1257 rebuild env expr (Stop _ _ _)                 = rebuildDone env expr
1258 rebuild env expr (ArgOf _ _ _ cont_fn)        = cont_fn env expr
1259 rebuild env expr (CoerceIt to_ty cont)        = rebuild env (mkCoerce to_ty expr) cont
1260 rebuild env expr (InlinePlease cont)          = rebuild env (Note InlineCall expr) cont
1261 rebuild env expr (Select _ bndr alts se cont) = rebuildCase (setInScope se env) expr bndr alts cont
1262 rebuild env expr (ApplyTo _ arg se cont)      = rebuildApp  (setInScope se env) expr arg cont
1263
1264 rebuildApp env fun arg cont
1265   = simplExpr env arg   `thenSmpl` \ arg' ->
1266     rebuild env (App fun arg') cont
1267
1268 rebuildDone env expr = returnSmpl (emptyFloats env, expr)
1269 \end{code}
1270
1271
1272 %************************************************************************
1273 %*                                                                      *
1274 \subsection{Functions dealing with a case}
1275 %*                                                                      *
1276 %************************************************************************
1277
1278 Blob of helper functions for the "case-of-something-else" situation.
1279
1280 \begin{code}
1281 ---------------------------------------------------------
1282 --      Eliminate the case if possible
1283
1284 rebuildCase :: SimplEnv
1285             -> OutExpr          -- Scrutinee
1286             -> InId             -- Case binder
1287             -> [InAlt]          -- Alternatives
1288             -> SimplCont
1289             -> SimplM FloatsWithExpr
1290
1291 rebuildCase env scrut case_bndr alts cont
1292   | Just (con,args) <- exprIsConApp_maybe scrut 
1293         -- Works when the scrutinee is a variable with a known unfolding
1294         -- as well as when it's an explicit constructor application
1295   = knownCon env (DataAlt con) args case_bndr alts cont
1296
1297   | Lit lit <- scrut    -- No need for same treatment as constructors
1298                         -- because literals are inlined more vigorously
1299   = knownCon env (LitAlt lit) [] case_bndr alts cont
1300
1301   | otherwise
1302   = prepareAlts scrut case_bndr alts            `thenSmpl` \ (better_alts, handled_cons) -> 
1303         
1304         -- Deal with the case binder, and prepare the continuation;
1305         -- The new subst_env is in place
1306     prepareCaseCont env better_alts cont        `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1307     addFloats env floats                        $ \ env ->      
1308
1309         -- Deal with variable scrutinee
1310     simplCaseBinder env scrut case_bndr         `thenSmpl` \ (alt_env, case_bndr', zap_occ_info) ->
1311
1312         -- Deal with the case alternatives
1313     simplAlts alt_env zap_occ_info handled_cons
1314               case_bndr' better_alts dup_cont   `thenSmpl` \ alts' ->
1315
1316         -- Put the case back together
1317     mkCase scrut case_bndr' alts'               `thenSmpl` \ case_expr ->
1318
1319         -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1320         -- The case binder *not* scope over the whole returned case-expression
1321     rebuild env case_expr nondup_cont
1322 \end{code}
1323
1324 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1325 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1326 way, there's a chance that v will now only be used once, and hence
1327 inlined.
1328
1329 Note 1
1330 ~~~~~~
1331 There is a time we *don't* want to do that, namely when
1332 -fno-case-of-case is on.  This happens in the first simplifier pass,
1333 and enhances full laziness.  Here's the bad case:
1334         f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1335 If we eliminate the inner case, we trap it inside the I# v -> arm,
1336 which might prevent some full laziness happening.  I've seen this
1337 in action in spectral/cichelli/Prog.hs:
1338          [(m,n) | m <- [1..max], n <- [1..max]]
1339 Hence the check for NoCaseOfCase.
1340
1341 Note 2
1342 ~~~~~~
1343 There is another situation when we don't want to do it.  If we have
1344
1345     case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1346                    ...other cases .... }
1347
1348 We'll perform the binder-swap for the outer case, giving
1349
1350     case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 } 
1351                    ...other cases .... }
1352
1353 But there is no point in doing it for the inner case, because w1 can't
1354 be inlined anyway.  Furthermore, doing the case-swapping involves
1355 zapping w2's occurrence info (see paragraphs that follow), and that
1356 forces us to bind w2 when doing case merging.  So we get
1357
1358     case x of w1 { A -> let w2 = w1 in e1
1359                    B -> let w2 = w1 in e2
1360                    ...other cases .... }
1361
1362 This is plain silly in the common case where w2 is dead.
1363
1364 Even so, I can't see a good way to implement this idea.  I tried
1365 not doing the binder-swap if the scrutinee was already evaluated
1366 but that failed big-time:
1367
1368         data T = MkT !Int
1369
1370         case v of w  { MkT x ->
1371         case x of x1 { I# y1 ->
1372         case x of x2 { I# y2 -> ...
1373
1374 Notice that because MkT is strict, x is marked "evaluated".  But to
1375 eliminate the last case, we must either make sure that x (as well as
1376 x1) has unfolding MkT y1.  THe straightforward thing to do is to do
1377 the binder-swap.  So this whole note is a no-op.
1378
1379 Note 3
1380 ~~~~~~
1381 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1382 any occurrence info (eg IAmDead) in the case binder, because the
1383 case-binder now effectively occurs whenever v does.  AND we have to do
1384 the same for the pattern-bound variables!  Example:
1385
1386         (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1387
1388 Here, b and p are dead.  But when we move the argment inside the first
1389 case RHS, and eliminate the second case, we get
1390
1391         case x or { (a,b) -> a b }
1392
1393 Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
1394 happened.  Hence the zap_occ_info function returned by simplCaseBinder
1395
1396 \begin{code}
1397 simplCaseBinder env (Var v) case_bndr
1398   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
1399
1400 -- Failed try [see Note 2 above]
1401 --     not (isEvaldUnfolding (idUnfolding v))
1402
1403   = simplBinder env (zap case_bndr)             `thenSmpl` \ (env, case_bndr') ->
1404     returnSmpl (modifyInScope env v case_bndr', case_bndr', zap)
1405         -- We could extend the substitution instead, but it would be
1406         -- a hack because then the substitution wouldn't be idempotent
1407         -- any more (v is an OutId).  And this just just as well.
1408   where
1409     zap b = b `setIdOccInfo` NoOccInfo
1410             
1411 simplCaseBinder env other_scrut case_bndr 
1412   = simplBinder env case_bndr           `thenSmpl` \ (env, case_bndr') ->
1413     returnSmpl (env, case_bndr', \ bndr -> bndr)        -- NoOp on bndr
1414 \end{code}
1415
1416
1417
1418 \begin{code}
1419 simplAlts :: SimplEnv 
1420           -> (InId -> InId)             -- Occ-info zapper
1421           -> [AltCon]                   -- Alternatives the scrutinee can't be
1422                                         -- in the default case
1423           -> OutId                      -- Case binder
1424           -> [InAlt] -> SimplCont
1425           -> SimplM [OutAlt]            -- Includes the continuation
1426
1427 simplAlts env zap_occ_info handled_cons case_bndr' alts cont'
1428   = mapSmpl simpl_alt alts
1429   where
1430     inst_tys' = tyConAppArgs (idType case_bndr')
1431
1432     simpl_alt (DEFAULT, _, rhs)
1433         = let
1434                 -- In the default case we record the constructors that the
1435                 -- case-binder *can't* be.
1436                 -- We take advantage of any OtherCon info in the case scrutinee
1437                 case_bndr_w_unf = case_bndr' `setIdUnfolding` mkOtherCon handled_cons
1438                 env_with_unf    = modifyInScope env case_bndr' case_bndr_w_unf 
1439           in
1440           simplExprC env_with_unf rhs cont'     `thenSmpl` \ rhs' ->
1441           returnSmpl (DEFAULT, [], rhs')
1442
1443     simpl_alt (con, vs, rhs)
1444         =       -- Deal with the pattern-bound variables
1445                 -- Mark the ones that are in ! positions in the data constructor
1446                 -- as certainly-evaluated.
1447                 -- NB: it happens that simplBinders does *not* erase the OtherCon
1448                 --     form of unfolding, so it's ok to add this info before 
1449                 --     doing simplBinders
1450           simplBinders env (add_evals con vs)           `thenSmpl` \ (env, vs') ->
1451
1452                 -- Bind the case-binder to (con args)
1453           let
1454                 unfolding    = mkUnfolding False (mkAltExpr con vs' inst_tys')
1455                 env_with_unf = modifyInScope env case_bndr' (case_bndr' `setIdUnfolding` unfolding)
1456           in
1457           simplExprC env_with_unf rhs cont'             `thenSmpl` \ rhs' ->
1458           returnSmpl (con, vs', rhs')
1459
1460
1461         -- add_evals records the evaluated-ness of the bound variables of
1462         -- a case pattern.  This is *important*.  Consider
1463         --      data T = T !Int !Int
1464         --
1465         --      case x of { T a b -> T (a+1) b }
1466         --
1467         -- We really must record that b is already evaluated so that we don't
1468         -- go and re-evaluate it when constructing the result.
1469
1470     add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1471     add_evals other_con    vs = vs
1472
1473     cat_evals [] [] = []
1474     cat_evals (v:vs) (str:strs)
1475         | isTyVar v          = v        : cat_evals vs (str:strs)
1476         | isMarkedStrict str = evald_v  : cat_evals vs strs
1477         | otherwise          = zapped_v : cat_evals vs strs
1478         where
1479           zapped_v = zap_occ_info v
1480           evald_v  = zapped_v `setIdUnfolding` mkOtherCon []
1481 \end{code}
1482
1483
1484 %************************************************************************
1485 %*                                                                      *
1486 \subsection{Known constructor}
1487 %*                                                                      *
1488 %************************************************************************
1489
1490 We are a bit careful with occurrence info.  Here's an example
1491
1492         (\x* -> case x of (a*, b) -> f a) (h v, e)
1493
1494 where the * means "occurs once".  This effectively becomes
1495         case (h v, e) of (a*, b) -> f a)
1496 and then
1497         let a* = h v; b = e in f a
1498 and then
1499         f (h v)
1500
1501 All this should happen in one sweep.
1502
1503 \begin{code}
1504 knownCon :: SimplEnv -> AltCon -> [OutExpr]
1505          -> InId -> [InAlt] -> SimplCont
1506          -> SimplM FloatsWithExpr
1507
1508 knownCon env con args bndr alts cont
1509   = tick (KnownBranch bndr)     `thenSmpl_`
1510     case findAlt con alts of
1511         (DEFAULT, bs, rhs)     -> ASSERT( null bs )
1512                                   simplNonRecX env bndr scrut   $ \ env ->
1513                                         -- This might give rise to a binding with non-atomic args
1514                                         -- like x = Node (f x) (g x)
1515                                         -- but no harm will be done
1516                                   simplExprF env rhs cont
1517                                 where
1518                                   scrut = case con of
1519                                             LitAlt lit -> Lit lit
1520                                             DataAlt dc -> mkConApp dc args
1521
1522         (LitAlt lit, bs, rhs) ->  ASSERT( null bs )
1523                                   simplNonRecX env bndr (Lit lit)       $ \ env ->
1524                                   simplExprF env rhs cont
1525
1526         (DataAlt dc, bs, rhs)  -> ASSERT( length bs + n_tys == length args )
1527                                   bind_args env bs (drop n_tys args)    $ \ env ->
1528                                   let
1529                                     con_app  = mkConApp dc (take n_tys args ++ con_args)
1530                                     con_args = [substExpr (getSubst env) (varToCoreExpr b) | b <- bs]
1531                                         -- args are aready OutExprs, but bs are InIds
1532                                   in
1533                                   simplNonRecX env bndr con_app         $ \ env ->
1534                                   simplExprF env rhs cont
1535                                where
1536                                   n_tys = dataConNumInstArgs dc -- Non-existential type args
1537 -- Ugh!
1538 bind_args env [] _ thing_inside = thing_inside env
1539
1540 bind_args env (b:bs) (Type ty : args) thing_inside
1541   = bind_args (extendSubst env b (DoneTy ty)) bs args thing_inside
1542     
1543 bind_args env (b:bs) (arg : args) thing_inside
1544   = simplNonRecX env b arg      $ \ env ->
1545     bind_args env bs args thing_inside
1546 \end{code}
1547
1548
1549 %************************************************************************
1550 %*                                                                      *
1551 \subsection{Duplicating continuations}
1552 %*                                                                      *
1553 %************************************************************************
1554
1555 \begin{code}
1556 prepareCaseCont :: SimplEnv
1557                 -> [InAlt] -> SimplCont
1558                 -> SimplM (FloatsWith (SimplCont,SimplCont))    
1559                         -- Return a duplicatable continuation, a non-duplicable part 
1560                         -- plus some extra bindings
1561
1562         -- No need to make it duplicatable if there's only one alternative
1563 prepareCaseCont env [alt] cont = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1564 prepareCaseCont env alts  cont = mkDupableCont env cont
1565 \end{code}
1566
1567 \begin{code}
1568 mkDupableCont :: SimplEnv -> SimplCont 
1569               -> SimplM (FloatsWith (SimplCont, SimplCont))
1570
1571 mkDupableCont env cont
1572   | contIsDupable cont
1573   = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1574
1575 mkDupableCont env (CoerceIt ty cont)
1576   = mkDupableCont env cont              `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1577     returnSmpl (floats, (CoerceIt ty dup_cont, nondup_cont))
1578
1579 mkDupableCont env (InlinePlease cont)
1580   = mkDupableCont env cont              `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1581     returnSmpl (floats, (InlinePlease dup_cont, nondup_cont))
1582
1583 mkDupableCont env cont@(ArgOf _ arg_ty _ _)
1584   =  returnSmpl (emptyFloats env, (mkBoringStop arg_ty, cont))
1585         -- Do *not* duplicate an ArgOf continuation
1586         -- Because ArgOf continuations are opaque, we gain nothing by
1587         -- propagating them into the expressions, and we do lose a lot.
1588         -- Here's an example:
1589         --      && (case x of { T -> F; F -> T }) E
1590         -- Now, && is strict so we end up simplifying the case with
1591         -- an ArgOf continuation.  If we let-bind it, we get
1592         --
1593         --      let $j = \v -> && v E
1594         --      in simplExpr (case x of { T -> F; F -> T })
1595         --                   (ArgOf (\r -> $j r)
1596         -- And after simplifying more we get
1597         --
1598         --      let $j = \v -> && v E
1599         --      in case of { T -> $j F; F -> $j T }
1600         -- Which is a Very Bad Thing
1601         --
1602         -- The desire not to duplicate is the entire reason that
1603         -- mkDupableCont returns a pair of continuations.
1604         --
1605         -- The original plan had:
1606         -- e.g.         (...strict-fn...) [...hole...]
1607         --      ==>
1608         --              let $j = \a -> ...strict-fn...
1609         --              in $j [...hole...]
1610
1611 mkDupableCont env (ApplyTo _ arg se cont)
1612   =     -- e.g.         [...hole...] (...arg...)
1613         --      ==>
1614         --              let a = ...arg... 
1615         --              in [...hole...] a
1616     simplExpr (setInScope se env) arg                   `thenSmpl` \ arg' ->
1617
1618     mkDupableCont env cont                              `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1619     addFloats env floats                                $ \ env ->
1620
1621     if exprIsDupable arg' then
1622         returnSmpl (emptyFloats env, (ApplyTo OkToDup arg' (zapSubstEnv se) dup_cont, nondup_cont))
1623     else
1624     newId FSLIT("a") (exprType arg')                    `thenSmpl` \ arg_id ->
1625
1626     tick (CaseOfCase arg_id)                            `thenSmpl_`
1627         -- Want to tick here so that we go round again,
1628         -- and maybe copy or inline the code.
1629         -- Not strictly CaseOfCase, but never mind
1630
1631     returnSmpl (unitFloat env arg_id arg', 
1632                 (ApplyTo OkToDup (Var arg_id) (zapSubstEnv se) dup_cont,
1633                  nondup_cont))
1634         -- But what if the arg should be case-bound? 
1635         -- This has been this way for a long time, so I'll leave it,
1636         -- but I can't convince myself that it's right.
1637
1638
1639 mkDupableCont env (Select _ case_bndr alts se cont)
1640   =     -- e.g.         (case [...hole...] of { pi -> ei })
1641         --      ===>
1642         --              let ji = \xij -> ei 
1643         --              in case [...hole...] of { pi -> ji xij }
1644     tick (CaseOfCase case_bndr)                                 `thenSmpl_`
1645     let
1646         alt_env = setInScope se env
1647     in
1648     prepareCaseCont alt_env alts cont                           `thenSmpl` \ (floats1, (dup_cont, nondup_cont)) ->
1649     addFloats alt_env floats1                                   $ \ alt_env ->
1650
1651     simplBinder alt_env case_bndr                               `thenSmpl` \ (alt_env, case_bndr') ->
1652         -- NB: simplBinder does not zap deadness occ-info, so
1653         -- a dead case_bndr' will still advertise its deadness
1654         -- This is really important because in
1655         --      case e of b { (# a,b #) -> ... }
1656         -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1657         -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1658         -- In the new alts we build, we have the new case binder, so it must retain
1659         -- its deadness.
1660
1661     mkDupableAlts alt_env case_bndr' alts dup_cont      `thenSmpl` \ (floats2, alts') ->
1662     addFloats alt_env floats2                           $ \ alt_env ->
1663     returnSmpl (emptyFloats alt_env, 
1664                 (Select OkToDup case_bndr' alts' (zapSubstEnv se) 
1665                         (mkBoringStop (contResultType dup_cont)),
1666                  nondup_cont))
1667
1668 mkDupableAlts :: SimplEnv -> OutId -> [InAlt] -> SimplCont
1669               -> SimplM (FloatsWith [InAlt])
1670 -- Absorbs the continuation into the new alternatives
1671
1672 mkDupableAlts env case_bndr' alts dupable_cont 
1673   = go env alts
1674   where
1675     go env [] = returnSmpl (emptyFloats env, [])
1676     go env (alt:alts)
1677         = mkDupableAlt env case_bndr' dupable_cont alt  `thenSmpl` \ (floats1, alt') ->
1678           addFloats env floats1                         $ \ env ->
1679           go env alts                                   `thenSmpl` \ (floats2, alts') ->
1680           returnSmpl (floats2, alt' : alts')
1681                                         
1682 mkDupableAlt env case_bndr' cont alt@(con, bndrs, rhs)
1683   = simplBinders env bndrs                              `thenSmpl` \ (env, bndrs') ->
1684     simplExprC env rhs cont                             `thenSmpl` \ rhs' ->
1685
1686     if exprIsDupable rhs' then
1687         returnSmpl (emptyFloats env, (con, bndrs', rhs'))
1688         -- It is worth checking for a small RHS because otherwise we
1689         -- get extra let bindings that may cause an extra iteration of the simplifier to
1690         -- inline back in place.  Quite often the rhs is just a variable or constructor.
1691         -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1692         -- iterations because the version with the let bindings looked big, and so wasn't
1693         -- inlined, but after the join points had been inlined it looked smaller, and so
1694         -- was inlined.
1695         --
1696         -- NB: we have to check the size of rhs', not rhs. 
1697         -- Duplicating a small InAlt might invalidate occurrence information
1698         -- However, if it *is* dupable, we return the *un* simplified alternative,
1699         -- because otherwise we'd need to pair it up with an empty subst-env....
1700         -- but we only have one env shared between all the alts.
1701         -- (Remember we must zap the subst-env before re-simplifying something).
1702         -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1703
1704     else
1705     let
1706         rhs_ty'     = exprType rhs'
1707         used_bndrs' = filter (not . isDeadBinder) (case_bndr' : bndrs')
1708                 -- The deadness info on the new binders is unscathed
1709     in
1710         -- If we try to lift a primitive-typed something out
1711         -- for let-binding-purposes, we will *caseify* it (!),
1712         -- with potentially-disastrous strictness results.  So
1713         -- instead we turn it into a function: \v -> e
1714         -- where v::State# RealWorld#.  The value passed to this function
1715         -- is realworld#, which generates (almost) no code.
1716
1717         -- There's a slight infelicity here: we pass the overall 
1718         -- case_bndr to all the join points if it's used in *any* RHS,
1719         -- because we don't know its usage in each RHS separately
1720
1721         -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1722         -- we make the join point into a function whenever used_bndrs'
1723         -- is empty.  This makes the join-point more CPR friendly. 
1724         -- Consider:    let j = if .. then I# 3 else I# 4
1725         --              in case .. of { A -> j; B -> j; C -> ... }
1726         --
1727         -- Now CPR doesn't w/w j because it's a thunk, so
1728         -- that means that the enclosing function can't w/w either,
1729         -- which is a lose.  Here's the example that happened in practice:
1730         --      kgmod :: Int -> Int -> Int
1731         --      kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1732         --                  then 78
1733         --                  else 5
1734         --
1735         -- I have seen a case alternative like this:
1736         --      True -> \v -> ...
1737         -- It's a bit silly to add the realWorld dummy arg in this case, making
1738         --      $j = \s v -> ...
1739         --         True -> $j s
1740         -- (the \v alone is enough to make CPR happy) but I think it's rare
1741
1742     ( if null used_bndrs' 
1743         then newId FSLIT("w") realWorldStatePrimTy      `thenSmpl` \ rw_id ->
1744              returnSmpl ([rw_id], [Var realWorldPrimId])
1745         else 
1746              returnSmpl (used_bndrs', map varToCoreExpr used_bndrs')
1747     )                                                   `thenSmpl` \ (final_bndrs', final_args) ->
1748
1749         -- See comment about "$j" name above
1750     newId (encodeFS FSLIT("$j")) (mkPiTypes final_bndrs' rhs_ty')       `thenSmpl` \ join_bndr ->
1751         -- Notice the funky mkPiTypes.  If the contructor has existentials
1752         -- it's possible that the join point will be abstracted over
1753         -- type varaibles as well as term variables.
1754         --  Example:  Suppose we have
1755         --      data T = forall t.  C [t]
1756         --  Then faced with
1757         --      case (case e of ...) of
1758         --          C t xs::[t] -> rhs
1759         --  We get the join point
1760         --      let j :: forall t. [t] -> ...
1761         --          j = /\t \xs::[t] -> rhs
1762         --      in
1763         --      case (case e of ...) of
1764         --          C t xs::[t] -> j t xs
1765     let 
1766         -- We make the lambdas into one-shot-lambdas.  The
1767         -- join point is sure to be applied at most once, and doing so
1768         -- prevents the body of the join point being floated out by
1769         -- the full laziness pass
1770         really_final_bndrs     = map one_shot final_bndrs'
1771         one_shot v | isId v    = setOneShotLambda v
1772                    | otherwise = v
1773         join_rhs  = mkLams really_final_bndrs rhs'
1774         join_call = mkApps (Var join_bndr) final_args
1775     in
1776     returnSmpl (unitFloat env join_bndr join_rhs, (con, bndrs', join_call))
1777 \end{code}