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