Add pprDefiniteTrace and use it
[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, isNothing )
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           pprDefiniteTrace "Inlining done:" (ppr var) stuff
1241         else stuff
1242       | otherwise
1243       = pprDefiniteTrace ("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
1395       | not (dopt Opt_D_dump_rule_rewrites dflags)
1396       = pprDefiniteTrace "Rule fired:" (ftext (ru_name rule)) stuff
1397
1398       | otherwise
1399       = pprDefiniteTrace "Rule fired"
1400            (vcat [text "Rule:" <+> ftext (ru_name rule),
1401                   text "Before:" <+> hang (ppr fn) 2 (sep (map pprParendExpr args)),
1402                   text "After: " <+> pprCoreExpr rule_rhs,
1403                   text "Cont:  " <+> ppr call_cont])
1404            stuff
1405 \end{code}
1406
1407 Note [Rules for recursive functions]
1408 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1409 You might think that we shouldn't apply rules for a loop breaker:
1410 doing so might give rise to an infinite loop, because a RULE is
1411 rather like an extra equation for the function:
1412      RULE:           f (g x) y = x+y
1413      Eqn:            f a     y = a-y
1414
1415 But it's too drastic to disable rules for loop breakers.
1416 Even the foldr/build rule would be disabled, because foldr
1417 is recursive, and hence a loop breaker:
1418      foldr k z (build g) = g k z
1419 So it's up to the programmer: rules can cause divergence
1420
1421
1422 %************************************************************************
1423 %*                                                                      *
1424                 Rebuilding a case expression
1425 %*                                                                      *
1426 %************************************************************************
1427
1428 Note [Case elimination]
1429 ~~~~~~~~~~~~~~~~~~~~~~~
1430 The case-elimination transformation discards redundant case expressions.
1431 Start with a simple situation:
1432
1433         case x# of      ===>   let y# = x# in e
1434           y# -> e
1435
1436 (when x#, y# are of primitive type, of course).  We can't (in general)
1437 do this for algebraic cases, because we might turn bottom into
1438 non-bottom!
1439
1440 The code in SimplUtils.prepareAlts has the effect of generalise this
1441 idea to look for a case where we're scrutinising a variable, and we
1442 know that only the default case can match.  For example:
1443
1444         case x of
1445           0#      -> ...
1446           DEFAULT -> ...(case x of
1447                          0#      -> ...
1448                          DEFAULT -> ...) ...
1449
1450 Here the inner case is first trimmed to have only one alternative, the
1451 DEFAULT, after which it's an instance of the previous case.  This
1452 really only shows up in eliminating error-checking code.
1453
1454 Note that SimplUtils.mkCase combines identical RHSs.  So
1455
1456         case e of       ===> case e of DEFAULT -> r
1457            True  -> r
1458            False -> r
1459
1460 Now again the case may be elminated by the CaseElim transformation.
1461 This includes things like (==# a# b#)::Bool so that we simplify
1462       case ==# a# b# of { True -> x; False -> x }
1463 to just
1464       x
1465 This particular example shows up in default methods for
1466 comparision operations (e.g. in (>=) for Int.Int32)
1467
1468 Note [CaseElimination: lifted case]
1469 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1470 We also make sure that we deal with this very common case,
1471 where x has a lifted type:
1472
1473         case e of
1474           x -> ...x...
1475
1476 Here we are using the case as a strict let; if x is used only once
1477 then we want to inline it.  We have to be careful that this doesn't
1478 make the program terminate when it would have diverged before, so we
1479 check that
1480         (a) 'e' is already evaluated (it may so if e is a variable)
1481             Specifically we check (exprIsHNF e)
1482 or
1483         (b) the scrutinee is a variable and 'x' is used strictly
1484 or
1485         (c) 'x' is not used at all and e is ok-for-speculation
1486
1487 For the (c), consider
1488    case (case a ># b of { True -> (p,q); False -> (q,p) }) of
1489      r -> blah
1490 The scrutinee is ok-for-speculation (it looks inside cases), but we do
1491 not want to transform to
1492    let r = case a ># b of { True -> (p,q); False -> (q,p) }
1493    in blah
1494 because that builds an unnecessary thunk.
1495
1496
1497 Further notes about case elimination
1498 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1499 Consider:       test :: Integer -> IO ()
1500                 test = print
1501
1502 Turns out that this compiles to:
1503     Print.test
1504       = \ eta :: Integer
1505           eta1 :: State# RealWorld ->
1506           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1507           case hPutStr stdout
1508                  (PrelNum.jtos eta ($w[] @ Char))
1509                  eta1
1510           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1511
1512 Notice the strange '<' which has no effect at all. This is a funny one.
1513 It started like this:
1514
1515 f x y = if x < 0 then jtos x
1516           else if y==0 then "" else jtos x
1517
1518 At a particular call site we have (f v 1).  So we inline to get
1519
1520         if v < 0 then jtos x
1521         else if 1==0 then "" else jtos x
1522
1523 Now simplify the 1==0 conditional:
1524
1525         if v<0 then jtos v else jtos v
1526
1527 Now common-up the two branches of the case:
1528
1529         case (v<0) of DEFAULT -> jtos v
1530
1531 Why don't we drop the case?  Because it's strict in v.  It's technically
1532 wrong to drop even unnecessary evaluations, and in practice they
1533 may be a result of 'seq' so we *definitely* don't want to drop those.
1534 I don't really know how to improve this situation.
1535
1536 \begin{code}
1537 ---------------------------------------------------------
1538 --      Eliminate the case if possible
1539
1540 rebuildCase, reallyRebuildCase
1541    :: SimplEnv
1542    -> OutExpr          -- Scrutinee
1543    -> InId             -- Case binder
1544    -> [InAlt]          -- Alternatives (inceasing order)
1545    -> SimplCont
1546    -> SimplM (SimplEnv, OutExpr)
1547
1548 --------------------------------------------------
1549 --      1. Eliminate the case if there's a known constructor
1550 --------------------------------------------------
1551
1552 rebuildCase env scrut case_bndr alts cont
1553   | Lit lit <- scrut    -- No need for same treatment as constructors
1554                         -- because literals are inlined more vigorously
1555   = do  { tick (KnownBranch case_bndr)
1556         ; case findAlt (LitAlt lit) alts of
1557             Nothing           -> missingAlt env case_bndr alts cont
1558             Just (_, bs, rhs) -> simple_rhs bs rhs }
1559
1560   | Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
1561         -- Works when the scrutinee is a variable with a known unfolding
1562         -- as well as when it's an explicit constructor application
1563   = do  { tick (KnownBranch case_bndr)
1564         ; case findAlt (DataAlt con) alts of
1565             Nothing  -> missingAlt env case_bndr alts cont
1566             Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1567             Just (_, bs, rhs)       -> knownCon env scrut con ty_args other_args 
1568                                                 case_bndr bs rhs cont
1569         }
1570   where
1571     simple_rhs bs rhs = ASSERT( null bs ) 
1572                         do { env' <- simplNonRecX env case_bndr scrut
1573                            ; simplExprF env' rhs cont }
1574
1575
1576 --------------------------------------------------
1577 --      2. Eliminate the case if scrutinee is evaluated
1578 --------------------------------------------------
1579
1580 rebuildCase env scrut case_bndr [(_, bndrs, rhs)] cont
1581   -- See if we can get rid of the case altogether
1582   -- See Note [Case elimination] 
1583   -- mkCase made sure that if all the alternatives are equal,
1584   -- then there is now only one (DEFAULT) rhs
1585  | all isDeadBinder bndrs       -- bndrs are [InId]
1586
1587  , if isUnLiftedType (idType case_bndr)
1588    then ok_for_spec         -- Satisfy the let-binding invariant
1589    else elim_lifted
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     elim_lifted   -- See Note [Case elimination: lifted case]
1596       = exprIsHNF scrut
1597      || (strict_case_bndr && scrut_is_var scrut) 
1598               -- The case binder is going to be evaluated later,
1599               -- and the scrutinee is a simple variable
1600
1601      || (is_plain_seq && ok_for_spec)
1602               -- Note: not the same as exprIsHNF
1603
1604     ok_for_spec      = exprOkForSpeculation scrut
1605     is_plain_seq     = isDeadBinder case_bndr   -- Evaluation *only* for effect
1606     strict_case_bndr = isStrictDmd (idDemandInfo case_bndr)
1607
1608     scrut_is_var (Cast s _) = scrut_is_var s
1609     scrut_is_var (Var v)    = not (isTickBoxOp v)
1610                                     -- ugly hack; covering this case is what
1611                                     -- exprOkForSpeculation was intended for.
1612     scrut_is_var _          = False
1613
1614
1615 --------------------------------------------------
1616 --      3. Try seq rules; see Note [User-defined RULES for seq] in MkId
1617 --------------------------------------------------
1618
1619 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1620   | all isDeadBinder (case_bndr : bndrs)  -- So this is just 'seq'
1621   = do { let rhs' = substExpr (text "rebuild-case") env rhs
1622              out_args = [Type (substTy env (idType case_bndr)), 
1623                          Type (exprType rhs'), scrut, rhs']
1624                       -- Lazily evaluated, so we don't do most of this
1625
1626        ; rule_base <- getSimplRules
1627        ; mb_rule <- tryRules env (getRules rule_base seqId) seqId out_args cont
1628        ; case mb_rule of 
1629            Just (n_args, res) -> simplExprF (zapSubstEnv env) 
1630                                             (mkApps res (drop n_args out_args))
1631                                             cont
1632            Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1633
1634 rebuildCase env scrut case_bndr alts cont
1635   = reallyRebuildCase env scrut case_bndr alts cont
1636
1637 --------------------------------------------------
1638 --      3. Catch-all case
1639 --------------------------------------------------
1640
1641 reallyRebuildCase env scrut case_bndr alts cont
1642   = do  {       -- Prepare the continuation;
1643                 -- The new subst_env is in place
1644           (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1645
1646         -- Simplify the alternatives
1647         ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1648
1649         -- Check for empty alternatives
1650         ; if null alts' then missingAlt env case_bndr alts cont
1651           else do
1652         { dflags <- getDOptsSmpl
1653         ; case_expr <- mkCase dflags scrut' case_bndr' alts'
1654
1655         -- Notice that rebuild gets the in-scope set from env', not alt_env
1656         -- (which in any case is only build in simplAlts)
1657         -- The case binder *not* scope over the whole returned case-expression
1658         ; rebuild env' case_expr nodup_cont } }
1659 \end{code}
1660
1661 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1662 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1663 way, there's a chance that v will now only be used once, and hence
1664 inlined.
1665
1666 Historical note: we use to do the "case binder swap" in the Simplifier
1667 so there were additional complications if the scrutinee was a variable.
1668 Now the binder-swap stuff is done in the occurrence analyer; see
1669 OccurAnal Note [Binder swap].
1670
1671 Note [zapOccInfo]
1672 ~~~~~~~~~~~~~~~~~
1673 If the case binder is not dead, then neither are the pattern bound
1674 variables:  
1675         case <any> of x { (a,b) ->
1676         case x of { (p,q) -> p } }
1677 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1678 The point is that we bring into the envt a binding
1679         let x = (a,b)
1680 after the outer case, and that makes (a,b) alive.  At least we do unless
1681 the case binder is guaranteed dead.
1682
1683 In practice, the scrutinee is almost always a variable, so we pretty
1684 much always zap the OccInfo of the binders.  It doesn't matter much though.
1685
1686 Note [Improving seq]
1687 ~~~~~~~~~~~~~~~~~~~
1688 Consider
1689         type family F :: * -> *
1690         type instance F Int = Int
1691
1692         ... case e of x { DEFAULT -> rhs } ...
1693
1694 where x::F Int.  Then we'd like to rewrite (F Int) to Int, getting
1695
1696         case e `cast` co of x'::Int
1697            I# x# -> let x = x' `cast` sym co
1698                     in rhs
1699
1700 so that 'rhs' can take advantage of the form of x'.  
1701
1702 Notice that Note [Case of cast] (in OccurAnal) may then apply to the result. 
1703
1704 Nota Bene: We only do the [Improving seq] transformation if the 
1705 case binder 'x' is actually used in the rhs; that is, if the case 
1706 is *not* a *pure* seq.  
1707   a) There is no point in adding the cast to a pure seq.
1708   b) There is a good reason not to: doing so would interfere 
1709      with seq rules (Note [Built-in RULES for seq] in MkId).
1710      In particular, this [Improving seq] thing *adds* a cast
1711      while [Built-in RULES for seq] *removes* one, so they
1712      just flip-flop.
1713
1714 You might worry about 
1715    case v of x { __DEFAULT ->
1716       ... case (v `cast` co) of y { I# -> ... }}
1717 This is a pure seq (since x is unused), so [Improving seq] won't happen.
1718 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
1719    case v of x { __DEFAULT ->
1720       ... case (x `cast` co) of y { I# -> ... }}
1721 Now the outer case is not a pure seq, so [Improving seq] will happen,
1722 and then the inner case will disappear.
1723
1724 The need for [Improving seq] showed up in Roman's experiments.  Example:
1725   foo :: F Int -> Int -> Int
1726   foo t n = t `seq` bar n
1727      where
1728        bar 0 = 0
1729        bar n = bar (n - case t of TI i -> i)
1730 Here we'd like to avoid repeated evaluating t inside the loop, by
1731 taking advantage of the `seq`.
1732
1733 At one point I did transformation in LiberateCase, but it's more
1734 robust here.  (Otherwise, there's a danger that we'll simply drop the
1735 'seq' altogether, before LiberateCase gets to see it.)
1736
1737 \begin{code}
1738 simplAlts :: SimplEnv
1739           -> OutExpr
1740           -> InId                       -- Case binder
1741           -> [InAlt]                    -- Non-empty
1742           -> SimplCont
1743           -> SimplM (OutExpr, OutId, [OutAlt])  -- Includes the continuation
1744 -- Like simplExpr, this just returns the simplified alternatives;
1745 -- it does not return an environment
1746
1747 simplAlts env scrut case_bndr alts cont'
1748   = -- pprTrace "simplAlts" (ppr alts $$ ppr (seTvSubst env)) $
1749     do  { let env0 = zapFloats env
1750
1751         ; (env1, case_bndr1) <- simplBinder env0 case_bndr
1752
1753         ; fam_envs <- getFamEnvs
1754         ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut 
1755                                                        case_bndr case_bndr1 alts
1756
1757         ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
1758
1759         ; let mb_var_scrut = case scrut' of { Var v -> Just v; _ -> Nothing }
1760         ; alts' <- mapM (simplAlt alt_env' mb_var_scrut
1761                              imposs_deflt_cons case_bndr' cont') in_alts
1762         ; return (scrut', case_bndr', alts') }
1763
1764
1765 ------------------------------------
1766 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
1767            -> OutExpr -> InId -> OutId -> [InAlt]
1768            -> SimplM (SimplEnv, OutExpr, OutId)
1769 -- Note [Improving seq]
1770 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
1771   | not (isDeadBinder case_bndr)        -- Not a pure seq!  See Note [Improving seq]
1772   , Just (co, ty2) <- topNormaliseType fam_envs (idType case_bndr1)
1773   = do { case_bndr2 <- newId (fsLit "nt") ty2
1774         ; let rhs  = DoneEx (Var case_bndr2 `Cast` mkSymCoercion co)
1775               env2 = extendIdSubst env case_bndr rhs
1776         ; return (env2, scrut `Cast` co, case_bndr2) }
1777
1778 improveSeq _ env scrut _ case_bndr1 _
1779   = return (env, scrut, case_bndr1)
1780
1781
1782 ------------------------------------
1783 simplAlt :: SimplEnv
1784          -> Maybe OutId    -- Scrutinee
1785          -> [AltCon]       -- These constructors can't be present when
1786                            -- matching the DEFAULT alternative
1787          -> OutId          -- The case binder
1788          -> SimplCont
1789          -> InAlt
1790          -> SimplM OutAlt
1791
1792 simplAlt env scrut imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
1793   = ASSERT( null bndrs )
1794     do  { let env' = addBinderUnfolding env scrut case_bndr' 
1795                                         (mkOtherCon imposs_deflt_cons)
1796                 -- Record the constructors that the case-binder *can't* be.
1797         ; rhs' <- simplExprC env' rhs cont'
1798         ; return (DEFAULT, [], rhs') }
1799
1800 simplAlt env scrut _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
1801   = ASSERT( null bndrs )
1802     do  { let env' = addBinderUnfolding env scrut case_bndr' 
1803                                         (mkSimpleUnfolding (Lit lit))
1804         ; rhs' <- simplExprC env' rhs cont'
1805         ; return (LitAlt lit, [], rhs') }
1806
1807 simplAlt env scrut _ case_bndr' cont' (DataAlt con, vs, rhs)
1808   = do  {       -- Deal with the pattern-bound variables
1809                 -- Mark the ones that are in ! positions in the
1810                 -- data constructor as certainly-evaluated.
1811                 -- NB: simplLamBinders preserves this eval info
1812           let vs_with_evals = add_evals (dataConRepStrictness con)
1813         ; (env', vs') <- simplLamBndrs env vs_with_evals
1814
1815                 -- Bind the case-binder to (con args)
1816         ; let inst_tys' = tyConAppArgs (idType case_bndr')
1817               con_args  = map Type inst_tys' ++ varsToCoreExprs vs'
1818               unf       = mkSimpleUnfolding (mkConApp con con_args)
1819               env''     = addBinderUnfolding env' scrut case_bndr' unf
1820
1821         ; rhs' <- simplExprC env'' rhs cont'
1822         ; return (DataAlt con, vs', rhs') }
1823   where
1824         -- add_evals records the evaluated-ness of the bound variables of
1825         -- a case pattern.  This is *important*.  Consider
1826         --      data T = T !Int !Int
1827         --
1828         --      case x of { T a b -> T (a+1) b }
1829         --
1830         -- We really must record that b is already evaluated so that we don't
1831         -- go and re-evaluate it when constructing the result.
1832         -- See Note [Data-con worker strictness] in MkId.lhs
1833     add_evals the_strs
1834         = go vs the_strs
1835         where
1836           go [] [] = []
1837           go (v:vs') strs | isTyCoVar v = v : go vs' strs
1838           go (v:vs') (str:strs)
1839             | isMarkedStrict str = evald_v  : go vs' strs
1840             | otherwise          = zapped_v : go vs' strs
1841             where
1842               zapped_v = zapBndrOccInfo keep_occ_info v
1843               evald_v  = zapped_v `setIdUnfolding` evaldUnfolding
1844           go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
1845
1846         -- See Note [zapOccInfo]
1847         -- zap_occ_info: if the case binder is alive, then we add the unfolding
1848         --      case_bndr = C vs
1849         -- to the envt; so vs are now very much alive
1850         -- Note [Aug06] I can't see why this actually matters, but it's neater
1851         --        case e of t { (a,b) -> ...(case t of (p,q) -> p)... }
1852         --   ==>  case e of t { (a,b) -> ...(a)... }
1853         -- Look, Ma, a is alive now.
1854     keep_occ_info = isDeadBinder case_bndr' && isNothing scrut
1855
1856 addBinderUnfolding :: SimplEnv -> Maybe OutId -> Id -> Unfolding -> SimplEnv
1857 addBinderUnfolding env scrut bndr unf
1858   = case scrut of
1859        Just v -> modifyInScope env1 (v `setIdUnfolding` unf)
1860        _      -> env1
1861   where
1862     env1 = modifyInScope env bndr_w_unf
1863     bndr_w_unf = bndr `setIdUnfolding` unf
1864
1865 zapBndrOccInfo :: Bool -> Id -> Id
1866 -- Consider  case e of b { (a,b) -> ... }
1867 -- Then if we bind b to (a,b) in "...", and b is not dead,
1868 -- then we must zap the deadness info on a,b
1869 zapBndrOccInfo keep_occ_info pat_id
1870   | keep_occ_info = pat_id
1871   | otherwise     = zapIdOccInfo pat_id
1872 \end{code}
1873
1874 Note [Add unfolding for scrutinee]
1875 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1876 In general it's unlikely that a variable scrutinee will appear 
1877 in the case alternatives   case x of { ...x unlikely to appear... }
1878 because the binder-swap in OccAnal has got rid of all such occcurrences
1879 See Note [Binder swap] in OccAnal.
1880
1881 BUT it is still VERY IMPORTANT to add a suitable unfolding for a
1882 variable scrutinee, in simplAlt.  Here's why
1883    case x of y
1884      (a,b) -> case b of c
1885                 I# v -> ...(f y)...
1886 There is no occurrence of 'b' in the (...(f y)...).  But y gets
1887 the unfolding (a,b), and *that* mentions b.  If f has a RULE
1888     RULE f (p, I# q) = ...
1889 we want that rule to match, so we must extend the in-scope env with a
1890 suitable unfolding for 'y'.  It's *essential* for rule matching; but
1891 it's also good for case-elimintation -- suppose that 'f' was inlined
1892 and did multi-level case analysis, then we'd solve it in one
1893 simplifier sweep instead of two.
1894
1895 Exactly the same issue arises in SpecConstr; 
1896 see Note [Add scrutinee to ValueEnv too] in SpecConstr
1897
1898 %************************************************************************
1899 %*                                                                      *
1900 \subsection{Known constructor}
1901 %*                                                                      *
1902 %************************************************************************
1903
1904 We are a bit careful with occurrence info.  Here's an example
1905
1906         (\x* -> case x of (a*, b) -> f a) (h v, e)
1907
1908 where the * means "occurs once".  This effectively becomes
1909         case (h v, e) of (a*, b) -> f a)
1910 and then
1911         let a* = h v; b = e in f a
1912 and then
1913         f (h v)
1914
1915 All this should happen in one sweep.
1916
1917 \begin{code}
1918 knownCon :: SimplEnv            
1919          -> OutExpr                             -- The scrutinee
1920          -> DataCon -> [OutType] -> [OutExpr]   -- The scrutinee (in pieces)
1921          -> InId -> [InBndr] -> InExpr          -- The alternative
1922          -> SimplCont
1923          -> SimplM (SimplEnv, OutExpr)
1924
1925 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
1926   = do  { env'  <- bind_args env bs dc_args
1927         ; env'' <- bind_case_bndr env'
1928         ; simplExprF env'' rhs cont }
1929   where
1930     zap_occ = zapBndrOccInfo (isDeadBinder bndr)    -- bndr is an InId
1931
1932                   -- Ugh!
1933     bind_args env' [] _  = return env'
1934
1935     bind_args env' (b:bs') (Type ty : args)
1936       = ASSERT( isTyCoVar b )
1937         bind_args (extendTvSubst env' b ty) bs' args
1938
1939     bind_args env' (b:bs') (arg : args)
1940       = ASSERT( isId b )
1941         do { let b' = zap_occ b
1942              -- Note that the binder might be "dead", because it doesn't
1943              -- occur in the RHS; and simplNonRecX may therefore discard
1944              -- it via postInlineUnconditionally.
1945              -- Nevertheless we must keep it if the case-binder is alive,
1946              -- because it may be used in the con_app.  See Note [zapOccInfo]
1947            ; env'' <- simplNonRecX env' b' arg
1948            ; bind_args env'' bs' args }
1949
1950     bind_args _ _ _ =
1951       pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
1952                              text "scrut:" <+> ppr scrut
1953
1954        -- It's useful to bind bndr to scrut, rather than to a fresh
1955        -- binding      x = Con arg1 .. argn
1956        -- because very often the scrut is a variable, so we avoid
1957        -- creating, and then subsequently eliminating, a let-binding
1958        -- BUT, if scrut is a not a variable, we must be careful
1959        -- about duplicating the arg redexes; in that case, make
1960        -- a new con-app from the args
1961     bind_case_bndr env
1962       | isDeadBinder bndr   = return env
1963       | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut))
1964       | otherwise           = do { dc_args <- mapM (simplVar env) bs
1965                                          -- dc_ty_args are aready OutTypes, 
1966                                          -- but bs are InBndrs
1967                                  ; let con_app = Var (dataConWorkId dc) 
1968                                                  `mkTyApps` dc_ty_args      
1969                                                  `mkApps`   dc_args
1970                                  ; simplNonRecX env bndr con_app }
1971   
1972 -------------------
1973 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
1974                 -- This isn't strictly an error, although it is unusual. 
1975                 -- It's possible that the simplifer might "see" that 
1976                 -- an inner case has no accessible alternatives before 
1977                 -- it "sees" that the entire branch of an outer case is 
1978                 -- inaccessible.  So we simply put an error case here instead.
1979 missingAlt env case_bndr alts cont
1980   = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
1981     return (env, mkImpossibleExpr res_ty)
1982   where
1983     res_ty = contResultType env (substTy env (coreAltsType alts)) cont
1984 \end{code}
1985
1986
1987 %************************************************************************
1988 %*                                                                      *
1989 \subsection{Duplicating continuations}
1990 %*                                                                      *
1991 %************************************************************************
1992
1993 \begin{code}
1994 prepareCaseCont :: SimplEnv
1995                 -> [InAlt] -> SimplCont
1996                 -> SimplM (SimplEnv, SimplCont, SimplCont)
1997 -- We are considering
1998 --     K[case _ of { p1 -> r1; ...; pn -> rn }] 
1999 -- where K is some enclosing continuation for the case
2000 -- Goal: split K into two pieces Kdup,Knodup so that
2001 --       a) Kdup can be duplicated
2002 --       b) Knodup[Kdup[e]] = K[e]
2003 -- The idea is that we'll transform thus:
2004 --          Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }
2005 --
2006 -- We also return some extra bindings in SimplEnv (that scope over 
2007 -- the entire continuation)
2008
2009 prepareCaseCont env alts cont 
2010   | many_alts alts = mkDupableCont env cont 
2011   | otherwise      = return (env, cont, mkBoringStop)
2012   where
2013     many_alts :: [InAlt] -> Bool  -- True iff strictly > 1 non-bottom alternative
2014     many_alts []  = False         -- See Note [Bottom alternatives]
2015     many_alts [_] = False
2016     many_alts (alt:alts) 
2017       | is_bot_alt alt = many_alts alts   
2018       | otherwise      = not (all is_bot_alt alts)
2019   
2020     is_bot_alt (_,_,rhs) = exprIsBottom rhs
2021 \end{code}
2022
2023 Note [Bottom alternatives]
2024 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2025 When we have
2026      case (case x of { A -> error .. ; B -> e; C -> error ..) 
2027        of alts
2028 then we can just duplicate those alts because the A and C cases
2029 will disappear immediately.  This is more direct than creating
2030 join points and inlining them away; and in some cases we would
2031 not even create the join points (see Note [Single-alternative case])
2032 and we would keep the case-of-case which is silly.  See Trac #4930.
2033
2034 \begin{code}
2035 mkDupableCont :: SimplEnv -> SimplCont
2036               -> SimplM (SimplEnv, SimplCont, SimplCont)
2037
2038 mkDupableCont env cont
2039   | contIsDupable cont
2040   = return (env, cont, mkBoringStop)
2041
2042 mkDupableCont _   (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn
2043
2044 mkDupableCont env (CoerceIt ty cont)
2045   = do  { (env', dup, nodup) <- mkDupableCont env cont
2046         ; return (env', CoerceIt ty dup, nodup) }
2047
2048 mkDupableCont env cont@(StrictBind {})
2049   =  return (env, mkBoringStop, cont)
2050         -- See Note [Duplicating StrictBind]
2051
2052 mkDupableCont env (StrictArg info cci cont)
2053         -- See Note [Duplicating StrictArg]
2054   = do { (env', dup, nodup) <- mkDupableCont env cont
2055        ; (env'', args')     <- mapAccumLM (makeTrivial NotTopLevel) env' (ai_args info)
2056        ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
2057
2058 mkDupableCont env (ApplyTo _ arg se cont)
2059   =     -- e.g.         [...hole...] (...arg...)
2060         --      ==>
2061         --              let a = ...arg...
2062         --              in [...hole...] a
2063     do  { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
2064         ; arg' <- simplExpr (se `setInScope` env') arg
2065         ; (env'', arg'') <- makeTrivial NotTopLevel env' arg'
2066         ; let app_cont = ApplyTo OkToDup arg'' (zapSubstEnv env'') dup_cont
2067         ; return (env'', app_cont, nodup_cont) }
2068
2069 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
2070 --  See Note [Single-alternative case]
2071 --  | not (exprIsDupable rhs && contIsDupable case_cont)
2072 --  | not (isDeadBinder case_bndr)
2073   | all isDeadBinder bs  -- InIds
2074     && not (isUnLiftedType (idType case_bndr))
2075     -- Note [Single-alternative-unlifted]
2076   = return (env, mkBoringStop, cont)
2077
2078 mkDupableCont env (Select _ case_bndr alts se cont)
2079   =     -- e.g.         (case [...hole...] of { pi -> ei })
2080         --      ===>
2081         --              let ji = \xij -> ei
2082         --              in case [...hole...] of { pi -> ji xij }
2083     do  { tick (CaseOfCase case_bndr)
2084         ; (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
2085                 -- NB: We call prepareCaseCont here.  If there is only one
2086                 -- alternative, then dup_cont may be big, but that's ok
2087                 -- becuase we push it into the single alternative, and then
2088                 -- use mkDupableAlt to turn that simplified alternative into
2089                 -- a join point if it's too big to duplicate.
2090                 -- And this is important: see Note [Fusing case continuations]
2091
2092         ; let alt_env = se `setInScope` env'
2093         ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
2094         ; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' dup_cont) alts
2095         -- Safe to say that there are no handled-cons for the DEFAULT case
2096                 -- NB: simplBinder does not zap deadness occ-info, so
2097                 -- a dead case_bndr' will still advertise its deadness
2098                 -- This is really important because in
2099                 --      case e of b { (# p,q #) -> ... }
2100                 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
2101                 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
2102                 -- In the new alts we build, we have the new case binder, so it must retain
2103                 -- its deadness.
2104         -- NB: we don't use alt_env further; it has the substEnv for
2105         --     the alternatives, and we don't want that
2106
2107         ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
2108         ; return (env'',  -- Note [Duplicated env]
2109                   Select OkToDup case_bndr' alts'' (zapSubstEnv env'') mkBoringStop,
2110                   nodup_cont) }
2111
2112
2113 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
2114               -> SimplM (SimplEnv, [InAlt])
2115 -- Absorbs the continuation into the new alternatives
2116
2117 mkDupableAlts env case_bndr' the_alts
2118   = go env the_alts
2119   where
2120     go env0 [] = return (env0, [])
2121     go env0 (alt:alts)
2122         = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
2123              ; (env2, alts') <- go env1 alts
2124              ; return (env2, alt' : alts' ) }
2125
2126 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
2127               -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
2128 mkDupableAlt env case_bndr (con, bndrs', rhs')
2129   | exprIsDupable rhs'  -- Note [Small alternative rhs]
2130   = return (env, (con, bndrs', rhs'))
2131   | otherwise
2132   = do  { let rhs_ty'  = exprType rhs'
2133               scrut_ty = idType case_bndr
2134               case_bndr_w_unf   
2135                 = case con of 
2136                       DEFAULT    -> case_bndr                                   
2137                       DataAlt dc -> setIdUnfolding case_bndr unf
2138                           where
2139                                  -- See Note [Case binders and join points]
2140                              unf = mkInlineUnfolding Nothing rhs
2141                              rhs = mkConApp dc (map Type (tyConAppArgs scrut_ty)
2142                                                 ++ varsToCoreExprs bndrs')
2143
2144                       LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
2145                                                 <+> ppr case_bndr <+> ppr con )
2146                                    case_bndr
2147                            -- The case binder is alive but trivial, so why has 
2148                            -- it not been substituted away?
2149
2150               used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
2151                           | otherwise              = bndrs' ++ [case_bndr_w_unf]
2152               
2153               abstract_over bndr
2154                   | isTyCoVar bndr = True -- Abstract over all type variables just in case
2155                   | otherwise    = not (isDeadBinder bndr)
2156                         -- The deadness info on the new Ids is preserved by simplBinders
2157
2158         ; (final_bndrs', final_args)    -- Note [Join point abstraction]
2159                 <- if (any isId used_bndrs')
2160                    then return (used_bndrs', varsToCoreExprs used_bndrs')
2161                     else do { rw_id <- newId (fsLit "w") realWorldStatePrimTy
2162                             ; return ([rw_id], [Var realWorldPrimId]) }
2163
2164         ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
2165                 -- Note [Funky mkPiTypes]
2166
2167         ; let   -- We make the lambdas into one-shot-lambdas.  The
2168                 -- join point is sure to be applied at most once, and doing so
2169                 -- prevents the body of the join point being floated out by
2170                 -- the full laziness pass
2171                 really_final_bndrs     = map one_shot final_bndrs'
2172                 one_shot v | isId v    = setOneShotLambda v
2173                            | otherwise = v
2174                 join_rhs  = mkLams really_final_bndrs rhs'
2175                 join_call = mkApps (Var join_bndr) final_args
2176
2177         ; env' <- addPolyBind NotTopLevel env (NonRec join_bndr join_rhs)
2178         ; return (env', (con, bndrs', join_call)) }
2179                 -- See Note [Duplicated env]
2180 \end{code}
2181
2182 Note [Fusing case continuations]
2183 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2184 It's important to fuse two successive case continuations when the
2185 first has one alternative.  That's why we call prepareCaseCont here.
2186 Consider this, which arises from thunk splitting (see Note [Thunk
2187 splitting] in WorkWrap):
2188
2189       let
2190         x* = case (case v of {pn -> rn}) of 
2191                I# a -> I# a
2192       in body
2193
2194 The simplifier will find
2195     (Var v) with continuation  
2196             Select (pn -> rn) (
2197             Select [I# a -> I# a] (
2198             StrictBind body Stop
2199
2200 So we'll call mkDupableCont on 
2201    Select [I# a -> I# a] (StrictBind body Stop)
2202 There is just one alternative in the first Select, so we want to
2203 simplify the rhs (I# a) with continuation (StricgtBind body Stop)
2204 Supposing that body is big, we end up with
2205           let $j a = <let x = I# a in body> 
2206           in case v of { pn -> case rn of 
2207                                  I# a -> $j a }
2208 This is just what we want because the rn produces a box that
2209 the case rn cancels with.  
2210
2211 See Trac #4957 a fuller example.
2212
2213 Note [Case binders and join points]
2214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2215 Consider this 
2216    case (case .. ) of c {
2217      I# c# -> ....c....
2218
2219 If we make a join point with c but not c# we get
2220   $j = \c -> ....c....
2221
2222 But if later inlining scrutines the c, thus
2223
2224   $j = \c -> ... case c of { I# y -> ... } ...
2225
2226 we won't see that 'c' has already been scrutinised.  This actually
2227 happens in the 'tabulate' function in wave4main, and makes a significant
2228 difference to allocation.
2229
2230 An alternative plan is this:
2231
2232    $j = \c# -> let c = I# c# in ...c....
2233
2234 but that is bad if 'c' is *not* later scrutinised.  
2235
2236 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2237 (an InlineRule) that it's really I# c#, thus
2238    
2239    $j = \c# -> \c[=I# c#] -> ...c....
2240
2241 Absence analysis may later discard 'c'.
2242
2243 NB: take great care when doing strictness analysis; 
2244     see Note [Lamba-bound unfoldings] in DmdAnal.
2245
2246 Also note that we can still end up passing stuff that isn't used.  Before
2247 strictness analysis we have
2248    let $j x y c{=(x,y)} = (h c, ...)
2249    in ...
2250 After strictness analysis we see that h is strict, we end up with
2251    let $j x y c{=(x,y)} = ($wh x y, ...)
2252 and c is unused.
2253    
2254 Note [Duplicated env]
2255 ~~~~~~~~~~~~~~~~~~~~~
2256 Some of the alternatives are simplified, but have not been turned into a join point
2257 So they *must* have an zapped subst-env.  So we can't use completeNonRecX to
2258 bind the join point, because it might to do PostInlineUnconditionally, and
2259 we'd lose that when zapping the subst-env.  We could have a per-alt subst-env,
2260 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2261 at worst delays the join-point inlining.
2262
2263 Note [Small alternative rhs]
2264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2265 It is worth checking for a small RHS because otherwise we
2266 get extra let bindings that may cause an extra iteration of the simplifier to
2267 inline back in place.  Quite often the rhs is just a variable or constructor.
2268 The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
2269 iterations because the version with the let bindings looked big, and so wasn't
2270 inlined, but after the join points had been inlined it looked smaller, and so
2271 was inlined.
2272
2273 NB: we have to check the size of rhs', not rhs.
2274 Duplicating a small InAlt might invalidate occurrence information
2275 However, if it *is* dupable, we return the *un* simplified alternative,
2276 because otherwise we'd need to pair it up with an empty subst-env....
2277 but we only have one env shared between all the alts.
2278 (Remember we must zap the subst-env before re-simplifying something).
2279 Rather than do this we simply agree to re-simplify the original (small) thing later.
2280
2281 Note [Funky mkPiTypes]
2282 ~~~~~~~~~~~~~~~~~~~~~~
2283 Notice the funky mkPiTypes.  If the contructor has existentials
2284 it's possible that the join point will be abstracted over
2285 type varaibles as well as term variables.
2286  Example:  Suppose we have
2287         data T = forall t.  C [t]
2288  Then faced with
2289         case (case e of ...) of
2290             C t xs::[t] -> rhs
2291  We get the join point
2292         let j :: forall t. [t] -> ...
2293             j = /\t \xs::[t] -> rhs
2294         in
2295         case (case e of ...) of
2296             C t xs::[t] -> j t xs
2297
2298 Note [Join point abstaction]
2299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2300 If we try to lift a primitive-typed something out
2301 for let-binding-purposes, we will *caseify* it (!),
2302 with potentially-disastrous strictness results.  So
2303 instead we turn it into a function: \v -> e
2304 where v::State# RealWorld#.  The value passed to this function
2305 is realworld#, which generates (almost) no code.
2306
2307 There's a slight infelicity here: we pass the overall
2308 case_bndr to all the join points if it's used in *any* RHS,
2309 because we don't know its usage in each RHS separately
2310
2311 We used to say "&& isUnLiftedType rhs_ty'" here, but now
2312 we make the join point into a function whenever used_bndrs'
2313 is empty.  This makes the join-point more CPR friendly.
2314 Consider:       let j = if .. then I# 3 else I# 4
2315                 in case .. of { A -> j; B -> j; C -> ... }
2316
2317 Now CPR doesn't w/w j because it's a thunk, so
2318 that means that the enclosing function can't w/w either,
2319 which is a lose.  Here's the example that happened in practice:
2320         kgmod :: Int -> Int -> Int
2321         kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2322                     then 78
2323                     else 5
2324
2325 I have seen a case alternative like this:
2326         True -> \v -> ...
2327 It's a bit silly to add the realWorld dummy arg in this case, making
2328         $j = \s v -> ...
2329            True -> $j s
2330 (the \v alone is enough to make CPR happy) but I think it's rare
2331
2332 Note [Duplicating StrictArg]
2333 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2334 The original plan had (where E is a big argument)
2335 e.g.    f E [..hole..]
2336         ==>     let $j = \a -> f E a
2337                 in $j [..hole..]
2338
2339 But this is terrible! Here's an example:
2340         && E (case x of { T -> F; F -> T })
2341 Now, && is strict so we end up simplifying the case with
2342 an ArgOf continuation.  If we let-bind it, we get
2343         let $j = \v -> && E v
2344         in simplExpr (case x of { T -> F; F -> T })
2345                      (ArgOf (\r -> $j r)
2346 And after simplifying more we get
2347         let $j = \v -> && E v
2348         in case x of { T -> $j F; F -> $j T }
2349 Which is a Very Bad Thing
2350
2351 What we do now is this
2352         f E [..hole..]
2353         ==>     let a = E
2354                 in f a [..hole..]
2355 Now if the thing in the hole is a case expression (which is when
2356 we'll call mkDupableCont), we'll push the function call into the
2357 branches, which is what we want.  Now RULES for f may fire, and
2358 call-pattern specialisation.  Here's an example from Trac #3116
2359      go (n+1) (case l of
2360                  1  -> bs'
2361                  _  -> Chunk p fpc (o+1) (l-1) bs')
2362 If we can push the call for 'go' inside the case, we get
2363 call-pattern specialisation for 'go', which is *crucial* for 
2364 this program.
2365
2366 Here is the (&&) example: 
2367         && E (case x of { T -> F; F -> T })
2368   ==>   let a = E in 
2369         case x of { T -> && a F; F -> && a T }
2370 Much better!
2371
2372 Notice that 
2373   * Arguments to f *after* the strict one are handled by 
2374     the ApplyTo case of mkDupableCont.  Eg
2375         f [..hole..] E
2376
2377   * We can only do the let-binding of E because the function
2378     part of a StrictArg continuation is an explicit syntax
2379     tree.  In earlier versions we represented it as a function
2380     (CoreExpr -> CoreEpxr) which we couldn't take apart.
2381
2382 Do *not* duplicate StrictBind and StritArg continuations.  We gain
2383 nothing by propagating them into the expressions, and we do lose a
2384 lot.  
2385
2386 The desire not to duplicate is the entire reason that
2387 mkDupableCont returns a pair of continuations.
2388
2389 Note [Duplicating StrictBind]
2390 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2391 Unlike StrictArg, there doesn't seem anything to gain from
2392 duplicating a StrictBind continuation, so we don't.
2393
2394
2395 Note [Single-alternative cases]
2396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2397 This case is just like the ArgOf case.  Here's an example:
2398         data T a = MkT !a
2399         ...(MkT (abs x))...
2400 Then we get
2401         case (case x of I# x' ->
2402               case x' <# 0# of
2403                 True  -> I# (negate# x')
2404                 False -> I# x') of y {
2405           DEFAULT -> MkT y
2406 Because the (case x) has only one alternative, we'll transform to
2407         case x of I# x' ->
2408         case (case x' <# 0# of
2409                 True  -> I# (negate# x')
2410                 False -> I# x') of y {
2411           DEFAULT -> MkT y
2412 But now we do *NOT* want to make a join point etc, giving
2413         case x of I# x' ->
2414         let $j = \y -> MkT y
2415         in case x' <# 0# of
2416                 True  -> $j (I# (negate# x'))
2417                 False -> $j (I# x')
2418 In this case the $j will inline again, but suppose there was a big
2419 strict computation enclosing the orginal call to MkT.  Then, it won't
2420 "see" the MkT any more, because it's big and won't get duplicated.
2421 And, what is worse, nothing was gained by the case-of-case transform.
2422
2423 So, in circumstances like these, we don't want to build join points
2424 and push the outer case into the branches of the inner one. Instead,
2425 don't duplicate the continuation. 
2426
2427 When should we use this strategy?  We should not use it on *every*
2428 single-alternative case:
2429   e.g.  case (case ....) of (a,b) -> (# a,b #)
2430 Here we must push the outer case into the inner one!
2431 Other choices:
2432
2433    * Match [(DEFAULT,_,_)], but in the common case of Int,
2434      the alternative-filling-in code turned the outer case into
2435                 case (...) of y { I# _ -> MkT y }
2436
2437    * Match on single alternative plus (not (isDeadBinder case_bndr))
2438      Rationale: pushing the case inwards won't eliminate the construction.
2439      But there's a risk of
2440                 case (...) of y { (a,b) -> let z=(a,b) in ... }
2441      Now y looks dead, but it'll come alive again.  Still, this
2442      seems like the best option at the moment.
2443
2444    * Match on single alternative plus (all (isDeadBinder bndrs))
2445      Rationale: this is essentially  seq.
2446
2447    * Match when the rhs is *not* duplicable, and hence would lead to a
2448      join point.  This catches the disaster-case above.  We can test
2449      the *un-simplified* rhs, which is fine.  It might get bigger or
2450      smaller after simplification; if it gets smaller, this case might
2451      fire next time round.  NB also that we must test contIsDupable
2452      case_cont *too, because case_cont might be big!
2453
2454      HOWEVER: I found that this version doesn't work well, because
2455      we can get         let x = case (...) of { small } in ...case x...
2456      When x is inlined into its full context, we find that it was a bad
2457      idea to have pushed the outer case inside the (...) case.
2458
2459 Note [Single-alternative-unlifted]
2460 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2461 Here's another single-alternative where we really want to do case-of-case:
2462
2463 data Mk1 = Mk1 Int# | Mk2 Int#
2464
2465 M1.f =
2466     \r [x_s74 y_s6X]
2467         case
2468             case y_s6X of tpl_s7m {
2469               M1.Mk1 ipv_s70 -> ipv_s70;
2470               M1.Mk2 ipv_s72 -> ipv_s72;
2471             }
2472         of
2473         wild_s7c
2474         { __DEFAULT ->
2475               case
2476                   case x_s74 of tpl_s7n {
2477                     M1.Mk1 ipv_s77 -> ipv_s77;
2478                     M1.Mk2 ipv_s79 -> ipv_s79;
2479                   }
2480               of
2481               wild1_s7b
2482               { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2483               };
2484         };
2485
2486 So the outer case is doing *nothing at all*, other than serving as a
2487 join-point.  In this case we really want to do case-of-case and decide
2488 whether to use a real join point or just duplicate the continuation:
2489
2490     let $j s7c = case x of
2491                    Mk1 ipv77 -> (==) s7c ipv77
2492                    Mk1 ipv79 -> (==) s7c ipv79
2493     in
2494     case y of 
2495       Mk1 ipv70 -> $j ipv70
2496       Mk2 ipv72 -> $j ipv72
2497
2498 Hence: check whether the case binder's type is unlifted, because then
2499 the outer case is *not* a seq.