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