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