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