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