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