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