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