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