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