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