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