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