92fb9dd5b3db6d0c8aacc4a0df55051d92eb226f
[ghc-hetmet.git] / ghc / compiler / simplCore / Simplify.lhs
1
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[Simplify]{The main module of the simplifier}
5
6 \begin{code}
7 module Simplify ( simplTopBinds, simplExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( intSwitchSet, switchIsOn,
12                           opt_SccProfilingOn, opt_PprStyle_Debug, opt_SimplDoEtaReduction,
13                           opt_SimplNoPreInlining, opt_DictsStrict, opt_SimplPedanticBottoms,
14                           SimplifierSwitch(..)
15                         )
16 import SimplMonad
17 import SimplUtils       ( mkCase, transformRhs, findAlt, etaCoreExpr,
18                           simplBinder, simplBinders, simplIds, findDefault, mkCoerce
19                         )
20 import Var              ( TyVar, mkSysTyVar, tyVarKind, maybeModifyIdInfo )
21 import VarEnv
22 import VarSet
23 import Id               ( Id, idType, idInfo, idUnique,
24                           getIdUnfolding, setIdUnfolding, isExportedId, 
25                           getIdSpecialisation, setIdSpecialisation,
26                           getIdDemandInfo, setIdDemandInfo,
27                           setIdInfo,
28                           getIdOccInfo, setIdOccInfo,
29                           zapLamIdInfo, zapFragileIdInfo,
30                           getIdStrictness, 
31                           setInlinePragma, mayHaveNoBinding,
32                           setOneShotLambda, maybeModifyIdInfo
33                         )
34 import IdInfo           ( InlinePragInfo(..), OccInfo(..), StrictnessInfo(..), 
35                           ArityInfo(..), atLeastArity, arityLowerBound, unknownArity,
36                           specInfo, inlinePragInfo, setArityInfo, setInlinePragInfo, setUnfoldingInfo
37                         )
38 import Demand           ( Demand, isStrict, wwLazy )
39 import Const            ( isWHNFCon, conOkForAlt )
40 import ConFold          ( tryPrimOp )
41 import PrimOp           ( PrimOp, primOpStrictness, primOpType )
42 import DataCon          ( DataCon, dataConNumInstArgs, dataConRepStrictness, dataConSig, dataConArgTys )
43 import Const            ( Con(..) )
44 import Name             ( isLocallyDefined )
45 import CoreSyn
46 import CoreFVs          ( exprFreeVars )
47 import CoreUnfold       ( Unfolding, mkOtherCon, mkUnfolding, otherCons,
48                           callSiteInline, hasSomeUnfolding
49                         )
50 import CoreUtils        ( cheapEqExpr, exprIsDupable, exprIsCheap, exprIsTrivial,
51                           coreExprType, coreAltsType, exprArity, exprIsValue,
52                           exprOkForSpeculation
53                         )
54 import Rules            ( lookupRule )
55 import CostCentre       ( isSubsumedCCS, currentCCS, isEmptyCC )
56 import Type             ( Type, mkTyVarTy, mkTyVarTys, isUnLiftedType, seqType,
57                           mkFunTy, splitFunTys, splitTyConApp_maybe, splitFunTy_maybe,
58                           funResultTy, isDictTy, isDataType, applyTy, applyTys, mkFunTys
59                         )
60 import Subst            ( Subst, mkSubst, emptySubst, substTy, substExpr,
61                           substEnv, isInScope, lookupInScope, lookupIdSubst, substIdInfo
62                         )
63 import TyCon            ( isDataTyCon, tyConDataCons, tyConClass_maybe, tyConArity, isDataTyCon )
64 import TysPrim          ( realWorldStatePrimTy )
65 import PrelInfo         ( realWorldPrimId )
66 import BasicTypes       ( TopLevelFlag(..), isTopLevel )
67 import Maybes           ( maybeToBool )
68 import Util             ( zipWithEqual, stretchZipEqual, lengthExceeds )
69 import PprCore
70 import Outputable
71 import Unique           ( foldrIdKey )  -- Temp
72 \end{code}
73
74
75 The guts of the simplifier is in this module, but the driver
76 loop for the simplifier is in SimplCore.lhs.
77
78
79 %************************************************************************
80 %*                                                                      *
81 \subsection{Bindings}
82 %*                                                                      *
83 %************************************************************************
84
85 \begin{code}
86 simplTopBinds :: [InBind] -> SimplM [OutBind]
87
88 simplTopBinds binds
89   =     -- Put all the top-level binders into scope at the start
90         -- so that if a transformation rule has unexpectedly brought
91         -- anything into scope, then we don't get a complaint about that.
92         -- It's rather as if the top-level binders were imported.
93     simplIds (bindersOfBinds binds)     $ \ bndrs' -> 
94     simpl_binds binds bndrs'            `thenSmpl` \ (binds', _) ->
95     freeTick SimplifierDone             `thenSmpl_`
96     returnSmpl binds'
97   where
98
99         -- We need to track the zapped top-level binders, because
100         -- they should have their fragile IdInfo zapped (notably occurrence info)
101     simpl_binds []                        bs     = ASSERT( null bs ) returnSmpl ([], panic "simplTopBinds corner")
102     simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr  b rhs       (simpl_binds binds bs)
103     simpl_binds (Rec pairs       : binds) bs     = simplRecBind  True pairs (take n bs) (simpl_binds binds (drop n bs))
104                                                  where 
105                                                    n = length pairs
106
107 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
108              -> SimplM (OutStuff a) -> SimplM (OutStuff a)
109 simplRecBind top_lvl pairs bndrs' thing_inside
110   = go pairs bndrs'             `thenSmpl` \ (binds', stuff) ->
111     returnSmpl (addBind (Rec (flattenBinds binds')) stuff)
112   where
113     go [] _ = thing_inside      `thenSmpl` \ stuff ->
114               returnSmpl ([], stuff)
115         
116     go ((bndr, rhs) : pairs) (bndr' : bndrs')
117         = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
118                 -- Don't float unboxed bindings out,
119                 -- because we can't "rec" them
120 \end{code}
121
122
123 %************************************************************************
124 %*                                                                      *
125 \subsection[Simplify-simplExpr]{The main function: simplExpr}
126 %*                                                                      *
127 %************************************************************************
128
129 \begin{code}
130 addBind :: CoreBind -> OutStuff a -> OutStuff a
131 addBind bind    (binds,  res) = (bind:binds,     res)
132
133 addBinds :: [CoreBind] -> OutStuff a -> OutStuff a
134 addBinds []     stuff         = stuff
135 addBinds binds1 (binds2, res) = (binds1++binds2, res)
136 \end{code}
137
138 The reason for this OutExprStuff stuff is that we want to float *after*
139 simplifying a RHS, not before.  If we do so naively we get quadratic
140 behaviour as things float out.
141
142 To see why it's important to do it after, consider this (real) example:
143
144         let t = f x
145         in fst t
146 ==>
147         let t = let a = e1
148                     b = e2
149                 in (a,b)
150         in fst t
151 ==>
152         let a = e1
153             b = e2
154             t = (a,b)
155         in
156         a       -- Can't inline a this round, cos it appears twice
157 ==>
158         e1
159
160 Each of the ==> steps is a round of simplification.  We'd save a
161 whole round if we float first.  This can cascade.  Consider
162
163         let f = g d
164         in \x -> ...f...
165 ==>
166         let f = let d1 = ..d.. in \y -> e
167         in \x -> ...f...
168 ==>
169         let d1 = ..d..
170         in \x -> ...(\y ->e)...
171
172 Only in this second round can the \y be applied, and it 
173 might do the same again.
174
175
176 \begin{code}
177 simplExpr :: CoreExpr -> SimplM CoreExpr
178 simplExpr expr = getSubst       `thenSmpl` \ subst ->
179                  simplExprC expr (Stop (substTy subst (coreExprType expr)))
180         -- The type in the Stop continuation is usually not used
181         -- It's only needed when discarding continuations after finding
182         -- a function that returns bottom.
183         -- Hence the lazy substitution
184
185 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
186         -- Simplify an expression, given a continuation
187
188 simplExprC expr cont = simplExprF expr cont     `thenSmpl` \ (floats, (_, body)) ->
189                        returnSmpl (mkLets floats body)
190
191 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
192         -- Simplify an expression, returning floated binds
193
194 simplExprF (Var v) cont
195   = simplVar v cont
196
197 simplExprF expr@(Con (PrimOp op) args) cont
198   = getSubstEnv                         `thenSmpl` \ se ->
199     prepareArgs (ppr op)
200                 (primOpType op)
201                 (primOpStrictness op)
202                 (pushArgs se args cont) $ \ args1 cont1 ->
203
204     let
205         -- Boring... we may have too many arguments now, so we push them back
206         n_args = length args
207         args2 = ASSERT( length args1 >= n_args )
208                  take n_args args1
209         cont2 = pushArgs emptySubstEnv (drop n_args args1) cont1
210     in                          
211         --      Try the prim op simplification
212         -- It's really worth trying simplExpr again if it succeeds,
213         -- because you can find
214         --      case (eqChar# x 'a') of ...
215         -- ==>  
216         --      case (case x of 'a' -> True; other -> False) of ...
217
218     case tryPrimOp op args2 of
219           Just e' -> zapSubstEnv (simplExprF e' cont2)
220           Nothing -> rebuild (Con (PrimOp op) args2) cont2
221
222
223 simplExprF (Con con@(DataCon _) args) cont
224   = simplConArgs args           $ \ args' ->
225     rebuild (Con con args') cont
226
227 simplExprF expr@(Con con@(Literal _) args) cont
228   = ASSERT( null args )
229     rebuild expr cont
230
231 simplExprF (App fun arg) cont
232   = getSubstEnv         `thenSmpl` \ se ->
233     simplExprF fun (ApplyTo NoDup arg se cont)
234
235 simplExprF (Case scrut bndr alts) cont
236   = getSubstEnv         `thenSmpl` \ se ->
237     simplExprF scrut (Select NoDup bndr alts se cont)
238
239
240 simplExprF (Let (Rec pairs) body) cont
241   = simplIds (map fst pairs)            $ \ bndrs' -> 
242         -- NB: bndrs' don't have unfoldings or spec-envs
243         -- We add them as we go down, using simplPrags
244
245     simplRecBind False pairs bndrs' (simplExprF body cont)
246
247 simplExprF expr@(Lam _ _) cont = simplLam expr cont
248
249 simplExprF (Type ty) cont
250   = ASSERT( case cont of { Stop _ -> True; ArgOf _ _ _ -> True; other -> False } )
251     simplType ty        `thenSmpl` \ ty' ->
252     rebuild (Type ty') cont
253
254 -- Comments about the Coerce case
255 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
256 -- It's worth checking for a coerce in the continuation,
257 -- in case we can cancel them.  For example, in the initial form of a worker
258 -- we may find  (coerce T (coerce S (\x.e))) y
259 -- and we'd like it to simplify to e[y/x] in one round of simplification
260
261 simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
262   = simplType from              `thenSmpl` \ from' ->
263     if outer_to == from' then
264         -- The coerces cancel out
265         simplExprF e cont
266     else
267         -- They don't cancel, but the inner one is redundant
268         simplExprF e (CoerceIt outer_to cont)
269
270 simplExprF (Note (Coerce to from) e) cont
271   = simplType to                `thenSmpl` \ to' ->
272     simplExprF e (CoerceIt to' cont)
273
274 -- hack: we only distinguish subsumed cost centre stacks for the purposes of
275 -- inlining.  All other CCCSs are mapped to currentCCS.
276 simplExprF (Note (SCC cc) e) cont
277   = setEnclosingCC currentCCS $
278     simplExpr e         `thenSmpl` \ e ->
279     rebuild (mkNote (SCC cc) e) cont
280
281 simplExprF (Note InlineCall e) cont
282   = simplExprF e (InlinePlease cont)
283
284 -- Comments about the InlineMe case 
285 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
286 -- Don't inline in the RHS of something that has an
287 -- inline pragma.  But be careful that the InScopeEnv that
288 -- we return does still have inlinings on!
289 -- 
290 -- It really is important to switch off inlinings.  This function
291 -- may be inlinined in other modules, so we don't want to remove
292 -- (by inlining) calls to functions that have specialisations, or
293 -- that may have transformation rules in an importing scope.
294 -- E.g.         {-# INLINE f #-}
295 --              f x = ...g...
296 -- and suppose that g is strict *and* has specialisations.
297 -- If we inline g's wrapper, we deny f the chance of getting
298 -- the specialised version of g when f is inlined at some call site
299 -- (perhaps in some other module).
300
301 simplExprF (Note InlineMe e) cont
302   = case cont of
303         Stop _ ->       -- Totally boring continuation
304                         -- Don't inline inside an INLINE expression
305                   switchOffInlining (simplExpr e)       `thenSmpl` \ e' ->
306                   rebuild (mkNote InlineMe e') cont
307
308         other  ->       -- Dissolve the InlineMe note if there's
309                         -- an interesting context of any kind to combine with
310                         -- (even a type application -- anything except Stop)
311                   simplExprF e cont     
312
313 -- A non-recursive let is dealt with by simplBeta
314 simplExprF (Let (NonRec bndr rhs) body) cont
315   = getSubstEnv                 `thenSmpl` \ se ->
316     simplBeta bndr rhs se (contResultType cont) $
317     simplExprF body cont
318 \end{code}
319
320
321 ---------------------------------
322
323 \begin{code}
324 simplLam fun cont
325   = go fun cont
326   where
327     zap_it  = mkLamBndrZapper fun cont
328     cont_ty = contResultType cont
329
330         -- Type-beta reduction
331     go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
332       = ASSERT( isTyVar bndr )
333         tick (BetaReduction bndr)               `thenSmpl_`
334         getInScope                              `thenSmpl` \ in_scope ->
335         let
336                 ty' = substTy (mkSubst in_scope arg_se) ty_arg
337         in
338         seqType ty'     `seq`
339         extendSubst bndr (DoneTy ty')
340         (go body body_cont)
341
342         -- Ordinary beta reduction
343     go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
344       = tick (BetaReduction bndr)                       `thenSmpl_`
345         simplBeta zapped_bndr arg arg_se cont_ty
346         (go body body_cont)
347       where
348         zapped_bndr = zap_it bndr
349
350         -- Not enough args
351     go lam@(Lam _ _) cont = completeLam [] lam cont
352
353         -- Exactly enough args
354     go expr cont = simplExprF expr cont
355
356 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
357 -- continuation.  
358 -- We used to try for eta reduction here, but I found that this was
359 -- eta reducing things like 
360 --      f = \x -> (coerce (\x -> e))
361 -- This made f's arity reduce, which is a bad thing, so I removed the
362 -- eta reduction at this point, and now do it only when binding 
363 -- (at the call to postInlineUnconditionally
364
365 completeLam acc (Lam bndr body) cont
366   = simplBinder bndr                    $ \ bndr' ->
367     completeLam (bndr':acc) body cont
368
369 completeLam acc body cont
370   = simplExpr body                      `thenSmpl` \ body' ->
371     rebuild (foldl (flip Lam) body' acc) cont
372                 -- Remember, acc is the *reversed* binders
373
374 mkLamBndrZapper :: CoreExpr     -- Function
375                 -> SimplCont    -- The context
376                 -> Id -> Id     -- Use this to zap the binders
377 mkLamBndrZapper fun cont
378   | n_args >= n_params fun = \b -> b            -- Enough args
379   | otherwise              = \b -> zapLamIdInfo b
380   where
381         -- NB: we count all the args incl type args
382         -- so we must count all the binders (incl type lambdas)
383     n_args = countArgs cont
384
385     n_params (Note _ e) = n_params e
386     n_params (Lam b e)  = 1 + n_params e
387     n_params other      = 0::Int
388 \end{code}
389
390
391 ---------------------------------
392 simplConArgs makes sure that the arguments all end up being atomic.
393 That means it may generate some Lets, hence the strange type
394
395 \begin{code}
396 simplConArgs :: [InArg] -> ([OutArg] -> SimplM OutExprStuff) -> SimplM OutExprStuff
397 simplConArgs args thing_inside
398   = getSubst    `thenSmpl` \ subst ->
399     go subst args thing_inside
400   where
401     go subst [] thing_inside 
402         = thing_inside []
403     go subst (arg:args) thing_inside 
404         | exprIsTrivial arg
405         = let
406                 arg1 = substExpr subst arg
407                 -- Simplify the RHS with inlining switched off, so that
408                 -- only absolutely essential things will happen.
409                 -- If we don't do this, consider:
410                 --      let x = e in C {x}
411                 -- We end up inlining x back into C's argument,
412                 -- and then let-binding it again!
413                 --
414                 -- It's important that the substitution *does* deal with case-binder synonyms:
415                 --      case x of y { True -> (x,1) }
416                 -- Here we must be sure to substitute y for x when simplifying the args of the pair,
417                 -- to increase the chances of being able to inline x.  The substituter will do
418                 -- that because the x->y mapping is held in the in-scope set.
419           in
420           ASSERT( exprIsTrivial arg1 )
421           go subst args                         $ \ args1 ->
422           thing_inside (arg1 : args1)
423
424         | otherwise
425         =       -- If the argument ain't trivial, then let-bind it
426           simplExpr arg                         `thenSmpl` \ arg1 ->
427           newId (coreExprType arg1)             $ \ arg_id ->
428           go subst args                         $ \ args1 ->
429           thing_inside (Var arg_id : args1)     `thenSmpl` \ res ->
430           returnSmpl (addBind (NonRec arg_id arg1) res)
431                 -- I used to use completeBeta but that was wrong, because
432                 -- arg_id isn't an InId
433 \end{code}
434
435
436 ---------------------------------
437 \begin{code}
438 simplType :: InType -> SimplM OutType
439 simplType ty
440   = getSubst    `thenSmpl` \ subst ->
441     let
442         new_ty = substTy subst ty
443     in
444     seqType new_ty `seq`  
445     returnSmpl new_ty
446 \end{code}
447
448
449 %************************************************************************
450 %*                                                                      *
451 \subsection{Binding}
452 %*                                                                      *
453 %************************************************************************
454
455 @simplBeta@ is used for non-recursive lets in expressions, 
456 as well as true beta reduction.
457
458 Very similar to @simplLazyBind@, but not quite the same.
459
460 \begin{code}
461 simplBeta :: InId                       -- Binder
462           -> InExpr -> SubstEnv         -- Arg, with its subst-env
463           -> OutType                    -- Type of thing computed by the context
464           -> SimplM OutExprStuff        -- The body
465           -> SimplM OutExprStuff
466 #ifdef DEBUG
467 simplBeta bndr rhs rhs_se cont_ty thing_inside
468   | isTyVar bndr
469   = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
470 #endif
471
472 simplBeta bndr rhs rhs_se cont_ty thing_inside
473   | preInlineUnconditionally False {- not black listed -} bndr
474   = tick (PreInlineUnconditionally bndr)                `thenSmpl_`
475     extendSubst bndr (ContEx rhs_se rhs) thing_inside
476
477   | otherwise
478   =     -- Simplify the RHS
479     simplBinder bndr                                    $ \ bndr' ->
480     simplArg (idType bndr') (getIdDemandInfo bndr)
481              rhs rhs_se cont_ty                         $ \ rhs' ->
482
483         -- Now complete the binding and simplify the body
484     completeBeta bndr bndr' rhs' thing_inside
485
486 completeBeta bndr bndr' rhs' thing_inside
487   | isUnLiftedType (idType bndr') && not (exprOkForSpeculation rhs')
488         -- Make a case expression instead of a let
489         -- These can arise either from the desugarer,
490         -- or from beta reductions: (\x.e) (x +# y)
491   = getInScope                  `thenSmpl` \ in_scope ->
492     thing_inside                `thenSmpl` \ (floats, (_, body)) ->
493     returnSmpl ([], (in_scope, Case rhs' bndr' [(DEFAULT, [], mkLets floats body)]))
494
495   | otherwise
496   = completeBinding bndr bndr' False False rhs' thing_inside
497 \end{code}
498
499
500 \begin{code}
501 simplArg :: OutType -> Demand
502          -> InExpr -> SubstEnv
503          -> OutType             -- Type of thing computed by the context
504          -> (OutExpr -> SimplM OutExprStuff)
505          -> SimplM OutExprStuff
506 simplArg arg_ty demand arg arg_se cont_ty thing_inside
507   | isStrict demand || 
508     isUnLiftedType arg_ty || 
509     (opt_DictsStrict && isDictTy arg_ty && isDataType arg_ty)
510         -- Return true only for dictionary types where the dictionary
511         -- has more than one component (else we risk poking on the component
512         -- of a newtype dictionary)
513   = transformRhs arg                    `thenSmpl` \ t_arg ->
514     getEnv                              `thenSmpl` \ env ->
515     setSubstEnv arg_se                          $
516     simplExprF t_arg (ArgOf NoDup cont_ty       $ \ rhs' ->
517     setAllExceptInScope env                     $
518     etaFirst thing_inside rhs')
519
520   | otherwise
521   = simplRhs False {- Not top level -} 
522              True {- OK to float unboxed -}
523              arg_ty arg arg_se 
524              thing_inside
525    
526 -- Do eta-reduction on the simplified RHS, if eta reduction is on
527 -- NB: etaCoreExpr only eta-reduces if that results in something trivial
528 etaFirst | opt_SimplDoEtaReduction = \ thing_inside rhs -> thing_inside (etaCoreExprToTrivial rhs)
529          | otherwise               = \ thing_inside rhs -> thing_inside rhs
530
531 -- Try for eta reduction, but *only* if we get all
532 -- the way to an exprIsTrivial expression.    We don't want to remove
533 -- extra lambdas unless we are going to avoid allocating this thing altogether
534 etaCoreExprToTrivial rhs | exprIsTrivial rhs' = rhs'
535                          | otherwise          = rhs
536                          where
537                            rhs' = etaCoreExpr rhs
538 \end{code}
539
540
541 completeBinding
542         - deals only with Ids, not TyVars
543         - take an already-simplified RHS
544
545 It does *not* attempt to do let-to-case.  Why?  Because they are used for
546
547         - top-level bindings
548                 (when let-to-case is impossible) 
549
550         - many situations where the "rhs" is known to be a WHNF
551                 (so let-to-case is inappropriate).
552
553 \begin{code}
554 completeBinding :: InId                 -- Binder
555                 -> OutId                -- New binder
556                 -> Bool                 -- True <=> top level
557                 -> Bool                 -- True <=> black-listed; don't inline
558                 -> OutExpr              -- Simplified RHS
559                 -> SimplM (OutStuff a)  -- Thing inside
560                 -> SimplM (OutStuff a)
561
562 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
563   |  (case occ_info of          -- This happens; for example, the case_bndr during case of
564         IAmDead -> True         -- known constructor:  case (a,b) of x { (p,q) -> ... }
565         other   -> False)       -- Here x isn't mentioned in the RHS, so we don't want to
566                                 -- create the (dead) let-binding  let x = (a,b) in ...
567   =  thing_inside
568
569   |  postInlineUnconditionally black_listed occ_info old_bndr new_rhs
570         -- Maybe we don't need a let-binding!  Maybe we can just
571         -- inline it right away.  Unlike the preInlineUnconditionally case
572         -- we are allowed to look at the RHS.
573         --
574         -- NB: a loop breaker never has postInlineUnconditionally True
575         -- and non-loop-breakers only have *forward* references
576         -- Hence, it's safe to discard the binding
577         --      
578         -- NB: You might think that postInlineUnconditionally is an optimisation,
579         -- but if we have
580         --      let x = f Bool in (x, y)
581         -- then because of the constructor, x will not be *inlined* in the pair,
582         -- so the trivial binding will stay.  But in this postInlineUnconditionally 
583         -- gag we use the *substitution* to substitute (f Bool) for x, and that *will*
584         -- happen.
585   =  tick (PostInlineUnconditionally old_bndr)  `thenSmpl_`
586      extendSubst old_bndr (DoneEx new_rhs)      
587      thing_inside
588
589   |  otherwise
590   =  getSubst                   `thenSmpl` \ subst ->
591      let
592         -- We make new IdInfo for the new binder by starting from the old binder, 
593         -- doing appropriate substitutions.
594         -- Then we add arity and unfolding info to get the new binder
595         new_bndr_info = substIdInfo subst (idInfo old_bndr) (idInfo new_bndr)
596                         `setArityInfo` ArityAtLeast (exprArity new_rhs)
597                         `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
598
599         final_id = new_bndr `setIdInfo` new_bndr_info
600      in
601         -- These seqs force the Ids, and hence the IdInfos, and hence any
602         -- inner substitutions
603      final_id   `seq`
604
605      (modifyInScope new_bndr final_id thing_inside      `thenSmpl` \ stuff ->
606       returnSmpl (addBind (NonRec final_id new_rhs) stuff))
607
608   where
609     occ_info = getIdOccInfo old_bndr
610 \end{code}    
611
612
613 %************************************************************************
614 %*                                                                      *
615 \subsection{simplLazyBind}
616 %*                                                                      *
617 %************************************************************************
618
619 simplLazyBind basically just simplifies the RHS of a let(rec).
620 It does two important optimisations though:
621
622         * It floats let(rec)s out of the RHS, even if they
623           are hidden by big lambdas
624
625         * It does eta expansion
626
627 \begin{code}
628 simplLazyBind :: Bool                   -- True <=> top level
629               -> InId -> OutId
630               -> InExpr                 -- The RHS
631               -> SimplM (OutStuff a)    -- The body of the binding
632               -> SimplM (OutStuff a)
633 -- When called, the subst env is correct for the entire let-binding
634 -- and hence right for the RHS.
635 -- Also the binder has already been simplified, and hence is in scope
636
637 simplLazyBind top_lvl bndr bndr' rhs thing_inside
638   = getBlackList                `thenSmpl` \ black_list_fn ->
639     let
640         black_listed = black_list_fn bndr
641     in
642
643     if preInlineUnconditionally black_listed bndr then
644         -- Inline unconditionally
645         tick (PreInlineUnconditionally bndr)    `thenSmpl_`
646         getSubstEnv                             `thenSmpl` \ rhs_se ->
647         (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
648     else
649
650         -- Simplify the RHS
651     getSubstEnv                                         `thenSmpl` \ rhs_se ->
652     simplRhs top_lvl False {- Not ok to float unboxed -}
653              (idType bndr')
654              rhs rhs_se                                 $ \ rhs' ->
655
656         -- Now compete the binding and simplify the body
657     completeBinding bndr bndr' top_lvl black_listed rhs' thing_inside
658 \end{code}
659
660
661
662 \begin{code}
663 simplRhs :: Bool                -- True <=> Top level
664          -> Bool                -- True <=> OK to float unboxed (speculative) bindings
665          -> OutType -> InExpr -> SubstEnv
666          -> (OutExpr -> SimplM (OutStuff a))
667          -> SimplM (OutStuff a)
668 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
669   =     -- Swizzle the inner lets past the big lambda (if any)
670         -- and try eta expansion
671     transformRhs rhs                                    `thenSmpl` \ t_rhs ->
672
673         -- Simplify it
674     setSubstEnv rhs_se (simplExprF t_rhs (Stop rhs_ty)) `thenSmpl` \ (floats, (in_scope', rhs')) ->
675
676         -- Float lets out of RHS
677     let
678         (floats_out, rhs'') | float_ubx = (floats, rhs')
679                             | otherwise = splitFloats floats rhs' 
680     in
681     if (top_lvl || exprIsCheap rhs') &&         -- Float lets if (a) we're at the top level
682         not (null floats_out)                   -- or            (b) it exposes a cheap (i.e. duplicatable) expression
683     then
684         tickLetFloat floats_out                         `thenSmpl_`
685                 -- Do the float
686                 -- 
687                 -- There's a subtlety here.  There may be a binding (x* = e) in the
688                 -- floats, where the '*' means 'will be demanded'.  So is it safe
689                 -- to float it out?  Answer no, but it won't matter because
690                 -- we only float if arg' is a WHNF,
691                 -- and so there can't be any 'will be demanded' bindings in the floats.
692                 -- Hence the assert
693         WARN( any demanded_float floats_out, ppr floats_out )
694         setInScope in_scope' (etaFirst thing_inside rhs'')      `thenSmpl` \ stuff ->
695                 -- in_scope' may be excessive, but that's OK;
696                 -- it's a superset of what's in scope
697         returnSmpl (addBinds floats_out stuff)
698     else        
699                 -- Don't do the float
700         etaFirst thing_inside (mkLets floats rhs')
701
702 -- In a let-from-let float, we just tick once, arbitrarily
703 -- choosing the first floated binder to identify it
704 tickLetFloat (NonRec b r      : fs) = tick (LetFloatFromLet b)
705 tickLetFloat (Rec ((b,r):prs) : fs) = tick (LetFloatFromLet b)
706         
707 demanded_float (NonRec b r) = isStrict (getIdDemandInfo b) && not (isUnLiftedType (idType b))
708                 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
709 demanded_float (Rec _)      = False
710
711 -- Don't float any unlifted bindings out, because the context
712 -- is either a Rec group, or the top level, neither of which
713 -- can tolerate them.
714 splitFloats floats rhs
715   = go floats
716   where
717     go []                   = ([], rhs)
718     go (f:fs) | must_stay f = ([], mkLets (f:fs) rhs)
719               | otherwise   = case go fs of
720                                    (out, rhs') -> (f:out, rhs')
721
722     must_stay (Rec prs)    = False      -- No unlifted bindings in here
723     must_stay (NonRec b r) = isUnLiftedType (idType b)
724 \end{code}
725
726
727
728 %************************************************************************
729 %*                                                                      *
730 \subsection{Variables}
731 %*                                                                      *
732 %************************************************************************
733
734 \begin{code}
735 simplVar var cont
736   = getSubst            `thenSmpl` \ subst ->
737     case lookupIdSubst subst var of
738         DoneEx e        -> zapSubstEnv (simplExprF e cont)
739         ContEx env1 e   -> setSubstEnv env1 (simplExprF e cont)
740         DoneId var1 occ -> WARN( not (isInScope var1 subst) && isLocallyDefined var1 && not (mayHaveNoBinding var1),
741                                  text "simplVar:" <+> ppr var )
742                                         -- The mayHaveNoBinding test accouunts for the fact
743                                         -- that class dictionary constructors dont have top level
744                                         -- bindings and hence aren't in scope.
745                            finish_var var1 occ
746   where
747     finish_var var occ
748       = getBlackList            `thenSmpl` \ black_list ->
749         getInScope              `thenSmpl` \ in_scope ->
750         completeCall black_list in_scope occ var cont
751
752 ---------------------------------------------------------
753 --      Dealing with a call
754
755 completeCall black_list_fn in_scope occ var cont
756
757         -- Look for an unfolding. There's a binding for the
758         -- thing, but perhaps we want to inline it anyway
759   | maybeToBool maybe_inline
760   = tick (UnfoldingDone var)            `thenSmpl_`
761     zapSubstEnv (completeInlining var unf_template discard_inline_cont)
762                 -- The template is already simplified, so don't re-substitute.
763                 -- This is VITAL.  Consider
764                 --      let x = e in
765                 --      let y = \z -> ...x... in
766                 --      \ x -> ...y...
767                 -- We'll clone the inner \x, adding x->x' in the id_subst
768                 -- Then when we inline y, we must *not* replace x by x' in
769                 -- the inlined copy!!
770     
771   | otherwise           -- No inlining
772                         -- Use prepareArgs to use function strictness
773   = prepareArgs (ppr var) (idType var) (get_str var) cont       $ \ args' cont' ->
774
775         -- Look for rules or specialisations that match
776         --
777         -- It's important to simplify the args first, because the rule-matcher
778         -- doesn't do substitution as it goes.  We don't want to use subst_args
779         -- (defined in the 'where') because that throws away useful occurrence info,
780         -- and perhaps-very-important specialisations.
781         --
782         -- Some functions have specialisations *and* are strict; in this case,
783         -- we don't want to inline the wrapper of the non-specialised thing; better
784         -- to call the specialised thing instead.
785         -- But the black-listing mechanism means that inlining of the wrapper
786         -- won't occur for things that have specialisations till a later phase, so
787         -- it's ok to try for inlining first.
788     getSwitchChecker                                            `thenSmpl` \ chkr ->
789     if switchIsOn chkr DontApplyRules then
790         -- Don't try rules
791         rebuild (mkApps (Var var) args') cont'
792     else
793         -- Try rules first
794     case lookupRule in_scope var args' of
795         Just (rule_name, rule_rhs) -> 
796                 tick (RuleFired rule_name)                      `thenSmpl_`
797                 zapSubstEnv (simplExprF rule_rhs cont')
798                         -- See note above about zapping the substitution here
799         
800         Nothing -> rebuild (mkApps (Var var) args') cont'
801
802   where
803     get_str var = case getIdStrictness var of
804                         NoStrictnessInfo                  -> (repeat wwLazy, False)
805                         StrictnessInfo demands result_bot -> (demands, result_bot)
806
807         ---------- Unfolding stuff
808     (subst_args, result_cont) = contArgs in_scope cont
809     val_args                  = filter isValArg subst_args
810     arg_infos                 = map (interestingArg in_scope) val_args
811     inline_call               = contIsInline result_cont
812     interesting_cont          = contIsInteresting result_cont
813     discard_inline_cont       | inline_call = discardInline cont
814                               | otherwise   = cont
815
816     maybe_inline  = callSiteInline black_listed inline_call occ
817                                    var arg_infos interesting_cont
818     Just unf_template = maybe_inline
819     black_listed      = black_list_fn var
820
821
822 -- An argument is interesting if it has *some* structure
823 -- We are here trying to avoid unfolding a function that
824 -- is applied only to variables that have no unfolding
825 -- (i.e. they are probably lambda bound): f x y z
826 -- There is little point in inlining f here.
827 interestingArg in_scope (Type _)          = False
828 interestingArg in_scope (App fn (Type _)) = interestingArg in_scope fn
829 interestingArg in_scope (Var v)           = hasSomeUnfolding (getIdUnfolding v')
830                                           where
831                                             v' = case lookupVarSet in_scope v of
832                                                         Just v' -> v'
833                                                         other   -> v
834 interestingArg in_scope other             = True
835
836
837 -- First a special case
838 -- Don't actually inline the scrutinee when we see
839 --      case x of y { .... }
840 -- and x has unfolding (C a b).  Why not?  Because
841 -- we get a silly binding y = C a b.  If we don't
842 -- inline knownCon can directly substitute x for y instead.
843 completeInlining var (Con con con_args) (Select _ bndr alts se cont)
844   | conOkForAlt con 
845   = knownCon (Var var) con con_args bndr alts se cont
846
847 -- Now the normal case
848 completeInlining var unfolding cont
849   = simplExprF unfolding cont
850
851 ----------- costCentreOk
852 -- costCentreOk checks that it's ok to inline this thing
853 -- The time it *isn't* is this:
854 --
855 --      f x = let y = E in
856 --            scc "foo" (...y...)
857 --
858 -- Here y has a "current cost centre", and we can't inline it inside "foo",
859 -- regardless of whether E is a WHNF or not.
860     
861 costCentreOk ccs_encl cc_rhs
862   =  not opt_SccProfilingOn
863   || isSubsumedCCS ccs_encl       -- can unfold anything into a subsumed scope
864   || not (isEmptyCC cc_rhs)       -- otherwise need a cc on the unfolding
865 \end{code}                 
866
867
868 \begin{code}
869 ---------------------------------------------------------
870 --      Preparing arguments for a call
871
872 prepareArgs :: SDoc     -- Error message info
873             -> OutType -> ([Demand],Bool) -> SimplCont
874             -> ([OutExpr] -> SimplCont -> SimplM OutExprStuff)
875             -> SimplM OutExprStuff
876
877 prepareArgs pp_fun orig_fun_ty (fun_demands, result_bot) orig_cont thing_inside
878   = go [] demands orig_fun_ty orig_cont
879   where
880     not_enough_args = fun_demands `lengthExceeds` countValArgs orig_cont
881         -- "No strictness info" is signalled by an infinite list of wwLazy
882  
883     demands | not_enough_args = repeat wwLazy                   -- Not enough args, or no strictness
884             | result_bot      = fun_demands                     -- Enough args, and function returns bottom
885             | otherwise       = fun_demands ++ repeat wwLazy    -- Enough args and function does not return bottom
886         -- NB: demands is finite iff enough args and result_bot is True
887
888         -- Main game plan: loop through the arguments, simplifying
889         -- each of them in turn.  We carry with us a list of demands,
890         -- and the type of the function-applied-to-earlier-args
891
892         -- Type argument
893     go acc ds fun_ty (ApplyTo _ arg@(Type ty_arg) se cont)
894         = getInScope            `thenSmpl` \ in_scope ->
895           let
896                 ty_arg' = substTy (mkSubst in_scope se) ty_arg
897                 res_ty  = applyTy fun_ty ty_arg'
898           in
899           seqType ty_arg'       `seq`
900           go (Type ty_arg' : acc) ds res_ty cont
901
902         -- Value argument
903     go acc (d:ds) fun_ty (ApplyTo _ val_arg se cont)
904         = case splitFunTy_maybe fun_ty of {
905                 Nothing -> pprTrace "prepareArgs" (pp_fun $$ ppr orig_fun_ty $$ ppr orig_cont) 
906                            (thing_inside (reverse acc) cont) ;
907                 Just (arg_ty, res_ty) ->
908           simplArg arg_ty d val_arg se (contResultType cont)    $ \ arg' ->
909           go (arg':acc) ds res_ty cont }
910
911         -- We've run out of demands, which only happens for functions
912         -- we *know* now return bottom
913         -- This deals with
914         --      * case (error "hello") of { ... }
915         --      * (error "Hello") arg
916         --      * f (error "Hello") where f is strict
917         --      etc
918     go acc [] fun_ty cont = tick_case_of_error cont             `thenSmpl_`
919                             thing_inside (reverse acc) (discardCont cont)
920
921         -- We're run out of arguments
922     go acc ds fun_ty cont = thing_inside (reverse acc) cont
923
924 -- Boring: we must only record a tick if there was an interesting
925 --         continuation to discard.  If not, we tick forever.
926 tick_case_of_error (Stop _)              = returnSmpl ()
927 tick_case_of_error (CoerceIt _ (Stop _)) = returnSmpl ()
928 tick_case_of_error other                 = tick BottomFound
929 \end{code}
930
931 %************************************************************************
932 %*                                                                      *
933 \subsection{Decisions about inlining}
934 %*                                                                      *
935 %************************************************************************
936
937 NB: At one time I tried not pre/post-inlining top-level things,
938 even if they occur exactly once.  Reason: 
939         (a) some might appear as a function argument, so we simply
940                 replace static allocation with dynamic allocation:
941                    l = <...>
942                    x = f x
943         becomes
944                    x = f <...>
945
946         (b) some top level things might be black listed
947
948 HOWEVER, I found that some useful foldr/build fusion was lost (most
949 notably in spectral/hartel/parstof) because the foldr didn't see the build.
950
951 Doing the dynamic allocation isn't a big deal, in fact, but losing the
952 fusion can be.
953
954 \begin{code}
955 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
956         -- Examines a bndr to see if it is used just once in a 
957         -- completely safe way, so that it is safe to discard the binding
958         -- inline its RHS at the (unique) usage site, REGARDLESS of how
959         -- big the RHS might be.  If this is the case we don't simplify
960         -- the RHS first, but just inline it un-simplified.
961         --
962         -- This is much better than first simplifying a perhaps-huge RHS
963         -- and then inlining and re-simplifying it.
964         --
965         -- NB: we don't even look at the RHS to see if it's trivial
966         -- We might have
967         --                      x = y
968         -- where x is used many times, but this is the unique occurrence
969         -- of y.  We should NOT inline x at all its uses, because then
970         -- we'd do the same for y -- aargh!  So we must base this
971         -- pre-rhs-simplification decision solely on x's occurrences, not
972         -- on its rhs.
973         -- 
974         -- Evne RHSs labelled InlineMe aren't caught here, because
975         -- there might be no benefit from inlining at the call site.
976
977 preInlineUnconditionally black_listed bndr
978   | black_listed || opt_SimplNoPreInlining = False
979   | otherwise = case getIdOccInfo bndr of
980                   OneOcc in_lam once -> not in_lam && once
981                         -- Not inside a lambda, one occurrence ==> safe!
982                   other              -> False
983
984
985 postInlineUnconditionally :: Bool       -- Black listed
986                           -> OccInfo
987                           -> InId -> OutExpr -> Bool
988         -- Examines a (bndr = rhs) binding, AFTER the rhs has been simplified
989         -- It returns True if it's ok to discard the binding and inline the
990         -- RHS at every use site.
991
992         -- NOTE: This isn't our last opportunity to inline.
993         -- We're at the binding site right now, and
994         -- we'll get another opportunity when we get to the ocurrence(s)
995
996 postInlineUnconditionally black_listed occ_info bndr rhs
997   | isExportedId bndr   || 
998     black_listed        || 
999     loop_breaker        = False                 -- Don't inline these
1000   | otherwise           = exprIsTrivial rhs     -- Duplicating is free
1001         -- Don't inline even WHNFs inside lambdas; doing so may
1002         -- simply increase allocation when the function is called
1003         -- This isn't the last chance; see NOTE above.
1004         --
1005         -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
1006         -- Why?  Because we don't even want to inline them into the
1007         -- RHS of constructor arguments. See NOTE above
1008         --
1009         -- NB: Even NOINLINEis ignored here: if the rhs is trivial
1010         -- it's best to inline it anyway.  We often get a=E; b=a
1011         -- from desugaring, with both a and b marked NOINLINE.
1012   where
1013     loop_breaker = case occ_info of
1014                         IAmALoopBreaker -> True
1015                         other           -> False
1016 \end{code}
1017
1018
1019
1020 %************************************************************************
1021 %*                                                                      *
1022 \subsection{The main rebuilder}
1023 %*                                                                      *
1024 %************************************************************************
1025
1026 \begin{code}
1027 -------------------------------------------------------------------
1028 -- Finish rebuilding
1029 rebuild_done expr
1030   = getInScope                  `thenSmpl` \ in_scope ->
1031     returnSmpl ([], (in_scope, expr))
1032
1033 ---------------------------------------------------------
1034 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1035
1036 --      Stop continuation
1037 rebuild expr (Stop _) = rebuild_done expr
1038
1039 --      ArgOf continuation
1040 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1041
1042 --      ApplyTo continuation
1043 rebuild expr cont@(ApplyTo _ arg se cont')
1044   = setSubstEnv se (simplExpr arg)      `thenSmpl` \ arg' ->
1045     rebuild (App expr arg') cont'
1046
1047 --      Coerce continuation
1048 rebuild expr (CoerceIt to_ty cont)
1049   = rebuild (mkCoerce to_ty expr) cont
1050
1051 --      Inline continuation
1052 rebuild expr (InlinePlease cont)
1053   = rebuild (Note InlineCall expr) cont
1054
1055 rebuild scrut (Select _ bndr alts se cont)
1056   = rebuild_case scrut bndr alts se cont
1057
1058 \end{code}
1059
1060 Case elimination [see the code above]
1061 ~~~~~~~~~~~~~~~~
1062 Start with a simple situation:
1063
1064         case x# of      ===>   e[x#/y#]
1065           y# -> e
1066
1067 (when x#, y# are of primitive type, of course).  We can't (in general)
1068 do this for algebraic cases, because we might turn bottom into
1069 non-bottom!
1070
1071 Actually, we generalise this idea to look for a case where we're
1072 scrutinising a variable, and we know that only the default case can
1073 match.  For example:
1074 \begin{verbatim}
1075         case x of
1076           0#    -> ...
1077           other -> ...(case x of
1078                          0#    -> ...
1079                          other -> ...) ...
1080 \end{code}
1081 Here the inner case can be eliminated.  This really only shows up in
1082 eliminating error-checking code.
1083
1084 We also make sure that we deal with this very common case:
1085
1086         case e of 
1087           x -> ...x...
1088
1089 Here we are using the case as a strict let; if x is used only once
1090 then we want to inline it.  We have to be careful that this doesn't 
1091 make the program terminate when it would have diverged before, so we
1092 check that 
1093         - x is used strictly, or
1094         - e is already evaluated (it may so if e is a variable)
1095
1096 Lastly, we generalise the transformation to handle this:
1097
1098         case e of       ===> r
1099            True  -> r
1100            False -> r
1101
1102 We only do this for very cheaply compared r's (constructors, literals
1103 and variables).  If pedantic bottoms is on, we only do it when the
1104 scrutinee is a PrimOp which can't fail.
1105
1106 We do it *here*, looking at un-simplified alternatives, because we
1107 have to check that r doesn't mention the variables bound by the
1108 pattern in each alternative, so the binder-info is rather useful.
1109
1110 So the case-elimination algorithm is:
1111
1112         1. Eliminate alternatives which can't match
1113
1114         2. Check whether all the remaining alternatives
1115                 (a) do not mention in their rhs any of the variables bound in their pattern
1116            and  (b) have equal rhss
1117
1118         3. Check we can safely ditch the case:
1119                    * PedanticBottoms is off,
1120                 or * the scrutinee is an already-evaluated variable
1121                 or * the scrutinee is a primop which is ok for speculation
1122                         -- ie we want to preserve divide-by-zero errors, and
1123                         -- calls to error itself!
1124
1125                 or * [Prim cases] the scrutinee is a primitive variable
1126
1127                 or * [Alg cases] the scrutinee is a variable and
1128                      either * the rhs is the same variable
1129                         (eg case x of C a b -> x  ===>   x)
1130                      or     * there is only one alternative, the default alternative,
1131                                 and the binder is used strictly in its scope.
1132                                 [NB this is helped by the "use default binder where
1133                                  possible" transformation; see below.]
1134
1135
1136 If so, then we can replace the case with one of the rhss.
1137
1138
1139 Blob of helper functions for the "case-of-something-else" situation.
1140
1141 \begin{code}
1142
1143 ---------------------------------------------------------
1144 --      Case of known constructor or literal
1145
1146 rebuild_case scrut@(Con con args) bndr alts se cont
1147   | conOkForAlt con     -- Knocks out PrimOps and NoRepLits
1148   = knownCon scrut con args bndr alts se cont
1149
1150 ---------------------------------------------------------
1151 --      Eliminate the case if possible
1152
1153 rebuild_case scrut bndr alts se cont
1154   |     -- Check that the RHSs are all the same, and
1155         -- don't use the binders in the alternatives
1156         -- This test succeeds rapidly in the common case of
1157         -- a single DEFAULT alternative
1158     all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1159
1160         -- Check that the scrutinee can be let-bound instead of case-bound
1161     && (   exprOkForSpeculation scrut
1162                 -- OK not to evaluate it
1163                 -- This includes things like (==# a# b#)::Bool
1164                 -- so that we simplify 
1165                 --      case ==# a# b# of { True -> x; False -> x }
1166                 -- to just
1167                 --      x
1168                 -- This particular example shows up in default methods for
1169                 -- comparision operations (e.g. in (>=) for Int.Int32)
1170         || exprIsValue scrut                    -- It's already evaluated
1171         || var_demanded_later scrut             -- It'll be demanded later
1172
1173 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1174 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1175 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1176 --      its argument:  case x of { y -> dataToTag# y }
1177 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1178 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1179 --      other problems
1180        )
1181
1182 --    && opt_SimplDoCaseElim
1183 --      [June 99; don't test this flag.  The code generator dies if it sees
1184 --              case (\x.e) of f -> ...  
1185 --      so better to always do it
1186
1187         -- Get rid of the case altogether
1188         -- See the extensive notes on case-elimination above
1189         -- Remember to bind the binder though!
1190   = tick (CaseElim bndr)                        `thenSmpl_` (
1191     setSubstEnv se                              $                       
1192     simplBinder bndr                            $ \ bndr' ->
1193     completeBinding bndr bndr' False False scrut        $
1194     simplExprF rhs1 cont)
1195
1196   where
1197     (rhs1:other_rhss)            = [rhs | (_,_,rhs) <- alts]
1198     binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1199
1200     var_demanded_later (Var v) = isStrict (getIdDemandInfo bndr)        -- It's going to be evaluated later
1201     var_demanded_later other   = False
1202
1203 ---------------------------------------------------------
1204 --      Case of something else
1205
1206 rebuild_case scrut case_bndr alts se cont
1207   =     -- Prepare case alternatives
1208     prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1209                     scrut_cons alts             `thenSmpl` \ better_alts ->
1210     
1211         -- Set the new subst-env in place (before dealing with the case binder)
1212     setSubstEnv se                              $
1213
1214         -- Deal with the case binder, and prepare the continuation;
1215         -- The new subst_env is in place
1216     prepareCaseCont better_alts cont            $ \ cont' ->
1217         
1218
1219         -- Deal with variable scrutinee
1220     (   simplCaseBinder scrut case_bndr         $ \ case_bndr' zap_occ_info ->
1221
1222         -- Deal with the case alternatives
1223         simplAlts zap_occ_info scrut_cons 
1224                   case_bndr' better_alts cont'  `thenSmpl` \ alts' ->
1225
1226         mkCase scrut case_bndr' alts'
1227     )                                           `thenSmpl` \ case_expr ->
1228
1229         -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1230         -- over the rebuild_done; rebuild_done returns the in-scope set, and
1231         -- that should not include these chaps!
1232     rebuild_done case_expr      
1233   where
1234         -- scrut_cons tells what constructors the scrutinee can't possibly match
1235     scrut_cons = case scrut of
1236                    Var v -> otherCons (getIdUnfolding v)
1237                    other -> []
1238
1239
1240 knownCon expr con args bndr alts se cont
1241   = tick (KnownBranch bndr)     `thenSmpl_`
1242     setSubstEnv se              (
1243     simplBinder bndr            $ \ bndr' ->
1244     case findAlt con alts of
1245         (DEFAULT, bs, rhs)     -> ASSERT( null bs )
1246                                   completeBinding bndr bndr' False False expr $
1247                                         -- Don't use completeBeta here.  The expr might be
1248                                         -- an unboxed literal, like 3, or a variable
1249                                         -- whose unfolding is an unboxed literal... and
1250                                         -- completeBeta will just construct another case
1251                                         -- expression!
1252                                   simplExprF rhs cont
1253
1254         (Literal lit, bs, rhs) -> ASSERT( null bs )
1255                                   extendSubst bndr (DoneEx expr)        $
1256                                         -- Unconditionally substitute, because expr must
1257                                         -- be a variable or a literal.  It can't be a
1258                                         -- NoRep literal because they don't occur in
1259                                         -- case patterns.
1260                                   simplExprF rhs cont
1261
1262         (DataCon dc, bs, rhs)  -> ASSERT( length bs == length real_args )
1263                                   completeBinding bndr bndr' False False expr   $
1264                                         -- See note above
1265                                   extendSubstList bs (map mk real_args) $
1266                                   simplExprF rhs cont
1267                                where
1268                                   real_args    = drop (dataConNumInstArgs dc) args
1269                                   mk (Type ty) = DoneTy ty
1270                                   mk other     = DoneEx other
1271     )
1272 \end{code}
1273
1274 \begin{code}
1275 prepareCaseCont :: [InAlt] -> SimplCont
1276                 -> (SimplCont -> SimplM (OutStuff a))
1277                 -> SimplM (OutStuff a)
1278         -- Polymorphic recursion here!
1279
1280 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1281 prepareCaseCont alts  cont thing_inside = simplType (coreAltsType alts)         `thenSmpl` \ alts_ty ->
1282                                           mkDupableCont alts_ty cont thing_inside
1283         -- At one time I passed in the un-simplified type, and simplified
1284         -- it only if we needed to construct a join binder, but that    
1285         -- didn't work because we have to decompse function types
1286         -- (using funResultTy) in mkDupableCont.
1287 \end{code}
1288
1289 simplCaseBinder checks whether the scrutinee is a variable, v.
1290 If so, try to eliminate uses of v in the RHSs in favour of case_bndr; 
1291 that way, there's a chance that v will now only be used once, and hence inlined.
1292
1293 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1294 in the case binder, because the case-binder now effectively occurs
1295 whenever v does.  AND we have to do the same for the pattern-bound
1296 variables!  Example:
1297
1298         (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1299
1300 Here, b and p are dead.  But when we move the argment inside the first
1301 case RHS, and eliminate the second case, we get
1302
1303         case x or { (a,b) -> a b }
1304
1305 Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
1306 happened.  Hence the zap_occ_info function returned by simplCaseBinder
1307
1308 \begin{code}
1309 simplCaseBinder (Var v) case_bndr thing_inside
1310   = simplBinder (zap case_bndr)                                 $ \ case_bndr' ->
1311     modifyInScope v case_bndr'                                  $
1312         -- We could extend the substitution instead, but it would be
1313         -- a hack because then the substitution wouldn't be idempotent
1314         -- any more (v is an OutId).  And this just just as well.
1315     thing_inside case_bndr' zap
1316   where
1317     zap b = b `setIdOccInfo` NoOccInfo
1318             
1319 simplCaseBinder other_scrut case_bndr thing_inside
1320   = simplBinder case_bndr               $ \ case_bndr' ->
1321     thing_inside case_bndr' (\ bndr -> bndr)    -- NoOp on bndr
1322 \end{code}
1323
1324 prepareCaseAlts does two things:
1325
1326 1.  Remove impossible alternatives
1327
1328 2.  If the DEFAULT alternative can match only one possible constructor,
1329     then make that constructor explicit.
1330     e.g.
1331         case e of x { DEFAULT -> rhs }
1332      ===>
1333         case e of x { (a,b) -> rhs }
1334     where the type is a single constructor type.  This gives better code
1335     when rhs also scrutinises x or e.
1336
1337 \begin{code}
1338 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1339   | isDataTyCon tycon
1340   = case (findDefault filtered_alts, missing_cons) of
1341
1342         ((alts_no_deflt, Just rhs), [data_con])         -- Just one missing constructor!
1343                 -> tick (FillInCaseDefault bndr)        `thenSmpl_`
1344                    let
1345                         (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1346                    in
1347                    getUniquesSmpl (length ex_tyvars)                            `thenSmpl` \ tv_uniqs ->
1348                    let
1349                         ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
1350                         mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1351                    in
1352                    newIds (dataConArgTys
1353                                 data_con
1354                                 (inst_tys ++ mkTyVarTys ex_tyvars'))            $ \ bndrs ->
1355                    returnSmpl ((DataCon data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1356
1357         other -> returnSmpl filtered_alts
1358   where
1359         -- Filter out alternatives that can't possibly match
1360     filtered_alts = case scrut_cons of
1361                         []    -> alts
1362                         other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1363
1364     missing_cons = [data_con | data_con <- tyConDataCons tycon, 
1365                                not (data_con `elem` handled_data_cons)]
1366     handled_data_cons = [data_con | DataCon data_con         <- scrut_cons] ++
1367                         [data_con | (DataCon data_con, _, _) <- filtered_alts]
1368
1369 -- The default case
1370 prepareCaseAlts _ _ scrut_cons alts
1371   = returnSmpl alts                     -- Functions
1372
1373
1374 ----------------------
1375 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1376   = mapSmpl simpl_alt alts
1377   where
1378     inst_tys' = case splitTyConApp_maybe (idType case_bndr') of
1379                         Just (tycon, inst_tys) -> inst_tys
1380
1381         -- handled_cons is all the constructors that are dealt
1382         -- with, either by being impossible, or by there being an alternative
1383     handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1384
1385     simpl_alt (DEFAULT, _, rhs)
1386         =       -- In the default case we record the constructors that the
1387                 -- case-binder *can't* be.
1388                 -- We take advantage of any OtherCon info in the case scrutinee
1389           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons)        $ 
1390           simplExprC rhs cont'                                                  `thenSmpl` \ rhs' ->
1391           returnSmpl (DEFAULT, [], rhs')
1392
1393     simpl_alt (con, vs, rhs)
1394         =       -- Deal with the pattern-bound variables
1395                 -- Mark the ones that are in ! positions in the data constructor
1396                 -- as certainly-evaluated.
1397                 -- NB: it happens that simplBinders does *not* erase the OtherCon
1398                 --     form of unfolding, so it's ok to add this info before 
1399                 --     doing simplBinders
1400           simplBinders (add_evals con vs)                                       $ \ vs' ->
1401
1402                 -- Bind the case-binder to (Con args)
1403           let
1404                 con_app = Con con (map Type inst_tys' ++ map varToCoreExpr vs')
1405           in
1406           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkUnfolding False con_app)      $
1407           simplExprC rhs cont'          `thenSmpl` \ rhs' ->
1408           returnSmpl (con, vs', rhs')
1409
1410
1411         -- add_evals records the evaluated-ness of the bound variables of
1412         -- a case pattern.  This is *important*.  Consider
1413         --      data T = T !Int !Int
1414         --
1415         --      case x of { T a b -> T (a+1) b }
1416         --
1417         -- We really must record that b is already evaluated so that we don't
1418         -- go and re-evaluate it when constructing the result.
1419
1420     add_evals (DataCon dc) vs = cat_evals vs (dataConRepStrictness dc)
1421     add_evals other_con    vs = vs
1422
1423     cat_evals [] [] = []
1424     cat_evals (v:vs) (str:strs)
1425         | isTyVar v    = v                                   : cat_evals vs (str:strs)
1426         | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1427         | otherwise    = v'                                  : cat_evals vs strs
1428         where
1429           v' = zap_occ_info v
1430 \end{code}
1431
1432
1433 %************************************************************************
1434 %*                                                                      *
1435 \subsection{Duplicating continuations}
1436 %*                                                                      *
1437 %************************************************************************
1438
1439 \begin{code}
1440 mkDupableCont :: OutType                -- Type of the thing to be given to the continuation
1441               -> SimplCont 
1442               -> (SimplCont -> SimplM (OutStuff a))
1443               -> SimplM (OutStuff a)
1444 mkDupableCont ty cont thing_inside 
1445   | contIsDupable cont
1446   = thing_inside cont
1447
1448 mkDupableCont _ (CoerceIt ty cont) thing_inside
1449   = mkDupableCont ty cont               $ \ cont' ->
1450     thing_inside (CoerceIt ty cont')
1451
1452 mkDupableCont ty (InlinePlease cont) thing_inside
1453   = mkDupableCont ty cont               $ \ cont' ->
1454     thing_inside (InlinePlease cont')
1455
1456 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1457   =     -- Build the RHS of the join point
1458     newId join_arg_ty                                   ( \ arg_id ->
1459         cont_fn (Var arg_id)                            `thenSmpl` \ (binds, (_, rhs)) ->
1460         returnSmpl (Lam (setOneShotLambda arg_id) (mkLets binds rhs))
1461     )                                                   `thenSmpl` \ join_rhs ->
1462    
1463         -- Build the join Id and continuation
1464     newId (coreExprType join_rhs)               $ \ join_id ->
1465     let
1466         new_cont = ArgOf OkToDup cont_ty
1467                          (\arg' -> rebuild_done (App (Var join_id) arg'))
1468     in
1469
1470     tick (CaseOfCase join_id)                                           `thenSmpl_`
1471         -- Want to tick here so that we go round again,
1472         -- and maybe copy or inline the code;
1473         -- not strictly CaseOf Case
1474     thing_inside new_cont               `thenSmpl` \ res ->
1475     returnSmpl (addBind (NonRec join_id join_rhs) res)
1476
1477 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1478   = mkDupableCont (funResultTy ty) cont                 $ \ cont' ->
1479     setSubstEnv se (simplExpr arg)                      `thenSmpl` \ arg' ->
1480     if exprIsDupable arg' then
1481         thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1482     else
1483     newId (coreExprType arg')                                           $ \ bndr ->
1484
1485     tick (CaseOfCase bndr)                                              `thenSmpl_`
1486         -- Want to tick here so that we go round again,
1487         -- and maybe copy or inline the code;
1488         -- not strictly CaseOf Case
1489     thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')       `thenSmpl` \ res ->
1490     returnSmpl (addBind (NonRec bndr arg') res)
1491
1492 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1493   = tick (CaseOfCase case_bndr)                                         `thenSmpl_`
1494     setSubstEnv se (
1495         simplBinder case_bndr                                           $ \ case_bndr' ->
1496         prepareCaseCont alts cont                                       $ \ cont' ->
1497         mapAndUnzipSmpl (mkDupableAlt case_bndr case_bndr' cont') alts  `thenSmpl` \ (alt_binds_s, alts') ->
1498         returnSmpl (concat alt_binds_s, alts')
1499     )                                   `thenSmpl` \ (alt_binds, alts') ->
1500
1501     extendInScopes [b | NonRec b _ <- alt_binds]                $
1502
1503         -- NB that the new alternatives, alts', are still InAlts, using the original
1504         -- binders.  That means we can keep the case_bndr intact. This is important
1505         -- because another case-of-case might strike, and so we want to keep the
1506         -- info that the case_bndr is dead (if it is, which is often the case).
1507         -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1508         -- case in I/O rich code.  We aren't allowed a lambda bound
1509         -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1510     thing_inside (Select OkToDup case_bndr alts' se (Stop (contResultType cont)))       `thenSmpl` \ res ->
1511
1512     returnSmpl (addBinds alt_binds res)
1513
1514
1515 mkDupableAlt :: InId -> OutId -> SimplCont -> InAlt -> SimplM (OutStuff InAlt)
1516 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs)
1517   = simplBinders bndrs                                  $ \ bndrs' ->
1518     simplExprC rhs cont                                 `thenSmpl` \ rhs' ->
1519
1520     if (case cont of { Stop _ -> exprIsDupable rhs'; other -> False}) then
1521         -- It is worth checking for a small RHS because otherwise we
1522         -- get extra let bindings that may cause an extra iteration of the simplifier to
1523         -- inline back in place.  Quite often the rhs is just a variable or constructor.
1524         -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1525         -- iterations because the version with the let bindings looked big, and so wasn't
1526         -- inlined, but after the join points had been inlined it looked smaller, and so
1527         -- was inlined.
1528         --
1529         -- But since the continuation is absorbed into the rhs, we only do this
1530         -- for a Stop continuation.
1531         --
1532         -- NB: we have to check the size of rhs', not rhs. 
1533         -- Duplicating a small InAlt might invalidate occurrence information
1534         -- However, if it *is* dupable, we return the *un* simplified alternative,
1535         -- because otherwise we'd need to pair it up with an empty subst-env.
1536         -- (Remember we must zap the subst-env before re-simplifying something).
1537         -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1538         returnSmpl ([], alt)
1539
1540     else
1541     let
1542         rhs_ty' = coreExprType rhs'
1543         (used_bndrs, used_bndrs')
1544            = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr  : bndrs)
1545                                                 (case_bndr' : bndrs'),
1546                          not (isDeadBinder bndr)]
1547                 -- The new binders have lost their occurrence info,
1548                 -- so we have to extract it from the old ones
1549     in
1550     ( if null used_bndrs' 
1551         -- If we try to lift a primitive-typed something out
1552         -- for let-binding-purposes, we will *caseify* it (!),
1553         -- with potentially-disastrous strictness results.  So
1554         -- instead we turn it into a function: \v -> e
1555         -- where v::State# RealWorld#.  The value passed to this function
1556         -- is realworld#, which generates (almost) no code.
1557
1558         -- There's a slight infelicity here: we pass the overall 
1559         -- case_bndr to all the join points if it's used in *any* RHS,
1560         -- because we don't know its usage in each RHS separately
1561
1562         -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1563         -- we make the join point into a function whenever used_bndrs'
1564         -- is empty.  This makes the join-point more CPR friendly. 
1565         -- Consider:    let j = if .. then I# 3 else I# 4
1566         --              in case .. of { A -> j; B -> j; C -> ... }
1567         --
1568         -- Now CPR should not w/w j because it's a thunk, so
1569         -- that means that the enclosing function can't w/w either,
1570         -- which is a lose.  Here's the example that happened in practice:
1571         --      kgmod :: Int -> Int -> Int
1572         --      kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1573         --                  then 78
1574         --                  else 5
1575
1576         then newId realWorldStatePrimTy  $ \ rw_id ->
1577              returnSmpl ([rw_id], [Var realWorldPrimId])
1578         else 
1579              returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1580     )
1581         `thenSmpl` \ (final_bndrs', final_args) ->
1582
1583     newId (foldr (mkFunTy . idType) rhs_ty' final_bndrs')       $ \ join_bndr ->
1584
1585         -- Notice that we make the lambdas into one-shot-lambdas.  The
1586         -- join point is sure to be applied at most once, and doing so
1587         -- prevents the body of the join point being floated out by
1588         -- the full laziness pass
1589     returnSmpl ([NonRec join_bndr (mkLams (map setOneShotLambda final_bndrs') rhs')],
1590                 (con, bndrs, mkApps (Var join_bndr) final_args))
1591 \end{code}