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