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