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