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