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