223d61a2f487c66f4bcfcd74375793c65da182d9
[ghc-hetmet.git] / ghc / 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, prepareAlts,
17                           SimplCont(..), DupFlag(..), LetRhsFlag(..), 
18                           mkRhsStop, mkBoringStop,  pushContArgs,
19                           contResultType, countArgs, contIsDupable, contIsRhsOrArg,
20                           getContArgs, interestingCallContext, interestingArg, isStrictType,
21                           preInlineUnconditionally, postInlineUnconditionally, 
22                           inlineMode, activeInline, activeRule
23                         )
24 import Id               ( Id, idType, idInfo, idArity, isDataConWorkId, 
25                           setIdUnfolding, isDeadBinder,
26                           idNewDemandInfo, setIdInfo, 
27                           setIdOccInfo, zapLamIdInfo, setOneShotLambda
28                         )
29 import MkId             ( eRROR_ID )
30 import Literal          ( mkStringLit )
31 import IdInfo           ( OccInfo(..), isLoopBreaker,
32                           setArityInfo, zapDemandInfo,
33                           setUnfoldingInfo, 
34                           occInfo
35                         )
36 import NewDemand        ( isStrictDmd )
37 import Unify            ( coreRefineTys )
38 import DataCon          ( dataConTyCon, dataConRepStrictness, isVanillaDataCon )
39 import TyCon            ( tyConArity )
40 import CoreSyn
41 import PprCore          ( pprParendExpr, pprCoreExpr )
42 import CoreUnfold       ( mkUnfolding, callSiteInline )
43 import CoreUtils        ( exprIsDupable, exprIsTrivial, needsCaseBinding,
44                           exprIsConApp_maybe, mkPiTypes, findAlt, 
45                           exprType, exprIsHNF, 
46                           exprOkForSpeculation, exprArity, 
47                           mkCoerce, mkCoerce2, mkSCC, mkInlineMe, applyTypeToArg
48                         )
49 import Rules            ( lookupRule )
50 import BasicTypes       ( isMarkedStrict )
51 import CostCentre       ( currentCCS )
52 import Type             ( TvSubstEnv, isUnLiftedType, seqType, tyConAppArgs, funArgTy,
53                           splitFunTy_maybe, splitFunTy, coreEqType 
54                         )
55 import VarEnv           ( elemVarEnv, emptyVarEnv )
56 import TysPrim          ( realWorldStatePrimTy )
57 import PrelInfo         ( realWorldPrimId )
58 import BasicTypes       ( TopLevelFlag(..), isTopLevel, 
59                           RecFlag(..), isNonRec
60                         )
61 import StaticFlags      ( opt_PprStyle_Debug )
62 import OrdList
63 import Maybes           ( orElse )
64 import Outputable
65 import Util             ( notNull )
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     simplLetBndrs 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     simplLetBndr 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         -- simplLetBndr doesn't deal with the IdInfo, so we must
317         -- do so here (c.f. simplLazyBind)
318         bndr2  = bndr1 `setIdInfo` simplIdInfo env (idInfo bndr)
319         env2   = modifyInScope env1 bndr2 bndr2
320     in
321     if needsCaseBinding bndr_ty rhs1
322     then
323       thing_inside env2                                 `thenSmpl` \ (floats, body) ->
324       returnSmpl (emptyFloats env2, Case rhs1 bndr2 (exprType body) 
325                                         [(DEFAULT, [], wrapFloats floats body)])
326     else
327       completeNonRecX env2 True {- strict -} bndr bndr2 rhs1 thing_inside
328
329   | otherwise                                                   -- Normal, lazy case
330   =     -- Don't use simplBinder because that doesn't keep 
331         -- fragile occurrence info in the substitution
332     simplLetBndr env bndr                               `thenSmpl` \ (env, bndr') ->
333     simplLazyBind env NotTopLevel NonRecursive
334                   bndr bndr' rhs rhs_se                 `thenSmpl` \ (floats, env) ->
335     addFloats env floats thing_inside
336
337   where
338     bndr_ty = idType bndr
339 \end{code}
340
341 A specialised variant of simplNonRec used when the RHS is already simplified, notably
342 in knownCon.  It uses case-binding where necessary.
343
344 \begin{code}
345 simplNonRecX :: SimplEnv
346              -> InId            -- Old binder
347              -> OutExpr         -- Simplified RHS
348              -> (SimplEnv -> SimplM FloatsWithExpr)
349              -> SimplM FloatsWithExpr
350
351 simplNonRecX env bndr new_rhs thing_inside
352   | needsCaseBinding (idType bndr) new_rhs
353         -- Make this test *before* the preInlineUnconditionally
354         -- Consider     case I# (quotInt# x y) of 
355         --                I# v -> let w = J# v in ...
356         -- If we gaily inline (quotInt# x y) for v, we end up building an
357         -- extra thunk:
358         --                let w = J# (quotInt# x y) in ...
359         -- because quotInt# can fail.
360   = simplBinder env bndr        `thenSmpl` \ (env, bndr') ->
361     thing_inside env            `thenSmpl` \ (floats, body) ->
362     let body' = wrapFloats floats body in 
363     returnSmpl (emptyFloats env, Case new_rhs bndr' (exprType body') [(DEFAULT, [], body')])
364
365   | preInlineUnconditionally env NotTopLevel bndr new_rhs
366         -- This happens; for example, the case_bndr during case of
367         -- known constructor:  case (a,b) of x { (p,q) -> ... }
368         -- Here x isn't mentioned in the RHS, so we don't want to
369         -- create the (dead) let-binding  let x = (a,b) in ...
370         --
371         -- Similarly, single occurrences can be inlined vigourously
372         -- e.g.  case (f x, g y) of (a,b) -> ....
373         -- If a,b occur once we can avoid constructing the let binding for them.
374   = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
375
376   | otherwise
377   = simplBinder env bndr        `thenSmpl` \ (env, bndr') ->
378     completeNonRecX env False {- Non-strict; pessimistic -} 
379                     bndr bndr' new_rhs thing_inside
380
381 completeNonRecX env is_strict old_bndr new_bndr new_rhs thing_inside
382   = mkAtomicArgs is_strict 
383                  True {- OK to float unlifted -} 
384                  new_rhs                        `thenSmpl` \ (aux_binds, rhs2) ->
385
386         -- Make the arguments atomic if necessary, 
387         -- adding suitable bindings
388     addAtomicBindsE env (fromOL aux_binds)      $ \ env ->
389     completeLazyBind env NotTopLevel
390                      old_bndr new_bndr rhs2     `thenSmpl` \ (floats, env) ->
391     addFloats env floats thing_inside
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397 \subsection{Lazy bindings}
398 %*                                                                      *
399 %************************************************************************
400
401 simplRecBind is used for
402         * recursive bindings only
403
404 \begin{code}
405 simplRecBind :: SimplEnv -> TopLevelFlag
406              -> [(InId, InExpr)] -> [OutId]
407              -> SimplM (FloatsWith SimplEnv)
408 simplRecBind env top_lvl pairs bndrs'
409   = go env pairs bndrs'         `thenSmpl` \ (floats, env) ->
410     returnSmpl (flattenFloats floats, env)
411   where
412     go env [] _ = returnSmpl (emptyFloats env, env)
413         
414     go env ((bndr, rhs) : pairs) (bndr' : bndrs')
415         = simplRecOrTopPair env top_lvl bndr bndr' rhs  `thenSmpl` \ (floats, env) ->
416           addFloats env floats (\env -> go env pairs bndrs')
417 \end{code}
418
419
420 simplRecOrTopPair is used for
421         * recursive bindings (whether top level or not)
422         * top-level non-recursive bindings
423
424 It assumes the binder has already been simplified, but not its IdInfo.
425
426 \begin{code}
427 simplRecOrTopPair :: SimplEnv
428                   -> TopLevelFlag
429                   -> InId -> OutId              -- Binder, both pre-and post simpl
430                   -> InExpr                     -- The RHS and its environment
431                   -> SimplM (FloatsWith SimplEnv)
432
433 simplRecOrTopPair env top_lvl bndr bndr' rhs
434   | preInlineUnconditionally env top_lvl bndr rhs       -- Check for unconditional inline
435   = tick (PreInlineUnconditionally bndr)                `thenSmpl_`
436     returnSmpl (emptyFloats env, extendIdSubst env bndr (mkContEx env rhs))
437
438   | otherwise
439   = simplLazyBind env top_lvl Recursive bndr bndr' rhs env
440         -- May not actually be recursive, but it doesn't matter
441 \end{code}
442
443
444 simplLazyBind is used for
445         * recursive bindings (whether top level or not)
446         * top-level non-recursive bindings
447         * non-top-level *lazy* non-recursive bindings
448
449 [Thus it deals with the lazy cases from simplNonRecBind, and all cases
450 from SimplRecOrTopBind]
451
452 Nota bene:
453     1. It assumes that the binder is *already* simplified, 
454        and is in scope, but not its IdInfo
455
456     2. It assumes that the binder type is lifted.
457
458     3. It does not check for pre-inline-unconditionallly;
459        that should have been done already.
460
461 \begin{code}
462 simplLazyBind :: SimplEnv
463               -> TopLevelFlag -> RecFlag
464               -> InId -> OutId          -- Binder, both pre-and post simpl
465               -> InExpr -> SimplEnv     -- The RHS and its environment
466               -> SimplM (FloatsWith SimplEnv)
467
468 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
469   = let -- Transfer the IdInfo of the original binder to the new binder
470         -- This is crucial: we must preserve
471         --      strictness
472         --      rules
473         --      worker info
474         -- etc.  To do this we must apply the current substitution, 
475         -- which incorporates earlier substitutions in this very letrec group.
476         --
477         -- NB 1.  We do this *before* processing the RHS of the binder, so that
478         -- its substituted rules are visible in its own RHS.
479         -- This is important.  Manuel found cases where he really, really
480         -- wanted a RULE for a recursive function to apply in that function's
481         -- own right-hand side.
482         --
483         -- NB 2: We do not transfer the arity (see Subst.substIdInfo)
484         -- The arity of an Id should not be visible
485         -- in its own RHS, else we eta-reduce
486         --      f = \x -> f x
487         -- to
488         --      f = f
489         -- which isn't sound.  And it makes the arity in f's IdInfo greater than
490         -- the manifest arity, which isn't good.
491         -- The arity will get added later.
492         --
493         -- NB 3: It's important that we *do* transer the loop-breaker OccInfo,
494         -- because that's what stops the Id getting inlined infinitely, in the body
495         -- of the letrec.
496
497         -- NB 4: does no harm for non-recursive bindings
498
499         bndr2             = bndr1 `setIdInfo` simplIdInfo env (idInfo bndr)
500         env1              = modifyInScope env bndr2 bndr2
501         rhs_env           = setInScope rhs_se env1
502         is_top_level      = isTopLevel top_lvl
503         ok_float_unlifted = not is_top_level && isNonRec is_rec
504         rhs_cont          = mkRhsStop (idType bndr1)
505     in
506         -- Simplify the RHS; note the mkRhsStop, which tells 
507         -- the simplifier that this is the RHS of a let.
508     simplExprF rhs_env rhs rhs_cont             `thenSmpl` \ (floats, rhs1) ->
509
510         -- If any of the floats can't be floated, give up now
511         -- (The allLifted predicate says True for empty floats.)
512     if (not ok_float_unlifted && not (allLifted floats)) then
513         completeLazyBind env1 top_lvl bndr bndr2
514                          (wrapFloats floats rhs1)
515     else        
516
517         -- ANF-ise a constructor or PAP rhs
518     mkAtomicArgs False {- Not strict -} 
519                  ok_float_unlifted rhs1                 `thenSmpl` \ (aux_binds, rhs2) ->
520
521         -- If the result is a PAP, float the floats out, else wrap them
522         -- By this time it's already been ANF-ised (if necessary)
523     if isEmptyFloats floats && isNilOL aux_binds then   -- Shortcut a common case
524         completeLazyBind env1 top_lvl bndr bndr2 rhs2
525
526     else if is_top_level || exprIsTrivial rhs2 || exprIsHNF rhs2 then
527         --      WARNING: long dodgy argument coming up
528         --      WANTED: a better way to do this
529         --              
530         -- We can't use "exprIsCheap" instead of exprIsHNF, 
531         -- because that causes a strictness bug.
532         --         x = let y* = E in case (scc y) of { T -> F; F -> T}
533         -- The case expression is 'cheap', but it's wrong to transform to
534         --         y* = E; x = case (scc y) of {...}
535         -- Either we must be careful not to float demanded non-values, or
536         -- we must use exprIsHNF for the test, which ensures that the
537         -- thing is non-strict.  So exprIsHNF => bindings are non-strict
538         -- I think.  The WARN below tests for this.
539         --
540         -- We use exprIsTrivial here because we want to reveal lone variables.  
541         -- E.g.  let { x = letrec { y = E } in y } in ...
542         -- Here we definitely want to float the y=E defn. 
543         -- exprIsHNF definitely isn't right for that.
544         --
545         -- Again, the floated binding can't be strict; if it's recursive it'll
546         -- be non-strict; if it's non-recursive it'd be inlined.
547         --
548         -- Note [SCC-and-exprIsTrivial]
549         -- If we have
550         --      y = let { x* = E } in scc "foo" x
551         -- then we do *not* want to float out the x binding, because
552         -- it's strict!  Fortunately, exprIsTrivial replies False to
553         -- (scc "foo" x).
554
555                 -- There's a subtlety here.  There may be a binding (x* = e) in the
556                 -- floats, where the '*' means 'will be demanded'.  So is it safe
557                 -- to float it out?  Answer no, but it won't matter because
558                 -- we only float if (a) arg' is a WHNF, or (b) it's going to top level
559                 -- and so there can't be any 'will be demanded' bindings in the floats.
560                 -- Hence the warning
561         ASSERT2( is_top_level || not (any demanded_float (floatBinds floats)), 
562                  ppr (filter demanded_float (floatBinds floats)) )
563
564         tick LetFloatFromLet                    `thenSmpl_` (
565         addFloats env1 floats                   $ \ env2 ->
566         addAtomicBinds env2 (fromOL aux_binds)  $ \ env3 ->
567         completeLazyBind env3 top_lvl bndr bndr2 rhs2)
568
569     else
570         completeLazyBind env1 top_lvl bndr bndr2 (wrapFloats floats rhs1)
571
572 #ifdef DEBUG
573 demanded_float (NonRec b r) = isStrictDmd (idNewDemandInfo b) && not (isUnLiftedType (idType b))
574                 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
575 demanded_float (Rec _)      = False
576 #endif
577 \end{code}
578
579
580 %************************************************************************
581 %*                                                                      *
582 \subsection{Completing a lazy binding}
583 %*                                                                      *
584 %************************************************************************
585
586 completeLazyBind
587         * deals only with Ids, not TyVars
588         * takes an already-simplified binder and RHS
589         * is used for both recursive and non-recursive bindings
590         * is used for both top-level and non-top-level bindings
591
592 It does the following:
593   - tries discarding a dead binding
594   - tries PostInlineUnconditionally
595   - add unfolding [this is the only place we add an unfolding]
596   - add arity
597
598 It does *not* attempt to do let-to-case.  Why?  Because it is used for
599         - top-level bindings (when let-to-case is impossible) 
600         - many situations where the "rhs" is known to be a WHNF
601                 (so let-to-case is inappropriate).
602
603 \begin{code}
604 completeLazyBind :: SimplEnv
605                  -> TopLevelFlag        -- Flag stuck into unfolding
606                  -> InId                -- Old binder
607                  -> OutId               -- New binder
608                  -> OutExpr             -- Simplified RHS
609                  -> SimplM (FloatsWith SimplEnv)
610 -- We return a new SimplEnv, because completeLazyBind may choose to do its work
611 -- by extending the substitution (e.g. let x = y in ...)
612 -- The new binding (if any) is returned as part of the floats.
613 -- NB: the returned SimplEnv has the right SubstEnv, but you should
614 --     (as usual) use the in-scope-env from the floats
615
616 completeLazyBind env top_lvl old_bndr new_bndr new_rhs
617   | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
618   =             -- Drop the binding
619     tick (PostInlineUnconditionally old_bndr)   `thenSmpl_`
620     returnSmpl (emptyFloats env, extendIdSubst env old_bndr (DoneEx new_rhs))
621                 -- Use the substitution to make quite, quite sure that the substitution
622                 -- will happen, since we are going to discard the binding
623
624   |  otherwise
625   = let
626                 -- Add arity info
627         new_bndr_info = idInfo new_bndr `setArityInfo` exprArity new_rhs
628
629         -- Add the unfolding *only* for non-loop-breakers
630         -- Making loop breakers not have an unfolding at all 
631         -- means that we can avoid tests in exprIsConApp, for example.
632         -- This is important: if exprIsConApp says 'yes' for a recursive
633         -- thing, then we can get into an infinite loop
634
635         -- If the unfolding is a value, the demand info may
636         -- go pear-shaped, so we nuke it.  Example:
637         --      let x = (a,b) in
638         --      case x of (p,q) -> h p q x
639         -- Here x is certainly demanded. But after we've nuked
640         -- the case, we'll get just
641         --      let x = (a,b) in h a b x
642         -- and now x is not demanded (I'm assuming h is lazy)
643         -- This really happens.  Similarly
644         --      let f = \x -> e in ...f..f...
645         -- After inling f at some of its call sites the original binding may
646         -- (for example) be no longer strictly demanded.
647         -- The solution here is a bit ad hoc...
648         info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
649         final_info | loop_breaker               = new_bndr_info
650                    | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
651                    | otherwise                  = info_w_unf
652
653         final_id = new_bndr `setIdInfo` final_info
654     in
655                 -- These seqs forces the Id, and hence its IdInfo,
656                 -- and hence any inner substitutions
657     final_id                                    `seq`
658     returnSmpl (unitFloat env final_id new_rhs, env)
659
660   where 
661     unfolding    = mkUnfolding (isTopLevel top_lvl) new_rhs
662     loop_breaker = isLoopBreaker occ_info
663     old_info     = idInfo old_bndr
664     occ_info     = occInfo old_info
665 \end{code}    
666
667
668
669 %************************************************************************
670 %*                                                                      *
671 \subsection[Simplify-simplExpr]{The main function: simplExpr}
672 %*                                                                      *
673 %************************************************************************
674
675 The reason for this OutExprStuff stuff is that we want to float *after*
676 simplifying a RHS, not before.  If we do so naively we get quadratic
677 behaviour as things float out.
678
679 To see why it's important to do it after, consider this (real) example:
680
681         let t = f x
682         in fst t
683 ==>
684         let t = let a = e1
685                     b = e2
686                 in (a,b)
687         in fst t
688 ==>
689         let a = e1
690             b = e2
691             t = (a,b)
692         in
693         a       -- Can't inline a this round, cos it appears twice
694 ==>
695         e1
696
697 Each of the ==> steps is a round of simplification.  We'd save a
698 whole round if we float first.  This can cascade.  Consider
699
700         let f = g d
701         in \x -> ...f...
702 ==>
703         let f = let d1 = ..d.. in \y -> e
704         in \x -> ...f...
705 ==>
706         let d1 = ..d..
707         in \x -> ...(\y ->e)...
708
709 Only in this second round can the \y be applied, and it 
710 might do the same again.
711
712
713 \begin{code}
714 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
715 simplExpr env expr = simplExprC env expr (mkBoringStop expr_ty')
716                    where
717                      expr_ty' = substTy env (exprType expr)
718         -- The type in the Stop continuation, expr_ty', is usually not used
719         -- It's only needed when discarding continuations after finding
720         -- a function that returns bottom.
721         -- Hence the lazy substitution
722
723
724 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
725         -- Simplify an expression, given a continuation
726 simplExprC env expr cont 
727   = simplExprF env expr cont    `thenSmpl` \ (floats, expr) ->
728     returnSmpl (wrapFloats floats expr)
729
730 simplExprF :: SimplEnv -> InExpr -> SimplCont -> SimplM FloatsWithExpr
731         -- Simplify an expression, returning floated binds
732
733 simplExprF env (Var v)          cont = simplVar env v cont
734 simplExprF env (Lit lit)        cont = rebuild env (Lit lit) cont
735 simplExprF env expr@(Lam _ _)   cont = simplLam env expr cont
736 simplExprF env (Note note expr) cont = simplNote env note expr cont
737 simplExprF env (App fun arg)    cont = simplExprF env fun (ApplyTo NoDup arg env cont)
738
739 simplExprF env (Type ty) cont
740   = ASSERT( contIsRhsOrArg cont )
741     simplType env ty                    `thenSmpl` \ ty' ->
742     rebuild env (Type ty') cont
743
744 simplExprF env (Case scrut bndr case_ty alts) cont
745   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
746   =     -- Simplify the scrutinee with a Select continuation
747     simplExprF env scrut (Select NoDup bndr alts env cont)
748
749   | otherwise
750   =     -- If case-of-case is off, simply simplify the case expression
751         -- in a vanilla Stop context, and rebuild the result around it
752     simplExprC env scrut case_cont      `thenSmpl` \ case_expr' ->
753     rebuild env case_expr' cont
754   where
755     case_cont = Select NoDup bndr alts env (mkBoringStop case_ty')
756     case_ty'  = substTy env case_ty     -- c.f. defn of simplExpr
757
758 simplExprF env (Let (Rec pairs) body) cont
759   = simplLetBndrs env (map fst pairs)           `thenSmpl` \ (env, bndrs') -> 
760         -- NB: bndrs' don't have unfoldings or rules
761         -- We add them as we go down
762
763     simplRecBind env NotTopLevel pairs bndrs'   `thenSmpl` \ (floats, env) ->
764     addFloats env floats                        $ \ env ->
765     simplExprF env body cont
766
767 -- A non-recursive let is dealt with by simplNonRecBind
768 simplExprF env (Let (NonRec bndr rhs) body) cont
769   = simplNonRecBind env bndr rhs env (contResultType cont)      $ \ env ->
770     simplExprF env body cont
771
772
773 ---------------------------------
774 simplType :: SimplEnv -> InType -> SimplM OutType
775         -- Kept monadic just so we can do the seqType
776 simplType env ty
777   = seqType new_ty   `seq`   returnSmpl new_ty
778   where
779     new_ty = substTy env ty
780 \end{code}
781
782
783 %************************************************************************
784 %*                                                                      *
785 \subsection{Lambdas}
786 %*                                                                      *
787 %************************************************************************
788
789 \begin{code}
790 simplLam env fun cont
791   = go env fun cont
792   where
793     zap_it  = mkLamBndrZapper fun (countArgs cont)
794     cont_ty = contResultType cont
795
796         -- Type-beta reduction
797     go env (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
798       = ASSERT( isTyVar bndr )
799         tick (BetaReduction bndr)                       `thenSmpl_`
800         simplType (setInScope arg_se env) ty_arg        `thenSmpl` \ ty_arg' ->
801         go (extendTvSubst env bndr ty_arg') body body_cont
802
803         -- Ordinary beta reduction
804     go env (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
805       = tick (BetaReduction bndr)                               `thenSmpl_`
806         simplNonRecBind env (zap_it bndr) arg arg_se cont_ty    $ \ env -> 
807         go env body body_cont
808
809         -- Not enough args, so there are real lambdas left to put in the result
810     go env lam@(Lam _ _) cont
811       = simplLamBndrs env bndrs         `thenSmpl` \ (env, bndrs') ->
812         simplExpr env body              `thenSmpl` \ body' ->
813         mkLam env bndrs' body' cont     `thenSmpl` \ (floats, new_lam) ->
814         addFloats env floats            $ \ env -> 
815         rebuild env new_lam cont
816       where
817         (bndrs,body) = collectBinders lam
818
819         -- Exactly enough args
820     go env expr cont = simplExprF env expr cont
821
822 mkLamBndrZapper :: CoreExpr     -- Function
823                 -> Int          -- Number of args supplied, *including* type args
824                 -> Id -> Id     -- Use this to zap the binders
825 mkLamBndrZapper fun n_args
826   | n_args >= n_params fun = \b -> b            -- Enough args
827   | otherwise              = \b -> zapLamIdInfo b
828   where
829         -- NB: we count all the args incl type args
830         -- so we must count all the binders (incl type lambdas)
831     n_params (Note _ e) = n_params e
832     n_params (Lam b e)  = 1 + n_params e
833     n_params other      = 0::Int
834 \end{code}
835
836
837 %************************************************************************
838 %*                                                                      *
839 \subsection{Notes}
840 %*                                                                      *
841 %************************************************************************
842
843 \begin{code}
844 simplNote env (Coerce to from) body cont
845   = let
846         addCoerce s1 k1 cont    -- Drop redundant coerces.  This can happen if a polymoprhic
847                                 -- (coerce a b e) is instantiated with a=ty1 b=ty2 and the
848                                 -- two are the same. This happens a lot in Happy-generated parsers
849           | s1 `coreEqType` k1 = cont
850
851         addCoerce s1 k1 (CoerceIt t1 cont)
852                 --      coerce T1 S1 (coerce S1 K1 e)
853                 -- ==>
854                 --      e,                      if T1=K1
855                 --      coerce T1 K1 e,         otherwise
856                 --
857                 -- For example, in the initial form of a worker
858                 -- we may find  (coerce T (coerce S (\x.e))) y
859                 -- and we'd like it to simplify to e[y/x] in one round 
860                 -- of simplification
861           | t1 `coreEqType` k1  = cont                  -- The coerces cancel out
862           | otherwise           = CoerceIt t1 cont      -- They don't cancel, but 
863                                                         -- the inner one is redundant
864
865         addCoerce t1t2 s1s2 (ApplyTo dup arg arg_se cont)
866           | not (isTypeArg arg),        -- This whole case only works for value args
867                                         -- Could upgrade to have equiv thing for type apps too  
868             Just (s1, s2) <- splitFunTy_maybe s1s2
869                 --      (coerce (T1->T2) (S1->S2) F) E
870                 -- ===> 
871                 --      coerce T2 S2 (F (coerce S1 T1 E))
872                 --
873                 -- t1t2 must be a function type, T1->T2, because it's applied to something
874                 -- but s1s2 might conceivably not be
875                 --
876                 -- When we build the ApplyTo we can't mix the out-types
877                 -- with the InExpr in the argument, so we simply substitute
878                 -- to make it all consistent.  It's a bit messy.
879                 -- But it isn't a common case.
880           = let 
881                 (t1,t2) = splitFunTy t1t2
882                 new_arg = mkCoerce2 s1 t1 (substExpr arg_env arg)
883                 arg_env = setInScope arg_se env
884             in
885             ApplyTo dup new_arg (zapSubstEnv env) (addCoerce t2 s2 cont)
886                         
887         addCoerce to' _ cont = CoerceIt to' cont
888     in
889     simplType env to            `thenSmpl` \ to' ->
890     simplType env from          `thenSmpl` \ from' ->
891     simplExprF env body (addCoerce to' from' cont)
892
893                 
894 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
895 -- inlining.  All other CCCSs are mapped to currentCCS.
896 simplNote env (SCC cc) e cont
897   = simplExpr (setEnclosingCC env currentCCS) e         `thenSmpl` \ e' ->
898     rebuild env (mkSCC cc e') cont
899
900 simplNote env InlineCall e cont
901   = simplExprF env e (InlinePlease cont)
902
903 -- See notes with SimplMonad.inlineMode
904 simplNote env InlineMe e cont
905   | contIsRhsOrArg cont         -- Totally boring continuation; see notes above
906   =                             -- Don't inline inside an INLINE expression
907     simplExpr (setMode inlineMode env )  e      `thenSmpl` \ e' ->
908     rebuild env (mkInlineMe e') cont
909
910   | otherwise   -- Dissolve the InlineMe note if there's
911                 -- an interesting context of any kind to combine with
912                 -- (even a type application -- anything except Stop)
913   = simplExprF env e cont
914
915 simplNote env (CoreNote s) e cont
916   = simplExpr env e    `thenSmpl` \ e' ->
917     rebuild env (Note (CoreNote s) e') cont
918 \end{code}
919
920
921 %************************************************************************
922 %*                                                                      *
923 \subsection{Dealing with calls}
924 %*                                                                      *
925 %************************************************************************
926
927 \begin{code}
928 simplVar env var cont
929   = case substId env var of
930         DoneEx e         -> simplExprF (zapSubstEnv env) e cont
931         ContEx tvs ids e -> simplExprF (setSubstEnv env tvs ids) e cont
932         DoneId var1 occ  -> completeCall (zapSubstEnv env) var1 occ cont
933                 -- Note [zapSubstEnv]
934                 -- The template is already simplified, so don't re-substitute.
935                 -- This is VITAL.  Consider
936                 --      let x = e in
937                 --      let y = \z -> ...x... in
938                 --      \ x -> ...y...
939                 -- We'll clone the inner \x, adding x->x' in the id_subst
940                 -- Then when we inline y, we must *not* replace x by x' in
941                 -- the inlined copy!!
942
943 ---------------------------------------------------------
944 --      Dealing with a call site
945
946 completeCall env var occ_info cont
947   =     -- Simplify the arguments
948     getDOptsSmpl                                        `thenSmpl` \ dflags ->
949     let
950         chkr                           = getSwitchChecker env
951         (args, call_cont, inline_call) = getContArgs chkr var cont
952         fn_ty                          = idType var
953     in
954     simplifyArgs env fn_ty args (contResultType call_cont)      $ \ env args ->
955
956         -- Next, look for rules or specialisations that match
957         --
958         -- It's important to simplify the args first, because the rule-matcher
959         -- doesn't do substitution as it goes.  We don't want to use subst_args
960         -- (defined in the 'where') because that throws away useful occurrence info,
961         -- and perhaps-very-important specialisations.
962         --
963         -- Some functions have specialisations *and* are strict; in this case,
964         -- we don't want to inline the wrapper of the non-specialised thing; better
965         -- to call the specialised thing instead.
966         -- We used to use the black-listing mechanism to ensure that inlining of 
967         -- the wrapper didn't occur for things that have specialisations till a 
968         -- later phase, so but now we just try RULES first
969         --
970         -- You might think that we shouldn't apply rules for a loop breaker: 
971         -- doing so might give rise to an infinite loop, because a RULE is
972         -- rather like an extra equation for the function:
973         --      RULE:           f (g x) y = x+y
974         --      Eqn:            f a     y = a-y
975         --
976         -- But it's too drastic to disable rules for loop breakers.  
977         -- Even the foldr/build rule would be disabled, because foldr 
978         -- is recursive, and hence a loop breaker:
979         --      foldr k z (build g) = g k z
980         -- So it's up to the programmer: rules can cause divergence
981
982     let
983         in_scope   = getInScope env
984         rules      = getRules env
985         maybe_rule = case activeRule env of
986                         Nothing     -> Nothing  -- No rules apply
987                         Just act_fn -> lookupRule act_fn in_scope rules var args 
988     in
989     case maybe_rule of {
990         Just (rule_name, rule_rhs) -> 
991                 tick (RuleFired rule_name)                      `thenSmpl_`
992                 (if dopt Opt_D_dump_inlinings dflags then
993                    pprTrace "Rule fired" (vcat [
994                         text "Rule:" <+> ftext rule_name,
995                         text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
996                         text "After: " <+> pprCoreExpr rule_rhs,
997                         text "Cont:  " <+> ppr call_cont])
998                  else
999                         id)             $
1000                 simplExprF env rule_rhs call_cont ;
1001         
1002         Nothing ->              -- No rules
1003
1004         -- Next, look for an inlining
1005     let
1006         arg_infos = [ interestingArg arg | arg <- args, isValArg arg]
1007
1008         interesting_cont = interestingCallContext (notNull args)
1009                                                   (notNull arg_infos)
1010                                                   call_cont
1011
1012         active_inline = activeInline env var occ_info
1013         maybe_inline  = callSiteInline dflags active_inline inline_call occ_info
1014                                        var arg_infos interesting_cont
1015     in
1016     case maybe_inline of {
1017         Just unfolding          -- There is an inlining!
1018           ->  tick (UnfoldingDone var)          `thenSmpl_`
1019                 (if dopt Opt_D_dump_inlinings dflags then
1020                    pprTrace "Inlining done" (vcat [
1021                         text "Before:" <+> ppr var <+> sep (map pprParendExpr args),
1022                         text "Inlined fn: " <+> ppr unfolding,
1023                         text "Cont:  " <+> ppr call_cont])
1024                  else
1025                         id)             $
1026               makeThatCall env var unfolding args call_cont
1027
1028         ;
1029         Nothing ->              -- No inlining!
1030
1031         -- Done
1032     rebuild env (mkApps (Var var) args) call_cont
1033     }}
1034
1035 makeThatCall :: SimplEnv
1036              -> Id
1037              -> InExpr          -- Inlined function rhs 
1038              -> [OutExpr]       -- Arguments, already simplified
1039              -> SimplCont       -- After the call
1040              -> SimplM FloatsWithExpr
1041 -- Similar to simplLam, but this time 
1042 -- the arguments are already simplified
1043 makeThatCall orig_env var fun@(Lam _ _) args cont
1044   = go orig_env fun args
1045   where
1046     zap_it = mkLamBndrZapper fun (length args)
1047
1048         -- Type-beta reduction
1049     go env (Lam bndr body) (Type ty_arg : args)
1050       = ASSERT( isTyVar bndr )
1051         tick (BetaReduction bndr)                       `thenSmpl_`
1052         go (extendTvSubst env bndr ty_arg) body args
1053
1054         -- Ordinary beta reduction
1055     go env (Lam bndr body) (arg : args)
1056       = tick (BetaReduction bndr)                       `thenSmpl_`
1057         simplNonRecX env (zap_it bndr) arg              $ \ env -> 
1058         go env body args
1059
1060         -- Not enough args, so there are real lambdas left to put in the result
1061     go env fun args
1062       = simplExprF env fun (pushContArgs orig_env args cont)
1063         -- NB: orig_env; the correct environment to capture with
1064         -- the arguments.... env has been augmented with substitutions 
1065         -- from the beta reductions.
1066
1067 makeThatCall env var fun args cont
1068   = simplExprF env fun (pushContArgs env args cont)
1069 \end{code}                 
1070
1071
1072 %************************************************************************
1073 %*                                                                      *
1074 \subsection{Arguments}
1075 %*                                                                      *
1076 %************************************************************************
1077
1078 \begin{code}
1079 ---------------------------------------------------------
1080 --      Simplifying the arguments of a call
1081
1082 simplifyArgs :: SimplEnv 
1083              -> OutType                         -- Type of the function
1084              -> [(InExpr, SimplEnv, Bool)]      -- Details of the arguments
1085              -> OutType                         -- Type of the continuation
1086              -> (SimplEnv -> [OutExpr] -> SimplM FloatsWithExpr)
1087              -> SimplM FloatsWithExpr
1088
1089 -- [CPS-like because of strict arguments]
1090
1091 -- Simplify the arguments to a call.
1092 -- This part of the simplifier may break the no-shadowing invariant
1093 -- Consider
1094 --      f (...(\a -> e)...) (case y of (a,b) -> e')
1095 -- where f is strict in its second arg
1096 -- If we simplify the innermost one first we get (...(\a -> e)...)
1097 -- Simplifying the second arg makes us float the case out, so we end up with
1098 --      case y of (a,b) -> f (...(\a -> e)...) e'
1099 -- So the output does not have the no-shadowing invariant.  However, there is
1100 -- no danger of getting name-capture, because when the first arg was simplified
1101 -- we used an in-scope set that at least mentioned all the variables free in its
1102 -- static environment, and that is enough.
1103 --
1104 -- We can't just do innermost first, or we'd end up with a dual problem:
1105 --      case x of (a,b) -> f e (...(\a -> e')...)
1106 --
1107 -- I spent hours trying to recover the no-shadowing invariant, but I just could
1108 -- not think of an elegant way to do it.  The simplifier is already knee-deep in
1109 -- continuations.  We have to keep the right in-scope set around; AND we have
1110 -- to get the effect that finding (error "foo") in a strict arg position will
1111 -- discard the entire application and replace it with (error "foo").  Getting
1112 -- all this at once is TOO HARD!
1113
1114 simplifyArgs env fn_ty args cont_ty thing_inside
1115   = go env fn_ty args thing_inside
1116   where
1117     go env fn_ty []         thing_inside = thing_inside env []
1118     go env fn_ty (arg:args) thing_inside = simplifyArg env fn_ty arg cont_ty            $ \ env arg' ->
1119                                            go env (applyTypeToArg fn_ty arg') args      $ \ env args' ->
1120                                            thing_inside env (arg':args')
1121
1122 simplifyArg env fn_ty (Type ty_arg, se, _) cont_ty thing_inside
1123   = simplType (setInScope se env) ty_arg        `thenSmpl` \ new_ty_arg ->
1124     thing_inside env (Type new_ty_arg)
1125
1126 simplifyArg env fn_ty (val_arg, arg_se, is_strict) cont_ty thing_inside 
1127   | is_strict 
1128   = simplStrictArg AnArg env val_arg arg_se arg_ty cont_ty thing_inside
1129
1130   | otherwise   -- Lazy argument
1131                 -- DO NOT float anything outside, hence simplExprC
1132                 -- There is no benefit (unlike in a let-binding), and we'd
1133                 -- have to be very careful about bogus strictness through 
1134                 -- floating a demanded let.
1135   = simplExprC (setInScope arg_se env) val_arg
1136                (mkBoringStop arg_ty)            `thenSmpl` \ arg1 ->
1137    thing_inside env arg1
1138   where
1139     arg_ty = funArgTy fn_ty
1140
1141
1142 simplStrictArg ::  LetRhsFlag
1143                 -> SimplEnv             -- The env of the call
1144                 -> InExpr -> SimplEnv   -- The arg plus its env
1145                 -> OutType              -- arg_ty: type of the argument
1146                 -> OutType              -- cont_ty: Type of thing computed by the context
1147                 -> (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)       
1148                                         -- Takes an expression of type rhs_ty, 
1149                                         -- returns an expression of type cont_ty
1150                                         -- The env passed to this continuation is the
1151                                         -- env of the call, plus any new in-scope variables
1152                 -> SimplM FloatsWithExpr        -- An expression of type cont_ty
1153
1154 simplStrictArg is_rhs call_env arg arg_env arg_ty cont_ty thing_inside
1155   = simplExprF (setInScope arg_env call_env) arg
1156                (ArgOf is_rhs arg_ty cont_ty (\ new_env -> thing_inside (setInScope call_env new_env)))
1157   -- Notice the way we use arg_env (augmented with in-scope vars from call_env) 
1158   --    to simplify the argument
1159   -- and call-env (augmented with in-scope vars from the arg) to pass to the continuation
1160 \end{code}
1161
1162
1163 %************************************************************************
1164 %*                                                                      *
1165 \subsection{mkAtomicArgs}
1166 %*                                                                      *
1167 %************************************************************************
1168
1169 mkAtomicArgs takes a putative RHS, checks whether it's a PAP or
1170 constructor application and, if so, converts it to ANF, so that the 
1171 resulting thing can be inlined more easily.  Thus
1172         x = (f a, g b)
1173 becomes
1174         t1 = f a
1175         t2 = g b
1176         x = (t1,t2)
1177
1178 There are three sorts of binding context, specified by the two
1179 boolean arguments
1180
1181 Strict
1182    OK-unlifted
1183
1184 N  N    Top-level or recursive                  Only bind args of lifted type
1185
1186 N  Y    Non-top-level and non-recursive,        Bind args of lifted type, or
1187                 but lazy                        unlifted-and-ok-for-speculation
1188
1189 Y  Y    Non-top-level, non-recursive,           Bind all args
1190                  and strict (demanded)
1191         
1192
1193 For example, given
1194
1195         x = MkC (y div# z)
1196
1197 there is no point in transforming to
1198
1199         x = case (y div# z) of r -> MkC r
1200
1201 because the (y div# z) can't float out of the let. But if it was
1202 a *strict* let, then it would be a good thing to do.  Hence the
1203 context information.
1204
1205 \begin{code}
1206 mkAtomicArgs :: Bool    -- A strict binding
1207              -> Bool    -- OK to float unlifted args
1208              -> OutExpr
1209              -> SimplM (OrdList (OutId,OutExpr),  -- The floats (unusually) may include
1210                         OutExpr)                  -- things that need case-binding,
1211                                                   -- if the strict-binding flag is on
1212
1213 mkAtomicArgs is_strict ok_float_unlifted rhs
1214   | (Var fun, args) <- collectArgs rhs,                         -- It's an application
1215     isDataConWorkId fun || valArgCount args < idArity fun       -- And it's a constructor or PAP
1216   = go fun nilOL [] args        -- Have a go
1217
1218   | otherwise = bale_out        -- Give up
1219
1220   where
1221     bale_out = returnSmpl (nilOL, rhs)
1222
1223     go fun binds rev_args [] 
1224         = returnSmpl (binds, mkApps (Var fun) (reverse rev_args))
1225
1226     go fun binds rev_args (arg : args) 
1227         | exprIsTrivial arg     -- Easy case
1228         = go fun binds (arg:rev_args) args
1229
1230         | not can_float_arg     -- Can't make this arg atomic
1231         = bale_out              -- ... so give up
1232
1233         | otherwise     -- Don't forget to do it recursively
1234                         -- E.g.  x = a:b:c:[]
1235         =  mkAtomicArgs is_strict ok_float_unlifted arg `thenSmpl` \ (arg_binds, arg') ->
1236            newId FSLIT("a") arg_ty                      `thenSmpl` \ arg_id ->
1237            go fun ((arg_binds `snocOL` (arg_id,arg')) `appOL` binds) 
1238               (Var arg_id : rev_args) args
1239         where
1240           arg_ty        = exprType arg
1241           can_float_arg =  is_strict 
1242                         || not (isUnLiftedType arg_ty)
1243                         || (ok_float_unlifted && exprOkForSpeculation arg)
1244
1245
1246 addAtomicBinds :: SimplEnv -> [(OutId,OutExpr)]
1247                -> (SimplEnv -> SimplM (FloatsWith a))
1248                -> SimplM (FloatsWith a)
1249 addAtomicBinds env []         thing_inside = thing_inside env
1250 addAtomicBinds env ((v,r):bs) thing_inside = addAuxiliaryBind env (NonRec v r) $ \ env -> 
1251                                              addAtomicBinds env bs thing_inside
1252
1253 addAtomicBindsE :: SimplEnv -> [(OutId,OutExpr)]
1254                 -> (SimplEnv -> SimplM FloatsWithExpr)
1255                 -> SimplM FloatsWithExpr
1256 -- Same again, but this time we're in an expression context,
1257 -- and may need to do some case bindings
1258
1259 addAtomicBindsE env [] thing_inside 
1260   = thing_inside env
1261 addAtomicBindsE env ((v,r):bs) thing_inside 
1262   | needsCaseBinding (idType v) r
1263   = addAtomicBindsE (addNewInScopeIds env [v]) bs thing_inside  `thenSmpl` \ (floats, expr) ->
1264     WARN( exprIsTrivial expr, ppr v <+> pprCoreExpr expr )
1265     (let body = wrapFloats floats expr in 
1266      returnSmpl (emptyFloats env, Case r v (exprType body) [(DEFAULT,[],body)]))
1267
1268   | otherwise
1269   = addAuxiliaryBind env (NonRec v r)   $ \ env -> 
1270     addAtomicBindsE env bs thing_inside
1271 \end{code}
1272
1273
1274 %************************************************************************
1275 %*                                                                      *
1276 \subsection{The main rebuilder}
1277 %*                                                                      *
1278 %************************************************************************
1279
1280 \begin{code}
1281 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
1282
1283 rebuild env expr (Stop _ _ _)                 = rebuildDone env expr
1284 rebuild env expr (ArgOf _ _ _ cont_fn)        = cont_fn env expr
1285 rebuild env expr (CoerceIt to_ty cont)        = rebuild env (mkCoerce to_ty expr) cont
1286 rebuild env expr (InlinePlease cont)          = rebuild env (Note InlineCall expr) cont
1287 rebuild env expr (Select _ bndr alts se cont) = rebuildCase (setInScope se env) expr bndr alts cont
1288 rebuild env expr (ApplyTo _ arg se cont)      = rebuildApp  (setInScope se env) expr arg cont
1289
1290 rebuildApp env fun arg cont
1291   = simplExpr env arg   `thenSmpl` \ arg' ->
1292     rebuild env (App fun arg') cont
1293
1294 rebuildDone env expr = returnSmpl (emptyFloats env, expr)
1295 \end{code}
1296
1297
1298 %************************************************************************
1299 %*                                                                      *
1300 \subsection{Functions dealing with a case}
1301 %*                                                                      *
1302 %************************************************************************
1303
1304 Blob of helper functions for the "case-of-something-else" situation.
1305
1306 \begin{code}
1307 ---------------------------------------------------------
1308 --      Eliminate the case if possible
1309
1310 rebuildCase :: SimplEnv
1311             -> OutExpr          -- Scrutinee
1312             -> InId             -- Case binder
1313             -> [InAlt]          -- Alternatives (inceasing order)
1314             -> SimplCont
1315             -> SimplM FloatsWithExpr
1316
1317 rebuildCase env scrut case_bndr alts cont
1318   | Just (con,args) <- exprIsConApp_maybe scrut 
1319         -- Works when the scrutinee is a variable with a known unfolding
1320         -- as well as when it's an explicit constructor application
1321   = knownCon env (DataAlt con) args case_bndr alts cont
1322
1323   | Lit lit <- scrut    -- No need for same treatment as constructors
1324                         -- because literals are inlined more vigorously
1325   = knownCon env (LitAlt lit) [] case_bndr alts cont
1326
1327   | otherwise
1328   =     -- Prepare the alternatives.
1329     prepareAlts scrut case_bndr alts            `thenSmpl` \ (better_alts, handled_cons) -> 
1330         
1331         -- Prepare the continuation;
1332         -- The new subst_env is in place
1333     prepareCaseCont env better_alts cont        `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1334     addFloats env floats                        $ \ env ->      
1335
1336     let
1337         -- The case expression is annotated with the result type of the continuation
1338         -- This may differ from the type originally on the case.  For example
1339         --      case(T) (case(Int#) a of { True -> 1#; False -> 0# }) of
1340         --         a# -> <blob>
1341         -- ===>
1342         --      let j a# = <blob>
1343         --      in case(T) a of { True -> j 1#; False -> j 0# }
1344         -- Note that the case that scrutinises a now returns a T not an Int#
1345         res_ty' = contResultType dup_cont
1346     in
1347
1348         -- Deal with case binder
1349     simplCaseBinder env scrut case_bndr         `thenSmpl` \ (alt_env, case_bndr') ->
1350
1351         -- Deal with the case alternatives
1352     simplAlts alt_env handled_cons
1353               case_bndr' better_alts dup_cont   `thenSmpl` \ alts' ->
1354
1355         -- Put the case back together
1356     mkCase scrut case_bndr' res_ty' alts'       `thenSmpl` \ case_expr ->
1357
1358         -- Notice that rebuildDone returns the in-scope set from env, not alt_env
1359         -- The case binder *not* scope over the whole returned case-expression
1360     rebuild env case_expr nondup_cont
1361 \end{code}
1362
1363 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1364 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1365 way, there's a chance that v will now only be used once, and hence
1366 inlined.
1367
1368 Note 1
1369 ~~~~~~
1370 There is a time we *don't* want to do that, namely when
1371 -fno-case-of-case is on.  This happens in the first simplifier pass,
1372 and enhances full laziness.  Here's the bad case:
1373         f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1374 If we eliminate the inner case, we trap it inside the I# v -> arm,
1375 which might prevent some full laziness happening.  I've seen this
1376 in action in spectral/cichelli/Prog.hs:
1377          [(m,n) | m <- [1..max], n <- [1..max]]
1378 Hence the check for NoCaseOfCase.
1379
1380 Note 2
1381 ~~~~~~
1382 There is another situation when we don't want to do it.  If we have
1383
1384     case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1385                    ...other cases .... }
1386
1387 We'll perform the binder-swap for the outer case, giving
1388
1389     case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 } 
1390                    ...other cases .... }
1391
1392 But there is no point in doing it for the inner case, because w1 can't
1393 be inlined anyway.  Furthermore, doing the case-swapping involves
1394 zapping w2's occurrence info (see paragraphs that follow), and that
1395 forces us to bind w2 when doing case merging.  So we get
1396
1397     case x of w1 { A -> let w2 = w1 in e1
1398                    B -> let w2 = w1 in e2
1399                    ...other cases .... }
1400
1401 This is plain silly in the common case where w2 is dead.
1402
1403 Even so, I can't see a good way to implement this idea.  I tried
1404 not doing the binder-swap if the scrutinee was already evaluated
1405 but that failed big-time:
1406
1407         data T = MkT !Int
1408
1409         case v of w  { MkT x ->
1410         case x of x1 { I# y1 ->
1411         case x of x2 { I# y2 -> ...
1412
1413 Notice that because MkT is strict, x is marked "evaluated".  But to
1414 eliminate the last case, we must either make sure that x (as well as
1415 x1) has unfolding MkT y1.  THe straightforward thing to do is to do
1416 the binder-swap.  So this whole note is a no-op.
1417
1418 Note 3
1419 ~~~~~~
1420 If we replace the scrutinee, v, by tbe case binder, then we have to nuke
1421 any occurrence info (eg IAmDead) in the case binder, because the
1422 case-binder now effectively occurs whenever v does.  AND we have to do
1423 the same for the pattern-bound variables!  Example:
1424
1425         (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1426
1427 Here, b and p are dead.  But when we move the argment inside the first
1428 case RHS, and eliminate the second case, we get
1429
1430         case x of { (a,b) -> a b }
1431
1432 Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
1433 happened.  
1434
1435 Indeed, this can happen anytime the case binder isn't dead:
1436         case <any> of x { (a,b) -> 
1437         case x of { (p,q) -> p } }
1438 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1439 The point is that we bring into the envt a binding
1440         let x = (a,b) 
1441 after the outer case, and that makes (a,b) alive.  At least we do unless
1442 the case binder is guaranteed dead.
1443
1444 \begin{code}
1445 simplCaseBinder env (Var v) case_bndr
1446   | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
1447
1448 -- Failed try [see Note 2 above]
1449 --     not (isEvaldUnfolding (idUnfolding v))
1450
1451   = simplBinder env (zap case_bndr)             `thenSmpl` \ (env, case_bndr') ->
1452     returnSmpl (modifyInScope env v case_bndr', case_bndr')
1453         -- We could extend the substitution instead, but it would be
1454         -- a hack because then the substitution wouldn't be idempotent
1455         -- any more (v is an OutId).  And this does just as well.
1456   where
1457     zap b = b `setIdOccInfo` NoOccInfo
1458             
1459 simplCaseBinder env other_scrut case_bndr 
1460   = simplBinder env case_bndr           `thenSmpl` \ (env, case_bndr') ->
1461     returnSmpl (env, case_bndr')
1462 \end{code}
1463
1464
1465
1466 \begin{code}
1467 simplAlts :: SimplEnv 
1468           -> [AltCon]                   -- Alternatives the scrutinee can't be
1469                                         -- in the default case
1470           -> OutId                      -- Case binder
1471           -> [InAlt] -> SimplCont
1472           -> SimplM [OutAlt]            -- Includes the continuation
1473
1474 simplAlts env handled_cons case_bndr' alts cont'
1475   = do  { mb_alts <- mapSmpl simpl_alt alts
1476         ; return [alt' | Just (_, alt') <- mb_alts] }
1477         -- Filter out the alternatives that are inaccessible
1478   where
1479     simpl_alt alt = simplAlt env handled_cons case_bndr' alt cont'
1480
1481 simplAlt :: SimplEnv -> [AltCon] -> OutId -> InAlt -> SimplCont
1482          -> SimplM (Maybe (TvSubstEnv, OutAlt))
1483 -- Simplify an alternative, returning the type refinement for the 
1484 -- alternative, if the alternative does any refinement at all
1485 -- Nothing => the alternative is inaccessible
1486
1487 simplAlt env handled_cons case_bndr' (DEFAULT, bndrs, rhs) cont'
1488   = ASSERT( null bndrs )
1489     simplExprC env' rhs cont'   `thenSmpl` \ rhs' ->
1490     returnSmpl (Just (emptyVarEnv, (DEFAULT, [], rhs')))
1491   where
1492     env' = mk_rhs_env env case_bndr' (mkOtherCon handled_cons)
1493         -- Record the constructors that the case-binder *can't* be.
1494
1495 simplAlt env handled_cons case_bndr' (LitAlt lit, bndrs, rhs) cont'
1496   = ASSERT( null bndrs )
1497     simplExprC env' rhs cont'   `thenSmpl` \ rhs' ->
1498     returnSmpl (Just (emptyVarEnv, (LitAlt lit, [], rhs')))
1499   where
1500     env' = mk_rhs_env env case_bndr' (mkUnfolding False (Lit lit))
1501
1502 simplAlt env handled_cons case_bndr' (DataAlt con, vs, rhs) cont'
1503   | isVanillaDataCon con
1504   =     -- Deal with the pattern-bound variables
1505         -- Mark the ones that are in ! positions in the data constructor
1506         -- as certainly-evaluated.
1507         -- NB: it happens that simplBinders does *not* erase the OtherCon
1508         --     form of unfolding, so it's ok to add this info before 
1509         --     doing simplBinders
1510     simplBinders env (add_evals con vs)         `thenSmpl` \ (env, vs') ->
1511
1512                 -- Bind the case-binder to (con args)
1513     let unf       = mkUnfolding False (mkConApp con con_args)
1514         inst_tys' = tyConAppArgs (idType case_bndr')
1515         con_args  = map Type inst_tys' ++ map varToCoreExpr vs' 
1516         env'      = mk_rhs_env env case_bndr' unf
1517     in
1518     simplExprC env' rhs cont'   `thenSmpl` \ rhs' ->
1519     returnSmpl (Just (emptyVarEnv, (DataAlt con, vs', rhs')))
1520
1521   | otherwise   -- GADT case
1522   = let
1523         (tvs,ids) = span isTyVar vs
1524     in
1525     simplBinders env tvs                        `thenSmpl` \ (env1, tvs') ->
1526     case coreRefineTys con tvs' (idType case_bndr') of {
1527         Nothing         -- Inaccessible
1528             | opt_PprStyle_Debug        -- Hack: if debugging is on, generate an error case 
1529                                         --       so we can see it
1530             ->  let rhs' = mkApps (Var eRROR_ID) 
1531                                 [Type (substTy env (exprType rhs)),
1532                                  Lit (mkStringLit "Impossible alternative (GADT)")]
1533                 in 
1534                 simplBinders env1 ids           `thenSmpl` \ (env2, ids') -> 
1535                 returnSmpl (Just (emptyVarEnv, (DataAlt con, tvs' ++ ids', rhs'))) 
1536
1537             | otherwise -- Filter out the inaccessible branch
1538             -> return Nothing ; 
1539
1540         Just refine@(tv_subst_env, _) ->        -- The normal case
1541
1542     let 
1543         env2 = refineSimplEnv env1 refine
1544         -- Simplify the Ids in the refined environment, so their types
1545         -- reflect the refinement.  Usually this doesn't matter, but it helps
1546         -- in mkDupableAlt, when we want to float a lambda that uses these binders
1547         -- Furthermore, it means the binders contain maximal type information
1548     in
1549     simplBinders env2 (add_evals con ids)       `thenSmpl` \ (env3, ids') ->
1550     let unf        = mkUnfolding False con_app
1551         con_app    = mkConApp con con_args
1552         con_args   = map varToCoreExpr vs'      -- NB: no inst_tys'
1553         env_w_unf  = mk_rhs_env env3 case_bndr' unf
1554         vs'        = tvs' ++ ids'
1555     in
1556     simplExprC env_w_unf rhs cont'      `thenSmpl` \ rhs' ->
1557     returnSmpl (Just (tv_subst_env, (DataAlt con, vs', rhs'))) }
1558
1559   where
1560         -- add_evals records the evaluated-ness of the bound variables of
1561         -- a case pattern.  This is *important*.  Consider
1562         --      data T = T !Int !Int
1563         --
1564         --      case x of { T a b -> T (a+1) b }
1565         --
1566         -- We really must record that b is already evaluated so that we don't
1567         -- go and re-evaluate it when constructing the result.
1568     add_evals dc vs = cat_evals dc vs (dataConRepStrictness dc)
1569
1570     cat_evals dc vs strs
1571         = go vs strs
1572         where
1573           go [] [] = []
1574           go (v:vs) strs | isTyVar v = v : go vs strs
1575           go (v:vs) (str:strs)
1576             | isMarkedStrict str = evald_v  : go vs strs
1577             | otherwise          = zapped_v : go vs strs
1578             where
1579               zapped_v = zap_occ_info v
1580               evald_v  = zapped_v `setIdUnfolding` evaldUnfolding
1581           go _ _ = pprPanic "cat_evals" (ppr dc $$ ppr vs $$ ppr strs)
1582
1583         -- If the case binder is alive, then we add the unfolding
1584         --      case_bndr = C vs
1585         -- to the envt; so vs are now very much alive
1586     zap_occ_info | isDeadBinder case_bndr' = \id -> id
1587                  | otherwise               = \id -> id `setIdOccInfo` NoOccInfo
1588
1589 mk_rhs_env env case_bndr' case_bndr_unf
1590   = modifyInScope env case_bndr' (case_bndr' `setIdUnfolding` case_bndr_unf)
1591 \end{code}
1592
1593
1594 %************************************************************************
1595 %*                                                                      *
1596 \subsection{Known constructor}
1597 %*                                                                      *
1598 %************************************************************************
1599
1600 We are a bit careful with occurrence info.  Here's an example
1601
1602         (\x* -> case x of (a*, b) -> f a) (h v, e)
1603
1604 where the * means "occurs once".  This effectively becomes
1605         case (h v, e) of (a*, b) -> f a)
1606 and then
1607         let a* = h v; b = e in f a
1608 and then
1609         f (h v)
1610
1611 All this should happen in one sweep.
1612
1613 \begin{code}
1614 knownCon :: SimplEnv -> AltCon -> [OutExpr]
1615          -> InId -> [InAlt] -> SimplCont
1616          -> SimplM FloatsWithExpr
1617
1618 knownCon env con args bndr alts cont
1619   = tick (KnownBranch bndr)     `thenSmpl_`
1620     case findAlt con alts of
1621         (DEFAULT, bs, rhs)     -> ASSERT( null bs )
1622                                   simplNonRecX env bndr scrut   $ \ env ->
1623                                         -- This might give rise to a binding with non-atomic args
1624                                         -- like x = Node (f x) (g x)
1625                                         -- but no harm will be done
1626                                   simplExprF env rhs cont
1627                                 where
1628                                   scrut = case con of
1629                                             LitAlt lit -> Lit lit
1630                                             DataAlt dc -> mkConApp dc args
1631
1632         (LitAlt lit, bs, rhs) ->  ASSERT( null bs )
1633                                   simplNonRecX env bndr (Lit lit)       $ \ env ->
1634                                   simplExprF env rhs cont
1635
1636         (DataAlt dc, bs, rhs)  
1637                 -> ASSERT( n_drop_tys + length bs == length args )
1638                    bind_args env bs (drop n_drop_tys args)      $ \ env ->
1639                    let
1640                         con_app  = mkConApp dc (take n_drop_tys args ++ con_args)
1641                         con_args = [substExpr env (varToCoreExpr b) | b <- bs]
1642                                         -- args are aready OutExprs, but bs are InIds
1643                    in
1644                    simplNonRecX env bndr con_app                $ \ env ->
1645                    simplExprF env rhs cont
1646                 where
1647                    n_drop_tys | isVanillaDataCon dc = tyConArity (dataConTyCon dc)
1648                               | otherwise           = 0
1649                         -- Vanilla data constructors lack type arguments in the pattern
1650
1651 -- Ugh!
1652 bind_args env [] _ thing_inside = thing_inside env
1653
1654 bind_args env (b:bs) (Type ty : args) thing_inside
1655   = ASSERT( isTyVar b )
1656     bind_args (extendTvSubst env b ty) bs args thing_inside
1657     
1658 bind_args env (b:bs) (arg : args) thing_inside
1659   = ASSERT( isId b )
1660     simplNonRecX env b arg      $ \ env ->
1661     bind_args env bs args thing_inside
1662 \end{code}
1663
1664
1665 %************************************************************************
1666 %*                                                                      *
1667 \subsection{Duplicating continuations}
1668 %*                                                                      *
1669 %************************************************************************
1670
1671 \begin{code}
1672 prepareCaseCont :: SimplEnv
1673                 -> [InAlt] -> SimplCont
1674                 -> SimplM (FloatsWith (SimplCont,SimplCont))    
1675                         -- Return a duplicatable continuation, a non-duplicable part 
1676                         -- plus some extra bindings
1677
1678         -- No need to make it duplicatable if there's only one alternative
1679 prepareCaseCont env [alt] cont = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1680 prepareCaseCont env alts  cont = mkDupableCont env cont
1681 \end{code}
1682
1683 \begin{code}
1684 mkDupableCont :: SimplEnv -> SimplCont 
1685               -> SimplM (FloatsWith (SimplCont, SimplCont))
1686
1687 mkDupableCont env cont
1688   | contIsDupable cont
1689   = returnSmpl (emptyFloats env, (cont, mkBoringStop (contResultType cont)))
1690
1691 mkDupableCont env (CoerceIt ty cont)
1692   = mkDupableCont env cont              `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1693     returnSmpl (floats, (CoerceIt ty dup_cont, nondup_cont))
1694
1695 mkDupableCont env (InlinePlease cont)
1696   = mkDupableCont env cont              `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1697     returnSmpl (floats, (InlinePlease dup_cont, nondup_cont))
1698
1699 mkDupableCont env cont@(ArgOf _ arg_ty _ _)
1700   =  returnSmpl (emptyFloats env, (mkBoringStop arg_ty, cont))
1701         -- Do *not* duplicate an ArgOf continuation
1702         -- Because ArgOf continuations are opaque, we gain nothing by
1703         -- propagating them into the expressions, and we do lose a lot.
1704         -- Here's an example:
1705         --      && (case x of { T -> F; F -> T }) E
1706         -- Now, && is strict so we end up simplifying the case with
1707         -- an ArgOf continuation.  If we let-bind it, we get
1708         --
1709         --      let $j = \v -> && v E
1710         --      in simplExpr (case x of { T -> F; F -> T })
1711         --                   (ArgOf (\r -> $j r)
1712         -- And after simplifying more we get
1713         --
1714         --      let $j = \v -> && v E
1715         --      in case of { T -> $j F; F -> $j T }
1716         -- Which is a Very Bad Thing
1717         --
1718         -- The desire not to duplicate is the entire reason that
1719         -- mkDupableCont returns a pair of continuations.
1720         --
1721         -- The original plan had:
1722         -- e.g.         (...strict-fn...) [...hole...]
1723         --      ==>
1724         --              let $j = \a -> ...strict-fn...
1725         --              in $j [...hole...]
1726
1727 mkDupableCont env (ApplyTo _ arg se cont)
1728   =     -- e.g.         [...hole...] (...arg...)
1729         --      ==>
1730         --              let a = ...arg... 
1731         --              in [...hole...] a
1732     simplExpr (setInScope se env) arg                   `thenSmpl` \ arg' ->
1733
1734     mkDupableCont env cont                              `thenSmpl` \ (floats, (dup_cont, nondup_cont)) ->
1735     addFloats env floats                                $ \ env ->
1736
1737     if exprIsDupable arg' then
1738         returnSmpl (emptyFloats env, (ApplyTo OkToDup arg' (zapSubstEnv se) dup_cont, nondup_cont))
1739     else
1740     newId FSLIT("a") (exprType arg')                    `thenSmpl` \ arg_id ->
1741
1742     tick (CaseOfCase arg_id)                            `thenSmpl_`
1743         -- Want to tick here so that we go round again,
1744         -- and maybe copy or inline the code.
1745         -- Not strictly CaseOfCase, but never mind
1746
1747     returnSmpl (unitFloat env arg_id arg', 
1748                 (ApplyTo OkToDup (Var arg_id) (zapSubstEnv se) dup_cont,
1749                  nondup_cont))
1750         -- But what if the arg should be case-bound? 
1751         -- This has been this way for a long time, so I'll leave it,
1752         -- but I can't convince myself that it's right.
1753
1754 mkDupableCont env (Select _ case_bndr alts se cont)
1755   =     -- e.g.         (case [...hole...] of { pi -> ei })
1756         --      ===>
1757         --              let ji = \xij -> ei 
1758         --              in case [...hole...] of { pi -> ji xij }
1759     tick (CaseOfCase case_bndr)                                 `thenSmpl_`
1760     let
1761         alt_env = setInScope se env
1762     in
1763     prepareCaseCont alt_env alts cont                           `thenSmpl` \ (floats1, (dup_cont, nondup_cont)) ->
1764     addFloats alt_env floats1                                   $ \ alt_env ->
1765
1766     simplBinder alt_env case_bndr                               `thenSmpl` \ (alt_env, case_bndr') ->
1767         -- NB: simplBinder does not zap deadness occ-info, so
1768         -- a dead case_bndr' will still advertise its deadness
1769         -- This is really important because in
1770         --      case e of b { (# a,b #) -> ... }
1771         -- b is always dead, and indeed we are not allowed to bind b to (# a,b #),
1772         -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
1773         -- In the new alts we build, we have the new case binder, so it must retain
1774         -- its deadness.
1775
1776     mkDupableAlts alt_env case_bndr' alts dup_cont      `thenSmpl` \ (floats2, alts') ->
1777     addFloats alt_env floats2                           $ \ alt_env ->
1778     returnSmpl (emptyFloats alt_env, 
1779                 (Select OkToDup case_bndr' alts' (zapSubstEnv se) 
1780                         (mkBoringStop (contResultType dup_cont)),
1781                  nondup_cont))
1782
1783 mkDupableAlts :: SimplEnv -> OutId -> [InAlt] -> SimplCont
1784               -> SimplM (FloatsWith [InAlt])
1785 -- Absorbs the continuation into the new alternatives
1786
1787 mkDupableAlts env case_bndr' alts dupable_cont 
1788   = go env alts
1789   where
1790     go env [] = returnSmpl (emptyFloats env, [])
1791     go env (alt:alts)
1792         = do { (floats1, mb_alt') <- mkDupableAlt env case_bndr' dupable_cont alt
1793              ; addFloats env floats1    $ \ env -> do
1794              { (floats2, alts') <- go env alts
1795              ; returnSmpl (floats2, case mb_alt' of
1796                                         Just alt' -> alt' : alts'
1797                                         Nothing   -> alts'
1798                           )}}
1799                                         
1800 mkDupableAlt env case_bndr' cont alt
1801   = simplAlt env [] case_bndr' alt cont         `thenSmpl` \ mb_stuff ->
1802     case mb_stuff of {
1803         Nothing -> returnSmpl (emptyFloats env, Nothing) ;
1804
1805         Just (reft, (con, bndrs', rhs')) ->
1806         -- Safe to say that there are no handled-cons for the DEFAULT case
1807
1808     if exprIsDupable rhs' then
1809         returnSmpl (emptyFloats env, Just (con, bndrs', rhs'))
1810         -- It is worth checking for a small RHS because otherwise we
1811         -- get extra let bindings that may cause an extra iteration of the simplifier to
1812         -- inline back in place.  Quite often the rhs is just a variable or constructor.
1813         -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1814         -- iterations because the version with the let bindings looked big, and so wasn't
1815         -- inlined, but after the join points had been inlined it looked smaller, and so
1816         -- was inlined.
1817         --
1818         -- NB: we have to check the size of rhs', not rhs. 
1819         -- Duplicating a small InAlt might invalidate occurrence information
1820         -- However, if it *is* dupable, we return the *un* simplified alternative,
1821         -- because otherwise we'd need to pair it up with an empty subst-env....
1822         -- but we only have one env shared between all the alts.
1823         -- (Remember we must zap the subst-env before re-simplifying something).
1824         -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1825
1826     else
1827     let
1828         rhs_ty'     = exprType rhs'
1829         used_bndrs' = filter abstract_over (case_bndr' : bndrs')
1830         abstract_over bndr
1831           | isTyVar bndr = not (bndr `elemVarEnv` reft)
1832                 -- Don't abstract over tyvar binders which are refined away
1833                 -- See Note [Refinement] below
1834           | otherwise    = not (isDeadBinder bndr)
1835                 -- The deadness info on the new Ids is preserved by simplBinders
1836     in
1837         -- If we try to lift a primitive-typed something out
1838         -- for let-binding-purposes, we will *caseify* it (!),
1839         -- with potentially-disastrous strictness results.  So
1840         -- instead we turn it into a function: \v -> e
1841         -- where v::State# RealWorld#.  The value passed to this function
1842         -- is realworld#, which generates (almost) no code.
1843
1844         -- There's a slight infelicity here: we pass the overall 
1845         -- case_bndr to all the join points if it's used in *any* RHS,
1846         -- because we don't know its usage in each RHS separately
1847
1848         -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1849         -- we make the join point into a function whenever used_bndrs'
1850         -- is empty.  This makes the join-point more CPR friendly. 
1851         -- Consider:    let j = if .. then I# 3 else I# 4
1852         --              in case .. of { A -> j; B -> j; C -> ... }
1853         --
1854         -- Now CPR doesn't w/w j because it's a thunk, so
1855         -- that means that the enclosing function can't w/w either,
1856         -- which is a lose.  Here's the example that happened in practice:
1857         --      kgmod :: Int -> Int -> Int
1858         --      kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1859         --                  then 78
1860         --                  else 5
1861         --
1862         -- I have seen a case alternative like this:
1863         --      True -> \v -> ...
1864         -- It's a bit silly to add the realWorld dummy arg in this case, making
1865         --      $j = \s v -> ...
1866         --         True -> $j s
1867         -- (the \v alone is enough to make CPR happy) but I think it's rare
1868
1869     ( if not (any isId used_bndrs')
1870         then newId FSLIT("w") realWorldStatePrimTy      `thenSmpl` \ rw_id ->
1871              returnSmpl ([rw_id], [Var realWorldPrimId])
1872         else 
1873              returnSmpl (used_bndrs', map varToCoreExpr used_bndrs')
1874     )                                                   `thenSmpl` \ (final_bndrs', final_args) ->
1875
1876         -- See comment about "$j" name above
1877     newId FSLIT("$j") (mkPiTypes final_bndrs' rhs_ty')  `thenSmpl` \ join_bndr ->
1878         -- Notice the funky mkPiTypes.  If the contructor has existentials
1879         -- it's possible that the join point will be abstracted over
1880         -- type varaibles as well as term variables.
1881         --  Example:  Suppose we have
1882         --      data T = forall t.  C [t]
1883         --  Then faced with
1884         --      case (case e of ...) of
1885         --          C t xs::[t] -> rhs
1886         --  We get the join point
1887         --      let j :: forall t. [t] -> ...
1888         --          j = /\t \xs::[t] -> rhs
1889         --      in
1890         --      case (case e of ...) of
1891         --          C t xs::[t] -> j t xs
1892     let 
1893         -- We make the lambdas into one-shot-lambdas.  The
1894         -- join point is sure to be applied at most once, and doing so
1895         -- prevents the body of the join point being floated out by
1896         -- the full laziness pass
1897         really_final_bndrs     = map one_shot final_bndrs'
1898         one_shot v | isId v    = setOneShotLambda v
1899                    | otherwise = v
1900         join_rhs  = mkLams really_final_bndrs rhs'
1901         join_call = mkApps (Var join_bndr) final_args
1902     in
1903     returnSmpl (unitFloat env join_bndr join_rhs, Just (con, bndrs', join_call)) }
1904 \end{code}
1905
1906 Note [Refinement]
1907 ~~~~~~~~~~~~~~~~~
1908 Consider
1909         data T a where
1910           MkT :: a -> b -> T a
1911
1912         f = /\a. \(w::a).
1913            case (case ...) of
1914                   MkT a' b (p::a') (q::b) -> [p,w]
1915
1916 The danger is that we'll make a join point
1917         
1918         j a' p = [p,w]
1919
1920 and that's ill-typed, because (p::a') but (w::a).  
1921
1922 Solution so far: don't abstract over a', because the type refinement
1923 maps [a' -> a] .  Ultimately that won't work when real refinement goes on.
1924
1925 Then we must abstract over any refined free variables.  Hmm.  Maybe we 
1926 could just abstract over *all* free variables, thereby lambda-lifting
1927 the join point?   We should try this.