Another refactoring on the shape of an Unfolding
[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 FamInstEnv       ( FamInstEnv )
17 import Id
18 import MkId             ( mkImpossibleExpr, seqId )
19 import Var
20 import IdInfo
21 import Coercion
22 import FamInstEnv       ( topNormaliseType )
23 import DataCon          ( DataCon, dataConWorkId, dataConRepStrictness )
24 import CoreSyn
25 import NewDemand        ( isStrictDmd, splitStrictSig )
26 import PprCore          ( pprParendExpr, pprCoreExpr )
27 import CoreUnfold       ( mkUnfolding, mkCoreUnfolding, mkInlineRule, 
28                           exprIsConApp_maybe, callSiteInline, CallCtxt(..) )
29 import CoreUtils
30 import qualified CoreSubst
31 import CoreArity        ( exprArity )
32 import Rules            ( lookupRule, getRules )
33 import BasicTypes       ( isMarkedStrict, Arity )
34 import CostCentre       ( currentCCS, pushCCisNop )
35 import TysPrim          ( realWorldStatePrimTy )
36 import PrelInfo         ( realWorldPrimId )
37 import BasicTypes       ( TopLevelFlag(..), isTopLevel,
38                           RecFlag(..), isNonRuleLoopBreaker )
39 import MonadUtils       ( foldlM )
40 import Maybes           ( orElse )
41 import Data.List        ( mapAccumL )
42 import Outputable
43 import FastString
44 \end{code}
45
46
47 The guts of the simplifier is in this module, but the driver loop for
48 the simplifier is in SimplCore.lhs.
49
50
51 -----------------------------------------
52         *** IMPORTANT NOTE ***
53 -----------------------------------------
54 The simplifier used to guarantee that the output had no shadowing, but
55 it does not do so any more.   (Actually, it never did!)  The reason is
56 documented with simplifyArgs.
57
58
59 -----------------------------------------
60         *** IMPORTANT NOTE ***
61 -----------------------------------------
62 Many parts of the simplifier return a bunch of "floats" as well as an
63 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
64
65 All "floats" are let-binds, not case-binds, but some non-rec lets may
66 be unlifted (with RHS ok-for-speculation).
67
68
69
70 -----------------------------------------
71         ORGANISATION OF FUNCTIONS
72 -----------------------------------------
73 simplTopBinds
74   - simplify all top-level binders
75   - for NonRec, call simplRecOrTopPair
76   - for Rec,    call simplRecBind
77
78
79         ------------------------------
80 simplExpr (applied lambda)      ==> simplNonRecBind
81 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
82 simplExpr (Let (Rec ...)    ..) ==> simplify binders; simplRecBind
83
84         ------------------------------
85 simplRecBind    [binders already simplfied]
86   - use simplRecOrTopPair on each pair in turn
87
88 simplRecOrTopPair [binder already simplified]
89   Used for: recursive bindings (top level and nested)
90             top-level non-recursive bindings
91   Returns:
92   - check for PreInlineUnconditionally
93   - simplLazyBind
94
95 simplNonRecBind
96   Used for: non-top-level non-recursive bindings
97             beta reductions (which amount to the same thing)
98   Because it can deal with strict arts, it takes a
99         "thing-inside" and returns an expression
100
101   - check for PreInlineUnconditionally
102   - simplify binder, including its IdInfo
103   - if strict binding
104         simplStrictArg
105         mkAtomicArgs
106         completeNonRecX
107     else
108         simplLazyBind
109         addFloats
110
111 simplNonRecX:   [given a *simplified* RHS, but an *unsimplified* binder]
112   Used for: binding case-binder and constr args in a known-constructor case
113   - check for PreInLineUnconditionally
114   - simplify binder
115   - completeNonRecX
116
117         ------------------------------
118 simplLazyBind:  [binder already simplified, RHS not]
119   Used for: recursive bindings (top level and nested)
120             top-level non-recursive bindings
121             non-top-level, but *lazy* non-recursive bindings
122         [must not be strict or unboxed]
123   Returns floats + an augmented environment, not an expression
124   - substituteIdInfo and add result to in-scope
125         [so that rules are available in rec rhs]
126   - simplify rhs
127   - mkAtomicArgs
128   - float if exposes constructor or PAP
129   - completeBind
130
131
132 completeNonRecX:        [binder and rhs both simplified]
133   - if the the thing needs case binding (unlifted and not ok-for-spec)
134         build a Case
135    else
136         completeBind
137         addFloats
138
139 completeBind:   [given a simplified RHS]
140         [used for both rec and non-rec bindings, top level and not]
141   - try PostInlineUnconditionally
142   - add unfolding [this is the only place we add an unfolding]
143   - add arity
144
145
146
147 Right hand sides and arguments
148 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
149 In many ways we want to treat
150         (a) the right hand side of a let(rec), and
151         (b) a function argument
152 in the same way.  But not always!  In particular, we would
153 like to leave these arguments exactly as they are, so they
154 will match a RULE more easily.
155
156         f (g x, h x)
157         g (+ x)
158
159 It's harder to make the rule match if we ANF-ise the constructor,
160 or eta-expand the PAP:
161
162         f (let { a = g x; b = h x } in (a,b))
163         g (\y. + x y)
164
165 On the other hand if we see the let-defns
166
167         p = (g x, h x)
168         q = + x
169
170 then we *do* want to ANF-ise and eta-expand, so that p and q
171 can be safely inlined.
172
173 Even floating lets out is a bit dubious.  For let RHS's we float lets
174 out if that exposes a value, so that the value can be inlined more vigorously.
175 For example
176
177         r = let x = e in (x,x)
178
179 Here, if we float the let out we'll expose a nice constructor. We did experiments
180 that showed this to be a generally good thing.  But it was a bad thing to float
181 lets out unconditionally, because that meant they got allocated more often.
182
183 For function arguments, there's less reason to expose a constructor (it won't
184 get inlined).  Just possibly it might make a rule match, but I'm pretty skeptical.
185 So for the moment we don't float lets out of function arguments either.
186
187
188 Eta expansion
189 ~~~~~~~~~~~~~~
190 For eta expansion, we want to catch things like
191
192         case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
193
194 If the \x was on the RHS of a let, we'd eta expand to bring the two
195 lambdas together.  And in general that's a good thing to do.  Perhaps
196 we should eta expand wherever we find a (value) lambda?  Then the eta
197 expansion at a let RHS can concentrate solely on the PAP case.
198
199
200 %************************************************************************
201 %*                                                                      *
202 \subsection{Bindings}
203 %*                                                                      *
204 %************************************************************************
205
206 \begin{code}
207 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
208
209 simplTopBinds env0 binds0
210   = do  {       -- Put all the top-level binders into scope at the start
211                 -- so that if a transformation rule has unexpectedly brought
212                 -- anything into scope, then we don't get a complaint about that.
213                 -- It's rather as if the top-level binders were imported.
214         ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
215         ; dflags <- getDOptsSmpl
216         ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
217                           dopt Opt_D_dump_rule_firings dflags
218         ; env2 <- simpl_binds dump_flag env1 binds0
219         ; freeTick SimplifierDone
220         ; return env2 }
221   where
222         -- We need to track the zapped top-level binders, because
223         -- they should have their fragile IdInfo zapped (notably occurrence info)
224         -- That's why we run down binds and bndrs' simultaneously.
225         --
226         -- The dump-flag emits a trace for each top-level binding, which
227         -- helps to locate the tracing for inlining and rule firing
228     simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
229     simpl_binds _    env []           = return env
230     simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
231                                                      simpl_bind env bind
232                                            ; simpl_binds dump env' binds }
233
234     trace_bind True  bind = pprTrace "SimplBind" (ppr (bindersOf bind))
235     trace_bind False _    = \x -> x
236
237     simpl_bind env (Rec pairs)  = simplRecBind      env  TopLevel pairs
238     simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
239         where
240           (env', b') = addBndrRules env b (lookupRecBndr env b)
241 \end{code}
242
243
244 %************************************************************************
245 %*                                                                      *
246 \subsection{Lazy bindings}
247 %*                                                                      *
248 %************************************************************************
249
250 simplRecBind is used for
251         * recursive bindings only
252
253 \begin{code}
254 simplRecBind :: SimplEnv -> TopLevelFlag
255              -> [(InId, InExpr)]
256              -> SimplM SimplEnv
257 simplRecBind env0 top_lvl pairs0
258   = do  { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
259         ; env1 <- go (zapFloats env_with_info) triples
260         ; return (env0 `addRecFloats` env1) }
261         -- addFloats adds the floats from env1,
262         -- _and_ updates env0 with the in-scope set from env1
263   where
264     add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
265         -- Add the (substituted) rules to the binder
266     add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
267         where
268           (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
269
270     go env [] = return env
271
272     go env ((old_bndr, new_bndr, rhs) : pairs)
273         = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
274              ; go env' pairs }
275 \end{code}
276
277 simplOrTopPair is used for
278         * recursive bindings (whether top level or not)
279         * top-level non-recursive bindings
280
281 It assumes the binder has already been simplified, but not its IdInfo.
282
283 \begin{code}
284 simplRecOrTopPair :: SimplEnv
285                   -> TopLevelFlag
286                   -> InId -> OutBndr -> InExpr  -- Binder and rhs
287                   -> SimplM SimplEnv    -- Returns an env that includes the binding
288
289 simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
290   | preInlineUnconditionally env top_lvl old_bndr rhs   -- Check for unconditional inline
291   = do  { tick (PreInlineUnconditionally old_bndr)
292         ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
293
294   | otherwise
295   = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
296         -- May not actually be recursive, but it doesn't matter
297 \end{code}
298
299
300 simplLazyBind is used for
301   * [simplRecOrTopPair] recursive bindings (whether top level or not)
302   * [simplRecOrTopPair] top-level non-recursive bindings
303   * [simplNonRecE]      non-top-level *lazy* non-recursive bindings
304
305 Nota bene:
306     1. It assumes that the binder is *already* simplified,
307        and is in scope, and its IdInfo too, except unfolding
308
309     2. It assumes that the binder type is lifted.
310
311     3. It does not check for pre-inline-unconditionallly;
312        that should have been done already.
313
314 \begin{code}
315 simplLazyBind :: SimplEnv
316               -> TopLevelFlag -> RecFlag
317               -> InId -> OutId          -- Binder, both pre-and post simpl
318                                         -- The OutId has IdInfo, except arity, unfolding
319               -> InExpr -> SimplEnv     -- The RHS and its environment
320               -> SimplM SimplEnv
321
322 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
323   = do  { let   rhs_env     = rhs_se `setInScope` env
324                 (tvs, body) = case collectTyBinders rhs of
325                                 (tvs, body) | not_lam body -> (tvs,body)
326                                             | otherwise    -> ([], rhs)
327                 not_lam (Lam _ _) = False
328                 not_lam _         = True
329                         -- Do not do the "abstract tyyvar" thing if there's
330                         -- a lambda inside, becuase it defeats eta-reduction
331                         --    f = /\a. \x. g a x  
332                         -- should eta-reduce
333
334         ; (body_env, tvs') <- simplBinders rhs_env tvs
335                 -- See Note [Floating and type abstraction] in SimplUtils
336
337         -- Simplify the RHS
338         ; (body_env1, body1) <- simplExprF body_env body mkBoringStop
339
340         -- ANF-ise a constructor or PAP rhs
341         ; (body_env2, body2) <- prepareRhs body_env1 body1
342
343         ; (env', rhs')
344             <-  if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
345                 then                            -- No floating, just wrap up!
346                      do { rhs' <- mkLam env tvs' (wrapFloats body_env2 body2)
347                         ; return (env, rhs') }
348
349                 else if null tvs then           -- Simple floating
350                      do { tick LetFloatFromLet
351                         ; return (addFloats env body_env2, body2) }
352
353                 else                            -- Do type-abstraction first
354                      do { tick LetFloatFromLet
355                         ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
356                         ; rhs' <- mkLam env tvs' body3
357                         ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
358                         ; return (env', rhs') }
359
360         ; completeBind env' top_lvl bndr bndr1 rhs' }
361 \end{code}
362
363 A specialised variant of simplNonRec used when the RHS is already simplified,
364 notably in knownCon.  It uses case-binding where necessary.
365
366 \begin{code}
367 simplNonRecX :: SimplEnv
368              -> InId            -- Old binder
369              -> OutExpr         -- Simplified RHS
370              -> SimplM SimplEnv
371
372 simplNonRecX env bndr new_rhs
373   | isDeadBinder bndr   -- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
374   = return env          --               Here b is dead, and we avoid creating
375   | otherwise           --               the binding b = (a,b)
376   = do  { (env', bndr') <- simplBinder env bndr
377         ; completeNonRecX env' (isStrictId bndr) bndr bndr' new_rhs }
378
379 completeNonRecX :: SimplEnv
380                 -> Bool
381                 -> InId                 -- Old binder
382                 -> OutId                -- New binder
383                 -> OutExpr              -- Simplified RHS
384                 -> SimplM SimplEnv
385
386 completeNonRecX env is_strict old_bndr new_bndr new_rhs
387   = do  { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
388         ; (env2, rhs2) <-
389                 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
390                 then do { tick LetFloatFromLet
391                         ; return (addFloats env env1, rhs1) }   -- Add the floats to the main env
392                 else return (env, wrapFloats env1 rhs1)         -- Wrap the floats around the RHS
393         ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
394 \end{code}
395
396 {- No, no, no!  Do not try preInlineUnconditionally in completeNonRecX
397    Doing so risks exponential behaviour, because new_rhs has been simplified once already
398    In the cases described by the folowing commment, postInlineUnconditionally will
399    catch many of the relevant cases.
400         -- This happens; for example, the case_bndr during case of
401         -- known constructor:  case (a,b) of x { (p,q) -> ... }
402         -- Here x isn't mentioned in the RHS, so we don't want to
403         -- create the (dead) let-binding  let x = (a,b) in ...
404         --
405         -- Similarly, single occurrences can be inlined vigourously
406         -- e.g.  case (f x, g y) of (a,b) -> ....
407         -- If a,b occur once we can avoid constructing the let binding for them.
408
409    Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
410         -- Consider     case I# (quotInt# x y) of
411         --                I# v -> let w = J# v in ...
412         -- If we gaily inline (quotInt# x y) for v, we end up building an
413         -- extra thunk:
414         --                let w = J# (quotInt# x y) in ...
415         -- because quotInt# can fail.
416
417   | preInlineUnconditionally env NotTopLevel bndr new_rhs
418   = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
419 -}
420
421 ----------------------------------
422 prepareRhs takes a putative RHS, checks whether it's a PAP or
423 constructor application and, if so, converts it to ANF, so that the
424 resulting thing can be inlined more easily.  Thus
425         x = (f a, g b)
426 becomes
427         t1 = f a
428         t2 = g b
429         x = (t1,t2)
430
431 We also want to deal well cases like this
432         v = (f e1 `cast` co) e2
433 Here we want to make e1,e2 trivial and get
434         x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
435 That's what the 'go' loop in prepareRhs does
436
437 \begin{code}
438 prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
439 -- Adds new floats to the env iff that allows us to return a good RHS
440 prepareRhs env (Cast rhs co)    -- Note [Float coercions]
441   | (ty1, _ty2) <- coercionKind co       -- Do *not* do this if rhs has an unlifted type
442   , not (isUnLiftedType ty1)            -- see Note [Float coercions (unlifted)]
443   = do  { (env', rhs') <- makeTrivial env rhs
444         ; return (env', Cast rhs' co) }
445
446 prepareRhs env0 rhs0
447   = do  { (_is_val, env1, rhs1) <- go 0 env0 rhs0
448         ; return (env1, rhs1) }
449   where
450     go n_val_args env (Cast rhs co)
451         = do { (is_val, env', rhs') <- go n_val_args env rhs
452              ; return (is_val, env', Cast rhs' co) }
453     go n_val_args env (App fun (Type ty))
454         = do { (is_val, env', rhs') <- go n_val_args env fun
455              ; return (is_val, env', App rhs' (Type ty)) }
456     go n_val_args env (App fun arg)
457         = do { (is_val, env', fun') <- go (n_val_args+1) env fun
458              ; case is_val of
459                 True -> do { (env'', arg') <- makeTrivial env' arg
460                            ; return (True, env'', App fun' arg') }
461                 False -> return (False, env, App fun arg) }
462     go n_val_args env (Var fun)
463         = return (is_val, env, Var fun)
464         where
465           is_val = n_val_args > 0       -- There is at least one arg
466                                         -- ...and the fun a constructor or PAP
467                  && (isConLikeId fun || n_val_args < idArity fun)
468                                    -- See Note [CONLIKE pragma] in BasicTypes
469     go _ env other
470         = return (False, env, other)
471 \end{code}
472
473
474 Note [Float coercions]
475 ~~~~~~~~~~~~~~~~~~~~~~
476 When we find the binding
477         x = e `cast` co
478 we'd like to transform it to
479         x' = e
480         x = x `cast` co         -- A trivial binding
481 There's a chance that e will be a constructor application or function, or something
482 like that, so moving the coerion to the usage site may well cancel the coersions
483 and lead to further optimisation.  Example:
484
485      data family T a :: *
486      data instance T Int = T Int
487
488      foo :: Int -> Int -> Int
489      foo m n = ...
490         where
491           x = T m
492           go 0 = 0
493           go n = case x of { T m -> go (n-m) }
494                 -- This case should optimise
495
496 Note [Float coercions (unlifted)]
497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
498 BUT don't do [Float coercions] if 'e' has an unlifted type.
499 This *can* happen:
500
501      foo :: Int = (error (# Int,Int #) "urk")
502                   `cast` CoUnsafe (# Int,Int #) Int
503
504 If do the makeTrivial thing to the error call, we'll get
505     foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
506 But 'v' isn't in scope!
507
508 These strange casts can happen as a result of case-of-case
509         bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
510                 (# p,q #) -> p+q
511
512
513 \begin{code}
514 makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
515 -- Binds the expression to a variable, if it's not trivial, returning the variable
516 makeTrivial env expr
517   | exprIsTrivial expr
518   = return (env, expr)
519   | otherwise           -- See Note [Take care] below
520   = do  { var <- newId (fsLit "a") (exprType expr)
521         ; env' <- completeNonRecX env False var var expr
522 --        pprTrace "makeTrivial" (vcat [ppr var <+> ppr (exprArity (substExpr env' (Var var)))
523 --                                     , ppr expr
524 --                                     , ppr (substExpr env' (Var var))
525 --                                     , ppr (idArity (fromJust (lookupInScope (seInScope env') var))) ]) $
526         ; return (env', substExpr env' (Var var)) }
527         -- The substitution is needed becase we're constructing a new binding
528         --     a = rhs
529         -- And if rhs is of form (rhs1 |> co), then we might get
530         --     a1 = rhs1
531         --     a = a1 |> co
532         -- and now a's RHS is trivial and can be substituted out, and that
533         -- is what completeNonRecX will do
534 \end{code}
535
536
537 %************************************************************************
538 %*                                                                      *
539 \subsection{Completing a lazy binding}
540 %*                                                                      *
541 %************************************************************************
542
543 completeBind
544   * deals only with Ids, not TyVars
545   * takes an already-simplified binder and RHS
546   * is used for both recursive and non-recursive bindings
547   * is used for both top-level and non-top-level bindings
548
549 It does the following:
550   - tries discarding a dead binding
551   - tries PostInlineUnconditionally
552   - add unfolding [this is the only place we add an unfolding]
553   - add arity
554
555 It does *not* attempt to do let-to-case.  Why?  Because it is used for
556   - top-level bindings (when let-to-case is impossible)
557   - many situations where the "rhs" is known to be a WHNF
558                 (so let-to-case is inappropriate).
559
560 Nor does it do the atomic-argument thing
561
562 \begin{code}
563 completeBind :: SimplEnv
564              -> TopLevelFlag            -- Flag stuck into unfolding
565              -> InId                    -- Old binder
566              -> OutId -> OutExpr        -- New binder and RHS
567              -> SimplM SimplEnv
568 -- completeBind may choose to do its work
569 --      * by extending the substitution (e.g. let x = y in ...)
570 --      * or by adding to the floats in the envt
571
572 completeBind env top_lvl old_bndr new_bndr new_rhs
573   = do  { let old_info = idInfo old_bndr
574               old_unf  = unfoldingInfo old_info
575               occ_info = occInfo old_info
576
577         ; new_unfolding <- simplUnfolding env top_lvl old_bndr occ_info new_rhs old_unf
578
579         ; if postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs new_unfolding
580                         -- Inline and discard the binding
581           then do  { tick (PostInlineUnconditionally old_bndr)
582                     ; return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
583                 -- Use the substitution to make quite, quite sure that the
584                 -- substitution will happen, since we are going to discard the binding
585
586           else return (addNonRecWithUnf env new_bndr new_rhs new_unfolding) }
587
588 ------------------------------
589 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
590 -- Add a new binding to the environment, complete with its unfolding
591 -- but *do not* do postInlineUnconditionally, because we have already
592 -- processed some of the scope of the binding
593 -- We still want the unfolding though.  Consider
594 --      let 
595 --            x = /\a. let y = ... in Just y
596 --      in body
597 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
598 -- but 'x' may well then be inlined in 'body' in which case we'd like the 
599 -- opportunity to inline 'y' too.
600
601 addPolyBind top_lvl env (NonRec poly_id rhs)
602   = do  { unfolding <- simplUnfolding env top_lvl poly_id NoOccInfo rhs noUnfolding
603                         -- Assumes that poly_id did not have an INLINE prag
604                         -- which is perhaps wrong.  ToDo: think about this
605         ; return (addNonRecWithUnf env poly_id rhs unfolding) }
606
607 addPolyBind _ env bind@(Rec _) = return (extendFloats env bind)
608                 -- Hack: letrecs are more awkward, so we extend "by steam"
609                 -- without adding unfoldings etc.  At worst this leads to
610                 -- more simplifier iterations
611
612 ------------------------------
613 addNonRecWithUnf :: SimplEnv
614                  -> OutId -> OutExpr    -- New binder and RHS
615                  -> Unfolding           -- New unfolding
616                  -> SimplEnv
617 addNonRecWithUnf env new_bndr new_rhs new_unfolding
618   = let new_arity = exprArity new_rhs
619         old_arity = idArity new_bndr
620         info1 = idInfo new_bndr `setArityInfo` new_arity
621         
622               -- Unfolding info: Note [Setting the new unfolding]
623         info2 = info1 `setUnfoldingInfo` new_unfolding
624
625         -- Demand info: Note [Setting the demand info]
626         info3 | isEvaldUnfolding new_unfolding = zapDemandInfo info2 `orElse` info2
627               | otherwise                      = info2
628
629         final_id = new_bndr `setIdInfo` info3
630         dmd_arity = length $ fst $ splitStrictSig $ idNewStrictness new_bndr
631     in
632     ASSERT( isId new_bndr )
633     WARN( new_arity < old_arity || new_arity < dmd_arity, 
634           (ptext (sLit "Arity decrease:") <+> ppr final_id <+> ppr old_arity
635                 <+> ppr new_arity <+> ppr dmd_arity) )
636         -- Note [Arity decrease]
637
638     final_id `seq`   -- This seq forces the Id, and hence its IdInfo,
639                      -- and hence any inner substitutions
640             -- pprTrace "Binding" (ppr final_id <+> ppr unfolding) $
641     addNonRec env final_id new_rhs
642                 -- The addNonRec adds it to the in-scope set too
643
644 ------------------------------
645 simplUnfolding :: SimplEnv-> TopLevelFlag
646                -> Id    -- Debug output only
647                -> OccInfo -> OutExpr
648                -> Unfolding -> SimplM Unfolding
649 -- Note [Setting the new unfolding]
650 simplUnfolding env _ _ _ _ (DFunUnfolding con ops)
651   = return (DFunUnfolding con ops')
652   where
653     ops' = map (CoreSubst.substExpr (mkCoreSubst env)) ops
654
655 simplUnfolding env top_lvl _ _ _ 
656     (CoreUnfolding { uf_tmpl = expr, uf_arity = arity
657                    , uf_guidance = guide@(InlineRule {}) })
658   = do { expr' <- simplExpr (setMode SimplGently env) expr
659                -- See Note [Simplifying gently inside InlineRules] in SimplUtils
660        ; let mb_wkr' = CoreSubst.substInlineRuleInfo (mkCoreSubst env) (ir_info guide)
661        ; return (mkCoreUnfolding (isTopLevel top_lvl) expr' arity 
662                                  (guide { ir_info = mb_wkr' })) }
663                 -- See Note [Top-level flag on inline rules] in CoreUnfold
664
665 simplUnfolding _ top_lvl _ occ_info new_rhs _
666   | omit_unfolding = return NoUnfolding 
667   | otherwise      = return (mkUnfolding (isTopLevel top_lvl) new_rhs)
668   where
669     omit_unfolding = isNonRuleLoopBreaker occ_info
670 \end{code}
671
672 Note [Arity decrease]
673 ~~~~~~~~~~~~~~~~~~~~~
674 Generally speaking the arity of a binding should not decrease.  But it *can* 
675 legitimately happen becuase of RULES.  Eg
676         f = g Int
677 where g has arity 2, will have arity 2.  But if there's a rewrite rule
678         g Int --> h
679 where h has arity 1, then f's arity will decrease.  Here's a real-life example,
680 which is in the output of Specialise:
681
682      Rec {
683         $dm {Arity 2} = \d.\x. op d
684         {-# RULES forall d. $dm Int d = $s$dm #-}
685         
686         dInt = MkD .... opInt ...
687         opInt {Arity 1} = $dm dInt
688
689         $s$dm {Arity 0} = \x. op dInt }
690
691 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
692 That's why Specialise goes to a little trouble to pin the right arity
693 on specialised functions too.
694
695 Note [Setting the new unfolding]
696 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
697 * If there's an INLINE pragma, we simplify the RHS gently.  Maybe we
698   should do nothing at all, but simplifying gently might get rid of 
699   more crap.
700
701 * If not, we make an unfolding from the new RHS.  But *only* for
702   non-loop-breakers. Making loop breakers not have an unfolding at all
703   means that we can avoid tests in exprIsConApp, for example.  This is
704   important: if exprIsConApp says 'yes' for a recursive thing, then we
705   can get into an infinite loop
706
707 If there's an InlineRule on a loop breaker, we hang on to the inlining.
708 It's pretty dodgy, but the user did say 'INLINE'.  May need to revisit
709 this choice.
710
711 Note [Setting the demand info]
712 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
713 If the unfolding is a value, the demand info may
714 go pear-shaped, so we nuke it.  Example:
715      let x = (a,b) in
716      case x of (p,q) -> h p q x
717 Here x is certainly demanded. But after we've nuked
718 the case, we'll get just
719      let x = (a,b) in h a b x
720 and now x is not demanded (I'm assuming h is lazy)
721 This really happens.  Similarly
722      let f = \x -> e in ...f..f...
723 After inlining f at some of its call sites the original binding may
724 (for example) be no longer strictly demanded.
725 The solution here is a bit ad hoc...
726
727
728 %************************************************************************
729 %*                                                                      *
730 \subsection[Simplify-simplExpr]{The main function: simplExpr}
731 %*                                                                      *
732 %************************************************************************
733
734 The reason for this OutExprStuff stuff is that we want to float *after*
735 simplifying a RHS, not before.  If we do so naively we get quadratic
736 behaviour as things float out.
737
738 To see why it's important to do it after, consider this (real) example:
739
740         let t = f x
741         in fst t
742 ==>
743         let t = let a = e1
744                     b = e2
745                 in (a,b)
746         in fst t
747 ==>
748         let a = e1
749             b = e2
750             t = (a,b)
751         in
752         a       -- Can't inline a this round, cos it appears twice
753 ==>
754         e1
755
756 Each of the ==> steps is a round of simplification.  We'd save a
757 whole round if we float first.  This can cascade.  Consider
758
759         let f = g d
760         in \x -> ...f...
761 ==>
762         let f = let d1 = ..d.. in \y -> e
763         in \x -> ...f...
764 ==>
765         let d1 = ..d..
766         in \x -> ...(\y ->e)...
767
768 Only in this second round can the \y be applied, and it
769 might do the same again.
770
771
772 \begin{code}
773 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
774 simplExpr env expr = simplExprC env expr mkBoringStop
775
776 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
777         -- Simplify an expression, given a continuation
778 simplExprC env expr cont
779   = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
780     do  { (env', expr') <- simplExprF (zapFloats env) expr cont
781         ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
782           -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
783           -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
784           return (wrapFloats env' expr') }
785
786 --------------------------------------------------
787 simplExprF :: SimplEnv -> InExpr -> SimplCont
788            -> SimplM (SimplEnv, OutExpr)
789
790 simplExprF env e cont
791   = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
792     simplExprF' env e cont
793
794 simplExprF' :: SimplEnv -> InExpr -> SimplCont
795             -> SimplM (SimplEnv, OutExpr)
796 simplExprF' env (Var v)        cont = simplVar env v cont
797 simplExprF' env (Lit lit)      cont = rebuild env (Lit lit) cont
798 simplExprF' env (Note n expr)  cont = simplNote env n expr cont
799 simplExprF' env (Cast body co) cont = simplCast env body co cont
800 simplExprF' env (App fun arg)  cont = simplExprF env fun $
801                                       ApplyTo NoDup arg env cont
802
803 simplExprF' env expr@(Lam _ _) cont
804   = simplLam env (map zap bndrs) body cont
805         -- The main issue here is under-saturated lambdas
806         --   (\x1. \x2. e) arg1
807         -- Here x1 might have "occurs-once" occ-info, because occ-info
808         -- is computed assuming that a group of lambdas is applied
809         -- all at once.  If there are too few args, we must zap the
810         -- occ-info.
811   where
812     n_args   = countArgs cont
813     n_params = length bndrs
814     (bndrs, body) = collectBinders expr
815     zap | n_args >= n_params = \b -> b
816         | otherwise          = \b -> if isTyVar b then b
817                                      else zapLamIdInfo b
818         -- NB: we count all the args incl type args
819         -- so we must count all the binders (incl type lambdas)
820
821 simplExprF' env (Type ty) cont
822   = ASSERT( contIsRhsOrArg cont )
823     do  { ty' <- simplCoercion env ty
824         ; rebuild env (Type ty') cont }
825
826 simplExprF' env (Case scrut bndr _ alts) cont
827   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
828   =     -- Simplify the scrutinee with a Select continuation
829     simplExprF env scrut (Select NoDup bndr alts env cont)
830
831   | otherwise
832   =     -- If case-of-case is off, simply simplify the case expression
833         -- in a vanilla Stop context, and rebuild the result around it
834     do  { case_expr' <- simplExprC env scrut case_cont
835         ; rebuild env case_expr' cont }
836   where
837     case_cont = Select NoDup bndr alts env mkBoringStop
838
839 simplExprF' env (Let (Rec pairs) body) cont
840   = do  { env' <- simplRecBndrs env (map fst pairs)
841                 -- NB: bndrs' don't have unfoldings or rules
842                 -- We add them as we go down
843
844         ; env'' <- simplRecBind env' NotTopLevel pairs
845         ; simplExprF env'' body cont }
846
847 simplExprF' env (Let (NonRec bndr rhs) body) cont
848   = simplNonRecE env bndr (rhs, env) ([], body) cont
849
850 ---------------------------------
851 simplType :: SimplEnv -> InType -> SimplM OutType
852         -- Kept monadic just so we can do the seqType
853 simplType env ty
854   = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
855     seqType new_ty   `seq`   return new_ty
856   where
857     new_ty = substTy env ty
858
859 ---------------------------------
860 simplCoercion :: SimplEnv -> InType -> SimplM OutType
861 -- The InType isn't *necessarily* a coercion, but it might be
862 -- (in a type application, say) and optCoercion is a no-op on types
863 simplCoercion env co
864   = do { co' <- simplType env co
865        ; return (optCoercion co') }
866 \end{code}
867
868
869 %************************************************************************
870 %*                                                                      *
871 \subsection{The main rebuilder}
872 %*                                                                      *
873 %************************************************************************
874
875 \begin{code}
876 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
877 -- At this point the substitution in the SimplEnv should be irrelevant
878 -- only the in-scope set and floats should matter
879 rebuild env expr cont0
880   = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
881     case cont0 of
882       Stop {}                      -> return (env, expr)
883       CoerceIt co cont             -> rebuild env (mkCoerce co expr) cont
884       Select _ bndr alts se cont   -> rebuildCase (se `setFloats` env) expr bndr alts cont
885       StrictArg fun _ info cont    -> rebuildCall env (fun `App` expr) info cont
886       StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
887                                          ; simplLam env' bs body cont }
888       ApplyTo _ arg se cont        -> do { arg' <- simplExpr (se `setInScope` env) arg
889                                          ; rebuild env (App expr arg') cont }
890 \end{code}
891
892
893 %************************************************************************
894 %*                                                                      *
895 \subsection{Lambdas}
896 %*                                                                      *
897 %************************************************************************
898
899 \begin{code}
900 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
901           -> SimplM (SimplEnv, OutExpr)
902 simplCast env body co0 cont0
903   = do  { co1 <- simplCoercion env co0
904         ; simplExprF env body (addCoerce co1 cont0) }
905   where
906        addCoerce co cont = add_coerce co (coercionKind co) cont
907
908        add_coerce _co (s1, k1) cont     -- co :: ty~ty
909          | s1 `coreEqType` k1 = cont    -- is a no-op
910
911        add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
912          | (_l1, t1) <- coercionKind co2
913                 --      e |> (g1 :: S1~L) |> (g2 :: L~T1)
914                 -- ==>
915                 --      e,                       if S1=T1
916                 --      e |> (g1 . g2 :: S1~T1)  otherwise
917                 --
918                 -- For example, in the initial form of a worker
919                 -- we may find  (coerce T (coerce S (\x.e))) y
920                 -- and we'd like it to simplify to e[y/x] in one round
921                 -- of simplification
922          , s1 `coreEqType` t1  = cont            -- The coerces cancel out
923          | otherwise           = CoerceIt (mkTransCoercion co1 co2) cont
924
925        add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
926                 -- (f |> g) ty  --->   (f ty) |> (g @ ty)
927                 -- This implements the PushT rule from the paper
928          | Just (tyvar,_) <- splitForAllTy_maybe s1s2
929          , not (isCoVar tyvar)
930          = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
931          where
932            ty' = substTy (arg_se `setInScope` env) arg_ty
933
934         -- ToDo: the PushC rule is not implemented at all
935
936        add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
937          | not (isTypeArg arg)  -- This implements the Push rule from the paper
938          , isFunTy s1s2   -- t1t2 must be a function type, becuase it's applied
939                 --      (e |> (g :: s1s2 ~ t1->t2)) f
940                 -- ===>
941                 --      (e (f |> (arg g :: t1~s1))
942                 --      |> (res g :: s2->t2)
943                 --
944                 -- t1t2 must be a function type, t1->t2, because it's applied
945                 -- to something but s1s2 might conceivably not be
946                 --
947                 -- When we build the ApplyTo we can't mix the out-types
948                 -- with the InExpr in the argument, so we simply substitute
949                 -- to make it all consistent.  It's a bit messy.
950                 -- But it isn't a common case.
951                 --
952                 -- Example of use: Trac #995
953          = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
954          where
955            -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
956            -- t2 ~ s2 with left and right on the curried form:
957            --    (->) t1 t2 ~ (->) s1 s2
958            [co1, co2] = decomposeCo 2 co
959            new_arg    = mkCoerce (mkSymCoercion co1) arg'
960            arg'       = substExpr (arg_se `setInScope` env) arg
961
962        add_coerce co _ cont = CoerceIt co cont
963 \end{code}
964
965
966 %************************************************************************
967 %*                                                                      *
968 \subsection{Lambdas}
969 %*                                                                      *
970 %************************************************************************
971
972 \begin{code}
973 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
974          -> SimplM (SimplEnv, OutExpr)
975
976 simplLam env [] body cont = simplExprF env body cont
977
978         -- Beta reduction
979 simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
980   = do  { tick (BetaReduction bndr)
981         ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
982
983         -- Not enough args, so there are real lambdas left to put in the result
984 simplLam env bndrs body cont
985   = do  { (env', bndrs') <- simplLamBndrs env bndrs
986         ; body' <- simplExpr env' body
987         ; new_lam <- mkLam env' bndrs' body'
988         ; rebuild env' new_lam cont }
989
990 ------------------
991 simplNonRecE :: SimplEnv
992              -> InBndr                  -- The binder
993              -> (InExpr, SimplEnv)      -- Rhs of binding (or arg of lambda)
994              -> ([InBndr], InExpr)      -- Body of the let/lambda
995                                         --      \xs.e
996              -> SimplCont
997              -> SimplM (SimplEnv, OutExpr)
998
999 -- simplNonRecE is used for
1000 --  * non-top-level non-recursive lets in expressions
1001 --  * beta reduction
1002 --
1003 -- It deals with strict bindings, via the StrictBind continuation,
1004 -- which may abort the whole process
1005 --
1006 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1007 -- representing a lambda; so we recurse back to simplLam
1008 -- Why?  Because of the binder-occ-info-zapping done before
1009 --       the call to simplLam in simplExprF (Lam ...)
1010
1011         -- First deal with type applications and type lets
1012         --   (/\a. e) (Type ty)   and   (let a = Type ty in e)
1013 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
1014   = ASSERT( isTyVar bndr )
1015     do  { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
1016         ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
1017
1018 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1019   | preInlineUnconditionally env NotTopLevel bndr rhs
1020   = do  { tick (PreInlineUnconditionally bndr)
1021         ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1022
1023   | isStrictId bndr
1024   = do  { simplExprF (rhs_se `setFloats` env) rhs
1025                      (StrictBind bndr bndrs body env cont) }
1026
1027   | otherwise
1028   = ASSERT( not (isTyVar bndr) )
1029     do  { (env1, bndr1) <- simplNonRecBndr env bndr
1030         ; let (env2, bndr2) = addBndrRules env1 bndr bndr1
1031         ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1032         ; simplLam env3 bndrs body cont }
1033 \end{code}
1034
1035
1036 %************************************************************************
1037 %*                                                                      *
1038 \subsection{Notes}
1039 %*                                                                      *
1040 %************************************************************************
1041
1042 \begin{code}
1043 -- Hack alert: we only distinguish subsumed cost centre stacks for the
1044 -- purposes of inlining.  All other CCCSs are mapped to currentCCS.
1045 simplNote :: SimplEnv -> Note -> CoreExpr -> SimplCont
1046           -> SimplM (SimplEnv, OutExpr)
1047 simplNote env (SCC cc) e cont
1048   | pushCCisNop cc (getEnclosingCC env)  -- scc "f" (...(scc "f" e)...) 
1049   = simplExprF env e cont                -- ==>  scc "f" (...e...)
1050   | otherwise
1051   = do  { e' <- simplExpr (setEnclosingCC env currentCCS) e
1052         ; rebuild env (mkSCC cc e') cont }
1053
1054 simplNote env (CoreNote s) e cont
1055   = do { e' <- simplExpr env e
1056        ; rebuild env (Note (CoreNote s) e') cont }
1057 \end{code}
1058
1059
1060 %************************************************************************
1061 %*                                                                      *
1062 \subsection{Dealing with calls}
1063 %*                                                                      *
1064 %************************************************************************
1065
1066 \begin{code}
1067 simplVar :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1068 simplVar env var cont
1069   = case substId env var of
1070         DoneEx e         -> simplExprF (zapSubstEnv env) e cont
1071         ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
1072         DoneId var1      -> completeCall (zapSubstEnv env) var1 cont
1073                 -- Note [zapSubstEnv]
1074                 -- The template is already simplified, so don't re-substitute.
1075                 -- This is VITAL.  Consider
1076                 --      let x = e in
1077                 --      let y = \z -> ...x... in
1078                 --      \ x -> ...y...
1079                 -- We'll clone the inner \x, adding x->x' in the id_subst
1080                 -- Then when we inline y, we must *not* replace x by x' in
1081                 -- the inlined copy!!
1082
1083 ---------------------------------------------------------
1084 --      Dealing with a call site
1085
1086 completeCall :: SimplEnv -> Id -> SimplCont -> SimplM (SimplEnv, OutExpr)
1087 completeCall env var cont
1088   = do  { let   (args,call_cont) = contArgs cont
1089                 -- The args are OutExprs, obtained by *lazily* substituting
1090                 -- in the args found in cont.  These args are only examined
1091                 -- to limited depth (unless a rule fires).  But we must do
1092                 -- the substitution; rule matching on un-simplified args would
1093                 -- be bogus
1094
1095         ------------- First try rules ----------------
1096         -- Do this before trying inlining.  Some functions have
1097         -- rules *and* are strict; in this case, we don't want to
1098         -- inline the wrapper of the non-specialised thing; better
1099         -- to call the specialised thing instead.
1100         --
1101         -- We used to use the black-listing mechanism to ensure that inlining of
1102         -- the wrapper didn't occur for things that have specialisations till a
1103         -- later phase, so but now we just try RULES first
1104         -- 
1105         -- See also Note [Rules for recursive functions]
1106         ; rule_base <- getSimplRules
1107         ; let rules = getRules rule_base var
1108         ; mb_rule <- tryRules env var rules args call_cont
1109         ; case mb_rule of {
1110              Just (n_args, rule_rhs) -> simplExprF env rule_rhs (dropArgs n_args cont) ;
1111                  -- The ruleArity says how many args the rule consumed
1112            ; Nothing -> do       -- No rules
1113
1114
1115         ------------- Next try inlining ----------------
1116         { dflags <- getDOptsSmpl
1117         ; let   arg_infos = [interestingArg arg | arg <- args, isValArg arg]
1118                 n_val_args = length arg_infos
1119                 interesting_cont = interestingCallContext call_cont
1120                 active_inline = activeInline env var
1121                 maybe_inline  = callSiteInline dflags active_inline var
1122                                                (null args) arg_infos interesting_cont
1123         ; case maybe_inline of {
1124             Just unfolding      -- There is an inlining!
1125               ->  do { tick (UnfoldingDone var)
1126                      ; (if dopt Opt_D_dump_inlinings dflags then
1127                            pprTrace ("Inlining done: " ++ showSDoc (ppr var)) (vcat [
1128                                 text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1129                                 text "Inlined fn: " <+> nest 2 (ppr unfolding),
1130                                 text "Cont:  " <+> ppr call_cont])
1131                          else
1132                                 id)
1133                        simplExprF env unfolding cont }
1134
1135             ; Nothing ->                -- No inlining!
1136
1137         ------------- No inlining! ----------------
1138         -- Next, look for rules or specialisations that match
1139         --
1140         rebuildCall env (Var var)
1141                     (mkArgInfo var rules n_val_args call_cont) 
1142                     cont
1143     }}}}
1144
1145 rebuildCall :: SimplEnv
1146             -> OutExpr       -- Function 
1147             -> ArgInfo
1148             -> SimplCont
1149             -> SimplM (SimplEnv, OutExpr)
1150 rebuildCall env fun (ArgInfo { ai_strs = [] }) cont
1151   -- When we run out of strictness args, it means
1152   -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1153   -- Then we want to discard the entire strict continuation.  E.g.
1154   --    * case (error "hello") of { ... }
1155   --    * (error "Hello") arg
1156   --    * f (error "Hello") where f is strict
1157   --    etc
1158   -- Then, especially in the first of these cases, we'd like to discard
1159   -- the continuation, leaving just the bottoming expression.  But the
1160   -- type might not be right, so we may have to add a coerce.
1161   | not (contIsTrivial cont)     -- Only do this if there is a non-trivial
1162   = return (env, mk_coerce fun)  -- contination to discard, else we do it
1163   where                          -- again and again!
1164     fun_ty  = exprType fun
1165     cont_ty = contResultType env fun_ty cont
1166     co      = mkUnsafeCoercion fun_ty cont_ty
1167     mk_coerce expr | cont_ty `coreEqType` fun_ty = expr
1168                    | otherwise = mkCoerce co expr
1169
1170 rebuildCall env fun info (ApplyTo _ (Type arg_ty) se cont)
1171   = do  { ty' <- simplCoercion (se `setInScope` env) arg_ty
1172         ; rebuildCall env (fun `App` Type ty') info cont }
1173
1174 rebuildCall env fun 
1175            (ArgInfo { ai_rules = has_rules, ai_strs = str:strs, ai_discs = disc:discs })
1176            (ApplyTo _ arg arg_se cont)
1177   | str                 -- Strict argument
1178   = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1179     simplExprF (arg_se `setFloats` env) arg
1180                (StrictArg fun cci arg_info' cont)
1181                 -- Note [Shadowing]
1182
1183   | otherwise                           -- Lazy argument
1184         -- DO NOT float anything outside, hence simplExprC
1185         -- There is no benefit (unlike in a let-binding), and we'd
1186         -- have to be very careful about bogus strictness through
1187         -- floating a demanded let.
1188   = do  { arg' <- simplExprC (arg_se `setInScope` env) arg
1189                              (mkLazyArgStop cci)
1190         ; rebuildCall env (fun `App` arg') arg_info' cont }
1191   where
1192     arg_info' = ArgInfo { ai_rules = has_rules, ai_strs = strs, ai_discs = discs }
1193     cci | has_rules || disc > 0 = ArgCtxt has_rules disc  -- Be keener here
1194         | otherwise             = BoringCtxt              -- Nothing interesting
1195
1196 rebuildCall env fun _ cont
1197   = rebuild env fun cont
1198 \end{code}
1199
1200 Note [Shadowing]
1201 ~~~~~~~~~~~~~~~~
1202 This part of the simplifier may break the no-shadowing invariant
1203 Consider
1204         f (...(\a -> e)...) (case y of (a,b) -> e')
1205 where f is strict in its second arg
1206 If we simplify the innermost one first we get (...(\a -> e)...)
1207 Simplifying the second arg makes us float the case out, so we end up with
1208         case y of (a,b) -> f (...(\a -> e)...) e'
1209 So the output does not have the no-shadowing invariant.  However, there is
1210 no danger of getting name-capture, because when the first arg was simplified
1211 we used an in-scope set that at least mentioned all the variables free in its
1212 static environment, and that is enough.
1213
1214 We can't just do innermost first, or we'd end up with a dual problem:
1215         case x of (a,b) -> f e (...(\a -> e')...)
1216
1217 I spent hours trying to recover the no-shadowing invariant, but I just could
1218 not think of an elegant way to do it.  The simplifier is already knee-deep in
1219 continuations.  We have to keep the right in-scope set around; AND we have
1220 to get the effect that finding (error "foo") in a strict arg position will
1221 discard the entire application and replace it with (error "foo").  Getting
1222 all this at once is TOO HARD!
1223
1224
1225 %************************************************************************
1226 %*                                                                      *
1227                 Rewrite rules
1228 %*                                                                      *
1229 %************************************************************************
1230
1231 \begin{code}
1232 tryRules :: SimplEnv
1233          -> Id -> [CoreRule] -> [OutExpr] -> SimplCont 
1234          -> SimplM (Maybe (Arity, CoreExpr))         -- The arity is the number of
1235                                                      -- args consumed by the rule
1236 tryRules env fn rules args call_cont
1237   | null rules
1238   = return Nothing
1239   | otherwise
1240   = do { dflags <- getDOptsSmpl
1241        ; case activeRule dflags env of {
1242            Nothing     -> return Nothing  ; -- No rules apply
1243            Just act_fn -> 
1244
1245          case lookupRule act_fn (getInScope env) fn args rules of {
1246            Nothing               -> return Nothing ;   -- No rule matches
1247            Just (rule, rule_rhs) ->
1248
1249              do { tick (RuleFired (ru_name rule))
1250                 ; (if dopt Opt_D_dump_rule_firings dflags then
1251                      pprTrace "Rule fired" (vcat [
1252                         text "Rule:" <+> ftext (ru_name rule),
1253                         text "Before:" <+> ppr fn <+> sep (map pprParendExpr args),
1254                         text "After: " <+> pprCoreExpr rule_rhs,
1255                         text "Cont:  " <+> ppr call_cont])
1256                    else
1257                         id)             $
1258                    return (Just (ruleArity rule, rule_rhs)) }}}}
1259 \end{code}
1260
1261 Note [Rules for recursive functions]
1262 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1263 You might think that we shouldn't apply rules for a loop breaker:
1264 doing so might give rise to an infinite loop, because a RULE is
1265 rather like an extra equation for the function:
1266      RULE:           f (g x) y = x+y
1267      Eqn:            f a     y = a-y
1268
1269 But it's too drastic to disable rules for loop breakers.
1270 Even the foldr/build rule would be disabled, because foldr
1271 is recursive, and hence a loop breaker:
1272      foldr k z (build g) = g k z
1273 So it's up to the programmer: rules can cause divergence
1274
1275
1276 %************************************************************************
1277 %*                                                                      *
1278                 Rebuilding a cse expression
1279 %*                                                                      *
1280 %************************************************************************
1281
1282 Note [Case elimination]
1283 ~~~~~~~~~~~~~~~~~~~~~~~
1284 The case-elimination transformation discards redundant case expressions.
1285 Start with a simple situation:
1286
1287         case x# of      ===>   e[x#/y#]
1288           y# -> e
1289
1290 (when x#, y# are of primitive type, of course).  We can't (in general)
1291 do this for algebraic cases, because we might turn bottom into
1292 non-bottom!
1293
1294 The code in SimplUtils.prepareAlts has the effect of generalise this
1295 idea to look for a case where we're scrutinising a variable, and we
1296 know that only the default case can match.  For example:
1297
1298         case x of
1299           0#      -> ...
1300           DEFAULT -> ...(case x of
1301                          0#      -> ...
1302                          DEFAULT -> ...) ...
1303
1304 Here the inner case is first trimmed to have only one alternative, the
1305 DEFAULT, after which it's an instance of the previous case.  This
1306 really only shows up in eliminating error-checking code.
1307
1308 We also make sure that we deal with this very common case:
1309
1310         case e of
1311           x -> ...x...
1312
1313 Here we are using the case as a strict let; if x is used only once
1314 then we want to inline it.  We have to be careful that this doesn't
1315 make the program terminate when it would have diverged before, so we
1316 check that
1317         - e is already evaluated (it may so if e is a variable)
1318         - x is used strictly, or
1319
1320 Lastly, the code in SimplUtils.mkCase combines identical RHSs.  So
1321
1322         case e of       ===> case e of DEFAULT -> r
1323            True  -> r
1324            False -> r
1325
1326 Now again the case may be elminated by the CaseElim transformation.
1327
1328
1329 Further notes about case elimination
1330 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1331 Consider:       test :: Integer -> IO ()
1332                 test = print
1333
1334 Turns out that this compiles to:
1335     Print.test
1336       = \ eta :: Integer
1337           eta1 :: State# RealWorld ->
1338           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1339           case hPutStr stdout
1340                  (PrelNum.jtos eta ($w[] @ Char))
1341                  eta1
1342           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1343
1344 Notice the strange '<' which has no effect at all. This is a funny one.
1345 It started like this:
1346
1347 f x y = if x < 0 then jtos x
1348           else if y==0 then "" else jtos x
1349
1350 At a particular call site we have (f v 1).  So we inline to get
1351
1352         if v < 0 then jtos x
1353         else if 1==0 then "" else jtos x
1354
1355 Now simplify the 1==0 conditional:
1356
1357         if v<0 then jtos v else jtos v
1358
1359 Now common-up the two branches of the case:
1360
1361         case (v<0) of DEFAULT -> jtos v
1362
1363 Why don't we drop the case?  Because it's strict in v.  It's technically
1364 wrong to drop even unnecessary evaluations, and in practice they
1365 may be a result of 'seq' so we *definitely* don't want to drop those.
1366 I don't really know how to improve this situation.
1367
1368 \begin{code}
1369 ---------------------------------------------------------
1370 --      Eliminate the case if possible
1371
1372 rebuildCase, reallyRebuildCase
1373    :: SimplEnv
1374    -> OutExpr          -- Scrutinee
1375    -> InId             -- Case binder
1376    -> [InAlt]          -- Alternatives (inceasing order)
1377    -> SimplCont
1378    -> SimplM (SimplEnv, OutExpr)
1379
1380 --------------------------------------------------
1381 --      1. Eliminate the case if there's a known constructor
1382 --------------------------------------------------
1383
1384 rebuildCase env scrut case_bndr alts cont
1385   | Lit lit <- scrut    -- No need for same treatment as constructors
1386                         -- because literals are inlined more vigorously
1387   = do  { tick (KnownBranch case_bndr)
1388         ; case findAlt (LitAlt lit) alts of
1389             Nothing           -> missingAlt env case_bndr alts cont
1390             Just (_, bs, rhs) -> simple_rhs bs rhs }
1391
1392   | Just (con, ty_args, other_args) <- exprIsConApp_maybe scrut
1393         -- Works when the scrutinee is a variable with a known unfolding
1394         -- as well as when it's an explicit constructor application
1395   = do  { tick (KnownBranch case_bndr)
1396         ; case findAlt (DataAlt con) alts of
1397             Nothing  -> missingAlt env case_bndr alts cont
1398             Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1399             Just (_, bs, rhs)       -> knownCon env scrut con ty_args other_args 
1400                                                 case_bndr bs rhs cont
1401         }
1402   where
1403     simple_rhs bs rhs = ASSERT( null bs ) 
1404                         do { env' <- simplNonRecX env case_bndr scrut
1405                            ; simplExprF env' rhs cont }
1406
1407
1408 --------------------------------------------------
1409 --      2. Eliminate the case if scrutinee is evaluated
1410 --------------------------------------------------
1411
1412 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1413   -- See if we can get rid of the case altogether
1414   -- See Note [Case eliminiation] 
1415   -- mkCase made sure that if all the alternatives are equal,
1416   -- then there is now only one (DEFAULT) rhs
1417  | all isDeadBinder bndrs       -- bndrs are [InId]
1418
1419         -- Check that the scrutinee can be let-bound instead of case-bound
1420  , exprOkForSpeculation scrut
1421                 -- OK not to evaluate it
1422                 -- This includes things like (==# a# b#)::Bool
1423                 -- so that we simplify
1424                 --      case ==# a# b# of { True -> x; False -> x }
1425                 -- to just
1426                 --      x
1427                 -- This particular example shows up in default methods for
1428                 -- comparision operations (e.g. in (>=) for Int.Int32)
1429         || exprIsHNF scrut                      -- It's already evaluated
1430         || var_demanded_later scrut             -- It'll be demanded later
1431
1432 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1433 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1434 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1435 --      its argument:  case x of { y -> dataToTag# y }
1436 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1437 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1438 --      other problems
1439 --      Also we don't want to discard 'seq's
1440   = do  { tick (CaseElim case_bndr)
1441         ; env' <- simplNonRecX env case_bndr scrut
1442         ; simplExprF env' rhs cont }
1443   where
1444         -- The case binder is going to be evaluated later,
1445         -- and the scrutinee is a simple variable
1446     var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1447                                  && not (isTickBoxOp v)
1448                                     -- ugly hack; covering this case is what
1449                                     -- exprOkForSpeculation was intended for.
1450     var_demanded_later _       = False
1451
1452 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1453   | all isDeadBinder (case_bndr : bndrs)  -- So this is just 'seq'
1454   =     -- For this case, see Note [User-defined RULES for seq] in MkId
1455     do { let rhs' = substExpr env rhs
1456              out_args = [Type (substTy env (idType case_bndr)), 
1457                          Type (exprType rhs'), scrut, rhs']
1458                       -- Lazily evaluated, so we don't do most of this
1459
1460        ; rule_base <- getSimplRules
1461        ; let rules = getRules rule_base seqId
1462        ; mb_rule <- tryRules env seqId rules out_args cont
1463        ; case mb_rule of 
1464            Just (n_args, res) -> simplExprF (zapSubstEnv env) 
1465                                             (mkApps res (drop n_args out_args))
1466                                             cont
1467            Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1468
1469 rebuildCase env scrut case_bndr alts cont
1470   = reallyRebuildCase env scrut case_bndr alts cont
1471
1472 --------------------------------------------------
1473 --      3. Catch-all case
1474 --------------------------------------------------
1475
1476 reallyRebuildCase env scrut case_bndr alts cont
1477   = do  {       -- Prepare the continuation;
1478                 -- The new subst_env is in place
1479           (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1480
1481         -- Simplify the alternatives
1482         ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1483
1484         -- Check for empty alternatives
1485         ; if null alts' then missingAlt env case_bndr alts cont
1486           else do
1487         { case_expr <- mkCase scrut' case_bndr' alts'
1488
1489         -- Notice that rebuild gets the in-scope set from env, not alt_env
1490         -- The case binder *not* scope over the whole returned case-expression
1491         ; rebuild env' case_expr nodup_cont } }
1492 \end{code}
1493
1494 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1495 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1496 way, there's a chance that v will now only be used once, and hence
1497 inlined.
1498
1499 Historical note: we use to do the "case binder swap" in the Simplifier
1500 so there were additional complications if the scrutinee was a variable.
1501 Now the binder-swap stuff is done in the occurrence analyer; see
1502 OccurAnal Note [Binder swap].
1503
1504 Note [zapOccInfo]
1505 ~~~~~~~~~~~~~~~~~
1506 If the case binder is not dead, then neither are the pattern bound
1507 variables:  
1508         case <any> of x { (a,b) ->
1509         case x of { (p,q) -> p } }
1510 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1511 The point is that we bring into the envt a binding
1512         let x = (a,b)
1513 after the outer case, and that makes (a,b) alive.  At least we do unless
1514 the case binder is guaranteed dead.
1515
1516 In practice, the scrutinee is almost always a variable, so we pretty
1517 much always zap the OccInfo of the binders.  It doesn't matter much though.
1518
1519
1520 Note [Case of cast]
1521 ~~~~~~~~~~~~~~~~~~~
1522 Consider        case (v `cast` co) of x { I# y ->
1523                 ... (case (v `cast` co) of {...}) ...
1524 We'd like to eliminate the inner case.  We can get this neatly by
1525 arranging that inside the outer case we add the unfolding
1526         v |-> x `cast` (sym co)
1527 to v.  Then we should inline v at the inner case, cancel the casts, and away we go
1528
1529 Note [Improving seq]
1530 ~~~~~~~~~~~~~~~~~~~
1531 Consider
1532         type family F :: * -> *
1533         type instance F Int = Int
1534
1535         ... case e of x { DEFAULT -> rhs } ...
1536
1537 where x::F Int.  Then we'd like to rewrite (F Int) to Int, getting
1538
1539         case e `cast` co of x'::Int
1540            I# x# -> let x = x' `cast` sym co
1541                     in rhs
1542
1543 so that 'rhs' can take advantage of the form of x'.  
1544
1545 Notice that Note [Case of cast] may then apply to the result. 
1546
1547 Nota Bene: We only do the [Improving seq] transformation if the 
1548 case binder 'x' is actually used in the rhs; that is, if the case 
1549 is *not* a *pure* seq.  
1550   a) There is no point in adding the cast to a pure seq.
1551   b) There is a good reason not to: doing so would interfere 
1552      with seq rules (Note [Built-in RULES for seq] in MkId).
1553      In particular, this [Improving seq] thing *adds* a cast
1554      while [Built-in RULES for seq] *removes* one, so they
1555      just flip-flop.
1556
1557 You might worry about 
1558    case v of x { __DEFAULT ->
1559       ... case (v `cast` co) of y { I# -> ... }}
1560 This is a pure seq (since x is unused), so [Improving seq] won't happen.
1561 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
1562    case v of x { __DEFAULT ->
1563       ... case (x `cast` co) of y { I# -> ... }}
1564 Now the outer case is not a pure seq, so [Improving seq] will happen,
1565 and then the inner case will disappear.
1566
1567 The need for [Improving seq] showed up in Roman's experiments.  Example:
1568   foo :: F Int -> Int -> Int
1569   foo t n = t `seq` bar n
1570      where
1571        bar 0 = 0
1572        bar n = bar (n - case t of TI i -> i)
1573 Here we'd like to avoid repeated evaluating t inside the loop, by
1574 taking advantage of the `seq`.
1575
1576 At one point I did transformation in LiberateCase, but it's more
1577 robust here.  (Otherwise, there's a danger that we'll simply drop the
1578 'seq' altogether, before LiberateCase gets to see it.)
1579
1580
1581 \begin{code}
1582 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1583            -> OutExpr -> InId -> OutId -> [InAlt]
1584            -> SimplM (SimplEnv, OutExpr, OutId)
1585 -- Note [Improving seq]
1586 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1587   | not (isDeadBinder case_bndr)        -- Not a pure seq!  See the Note!
1588   , Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1589   = do { case_bndr2 <- newId (fsLit "nt") ty2
1590         ; let rhs  = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1591               env2 = extendIdSubst env case_bndr rhs
1592         ; return (env2, scrut `Cast` co, case_bndr2) }
1593
1594 improveSeq _ env scrut _ case_bndr1 _
1595   = return (env, scrut, case_bndr1)
1596
1597 {-
1598     improve_case_bndr env scrut case_bndr
1599         -- See Note [no-case-of-case]
1600         --  | switchIsOn (getSwitchChecker env) NoCaseOfCase
1601         --  = (env, case_bndr)
1602
1603         | otherwise     -- Failed try; see Note [Suppressing the case binder-swap]
1604                         --     not (isEvaldUnfolding (idUnfolding v))
1605         = case scrut of
1606             Var v -> (modifyInScope env1 v case_bndr', case_bndr')
1607                 -- Note about using modifyInScope for v here
1608                 -- We could extend the substitution instead, but it would be
1609                 -- a hack because then the substitution wouldn't be idempotent
1610                 -- any more (v is an OutId).  And this does just as well.
1611
1612             Cast (Var v) co -> (addBinderUnfolding env1 v rhs, case_bndr')
1613                             where
1614                                 rhs = Cast (Var case_bndr') (mkSymCoercion co)
1615
1616             _ -> (env, case_bndr)
1617         where
1618           case_bndr' = zapIdOccInfo case_bndr
1619           env1       = modifyInScope env case_bndr case_bndr'
1620 -}
1621 \end{code}
1622
1623
1624 simplAlts does two things:
1625
1626 1.  Eliminate alternatives that cannot match, including the
1627     DEFAULT alternative.
1628
1629 2.  If the DEFAULT alternative can match only one possible constructor,
1630     then make that constructor explicit.
1631     e.g.
1632         case e of x { DEFAULT -> rhs }
1633      ===>
1634         case e of x { (a,b) -> rhs }
1635     where the type is a single constructor type.  This gives better code
1636     when rhs also scrutinises x or e.
1637
1638 Here "cannot match" includes knowledge from GADTs
1639
1640 It's a good idea do do this stuff before simplifying the alternatives, to
1641 avoid simplifying alternatives we know can't happen, and to come up with
1642 the list of constructors that are handled, to put into the IdInfo of the
1643 case binder, for use when simplifying the alternatives.
1644
1645 Eliminating the default alternative in (1) isn't so obvious, but it can
1646 happen:
1647
1648 data Colour = Red | Green | Blue
1649
1650 f x = case x of
1651         Red -> ..
1652         Green -> ..
1653         DEFAULT -> h x
1654
1655 h y = case y of
1656         Blue -> ..
1657         DEFAULT -> [ case y of ... ]
1658
1659 If we inline h into f, the default case of the inlined h can't happen.
1660 If we don't notice this, we may end up filtering out *all* the cases
1661 of the inner case y, which give us nowhere to go!
1662
1663
1664 \begin{code}
1665 simplAlts :: SimplEnv
1666           -> OutExpr
1667           -> InId                       -- Case binder
1668           -> [InAlt]                    -- Non-empty
1669           -> SimplCont
1670           -> SimplM (OutExpr, OutId, [OutAlt])  -- Includes the continuation
1671 -- Like simplExpr, this just returns the simplified alternatives;
1672 -- it not return an environment
1673
1674 simplAlts env scrut case_bndr alts cont'
1675   = -- pprTrace "simplAlts" (ppr alts $$ ppr (seIdSubst env)) $
1676     do  { let env0 = zapFloats env
1677
1678         ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1679
1680         ; fam_envs <- getFamEnvs
1681         ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut 
1682                                                        case_bndr case_bndr1 alts
1683
1684         ; (imposs_deflt_cons, in_alts) <- prepareAlts alt_env' scrut' case_bndr' alts
1685
1686         ; alts' <- mapM (simplAlt alt_env' imposs_deflt_cons case_bndr' cont') in_alts
1687         ; return (scrut', case_bndr', alts') }
1688
1689 ------------------------------------
1690 simplAlt :: SimplEnv
1691          -> [AltCon]    -- These constructors can't be present when
1692                         -- matching the DEFAULT alternative
1693          -> OutId       -- The case binder
1694          -> SimplCont
1695          -> InAlt
1696          -> SimplM OutAlt
1697
1698 simplAlt env imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1699   = ASSERT( null bndrs )
1700     do  { let env' = addBinderOtherCon env case_bndr' imposs_deflt_cons
1701                 -- Record the constructors that the case-binder *can't* be.
1702         ; rhs' <- simplExprC env' rhs cont'
1703         ; return (DEFAULT, [], rhs') }
1704
1705 simplAlt env _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1706   = ASSERT( null bndrs )
1707     do  { let env' = addBinderUnfolding env case_bndr' (Lit lit)
1708         ; rhs' <- simplExprC env' rhs cont'
1709         ; return (LitAlt lit, [], rhs') }
1710
1711 simplAlt env _ case_bndr' cont' (DataAlt con, vs, rhs)
1712   = do  {       -- Deal with the pattern-bound variables
1713                 -- Mark the ones that are in ! positions in the
1714                 -- data constructor as certainly-evaluated.
1715                 -- NB: simplLamBinders preserves this eval info
1716           let vs_with_evals = add_evals (dataConRepStrictness con)
1717         ; (env', vs') <- simplLamBndrs env vs_with_evals
1718
1719                 -- Bind the case-binder to (con args)
1720         ; let inst_tys' = tyConAppArgs (idType case_bndr')
1721               con_args  = map Type inst_tys' ++ varsToCoreExprs vs'
1722               env''     = addBinderUnfolding env' case_bndr'
1723                                              (mkConApp con con_args)
1724
1725         ; rhs' <- simplExprC env'' rhs cont'
1726         ; return (DataAlt con, vs', rhs') }
1727   where
1728         -- add_evals records the evaluated-ness of the bound variables of
1729         -- a case pattern.  This is *important*.  Consider
1730         --      data T = T !Int !Int
1731         --
1732         --      case x of { T a b -> T (a+1) b }
1733         --
1734         -- We really must record that b is already evaluated so that we don't
1735         -- go and re-evaluate it when constructing the result.
1736         -- See Note [Data-con worker strictness] in MkId.lhs
1737     add_evals the_strs
1738         = go vs the_strs
1739         where
1740           go [] [] = []
1741           go (v:vs') strs | isTyVar v = v : go vs' strs
1742           go (v:vs') (str:strs)
1743             | isMarkedStrict str = evald_v  : go vs' strs
1744             | otherwise          = zapped_v : go vs' strs
1745             where
1746               zapped_v = zap_occ_info v
1747               evald_v  = zapped_v `setIdUnfolding` evaldUnfolding
1748           go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1749
1750         -- See Note [zapOccInfo]
1751         -- zap_occ_info: if the case binder is alive, then we add the unfolding
1752         --      case_bndr = C vs
1753         -- to the envt; so vs are now very much alive
1754         -- Note [Aug06] I can't see why this actually matters, but it's neater
1755         --        case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1756         --   ==>  case e of t { (a,b) -> ...(a)... }
1757         -- Look, Ma, a is alive now.
1758     zap_occ_info = zapCasePatIdOcc case_bndr'
1759
1760 addBinderUnfolding :: SimplEnv -> Id -> CoreExpr -> SimplEnv
1761 addBinderUnfolding env bndr rhs
1762   = modifyInScope env (bndr `setIdUnfolding` mkUnfolding False rhs)
1763
1764 addBinderOtherCon :: SimplEnv -> Id -> [AltCon] -> SimplEnv
1765 addBinderOtherCon env bndr cons
1766   = modifyInScope env (bndr `setIdUnfolding` mkOtherCon cons)
1767
1768 zapCasePatIdOcc :: Id -> Id -> Id
1769 -- Consider  case e of b { (a,b) -> ... }
1770 -- Then if we bind b to (a,b) in "...", and b is not dead,
1771 -- then we must zap the deadness info on a,b
1772 zapCasePatIdOcc case_bndr
1773   | isDeadBinder case_bndr = \ pat_id -> pat_id
1774   | otherwise              = \ pat_id -> zapIdOccInfo pat_id
1775 \end{code}
1776
1777
1778 %************************************************************************
1779 %*                                                                      *
1780 \subsection{Known constructor}
1781 %*                                                                      *
1782 %************************************************************************
1783
1784 We are a bit careful with occurrence info.  Here's an example
1785
1786         (\x* -> case x of (a*, b) -> f a) (h v, e)
1787
1788 where the * means "occurs once".  This effectively becomes
1789         case (h v, e) of (a*, b) -> f a)
1790 and then
1791         let a* = h v; b = e in f a
1792 and then
1793         f (h v)
1794
1795 All this should happen in one sweep.
1796
1797 \begin{code}
1798 knownCon :: SimplEnv            
1799          -> OutExpr                             -- The scrutinee
1800          -> DataCon -> [OutType] -> [OutExpr]   -- The scrutinee (in pieces)
1801          -> InId -> [InBndr] -> InExpr          -- The alternative
1802          -> SimplCont
1803          -> SimplM (SimplEnv, OutExpr)
1804
1805 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
1806   = do  { env' <- bind_args env bs dc_args
1807         ; let
1808                 -- It's useful to bind bndr to scrut, rather than to a fresh
1809                 -- binding      x = Con arg1 .. argn
1810                 -- because very often the scrut is a variable, so we avoid
1811                 -- creating, and then subsequently eliminating, a let-binding
1812                 -- BUT, if scrut is a not a variable, we must be careful
1813                 -- about duplicating the arg redexes; in that case, make
1814                 -- a new con-app from the args
1815                 bndr_rhs | exprIsTrivial scrut = scrut
1816                          | otherwise           = con_app
1817                 con_app = Var (dataConWorkId dc) 
1818                           `mkTyApps` dc_ty_args
1819                           `mkApps`   [substExpr env' (varToCoreExpr b) | b <- bs]
1820                          -- dc_ty_args are aready OutTypes, but bs are InBndrs
1821
1822         ; env'' <- simplNonRecX env' bndr bndr_rhs
1823         ; simplExprF env'' rhs cont }
1824   where
1825     zap_occ = zapCasePatIdOcc bndr    -- bndr is an InId
1826
1827                   -- Ugh!
1828     bind_args env' [] _  = return env'
1829
1830     bind_args env' (b:bs') (Type ty : args)
1831       = ASSERT( isTyVar b )
1832         bind_args (extendTvSubst env' b ty) bs' args
1833
1834     bind_args env' (b:bs') (arg : args)
1835       = ASSERT( isId b )
1836         do { let b' = zap_occ b
1837              -- Note that the binder might be "dead", because it doesn't
1838              -- occur in the RHS; and simplNonRecX may therefore discard
1839              -- it via postInlineUnconditionally.
1840              -- Nevertheless we must keep it if the case-binder is alive,
1841              -- because it may be used in the con_app.  See Note [zapOccInfo]
1842            ; env'' <- simplNonRecX env' b' arg
1843            ; bind_args env'' bs' args }
1844
1845     bind_args _ _ _ =
1846       pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
1847                              text "scrut:" <+> ppr scrut
1848
1849 -------------------
1850 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
1851                 -- This isn't strictly an error, although it is unusual. 
1852                 -- It's possible that the simplifer might "see" that 
1853                 -- an inner case has no accessible alternatives before 
1854                 -- it "sees" that the entire branch of an outer case is 
1855                 -- inaccessible.  So we simply put an error case here instead.
1856 missingAlt env case_bndr alts cont
1857   = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
1858     return (env, mkImpossibleExpr res_ty)
1859   where
1860     res_ty = contResultType env (substTy env (coreAltsType alts)) cont
1861 \end{code}
1862
1863
1864 %************************************************************************
1865 %*                                                                      *
1866 \subsection{Duplicating continuations}
1867 %*                                                                      *
1868 %************************************************************************
1869
1870 \begin{code}
1871 prepareCaseCont :: SimplEnv
1872                 -> [InAlt] -> SimplCont
1873                 -> SimplM (SimplEnv, SimplCont,SimplCont)
1874                         -- Return a duplicatable continuation, a non-duplicable part
1875                         -- plus some extra bindings (that scope over the entire
1876                         -- continunation)
1877
1878         -- No need to make it duplicatable if there's only one alternative
1879 prepareCaseCont env [_] cont = return (env, cont, mkBoringStop)
1880 prepareCaseCont env _   cont = mkDupableCont env cont
1881 \end{code}
1882
1883 \begin{code}
1884 mkDupableCont :: SimplEnv -> SimplCont
1885               -> SimplM (SimplEnv, SimplCont, SimplCont)
1886
1887 mkDupableCont env cont
1888   | contIsDupable cont
1889   = return (env, cont, mkBoringStop)
1890
1891 mkDupableCont _   (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn
1892
1893 mkDupableCont env (CoerceIt ty cont)
1894   = do  { (env', dup, nodup) <- mkDupableCont env cont
1895         ; return (env', CoerceIt ty dup, nodup) }
1896
1897 mkDupableCont env cont@(StrictBind {})
1898   =  return (env, mkBoringStop, cont)
1899         -- See Note [Duplicating StrictBind]
1900
1901 mkDupableCont env (StrictArg fun cci ai cont)
1902         -- See Note [Duplicating StrictArg]
1903   = do { (env', dup, nodup) <- mkDupableCont env cont
1904        ; (env'', fun') <- mk_dupable_call env' fun
1905        ; return (env'', StrictArg fun' cci ai dup, nodup) }
1906   where
1907     mk_dupable_call env (Var v)       = return (env, Var v)
1908     mk_dupable_call env (App fun arg) = do { (env', fun') <- mk_dupable_call env fun
1909                                            ; (env'', arg') <- makeTrivial env' arg
1910                                            ; return (env'', fun' `App` arg') }
1911     mk_dupable_call _ other = pprPanic "mk_dupable_call" (ppr other)
1912         -- The invariant of StrictArg is that the first arg is always an App chain
1913
1914 mkDupableCont env (ApplyTo _ arg se cont)
1915   =     -- e.g.         [...hole...] (...arg...)
1916         --      ==>
1917         --              let a = ...arg...
1918         --              in [...hole...] a
1919     do  { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1920         ; arg' <- simplExpr (se `setInScope` env') arg
1921         ; (env'', arg'') <- makeTrivial env' arg'
1922         ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
1923         ; return (env'', app_cont, nodup_cont) }
1924
1925 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
1926 --  See Note [Single-alternative case]
1927 --  | not (exprIsDupable rhs && contIsDupable case_cont)
1928 --  | not (isDeadBinder case_bndr)
1929   | all isDeadBinder bs  -- InIds
1930     && not (isUnLiftedType (idType case_bndr))
1931     -- Note [Single-alternative-unlifted]
1932   = return (env, mkBoringStop, cont)
1933
1934 mkDupableCont env (Select _ case_bndr alts se cont)
1935   =     -- e.g.         (case [...hole...] of { pi -> ei })
1936         --      ===>
1937         --              let ji = \xij -> ei
1938         --              in case [...hole...] of { pi -> ji xij }
1939     do  { tick (CaseOfCase case_bndr)
1940         ; (env', dup_cont, nodup_cont) <- mkDupableCont env cont
1941                 -- NB: call mkDupableCont here, *not* prepareCaseCont
1942                 -- We must make a duplicable continuation, whereas prepareCaseCont
1943                 -- doesn't when there is a single case branch
1944
1945         ; let alt_env = se `setInScope` env'
1946         ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
1947         ; alts' <- mapM (simplAlt alt_env' [] case_bndr' dup_cont) alts
1948         -- Safe to say that there are no handled-cons for the DEFAULT case
1949                 -- NB: simplBinder does not zap deadness occ-info, so
1950                 -- a dead case_bndr' will still advertise its deadness
1951                 -- This is really important because in
1952                 --      case e of b { (# p,q #) -> ... }
1953                 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
1954                 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1955                 -- In the new alts we build, we have the new case binder, so it must retain
1956                 -- its deadness.
1957         -- NB: we don't use alt_env further; it has the substEnv for
1958         --     the alternatives, and we don't want that
1959
1960         ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
1961         ; return (env'',  -- Note [Duplicated env]
1962                   Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
1963                   nodup_cont) }
1964
1965
1966 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
1967               -> SimplM (SimplEnv, [InAlt])
1968 -- Absorbs the continuation into the new alternatives
1969
1970 mkDupableAlts env case_bndr' the_alts
1971   = go env the_alts
1972   where
1973     go env0 [] = return (env0, [])
1974     go env0 (alt:alts)
1975         = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
1976              ; (env2, alts') <- go env1 alts
1977              ; return (env2, alt' : alts' ) }
1978
1979 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
1980               -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
1981 mkDupableAlt env case_bndr (con, bndrs', rhs')
1982   | exprIsDupable rhs'  -- Note [Small alternative rhs]
1983   = return (env, (con, bndrs', rhs'))
1984   | otherwise
1985   = do  { let rhs_ty'  = exprType rhs'
1986               scrut_ty = idType case_bndr
1987               case_bndr_w_unf   
1988                 = case con of 
1989                       DEFAULT    -> case_bndr                                   
1990                       DataAlt dc -> setIdUnfolding case_bndr unf
1991                           where
1992                                  -- See Note [Case binders and join points]
1993                              unf = mkInlineRule InlSat rhs 0
1994                              rhs = mkConApp dc (map Type (tyConAppArgs scrut_ty)
1995                                                 ++ varsToCoreExprs bndrs')
1996
1997                       LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
1998                                                 <+> ppr case_bndr <+> ppr con )
1999                                    case_bndr
2000                            -- The case binder is alive but trivial, so why has 
2001                            -- it not been substituted away?
2002
2003               used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
2004                           | otherwise              = bndrs' ++ [case_bndr_w_unf]
2005               
2006               abstract_over bndr
2007                   | isTyVar bndr = True -- Abstract over all type variables just in case
2008                   | otherwise    = not (isDeadBinder bndr)
2009                         -- The deadness info on the new Ids is preserved by simplBinders
2010
2011         ; (final_bndrs', final_args)    -- Note [Join point abstraction]
2012                 <- if (any isId used_bndrs')
2013                    then return (used_bndrs', varsToCoreExprs used_bndrs')
2014                     else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
2015                             ; return ([rw_id], [Var realWorldPrimId]) }
2016
2017         ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
2018                 -- Note [Funky mkPiTypes]
2019
2020         ; let   -- We make the lambdas into one-shot-lambdas.  The
2021                 -- join point is sure to be applied at most once, and doing so
2022                 -- prevents the body of the join point being floated out by
2023                 -- the full laziness pass
2024                 really_final_bndrs     = map one_shot final_bndrs'
2025                 one_shot v | isId v    = setOneShotLambda v
2026                            | otherwise = v
2027                 join_rhs  = mkLams really_final_bndrs rhs'
2028                 join_call = mkApps (Var join_bndr) final_args
2029
2030         ; env' <- addPolyBind NotTopLevel env (NonRec join_bndr join_rhs)
2031         ; return (env', (con, bndrs', join_call)) }
2032                 -- See Note [Duplicated env]
2033 \end{code}
2034
2035 Note [Case binders and join points]
2036 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2037 Consider this 
2038    case (case .. ) of c {
2039      I# c# -> ....c....
2040
2041 If we make a join point with c but not c# we get
2042   $j = \c -> ....c....
2043
2044 But if later inlining scrutines the c, thus
2045
2046   $j = \c -> ... case c of { I# y -> ... } ...
2047
2048 we won't see that 'c' has already been scrutinised.  This actually
2049 happens in the 'tabulate' function in wave4main, and makes a significant
2050 difference to allocation.
2051
2052 An alternative plan is this:
2053
2054    $j = \c# -> let c = I# c# in ...c....
2055
2056 but that is bad if 'c' is *not* later scrutinised.  
2057
2058 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2059 that it's really I# c#, thus
2060    
2061    $j = \c# -> \c[=I# c#] -> ...c....
2062
2063 Absence analysis may later discard 'c'.
2064
2065    
2066 Note [Duplicated env]
2067 ~~~~~~~~~~~~~~~~~~~~~
2068 Some of the alternatives are simplified, but have not been turned into a join point
2069 So they *must* have an zapped subst-env.  So we can't use completeNonRecX to
2070 bind the join point, because it might to do PostInlineUnconditionally, and
2071 we'd lose that when zapping the subst-env.  We could have a per-alt subst-env,
2072 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2073 at worst delays the join-point inlining.
2074
2075 Note [Small alternative rhs]
2076 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2077 It is worth checking for a small RHS because otherwise we
2078 get extra let bindings that may cause an extra iteration of the simplifier to
2079 inline back in place.  Quite often the rhs is just a variable or constructor.
2080 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
2081 iterations because the version with the let bindings looked big, and so wasn't
2082 inlined, but after the join points had been inlined it looked smaller, and so
2083 was inlined.
2084
2085 NB: we have to check the size of rhs', not rhs.
2086 Duplicating a small InAlt might invalidate occurrence information
2087 However, if it *is* dupable, we return the *un* simplified alternative,
2088 because otherwise we'd need to pair it up with an empty subst-env....
2089 but we only have one env shared between all the alts.
2090 (Remember we must zap the subst-env before re-simplifying something).
2091 Rather than do this we simply agree to re-simplify the original (small) thing later.
2092
2093 Note [Funky mkPiTypes]
2094 ~~~~~~~~~~~~~~~~~~~~~~
2095 Notice the funky mkPiTypes.  If the contructor has existentials
2096 it's possible that the join point will be abstracted over
2097 type varaibles as well as term variables.
2098  Example:  Suppose we have
2099         data T = forall t.  C [t]
2100  Then faced with
2101         case (case e of ...) of
2102             C t xs::[t] -> rhs
2103  We get the join point
2104         let j :: forall t. [t] -> ...
2105             j = /\t \xs::[t] -> rhs
2106         in
2107         case (case e of ...) of
2108             C t xs::[t] -> j t xs
2109
2110 Note [Join point abstaction]
2111 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2112 If we try to lift a primitive-typed something out
2113 for let-binding-purposes, we will *caseify* it (!),
2114 with potentially-disastrous strictness results.  So
2115 instead we turn it into a function: \v -> e
2116 where v::State# RealWorld#.  The value passed to this function
2117 is realworld#, which generates (almost) no code.
2118
2119 There's a slight infelicity here: we pass the overall
2120 case_bndr to all the join points if it's used in *any* RHS,
2121 because we don't know its usage in each RHS separately
2122
2123 We used to say "&& isUnLiftedType rhs_ty'" here, but now
2124 we make the join point into a function whenever used_bndrs'
2125 is empty.  This makes the join-point more CPR friendly.
2126 Consider:       let j = if .. then I# 3 else I# 4
2127                 in case .. of { A -> j; B -> j; C -> ... }
2128
2129 Now CPR doesn't w/w j because it's a thunk, so
2130 that means that the enclosing function can't w/w either,
2131 which is a lose.  Here's the example that happened in practice:
2132         kgmod :: Int -> Int -> Int
2133         kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2134                     then 78
2135                     else 5
2136
2137 I have seen a case alternative like this:
2138         True -> \v -> ...
2139 It's a bit silly to add the realWorld dummy arg in this case, making
2140         $j = \s v -> ...
2141            True -> $j s
2142 (the \v alone is enough to make CPR happy) but I think it's rare
2143
2144 Note [Duplicating StrictArg]
2145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2146 The original plan had (where E is a big argument)
2147 e.g.    f E [..hole..]
2148         ==>     let $j = \a -> f E a
2149                 in $j [..hole..]
2150
2151 But this is terrible! Here's an example:
2152         && E (case x of { T -> F; F -> T })
2153 Now, && is strict so we end up simplifying the case with
2154 an ArgOf continuation.  If we let-bind it, we get
2155         let $j = \v -> && E v
2156         in simplExpr (case x of { T -> F; F -> T })
2157                      (ArgOf (\r -> $j r)
2158 And after simplifying more we get
2159         let $j = \v -> && E v
2160         in case x of { T -> $j F; F -> $j T }
2161 Which is a Very Bad Thing
2162
2163 What we do now is this
2164         f E [..hole..]
2165         ==>     let a = E
2166                 in f a [..hole..]
2167 Now if the thing in the hole is a case expression (which is when
2168 we'll call mkDupableCont), we'll push the function call into the
2169 branches, which is what we want.  Now RULES for f may fire, and
2170 call-pattern specialisation.  Here's an example from Trac #3116
2171      go (n+1) (case l of
2172                  1  -> bs'
2173                  _  -> Chunk p fpc (o+1) (l-1) bs')
2174 If we can push the call for 'go' inside the case, we get
2175 call-pattern specialisation for 'go', which is *crucial* for 
2176 this program.
2177
2178 Here is the (&&) example: 
2179         && E (case x of { T -> F; F -> T })
2180   ==>   let a = E in 
2181         case x of { T -> && a F; F -> && a T }
2182 Much better!
2183
2184 Notice that 
2185   * Arguments to f *after* the strict one are handled by 
2186     the ApplyTo case of mkDupableCont.  Eg
2187         f [..hole..] E
2188
2189   * We can only do the let-binding of E because the function
2190     part of a StrictArg continuation is an explicit syntax
2191     tree.  In earlier versions we represented it as a function
2192     (CoreExpr -> CoreEpxr) which we couldn't take apart.
2193
2194 Do *not* duplicate StrictBind and StritArg continuations.  We gain
2195 nothing by propagating them into the expressions, and we do lose a
2196 lot.  
2197
2198 The desire not to duplicate is the entire reason that
2199 mkDupableCont returns a pair of continuations.
2200
2201 Note [Duplicating StrictBind]
2202 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2203 Unlike StrictArg, there doesn't seem anything to gain from
2204 duplicating a StrictBind continuation, so we don't.
2205
2206 The desire not to duplicate is the entire reason that
2207 mkDupableCont returns a pair of continuations.
2208
2209
2210 Note [Single-alternative cases]
2211 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2212 This case is just like the ArgOf case.  Here's an example:
2213         data T a = MkT !a
2214         ...(MkT (abs x))...
2215 Then we get
2216         case (case x of I# x' ->
2217               case x' <# 0# of
2218                 True  -> I# (negate# x')
2219                 False -> I# x') of y {
2220           DEFAULT -> MkT y
2221 Because the (case x) has only one alternative, we'll transform to
2222         case x of I# x' ->
2223         case (case x' <# 0# of
2224                 True  -> I# (negate# x')
2225                 False -> I# x') of y {
2226           DEFAULT -> MkT y
2227 But now we do *NOT* want to make a join point etc, giving
2228         case x of I# x' ->
2229         let $j = \y -> MkT y
2230         in case x' <# 0# of
2231                 True  -> $j (I# (negate# x'))
2232                 False -> $j (I# x')
2233 In this case the $j will inline again, but suppose there was a big
2234 strict computation enclosing the orginal call to MkT.  Then, it won't
2235 "see" the MkT any more, because it's big and won't get duplicated.
2236 And, what is worse, nothing was gained by the case-of-case transform.
2237
2238 When should use this case of mkDupableCont?
2239 However, matching on *any* single-alternative case is a *disaster*;
2240   e.g.  case (case ....) of (a,b) -> (# a,b #)
2241   We must push the outer case into the inner one!
2242 Other choices:
2243
2244    * Match [(DEFAULT,_,_)], but in the common case of Int,
2245      the alternative-filling-in code turned the outer case into
2246                 case (...) of y { I# _ -> MkT y }
2247
2248    * Match on single alternative plus (not (isDeadBinder case_bndr))
2249      Rationale: pushing the case inwards won't eliminate the construction.
2250      But there's a risk of
2251                 case (...) of y { (a,b) -> let z=(a,b) in ... }
2252      Now y looks dead, but it'll come alive again.  Still, this
2253      seems like the best option at the moment.
2254
2255    * Match on single alternative plus (all (isDeadBinder bndrs))
2256      Rationale: this is essentially  seq.
2257
2258    * Match when the rhs is *not* duplicable, and hence would lead to a
2259      join point.  This catches the disaster-case above.  We can test
2260      the *un-simplified* rhs, which is fine.  It might get bigger or
2261      smaller after simplification; if it gets smaller, this case might
2262      fire next time round.  NB also that we must test contIsDupable
2263      case_cont *btoo, because case_cont might be big!
2264
2265      HOWEVER: I found that this version doesn't work well, because
2266      we can get         let x = case (...) of { small } in ...case x...
2267      When x is inlined into its full context, we find that it was a bad
2268      idea to have pushed the outer case inside the (...) case.
2269
2270 Note [Single-alternative-unlifted]
2271 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2272 Here's another single-alternative where we really want to do case-of-case:
2273
2274 data Mk1 = Mk1 Int#
2275 data Mk1 = Mk2 Int#
2276
2277 M1.f =
2278     \r [x_s74 y_s6X]
2279         case
2280             case y_s6X of tpl_s7m {
2281               M1.Mk1 ipv_s70 -> ipv_s70;
2282               M1.Mk2 ipv_s72 -> ipv_s72;
2283             }
2284         of
2285         wild_s7c
2286         { __DEFAULT ->
2287               case
2288                   case x_s74 of tpl_s7n {
2289                     M1.Mk1 ipv_s77 -> ipv_s77;
2290                     M1.Mk2 ipv_s79 -> ipv_s79;
2291                   }
2292               of
2293               wild1_s7b
2294               { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2295               };
2296         };
2297
2298 So the outer case is doing *nothing at all*, other than serving as a
2299 join-point.  In this case we really want to do case-of-case and decide
2300 whether to use a real join point or just duplicate the continuation.
2301
2302 Hence: check whether the case binder's type is unlifted, because then
2303 the outer case is *not* a seq.