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