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