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,
18 simplBinder, simplBinders, simplIds, findDefault,
19 SimplCont(..), DupFlag(..), contResultType, analyseCont,
20 discardInline, countArgs, countValArgs, discardCont, contIsDupable
22 import Var ( TyVar, mkSysTyVar, tyVarKind, maybeModifyIdInfo )
25 import Id ( Id, idType, idInfo, idUnique, isDataConId, isDataConId_maybe,
26 idUnfolding, setIdUnfolding, isExportedId, isDeadBinder,
27 idSpecialisation, setIdSpecialisation,
30 idOccInfo, setIdOccInfo,
31 zapLamIdInfo, zapFragileIdInfo,
32 idStrictness, isBottomingId,
34 setOneShotLambda, maybeModifyIdInfo
36 import IdInfo ( InlinePragInfo(..), OccInfo(..), StrictnessInfo(..),
37 ArityInfo(..), atLeastArity, arityLowerBound, unknownArity,
38 specInfo, inlinePragInfo, setArityInfo, setInlinePragInfo, setUnfoldingInfo,
39 CprInfo(..), cprInfo, occInfo
41 import Demand ( Demand, isStrict, wwLazy )
42 import DataCon ( DataCon, dataConNumInstArgs, dataConRepStrictness, dataConRepArity,
43 dataConSig, dataConArgTys
46 import CoreFVs ( exprFreeVars, mustHaveLocalBinding )
47 import CoreUnfold ( Unfolding, mkOtherCon, mkUnfolding, otherCons, maybeUnfoldingTemplate,
48 callSiteInline, hasSomeUnfolding, noUnfolding
50 import CoreUtils ( cheapEqExpr, exprIsDupable, exprIsCheap, exprIsTrivial, exprIsConApp_maybe,
51 exprType, coreAltsType, exprArity, exprIsValue, idAppIsCheap,
52 exprOkForSpeculation, etaReduceExpr,
53 mkCoerce, mkSCC, mkInlineMe, mkAltExpr
55 import Rules ( lookupRule )
56 import CostCentre ( isSubsumedCCS, currentCCS, isEmptyCC )
57 import Type ( Type, mkTyVarTy, mkTyVarTys, isUnLiftedType, seqType,
58 mkFunTy, splitFunTy, splitFunTys, splitFunTy_maybe,
60 funResultTy, isDictTy, isDataType, applyTy, applyTys, mkFunTys
62 import Subst ( Subst, mkSubst, emptySubst, substTy, substExpr,
63 substEnv, isInScope, lookupIdSubst, substIdInfo
65 import TyCon ( isDataTyCon, tyConDataConsIfAvailable,
66 tyConClass_maybe, tyConArity, isDataTyCon
68 import TysPrim ( realWorldStatePrimTy )
69 import PrelInfo ( realWorldPrimId )
70 import BasicTypes ( TopLevelFlag(..), isTopLevel, isLoopBreaker )
71 import Maybes ( maybeToBool )
72 import Util ( zipWithEqual, lengthExceeds )
75 import Unique ( foldrIdKey ) -- Temp
79 The guts of the simplifier is in this module, but the driver
80 loop for the simplifier is in SimplCore.lhs.
83 %************************************************************************
87 %************************************************************************
90 simplTopBinds :: [InBind] -> SimplM [OutBind]
93 = -- Put all the top-level binders into scope at the start
94 -- so that if a transformation rule has unexpectedly brought
95 -- anything into scope, then we don't get a complaint about that.
96 -- It's rather as if the top-level binders were imported.
97 simplIds (bindersOfBinds binds) $ \ bndrs' ->
98 simpl_binds binds bndrs' `thenSmpl` \ (binds', _) ->
99 freeTick SimplifierDone `thenSmpl_`
103 -- We need to track the zapped top-level binders, because
104 -- they should have their fragile IdInfo zapped (notably occurrence info)
105 simpl_binds [] bs = ASSERT( null bs ) returnSmpl ([], panic "simplTopBinds corner")
106 simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr b rhs (simpl_binds binds bs)
107 simpl_binds (Rec pairs : binds) bs = simplRecBind True pairs (take n bs) (simpl_binds binds (drop n bs))
111 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
112 -> SimplM (OutStuff a) -> SimplM (OutStuff a)
113 simplRecBind top_lvl pairs bndrs' thing_inside
114 = go pairs bndrs' `thenSmpl` \ (binds', (binds'', res)) ->
115 returnSmpl (Rec (flattenBinds binds') : binds'', res)
117 go [] _ = thing_inside `thenSmpl` \ stuff ->
118 returnSmpl ([], stuff)
120 go ((bndr, rhs) : pairs) (bndr' : bndrs')
121 = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
122 -- Don't float unboxed bindings out,
123 -- because we can't "rec" them
127 %************************************************************************
129 \subsection[Simplify-simplExpr]{The main function: simplExpr}
131 %************************************************************************
134 addLetBind :: OutId -> OutExpr -> SimplM (OutStuff a) -> SimplM (OutStuff a)
135 addLetBind bndr rhs thing_inside
136 = thing_inside `thenSmpl` \ (binds, res) ->
137 returnSmpl (NonRec bndr rhs : binds, res)
139 addLetBinds :: [CoreBind] -> SimplM (OutStuff a) -> SimplM (OutStuff a)
140 addLetBinds binds1 thing_inside
141 = thing_inside `thenSmpl` \ (binds2, res) ->
142 returnSmpl (binds1 ++ binds2, res)
144 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
145 -- Make a case expression instead of a let
146 -- These can arise either from the desugarer,
147 -- or from beta reductions: (\x.e) (x +# y)
149 addCaseBind bndr rhs thing_inside
150 = getInScope `thenSmpl` \ in_scope ->
151 thing_inside `thenSmpl` \ (floats, (_, body)) ->
152 returnSmpl ([], (in_scope, Case rhs bndr [(DEFAULT, [], mkLets floats body)]))
154 addNonRecBind bndr rhs thing_inside
155 -- Checks for needing a case binding
156 | needsCaseBinding (idType bndr) rhs = addCaseBind bndr rhs thing_inside
157 | otherwise = addLetBind bndr rhs thing_inside
160 The reason for this OutExprStuff stuff is that we want to float *after*
161 simplifying a RHS, not before. If we do so naively we get quadratic
162 behaviour as things float out.
164 To see why it's important to do it after, consider this (real) example:
178 a -- Can't inline a this round, cos it appears twice
182 Each of the ==> steps is a round of simplification. We'd save a
183 whole round if we float first. This can cascade. Consider
188 let f = let d1 = ..d.. in \y -> e
192 in \x -> ...(\y ->e)...
194 Only in this second round can the \y be applied, and it
195 might do the same again.
199 simplExpr :: CoreExpr -> SimplM CoreExpr
200 simplExpr expr = getSubst `thenSmpl` \ subst ->
201 simplExprC expr (Stop (substTy subst (exprType expr)))
202 -- The type in the Stop continuation is usually not used
203 -- It's only needed when discarding continuations after finding
204 -- a function that returns bottom.
205 -- Hence the lazy substitution
207 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
208 -- Simplify an expression, given a continuation
210 simplExprC expr cont = simplExprF expr cont `thenSmpl` \ (floats, (_, body)) ->
211 returnSmpl (mkLets floats body)
213 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
214 -- Simplify an expression, returning floated binds
216 simplExprF (Var v) cont
219 simplExprF (Lit lit) (Select _ bndr alts se cont)
220 = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
222 simplExprF (Lit lit) cont
223 = rebuild (Lit lit) cont
225 simplExprF (App fun arg) cont
226 = getSubstEnv `thenSmpl` \ se ->
227 simplExprF fun (ApplyTo NoDup arg se cont)
229 simplExprF (Case scrut bndr alts) cont
230 = getSubstEnv `thenSmpl` \ subst_env ->
231 getSwitchChecker `thenSmpl` \ chkr ->
232 if not (switchIsOn chkr NoCaseOfCase) then
233 -- Simplify the scrutinee with a Select continuation
234 simplExprF scrut (Select NoDup bndr alts subst_env cont)
237 -- If case-of-case is off, simply simplify the case expression
238 -- in a vanilla Stop context, and rebuild the result around it
239 simplExprC scrut (Select NoDup bndr alts subst_env
240 (Stop (contResultType cont))) `thenSmpl` \ case_expr' ->
241 rebuild case_expr' cont
244 simplExprF (Let (Rec pairs) body) cont
245 = simplIds (map fst pairs) $ \ bndrs' ->
246 -- NB: bndrs' don't have unfoldings or spec-envs
247 -- We add them as we go down, using simplPrags
249 simplRecBind False pairs bndrs' (simplExprF body cont)
251 simplExprF expr@(Lam _ _) cont = simplLam expr cont
253 simplExprF (Type ty) cont
254 = ASSERT( case cont of { Stop _ -> True; ArgOf _ _ _ -> True; other -> False } )
255 simplType ty `thenSmpl` \ ty' ->
256 rebuild (Type ty') cont
258 -- Comments about the Coerce case
259 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
260 -- It's worth checking for a coerce in the continuation,
261 -- in case we can cancel them. For example, in the initial form of a worker
262 -- we may find (coerce T (coerce S (\x.e))) y
263 -- and we'd like it to simplify to e[y/x] in one round of simplification
265 simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
266 = simplType from `thenSmpl` \ from' ->
267 if outer_to == from' then
268 -- The coerces cancel out
271 -- They don't cancel, but the inner one is redundant
272 simplExprF e (CoerceIt outer_to cont)
274 simplExprF (Note (Coerce to from) e) cont
275 = simplType to `thenSmpl` \ to' ->
276 simplExprF e (CoerceIt to' cont)
278 -- hack: we only distinguish subsumed cost centre stacks for the purposes of
279 -- inlining. All other CCCSs are mapped to currentCCS.
280 simplExprF (Note (SCC cc) e) cont
281 = setEnclosingCC currentCCS $
282 simplExpr e `thenSmpl` \ e ->
283 rebuild (mkSCC cc e) cont
285 simplExprF (Note InlineCall e) cont
286 = simplExprF e (InlinePlease cont)
288 -- Comments about the InlineMe case
289 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 -- Don't inline in the RHS of something that has an
291 -- inline pragma. But be careful that the InScopeEnv that
292 -- we return does still have inlinings on!
294 -- It really is important to switch off inlinings. This function
295 -- may be inlinined in other modules, so we don't want to remove
296 -- (by inlining) calls to functions that have specialisations, or
297 -- that may have transformation rules in an importing scope.
298 -- E.g. {-# INLINE f #-}
300 -- and suppose that g is strict *and* has specialisations.
301 -- If we inline g's wrapper, we deny f the chance of getting
302 -- the specialised version of g when f is inlined at some call site
303 -- (perhaps in some other module).
305 simplExprF (Note InlineMe e) cont
307 Stop _ -> -- Totally boring continuation
308 -- Don't inline inside an INLINE expression
309 switchOffInlining (simplExpr e) `thenSmpl` \ e' ->
310 rebuild (mkInlineMe e') cont
312 other -> -- Dissolve the InlineMe note if there's
313 -- an interesting context of any kind to combine with
314 -- (even a type application -- anything except Stop)
317 -- A non-recursive let is dealt with by simplBeta
318 simplExprF (Let (NonRec bndr rhs) body) cont
319 = getSubstEnv `thenSmpl` \ se ->
320 simplBeta bndr rhs se (contResultType cont) $
325 ---------------------------------
331 zap_it = mkLamBndrZapper fun cont
332 cont_ty = contResultType cont
334 -- Type-beta reduction
335 go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
336 = ASSERT( isTyVar bndr )
337 tick (BetaReduction bndr) `thenSmpl_`
338 simplTyArg ty_arg arg_se `thenSmpl` \ ty_arg' ->
339 extendSubst bndr (DoneTy ty_arg')
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 ---------------------------------
393 simplType :: InType -> SimplM OutType
395 = getSubst `thenSmpl` \ subst ->
397 new_ty = substTy subst ty
404 %************************************************************************
408 %************************************************************************
410 @simplBeta@ is used for non-recursive lets in expressions,
411 as well as true beta reduction.
413 Very similar to @simplLazyBind@, but not quite the same.
416 simplBeta :: InId -- Binder
417 -> InExpr -> SubstEnv -- Arg, with its subst-env
418 -> OutType -- Type of thing computed by the context
419 -> SimplM OutExprStuff -- The body
420 -> SimplM OutExprStuff
422 simplBeta bndr rhs rhs_se cont_ty thing_inside
424 = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
427 simplBeta bndr rhs rhs_se cont_ty thing_inside
428 | preInlineUnconditionally False {- not black listed -} bndr
429 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
430 extendSubst bndr (ContEx rhs_se rhs) thing_inside
433 = -- Simplify the RHS
434 simplBinder bndr $ \ bndr' ->
435 simplValArg (idType bndr') (idDemandInfo bndr)
436 rhs rhs_se cont_ty $ \ rhs' ->
438 -- Now complete the binding and simplify the body
439 if needsCaseBinding (idType bndr') rhs' then
440 addCaseBind bndr' rhs' thing_inside
442 completeBinding bndr bndr' False False rhs' thing_inside
447 simplTyArg :: InType -> SubstEnv -> SimplM OutType
449 = getInScope `thenSmpl` \ in_scope ->
451 ty_arg' = substTy (mkSubst in_scope se) ty_arg
453 seqType ty_arg' `seq`
456 simplValArg :: OutType -- Type of arg
457 -> Demand -- Demand on the argument
458 -> InExpr -> SubstEnv
459 -> OutType -- Type of thing computed by the context
460 -> (OutExpr -> SimplM OutExprStuff)
461 -> SimplM OutExprStuff
463 simplValArg arg_ty demand arg arg_se cont_ty thing_inside
465 isUnLiftedType arg_ty ||
466 (opt_DictsStrict && isDictTy arg_ty && isDataType arg_ty)
467 -- Return true only for dictionary types where the dictionary
468 -- has more than one component (else we risk poking on the component
469 -- of a newtype dictionary)
470 = transformRhs arg `thenSmpl` \ t_arg ->
471 getEnv `thenSmpl` \ env ->
473 simplExprF t_arg (ArgOf NoDup cont_ty $ \ rhs' ->
474 setAllExceptInScope env $
475 etaFirst thing_inside rhs')
478 = simplRhs False {- Not top level -}
479 True {- OK to float unboxed -}
483 -- Do eta-reduction on the simplified RHS, if eta reduction is on
484 -- NB: etaFirst only eta-reduces if that results in something trivial
485 etaFirst | opt_SimplDoEtaReduction = \ thing_inside rhs -> thing_inside (etaCoreExprToTrivial rhs)
486 | otherwise = \ thing_inside rhs -> thing_inside rhs
488 -- Try for eta reduction, but *only* if we get all
489 -- the way to an exprIsTrivial expression. We don't want to remove
490 -- extra lambdas unless we are going to avoid allocating this thing altogether
491 etaCoreExprToTrivial rhs | exprIsTrivial rhs' = rhs'
494 rhs' = etaReduceExpr rhs
499 - deals only with Ids, not TyVars
500 - take an already-simplified RHS
502 It does *not* attempt to do let-to-case. Why? Because they are used for
505 (when let-to-case is impossible)
507 - many situations where the "rhs" is known to be a WHNF
508 (so let-to-case is inappropriate).
511 completeBinding :: InId -- Binder
512 -> OutId -- New binder
513 -> Bool -- True <=> top level
514 -> Bool -- True <=> black-listed; don't inline
515 -> OutExpr -- Simplified RHS
516 -> SimplM (OutStuff a) -- Thing inside
517 -> SimplM (OutStuff a)
519 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
520 | (case occ_info of -- This happens; for example, the case_bndr during case of
521 IAmDead -> True -- known constructor: case (a,b) of x { (p,q) -> ... }
522 other -> False) -- Here x isn't mentioned in the RHS, so we don't want to
523 -- create the (dead) let-binding let x = (a,b) in ...
526 | postInlineUnconditionally black_listed occ_info old_bndr new_rhs
527 -- Maybe we don't need a let-binding! Maybe we can just
528 -- inline it right away. Unlike the preInlineUnconditionally case
529 -- we are allowed to look at the RHS.
531 -- NB: a loop breaker never has postInlineUnconditionally True
532 -- and non-loop-breakers only have *forward* references
533 -- Hence, it's safe to discard the binding
535 -- NB: You might think that postInlineUnconditionally is an optimisation,
537 -- let x = f Bool in (x, y)
538 -- then because of the constructor, x will not be *inlined* in the pair,
539 -- so the trivial binding will stay. But in this postInlineUnconditionally
540 -- gag we use the *substitution* to substitute (f Bool) for x, and that *will*
542 = tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
543 extendSubst old_bndr (DoneEx new_rhs)
547 = getSubst `thenSmpl` \ subst ->
549 -- We make new IdInfo for the new binder by starting from the old binder,
550 -- doing appropriate substitutions.
551 -- Then we add arity and unfolding info to get the new binder
552 old_info = idInfo old_bndr
553 new_bndr_info = substIdInfo subst old_info (idInfo new_bndr)
554 `setArityInfo` ArityAtLeast (exprArity new_rhs)
556 -- Add the unfolding *only* for non-loop-breakers
557 -- Making loop breakers not have an unfolding at all
558 -- means that we can avoid tests in exprIsConApp, for example.
559 -- This is important: if exprIsConApp says 'yes' for a recursive
560 -- thing we can get into an infinite loop
561 info_w_unf | isLoopBreaker (occInfo old_info) = new_bndr_info
562 | otherwise = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
564 final_id = new_bndr `setIdInfo` info_w_unf
566 -- These seqs forces the Id, and hence its IdInfo,
567 -- and hence any inner substitutions
569 addLetBind final_id new_rhs $
570 modifyInScope new_bndr final_id thing_inside
573 occ_info = idOccInfo old_bndr
577 %************************************************************************
579 \subsection{simplLazyBind}
581 %************************************************************************
583 simplLazyBind basically just simplifies the RHS of a let(rec).
584 It does two important optimisations though:
586 * It floats let(rec)s out of the RHS, even if they
587 are hidden by big lambdas
589 * It does eta expansion
592 simplLazyBind :: Bool -- True <=> top level
595 -> SimplM (OutStuff a) -- The body of the binding
596 -> SimplM (OutStuff a)
597 -- When called, the subst env is correct for the entire let-binding
598 -- and hence right for the RHS.
599 -- Also the binder has already been simplified, and hence is in scope
601 simplLazyBind top_lvl bndr bndr' rhs thing_inside
602 = getBlackList `thenSmpl` \ black_list_fn ->
604 black_listed = black_list_fn bndr
607 if preInlineUnconditionally black_listed bndr then
608 -- Inline unconditionally
609 tick (PreInlineUnconditionally bndr) `thenSmpl_`
610 getSubstEnv `thenSmpl` \ rhs_se ->
611 (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
615 getSubstEnv `thenSmpl` \ rhs_se ->
616 simplRhs top_lvl False {- Not ok to float unboxed -}
618 rhs rhs_se $ \ rhs' ->
620 -- Now compete the binding and simplify the body
621 completeBinding bndr bndr' top_lvl black_listed rhs' thing_inside
627 simplRhs :: Bool -- True <=> Top level
628 -> Bool -- True <=> OK to float unboxed (speculative) bindings
629 -> OutType -> InExpr -> SubstEnv
630 -> (OutExpr -> SimplM (OutStuff a))
631 -> SimplM (OutStuff a)
632 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
633 = -- Swizzle the inner lets past the big lambda (if any)
634 -- and try eta expansion
635 transformRhs rhs `thenSmpl` \ t_rhs ->
638 setSubstEnv rhs_se (simplExprF t_rhs (Stop rhs_ty)) `thenSmpl` \ (floats, (in_scope', rhs')) ->
640 -- Float lets out of RHS
642 (floats_out, rhs'') | float_ubx = (floats, rhs')
643 | otherwise = splitFloats floats rhs'
645 if (top_lvl || wantToExpose 0 rhs') && -- Float lets if (a) we're at the top level
646 not (null floats_out) -- or (b) the resulting RHS is one we'd like to expose
648 tickLetFloat floats_out `thenSmpl_`
651 -- There's a subtlety here. There may be a binding (x* = e) in the
652 -- floats, where the '*' means 'will be demanded'. So is it safe
653 -- to float it out? Answer no, but it won't matter because
654 -- we only float if arg' is a WHNF,
655 -- and so there can't be any 'will be demanded' bindings in the floats.
657 WARN( any demanded_float floats_out, ppr floats_out )
658 addLetBinds floats_out $
659 setInScope in_scope' $
660 etaFirst thing_inside rhs''
661 -- in_scope' may be excessive, but that's OK;
662 -- it's a superset of what's in scope
664 -- Don't do the float
665 etaFirst thing_inside (mkLets floats rhs')
667 -- In a let-from-let float, we just tick once, arbitrarily
668 -- choosing the first floated binder to identify it
669 tickLetFloat (NonRec b r : fs) = tick (LetFloatFromLet b)
670 tickLetFloat (Rec ((b,r):prs) : fs) = tick (LetFloatFromLet b)
672 demanded_float (NonRec b r) = isStrict (idDemandInfo b) && not (isUnLiftedType (idType b))
673 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
674 demanded_float (Rec _) = False
676 -- Don't float any unlifted bindings out, because the context
677 -- is either a Rec group, or the top level, neither of which
678 -- can tolerate them.
679 splitFloats floats rhs
683 go (f:fs) | must_stay f = ([], mkLets (f:fs) rhs)
684 | otherwise = case go fs of
685 (out, rhs') -> (f:out, rhs')
687 must_stay (Rec prs) = False -- No unlifted bindings in here
688 must_stay (NonRec b r) = isUnLiftedType (idType b)
690 wantToExpose :: Int -> CoreExpr -> Bool
691 -- True for expressions that we'd like to expose at the
692 -- top level of an RHS. This includes partial applications
693 -- even if the args aren't cheap; the next pass will let-bind the
694 -- args and eta expand the partial application. So exprIsCheap won't do.
695 -- Here's the motivating example:
696 -- z = letrec g = \x y -> ...g... in g E
697 -- Even though E is a redex we'd like to float the letrec to give
698 -- g = \x y -> ...g...
700 -- Now the next use of SimplUtils.tryEtaExpansion will give
701 -- g = \x y -> ...g...
702 -- z = let v = E in \w -> g v w
703 -- And now we'll float the v to give
704 -- g = \x y -> ...g...
707 -- Which is what we want; chances are z will be inlined now.
709 -- This defn isn't quite like
710 -- exprIsCheap (it ignores non-cheap args)
711 -- exprIsValue (may not say True for a lone variable)
712 -- which is slightly weird
713 wantToExpose n (Var v) = idAppIsCheap v n
714 wantToExpose n (Lit l) = True
715 wantToExpose n (Lam _ e) = True
716 wantToExpose n (Note _ e) = wantToExpose n e
717 wantToExpose n (App f (Type _)) = wantToExpose n f
718 wantToExpose n (App f a) = wantToExpose (n+1) f
719 wantToExpose n other = False -- There won't be any lets
724 %************************************************************************
726 \subsection{Variables}
728 %************************************************************************
732 = getSubst `thenSmpl` \ subst ->
733 case lookupIdSubst subst var of
734 DoneEx e -> zapSubstEnv (simplExprF e cont)
735 ContEx env1 e -> setSubstEnv env1 (simplExprF e cont)
736 DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
737 text "simplVar:" <+> ppr var )
738 zapSubstEnv (completeCall var1 occ cont)
739 -- The template is already simplified, so don't re-substitute.
740 -- This is VITAL. Consider
742 -- let y = \z -> ...x... in
744 -- We'll clone the inner \x, adding x->x' in the id_subst
745 -- Then when we inline y, we must *not* replace x by x' in
746 -- the inlined copy!!
748 ---------------------------------------------------------
749 -- Dealing with a call
751 completeCall var occ cont
752 = getBlackList `thenSmpl` \ black_list_fn ->
753 getInScope `thenSmpl` \ in_scope ->
754 getSwitchChecker `thenSmpl` \ chkr ->
756 dont_use_rules = switchIsOn chkr DontApplyRules
757 no_case_of_case = switchIsOn chkr NoCaseOfCase
758 black_listed = black_list_fn var
760 (arg_infos, interesting_cont, inline_call) = analyseCont in_scope cont
761 discard_inline_cont | inline_call = discardInline cont
764 maybe_inline = callSiteInline black_listed inline_call occ
765 var arg_infos interesting_cont
767 -- First, look for an inlining
769 case maybe_inline of {
770 Just unfolding -- There is an inlining!
771 -> tick (UnfoldingDone var) `thenSmpl_`
772 simplExprF unfolding discard_inline_cont
775 Nothing -> -- No inlining!
777 -- Next, look for rules or specialisations that match
779 -- It's important to simplify the args first, because the rule-matcher
780 -- doesn't do substitution as it goes. We don't want to use subst_args
781 -- (defined in the 'where') because that throws away useful occurrence info,
782 -- and perhaps-very-important specialisations.
784 -- Some functions have specialisations *and* are strict; in this case,
785 -- we don't want to inline the wrapper of the non-specialised thing; better
786 -- to call the specialised thing instead.
787 -- But the black-listing mechanism means that inlining of the wrapper
788 -- won't occur for things that have specialisations till a later phase, so
789 -- it's ok to try for inlining first.
791 prepareArgs no_case_of_case var cont $ \ args' cont' ->
793 maybe_rule | dont_use_rules = Nothing
794 | otherwise = lookupRule in_scope var args'
797 Just (rule_name, rule_rhs) ->
798 tick (RuleFired rule_name) `thenSmpl_`
799 simplExprF rule_rhs cont' ;
801 Nothing -> -- No rules
804 rebuild (mkApps (Var var) args') cont'
810 ---------------------------------------------------------
811 -- Preparing arguments for a call
813 prepareArgs :: Bool -- True if the no-case-of-case switch is on
814 -> OutId -> SimplCont
815 -> ([OutExpr] -> SimplCont -> SimplM OutExprStuff)
816 -> SimplM OutExprStuff
817 prepareArgs no_case_of_case fun orig_cont thing_inside
818 = go [] demands orig_fun_ty orig_cont
820 orig_fun_ty = idType fun
821 is_data_con = isDataConId fun
823 (demands, result_bot)
824 | no_case_of_case = ([], False) -- Ignore strictness info if the no-case-of-case
825 -- flag is on. Strictness changes evaluation order
826 -- and that can change full laziness
828 = case idStrictness fun of
829 StrictnessInfo demands result_bot
830 | not (demands `lengthExceeds` countValArgs orig_cont)
831 -> -- Enough args, use the strictness given.
832 -- For bottoming functions we used to pretend that the arg
833 -- is lazy, so that we don't treat the arg as an
834 -- interesting context. This avoids substituting
835 -- top-level bindings for (say) strings into
836 -- calls to error. But now we are more careful about
837 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
838 (demands, result_bot)
840 other -> ([], False) -- Not enough args, or no strictness
842 -- Main game plan: loop through the arguments, simplifying
843 -- each of them in turn. We carry with us a list of demands,
844 -- and the type of the function-applied-to-earlier-args
846 -- We've run out of demands, and the result is now bottom
848 -- * case (error "hello") of { ... }
849 -- * (error "Hello") arg
850 -- * f (error "Hello") where f is strict
852 go acc [] fun_ty cont
854 = tick_case_of_error cont `thenSmpl_`
855 thing_inside (reverse acc) (discardCont cont)
858 go acc ds fun_ty (ApplyTo _ arg@(Type ty_arg) se cont)
859 = simplTyArg ty_arg se `thenSmpl` \ new_ty_arg ->
860 go (Type new_ty_arg : acc) ds (applyTy fun_ty new_ty_arg) cont
863 go acc ds fun_ty (ApplyTo _ val_arg se cont)
864 | not is_data_con -- Function isn't a data constructor
865 = simplValArg arg_ty dem val_arg se (contResultType cont) $ \ new_arg ->
866 go (new_arg : acc) ds' res_ty cont
868 | exprIsTrivial val_arg -- Function is a data contstructor, arg is trivial
869 = getInScope `thenSmpl` \ in_scope ->
871 new_arg = substExpr (mkSubst in_scope se) val_arg
872 -- Simplify the RHS with inlining switched off, so that
873 -- only absolutely essential things will happen.
874 -- If we don't do this, consider:
875 -- let x = +# p q in C {x}
876 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
877 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
879 -- It's important that the substitution *does* deal with case-binder synonyms:
880 -- case x of y { True -> (x,1) }
881 -- Here we must be sure to substitute y for x when simplifying the args of the pair,
882 -- to increase the chances of being able to inline x. The substituter will do
883 -- that because the x->y mapping is held in the in-scope set.
885 -- It's not always the case that the new arg will be trivial
887 -- where, in one pass, f gets substituted by a constructor,
888 -- but x gets substituted by an expression (assume this is the
889 -- unique occurrence of x). It doesn't really matter -- it'll get
890 -- fixed up next pass. And it happens for dictionary construction,
891 -- which mentions the wrapper constructor to start with.
893 go (new_arg : acc) ds' res_ty cont
896 = simplValArg arg_ty dem val_arg se (contResultType cont) $ \ new_arg ->
897 -- A data constructor whose argument is now non-trivial;
898 -- so let/case bind it.
899 newId SLIT("a") arg_ty $ \ arg_id ->
900 addNonRecBind arg_id new_arg $
901 go (Var arg_id : acc) ds' res_ty cont
904 (arg_ty, res_ty) = splitFunTy fun_ty
905 (dem, ds') = case ds of
909 -- We're run out of arguments and the result ain't bottom
910 go acc ds fun_ty cont = thing_inside (reverse acc) cont
912 -- Boring: we must only record a tick if there was an interesting
913 -- continuation to discard. If not, we tick forever.
914 tick_case_of_error (Stop _) = returnSmpl ()
915 tick_case_of_error (CoerceIt _ (Stop _)) = returnSmpl ()
916 tick_case_of_error other = tick BottomFound
920 %************************************************************************
922 \subsection{Decisions about inlining}
924 %************************************************************************
926 NB: At one time I tried not pre/post-inlining top-level things,
927 even if they occur exactly once. Reason:
928 (a) some might appear as a function argument, so we simply
929 replace static allocation with dynamic allocation:
935 (b) some top level things might be black listed
937 HOWEVER, I found that some useful foldr/build fusion was lost (most
938 notably in spectral/hartel/parstof) because the foldr didn't see the build.
940 Doing the dynamic allocation isn't a big deal, in fact, but losing the
944 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
945 -- Examines a bndr to see if it is used just once in a
946 -- completely safe way, so that it is safe to discard the binding
947 -- inline its RHS at the (unique) usage site, REGARDLESS of how
948 -- big the RHS might be. If this is the case we don't simplify
949 -- the RHS first, but just inline it un-simplified.
951 -- This is much better than first simplifying a perhaps-huge RHS
952 -- and then inlining and re-simplifying it.
954 -- NB: we don't even look at the RHS to see if it's trivial
957 -- where x is used many times, but this is the unique occurrence
958 -- of y. We should NOT inline x at all its uses, because then
959 -- we'd do the same for y -- aargh! So we must base this
960 -- pre-rhs-simplification decision solely on x's occurrences, not
963 -- Evne RHSs labelled InlineMe aren't caught here, because
964 -- there might be no benefit from inlining at the call site.
966 preInlineUnconditionally black_listed bndr
967 | black_listed || opt_SimplNoPreInlining = False
968 | otherwise = case idOccInfo bndr of
969 OneOcc in_lam once -> not in_lam && once
970 -- Not inside a lambda, one occurrence ==> safe!
974 postInlineUnconditionally :: Bool -- Black listed
976 -> InId -> OutExpr -> Bool
977 -- Examines a (bndr = rhs) binding, AFTER the rhs has been simplified
978 -- It returns True if it's ok to discard the binding and inline the
979 -- RHS at every use site.
981 -- NOTE: This isn't our last opportunity to inline.
982 -- We're at the binding site right now, and
983 -- we'll get another opportunity when we get to the ocurrence(s)
985 postInlineUnconditionally black_listed occ_info bndr rhs
986 | isExportedId bndr = False -- Don't inline these, ever
987 | black_listed = False
988 | isLoopBreaker occ_info = False
989 | otherwise = exprIsTrivial rhs -- Duplicating is free
990 -- Don't inline even WHNFs inside lambdas; doing so may
991 -- simply increase allocation when the function is called
992 -- This isn't the last chance; see NOTE above.
994 -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
995 -- Why? Because we don't even want to inline them into the
996 -- RHS of constructor arguments. See NOTE above
998 -- NB: Even NOINLINEis ignored here: if the rhs is trivial
999 -- it's best to inline it anyway. We often get a=E; b=a
1000 -- from desugaring, with both a and b marked NOINLINE.
1005 %************************************************************************
1007 \subsection{The main rebuilder}
1009 %************************************************************************
1012 -------------------------------------------------------------------
1013 -- Finish rebuilding
1015 = getInScope `thenSmpl` \ in_scope ->
1016 returnSmpl ([], (in_scope, expr))
1018 ---------------------------------------------------------
1019 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1021 -- Stop continuation
1022 rebuild expr (Stop _) = rebuild_done expr
1024 -- ArgOf continuation
1025 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1027 -- ApplyTo continuation
1028 rebuild expr cont@(ApplyTo _ arg se cont')
1029 = setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1030 rebuild (App expr arg') cont'
1032 -- Coerce continuation
1033 rebuild expr (CoerceIt to_ty cont)
1034 = rebuild (mkCoerce to_ty (exprType expr) expr) cont
1036 -- Inline continuation
1037 rebuild expr (InlinePlease cont)
1038 = rebuild (Note InlineCall expr) cont
1040 rebuild scrut (Select _ bndr alts se cont)
1041 = rebuild_case scrut bndr alts se cont
1044 Case elimination [see the code above]
1046 Start with a simple situation:
1048 case x# of ===> e[x#/y#]
1051 (when x#, y# are of primitive type, of course). We can't (in general)
1052 do this for algebraic cases, because we might turn bottom into
1055 Actually, we generalise this idea to look for a case where we're
1056 scrutinising a variable, and we know that only the default case can
1061 other -> ...(case x of
1065 Here the inner case can be eliminated. This really only shows up in
1066 eliminating error-checking code.
1068 We also make sure that we deal with this very common case:
1073 Here we are using the case as a strict let; if x is used only once
1074 then we want to inline it. We have to be careful that this doesn't
1075 make the program terminate when it would have diverged before, so we
1077 - x is used strictly, or
1078 - e is already evaluated (it may so if e is a variable)
1080 Lastly, we generalise the transformation to handle this:
1086 We only do this for very cheaply compared r's (constructors, literals
1087 and variables). If pedantic bottoms is on, we only do it when the
1088 scrutinee is a PrimOp which can't fail.
1090 We do it *here*, looking at un-simplified alternatives, because we
1091 have to check that r doesn't mention the variables bound by the
1092 pattern in each alternative, so the binder-info is rather useful.
1094 So the case-elimination algorithm is:
1096 1. Eliminate alternatives which can't match
1098 2. Check whether all the remaining alternatives
1099 (a) do not mention in their rhs any of the variables bound in their pattern
1100 and (b) have equal rhss
1102 3. Check we can safely ditch the case:
1103 * PedanticBottoms is off,
1104 or * the scrutinee is an already-evaluated variable
1105 or * the scrutinee is a primop which is ok for speculation
1106 -- ie we want to preserve divide-by-zero errors, and
1107 -- calls to error itself!
1109 or * [Prim cases] the scrutinee is a primitive variable
1111 or * [Alg cases] the scrutinee is a variable and
1112 either * the rhs is the same variable
1113 (eg case x of C a b -> x ===> x)
1114 or * there is only one alternative, the default alternative,
1115 and the binder is used strictly in its scope.
1116 [NB this is helped by the "use default binder where
1117 possible" transformation; see below.]
1120 If so, then we can replace the case with one of the rhss.
1123 Blob of helper functions for the "case-of-something-else" situation.
1126 ---------------------------------------------------------
1127 -- Eliminate the case if possible
1129 rebuild_case scrut bndr alts se cont
1130 | maybeToBool maybe_con_app
1131 = knownCon scrut (DataAlt con) args bndr alts se cont
1133 | canEliminateCase scrut bndr alts
1134 = tick (CaseElim bndr) `thenSmpl_` (
1136 simplBinder bndr $ \ bndr' ->
1137 -- Remember to bind the case binder!
1138 completeBinding bndr bndr' False False scrut $
1139 simplExprF (head (rhssOfAlts alts)) cont)
1142 = complete_case scrut bndr alts se cont
1145 maybe_con_app = exprIsConApp_maybe scrut
1146 Just (con, args) = maybe_con_app
1148 -- See if we can get rid of the case altogether
1149 -- See the extensive notes on case-elimination above
1150 canEliminateCase scrut bndr alts
1151 = -- Check that the RHSs are all the same, and
1152 -- don't use the binders in the alternatives
1153 -- This test succeeds rapidly in the common case of
1154 -- a single DEFAULT alternative
1155 all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1157 -- Check that the scrutinee can be let-bound instead of case-bound
1158 && ( exprOkForSpeculation scrut
1159 -- OK not to evaluate it
1160 -- This includes things like (==# a# b#)::Bool
1161 -- so that we simplify
1162 -- case ==# a# b# of { True -> x; False -> x }
1165 -- This particular example shows up in default methods for
1166 -- comparision operations (e.g. in (>=) for Int.Int32)
1167 || exprIsValue scrut -- It's already evaluated
1168 || var_demanded_later scrut -- It'll be demanded later
1170 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1171 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1172 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1173 -- its argument: case x of { y -> dataToTag# y }
1174 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1175 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1180 (rhs1:other_rhss) = rhssOfAlts alts
1181 binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1183 var_demanded_later (Var v) = isStrict (idDemandInfo bndr) -- It's going to be evaluated later
1184 var_demanded_later other = False
1187 ---------------------------------------------------------
1188 -- Case of something else
1190 complete_case scrut case_bndr alts se cont
1191 = -- Prepare case alternatives
1192 prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1193 impossible_cons alts `thenSmpl` \ better_alts ->
1195 -- Set the new subst-env in place (before dealing with the case binder)
1198 -- Deal with the case binder, and prepare the continuation;
1199 -- The new subst_env is in place
1200 prepareCaseCont better_alts cont $ \ cont' ->
1203 -- Deal with variable scrutinee
1205 getSwitchChecker `thenSmpl` \ chkr ->
1206 simplCaseBinder (switchIsOn chkr NoCaseOfCase)
1207 scrut case_bndr $ \ case_bndr' zap_occ_info ->
1209 -- Deal with the case alternatives
1210 simplAlts zap_occ_info impossible_cons
1211 case_bndr' better_alts cont' `thenSmpl` \ alts' ->
1213 mkCase scrut case_bndr' alts'
1214 ) `thenSmpl` \ case_expr ->
1216 -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1217 -- over the rebuild_done; rebuild_done returns the in-scope set, and
1218 -- that should not include these chaps!
1219 rebuild_done case_expr
1221 impossible_cons = case scrut of
1222 Var v -> otherCons (idUnfolding v)
1226 knownCon :: OutExpr -> AltCon -> [OutExpr]
1227 -> InId -> [InAlt] -> SubstEnv -> SimplCont
1228 -> SimplM OutExprStuff
1230 knownCon expr con args bndr alts se cont
1231 = tick (KnownBranch bndr) `thenSmpl_`
1233 simplBinder bndr $ \ bndr' ->
1234 completeBinding bndr bndr' False False expr $
1235 -- Don't use completeBeta here. The expr might be
1236 -- an unboxed literal, like 3, or a variable
1237 -- whose unfolding is an unboxed literal... and
1238 -- completeBeta will just construct another case
1240 case findAlt con alts of
1241 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1244 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1247 (DataAlt dc, bs, rhs) -> ASSERT( length bs == length real_args )
1248 extendSubstList bs (map mk real_args) $
1251 real_args = drop (dataConNumInstArgs dc) args
1252 mk (Type ty) = DoneTy ty
1253 mk other = DoneEx other
1258 prepareCaseCont :: [InAlt] -> SimplCont
1259 -> (SimplCont -> SimplM (OutStuff a))
1260 -> SimplM (OutStuff a)
1261 -- Polymorphic recursion here!
1263 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1264 prepareCaseCont alts cont thing_inside = simplType (coreAltsType alts) `thenSmpl` \ alts_ty ->
1265 mkDupableCont alts_ty cont thing_inside
1266 -- At one time I passed in the un-simplified type, and simplified
1267 -- it only if we needed to construct a join binder, but that
1268 -- didn't work because we have to decompse function types
1269 -- (using funResultTy) in mkDupableCont.
1272 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1273 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1274 way, there's a chance that v will now only be used once, and hence
1277 There is a time we *don't* want to do that, namely when
1278 -fno-case-of-case is on. This happens in the first simplifier pass,
1279 and enhances full laziness. Here's the bad case:
1280 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1281 If we eliminate the inner case, we trap it inside the I# v -> arm,
1282 which might prevent some full laziness happening. I've seen this
1283 in action in spectral/cichelli/Prog.hs:
1284 [(m,n) | m <- [1..max], n <- [1..max]]
1285 Hence the no_case_of_case argument
1288 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1289 in the case binder, because the case-binder now effectively occurs
1290 whenever v does. AND we have to do the same for the pattern-bound
1293 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1295 Here, b and p are dead. But when we move the argment inside the first
1296 case RHS, and eliminate the second case, we get
1298 case x or { (a,b) -> a b }
1300 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1301 happened. Hence the zap_occ_info function returned by simplCaseBinder
1304 simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
1305 | not no_case_of_case
1306 = simplBinder (zap case_bndr) $ \ case_bndr' ->
1307 modifyInScope v case_bndr' $
1308 -- We could extend the substitution instead, but it would be
1309 -- a hack because then the substitution wouldn't be idempotent
1310 -- any more (v is an OutId). And this just just as well.
1311 thing_inside case_bndr' zap
1313 zap b = b `setIdOccInfo` NoOccInfo
1315 simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
1316 = simplBinder case_bndr $ \ case_bndr' ->
1317 thing_inside case_bndr' (\ bndr -> bndr) -- NoOp on bndr
1320 prepareCaseAlts does two things:
1322 1. Remove impossible alternatives
1324 2. If the DEFAULT alternative can match only one possible constructor,
1325 then make that constructor explicit.
1327 case e of x { DEFAULT -> rhs }
1329 case e of x { (a,b) -> rhs }
1330 where the type is a single constructor type. This gives better code
1331 when rhs also scrutinises x or e.
1334 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1336 = case (findDefault filtered_alts, missing_cons) of
1338 ((alts_no_deflt, Just rhs), [data_con]) -- Just one missing constructor!
1339 -> tick (FillInCaseDefault bndr) `thenSmpl_`
1341 (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1343 getUniquesSmpl (length ex_tyvars) `thenSmpl` \ tv_uniqs ->
1345 ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
1346 mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1347 arg_tys = dataConArgTys data_con
1348 (inst_tys ++ mkTyVarTys ex_tyvars')
1350 newIds SLIT("a") arg_tys $ \ bndrs ->
1351 returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1353 other -> returnSmpl filtered_alts
1355 -- Filter out alternatives that can't possibly match
1356 filtered_alts = case scrut_cons of
1358 other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1360 missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon,
1361 not (data_con `elem` handled_data_cons)]
1362 handled_data_cons = [data_con | DataAlt data_con <- scrut_cons] ++
1363 [data_con | (DataAlt data_con, _, _) <- filtered_alts]
1366 prepareCaseAlts _ _ scrut_cons alts
1367 = returnSmpl alts -- Functions
1370 ----------------------
1371 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1372 = mapSmpl simpl_alt alts
1374 inst_tys' = case splitTyConApp_maybe (idType case_bndr') of
1375 Just (tycon, inst_tys) -> inst_tys
1377 -- handled_cons is all the constructors that are dealt
1378 -- with, either by being impossible, or by there being an alternative
1379 handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1381 simpl_alt (DEFAULT, _, rhs)
1382 = -- In the default case we record the constructors that the
1383 -- case-binder *can't* be.
1384 -- We take advantage of any OtherCon info in the case scrutinee
1385 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons) $
1386 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1387 returnSmpl (DEFAULT, [], rhs')
1389 simpl_alt (con, vs, rhs)
1390 = -- Deal with the pattern-bound variables
1391 -- Mark the ones that are in ! positions in the data constructor
1392 -- as certainly-evaluated.
1393 -- NB: it happens that simplBinders does *not* erase the OtherCon
1394 -- form of unfolding, so it's ok to add this info before
1395 -- doing simplBinders
1396 simplBinders (add_evals con vs) $ \ vs' ->
1398 -- Bind the case-binder to (con args)
1400 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1402 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding) $
1403 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1404 returnSmpl (con, vs', rhs')
1407 -- add_evals records the evaluated-ness of the bound variables of
1408 -- a case pattern. This is *important*. Consider
1409 -- data T = T !Int !Int
1411 -- case x of { T a b -> T (a+1) b }
1413 -- We really must record that b is already evaluated so that we don't
1414 -- go and re-evaluate it when constructing the result.
1416 add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1417 add_evals other_con vs = vs
1419 cat_evals [] [] = []
1420 cat_evals (v:vs) (str:strs)
1421 | isTyVar v = v : cat_evals vs (str:strs)
1422 | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1423 | otherwise = v' : cat_evals vs strs
1429 %************************************************************************
1431 \subsection{Duplicating continuations}
1433 %************************************************************************
1436 mkDupableCont :: OutType -- Type of the thing to be given to the continuation
1438 -> (SimplCont -> SimplM (OutStuff a))
1439 -> SimplM (OutStuff a)
1440 mkDupableCont ty cont thing_inside
1441 | contIsDupable cont
1444 mkDupableCont _ (CoerceIt ty cont) thing_inside
1445 = mkDupableCont ty cont $ \ cont' ->
1446 thing_inside (CoerceIt ty cont')
1448 mkDupableCont ty (InlinePlease cont) thing_inside
1449 = mkDupableCont ty cont $ \ cont' ->
1450 thing_inside (InlinePlease cont')
1452 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1453 = -- Build the RHS of the join point
1454 newId SLIT("a") join_arg_ty ( \ arg_id ->
1455 cont_fn (Var arg_id) `thenSmpl` \ (binds, (_, rhs)) ->
1456 returnSmpl (Lam (setOneShotLambda arg_id) (mkLets binds rhs))
1457 ) `thenSmpl` \ join_rhs ->
1459 -- Build the join Id and continuation
1460 -- We give it a "$j" name just so that for later amusement
1461 -- we can identify any join points that don't end up as let-no-escapes
1462 newId SLIT("$j") (exprType join_rhs) $ \ join_id ->
1464 new_cont = ArgOf OkToDup cont_ty
1465 (\arg' -> rebuild_done (App (Var join_id) arg'))
1468 tick (CaseOfCase join_id) `thenSmpl_`
1469 -- Want to tick here so that we go round again,
1470 -- and maybe copy or inline the code;
1471 -- not strictly CaseOf Case
1472 addLetBind join_id join_rhs (thing_inside new_cont)
1474 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1475 = mkDupableCont (funResultTy ty) cont $ \ cont' ->
1476 setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1477 if exprIsDupable arg' then
1478 thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1480 newId SLIT("a") (exprType arg') $ \ bndr ->
1482 tick (CaseOfCase bndr) `thenSmpl_`
1483 -- Want to tick here so that we go round again,
1484 -- and maybe copy or inline the code;
1485 -- not strictly CaseOf Case
1487 addLetBind bndr arg' $
1488 -- But what if the arg should be case-bound? We can't use
1489 -- addNonRecBind here because its type is too specific.
1490 -- This has been this way for a long time, so I'll leave it,
1491 -- but I can't convince myself that it's right.
1493 thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1496 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1497 = tick (CaseOfCase case_bndr) `thenSmpl_`
1499 simplBinder case_bndr $ \ case_bndr' ->
1500 prepareCaseCont alts cont $ \ cont' ->
1501 mapAndUnzipSmpl (mkDupableAlt case_bndr case_bndr' cont') alts `thenSmpl` \ (alt_binds_s, alts') ->
1502 returnSmpl (concat alt_binds_s, alts')
1503 ) `thenSmpl` \ (alt_binds, alts') ->
1505 extendInScopes [b | NonRec b _ <- alt_binds] $
1507 -- NB that the new alternatives, alts', are still InAlts, using the original
1508 -- binders. That means we can keep the case_bndr intact. This is important
1509 -- because another case-of-case might strike, and so we want to keep the
1510 -- info that the case_bndr is dead (if it is, which is often the case).
1511 -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1512 -- case in I/O rich code. We aren't allowed a lambda bound
1513 -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1514 addLetBinds alt_binds $
1515 thing_inside (Select OkToDup case_bndr alts' se (Stop (contResultType cont)))
1517 mkDupableAlt :: InId -> OutId -> SimplCont -> InAlt -> SimplM (OutStuff InAlt)
1518 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs)
1519 = simplBinders bndrs $ \ bndrs' ->
1520 simplExprC rhs cont `thenSmpl` \ rhs' ->
1522 if (case cont of { Stop _ -> exprIsDupable rhs'; other -> False}) then
1523 -- It is worth checking for a small RHS because otherwise we
1524 -- get extra let bindings that may cause an extra iteration of the simplifier to
1525 -- inline back in place. Quite often the rhs is just a variable or constructor.
1526 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1527 -- iterations because the version with the let bindings looked big, and so wasn't
1528 -- inlined, but after the join points had been inlined it looked smaller, and so
1531 -- But since the continuation is absorbed into the rhs, we only do this
1532 -- for a Stop continuation.
1534 -- NB: we have to check the size of rhs', not rhs.
1535 -- Duplicating a small InAlt might invalidate occurrence information
1536 -- However, if it *is* dupable, we return the *un* simplified alternative,
1537 -- because otherwise we'd need to pair it up with an empty subst-env.
1538 -- (Remember we must zap the subst-env before re-simplifying something).
1539 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1540 returnSmpl ([], alt)
1544 rhs_ty' = exprType rhs'
1545 (used_bndrs, used_bndrs')
1546 = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr : bndrs)
1547 (case_bndr' : bndrs'),
1548 not (isDeadBinder bndr)]
1549 -- The new binders have lost their occurrence info,
1550 -- so we have to extract it from the old ones
1552 ( if null used_bndrs'
1553 -- If we try to lift a primitive-typed something out
1554 -- for let-binding-purposes, we will *caseify* it (!),
1555 -- with potentially-disastrous strictness results. So
1556 -- instead we turn it into a function: \v -> e
1557 -- where v::State# RealWorld#. The value passed to this function
1558 -- is realworld#, which generates (almost) no code.
1560 -- There's a slight infelicity here: we pass the overall
1561 -- case_bndr to all the join points if it's used in *any* RHS,
1562 -- because we don't know its usage in each RHS separately
1564 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1565 -- we make the join point into a function whenever used_bndrs'
1566 -- is empty. This makes the join-point more CPR friendly.
1567 -- Consider: let j = if .. then I# 3 else I# 4
1568 -- in case .. of { A -> j; B -> j; C -> ... }
1570 -- Now CPR should not w/w j because it's a thunk, so
1571 -- that means that the enclosing function can't w/w either,
1572 -- which is a lose. Here's the example that happened in practice:
1573 -- kgmod :: Int -> Int -> Int
1574 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1578 then newId SLIT("w") realWorldStatePrimTy $ \ rw_id ->
1579 returnSmpl ([rw_id], [Var realWorldPrimId])
1581 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1583 `thenSmpl` \ (final_bndrs', final_args) ->
1585 -- See comment about "$j" name above
1586 newId SLIT("$j") (foldr (mkFunTy . idType) rhs_ty' final_bndrs') $ \ join_bndr ->
1588 -- Notice that we make the lambdas into one-shot-lambdas. The
1589 -- join point is sure to be applied at most once, and doing so
1590 -- prevents the body of the join point being floated out by
1591 -- the full laziness pass
1592 returnSmpl ([NonRec join_bndr (mkLams (map setOneShotLambda final_bndrs') rhs')],
1593 (con, bndrs, mkApps (Var join_bndr) final_args))