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,
18 simplBinder, simplBinders, simplRecIds, simplLetId,
19 SimplCont(..), DupFlag(..), mkStop, mkRhsStop,
20 contResultType, discardInline, countArgs, contIsDupable,
21 getContArgs, interestingCallContext, interestingArg, isStrictType
23 import Var ( mkSysTyVar, tyVarKind, mustHaveLocalBinding )
25 import Literal ( Literal )
26 import Id ( Id, idType, idInfo, isDataConId, hasNoBinding,
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 CoreUnfold ( mkOtherCon, mkUnfolding, otherCons,
46 import CoreUtils ( cheapEqExpr, exprIsDupable, exprIsTrivial,
47 exprIsConApp_maybe, mkPiType, findAlt, findDefault,
48 exprType, coreAltsType, exprIsValue,
49 exprOkForSpeculation, exprArity, exprIsCheap,
50 mkCoerce, mkSCC, mkInlineMe, mkAltExpr
52 import Rules ( lookupRule )
53 import CostCentre ( currentCCS )
54 import Type ( mkTyVarTys, isUnLiftedType, seqType,
55 mkFunTy, splitTyConApp_maybe, tyConAppArgs,
56 funResultTy, splitFunTy_maybe, splitFunTy
58 import Subst ( mkSubst, substTy, substEnv, substExpr,
59 isInScope, lookupIdSubst, simplIdInfo
61 import TyCon ( isDataTyCon, tyConDataConsIfAvailable )
62 import TysPrim ( realWorldStatePrimTy )
63 import PrelInfo ( realWorldPrimId )
65 import Maybes ( maybeToBool )
66 import Util ( zipWithEqual )
71 The guts of the simplifier is in this module, but the driver
72 loop for the simplifier is in SimplCore.lhs.
75 -----------------------------------------
76 *** IMPORTANT NOTE ***
77 -----------------------------------------
78 The simplifier used to guarantee that the output had no shadowing, but
79 it does not do so any more. (Actually, it never did!) The reason is
80 documented with simplifyArgs.
85 %************************************************************************
89 %************************************************************************
92 simplTopBinds :: [InBind] -> SimplM [OutBind]
95 = -- Put all the top-level binders into scope at the start
96 -- so that if a transformation rule has unexpectedly brought
97 -- anything into scope, then we don't get a complaint about that.
98 -- It's rather as if the top-level binders were imported.
99 simplRecIds (bindersOfBinds binds) $ \ bndrs' ->
100 simpl_binds binds bndrs' `thenSmpl` \ (binds', _) ->
101 freeTick SimplifierDone `thenSmpl_`
102 returnSmpl (fromOL binds')
105 -- We need to track the zapped top-level binders, because
106 -- they should have their fragile IdInfo zapped (notably occurrence info)
107 simpl_binds [] bs = ASSERT( null bs ) returnSmpl (nilOL, panic "simplTopBinds corner")
108 simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr b rhs (simpl_binds binds bs)
109 simpl_binds (Rec pairs : binds) bs = simplRecBind True pairs (take n bs) (simpl_binds binds (drop n bs))
113 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
114 -> SimplM (OutStuff a) -> SimplM (OutStuff a)
115 simplRecBind top_lvl pairs bndrs' thing_inside
116 = go pairs bndrs' `thenSmpl` \ (binds', (_, (binds'', res))) ->
117 returnSmpl (unitOL (Rec (flattenBinds (fromOL binds'))) `appOL` binds'', res)
119 go [] _ = thing_inside `thenSmpl` \ stuff ->
122 go ((bndr, rhs) : pairs) (bndr' : bndrs')
123 = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
124 -- Don't float unboxed bindings out,
125 -- because we can't "rec" them
129 %************************************************************************
131 \subsection[Simplify-simplExpr]{The main function: simplExpr}
133 %************************************************************************
135 The reason for this OutExprStuff stuff is that we want to float *after*
136 simplifying a RHS, not before. If we do so naively we get quadratic
137 behaviour as things float out.
139 To see why it's important to do it after, consider this (real) example:
153 a -- Can't inline a this round, cos it appears twice
157 Each of the ==> steps is a round of simplification. We'd save a
158 whole round if we float first. This can cascade. Consider
163 let f = let d1 = ..d.. in \y -> e
167 in \x -> ...(\y ->e)...
169 Only in this second round can the \y be applied, and it
170 might do the same again.
174 simplExpr :: CoreExpr -> SimplM CoreExpr
175 simplExpr expr = getSubst `thenSmpl` \ subst ->
176 simplExprC expr (mkStop (substTy subst (exprType expr)))
177 -- The type in the Stop continuation is usually not used
178 -- It's only needed when discarding continuations after finding
179 -- a function that returns bottom.
180 -- Hence the lazy substitution
182 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
183 -- Simplify an expression, given a continuation
185 simplExprC expr cont = simplExprF expr cont `thenSmpl` \ (floats, (_, body)) ->
186 returnSmpl (wrapFloats floats body)
188 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
189 -- Simplify an expression, returning floated binds
191 simplExprF (Var v) cont = simplVar v cont
192 simplExprF (Lit lit) cont = simplLit lit cont
193 simplExprF expr@(Lam _ _) cont = simplLam expr cont
194 simplExprF (Note note expr) cont = simplNote note expr cont
196 simplExprF (App fun arg) cont
197 = getSubstEnv `thenSmpl` \ se ->
198 simplExprF fun (ApplyTo NoDup arg se cont)
200 simplExprF (Type ty) cont
201 = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
202 simplType ty `thenSmpl` \ ty' ->
203 rebuild (Type ty') 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
219 simplExprF (Let (Rec pairs) body) cont
220 = simplRecIds (map fst pairs) $ \ bndrs' ->
221 -- NB: bndrs' don't have unfoldings or spec-envs
222 -- We add them as we go down, using simplPrags
224 simplRecBind False pairs bndrs' (simplExprF body cont)
226 -- A non-recursive let is dealt with by simplNonRecBind
227 simplExprF (Let (NonRec bndr rhs) body) cont
228 = getSubstEnv `thenSmpl` \ se ->
229 simplNonRecBind bndr rhs se (contResultType cont) $
233 ---------------------------------
234 simplType :: InType -> SimplM OutType
236 = getSubst `thenSmpl` \ subst ->
238 new_ty = substTy subst ty
243 ---------------------------------
244 simplLit :: Literal -> SimplCont -> SimplM OutExprStuff
246 simplLit lit (Select _ bndr alts se cont)
247 = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
249 simplLit lit cont = rebuild (Lit lit) cont
253 %************************************************************************
257 %************************************************************************
263 zap_it = mkLamBndrZapper fun cont
264 cont_ty = contResultType cont
266 -- Type-beta reduction
267 go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
268 = ASSERT( isTyVar bndr )
269 tick (BetaReduction bndr) `thenSmpl_`
270 simplTyArg ty_arg arg_se `thenSmpl` \ ty_arg' ->
271 extendSubst bndr (DoneTy ty_arg')
274 -- Ordinary beta reduction
275 go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
276 = tick (BetaReduction bndr) `thenSmpl_`
277 simplNonRecBind zapped_bndr arg arg_se cont_ty
280 zapped_bndr = zap_it bndr
283 go lam@(Lam _ _) cont = completeLam [] lam cont
285 -- Exactly enough args
286 go expr cont = simplExprF expr cont
288 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
289 -- continuation, so there are real lambdas left to put in the result
291 -- We try for eta reduction here, but *only* if we get all the
292 -- way to an exprIsTrivial expression.
293 -- We don't want to remove extra lambdas unless we are going
294 -- to avoid allocating this thing altogether
296 completeLam rev_bndrs (Lam bndr body) cont
297 = simplBinder bndr $ \ bndr' ->
298 completeLam (bndr':rev_bndrs) body cont
300 completeLam rev_bndrs body cont
301 = simplExpr body `thenSmpl` \ body' ->
302 case try_eta body' of
303 Just etad_lam -> tick (EtaReduction (head rev_bndrs)) `thenSmpl_`
304 rebuild etad_lam cont
306 Nothing -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
308 -- We don't use CoreUtils.etaReduce, because we can be more
310 -- (a) we already have the binders,
311 -- (b) we can do the triviality test before computing the free vars
312 -- [in fact I take the simple path and look for just a variable]
313 -- (c) we don't want to eta-reduce a data con worker or primop
314 -- because we only have to eta-expand them later when we saturate
315 try_eta body | not opt_SimplDoEtaReduction = Nothing
316 | otherwise = go rev_bndrs body
318 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
319 go [] body | ok_body body = Just body -- Success!
320 go _ _ = Nothing -- Failure!
322 ok_body (Var v) = not (v `elem` rev_bndrs) && not (hasNoBinding v)
323 ok_body other = False
324 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
326 mkLamBndrZapper :: CoreExpr -- Function
327 -> SimplCont -- The context
328 -> Id -> Id -- Use this to zap the binders
329 mkLamBndrZapper fun cont
330 | n_args >= n_params fun = \b -> b -- Enough args
331 | otherwise = \b -> zapLamIdInfo b
333 -- NB: we count all the args incl type args
334 -- so we must count all the binders (incl type lambdas)
335 n_args = countArgs cont
337 n_params (Note _ e) = n_params e
338 n_params (Lam b e) = 1 + n_params e
339 n_params other = 0::Int
343 %************************************************************************
347 %************************************************************************
350 simplNote (Coerce to from) body cont
351 = getInScope `thenSmpl` \ in_scope ->
353 addCoerce s1 k1 (CoerceIt t1 cont)
354 -- coerce T1 S1 (coerce S1 K1 e)
357 -- coerce T1 K1 e, otherwise
359 -- For example, in the initial form of a worker
360 -- we may find (coerce T (coerce S (\x.e))) y
361 -- and we'd like it to simplify to e[y/x] in one round
363 | t1 == k1 = cont -- The coerces cancel out
364 | otherwise = CoerceIt t1 cont -- They don't cancel, but
365 -- the inner one is redundant
367 addCoerce t1t2 s1s2 (ApplyTo dup arg arg_se cont)
368 | Just (s1, s2) <- splitFunTy_maybe s1s2
369 -- (coerce (T1->T2) (S1->S2) F) E
371 -- coerce T2 S2 (F (coerce S1 T1 E))
373 -- t1t2 must be a function type, T1->T2
374 -- but s1s2 might conceivably not be
376 -- When we build the ApplyTo we can't mix the out-types
377 -- with the InExpr in the argument, so we simply substitute
378 -- to make it all consistent. This isn't a common case.
380 (t1,t2) = splitFunTy t1t2
381 new_arg = mkCoerce s1 t1 (substExpr (mkSubst in_scope arg_se) arg)
383 ApplyTo dup new_arg emptySubstEnv (addCoerce t2 s2 cont)
385 addCoerce to' _ cont = CoerceIt to' cont
387 simplType to `thenSmpl` \ to' ->
388 simplType from `thenSmpl` \ from' ->
389 simplExprF body (addCoerce to' from' cont)
392 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
393 -- inlining. All other CCCSs are mapped to currentCCS.
394 simplNote (SCC cc) e cont
395 = setEnclosingCC currentCCS $
396 simplExpr e `thenSmpl` \ e ->
397 rebuild (mkSCC cc e) cont
399 simplNote InlineCall e cont
400 = simplExprF e (InlinePlease cont)
402 -- Comments about the InlineMe case
403 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404 -- Don't inline in the RHS of something that has an
405 -- inline pragma. But be careful that the InScopeEnv that
406 -- we return does still have inlinings on!
408 -- It really is important to switch off inlinings. This function
409 -- may be inlinined in other modules, so we don't want to remove
410 -- (by inlining) calls to functions that have specialisations, or
411 -- that may have transformation rules in an importing scope.
412 -- E.g. {-# INLINE f #-}
414 -- and suppose that g is strict *and* has specialisations.
415 -- If we inline g's wrapper, we deny f the chance of getting
416 -- the specialised version of g when f is inlined at some call site
417 -- (perhaps in some other module).
419 -- It's also important not to inline a worker back into a wrapper.
420 -- A wrapper looks like
421 -- wraper = inline_me (\x -> ...worker... )
422 -- Normally, the inline_me prevents the worker getting inlined into
423 -- the wrapper (initially, the worker's only call site!). But,
424 -- if the wrapper is sure to be called, the strictness analyser will
425 -- mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
426 -- continuation. That's why the keep_inline predicate returns True for
427 -- ArgOf continuations. It shouldn't do any harm not to dissolve the
428 -- inline-me note under these circumstances
430 simplNote InlineMe e cont
431 | keep_inline cont -- Totally boring continuation
432 = -- Don't inline inside an INLINE expression
433 setBlackList noInlineBlackList (simplExpr e) `thenSmpl` \ e' ->
434 rebuild (mkInlineMe e') cont
436 | otherwise -- Dissolve the InlineMe note if there's
437 -- an interesting context of any kind to combine with
438 -- (even a type application -- anything except Stop)
441 keep_inline (Stop _ _) = True -- See notes above
442 keep_inline (ArgOf _ _ _) = True -- about this predicate
443 keep_inline other = False
447 %************************************************************************
451 %************************************************************************
453 @simplNonRecBind@ is used for non-recursive lets in expressions,
454 as well as true beta reduction.
456 Very similar to @simplLazyBind@, but not quite the same.
459 simplNonRecBind :: InId -- Binder
460 -> InExpr -> SubstEnv -- Arg, with its subst-env
461 -> OutType -- Type of thing computed by the context
462 -> SimplM OutExprStuff -- The body
463 -> SimplM OutExprStuff
465 simplNonRecBind bndr rhs rhs_se cont_ty thing_inside
467 = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
470 simplNonRecBind bndr rhs rhs_se cont_ty thing_inside
471 | preInlineUnconditionally False {- not black listed -} bndr
472 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
473 extendSubst bndr (ContEx rhs_se rhs) thing_inside
476 = -- Simplify the binder.
477 -- Don't use simplBinder because that doesn't keep
478 -- fragile occurrence in the substitution
479 simplLetId bndr $ \ bndr' ->
480 getSubst `thenSmpl` \ bndr_subst ->
482 -- Substitute its IdInfo (which simplLetId does not)
483 -- The appropriate substitution env is the one right here,
484 -- not rhs_se. Often they are the same, when all this
485 -- has arisen from an application (\x. E) RHS, perhaps they aren't
486 bndr'' = simplIdInfo bndr_subst (idInfo bndr) bndr'
487 bndr_ty' = idType bndr'
488 is_strict = isStrict (idDemandInfo bndr) || isStrictType bndr_ty'
490 modifyInScope bndr'' bndr'' $
492 -- Simplify the argument
493 simplValArg bndr_ty' is_strict rhs rhs_se cont_ty $ \ rhs' ->
495 -- Now complete the binding and simplify the body
496 if needsCaseBinding bndr_ty' rhs' then
497 addCaseBind bndr'' rhs' thing_inside
499 completeBinding bndr bndr'' False False rhs' thing_inside
504 simplTyArg :: InType -> SubstEnv -> SimplM OutType
506 = getInScope `thenSmpl` \ in_scope ->
508 ty_arg' = substTy (mkSubst in_scope se) ty_arg
510 seqType ty_arg' `seq`
513 simplValArg :: OutType -- rhs_ty: Type of arg; used only occasionally
514 -> Bool -- True <=> evaluate eagerly
515 -> InExpr -> SubstEnv
516 -> OutType -- cont_ty: Type of thing computed by the context
517 -> (OutExpr -> SimplM OutExprStuff)
518 -- Takes an expression of type rhs_ty,
519 -- returns an expression of type cont_ty
520 -> SimplM OutExprStuff -- An expression of type cont_ty
522 simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
524 = getEnv `thenSmpl` \ env ->
526 simplExprF arg (ArgOf NoDup cont_ty $ \ rhs' ->
527 setAllExceptInScope env $
531 = simplRhs False {- Not top level -}
532 True {- OK to float unboxed -}
539 - deals only with Ids, not TyVars
540 - take an already-simplified RHS
542 It does *not* attempt to do let-to-case. Why? Because they are used for
545 (when let-to-case is impossible)
547 - many situations where the "rhs" is known to be a WHNF
548 (so let-to-case is inappropriate).
551 completeBinding :: InId -- Binder
552 -> OutId -- New binder
553 -> Bool -- True <=> top level
554 -> Bool -- True <=> black-listed; don't inline
555 -> OutExpr -- Simplified RHS
556 -> SimplM (OutStuff a) -- Thing inside
557 -> SimplM (OutStuff a)
559 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
560 | isDeadOcc occ_info -- This happens; for example, the case_bndr during case of
561 -- known constructor: case (a,b) of x { (p,q) -> ... }
562 -- Here x isn't mentioned in the RHS, so we don't want to
563 -- create the (dead) let-binding let x = (a,b) in ...
566 | trivial_rhs && not must_keep_binding
567 -- We're looking at a binding with a trivial RHS, so
568 -- perhaps we can discard it altogether!
570 -- NB: a loop breaker has must_keep_binding = True
571 -- and non-loop-breakers only have *forward* references
572 -- Hence, it's safe to discard the binding
574 -- NOTE: This isn't our last opportunity to inline.
575 -- We're at the binding site right now, and
576 -- we'll get another opportunity when we get to the ocurrence(s)
578 -- Note that we do this unconditional inlining only for trival RHSs.
579 -- Don't inline even WHNFs inside lambdas; doing so may
580 -- simply increase allocation when the function is called
581 -- This isn't the last chance; see NOTE above.
583 -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
584 -- Why? Because we don't even want to inline them into the
585 -- RHS of constructor arguments. See NOTE above
587 -- NB: Even NOINLINEis ignored here: if the rhs is trivial
588 -- it's best to inline it anyway. We often get a=E; b=a
589 -- from desugaring, with both a and b marked NOINLINE.
590 = -- Drop the binding
591 extendSubst old_bndr (DoneEx new_rhs) $
592 -- Use the substitution to make quite, quite sure that the substitution
593 -- will happen, since we are going to discard the binding
594 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
597 | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs,
598 not trivial_rhs && not (isUnLiftedType inner_ty)
599 -- x = coerce t e ==> c = e; x = inline_me (coerce t c)
600 -- Now x can get inlined, which moves the coercion
601 -- to the usage site. This is a bit like worker/wrapper stuff,
602 -- but it's useful to do it very promptly, so that
603 -- x = coerce T (I# 3)
607 -- This in turn means that
608 -- case (coerce Int x) of ...
610 -- Also the full-blown w/w thing isn't set up for non-functions
612 -- The (not (isUnLiftedType inner_ty)) avoids the nasty case of
613 -- x::Int = coerce Int Int# (foo y)
616 -- x::Int = coerce Int Int# v
617 -- which would be bogus because then v will be evaluated strictly.
618 -- How can this arise? Via
619 -- x::Int = case (foo y) of { ... }
620 -- followed by case elimination.
622 -- The inline_me note is so that the simplifier doesn't
623 -- just substitute c back inside x's rhs! (Typically, x will
624 -- get substituted away, but not if it's exported.)
625 = newId SLIT("c") inner_ty $ \ c_id ->
626 completeBinding c_id c_id top_lvl False inner_rhs $
627 completeBinding old_bndr new_bndr top_lvl black_listed
628 (Note InlineMe (Note coercion (Var c_id))) $
633 -- We make new IdInfo for the new binder by starting from the old binder,
634 -- doing appropriate substitutions.
635 -- Then we add arity and unfolding info to get the new binder
636 new_bndr_info = idInfo new_bndr `setArityInfo` arity_info
638 -- Add the unfolding *only* for non-loop-breakers
639 -- Making loop breakers not have an unfolding at all
640 -- means that we can avoid tests in exprIsConApp, for example.
641 -- This is important: if exprIsConApp says 'yes' for a recursive
642 -- thing, then we can get into an infinite loop
643 info_w_unf | loop_breaker = new_bndr_info
644 | otherwise = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
646 final_id = new_bndr `setIdInfo` info_w_unf
648 -- These seqs forces the Id, and hence its IdInfo,
649 -- and hence any inner substitutions
651 addLetBind (NonRec final_id new_rhs) $
652 modifyInScope new_bndr final_id thing_inside
655 old_info = idInfo old_bndr
656 occ_info = occInfo old_info
657 loop_breaker = isLoopBreaker occ_info
658 trivial_rhs = exprIsTrivial new_rhs
659 must_keep_binding = black_listed || loop_breaker || isExportedId old_bndr
660 arity_info = atLeastArity (exprArity new_rhs)
665 %************************************************************************
667 \subsection{simplLazyBind}
669 %************************************************************************
671 simplLazyBind basically just simplifies the RHS of a let(rec).
672 It does two important optimisations though:
674 * It floats let(rec)s out of the RHS, even if they
675 are hidden by big lambdas
677 * It does eta expansion
680 simplLazyBind :: Bool -- True <=> top level
683 -> SimplM (OutStuff a) -- The body of the binding
684 -> SimplM (OutStuff a)
685 -- When called, the subst env is correct for the entire let-binding
686 -- and hence right for the RHS.
687 -- Also the binder has already been simplified, and hence is in scope
689 simplLazyBind top_lvl bndr bndr' rhs thing_inside
690 = getBlackList `thenSmpl` \ black_list_fn ->
692 black_listed = black_list_fn bndr
695 if preInlineUnconditionally black_listed bndr then
696 -- Inline unconditionally
697 tick (PreInlineUnconditionally bndr) `thenSmpl_`
698 getSubstEnv `thenSmpl` \ rhs_se ->
699 (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
703 getSubst `thenSmpl` \ rhs_subst ->
705 -- Substitute IdInfo on binder, in the light of earlier
706 -- substitutions in this very letrec, and extend the in-scope
707 -- env so that it can see the new thing
708 bndr'' = simplIdInfo rhs_subst (idInfo bndr) bndr'
710 modifyInScope bndr'' bndr'' $
712 simplRhs top_lvl False {- Not ok to float unboxed (conservative) -}
714 rhs (substEnv rhs_subst) $ \ rhs' ->
716 -- Now compete the binding and simplify the body
717 completeBinding bndr bndr'' top_lvl black_listed rhs' thing_inside
723 simplRhs :: Bool -- True <=> Top level
724 -> Bool -- True <=> OK to float unboxed (speculative) bindings
725 -- False for (a) recursive and (b) top-level bindings
726 -> OutType -- Type of RHS; used only occasionally
727 -> InExpr -> SubstEnv
728 -> (OutExpr -> SimplM (OutStuff a))
729 -> SimplM (OutStuff a)
730 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
732 setSubstEnv rhs_se (simplExprF rhs (mkRhsStop rhs_ty)) `thenSmpl` \ (floats1, (rhs_in_scope, rhs1)) ->
734 (floats2, rhs2) = splitFloats float_ubx floats1 rhs1
736 -- There's a subtlety here. There may be a binding (x* = e) in the
737 -- floats, where the '*' means 'will be demanded'. So is it safe
738 -- to float it out? Answer no, but it won't matter because
739 -- we only float if arg' is a WHNF,
740 -- and so there can't be any 'will be demanded' bindings in the floats.
742 WARN( any demanded_float (fromOL floats2), ppr (fromOL floats2) )
745 -- It's important that we do eta expansion on function *arguments* (which are
746 -- simplified with simplRhs), as well as let-bound right-hand sides.
747 -- Otherwise we find that things like
748 -- f (\x -> case x of I# x' -> coerce T (\ y -> ...))
749 -- get right through to the code generator as two separate lambdas,
750 -- which is a Bad Thing
751 tryRhsTyLam rhs2 `thenSmpl` \ (floats3, rhs3) ->
752 tryEtaExpansion rhs3 rhs_ty `thenSmpl` \ (floats4, rhs4) ->
754 -- Float lets if (a) we're at the top level
755 -- or (b) the resulting RHS is one we'd like to expose
756 if (top_lvl || exprIsCheap rhs4) then
757 (if (isNilOL floats2 && null floats3 && null floats4) then
760 tick LetFloatFromLet) `thenSmpl_`
762 addFloats floats2 rhs_in_scope $
763 addAuxiliaryBinds floats3 $
764 addAuxiliaryBinds floats4 $
767 -- Don't do the float
768 thing_inside (wrapFloats floats1 rhs1)
770 demanded_float (NonRec b r) = isStrict (idDemandInfo b) && not (isUnLiftedType (idType b))
771 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
772 demanded_float (Rec _) = False
774 -- If float_ubx is true we float all the bindings, otherwise
775 -- we just float until we come across an unlifted one.
776 -- Remember that the unlifted bindings in the floats are all for
777 -- guaranteed-terminating non-exception-raising unlifted things,
778 -- which we are happy to do speculatively. However, we may still
779 -- not be able to float them out, because the context
780 -- is either a Rec group, or the top level, neither of which
781 -- can tolerate them.
782 splitFloats float_ubx floats rhs
783 | float_ubx = (floats, rhs) -- Float them all
784 | otherwise = go (fromOL floats)
787 go (f:fs) | must_stay f = (nilOL, mkLets (f:fs) rhs)
788 | otherwise = case go fs of
789 (out, rhs') -> (f `consOL` out, rhs')
791 must_stay (Rec prs) = False -- No unlifted bindings in here
792 must_stay (NonRec b r) = isUnLiftedType (idType b)
797 %************************************************************************
799 \subsection{Variables}
801 %************************************************************************
805 = getSubst `thenSmpl` \ subst ->
806 case lookupIdSubst subst var of
807 DoneEx e -> zapSubstEnv (simplExprF e cont)
808 ContEx env1 e -> setSubstEnv env1 (simplExprF e cont)
809 DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
810 text "simplVar:" <+> ppr var )
811 zapSubstEnv (completeCall var1 occ cont)
812 -- The template is already simplified, so don't re-substitute.
813 -- This is VITAL. Consider
815 -- let y = \z -> ...x... in
817 -- We'll clone the inner \x, adding x->x' in the id_subst
818 -- Then when we inline y, we must *not* replace x by x' in
819 -- the inlined copy!!
821 ---------------------------------------------------------
822 -- Dealing with a call
824 completeCall var occ_info cont
825 = getBlackList `thenSmpl` \ black_list_fn ->
826 getInScope `thenSmpl` \ in_scope ->
827 getContArgs var cont `thenSmpl` \ (args, call_cont, inline_call) ->
828 getDOptsSmpl `thenSmpl` \ dflags ->
830 black_listed = black_list_fn var
831 arg_infos = [ interestingArg in_scope arg subst
832 | (arg, subst, _) <- args, isValArg arg]
834 interesting_cont = interestingCallContext (not (null args))
835 (not (null arg_infos))
838 inline_cont | inline_call = discardInline cont
841 maybe_inline = callSiteInline dflags black_listed inline_call occ_info
842 var arg_infos interesting_cont
844 -- First, look for an inlining
845 case maybe_inline of {
846 Just unfolding -- There is an inlining!
847 -> tick (UnfoldingDone var) `thenSmpl_`
848 simplExprF unfolding inline_cont
851 Nothing -> -- No inlining!
854 simplifyArgs (isDataConId var) args (contResultType call_cont) $ \ args' ->
856 -- Next, look for rules or specialisations that match
858 -- It's important to simplify the args first, because the rule-matcher
859 -- doesn't do substitution as it goes. We don't want to use subst_args
860 -- (defined in the 'where') because that throws away useful occurrence info,
861 -- and perhaps-very-important specialisations.
863 -- Some functions have specialisations *and* are strict; in this case,
864 -- we don't want to inline the wrapper of the non-specialised thing; better
865 -- to call the specialised thing instead.
866 -- But the black-listing mechanism means that inlining of the wrapper
867 -- won't occur for things that have specialisations till a later phase, so
868 -- it's ok to try for inlining first.
870 -- You might think that we shouldn't apply rules for a loop breaker:
871 -- doing so might give rise to an infinite loop, because a RULE is
872 -- rather like an extra equation for the function:
873 -- RULE: f (g x) y = x+y
876 -- But it's too drastic to disable rules for loop breakers.
877 -- Even the foldr/build rule would be disabled, because foldr
878 -- is recursive, and hence a loop breaker:
879 -- foldr k z (build g) = g k z
880 -- So it's up to the programmer: rules can cause divergence
882 getSwitchChecker `thenSmpl` \ chkr ->
884 maybe_rule | switchIsOn chkr DontApplyRules = Nothing
885 | otherwise = lookupRule in_scope var args'
888 Just (rule_name, rule_rhs) ->
889 tick (RuleFired rule_name) `thenSmpl_`
891 (if dopt Opt_D_dump_inlinings dflags then
892 pprTrace "Rule fired" (vcat [
893 text "Rule:" <+> ptext rule_name,
894 text "Before:" <+> ppr var <+> sep (map pprParendExpr args'),
895 text "After: " <+> pprCoreExpr rule_rhs])
899 simplExprF rule_rhs call_cont ;
901 Nothing -> -- No rules
904 rebuild (mkApps (Var var) args') call_cont
908 ---------------------------------------------------------
909 -- Simplifying the arguments of a call
911 simplifyArgs :: Bool -- It's a data constructor
912 -> [(InExpr, SubstEnv, Bool)] -- Details of the arguments
913 -> OutType -- Type of the continuation
914 -> ([OutExpr] -> SimplM OutExprStuff)
915 -> SimplM OutExprStuff
917 -- Simplify the arguments to a call.
918 -- This part of the simplifier may break the no-shadowing invariant
920 -- f (...(\a -> e)...) (case y of (a,b) -> e')
921 -- where f is strict in its second arg
922 -- If we simplify the innermost one first we get (...(\a -> e)...)
923 -- Simplifying the second arg makes us float the case out, so we end up with
924 -- case y of (a,b) -> f (...(\a -> e)...) e'
925 -- So the output does not have the no-shadowing invariant. However, there is
926 -- no danger of getting name-capture, because when the first arg was simplified
927 -- we used an in-scope set that at least mentioned all the variables free in its
928 -- static environment, and that is enough.
930 -- We can't just do innermost first, or we'd end up with a dual problem:
931 -- case x of (a,b) -> f e (...(\a -> e')...)
933 -- I spent hours trying to recover the no-shadowing invariant, but I just could
934 -- not think of an elegant way to do it. The simplifier is already knee-deep in
935 -- continuations. We have to keep the right in-scope set around; AND we have
936 -- to get the effect that finding (error "foo") in a strict arg position will
937 -- discard the entire application and replace it with (error "foo"). Getting
938 -- all this at once is TOO HARD!
940 simplifyArgs is_data_con args cont_ty thing_inside
942 = go args thing_inside
944 | otherwise -- It's a data constructor, so we want
945 -- to switch off inlining in the arguments
946 -- If we don't do this, consider:
947 -- let x = +# p q in C {x}
948 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
949 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
950 = getBlackList `thenSmpl` \ old_bl ->
951 setBlackList noInlineBlackList $
953 setBlackList old_bl $
957 go [] thing_inside = thing_inside []
958 go (arg:args) thing_inside = simplifyArg is_data_con arg cont_ty $ \ arg' ->
960 thing_inside (arg':args')
962 simplifyArg is_data_con (Type ty_arg, se, _) cont_ty thing_inside
963 = simplTyArg ty_arg se `thenSmpl` \ new_ty_arg ->
964 thing_inside (Type new_ty_arg)
966 simplifyArg is_data_con (val_arg, se, is_strict) cont_ty thing_inside
967 = getInScope `thenSmpl` \ in_scope ->
969 arg_ty = substTy (mkSubst in_scope se) (exprType val_arg)
971 if not is_data_con then
972 -- An ordinary function
973 simplValArg arg_ty is_strict val_arg se cont_ty thing_inside
975 -- A data constructor
976 -- simplifyArgs has already switched off inlining, so
977 -- all we have to do here is to let-bind any non-trivial argument
979 -- It's not always the case that new_arg will be trivial
981 -- where, in one pass, f gets substituted by a constructor,
982 -- but x gets substituted by an expression (assume this is the
983 -- unique occurrence of x). It doesn't really matter -- it'll get
984 -- fixed up next pass. And it happens for dictionary construction,
985 -- which mentions the wrapper constructor to start with.
986 simplValArg arg_ty is_strict val_arg se cont_ty $ \ arg' ->
988 if exprIsTrivial arg' then
991 newId SLIT("a") (exprType arg') $ \ arg_id ->
992 addNonRecBind arg_id arg' $
993 thing_inside (Var arg_id)
997 %************************************************************************
999 \subsection{Decisions about inlining}
1001 %************************************************************************
1003 NB: At one time I tried not pre/post-inlining top-level things,
1004 even if they occur exactly once. Reason:
1005 (a) some might appear as a function argument, so we simply
1006 replace static allocation with dynamic allocation:
1012 (b) some top level things might be black listed
1014 HOWEVER, I found that some useful foldr/build fusion was lost (most
1015 notably in spectral/hartel/parstof) because the foldr didn't see the build.
1017 Doing the dynamic allocation isn't a big deal, in fact, but losing the
1021 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
1022 -- Examines a bndr to see if it is used just once in a
1023 -- completely safe way, so that it is safe to discard the binding
1024 -- inline its RHS at the (unique) usage site, REGARDLESS of how
1025 -- big the RHS might be. If this is the case we don't simplify
1026 -- the RHS first, but just inline it un-simplified.
1028 -- This is much better than first simplifying a perhaps-huge RHS
1029 -- and then inlining and re-simplifying it.
1031 -- NB: we don't even look at the RHS to see if it's trivial
1034 -- where x is used many times, but this is the unique occurrence
1035 -- of y. We should NOT inline x at all its uses, because then
1036 -- we'd do the same for y -- aargh! So we must base this
1037 -- pre-rhs-simplification decision solely on x's occurrences, not
1040 -- Evne RHSs labelled InlineMe aren't caught here, because
1041 -- there might be no benefit from inlining at the call site.
1043 preInlineUnconditionally black_listed bndr
1044 | black_listed || opt_SimplNoPreInlining = False
1045 | otherwise = case idOccInfo bndr of
1046 OneOcc in_lam once -> not in_lam && once
1047 -- Not inside a lambda, one occurrence ==> safe!
1053 %************************************************************************
1055 \subsection{The main rebuilder}
1057 %************************************************************************
1060 -------------------------------------------------------------------
1061 -- Finish rebuilding
1062 rebuild_done expr = returnOutStuff expr
1064 ---------------------------------------------------------
1065 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1067 -- Stop continuation
1068 rebuild expr (Stop _ _) = rebuild_done expr
1070 -- ArgOf continuation
1071 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1073 -- ApplyTo continuation
1074 rebuild expr cont@(ApplyTo _ arg se cont')
1075 = setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1076 rebuild (App expr arg') cont'
1078 -- Coerce continuation
1079 rebuild expr (CoerceIt to_ty cont)
1080 = rebuild (mkCoerce to_ty (exprType expr) expr) cont
1082 -- Inline continuation
1083 rebuild expr (InlinePlease cont)
1084 = rebuild (Note InlineCall expr) cont
1086 rebuild scrut (Select _ bndr alts se cont)
1087 = rebuild_case scrut bndr alts se cont
1090 Case elimination [see the code above]
1092 Start with a simple situation:
1094 case x# of ===> e[x#/y#]
1097 (when x#, y# are of primitive type, of course). We can't (in general)
1098 do this for algebraic cases, because we might turn bottom into
1101 Actually, we generalise this idea to look for a case where we're
1102 scrutinising a variable, and we know that only the default case can
1107 other -> ...(case x of
1111 Here the inner case can be eliminated. This really only shows up in
1112 eliminating error-checking code.
1114 We also make sure that we deal with this very common case:
1119 Here we are using the case as a strict let; if x is used only once
1120 then we want to inline it. We have to be careful that this doesn't
1121 make the program terminate when it would have diverged before, so we
1123 - x is used strictly, or
1124 - e is already evaluated (it may so if e is a variable)
1126 Lastly, we generalise the transformation to handle this:
1132 We only do this for very cheaply compared r's (constructors, literals
1133 and variables). If pedantic bottoms is on, we only do it when the
1134 scrutinee is a PrimOp which can't fail.
1136 We do it *here*, looking at un-simplified alternatives, because we
1137 have to check that r doesn't mention the variables bound by the
1138 pattern in each alternative, so the binder-info is rather useful.
1140 So the case-elimination algorithm is:
1142 1. Eliminate alternatives which can't match
1144 2. Check whether all the remaining alternatives
1145 (a) do not mention in their rhs any of the variables bound in their pattern
1146 and (b) have equal rhss
1148 3. Check we can safely ditch the case:
1149 * PedanticBottoms is off,
1150 or * the scrutinee is an already-evaluated variable
1151 or * the scrutinee is a primop which is ok for speculation
1152 -- ie we want to preserve divide-by-zero errors, and
1153 -- calls to error itself!
1155 or * [Prim cases] the scrutinee is a primitive variable
1157 or * [Alg cases] the scrutinee is a variable and
1158 either * the rhs is the same variable
1159 (eg case x of C a b -> x ===> x)
1160 or * there is only one alternative, the default alternative,
1161 and the binder is used strictly in its scope.
1162 [NB this is helped by the "use default binder where
1163 possible" transformation; see below.]
1166 If so, then we can replace the case with one of the rhss.
1169 Blob of helper functions for the "case-of-something-else" situation.
1172 ---------------------------------------------------------
1173 -- Eliminate the case if possible
1175 rebuild_case scrut bndr alts se cont
1176 | maybeToBool maybe_con_app
1177 = knownCon scrut (DataAlt con) args bndr alts se cont
1179 | canEliminateCase scrut bndr alts
1180 = tick (CaseElim bndr) `thenSmpl_` (
1182 simplBinder bndr $ \ bndr' ->
1183 -- Remember to bind the case binder!
1184 completeBinding bndr bndr' False False scrut $
1185 simplExprF (head (rhssOfAlts alts)) cont)
1188 = complete_case scrut bndr alts se cont
1191 maybe_con_app = exprIsConApp_maybe scrut
1192 Just (con, args) = maybe_con_app
1194 -- See if we can get rid of the case altogether
1195 -- See the extensive notes on case-elimination above
1196 canEliminateCase scrut bndr alts
1197 = -- Check that the RHSs are all the same, and
1198 -- don't use the binders in the alternatives
1199 -- This test succeeds rapidly in the common case of
1200 -- a single DEFAULT alternative
1201 all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1203 -- Check that the scrutinee can be let-bound instead of case-bound
1204 && ( exprOkForSpeculation scrut
1205 -- OK not to evaluate it
1206 -- This includes things like (==# a# b#)::Bool
1207 -- so that we simplify
1208 -- case ==# a# b# of { True -> x; False -> x }
1211 -- This particular example shows up in default methods for
1212 -- comparision operations (e.g. in (>=) for Int.Int32)
1213 || exprIsValue scrut -- It's already evaluated
1214 || var_demanded_later scrut -- It'll be demanded later
1216 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1217 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1218 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1219 -- its argument: case x of { y -> dataToTag# y }
1220 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1221 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1226 (rhs1:other_rhss) = rhssOfAlts alts
1227 binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1229 var_demanded_later (Var v) = isStrict (idDemandInfo bndr) -- It's going to be evaluated later
1230 var_demanded_later other = False
1233 ---------------------------------------------------------
1234 -- Case of something else
1236 complete_case scrut case_bndr alts se cont
1237 = -- Prepare case alternatives
1238 prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1239 impossible_cons alts `thenSmpl` \ better_alts ->
1241 -- Set the new subst-env in place (before dealing with the case binder)
1244 -- Deal with the case binder, and prepare the continuation;
1245 -- The new subst_env is in place
1246 prepareCaseCont better_alts cont $ \ cont' ->
1249 -- Deal with variable scrutinee
1251 getSwitchChecker `thenSmpl` \ chkr ->
1252 simplCaseBinder (switchIsOn chkr NoCaseOfCase)
1253 scrut case_bndr $ \ case_bndr' zap_occ_info ->
1255 -- Deal with the case alternatives
1256 simplAlts zap_occ_info impossible_cons
1257 case_bndr' better_alts cont' `thenSmpl` \ alts' ->
1259 mkCase scrut case_bndr' alts'
1260 ) `thenSmpl` \ case_expr ->
1262 -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1263 -- over the rebuild_done; rebuild_done returns the in-scope set, and
1264 -- that should not include these chaps!
1265 rebuild_done case_expr
1267 impossible_cons = case scrut of
1268 Var v -> otherCons (idUnfolding v)
1272 knownCon :: OutExpr -> AltCon -> [OutExpr]
1273 -> InId -> [InAlt] -> SubstEnv -> SimplCont
1274 -> SimplM OutExprStuff
1276 knownCon expr con args bndr alts se cont
1277 = -- Arguments should be atomic;
1279 WARN( not (all exprIsTrivial args),
1280 text "knownCon" <+> ppr expr )
1281 tick (KnownBranch bndr) `thenSmpl_`
1283 simplBinder bndr $ \ bndr' ->
1284 completeBinding bndr bndr' False False expr $
1285 -- Don't use completeBeta here. The expr might be
1286 -- an unboxed literal, like 3, or a variable
1287 -- whose unfolding is an unboxed literal... and
1288 -- completeBeta will just construct another case
1290 case findAlt con alts of
1291 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1294 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1297 (DataAlt dc, bs, rhs) -> ASSERT( length bs == length real_args )
1298 extendSubstList bs (map mk real_args) $
1301 real_args = drop (dataConNumInstArgs dc) args
1302 mk (Type ty) = DoneTy ty
1303 mk other = DoneEx other
1308 prepareCaseCont :: [InAlt] -> SimplCont
1309 -> (SimplCont -> SimplM (OutStuff a))
1310 -> SimplM (OutStuff a)
1311 -- Polymorphic recursion here!
1313 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1314 prepareCaseCont alts cont thing_inside = simplType (coreAltsType alts) `thenSmpl` \ alts_ty ->
1315 mkDupableCont alts_ty cont thing_inside
1316 -- At one time I passed in the un-simplified type, and simplified
1317 -- it only if we needed to construct a join binder, but that
1318 -- didn't work because we have to decompse function types
1319 -- (using funResultTy) in mkDupableCont.
1322 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1323 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1324 way, there's a chance that v will now only be used once, and hence
1327 There is a time we *don't* want to do that, namely when
1328 -fno-case-of-case is on. This happens in the first simplifier pass,
1329 and enhances full laziness. Here's the bad case:
1330 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1331 If we eliminate the inner case, we trap it inside the I# v -> arm,
1332 which might prevent some full laziness happening. I've seen this
1333 in action in spectral/cichelli/Prog.hs:
1334 [(m,n) | m <- [1..max], n <- [1..max]]
1335 Hence the no_case_of_case argument
1338 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1339 in the case binder, because the case-binder now effectively occurs
1340 whenever v does. AND we have to do the same for the pattern-bound
1343 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1345 Here, b and p are dead. But when we move the argment inside the first
1346 case RHS, and eliminate the second case, we get
1348 case x or { (a,b) -> a b }
1350 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1351 happened. Hence the zap_occ_info function returned by simplCaseBinder
1354 simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
1355 | not no_case_of_case
1356 = simplBinder (zap case_bndr) $ \ case_bndr' ->
1357 modifyInScope v case_bndr' $
1358 -- We could extend the substitution instead, but it would be
1359 -- a hack because then the substitution wouldn't be idempotent
1360 -- any more (v is an OutId). And this just just as well.
1361 thing_inside case_bndr' zap
1363 zap b = b `setIdOccInfo` NoOccInfo
1365 simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
1366 = simplBinder case_bndr $ \ case_bndr' ->
1367 thing_inside case_bndr' (\ bndr -> bndr) -- NoOp on bndr
1370 prepareCaseAlts does two things:
1372 1. Remove impossible alternatives
1374 2. If the DEFAULT alternative can match only one possible constructor,
1375 then make that constructor explicit.
1377 case e of x { DEFAULT -> rhs }
1379 case e of x { (a,b) -> rhs }
1380 where the type is a single constructor type. This gives better code
1381 when rhs also scrutinises x or e.
1384 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1386 = case (findDefault filtered_alts, missing_cons) of
1388 ((alts_no_deflt, Just rhs), [data_con]) -- Just one missing constructor!
1389 -> tick (FillInCaseDefault bndr) `thenSmpl_`
1391 (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1393 getUniquesSmpl (length ex_tyvars) `thenSmpl` \ tv_uniqs ->
1395 ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
1396 mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1397 arg_tys = dataConArgTys data_con
1398 (inst_tys ++ mkTyVarTys ex_tyvars')
1400 newIds SLIT("a") arg_tys $ \ bndrs ->
1401 returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1403 other -> returnSmpl filtered_alts
1405 -- Filter out alternatives that can't possibly match
1406 filtered_alts = case scrut_cons of
1408 other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1410 missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon,
1411 not (data_con `elem` handled_data_cons)]
1412 handled_data_cons = [data_con | DataAlt data_con <- scrut_cons] ++
1413 [data_con | (DataAlt data_con, _, _) <- filtered_alts]
1416 prepareCaseAlts _ _ scrut_cons alts
1417 = returnSmpl alts -- Functions
1420 ----------------------
1421 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1422 = mapSmpl simpl_alt alts
1424 inst_tys' = tyConAppArgs (idType case_bndr')
1426 -- handled_cons is all the constructors that are dealt
1427 -- with, either by being impossible, or by there being an alternative
1428 handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1430 simpl_alt (DEFAULT, _, rhs)
1431 = -- In the default case we record the constructors that the
1432 -- case-binder *can't* be.
1433 -- We take advantage of any OtherCon info in the case scrutinee
1434 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons) $
1435 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1436 returnSmpl (DEFAULT, [], rhs')
1438 simpl_alt (con, vs, rhs)
1439 = -- Deal with the pattern-bound variables
1440 -- Mark the ones that are in ! positions in the data constructor
1441 -- as certainly-evaluated.
1442 -- NB: it happens that simplBinders does *not* erase the OtherCon
1443 -- form of unfolding, so it's ok to add this info before
1444 -- doing simplBinders
1445 simplBinders (add_evals con vs) $ \ vs' ->
1447 -- Bind the case-binder to (con args)
1449 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1451 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding) $
1452 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1453 returnSmpl (con, vs', rhs')
1456 -- add_evals records the evaluated-ness of the bound variables of
1457 -- a case pattern. This is *important*. Consider
1458 -- data T = T !Int !Int
1460 -- case x of { T a b -> T (a+1) b }
1462 -- We really must record that b is already evaluated so that we don't
1463 -- go and re-evaluate it when constructing the result.
1465 add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1466 add_evals other_con vs = vs
1468 cat_evals [] [] = []
1469 cat_evals (v:vs) (str:strs)
1470 | isTyVar v = v : cat_evals vs (str:strs)
1471 | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1472 | otherwise = v' : cat_evals vs strs
1478 %************************************************************************
1480 \subsection{Duplicating continuations}
1482 %************************************************************************
1485 mkDupableCont :: OutType -- Type of the thing to be given to the continuation
1487 -> (SimplCont -> SimplM (OutStuff a))
1488 -> SimplM (OutStuff a)
1489 mkDupableCont ty cont thing_inside
1490 | contIsDupable cont
1493 mkDupableCont _ (CoerceIt ty cont) thing_inside
1494 = mkDupableCont ty cont $ \ cont' ->
1495 thing_inside (CoerceIt ty cont')
1497 mkDupableCont ty (InlinePlease cont) thing_inside
1498 = mkDupableCont ty cont $ \ cont' ->
1499 thing_inside (InlinePlease cont')
1501 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1502 = -- Build the RHS of the join point
1503 newId SLIT("a") join_arg_ty ( \ arg_id ->
1504 cont_fn (Var arg_id) `thenSmpl` \ (floats, (_, rhs)) ->
1505 returnSmpl (Lam (setOneShotLambda arg_id) (wrapFloats floats rhs))
1506 ) `thenSmpl` \ join_rhs ->
1508 -- Build the join Id and continuation
1509 -- We give it a "$j" name just so that for later amusement
1510 -- we can identify any join points that don't end up as let-no-escapes
1511 -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
1512 newId SLIT("$j") (mkFunTy join_arg_ty cont_ty) $ \ join_id ->
1514 new_cont = ArgOf OkToDup cont_ty
1515 (\arg' -> rebuild_done (App (Var join_id) arg'))
1518 tick (CaseOfCase join_id) `thenSmpl_`
1519 -- Want to tick here so that we go round again,
1520 -- and maybe copy or inline the code;
1521 -- not strictly CaseOf Case
1522 addLetBind (NonRec join_id join_rhs) $
1523 thing_inside new_cont
1525 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1526 = mkDupableCont (funResultTy ty) cont $ \ cont' ->
1527 setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1528 if exprIsDupable arg' then
1529 thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1531 newId SLIT("a") (exprType arg') $ \ bndr ->
1533 tick (CaseOfCase bndr) `thenSmpl_`
1534 -- Want to tick here so that we go round again,
1535 -- and maybe copy or inline the code;
1536 -- not strictly CaseOf Case
1538 addLetBind (NonRec bndr arg') $
1539 -- But what if the arg should be case-bound? We can't use
1540 -- addNonRecBind here because its type is too specific.
1541 -- This has been this way for a long time, so I'll leave it,
1542 -- but I can't convince myself that it's right.
1544 thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1547 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1548 = tick (CaseOfCase case_bndr) `thenSmpl_`
1550 simplBinder case_bndr $ \ case_bndr' ->
1551 prepareCaseCont alts cont $ \ cont' ->
1552 mkDupableAlts case_bndr case_bndr' cont' alts $ \ alts' ->
1553 returnOutStuff alts'
1554 ) `thenSmpl` \ (alt_binds, (in_scope, alts')) ->
1556 addFloats alt_binds in_scope $
1558 -- NB that the new alternatives, alts', are still InAlts, using the original
1559 -- binders. That means we can keep the case_bndr intact. This is important
1560 -- because another case-of-case might strike, and so we want to keep the
1561 -- info that the case_bndr is dead (if it is, which is often the case).
1562 -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1563 -- case in I/O rich code. We aren't allowed a lambda bound
1564 -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1565 thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
1567 mkDupableAlts :: InId -> OutId -> SimplCont -> [InAlt]
1568 -> ([InAlt] -> SimplM (OutStuff a))
1569 -> SimplM (OutStuff a)
1570 mkDupableAlts case_bndr case_bndr' cont [] thing_inside
1572 mkDupableAlts case_bndr case_bndr' cont (alt:alts) thing_inside
1573 = mkDupableAlt case_bndr case_bndr' cont alt $ \ alt' ->
1574 mkDupableAlts case_bndr case_bndr' cont alts $ \ alts' ->
1575 thing_inside (alt' : alts')
1577 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs) thing_inside
1578 = simplBinders bndrs $ \ bndrs' ->
1579 simplExprC rhs cont `thenSmpl` \ rhs' ->
1581 if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
1582 -- It is worth checking for a small RHS because otherwise we
1583 -- get extra let bindings that may cause an extra iteration of the simplifier to
1584 -- inline back in place. Quite often the rhs is just a variable or constructor.
1585 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1586 -- iterations because the version with the let bindings looked big, and so wasn't
1587 -- inlined, but after the join points had been inlined it looked smaller, and so
1590 -- But since the continuation is absorbed into the rhs, we only do this
1591 -- for a Stop continuation.
1593 -- NB: we have to check the size of rhs', not rhs.
1594 -- Duplicating a small InAlt might invalidate occurrence information
1595 -- However, if it *is* dupable, we return the *un* simplified alternative,
1596 -- because otherwise we'd need to pair it up with an empty subst-env.
1597 -- (Remember we must zap the subst-env before re-simplifying something).
1598 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1603 rhs_ty' = exprType rhs'
1604 (used_bndrs, used_bndrs')
1605 = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr : bndrs)
1606 (case_bndr' : bndrs'),
1607 not (isDeadBinder bndr)]
1608 -- The new binders have lost their occurrence info,
1609 -- so we have to extract it from the old ones
1611 ( if null used_bndrs'
1612 -- If we try to lift a primitive-typed something out
1613 -- for let-binding-purposes, we will *caseify* it (!),
1614 -- with potentially-disastrous strictness results. So
1615 -- instead we turn it into a function: \v -> e
1616 -- where v::State# RealWorld#. The value passed to this function
1617 -- is realworld#, which generates (almost) no code.
1619 -- There's a slight infelicity here: we pass the overall
1620 -- case_bndr to all the join points if it's used in *any* RHS,
1621 -- because we don't know its usage in each RHS separately
1623 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1624 -- we make the join point into a function whenever used_bndrs'
1625 -- is empty. This makes the join-point more CPR friendly.
1626 -- Consider: let j = if .. then I# 3 else I# 4
1627 -- in case .. of { A -> j; B -> j; C -> ... }
1629 -- Now CPR should not w/w j because it's a thunk, so
1630 -- that means that the enclosing function can't w/w either,
1631 -- which is a lose. Here's the example that happened in practice:
1632 -- kgmod :: Int -> Int -> Int
1633 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1637 then newId SLIT("w") realWorldStatePrimTy $ \ rw_id ->
1638 returnSmpl ([rw_id], [Var realWorldPrimId])
1640 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1642 `thenSmpl` \ (final_bndrs', final_args) ->
1644 -- See comment about "$j" name above
1645 newId SLIT("$j") (foldr mkPiType rhs_ty' final_bndrs') $ \ join_bndr ->
1646 -- Notice the funky mkPiType. If the contructor has existentials
1647 -- it's possible that the join point will be abstracted over
1648 -- type varaibles as well as term variables.
1649 -- Example: Suppose we have
1650 -- data T = forall t. C [t]
1652 -- case (case e of ...) of
1653 -- C t xs::[t] -> rhs
1654 -- We get the join point
1655 -- let j :: forall t. [t] -> ...
1656 -- j = /\t \xs::[t] -> rhs
1658 -- case (case e of ...) of
1659 -- C t xs::[t] -> j t xs
1662 -- We make the lambdas into one-shot-lambdas. The
1663 -- join point is sure to be applied at most once, and doing so
1664 -- prevents the body of the join point being floated out by
1665 -- the full laziness pass
1666 really_final_bndrs = map one_shot final_bndrs'
1667 one_shot v | isId v = setOneShotLambda v
1670 addLetBind (NonRec join_bndr (mkLams really_final_bndrs rhs')) $
1671 thing_inside (con, bndrs, mkApps (Var join_bndr) final_args)