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