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 ( intSwitchSet, switchIsOn,
12 opt_SccProfilingOn, opt_PprStyle_Debug, opt_SimplDoEtaReduction,
13 opt_SimplNoPreInlining, opt_DictsStrict, opt_SimplPedanticBottoms,
17 import SimplUtils ( mkCase, transformRhs, findAlt, etaCoreExpr,
18 simplBinder, simplBinders, simplIds, findDefault, mkCoerce
20 import Var ( TyVar, mkSysTyVar, tyVarKind, maybeModifyIdInfo )
23 import Id ( Id, idType, idInfo, idUnique,
24 getIdUnfolding, setIdUnfolding, isExportedId,
25 getIdSpecialisation, setIdSpecialisation,
26 getIdDemandInfo, setIdDemandInfo,
28 getIdOccInfo, setIdOccInfo,
29 zapLamIdInfo, zapFragileIdInfo,
31 setInlinePragma, mayHaveNoBinding,
32 setOneShotLambda, maybeModifyIdInfo
34 import IdInfo ( InlinePragInfo(..), OccInfo(..), StrictnessInfo(..),
35 ArityInfo(..), atLeastArity, arityLowerBound, unknownArity,
36 specInfo, inlinePragInfo, setArityInfo, setInlinePragInfo, setUnfoldingInfo
38 import Demand ( Demand, isStrict, wwLazy )
39 import Const ( isWHNFCon, conOkForAlt )
40 import ConFold ( tryPrimOp )
41 import PrimOp ( PrimOp, primOpStrictness, primOpType )
42 import DataCon ( DataCon, dataConNumInstArgs, dataConRepStrictness, dataConSig, dataConArgTys )
43 import Const ( Con(..) )
44 import Name ( isLocallyDefined )
46 import CoreFVs ( exprFreeVars )
47 import CoreUnfold ( Unfolding, mkOtherCon, mkUnfolding, otherCons,
48 callSiteInline, hasSomeUnfolding
50 import CoreUtils ( cheapEqExpr, exprIsDupable, exprIsCheap, exprIsTrivial,
51 coreExprType, coreAltsType, exprArity, exprIsValue,
54 import Rules ( lookupRule )
55 import CostCentre ( isSubsumedCCS, currentCCS, isEmptyCC )
56 import Type ( Type, mkTyVarTy, mkTyVarTys, isUnLiftedType, seqType,
57 mkFunTy, splitFunTys, splitTyConApp_maybe, splitFunTy_maybe,
58 funResultTy, isDictTy, isDataType, applyTy, applyTys, mkFunTys
60 import Subst ( Subst, mkSubst, emptySubst, substTy, substExpr,
61 substEnv, isInScope, lookupInScope, lookupIdSubst, substIdInfo
63 import TyCon ( isDataTyCon, tyConDataCons, tyConClass_maybe, tyConArity, isDataTyCon )
64 import TysPrim ( realWorldStatePrimTy )
65 import PrelInfo ( realWorldPrimId )
66 import BasicTypes ( TopLevelFlag(..), isTopLevel )
67 import Maybes ( maybeToBool )
68 import Util ( zipWithEqual, stretchZipEqual, lengthExceeds )
71 import Unique ( foldrIdKey ) -- Temp
75 The guts of the simplifier is in this module, but the driver
76 loop for the simplifier is in SimplCore.lhs.
79 %************************************************************************
83 %************************************************************************
86 simplTopBinds :: [InBind] -> SimplM [OutBind]
89 = -- Put all the top-level binders into scope at the start
90 -- so that if a transformation rule has unexpectedly brought
91 -- anything into scope, then we don't get a complaint about that.
92 -- It's rather as if the top-level binders were imported.
93 simplIds (bindersOfBinds binds) $ \ bndrs' ->
94 simpl_binds binds bndrs' `thenSmpl` \ (binds', _) ->
95 freeTick SimplifierDone `thenSmpl_`
99 -- We need to track the zapped top-level binders, because
100 -- they should have their fragile IdInfo zapped (notably occurrence info)
101 simpl_binds [] bs = ASSERT( null bs ) returnSmpl ([], panic "simplTopBinds corner")
102 simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr b rhs (simpl_binds binds bs)
103 simpl_binds (Rec pairs : binds) bs = simplRecBind True pairs (take n bs) (simpl_binds binds (drop n bs))
107 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
108 -> SimplM (OutStuff a) -> SimplM (OutStuff a)
109 simplRecBind top_lvl pairs bndrs' thing_inside
110 = go pairs bndrs' `thenSmpl` \ (binds', stuff) ->
111 returnSmpl (addBind (Rec (flattenBinds binds')) stuff)
113 go [] _ = thing_inside `thenSmpl` \ stuff ->
114 returnSmpl ([], stuff)
116 go ((bndr, rhs) : pairs) (bndr' : bndrs')
117 = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
118 -- Don't float unboxed bindings out,
119 -- because we can't "rec" them
123 %************************************************************************
125 \subsection[Simplify-simplExpr]{The main function: simplExpr}
127 %************************************************************************
130 addBind :: CoreBind -> OutStuff a -> OutStuff a
131 addBind bind (binds, res) = (bind:binds, res)
133 addBinds :: [CoreBind] -> OutStuff a -> OutStuff a
134 addBinds [] stuff = stuff
135 addBinds binds1 (binds2, res) = (binds1++binds2, res)
138 The reason for this OutExprStuff stuff is that we want to float *after*
139 simplifying a RHS, not before. If we do so naively we get quadratic
140 behaviour as things float out.
142 To see why it's important to do it after, consider this (real) example:
156 a -- Can't inline a this round, cos it appears twice
160 Each of the ==> steps is a round of simplification. We'd save a
161 whole round if we float first. This can cascade. Consider
166 let f = let d1 = ..d.. in \y -> e
170 in \x -> ...(\y ->e)...
172 Only in this second round can the \y be applied, and it
173 might do the same again.
177 simplExpr :: CoreExpr -> SimplM CoreExpr
178 simplExpr expr = getSubst `thenSmpl` \ subst ->
179 simplExprC expr (Stop (substTy subst (coreExprType expr)))
180 -- The type in the Stop continuation is usually not used
181 -- It's only needed when discarding continuations after finding
182 -- a function that returns bottom.
183 -- Hence the lazy substitution
185 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
186 -- Simplify an expression, given a continuation
188 simplExprC expr cont = simplExprF expr cont `thenSmpl` \ (floats, (_, body)) ->
189 returnSmpl (mkLets floats body)
191 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
192 -- Simplify an expression, returning floated binds
194 simplExprF (Var v) cont
197 simplExprF expr@(Con (PrimOp op) args) cont
198 = getSubstEnv `thenSmpl` \ se ->
201 (primOpStrictness op)
202 (pushArgs se args cont) $ \ args1 cont1 ->
205 -- Boring... we may have too many arguments now, so we push them back
207 args2 = ASSERT( length args1 >= n_args )
209 cont2 = pushArgs emptySubstEnv (drop n_args args1) cont1
211 -- Try the prim op simplification
212 -- It's really worth trying simplExpr again if it succeeds,
213 -- because you can find
214 -- case (eqChar# x 'a') of ...
216 -- case (case x of 'a' -> True; other -> False) of ...
218 case tryPrimOp op args2 of
219 Just e' -> zapSubstEnv (simplExprF e' cont2)
220 Nothing -> rebuild (Con (PrimOp op) args2) cont2
223 simplExprF (Con con@(DataCon _) args) cont
224 = simplConArgs args $ \ args' ->
225 rebuild (Con con args') cont
227 simplExprF expr@(Con con@(Literal _) args) cont
228 = ASSERT( null args )
231 simplExprF (App fun arg) cont
232 = getSubstEnv `thenSmpl` \ se ->
233 simplExprF fun (ApplyTo NoDup arg se cont)
235 simplExprF (Case scrut bndr alts) cont
236 = getSubstEnv `thenSmpl` \ se ->
237 simplExprF scrut (Select NoDup bndr alts se cont)
240 simplExprF (Let (Rec pairs) body) cont
241 = simplIds (map fst pairs) $ \ bndrs' ->
242 -- NB: bndrs' don't have unfoldings or spec-envs
243 -- We add them as we go down, using simplPrags
245 simplRecBind False pairs bndrs' (simplExprF body cont)
247 simplExprF expr@(Lam _ _) cont = simplLam expr cont
249 simplExprF (Type ty) cont
250 = ASSERT( case cont of { Stop _ -> True; ArgOf _ _ _ -> True; other -> False } )
251 simplType ty `thenSmpl` \ ty' ->
252 rebuild (Type ty') cont
254 -- Comments about the Coerce case
255 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
256 -- It's worth checking for a coerce in the continuation,
257 -- in case we can cancel them. For example, in the initial form of a worker
258 -- we may find (coerce T (coerce S (\x.e))) y
259 -- and we'd like it to simplify to e[y/x] in one round of simplification
261 simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
262 = simplType from `thenSmpl` \ from' ->
263 if outer_to == from' then
264 -- The coerces cancel out
267 -- They don't cancel, but the inner one is redundant
268 simplExprF e (CoerceIt outer_to cont)
270 simplExprF (Note (Coerce to from) e) cont
271 = simplType to `thenSmpl` \ to' ->
272 simplExprF e (CoerceIt to' cont)
274 -- hack: we only distinguish subsumed cost centre stacks for the purposes of
275 -- inlining. All other CCCSs are mapped to currentCCS.
276 simplExprF (Note (SCC cc) e) cont
277 = setEnclosingCC currentCCS $
278 simplExpr e `thenSmpl` \ e ->
279 rebuild (mkNote (SCC cc) e) cont
281 simplExprF (Note InlineCall e) cont
282 = simplExprF e (InlinePlease cont)
284 -- Comments about the InlineMe case
285 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
286 -- Don't inline in the RHS of something that has an
287 -- inline pragma. But be careful that the InScopeEnv that
288 -- we return does still have inlinings on!
290 -- It really is important to switch off inlinings. This function
291 -- may be inlinined in other modules, so we don't want to remove
292 -- (by inlining) calls to functions that have specialisations, or
293 -- that may have transformation rules in an importing scope.
294 -- E.g. {-# INLINE f #-}
296 -- and suppose that g is strict *and* has specialisations.
297 -- If we inline g's wrapper, we deny f the chance of getting
298 -- the specialised version of g when f is inlined at some call site
299 -- (perhaps in some other module).
301 simplExprF (Note InlineMe e) cont
303 Stop _ -> -- Totally boring continuation
304 -- Don't inline inside an INLINE expression
305 switchOffInlining (simplExpr e) `thenSmpl` \ e' ->
306 rebuild (mkNote InlineMe e') cont
308 other -> -- Dissolve the InlineMe note if there's
309 -- an interesting context of any kind to combine with
310 -- (even a type application -- anything except Stop)
313 -- A non-recursive let is dealt with by simplBeta
314 simplExprF (Let (NonRec bndr rhs) body) cont
315 = getSubstEnv `thenSmpl` \ se ->
316 simplBeta bndr rhs se (contResultType cont) $
321 ---------------------------------
327 zap_it = mkLamBndrZapper fun cont
328 cont_ty = contResultType cont
330 -- Type-beta reduction
331 go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
332 = ASSERT( isTyVar bndr )
333 tick (BetaReduction bndr) `thenSmpl_`
334 getInScope `thenSmpl` \ in_scope ->
336 ty' = substTy (mkSubst in_scope arg_se) ty_arg
339 extendSubst bndr (DoneTy ty')
342 -- Ordinary beta reduction
343 go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
344 = tick (BetaReduction bndr) `thenSmpl_`
345 simplBeta zapped_bndr arg arg_se cont_ty
348 zapped_bndr = zap_it bndr
351 go lam@(Lam _ _) cont = completeLam [] lam cont
353 -- Exactly enough args
354 go expr cont = simplExprF expr cont
356 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
358 -- We used to try for eta reduction here, but I found that this was
359 -- eta reducing things like
360 -- f = \x -> (coerce (\x -> e))
361 -- This made f's arity reduce, which is a bad thing, so I removed the
362 -- eta reduction at this point, and now do it only when binding
363 -- (at the call to postInlineUnconditionally
365 completeLam acc (Lam bndr body) cont
366 = simplBinder bndr $ \ bndr' ->
367 completeLam (bndr':acc) body cont
369 completeLam acc body cont
370 = simplExpr body `thenSmpl` \ body' ->
371 rebuild (foldl (flip Lam) body' acc) cont
372 -- Remember, acc is the *reversed* binders
374 mkLamBndrZapper :: CoreExpr -- Function
375 -> SimplCont -- The context
376 -> Id -> Id -- Use this to zap the binders
377 mkLamBndrZapper fun cont
378 | n_args >= n_params fun = \b -> b -- Enough args
379 | otherwise = \b -> zapLamIdInfo b
381 -- NB: we count all the args incl type args
382 -- so we must count all the binders (incl type lambdas)
383 n_args = countArgs cont
385 n_params (Note _ e) = n_params e
386 n_params (Lam b e) = 1 + n_params e
387 n_params other = 0::Int
391 ---------------------------------
392 simplConArgs makes sure that the arguments all end up being atomic.
393 That means it may generate some Lets, hence the strange type
396 simplConArgs :: [InArg] -> ([OutArg] -> SimplM OutExprStuff) -> SimplM OutExprStuff
397 simplConArgs args thing_inside
398 = getSubst `thenSmpl` \ subst ->
399 go subst args thing_inside
401 go subst [] thing_inside
403 go subst (arg:args) thing_inside
406 arg1 = substExpr subst arg
407 -- Simplify the RHS with inlining switched off, so that
408 -- only absolutely essential things will happen.
409 -- If we don't do this, consider:
410 -- let x = e in C {x}
411 -- We end up inlining x back into C's argument,
412 -- and then let-binding it again!
414 -- It's important that the substitution *does* deal with case-binder synonyms:
415 -- case x of y { True -> (x,1) }
416 -- Here we must be sure to substitute y for x when simplifying the args of the pair,
417 -- to increase the chances of being able to inline x. The substituter will do
418 -- that because the x->y mapping is held in the in-scope set.
420 ASSERT( exprIsTrivial arg1 )
421 go subst args $ \ args1 ->
422 thing_inside (arg1 : args1)
425 = -- If the argument ain't trivial, then let-bind it
426 simplExpr arg `thenSmpl` \ arg1 ->
427 newId (coreExprType arg1) $ \ arg_id ->
428 go subst args $ \ args1 ->
429 thing_inside (Var arg_id : args1) `thenSmpl` \ res ->
430 returnSmpl (addBind (NonRec arg_id arg1) res)
431 -- I used to use completeBeta but that was wrong, because
432 -- arg_id isn't an InId
436 ---------------------------------
438 simplType :: InType -> SimplM OutType
440 = getSubst `thenSmpl` \ subst ->
442 new_ty = substTy subst ty
449 %************************************************************************
453 %************************************************************************
455 @simplBeta@ is used for non-recursive lets in expressions,
456 as well as true beta reduction.
458 Very similar to @simplLazyBind@, but not quite the same.
461 simplBeta :: InId -- Binder
462 -> InExpr -> SubstEnv -- Arg, with its subst-env
463 -> OutType -- Type of thing computed by the context
464 -> SimplM OutExprStuff -- The body
465 -> SimplM OutExprStuff
467 simplBeta bndr rhs rhs_se cont_ty thing_inside
469 = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
472 simplBeta bndr rhs rhs_se cont_ty thing_inside
473 | preInlineUnconditionally False {- not black listed -} bndr
474 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
475 extendSubst bndr (ContEx rhs_se rhs) thing_inside
478 = -- Simplify the RHS
479 simplBinder bndr $ \ bndr' ->
480 simplArg (idType bndr') (getIdDemandInfo bndr)
481 rhs rhs_se cont_ty $ \ rhs' ->
483 -- Now complete the binding and simplify the body
484 completeBeta bndr bndr' rhs' thing_inside
486 completeBeta bndr bndr' rhs' thing_inside
487 | isUnLiftedType (idType bndr') && not (exprOkForSpeculation rhs')
488 -- Make a case expression instead of a let
489 -- These can arise either from the desugarer,
490 -- or from beta reductions: (\x.e) (x +# y)
491 = getInScope `thenSmpl` \ in_scope ->
492 thing_inside `thenSmpl` \ (floats, (_, body)) ->
493 returnSmpl ([], (in_scope, Case rhs' bndr' [(DEFAULT, [], mkLets floats body)]))
496 = completeBinding bndr bndr' False False rhs' thing_inside
501 simplArg :: OutType -> Demand
502 -> InExpr -> SubstEnv
503 -> OutType -- Type of thing computed by the context
504 -> (OutExpr -> SimplM OutExprStuff)
505 -> SimplM OutExprStuff
506 simplArg arg_ty demand arg arg_se cont_ty thing_inside
508 isUnLiftedType arg_ty ||
509 (opt_DictsStrict && isDictTy arg_ty && isDataType arg_ty)
510 -- Return true only for dictionary types where the dictionary
511 -- has more than one component (else we risk poking on the component
512 -- of a newtype dictionary)
513 = transformRhs arg `thenSmpl` \ t_arg ->
514 getEnv `thenSmpl` \ env ->
516 simplExprF t_arg (ArgOf NoDup cont_ty $ \ rhs' ->
517 setAllExceptInScope env $
518 etaFirst thing_inside rhs')
521 = simplRhs False {- Not top level -}
522 True {- OK to float unboxed -}
526 -- Do eta-reduction on the simplified RHS, if eta reduction is on
527 -- NB: etaCoreExpr only eta-reduces if that results in something trivial
528 etaFirst | opt_SimplDoEtaReduction = \ thing_inside rhs -> thing_inside (etaCoreExprToTrivial rhs)
529 | otherwise = \ thing_inside rhs -> thing_inside rhs
531 -- Try for eta reduction, but *only* if we get all
532 -- the way to an exprIsTrivial expression. We don't want to remove
533 -- extra lambdas unless we are going to avoid allocating this thing altogether
534 etaCoreExprToTrivial rhs | exprIsTrivial rhs' = rhs'
537 rhs' = etaCoreExpr rhs
542 - deals only with Ids, not TyVars
543 - take an already-simplified RHS
545 It does *not* attempt to do let-to-case. Why? Because they are used for
548 (when let-to-case is impossible)
550 - many situations where the "rhs" is known to be a WHNF
551 (so let-to-case is inappropriate).
554 completeBinding :: InId -- Binder
555 -> OutId -- New binder
556 -> Bool -- True <=> top level
557 -> Bool -- True <=> black-listed; don't inline
558 -> OutExpr -- Simplified RHS
559 -> SimplM (OutStuff a) -- Thing inside
560 -> SimplM (OutStuff a)
562 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
563 | (case occ_info of -- This happens; for example, the case_bndr during case of
564 IAmDead -> True -- known constructor: case (a,b) of x { (p,q) -> ... }
565 other -> False) -- Here x isn't mentioned in the RHS, so we don't want to
566 -- create the (dead) let-binding let x = (a,b) in ...
569 | postInlineUnconditionally black_listed occ_info old_bndr new_rhs
570 -- Maybe we don't need a let-binding! Maybe we can just
571 -- inline it right away. Unlike the preInlineUnconditionally case
572 -- we are allowed to look at the RHS.
574 -- NB: a loop breaker never has postInlineUnconditionally True
575 -- and non-loop-breakers only have *forward* references
576 -- Hence, it's safe to discard the binding
578 -- NB: You might think that postInlineUnconditionally is an optimisation,
580 -- let x = f Bool in (x, y)
581 -- then because of the constructor, x will not be *inlined* in the pair,
582 -- so the trivial binding will stay. But in this postInlineUnconditionally
583 -- gag we use the *substitution* to substitute (f Bool) for x, and that *will*
585 = tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
586 extendSubst old_bndr (DoneEx new_rhs)
590 = getSubst `thenSmpl` \ subst ->
592 -- We make new IdInfo for the new binder by starting from the old binder,
593 -- doing appropriate substitutions.
594 -- Then we add arity and unfolding info to get the new binder
595 new_bndr_info = substIdInfo subst (idInfo old_bndr) (idInfo new_bndr)
596 `setArityInfo` ArityAtLeast (exprArity new_rhs)
597 `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
599 final_id = new_bndr `setIdInfo` new_bndr_info
601 -- These seqs force the Ids, and hence the IdInfos, and hence any
602 -- inner substitutions
605 (modifyInScope new_bndr final_id thing_inside `thenSmpl` \ stuff ->
606 returnSmpl (addBind (NonRec final_id new_rhs) stuff))
609 occ_info = getIdOccInfo old_bndr
613 %************************************************************************
615 \subsection{simplLazyBind}
617 %************************************************************************
619 simplLazyBind basically just simplifies the RHS of a let(rec).
620 It does two important optimisations though:
622 * It floats let(rec)s out of the RHS, even if they
623 are hidden by big lambdas
625 * It does eta expansion
628 simplLazyBind :: Bool -- True <=> top level
631 -> SimplM (OutStuff a) -- The body of the binding
632 -> SimplM (OutStuff a)
633 -- When called, the subst env is correct for the entire let-binding
634 -- and hence right for the RHS.
635 -- Also the binder has already been simplified, and hence is in scope
637 simplLazyBind top_lvl bndr bndr' rhs thing_inside
638 = getBlackList `thenSmpl` \ black_list_fn ->
640 black_listed = black_list_fn bndr
643 if preInlineUnconditionally black_listed bndr then
644 -- Inline unconditionally
645 tick (PreInlineUnconditionally bndr) `thenSmpl_`
646 getSubstEnv `thenSmpl` \ rhs_se ->
647 (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
651 getSubstEnv `thenSmpl` \ rhs_se ->
652 simplRhs top_lvl False {- Not ok to float unboxed -}
654 rhs rhs_se $ \ rhs' ->
656 -- Now compete the binding and simplify the body
657 completeBinding bndr bndr' top_lvl black_listed rhs' thing_inside
663 simplRhs :: Bool -- True <=> Top level
664 -> Bool -- True <=> OK to float unboxed (speculative) bindings
665 -> OutType -> InExpr -> SubstEnv
666 -> (OutExpr -> SimplM (OutStuff a))
667 -> SimplM (OutStuff a)
668 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
669 = -- Swizzle the inner lets past the big lambda (if any)
670 -- and try eta expansion
671 transformRhs rhs `thenSmpl` \ t_rhs ->
674 setSubstEnv rhs_se (simplExprF t_rhs (Stop rhs_ty)) `thenSmpl` \ (floats, (in_scope', rhs')) ->
676 -- Float lets out of RHS
678 (floats_out, rhs'') | float_ubx = (floats, rhs')
679 | otherwise = splitFloats floats rhs'
681 if (top_lvl || exprIsCheap rhs') && -- Float lets if (a) we're at the top level
682 not (null floats_out) -- or (b) it exposes a cheap (i.e. duplicatable) expression
684 tickLetFloat floats_out `thenSmpl_`
687 -- There's a subtlety here. There may be a binding (x* = e) in the
688 -- floats, where the '*' means 'will be demanded'. So is it safe
689 -- to float it out? Answer no, but it won't matter because
690 -- we only float if arg' is a WHNF,
691 -- and so there can't be any 'will be demanded' bindings in the floats.
693 WARN( any demanded_float floats_out, ppr floats_out )
694 setInScope in_scope' (etaFirst thing_inside rhs'') `thenSmpl` \ stuff ->
695 -- in_scope' may be excessive, but that's OK;
696 -- it's a superset of what's in scope
697 returnSmpl (addBinds floats_out stuff)
699 -- Don't do the float
700 etaFirst thing_inside (mkLets floats rhs')
702 -- In a let-from-let float, we just tick once, arbitrarily
703 -- choosing the first floated binder to identify it
704 tickLetFloat (NonRec b r : fs) = tick (LetFloatFromLet b)
705 tickLetFloat (Rec ((b,r):prs) : fs) = tick (LetFloatFromLet b)
707 demanded_float (NonRec b r) = isStrict (getIdDemandInfo b) && not (isUnLiftedType (idType b))
708 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
709 demanded_float (Rec _) = False
711 -- Don't float any unlifted bindings out, because the context
712 -- is either a Rec group, or the top level, neither of which
713 -- can tolerate them.
714 splitFloats floats rhs
718 go (f:fs) | must_stay f = ([], mkLets (f:fs) rhs)
719 | otherwise = case go fs of
720 (out, rhs') -> (f:out, rhs')
722 must_stay (Rec prs) = False -- No unlifted bindings in here
723 must_stay (NonRec b r) = isUnLiftedType (idType b)
728 %************************************************************************
730 \subsection{Variables}
732 %************************************************************************
736 = getSubst `thenSmpl` \ subst ->
737 case lookupIdSubst subst var of
738 DoneEx e -> zapSubstEnv (simplExprF e cont)
739 ContEx env1 e -> setSubstEnv env1 (simplExprF e cont)
740 DoneId var1 occ -> WARN( not (isInScope var1 subst) && isLocallyDefined var1 && not (mayHaveNoBinding var1),
741 text "simplVar:" <+> ppr var )
742 -- The mayHaveNoBinding test accouunts for the fact
743 -- that class dictionary constructors dont have top level
744 -- bindings and hence aren't in scope.
748 = getBlackList `thenSmpl` \ black_list ->
749 getInScope `thenSmpl` \ in_scope ->
750 completeCall black_list in_scope occ var cont
752 ---------------------------------------------------------
753 -- Dealing with a call
755 completeCall black_list_fn in_scope occ var cont
757 -- Look for an unfolding. There's a binding for the
758 -- thing, but perhaps we want to inline it anyway
759 | maybeToBool maybe_inline
760 = tick (UnfoldingDone var) `thenSmpl_`
761 zapSubstEnv (completeInlining var unf_template discard_inline_cont)
762 -- The template is already simplified, so don't re-substitute.
763 -- This is VITAL. Consider
765 -- let y = \z -> ...x... in
767 -- We'll clone the inner \x, adding x->x' in the id_subst
768 -- Then when we inline y, we must *not* replace x by x' in
769 -- the inlined copy!!
771 | otherwise -- No inlining
772 -- Use prepareArgs to use function strictness
773 = prepareArgs (ppr var) (idType var) (get_str var) cont $ \ args' cont' ->
775 -- Look for rules or specialisations that match
777 -- It's important to simplify the args first, because the rule-matcher
778 -- doesn't do substitution as it goes. We don't want to use subst_args
779 -- (defined in the 'where') because that throws away useful occurrence info,
780 -- and perhaps-very-important specialisations.
782 -- Some functions have specialisations *and* are strict; in this case,
783 -- we don't want to inline the wrapper of the non-specialised thing; better
784 -- to call the specialised thing instead.
785 -- But the black-listing mechanism means that inlining of the wrapper
786 -- won't occur for things that have specialisations till a later phase, so
787 -- it's ok to try for inlining first.
788 getSwitchChecker `thenSmpl` \ chkr ->
789 if switchIsOn chkr DontApplyRules then
791 rebuild (mkApps (Var var) args') cont'
794 case lookupRule in_scope var args' of
795 Just (rule_name, rule_rhs) ->
796 tick (RuleFired rule_name) `thenSmpl_`
797 zapSubstEnv (simplExprF rule_rhs cont')
798 -- See note above about zapping the substitution here
800 Nothing -> rebuild (mkApps (Var var) args') cont'
803 get_str var = case getIdStrictness var of
804 NoStrictnessInfo -> (repeat wwLazy, False)
805 StrictnessInfo demands result_bot -> (demands, result_bot)
807 ---------- Unfolding stuff
808 (subst_args, result_cont) = contArgs in_scope cont
809 val_args = filter isValArg subst_args
810 arg_infos = map (interestingArg in_scope) val_args
811 inline_call = contIsInline result_cont
812 interesting_cont = contIsInteresting result_cont
813 discard_inline_cont | inline_call = discardInline cont
816 maybe_inline = callSiteInline black_listed inline_call occ
817 var arg_infos interesting_cont
818 Just unf_template = maybe_inline
819 black_listed = black_list_fn var
822 -- An argument is interesting if it has *some* structure
823 -- We are here trying to avoid unfolding a function that
824 -- is applied only to variables that have no unfolding
825 -- (i.e. they are probably lambda bound): f x y z
826 -- There is little point in inlining f here.
827 interestingArg in_scope (Type _) = False
828 interestingArg in_scope (App fn (Type _)) = interestingArg in_scope fn
829 interestingArg in_scope (Var v) = hasSomeUnfolding (getIdUnfolding v')
831 v' = case lookupVarSet in_scope v of
834 interestingArg in_scope other = True
837 -- First a special case
838 -- Don't actually inline the scrutinee when we see
839 -- case x of y { .... }
840 -- and x has unfolding (C a b). Why not? Because
841 -- we get a silly binding y = C a b. If we don't
842 -- inline knownCon can directly substitute x for y instead.
843 completeInlining var (Con con con_args) (Select _ bndr alts se cont)
845 = knownCon (Var var) con con_args bndr alts se cont
847 -- Now the normal case
848 completeInlining var unfolding cont
849 = simplExprF unfolding cont
851 ----------- costCentreOk
852 -- costCentreOk checks that it's ok to inline this thing
853 -- The time it *isn't* is this:
855 -- f x = let y = E in
856 -- scc "foo" (...y...)
858 -- Here y has a "current cost centre", and we can't inline it inside "foo",
859 -- regardless of whether E is a WHNF or not.
861 costCentreOk ccs_encl cc_rhs
862 = not opt_SccProfilingOn
863 || isSubsumedCCS ccs_encl -- can unfold anything into a subsumed scope
864 || not (isEmptyCC cc_rhs) -- otherwise need a cc on the unfolding
869 ---------------------------------------------------------
870 -- Preparing arguments for a call
872 prepareArgs :: SDoc -- Error message info
873 -> OutType -> ([Demand],Bool) -> SimplCont
874 -> ([OutExpr] -> SimplCont -> SimplM OutExprStuff)
875 -> SimplM OutExprStuff
877 prepareArgs pp_fun orig_fun_ty (fun_demands, result_bot) orig_cont thing_inside
878 = go [] demands orig_fun_ty orig_cont
880 not_enough_args = fun_demands `lengthExceeds` countValArgs orig_cont
881 -- "No strictness info" is signalled by an infinite list of wwLazy
883 demands | not_enough_args = repeat wwLazy -- Not enough args, or no strictness
884 | result_bot = fun_demands -- Enough args, and function returns bottom
885 | otherwise = fun_demands ++ repeat wwLazy -- Enough args and function does not return bottom
886 -- NB: demands is finite iff enough args and result_bot is True
888 -- Main game plan: loop through the arguments, simplifying
889 -- each of them in turn. We carry with us a list of demands,
890 -- and the type of the function-applied-to-earlier-args
893 go acc ds fun_ty (ApplyTo _ arg@(Type ty_arg) se cont)
894 = getInScope `thenSmpl` \ in_scope ->
896 ty_arg' = substTy (mkSubst in_scope se) ty_arg
897 res_ty = applyTy fun_ty ty_arg'
899 seqType ty_arg' `seq`
900 go (Type ty_arg' : acc) ds res_ty cont
903 go acc (d:ds) fun_ty (ApplyTo _ val_arg se cont)
904 = case splitFunTy_maybe fun_ty of {
905 Nothing -> pprTrace "prepareArgs" (pp_fun $$ ppr orig_fun_ty $$ ppr orig_cont)
906 (thing_inside (reverse acc) cont) ;
907 Just (arg_ty, res_ty) ->
908 simplArg arg_ty d val_arg se (contResultType cont) $ \ arg' ->
909 go (arg':acc) ds res_ty cont }
911 -- We've run out of demands, which only happens for functions
912 -- we *know* now return bottom
914 -- * case (error "hello") of { ... }
915 -- * (error "Hello") arg
916 -- * f (error "Hello") where f is strict
918 go acc [] fun_ty cont = tick_case_of_error cont `thenSmpl_`
919 thing_inside (reverse acc) (discardCont cont)
921 -- We're run out of arguments
922 go acc ds fun_ty cont = thing_inside (reverse acc) cont
924 -- Boring: we must only record a tick if there was an interesting
925 -- continuation to discard. If not, we tick forever.
926 tick_case_of_error (Stop _) = returnSmpl ()
927 tick_case_of_error (CoerceIt _ (Stop _)) = returnSmpl ()
928 tick_case_of_error other = tick BottomFound
931 %************************************************************************
933 \subsection{Decisions about inlining}
935 %************************************************************************
937 NB: At one time I tried not pre/post-inlining top-level things,
938 even if they occur exactly once. Reason:
939 (a) some might appear as a function argument, so we simply
940 replace static allocation with dynamic allocation:
946 (b) some top level things might be black listed
948 HOWEVER, I found that some useful foldr/build fusion was lost (most
949 notably in spectral/hartel/parstof) because the foldr didn't see the build.
951 Doing the dynamic allocation isn't a big deal, in fact, but losing the
955 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
956 -- Examines a bndr to see if it is used just once in a
957 -- completely safe way, so that it is safe to discard the binding
958 -- inline its RHS at the (unique) usage site, REGARDLESS of how
959 -- big the RHS might be. If this is the case we don't simplify
960 -- the RHS first, but just inline it un-simplified.
962 -- This is much better than first simplifying a perhaps-huge RHS
963 -- and then inlining and re-simplifying it.
965 -- NB: we don't even look at the RHS to see if it's trivial
968 -- where x is used many times, but this is the unique occurrence
969 -- of y. We should NOT inline x at all its uses, because then
970 -- we'd do the same for y -- aargh! So we must base this
971 -- pre-rhs-simplification decision solely on x's occurrences, not
974 -- Evne RHSs labelled InlineMe aren't caught here, because
975 -- there might be no benefit from inlining at the call site.
977 preInlineUnconditionally black_listed bndr
978 | black_listed || opt_SimplNoPreInlining = False
979 | otherwise = case getIdOccInfo bndr of
980 OneOcc in_lam once -> not in_lam && once
981 -- Not inside a lambda, one occurrence ==> safe!
985 postInlineUnconditionally :: Bool -- Black listed
987 -> InId -> OutExpr -> Bool
988 -- Examines a (bndr = rhs) binding, AFTER the rhs has been simplified
989 -- It returns True if it's ok to discard the binding and inline the
990 -- RHS at every use site.
992 -- NOTE: This isn't our last opportunity to inline.
993 -- We're at the binding site right now, and
994 -- we'll get another opportunity when we get to the ocurrence(s)
996 postInlineUnconditionally black_listed occ_info bndr rhs
997 | isExportedId bndr ||
999 loop_breaker = False -- Don't inline these
1000 | otherwise = exprIsTrivial rhs -- Duplicating is free
1001 -- Don't inline even WHNFs inside lambdas; doing so may
1002 -- simply increase allocation when the function is called
1003 -- This isn't the last chance; see NOTE above.
1005 -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
1006 -- Why? Because we don't even want to inline them into the
1007 -- RHS of constructor arguments. See NOTE above
1009 -- NB: Even NOINLINEis ignored here: if the rhs is trivial
1010 -- it's best to inline it anyway. We often get a=E; b=a
1011 -- from desugaring, with both a and b marked NOINLINE.
1013 loop_breaker = case occ_info of
1014 IAmALoopBreaker -> True
1020 %************************************************************************
1022 \subsection{The main rebuilder}
1024 %************************************************************************
1027 -------------------------------------------------------------------
1028 -- Finish rebuilding
1030 = getInScope `thenSmpl` \ in_scope ->
1031 returnSmpl ([], (in_scope, expr))
1033 ---------------------------------------------------------
1034 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1036 -- Stop continuation
1037 rebuild expr (Stop _) = rebuild_done expr
1039 -- ArgOf continuation
1040 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1042 -- ApplyTo continuation
1043 rebuild expr cont@(ApplyTo _ arg se cont')
1044 = setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1045 rebuild (App expr arg') cont'
1047 -- Coerce continuation
1048 rebuild expr (CoerceIt to_ty cont)
1049 = rebuild (mkCoerce to_ty expr) cont
1051 -- Inline continuation
1052 rebuild expr (InlinePlease cont)
1053 = rebuild (Note InlineCall expr) cont
1055 rebuild scrut (Select _ bndr alts se cont)
1056 = rebuild_case scrut bndr alts se cont
1060 Case elimination [see the code above]
1062 Start with a simple situation:
1064 case x# of ===> e[x#/y#]
1067 (when x#, y# are of primitive type, of course). We can't (in general)
1068 do this for algebraic cases, because we might turn bottom into
1071 Actually, we generalise this idea to look for a case where we're
1072 scrutinising a variable, and we know that only the default case can
1077 other -> ...(case x of
1081 Here the inner case can be eliminated. This really only shows up in
1082 eliminating error-checking code.
1084 We also make sure that we deal with this very common case:
1089 Here we are using the case as a strict let; if x is used only once
1090 then we want to inline it. We have to be careful that this doesn't
1091 make the program terminate when it would have diverged before, so we
1093 - x is used strictly, or
1094 - e is already evaluated (it may so if e is a variable)
1096 Lastly, we generalise the transformation to handle this:
1102 We only do this for very cheaply compared r's (constructors, literals
1103 and variables). If pedantic bottoms is on, we only do it when the
1104 scrutinee is a PrimOp which can't fail.
1106 We do it *here*, looking at un-simplified alternatives, because we
1107 have to check that r doesn't mention the variables bound by the
1108 pattern in each alternative, so the binder-info is rather useful.
1110 So the case-elimination algorithm is:
1112 1. Eliminate alternatives which can't match
1114 2. Check whether all the remaining alternatives
1115 (a) do not mention in their rhs any of the variables bound in their pattern
1116 and (b) have equal rhss
1118 3. Check we can safely ditch the case:
1119 * PedanticBottoms is off,
1120 or * the scrutinee is an already-evaluated variable
1121 or * the scrutinee is a primop which is ok for speculation
1122 -- ie we want to preserve divide-by-zero errors, and
1123 -- calls to error itself!
1125 or * [Prim cases] the scrutinee is a primitive variable
1127 or * [Alg cases] the scrutinee is a variable and
1128 either * the rhs is the same variable
1129 (eg case x of C a b -> x ===> x)
1130 or * there is only one alternative, the default alternative,
1131 and the binder is used strictly in its scope.
1132 [NB this is helped by the "use default binder where
1133 possible" transformation; see below.]
1136 If so, then we can replace the case with one of the rhss.
1139 Blob of helper functions for the "case-of-something-else" situation.
1143 ---------------------------------------------------------
1144 -- Case of known constructor or literal
1146 rebuild_case scrut@(Con con args) bndr alts se cont
1147 | conOkForAlt con -- Knocks out PrimOps and NoRepLits
1148 = knownCon scrut con args bndr alts se cont
1150 ---------------------------------------------------------
1151 -- Eliminate the case if possible
1153 rebuild_case scrut bndr alts se cont
1154 | -- Check that the RHSs are all the same, and
1155 -- don't use the binders in the alternatives
1156 -- This test succeeds rapidly in the common case of
1157 -- a single DEFAULT alternative
1158 all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1160 -- Check that the scrutinee can be let-bound instead of case-bound
1161 && ( exprOkForSpeculation scrut
1162 -- OK not to evaluate it
1163 -- This includes things like (==# a# b#)::Bool
1164 -- so that we simplify
1165 -- case ==# a# b# of { True -> x; False -> x }
1168 -- This particular example shows up in default methods for
1169 -- comparision operations (e.g. in (>=) for Int.Int32)
1170 || exprIsValue scrut -- It's already evaluated
1171 || var_demanded_later scrut -- It'll be demanded later
1173 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1174 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1175 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1176 -- its argument: case x of { y -> dataToTag# y }
1177 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1178 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1182 -- && opt_SimplDoCaseElim
1183 -- [June 99; don't test this flag. The code generator dies if it sees
1184 -- case (\x.e) of f -> ...
1185 -- so better to always do it
1187 -- Get rid of the case altogether
1188 -- See the extensive notes on case-elimination above
1189 -- Remember to bind the binder though!
1190 = tick (CaseElim bndr) `thenSmpl_` (
1192 simplBinder bndr $ \ bndr' ->
1193 completeBinding bndr bndr' False False scrut $
1194 simplExprF rhs1 cont)
1197 (rhs1:other_rhss) = [rhs | (_,_,rhs) <- alts]
1198 binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1200 var_demanded_later (Var v) = isStrict (getIdDemandInfo bndr) -- It's going to be evaluated later
1201 var_demanded_later other = False
1203 ---------------------------------------------------------
1204 -- Case of something else
1206 rebuild_case scrut case_bndr alts se cont
1207 = -- Prepare case alternatives
1208 prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1209 scrut_cons alts `thenSmpl` \ better_alts ->
1211 -- Set the new subst-env in place (before dealing with the case binder)
1214 -- Deal with the case binder, and prepare the continuation;
1215 -- The new subst_env is in place
1216 prepareCaseCont better_alts cont $ \ cont' ->
1219 -- Deal with variable scrutinee
1220 ( simplCaseBinder scrut case_bndr $ \ case_bndr' zap_occ_info ->
1222 -- Deal with the case alternatives
1223 simplAlts zap_occ_info scrut_cons
1224 case_bndr' better_alts cont' `thenSmpl` \ alts' ->
1226 mkCase scrut case_bndr' alts'
1227 ) `thenSmpl` \ case_expr ->
1229 -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1230 -- over the rebuild_done; rebuild_done returns the in-scope set, and
1231 -- that should not include these chaps!
1232 rebuild_done case_expr
1234 -- scrut_cons tells what constructors the scrutinee can't possibly match
1235 scrut_cons = case scrut of
1236 Var v -> otherCons (getIdUnfolding v)
1240 knownCon expr con args bndr alts se cont
1241 = tick (KnownBranch bndr) `thenSmpl_`
1243 simplBinder bndr $ \ bndr' ->
1244 case findAlt con alts of
1245 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1246 completeBinding bndr bndr' False False expr $
1247 -- Don't use completeBeta here. The expr might be
1248 -- an unboxed literal, like 3, or a variable
1249 -- whose unfolding is an unboxed literal... and
1250 -- completeBeta will just construct another case
1254 (Literal lit, bs, rhs) -> ASSERT( null bs )
1255 extendSubst bndr (DoneEx expr) $
1256 -- Unconditionally substitute, because expr must
1257 -- be a variable or a literal. It can't be a
1258 -- NoRep literal because they don't occur in
1262 (DataCon dc, bs, rhs) -> ASSERT( length bs == length real_args )
1263 completeBinding bndr bndr' False False expr $
1265 extendSubstList bs (map mk real_args) $
1268 real_args = drop (dataConNumInstArgs dc) args
1269 mk (Type ty) = DoneTy ty
1270 mk other = DoneEx other
1275 prepareCaseCont :: [InAlt] -> SimplCont
1276 -> (SimplCont -> SimplM (OutStuff a))
1277 -> SimplM (OutStuff a)
1278 -- Polymorphic recursion here!
1280 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1281 prepareCaseCont alts cont thing_inside = simplType (coreAltsType alts) `thenSmpl` \ alts_ty ->
1282 mkDupableCont alts_ty cont thing_inside
1283 -- At one time I passed in the un-simplified type, and simplified
1284 -- it only if we needed to construct a join binder, but that
1285 -- didn't work because we have to decompse function types
1286 -- (using funResultTy) in mkDupableCont.
1289 simplCaseBinder checks whether the scrutinee is a variable, v.
1290 If so, try to eliminate uses of v in the RHSs in favour of case_bndr;
1291 that way, there's a chance that v will now only be used once, and hence inlined.
1293 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1294 in the case binder, because the case-binder now effectively occurs
1295 whenever v does. AND we have to do the same for the pattern-bound
1298 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1300 Here, b and p are dead. But when we move the argment inside the first
1301 case RHS, and eliminate the second case, we get
1303 case x or { (a,b) -> a b }
1305 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1306 happened. Hence the zap_occ_info function returned by simplCaseBinder
1309 simplCaseBinder (Var v) case_bndr thing_inside
1310 = simplBinder (zap case_bndr) $ \ case_bndr' ->
1311 modifyInScope v case_bndr' $
1312 -- We could extend the substitution instead, but it would be
1313 -- a hack because then the substitution wouldn't be idempotent
1314 -- any more (v is an OutId). And this just just as well.
1315 thing_inside case_bndr' zap
1317 zap b = b `setIdOccInfo` NoOccInfo
1319 simplCaseBinder other_scrut case_bndr thing_inside
1320 = simplBinder case_bndr $ \ case_bndr' ->
1321 thing_inside case_bndr' (\ bndr -> bndr) -- NoOp on bndr
1324 prepareCaseAlts does two things:
1326 1. Remove impossible alternatives
1328 2. If the DEFAULT alternative can match only one possible constructor,
1329 then make that constructor explicit.
1331 case e of x { DEFAULT -> rhs }
1333 case e of x { (a,b) -> rhs }
1334 where the type is a single constructor type. This gives better code
1335 when rhs also scrutinises x or e.
1338 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1340 = case (findDefault filtered_alts, missing_cons) of
1342 ((alts_no_deflt, Just rhs), [data_con]) -- Just one missing constructor!
1343 -> tick (FillInCaseDefault bndr) `thenSmpl_`
1345 (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1347 getUniquesSmpl (length ex_tyvars) `thenSmpl` \ tv_uniqs ->
1349 ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
1350 mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1352 newIds (dataConArgTys
1354 (inst_tys ++ mkTyVarTys ex_tyvars')) $ \ bndrs ->
1355 returnSmpl ((DataCon data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1357 other -> returnSmpl filtered_alts
1359 -- Filter out alternatives that can't possibly match
1360 filtered_alts = case scrut_cons of
1362 other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1364 missing_cons = [data_con | data_con <- tyConDataCons tycon,
1365 not (data_con `elem` handled_data_cons)]
1366 handled_data_cons = [data_con | DataCon data_con <- scrut_cons] ++
1367 [data_con | (DataCon data_con, _, _) <- filtered_alts]
1370 prepareCaseAlts _ _ scrut_cons alts
1371 = returnSmpl alts -- Functions
1374 ----------------------
1375 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1376 = mapSmpl simpl_alt alts
1378 inst_tys' = case splitTyConApp_maybe (idType case_bndr') of
1379 Just (tycon, inst_tys) -> inst_tys
1381 -- handled_cons is all the constructors that are dealt
1382 -- with, either by being impossible, or by there being an alternative
1383 handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1385 simpl_alt (DEFAULT, _, rhs)
1386 = -- In the default case we record the constructors that the
1387 -- case-binder *can't* be.
1388 -- We take advantage of any OtherCon info in the case scrutinee
1389 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons) $
1390 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1391 returnSmpl (DEFAULT, [], rhs')
1393 simpl_alt (con, vs, rhs)
1394 = -- Deal with the pattern-bound variables
1395 -- Mark the ones that are in ! positions in the data constructor
1396 -- as certainly-evaluated.
1397 -- NB: it happens that simplBinders does *not* erase the OtherCon
1398 -- form of unfolding, so it's ok to add this info before
1399 -- doing simplBinders
1400 simplBinders (add_evals con vs) $ \ vs' ->
1402 -- Bind the case-binder to (Con args)
1404 con_app = Con con (map Type inst_tys' ++ map varToCoreExpr vs')
1406 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkUnfolding False con_app) $
1407 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1408 returnSmpl (con, vs', rhs')
1411 -- add_evals records the evaluated-ness of the bound variables of
1412 -- a case pattern. This is *important*. Consider
1413 -- data T = T !Int !Int
1415 -- case x of { T a b -> T (a+1) b }
1417 -- We really must record that b is already evaluated so that we don't
1418 -- go and re-evaluate it when constructing the result.
1420 add_evals (DataCon dc) vs = cat_evals vs (dataConRepStrictness dc)
1421 add_evals other_con vs = vs
1423 cat_evals [] [] = []
1424 cat_evals (v:vs) (str:strs)
1425 | isTyVar v = v : cat_evals vs (str:strs)
1426 | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1427 | otherwise = v' : cat_evals vs strs
1433 %************************************************************************
1435 \subsection{Duplicating continuations}
1437 %************************************************************************
1440 mkDupableCont :: OutType -- Type of the thing to be given to the continuation
1442 -> (SimplCont -> SimplM (OutStuff a))
1443 -> SimplM (OutStuff a)
1444 mkDupableCont ty cont thing_inside
1445 | contIsDupable cont
1448 mkDupableCont _ (CoerceIt ty cont) thing_inside
1449 = mkDupableCont ty cont $ \ cont' ->
1450 thing_inside (CoerceIt ty cont')
1452 mkDupableCont ty (InlinePlease cont) thing_inside
1453 = mkDupableCont ty cont $ \ cont' ->
1454 thing_inside (InlinePlease cont')
1456 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1457 = -- Build the RHS of the join point
1458 newId join_arg_ty ( \ arg_id ->
1459 cont_fn (Var arg_id) `thenSmpl` \ (binds, (_, rhs)) ->
1460 returnSmpl (Lam (setOneShotLambda arg_id) (mkLets binds rhs))
1461 ) `thenSmpl` \ join_rhs ->
1463 -- Build the join Id and continuation
1464 newId (coreExprType join_rhs) $ \ join_id ->
1466 new_cont = ArgOf OkToDup cont_ty
1467 (\arg' -> rebuild_done (App (Var join_id) arg'))
1470 tick (CaseOfCase join_id) `thenSmpl_`
1471 -- Want to tick here so that we go round again,
1472 -- and maybe copy or inline the code;
1473 -- not strictly CaseOf Case
1474 thing_inside new_cont `thenSmpl` \ res ->
1475 returnSmpl (addBind (NonRec join_id join_rhs) res)
1477 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1478 = mkDupableCont (funResultTy ty) cont $ \ cont' ->
1479 setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1480 if exprIsDupable arg' then
1481 thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1483 newId (coreExprType arg') $ \ bndr ->
1485 tick (CaseOfCase bndr) `thenSmpl_`
1486 -- Want to tick here so that we go round again,
1487 -- and maybe copy or inline the code;
1488 -- not strictly CaseOf Case
1489 thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont') `thenSmpl` \ res ->
1490 returnSmpl (addBind (NonRec bndr arg') res)
1492 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1493 = tick (CaseOfCase case_bndr) `thenSmpl_`
1495 simplBinder case_bndr $ \ case_bndr' ->
1496 prepareCaseCont alts cont $ \ cont' ->
1497 mapAndUnzipSmpl (mkDupableAlt case_bndr case_bndr' cont') alts `thenSmpl` \ (alt_binds_s, alts') ->
1498 returnSmpl (concat alt_binds_s, alts')
1499 ) `thenSmpl` \ (alt_binds, alts') ->
1501 extendInScopes [b | NonRec b _ <- alt_binds] $
1503 -- NB that the new alternatives, alts', are still InAlts, using the original
1504 -- binders. That means we can keep the case_bndr intact. This is important
1505 -- because another case-of-case might strike, and so we want to keep the
1506 -- info that the case_bndr is dead (if it is, which is often the case).
1507 -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1508 -- case in I/O rich code. We aren't allowed a lambda bound
1509 -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1510 thing_inside (Select OkToDup case_bndr alts' se (Stop (contResultType cont))) `thenSmpl` \ res ->
1512 returnSmpl (addBinds alt_binds res)
1515 mkDupableAlt :: InId -> OutId -> SimplCont -> InAlt -> SimplM (OutStuff InAlt)
1516 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs)
1517 = simplBinders bndrs $ \ bndrs' ->
1518 simplExprC rhs cont `thenSmpl` \ rhs' ->
1520 if (case cont of { Stop _ -> exprIsDupable rhs'; other -> False}) then
1521 -- It is worth checking for a small RHS because otherwise we
1522 -- get extra let bindings that may cause an extra iteration of the simplifier to
1523 -- inline back in place. Quite often the rhs is just a variable or constructor.
1524 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1525 -- iterations because the version with the let bindings looked big, and so wasn't
1526 -- inlined, but after the join points had been inlined it looked smaller, and so
1529 -- But since the continuation is absorbed into the rhs, we only do this
1530 -- for a Stop continuation.
1532 -- NB: we have to check the size of rhs', not rhs.
1533 -- Duplicating a small InAlt might invalidate occurrence information
1534 -- However, if it *is* dupable, we return the *un* simplified alternative,
1535 -- because otherwise we'd need to pair it up with an empty subst-env.
1536 -- (Remember we must zap the subst-env before re-simplifying something).
1537 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1538 returnSmpl ([], alt)
1542 rhs_ty' = coreExprType rhs'
1543 (used_bndrs, used_bndrs')
1544 = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr : bndrs)
1545 (case_bndr' : bndrs'),
1546 not (isDeadBinder bndr)]
1547 -- The new binders have lost their occurrence info,
1548 -- so we have to extract it from the old ones
1550 ( if null used_bndrs'
1551 -- If we try to lift a primitive-typed something out
1552 -- for let-binding-purposes, we will *caseify* it (!),
1553 -- with potentially-disastrous strictness results. So
1554 -- instead we turn it into a function: \v -> e
1555 -- where v::State# RealWorld#. The value passed to this function
1556 -- is realworld#, which generates (almost) no code.
1558 -- There's a slight infelicity here: we pass the overall
1559 -- case_bndr to all the join points if it's used in *any* RHS,
1560 -- because we don't know its usage in each RHS separately
1562 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1563 -- we make the join point into a function whenever used_bndrs'
1564 -- is empty. This makes the join-point more CPR friendly.
1565 -- Consider: let j = if .. then I# 3 else I# 4
1566 -- in case .. of { A -> j; B -> j; C -> ... }
1568 -- Now CPR should not w/w j because it's a thunk, so
1569 -- that means that the enclosing function can't w/w either,
1570 -- which is a lose. Here's the example that happened in practice:
1571 -- kgmod :: Int -> Int -> Int
1572 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1576 then newId realWorldStatePrimTy $ \ rw_id ->
1577 returnSmpl ([rw_id], [Var realWorldPrimId])
1579 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1581 `thenSmpl` \ (final_bndrs', final_args) ->
1583 newId (foldr (mkFunTy . idType) rhs_ty' final_bndrs') $ \ join_bndr ->
1585 -- Notice that we make the lambdas into one-shot-lambdas. The
1586 -- join point is sure to be applied at most once, and doing so
1587 -- prevents the body of the join point being floated out by
1588 -- the full laziness pass
1589 returnSmpl ([NonRec join_bndr (mkLams (map setOneShotLambda final_bndrs') rhs')],
1590 (con, bndrs, mkApps (Var join_bndr) final_args))