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