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