2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[Simplify]{The main module of the simplifier}
7 module Simplify ( simplTopBinds, simplExpr ) where
9 #include "HsVersions.h"
11 import CmdLineOpts ( switchIsOn, opt_SimplDoEtaReduction,
12 opt_SimplNoPreInlining,
13 dopt, DynFlag(Opt_D_dump_inlinings),
17 import SimplUtils ( mkCase, tryRhsTyLam, tryEtaExpansion, findAlt,
18 simplBinder, simplBinders, simplIds, findDefault,
19 SimplCont(..), DupFlag(..), mkStop, mkRhsStop,
20 contResultType, discardInline, countArgs, contIsDupable,
21 getContArgs, interestingCallContext, interestingArg, isStrictType
23 import Var ( mkSysTyVar, tyVarKind )
25 import VarSet ( elemVarSet )
26 import Id ( Id, idType, idInfo, isDataConId,
27 idUnfolding, setIdUnfolding, isExportedId, isDeadBinder,
28 idDemandInfo, setIdInfo,
29 idOccInfo, setIdOccInfo,
30 zapLamIdInfo, setOneShotLambda,
32 import IdInfo ( OccInfo(..), isDeadOcc, isLoopBreaker,
34 setUnfoldingInfo, atLeastArity,
37 import Demand ( isStrict )
38 import DataCon ( dataConNumInstArgs, dataConRepStrictness,
39 dataConSig, dataConArgTys
42 import PprCore ( pprParendExpr, pprCoreExpr )
43 import CoreFVs ( mustHaveLocalBinding, exprFreeVars )
44 import CoreUnfold ( mkOtherCon, mkUnfolding, otherCons,
47 import CoreUtils ( cheapEqExpr, exprIsDupable, exprIsTrivial,
48 exprIsConApp_maybe, mkPiType,
49 exprType, coreAltsType, exprIsValue,
50 exprOkForSpeculation, exprArity, exprIsCheap,
51 mkCoerce, mkSCC, mkInlineMe, mkAltExpr
53 import Rules ( lookupRule )
54 import CostCentre ( currentCCS )
55 import Type ( mkTyVarTys, isUnLiftedType, seqType,
56 mkFunTy, splitTyConApp_maybe, tyConAppArgs,
59 import Subst ( mkSubst, substTy,
60 isInScope, lookupIdSubst, substIdInfo
62 import TyCon ( isDataTyCon, tyConDataConsIfAvailable )
63 import TysPrim ( realWorldStatePrimTy )
64 import PrelInfo ( realWorldPrimId )
66 import Maybes ( maybeToBool )
67 import Util ( zipWithEqual )
72 The guts of the simplifier is in this module, but the driver
73 loop for the simplifier is in SimplCore.lhs.
76 -----------------------------------------
77 *** IMPORTANT NOTE ***
78 -----------------------------------------
79 The simplifier used to guarantee that the output had no shadowing, but
80 it does not do so any more. (Actually, it never did!) The reason is
81 documented with simplifyArgs.
86 %************************************************************************
90 %************************************************************************
93 simplTopBinds :: [InBind] -> SimplM [OutBind]
96 = -- Put all the top-level binders into scope at the start
97 -- so that if a transformation rule has unexpectedly brought
98 -- anything into scope, then we don't get a complaint about that.
99 -- It's rather as if the top-level binders were imported.
100 simplIds (bindersOfBinds binds) $ \ bndrs' ->
101 simpl_binds binds bndrs' `thenSmpl` \ (binds', _) ->
102 freeTick SimplifierDone `thenSmpl_`
103 returnSmpl (fromOL binds')
106 -- We need to track the zapped top-level binders, because
107 -- they should have their fragile IdInfo zapped (notably occurrence info)
108 simpl_binds [] bs = ASSERT( null bs ) returnSmpl (nilOL, panic "simplTopBinds corner")
109 simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr b rhs (simpl_binds binds bs)
110 simpl_binds (Rec pairs : binds) bs = simplRecBind True pairs (take n bs) (simpl_binds binds (drop n bs))
114 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
115 -> SimplM (OutStuff a) -> SimplM (OutStuff a)
116 simplRecBind top_lvl pairs bndrs' thing_inside
117 = go pairs bndrs' `thenSmpl` \ (binds', (_, (binds'', res))) ->
118 returnSmpl (unitOL (Rec (flattenBinds (fromOL binds'))) `appOL` binds'', res)
120 go [] _ = thing_inside `thenSmpl` \ stuff ->
123 go ((bndr, rhs) : pairs) (bndr' : bndrs')
124 = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
125 -- Don't float unboxed bindings out,
126 -- because we can't "rec" them
130 %************************************************************************
132 \subsection[Simplify-simplExpr]{The main function: simplExpr}
134 %************************************************************************
136 The reason for this OutExprStuff stuff is that we want to float *after*
137 simplifying a RHS, not before. If we do so naively we get quadratic
138 behaviour as things float out.
140 To see why it's important to do it after, consider this (real) example:
154 a -- Can't inline a this round, cos it appears twice
158 Each of the ==> steps is a round of simplification. We'd save a
159 whole round if we float first. This can cascade. Consider
164 let f = let d1 = ..d.. in \y -> e
168 in \x -> ...(\y ->e)...
170 Only in this second round can the \y be applied, and it
171 might do the same again.
175 simplExpr :: CoreExpr -> SimplM CoreExpr
176 simplExpr expr = getSubst `thenSmpl` \ subst ->
177 simplExprC expr (mkStop (substTy subst (exprType expr)))
178 -- The type in the Stop continuation is usually not used
179 -- It's only needed when discarding continuations after finding
180 -- a function that returns bottom.
181 -- Hence the lazy substitution
183 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
184 -- Simplify an expression, given a continuation
186 simplExprC expr cont = simplExprF expr cont `thenSmpl` \ (floats, (_, body)) ->
187 returnSmpl (wrapFloats floats body)
189 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
190 -- Simplify an expression, returning floated binds
192 simplExprF (Var v) cont
195 simplExprF (Lit lit) (Select _ bndr alts se cont)
196 = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
198 simplExprF (Lit lit) cont
199 = rebuild (Lit lit) cont
201 simplExprF (App fun arg) cont
202 = getSubstEnv `thenSmpl` \ se ->
203 simplExprF fun (ApplyTo NoDup arg se cont)
205 simplExprF (Case scrut bndr alts) cont
206 = getSubstEnv `thenSmpl` \ subst_env ->
207 getSwitchChecker `thenSmpl` \ chkr ->
208 if not (switchIsOn chkr NoCaseOfCase) then
209 -- Simplify the scrutinee with a Select continuation
210 simplExprF scrut (Select NoDup bndr alts subst_env cont)
213 -- If case-of-case is off, simply simplify the case expression
214 -- in a vanilla Stop context, and rebuild the result around it
215 simplExprC scrut (Select NoDup bndr alts subst_env
216 (mkStop (contResultType cont))) `thenSmpl` \ case_expr' ->
217 rebuild case_expr' cont
220 simplExprF (Let (Rec pairs) body) cont
221 = simplIds (map fst pairs) $ \ bndrs' ->
222 -- NB: bndrs' don't have unfoldings or spec-envs
223 -- We add them as we go down, using simplPrags
225 simplRecBind False pairs bndrs' (simplExprF body cont)
227 simplExprF expr@(Lam _ _) cont = simplLam expr cont
229 simplExprF (Type ty) cont
230 = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
231 simplType ty `thenSmpl` \ ty' ->
232 rebuild (Type ty') cont
234 -- Comments about the Coerce case
235 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
236 -- It's worth checking for a coerce in the continuation,
237 -- in case we can cancel them. For example, in the initial form of a worker
238 -- we may find (coerce T (coerce S (\x.e))) y
239 -- and we'd like it to simplify to e[y/x] in one round of simplification
241 simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
242 = simplType from `thenSmpl` \ from' ->
243 if outer_to == from' then
244 -- The coerces cancel out
247 -- They don't cancel, but the inner one is redundant
248 simplExprF e (CoerceIt outer_to cont)
250 simplExprF (Note (Coerce to from) e) cont
251 = simplType to `thenSmpl` \ to' ->
252 simplExprF e (CoerceIt to' cont)
254 -- hack: we only distinguish subsumed cost centre stacks for the purposes of
255 -- inlining. All other CCCSs are mapped to currentCCS.
256 simplExprF (Note (SCC cc) e) cont
257 = setEnclosingCC currentCCS $
258 simplExpr e `thenSmpl` \ e ->
259 rebuild (mkSCC cc e) cont
261 simplExprF (Note InlineCall e) cont
262 = simplExprF e (InlinePlease cont)
264 -- Comments about the InlineMe case
265 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266 -- Don't inline in the RHS of something that has an
267 -- inline pragma. But be careful that the InScopeEnv that
268 -- we return does still have inlinings on!
270 -- It really is important to switch off inlinings. This function
271 -- may be inlinined in other modules, so we don't want to remove
272 -- (by inlining) calls to functions that have specialisations, or
273 -- that may have transformation rules in an importing scope.
274 -- E.g. {-# INLINE f #-}
276 -- and suppose that g is strict *and* has specialisations.
277 -- If we inline g's wrapper, we deny f the chance of getting
278 -- the specialised version of g when f is inlined at some call site
279 -- (perhaps in some other module).
281 -- It's also important not to inline a worker back into a wrapper.
282 -- A wrapper looks like
283 -- wraper = inline_me (\x -> ...worker... )
284 -- Normally, the inline_me prevents the worker getting inlined into
285 -- the wrapper (initially, the worker's only call site!). But,
286 -- if the wrapper is sure to be called, the strictness analyser will
287 -- mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
288 -- continuation. That's why the keep_inline predicate returns True for
289 -- ArgOf continuations. It shouldn't do any harm not to dissolve the
290 -- inline-me note under these circumstances
292 simplExprF (Note InlineMe e) cont
293 | keep_inline cont -- Totally boring continuation
294 = -- Don't inline inside an INLINE expression
295 setBlackList noInlineBlackList (simplExpr e) `thenSmpl` \ e' ->
296 rebuild (mkInlineMe e') cont
298 | otherwise -- Dissolve the InlineMe note if there's
299 -- an interesting context of any kind to combine with
300 -- (even a type application -- anything except Stop)
303 keep_inline (Stop _ _) = True -- See notes above
304 keep_inline (ArgOf _ _ _) = True -- about this predicate
305 keep_inline other = False
307 -- A non-recursive let is dealt with by simplBeta
308 simplExprF (Let (NonRec bndr rhs) body) cont
309 = getSubstEnv `thenSmpl` \ se ->
310 simplBeta bndr rhs se (contResultType cont) $
315 ---------------------------------
321 zap_it = mkLamBndrZapper fun cont
322 cont_ty = contResultType cont
324 -- Type-beta reduction
325 go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
326 = ASSERT( isTyVar bndr )
327 tick (BetaReduction bndr) `thenSmpl_`
328 simplTyArg ty_arg arg_se `thenSmpl` \ ty_arg' ->
329 extendSubst bndr (DoneTy ty_arg')
332 -- Ordinary beta reduction
333 go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
334 = tick (BetaReduction bndr) `thenSmpl_`
335 simplBeta zapped_bndr arg arg_se cont_ty
338 zapped_bndr = zap_it bndr
341 go lam@(Lam _ _) cont = completeLam [] lam cont
343 -- Exactly enough args
344 go expr cont = simplExprF expr cont
346 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
347 -- continuation, so there are real lambdas left to put in the result
349 -- We try for eta reduction here, but *only* if we get all the
350 -- way to an exprIsTrivial expression.
351 -- We don't want to remove extra lambdas unless we are going
352 -- to avoid allocating this thing altogether
354 completeLam rev_bndrs (Lam bndr body) cont
355 = simplBinder bndr $ \ bndr' ->
356 completeLam (bndr':rev_bndrs) body cont
358 completeLam rev_bndrs body cont
359 = simplExpr body `thenSmpl` \ body' ->
360 case try_eta body' of
361 Just etad_lam -> tick (EtaReduction (head rev_bndrs)) `thenSmpl_`
362 rebuild etad_lam cont
364 Nothing -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
366 -- We don't use CoreUtils.etaReduce, because we can be more
367 -- efficient here: (a) we already have the binders, (b) we can do
368 -- the triviality test before computing the free vars
369 try_eta body | not opt_SimplDoEtaReduction = Nothing
370 | otherwise = go rev_bndrs body
372 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
373 go [] body | ok_body body = Just body -- Success!
374 go _ _ = Nothing -- Failure!
376 ok_body body = exprIsTrivial body && not (any (`elemVarSet` exprFreeVars body) rev_bndrs)
377 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
379 mkLamBndrZapper :: CoreExpr -- Function
380 -> SimplCont -- The context
381 -> Id -> Id -- Use this to zap the binders
382 mkLamBndrZapper fun cont
383 | n_args >= n_params fun = \b -> b -- Enough args
384 | otherwise = \b -> zapLamIdInfo b
386 -- NB: we count all the args incl type args
387 -- so we must count all the binders (incl type lambdas)
388 n_args = countArgs cont
390 n_params (Note _ e) = n_params e
391 n_params (Lam b e) = 1 + n_params e
392 n_params other = 0::Int
396 ---------------------------------
398 simplType :: InType -> SimplM OutType
400 = getSubst `thenSmpl` \ subst ->
402 new_ty = substTy subst ty
409 %************************************************************************
413 %************************************************************************
415 @simplBeta@ is used for non-recursive lets in expressions,
416 as well as true beta reduction.
418 Very similar to @simplLazyBind@, but not quite the same.
421 simplBeta :: InId -- Binder
422 -> InExpr -> SubstEnv -- Arg, with its subst-env
423 -> OutType -- Type of thing computed by the context
424 -> SimplM OutExprStuff -- The body
425 -> SimplM OutExprStuff
427 simplBeta bndr rhs rhs_se cont_ty thing_inside
429 = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
432 simplBeta bndr rhs rhs_se cont_ty thing_inside
433 | preInlineUnconditionally False {- not black listed -} bndr
434 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
435 extendSubst bndr (ContEx rhs_se rhs) thing_inside
438 = -- Simplify the RHS
439 simplBinder bndr $ \ bndr' ->
441 bndr_ty' = idType bndr'
442 is_strict = isStrict (idDemandInfo bndr) || isStrictType bndr_ty'
444 simplValArg bndr_ty' is_strict rhs rhs_se cont_ty $ \ rhs' ->
446 -- Now complete the binding and simplify the body
447 if needsCaseBinding bndr_ty' rhs' then
448 addCaseBind bndr' rhs' thing_inside
450 completeBinding bndr bndr' False False rhs' thing_inside
455 simplTyArg :: InType -> SubstEnv -> SimplM OutType
457 = getInScope `thenSmpl` \ in_scope ->
459 ty_arg' = substTy (mkSubst in_scope se) ty_arg
461 seqType ty_arg' `seq`
464 simplValArg :: OutType -- rhs_ty: Type of arg; used only occasionally
465 -> Bool -- True <=> evaluate eagerly
466 -> InExpr -> SubstEnv
467 -> OutType -- cont_ty: Type of thing computed by the context
468 -> (OutExpr -> SimplM OutExprStuff)
469 -- Takes an expression of type rhs_ty,
470 -- returns an expression of type cont_ty
471 -> SimplM OutExprStuff -- An expression of type cont_ty
473 simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
475 = getEnv `thenSmpl` \ env ->
477 simplExprF arg (ArgOf NoDup cont_ty $ \ rhs' ->
478 setAllExceptInScope env $
482 = simplRhs False {- Not top level -}
483 True {- OK to float unboxed -}
490 - deals only with Ids, not TyVars
491 - take an already-simplified RHS
493 It does *not* attempt to do let-to-case. Why? Because they are used for
496 (when let-to-case is impossible)
498 - many situations where the "rhs" is known to be a WHNF
499 (so let-to-case is inappropriate).
502 completeBinding :: InId -- Binder
503 -> OutId -- New binder
504 -> Bool -- True <=> top level
505 -> Bool -- True <=> black-listed; don't inline
506 -> OutExpr -- Simplified RHS
507 -> SimplM (OutStuff a) -- Thing inside
508 -> SimplM (OutStuff a)
510 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
511 | isDeadOcc occ_info -- This happens; for example, the case_bndr during case of
512 -- known constructor: case (a,b) of x { (p,q) -> ... }
513 -- Here x isn't mentioned in the RHS, so we don't want to
514 -- create the (dead) let-binding let x = (a,b) in ...
517 | trivial_rhs && not must_keep_binding
518 -- We're looking at a binding with a trivial RHS, so
519 -- perhaps we can discard it altogether!
521 -- NB: a loop breaker has must_keep_binding = True
522 -- and non-loop-breakers only have *forward* references
523 -- Hence, it's safe to discard the binding
525 -- NOTE: This isn't our last opportunity to inline.
526 -- We're at the binding site right now, and
527 -- we'll get another opportunity when we get to the ocurrence(s)
529 -- Note that we do this unconditional inlining only for trival RHSs.
530 -- Don't inline even WHNFs inside lambdas; doing so may
531 -- simply increase allocation when the function is called
532 -- This isn't the last chance; see NOTE above.
534 -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
535 -- Why? Because we don't even want to inline them into the
536 -- RHS of constructor arguments. See NOTE above
538 -- NB: Even NOINLINEis ignored here: if the rhs is trivial
539 -- it's best to inline it anyway. We often get a=E; b=a
540 -- from desugaring, with both a and b marked NOINLINE.
541 = -- Drop the binding
542 extendSubst old_bndr (DoneEx new_rhs) $
543 -- Use the substitution to make quite, quite sure that the substitution
544 -- will happen, since we are going to discard the binding
545 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
548 | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs,
549 not trivial_rhs && not (isUnLiftedType inner_ty)
550 -- x = coerce t e ==> c = e; x = inline_me (coerce t c)
551 -- Now x can get inlined, which moves the coercion
552 -- to the usage site. This is a bit like worker/wrapper stuff,
553 -- but it's useful to do it very promptly, so that
554 -- x = coerce T (I# 3)
558 -- This in turn means that
559 -- case (coerce Int x) of ...
561 -- Also the full-blown w/w thing isn't set up for non-functions
563 -- The (not (isUnLiftedType inner_ty)) avoids the nasty case of
564 -- x::Int = coerce Int Int# (foo y)
567 -- x::Int = coerce Int Int# v
568 -- which would be bogus because then v will be evaluated strictly.
569 -- How can this arise? Via
570 -- x::Int = case (foo y) of { ... }
571 -- followed by case elimination.
573 -- The inline_me note is so that the simplifier doesn't
574 -- just substitute c back inside x's rhs! (Typically, x will
575 -- get substituted away, but not if it's exported.)
576 = newId SLIT("c") inner_ty $ \ c_id ->
577 completeBinding c_id c_id top_lvl False inner_rhs $
578 completeBinding old_bndr new_bndr top_lvl black_listed
579 (Note InlineMe (Note coercion (Var c_id))) $
583 = getSubst `thenSmpl` \ subst ->
585 -- We make new IdInfo for the new binder by starting from the old binder,
586 -- doing appropriate substitutions.
587 -- Then we add arity and unfolding info to get the new binder
588 new_bndr_info = substIdInfo subst old_info (idInfo new_bndr)
589 `setArityInfo` arity_info
591 -- Add the unfolding *only* for non-loop-breakers
592 -- Making loop breakers not have an unfolding at all
593 -- means that we can avoid tests in exprIsConApp, for example.
594 -- This is important: if exprIsConApp says 'yes' for a recursive
595 -- thing, then we can get into an infinite loop
596 info_w_unf | loop_breaker = new_bndr_info
597 | otherwise = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
599 final_id = new_bndr `setIdInfo` info_w_unf
601 -- These seqs forces the Id, and hence its IdInfo,
602 -- and hence any inner substitutions
604 addLetBind (NonRec final_id new_rhs) $
605 modifyInScope new_bndr final_id thing_inside
608 old_info = idInfo old_bndr
609 occ_info = occInfo old_info
610 loop_breaker = isLoopBreaker occ_info
611 trivial_rhs = exprIsTrivial new_rhs
612 must_keep_binding = black_listed || loop_breaker || isExportedId old_bndr
613 arity_info = atLeastArity (exprArity new_rhs)
618 %************************************************************************
620 \subsection{simplLazyBind}
622 %************************************************************************
624 simplLazyBind basically just simplifies the RHS of a let(rec).
625 It does two important optimisations though:
627 * It floats let(rec)s out of the RHS, even if they
628 are hidden by big lambdas
630 * It does eta expansion
633 simplLazyBind :: Bool -- True <=> top level
636 -> SimplM (OutStuff a) -- The body of the binding
637 -> SimplM (OutStuff a)
638 -- When called, the subst env is correct for the entire let-binding
639 -- and hence right for the RHS.
640 -- Also the binder has already been simplified, and hence is in scope
642 simplLazyBind top_lvl bndr bndr' rhs thing_inside
643 = getBlackList `thenSmpl` \ black_list_fn ->
645 black_listed = black_list_fn bndr
648 if preInlineUnconditionally black_listed bndr then
649 -- Inline unconditionally
650 tick (PreInlineUnconditionally bndr) `thenSmpl_`
651 getSubstEnv `thenSmpl` \ rhs_se ->
652 (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
656 getSubstEnv `thenSmpl` \ rhs_se ->
657 simplRhs top_lvl False {- Not ok to float unboxed (conservative) -}
659 rhs rhs_se $ \ rhs' ->
661 -- Now compete the binding and simplify the body
662 completeBinding bndr bndr' top_lvl black_listed rhs' thing_inside
668 simplRhs :: Bool -- True <=> Top level
669 -> Bool -- True <=> OK to float unboxed (speculative) bindings
670 -- False for (a) recursive and (b) top-level bindings
671 -> OutType -- Type of RHS; used only occasionally
672 -> InExpr -> SubstEnv
673 -> (OutExpr -> SimplM (OutStuff a))
674 -> SimplM (OutStuff a)
675 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
677 setSubstEnv rhs_se (simplExprF rhs (mkRhsStop rhs_ty)) `thenSmpl` \ (floats1, (rhs_in_scope, rhs1)) ->
679 (floats2, rhs2) = splitFloats float_ubx floats1 rhs1
681 -- There's a subtlety here. There may be a binding (x* = e) in the
682 -- floats, where the '*' means 'will be demanded'. So is it safe
683 -- to float it out? Answer no, but it won't matter because
684 -- we only float if arg' is a WHNF,
685 -- and so there can't be any 'will be demanded' bindings in the floats.
687 WARN( any demanded_float (fromOL floats2), ppr (fromOL floats2) )
690 -- It's important that we do eta expansion on function *arguments* (which are
691 -- simplified with simplRhs), as well as let-bound right-hand sides.
692 -- Otherwise we find that things like
693 -- f (\x -> case x of I# x' -> coerce T (\ y -> ...))
694 -- get right through to the code generator as two separate lambdas,
695 -- which is a Bad Thing
696 tryRhsTyLam rhs2 `thenSmpl` \ (floats3, rhs3) ->
697 tryEtaExpansion rhs3 rhs_ty `thenSmpl` \ (floats4, rhs4) ->
699 -- Float lets if (a) we're at the top level
700 -- or (b) the resulting RHS is one we'd like to expose
701 if (top_lvl || exprIsCheap rhs4) then
702 (if (isNilOL floats2 && null floats3 && null floats4) then
705 tick LetFloatFromLet) `thenSmpl_`
707 addFloats floats2 rhs_in_scope $
708 addAuxiliaryBinds floats3 $
709 addAuxiliaryBinds floats4 $
712 -- Don't do the float
713 thing_inside (wrapFloats floats1 rhs1)
715 demanded_float (NonRec b r) = isStrict (idDemandInfo b) && not (isUnLiftedType (idType b))
716 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
717 demanded_float (Rec _) = False
719 -- If float_ubx is true we float all the bindings, otherwise
720 -- we just float until we come across an unlifted one.
721 -- Remember that the unlifted bindings in the floats are all for
722 -- guaranteed-terminating non-exception-raising unlifted things,
723 -- which we are happy to do speculatively. However, we may still
724 -- not be able to float them out, because the context
725 -- is either a Rec group, or the top level, neither of which
726 -- can tolerate them.
727 splitFloats float_ubx floats rhs
728 | float_ubx = (floats, rhs) -- Float them all
729 | otherwise = go (fromOL floats)
732 go (f:fs) | must_stay f = (nilOL, mkLets (f:fs) rhs)
733 | otherwise = case go fs of
734 (out, rhs') -> (f `consOL` out, rhs')
736 must_stay (Rec prs) = False -- No unlifted bindings in here
737 must_stay (NonRec b r) = isUnLiftedType (idType b)
742 %************************************************************************
744 \subsection{Variables}
746 %************************************************************************
750 = getSubst `thenSmpl` \ subst ->
751 case lookupIdSubst subst var of
752 DoneEx e -> zapSubstEnv (simplExprF e cont)
753 ContEx env1 e -> setSubstEnv env1 (simplExprF e cont)
754 DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
755 text "simplVar:" <+> ppr var )
756 zapSubstEnv (completeCall var1 occ cont)
757 -- The template is already simplified, so don't re-substitute.
758 -- This is VITAL. Consider
760 -- let y = \z -> ...x... in
762 -- We'll clone the inner \x, adding x->x' in the id_subst
763 -- Then when we inline y, we must *not* replace x by x' in
764 -- the inlined copy!!
766 ---------------------------------------------------------
767 -- Dealing with a call
769 completeCall var occ_info cont
770 = getBlackList `thenSmpl` \ black_list_fn ->
771 getInScope `thenSmpl` \ in_scope ->
772 getContArgs var cont `thenSmpl` \ (args, call_cont, inline_call) ->
773 getDOptsSmpl `thenSmpl` \ dflags ->
775 black_listed = black_list_fn var
776 arg_infos = [ interestingArg in_scope arg subst
777 | (arg, subst, _) <- args, isValArg arg]
779 interesting_cont = interestingCallContext (not (null args))
780 (not (null arg_infos))
783 inline_cont | inline_call = discardInline cont
786 maybe_inline = callSiteInline dflags black_listed inline_call occ_info
787 var arg_infos interesting_cont
789 -- First, look for an inlining
790 case maybe_inline of {
791 Just unfolding -- There is an inlining!
792 -> tick (UnfoldingDone var) `thenSmpl_`
793 simplExprF unfolding inline_cont
796 Nothing -> -- No inlining!
799 simplifyArgs (isDataConId var) args (contResultType call_cont) $ \ args' ->
801 -- Next, look for rules or specialisations that match
803 -- It's important to simplify the args first, because the rule-matcher
804 -- doesn't do substitution as it goes. We don't want to use subst_args
805 -- (defined in the 'where') because that throws away useful occurrence info,
806 -- and perhaps-very-important specialisations.
808 -- Some functions have specialisations *and* are strict; in this case,
809 -- we don't want to inline the wrapper of the non-specialised thing; better
810 -- to call the specialised thing instead.
811 -- But the black-listing mechanism means that inlining of the wrapper
812 -- won't occur for things that have specialisations till a later phase, so
813 -- it's ok to try for inlining first.
815 -- You might think that we shouldn't apply rules for a loop breaker:
816 -- doing so might give rise to an infinite loop, because a RULE is
817 -- rather like an extra equation for the function:
818 -- RULE: f (g x) y = x+y
821 -- But it's too drastic to disable rules for loop breakers.
822 -- Even the foldr/build rule would be disabled, because foldr
823 -- is recursive, and hence a loop breaker:
824 -- foldr k z (build g) = g k z
825 -- So it's up to the programmer: rules can cause divergence
827 getSwitchChecker `thenSmpl` \ chkr ->
829 maybe_rule | switchIsOn chkr DontApplyRules = Nothing
830 | otherwise = lookupRule in_scope var args'
833 Just (rule_name, rule_rhs) ->
834 tick (RuleFired rule_name) `thenSmpl_`
836 (if dopt Opt_D_dump_inlinings dflags then
837 pprTrace "Rule fired" (vcat [
838 text "Rule:" <+> ptext rule_name,
839 text "Before:" <+> ppr var <+> sep (map pprParendExpr args'),
840 text "After: " <+> pprCoreExpr rule_rhs])
844 simplExprF rule_rhs call_cont ;
846 Nothing -> -- No rules
849 rebuild (mkApps (Var var) args') call_cont
853 ---------------------------------------------------------
854 -- Simplifying the arguments of a call
856 simplifyArgs :: Bool -- It's a data constructor
857 -> [(InExpr, SubstEnv, Bool)] -- Details of the arguments
858 -> OutType -- Type of the continuation
859 -> ([OutExpr] -> SimplM OutExprStuff)
860 -> SimplM OutExprStuff
862 -- Simplify the arguments to a call.
863 -- This part of the simplifier may break the no-shadowing invariant
865 -- f (...(\a -> e)...) (case y of (a,b) -> e')
866 -- where f is strict in its second arg
867 -- If we simplify the innermost one first we get (...(\a -> e)...)
868 -- Simplifying the second arg makes us float the case out, so we end up with
869 -- case y of (a,b) -> f (...(\a -> e)...) e'
870 -- So the output does not have the no-shadowing invariant. However, there is
871 -- no danger of getting name-capture, because when the first arg was simplified
872 -- we used an in-scope set that at least mentioned all the variables free in its
873 -- static environment, and that is enough.
875 -- We can't just do innermost first, or we'd end up with a dual problem:
876 -- case x of (a,b) -> f e (...(\a -> e')...)
878 -- I spent hours trying to recover the no-shadowing invariant, but I just could
879 -- not think of an elegant way to do it. The simplifier is already knee-deep in
880 -- continuations. We have to keep the right in-scope set around; AND we have
881 -- to get the effect that finding (error "foo") in a strict arg position will
882 -- discard the entire application and replace it with (error "foo"). Getting
883 -- all this at once is TOO HARD!
885 simplifyArgs is_data_con args cont_ty thing_inside
887 = go args thing_inside
889 | otherwise -- It's a data constructor, so we want
890 -- to switch off inlining in the arguments
891 -- If we don't do this, consider:
892 -- let x = +# p q in C {x}
893 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
894 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
895 = getBlackList `thenSmpl` \ old_bl ->
896 setBlackList noInlineBlackList $
898 setBlackList old_bl $
902 go [] thing_inside = thing_inside []
903 go (arg:args) thing_inside = simplifyArg is_data_con arg cont_ty $ \ arg' ->
905 thing_inside (arg':args')
907 simplifyArg is_data_con (Type ty_arg, se, _) cont_ty thing_inside
908 = simplTyArg ty_arg se `thenSmpl` \ new_ty_arg ->
909 thing_inside (Type new_ty_arg)
911 simplifyArg is_data_con (val_arg, se, is_strict) cont_ty thing_inside
912 = getInScope `thenSmpl` \ in_scope ->
914 arg_ty = substTy (mkSubst in_scope se) (exprType val_arg)
916 if not is_data_con then
917 -- An ordinary function
918 simplValArg arg_ty is_strict val_arg se cont_ty thing_inside
920 -- A data constructor
921 -- simplifyArgs has already switched off inlining, so
922 -- all we have to do here is to let-bind any non-trivial argument
924 -- It's not always the case that new_arg will be trivial
926 -- where, in one pass, f gets substituted by a constructor,
927 -- but x gets substituted by an expression (assume this is the
928 -- unique occurrence of x). It doesn't really matter -- it'll get
929 -- fixed up next pass. And it happens for dictionary construction,
930 -- which mentions the wrapper constructor to start with.
931 simplValArg arg_ty is_strict val_arg se cont_ty $ \ arg' ->
933 if exprIsTrivial arg' then
936 newId SLIT("a") (exprType arg') $ \ arg_id ->
937 addNonRecBind arg_id arg' $
938 thing_inside (Var arg_id)
942 %************************************************************************
944 \subsection{Decisions about inlining}
946 %************************************************************************
948 NB: At one time I tried not pre/post-inlining top-level things,
949 even if they occur exactly once. Reason:
950 (a) some might appear as a function argument, so we simply
951 replace static allocation with dynamic allocation:
957 (b) some top level things might be black listed
959 HOWEVER, I found that some useful foldr/build fusion was lost (most
960 notably in spectral/hartel/parstof) because the foldr didn't see the build.
962 Doing the dynamic allocation isn't a big deal, in fact, but losing the
966 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
967 -- Examines a bndr to see if it is used just once in a
968 -- completely safe way, so that it is safe to discard the binding
969 -- inline its RHS at the (unique) usage site, REGARDLESS of how
970 -- big the RHS might be. If this is the case we don't simplify
971 -- the RHS first, but just inline it un-simplified.
973 -- This is much better than first simplifying a perhaps-huge RHS
974 -- and then inlining and re-simplifying it.
976 -- NB: we don't even look at the RHS to see if it's trivial
979 -- where x is used many times, but this is the unique occurrence
980 -- of y. We should NOT inline x at all its uses, because then
981 -- we'd do the same for y -- aargh! So we must base this
982 -- pre-rhs-simplification decision solely on x's occurrences, not
985 -- Evne RHSs labelled InlineMe aren't caught here, because
986 -- there might be no benefit from inlining at the call site.
988 preInlineUnconditionally black_listed bndr
989 | black_listed || opt_SimplNoPreInlining = False
990 | otherwise = case idOccInfo bndr of
991 OneOcc in_lam once -> not in_lam && once
992 -- Not inside a lambda, one occurrence ==> safe!
998 %************************************************************************
1000 \subsection{The main rebuilder}
1002 %************************************************************************
1005 -------------------------------------------------------------------
1006 -- Finish rebuilding
1007 rebuild_done expr = returnOutStuff expr
1009 ---------------------------------------------------------
1010 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1012 -- Stop continuation
1013 rebuild expr (Stop _ _) = rebuild_done expr
1015 -- ArgOf continuation
1016 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1018 -- ApplyTo continuation
1019 rebuild expr cont@(ApplyTo _ arg se cont')
1020 = setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1021 rebuild (App expr arg') cont'
1023 -- Coerce continuation
1024 rebuild expr (CoerceIt to_ty cont)
1025 = rebuild (mkCoerce to_ty (exprType expr) expr) cont
1027 -- Inline continuation
1028 rebuild expr (InlinePlease cont)
1029 = rebuild (Note InlineCall expr) cont
1031 rebuild scrut (Select _ bndr alts se cont)
1032 = rebuild_case scrut bndr alts se cont
1035 Case elimination [see the code above]
1037 Start with a simple situation:
1039 case x# of ===> e[x#/y#]
1042 (when x#, y# are of primitive type, of course). We can't (in general)
1043 do this for algebraic cases, because we might turn bottom into
1046 Actually, we generalise this idea to look for a case where we're
1047 scrutinising a variable, and we know that only the default case can
1052 other -> ...(case x of
1056 Here the inner case can be eliminated. This really only shows up in
1057 eliminating error-checking code.
1059 We also make sure that we deal with this very common case:
1064 Here we are using the case as a strict let; if x is used only once
1065 then we want to inline it. We have to be careful that this doesn't
1066 make the program terminate when it would have diverged before, so we
1068 - x is used strictly, or
1069 - e is already evaluated (it may so if e is a variable)
1071 Lastly, we generalise the transformation to handle this:
1077 We only do this for very cheaply compared r's (constructors, literals
1078 and variables). If pedantic bottoms is on, we only do it when the
1079 scrutinee is a PrimOp which can't fail.
1081 We do it *here*, looking at un-simplified alternatives, because we
1082 have to check that r doesn't mention the variables bound by the
1083 pattern in each alternative, so the binder-info is rather useful.
1085 So the case-elimination algorithm is:
1087 1. Eliminate alternatives which can't match
1089 2. Check whether all the remaining alternatives
1090 (a) do not mention in their rhs any of the variables bound in their pattern
1091 and (b) have equal rhss
1093 3. Check we can safely ditch the case:
1094 * PedanticBottoms is off,
1095 or * the scrutinee is an already-evaluated variable
1096 or * the scrutinee is a primop which is ok for speculation
1097 -- ie we want to preserve divide-by-zero errors, and
1098 -- calls to error itself!
1100 or * [Prim cases] the scrutinee is a primitive variable
1102 or * [Alg cases] the scrutinee is a variable and
1103 either * the rhs is the same variable
1104 (eg case x of C a b -> x ===> x)
1105 or * there is only one alternative, the default alternative,
1106 and the binder is used strictly in its scope.
1107 [NB this is helped by the "use default binder where
1108 possible" transformation; see below.]
1111 If so, then we can replace the case with one of the rhss.
1114 Blob of helper functions for the "case-of-something-else" situation.
1117 ---------------------------------------------------------
1118 -- Eliminate the case if possible
1120 rebuild_case scrut bndr alts se cont
1121 | maybeToBool maybe_con_app
1122 = knownCon scrut (DataAlt con) args bndr alts se cont
1124 | canEliminateCase scrut bndr alts
1125 = tick (CaseElim bndr) `thenSmpl_` (
1127 simplBinder bndr $ \ bndr' ->
1128 -- Remember to bind the case binder!
1129 completeBinding bndr bndr' False False scrut $
1130 simplExprF (head (rhssOfAlts alts)) cont)
1133 = complete_case scrut bndr alts se cont
1136 maybe_con_app = exprIsConApp_maybe scrut
1137 Just (con, args) = maybe_con_app
1139 -- See if we can get rid of the case altogether
1140 -- See the extensive notes on case-elimination above
1141 canEliminateCase scrut bndr alts
1142 = -- Check that the RHSs are all the same, and
1143 -- don't use the binders in the alternatives
1144 -- This test succeeds rapidly in the common case of
1145 -- a single DEFAULT alternative
1146 all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1148 -- Check that the scrutinee can be let-bound instead of case-bound
1149 && ( exprOkForSpeculation scrut
1150 -- OK not to evaluate it
1151 -- This includes things like (==# a# b#)::Bool
1152 -- so that we simplify
1153 -- case ==# a# b# of { True -> x; False -> x }
1156 -- This particular example shows up in default methods for
1157 -- comparision operations (e.g. in (>=) for Int.Int32)
1158 || exprIsValue scrut -- It's already evaluated
1159 || var_demanded_later scrut -- It'll be demanded later
1161 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1162 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1163 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1164 -- its argument: case x of { y -> dataToTag# y }
1165 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1166 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1171 (rhs1:other_rhss) = rhssOfAlts alts
1172 binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1174 var_demanded_later (Var v) = isStrict (idDemandInfo bndr) -- It's going to be evaluated later
1175 var_demanded_later other = False
1178 ---------------------------------------------------------
1179 -- Case of something else
1181 complete_case scrut case_bndr alts se cont
1182 = -- Prepare case alternatives
1183 prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1184 impossible_cons alts `thenSmpl` \ better_alts ->
1186 -- Set the new subst-env in place (before dealing with the case binder)
1189 -- Deal with the case binder, and prepare the continuation;
1190 -- The new subst_env is in place
1191 prepareCaseCont better_alts cont $ \ cont' ->
1194 -- Deal with variable scrutinee
1196 getSwitchChecker `thenSmpl` \ chkr ->
1197 simplCaseBinder (switchIsOn chkr NoCaseOfCase)
1198 scrut case_bndr $ \ case_bndr' zap_occ_info ->
1200 -- Deal with the case alternatives
1201 simplAlts zap_occ_info impossible_cons
1202 case_bndr' better_alts cont' `thenSmpl` \ alts' ->
1204 mkCase scrut case_bndr' alts'
1205 ) `thenSmpl` \ case_expr ->
1207 -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1208 -- over the rebuild_done; rebuild_done returns the in-scope set, and
1209 -- that should not include these chaps!
1210 rebuild_done case_expr
1212 impossible_cons = case scrut of
1213 Var v -> otherCons (idUnfolding v)
1217 knownCon :: OutExpr -> AltCon -> [OutExpr]
1218 -> InId -> [InAlt] -> SubstEnv -> SimplCont
1219 -> SimplM OutExprStuff
1221 knownCon expr con args bndr alts se cont
1222 = -- Arguments should be atomic;
1224 WARN( not (all exprIsTrivial args),
1225 text "knownCon" <+> ppr expr )
1226 tick (KnownBranch bndr) `thenSmpl_`
1228 simplBinder bndr $ \ bndr' ->
1229 completeBinding bndr bndr' False False expr $
1230 -- Don't use completeBeta here. The expr might be
1231 -- an unboxed literal, like 3, or a variable
1232 -- whose unfolding is an unboxed literal... and
1233 -- completeBeta will just construct another case
1235 case findAlt con alts of
1236 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1239 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1242 (DataAlt dc, bs, rhs) -> ASSERT( length bs == length real_args )
1243 extendSubstList bs (map mk real_args) $
1246 real_args = drop (dataConNumInstArgs dc) args
1247 mk (Type ty) = DoneTy ty
1248 mk other = DoneEx other
1253 prepareCaseCont :: [InAlt] -> SimplCont
1254 -> (SimplCont -> SimplM (OutStuff a))
1255 -> SimplM (OutStuff a)
1256 -- Polymorphic recursion here!
1258 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1259 prepareCaseCont alts cont thing_inside = simplType (coreAltsType alts) `thenSmpl` \ alts_ty ->
1260 mkDupableCont alts_ty cont thing_inside
1261 -- At one time I passed in the un-simplified type, and simplified
1262 -- it only if we needed to construct a join binder, but that
1263 -- didn't work because we have to decompse function types
1264 -- (using funResultTy) in mkDupableCont.
1267 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1268 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1269 way, there's a chance that v will now only be used once, and hence
1272 There is a time we *don't* want to do that, namely when
1273 -fno-case-of-case is on. This happens in the first simplifier pass,
1274 and enhances full laziness. Here's the bad case:
1275 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1276 If we eliminate the inner case, we trap it inside the I# v -> arm,
1277 which might prevent some full laziness happening. I've seen this
1278 in action in spectral/cichelli/Prog.hs:
1279 [(m,n) | m <- [1..max], n <- [1..max]]
1280 Hence the no_case_of_case argument
1283 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1284 in the case binder, because the case-binder now effectively occurs
1285 whenever v does. AND we have to do the same for the pattern-bound
1288 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1290 Here, b and p are dead. But when we move the argment inside the first
1291 case RHS, and eliminate the second case, we get
1293 case x or { (a,b) -> a b }
1295 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1296 happened. Hence the zap_occ_info function returned by simplCaseBinder
1299 simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
1300 | not no_case_of_case
1301 = simplBinder (zap case_bndr) $ \ case_bndr' ->
1302 modifyInScope v case_bndr' $
1303 -- We could extend the substitution instead, but it would be
1304 -- a hack because then the substitution wouldn't be idempotent
1305 -- any more (v is an OutId). And this just just as well.
1306 thing_inside case_bndr' zap
1308 zap b = b `setIdOccInfo` NoOccInfo
1310 simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
1311 = simplBinder case_bndr $ \ case_bndr' ->
1312 thing_inside case_bndr' (\ bndr -> bndr) -- NoOp on bndr
1315 prepareCaseAlts does two things:
1317 1. Remove impossible alternatives
1319 2. If the DEFAULT alternative can match only one possible constructor,
1320 then make that constructor explicit.
1322 case e of x { DEFAULT -> rhs }
1324 case e of x { (a,b) -> rhs }
1325 where the type is a single constructor type. This gives better code
1326 when rhs also scrutinises x or e.
1329 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1331 = case (findDefault filtered_alts, missing_cons) of
1333 ((alts_no_deflt, Just rhs), [data_con]) -- Just one missing constructor!
1334 -> tick (FillInCaseDefault bndr) `thenSmpl_`
1336 (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1338 getUniquesSmpl (length ex_tyvars) `thenSmpl` \ tv_uniqs ->
1340 ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
1341 mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1342 arg_tys = dataConArgTys data_con
1343 (inst_tys ++ mkTyVarTys ex_tyvars')
1345 newIds SLIT("a") arg_tys $ \ bndrs ->
1346 returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1348 other -> returnSmpl filtered_alts
1350 -- Filter out alternatives that can't possibly match
1351 filtered_alts = case scrut_cons of
1353 other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1355 missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon,
1356 not (data_con `elem` handled_data_cons)]
1357 handled_data_cons = [data_con | DataAlt data_con <- scrut_cons] ++
1358 [data_con | (DataAlt data_con, _, _) <- filtered_alts]
1361 prepareCaseAlts _ _ scrut_cons alts
1362 = returnSmpl alts -- Functions
1365 ----------------------
1366 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1367 = mapSmpl simpl_alt alts
1369 inst_tys' = tyConAppArgs (idType case_bndr')
1371 -- handled_cons is all the constructors that are dealt
1372 -- with, either by being impossible, or by there being an alternative
1373 handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1375 simpl_alt (DEFAULT, _, rhs)
1376 = -- In the default case we record the constructors that the
1377 -- case-binder *can't* be.
1378 -- We take advantage of any OtherCon info in the case scrutinee
1379 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons) $
1380 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1381 returnSmpl (DEFAULT, [], rhs')
1383 simpl_alt (con, vs, rhs)
1384 = -- Deal with the pattern-bound variables
1385 -- Mark the ones that are in ! positions in the data constructor
1386 -- as certainly-evaluated.
1387 -- NB: it happens that simplBinders does *not* erase the OtherCon
1388 -- form of unfolding, so it's ok to add this info before
1389 -- doing simplBinders
1390 simplBinders (add_evals con vs) $ \ vs' ->
1392 -- Bind the case-binder to (con args)
1394 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1396 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding) $
1397 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1398 returnSmpl (con, vs', rhs')
1401 -- add_evals records the evaluated-ness of the bound variables of
1402 -- a case pattern. This is *important*. Consider
1403 -- data T = T !Int !Int
1405 -- case x of { T a b -> T (a+1) b }
1407 -- We really must record that b is already evaluated so that we don't
1408 -- go and re-evaluate it when constructing the result.
1410 add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1411 add_evals other_con vs = vs
1413 cat_evals [] [] = []
1414 cat_evals (v:vs) (str:strs)
1415 | isTyVar v = v : cat_evals vs (str:strs)
1416 | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1417 | otherwise = v' : cat_evals vs strs
1423 %************************************************************************
1425 \subsection{Duplicating continuations}
1427 %************************************************************************
1430 mkDupableCont :: OutType -- Type of the thing to be given to the continuation
1432 -> (SimplCont -> SimplM (OutStuff a))
1433 -> SimplM (OutStuff a)
1434 mkDupableCont ty cont thing_inside
1435 | contIsDupable cont
1438 mkDupableCont _ (CoerceIt ty cont) thing_inside
1439 = mkDupableCont ty cont $ \ cont' ->
1440 thing_inside (CoerceIt ty cont')
1442 mkDupableCont ty (InlinePlease cont) thing_inside
1443 = mkDupableCont ty cont $ \ cont' ->
1444 thing_inside (InlinePlease cont')
1446 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1447 = -- Build the RHS of the join point
1448 newId SLIT("a") join_arg_ty ( \ arg_id ->
1449 cont_fn (Var arg_id) `thenSmpl` \ (floats, (_, rhs)) ->
1450 returnSmpl (Lam (setOneShotLambda arg_id) (wrapFloats floats rhs))
1451 ) `thenSmpl` \ join_rhs ->
1453 -- Build the join Id and continuation
1454 -- We give it a "$j" name just so that for later amusement
1455 -- we can identify any join points that don't end up as let-no-escapes
1456 -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
1457 newId SLIT("$j") (mkFunTy join_arg_ty cont_ty) $ \ join_id ->
1459 new_cont = ArgOf OkToDup cont_ty
1460 (\arg' -> rebuild_done (App (Var join_id) arg'))
1463 tick (CaseOfCase join_id) `thenSmpl_`
1464 -- Want to tick here so that we go round again,
1465 -- and maybe copy or inline the code;
1466 -- not strictly CaseOf Case
1467 addLetBind (NonRec join_id join_rhs) $
1468 thing_inside new_cont
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')
1476 newId SLIT("a") (exprType arg') $ \ bndr ->
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
1483 addLetBind (NonRec 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.
1489 thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1492 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1493 = tick (CaseOfCase case_bndr) `thenSmpl_`
1495 simplBinder case_bndr $ \ case_bndr' ->
1496 prepareCaseCont alts cont $ \ cont' ->
1497 mkDupableAlts case_bndr case_bndr' cont' alts $ \ alts' ->
1498 returnOutStuff alts'
1499 ) `thenSmpl` \ (alt_binds, (in_scope, alts')) ->
1501 addFloats alt_binds in_scope $
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 thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
1512 mkDupableAlts :: InId -> OutId -> SimplCont -> [InAlt]
1513 -> ([InAlt] -> SimplM (OutStuff a))
1514 -> SimplM (OutStuff a)
1515 mkDupableAlts case_bndr case_bndr' cont [] thing_inside
1517 mkDupableAlts case_bndr case_bndr' cont (alt:alts) thing_inside
1518 = mkDupableAlt case_bndr case_bndr' cont alt $ \ alt' ->
1519 mkDupableAlts case_bndr case_bndr' cont alts $ \ alts' ->
1520 thing_inside (alt' : alts')
1522 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs) thing_inside
1523 = simplBinders bndrs $ \ bndrs' ->
1524 simplExprC rhs cont `thenSmpl` \ rhs' ->
1526 if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
1527 -- It is worth checking for a small RHS because otherwise we
1528 -- get extra let bindings that may cause an extra iteration of the simplifier to
1529 -- inline back in place. Quite often the rhs is just a variable or constructor.
1530 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1531 -- iterations because the version with the let bindings looked big, and so wasn't
1532 -- inlined, but after the join points had been inlined it looked smaller, and so
1535 -- But since the continuation is absorbed into the rhs, we only do this
1536 -- for a Stop continuation.
1538 -- NB: we have to check the size of rhs', not rhs.
1539 -- Duplicating a small InAlt might invalidate occurrence information
1540 -- However, if it *is* dupable, we return the *un* simplified alternative,
1541 -- because otherwise we'd need to pair it up with an empty subst-env.
1542 -- (Remember we must zap the subst-env before re-simplifying something).
1543 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1548 rhs_ty' = exprType rhs'
1549 (used_bndrs, used_bndrs')
1550 = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr : bndrs)
1551 (case_bndr' : bndrs'),
1552 not (isDeadBinder bndr)]
1553 -- The new binders have lost their occurrence info,
1554 -- so we have to extract it from the old ones
1556 ( if null used_bndrs'
1557 -- If we try to lift a primitive-typed something out
1558 -- for let-binding-purposes, we will *caseify* it (!),
1559 -- with potentially-disastrous strictness results. So
1560 -- instead we turn it into a function: \v -> e
1561 -- where v::State# RealWorld#. The value passed to this function
1562 -- is realworld#, which generates (almost) no code.
1564 -- There's a slight infelicity here: we pass the overall
1565 -- case_bndr to all the join points if it's used in *any* RHS,
1566 -- because we don't know its usage in each RHS separately
1568 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1569 -- we make the join point into a function whenever used_bndrs'
1570 -- is empty. This makes the join-point more CPR friendly.
1571 -- Consider: let j = if .. then I# 3 else I# 4
1572 -- in case .. of { A -> j; B -> j; C -> ... }
1574 -- Now CPR should not w/w j because it's a thunk, so
1575 -- that means that the enclosing function can't w/w either,
1576 -- which is a lose. Here's the example that happened in practice:
1577 -- kgmod :: Int -> Int -> Int
1578 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1582 then newId SLIT("w") realWorldStatePrimTy $ \ rw_id ->
1583 returnSmpl ([rw_id], [Var realWorldPrimId])
1585 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1587 `thenSmpl` \ (final_bndrs', final_args) ->
1589 -- See comment about "$j" name above
1590 newId SLIT("$j") (foldr mkPiType rhs_ty' final_bndrs') $ \ join_bndr ->
1591 -- Notice the funky mkPiType. If the contructor has existentials
1592 -- it's possible that the join point will be abstracted over
1593 -- type varaibles as well as term variables.
1594 -- Example: Suppose we have
1595 -- data T = forall t. C [t]
1597 -- case (case e of ...) of
1598 -- C t xs::[t] -> rhs
1599 -- We get the join point
1600 -- let j :: forall t. [t] -> ...
1601 -- j = /\t \xs::[t] -> rhs
1603 -- case (case e of ...) of
1604 -- C t xs::[t] -> j t xs
1607 -- We make the lambdas into one-shot-lambdas. The
1608 -- join point is sure to be applied at most once, and doing so
1609 -- prevents the body of the join point being floated out by
1610 -- the full laziness pass
1611 really_final_bndrs = map one_shot final_bndrs'
1612 one_shot v | isId v = setOneShotLambda v
1615 addLetBind (NonRec join_bndr (mkLams really_final_bndrs rhs')) $
1616 thing_inside (con, bndrs, mkApps (Var join_bndr) final_args)