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