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