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