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,
16 import SimplUtils ( mkCase, tryRhsTyLam, tryEtaExpansion, findAlt,
17 simplBinder, simplBinders, simplIds, findDefault,
18 SimplCont(..), DupFlag(..), mkStop, mkRhsStop,
19 contResultType, discardInline, countArgs, contIsDupable,
20 getContArgs, interestingCallContext, interestingArg, isStrictType
22 import Var ( mkSysTyVar, tyVarKind )
24 import VarSet ( elemVarSet )
25 import Id ( Id, idType, idInfo, isDataConId,
26 idUnfolding, setIdUnfolding, isExportedId, isDeadBinder,
27 idDemandInfo, setIdInfo,
28 idOccInfo, setIdOccInfo,
29 zapLamIdInfo, setOneShotLambda,
31 import IdInfo ( OccInfo(..), isDeadOcc, isLoopBreaker,
33 setUnfoldingInfo, atLeastArity,
36 import Demand ( isStrict )
37 import DataCon ( dataConNumInstArgs, dataConRepStrictness,
38 dataConSig, dataConArgTys
41 import CoreFVs ( mustHaveLocalBinding, exprFreeVars )
42 import CoreUnfold ( mkOtherCon, mkUnfolding, otherCons,
45 import CoreUtils ( cheapEqExpr, exprIsDupable, exprIsTrivial,
46 exprIsConApp_maybe, mkPiType,
47 exprType, coreAltsType, exprIsValue,
48 exprOkForSpeculation, exprArity, exprIsCheap,
49 mkCoerce, mkSCC, mkInlineMe, mkAltExpr
51 import Rules ( lookupRule )
52 import CostCentre ( currentCCS )
53 import Type ( mkTyVarTys, isUnLiftedType, seqType,
54 mkFunTy, splitTyConApp_maybe, tyConAppArgs,
57 import Subst ( mkSubst, substTy,
58 isInScope, lookupIdSubst, substIdInfo
60 import TyCon ( isDataTyCon, tyConDataConsIfAvailable )
61 import TysPrim ( realWorldStatePrimTy )
62 import PrelInfo ( realWorldPrimId )
64 import Maybes ( maybeToBool )
65 import Util ( zipWithEqual )
70 The guts of the simplifier is in this module, but the driver
71 loop for the simplifier is in SimplCore.lhs.
74 -----------------------------------------
75 *** IMPORTANT NOTE ***
76 -----------------------------------------
77 The simplifier used to guarantee that the output had no shadowing, but
78 it does not do so any more. (Actually, it never did!) The reason is
79 documented with simplifyArgs.
84 %************************************************************************
88 %************************************************************************
91 simplTopBinds :: [InBind] -> SimplM [OutBind]
94 = -- Put all the top-level binders into scope at the start
95 -- so that if a transformation rule has unexpectedly brought
96 -- anything into scope, then we don't get a complaint about that.
97 -- It's rather as if the top-level binders were imported.
98 simplIds (bindersOfBinds binds) $ \ bndrs' ->
99 simpl_binds binds bndrs' `thenSmpl` \ (binds', _) ->
100 freeTick SimplifierDone `thenSmpl_`
101 returnSmpl (fromOL binds')
104 -- We need to track the zapped top-level binders, because
105 -- they should have their fragile IdInfo zapped (notably occurrence info)
106 simpl_binds [] bs = ASSERT( null bs ) returnSmpl (nilOL, panic "simplTopBinds corner")
107 simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr b rhs (simpl_binds binds bs)
108 simpl_binds (Rec pairs : binds) bs = simplRecBind True pairs (take n bs) (simpl_binds binds (drop n bs))
112 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
113 -> SimplM (OutStuff a) -> SimplM (OutStuff a)
114 simplRecBind top_lvl pairs bndrs' thing_inside
115 = go pairs bndrs' `thenSmpl` \ (binds', (_, (binds'', res))) ->
116 returnSmpl (unitOL (Rec (flattenBinds (fromOL binds'))) `appOL` binds'', res)
118 go [] _ = thing_inside `thenSmpl` \ stuff ->
121 go ((bndr, rhs) : pairs) (bndr' : bndrs')
122 = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
123 -- Don't float unboxed bindings out,
124 -- because we can't "rec" them
128 %************************************************************************
130 \subsection[Simplify-simplExpr]{The main function: simplExpr}
132 %************************************************************************
134 The reason for this OutExprStuff stuff is that we want to float *after*
135 simplifying a RHS, not before. If we do so naively we get quadratic
136 behaviour as things float out.
138 To see why it's important to do it after, consider this (real) example:
152 a -- Can't inline a this round, cos it appears twice
156 Each of the ==> steps is a round of simplification. We'd save a
157 whole round if we float first. This can cascade. Consider
162 let f = let d1 = ..d.. in \y -> e
166 in \x -> ...(\y ->e)...
168 Only in this second round can the \y be applied, and it
169 might do the same again.
173 simplExpr :: CoreExpr -> SimplM CoreExpr
174 simplExpr expr = getSubst `thenSmpl` \ subst ->
175 simplExprC expr (mkStop (substTy subst (exprType expr)))
176 -- The type in the Stop continuation is usually not used
177 -- It's only needed when discarding continuations after finding
178 -- a function that returns bottom.
179 -- Hence the lazy substitution
181 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
182 -- Simplify an expression, given a continuation
184 simplExprC expr cont = simplExprF expr cont `thenSmpl` \ (floats, (_, body)) ->
185 returnSmpl (wrapFloats floats body)
187 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
188 -- Simplify an expression, returning floated binds
190 simplExprF (Var v) cont
193 simplExprF (Lit lit) (Select _ bndr alts se cont)
194 = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
196 simplExprF (Lit lit) cont
197 = rebuild (Lit lit) cont
199 simplExprF (App fun arg) cont
200 = getSubstEnv `thenSmpl` \ se ->
201 simplExprF fun (ApplyTo NoDup arg se cont)
203 simplExprF (Case scrut bndr alts) cont
204 = getSubstEnv `thenSmpl` \ subst_env ->
205 getSwitchChecker `thenSmpl` \ chkr ->
206 if not (switchIsOn chkr NoCaseOfCase) then
207 -- Simplify the scrutinee with a Select continuation
208 simplExprF scrut (Select NoDup bndr alts subst_env cont)
211 -- If case-of-case is off, simply simplify the case expression
212 -- in a vanilla Stop context, and rebuild the result around it
213 simplExprC scrut (Select NoDup bndr alts subst_env
214 (mkStop (contResultType cont))) `thenSmpl` \ case_expr' ->
215 rebuild case_expr' cont
218 simplExprF (Let (Rec pairs) body) cont
219 = simplIds (map fst pairs) $ \ bndrs' ->
220 -- NB: bndrs' don't have unfoldings or spec-envs
221 -- We add them as we go down, using simplPrags
223 simplRecBind False pairs bndrs' (simplExprF body cont)
225 simplExprF expr@(Lam _ _) cont = simplLam expr cont
227 simplExprF (Type ty) cont
228 = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
229 simplType ty `thenSmpl` \ ty' ->
230 rebuild (Type ty') cont
232 -- Comments about the Coerce case
233 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
234 -- It's worth checking for a coerce in the continuation,
235 -- in case we can cancel them. For example, in the initial form of a worker
236 -- we may find (coerce T (coerce S (\x.e))) y
237 -- and we'd like it to simplify to e[y/x] in one round of simplification
239 simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
240 = simplType from `thenSmpl` \ from' ->
241 if outer_to == from' then
242 -- The coerces cancel out
245 -- They don't cancel, but the inner one is redundant
246 simplExprF e (CoerceIt outer_to cont)
248 simplExprF (Note (Coerce to from) e) cont
249 = simplType to `thenSmpl` \ to' ->
250 simplExprF e (CoerceIt to' cont)
252 -- hack: we only distinguish subsumed cost centre stacks for the purposes of
253 -- inlining. All other CCCSs are mapped to currentCCS.
254 simplExprF (Note (SCC cc) e) cont
255 = setEnclosingCC currentCCS $
256 simplExpr e `thenSmpl` \ e ->
257 rebuild (mkSCC cc e) cont
259 simplExprF (Note InlineCall e) cont
260 = simplExprF e (InlinePlease cont)
262 -- Comments about the InlineMe case
263 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264 -- Don't inline in the RHS of something that has an
265 -- inline pragma. But be careful that the InScopeEnv that
266 -- we return does still have inlinings on!
268 -- It really is important to switch off inlinings. This function
269 -- may be inlinined in other modules, so we don't want to remove
270 -- (by inlining) calls to functions that have specialisations, or
271 -- that may have transformation rules in an importing scope.
272 -- E.g. {-# INLINE f #-}
274 -- and suppose that g is strict *and* has specialisations.
275 -- If we inline g's wrapper, we deny f the chance of getting
276 -- the specialised version of g when f is inlined at some call site
277 -- (perhaps in some other module).
279 -- It's also important not to inline a worker back into a wrapper.
280 -- A wrapper looks like
281 -- wraper = inline_me (\x -> ...worker... )
282 -- Normally, the inline_me prevents the worker getting inlined into
283 -- the wrapper (initially, the worker's only call site!). But,
284 -- if the wrapper is sure to be called, the strictness analyser will
285 -- mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
286 -- continuation. That's why the keep_inline predicate returns True for
287 -- ArgOf continuations. It shouldn't do any harm not to dissolve the
288 -- inline-me note under these circumstances
290 simplExprF (Note InlineMe e) cont
291 | keep_inline cont -- Totally boring continuation
292 = -- Don't inline inside an INLINE expression
293 setBlackList noInlineBlackList (simplExpr e) `thenSmpl` \ e' ->
294 rebuild (mkInlineMe e') cont
296 | otherwise -- Dissolve the InlineMe note if there's
297 -- an interesting context of any kind to combine with
298 -- (even a type application -- anything except Stop)
301 keep_inline (Stop _ _) = True -- See notes above
302 keep_inline (ArgOf _ _ _) = True -- about this predicate
303 keep_inline other = False
305 -- A non-recursive let is dealt with by simplBeta
306 simplExprF (Let (NonRec bndr rhs) body) cont
307 = getSubstEnv `thenSmpl` \ se ->
308 simplBeta bndr rhs se (contResultType cont) $
313 ---------------------------------
319 zap_it = mkLamBndrZapper fun cont
320 cont_ty = contResultType cont
322 -- Type-beta reduction
323 go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
324 = ASSERT( isTyVar bndr )
325 tick (BetaReduction bndr) `thenSmpl_`
326 simplTyArg ty_arg arg_se `thenSmpl` \ ty_arg' ->
327 extendSubst bndr (DoneTy ty_arg')
330 -- Ordinary beta reduction
331 go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
332 = tick (BetaReduction bndr) `thenSmpl_`
333 simplBeta zapped_bndr arg arg_se cont_ty
336 zapped_bndr = zap_it bndr
339 go lam@(Lam _ _) cont = completeLam [] lam cont
341 -- Exactly enough args
342 go expr cont = simplExprF expr cont
344 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
345 -- continuation, so there are real lambdas left to put in the result
347 -- We try for eta reduction here, but *only* if we get all the
348 -- way to an exprIsTrivial expression.
349 -- We don't want to remove extra lambdas unless we are going
350 -- to avoid allocating this thing altogether
352 completeLam rev_bndrs (Lam bndr body) cont
353 = simplBinder bndr $ \ bndr' ->
354 completeLam (bndr':rev_bndrs) body cont
356 completeLam rev_bndrs body cont
357 = simplExpr body `thenSmpl` \ body' ->
358 case try_eta body' of
359 Just etad_lam -> tick (EtaReduction (head rev_bndrs)) `thenSmpl_`
360 rebuild etad_lam cont
362 Nothing -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
364 -- We don't use CoreUtils.etaReduce, because we can be more
365 -- efficient here: (a) we already have the binders, (b) we can do
366 -- the triviality test before computing the free vars
367 try_eta body | not opt_SimplDoEtaReduction = Nothing
368 | otherwise = go rev_bndrs body
370 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
371 go [] body | ok_body body = Just body -- Success!
372 go _ _ = Nothing -- Failure!
374 ok_body body = exprIsTrivial body && not (any (`elemVarSet` exprFreeVars body) rev_bndrs)
375 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
377 mkLamBndrZapper :: CoreExpr -- Function
378 -> SimplCont -- The context
379 -> Id -> Id -- Use this to zap the binders
380 mkLamBndrZapper fun cont
381 | n_args >= n_params fun = \b -> b -- Enough args
382 | otherwise = \b -> zapLamIdInfo b
384 -- NB: we count all the args incl type args
385 -- so we must count all the binders (incl type lambdas)
386 n_args = countArgs cont
388 n_params (Note _ e) = n_params e
389 n_params (Lam b e) = 1 + n_params e
390 n_params other = 0::Int
394 ---------------------------------
396 simplType :: InType -> SimplM OutType
398 = getSubst `thenSmpl` \ subst ->
400 new_ty = substTy subst ty
407 %************************************************************************
411 %************************************************************************
413 @simplBeta@ is used for non-recursive lets in expressions,
414 as well as true beta reduction.
416 Very similar to @simplLazyBind@, but not quite the same.
419 simplBeta :: InId -- Binder
420 -> InExpr -> SubstEnv -- Arg, with its subst-env
421 -> OutType -- Type of thing computed by the context
422 -> SimplM OutExprStuff -- The body
423 -> SimplM OutExprStuff
425 simplBeta bndr rhs rhs_se cont_ty thing_inside
427 = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
430 simplBeta bndr rhs rhs_se cont_ty thing_inside
431 | preInlineUnconditionally False {- not black listed -} bndr
432 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
433 extendSubst bndr (ContEx rhs_se rhs) thing_inside
436 = -- Simplify the RHS
437 simplBinder bndr $ \ bndr' ->
439 bndr_ty' = idType bndr'
440 is_strict = isStrict (idDemandInfo bndr) || isStrictType bndr_ty'
442 simplValArg bndr_ty' is_strict rhs rhs_se cont_ty $ \ rhs' ->
444 -- Now complete the binding and simplify the body
445 if needsCaseBinding bndr_ty' rhs' then
446 addCaseBind bndr' rhs' thing_inside
448 completeBinding bndr bndr' False False rhs' thing_inside
453 simplTyArg :: InType -> SubstEnv -> SimplM OutType
455 = getInScope `thenSmpl` \ in_scope ->
457 ty_arg' = substTy (mkSubst in_scope se) ty_arg
459 seqType ty_arg' `seq`
462 simplValArg :: OutType -- rhs_ty: Type of arg; used only occasionally
463 -> Bool -- True <=> evaluate eagerly
464 -> InExpr -> SubstEnv
465 -> OutType -- cont_ty: Type of thing computed by the context
466 -> (OutExpr -> SimplM OutExprStuff)
467 -- Takes an expression of type rhs_ty,
468 -- returns an expression of type cont_ty
469 -> SimplM OutExprStuff -- An expression of type cont_ty
471 simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
473 = getEnv `thenSmpl` \ env ->
475 simplExprF arg (ArgOf NoDup cont_ty $ \ rhs' ->
476 setAllExceptInScope env $
480 = simplRhs False {- Not top level -}
481 True {- OK to float unboxed -}
488 - deals only with Ids, not TyVars
489 - take an already-simplified RHS
491 It does *not* attempt to do let-to-case. Why? Because they are used for
494 (when let-to-case is impossible)
496 - many situations where the "rhs" is known to be a WHNF
497 (so let-to-case is inappropriate).
500 completeBinding :: InId -- Binder
501 -> OutId -- New binder
502 -> Bool -- True <=> top level
503 -> Bool -- True <=> black-listed; don't inline
504 -> OutExpr -- Simplified RHS
505 -> SimplM (OutStuff a) -- Thing inside
506 -> SimplM (OutStuff a)
508 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
509 | isDeadOcc occ_info -- This happens; for example, the case_bndr during case of
510 -- known constructor: case (a,b) of x { (p,q) -> ... }
511 -- Here x isn't mentioned in the RHS, so we don't want to
512 -- create the (dead) let-binding let x = (a,b) in ...
515 | trivial_rhs && not must_keep_binding
516 -- We're looking at a binding with a trivial RHS, so
517 -- perhaps we can discard it altogether!
519 -- NB: a loop breaker never has postInlineUnconditionally True
520 -- and non-loop-breakers only have *forward* references
521 -- Hence, it's safe to discard the binding
523 -- NOTE: This isn't our last opportunity to inline.
524 -- We're at the binding site right now, and
525 -- we'll get another opportunity when we get to the ocurrence(s)
527 -- Note that we do this unconditional inlining only for trival RHSs.
528 -- Don't inline even WHNFs inside lambdas; doing so may
529 -- simply increase allocation when the function is called
530 -- This isn't the last chance; see NOTE above.
532 -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
533 -- Why? Because we don't even want to inline them into the
534 -- RHS of constructor arguments. See NOTE above
536 -- NB: Even NOINLINEis ignored here: if the rhs is trivial
537 -- it's best to inline it anyway. We often get a=E; b=a
538 -- from desugaring, with both a and b marked NOINLINE.
539 = -- Drop the binding
540 extendSubst old_bndr (DoneEx new_rhs) $
541 -- Use the substitution to make quite, quite sure that the substitution
542 -- will happen, since we are going to discard the binding
543 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
546 | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs,
547 not trivial_rhs && not (isUnLiftedType inner_ty)
548 -- x = coerce t e ==> c = e; x = inline_me (coerce t c)
549 -- Now x can get inlined, which moves the coercion
550 -- to the usage site. This is a bit like worker/wrapper stuff,
551 -- but it's useful to do it very promptly, so that
552 -- x = coerce T (I# 3)
556 -- This in turn means that
557 -- case (coerce Int x) of ...
559 -- Also the full-blown w/w thing isn't set up for non-functions
561 -- The (not (isUnLiftedType inner_ty)) avoids the nasty case of
562 -- x::Int = coerce Int Int# (foo y)
565 -- x::Int = coerce Int Int# v
566 -- which would be bogus because then v will be evaluated strictly.
567 -- How can this arise? Via
568 -- x::Int = case (foo y) of { ... }
569 -- followed by case elimination.
571 -- The inline_me note is so that the simplifier doesn't
572 -- just substitute c back inside x's rhs! (Typically, x will
573 -- get substituted away, but not if it's exported.)
574 = newId SLIT("c") inner_ty $ \ c_id ->
575 completeBinding c_id c_id top_lvl False inner_rhs $
576 completeBinding old_bndr new_bndr top_lvl black_listed
577 (Note InlineMe (Note coercion (Var c_id))) $
581 = getSubst `thenSmpl` \ subst ->
583 -- We make new IdInfo for the new binder by starting from the old binder,
584 -- doing appropriate substitutions.
585 -- Then we add arity and unfolding info to get the new binder
586 new_bndr_info = substIdInfo subst old_info (idInfo new_bndr)
587 `setArityInfo` arity_info
589 -- Add the unfolding *only* for non-loop-breakers
590 -- Making loop breakers not have an unfolding at all
591 -- means that we can avoid tests in exprIsConApp, for example.
592 -- This is important: if exprIsConApp says 'yes' for a recursive
593 -- thing, then we can get into an infinite loop
594 info_w_unf | loop_breaker = new_bndr_info
595 | otherwise = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
597 final_id = new_bndr `setIdInfo` info_w_unf
599 -- These seqs forces the Id, and hence its IdInfo,
600 -- and hence any inner substitutions
602 addLetBind (NonRec final_id new_rhs) $
603 modifyInScope new_bndr final_id thing_inside
606 old_info = idInfo old_bndr
607 occ_info = occInfo old_info
608 loop_breaker = isLoopBreaker occ_info
609 trivial_rhs = exprIsTrivial new_rhs
610 must_keep_binding = black_listed || loop_breaker || isExportedId old_bndr
611 arity_info = atLeastArity (exprArity new_rhs)
616 %************************************************************************
618 \subsection{simplLazyBind}
620 %************************************************************************
622 simplLazyBind basically just simplifies the RHS of a let(rec).
623 It does two important optimisations though:
625 * It floats let(rec)s out of the RHS, even if they
626 are hidden by big lambdas
628 * It does eta expansion
631 simplLazyBind :: Bool -- True <=> top level
634 -> SimplM (OutStuff a) -- The body of the binding
635 -> SimplM (OutStuff a)
636 -- When called, the subst env is correct for the entire let-binding
637 -- and hence right for the RHS.
638 -- Also the binder has already been simplified, and hence is in scope
640 simplLazyBind top_lvl bndr bndr' rhs thing_inside
641 = getBlackList `thenSmpl` \ black_list_fn ->
643 black_listed = black_list_fn bndr
646 if preInlineUnconditionally black_listed bndr then
647 -- Inline unconditionally
648 tick (PreInlineUnconditionally bndr) `thenSmpl_`
649 getSubstEnv `thenSmpl` \ rhs_se ->
650 (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
654 getSubstEnv `thenSmpl` \ rhs_se ->
655 simplRhs top_lvl False {- Not ok to float unboxed (conservative) -}
657 rhs rhs_se $ \ rhs' ->
659 -- Now compete the binding and simplify the body
660 completeBinding bndr bndr' top_lvl black_listed rhs' thing_inside
666 simplRhs :: Bool -- True <=> Top level
667 -> Bool -- True <=> OK to float unboxed (speculative) bindings
668 -- False for (a) recursive and (b) top-level bindings
669 -> OutType -- Type of RHS; used only occasionally
670 -> InExpr -> SubstEnv
671 -> (OutExpr -> SimplM (OutStuff a))
672 -> SimplM (OutStuff a)
673 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
675 setSubstEnv rhs_se (simplExprF rhs (mkRhsStop rhs_ty)) `thenSmpl` \ (floats1, (rhs_in_scope, rhs1)) ->
677 (floats2, rhs2) = splitFloats float_ubx floats1 rhs1
679 -- There's a subtlety here. There may be a binding (x* = e) in the
680 -- floats, where the '*' means 'will be demanded'. So is it safe
681 -- to float it out? Answer no, but it won't matter because
682 -- we only float if arg' is a WHNF,
683 -- and so there can't be any 'will be demanded' bindings in the floats.
685 WARN( any demanded_float (fromOL floats2), ppr (fromOL floats2) )
688 -- It's important that we do eta expansion on function *arguments* (which are
689 -- simplified with simplRhs), as well as let-bound right-hand sides.
690 -- Otherwise we find that things like
691 -- f (\x -> case x of I# x' -> coerce T (\ y -> ...))
692 -- get right through to the code generator as two separate lambdas,
693 -- which is a Bad Thing
694 tryRhsTyLam rhs2 `thenSmpl` \ (floats3, rhs3) ->
695 tryEtaExpansion rhs3 rhs_ty `thenSmpl` \ (floats4, rhs4) ->
697 -- Float lets if (a) we're at the top level
698 -- or (b) the resulting RHS is one we'd like to expose
699 if (top_lvl || exprIsCheap rhs4) then
700 (if (isNilOL floats2 && null floats3 && null floats4) then
703 tick LetFloatFromLet) `thenSmpl_`
705 addFloats floats2 rhs_in_scope $
706 addAuxiliaryBinds floats3 $
707 addAuxiliaryBinds floats4 $
710 -- Don't do the float
711 thing_inside (wrapFloats floats1 rhs1)
713 demanded_float (NonRec b r) = isStrict (idDemandInfo b) && not (isUnLiftedType (idType b))
714 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
715 demanded_float (Rec _) = False
717 -- If float_ubx is true we float all the bindings, otherwise
718 -- we just float until we come across an unlifted one.
719 -- Remember that the unlifted bindings in the floats are all for
720 -- guaranteed-terminating non-exception-raising unlifted things,
721 -- which we are happy to do speculatively. However, we may still
722 -- not be able to float them out, because the context
723 -- is either a Rec group, or the top level, neither of which
724 -- can tolerate them.
725 splitFloats float_ubx floats rhs
726 | float_ubx = (floats, rhs) -- Float them all
727 | otherwise = go (fromOL floats)
730 go (f:fs) | must_stay f = (nilOL, mkLets (f:fs) rhs)
731 | otherwise = case go fs of
732 (out, rhs') -> (f `consOL` out, rhs')
734 must_stay (Rec prs) = False -- No unlifted bindings in here
735 must_stay (NonRec b r) = isUnLiftedType (idType b)
740 %************************************************************************
742 \subsection{Variables}
744 %************************************************************************
748 = getSubst `thenSmpl` \ subst ->
749 case lookupIdSubst subst var of
750 DoneEx e -> zapSubstEnv (simplExprF e cont)
751 ContEx env1 e -> setSubstEnv env1 (simplExprF e cont)
752 DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
753 text "simplVar:" <+> ppr var )
754 zapSubstEnv (completeCall var1 occ cont)
755 -- The template is already simplified, so don't re-substitute.
756 -- This is VITAL. Consider
758 -- let y = \z -> ...x... in
760 -- We'll clone the inner \x, adding x->x' in the id_subst
761 -- Then when we inline y, we must *not* replace x by x' in
762 -- the inlined copy!!
764 ---------------------------------------------------------
765 -- Dealing with a call
767 completeCall var occ cont
768 = getBlackList `thenSmpl` \ black_list_fn ->
769 getInScope `thenSmpl` \ in_scope ->
770 getContArgs var cont `thenSmpl` \ (args, call_cont, inline_call) ->
771 getDOptsSmpl `thenSmpl` \ dflags ->
773 black_listed = black_list_fn var
774 arg_infos = [ interestingArg in_scope arg subst
775 | (arg, subst, _) <- args, isValArg arg]
777 interesting_cont = interestingCallContext (not (null args))
778 (not (null arg_infos))
781 inline_cont | inline_call = discardInline cont
784 maybe_inline = callSiteInline dflags black_listed inline_call occ
785 var arg_infos interesting_cont
787 -- First, look for an inlining
788 case maybe_inline of {
789 Just unfolding -- There is an inlining!
790 -> tick (UnfoldingDone var) `thenSmpl_`
791 simplExprF unfolding inline_cont
794 Nothing -> -- No inlining!
797 simplifyArgs (isDataConId var) args (contResultType call_cont) $ \ args' ->
799 -- Next, look for rules or specialisations that match
801 -- It's important to simplify the args first, because the rule-matcher
802 -- doesn't do substitution as it goes. We don't want to use subst_args
803 -- (defined in the 'where') because that throws away useful occurrence info,
804 -- and perhaps-very-important specialisations.
806 -- Some functions have specialisations *and* are strict; in this case,
807 -- we don't want to inline the wrapper of the non-specialised thing; better
808 -- to call the specialised thing instead.
809 -- But the black-listing mechanism means that inlining of the wrapper
810 -- won't occur for things that have specialisations till a later phase, so
811 -- it's ok to try for inlining first.
813 getSwitchChecker `thenSmpl` \ chkr ->
815 maybe_rule | switchIsOn chkr DontApplyRules = Nothing
816 | otherwise = lookupRule in_scope var args'
819 Just (rule_name, rule_rhs) ->
820 tick (RuleFired rule_name) `thenSmpl_`
821 simplExprF rule_rhs call_cont ;
823 Nothing -> -- No rules
826 rebuild (mkApps (Var var) args') call_cont
830 ---------------------------------------------------------
831 -- Simplifying the arguments of a call
833 simplifyArgs :: Bool -- It's a data constructor
834 -> [(InExpr, SubstEnv, Bool)] -- Details of the arguments
835 -> OutType -- Type of the continuation
836 -> ([OutExpr] -> SimplM OutExprStuff)
837 -> SimplM OutExprStuff
839 -- Simplify the arguments to a call.
840 -- This part of the simplifier may break the no-shadowing invariant
842 -- f (...(\a -> e)...) (case y of (a,b) -> e')
843 -- where f is strict in its second arg
844 -- If we simplify the innermost one first we get (...(\a -> e)...)
845 -- Simplifying the second arg makes us float the case out, so we end up with
846 -- case y of (a,b) -> f (...(\a -> e)...) e'
847 -- So the output does not have the no-shadowing invariant. However, there is
848 -- no danger of getting name-capture, because when the first arg was simplified
849 -- we used an in-scope set that at least mentioned all the variables free in its
850 -- static environment, and that is enough.
852 -- We can't just do innermost first, or we'd end up with a dual problem:
853 -- case x of (a,b) -> f e (...(\a -> e')...)
855 -- I spent hours trying to recover the no-shadowing invariant, but I just could
856 -- not think of an elegant way to do it. The simplifier is already knee-deep in
857 -- continuations. We have to keep the right in-scope set around; AND we have
858 -- to get the effect that finding (error "foo") in a strict arg position will
859 -- discard the entire application and replace it with (error "foo"). Getting
860 -- all this at once is TOO HARD!
862 simplifyArgs is_data_con args cont_ty thing_inside
864 = go args thing_inside
866 | otherwise -- It's a data constructor, so we want
867 -- to switch off inlining in the arguments
868 -- If we don't do this, consider:
869 -- let x = +# p q in C {x}
870 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
871 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
872 = getBlackList `thenSmpl` \ old_bl ->
873 setBlackList noInlineBlackList $
875 setBlackList old_bl $
879 go [] thing_inside = thing_inside []
880 go (arg:args) thing_inside = simplifyArg is_data_con arg cont_ty $ \ arg' ->
882 thing_inside (arg':args')
884 simplifyArg is_data_con (Type ty_arg, se, _) cont_ty thing_inside
885 = simplTyArg ty_arg se `thenSmpl` \ new_ty_arg ->
886 thing_inside (Type new_ty_arg)
888 simplifyArg is_data_con (val_arg, se, is_strict) cont_ty thing_inside
889 = getInScope `thenSmpl` \ in_scope ->
891 arg_ty = substTy (mkSubst in_scope se) (exprType val_arg)
893 if not is_data_con then
894 -- An ordinary function
895 simplValArg arg_ty is_strict val_arg se cont_ty thing_inside
897 -- A data constructor
898 -- simplifyArgs has already switched off inlining, so
899 -- all we have to do here is to let-bind any non-trivial argument
901 -- It's not always the case that new_arg will be trivial
903 -- where, in one pass, f gets substituted by a constructor,
904 -- but x gets substituted by an expression (assume this is the
905 -- unique occurrence of x). It doesn't really matter -- it'll get
906 -- fixed up next pass. And it happens for dictionary construction,
907 -- which mentions the wrapper constructor to start with.
908 simplValArg arg_ty is_strict val_arg se cont_ty $ \ arg' ->
910 if exprIsTrivial arg' then
913 newId SLIT("a") (exprType arg') $ \ arg_id ->
914 addNonRecBind arg_id arg' $
915 thing_inside (Var arg_id)
919 %************************************************************************
921 \subsection{Decisions about inlining}
923 %************************************************************************
925 NB: At one time I tried not pre/post-inlining top-level things,
926 even if they occur exactly once. Reason:
927 (a) some might appear as a function argument, so we simply
928 replace static allocation with dynamic allocation:
934 (b) some top level things might be black listed
936 HOWEVER, I found that some useful foldr/build fusion was lost (most
937 notably in spectral/hartel/parstof) because the foldr didn't see the build.
939 Doing the dynamic allocation isn't a big deal, in fact, but losing the
943 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
944 -- Examines a bndr to see if it is used just once in a
945 -- completely safe way, so that it is safe to discard the binding
946 -- inline its RHS at the (unique) usage site, REGARDLESS of how
947 -- big the RHS might be. If this is the case we don't simplify
948 -- the RHS first, but just inline it un-simplified.
950 -- This is much better than first simplifying a perhaps-huge RHS
951 -- and then inlining and re-simplifying it.
953 -- NB: we don't even look at the RHS to see if it's trivial
956 -- where x is used many times, but this is the unique occurrence
957 -- of y. We should NOT inline x at all its uses, because then
958 -- we'd do the same for y -- aargh! So we must base this
959 -- pre-rhs-simplification decision solely on x's occurrences, not
962 -- Evne RHSs labelled InlineMe aren't caught here, because
963 -- there might be no benefit from inlining at the call site.
965 preInlineUnconditionally black_listed bndr
966 | black_listed || opt_SimplNoPreInlining = False
967 | otherwise = case idOccInfo bndr of
968 OneOcc in_lam once -> not in_lam && once
969 -- Not inside a lambda, one occurrence ==> safe!
975 %************************************************************************
977 \subsection{The main rebuilder}
979 %************************************************************************
982 -------------------------------------------------------------------
984 rebuild_done expr = returnOutStuff expr
986 ---------------------------------------------------------
987 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
990 rebuild expr (Stop _ _) = rebuild_done expr
992 -- ArgOf continuation
993 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
995 -- ApplyTo continuation
996 rebuild expr cont@(ApplyTo _ arg se cont')
997 = setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
998 rebuild (App expr arg') cont'
1000 -- Coerce continuation
1001 rebuild expr (CoerceIt to_ty cont)
1002 = rebuild (mkCoerce to_ty (exprType expr) expr) cont
1004 -- Inline continuation
1005 rebuild expr (InlinePlease cont)
1006 = rebuild (Note InlineCall expr) cont
1008 rebuild scrut (Select _ bndr alts se cont)
1009 = rebuild_case scrut bndr alts se cont
1012 Case elimination [see the code above]
1014 Start with a simple situation:
1016 case x# of ===> e[x#/y#]
1019 (when x#, y# are of primitive type, of course). We can't (in general)
1020 do this for algebraic cases, because we might turn bottom into
1023 Actually, we generalise this idea to look for a case where we're
1024 scrutinising a variable, and we know that only the default case can
1029 other -> ...(case x of
1033 Here the inner case can be eliminated. This really only shows up in
1034 eliminating error-checking code.
1036 We also make sure that we deal with this very common case:
1041 Here we are using the case as a strict let; if x is used only once
1042 then we want to inline it. We have to be careful that this doesn't
1043 make the program terminate when it would have diverged before, so we
1045 - x is used strictly, or
1046 - e is already evaluated (it may so if e is a variable)
1048 Lastly, we generalise the transformation to handle this:
1054 We only do this for very cheaply compared r's (constructors, literals
1055 and variables). If pedantic bottoms is on, we only do it when the
1056 scrutinee is a PrimOp which can't fail.
1058 We do it *here*, looking at un-simplified alternatives, because we
1059 have to check that r doesn't mention the variables bound by the
1060 pattern in each alternative, so the binder-info is rather useful.
1062 So the case-elimination algorithm is:
1064 1. Eliminate alternatives which can't match
1066 2. Check whether all the remaining alternatives
1067 (a) do not mention in their rhs any of the variables bound in their pattern
1068 and (b) have equal rhss
1070 3. Check we can safely ditch the case:
1071 * PedanticBottoms is off,
1072 or * the scrutinee is an already-evaluated variable
1073 or * the scrutinee is a primop which is ok for speculation
1074 -- ie we want to preserve divide-by-zero errors, and
1075 -- calls to error itself!
1077 or * [Prim cases] the scrutinee is a primitive variable
1079 or * [Alg cases] the scrutinee is a variable and
1080 either * the rhs is the same variable
1081 (eg case x of C a b -> x ===> x)
1082 or * there is only one alternative, the default alternative,
1083 and the binder is used strictly in its scope.
1084 [NB this is helped by the "use default binder where
1085 possible" transformation; see below.]
1088 If so, then we can replace the case with one of the rhss.
1091 Blob of helper functions for the "case-of-something-else" situation.
1094 ---------------------------------------------------------
1095 -- Eliminate the case if possible
1097 rebuild_case scrut bndr alts se cont
1098 | maybeToBool maybe_con_app
1099 = knownCon scrut (DataAlt con) args bndr alts se cont
1101 | canEliminateCase scrut bndr alts
1102 = tick (CaseElim bndr) `thenSmpl_` (
1104 simplBinder bndr $ \ bndr' ->
1105 -- Remember to bind the case binder!
1106 completeBinding bndr bndr' False False scrut $
1107 simplExprF (head (rhssOfAlts alts)) cont)
1110 = complete_case scrut bndr alts se cont
1113 maybe_con_app = exprIsConApp_maybe scrut
1114 Just (con, args) = maybe_con_app
1116 -- See if we can get rid of the case altogether
1117 -- See the extensive notes on case-elimination above
1118 canEliminateCase scrut bndr alts
1119 = -- Check that the RHSs are all the same, and
1120 -- don't use the binders in the alternatives
1121 -- This test succeeds rapidly in the common case of
1122 -- a single DEFAULT alternative
1123 all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1125 -- Check that the scrutinee can be let-bound instead of case-bound
1126 && ( exprOkForSpeculation scrut
1127 -- OK not to evaluate it
1128 -- This includes things like (==# a# b#)::Bool
1129 -- so that we simplify
1130 -- case ==# a# b# of { True -> x; False -> x }
1133 -- This particular example shows up in default methods for
1134 -- comparision operations (e.g. in (>=) for Int.Int32)
1135 || exprIsValue scrut -- It's already evaluated
1136 || var_demanded_later scrut -- It'll be demanded later
1138 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1139 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1140 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1141 -- its argument: case x of { y -> dataToTag# y }
1142 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1143 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1148 (rhs1:other_rhss) = rhssOfAlts alts
1149 binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1151 var_demanded_later (Var v) = isStrict (idDemandInfo bndr) -- It's going to be evaluated later
1152 var_demanded_later other = False
1155 ---------------------------------------------------------
1156 -- Case of something else
1158 complete_case scrut case_bndr alts se cont
1159 = -- Prepare case alternatives
1160 prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1161 impossible_cons alts `thenSmpl` \ better_alts ->
1163 -- Set the new subst-env in place (before dealing with the case binder)
1166 -- Deal with the case binder, and prepare the continuation;
1167 -- The new subst_env is in place
1168 prepareCaseCont better_alts cont $ \ cont' ->
1171 -- Deal with variable scrutinee
1173 getSwitchChecker `thenSmpl` \ chkr ->
1174 simplCaseBinder (switchIsOn chkr NoCaseOfCase)
1175 scrut case_bndr $ \ case_bndr' zap_occ_info ->
1177 -- Deal with the case alternatives
1178 simplAlts zap_occ_info impossible_cons
1179 case_bndr' better_alts cont' `thenSmpl` \ alts' ->
1181 mkCase scrut case_bndr' alts'
1182 ) `thenSmpl` \ case_expr ->
1184 -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1185 -- over the rebuild_done; rebuild_done returns the in-scope set, and
1186 -- that should not include these chaps!
1187 rebuild_done case_expr
1189 impossible_cons = case scrut of
1190 Var v -> otherCons (idUnfolding v)
1194 knownCon :: OutExpr -> AltCon -> [OutExpr]
1195 -> InId -> [InAlt] -> SubstEnv -> SimplCont
1196 -> SimplM OutExprStuff
1198 knownCon expr con args bndr alts se cont
1199 = tick (KnownBranch bndr) `thenSmpl_`
1201 simplBinder bndr $ \ bndr' ->
1202 completeBinding bndr bndr' False False expr $
1203 -- Don't use completeBeta here. The expr might be
1204 -- an unboxed literal, like 3, or a variable
1205 -- whose unfolding is an unboxed literal... and
1206 -- completeBeta will just construct another case
1208 case findAlt con alts of
1209 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1212 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1215 (DataAlt dc, bs, rhs) -> ASSERT( length bs == length real_args )
1216 extendSubstList bs (map mk real_args) $
1219 real_args = drop (dataConNumInstArgs dc) args
1220 mk (Type ty) = DoneTy ty
1221 mk other = DoneEx other
1226 prepareCaseCont :: [InAlt] -> SimplCont
1227 -> (SimplCont -> SimplM (OutStuff a))
1228 -> SimplM (OutStuff a)
1229 -- Polymorphic recursion here!
1231 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1232 prepareCaseCont alts cont thing_inside = simplType (coreAltsType alts) `thenSmpl` \ alts_ty ->
1233 mkDupableCont alts_ty cont thing_inside
1234 -- At one time I passed in the un-simplified type, and simplified
1235 -- it only if we needed to construct a join binder, but that
1236 -- didn't work because we have to decompse function types
1237 -- (using funResultTy) in mkDupableCont.
1240 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1241 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1242 way, there's a chance that v will now only be used once, and hence
1245 There is a time we *don't* want to do that, namely when
1246 -fno-case-of-case is on. This happens in the first simplifier pass,
1247 and enhances full laziness. Here's the bad case:
1248 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1249 If we eliminate the inner case, we trap it inside the I# v -> arm,
1250 which might prevent some full laziness happening. I've seen this
1251 in action in spectral/cichelli/Prog.hs:
1252 [(m,n) | m <- [1..max], n <- [1..max]]
1253 Hence the no_case_of_case argument
1256 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1257 in the case binder, because the case-binder now effectively occurs
1258 whenever v does. AND we have to do the same for the pattern-bound
1261 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1263 Here, b and p are dead. But when we move the argment inside the first
1264 case RHS, and eliminate the second case, we get
1266 case x or { (a,b) -> a b }
1268 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1269 happened. Hence the zap_occ_info function returned by simplCaseBinder
1272 simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
1273 | not no_case_of_case
1274 = simplBinder (zap case_bndr) $ \ case_bndr' ->
1275 modifyInScope v case_bndr' $
1276 -- We could extend the substitution instead, but it would be
1277 -- a hack because then the substitution wouldn't be idempotent
1278 -- any more (v is an OutId). And this just just as well.
1279 thing_inside case_bndr' zap
1281 zap b = b `setIdOccInfo` NoOccInfo
1283 simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
1284 = simplBinder case_bndr $ \ case_bndr' ->
1285 thing_inside case_bndr' (\ bndr -> bndr) -- NoOp on bndr
1288 prepareCaseAlts does two things:
1290 1. Remove impossible alternatives
1292 2. If the DEFAULT alternative can match only one possible constructor,
1293 then make that constructor explicit.
1295 case e of x { DEFAULT -> rhs }
1297 case e of x { (a,b) -> rhs }
1298 where the type is a single constructor type. This gives better code
1299 when rhs also scrutinises x or e.
1302 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1304 = case (findDefault filtered_alts, missing_cons) of
1306 ((alts_no_deflt, Just rhs), [data_con]) -- Just one missing constructor!
1307 -> tick (FillInCaseDefault bndr) `thenSmpl_`
1309 (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1311 getUniquesSmpl (length ex_tyvars) `thenSmpl` \ tv_uniqs ->
1313 ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
1314 mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1315 arg_tys = dataConArgTys data_con
1316 (inst_tys ++ mkTyVarTys ex_tyvars')
1318 newIds SLIT("a") arg_tys $ \ bndrs ->
1319 returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1321 other -> returnSmpl filtered_alts
1323 -- Filter out alternatives that can't possibly match
1324 filtered_alts = case scrut_cons of
1326 other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1328 missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon,
1329 not (data_con `elem` handled_data_cons)]
1330 handled_data_cons = [data_con | DataAlt data_con <- scrut_cons] ++
1331 [data_con | (DataAlt data_con, _, _) <- filtered_alts]
1334 prepareCaseAlts _ _ scrut_cons alts
1335 = returnSmpl alts -- Functions
1338 ----------------------
1339 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1340 = mapSmpl simpl_alt alts
1342 inst_tys' = tyConAppArgs (idType case_bndr')
1344 -- handled_cons is all the constructors that are dealt
1345 -- with, either by being impossible, or by there being an alternative
1346 handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1348 simpl_alt (DEFAULT, _, rhs)
1349 = -- In the default case we record the constructors that the
1350 -- case-binder *can't* be.
1351 -- We take advantage of any OtherCon info in the case scrutinee
1352 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons) $
1353 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1354 returnSmpl (DEFAULT, [], rhs')
1356 simpl_alt (con, vs, rhs)
1357 = -- Deal with the pattern-bound variables
1358 -- Mark the ones that are in ! positions in the data constructor
1359 -- as certainly-evaluated.
1360 -- NB: it happens that simplBinders does *not* erase the OtherCon
1361 -- form of unfolding, so it's ok to add this info before
1362 -- doing simplBinders
1363 simplBinders (add_evals con vs) $ \ vs' ->
1365 -- Bind the case-binder to (con args)
1367 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1369 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding) $
1370 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1371 returnSmpl (con, vs', rhs')
1374 -- add_evals records the evaluated-ness of the bound variables of
1375 -- a case pattern. This is *important*. Consider
1376 -- data T = T !Int !Int
1378 -- case x of { T a b -> T (a+1) b }
1380 -- We really must record that b is already evaluated so that we don't
1381 -- go and re-evaluate it when constructing the result.
1383 add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1384 add_evals other_con vs = vs
1386 cat_evals [] [] = []
1387 cat_evals (v:vs) (str:strs)
1388 | isTyVar v = v : cat_evals vs (str:strs)
1389 | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1390 | otherwise = v' : cat_evals vs strs
1396 %************************************************************************
1398 \subsection{Duplicating continuations}
1400 %************************************************************************
1403 mkDupableCont :: OutType -- Type of the thing to be given to the continuation
1405 -> (SimplCont -> SimplM (OutStuff a))
1406 -> SimplM (OutStuff a)
1407 mkDupableCont ty cont thing_inside
1408 | contIsDupable cont
1411 mkDupableCont _ (CoerceIt ty cont) thing_inside
1412 = mkDupableCont ty cont $ \ cont' ->
1413 thing_inside (CoerceIt ty cont')
1415 mkDupableCont ty (InlinePlease cont) thing_inside
1416 = mkDupableCont ty cont $ \ cont' ->
1417 thing_inside (InlinePlease cont')
1419 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1420 = -- Build the RHS of the join point
1421 newId SLIT("a") join_arg_ty ( \ arg_id ->
1422 cont_fn (Var arg_id) `thenSmpl` \ (floats, (_, rhs)) ->
1423 returnSmpl (Lam (setOneShotLambda arg_id) (wrapFloats floats rhs))
1424 ) `thenSmpl` \ join_rhs ->
1426 -- Build the join Id and continuation
1427 -- We give it a "$j" name just so that for later amusement
1428 -- we can identify any join points that don't end up as let-no-escapes
1429 -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
1430 newId SLIT("$j") (mkFunTy join_arg_ty cont_ty) $ \ join_id ->
1432 new_cont = ArgOf OkToDup cont_ty
1433 (\arg' -> rebuild_done (App (Var join_id) arg'))
1436 tick (CaseOfCase join_id) `thenSmpl_`
1437 -- Want to tick here so that we go round again,
1438 -- and maybe copy or inline the code;
1439 -- not strictly CaseOf Case
1440 addLetBind (NonRec join_id join_rhs) $
1441 thing_inside new_cont
1443 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1444 = mkDupableCont (funResultTy ty) cont $ \ cont' ->
1445 setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1446 if exprIsDupable arg' then
1447 thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1449 newId SLIT("a") (exprType arg') $ \ bndr ->
1451 tick (CaseOfCase bndr) `thenSmpl_`
1452 -- Want to tick here so that we go round again,
1453 -- and maybe copy or inline the code;
1454 -- not strictly CaseOf Case
1456 addLetBind (NonRec bndr arg') $
1457 -- But what if the arg should be case-bound? We can't use
1458 -- addNonRecBind here because its type is too specific.
1459 -- This has been this way for a long time, so I'll leave it,
1460 -- but I can't convince myself that it's right.
1462 thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1465 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1466 = tick (CaseOfCase case_bndr) `thenSmpl_`
1468 simplBinder case_bndr $ \ case_bndr' ->
1469 prepareCaseCont alts cont $ \ cont' ->
1470 mkDupableAlts case_bndr case_bndr' cont' alts $ \ alts' ->
1471 returnOutStuff alts'
1472 ) `thenSmpl` \ (alt_binds, (in_scope, alts')) ->
1474 addFloats alt_binds in_scope $
1476 -- NB that the new alternatives, alts', are still InAlts, using the original
1477 -- binders. That means we can keep the case_bndr intact. This is important
1478 -- because another case-of-case might strike, and so we want to keep the
1479 -- info that the case_bndr is dead (if it is, which is often the case).
1480 -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1481 -- case in I/O rich code. We aren't allowed a lambda bound
1482 -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1483 thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
1485 mkDupableAlts :: InId -> OutId -> SimplCont -> [InAlt]
1486 -> ([InAlt] -> SimplM (OutStuff a))
1487 -> SimplM (OutStuff a)
1488 mkDupableAlts case_bndr case_bndr' cont [] thing_inside
1490 mkDupableAlts case_bndr case_bndr' cont (alt:alts) thing_inside
1491 = mkDupableAlt case_bndr case_bndr' cont alt $ \ alt' ->
1492 mkDupableAlts case_bndr case_bndr' cont alts $ \ alts' ->
1493 thing_inside (alt' : alts')
1495 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs) thing_inside
1496 = simplBinders bndrs $ \ bndrs' ->
1497 simplExprC rhs cont `thenSmpl` \ rhs' ->
1499 if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
1500 -- It is worth checking for a small RHS because otherwise we
1501 -- get extra let bindings that may cause an extra iteration of the simplifier to
1502 -- inline back in place. Quite often the rhs is just a variable or constructor.
1503 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1504 -- iterations because the version with the let bindings looked big, and so wasn't
1505 -- inlined, but after the join points had been inlined it looked smaller, and so
1508 -- But since the continuation is absorbed into the rhs, we only do this
1509 -- for a Stop continuation.
1511 -- NB: we have to check the size of rhs', not rhs.
1512 -- Duplicating a small InAlt might invalidate occurrence information
1513 -- However, if it *is* dupable, we return the *un* simplified alternative,
1514 -- because otherwise we'd need to pair it up with an empty subst-env.
1515 -- (Remember we must zap the subst-env before re-simplifying something).
1516 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1521 rhs_ty' = exprType rhs'
1522 (used_bndrs, used_bndrs')
1523 = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr : bndrs)
1524 (case_bndr' : bndrs'),
1525 not (isDeadBinder bndr)]
1526 -- The new binders have lost their occurrence info,
1527 -- so we have to extract it from the old ones
1529 ( if null used_bndrs'
1530 -- If we try to lift a primitive-typed something out
1531 -- for let-binding-purposes, we will *caseify* it (!),
1532 -- with potentially-disastrous strictness results. So
1533 -- instead we turn it into a function: \v -> e
1534 -- where v::State# RealWorld#. The value passed to this function
1535 -- is realworld#, which generates (almost) no code.
1537 -- There's a slight infelicity here: we pass the overall
1538 -- case_bndr to all the join points if it's used in *any* RHS,
1539 -- because we don't know its usage in each RHS separately
1541 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1542 -- we make the join point into a function whenever used_bndrs'
1543 -- is empty. This makes the join-point more CPR friendly.
1544 -- Consider: let j = if .. then I# 3 else I# 4
1545 -- in case .. of { A -> j; B -> j; C -> ... }
1547 -- Now CPR should not w/w j because it's a thunk, so
1548 -- that means that the enclosing function can't w/w either,
1549 -- which is a lose. Here's the example that happened in practice:
1550 -- kgmod :: Int -> Int -> Int
1551 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1555 then newId SLIT("w") realWorldStatePrimTy $ \ rw_id ->
1556 returnSmpl ([rw_id], [Var realWorldPrimId])
1558 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1560 `thenSmpl` \ (final_bndrs', final_args) ->
1562 -- See comment about "$j" name above
1563 newId SLIT("$j") (foldr mkPiType rhs_ty' final_bndrs') $ \ join_bndr ->
1564 -- Notice the funky mkPiType. If the contructor has existentials
1565 -- it's possible that the join point will be abstracted over
1566 -- type varaibles as well as term variables.
1567 -- Example: Suppose we have
1568 -- data T = forall t. C [t]
1570 -- case (case e of ...) of
1571 -- C t xs::[t] -> rhs
1572 -- We get the join point
1573 -- let j :: forall t. [t] -> ...
1574 -- j = /\t \xs::[t] -> rhs
1576 -- case (case e of ...) of
1577 -- C t xs::[t] -> j t xs
1580 -- We make the lambdas into one-shot-lambdas. The
1581 -- join point is sure to be applied at most once, and doing so
1582 -- prevents the body of the join point being floated out by
1583 -- the full laziness pass
1584 really_final_bndrs = map one_shot final_bndrs'
1585 one_shot v | isId v = setOneShotLambda v
1588 addLetBind (NonRec join_bndr (mkLams really_final_bndrs rhs')) $
1589 thing_inside (con, bndrs, mkApps (Var join_bndr) final_args)