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