2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
12 preInlineUnconditionally, postInlineUnconditionally,
13 activeInline, activeRule, inlineMode,
15 -- The continuation type
16 SimplCont(..), DupFlag(..), LetRhsFlag(..),
17 contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs,
18 countValArgs, countArgs,
19 mkBoringStop, mkLazyArgStop, mkRhsStop, contIsRhsOrArg,
20 interestingCallContext, interestingArgContext,
22 interestingArg, mkArgInfo
25 #include "HsVersions.h"
50 %************************************************************************
54 %************************************************************************
56 A SimplCont allows the simplifier to traverse the expression in a
57 zipper-like fashion. The SimplCont represents the rest of the expression,
58 "above" the point of interest.
60 You can also think of a SimplCont as an "evaluation context", using
61 that term in the way it is used for operational semantics. This is the
62 way I usually think of it, For example you'll often see a syntax for
63 evaluation context looking like
64 C ::= [] | C e | case C of alts | C `cast` co
65 That's the kind of thing we are doing here, and I use that syntax in
70 * A SimplCont describes a *strict* context (just like
71 evaluation contexts do). E.g. Just [] is not a SimplCont
73 * A SimplCont describes a context that *does not* bind
74 any variables. E.g. \x. [] is not a SimplCont
78 = Stop -- An empty context, or hole, []
79 OutType -- Type of the result
81 Bool -- True <=> There is something interesting about
82 -- the context, and hence the inliner
83 -- should be a bit keener (see interestingCallContext)
85 -- (a) This is the RHS of a thunk whose type suggests
86 -- that update-in-place would be possible
87 -- (b) This is an argument of a function that has RULES
88 -- Inlining the call might allow the rule to fire
90 | CoerceIt -- C `cast` co
91 OutCoercion -- The coercion simplified
96 InExpr SimplEnv -- The argument and its static env
99 | Select -- case C of alts
101 InId [InAlt] SimplEnv -- The case binder, alts, and subst-env
104 -- The two strict forms have no DupFlag, because we never duplicate them
105 | StrictBind -- (\x* \xs. e) C
106 InId [InBndr] -- let x* = [] in e
107 InExpr SimplEnv -- is a special case
111 OutExpr OutType -- e and its type
112 (Bool,[Bool]) -- Whether the function at the head of e has rules,
113 SimplCont -- plus strictness flags for further args
115 data LetRhsFlag = AnArg -- It's just an argument not a let RHS
116 | AnRhs -- It's the RHS of a let (so please float lets out of big lambdas)
118 instance Outputable LetRhsFlag where
119 ppr AnArg = ptext SLIT("arg")
120 ppr AnRhs = ptext SLIT("rhs")
122 instance Outputable SimplCont where
123 ppr (Stop ty is_rhs _) = ptext SLIT("Stop") <> brackets (ppr is_rhs) <+> ppr ty
124 ppr (ApplyTo dup arg se cont) = ((ptext SLIT("ApplyTo") <+> ppr dup <+> pprParendExpr arg) $$
125 nest 2 (pprSimplEnv se)) $$ ppr cont
126 ppr (StrictBind b _ _ _ cont) = (ptext SLIT("StrictBind") <+> ppr b) $$ ppr cont
127 ppr (StrictArg f _ _ cont) = (ptext SLIT("StrictArg") <+> ppr f) $$ ppr cont
128 ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$
129 (nest 4 (ppr alts $$ pprSimplEnv se)) $$ ppr cont
130 ppr (CoerceIt co cont) = (ptext SLIT("CoerceIt") <+> ppr co) $$ ppr cont
132 data DupFlag = OkToDup | NoDup
134 instance Outputable DupFlag where
135 ppr OkToDup = ptext SLIT("ok")
136 ppr NoDup = ptext SLIT("nodup")
141 mkBoringStop :: OutType -> SimplCont
142 mkBoringStop ty = Stop ty AnArg False
144 mkLazyArgStop :: OutType -> Bool -> SimplCont
145 mkLazyArgStop ty has_rules = Stop ty AnArg (canUpdateInPlace ty || has_rules)
147 mkRhsStop :: OutType -> SimplCont
148 mkRhsStop ty = Stop ty AnRhs (canUpdateInPlace ty)
150 contIsRhsOrArg (Stop _ _ _) = True
151 contIsRhsOrArg (StrictBind {}) = True
152 contIsRhsOrArg (StrictArg {}) = True
153 contIsRhsOrArg other = False
156 contIsDupable :: SimplCont -> Bool
157 contIsDupable (Stop _ _ _) = True
158 contIsDupable (ApplyTo OkToDup _ _ _) = True
159 contIsDupable (Select OkToDup _ _ _ _) = True
160 contIsDupable (CoerceIt _ cont) = contIsDupable cont
161 contIsDupable other = False
164 contIsTrivial :: SimplCont -> Bool
165 contIsTrivial (Stop _ _ _) = True
166 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
167 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
168 contIsTrivial other = False
171 contResultType :: SimplCont -> OutType
172 contResultType (Stop to_ty _ _) = to_ty
173 contResultType (StrictArg _ _ _ cont) = contResultType cont
174 contResultType (StrictBind _ _ _ _ cont) = contResultType cont
175 contResultType (ApplyTo _ _ _ cont) = contResultType cont
176 contResultType (CoerceIt _ cont) = contResultType cont
177 contResultType (Select _ _ _ _ cont) = contResultType cont
180 countValArgs :: SimplCont -> Int
181 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
182 countValArgs (ApplyTo _ val_arg se cont) = 1 + countValArgs cont
183 countValArgs other = 0
185 countArgs :: SimplCont -> Int
186 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
189 contArgs :: SimplCont -> ([OutExpr], SimplCont)
190 -- Uses substitution to turn each arg into an OutExpr
191 contArgs cont = go [] cont
193 go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
194 go args cont = (reverse args, cont)
196 dropArgs :: Int -> SimplCont -> SimplCont
197 dropArgs 0 cont = cont
198 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
199 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
204 interestingArg :: OutExpr -> Bool
205 -- An argument is interesting if it has *some* structure
206 -- We are here trying to avoid unfolding a function that
207 -- is applied only to variables that have no unfolding
208 -- (i.e. they are probably lambda bound): f x y z
209 -- There is little point in inlining f here.
210 interestingArg (Var v) = hasSomeUnfolding (idUnfolding v)
211 -- Was: isValueUnfolding (idUnfolding v')
212 -- But that seems over-pessimistic
214 -- This accounts for an argument like
215 -- () or [], which is definitely interesting
216 interestingArg (Type _) = False
217 interestingArg (App fn (Type _)) = interestingArg fn
218 interestingArg (Note _ a) = interestingArg a
220 -- Idea (from Sam B); I'm not sure if it's a good idea, so commented out for now
221 -- interestingArg expr | isUnLiftedType (exprType expr)
222 -- -- Unlifted args are only ever interesting if we know what they are
227 interestingArg other = True
228 -- Consider let x = 3 in f x
229 -- The substitution will contain (x -> ContEx 3), and we want to
230 -- to say that x is an interesting argument.
231 -- But consider also (\x. f x y) y
232 -- The substitution will contain (x -> ContEx y), and we want to say
233 -- that x is not interesting (assuming y has no unfolding)
237 Comment about interestingCallContext
238 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
239 We want to avoid inlining an expression where there can't possibly be
240 any gain, such as in an argument position. Hence, if the continuation
241 is interesting (eg. a case scrutinee, application etc.) then we
242 inline, otherwise we don't.
244 Previously some_benefit used to return True only if the variable was
245 applied to some value arguments. This didn't work:
247 let x = _coerce_ (T Int) Int (I# 3) in
248 case _coerce_ Int (T Int) x of
251 we want to inline x, but can't see that it's a constructor in a case
252 scrutinee position, and some_benefit is False.
256 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
258 .... case dMonadST _@_ x0 of (a,b,c) -> ....
260 we'd really like to inline dMonadST here, but we *don't* want to
261 inline if the case expression is just
263 case x of y { DEFAULT -> ... }
265 since we can just eliminate this case instead (x is in WHNF). Similar
266 applies when x is bound to a lambda expression. Hence
267 contIsInteresting looks for case expressions with just a single
271 interestingCallContext :: Bool -- False <=> no args at all
272 -> Bool -- False <=> no value args
274 -- The "lone-variable" case is important. I spent ages
275 -- messing about with unsatisfactory varaints, but this is nice.
276 -- The idea is that if a variable appear all alone
277 -- as an arg of lazy fn, or rhs Stop
278 -- as scrutinee of a case Select
279 -- as arg of a strict fn ArgOf
280 -- then we should not inline it (unless there is some other reason,
281 -- e.g. is is the sole occurrence). We achieve this by making
282 -- interestingCallContext return False for a lone variable.
284 -- Why? At least in the case-scrutinee situation, turning
285 -- let x = (a,b) in case x of y -> ...
287 -- let x = (a,b) in case (a,b) of y -> ...
289 -- let x = (a,b) in let y = (a,b) in ...
290 -- is bad if the binding for x will remain.
292 -- Another example: I discovered that strings
293 -- were getting inlined straight back into applications of 'error'
294 -- because the latter is strict.
296 -- f = \x -> ...(error s)...
298 -- Fundamentally such contexts should not ecourage inlining because
299 -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
300 -- so there's no gain.
302 -- However, even a type application or coercion isn't a lone variable.
304 -- case $fMonadST @ RealWorld of { :DMonad a b c -> c }
305 -- We had better inline that sucker! The case won't see through it.
307 -- For now, I'm treating treating a variable applied to types
308 -- in a *lazy* context "lone". The motivating example was
310 -- g = /\a. \y. h (f a)
311 -- There's no advantage in inlining f here, and perhaps
312 -- a significant disadvantage. Hence some_val_args in the Stop case
314 interestingCallContext some_args some_val_args cont
317 interesting (Select {}) = some_args
318 interesting (ApplyTo {}) = True -- Can happen if we have (coerce t (f x)) y
319 -- Perhaps True is a bit over-keen, but I've
320 -- seen (coerce f) x, where f has an INLINE prag,
321 -- So we have to give some motivaiton for inlining it
322 interesting (StrictArg {}) = some_val_args
323 interesting (StrictBind {}) = some_val_args -- ??
324 interesting (Stop ty _ interesting) = some_val_args && interesting
325 interesting (CoerceIt _ cont) = interesting cont
326 -- If this call is the arg of a strict function, the context
327 -- is a bit interesting. If we inline here, we may get useful
328 -- evaluation information to avoid repeated evals: e.g.
330 -- Here the contIsInteresting makes the '*' keener to inline,
331 -- which in turn exposes a constructor which makes the '+' inline.
332 -- Assuming that +,* aren't small enough to inline regardless.
334 -- It's also very important to inline in a strict context for things
337 -- Here, the context of (f x) is strict, and if f's unfolding is
338 -- a build it's *great* to inline it here. So we must ensure that
339 -- the context for (f x) is not totally uninteresting.
344 -> Int -- Number of value args
345 -> SimplCont -- Context of the cal
346 -> (Bool, [Bool]) -- Arg info
347 -- The arg info consists of
348 -- * A Bool indicating if the function has rules (recursively)
349 -- * A [Bool] indicating strictness for each arg
350 -- The [Bool] is usually infinite, but if it is finite it
351 -- guarantees that the function diverges after being given
352 -- that number of args
354 mkArgInfo fun n_val_args call_cont
355 = (interestingArgContext fun call_cont, fun_stricts)
357 vanilla_stricts, fun_stricts :: [Bool]
358 vanilla_stricts = repeat False
361 = case splitStrictSig (idNewStrictness fun) of
362 (demands, result_info)
363 | not (demands `lengthExceeds` n_val_args)
364 -> -- Enough args, use the strictness given.
365 -- For bottoming functions we used to pretend that the arg
366 -- is lazy, so that we don't treat the arg as an
367 -- interesting context. This avoids substituting
368 -- top-level bindings for (say) strings into
369 -- calls to error. But now we are more careful about
370 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
371 if isBotRes result_info then
372 map isStrictDmd demands -- Finite => result is bottom
374 map isStrictDmd demands ++ vanilla_stricts
376 other -> vanilla_stricts -- Not enough args, or no strictness
378 interestingArgContext :: Id -> SimplCont -> Bool
379 -- If the argument has form (f x y), where x,y are boring,
380 -- and f is marked INLINE, then we don't want to inline f.
381 -- But if the context of the argument is
383 -- where g has rules, then we *do* want to inline f, in case it
384 -- exposes a rule that might fire. Similarly, if the context is
386 -- where h has rules, then we do want to inline f.
387 -- The interesting_arg_ctxt flag makes this happen; if it's
388 -- set, the inliner gets just enough keener to inline f
389 -- regardless of how boring f's arguments are, if it's marked INLINE
391 -- The alternative would be to *always* inline an INLINE function,
392 -- regardless of how boring its context is; but that seems overkill
393 -- For example, it'd mean that wrapper functions were always inlined
394 interestingArgContext fn cont
395 = idHasRules fn || go cont
397 go (Select {}) = False
398 go (ApplyTo {}) = False
399 go (StrictArg {}) = True
400 go (StrictBind {}) = False -- ??
401 go (CoerceIt _ c) = go c
402 go (Stop _ _ interesting) = interesting
405 canUpdateInPlace :: Type -> Bool
406 -- Consider let x = <wurble> in ...
407 -- If <wurble> returns an explicit constructor, we might be able
408 -- to do update in place. So we treat even a thunk RHS context
409 -- as interesting if update in place is possible. We approximate
410 -- this by seeing if the type has a single constructor with a
411 -- small arity. But arity zero isn't good -- we share the single copy
412 -- for that case, so no point in sharing.
415 | not opt_UF_UpdateInPlace = False
417 = case splitTyConApp_maybe ty of
419 Just (tycon, _) -> case tyConDataCons_maybe tycon of
420 Just [dc] -> arity == 1 || arity == 2
422 arity = dataConRepArity dc
428 %************************************************************************
430 \subsection{Decisions about inlining}
432 %************************************************************************
434 Inlining is controlled partly by the SimplifierMode switch. This has two
437 SimplGently (a) Simplifying before specialiser/full laziness
438 (b) Simplifiying inside INLINE pragma
439 (c) Simplifying the LHS of a rule
440 (d) Simplifying a GHCi expression or Template
443 SimplPhase n Used at all other times
445 The key thing about SimplGently is that it does no call-site inlining.
446 Before full laziness we must be careful not to inline wrappers,
447 because doing so inhibits floating
448 e.g. ...(case f x of ...)...
449 ==> ...(case (case x of I# x# -> fw x#) of ...)...
450 ==> ...(case x of I# x# -> case fw x# of ...)...
451 and now the redex (f x) isn't floatable any more.
453 The no-inlining thing is also important for Template Haskell. You might be
454 compiling in one-shot mode with -O2; but when TH compiles a splice before
455 running it, we don't want to use -O2. Indeed, we don't want to inline
456 anything, because the byte-code interpreter might get confused about
457 unboxed tuples and suchlike.
461 SimplGently is also used as the mode to simplify inside an InlineMe note.
464 inlineMode :: SimplifierMode
465 inlineMode = SimplGently
468 It really is important to switch off inlinings inside such
469 expressions. Consider the following example
475 in ...g...g...g...g...g...
477 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
478 and thence copied multiple times when g is inlined.
481 This function may be inlinined in other modules, so we
482 don't want to remove (by inlining) calls to functions that have
483 specialisations, or that may have transformation rules in an importing
486 E.g. {-# INLINE f #-}
489 and suppose that g is strict *and* has specialisations. If we inline
490 g's wrapper, we deny f the chance of getting the specialised version
491 of g when f is inlined at some call site (perhaps in some other
494 It's also important not to inline a worker back into a wrapper.
496 wraper = inline_me (\x -> ...worker... )
497 Normally, the inline_me prevents the worker getting inlined into
498 the wrapper (initially, the worker's only call site!). But,
499 if the wrapper is sure to be called, the strictness analyser will
500 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
501 continuation. That's why the keep_inline predicate returns True for
502 ArgOf continuations. It shouldn't do any harm not to dissolve the
503 inline-me note under these circumstances.
505 Note that the result is that we do very little simplification
508 all xs = foldr (&&) True xs
509 any p = all . map p {-# INLINE any #-}
511 Problem: any won't get deforested, and so if it's exported and the
512 importer doesn't use the inlining, (eg passes it as an arg) then we
513 won't get deforestation at all. We havn't solved this problem yet!
516 preInlineUnconditionally
517 ~~~~~~~~~~~~~~~~~~~~~~~~
518 @preInlineUnconditionally@ examines a bndr to see if it is used just
519 once in a completely safe way, so that it is safe to discard the
520 binding inline its RHS at the (unique) usage site, REGARDLESS of how
521 big the RHS might be. If this is the case we don't simplify the RHS
522 first, but just inline it un-simplified.
524 This is much better than first simplifying a perhaps-huge RHS and then
525 inlining and re-simplifying it. Indeed, it can be at least quadratically
534 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
535 This can happen with cascades of functions too:
542 THE MAIN INVARIANT is this:
544 ---- preInlineUnconditionally invariant -----
545 IF preInlineUnconditionally chooses to inline x = <rhs>
546 THEN doing the inlining should not change the occurrence
547 info for the free vars of <rhs>
548 ----------------------------------------------
550 For example, it's tempting to look at trivial binding like
552 and inline it unconditionally. But suppose x is used many times,
553 but this is the unique occurrence of y. Then inlining x would change
554 y's occurrence info, which breaks the invariant. It matters: y
555 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
558 Evne RHSs labelled InlineMe aren't caught here, because there might be
559 no benefit from inlining at the call site.
561 [Sept 01] Don't unconditionally inline a top-level thing, because that
562 can simply make a static thing into something built dynamically. E.g.
566 [Remember that we treat \s as a one-shot lambda.] No point in
567 inlining x unless there is something interesting about the call site.
569 But watch out: if you aren't careful, some useful foldr/build fusion
570 can be lost (most notably in spectral/hartel/parstof) because the
571 foldr didn't see the build. Doing the dynamic allocation isn't a big
572 deal, in fact, but losing the fusion can be. But the right thing here
573 seems to be to do a callSiteInline based on the fact that there is
574 something interesting about the call site (it's strict). Hmm. That
577 Conclusion: inline top level things gaily until Phase 0 (the last
578 phase), at which point don't.
581 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
582 preInlineUnconditionally env top_lvl bndr rhs
584 | opt_SimplNoPreInlining = False
585 | otherwise = case idOccInfo bndr of
586 IAmDead -> True -- Happens in ((\x.1) v)
587 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
591 active = case phase of
592 SimplGently -> isAlwaysActive prag
593 SimplPhase n -> isActive n prag
594 prag = idInlinePragma bndr
596 try_once in_lam int_cxt -- There's one textual occurrence
597 | not in_lam = isNotTopLevel top_lvl || early_phase
598 | otherwise = int_cxt && canInlineInLam rhs
600 -- Be very careful before inlining inside a lambda, becuase (a) we must not
601 -- invalidate occurrence information, and (b) we want to avoid pushing a
602 -- single allocation (here) into multiple allocations (inside lambda).
603 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
604 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
606 -- is_cheap = exprIsCheap rhs
607 -- ok = is_cheap && int_cxt
609 -- int_cxt The context isn't totally boring
610 -- E.g. let f = \ab.BIG in \y. map f xs
611 -- Don't want to substitute for f, because then we allocate
612 -- its closure every time the \y is called
613 -- But: let f = \ab.BIG in \y. map (f y) xs
614 -- Now we do want to substitute for f, even though it's not
615 -- saturated, because we're going to allocate a closure for
616 -- (f y) every time round the loop anyhow.
618 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
619 -- so substituting rhs inside a lambda doesn't change the occ info.
620 -- Sadly, not quite the same as exprIsHNF.
621 canInlineInLam (Lit l) = True
622 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
623 canInlineInLam (Note _ e) = canInlineInLam e
624 canInlineInLam _ = False
626 early_phase = case phase of
627 SimplPhase 0 -> False
629 -- If we don't have this early_phase test, consider
630 -- x = length [1,2,3]
631 -- The full laziness pass carefully floats all the cons cells to
632 -- top level, and preInlineUnconditionally floats them all back in.
633 -- Result is (a) static allocation replaced by dynamic allocation
634 -- (b) many simplifier iterations because this tickles
635 -- a related problem; only one inlining per pass
637 -- On the other hand, I have seen cases where top-level fusion is
638 -- lost if we don't inline top level thing (e.g. string constants)
639 -- Hence the test for phase zero (which is the phase for all the final
640 -- simplifications). Until phase zero we take no special notice of
641 -- top level things, but then we become more leery about inlining
646 postInlineUnconditionally
647 ~~~~~~~~~~~~~~~~~~~~~~~~~
648 @postInlineUnconditionally@ decides whether to unconditionally inline
649 a thing based on the form of its RHS; in particular if it has a
650 trivial RHS. If so, we can inline and discard the binding altogether.
652 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
653 only have *forward* references Hence, it's safe to discard the binding
655 NOTE: This isn't our last opportunity to inline. We're at the binding
656 site right now, and we'll get another opportunity when we get to the
659 Note that we do this unconditional inlining only for trival RHSs.
660 Don't inline even WHNFs inside lambdas; doing so may simply increase
661 allocation when the function is called. This isn't the last chance; see
664 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
665 Because we don't even want to inline them into the RHS of constructor
666 arguments. See NOTE above
668 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
669 it's best to inline it anyway. We often get a=E; b=a from desugaring,
670 with both a and b marked NOINLINE. But that seems incompatible with
671 our new view that inlining is like a RULE, so I'm sticking to the 'active'
675 postInlineUnconditionally
676 :: SimplEnv -> TopLevelFlag
677 -> InId -- The binder (an OutId would be fine too)
678 -> OccInfo -- From the InId
682 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
684 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, dont' inline
685 -- because it might be referred to "earlier"
686 | isExportedId bndr = False
687 | exprIsTrivial rhs = True
690 -- The point of examining occ_info here is that for *non-values*
691 -- that occur outside a lambda, the call-site inliner won't have
692 -- a chance (becuase it doesn't know that the thing
693 -- only occurs once). The pre-inliner won't have gotten
694 -- it either, if the thing occurs in more than one branch
695 -- So the main target is things like
698 -- True -> case x of ...
699 -- False -> case x of ...
700 -- I'm not sure how important this is in practice
701 OneOcc in_lam one_br int_cxt -- OneOcc => no code-duplication issue
702 -> smallEnoughToInline unfolding -- Small enough to dup
703 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
705 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
706 -- Reason: doing so risks exponential behaviour. We simplify a big
707 -- expression, inline it, and simplify it again. But if the
708 -- very same thing happens in the big expression, we get
710 -- PRINCIPLE: when we've already simplified an expression once,
711 -- make sure that we only inline it if it's reasonably small.
713 && ((isNotTopLevel top_lvl && not in_lam) ||
714 -- But outside a lambda, we want to be reasonably aggressive
715 -- about inlining into multiple branches of case
716 -- e.g. let x = <non-value>
717 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
718 -- Inlining can be a big win if C3 is the hot-spot, even if
719 -- the uses in C1, C2 are not 'interesting'
720 -- An example that gets worse if you add int_cxt here is 'clausify'
722 (isCheapUnfolding unfolding && int_cxt))
723 -- isCheap => acceptable work duplication; in_lam may be true
724 -- int_cxt to prevent us inlining inside a lambda without some
725 -- good reason. See the notes on int_cxt in preInlineUnconditionally
727 IAmDead -> True -- This happens; for example, the case_bndr during case of
728 -- known constructor: case (a,b) of x { (p,q) -> ... }
729 -- Here x isn't mentioned in the RHS, so we don't want to
730 -- create the (dead) let-binding let x = (a,b) in ...
734 -- Here's an example that we don't handle well:
735 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
736 -- in \y. ....case f of {...} ....
737 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
739 -- * We can't preInlineUnconditionally because that woud invalidate
740 -- the occ info for b.
741 -- * We can't postInlineUnconditionally because the RHS is big, and
742 -- that risks exponential behaviour
743 -- * We can't call-site inline, because the rhs is big
747 active = case getMode env of
748 SimplGently -> isAlwaysActive prag
749 SimplPhase n -> isActive n prag
750 prag = idInlinePragma bndr
752 activeInline :: SimplEnv -> OutId -> Bool
754 = case getMode env of
756 -- No inlining at all when doing gentle stuff,
757 -- except for local things that occur once
758 -- The reason is that too little clean-up happens if you
759 -- don't inline use-once things. Also a bit of inlining is *good* for
760 -- full laziness; it can expose constant sub-expressions.
761 -- Example in spectral/mandel/Mandel.hs, where the mandelset
762 -- function gets a useful let-float if you inline windowToViewport
764 -- NB: we used to have a second exception, for data con wrappers.
765 -- On the grounds that we use gentle mode for rule LHSs, and
766 -- they match better when data con wrappers are inlined.
767 -- But that only really applies to the trivial wrappers (like (:)),
768 -- and they are now constructed as Compulsory unfoldings (in MkId)
769 -- so they'll happen anyway.
771 SimplPhase n -> isActive n prag
773 prag = idInlinePragma id
775 activeRule :: SimplEnv -> Maybe (Activation -> Bool)
776 -- Nothing => No rules at all
778 | opt_RulesOff = Nothing
780 = case getMode env of
781 SimplGently -> Just isAlwaysActive
782 -- Used to be Nothing (no rules in gentle mode)
783 -- Main motivation for changing is that I wanted
784 -- lift String ===> ...
785 -- to work in Template Haskell when simplifying
786 -- splices, so we get simpler code for literal strings
787 SimplPhase n -> Just (isActive n)
791 %************************************************************************
795 %************************************************************************
798 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
799 -- mkLam tries three things
800 -- a) eta reduction, if that gives a trivial expression
801 -- b) eta expansion [only if there are some value lambdas]
804 = do { dflags <- getDOptsSmpl
805 ; mkLam' dflags bndrs body }
807 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
808 mkLam' dflags bndrs (Cast body@(Lam _ _) co)
809 -- Note [Casts and lambdas]
810 = do { lam <- mkLam' dflags (bndrs ++ bndrs') body'
811 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
813 (bndrs',body') = collectBinders body
815 mkLam' dflags bndrs body
816 | dopt Opt_DoEtaReduction dflags,
817 Just etad_lam <- tryEtaReduce bndrs body
818 = do { tick (EtaReduction (head bndrs))
821 | dopt Opt_DoLambdaEtaExpansion dflags,
822 any isRuntimeVar bndrs
823 = do { body' <- tryEtaExpansion dflags body
824 ; return (mkLams bndrs body') }
827 = returnSmpl (mkLams bndrs body)
830 Note [Casts and lambdas]
831 ~~~~~~~~~~~~~~~~~~~~~~~~
833 (\x. (\y. e) `cast` g1) `cast` g2
834 There is a danger here that the two lambdas look separated, and the
835 full laziness pass might float an expression to between the two.
837 So this equation in mkLam' floats the g1 out, thus:
838 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
841 In general, this floats casts outside lambdas, where (I hope) they might meet
842 and cancel with some other cast.
845 -- c) floating lets out through big lambdas
846 -- [only if all tyvar lambdas, and only if this lambda
847 -- is the RHS of a let]
849 {- Sept 01: I'm experimenting with getting the
850 full laziness pass to float out past big lambdsa
851 | all isTyVar bndrs, -- Only for big lambdas
852 contIsRhs cont -- Only try the rhs type-lambda floating
853 -- if this is indeed a right-hand side; otherwise
854 -- we end up floating the thing out, only for float-in
855 -- to float it right back in again!
856 = tryRhsTyLam env bndrs body `thenSmpl` \ (floats, body') ->
857 returnSmpl (floats, mkLams bndrs body')
861 %************************************************************************
863 \subsection{Eta expansion and reduction}
865 %************************************************************************
867 We try for eta reduction here, but *only* if we get all the
868 way to an exprIsTrivial expression.
869 We don't want to remove extra lambdas unless we are going
870 to avoid allocating this thing altogether
873 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
874 tryEtaReduce bndrs body
875 -- We don't use CoreUtils.etaReduce, because we can be more
877 -- (a) we already have the binders
878 -- (b) we can do the triviality test before computing the free vars
879 = go (reverse bndrs) body
881 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
882 go [] fun | ok_fun fun = Just fun -- Success!
883 go _ _ = Nothing -- Failure!
885 ok_fun fun = exprIsTrivial fun
886 && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
887 && (exprIsHNF fun || all ok_lam bndrs)
888 ok_lam v = isTyVar v || isDictId v
889 -- The exprIsHNF is because eta reduction is not
890 -- valid in general: \x. bot /= bot
891 -- So we need to be sure that the "fun" is a value.
893 -- However, we always want to reduce (/\a -> f a) to f
894 -- This came up in a RULE: foldr (build (/\a -> g a))
895 -- did not match foldr (build (/\b -> ...something complex...))
896 -- The type checker can insert these eta-expanded versions,
897 -- with both type and dictionary lambdas; hence the slightly
900 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
904 Try eta expansion for RHSs
907 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
910 where (in both cases)
912 * The xi can include type variables
914 * The yi are all value variables
916 * N is a NORMAL FORM (i.e. no redexes anywhere)
917 wanting a suitable number of extra args.
919 We may have to sandwich some coerces between the lambdas
920 to make the types work. exprEtaExpandArity looks through coerces
921 when computing arity; and etaExpand adds the coerces as necessary when
922 actually computing the expansion.
925 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
926 -- There is at least one runtime binder in the binders
927 tryEtaExpansion dflags body
928 = getUniquesSmpl `thenSmpl` \ us ->
929 returnSmpl (etaExpand fun_arity us body (exprType body))
931 fun_arity = exprEtaExpandArity dflags body
935 %************************************************************************
937 \subsection{Floating lets out of big lambdas}
939 %************************************************************************
941 tryRhsTyLam tries this transformation, when the big lambda appears as
942 the RHS of a let(rec) binding:
944 /\abc -> let(rec) x = e in b
946 let(rec) x' = /\abc -> let x = x' a b c in e
948 /\abc -> let x = x' a b c in b
950 This is good because it can turn things like:
952 let f = /\a -> letrec g = ... g ... in g
954 letrec g' = /\a -> ... g' a ...
958 which is better. In effect, it means that big lambdas don't impede
961 This optimisation is CRUCIAL in eliminating the junk introduced by
962 desugaring mutually recursive definitions. Don't eliminate it lightly!
964 So far as the implementation is concerned:
966 Invariant: go F e = /\tvs -> F e
970 = Let x' = /\tvs -> F e
974 G = F . Let x = x' tvs
976 go F (Letrec xi=ei in b)
977 = Letrec {xi' = /\tvs -> G ei}
981 G = F . Let {xi = xi' tvs}
983 [May 1999] If we do this transformation *regardless* then we can
984 end up with some pretty silly stuff. For example,
987 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
992 st = /\s -> ...[y1 s/x1, y2 s/x2]
995 Unless the "..." is a WHNF there is really no point in doing this.
996 Indeed it can make things worse. Suppose x1 is used strictly,
999 x1* = case f y of { (a,b) -> e }
1001 If we abstract this wrt the tyvar we then can't do the case inline
1002 as we would normally do.
1006 {- Trying to do this in full laziness
1008 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
1009 -- Call ensures that all the binders are type variables
1011 tryRhsTyLam env tyvars body -- Only does something if there's a let
1012 | not (all isTyVar tyvars)
1013 || not (worth_it body) -- inside a type lambda,
1014 = returnSmpl (emptyFloats env, body) -- and a WHNF inside that
1017 = go env (\x -> x) body
1020 worth_it e@(Let _ _) = whnf_in_middle e
1023 whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
1024 whnf_in_middle (Let _ e) = whnf_in_middle e
1025 whnf_in_middle e = exprIsCheap e
1027 main_tyvar_set = mkVarSet tyvars
1029 go env fn (Let bind@(NonRec var rhs) body)
1031 = go env (fn . Let bind) body
1033 go env fn (Let (NonRec var rhs) body)
1034 = mk_poly tyvars_here var `thenSmpl` \ (var', rhs') ->
1035 addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs))) $ \ env ->
1036 go env (fn . Let (mk_silly_bind var rhs')) body
1040 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1041 -- Abstract only over the type variables free in the rhs
1042 -- wrt which the new binding is abstracted. But the naive
1043 -- approach of abstract wrt the tyvars free in the Id's type
1045 -- /\ a b -> let t :: (a,b) = (e1, e2)
1048 -- Here, b isn't free in x's type, but we must nevertheless
1049 -- abstract wrt b as well, because t's type mentions b.
1050 -- Since t is floated too, we'd end up with the bogus:
1051 -- poly_t = /\ a b -> (e1, e2)
1052 -- poly_x = /\ a -> fst (poly_t a *b*)
1053 -- So for now we adopt the even more naive approach of
1054 -- abstracting wrt *all* the tyvars. We'll see if that
1055 -- gives rise to problems. SLPJ June 98
1057 go env fn (Let (Rec prs) body)
1058 = mapAndUnzipSmpl (mk_poly tyvars_here) vars `thenSmpl` \ (vars', rhss') ->
1060 gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
1061 pairs = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
1063 addAuxiliaryBind env (Rec pairs) $ \ env ->
1066 (vars,rhss) = unzip prs
1067 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
1068 -- See notes with tyvars_here above
1070 go env fn body = returnSmpl (emptyFloats env, fn body)
1072 mk_poly tyvars_here var
1073 = getUniqueSmpl `thenSmpl` \ uniq ->
1075 poly_name = setNameUnique (idName var) uniq -- Keep same name
1076 poly_ty = mkForAllTys tyvars_here (idType var) -- But new type of course
1077 poly_id = mkLocalId poly_name poly_ty
1079 -- In the olden days, it was crucial to copy the occInfo of the original var,
1080 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1081 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1082 -- at already simplified code, so it doesn't matter
1084 -- It's even right to retain single-occurrence or dead-var info:
1085 -- Suppose we started with /\a -> let x = E in B
1086 -- where x occurs once in B. Then we transform to:
1087 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1088 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1089 -- the occurrences of x' will be just the occurrences originally
1092 returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
1094 mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
1095 -- Suppose we start with:
1097 -- x = /\ a -> let g = G in E
1099 -- Then we'll float to get
1101 -- x = let poly_g = /\ a -> G
1102 -- in /\ a -> let g = poly_g a in E
1104 -- But now the occurrence analyser will see just one occurrence
1105 -- of poly_g, not inside a lambda, so the simplifier will
1106 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1107 -- (I used to think that the "don't inline lone occurrences" stuff
1108 -- would stop this happening, but since it's the *only* occurrence,
1109 -- PreInlineUnconditionally kicks in first!)
1111 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1112 -- to appear many times. (NB: mkInlineMe eliminates
1113 -- such notes on trivial RHSs, so do it manually.)
1117 %************************************************************************
1119 \subsection{Case absorption and identity-case elimination}
1121 %************************************************************************
1124 mkCase puts a case expression back together, trying various transformations first.
1127 mkCase :: OutExpr -> OutId -> OutType
1128 -> [OutAlt] -- Increasing order
1131 mkCase scrut case_bndr ty alts
1132 = getDOptsSmpl `thenSmpl` \dflags ->
1133 mkAlts dflags scrut case_bndr alts `thenSmpl` \ better_alts ->
1134 mkCase1 scrut case_bndr ty better_alts
1138 mkAlts tries these things:
1140 1. If several alternatives are identical, merge them into
1141 a single DEFAULT alternative. I've occasionally seen this
1142 making a big difference:
1144 case e of =====> case e of
1145 C _ -> f x D v -> ....v....
1146 D v -> ....v.... DEFAULT -> f x
1149 The point is that we merge common RHSs, at least for the DEFAULT case.
1150 [One could do something more elaborate but I've never seen it needed.]
1151 To avoid an expensive test, we just merge branches equal to the *first*
1152 alternative; this picks up the common cases
1153 a) all branches equal
1154 b) some branches equal to the DEFAULT (which occurs first)
1157 case e of b { ==> case e of b {
1158 p1 -> rhs1 p1 -> rhs1
1160 pm -> rhsm pm -> rhsm
1161 _ -> case b of b' { pn -> let b'=b in rhsn
1163 ... po -> let b'=b in rhso
1164 po -> rhso _ -> let b'=b in rhsd
1168 which merges two cases in one case when -- the default alternative of
1169 the outer case scrutises the same variable as the outer case This
1170 transformation is called Case Merging. It avoids that the same
1171 variable is scrutinised multiple times.
1174 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1180 where @is@ was something like
1182 p `is` n = p /= (-1) && p == n
1184 This gave rise to a horrible sequence of cases
1191 and similarly in cascade for all the join points!
1196 --------------------------------------------------
1197 -- 1. Merge identical branches
1198 --------------------------------------------------
1199 mkAlts dflags scrut case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
1200 | all isDeadBinder bndrs1, -- Remember the default
1201 length filtered_alts < length con_alts -- alternative comes first
1202 = tick (AltMerge case_bndr) `thenSmpl_`
1203 returnSmpl better_alts
1205 filtered_alts = filter keep con_alts
1206 keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1207 better_alts = (DEFAULT, [], rhs1) : filtered_alts
1210 --------------------------------------------------
1211 -- 2. Merge nested cases
1212 --------------------------------------------------
1214 mkAlts dflags scrut outer_bndr outer_alts
1215 | dopt Opt_CaseMerge dflags,
1216 (outer_alts_without_deflt, maybe_outer_deflt) <- findDefault outer_alts,
1217 Just (Case (Var scrut_var) inner_bndr _ inner_alts) <- maybe_outer_deflt,
1218 scruting_same_var scrut_var
1220 munged_inner_alts = [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts]
1221 munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1223 new_alts = mergeAlts outer_alts_without_deflt munged_inner_alts
1224 -- The merge keeps the inner DEFAULT at the front, if there is one
1225 -- and eliminates any inner_alts that are shadowed by the outer_alts
1227 tick (CaseMerge outer_bndr) `thenSmpl_`
1229 -- Warning: don't call mkAlts recursively!
1230 -- Firstly, there's no point, because inner alts have already had
1231 -- mkCase applied to them, so they won't have a case in their default
1232 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1233 -- in munge_rhs may put a case into the DEFAULT branch!
1235 -- We are scrutinising the same variable if it's
1236 -- the outer case-binder, or if the outer case scrutinises a variable
1237 -- (and it's the same). Testing both allows us not to replace the
1238 -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1239 scruting_same_var = case scrut of
1240 Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1241 other -> \ v -> v == outer_bndr
1243 ------------------------------------------------
1245 ------------------------------------------------
1247 mkAlts dflags scrut case_bndr other_alts = returnSmpl other_alts
1252 =================================================================================
1254 mkCase1 tries these things
1256 1. Eliminate the case altogether if possible
1264 and similar friends.
1267 Start with a simple situation:
1269 case x# of ===> e[x#/y#]
1272 (when x#, y# are of primitive type, of course). We can't (in general)
1273 do this for algebraic cases, because we might turn bottom into
1276 Actually, we generalise this idea to look for a case where we're
1277 scrutinising a variable, and we know that only the default case can
1282 other -> ...(case x of
1286 Here the inner case can be eliminated. This really only shows up in
1287 eliminating error-checking code.
1289 We also make sure that we deal with this very common case:
1294 Here we are using the case as a strict let; if x is used only once
1295 then we want to inline it. We have to be careful that this doesn't
1296 make the program terminate when it would have diverged before, so we
1298 - x is used strictly, or
1299 - e is already evaluated (it may so if e is a variable)
1301 Lastly, we generalise the transformation to handle this:
1307 We only do this for very cheaply compared r's (constructors, literals
1308 and variables). If pedantic bottoms is on, we only do it when the
1309 scrutinee is a PrimOp which can't fail.
1311 We do it *here*, looking at un-simplified alternatives, because we
1312 have to check that r doesn't mention the variables bound by the
1313 pattern in each alternative, so the binder-info is rather useful.
1315 So the case-elimination algorithm is:
1317 1. Eliminate alternatives which can't match
1319 2. Check whether all the remaining alternatives
1320 (a) do not mention in their rhs any of the variables bound in their pattern
1321 and (b) have equal rhss
1323 3. Check we can safely ditch the case:
1324 * PedanticBottoms is off,
1325 or * the scrutinee is an already-evaluated variable
1326 or * the scrutinee is a primop which is ok for speculation
1327 -- ie we want to preserve divide-by-zero errors, and
1328 -- calls to error itself!
1330 or * [Prim cases] the scrutinee is a primitive variable
1332 or * [Alg cases] the scrutinee is a variable and
1333 either * the rhs is the same variable
1334 (eg case x of C a b -> x ===> x)
1335 or * there is only one alternative, the default alternative,
1336 and the binder is used strictly in its scope.
1337 [NB this is helped by the "use default binder where
1338 possible" transformation; see below.]
1341 If so, then we can replace the case with one of the rhss.
1343 Further notes about case elimination
1344 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1345 Consider: test :: Integer -> IO ()
1348 Turns out that this compiles to:
1351 eta1 :: State# RealWorld ->
1352 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1354 (PrelNum.jtos eta ($w[] @ Char))
1356 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1358 Notice the strange '<' which has no effect at all. This is a funny one.
1359 It started like this:
1361 f x y = if x < 0 then jtos x
1362 else if y==0 then "" else jtos x
1364 At a particular call site we have (f v 1). So we inline to get
1366 if v < 0 then jtos x
1367 else if 1==0 then "" else jtos x
1369 Now simplify the 1==0 conditional:
1371 if v<0 then jtos v else jtos v
1373 Now common-up the two branches of the case:
1375 case (v<0) of DEFAULT -> jtos v
1377 Why don't we drop the case? Because it's strict in v. It's technically
1378 wrong to drop even unnecessary evaluations, and in practice they
1379 may be a result of 'seq' so we *definitely* don't want to drop those.
1380 I don't really know how to improve this situation.
1384 --------------------------------------------------
1385 -- 0. Check for empty alternatives
1386 --------------------------------------------------
1388 -- This isn't strictly an error. It's possible that the simplifer might "see"
1389 -- that an inner case has no accessible alternatives before it "sees" that the
1390 -- entire branch of an outer case is inaccessible. So we simply
1391 -- put an error case here insteadd
1392 mkCase1 scrut case_bndr ty []
1393 = pprTrace "mkCase1: null alts" (ppr case_bndr <+> ppr scrut) $
1394 return (mkApps (Var eRROR_ID)
1395 [Type ty, Lit (mkStringLit "Impossible alternative")])
1397 --------------------------------------------------
1398 -- 1. Eliminate the case altogether if poss
1399 --------------------------------------------------
1401 mkCase1 scrut case_bndr ty [(con,bndrs,rhs)]
1402 -- See if we can get rid of the case altogether
1403 -- See the extensive notes on case-elimination above
1404 -- mkCase made sure that if all the alternatives are equal,
1405 -- then there is now only one (DEFAULT) rhs
1406 | all isDeadBinder bndrs,
1408 -- Check that the scrutinee can be let-bound instead of case-bound
1409 exprOkForSpeculation scrut
1410 -- OK not to evaluate it
1411 -- This includes things like (==# a# b#)::Bool
1412 -- so that we simplify
1413 -- case ==# a# b# of { True -> x; False -> x }
1416 -- This particular example shows up in default methods for
1417 -- comparision operations (e.g. in (>=) for Int.Int32)
1418 || exprIsHNF scrut -- It's already evaluated
1419 || var_demanded_later scrut -- It'll be demanded later
1421 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1422 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1423 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1424 -- its argument: case x of { y -> dataToTag# y }
1425 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1426 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1428 -- Also we don't want to discard 'seq's
1429 = tick (CaseElim case_bndr) `thenSmpl_`
1430 returnSmpl (bindCaseBndr case_bndr scrut rhs)
1433 -- The case binder is going to be evaluated later,
1434 -- and the scrutinee is a simple variable
1435 var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1436 var_demanded_later other = False
1439 --------------------------------------------------
1441 --------------------------------------------------
1443 mkCase1 scrut case_bndr ty alts -- Identity case
1444 | all identity_alt alts
1445 = tick (CaseIdentity case_bndr) `thenSmpl_`
1446 returnSmpl (re_cast scrut)
1448 identity_alt (con, args, rhs) = de_cast rhs `cheapEqExpr` mk_id_rhs con args
1450 mk_id_rhs (DataAlt con) args = mkConApp con (arg_tys ++ varsToCoreExprs args)
1451 mk_id_rhs (LitAlt lit) _ = Lit lit
1452 mk_id_rhs DEFAULT _ = Var case_bndr
1454 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1457 -- case e of x { _ -> x `cast` c }
1458 -- And we definitely want to eliminate this case, to give
1460 -- So we throw away the cast from the RHS, and reconstruct
1461 -- it at the other end. All the RHS casts must be the same
1462 -- if (all identity_alt alts) holds.
1464 -- Don't worry about nested casts, because the simplifier combines them
1465 de_cast (Cast e _) = e
1468 re_cast scrut = case head alts of
1469 (_,_,Cast _ co) -> Cast scrut co
1474 --------------------------------------------------
1476 --------------------------------------------------
1477 mkCase1 scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1481 When adding auxiliary bindings for the case binder, it's worth checking if
1482 its dead, because it often is, and occasionally these mkCase transformations
1483 cascade rather nicely.
1486 bindCaseBndr bndr rhs body
1487 | isDeadBinder bndr = body
1488 | otherwise = bindNonRec bndr rhs body